<jupyter_start><jupyter_text>Evaluation for minimal example *file*<jupyter_code># load data
import os
import numpy as np

best_sol_path = "experiments/1_qubit_model"
print(best_sol_path)<jupyter_output><empty_output><jupyter_text>Data analysis for results<jupyter_code>import json
res_path = os.path.join(best_sol_path,"results.json")
with open(res_path) as json_file:
    results = json.load(json_file)
from pprint import pprint
pprint(results)
from scipy.stats import spearmanr
# convert to numpy array
results_np = np.array([results[r] for r in results])
spearmanr(results_np)
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# create boxplots
results_high = [results[r][1] for r in results if (results[r][0]==1 and r.split(" ")[0] != "file")]
highs = ["High" for i in range(len(results_high))]
results_low = [1-results[r][1] for r in results if results[r][0]==0 and r.split(" ")[0] != "file"]
lows = ["Low" for i in range(len(results_low))]
results_amb = [results[r][1] for r in results if (r.split(" ")[0] == "file")]
ambs = ["Amb" for i in range(len(results_amb))]
data = pd.DataFrame({"Similarity": results_high+results_low+results_amb, "type": highs+lows+ambs})


dims = (10,7)
fig, ax = plt.subplots(figsize=dims)
plt.rcParams["font.size"] = "18"
ax = sns.boxplot(ax=ax, x="type", y="Similarity", data=data)
ax.set(ylim=(0.5, 1.1));<jupyter_output><empty_output><jupyter_text>Visualize vector on Bloch Sphere<jupyter_code>from jdiscopy.quantum import Ket, H, Rx, Ry, Rz, CX, sqrt, X, Circuit
from random import uniform
from math import pi


# Ansätze for 1-qubit states
def un_amb_verb_ansatz(p):
    return Ket(p[0])

def amb_verb_ansatz(p):
    return Ket(0) >> \
        Rx(p[0])

def noun_ansatz(p):
    return Ket(0) >> \
        Rx(p[0]) >> \
        Rz(p[1])


n_qubits_ansatz = 1
n_noun_params = 2
n_amb_params = 0

import jdiscopy.quantum as dq
dq.Rx
params_amb_verbs_path = os.path.join(best_sol_path,"parameters_amb_verbs.json")
with open(params_amb_verbs_path) as json_file:
    params_amb_verbs = json.load(json_file)
print(params_amb_verbs)

params_unamb_verbs_path = os.path.join(best_sol_path,"parameters_unamb_verbs.json")
with open(params_unamb_verbs_path) as json_file:
    params_unamb_verbs = json.load(json_file)
print(params_unamb_verbs)

params_nouns_path = os.path.join(best_sol_path,"params_nouns.json")
with open(params_nouns_path) as json_file:
    params_nouns = json.load(json_file)
print(params_nouns)

import qutip
from qutip.expect import expect
from qutip.operators import sigmax, sigmay, sigmaz
from qutip import Qobj

def convert_to_bloch_vec(states):
    if isinstance(states, Qobj):
        states = [states]
    
    vecs = []
    for state in states:
        vec = [expect(sigmax(), state),
                expect(sigmay(), state),
                expect(sigmaz(), state)]
        vecs.append(vec)
    return np.transpose(np.array(vecs))


vec = qutip.Qobj(amb_verb_ansatz(params_amb_verbs["file"]).eval().array)
unamb_verb_states = [qutip.Qobj(un_amb_verb_ansatz(params_unamb_verbs[verb]).eval().array) for verb in params_unamb_verbs]
noun_states_reg = convert_to_bloch_vec([qutip.Qobj(noun_ansatz(params_nouns[noun]).eval().array) for noun in params_nouns if results["register "+noun+"."][0]==1])
noun_states_smo = convert_to_bloch_vec([qutip.Qobj(noun_ansatz(params_nouns[noun]).eval().array) for noun in params_nouns if results["smooth "+noun+"."][0]==1])

vec
%matplotlib inline
b = qutip.Bloch(figsize=(7, 10))
b.add_states(vec)
b.add_states(unamb_verb_states)
b.add_points(noun_states_reg,meth="s")
b.add_points(noun_states_smo,meth="s")
b.render()<jupyter_output><empty_output><jupyter_text>Make animation with evolution data<jupyter_code>params_evo_path = os.path.join(best_sol_path,"params_evolution_noisy.json")
with open(params_evo_path) as json_file:
    params_evolution = json.load(json_file)
