Esempio n. 1
0
    def test_bootstrap(self):
        """Test bootstrap model generation"""
        ds = pygsti.data.DataSet(file_to_load_from=compare_files +
                                 "/drivers.dataset")
        tp_target = std.target_model()
        tp_target.set_all_parameterizations("full TP")
        mdl = pygsti.run_lgst(ds,
                              std.fiducials,
                              std.fiducials,
                              target_model=tp_target,
                              svd_truncate_to=4,
                              verbosity=0)

        default_maxLens = [0] + [2**k for k in range(5)]
        circuits = pygsti.circuits.create_lsgst_circuits(
            self.op_labels,
            self.fiducials,
            self.fiducials,
            self.germs,
            default_maxLens,
            fid_pairs=None,
            trunc_scheme="whole germ powers")
        ds_defaultMaxLens = pygsti.data.simulate_data(mdl,
                                                      circuits,
                                                      num_samples=10000,
                                                      sample_error='round')

        bootgs_p_defaultMaxLens = \
            pygsti.drivers.create_bootstrap_models(
                2, ds_defaultMaxLens, 'parametric', std.fiducials, std.fiducials,
                std.germs, default_maxLens, input_model=mdl, target_model=tp_target,
                return_data=False) #test when max_lengths == None ?
Esempio n. 2
0
def mdl_lgst(self):
    return pygsti.run_lgst(self.dataset,
                           self.fiducials,
                           self.fiducials,
                           self.model,
                           svd_truncate_to=4,
                           verbosity=0)
Esempio n. 3
0
    def test_LGST_no_sample_error(self):
        #change rep-count type so dataset can hold fractional counts for sampleError = 'none'
        oldType = pygsti.data.dataset.Repcount_type
        pygsti.data.dataset.Repcount_type = np.float64
        ds = pygsti.data.simulate_data(self.datagen_gateset,
                                       self.lgstStrings,
                                       num_samples=10000,
                                       sample_error='none')
        pygsti.data.dataset.Repcount_type = oldType

        mdl_lgst = pygsti.run_lgst(ds,
                                   self.fiducials,
                                   self.fiducials,
                                   self.model,
                                   svd_truncate_to=4,
                                   verbosity=0)
        print("DATAGEN:")
        print(self.datagen_gateset)
        print("\nLGST RAW:")
        print(mdl_lgst)
        mdl_lgst = pygsti.gaugeopt_to_target(mdl_lgst,
                                             self.datagen_gateset, {
                                                 'spam': 1.0,
                                                 'gates': 1.0
                                             },
                                             check_jac=False)
        print("\nAfter gauge opt:")
        print(mdl_lgst)
        print(mdl_lgst.strdiff(self.datagen_gateset))
        self.assertAlmostEqual(mdl_lgst.frobeniusdist(self.datagen_gateset),
                               0,
                               places=4)
Esempio n. 4
0
    def test_LGST_1overSqrtN_dependence(self):
        my_datagen_gateset = self.model.depolarize(op_noise=0.05, spam_noise=0)
        # !!don't depolarize spam or 1/sqrt(N) dependence saturates!!

        nSamplesList = np.array([16, 128, 1024, 8192])
        diffs = []
        for nSamples in nSamplesList:
            ds = pygsti.data.simulate_data(my_datagen_gateset,
                                           self.lgstStrings,
                                           nSamples,
                                           sample_error='binomial',
                                           seed=100)
            mdl_lgst = pygsti.run_lgst(ds,
                                       self.fiducials,
                                       self.fiducials,
                                       self.model,
                                       svd_truncate_to=4,
                                       verbosity=0)
            mdl_lgst_go = pygsti.gaugeopt_to_target(mdl_lgst,
                                                    my_datagen_gateset, {
                                                        'spam': 1.0,
                                                        'gate': 1.0
                                                    },
                                                    check_jac=True)
            diffs.append(my_datagen_gateset.frobeniusdist(mdl_lgst_go))

        diffs = np.array(diffs, 'd')
        a, b = polyfit(np.log10(nSamplesList), np.log10(diffs), deg=1)
        #print "\n",nSamplesList; print diffs; print a #DEBUG
        self.assertLess(a + 0.5, 0.05)
