Ejemplo n.º 1
0
    def test_mapcalc_hessian(self):
        chi2, chi2Hessian = pygsti.chi2(self.gateset, self.ds, 
                                        returnHessian=True)
        
        gs_mapcalc = self.gateset.copy()
        gs_mapcalc._calcClass = GateMapCalc
        chi2, chi2Hessian_mapcalc = pygsti.chi2(self.gateset, self.ds, 
                                        returnHessian=True)

        self.assertArraysAlmostEqual(chi2Hessian, chi2Hessian_mapcalc)
Ejemplo n.º 2
0
    def test_mapcalc_hessian(self):
        chi2, chi2Hessian = pygsti.chi2(self.model, self.ds,
                                        returnHessian=True)

        mdl_mapcalc = self.model.copy()
        mdl_mapcalc._calcClass = MapForwardSimulator
        chi2, chi2Hessian_mapcalc = pygsti.chi2(self.model, self.ds,
                                        returnHessian=True)

        self.assertArraysAlmostEqual(chi2Hessian, chi2Hessian_mapcalc)
Ejemplo n.º 3
0
    def test_chi2_fn(self):
        ds = pygsti.objects.DataSet(fileToLoadFrom="cmp_chk_files/analysis.dataset")
        chi2, grad = pygsti.chi2(ds, std.gs_target, returnGradient=True)

        pygsti.gate_string_chi2( ('Gx',), ds, std.gs_target)
        pygsti.chi2fn_2outcome( N=100, p=0.5, f=0.6)
        pygsti.chi2fn_2outcome_wfreqs( N=100, p=0.5, f=0.6)
        pygsti.chi2fn( N=100, p=0.5, f=0.6)
        pygsti.chi2fn_wfreqs( N=100, p=0.5, f=0.6)

        with self.assertRaises(ValueError):
            pygsti.chi2(ds, std.gs_target, useFreqWeightedChiSq=True) #no impl yet
Ejemplo n.º 4
0
    def test_hessian_projection(self):

        chi2, chi2Grad, chi2Hessian = pygsti.chi2(self.ds, self.gateset,
                                                  returnGradient=True,
                                                  returnHessian=True)

        proj_non_gauge = self.gateset.get_nongauge_projector()
        projectedHessian = np.dot(proj_non_gauge, 
                                  np.dot(chi2Hessian, proj_non_gauge))

        self.assertEqual( projectedHessian.shape, (56,56) )
        self.assertEqual( np.linalg.matrix_rank(proj_non_gauge), 40)        
        self.assertEqual( np.linalg.matrix_rank(projectedHessian), 40)

        eigvals = np.sort(abs(np.linalg.eigvals(projectedHessian)))
        
        eigvals_chk = np.array( 
            [  2.36932621e-11,   4.57739349e-11,   8.49888013e-11,   8.49888013e-11,
               1.22859895e-10,   1.22859895e-10,   1.38705957e-10,   1.38705957e-10,
               3.75441328e-10,   6.46644807e-10,   6.46644807e-10,   7.06181642e-10,
               7.06181642e-10,   7.65472749e-10,   1.62672899e-09,   1.62672899e-09,
               9.23280752e+04,   9.88622140e+04,   1.24577730e+05,   1.40500652e+05,
               1.88461602e+05,   1.98466608e+05,   2.07084497e+05,   2.27489018e+05,
               2.33403285e+05,   2.52573024e+05,   2.82350782e+05,   3.12087185e+05,
               3.21855420e+05,   3.31659734e+05,   3.52649174e+05,   3.60682071e+05,
               3.90777833e+05,   4.59913853e+05,   5.02652879e+05,   5.59311926e+05,
               5.78891070e+05,   6.82325323e+05,   7.57318263e+05,   8.16739390e+05,
               1.06466062e+06,   1.20075694e+06,   1.37368639e+06,   1.58356629e+06,
               1.68898356e+06,   2.12277359e+06,   3.30650801e+06,   3.75869331e+06,
               4.00195245e+06,   4.42427797e+06,   5.06956256e+06,   7.31166332e+06,
               9.19432790e+06,   9.99944236e+06,   1.31027722e+07,   5.80310818e+07] )
        for val,chk in zip(eigvals,eigvals_chk):
            self.assertAlmostEqual(abs(val-chk)/(abs(chk)+1e-6), 0.0, places=3)
Ejemplo n.º 5
0
    def test_model_selection(self):

        ds = self.ds
        #pygsti.construction.generate_fake_data(self.datagen_gateset, self.lsgstStrings[-1],
        #                                            nSamples=1000,sampleError='binomial', seed=100)


        mdl_lgst4 = pygsti.do_lgst(ds, self.fiducials, self.fiducials, self.model, svdTruncateTo=4, verbosity=0)
        mdl_lgst6 = pygsti.do_lgst(ds, self.fiducials, self.fiducials, self.model, svdTruncateTo=6, verbosity=0)
        sys.stdout.flush()

        self.runSilent(pygsti.do_lgst, ds, self.fiducials, self.fiducials, self.model, svdTruncateTo=6, verbosity=4) # test verbose prints

        chiSq4 = pygsti.chi2(mdl_lgst4, ds, self.lgstStrings, minProbClipForWeighting=1e-4)
        chiSq6 = pygsti.chi2(mdl_lgst6, ds, self.lgstStrings, minProbClipForWeighting=1e-4)

        print("LGST dim=4 chiSq = ",chiSq4)
        print("LGST dim=6 chiSq = ",chiSq6)
        #self.assertAlmostEqual(chiSq4, 174.061524953) #429.271983052)
        #self.assertAlmostEqual(chiSq6, 267012993.861, places=1) #1337.74222467) #Why is this so large??? -- DEBUG later

        # Least squares GST with model selection
        mdl_lsgst = self.runSilent(pygsti.do_iterative_mc2gst_with_model_selection, ds, mdl_lgst4, 1, self.lsgstStrings[0:3],
                                  verbosity=10, minProbClipForWeighting=1e-3, probClipInterval=(-1e5,1e5))

        # Run again with other parameters
        tuple_strings = [ list(map(tuple, gsList)) for gsList in self.lsgstStrings[0:3] ] #to test tuple argument
        errorVecs, mdl_lsgst_wts = self.runSilent(pygsti.do_iterative_mc2gst_with_model_selection, ds, mdl_lgst4,
                                                 1, tuple_strings, verbosity=10, minProbClipForWeighting=1e-3,
                                                 probClipInterval=(-1e5,1e5), circuitWeightsDict={ ('Gx',): 2.0 },
                                                 returnAll=True, returnErrorVec=True)

        # Do non-iterative to cover Circuit->tuple conversion
        mdl_non_iterative = self.runSilent( pygsti.do_mc2gst_with_model_selection, ds,
                                           mdl_lgst4, 1, self.lsgstStrings[0],
                                           verbosity=10, probClipInterval=(-1e5,1e5) )


        # RUN BELOW LINES TO SEED SAVED GATESET FILES
        if os.environ.get('PYGSTI_REGEN_REF_FILES','no').lower() in ("yes","1","true"):
            pygsti.io.write_model(mdl_lsgst,compare_files + "/lsgstMS.model", "Saved LSGST Model with model selection")

        mdl_lsgst_compare = pygsti.io.load_model(compare_files + "/lsgstMS.model")
        mdl_lsgst_go = pygsti.gaugeopt_to_target(mdl_lsgst, mdl_lsgst_compare, {'spam':1.0}, checkJac=True)
        self.assertAlmostEqual( mdl_lsgst_go.frobeniusdist(mdl_lsgst_compare), 0, places=4)
