BELLOP = 'chsh'
import matplotlib.pyplot as plt
import numpy as np
import json, csv
from functools import partial
#%config InlineBackend.figure_formats = ['svg']
import os
EXPORTDIR = 'data_export33'
FIGUREDIR = 'figures33'
os.makedirs(EXPORTDIR, exist_ok=True)
os.makedirs(FIGUREDIR, exist_ok=True)
def path_fig(filename):
return os.path.join(FIGUREDIR, filename)
SAVEFIG_KWARGS = {'metadata':{'CreationDate':None}}
def path_export(filename):
return os.path.join(EXPORTDIR, filename)
from IPython.display import Markdown as md, display, HTML
import html
import warnings
def report_error(message):
display(md('<b style="font-size:5rem; color:red; line-height:5rem">{}</b>'.format(
html.escape(message)
)))
display(md(f'# Results for {BELLOP.upper()} 3*3 state dim'))
from parse_log import parse_log_witness_bounds
FIELDS = [BELLOP,'cond_entropy','cond_entropy_bound','witncnt_before_failure',f'{BELLOP}_after_failures','cond_entropy_after_failures']
bell_val_bounds = {}
entropies_bounds = {}
success_bounds = {}
with open(path_export(f'witness_bounds33_{BELLOP}.tsv'), 'w', newline='') as outfile:
csvwr = csv.writer(outfile, delimiter='\t')
csvwr.writerow(FIELDS)
for bound in range(0, 105, 5):
entropies, bell_val = [], []
bound /= 100
case = f'bound_witnesses_{BELLOP}.{bound:.2f}'
success_bounds[-bound] = parse_log_witness_bounds(f'out_bell33/{case}.log')
with open(f'out_bell33/{case}.jsonl') as f:
last = {BELLOP:float('nan'), 'cond_entropy':float('nan')}
last_success = 0, last
failure = False
for i, (success, l) in enumerate(zip(success_bounds[-bound], f), start=1):
d = json.loads(l)
entropies.append(d['cond_entropy'])
bell_val.append(d[BELLOP])
if not failure:
if success:
last_success = i, d
else:
failure = True
last = d
witncnt_success, last_success = last_success
csvwr.writerow((last_success[BELLOP], last_success['cond_entropy'], -bound, witncnt_success, last[BELLOP], last['cond_entropy']))
bell_val_bounds[-bound] = bell_val
entropies_bounds[-bound] = entropies
fig = plt.figure(figsize=(8,7))
for bound, bell_val in reversed(bell_val_bounds.items()):
plt.plot(bell_val, label=str(bound))
errors = [(i, value) for i, (value, success) in enumerate(zip(bell_val, success_bounds[bound])) if not success]
plt.scatter([i for i, _ in errors], [v for _, v in errors], [2 if i != 0 else 25 for i, _ in enumerate(errors)])
plt.title(f'maximized {BELLOP.upper()}')
plt.xlabel('iterations (witness count)')
plt.ylabel(BELLOP.upper())
plt.grid()
plt.legend(loc='upper right')
plt.show(fig)
fig.savefig(path_fig(f'witn33_{BELLOP}_val.pdf'), **SAVEFIG_KWARGS)
plt.close(fig)
fig = plt.figure(figsize=(8,7))
for bound, entropies in entropies_bounds.items():
plt.plot(entropies, label=str(bound))
errors = [(i, entropy) for i, (entropy, success) in enumerate(zip(entropies, success_bounds[bound])) if not success]
plt.scatter([i for i, _ in errors], [e for _, e in errors], [2 if i != 0 else 25 for i, _ in enumerate(errors)])
plt.title(f'Entropies for maximized {BELLOP.upper()}')
plt.xlabel('iterations (witness count)')
plt.ylabel('conditional entropy')
plt.grid()
plt.legend(loc='lower right')
plt.show(fig)
fig.savefig(path_fig(f'witn33_{BELLOP}_entr.pdf'), **SAVEFIG_KWARGS)
plt.close(fig)
import pandas as pd
witness_bounds = pd.read_csv(path_export(f'witness_bounds33_{BELLOP}.tsv'), sep='\t')
fig, ax = plt.subplots(figsize=(12, 12), dpi=150)
hwitn, = ax.plot(witness_bounds['cond_entropy_bound'], witness_bounds[BELLOP], 'r-', marker=5, label=f'max_{BELLOP} with witness (fixed meas.)')
#fp1, = ax.plot(fixedm_p1['s_bound'], fixedm_p1[BELLOP], 'c-', marker=6, label=f'max_{BELLOP} apx=+1 fixed mesurements')
#hfm1, = ax.plot(fixedm_m1['s_bound'], fixedm_m1[BELLOP], 'b-', marker=7, label=f'max_{BELLOP} apx=-1 fixed mesurements')
#hp1, = ax.plot(stats['s_bound'], stats[f'max_{BELLOP}_+1'], 'x-', label=f'max_{BELLOP}[apx=+1]')
#hm1, = ax.plot(stats['s_bound'], stats[f'max_{BELLOP}_-1'], '.-', label=f'max_{BELLOP}[apx=-1]')
#fndp1, = ax.plot(foundm_p1['s_bound'], foundm_p1[BELLOP], '|--', label=f'max_{BELLOP} apx=+1 found meas.')
#fndm1, = ax.plot(foundm_m1['s_bound'], foundm_m1[BELLOP], '|--', label=f'max_{BELLOP} apx=-1 found meas.')
#ax.legend(handles=[hp1,hm1, hwitn, hfp1,hfm1, fndp1, fndm1])
ax.legend(handles=[hwitn])
ax.set_title('qutrit subsystems (9x9 state density matrix)')
ax.set_xlabel('conditional entropy')
ax.set_ylabel(BELLOP.upper())
ax.grid(True)
plt.show(fig)
fig.savefig(path_fig(f'witn_bound33_{BELLOP}.pdf'), **SAVEFIG_KWARGS)
plt.close(fig)
diff_cond_entr = witness_bounds['cond_entropy'] - witness_bounds['cond_entropy_after_failures']
diff_bellop = witness_bounds[BELLOP] - witness_bounds[f'{BELLOP}_after_failures']
fig, ax = plt.subplots(figsize=(12, 12), dpi=150)
hdiff, = ax.plot(witness_bounds['cond_entropy_bound'], diff_bellop, 'r-', marker=5)
#ax.legend(handles=[hdiff])
ax.set_title('2-qutrit system - difference between last success and numerical failure')
ax.set_xlabel('conditional entropy')
ax.set_ylabel(f'diff {BELLOP.upper()}')
ax.grid(True)
plt.show(fig)
fig.savefig(path_fig(f'witn_bound33_diffbellop_{BELLOP}.pdf'), **SAVEFIG_KWARGS)
plt.close(fig)
fig, ax = plt.subplots(figsize=(12, 12), dpi=150)
hdiff, = ax.plot(witness_bounds['cond_entropy_bound'], diff_cond_entr, 'r-', marker=5)
#ax.legend(handles=[hdiff])
ax.set_title(f'2-qutrit system - difference between last success and numerical failure ({BELLOP.upper()})')
ax.set_xlabel('conditional entropy')
ax.set_ylabel(f'diff conditional entropy')
ax.grid(True)
plt.show(fig)
fig.savefig(path_fig(f'witn_bound33_diffentr_{BELLOP}.pdf'), **SAVEFIG_KWARGS)
plt.close(fig)
fig, ax = plt.subplots(figsize=(12, 12), dpi=150)
rects = plt.bar(witness_bounds['cond_entropy_bound'], witness_bounds['witncnt_before_failure'], 0.04, label=witness_bounds['witncnt_before_failure'], log=True)
plt.title(f'2-qutrit system - witness count before first numerical failure ({BELLOP.upper()})')
plt.xlabel('conditional entropy')
plt.ylabel('successful iterations (witness count)')
ax.bar_label(rects)
plt.grid()
plt.show(fig)
fig.savefig(path_fig(f'witn33_witncnt_{BELLOP}.pdf'), **SAVEFIG_KWARGS)
plt.close(fig)