def test_circuitsim_stabilizer_1Qcheck(self): from pygsti.modelpacks import smq1Q_XYI as stdChk maxLengths = [1, 2, 4] listOfExperiments = pygsti.circuits.create_lsgst_circuits( stdChk.target_model(), stdChk.prep_fiducials(), stdChk.meas_fiducials(), stdChk.germs(), maxLengths) #listOfExperiments = pygsti.circuits.to_circuits([ ('Gcnot','Gxi') ]) #listOfExperiments = pygsti.circuits.to_circuits([ ('Gxi','Gcphase','Gxi','Gix') ]) mdl_normal = stdChk.target_model() self.assertTrue(mdl_normal._evotype == "densitymx") mdl_clifford = stdChk.target_model("static clifford", evotype='stabilizer') mdl_clifford.sim = "map" # only map sim works for stabilizer evotype #print(mdl_clifford['Gcnot']) #mdl_clifford.set_all_parameterizations('static unitary') # reduces dim... #self.assertTrue(mdl_clifford._evotype == "statevec") #mdl_clifford.set_all_parameterizations('clifford') self.assertTrue(mdl_clifford._evotype == "stabilizer") for opstr in listOfExperiments: #print(str(opstr)) p_normal = mdl_normal.probabilities(opstr) p_clifford = mdl_clifford.probabilities(opstr) #p_clifford = bprobs[opstr] for outcm in p_normal.keys(): if abs(p_normal[outcm] - p_clifford[outcm]) > 1e-8: print(str(opstr), " ERR: \n", p_normal, "\n", p_clifford) self.assertTrue(False) print("Done checking %d sequences!" % len(listOfExperiments))
def test_gst(self): comm = self.ralloc.comm exp_design = std.get_gst_experiment_design(4) mdl_datagen = std.target_model().depolarize(op_noise=0.1, spam_noise=0.01) ds = pygsti.data.simulate_data(mdl_datagen, exp_design, 1000, seed=1234, comm=comm) data = pygsti.protocols.ProtocolData(exp_design, ds) initial_model = std.target_model("full TP") proto = pygsti.protocols.GateSetTomography( initial_model, verbosity=1, optimizer={ 'maxiter': 100, 'serial_solve_proc_threshold': 100 }) results_serial = proto.run(data, comm=None) results_parallel = proto.run(data, comm=comm) # compare resulting models if comm is None or comm.rank == 0: best_params_serial = results_serial.estimates[ "GateSetTomography"].models['stdgaugeopt'].to_vector() best_params_parallel = results_parallel.estimates[ "GateSetTomography"].models['stdgaugeopt'].to_vector() assert np.allclose(best_params_serial, best_params_parallel)
def test_stdgst_prunedpath(self): # Using term-based (path integral) calculation with path pruning # This performs a map-based unitary evolution along each path. target_model = std.target_model("static unitary", evotype='statevec') target_model.set_all_parameterizations("H+S") target_model.sim = pygsti.forwardsims.TermForwardSimulator( mode='pruned', max_order=3, desired_perr=0.01, allowed_perr=0.1, max_paths_per_outcome=1000, perr_heuristic='meanscaled', max_term_stages=5) target_model.from_vector( 1e-10 * np.ones(target_model.num_params) ) # to seed term calc (starting with perfect zeros causes trouble) results = pygsti.run_long_sequence_gst(self.ds, target_model, std.prep_fiducials(), std.meas_fiducials(), std.germs(), self.maxLengths, verbosity=3) #RUN BELOW LINES TO SAVE GATESET (SAVE) if regenerate_references(): pygsti.serialization.json.dump( results.estimates[results.name].models['go0'], open(compare_files + "/test1Qcalc_std_prunedpath.model", 'w')) print("MISFIT nSigma = ", results.estimates[results.name].misfit_sigma()) self.assertAlmostEqual(results.estimates[results.name].misfit_sigma(), 1, delta=1.0)
def test_stdgst_map(self): # Using map-based calculation target_model = std.target_model() target_model.set_all_parameterizations("CPTP") target_model.sim = 'map' results = pygsti.run_long_sequence_gst(self.ds, target_model, std.prep_fiducials(), std.meas_fiducials(), std.germs(), self.maxLengths, verbosity=4) print("MISFIT nSigma = ", results.estimates[results.name].misfit_sigma()) self.assertAlmostEqual(results.estimates[results.name].misfit_sigma(), 1.0, delta=2.0) mdl_compare = pygsti.serialization.json.load( open(compare_files + "/test1Qcalc_std_exact.model")) gsEstimate = results.estimates[results.name].models['go0'].copy() gsEstimate.set_all_parameterizations("full") gsEstimate = pygsti.algorithms.gaugeopt_to_target( gsEstimate, mdl_compare) self.assertAlmostEqual(gsEstimate.frobeniusdist(mdl_compare), 0, places=0)
def test_fisher_information(self): target_model = smq1Q_XYI.target_model('TP') edesign = smq1Q_XYI.create_gst_experiment_design(8) # Basic usage start = time.time() fim1 = et.calculate_fisher_information_matrix(target_model, edesign.all_circuits_needing_data) fim1_time = time.time() - start # Try external regularized model version regularized_model = target_model.copy().depolarize(spam_noise=1e-3) fim2 = et.calculate_fisher_information_matrix(regularized_model, edesign.all_circuits_needing_data, regularize_spam=False) self.assertArraysAlmostEqual(fim1, fim2) # Try pre-cached version fim3_terms = et.calculate_fisher_information_per_circuit(regularized_model, edesign.all_circuits_needing_data) start = time.time() fim3 = et.calculate_fisher_information_matrix(target_model, edesign.all_circuits_needing_data, term_cache=fim3_terms) fim3_time = time.time() - start self.assertArraysAlmostEqual(fim1, fim3) self.assertLess(10*fim3_time, fim1_time) # Cached version should be very fast compared to uncached # Try by-L version fim_by_L = et.calculate_fisher_information_matrices_by_L(target_model, edesign.all_circuits_needing_data) self.assertArraysAlmostEqual(fim1, fim_by_L[8]) # Try pre-cached by-L version start = time.time() fim_by_L2 = et.calculate_fisher_information_matrices_by_L(target_model, edesign.all_circuits_needing_data, term_cache=fim3_terms) fim_by_L2_time = time.time() - start for k,v in fim_by_L2.items(): self.assertArraysAlmostEqual(v, fim_by_L[k]) self.assertLess(10*fim_by_L2_time, fim1_time) # Cached version should be very fast compared to uncached
def test_MPI_products(self): comm = self.ralloc.comm #Create some model mdl = std.target_model() mdl.kick(0.1, seed=1234) #Get some operation sequences maxLengths = [1, 2, 4, 8] gstrs = pygsti.circuits.create_lsgst_circuits(std.target_model(), std.fiducials(), std.fiducials(), std.germs(), maxLengths) #Check bulk products #bulk_product - no parallelization unless layout is split serial = mdl.sim.bulk_product(gstrs, scale=False) parallel = mdl.sim.bulk_product(gstrs, scale=False, resource_alloc=self.ralloc) assert (np.linalg.norm(serial - parallel) < 1e-6) serial_scl, sscale = mdl.sim.bulk_product(gstrs, scale=True) parallel, pscale = mdl.sim.bulk_product(gstrs, scale=True, resource_alloc=self.ralloc) assert (np.linalg.norm(serial_scl * sscale[:, None, None] - parallel * pscale[:, None, None]) < 1e-6) #bulk_dproduct - no split tree => parallel by col serial = mdl.sim.bulk_dproduct(gstrs, scale=False) parallel = mdl.sim.bulk_dproduct(gstrs, scale=False, resource_alloc=self.ralloc) assert (np.linalg.norm(serial - parallel) < 1e-6) serial_scl, sscale = mdl.sim.bulk_dproduct(gstrs, scale=True) parallel, pscale = mdl.sim.bulk_dproduct(gstrs, scale=True, resource_alloc=self.ralloc) assert (np.linalg.norm(serial_scl * sscale[:, None, None, None] - parallel * pscale[:, None, None, None]) < 1e-6)
def test_MPI_probs(self): comm = self.ralloc.comm #Create some model mdl = std.target_model() mdl.kick(0.1, seed=1234) #Get some operation sequences maxLengths = [1, 2, 4] circuits = pygsti.circuits.create_lsgst_circuits( list(std.target_model().operations.keys()), std.prep_fiducials(), std.meas_fiducials(), std.germs(), maxLengths) #Check all-spam-label bulk probabilities def compare_prob_dicts(a, b, indices=None): for opstr in circuits: for outcome in a[opstr].keys(): if indices is None: assert (np.linalg.norm(a[opstr][outcome] - b[opstr][outcome]) < 1e-6) else: for i in indices: assert (np.linalg.norm(a[opstr][outcome][i] - b[opstr][outcome][i]) < 1e-6) # non-split tree => automatically adjusts wrt_block_size to accomodate # the number of processors serial = mdl.sim.bulk_probs(circuits, clip_to=(-1e6, 1e6)) parallel = mdl.sim.bulk_probs(circuits, clip_to=(-1e6, 1e6), resource_alloc=self.ralloc) if comm is None or comm.rank == 0: # output is only given on root proc compare_prob_dicts(serial, parallel) serial = mdl.sim.bulk_dprobs(circuits) parallel = mdl.sim.bulk_dprobs(circuits, resource_alloc=self.ralloc) if comm is None or comm.rank == 0: # output is only given on root proc compare_prob_dicts(serial, parallel) serial = mdl.sim.bulk_hprobs(circuits) parallel = mdl.sim.bulk_hprobs(circuits, resource_alloc=self.ralloc) if comm is None or comm.rank == 0: # output is only given on root proc compare_prob_dicts(serial, parallel, (0, 1, 2))
def test_circuitsim_densitymx(self): # Density-matrix simulation (of superoperator gates) # These are the typical type of simulations used within GST. # The probability calculations can be done in a matrix- or map-based way. #Using simple "std" models (which are all density-matrix/superop type) mdl = std.target_model() probs1 = mdl.probabilities(self.circuit1) #self.circuit1.simulate(mdl) # calls probs - same as above line print(probs1) gs2 = std.target_model() gs2.sim = "map" probs1 = gs2.probabilities(self.circuit1) #self.circuit1.simulate(gs2) # calls probs - same as above line print(probs1) self.assert_outcomes(probs1, {('0', ): 0.5, ('1', ): 0.5}) #Using n-qubit models pspec = pygsti.processors.QubitProcessorSpec( self.csim_nQubits, ['Gi', 'Gxpi', 'Gypi', 'Gcnot'], geometry='line') mdl = pygsti.models.modelconstruction.create_crosstalk_free_model( pspec, simulator="matrix", ensure_composed_gates=False) probs1 = mdl.probabilities(self.circuit3) mdl = pygsti.models.modelconstruction.create_crosstalk_free_model( pspec, simulator="map", ensure_composed_gates=False) probs2 = mdl.probabilities(self.circuit3) expected = { ('000', ): 0.0, ('001', ): 0.0, ('010', ): 0.0, ('011', ): 0.0, ('100', ): 0.0, ('101', ): 0.0, ('110', ): 0.0, ('111', ): 1.0 } print(probs1) print(probs2) self.assert_outcomes(probs1, expected) self.assert_outcomes(probs2, expected)
def test_run(self): proto = gst.GateSetTomography(smq1Q_XYI.target_model("CPTP"), 'stdgaugeopt', name="testGST") results = proto.run(self.gst_data) mdl_result = results.estimates["testGST"].models['stdgaugeopt'] twoDLogL = two_delta_logl(mdl_result, self.gst_data.dataset) self.assertLessEqual(twoDLogL, 1.0) # should be near 0 for perfect data
def setUpClass(cls): cls.gst_design = smq1Q_XYI.get_gst_experiment_design(max_max_length=4) cls.mdl_target = smq1Q_XYI.target_model() cls.mdl_datagen = cls.mdl_target.depolarize(op_noise=0.05, spam_noise=0.025) ds = simulate_data(cls.mdl_datagen, cls.gst_design.all_circuits_needing_data, 1000, sample_error='none') cls.gst_data = ProtocolData(cls.gst_design, ds)
def test_stdgst_terms(self): # Using term-based (path integral) calculation # This performs a map-based unitary evolution along each path. target_model = std.target_model("static unitary", evotype='statevec') target_model.set_all_parameterizations("H+S") target_model.sim = pygsti.forwardsims.TermForwardSimulator( mode='taylor-order', max_order=1) target_model._print_gpindices() target_model.from_vector( 1e-10 * np.ones(target_model.num_params) ) # to seed term calc (starting with perfect zeros causes trouble) results = pygsti.run_long_sequence_gst(self.ds, target_model, std.prep_fiducials(), std.meas_fiducials(), std.germs(), self.maxLengths, verbosity=4) #RUN BELOW LINES TO SAVE GATESET (SAVE) if regenerate_references(): pygsti.serialization.json.dump( results.estimates[results.name].models['go0'], open(compare_files + "/test1Qcalc_std_terms.model", 'w')) print("MISFIT nSigma = ", results.estimates[results.name].misfit_sigma()) self.assertAlmostEqual(results.estimates[results.name].misfit_sigma(), 1, delta=1.0) mdl_compare = pygsti.serialization.json.load( open(compare_files + "/test1Qcalc_std_terms.model")) # can't easily gauge opt b/c term-based models can't be converted to "full" #mdl_compare.set_all_parameterizations("full") # #gsEstimate = results.estimates[results.name].models['go0'].copy() #gsEstimate.set_all_parameterizations("full") #gsEstimate = pygsti.algorithms.gaugeopt_to_target(gsEstimate, mdl_compare) #self.assertAlmostEqual( gsEstimate.frobeniusdist(mdl_compare), 0, places=0) #A direct vector comparison works if python (&numpy?) versions are identical, but # gauge freedoms make this incorrectly fail in other cases - so just check sigmas print("VEC DIFF = ", (results.estimates[results.name].models['go0'].to_vector() - mdl_compare.to_vector())) self.assertAlmostEqual(np.linalg.norm( results.estimates[results.name].models['go0'].to_vector() - mdl_compare.to_vector()), 0, places=1)
def test_stdgst_matrix(self): # Using matrix-based calculations target_model = std.target_model() target_model.set_all_parameterizations("CPTP") target_model.sim = 'matrix' # the default for 1Q, so we could remove this line results = pygsti.run_long_sequence_gst(self.ds, target_model, std.prep_fiducials(), std.meas_fiducials(), std.germs(), self.maxLengths, verbosity=4) #CHECK that copy gives identical models - this is checked by other # unit tests but here we're using a true "GST model" - so do it again: print("CHECK COPY") mdl = results.estimates[results.name].models['go0'] mdl_copy = mdl.copy() print(mdl.strdiff(mdl_copy)) self.assertAlmostEqual(mdl.frobeniusdist(mdl_copy), 0, places=2) #RUN BELOW LINES TO SAVE GATESET (SAVE) if regenerate_references(): pygsti.serialization.json.dump( results.estimates[results.name].models['go0'], open(compare_files + "/test1Qcalc_std_exact.model", 'w')) print("MISFIT nSigma = ", results.estimates[results.name].misfit_sigma()) self.assertAlmostEqual(results.estimates[results.name].misfit_sigma(), 1.0, delta=2.0) mdl_compare = pygsti.serialization.json.load( open(compare_files + "/test1Qcalc_std_exact.model")) #gauge opt before compare gsEstimate = results.estimates[results.name].models['go0'].copy() gsEstimate.set_all_parameterizations("full") gsEstimate = pygsti.algorithms.gaugeopt_to_target( gsEstimate, mdl_compare) print(gsEstimate.strdiff(mdl_compare)) self.assertAlmostEqual(gsEstimate.frobeniusdist(mdl_compare), 0, places=1)
def setUpClass(cls): #Construct a results object gst_design = smq1Q_XYI.get_gst_experiment_design(max_max_length=4) mdl_target = smq1Q_XYI.target_model() mdl_datagen = mdl_target.depolarize(op_noise=0.05, spam_noise=0.025) ds = simulate_data(mdl_datagen, gst_design.all_circuits_needing_data, 1000, seed=2020) data = ProtocolData(gst_design, ds) cls.results = gst.ModelEstimateResults(data, Protocol("test-protocol")) cls.results.add_estimate(Estimate.create_gst_estimate( cls.results, mdl_target, mdl_target, [mdl_datagen] * len(gst_design.circuit_lists), parameters={'objective': 'logl'}), estimate_key="test-estimate") cls.target_model = mdl_target
def test_simulate_data(self): comm = self.ralloc.comm exp_design = std.get_gst_experiment_design(4) mdl_datagen = std.target_model().depolarize(op_noise=0.1, spam_noise=0.01) ds_serial = pygsti.data.simulate_data(mdl_datagen, exp_design, 1000, seed=1234, comm=None) ds_parallel = pygsti.data.simulate_data(mdl_datagen, exp_design, 1000, seed=1234, comm=comm) if comm is None or comm.rank == 0: assert (set(ds_serial.keys()) == set(ds_parallel.keys())) for key in ds_serial.keys(): assert (ds_serial[key].to_dict() == ds_parallel[key].to_dict())
def run_objfn_values(self, sim, objfn, natoms): comm = self.ralloc.comm mdl = std.target_model() exp_design = std.get_gst_experiment_design(1) mdl_datagen = mdl.depolarize(op_noise=0.01, spam_noise=0.01) ds = pygsti.data.simulate_data(mdl_datagen, exp_design, 1000, seed=1234, comm=comm) builder = pygsti.objectivefns.ObjectiveFunctionBuilder.create_from( objfn) builder.additional_args['array_types'] = ('EP', 'EPP' ) # HACK - todo this better if sim == 'map': mdl.sim = pygsti.forwardsims.MapForwardSimulator(num_atoms=natoms) elif sim == 'matrix': mdl.sim = pygsti.forwardsims.MatrixForwardSimulator( num_atoms=natoms) else: raise RuntimeError( "Improper sim type passed by test_objfn_generator") circuits = exp_design.all_circuits_needing_data[0:10] objfn_parallel = builder.build(mdl, ds, circuits, self.ralloc, verbosity=0) objfn_serial = builder.build(mdl, ds, circuits, None, verbosity=0) #LSVEC TEST v_ref = objfn_serial.lsvec() v = objfn_parallel.lsvec() globalv = objfn_parallel.layout.gather_local_array('e', v) if comm is None or comm.rank == 0: finalv = np.empty_like(globalv) off = 0 for c in circuits: indices, outcomes = objfn_parallel.layout.global_layout.indices_and_outcomes( c) assert (outcomes == (('0', ), ('1', )) ) # I think this should always be the ordering (?) finalv[off:off + len(outcomes)] = globalv[indices] off += len(outcomes) finalv_ref = np.empty_like(v_ref) off = 0 for c in circuits: indices, outcomes = objfn_serial.layout.indices_and_outcomes(c) assert (outcomes == (('0', ), ('1', )) ) # I think this should always be the ordering (?) finalv_ref[off:off + len(outcomes)] = v_ref[indices] off += len(outcomes) assert np.allclose(finalv, finalv_ref) #TODO: DLSVEC? #HESSIAN TEST hessian_ref = objfn_serial.hessian() hessian = objfn_parallel.hessian( ) # already a global qty, just on root proc bhessian_ref = objfn_serial.hessian_brute() bhessian = objfn_parallel.hessian_brute() if comm is None or comm.rank == 0: assert np.allclose(bhessian_ref, hessian_ref) assert np.allclose(hessian, hessian_ref) assert np.allclose(bhessian, bhessian_ref)
def setUpClass(cls): """ Handle all once-per-class (slow) computation and loading, to avoid calling it for each test (like setUp). Store results in class variable for use within setUp. """ super(CalcMethods1QTestCase, cls).setUpClass() #Change to test_packages directory (since setUp hasn't been called yet...) origDir = os.getcwd() os.chdir(os.path.abspath(os.path.dirname(__file__))) os.chdir('..') # The test_packages directory #Standard GST dataset cls.maxLengths = [1, 2, 4] cls.mdl_datagen = std.target_model().depolarize(op_noise=0.03, spam_noise=0.001) cls.listOfExperiments = pygsti.circuits.create_lsgst_circuits( std.target_model(), std.prep_fiducials(), std.meas_fiducials(), std.germs(), cls.maxLengths) #RUN BELOW FOR DATAGEN (SAVE) if regenerate_references(): ds = pygsti.data.simulate_data(cls.mdl_datagen, cls.listOfExperiments, num_samples=1000, sample_error="multinomial", seed=1234) ds.save(compare_files + "/calcMethods1Q.dataset") #DEBUG TEST- was to make sure data files have same info -- seemed ultimately unnecessary #ds_swp = pygsti.objects.DataSet(file_to_load_from=compare_files + "/calcMethods1Q.datasetv3") # run in Python3 #pygsti.io.write_dataset(temp_files + "/dataset.3to2.txt", ds_swp) # run in Python3 #ds_swp = pygsti.io.read_dataset(temp_files + "/dataset.3to2.txt") # run in Python2 #ds_swp.save(compare_files + "/calcMethods1Q.dataset") # run in Python2 #assert(False),"STOP" cls.ds = pygsti.data.DataSet(file_to_load_from=compare_files + "/calcMethods1Q.dataset") #Reduced model GST dataset cls.nQubits = 1 # can't just change this now - see op_labels below cls.mdl_redmod_datagen = build_XYCNOT_cloudnoise_model( cls.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, simulator="matrix", verbosity=1, roughNoise=(1234, 0.01)) #Create a reduced set of fiducials and germs op_labels = [L('Gx', 0), L('Gy', 0)] # 1Q gate labels fids1Q = std1Q_XY.fiducials[ 1:2] # for speed, just take 1 non-empty fiducial cls.redmod_fiducials = [ Circuit([], line_labels=(0, )) ] # special case for empty fiducial (need to change line label) for i in range(cls.nQubits): cls.redmod_fiducials.extend( pygsti.circuits.manipulate_circuits(fids1Q, [((L('Gx'), ), (L('Gx', i), )), ((L('Gy'), ), (L('Gy', i), ))])) #print(redmod_fiducials, "Fiducials") cls.redmod_germs = pygsti.circuits.to_circuits([(gl, ) for gl in op_labels]) cls.redmod_maxLs = [1] expList = pygsti.circuits.create_lsgst_circuits( op_labels, cls.redmod_fiducials, cls.redmod_fiducials, cls.redmod_germs, cls.redmod_maxLs) #RUN BELOW FOR DATAGEN (SAVE) if regenerate_references(): redmod_ds = pygsti.data.simulate_data(cls.mdl_redmod_datagen, expList, 1000, "round", seed=1234) redmod_ds.save(compare_files + "/calcMethods1Q_redmod.dataset") cls.redmod_ds = pygsti.data.DataSet(file_to_load_from=compare_files + "/calcMethods1Q_redmod.dataset") #print(len(expList)," reduced model sequences") #Random starting points - little kick so we don't get hung up at start np.random.seed(1234) cls.rand_start18 = np.random.random(18) * 1e-6 cls.rand_start25 = np.random.random(30) * 1e-6 # TODO: rename? cls.rand_start36 = np.random.random(30) * 1e-6 # TODO: rename? #Circuit Simulation circuits cls.csim_nQubits = 3 cls.circuit1 = pygsti.circuits.Circuit((('Gxpi2', 0), ('Gypi2', 0))) # now Circuit adds qubit labels... pygsti.circuits.Circuit(layer_labels=('Gx','Gy'), num_lines=1) # 1-qubit circuit cls.circuit3 = pygsti.circuits.Circuit(layer_labels=[('Gxpi', 0), ('Gypi', 1), ('Gcnot', 1, 2)], num_lines=3) # 3-qubit circuit os.chdir(origDir) # return to original directory
def run_fills(self, sim, natoms, nparams): comm = self.ralloc.comm #Create some model mdl = std.target_model() mdl.kick(0.1, seed=1234) #Get some operation sequences maxLengths = [1] circuits = pygsti.circuits.create_lsgst_circuits( list(std.target_model().operations.keys()), std.prep_fiducials(), std.meas_fiducials(), std.germs(), maxLengths) nP = mdl.num_params if sim == 'map': mdl.sim = pygsti.forwardsims.MapForwardSimulator( num_atoms=natoms, param_blk_sizes=(nparams, nparams)) elif sim == 'matrix': mdl.sim = pygsti.forwardsims.MatrixForwardSimulator( num_atoms=natoms, param_blk_sizes=(nparams, nparams)) else: raise RuntimeError( "Improper sim type passed by test_fills_generator") serial_layout = mdl.sim.create_layout(circuits, array_types=('E', 'EP', 'EPP'), derivative_dimension=nP) nE = serial_layout.num_elements nC = len(circuits) vp_serial = np.empty(nE, 'd') vdp_serial = np.empty((nE, nP), 'd') vhp_serial = np.empty((nE, nP, nP), 'd') mdl.sim.bulk_fill_probs(vp_serial, serial_layout) mdl.sim.bulk_fill_dprobs(vdp_serial, serial_layout) mdl.sim.bulk_fill_hprobs(vhp_serial, serial_layout) #Note: when there are multiple atoms, the serial_layout returned above may not preserve # the original circuit ordering, i.e., serial_layout.circuits != circuits. The global # layout does have this property, and so we use it to avoid having to lookup which circuit # is which index in serial_layout. No gathering is needed, since there only 1 processor. global_serial_layout = serial_layout.global_layout #Use a parallel layout to compute the same probabilities & their derivatives local_layout = mdl.sim.create_layout(circuits, array_types=('E', 'EP', 'EPP'), derivative_dimension=nP, resource_alloc=self.ralloc) vp_local = local_layout.allocate_local_array('e', 'd') vdp_local = local_layout.allocate_local_array('ep', 'd') vhp_local = local_layout.allocate_local_array('epp', 'd') mdl.sim.bulk_fill_probs(vp_local, local_layout) mdl.sim.bulk_fill_dprobs(vdp_local, local_layout) mdl.sim.bulk_fill_hprobs(vhp_local, local_layout) #Gather data to produce arrays for the "global" layout (global_parallel_layout should be the same on all procs) # but only on proc 0 global_parallel_layout = local_layout.global_layout vp_global_parallel = local_layout.gather_local_array('e', vp_local) vdp_global_parallel = local_layout.gather_local_array('ep', vdp_local) vhp_global_parallel = local_layout.gather_local_array('epp', vhp_local) #Free the local arrays when we're done with them (they could be shared mem) local_layout.free_local_array(vp_local) local_layout.free_local_array(vdp_local) local_layout.free_local_array(vhp_local) #Compare the two, but note that different layouts may order the elements differently, # so we can't just compare the arrays directly - we have to use the layout to map # circuit index -> element indices: if comm is None or comm.rank == 0: for i, opstr in enumerate(circuits): assert (np.linalg.norm(vp_global_parallel[ global_parallel_layout.indices_for_index(i)] - vp_serial[ global_serial_layout.indices_for_index(i)]) < 1e-6) assert (np.linalg.norm(vdp_global_parallel[ global_parallel_layout.indices_for_index(i)] - vdp_serial[ global_serial_layout.indices_for_index(i)]) < 1e-6) assert (np.linalg.norm(vhp_global_parallel[ global_parallel_layout.indices_for_index(i)] - vhp_serial[ global_serial_layout.indices_for_index(i)]) < 1e-6)
def setUp(self): self.edesign = smq1Q_XYI.get_gst_experiment_design(max_max_length=2) self.target_model = smq1Q_XYI.target_model()
def test_explicit_model(self, pth): mdl = smq1Q_XYI.target_model() mdl2 = self.helper_serialize(mdl, pth) self.assertTrue(mdl.frobeniusdist(mdl2) < 1e-6) self.assertTrue(mdl.is_similar(mdl2)) self.assertTrue(mdl.is_equivalent(mdl2))
"""Shared test fixtures for pygsti.objects unit tests""" import pygsti from pygsti.modelpacks import smq1Q_XYI as smq from pygsti.baseobjs import Label from pygsti.circuits import Circuit, CircuitList from ..util import Namespace ns = Namespace() ns.model = smq.target_model('full TP') ns.max_max_length = 2 ns.aliases = {Label(('GA1', 0)): Circuit([('Gxpi2', 0)])} @ns.memo def datagen_model(self): return self.model.depolarize(op_noise=0.05, spam_noise=0.1) @ns.memo def circuits(self): return smq.create_gst_circuits(max_max_length=self.max_max_length) @ns.memo def dataset(self): return pygsti.data.simulate_data( self.datagen_model, self.circuits, 1000, seed=2020) @ns.memo def sparse_dataset(self):
def test_explicit_model_equal(self): mdl_explicit = smq1Q_XYI.target_model() self.check_model(mdl_explicit)