Ejemplo n.º 6
0
    def test_model_selection(self):

        ds = self.ds
        #pygsti.construction.generate_fake_data(self.datagen_gateset, self.lsgstStrings[-1],
        #                                            nSamples=1000,sampleError='binomial', seed=100)


        gs_lgst4 = pygsti.do_lgst(ds, self.specs, self.gateset, svdTruncateTo=4, verbosity=0)
        gs_lgst6 = pygsti.do_lgst(ds, self.specs, self.gateset, svdTruncateTo=6, verbosity=0)
        sys.stdout.flush()

        self.runSilent(pygsti.do_lgst, ds, self.specs, self.gateset, svdTruncateTo=6, verbosity=4) # test verbose prints

        chiSq4 = pygsti.chi2(ds, gs_lgst4, self.lgstStrings, minProbClipForWeighting=1e-4)
        chiSq6 = pygsti.chi2(ds, gs_lgst6, self.lgstStrings, minProbClipForWeighting=1e-4)

        print("LGST dim=4 chiSq = ",chiSq4)
        print("LGST dim=6 chiSq = ",chiSq6)
        #self.assertAlmostEqual(chiSq4, 174.061524953) #429.271983052)
        #self.assertAlmostEqual(chiSq6, 267012993.861, places=1) #1337.74222467) #Why is this so large??? -- DEBUG later

        # Least squares GST with model selection
        gs_lsgst = self.runSilent(pygsti.do_iterative_mc2gst_with_model_selection, ds, gs_lgst4, 1, self.lsgstStrings[0:3],
                                  verbosity=10, minProbClipForWeighting=1e-3, probClipInterval=(-1e5,1e5))

        # Run again with other parameters
        tuple_strings = [ list(map(tuple, gsList)) for gsList in self.lsgstStrings[0:3] ] #to test tuple argument
        errorVecs, gs_lsgst_wts = self.runSilent(pygsti.do_iterative_mc2gst_with_model_selection, ds, gs_lgst4,
                                                 1, tuple_strings, verbosity=10, minProbClipForWeighting=1e-3,
                                                 probClipInterval=(-1e5,1e5), gatestringWeightsDict={ ('Gx',): 2.0 },
                                                 returnAll=True, returnErrorVec=True)

        # Do non-iterative to cover GateString->tuple conversion
        gs_non_iterative = self.runSilent( pygsti.do_mc2gst_with_model_selection, ds,
                                           gs_lgst4, 1, self.lsgstStrings[0],
                                           verbosity=10, probClipInterval=(-1e5,1e5) )


        # RUN BELOW LINES TO SEED SAVED GATESET FILES
        #pygsti.io.write_gateset(gs_lsgst,compare_files + "/lsgstMS.gateset", "Saved LSGST Gateset with model selection")

        gs_lsgst_compare = pygsti.io.load_gateset(compare_files + "/lsgstMS.gateset")
        gs_lsgst_go = pygsti.optimize_gauge(gs_lsgst, 'target', targetGateset=gs_lsgst_compare, spamWeight=1.0)
        self.assertAlmostEqual( gs_lsgst_go.frobeniusdist(gs_lsgst_compare), 0, places=5)
Ejemplo n.º 7
0
    def test_chi2_fn(self):
        ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/analysis.dataset")
        chi2, grad = pygsti.chi2(ds, std.gs_target, returnGradient=True)
        pygsti.chi2(ds, std.gs_target, returnHessian=True)

        pygsti.gate_string_chi2( ('Gx',), ds, std.gs_target)
        pygsti.chi2fn_2outcome( N=100, p=0.5, f=0.6)
        pygsti.chi2fn_2outcome_wfreqs( N=100, p=0.5, f=0.6)
        pygsti.chi2fn( N=100, p=0.5, f=0.6)
        pygsti.chi2fn_wfreqs( N=100, p=0.5, f=0.6)

        with self.assertRaises(ValueError):
            pygsti.chi2(ds, std.gs_target, useFreqWeightedChiSq=True) #no impl yet

        # Memory tests

        with self.assertRaises(MemoryError):
            pygsti.chi2(ds, std.gs_target, memLimit=0) # No memory for you
        pygsti.chi2(ds, std.gs_target, memLimit=100000)
Ejemplo n.º 8
0
    def test_chi2_fn(self):
        ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files +
                                    "/analysis.dataset%s" % self.versionsuffix)
        chi2, grad = pygsti.chi2(std.gs_target, ds, returnGradient=True)
        pygsti.chi2(std.gs_target, ds, returnHessian=True)

        #pygsti.gate_string_chi2( ('Gx',), ds, std.gs_target)
        pygsti.chi2fn_2outcome(N=100, p=0.5, f=0.6)
        pygsti.chi2fn_2outcome_wfreqs(N=100, p=0.5, f=0.6)
        pygsti.chi2fn(N=100, p=0.5, f=0.6)
        pygsti.chi2fn_wfreqs(N=100, p=0.5, f=0.6)

        with self.assertRaises(ValueError):
            pygsti.chi2(std.gs_target, ds,
                        useFreqWeightedChiSq=True)  #no impl yet

        # Memory tests

        with self.assertRaises(MemoryError):
            pygsti.chi2(std.gs_target, ds, memLimit=0)  # No memory for you
        pygsti.chi2(std.gs_target, ds, memLimit=100000)
Ejemplo n.º 9
0
    def test_hessian_projection(self):

        chi2, chi2Grad, chi2Hessian = pygsti.chi2(self.model, self.ds,
                                                  returnGradient=True,
                                                  returnHessian=True)

        proj_non_gauge = self.model.get_nongauge_projector()
        projectedHessian = np.dot(proj_non_gauge,
                                  np.dot(chi2Hessian, proj_non_gauge))

        print(self.model.num_params())
        print(proj_non_gauge.shape)
        self.assertEqual( projectedHessian.shape, (60,60) )
        #print("Evals = ")
        #print("\n".join( [ "%d: %g" % (i,ev) for i,ev in enumerate(np.linalg.eigvals(projectedHessian))] ))
        self.assertEqual( np.linalg.matrix_rank(proj_non_gauge), 44)
        self.assertEqual( np.linalg.matrix_rank(projectedHessian), 44)

        eigvals = np.sort(abs(np.linalg.eigvals(projectedHessian)))

        print("eigvals = ",eigvals)

        eigvals_chk = np.array([2.51663034e-10, 2.51663034e-10, 6.81452335e-10, 7.72039792e-10,
                                8.76915081e-10, 8.76915081e-10, 1.31455011e-09, 3.03808236e-09,
                                3.03808236e-09, 3.13457752e-09, 3.21805358e-09, 3.21805358e-09,
                                4.78549720e-09, 7.83389490e-09, 1.82493106e-08, 1.82493106e-08,
                                9.23087831e+05, 1.05783101e+06, 1.16457705e+06, 1.39492929e+06,
                                1.84015484e+06, 2.10613947e+06, 2.37963392e+06, 2.47192689e+06,
                                2.64566761e+06, 2.68722871e+06, 2.82383377e+06, 2.86584033e+06,
                                2.94590436e+06, 2.96180212e+06, 3.08322015e+06, 3.29389050e+06,
                                3.66581786e+06, 3.76266448e+06, 3.81921738e+06, 3.86624688e+06,
                                3.89045873e+06, 4.72831630e+06, 4.96416855e+06, 6.53286834e+06,
                                1.01424911e+07, 1.11347312e+07, 1.26152967e+07, 1.30081040e+07,
                                1.36647082e+07, 1.49293583e+07, 1.58234599e+07, 1.80999182e+07,
                                2.09155048e+07, 2.17444267e+07, 2.46870311e+07, 2.64427393e+07,
                                2.72410297e+07, 3.34988002e+07, 3.45005948e+07, 3.69040745e+07,
                                5.08647137e+07, 9.43153151e+07, 1.36088308e+08, 6.30304807e+08])

        TOL = 1e-7
        for val,chk in zip(eigvals,eigvals_chk):
            if abs(val) > TOL or abs(chk) > TOL:
                self.assertAlmostEqual(abs(val-chk)/(abs(chk)+TOL), 0.0, places=3)
