def test_general_decomp(self): gs1 = std.target_model().depolarize(op_noise=0.1, spam_noise=0.05) gs2 = std.target_model() gs1.operations['Gx'] = np.array( [[-1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], 'd') # -1 eigenvalues => use approx log. rptbl.general_decomposition(gs1, gs2)
def tets_pickle_ConfidenceRegion(self): res = pygsti.obj.Results() res.init_dataset(self.ds) res.init_circuits(self.gss) res.add_estimate(stdxyi.target_model(), stdxyi.target_model(), [self.model] * len(self.maxLengthList), parameters={'objective': 'logl'}, estimate_key="default") res.add_confidence_region_factory('final iteration estimate', 'final') self.assertTrue( res.has_confidence_region_factory('final iteration estimate', 'final')) cfctry = res.get_confidence_region_factory('final iteration estimate', 'final') cfctry.compute_hessian() self.assertTrue(cfctry.has_hessian()) cfctry.project_hessian('std') ci_std = cfctry.view(95.0, 'normal', 'std') s = pickle.dumps(cfctry) cifctry2 = pickle.loads(s) s = pickle.dumps(ci_std) ci_std2 = pickle.loads(s)
def test_longSequenceGST_randomReduction(self): ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/drivers.dataset%s" % self.versionsuffix) ts = "whole germ powers" maxLens = self.maxLens #Without fixed initial fiducial pairs fidPairs = None reducedLists = pygsti.construction.make_lsgst_structs( std.target_model().operations.keys(), std.fiducials, std.fiducials, std.germs, maxLens, fidPairs, ts, keepFraction=0.5, keepSeed=1234) result = self.runSilent(pygsti.do_long_sequence_gst_base, ds, std.target_model(), reducedLists, advancedOptions={'truncScheme': ts}) #create a report... pygsti.report.create_standard_report(result, temp_files + "/full_report_RFPR", "RFPR report", verbosity=2) #With fixed initial fiducial pairs fidPairs = pygsti.alg.find_sufficient_fiducial_pairs( std.target_model(), std.fiducials, std.fiducials, std.germs, verbosity=0) reducedLists = pygsti.construction.make_lsgst_structs( std.target_model().operations.keys(), std.fiducials, std.fiducials, std.germs, maxLens, fidPairs, ts, keepFraction=0.5, keepSeed=1234) result2 = self.runSilent(pygsti.do_long_sequence_gst_base, ds, std.target_model(), reducedLists, advancedOptions={'truncScheme': ts}) #create a report... pygsti.report.create_standard_report(result2, temp_files + "/full_report_RFPR2.html", verbosity=2)
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_model_test(self): ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/drivers.dataset%s" % self.versionsuffix) mdl_guess = std.target_model().depolarize(op_noise=0.01,spam_noise=0.01) maxLens = self.maxLens output_pkl_stream = open(temp_files + "/driverModelTestResult1.pkl",'wb') result = self.runSilent(pygsti.do_model_test, mdl_guess, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, output_pkl=output_pkl_stream) output_pkl_stream.close() #Some parameter variants & output to pkl advancedOpts = {'objective': 'chi2', 'profile': 2 } result = self.runSilent(pygsti.do_model_test, mdl_guess, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, advancedOptions=advancedOpts, output_pkl = temp_files + "/driverModelTestResult2.pkl") with self.assertRaises(ValueError): advancedOpts = {'objective': 'foobar' } self.runSilent(pygsti.do_model_test, mdl_guess, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, advancedOptions=advancedOpts) with self.assertRaises(ValueError): advancedOpts = {'profile': 'foobar' } self.runSilent(pygsti.do_model_test, mdl_guess, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, advancedOptions=advancedOpts)
def test_circuitsim_stabilizer_1Qcheck(self): from pygsti.construction import std1Q_XYI as stdChk maxLengths = [1, 2, 4] listOfExperiments = pygsti.construction.make_lsgst_experiment_list( stdChk.target_model(), stdChk.prepStrs, stdChk.effectStrs, stdChk.germs, maxLengths) #listOfExperiments = pygsti.construction.circuit_list([ ('Gcnot','Gxi') ]) #listOfExperiments = pygsti.construction.circuit_list([ ('Gxi','Gcphase','Gxi','Gix') ]) mdl_normal = stdChk.target_model() mdl_clifford = stdChk.target_model() #print(mdl_clifford['Gcnot']) self.assertTrue(stdChk.target_model()._evotype == "densitymx") 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.probs(opstr) p_clifford = mdl_clifford.probs(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_std_clifford_comp(self): self.assertTrue( pygsti.report.factory.find_std_clifford_compilation( std.target_model(), 3) is not None) nonStdGS = std.target_model().rotate((0.15, -0.03, 0.03)) self.assertTrue( pygsti.report.factory.find_std_clifford_compilation(nonStdGS) is None)
def test_parameter_counting(self): #XY Model: SPAM=True n = stdxy.target_model().num_params() self.assertEqual(n, 44) # 2*16 + 3*4 = 44 n = stdxy.target_model().num_nongauge_params() self.assertEqual(n, 28) # full 16 gauge params #XY Model: SPAM=False tst = stdxy.target_model() del tst.preps['rho0'] del tst.povms['Mdefault'] n = tst.num_params() self.assertEqual(n, 32) # 2*16 = 32 n = tst.num_nongauge_params() self.assertEqual( n, 18 ) # gates are all unital & TP => only 14 gauge params (2 casimirs) #XYI Model: SPAM=True n = stdxyi.target_model().num_params() self.assertEqual(n, 60) # 3*16 + 3*4 = 60 n = stdxyi.target_model().num_nongauge_params() self.assertEqual(n, 44) # full 16 gauge params: SPAM gate + 3 others #XYI Model: SPAM=False tst = stdxyi.target_model() del tst.preps['rho0'] del tst.povms['Mdefault'] n = tst.num_params() self.assertEqual(n, 48) # 3*16 = 48 n = tst.num_nongauge_params() self.assertEqual( n, 34 ) # gates are all unital & TP => only 14 gauge params (2 casimirs) #XYI Model: SP0=False tst = stdxyi.target_model() tst.preps['rho0'] = pygsti.obj.TPSPAMVec(tst.preps['rho0']) n = tst.num_params() self.assertEqual(n, 59) # 3*16 + 2*4 + 3 = 59 n = tst.num_nongauge_params() self.assertEqual( n, 44) # 15 gauge params (minus one b/c can't change rho?) #XYI Model: G0=SP0=False tst.operations['Gi'] = pygsti.obj.TPDenseOp(tst.operations['Gi']) tst.operations['Gx'] = pygsti.obj.TPDenseOp(tst.operations['Gx']) tst.operations['Gy'] = pygsti.obj.TPDenseOp(tst.operations['Gy']) n = tst.num_params() self.assertEqual(n, 47) # 3*12 + 2*4 + 3 = 47 n = tst.num_nongauge_params() self.assertEqual(n, 35) # full 12 gauge params of single 4x3 gate
def test_closest_unitary(self): gs1 = std.target_model().depolarize(op_noise=0.1, spam_noise=0.05) gs2 = std.target_model() rptbl.closest_unitary_fidelity(gs1.operations['Gx'], gs2.operations['Gx'], "pp") # op2 is unitary rptbl.closest_unitary_fidelity(gs2.operations['Gx'], gs1.operations['Gx'], "pp") # op1 is unitary
def test_longSequenceGST_fiducialPairReduction(self): ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/drivers.dataset%s" % self.versionsuffix) maxLens = self.maxLens #Make list-of-lists of GST operation sequences fullStructs = pygsti.construction.make_lsgst_structs( std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens) lens = [ len(strct.allstrs) for strct in fullStructs ] self.assertEqual(lens, [92,168,450]) # ,817,1201, 1585] #Global FPR fidPairs = pygsti.alg.find_sufficient_fiducial_pairs( std.target_model(), std.fiducials, std.fiducials, std.germs, searchMode="random", nRandom=100, seed=1234, verbosity=1, memLimit=int(2*(1024)**3), minimumPairs=2) gfprStructs = pygsti.construction.make_lsgst_structs( std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, fidPairs=fidPairs) lens = [ len(strct.allstrs) for strct in gfprStructs ] #self.assertEqual(lens, [92,100,130]) #,163,196,229] #can't test reliably b/c "random" above # means different answers on different systems gfprExperiments = pygsti.construction.make_lsgst_experiment_list( std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, fidPairs=fidPairs) result = pygsti.do_long_sequence_gst_base(ds, std.target_model(), gfprStructs, verbosity=0) pygsti.report.create_standard_report(result, temp_files + "/full_report_GFPR", "GFPR report", verbosity=2) #Per-germ FPR fidPairsDict = pygsti.alg.find_sufficient_fiducial_pairs_per_germ( std.target_model(), std.fiducials, std.fiducials, std.germs, searchMode="random", constrainToTP=True, nRandom=100, seed=1234, verbosity=1, memLimit=int(2*(1024)**3)) pfprStructs = pygsti.construction.make_lsgst_structs( std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, fidPairs=fidPairsDict) #note: fidPairs arg can be a dict too! lens = [ len(strct.allstrs) for strct in pfprStructs ] #self.assertEqual(lens, [92,99,138]) # ,185,233,281] #can't test reliably b/c "random" above # means different answers on different systems pfprExperiments = pygsti.construction.make_lsgst_experiment_list( std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, fidPairs=fidPairsDict) result = pygsti.do_long_sequence_gst_base(ds, std.target_model(), pfprStructs, verbosity=0) pygsti.report.create_standard_report(result, temp_files + "/full_report_PFPR", "PFPR report", verbosity=2)
def runOneQubit(comm=None): from pygsti.construction import std1Q_XYI as std maxLengths = [1,2,4,8,16,32,64,128,256,512] #still need to define this manually specs = pygsti.construction.build_spam_specs( std.fiducials, prep_labels=std.target_model().get_prep_labels(), effect_labels=std.target_model().get_effect_labels()) gsets, dsGen = runMC2GSTAnalysis(specs, std.germs, std.target_model(), 1234, maxLengths, nSamples=1000, comm=comm) return gsets
def test_longSequenceGST_LengthAsExponent(self): ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/drivers_lae.dataset%s" % self.versionsuffix) ts = "length as exponent" maxLens = self.maxLens result = self.runSilent(pygsti.do_long_sequence_gst, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, advancedOptions={'truncScheme': ts}) result = self.runSilent(pygsti.do_long_sequence_gst, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, advancedOptions={'truncScheme': ts, 'objective': "chi2"})
def test_germsel_greedy(self): threshold = 1e6 randomizationStrength = 1e-3 neighborhoodSize = 5 gatesetNeighborhood = pygsti.alg.randomize_model_list([std.target_model()], randomizationStrength=randomizationStrength, numCopies=neighborhoodSize, seed=2014) forceStrs = pygsti.construction.circuit_list([ ('Gx',), ('Gy') ]) max_length = 6 gates = std.target_model().operations.keys() superGermSet = pygsti.construction.list_all_circuits_without_powers_and_cycles(gates, max_length) tinyGermSet = pygsti.construction.list_all_circuits_without_powers_and_cycles(gates, 1) #Depth first pygsti.alg.build_up(gatesetNeighborhood, superGermSet, randomize=False, seed=2014, scoreFunc='all', threshold=threshold, verbosity=1, opPenalty=1.0) # with forced operation sequences pygsti.alg.build_up(gatesetNeighborhood, superGermSet, randomize=False, seed=2014, scoreFunc='all', threshold=threshold, verbosity=1, opPenalty=1.0, force=forceStrs) tiny = pygsti.alg.build_up(gatesetNeighborhood, tinyGermSet, randomize=False, seed=2014, scoreFunc='all', threshold=threshold, verbosity=1, opPenalty=1.0) #incomplete initial set self.assertTrue(tiny is None) #Breadth first pygsti.alg.build_up_breadth(gatesetNeighborhood, superGermSet, randomize=False, seed=2014, scoreFunc='all', threshold=threshold, verbosity=1, opPenalty=1.0) # with forced operation sequences pygsti.alg.build_up_breadth(gatesetNeighborhood, superGermSet, randomize=False, seed=2014, scoreFunc='all', threshold=threshold, verbosity=1, opPenalty=1.0, force=forceStrs) # with small memory limit with self.assertRaises(MemoryError): pygsti.alg.build_up_breadth(gatesetNeighborhood, superGermSet, randomize=False, seed=2014, scoreFunc='all', threshold=threshold, verbosity=1, opPenalty=1.0, memLimit=1024) pygsti.alg.build_up_breadth(gatesetNeighborhood, superGermSet, randomize=False, seed=2014, scoreFunc='all', threshold=threshold, verbosity=1, opPenalty=1.0, memLimit=1024000)
def test_stdpracticeGST(self): ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/drivers.dataset%s" % self.versionsuffix) mdl_guess = std.target_model().depolarize(op_noise=0.01,spam_noise=0.01) #lower bad-fit threshold to zero to trigger bad-fit additional processing maxLens = self.maxLens result = self.runSilent(pygsti.do_stdpractice_gst, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, modes="TP,CPTP,Test,Target", modelsToTest = {"Test": mdl_guess}, comm=None, memLimit=None, verbosity=5) pygsti.report.create_standard_report(result, temp_files + "/full_report_stdpractice", "Std Practice Test Report", verbosity=2) #with string args, gaugeOptTarget, output pkl, and advanced options myGaugeOptSuiteDict = { 'MyGaugeOpt': { 'itemWeights': {'gates': 1, 'spam': 0.0001}, 'targetModel': std.target_model() # to test overriding internal target model (prints a warning) } } result = self.runSilent(pygsti.do_stdpractice_gst, temp_files + "/driver_test_dataset.txt", temp_files + "/driver.model", temp_files + "/driver_fiducials.txt", temp_files + "/driver_fiducials.txt", temp_files + "/driver_germs.txt", maxLens, modes="TP", comm=None, memLimit=None, verbosity=5, gaugeOptTarget = mdl_guess, gaugeOptSuite = myGaugeOptSuiteDict, output_pkl = temp_files + "/driver_results1.pkl", advancedOptions={ 'all': { 'objective': 'chi2', 'badFitThreshold': -100, # so we create a robust estimate and convey 'onBadFit': ["robust"] # guage opt to it. } } ) # test running just Target mode, and writing to an output *stream* out_pkl_stream = open(temp_files + "/driver_results2.pkl",'wb') self.runSilent(pygsti.do_stdpractice_gst, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, modes="Target", output_pkl=out_pkl_stream) out_pkl_stream.close() # test invalid mode with self.assertRaises(ValueError): self.runSilent(pygsti.do_stdpractice_gst, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, modes="Foobar")
def test_randomize_gateset(self): #with numCopies and a single model gatesetNeighborhood = pygsti.alg.randomize_model_list([std.target_model()], randomizationStrength=1e-3, numCopies=3, seed=2014) #with multiple models gatesetNeighborhood = pygsti.alg.randomize_model_list( [std.target_model(),std.target_model()], numCopies=None, randomizationStrength=1e-3, seed=2014) #cannot specify both: with self.assertRaises(ValueError): pygsti.alg.randomize_model_list([std.target_model(),std.target_model()], numCopies=3, randomizationStrength=1e-3, seed=2014)
def test_germsel_slack(self): germsToTest = pygsti.construction.list_all_circuits_without_powers_and_cycles( list(std.target_model().operations.keys()), 3) germsToTest2 = pygsti.construction.list_all_circuits_without_powers_and_cycles( list(std.target_model().operations.keys()), 4) + std.germs finalGerms = pygsti.alg.optimize_integer_germs_slack( self.mdl_target_noisy, germsToTest, initialWeights=None, fixedSlack=0.1, slackFrac=False, returnAll=False, tol=1e-6, verbosity=4) forceStrs = pygsti.construction.circuit_list([ ('Gx',), ('Gy') ]) finalGerms, wts, scoreDict = pygsti.alg.optimize_integer_germs_slack( self.mdl_target_noisy, germsToTest2, initialWeights=np.ones( len(germsToTest2), 'd' ), fixedSlack=False, slackFrac=0.1, returnAll=True, tol=1e-6, verbosity=4, force=forceStrs) finalGerms = pygsti.alg.optimize_integer_germs_slack( self.mdl_target_noisy, germsToTest2, initialWeights=np.ones( len(germsToTest2), 'd' ), fixedSlack=False, slackFrac=0.1, returnAll=True, tol=1e-6, verbosity=4, force=False) #don't force any strings (default would have been "singletons" with self.assertRaises(ValueError): pygsti.alg.optimize_integer_germs_slack( self.mdl_target_noisy, germsToTest2, initialWeights=np.ones( len(germsToTest2)+10, 'd' ), fixedSlack=False, slackFrac=0.1, returnAll=True, tol=1e-6, verbosity=4, force=forceStrs) # initialWeights has bad length (+10) self.runSilent(pygsti.alg.optimize_integer_germs_slack, self.mdl_target_noisy, germsToTest2, initialWeights=np.ones( len(germsToTest2), 'd' ), fixedSlack=False, slackFrac=0.1, returnAll=True, tol=1e-6, verbosity=4, maxIter=1) # test hitting max iterations with self.assertRaises(ValueError): pygsti.alg.optimize_integer_germs_slack( self.mdl_target_noisy, germsToTest, initialWeights=np.ones( len(germsToTest), 'd' ), returnAll=True, tol=1e-6, verbosity=4) # must specify either fixedSlack or slackFrac with self.assertRaises(ValueError): pygsti.alg.optimize_integer_germs_slack( self.mdl_target_noisy, germsToTest, initialWeights=np.ones( 1, 'd' ), returnAll=True, tol=1e-6, verbosity=4)
def setUp(self): super(DirectXTestCase, self).setUp() self.tgt = std.target_model() #OLDself.specs = pygsti.construction.build_spam_specs(None, std.prepStrs, std.effectStrs) self.prepStrs = std.prepStrs self.effectStrs = std.effectStrs self.strs = pygsti.construction.circuit_list([ (), #always need empty string ('Gx', ), ('Gy', ), ('Gi', ), #need these for includeTargetOps=True ('Gx', 'Gx'), ('Gx', 'Gy', 'Gx') ]) #additional expstrs = pygsti.construction.create_circuit_list( "f0+base+f1", order=['f0', 'f1', 'base'], f0=std.prepStrs, f1=std.effectStrs, base=self.strs) # expstrs.extend( pygsti.construction.create_circuit_list("f0+base+f1",order=['f0','f1','base'], # f0=std.prepStrs, f1=std.effectStrs, # base=self.strs) # expstrs = [ pygsti.objects.Circuit( () ) ] + expstrs #add empty string, which is always needed mdl_datagen = self.tgt.depolarize(op_noise=0.05, spam_noise=0.1) self.ds = pygsti.construction.generate_fake_data(mdl_datagen, expstrs, 1000, "multinomial", seed=1234)
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 setUp(self): #Add an instrument to the standard target model self.target_model = std.target_model() E = self.target_model.povms['Mdefault']['0'] Erem = self.target_model.povms['Mdefault']['1'] Gmz_plus = np.dot(E, E.T) Gmz_minus = np.dot(Erem, Erem.T) self.target_model.instruments['Iz'] = pygsti.obj.Instrument({ 'plus': Gmz_plus, 'minus': Gmz_minus }) self.povm_ident = self.target_model.povms['Mdefault'][ '0'] + self.target_model.povms['Mdefault']['1'] self.mdl_target_wTP = self.target_model.copy() self.mdl_target_wTP.instruments['IzTP'] = pygsti.obj.TPInstrument({ 'plus': Gmz_plus, 'minus': Gmz_minus }) super(InstrumentTestCase, self).setUp()
def test_robust_data_scaling(self): ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/drivers2.dataset%s" % self.versionsuffix) mdl_guess = std.target_model().depolarize(op_noise=0.01,spam_noise=0.01) #lower bad-fit threshold to zero to trigger bad-fit additional processing maxLens = self.maxLens result = self.runSilent(pygsti.do_long_sequence_gst, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, advancedOptions={'badFitThreshold': -100, 'onBadFit': ["do nothing","robust","Robust","robust+","Robust+"]}) with self.assertRaises(ValueError): self.runSilent(pygsti.do_long_sequence_gst, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, advancedOptions={'badFitThreshold': -100, 'onBadFit': ["foobar"]})
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_clifford_compilations(self): # Tests the Clifford compilations hard-coded into the various std models. Perhaps this can be # automated to run over all the std models that contain a Clifford compilation? from pygsti.construction import std1Q_Cliffords target_model = std1Q_Cliffords.target_model() clifford_group = rb.group.construct_1Q_Clifford_group() from pygsti.construction import std1Q_XY target_model = std1Q_XY.target_model() clifford_compilation = std1Q_XY.clifford_compilation compiled_cliffords = pygsti.construction.build_explicit_alias_model( target_model, clifford_compilation) for key in list(compiled_cliffords.operations.keys()): self.assertLess( np.sum( abs(compiled_cliffords.operations[key] - clifford_group.get_matrix(key))), 10**(-10)) from pygsti.construction import std1Q_XYI target_model = std1Q_XYI.target_model() clifford_compilation = std1Q_XYI.clifford_compilation compiled_cliffords = pygsti.construction.build_explicit_alias_model( target_model, clifford_compilation) for key in list(compiled_cliffords.operations.keys()): self.assertLess( np.sum( abs(compiled_cliffords.operations[key] - clifford_group.get_matrix(key))), 10**(-10))
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.probs(self.circuit1) #self.circuit1.simulate(mdl) # calls probs - same as above line print(probs1) gs2 = std.target_model() gs2.set_simtype("map") probs1 = gs2.probs(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 mdl = pygsti.construction.build_localnoise_model( self.csim_nQubits, ['Gi', 'Gxpi', 'Gypi', 'Gcnot'], sim_type="matrix", ensure_composed_gates=False) probs1 = mdl.probs(self.circuit3) mdl = pygsti.construction.build_localnoise_model( self.csim_nQubits, ['Gi', 'Gxpi', 'Gypi', 'Gcnot'], sim_type="map", ensure_composed_gates=False) probs2 = mdl.probs(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_rpe_tools(self): from pygsti.extras import rpe rpeconfig_inst_list = [rpeconfig_GxPi2_GyPi2_UpDn,rpeconfig_GxPi2_GyPi2_00] for rpeconfig_inst in rpeconfig_inst_list: xhat = 10 #1 counts for sin string yhat = 90 #1 counts for cos string k = 1 #experiment generation Nx = 100 # sin string clicks Ny = 100 # cos string clicks k1Alpha = rpe.extract_rotation_hat(xhat,yhat,k,Nx,Ny,"alpha", previousAngle=None, rpeconfig_inst=rpeconfig_inst) k1Eps = rpe.extract_rotation_hat(xhat,yhat,k,Nx,Ny,"epsilon", previousAngle=None, rpeconfig_inst=rpeconfig_inst) #self.assertAlmostEqual(k1Alpha, 0.785398163397) #self.assertAlmostEqual(k1Eps, -2.35619449019) k = 2 #experiment generation k2Alpha = rpe.extract_rotation_hat(xhat,yhat,k,Nx,Ny,"alpha", previousAngle=k1Alpha, rpeconfig_inst=rpeconfig_inst) k2Eps = rpe.extract_rotation_hat(xhat,yhat,k,Nx,Ny,"epsilon", previousAngle=k1Eps, rpeconfig_inst=rpeconfig_inst) #self.assertAlmostEqual(k2Alpha, 0.392699081699) #self.assertAlmostEqual(k2Eps, -1.1780972451) with self.assertRaises(Exception): rpe.extract_rotation_hat(xhat,yhat,2,Nx,Ny,"epsilon", previousAngle=None, rpeconfig_inst=rpeconfig_inst) #need previous angle with self.assertRaises(Exception): rpe.extract_rotation_hat(xhat,yhat,1,Nx,Ny,"foobar", rpeconfig_inst=rpeconfig_inst) #bad angle name from pygsti.construction import std1Q_XY as stdXY target = stdXY.target_model() target.operations['Gi'] = std.target_model().operations['Gi'] #need a Gi gate... stringListD = rpe.make_rpe_angle_string_list_dict(2,rpeconfig_inst) mdl_depolXZ = target.depolarize(op_noise=0.1,spam_noise=0.1) ds = pygsti.construction.generate_fake_data(mdl_depolXZ, stringListD['totalStrList'], nSamples=1000, sampleError='binomial') epslist = rpe.est_angle_list(ds,stringListD['epsilon','sin'],stringListD['epsilon','cos'], angleName="epsilon", rpeconfig_inst=rpeconfig_inst) tlist,dummy = rpe.est_theta_list(ds,stringListD['theta','sin'],stringListD['theta','cos'], epslist,returnPhiFunList=True, rpeconfig_inst=rpeconfig_inst) tlist = rpe.est_theta_list(ds,stringListD['theta','sin'],stringListD['theta','cos'], epslist,returnPhiFunList=False, rpeconfig_inst=rpeconfig_inst) alpha = rpe.extract_alpha( stdXY.target_model(), rpeconfig_inst) eps = rpe.extract_epsilon( stdXY.target_model(), rpeconfig_inst) theta = rpe.extract_theta( stdXY.target_model(), rpeconfig_inst) rpe.analyze_rpe_data(ds,mdl_depolXZ,stringListD,rpeconfig_inst)
def test_longSequenceGST_badfit(self): ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/drivers.dataset%s" % self.versionsuffix) ts = "whole germ powers" #lower bad-fit threshold to zero to trigger bad-fit additional processing maxLens = self.maxLens result = self.runSilent(pygsti.do_long_sequence_gst, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, advancedOptions={'truncScheme': ts, 'badFitThreshold': -100}) pygsti.report.create_standard_report(result, temp_files + "/full_report_badfit", "badfit report", verbosity=2) result_chi2 = self.runSilent(pygsti.do_long_sequence_gst, ds, std.target_model(), std.fiducials, std.fiducials, std.germs, maxLens, advancedOptions={'truncScheme': ts, 'badFitThreshold': -100, 'objective': 'chi2'})
def test_germsel_tests(self): germsToTest = pygsti.construction.list_all_circuits_without_powers_and_cycles( list(std.target_model().operations.keys()), 2) bSuccess, eigvals_finiteL = pygsti.alg.test_germ_list_finitel( self.mdl_target_noisy, germsToTest, L=16, returnSpectrum=True, tol=1e-3) self.assertFalse(bSuccess) bSuccess,eigvals_infiniteL = pygsti.alg.test_germ_list_infl( self.mdl_target_noisy, germsToTest, returnSpectrum=True, check=True) self.assertFalse(bSuccess)
def test_modelfunction(self): mdl = std.target_model() raw_gsf = pygsti.objects.modelfunction.ModelFunction(mdl, "all") self.assertTrue(raw_gsf.evaluate(mdl) is None) #another case that isn't covered elsewhere: "effect" mode of a vec-fn def vec_dummy(vecA, vecB, mxBasis): return np.linalg.norm(vecA-vecB) Vec_dummy = pygsti.objects.modelfunction.vecsfn_factory(vec_dummy) # init args == (model1, model2, label, typ) test = Vec_dummy(mdl, mdl, "Mdefault:0", "effect")
def test_longSequenceGST_wMapCalc(self): ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/drivers.dataset%s" % self.versionsuffix) ts = "whole germ powers" target_model = std.target_model() target_model._calcClass = MapForwardSimulator maxLens = self.maxLens result = self.runSilent(pygsti.do_long_sequence_gst, ds, target_model, std.fiducials, std.fiducials, std.germs, maxLens, advancedOptions={'truncScheme': ts})
def test_grasp_fidsel(self): prepFidList = pygsti.alg.grasp_fiducial_optimization( std.target_model(), std.fiducials, prepOrMeas="prep", alpha=0.0, verbosity=4) measFidList = pygsti.alg.grasp_fiducial_optimization( std.target_model(), std.fiducials, prepOrMeas="meas", alpha=1.0, verbosity=4) with self.assertRaises(ValueError): pygsti.alg.grasp_fiducial_optimization(std.target_model(), std.fiducials, prepOrMeas="foobar", alpha=0.5, verbosity=4)
def test_reports_logL_TP_noCIs(self): vs = self.versionsuffix #Also test adding a model-test estimate to this report mdl_guess = std.target_model().depolarize(op_noise=0.07, spam_noise=0.03) results = self.results_logL.copy() results.add_model_test(std.target_model(), mdl_guess, estimate_key='Test', gauge_opt_keys="auto") #Note: this report will have (un-combined) Robust estimates too pygsti.report.create_standard_report( results, temp_files + "/general_reportC", "Report C", confidenceLevel=None, verbosity=3, auto_open=False, advancedOptions={'combine_robust': False})