import matplotlib
from matplotlib import pyplot, animation
from mpl_toolkits.mplot3d import Axes3D

fig = pyplot.figure(figsize=(7,7),dpi=300)
ax = Axes3D(fig,azim=-40,elev=30)
sphere = qutip.Bloch(axes=ax)

def animate(frame):
    params_amb_verbs = params_evolution[frame]["amb_verbs"]
    params_nouns = params_evolution[frame]["nouns"]

    vec = qutip.Qobj(amb_verb_ansatz(params_amb_verbs["file"]).eval().array)
    unamb_verb_states = [qutip.Qobj(un_amb_verb_ansatz(params_unamb_verbs[verb]).eval().array) for verb in params_unamb_verbs]
    noun_states_reg = convert_to_bloch_vec([qutip.Qobj(noun_ansatz(params_nouns[noun]).eval().array) for noun in params_nouns if results["register "+noun+"."][0]==1])
    noun_states_smo = convert_to_bloch_vec([qutip.Qobj(noun_ansatz(params_nouns[noun]).eval().array) for noun in params_nouns if results["smooth "+noun+"."][0]==1])
    
    sphere.clear()
    sphere.add_states(vec)
    sphere.add_states(unamb_verb_states)
    sphere.add_points(noun_states_reg, meth="s")
    sphere.add_points(noun_states_smo, meth="s")
    sphere.make_sphere()

    return ax

def init():
   return ax

ani = animation.FuncAnimation(fig, animate, list(params_evolution.keys())[0:-1],
                              init_func=init, repeat=False);
ani.save('bloch_sphere.mp4', fps=30);<jupyter_output><empty_output><jupyter_text>Plot SPSA fit<jupyter_code>import matplotlib.pyplot as plt

loss = params_evolution["loss"]

dims = (10,7)
fig, ax = plt.subplots(figsize=dims)
plt.rcParams["font.size"] = "14"
plt.plot(range(len(loss)), loss, '-b', label='loss')
plt.xlabel("Iteration")
plt.ylabel("MSE")
plt.legend(loc='upper right')
plt.title("SPSA optimization 1-qubit example")<jupyter_output><empty_output><jupyter_text>Plot blochsphere process<jupyter_code>%matplotlib inline
frames = list(params_evolution.keys())[0:-1]
frames_to_plot = [frames[0], frames[49], frames[99], frames[199]]

dims = (7,7)
fig, ax = plt.subplots(figsize=dims)
ax = Axes3D(fig,azim=-40,elev=30)
sphere = qutip.Bloch(axes=ax)

frame = frames_to_plot[0]
params_amb_verbs = params_evolution[frame]["amb_verbs"]
params_nouns = params_evolution[frame]["nouns"]

vec = qutip.Qobj(amb_verb_ansatz(params_amb_verbs["file"]).eval().array)
unamb_verb_states = [qutip.Qobj(un_amb_verb_ansatz(params_unamb_verbs[verb]).eval().array) for verb in params_unamb_verbs]
noun_states_reg = convert_to_bloch_vec([qutip.Qobj(noun_ansatz(params_nouns[noun]).eval().array) for noun in params_nouns if results["register "+noun+"."][0]==1])
noun_states_smo = convert_to_bloch_vec([qutip.Qobj(noun_ansatz(params_nouns[noun]).eval().array) for noun in params_nouns if results["smooth "+noun+"."][0]==1])

sphere.clear()
sphere.add_states(vec)
sphere.add_states(unamb_verb_states)
sphere.add_points(noun_states_reg, meth="s")
sphere.add_points(noun_states_smo, meth="s")
sphere.render()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1423933894053416, 'fraction_numerical': 0.012837538733953076, 'mean_word_length': 6.415754923413567, 'pattern_counts': {'":': 2, '<': 25, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '111760', 'license': 'MIT', 'n_tokens_mistral': 2735, 'n_tokens_neox': 2642, 'n_words': 455, 'path': 'Evaluation_1qb_model.ipynb', 'repo_name': 'chapmanbe/Quantum-Models-for-Word-Sense-Disambiguation', 'size': '6777'}