Ejemplo n.º 10
0
    def test_confidenceRegion(self):

        chi2, chi2Hessian = pygsti.chi2(self.ds, self.gateset, returnHessian=True)
        ci_std = pygsti.obj.ConfidenceRegion(self.gateset, chi2Hessian, 95.0, hessianProjection="std")
        ci_noproj = pygsti.obj.ConfidenceRegion(self.gateset, chi2Hessian, 95.0, hessianProjection="none")
        ci_opt = pygsti.obj.ConfidenceRegion(
            self.gateset, chi2Hessian, 95.0, hessianProjection="optimal gate CIs", tol=0.1
        )  # very low tol so doesn't take long

        with self.assertRaises(ValueError):
            pygsti.obj.ConfidenceRegion(
                self.gateset, chi2Hessian, 95.0, hessianProjection="FooBar"
            )  # bad hessianProjection

        self.assertWarns(
            pygsti.obj.ConfidenceRegion, self.gateset, chi2Hessian, 0.95, hessianProjection="none"
        )  # percentage < 1.0

        ar_of_intervals_Gx = ci_std.get_profile_likelihood_confidence_intervals("Gx")
        ar_of_intervals_rho0 = ci_std.get_profile_likelihood_confidence_intervals("rho0")
        ar_of_intervals_E0 = ci_std.get_profile_likelihood_confidence_intervals("E0")
        ar_of_intervals = ci_std.get_profile_likelihood_confidence_intervals()

        def fnOfGate_float(mx):
            return float(mx[0, 0])

        def fnOfGate_0D(mx):
            return np.array(float(mx[0, 0]))

        def fnOfGate_1D(mx):
            return mx[0, :]

        def fnOfGate_2D(mx):
            return mx[:, :]

        def fnOfGate_3D(mx):
            return np.zeros((2, 2, 2), "d")  # just to test for error

        df = ci_std.get_gate_fn_confidence_interval(fnOfGate_float, "Gx", verbosity=0)
        df = ci_std.get_gate_fn_confidence_interval(fnOfGate_0D, "Gx", verbosity=0)
        df = ci_std.get_gate_fn_confidence_interval(fnOfGate_1D, "Gx", verbosity=0)
        df = ci_std.get_gate_fn_confidence_interval(fnOfGate_2D, "Gx", verbosity=0)
        df, f0 = self.runSilent(
            ci_std.get_gate_fn_confidence_interval, fnOfGate_float, "Gx", returnFnVal=True, verbosity=4
        )

        with self.assertRaises(ValueError):
            ci_std.get_gate_fn_confidence_interval(fnOfGate_3D, "Gx", verbosity=0)

        def fnOfSpam_float(rhoVecs, EVecs):
            return float(np.dot(rhoVecs[0].T, EVecs[0]))

        def fnOfSpam_0D(rhoVecs, EVecs):
            return np.array(float(np.dot(rhoVecs[0].T, EVecs[0])))

        def fnOfSpam_1D(rhoVecs, EVecs):
            return np.array([np.dot(rhoVecs[0].T, EVecs[0]), 0])

        def fnOfSpam_2D(rhoVecs, EVecs):
            return np.array([[np.dot(rhoVecs[0].T, EVecs[0]), 0], [0, 0]])

        def fnOfSpam_3D(rhoVecs, EVecs):
            return np.zeros((2, 2, 2), "d")  # just to test for error

        df = ci_std.get_spam_fn_confidence_interval(fnOfSpam_float, verbosity=0)
        df = ci_std.get_spam_fn_confidence_interval(fnOfSpam_0D, verbosity=0)
        df = ci_std.get_spam_fn_confidence_interval(fnOfSpam_1D, verbosity=0)
        df = ci_std.get_spam_fn_confidence_interval(fnOfSpam_2D, verbosity=0)
        df, f0 = self.runSilent(ci_std.get_spam_fn_confidence_interval, fnOfSpam_float, returnFnVal=True, verbosity=4)

        with self.assertRaises(ValueError):
            ci_std.get_spam_fn_confidence_interval(fnOfSpam_3D, verbosity=0)
Ejemplo n.º 11
0
    def test_table_generation(self):
        import pygsti.report.generation as gen
        formats = ['latex','html','test','ppt'] #all the formats we know
        tableclass = "cssClass"
        longtable = False
        confidenceRegionInfo = None

        gateset = pygsti.io.load_gateset(compare_files + "/analysis.gateset")
        ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/analysis.dataset")

        chi2, chi2Hessian = pygsti.chi2(ds, gateset, returnHessian=True)
        ci = pygsti.obj.ConfidenceRegion(gateset, chi2Hessian, 95.0,
                                         hessianProjection="std")
        gateset_tp = pygsti.contract(gateset,"TP"); gateset_tp.set_all_parameterizations("TP")
        chi2, chi2Hessian_TP = pygsti.chi2(ds, gateset_tp, returnHessian=True)
        ci_TP = pygsti.obj.ConfidenceRegion(gateset_tp, chi2Hessian_TP, 95.0,
                                            hessianProjection="std")

        chi2, chi2Hessian_tgt = pygsti.chi2(ds, std.gs_target, returnHessian=True)
        ci_tgt = pygsti.obj.ConfidenceRegion(std.gs_target, chi2Hessian_tgt, 95.0,
                                         hessianProjection="std")
        target_tp = std.gs_target.copy(); target_tp.set_all_parameterizations("TP")
        chi2, chi2Hessian_tgt_TP = pygsti.chi2(ds, target_tp, returnHessian=True)
        ci_TP_tgt = pygsti.obj.ConfidenceRegion(target_tp, chi2Hessian_tgt_TP, 95.0,
                                            hessianProjection="std")

        gateset_2q = pygsti.construction.build_gateset(
            [4], [('Q0','Q1')],['GIX','GIY','GXI','GYI','GCNOT'],
            [ "I(Q0):X(pi/2,Q1)", "I(Q0):Y(pi/2,Q1)", "X(pi/2,Q0):I(Q1)", "Y(pi/2,Q0):I(Q1)", "CX(pi,Q0,Q1)" ],
            prepLabels=['rho0'], prepExpressions=["0"], effectLabels=['E0','E1','E2'], effectExpressions=["0","1","2"],
            spamdefs={'upup': ('rho0','E0'), 'updn': ('rho0','E1'), 'dnup': ('rho0','E2'),
                           'dndn': ('rho0','remainder') }, basis="pp" )


        #tests which fill in the cracks of the full-report tests
        tab = gen.get_gateset_spam_table(gateset, None)
        tab_wCI = gen.get_gateset_spam_table(gateset, ci)
        table_wCI_as_str = str(tab_wCI)

        gen.get_gateset_spam_table(gateset, None)
        gen.get_gateset_gates_table(gateset_tp, ci_TP) #test zero-padding
        gen.get_unitary_gateset_gates_table(std.gs_target, ci_tgt) #unitary gates w/CIs
        gen.get_unitary_gateset_gates_table(target_tp, ci_TP_tgt) #unitary gates w/CIs
        gen.get_gateset_closest_unitary_table(gateset_2q, None) #test higher-dim gateset
        gen.get_gateset_closest_unitary_table(gateset, ci) #test with CIs (long...)
        gen.get_gateset_rotn_axis_table(std.gs_target, None) #try to get "--"s and "X"s to display
        gen.get_chi2_progress_table([0], [gateset_tp], [ [('Gx',)],], ds) #TP case
        gen.get_chi2_confidence_region(gateset_tp, ds, 95) #TP case

        gen.get_gatestring_multi_table([ [('Gx',),('Gz',)], [('Gy',)] ],
                                       ["list1","list2"], commonTitle=None) #commonTitle == None case w/diff length lists

        with self.assertRaises(ValueError):
            gen.get_unitary_gateset_gates_table(std.gs_target, ci) #gateset-CI mismatch
        with self.assertRaises(ValueError):
            gen.get_gateset_spam_parameters_table(std.gs_target, ci) #gateset-CI mismatch




        #LogL case tests
        gen.get_logl_progress_table([0], [gateset_tp], [ [('Gx',)],], ds) # logL case
        gen.get_logl_progress_table([0], [gateset], [ [('Gx',)],], ds) # logL case

        gen.get_logl_confidence_region(gateset_tp, ds, 95,
                                       gatestring_list=None, probClipInterval=(-1e6,1e6),
                                       minProbClip=1e-4, radius=1e-4, hessianProjection="std")
        gen.get_logl_confidence_region(gateset, ds, 95,
                                       gatestring_list=None, probClipInterval=(-1e6,1e6),
                                       minProbClip=1e-4, radius=1e-4, hessianProjection="std")
