def test_run1Q_end2end(comm): from pygsti.modelpacks.legacy import std1Q_XYI target_model = std1Q_XYI.target_model() fiducials = std1Q_XYI.fiducials germs = std1Q_XYI.germs maxLengths = [1,2,4] mdl_datagen = target_model.depolarize(op_noise=0.1, spam_noise=0.001) listOfExperiments = pygsti.construction.make_lsgst_experiment_list( list(target_model.operations.keys()), fiducials, fiducials, germs, maxLengths) ds = pygsti.construction.generate_fake_data(mdl_datagen, listOfExperiments, nSamples=1000, sampleError="binomial", seed=1234, comm=comm) if comm.Get_rank() == 0: pickle.dump(ds, open("mpi_dataset.pkl","wb")) comm.barrier() #to make sure dataset file is written #test with pkl file - should only read in on rank0 then broadcast results = pygsti.do_long_sequence_gst("mpi_dataset.pkl", target_model, fiducials, fiducials, germs, [1], comm=comm) #test with dataset object results = pygsti.do_long_sequence_gst(ds, target_model, fiducials, fiducials, germs, maxLengths, comm=comm) #Use dummy duplicate of results to trigger MPI data-comparison processing: pygsti.report.create_standard_report({"one": results, "two": results}, "mpi_test_report", "MPI test report", confidenceLevel=95, verbosity=2, comm=comm)
def test_time_dependent_gst_staticdata(self): #run GST in a time-dependent mode: prep_fiducials, meas_fiducials = std1Q_XYI.prepStrs, std1Q_XYI.effectStrs germs = std1Q_XYI.germs maxLengths = [1, 2] target_model = std1Q_XYI.target_model("TP", sim_type="map") mdl_datagen = target_model.depolarize(op_noise=0.01, spam_noise=0.001) listOfExperiments = pygsti.construction.make_lsgst_experiment_list( target_model, prep_fiducials, meas_fiducials, germs, maxLengths) # *sparse*, time-independent data ds = pygsti.construction.generate_fake_data(mdl_datagen, listOfExperiments, nSamples=10, sampleError="binomial", seed=1234, times=[0], recordZeroCnts=False) target_model.set_simtype( 'map', max_cache_size=0) # No caching allowed for time-dependent calcs self.assertEqual(ds.get_degrees_of_freedom(aggregate_times=False), 126) results = pygsti.do_long_sequence_gst(ds, target_model, prep_fiducials, meas_fiducials, germs, maxLengths, verbosity=3, advancedOptions={ 'timeDependent': True, 'starting point': 'target', 'alwaysPerformMLE': False, 'onlyPerformMLE': False }, gaugeOptParams=False) # Normal GST used as a check - should get same answer since data is time-independent results2 = pygsti.do_long_sequence_gst(ds, target_model, prep_fiducials, meas_fiducials, germs, maxLengths, verbosity=3, advancedOptions={ 'timeDependent': False, 'starting point': 'target', 'alwaysPerformMLE': False, 'onlyPerformMLE': False }, gaugeOptParams=False)
def test_reducedmod_map2_errorgens(self): # Using sparse embedded matrices and map-based calcs (same as above) # but w/*errcomp_type=errogens* Model (maybe not really necessary to include?) target_model = build_XYCNOT_cloudnoise_model(self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=True, sim_type="map", errcomp_type='errorgens', verbosity=1) print("Num params = ", target_model.num_params()) target_model.from_vector(self.rand_start25) results = pygsti.do_long_sequence_gst( self.redmod_ds, target_model, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 0.0, delta=1.0)
def test_reducedmod_map1(self): # Using dense embedded matrices and map-based calcs (maybe not really necessary to include?) gs_target = pc.build_nqnoise_gateset(self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=False, sim_type="map", verbosity=1) gs_target.from_vector(self.rand_start206) results = pygsti.do_long_sequence_gst( self.redmod_ds, gs_target, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 1.0, delta=1.0) gs_compare = pygsti.io.json.load( open(compare_files + "/test2Qcalc_redmod_exact.gateset")) self.assertAlmostEqual( results.estimates['default'].gatesets['go0'].frobeniusdist( gs_compare), 0, places=1)
def test_reducedmod_map2(self): # Using sparse embedded matrices and map-based calcs target_model = pc.build_nqnoise_model(self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=True, sim_type="map", verbosity=1) target_model.from_vector(self.rand_start206) results = pygsti.do_long_sequence_gst( self.redmod_ds, target_model, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 1.0, delta=1.0) mdl_compare = pygsti.io.json.load( open(compare_files + "/test2Qcalc_redmod_exact.model")) self.assertAlmostEqual(np.linalg.norm( results.estimates['default'].models['go0'].to_vector() - mdl_compare.to_vector()), 0, places=1)
def test_time_dependent_gst(self): #run GST in a time-dependent mode: prep_fiducials, meas_fiducials = std1Q_XYI.prepStrs, std1Q_XYI.effectStrs germs = std1Q_XYI.germs maxLengths = [1, 2] target_model = std1Q_XYI.target_model("TP",sim_type="map") mdl_datagen = target_model.depolarize(op_noise=0.01, spam_noise=0.001) mdl_datagen.operations['Gi'] = MyTimeDependentIdle(1.0) listOfExperiments = pygsti.construction.make_lsgst_experiment_list( target_model, prep_fiducials, meas_fiducials, germs, maxLengths) # *sparse*, time-independent data ds = pygsti.construction.generate_fake_data(mdl_datagen, listOfExperiments, nSamples=1000, sampleError="binomial", seed=1234, times=[0, 0.1, 0.2], recordZeroCnts=False) self.assertEqual(ds.get_degrees_of_freedom(aggregate_times=False), 500) target_model.operations['Gi'] = MyTimeDependentIdle(0.0) # start assuming no time dependent decay 0 target_model.set_simtype('map', max_cache_size=0) # No caching allowed for time-dependent calcs results = pygsti.do_long_sequence_gst(ds, target_model, prep_fiducials, meas_fiducials, germs, maxLengths, verbosity=3, advancedOptions={'timeDependent': True, 'starting point': 'target', 'alwaysPerformMLE': False, 'tolerance': 1e-4, # run faster! 'onlyPerformMLE': False}, gaugeOptParams=False) #we should recover the 1.0 decay we put into mdl_datagen['Gi']: final_mdl = results.estimates['default'].models['final iteration estimate'] print("Final decay rate = ", final_mdl.operations['Gi'].to_vector()) self.assertAlmostEqual(final_mdl.operations['Gi'].to_vector()[0], 1.0, places=1)
def test_reducedmod_cterm(self): # Using term-based calcs using map-based stabilizer-state propagation target_model = pc.build_nqnoise_model( self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=False, verbosity=1, sim_type="termorder:1", parameterization="H+S clifford terms") target_model.from_vector(self.rand_start228) results = pygsti.do_long_sequence_gst( self.redmod_ds, target_model, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 3.0, delta=1.0) mdl_compare = pygsti.io.json.load( open(compare_files + "/test2Qcalc_redmod_terms.model")) self.assertAlmostEqual(np.linalg.norm( results.estimates['default'].models['go0'].to_vector() - mdl_compare.to_vector()), 0, places=3)
def test_reducedmod_prunedpath_svterm_errogens(self): cache = {} target_model = build_XYCNOT_cloudnoise_model( self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=False, verbosity=1, sim_type="termgap:3:0.05:0.001:True", parameterization="H+S terms", errcomp_type='errorgens') print("Num params = ", target_model.num_params()) target_model.from_vector(self.rand_start36) results = pygsti.do_long_sequence_gst( self.redmod_ds, target_model, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 0.0, delta=1.0)
def test_reducedmod_cterm_errorgens(self): # Using term-based calcs using map-based stabilizer-state propagation (same as above) # but w/errcomp_type=errogens Model target_model = build_XYCNOT_cloudnoise_model( self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=False, verbosity=1, sim_type="termorder:1", parameterization="H+S clifford terms", errcomp_type='errorgens') print("Num params = ", target_model.num_params()) target_model.from_vector(self.rand_start36) results = pygsti.do_long_sequence_gst( self.redmod_ds, target_model, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 0.0, 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.set_simtype('map') results = pygsti.do_long_sequence_gst(self.ds, target_model, std.prepStrs, std.effectStrs, std.germs, self.maxLengths, verbosity=4) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 3.0, delta=2.0) mdl_compare = pygsti.io.json.load( open(compare_files + "/test1Qcalc_std_exact.model")) gsEstimate = results.estimates['default'].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_idletomog_gstdata_std1Q(self): from pygsti.construction import std1Q_XYI as std std = pygsti.construction.stdmodule_to_smqmodule(std) maxLens = [1, 2, 4] expList = pygsti.construction.make_lsgst_experiment_list( std.target_model(), std.prepStrs, std.effectStrs, std.germs_lite, maxLens) ds = pygsti.construction.generate_fake_data( std.target_model().depolarize(0.01, 0.01), expList, 1000, 'multinomial', seed=1234) result = pygsti.do_long_sequence_gst(ds, std.target_model(), std.prepStrs, std.effectStrs, std.germs_lite, maxLens, verbosity=3) #standard report will run idle tomography pygsti.report.create_standard_report( result, temp_files + "/gstWithIdleTomogTestReportStd1Q", "Test GST Report w/Idle Tomography Tab: StdXYI", verbosity=3, auto_open=False)
def test_idletomog_gstdata_1Qofstd2Q(self): # perform idle tomography on first qubit of 2Q from pygsti.modelpacks.legacy import std2Q_XYICNOT as std2Q from pygsti.modelpacks.legacy import std1Q_XYI as std std2Q = pygsti.construction.stdmodule_to_smqmodule(std2Q) std = pygsti.construction.stdmodule_to_smqmodule(std) maxLens = [1,2,4] expList = pygsti.construction.make_lsgst_experiment_list(std2Q.target_model(), std2Q.prepStrs, std2Q.effectStrs, std2Q.germs_lite, maxLens) mdl_datagen = std2Q.target_model().depolarize(0.01, 0.01) ds2Q = pygsti.construction.generate_fake_data(mdl_datagen, expList, 1000, 'multinomial', seed=1234) #Just analyze first qubit (qubit 0) ds = pygsti.construction.filter_dataset(ds2Q, (0,)) start = std.target_model() start.set_all_parameterizations("TP") result = pygsti.do_long_sequence_gst(ds, start, std.prepStrs[0:4], std.effectStrs[0:4], std.germs_lite, maxLens, verbosity=3, advancedOptions={'objective': 'chi2'}) #result = pygsti.do_model_test(start.depolarize(0.009,0.009), ds, std.target_model(), std.prepStrs[0:4], # std.effectStrs[0:4], std.germs_lite, maxLens) pygsti.report.create_standard_report(result, temp_files + "/gstWithIdleTomogTestReportStd1Qfrom2Q", "Test GST Report w/Idle Tomog.: StdXYI from StdXYICNOT", verbosity=3, auto_open=False)
def test_stdgst_matrix(self): # Using matrix-based calculations target_model = std.target_model().copy() target_model.set_all_parameterizations("CPTP") target_model.set_simtype( 'matrix') # the default for 1Q, so we could remove this line results = pygsti.do_long_sequence_gst(self.ds, target_model, std.prepStrs, std.effectStrs, self.germs, self.maxLengths, advancedOptions=self.advOpts, verbosity=4) #RUN BELOW LINES TO SAVE GATESET (UNCOMMENT to regenerate) #pygsti.io.write_model(results.estimates['default'].models['go0'], # compare_files + "/test2Qcalc_std_exact.model","Saved Standard-Calc 2Q test model") #Note: expected nSigma of 143 is so high b/c we use very high tol of 1e-2 => result isn't very good print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 143, delta=2.0) mdl_compare = pygsti.io.load_model(compare_files + "/test2Qcalc_std_exact.model") self.assertAlmostEqual( results.estimates['default'].models['go0'].frobeniusdist( mdl_compare), 0, places=3)
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() target_model.set_all_parameterizations("H+S terms") target_model.set_simtype('termgap', max_order=3, desired_perr=0.01, allowed_perr=0.1, max_paths_per_outcome=1000, perr_heuristic='scaled', max_term_stages=5) results = pygsti.do_long_sequence_gst(self.ds, target_model, std.prepStrs, std.effectStrs, std.germs, self.maxLengths, verbosity=3) #RUN BELOW LINES TO SAVE GATESET (SAVE) if regenerate_references(): pygsti.io.json.dump( results.estimates['default'].models['go0'], open(compare_files + "/test1Qcalc_std_prunedpath.model", 'w')) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 3, delta=1.0)
def test_stdgst_map(self): # Using map-based calculation target_model = std.target_model().copy() target_model.set_all_parameterizations("CPTP") target_model.set_simtype('map') results = pygsti.do_long_sequence_gst(self.ds, target_model, std.prepStrs, std.effectStrs, self.germs, self.maxLengths, advancedOptions=self.advOpts, verbosity=4) #Note: expected nSigma of 143 is so high b/c we use very high tol of 1e-2 => result isn't very good print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 143, delta=2.0) mdl_compare = pygsti.io.load_model(compare_files + "/test2Qcalc_std_exact.model") self.assertAlmostEqual( results.estimates['default'].models['go0'].frobeniusdist( mdl_compare), 0, places=3)
def test_stdgst_matrix(self): # Using matrix-based calculations gs_target = std.gs_target.copy() gs_target.set_all_parameterizations("CPTP") gs_target.set_simtype( 'matrix') # the default for 1Q, so we could remove this line results = pygsti.do_long_sequence_gst(self.ds, gs_target, std.prepStrs, std.effectStrs, std.germs, self.maxLengths, verbosity=4) #RUN BELOW LINES TO SAVE GATESET (UNCOMMENT to regenerate) #pygsti.io.json.dump(results.estimates['default'].gatesets['go0'], # open(compare_files + "/test1Qcalc_std_exact.gateset",'w')) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 3.0, delta=2.0) gs_compare = pygsti.io.json.load( open(compare_files + "/test1Qcalc_std_exact.gateset")) #gauge opt before compare gsEstimate = results.estimates['default'].gatesets['go0'].copy() gsEstimate.set_all_parameterizations("full") gsEstimate = pygsti.algorithms.gaugeopt_to_target( gsEstimate, gs_compare) print(gsEstimate.strdiff(gs_compare)) self.assertAlmostEqual(gsEstimate.frobeniusdist(gs_compare), 0, places=3)
def test_reducedmod_matrix(self): # Using dense matrices and matrix-based calcs target_model = build_XYCNOT_cloudnoise_model(self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=False, sim_type="matrix", verbosity=1) print("Num params = ", target_model.num_params()) target_model.from_vector(self.rand_start25) results = pygsti.do_long_sequence_gst( self.redmod_ds, target_model, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) #RUN BELOW LINES TO SAVE GATESET (UNCOMMENT to regenerate) (SAVE) if os.environ.get('PYGSTI_REGEN_REF_FILES', 'no').lower() in ("yes", "1", "true"): pygsti.io.json.dump( results.estimates['default'].models['go0'], open(compare_files + "/test1Qcalc_redmod_exact.model", 'w')) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 0.0, delta=1.0)
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().copy() target_model.set_all_parameterizations("H+S terms") target_model.set_simtype( 'termorder:1' ) # this is the default set by set_all_parameterizations above results = pygsti.do_long_sequence_gst(self.ds, target_model, std.prepStrs, std.effectStrs, self.germs, self.maxLengths, verbosity=4) #RUN BELOW LINES TO SAVE GATESET (UNCOMMENT to regenerate) #pygsti.io.json.dump(results.estimates['default'].models['go0'], # open(compare_files + "/test2Qcalc_std_terms.model",'w')) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 5, delta=1.0) mdl_compare = pygsti.io.json.load( open(compare_files + "/test2Qcalc_std_terms.model")) self.assertAlmostEqual(np.linalg.norm( results.estimates['default'].models['go0'].to_vector() - mdl_compare.to_vector()), 0, places=3)
def test_time_dependent_gst_staticdata(self): #run GST in a time-dependent mode: prep_fiducials, meas_fiducials = std1Q_XYI.prepStrs, std1Q_XYI.effectStrs germs = std1Q_XYI.germs maxLengths = [1, 2] target_model = std1Q_XYI.target_model("TP",sim_type="map") mdl_datagen = target_model.depolarize(op_noise=0.01, spam_noise=0.001) listOfExperiments = pygsti.construction.make_lsgst_experiment_list( target_model, prep_fiducials, meas_fiducials, germs, maxLengths) # *sparse*, time-independent data ds = pygsti.construction.generate_fake_data(mdl_datagen, listOfExperiments, nSamples=10, sampleError="binomial", seed=1234, times=[0], recordZeroCnts=False) target_model.set_simtype('map', max_cache_size=0) # No caching allowed for time-dependent calcs self.assertEqual(ds.get_degrees_of_freedom(aggregate_times=False), 126) results = pygsti.do_long_sequence_gst(ds, target_model, prep_fiducials, meas_fiducials, germs, maxLengths, verbosity=3, advancedOptions={'timeDependent': True, 'starting point': 'target', 'alwaysPerformMLE': False, 'onlyPerformMLE': False}, gaugeOptParams=False) # Normal GST used as a check - should get same answer since data is time-independent results2 = pygsti.do_long_sequence_gst(ds, target_model, prep_fiducials, meas_fiducials, germs, maxLengths, verbosity=3, advancedOptions={'timeDependent': False, 'starting point': 'target', 'alwaysPerformMLE': False, 'onlyPerformMLE': False}, gaugeOptParams=False) #Check that "timeDependent=True" mode matches behavior or "timeDependent=False" mode when model and data are time-independent. self.assertAlmostEqual(pygsti.tools.chi2(results.estimates['default'].models['iteration estimates'][0], results.dataset, results.circuit_lists['iteration'][0]), pygsti.tools.chi2(results2.estimates['default'].models['iteration estimates'][0], results2.dataset, results2.circuit_lists['iteration'][0]), places=1) self.assertAlmostEqual(pygsti.tools.chi2(results.estimates['default'].models['iteration estimates'][1], results.dataset, results.circuit_lists['iteration'][1]), pygsti.tools.chi2(results2.estimates['default'].models['iteration estimates'][1], results2.dataset, results2.circuit_lists['iteration'][1]), places=1) self.assertAlmostEqual(pygsti.tools.two_delta_logl(results.estimates['default'].models['final iteration estimate'], results.dataset), pygsti.tools.two_delta_logl(results2.estimates['default'].models['final iteration estimate'], results2.dataset), places=1)
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() target_model.set_all_parameterizations("H+S terms") target_model.set_simtype( 'termorder', max_order=1 ) # this is the default set by set_all_parameterizations above results = pygsti.do_long_sequence_gst(self.ds, target_model, std.prepStrs, std.effectStrs, std.germs, self.maxLengths, verbosity=1) #RUN BELOW LINES TO SAVE GATESET (SAVE) if regenerate_references(): pygsti.io.json.dump( results.estimates['default'].models['go0'], open(compare_files + "/test1Qcalc_std_terms.model", 'w')) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 1, delta=1.0) mdl_compare = pygsti.io.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['default'].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['default'].models['go0'].to_vector() - mdl_compare.to_vector())) self.assertAlmostEqual(np.linalg.norm( results.estimates['default'].models['go0'].to_vector() - mdl_compare.to_vector()), 0, places=3)
def runOneQubit_Tutorial(): from pygsti.construction import std1Q_XYI gs_target = std1Q_XYI.gs_target fiducials = std1Q_XYI.fiducials germs = std1Q_XYI.germs maxLengths = [0,1,2,4,8,16,32,64,128,256,512,1024,2048] gs_datagen = gs_target.depolarize(gate_noise=0.1, spam_noise=0.001) listOfExperiments = pygsti.construction.make_lsgst_experiment_list( gs_target.gates.keys(), fiducials, fiducials, germs, maxLengths) ds = pygsti.construction.generate_fake_data(gs_datagen, listOfExperiments, nSamples=1000, sampleError="binomial", seed=1234) results = pygsti.do_long_sequence_gst(ds, gs_target, fiducials, fiducials, germs, maxLengths, comm=comm)
def runOneQubit_Tutorial(): from pygsti.construction import std1Q_XYI gs_target = std1Q_XYI.gs_target fiducials = std1Q_XYI.fiducials germs = std1Q_XYI.germs maxLengths = [0,1,2,4,8,16,32,64,128,256,512,1024,2048] gs_datagen = gs_target.depolarize(gate_noise=0.1, spam_noise=0.001) listOfExperiments = pygsti.construction.make_lsgst_experiment_list( list(gs_target.gates.keys()), fiducials, fiducials, germs, maxLengths) ds = pygsti.construction.generate_fake_data(gs_datagen, listOfExperiments, nSamples=1000, sampleError="binomial", seed=1234) results = pygsti.do_long_sequence_gst(ds, gs_target, fiducials, fiducials, germs, maxLengths, comm=comm)
def perform_extended_GST_on_data(filename_data_input, filename_target_gateset, filename_fiducials, filename_germs, maxlength_germseq): """Performs extended/long GST on data -------------------------------------------------------------------------- Parameters: filename_data_input: string Filename of the .txt containing the listofexperiments with the counts as formatted according to the standard pyGSTi way,thus at every line a gatesequence, followed by the plus and minus count (|1> and |0>) filename_target_gateset: string Filename of the .txt file which contains the target gateset filename_fiducials: string Filename of the .txt file containing the fiducials filename_germs: string Filename of .txt file containing the germs maxlength_germpowerseq: integer Integer specifying the maximum length of the of the germ-power sequence used in the gates sequence. The germs are repeated an integer number of times, such that the total length of this repetition is smaller than a specified maxlength. The list of experiments is composed of all the gatesequences for a specified maxlength which is increasing. The maximum of this maxlength is the parameter ' maxlength_germpowerseq'. #This is still quite unclear/needs better clarification -------------------------------------------------------------------------- Returns: pyGSTi .Results object, on which you can apply several functions to create reports and get the estimates such as: results.gatesets['final estimate'] --> gives final estimate of the gateset results.create_full_report_pdf, --> creates full report results.create_brief_report_pdf ---> creates brief report """ maxLengths = [0] for i in range(int(np.log(maxlength_germseq) / np.log(2)) + 1): maxLengths.append((2)**i) results = pygsti.do_long_sequence_gst(filename_data_input, filename_target_gateset, filename_fiducials, filename_fiducials, filename_germs, maxLengths, gaugeOptRatio=1e-3) return results
def test_stdgst_matrix(self): # Using matrix-based calculations target_model = std.target_model() target_model.set_all_parameterizations("CPTP") target_model.set_simtype( 'matrix') # the default for 1Q, so we could remove this line results = pygsti.do_long_sequence_gst(self.ds, target_model, std.prepStrs, std.effectStrs, 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['default'].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 (UNCOMMENT to regenerate) (SAVE) if os.environ.get('PYGSTI_REGEN_REF_FILES', 'no').lower() in ("yes", "1", "true"): pygsti.io.json.dump( results.estimates['default'].models['go0'], open(compare_files + "/test1Qcalc_std_exact.model", 'w')) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 3.0, delta=2.0) mdl_compare = pygsti.io.json.load( open(compare_files + "/test1Qcalc_std_exact.model")) #gauge opt before compare gsEstimate = results.estimates['default'].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 perform_extended_GST_on_data(filename_data_input, filename_target_gateset, filename_fiducials, filename_germs, maxlength_germseq): """Performs extended/long GST on data -------------------------------------------------------------------------- Parameters: filename_data_input: string Filename of the .txt containing the listofexperiments with the counts as formatted according to the standard pyGSTi way,thus at every line a gatesequence, followed by the plus and minus count (|1> and |0>) filename_target_gateset: string Filename of the .txt file which contains the target gateset filename_fiducials: string Filename of the .txt file containing the fiducials filename_germs: string Filename of .txt file containing the germs maxlength_germpowerseq: integer Integer specifying the maximum length of the of the germ-power sequence used in the gates sequence. The germs are repeated an integer number of times, such that the total length of this repetition is smaller than a specified maxlength. The list of experiments is composed of all the gatesequences for a specified maxlength which is increasing. The maximum of this maxlength is the parameter ' maxlength_germpowerseq'. #This is still quite unclear/needs better clarification -------------------------------------------------------------------------- Returns: pyGSTi .Results object, on which you can apply several functions to create reports and get the estimates such as: results.gatesets['final estimate'] --> gives final estimate of the gateset results.create_full_report_pdf, --> creates full report results.create_brief_report_pdf ---> creates brief report """ maxLengths = [0] for i in range(int(np.log(maxlength_germseq)/np.log(2))+1): maxLengths.append((2)**i) results = pygsti.do_long_sequence_gst( filename_data_input, filename_target_gateset, filename_fiducials, filename_fiducials, filename_germs, maxLengths, gaugeOptRatio=1e-3) return results
def test_reducedmod_svterm(self): # Using term-based calcs using map-based state-vector propagation target_model = build_XYCNOT_cloudnoise_model( self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=False, verbosity=1, sim_type="termorder:1", parameterization="H+S terms", errcomp_type='gates') print("Num params = ", target_model.num_params()) target_model.from_vector(self.rand_start36) results = pygsti.do_long_sequence_gst( self.redmod_ds, target_model, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) #RUN BELOW LINES TO SAVE GATESET (UNCOMMENT to regenerate) (SAVE) if os.environ.get('PYGSTI_REGEN_REF_FILES', 'no').lower() in ("yes", "1", "true"): pygsti.io.json.dump( results.estimates['default'].models['go0'], open(compare_files + "/test1Qcalc_redmod_terms.model", 'w')) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 0.0, delta=1.0) mdl_compare = pygsti.io.json.load( open(compare_files + "/test1Qcalc_redmod_terms.model")) self.assertAlmostEqual(np.linalg.norm( results.estimates['default'].models['go0'].to_vector() - mdl_compare.to_vector()), 0, places=3)
def test_reducedmod_svterm(self): # Using term-based calcs using map-based state-vector propagation gs_target = pc.build_nqnoise_gateset(self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=False, verbosity=1, sim_type="termorder:1", parameterization="H+S terms") print("Num params = ", gs_target.num_params()) gs_target.from_vector(self.rand_start36) results = pygsti.do_long_sequence_gst( self.redmod_ds, gs_target, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) #RUN BELOW LINES TO SAVE GATESET (UNCOMMENT to regenerate) #pygsti.io.json.dump(results.estimates['default'].gatesets['go0'], # open(compare_files + "/test1Qcalc_redmod_terms.gateset",'w')) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 0.0, delta=1.0) gs_compare = pygsti.io.json.load( open(compare_files + "/test1Qcalc_redmod_terms.gateset")) self.assertAlmostEqual(np.linalg.norm( results.estimates['default'].gatesets['go0'].to_vector() - gs_compare.to_vector()), 0, places=3)
def test_reducedmod_prunedpath_svterm_errogens(self): target_model = build_XYCNOT_cloudnoise_model( self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=False, verbosity=1, sim_type="termgap", parameterization="H+S terms", errcomp_type='errorgens') #separately call set_simtype to set other params target_model.set_simtype('termgap', max_order=3, desired_perr=0.01, allowed_perr=0.05, max_paths_per_outcome=1000, perr_heuristic='none', max_term_stages=5) print("Num params = ", target_model.num_params()) target_model.from_vector(self.rand_start36) results = pygsti.do_long_sequence_gst( self.redmod_ds, target_model, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 0.0, delta=1.0)
def test_reducedmod_matrix(self): # Using dense matrices and matrix-based calcs gs_target = pc.build_nqnoise_gateset(self.nQubits, geometry="line", maxIdleWeight=1, maxhops=1, extraWeight1Hops=0, extraGateWeight=1, sparse=False, sim_type="matrix", verbosity=1) print("Num params = ", gs_target.num_params()) gs_target.from_vector(self.rand_start25) results = pygsti.do_long_sequence_gst( self.redmod_ds, gs_target, self.redmod_fiducials, self.redmod_fiducials, self.redmod_germs, self.redmod_maxLs, verbosity=4, advancedOptions={'tolerance': 1e-3}) #RUN BELOW LINES TO SAVE GATESET (UNCOMMENT to regenerate) #pygsti.io.json.dump(results.estimates['default'].gatesets['go0'], # open(compare_files + "/test1Qcalc_redmod_exact.gateset",'w')) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 0.0, delta=1.0) gs_compare = pygsti.io.json.load( open(compare_files + "/test1Qcalc_redmod_exact.gateset")) self.assertAlmostEqual( results.estimates['default'].gatesets['go0'].frobeniusdist( gs_compare), 0, places=3)
def test_stdgst_prunedpath(self): # Using term-based (path integral) calculation with path pruning # This performs a map-based unitary evolution along each path. cache = {} target_model = std.target_model() target_model.set_all_parameterizations("H+S terms") target_model.set_simtype('termgap:3:0.05:0.001:True', cache) try: results = pygsti.do_long_sequence_gst(self.ds, target_model, std.prepStrs, std.effectStrs, std.germs, self.maxLengths, verbosity=3) except ValueError as ve: try: basestring # Only defined in Python 2 version = 2 except NameError: version = 3 if version == 2: #HACK: Python 2.7 gets NaNs which cause a ValueError in scipy's linear solve # This seems related to scipy/numpy and isn't a problem worth debugging - just punt. return else: raise ve #RUN BELOW LINES TO SAVE GATESET (UNCOMMENT to regenerate) (SAVE) #if os.environ.get('PYGSTI_REGEN_REF_FILES','no').lower() in ("yes","1","true"): # pygsti.io.json.dump(results.estimates['default'].models['go0'], # open(compare_files + "/test1Qcalc_std_prunedpath.model",'w')) print("MISFIT nSigma = ", results.estimates['default'].misfit_sigma()) self.assertAlmostEqual(results.estimates['default'].misfit_sigma(), 7, delta=1.0)
def simulate_convergence(germs, prepFiducials, effectFiducials, targetGS, randStr=1e-2, numPertGS=5, maxLengthsPower=8, clickNums=32, numRuns=7, seed=None, randState=None, gaugeOptRatio=1e-3, constrainToTP=True): if not isinstance(clickNums, list): clickNums = [clickNums] if randState is None: randState = _np.random.RandomState(seed) perturbedGatesets = [targetGS.randomize_with_unitary(scale=randStr, randState=randState) for n in range(numPertGS)] maxLengths = [0] + [2**n for n in range(maxLengthsPower + 1)] expList = constr.make_lsgst_experiment_list(targetGS.gates.keys(), prepFiducials, effectFiducials, germs, maxLengths) errorDict = {} resultDict = {} for trueGatesetNum, trueGateset in enumerate(perturbedGatesets): for numClicks in clickNums: for run in range(numRuns): success = False failCount = 0 while not success and failCount < 10: try: ds = constr.generate_fake_data(trueGateset, expList, nSamples=numClicks, sampleError="binomial", randState=randState) result = pygsti.do_long_sequence_gst( ds, targetGS, prepFiducials, effectFiducials, germs, maxLengths, gaugeOptRatio=gaugeOptRatio, constrainToTP=constrainToTP) errors = [(trueGateset .frobeniusdist( alg.optimize_gauge( estimate, 'target', targetGateset=trueGateset, constrainToTP=constrainToTP, spamWeight=0.0), spamWeight=0.0), L) for estimate, L in zip(result .gatesets['iteration estimates'][1:], result .parameters['max length list'][1:])] resultDict[trueGatesetNum, numClicks, run] = result errorDict[trueGatesetNum, numClicks, run] = errors success = True except Exception as e: failCount += 1 if failCount == 10: raise e print(e) return obj.GermSetEval(germset=germs, gatesets=perturbedGatesets, resultDict=resultDict, errorDict=errorDict)
def simulate_convergence(germs, prepFiducials, effectFiducials, targetGS, randStr=1e-2, numPertGS=5, maxLengthsPower=8, clickNums=32, numRuns=7, seed=None, randState=None, gaugeOptRatio=1e-3, constrainToTP=True): if not isinstance(clickNums, list): clickNums = [clickNums] if randState is None: randState = _np.random.RandomState(seed) perturbedGatesets = [ targetGS.randomize_with_unitary(scale=randStr, randState=randState) for n in range(numPertGS) ] maxLengths = [0] + [2**n for n in range(maxLengthsPower + 1)] expList = constr.make_lsgst_experiment_list(targetGS.gates.keys(), prepFiducials, effectFiducials, germs, maxLengths) errorDict = {} resultDict = {} for trueGatesetNum, trueGateset in enumerate(perturbedGatesets): for numClicks in clickNums: for run in range(numRuns): success = False failCount = 0 while not success and failCount < 10: try: ds = constr.generate_fake_data(trueGateset, expList, nSamples=numClicks, sampleError="binomial", randState=randState) result = pygsti.do_long_sequence_gst( ds, targetGS, prepFiducials, effectFiducials, germs, maxLengths, gaugeOptRatio=gaugeOptRatio, constrainToTP=constrainToTP) errors = [(trueGateset.frobeniusdist( alg.optimize_gauge(estimate, 'target', targetGateset=trueGateset, constrainToTP=constrainToTP, spamWeight=0.0), spamWeight=0.0), L) for estimate, L in zip( result.gatesets['iteration estimates'][1:], result.parameters['max length list'][1:])] resultDict[trueGatesetNum, numClicks, run] = result errorDict[trueGatesetNum, numClicks, run] = errors success = True except Exception as e: failCount += 1 if failCount == 10: raise e print(e) return obj.GermSetEval(germset=germs, gatesets=perturbedGatesets, resultDict=resultDict, errorDict=errorDict)
def testIntermediateMeas(self): # Mess with the target model to add some error to the povm and instrument self.assertEqual(self.target_model.num_params(), 92) # 4*3 + 16*5 = 92 mdl = self.target_model.depolarize(op_noise=0.01, spam_noise=0.01) gs2 = self.target_model.depolarize( max_op_noise=0.01, max_spam_noise=0.01, seed=1234) #another way to depolarize mdl.povms['Mdefault'].depolarize(0.01) # Introducing a rotation error to the measurement Uerr = pygsti.rotation_gate_mx( [0, 0.02, 0]) # input angles are halved by the method E = np.dot(mdl.povms['Mdefault']['0'].T, Uerr).T # effect is stored as column vector Erem = self.povm_ident - E mdl.povms['Mdefault'] = pygsti.obj.UnconstrainedPOVM({ '0': E, '1': Erem }) # Now add the post-measurement gates from the vector E0 and remainder = id-E0 Gmz_plus = np.dot( E, E.T) #since E0 is stored internally as column spamvec Gmz_minus = np.dot(Erem, Erem.T) mdl.instruments['Iz'] = pygsti.obj.Instrument({ 'plus': Gmz_plus, 'minus': Gmz_minus }) self.assertEqual(mdl.num_params(), 92) # 4*3 + 16*5 = 92 #print(mdl) germs = std.germs fiducials = std.fiducials max_lengths = [1] #,2,4,8] glbls = list(mdl.operations.keys()) + list(mdl.instruments.keys()) lsgst_list = pygsti.construction.make_lsgst_experiment_list( glbls, fiducials, fiducials, germs, max_lengths) lsgst_list2 = pygsti.construction.make_lsgst_experiment_list( mdl, fiducials, fiducials, germs, max_lengths) #use mdl as source self.assertEqual(lsgst_list, lsgst_list2) mdl_datagen = mdl ds = pygsti.construction.generate_fake_data(mdl, lsgst_list, 1000, 'none') #'multinomial') pygsti.io.write_dataset(temp_files + "/intermediate_meas_dataset.txt", ds) ds2 = pygsti.io.load_dataset(temp_files + "/intermediate_meas_dataset.txt") for opstr, dsRow in ds.items(): for lbl, cnt in dsRow.counts.items(): self.assertAlmostEqual(cnt, ds2[opstr].counts[lbl], places=2) #print(ds) #LGST mdl_lgst = pygsti.do_lgst( ds, fiducials, fiducials, self.target_model) #, guessModelForGauge=mdl_datagen) self.assertTrue("Iz" in mdl_lgst.instruments) mdl_opt = pygsti.gaugeopt_to_target(mdl_lgst, mdl_datagen) #, method="BFGS") print(mdl_datagen.strdiff(mdl_opt)) print("Frobdiff = ", mdl_datagen.frobeniusdist(mdl_lgst)) print("Frobdiff after GOpt = ", mdl_datagen.frobeniusdist(mdl_opt)) self.assertAlmostEqual(mdl_datagen.frobeniusdist(mdl_opt), 0.0, places=4) #print(mdl_lgst) #print(mdl_datagen) #DEBUG compiling w/dataset #dbList = pygsti.construction.make_lsgst_experiment_list(self.target_model,fiducials,fiducials,germs,max_lengths) ##self.target_model.simplify_circuits(dbList, ds) #self.target_model.simplify_circuits([ pygsti.obj.Circuit(None,stringrep="Iz") ], ds ) #assert(False),"STOP" #LSGST results = pygsti.do_long_sequence_gst(ds, self.target_model, fiducials, fiducials, germs, max_lengths) #print(results.estimates['default'].models['go0']) mdl_est = results.estimates['default'].models['go0'] mdl_est_opt = pygsti.gaugeopt_to_target(mdl_est, mdl_datagen) print("Frobdiff = ", mdl_datagen.frobeniusdist(mdl_est)) print("Frobdiff after GOpt = ", mdl_datagen.frobeniusdist(mdl_est_opt)) self.assertAlmostEqual(mdl_datagen.frobeniusdist(mdl_est_opt), 0.0, places=4) #LGST w/TP gates mdl_targetTP = self.target_model.copy() mdl_targetTP.set_all_parameterizations("TP") self.assertEqual(mdl_targetTP.num_params(), 71) # 3 + 4*2 + 12*5 = 71 #print(mdl_targetTP) resultsTP = pygsti.do_long_sequence_gst(ds, mdl_targetTP, fiducials, fiducials, germs, max_lengths) mdl_est = resultsTP.estimates['default'].models['go0'] mdl_est_opt = pygsti.gaugeopt_to_target(mdl_est, mdl_datagen) print("TP Frobdiff = ", mdl_datagen.frobeniusdist(mdl_est)) print("TP Frobdiff after GOpt = ", mdl_datagen.frobeniusdist(mdl_est_opt)) self.assertAlmostEqual(mdl_datagen.frobeniusdist(mdl_est_opt), 0.0, places=4)