Esempio n. 5
0
    def test_LGST(self):

        ds = self.ds

        print("GG0 = ", self.model.default_gauge_group)
        mdl_lgst = pygsti.run_lgst(ds,
                                   self.fiducials,
                                   self.fiducials,
                                   self.model,
                                   svd_truncate_to=4,
                                   verbosity=0)
        mdl_lgst_verb = self.runSilent(pygsti.run_lgst,
                                       ds,
                                       self.fiducials,
                                       self.fiducials,
                                       self.model,
                                       svd_truncate_to=4,
                                       verbosity=10)
        self.assertAlmostEqual(mdl_lgst.frobeniusdist(mdl_lgst_verb), 0)

        print("GG = ", mdl_lgst.default_gauge_group)
        mdl_lgst_go = pygsti.gaugeopt_to_target(mdl_lgst,
                                                self.model, {
                                                    'spam': 1.0,
                                                    'gates': 1.0
                                                },
                                                check_jac=True)
        mdl_clgst = pygsti.contract(mdl_lgst_go, "CPTP")

        # RUN BELOW LINES TO SEED SAVED GATESET FILES
        if regenerate_references():
            pygsti.io.write_model(
                mdl_lgst, compare_files + "/lgst.model",
                "Saved LGST Model before gauge optimization")
            pygsti.io.write_model(mdl_lgst_go,
                                  compare_files + "/lgst_go.model",
                                  "Saved LGST Model after gauge optimization")
            pygsti.io.write_model(
                mdl_clgst, compare_files + "/clgst.model",
                "Saved LGST Model after G.O. and CPTP contraction")

        mdl_lgst_compare = pygsti.io.load_model(compare_files + "/lgst.model")
        mdl_lgst_go_compare = pygsti.io.load_model(compare_files +
                                                   "/lgst_go.model")
        mdl_clgst_compare = pygsti.io.load_model(compare_files +
                                                 "/clgst.model")

        self.assertAlmostEqual(mdl_lgst.frobeniusdist(mdl_lgst_compare),
                               0,
                               places=5)
        self.assertAlmostEqual(mdl_lgst_go.frobeniusdist(mdl_lgst_go_compare),
                               0,
                               places=5)
        self.assertAlmostEqual(mdl_clgst.frobeniusdist(mdl_clgst_compare),
                               0,
                               places=5)