Ejemplo n.º 12
0
 def test_total_chi2(self):
     chi2 = pygsti.chi2(self.ds, self.lsgst_gateset)
     self.assertAlmostEqual(chi2, 729.182015795)
Ejemplo n.º 13
0
    def test_table_generation(self):
        import pygsti.report.generation as gen
        formats = ['latex','html','py','ppt'] #all the formats we know
        tableclass = "cssClass"
        longtable = False
        confidenceRegionInfo = None

        gateset = pygsti.io.load_gateset("cmp_chk_files/analysis.gateset")
        ds = pygsti.objects.DataSet(fileToLoadFrom="cmp_chk_files/analysis.dataset")

        chi2, chi2Hessian = pygsti.chi2(ds, gateset, returnHessian=True)
        ci = pygsti.obj.ConfidenceRegion(gateset, chi2Hessian, 95.0,
                                         hessianProjection="std")
        gateset_tp = pygsti.contract(gateset,"TP"); gateset_tp.set_all_parameterizations("TP")
        chi2, chi2Hessian_TP = pygsti.chi2(ds, gateset_tp, returnHessian=True)
        ci_TP = pygsti.obj.ConfidenceRegion(gateset_tp, chi2Hessian_TP, 95.0,
                                            hessianProjection="std")

        chi2, chi2Hessian_tgt = pygsti.chi2(ds, std.gs_target, returnHessian=True)
        ci_tgt = pygsti.obj.ConfidenceRegion(std.gs_target, chi2Hessian_tgt, 95.0,
                                         hessianProjection="std")
        target_tp = std.gs_target.copy(); target_tp.set_all_parameterizations("TP")
        chi2, chi2Hessian_tgt_TP = pygsti.chi2(ds, target_tp, returnHessian=True)
        ci_TP_tgt = pygsti.obj.ConfidenceRegion(target_tp, chi2Hessian_tgt_TP, 95.0,
                                            hessianProjection="std")

        gateset_2q = pygsti.construction.build_gateset( 
            [4], [('Q0','Q1')],['GIX','GIY','GXI','GYI','GCNOT'], 
            [ "I(Q0):X(pi/2,Q1)", "I(Q0):Y(pi/2,Q1)", "X(pi/2,Q0):I(Q1)", "Y(pi/2,Q0):I(Q1)", "CX(pi,Q0,Q1)" ],
            prepLabels=['rho0'], prepExpressions=["0"], effectLabels=['E0','E1','E2'], effectExpressions=["0","1","2"], 
            spamdefs={'upup': ('rho0','E0'), 'updn': ('rho0','E1'), 'dnup': ('rho0','E2'),
                           'dndn': ('rho0','remainder') }, basis="pp" )
        

        #tests which fill in the cracks of the full-report tests
        with self.assertRaises(ValueError):
            gen.get_gateset_spam_table(gateset, formats, tableclass,
                                       longtable, None, mxBasis="fooBar")
        tab = gen.get_gateset_spam_table(gateset, formats, tableclass, longtable, None, mxBasis="gm")
        tab_wCI = gen.get_gateset_spam_table(gateset, formats, tableclass, longtable, ci, mxBasis="gm")
        gen.get_gateset_spam_table(gateset, formats, tableclass, longtable, None, mxBasis="std")
        gen.get_gateset_spam_table(gateset, formats, tableclass, longtable, None, mxBasis="pp")
        gen.get_gateset_gates_table(gateset_tp, formats, tableclass, longtable, ci_TP) #test zero-padding
        gen.get_unitary_gateset_gates_table(std.gs_target, formats, tableclass, longtable, ci_tgt) #unitary gates w/CIs
        gen.get_unitary_gateset_gates_table(target_tp, formats, tableclass, longtable, ci_TP_tgt) #unitary gates w/CIs
        gen.get_gateset_closest_unitary_table(gateset_2q, formats, tableclass, longtable, None) #test higher-dim gateset
        gen.get_gateset_closest_unitary_table(gateset, formats, tableclass, longtable, ci) #test with CIs (long...)
        gen.get_gateset_rotn_axis_table(std.gs_target, formats, tableclass, longtable, None) #try to get "--"s and "X"s to display
        gen.get_chi2_progress_table([0], [gateset_tp], [ [('Gx',)],], ds, formats, tableclass, longtable) #TP case
        gen.get_chi2_confidence_region(gateset_tp, ds, 95) #TP case

        gen.get_gatestring_multi_table([ [('Gx',),('Gz',)], [('Gy',)] ], ["list1","list2"], formats,
                                       tableclass, longtable, commonTitle=None) #commonTitle == None case w/diff length lists

        with self.assertRaises(ValueError):
            gen.get_unitary_gateset_gates_table(std.gs_target, formats, tableclass, longtable, ci) #gateset-CI mismatch
        with self.assertRaises(ValueError):
            gen.get_gateset_spam_parameters_table(std.gs_target, formats, tableclass, longtable, ci) #gateset-CI mismatch

        #Test ReportTable object
        rowLabels = tab.keys()
        row1Data = tab[rowLabels[0]]
        colLabels = row1Data.keys()

        self.assertTrue(rowLabels, tab.row_names)
        self.assertTrue(colLabels, tab.col_names)
        self.assertTrue(len(rowLabels), tab.num_rows)
        self.assertTrue(len(colLabels), tab.num_cols)

        el00 = tab[rowLabels[0]][colLabels[0]]
        self.assertTrue( rowLabels[0] in tab )
        self.assertTrue( tab.has_key(rowLabels[0]) )

        table_len = len(tab)
        self.assertEqual(table_len, tab.num_rows)

        table_as_str = str(tab)
        table_wCI_as_str = str(tab_wCI)
        row1a = tab.row(key=rowLabels[0])
        col1a = tab.col(key=colLabels[0])
        row1b = tab.row(index=0)
        col1b = tab.col(index=0)
        self.assertEqual(row1a,row1b)
        self.assertEqual(col1a,col1b)

        with self.assertRaises(KeyError):
            tab['foobar']
        with self.assertRaises(KeyError):
            tab.row(key='foobar') #invalid key
        with self.assertRaises(ValueError):
            tab.row(index=100000) #out of bounds
        with self.assertRaises(ValueError):
            tab.row() #must specify key or index
        with self.assertRaises(ValueError):
            tab.row(key='foobar',index=1) #cannot specify key and index
        with self.assertRaises(KeyError):
            tab.col(key='foobar') #invalid key
        with self.assertRaises(ValueError):
            tab.col(index=100000) #out of bounds
        with self.assertRaises(ValueError):
            tab.col() #must specify key or index
        with self.assertRaises(ValueError):
            tab.col(key='foobar',index=1) #cannot specify key and index

        with self.assertRaises(ValueError):
            tab.render(fmt="foobar") #invalid format

        latexOnlyTab = pygsti.report.table.ReportTable(['latex'], ['Col1','Col2'], (None,None),
                                                       "tableClass",False)
        with self.assertRaises(KeyError):
            x = str(latexOnlyTab) #must have 'py' format
            



        #LogL case tests
        gen.get_logl_progress_table([0], [gateset_tp], [ [('Gx',)],], ds, formats, tableclass, longtable) # logL case
        gen.get_logl_progress_table([0], [gateset], [ [('Gx',)],], ds, formats, tableclass, longtable) # logL case

        gen.get_logl_confidence_region(gateset_tp, ds, 95,
                                       gatestring_list=None, probClipInterval=(-1e6,1e6),
                                       minProbClip=1e-4, radius=1e-4, hessianProjection="std")
        gen.get_logl_confidence_region(gateset, ds, 95,
                                       gatestring_list=None, probClipInterval=(-1e6,1e6),
                                       minProbClip=1e-4, radius=1e-4, hessianProjection="std")
