def dumbest_dataset(d, p, total_sz, flnm=None): """ Tries the dumbest possible technique, making a bunch of random samples so we can evaluate the gradient without any hassle. p: float (between 0 and 0.5, to make sense it should be ~0.05) total_sz: combined number of training, validation and test instances. """ if not (d % 2): raise ValueError("doesn't work for even d") n_synds = int((d**2 - 1) / 2) sim = dc.Sim2D(d, d, p) input_arr = np.zeros((total_sz, n_synds)) label_arr = np.zeros(total_sz, dtype=np.int_) _, log_z = sim.layout.logicals() ancs = sorted([sim.layout.map[anc] for anc in sim.layout.z_ancs()]) for idx in range(total_sz): err = sim.random_error() x_synd, z_synd = sim.syndromes(err) #x errors only -> z syndromes only input_arr[idx, :] = map(float, synd_to_bits(z_synd, ancs)) #does correcting to the origin result in a logical? dumb_x_corr, _ = sim.dumb_correction((x_synd, z_synd), True) label_arr[idx] = (dumb_x_corr * err).com(log_z) if flnm is None: return {"input": input_arr, "labels": label_arr} else: with open(flnm, 'w') as phil: pkl.dump({"input": input_arr, "labels": label_arr}, phil) pass
def circuit_syndrome_test(): """ compares syndromes generated by measurement circuit with q = 0 to those generated by perfect stabiliser measurement from 2D simulation. They all ought to match. """ two_d_sim = dc2.Sim2D(15, 15, 0.00) three_d_sim = dc3.Sim3D(15, 1000, ('pq', 0.1, 0.0)) err_hist, synd_hist = three_d_sim.history() for idx, err in enumerate(err_hist): idl_x_synd, idl_z_synd = two_d_sim.syndromes(err) assert synd_hist['X'][idx] == set(idl_x_synd) assert synd_hist['Z'][idx] == set(idl_z_synd)
def unique_list(): distance = 5 x_anc_len = 12 test_layout = SCLayoutClass.SCLayout(distance) x_stabs = list(test_layout.stabilisers()['X'].values()) log = test_layout.logicals()[0] sim_test = dc.Sim2D( distance, distance, 0.01) # probability is irrelevant since we provide directly the error lst = [] z_ancs_keys = list(sim_test.layout.z_ancs()) cycles = 0 store_s = [] while len(lst) < 500: cycles += 1 rnd_err = sim_test.random_error() #print(rnd_err) synds = sim_test.syndromes(rnd_err) #print(synds[1]) dumb_x_corr, dumb_z_corr = sim_test.dumb_correction(synds) coset_rep = dumb_x_corr #sp.Pauli({5,13,22,26,33,42,46},{}) prob_dist = single_prob( weight_dist(x_stabs, sp.Pauli(), log, coset_rep), 0.01) list_z = [0] * len(z_ancs_keys) for k in synds[1]: key = sim_test.layout.map.inv[k] pos = z_ancs_keys.index(key) list_z[pos] = 1 s = '' for i in range(x_anc_len): s += str(list_z[i]) if s not in store_s: store_s.append(s) lst.append([s, prob_dist]) if cycles % 20 == 0: print(len(lst), cycles) #print('store_s ', store_s) for i in range(len(lst)): print(lst[i])
def dist_3_corr_tabulate(): """ Mostly a copypasta of dist_5_tabulate, but I'm trying for a depolarizing error model. """ sim_3 = dc.Sim2D(3, 3, 0.00) sim_3.error_model = em.depolarize(0.03, [[sim_3.layout.map[_]] for _ in sim_3.layout.datas]) x_anc_lst = sorted( [sim_3.layout.map[crd] for crd in sim_3.layout.x_ancs()]) z_anc_lst = sorted( [sim_3.layout.map[crd] for crd in sim_3.layout.z_ancs()]) anc_lst = sorted(x_anc_lst + z_anc_lst) log_x, log_z = sim_3.layout.logicals() stab_gens = sum( map(lambda x: x.values(), sim_3.layout.stabilisers().values()), []) synds = it.product(powerset(x_anc_lst), powerset(z_anc_lst)) output_dict = {} blsm_cosets = {} for x_synd, z_synd in synds: coset_rep = reduce( mul, sim_3.dumb_correction([x_synd, z_synd], origin=True)) key = synd_to_bits(x_synd + z_synd, anc_lst) val = full_weight_dist(stab_gens, log_x, log_z, coset_rep) x_corr = sim_3.graphAndCorrection(x_synd, 'Z') z_corr = sim_3.graphAndCorrection(z_synd, 'X') loop = x_corr * z_corr * coset_rep if loop.com(log_z): blsm_cosets[key] = 'Y' if loop.com(log_x) else 'X' else: blsm_cosets[key] = 'Z' if loop.com(log_x) else 'I' output_dict[key] = val with open('corr_wts_3.pkl', 'w') as phil: pkl.dump(output_dict, phil) with open('corr_cosets_3.pkl', 'w') as phil: pkl.dump(blsm_cosets, phil) pass
def path_pauli_len_test(): """ compares lengths of path paulis to distances indicated by pair_dist and bdy_info. """ two_d_sim = dc2.Sim2D(11, 11, 0.0) anc = two_d_sim.layout.ancillas x_pts = sum([list(anc[ki]) for ki in ['x_top', 'x_bot', 'x_sq']], []) z_pts = sum([list(anc[ki]) for ki in ['z_left', 'z_right', 'z_sq']], []) z_pts += two_d_sim.layout.boundary_points('X') x_pts += two_d_sim.layout.boundary_points('Z') for lst, err in zip([x_pts, z_pts], ['Z', 'X']): for pair in it.combinations(lst, 2): dist = dc2.pair_dist(*pair) p_len = two_d_sim.path_pauli(pair[0], pair[1], err).weight() if dist != p_len: print pair, err, dist, p_len assert dist == p_len
def dist_5_fancy_tabulate(): """ I want to know if Tom's weights produce disagreement for independent X/Z decoding @ distance 5. Checking at p = 0.01, there are no different syndromes when using fancy/non-fancy weights """ anc_lst = [0, 1, 8, 10, 18, 20, 28, 30, 38, 40, 47, 48] sim_5 = dc.Sim2D(5, 5, 0.01, useBlossom=False) log_x, log_z = sim_5.layout.logicals() x_stabs = list(sim_5.layout.stabilisers()['X'].values()) weight_dict = {} blsm_cosets = {} d_func = fancy_dist(5, 0.01) #test for other values of p? for subset in powerset(anc_lst): synd = [[], list(subset)] coset_rep = sim_5.dumb_correction(synd, origin=True)[0] g = sim_5.graph(subset, dist_func=d_func) blsm_corr = sim_5.correction(g, 'X') key = synd_to_bits(subset, anc_lst) blsm_cosets[key] = (blsm_corr * coset_rep).com(log_z) return blsm_cosets
def run_batch(err_lo, err_hi, n_points, dists, n_trials, flnm, sim_type='iidxz'): """ Makes a bunch of simulation objects and runs them, based on input parameters. """ sim_type = sim_type.lower() if sim_type not in ['iidxz', 'pq', 'circ']: raise ValueError("sim_type must be one of: ['iidxz', 'pq', 'circ']") errs = np.linspace(err_lo, err_hi, n_points) output_dict = locals() for dist in dists: failures = [] for err in errs: if sim_type == 'iidxz': current_sim = dc2.Sim2D(dist, dist, err) elif sim_type == 'pq': current_sim = dc3.Sim3D(dist, dist, ('pq', err, err)) elif sim_type == 'circ': raise NotImplementedError("Coming Soon!") current_sim.run(n_trials, progress=False) failures.append(current_sim.errors) output_dict.update({'failures ' + str(dist): failures}) with open(flnm, 'wb') as phil: pkl.dump(output_dict, phil) pass
def dist_5_tabulate(): """ I only intend to run this function once, it's going to pickle all the weight_dist's for a distance-5 code correcting x errors. """ anc_lst = [0, 1, 8, 10, 18, 20, 28, 30, 38, 40, 47, 48] sim_5 = dc.Sim2D(5, 5, 0.01) log_x, log_z = sim_5.layout.logicals() x_stabs = list(sim_5.layout.stabilisers()['X'].values()) weight_dict = {} blsm_cosets = {} for subset in powerset(anc_lst): coset_rep = sim_5.dumb_correction([[], list(subset)], origin=True)[0] blsm_corr = sim_5.graphAndCorrection(subset, 'X') key = synd_to_bits(subset, anc_lst) val = weight_dist(x_stabs, sp.Pauli(), log_x, coset_rep) weight_dict[key] = val blsm_cosets[key] = (blsm_corr * coset_rep).com(log_z) with open('weight_counts_5.pkl', 'w') as phil: pkl.dump(weight_dict, phil) with open('blsm_cosets_5.pkl', 'w') as phil: pkl.dump(blsm_cosets, phil)
# test_vec = dist_5_log_error_rate(p_arr) # dist_7_single_sample() #dumbest_dataset(5, 0.08, 1000000, 'd_5_dataset_million') d = 3 ms_rnd = 3 no_anc = int((d + 1) * (d - 1) / 2) p = 0.04 q = 0.04 samples = {} z_ancs = [0, 5, 11, 16] flp = [0] * no_anc flips_Z = [0] * (d + 1) for i in range(d + 1): flips_Z[i] = deepcopy(flp) no_samples = 10000 sim_test2d = dc2.Sim2D(d, d, p) sim_test = dc3.Sim3D(d, d, ('fowler', p), True) #err = sim_test.run(no_samples, progress=False, metric=None, bdy_info=None, final_perfect_rnd=True) #print(err) #calc_parity_3d(dist, meas_rnds, model, use_blossom) for cycl in range(1000000): err, synd = sim_test.history(True) rnd_err = err[2].x_set rd_er = sp.Pauli(rnd_err, []) corr_blossom = sim_test.correction(synd, metric=None, bdy_info=None) mwpm_log_err = sim_test.logical_error(err[-1], corr_blossom) synds_2d = sim_test2d.syndromes(rd_er) dumb_x_corr, dumb_z_corr = sim_test2d.dumb_correction(synds_2d, False) dumb_log_err = sim_test2d.logical_error(rd_er, dumb_x_corr,
from operator import itemgetter cnt = [] lst_z = [] list_train = [] list_target = [] dumb_logical = 0 cycles = 0 distance = 7 no_anc = 24 #((distance * distance)-1)/2 samples = {} while cycles < 1000000: cycles += 1 physprob = 0.005 sim_test = dc.Sim2D(distance, physprob) z_ancs_keys = list(sim_test.layout.z_ancs()) rnd_err = sim_test.random_error() synds = sim_test.syndromes(rnd_err) list_z = [0] * len(z_ancs_keys) for k in synds[1]: key = sim_test.layout.map.inv[k] pos = z_ancs_keys.index(key) list_z[pos] = 1 s = '' for i in range(no_anc): s += str(list_z[i])
import decoding_2d as dc import sparse_pauli as sp import tensorflow as tf import time import random random.seed(time.time()) physprob = 0.004 sim_test = dc.Sim2D(7, physprob) print(physprob) z_ancs_keys = list(sim_test.layout.z_ancs()) logicals = sim_test.layout.logicals() cycles = 0 mwpm_log_err = 0 mwpm = 0 dumb = 0 nn = 0 nn_dumb = 0 cnt_times = 0 temp_list = [] def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.2) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.0, shape=shape) return tf.Variable(initial) inputs = 24
def run_batch(err_lo, err_hi, n_points, dists, n_trials, flnm, sim_type='iidxz', bc='rotated', bp=False): """ Makes a bunch of simulation objects and runs them, based on input parameters. """ sim_type = sim_type.lower() if sim_type not in ['iidxz', 'dep', 'pq', 'circ']: raise ValueError( "sim_type must be one of: ['iidxz', 'dep', 'pq', 'circ']") errs = np.linspace(err_lo, err_hi, n_points) output_dict = locals() for dist in dists: failures = [] for err in errs: if sim_type in ['iidxz', 'dep']: # current_sim = dc2.Sim2D(dist, dist, err, useBlossom=False, boundary_conditions=bc) # dist_func = fancy_dist(dist, err, bc=bc) # dist_func = entropic_dist(dist, err) if bc == 'open': current_sim = dc2.Sim2D(dist, dist, err, useBlossom=True, boundary_conditions=bc) else: current_sim = dc2.Sim2D(dist, dist, err, useBlossom=True, boundary_conditions=bc) elif sim_type == 'pq': current_sim = dc3.Sim3D(dist, dist, ('pq', err, err)) elif sim_type == 'circ': current_sim = dc3.Sim3D(dist, dist, ('fowler', err)) met_fun = dc3.nest_metric(current_sim, err) bdy_fun = dc3.nest_bdy_tpl(current_sim, err) if sim_type == 'dep': current_sim.error_model = em.depolarize( err, [[current_sim.layout.map[_]] for _ in current_sim.layout.datas]) # dist_func = fancy_dist(dist, 0.66666667 * err) current_sim.run(n_trials, progress=False, bp=bp) # current_sim.run(n_trials, progress=False, bp=bp, bp_rounds=0) # current_sim.run(n_trials, progress=False, # metric=met_fun, bdy_info=bdy_fun) # current_sim.run(n_trials, progress=False, dist_func=dist_func) # hb.bravyi_run(current_sim, n_trials) failures.append(current_sim.errors) output_dict.update({'failures ' + str(dist): failures}) with open(flnm, 'wb') as phil: pkl.dump(output_dict, phil) pass
curr_corr = dumb_corr for stab_set in powerset(stabs): cs_prod = reduce(mul, stab_set, dumb_corr) for log in all_logs: test_corr = cs_prod * log if test_corr.weight() < curr_corr.weight(): curr_corr = test_corr return curr_corr def main(sim): xs = [sim.layout.map[_] for _ in sim.layout.x_ancs()] zs = [sim.layout.map[_] for _ in sim.layout.z_ancs()] x_combos = powerset(xs) z_combos = powerset(zs) stabs = sim.layout.stabilisers() stabs = [d.values() for d in stabs.values() ][0] + [d.values() for d in stabs.values()][1] logs = sim.layout.logicals() table = dict() bar = pb.ProgressBar() for synds in bar(list(it.product(x_combos, z_combos))): table[synds] = mwe(sim, synds, stabs, logs) return table if __name__ == '__main__': test_sim = dc2.Sim2D(3, 3, 0.0) table = main(test_sim)
dx = 12 dy = 12 p = 0.01 useBlossom = True trials = 1 print("Surface Code Simulation") useBlossom = True print("\n".join([ "Starting simulation with blossom", "trials : {}".format(trials), "dx : {}".format(dx), "dy : {}".format(dy), "p : {}".format(p), "useBlossom : {}".format(useBlossom) ])) sim = dc.Sim2D(dx, dy, p, useBlossom) start = timer() # prf.run("sim.run(trials, False, False, None, True)", "imran_blsm.prof") sim.run(trials, False, False, None, True) end = timer() totaltime = (end - start) print("Execution took : {0} ms".format(totaltime * 1e3)) del sim #useBlossom = True #print("\n".join([ #"Starting simulation with blossom", #"trials : {}".format(trials), #"dx : {}".format(dx), #"dy : {}".format(dy), #"p : {}".format(p),
import decoding_2d as dc import sparse_pauli as sp import tensorflow as tf import numpy as np import time from datetime import timedelta import random d = 3 p = 0.007 iterations = 200 sim_test = dc.Sim2D(d, d, p) z_ancs_keys = list(sim_test.layout.z_ancs()) logicals = sim_test.layout.logicals() cycles = 0 mwpm_log_err = 0 plut_log_err = 0 mwpm = 0 dumb = 0 nn = 0 def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.01) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.05, shape=shape) return tf.Variable(initial)
import decoding_2d as dc import sparse_pauli as sp import tensorflow as tf sim_test = dc.Sim2D(5, 0.1) z_ancs_keys = list(sim_test.layout.z_ancs()) logicals = sim_test.layout.logicals() cycles = 0 mwpm_log_err = 0 mwpm = 0 dumb = 0 nn = 0 def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.2) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.0, shape=shape) return tf.Variable(initial) inputs = 12 outputs = 1 nodes = [24] x_test = tf.placeholder(tf.float32, shape=[1, inputs]) W = [] W.append(weight_variable([inputs, nodes[0]]))