Esempio n. 6
0
    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(ReportBaseCase, cls).setUpClass()

        orig_cwd = os.getcwd()
        os.chdir(os.path.abspath(os.path.dirname(__file__)))
        os.chdir('..') # The test_packages directory

        target_model = std.target_model()
        datagen_gateset = target_model.depolarize(op_noise=0.05, spam_noise=0.1)
        datagen_gateset2 = target_model.depolarize(op_noise=0.1, spam_noise=0.05).rotate((0.15,-0.03,0.03))

        #cls.specs = pygsti.construction.build_spam_specs(std.fiducials, effect_labels=['E0'])
        #  #only use the first EVec

        op_labels = std.gates
        cls.lgstStrings = pygsti.circuits.create_lgst_circuits(std.fiducials, std.fiducials, op_labels)
        cls.maxLengthList = [1,2,4,8]

        cls.lsgstStrings = pygsti.circuits.create_lsgst_circuit_lists(
            op_labels, std.fiducials, std.fiducials, std.germs, cls.maxLengthList)
        cls.lsgstStructs = pygsti.circuits.make_lsgst_structs(
            op_labels, std.fiducials, std.fiducials, std.germs, cls.maxLengthList)


        # RUN BELOW LINES TO GENERATE ANALYSIS DATASET (SAVE)
        if regenerate_references():
            ds = pygsti.data.simulate_data(datagen_gateset, cls.lsgstStrings[-1], num_samples=1000,
                                                   sample_error='binomial', seed=100)
            ds.save(compare_files + "/reportgen.dataset")
            ds2 = pygsti.data.simulate_data(datagen_gateset2, cls.lsgstStrings[-1], num_samples=1000,
                                                    sample_error='binomial', seed=100)
            ds2.save(compare_files + "/reportgen2.dataset")


        cls.ds = pygsti.data.DataSet(file_to_load_from=compare_files + "/reportgen.dataset")
        cls.ds2 = pygsti.data.DataSet(file_to_load_from=compare_files + "/reportgen2.dataset")

        mdl_lgst = pygsti.run_lgst(cls.ds, std.fiducials, std.fiducials, target_model, svd_truncate_to=4, verbosity=0)
        mdl_lgst_go = pygsti.gaugeopt_to_target(mdl_lgst, target_model, {'gates': 1.0, 'spam': 0.0})
        cls.mdl_clgst = pygsti.contract(mdl_lgst_go, "CPTP")
        cls.mdl_clgst_tp = pygsti.contract(cls.mdl_clgst, "vSPAM")
        cls.mdl_clgst_tp.set_all_parameterizations("full TP")

        #Compute results for MC2GST
        lsgst_gatesets_prego, *_ = pygsti.run_iterative_gst(
            cls.ds, cls.mdl_clgst, cls.lsgstStrings,
            optimizer={'tol': 1e-5},
            iteration_objfn_builders=['chi2'],
            final_objfn_builders=[],
            resource_alloc=None,
            verbosity=0
        )

        experiment_design = pygsti.protocols.StandardGSTDesign(
            target_model.create_processor_spec(), std.fiducials, std.fiducials, std.germs, cls.maxLengthList
        )
        data = pygsti.protocols.ProtocolData(experiment_design, cls.ds)
        protocol = pygsti.protocols.StandardGST()
        cls.results = pygsti.protocols.gst.ModelEstimateResults(data, protocol)
        cls.results.add_estimate(pygsti.protocols.estimate.Estimate.create_gst_estimate(
            cls.results, target_model, cls.mdl_clgst,lsgst_gatesets_prego,
            {'objective': "chi2",
             'min_prob_clip_for_weighting': 1e-4,
             'prob_clip_interval': (-1e6,1e6), 'radius': 1e-4,
             'weights': None, 'defaultDirectory': temp_files + "",
             'defaultBasename': "MyDefaultReportName"}
        ))

        gaugeOptParams = collections.OrderedDict([
                ('model', lsgst_gatesets_prego[-1]),  #so can gauge-propagate CIs
                ('target_model', target_model),       #so can gauge-propagate CIs
                ('cptp_penalty_factor', 0),
                ('gates_metric',"frobenius"),
                ('spam_metric',"frobenius"),
                ('item_weights', {'gates': 1.0, 'spam': 0.001}),
                ('return_all', True) ])

        _, gaugeEl, go_final_gateset = pygsti.gaugeopt_to_target(**gaugeOptParams)
        gaugeOptParams['_gaugeGroupEl'] = gaugeEl  #so can gauge-propagate CIs
        cls.results.estimates['default'].add_gaugeoptimized(gaugeOptParams, go_final_gateset)
        cls.results.estimates['default'].add_gaugeoptimized(gaugeOptParams, go_final_gateset, "go_dup")

        #Compute results for MLGST with TP constraint
        # Use run_long_sequence_gst with a non-mark dataset to trigger data scaling
        tp_target = target_model.copy(); tp_target.set_all_parameterizations("full TP")


        cls.ds3 = cls.ds.copy_nonstatic()
        cls.ds3.add_counts_from_dataset(cls.ds2)
        cls.ds3.done_adding_data()

        cls.results_logL = pygsti.run_long_sequence_gst(cls.ds3, tp_target, std.fiducials, std.fiducials,
                                                        std.germs, cls.maxLengthList, verbosity=0,
                                                        advanced_options={'tolerance': 1e-6, 'starting_point': 'LGST',
                                                                        'on_bad_fit': ["robust","Robust","robust+","Robust+"],
                                                                        'bad_fit_threshold': -1.0,
                                                                        'germ_length_limits': {('Gx','Gi','Gi'): 2} })

        #OLD
        #lsgst_gatesets_TP = pygsti.do_iterative_mlgst(cls.ds, cls.mdl_clgst_tp, cls.lsgstStrings, verbosity=0,
        #                                           min_prob_clip=1e-4, prob_clip_interval=(-1e6,1e6),
        #                                           returnAll=True) #TP initial model => TP output models
        #cls.results_logL = pygsti.objects.Results()
        #cls.results_logL.init_dataset(cls.ds)
        #cls.results_logL.init_circuits(cls.lsgstStructs)
        #cls.results_logL.add_estimate(target_model, cls.mdl_clgst_tp,
        #                         lsgst_gatesets_TP,
        #                         {'objective': "logl",
        #                          'min_prob_clip': 1e-4,
        #                          'prob_clip_interval': (-1e6,1e6), 'radius': 1e-4,
        #                          'weights': None, 'defaultDirectory': temp_files + "",
        #                          'defaultBasename': "MyDefaultReportName"})
        #
        #tp_target = target_model.copy(); tp_target.set_all_parameterizations("full TP")
        #gaugeOptParams = gaugeOptParams.copy() #just to be safe
        #gaugeOptParams['model'] = lsgst_gatesets_TP[-1]  #so can gauge-propagate CIs
        #gaugeOptParams['target_model'] = tp_target  #so can gauge-propagate CIs
        #_, gaugeEl, go_final_gateset = pygsti.gaugeopt_to_target(**gaugeOptParams)
        #gaugeOptParams['_gaugeGroupEl'] = gaugeEl #so can gauge-propagate CIs
        #cls.results_logL.estimates['default'].add_gaugeoptimized(gaugeOptParams, go_final_gateset)
        #
        ##self.results_logL.options.precision = 3
        ##self.results_logL.options.polar_precision = 2

        os.chdir(orig_cwd)