Ejemplo n.º 14
0
    def test_hessian_projection(self):

        chi2, chi2Grad, chi2Hessian = pygsti.chi2(self.gateset, self.ds,
                                                  returnGradient=True,
                                                  returnHessian=True)

        proj_non_gauge = self.gateset.get_nongauge_projector()
        projectedHessian = np.dot(proj_non_gauge,
                                  np.dot(chi2Hessian, proj_non_gauge))

        print(self.gateset.num_params())
        print(proj_non_gauge.shape)
        self.assertEqual( projectedHessian.shape, (60,60) )
        #print("Evals = ")
        #print("\n".join( [ "%d: %g" % (i,ev) for i,ev in enumerate(np.linalg.eigvals(projectedHessian))] ))
        self.assertEqual( np.linalg.matrix_rank(proj_non_gauge), 44)
        self.assertEqual( np.linalg.matrix_rank(projectedHessian), 44)

        eigvals = np.sort(abs(np.linalg.eigvals(projectedHessian)))

        print("eigvals = ",eigvals)

        
        eigvals_chk =  np.array(
            [6.11142452e-11, 5.84760068e-10, 6.73066231e-10, 6.89070172e-10,
             6.89070172e-10, 1.16844369e-09, 1.99649746e-09, 1.99649746e-09,
             2.41697718e-09, 2.41697718e-09, 2.80832759e-09, 4.29148412e-09,
             4.29148412e-09, 6.59655396e-09, 6.59655396e-09, 6.76915973e-09,
             9.23087831e+05, 1.05783101e+06, 1.16457705e+06, 1.39492929e+06,
             1.84015484e+06, 2.10613947e+06, 2.37963392e+06, 2.47192689e+06,
             2.64566761e+06, 2.68722871e+06, 2.82383377e+06, 2.86584033e+06,
             2.94590436e+06, 2.96180212e+06, 3.08322015e+06, 3.29389050e+06,
             3.66581786e+06, 3.76266448e+06, 3.81921738e+06, 3.86624688e+06,
             3.89045873e+06, 4.72831630e+06, 4.96416855e+06, 6.53286834e+06,
             1.01424911e+07, 1.11347312e+07, 1.26152967e+07, 1.30081040e+07,
             1.36647082e+07, 1.49293583e+07, 1.58234599e+07, 1.80999182e+07,
             2.09155048e+07, 2.17444267e+07, 2.46870311e+07, 2.64427393e+07,
             2.72410297e+07, 3.34988002e+07, 3.45005948e+07, 3.69040745e+07,
             5.08647137e+07, 9.43153151e+07, 1.36088308e+08, 6.30304807e+08] )

            #OLD
            #[  1.06310603e-10,   2.65635664e-10,   6.50301005e-10,   7.97927477e-10,
            #   7.97927477e-10,   1.00960481e-09,   1.20668922e-09,   1.60395671e-09,
            #   1.60395671e-09,   2.10414039e-09,   2.40422523e-09,   2.66328705e-09,
            #   2.66328705e-09,   3.78157418e-09,   4.97929640e-09,   1.69073771e-08,
            #   9.22542920e+05,   1.05940963e+06,   1.16240250e+06,   1.39506940e+06,
            #   1.83925308e+06,   2.11037916e+06,   2.39385711e+06,   2.47432236e+06,
            #   2.63561759e+06,   2.68157105e+06,   2.81568070e+06,   2.86569765e+06,
            #   2.94543146e+06,   2.95039566e+06,   3.08684833e+06,   3.28869042e+06,
            #   3.66558726e+06,   3.76232707e+06,   3.82389736e+06,   3.86638791e+06,
            #   3.88874028e+06,   4.73808468e+06,   4.96550964e+06,   6.53177028e+06,
            #   1.01544928e+07,   1.11525472e+07,   1.25572253e+07,   1.30411488e+07,
            #   1.36881398e+07,   1.49309288e+07,   1.57790471e+07,   1.81263731e+07,
            #   2.08276405e+07,   2.18675949e+07,   2.46968548e+07,   2.64099665e+07,
            #   2.72117335e+07,   3.35172152e+07,   3.45138716e+07,   3.68918207e+07,
            #   5.09742531e+07,   9.43260992e+07,   1.36044734e+08,   6.30355637e+08])            

        TOL = 1e-7
        for val,chk in zip(eigvals,eigvals_chk):
            if abs(val) > TOL or abs(chk) > TOL:
                self.assertAlmostEqual(abs(val-chk)/(abs(chk)+TOL), 0.0, places=3)
Ejemplo n.º 15
0
    def test_hessian_projection(self):

        chi2, chi2Grad, chi2Hessian = pygsti.chi2(self.gateset,
                                                  self.ds,
                                                  returnGradient=True,
                                                  returnHessian=True)

        proj_non_gauge = self.gateset.get_nongauge_projector()
        projectedHessian = np.dot(proj_non_gauge,
                                  np.dot(chi2Hessian, proj_non_gauge))

        print(self.gateset.num_params())
        print(proj_non_gauge.shape)
        self.assertEqual(projectedHessian.shape, (60, 60))
        #print("Evals = ")
        #print("\n".join( [ "%d: %g" % (i,ev) for i,ev in enumerate(np.linalg.eigvals(projectedHessian))] ))
        self.assertEqual(np.linalg.matrix_rank(proj_non_gauge), 44)
        self.assertEqual(np.linalg.matrix_rank(projectedHessian), 44)

        eigvals = np.sort(abs(np.linalg.eigvals(projectedHessian)))

        print("eigvals = ", eigvals)

        eigvals_chk = np.array([
            1.06310603e-10, 2.65635664e-10, 6.50301005e-10, 7.97927477e-10,
            7.97927477e-10, 1.00960481e-09, 1.20668922e-09, 1.60395671e-09,
            1.60395671e-09, 2.10414039e-09, 2.40422523e-09, 2.66328705e-09,
            2.66328705e-09, 3.78157418e-09, 4.97929640e-09, 1.69073771e-08,
            9.22542920e+05, 1.05940963e+06, 1.16240250e+06, 1.39506940e+06,
            1.83925308e+06, 2.11037916e+06, 2.39385711e+06, 2.47432236e+06,
            2.63561759e+06, 2.68157105e+06, 2.81568070e+06, 2.86569765e+06,
            2.94543146e+06, 2.95039566e+06, 3.08684833e+06, 3.28869042e+06,
            3.66558726e+06, 3.76232707e+06, 3.82389736e+06, 3.86638791e+06,
            3.88874028e+06, 4.73808468e+06, 4.96550964e+06, 6.53177028e+06,
            1.01544928e+07, 1.11525472e+07, 1.25572253e+07, 1.30411488e+07,
            1.36881398e+07, 1.49309288e+07, 1.57790471e+07, 1.81263731e+07,
            2.08276405e+07, 2.18675949e+07, 2.46968548e+07, 2.64099665e+07,
            2.72117335e+07, 3.35172152e+07, 3.45138716e+07, 3.68918207e+07,
            5.09742531e+07, 9.43260992e+07, 1.36044734e+08, 6.30355637e+08
        ])

        #OLD
        #[  2.53636344e-10,   3.87263955e-10,   4.49523968e-10,
        #   8.17955744e-10,   8.17955744e-10,   1.22910388e-09,
        #   1.23803907e-09,   1.67547571e-09,   1.67547571e-09,
        #   1.75147770e-09,   2.20582127e-09,   2.20582127e-09,
        #   2.84333714e-09,   4.43169431e-09,   4.43169431e-09,
        #   1.75164250e-08,   9.38919779e+05,   9.57169426e+05,
        #   9.69271265e+05,   1.41963844e+06,   1.52443387e+06,
        #   1.89627852e+06,   1.97543819e+06,   2.05177386e+06,
        #   2.18333142e+06,   2.30078215e+06,   2.31036461e+06,
        #   2.40108194e+06,   2.63301339e+06,   2.72062783e+06,
        #   2.73970548e+06,   2.90332118e+06,   3.15705184e+06,
        #   3.86079309e+06,   3.87209620e+06,   4.70586582e+06,
        #   8.76738379e+06,   9.73067464e+06,   1.04062266e+07,
        #   1.15408214e+07,   1.21868610e+07,   1.33524791e+07,
        #   1.34516720e+07,   1.50757108e+07,   1.74290255e+07,
        #   1.83023511e+07,   2.15141700e+07,   2.22614418e+07,
        #   2.32690752e+07,   2.88149432e+07,   3.04306844e+07,
        #   3.10300863e+07,   4.25290585e+07,   8.95794195e+07,
        #   1.29723323e+08,   5.69560469e+08])

        TOL = 1e-7
        for val, chk in zip(eigvals, eigvals_chk):
            if abs(val) > TOL or abs(chk) > TOL:
                self.assertAlmostEqual(abs(val - chk) / (abs(chk) + TOL),
                                       0.0,
                                       places=3)
Ejemplo n.º 16
0
    def test_table_generation(self):
        import pygsti.report.generation as gen
        formats = ['latex', 'html', 'py', 'ppt']  #all the formats we know
        tableclass = "cssClass"
        longtable = False
        confidenceRegionInfo = None

        gateset = pygsti.io.load_gateset("cmp_chk_files/analysis.gateset")
        ds = pygsti.objects.DataSet(
            fileToLoadFrom="cmp_chk_files/analysis.dataset")

        chi2, chi2Hessian = pygsti.chi2(ds, gateset, returnHessian=True)
        ci = pygsti.obj.ConfidenceRegion(gateset,
                                         chi2Hessian,
                                         95.0,
                                         hessianProjection="std")
        gateset_tp = pygsti.contract(gateset, "TP")
        gateset_tp.set_all_parameterizations("TP")
        chi2, chi2Hessian_TP = pygsti.chi2(ds, gateset_tp, returnHessian=True)
        ci_TP = pygsti.obj.ConfidenceRegion(gateset_tp,
                                            chi2Hessian_TP,
                                            95.0,
                                            hessianProjection="std")

        chi2, chi2Hessian_tgt = pygsti.chi2(ds,
                                            std.gs_target,
                                            returnHessian=True)
        ci_tgt = pygsti.obj.ConfidenceRegion(std.gs_target,
                                             chi2Hessian_tgt,
                                             95.0,
                                             hessianProjection="std")
        target_tp = std.gs_target.copy()
        target_tp.set_all_parameterizations("TP")
        chi2, chi2Hessian_tgt_TP = pygsti.chi2(ds,
                                               target_tp,
                                               returnHessian=True)
        ci_TP_tgt = pygsti.obj.ConfidenceRegion(target_tp,
                                                chi2Hessian_tgt_TP,
                                                95.0,
                                                hessianProjection="std")

        gateset_2q = pygsti.construction.build_gateset(
            [4], [('Q0', 'Q1')], ['GIX', 'GIY', 'GXI', 'GYI', 'GCNOT'], [
                "I(Q0):X(pi/2,Q1)", "I(Q0):Y(pi/2,Q1)", "X(pi/2,Q0):I(Q1)",
                "Y(pi/2,Q0):I(Q1)", "CX(pi,Q0,Q1)"
            ],
            prepLabels=['rho0'],
            prepExpressions=["0"],
            effectLabels=['E0', 'E1', 'E2'],
            effectExpressions=["0", "1", "2"],
            spamdefs={
                'upup': ('rho0', 'E0'),
                'updn': ('rho0', 'E1'),
                'dnup': ('rho0', 'E2'),
                'dndn': ('rho0', 'remainder')
            },
            basis="pp")

        #tests which fill in the cracks of the full-report tests
        tab = gen.get_gateset_spam_table(gateset, None)
        tab_wCI = gen.get_gateset_spam_table(gateset, ci)
        gen.get_gateset_spam_table(gateset, None)
        gen.get_gateset_gates_table(gateset_tp, ci_TP)  #test zero-padding
        gen.get_unitary_gateset_gates_table(std.gs_target,
                                            ci_tgt)  #unitary gates w/CIs
        gen.get_unitary_gateset_gates_table(target_tp,
                                            ci_TP_tgt)  #unitary gates w/CIs
        gen.get_gateset_closest_unitary_table(gateset_2q,
                                              None)  #test higher-dim gateset
        gen.get_gateset_closest_unitary_table(gateset,
                                              ci)  #test with CIs (long...)
        gen.get_gateset_rotn_axis_table(
            std.gs_target, None)  #try to get "--"s and "X"s to display
        gen.get_chi2_progress_table([0], [gateset_tp], [
            [('Gx', )],
        ], ds)  #TP case
        gen.get_chi2_confidence_region(gateset_tp, ds, 95)  #TP case

        gen.get_gatestring_multi_table(
            [[('Gx', ), ('Gz', )], [('Gy', )]], ["list1", "list2"],
            commonTitle=None)  #commonTitle == None case w/diff length lists

        with self.assertRaises(ValueError):
            gen.get_unitary_gateset_gates_table(std.gs_target,
                                                ci)  #gateset-CI mismatch
        with self.assertRaises(ValueError):
            gen.get_gateset_spam_parameters_table(std.gs_target,
                                                  ci)  #gateset-CI mismatch

        #Test ReportTable object
        rowLabels = tab.keys()
        row1Data = tab[rowLabels[0]]
        colLabels = row1Data.keys()

        self.assertTrue(rowLabels, tab.row_names)
        self.assertTrue(colLabels, tab.col_names)
        self.assertTrue(len(rowLabels), tab.num_rows)
        self.assertTrue(len(colLabels), tab.num_cols)

        el00 = tab[rowLabels[0]][colLabels[0]]
        self.assertTrue(rowLabels[0] in tab)
        self.assertTrue(tab.has_key(rowLabels[0]))

        table_len = len(tab)
        self.assertEqual(table_len, tab.num_rows)

        table_as_str = str(tab)
        table_wCI_as_str = str(tab_wCI)
        row1a = tab.row(key=rowLabels[0])
        col1a = tab.col(key=colLabels[0])
        row1b = tab.row(index=0)
        col1b = tab.col(index=0)
        self.assertEqual(row1a, row1b)
        self.assertEqual(col1a, col1b)

        with self.assertRaises(KeyError):
            tab['foobar']
        with self.assertRaises(KeyError):
            tab.row(key='foobar')  #invalid key
        with self.assertRaises(ValueError):
            tab.row(index=100000)  #out of bounds
        with self.assertRaises(ValueError):
            tab.row()  #must specify key or index
        with self.assertRaises(ValueError):
            tab.row(key='foobar', index=1)  #cannot specify key and index
        with self.assertRaises(KeyError):
            tab.col(key='foobar')  #invalid key
        with self.assertRaises(ValueError):
            tab.col(index=100000)  #out of bounds
        with self.assertRaises(ValueError):
            tab.col()  #must specify key or index
        with self.assertRaises(ValueError):
            tab.col(key='foobar', index=1)  #cannot specify key and index

        with self.assertRaises(ValueError):
            tab.render(fmt="foobar")  #invalid format

        #LogL case tests
        gen.get_logl_progress_table([0], [gateset_tp], [
            [('Gx', )],
        ], ds)  # logL case
        gen.get_logl_progress_table([0], [gateset], [
            [('Gx', )],
        ], ds)  # logL case

        gen.get_logl_confidence_region(gateset_tp,
                                       ds,
                                       95,
                                       gatestring_list=None,
                                       probClipInterval=(-1e6, 1e6),
                                       minProbClip=1e-4,
                                       radius=1e-4,
                                       hessianProjection="std")
        gen.get_logl_confidence_region(gateset,
                                       ds,
                                       95,
                                       gatestring_list=None,
                                       probClipInterval=(-1e6, 1e6),
                                       minProbClip=1e-4,
                                       radius=1e-4,
                                       hessianProjection="std")