Esempio n. 7
0
    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.modelmembers.povms.UnconstrainedPOVM({'0': E, '1': Erem}, evotype='default')

        # 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.modelmembers.instruments.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_struct = pygsti.circuits.create_lsgst_circuits(
            glbls,fiducials,fiducials,germs,max_lengths)
        lsgst_struct2 = pygsti.circuits.create_lsgst_circuits(
            mdl,fiducials,fiducials,germs,max_lengths) #use mdl as source
        self.assertEqual(list(lsgst_struct), list(lsgst_struct2))



        mdl_datagen = mdl
        ds = pygsti.data.simulate_data(mdl, lsgst_struct, 1000, 'none') #'multinomial')
        pygsti.io.write_dataset(temp_files + "/intermediate_meas_dataset.txt", ds)
        ds2 = pygsti.io.read_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.run_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.circuits.create_lsgst_circuits(self.target_model,fiducials,fiducials,germs,max_lengths)
        ##self.target_model.simplify_circuits(dbList, ds)
        #self.target_model.simplify_circuits([ pygsti.circuits.Circuit(None,stringrep="Iz") ], ds )
        #assert(False),"STOP"

        #LSGST
        results = pygsti.run_long_sequence_gst(ds, self.target_model, fiducials, fiducials, germs, max_lengths)
        #print(results.estimates[results.name].models['go0'])
        mdl_est = results.estimates[results.name].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("full TP")
        self.assertEqual(mdl_targetTP.num_params,71) # 3 + 4*2 + 12*5 = 71
        #print(mdl_targetTP)
        resultsTP = pygsti.run_long_sequence_gst(ds, mdl_targetTP, fiducials, fiducials, germs, max_lengths, verbosity=4)
        mdl_est = resultsTP.estimates[resultsTP.name].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)