Ejemplo n.º 17
0
    def test_hessian_projection(self):

        chi2, chi2Grad, chi2Hessian = pygsti.chi2(self.model,
                                                  self.ds,
                                                  returnGradient=True,
                                                  returnHessian=True)

        proj_non_gauge = self.model.get_nongauge_projector()
        projectedHessian = np.dot(proj_non_gauge,
                                  np.dot(chi2Hessian, proj_non_gauge))

        print(self.model.num_params())
        print(proj_non_gauge.shape)
        self.assertEqual(projectedHessian.shape, (60, 60))
        #print("Evals = ")
        #print("\n".join( [ "%d: %g" % (i,ev) for i,ev in enumerate(np.linalg.eigvals(projectedHessian))] ))
        self.assertEqual(np.linalg.matrix_rank(proj_non_gauge), 44)
        self.assertEqual(np.linalg.matrix_rank(projectedHessian), 44)

        eigvals = np.sort(abs(np.linalg.eigvals(projectedHessian)))

        print("eigvals = ", eigvals)

        eigvals_chk = np.array([
            1.22771144e-10, 5.09703519e-10, 7.77414421e-10, 7.77414421e-10,
            9.54941949e-10, 9.54941949e-10, 1.31838597e-09, 1.68301591e-09,
            1.68301591e-09, 1.90734690e-09, 1.90734690e-09, 2.49398698e-09,
            2.63214649e-09, 5.55011910e-09, 8.25271609e-09, 1.79101190e-08,
            9.23263305e+05, 1.05796436e+06, 1.16544156e+06, 1.39483644e+06,
            1.83988792e+06, 2.10385396e+06, 2.37875879e+06, 2.47138866e+06,
            2.64517713e+06, 2.68781067e+06, 2.82400957e+06, 2.86645483e+06,
            2.94682035e+06, 2.96132874e+06, 3.08410148e+06, 3.29632639e+06,
            3.66669038e+06, 3.76286040e+06, 3.81791306e+06, 3.86566785e+06,
            3.88861934e+06, 4.72670353e+06, 4.96458456e+06, 6.53314879e+06,
            1.01442686e+07, 1.11366689e+07, 1.26150705e+07, 1.30030291e+07,
            1.36655922e+07, 1.49308924e+07, 1.58259068e+07, 1.81000865e+07,
            2.09105990e+07, 2.17439110e+07, 2.46822193e+07, 2.64512967e+07,
            2.72379830e+07, 3.34861817e+07, 3.44988014e+07, 3.68957880e+07,
            5.08236925e+07, 9.43118724e+07, 1.36087264e+08, 6.30301385e+08
        ])

        #OLD
        #[6.11142452e-11, 5.84760068e-10, 6.73066231e-10, 6.89070172e-10,
        # 6.89070172e-10, 1.16844369e-09, 1.99649746e-09, 1.99649746e-09,
        # 2.41697718e-09, 2.41697718e-09, 2.80832759e-09, 4.29148412e-09,
        # 4.29148412e-09, 6.59655396e-09, 6.59655396e-09, 6.76915973e-09,
        # 9.23087831e+05, 1.05783101e+06, 1.16457705e+06, 1.39492929e+06,
        # 1.84015484e+06, 2.10613947e+06, 2.37963392e+06, 2.47192689e+06,
        # 2.64566761e+06, 2.68722871e+06, 2.82383377e+06, 2.86584033e+06,
        # 2.94590436e+06, 2.96180212e+06, 3.08322015e+06, 3.29389050e+06,
        # 3.66581786e+06, 3.76266448e+06, 3.81921738e+06, 3.86624688e+06,
        # 3.89045873e+06, 4.72831630e+06, 4.96416855e+06, 6.53286834e+06,
        # 1.01424911e+07, 1.11347312e+07, 1.26152967e+07, 1.30081040e+07,
        # 1.36647082e+07, 1.49293583e+07, 1.58234599e+07, 1.80999182e+07,
        # 2.09155048e+07, 2.17444267e+07, 2.46870311e+07, 2.64427393e+07,
        # 2.72410297e+07, 3.34988002e+07, 3.45005948e+07, 3.69040745e+07,
        # 5.08647137e+07, 9.43153151e+07, 1.36088308e+08, 6.30304807e+08] )

        TOL = 1e-7
        for val, chk in zip(eigvals, eigvals_chk):
            if abs(val) > TOL or abs(chk) > TOL:
                self.assertAlmostEqual(abs(val - chk) / (abs(chk) + TOL),
                                       0.0,
                                       places=3)
Ejemplo n.º 18
0
    def test_hessian_projection(self):

        chi2, chi2Grad, chi2Hessian = pygsti.chi2(self.ds, self.gateset, returnGradient=True, returnHessian=True)

        proj_non_gauge = self.gateset.get_nongauge_projector()
        projectedHessian = np.dot(proj_non_gauge, np.dot(chi2Hessian, proj_non_gauge))

        self.assertEqual(projectedHessian.shape, (56, 56))
        self.assertEqual(np.linalg.matrix_rank(proj_non_gauge), 40)
        self.assertEqual(np.linalg.matrix_rank(projectedHessian), 40)

        eigvals = np.sort(abs(np.linalg.eigvals(projectedHessian)))

        eigvals_chk = np.array(
            [
                2.36932621e-11,
                4.57739349e-11,
                8.49888013e-11,
                8.49888013e-11,
                1.22859895e-10,
                1.22859895e-10,
                1.38705957e-10,
                1.38705957e-10,
                3.75441328e-10,
                6.46644807e-10,
                6.46644807e-10,
                7.06181642e-10,
                7.06181642e-10,
                7.65472749e-10,
                1.62672899e-09,
                1.62672899e-09,
                9.23280752e04,
                9.88622140e04,
                1.24577730e05,
                1.40500652e05,
                1.88461602e05,
                1.98466608e05,
                2.07084497e05,
                2.27489018e05,
                2.33403285e05,
                2.52573024e05,
                2.82350782e05,
                3.12087185e05,
                3.21855420e05,
                3.31659734e05,
                3.52649174e05,
                3.60682071e05,
                3.90777833e05,
                4.59913853e05,
                5.02652879e05,
                5.59311926e05,
                5.78891070e05,
                6.82325323e05,
                7.57318263e05,
                8.16739390e05,
                1.06466062e06,
                1.20075694e06,
                1.37368639e06,
                1.58356629e06,
                1.68898356e06,
                2.12277359e06,
                3.30650801e06,
                3.75869331e06,
                4.00195245e06,
                4.42427797e06,
                5.06956256e06,
                7.31166332e06,
                9.19432790e06,
                9.99944236e06,
                1.31027722e07,
                5.80310818e07,
            ]
        )

        TOL = 1e-7
        for val, chk in zip(eigvals, eigvals_chk):
            if abs(val) > TOL or abs(chk) > TOL:
                self.assertAlmostEqual(abs(val - chk) / (abs(chk) + TOL), 0.0, places=3)
Ejemplo n.º 19
0
    def test_model_selection(self):

        ds = self.ds
        #pygsti.construction.generate_fake_data(self.datagen_gateset, self.lsgstStrings[-1],
        #                                            nSamples=1000,sampleError='binomial', seed=100)

        gs_lgst4 = pygsti.do_lgst(ds,
                                  self.specs,
                                  self.gateset,
                                  svdTruncateTo=4,
                                  verbosity=0)
        gs_lgst6 = pygsti.do_lgst(ds,
                                  self.specs,
                                  self.gateset,
                                  svdTruncateTo=6,
                                  verbosity=0)
        sys.stdout.flush()

        self.runSilent(pygsti.do_lgst,
                       ds,
                       self.specs,
                       self.gateset,
                       svdTruncateTo=6,
                       verbosity=4)  # test verbose prints

        chiSq4 = pygsti.chi2(ds,
                             gs_lgst4,
                             self.lgstStrings,
                             minProbClipForWeighting=1e-4)
        chiSq6 = pygsti.chi2(ds,
                             gs_lgst6,
                             self.lgstStrings,
                             minProbClipForWeighting=1e-4)

        print("LGST dim=4 chiSq = ", chiSq4)
        print("LGST dim=6 chiSq = ", chiSq6)
        #self.assertAlmostEqual(chiSq4, 174.061524953) #429.271983052)
        #self.assertAlmostEqual(chiSq6, 267012993.861, places=1) #1337.74222467) #Why is this so large??? -- DEBUG later

        # Least squares GST with model selection
        gs_lsgst = self.runSilent(
            pygsti.do_iterative_mc2gst_with_model_selection,
            ds,
            gs_lgst4,
            1,
            self.lsgstStrings[0:3],
            verbosity=10,
            minProbClipForWeighting=1e-3,
            probClipInterval=(-1e5, 1e5))

        # Run again with other parameters
        tuple_strings = [
            list(map(tuple, gsList)) for gsList in self.lsgstStrings[0:3]
        ]  #to test tuple argument
        errorVecs, gs_lsgst_wts = self.runSilent(
            pygsti.do_iterative_mc2gst_with_model_selection,
            ds,
            gs_lgst4,
            1,
            tuple_strings,
            verbosity=10,
            minProbClipForWeighting=1e-3,
            probClipInterval=(-1e5, 1e5),
            gatestringWeightsDict={('Gx', ): 2.0},
            returnAll=True,
            returnErrorVec=True)

        # Do non-iterative to cover GateString->tuple conversion
        gs_non_iterative = self.runSilent(
            pygsti.do_mc2gst_with_model_selection,
            ds,
            gs_lgst4,
            1,
            self.lsgstStrings[0],
            verbosity=10,
            probClipInterval=(-1e5, 1e5))

        # RUN BELOW LINES TO SEED SAVED GATESET FILES
        #pygsti.io.write_gateset(gs_lsgst,compare_files + "/lsgstMS.gateset", "Saved LSGST Gateset with model selection")

        gs_lsgst_compare = pygsti.io.load_gateset(compare_files +
                                                  "/lsgstMS.gateset")
        gs_lsgst_go = pygsti.optimize_gauge(gs_lsgst,
                                            'target',
                                            targetGateset=gs_lsgst_compare,
                                            spamWeight=1.0)
        self.assertAlmostEqual(gs_lsgst_go.frobeniusdist(gs_lsgst_compare),
                               0,
                               places=5)
Ejemplo n.º 20
0
    def test_confidenceRegion(self):

        chi2, chi2Hessian = pygsti.chi2(self.ds, self.gateset,
                                        returnHessian=True)
        ci_std = pygsti.obj.ConfidenceRegion(self.gateset, chi2Hessian, 95.0,
                                             hessianProjection="std")
        ci_noproj = pygsti.obj.ConfidenceRegion(self.gateset, chi2Hessian, 95.0,
                                             hessianProjection="none")
        ci_opt = pygsti.obj.ConfidenceRegion(self.gateset, chi2Hessian, 95.0,
                                             hessianProjection="optimal gate CIs",
                                             tol=0.1) #very low tol so doesn't take long
        
        with self.assertRaises(ValueError):
            pygsti.obj.ConfidenceRegion(self.gateset, chi2Hessian, 95.0,
                                             hessianProjection="FooBar") #bad hessianProjection
            
        self.assertWarns(pygsti.obj.ConfidenceRegion, self.gateset,
                         chi2Hessian, 0.95, hessianProjection="none") # percentage < 1.0

        ar_of_intervals_Gx = ci_std.get_profile_likelihood_confidence_intervals("Gx")
        ar_of_intervals_rho0 = ci_std.get_profile_likelihood_confidence_intervals("rho0")
        ar_of_intervals_E0 = ci_std.get_profile_likelihood_confidence_intervals("E0")
        ar_of_intervals = ci_std.get_profile_likelihood_confidence_intervals()

        def fnOfGate_float(mx):
            return float(mx[0,0])
        def fnOfGate_0D(mx):
            return np.array( float(mx[0,0]) )
        def fnOfGate_1D(mx):
            return mx[0,:]
        def fnOfGate_2D(mx):
            return mx[:,:]
        def fnOfGate_3D(mx):
            return np.zeros( (2,2,2), 'd') #just to test for error


        df = ci_std.get_gate_fn_confidence_interval(fnOfGate_float, 'Gx', verbosity=0)
        df = ci_std.get_gate_fn_confidence_interval(fnOfGate_0D, 'Gx', verbosity=0)
        df = ci_std.get_gate_fn_confidence_interval(fnOfGate_1D, 'Gx', verbosity=0)
        df = ci_std.get_gate_fn_confidence_interval(fnOfGate_2D, 'Gx', verbosity=0)
        df, f0 = self.runSilent(ci_std.get_gate_fn_confidence_interval,
                                fnOfGate_float, 'Gx', returnFnVal=True, verbosity=4)

        with self.assertRaises(ValueError):
            ci_std.get_gate_fn_confidence_interval(fnOfGate_3D, 'Gx', verbosity=0)


        def fnOfSpam_float(rhoVecs, EVecs):
            return float( np.dot( rhoVecs[0].T, EVecs[0] ) )
        def fnOfSpam_0D(rhoVecs, EVecs):
            return np.array( float( np.dot( rhoVecs[0].T, EVecs[0] ) ) )
        def fnOfSpam_1D(rhoVecs, EVecs):
            return np.array( [ np.dot( rhoVecs[0].T, EVecs[0] ), 0] )
        def fnOfSpam_2D(rhoVecs, EVecs):
            return np.array( [[ np.dot( rhoVecs[0].T, EVecs[0] ), 0],[0,0]] )
        def fnOfSpam_3D(rhoVecs, EVecs):
            return np.zeros( (2,2,2), 'd') #just to test for error

        df = ci_std.get_spam_fn_confidence_interval(fnOfSpam_float, verbosity=0)
        df = ci_std.get_spam_fn_confidence_interval(fnOfSpam_0D, verbosity=0)
        df = ci_std.get_spam_fn_confidence_interval(fnOfSpam_1D, verbosity=0)
        df = ci_std.get_spam_fn_confidence_interval(fnOfSpam_2D, verbosity=0)
        df, f0 = self.runSilent(ci_std.get_spam_fn_confidence_interval,
                                fnOfSpam_float, returnFnVal=True, verbosity=4)

        with self.assertRaises(ValueError):
            ci_std.get_spam_fn_confidence_interval(fnOfSpam_3D, verbosity=0)
Ejemplo n.º 21
0
 def test_total_chi2(self):
     chi2 = pygsti.chi2( self.ds, self.lsgst_gateset )
     self.assertAlmostEqual(chi2, 729.182015795)