Esempio n. 1
0
    def test_labels_with_time_and_arguments(self):

        #Label with time and args
        l = L('Gx',(0,1),time=1.2, args=('1.4','1.7'))
        self.assertEqual(l.time, 1.2)
        self.assertEqual(l.args,('1.4','1.7'))
        self.assertEqual(tuple(l), ('Gx', 4, '1.4', '1.7', 0, 1) )

        l2 = L(('Gx',';1.4',';1.7',0,1,'!1.25'))
        self.assertEqual(tuple(l2), ('Gx', 4, '1.4', '1.7', 0, 1) )

        l3 = L(('Gx',';','1.4',';','1.7',0,1,'!',1.3))
        self.assertEqual(tuple(l3), ('Gx', 4, '1.4', '1.7', 0, 1) )

        self.assertTrue(l == l2 == l3)

        #Time without args
        l = L('Gx',(0,1),time=1.2)
        self.assertEqual(l.time, 1.2)
        self.assertEqual(l.args,())
        self.assertEqual(tuple(l), ('Gx', 0, 1) )

        #Args without time
        l = L('Gx',(0,1),args=('1.4',))
        self.assertEqual(l.time, 0)
        self.assertEqual(l.args,('1.4',))
        self.assertEqual(tuple(l), ('Gx', 3, '1.4', 0, 1) )
Esempio n. 2
0
 def test_only_nonzero_time_is_printed(self):
     l = L('GrotX',(0,1),args=('1.4',))
     self.assertEqual(str(l), "GrotX;1.4:0:1")  # make sure we don't print time when it's not given (i.e. zero)
     self.assertEqual(l.time, 0.0) # BUT l.time is still 0, not None
     l = L('GrotX',(0,1),args=('1.4',),time=0.2)
     self.assertEqual(str(l), "GrotX;1.4:0:1!0.2")  # make sure we do print time when it's nonzero
     self.assertEqual(l.time, 0.2)
Esempio n. 3
0
    def test_layerlizzard(self):
        #Test this here b/c auto-gators are associated with parallel operation labels
        availability = {'Gcnot': [(0,1)]}
        mdl = pc.build_cloudnoise_model_from_hops_and_weights(
            2, ['Gx','Gy','Gcnot'], {}, None, availability,
            None, "line", maxIdleWeight=1, maxhops=1,
            extraWeight1Hops=0, extraGateWeight=1, sparse=True,
            sim_type="map", parameterization="H+S")
        
        # mdl[('Gx',0)].factorops  # Composed([fullTargetOp,fullIdleErr,fullLocalErr])
        self.assertEqual( set(mdl.get_primitive_op_labels()), set([L('Gx',0), L('Gy',0), L('Gx',1), L('Gy',1), L('Gcnot',(0,1))]))

        #But we can *compute* with circuits containing parallel labels...
        parallelLbl = L( [('Gx',0),('Gy',1)] )

        with self.assertRaises(KeyError):
            mdl.operation_blks[parallelLbl]
        
        opstr = pygsti.obj.Circuit( (parallelLbl,) )
        probs = mdl.probs(opstr)
        print(probs)

        expected = { ('00',): 0.25, ('01',): 0.25, ('10',): 0.25, ('11',): 0.25 }
        for k,v in probs.items():
            self.assertAlmostEqual(v, expected[k])
Esempio n. 4
0
 def test_prs(self):
     self.fwdsim.prs(L('rho0'), [L('Mdefault_0')],
                     Ls('Gx', 'Gx'),
                     clipTo=(-1, 1))
     self.fwdsim.prs(L('rho0'), [L('Mdefault_0')],
                     Ls('Gx', 'Gx'),
                     clipTo=(-1, 1),
                     bUseScaling=True)
Esempio n. 5
0
    def test_python_string_conversion(self):
        mdl = pygsti.obj.Circuit(None, stringrep="Gx^3Gy^2GxGz")

        op_labels = (L('Gx'), L('Gy'), L('Gz'))
        pystr = mdl.to_pythonstr(op_labels)
        self.assertEqual(pystr, "AAABBAC")

        gs2_tup = pygsti.obj.Circuit.from_pythonstr(pystr, op_labels)
        self.assertEqual(gs2_tup, tuple(mdl))
Esempio n. 6
0
 def test_circuit_init(self):
     #Check that parallel gate labels get converted to circuits properly
     gstr = pygsti.obj.GateString(((('Gx', 0), ('Gy', 1)), ('Gcnot', 0, 1)))
     c = pygsti.obj.Circuit(gatestring=gstr, num_lines=2)
     print(c)
     self.assertEqual(c.line_items, [[L(
         ('Gx', 0)), L(
             ('Gcnot', 0, 1))], [L(
                 ('Gy', 1)), L(('Gcnot', 0, 1))]])
Esempio n. 7
0
    def test_python_string_conversion(self):
        gs = pygsti.obj.GateString(None, stringRepresentation="Gx^3Gy^2GxGz")

        gate_labels = (L('Gx'), L('Gy'), L('Gz'))
        pystr = gs.to_pythonstr(gate_labels)
        self.assertEqual(pystr, "AAABBAC")

        gs2_tup = pygsti.obj.GateString.from_pythonstr(pystr, gate_labels)
        self.assertEqual(gs2_tup, tuple(gs))
Esempio n. 8
0
    def test_label_time_is_not_hashed(self):
        #Ensure that time is not considered in the equality (or hashing) of labels - it's a
        # tag-along "comment" that does not change the real value of a Label.
        l1 = L('Gx',time=1.2)
        l2 = L('Gx')
        self.assertEqual(l1,l2)
        self.assertTrue(l1.time != l2.time)

        l1 = L('Gx',(0,),time=1.2)
        l2 = L('Gx',(0,))
        self.assertEqual(l1,l2)
        self.assertTrue(l1.time != l2.time)
Esempio n. 9
0
    def test_model_with_lgst_circuit_estimates(self):
        model = directx.model_with_lgst_circuit_estimates(self.strs,
                                                          self.ds,
                                                          self.prepStrs,
                                                          self.effectStrs,
                                                          self.tgt,
                                                          svdTruncateTo=4,
                                                          verbosity=10)
        # TODO assert correctness

        model = directx.model_with_lgst_circuit_estimates(
            self.strs,
            self.ds,
            self.prepStrs,
            self.effectStrs,
            self.tgt,
            includeTargetOps=False,
            svdTruncateTo=4,
            verbosity=10)
        # TODO assert correctness

        circuit_labels = [L('G0'), L('G1'), L('G2'), L('G3'), L('G4'), L('G5')]
        # circuit_labels = [L('G0'), L('G1'), L('G2'), L('G3')]
        model = directx.model_with_lgst_circuit_estimates(
            self.strs,
            self.ds,
            self.prepStrs,
            self.effectStrs,
            self.tgt,
            circuitLabels=circuit_labels,
            includeTargetOps=False,
            svdTruncateTo=4,
            verbosity=10)
        self.assertEqual(set(model.operations.keys()), set(circuit_labels))
Esempio n. 10
0
    def testLabels(self):
        labels = []
        labels.append(pygsti.obj.Label('Gx', 0))  # a LabelTup
        labels.append(pygsti.obj.Label('Gx', (0, 1)))  # a LabelTup
        labels.append(pygsti.obj.Label(('Gx', 0, 1)))  # a LabelTup
        labels.append(pygsti.obj.Label('Gx'))  # a LabelStr
        labels.append(pygsti.obj.Label('Gx', None))  #still a LabelStr
        labels.append(pygsti.obj.Label([('Gx', 0), ('Gy', 0)
                                        ]))  # a LabelTupTup of LabelTup objs
        labels.append(pygsti.obj.Label(
            (('Gx', None), ('Gy', None))))  # a LabelTupTup of LabelStr objs
        labels.append(pygsti.obj.Label([
            ('Gx', 0)
        ]))  # just a LabelTup b/c only one component
        labels.append(pygsti.obj.Label([L('Gx'), L('Gy')
                                        ]))  # a LabelTupTup of LabelStrs
        labels.append(pygsti.obj.Label(L('Gx')))  # Init from another label

        for l in labels:
            native = l.tonative()
            print(l, " (", type(l), "): native =", native)
            if isinstance(l, pygsti.baseobjs.label.LabelTupTup):
                print(
                    "  comps: ", ", ".join(
                        ["%s (%s)" % (c, str(type(c))) for c in l.components]))

            from_native = pygsti.obj.Label(native)
            self.assertEqual(from_native, l)

            s = pickle.dumps(l)
            l2 = pickle.loads(s)
            self.assertEqual(type(l), type(l2))

            j = jsoncodec.encode_obj(l, False)
            #print("Json: ",j)
            l3 = jsoncodec.decode_obj(j, False)
            #print("Unjsoned ", l3, " a ",type(l3))
            self.assertEqual(type(l), type(l3))
Esempio n. 11
0
    def test_alias_manips(self):
        orig_list = pygsti.construction.circuit_list([('Gx', 'Gx'),
                                                      ('Gx', 'Gy'),
                                                      ('Gx', 'Gx', 'Gx'),
                                                      ('Gy', 'Gy'), ('Gi', )])

        list0 = pygsti.construction.translate_circuit_list(orig_list, None)
        self.assertEqual(list0, orig_list)

        list1 = pygsti.construction.translate_circuit_list(
            orig_list, {
                L('Gx'): (L('Gx2'), ),
                L('Gy'): (L('Gy'), )
            })
        list2 = pygsti.construction.translate_circuit_list(
            orig_list, {L('Gi'): (L('Gx'), L('Gx'), L('Gx'), L('Gx'))})
        print(list1)

        expected_list1 = pygsti.construction.circuit_list([('Gx2', 'Gx2'),
                                                           ('Gx2', 'Gy'),
                                                           ('Gx2',
                                                            'Gx2', 'Gx2'),
                                                           ('Gy', 'Gy'),
                                                           ('Gi', )])
        expected_list2 = pygsti.construction.circuit_list([('Gx', 'Gx'),
                                                           ('Gx', 'Gy'),
                                                           ('Gx', 'Gx', 'Gx'),
                                                           ('Gy', 'Gy'),
                                                           ('Gx', 'Gx', 'Gx',
                                                            'Gx')])

        self.assertEqual(list1, expected_list1)
        self.assertEqual(list2, expected_list2)

        aliasDict1 = {'A': ('B', 'B')}
        aliasDict2 = {'B': ('C', 'C')}
        aliasDict3 = pygsti.construction.compose_alias_dicts(
            aliasDict1, aliasDict2)
        self.assertEqual(aliasDict3, {'A': ('C', 'C', 'C', 'C')})
Esempio n. 12
0
    def test_autogator(self):
        #Test this here b/c auto-gators are associated with parallel gate labels
        gs = pc.build_nqnoise_gateset(2,
                                      "line", [(0, 1)],
                                      maxIdleWeight=2,
                                      maxhops=1,
                                      extraWeight1Hops=0,
                                      extraGateWeight=1,
                                      verbosity=1,
                                      sim_type="map",
                                      parameterization="H+S",
                                      sparse=True)

        # gs[('Gx',0)].factorgates  # Composed([fullTargetOp,fullIdleErr,fullLocalErr])
        self.assertEqual(
            set(gs.gates.keys()),
            set([
                L('Gi'),
                L('Gx', 0),
                L('Gy', 0),
                L('Gx', 1),
                L('Gy', 1),
                L('Gcnot', (0, 1))
            ]))

        #But we can *compute* with gatestrings containing parallel labels...
        parallelLbl = L([('Gx', 0), ('Gy', 1)])

        with self.assertRaises(KeyError):
            gs.gates[parallelLbl]

        gstr = pygsti.obj.GateString((parallelLbl, ))
        probs = gs.probs(gstr)
        print(probs)

        expected = {
            ('00', ): 0.25,
            ('01', ): 0.25,
            ('10', ): 0.25,
            ('11', ): 0.25
        }
        for k, v in probs.items():
            self.assertAlmostEqual(v, expected[k])
Esempio n. 13
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(CalcMethods1QTestCase, cls).setUpClass()

        #Change to test_packages directory (since setUp hasn't been called yet...)
        origDir = os.getcwd()
        os.chdir(os.path.abspath(os.path.dirname(__file__)))
        os.chdir('..')  # The test_packages directory

        #Standard GST dataset
        cls.maxLengths = [1, 2, 4]
        cls.mdl_datagen = std.target_model().depolarize(op_noise=0.1,
                                                        spam_noise=0.001)
        cls.listOfExperiments = pygsti.construction.make_lsgst_experiment_list(
            std.target_model(), std.prepStrs, std.effectStrs, std.germs,
            cls.maxLengths)

        #RUN BELOW FOR DATAGEN (UNCOMMENT to regenerate) (SAVE)
        if os.environ.get(
                'PYGSTI_REGEN_REF_FILES',
                'no').lower() in ("yes", "1", "true",
                                  "v2"):  # "v2" to only gen version-dep files
            ds = pygsti.construction.generate_fake_data(
                cls.mdl_datagen,
                cls.listOfExperiments,
                nSamples=1000,
                sampleError="multinomial",
                seed=1234)
            ds.save(compare_files +
                    "/calcMethods1Q.dataset%s" % cls.versionsuffix)

        #DEBUG TEST- was to make sure data files have same info -- seemed ultimately unnecessary
        #ds_swp = pygsti.objects.DataSet(fileToLoadFrom=compare_files + "/calcMethods1Q.datasetv3") # run in Python3
        #pygsti.io.write_dataset(temp_files + "/dataset.3to2.txt", ds_swp) # run in Python3
        #ds_swp = pygsti.io.load_dataset(temp_files + "/dataset.3to2.txt") # run in Python2
        #ds_swp.save(compare_files + "/calcMethods1Q.dataset") # run in Python2
        #assert(False),"STOP"

        cls.ds = pygsti.objects.DataSet(
            fileToLoadFrom=compare_files +
            "/calcMethods1Q.dataset%s" % cls.versionsuffix)

        #Reduced model GST dataset
        cls.nQubits = 1  # can't just change this now - see opLabels below
        cls.mdl_redmod_datagen = build_XYCNOT_cloudnoise_model(
            cls.nQubits,
            geometry="line",
            maxIdleWeight=1,
            maxhops=1,
            extraWeight1Hops=0,
            extraGateWeight=1,
            sparse=False,
            sim_type="matrix",
            verbosity=1,
            roughNoise=(1234, 0.01))

        #Create a reduced set of fiducials and germs
        opLabels = [('Gx', 0), ('Gy', 0)]  # 1Q gate labels
        fids1Q = std1Q_XY.fiducials[0:2]  # for speed
        cls.redmod_fiducials = []
        for i in range(cls.nQubits):
            cls.redmod_fiducials.extend(
                pygsti.construction.manipulate_circuit_list(
                    fids1Q, [((L('Gx'), ), (L('Gx', i), )),
                             ((L('Gy'), ), (L('Gy', i), ))]))
        #print(redmod_fiducials, "Fiducials")

        cls.redmod_germs = pygsti.construction.circuit_list([
            (gl, ) for gl in opLabels
        ])
        cls.redmod_maxLs = [1]
        expList = pygsti.construction.make_lsgst_experiment_list(
            opLabels, cls.redmod_fiducials, cls.redmod_fiducials,
            cls.redmod_germs, cls.redmod_maxLs)

        #RUN BELOW FOR DATAGEN (UNCOMMENT to regenerate) (SAVE)
        if os.environ.get(
                'PYGSTI_REGEN_REF_FILES',
                'no').lower() in ("yes", "1", "true",
                                  "v2"):  # "v2" to only gen version-dep files
            redmod_ds = pygsti.construction.generate_fake_data(
                cls.mdl_redmod_datagen, expList, 1000, "round", seed=1234)
            redmod_ds.save(compare_files + "/calcMethods1Q_redmod.dataset%s" %
                           cls.versionsuffix)

        cls.redmod_ds = pygsti.objects.DataSet(
            fileToLoadFrom=compare_files +
            "/calcMethods1Q_redmod.dataset%s" % cls.versionsuffix)

        #print(len(expList)," reduced model sequences")

        #Random starting points - little kick so we don't get hung up at start
        np.random.seed(1234)
        cls.rand_start18 = np.random.random(18) * 1e-6
        cls.rand_start25 = np.random.random(30) * 1e-6  # TODO: rename?
        cls.rand_start36 = np.random.random(30) * 1e-6  # TODO: rename?

        #Circuit Simulation circuits
        cls.csim_nQubits = 3
        cls.circuit1 = pygsti.obj.Circuit(('Gx', 'Gy'))
        # now Circuit adds qubit labels... pygsti.obj.Circuit(layer_labels=('Gx','Gy'), num_lines=1) # 1-qubit circuit
        cls.circuit3 = pygsti.obj.Circuit(layer_labels=[('Gxpi', 0),
                                                        ('Gypi', 1),
                                                        ('Gcnot', 1, 2)],
                                          num_lines=3)  # 3-qubit circuit

        os.chdir(origDir)  # return to original directory
Esempio n. 14
0
 def test_hoperation(self):
     hg = self.fwdsim.hoperation(L('Gx'), flat=False)
     hgflat = self.fwdsim.hoperation(L('Gx'), flat=True)
Esempio n. 15
0
    def test_3Q(self):

        nQubits = 3
        print("Constructing Target Gate Set")
        gs_target = pygsti.construction.build_nqnoise_gateset(
            nQubits,
            geometry="line",
            maxIdleWeight=1,
            maxhops=1,
            extraWeight1Hops=0,
            extraGateWeight=1,
            sparse=True,
            sim_type="map",
            verbosity=1)
        #print("nElements test = ",gs_target.num_elements())
        #print("nParams test = ",gs_target.num_params())
        #print("nNonGaugeParams test = ",gs_target.num_nongauge_params())

        print("Constructing Datagen Gate Set")
        gs_datagen = pygsti.construction.build_nqnoise_gateset(
            nQubits,
            geometry="line",
            maxIdleWeight=1,
            maxhops=1,
            extraWeight1Hops=0,
            extraGateWeight=1,
            sparse=True,
            verbosity=1,
            gateNoise=(1234, 0.1),
            prepNoise=(456, 0.01),
            povmNoise=(789, 0.01),
            sim_type="map")

        gs_test = gs_datagen
        print(
            "Constructed gateset with %d gates, dim=%d, and nParams=%d.  Norm(paramvec) = %g"
            % (len(gs_test.gates), gs_test.dim, gs_test.num_params(),
               np.linalg.norm(gs_test.to_vector())))

        gateLabels = list(gs_target.gates.keys())
        fids1Q = std1Q_XY.fiducials
        fiducials = []
        for i in range(nQubits):
            fiducials.extend(
                pygsti.construction.manipulate_gatestring_list(
                    fids1Q, [((L('Gx'), ), (L('Gx', i), )),
                             ((L('Gy'), ), (L('Gy', i), ))]))
        print(len(fiducials), "Fiducials")
        prep_fiducials = meas_fiducials = fiducials
        #TODO: add fiducials for 2Q pairs (edges on graph)

        germs = pygsti.construction.gatestring_list([(gl, )
                                                     for gl in gateLabels])
        maxLs = [1]
        expList = pygsti.construction.make_lsgst_experiment_list(
            gs_datagen, prep_fiducials, meas_fiducials, germs, maxLs)
        self.assertTrue(() in expList)

        ds = pygsti.construction.generate_fake_data(gs_datagen,
                                                    expList,
                                                    1000,
                                                    "multinomial",
                                                    seed=1234)
        print("Created Dataset with %d strings" % len(ds))

        logL = pygsti.tools.logl(gs_datagen, ds, expList)
        max_logL = pygsti.tools.logl_max(gs_datagen, ds, expList)
        twoDeltaLogL = 2 * (max_logL - logL)
        chi2 = pygsti.tools.chi2(gs_datagen, ds, expList)

        dof = ds.get_degrees_of_freedom()
        nParams = gs_datagen.num_params()
        print("Datagen 2DeltaLogL = 2(%g-%g) = %g" %
              (logL, max_logL, twoDeltaLogL))
        print("Datagen chi2 = ", chi2)
        print("Datagen expected DOF = ", dof)
        print("nParams = ", nParams)
        print("Expected 2DeltaLogL or chi2 ~= %g-%g =%g" %
              (dof, nParams, dof - nParams))
        #print("EXIT"); exit()
        return

        results = pygsti.do_long_sequence_gst(
            ds,
            gs_target,
            prep_fiducials,
            meas_fiducials,
            germs,
            maxLs,
            verbosity=5,
            advancedOptions={
                'maxIterations': 2
            })  #keep this short; don't care if it doesn't converge.
        print("DONE!")
Esempio n. 16
0
 def test_circuit_init(self):
     #Check that parallel operation labels get converted to circuits properly
     opstr = pygsti.obj.Circuit( ((('Gx',0),('Gy',1)),('Gcnot',0,1)) )
     c = pygsti.obj.Circuit(layer_labels=opstr, num_lines=2)
     print(c._labels)
     self.assertEqual(c._labels, ( L( (('Gx',0),('Gy',1)) ), L('Gcnot',(0,1)) ))
Esempio n. 17
0
    def test_direct_core(self):
        mdl = directx.model_with_lgst_circuit_estimates(self.strs,
                                                        self.ds,
                                                        self.prepStrs,
                                                        self.effectStrs,
                                                        self.tgt,
                                                        includeTargetOps=True,
                                                        circuitLabels=None,
                                                        svdTruncateTo=4,
                                                        verbosity=10)

        mdl = directx.model_with_lgst_circuit_estimates(self.strs,
                                                        self.ds,
                                                        self.prepStrs,
                                                        self.effectStrs,
                                                        self.tgt,
                                                        includeTargetOps=False,
                                                        circuitLabels=[
                                                            L('G0'),
                                                            L('G1'),
                                                            L('G2'),
                                                            L('G3'),
                                                            L('G4'),
                                                            L('G5')
                                                        ],
                                                        svdTruncateTo=4,
                                                        verbosity=10)
        self.assertEqual(
            set(mdl.operations.keys()),
            set([L('G0'), L('G1'),
                 L('G2'), L('G3'),
                 L('G4'), L('G5')]))

        aliases = {'Gy2': ('Gy', )}
        mdl = directx.model_with_lgst_circuit_estimates(
            [pygsti.obj.Circuit(('Gy2', ))],
            self.ds,
            self.prepStrs,
            self.effectStrs,
            self.tgt,
            includeTargetOps=True,
            circuitLabels=None,
            svdTruncateTo=4,
            verbosity=10,
            opLabelAliases=aliases)
Esempio n. 18
0
    def test_MLGST(self):

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

        mdl_lgst = pygsti.do_lgst(ds, self.fiducials, self.fiducials, self.model, svdTruncateTo=4, verbosity=0)
        mdl_lgst_go = pygsti.gaugeopt_to_target(mdl_lgst,self.model, {'spam':1.0, 'gates': 1.0}, checkJac=True)
        mdl_clgst = pygsti.contract(mdl_lgst_go, "CPTP") 
        mdl_clgst = mdl_clgst.depolarize(op_noise=0.02, spam_noise=0.02) # just to avoid infinity objective funct & jacs below
        CM = pygsti.baseobjs.profiler._get_mem_usage()

        mdl_single_mlgst = pygsti.do_mlgst(ds, mdl_clgst, self.lsgstStrings[0], minProbClip=1e-4,
                                          probClipInterval=(-1e2,1e2), verbosity=0)

        #this test often gives an assetion error "finite Jacobian has inf norm!" on Travis CI Python 3 case
        try:
            mdl_single_mlgst_cpsp = pygsti.do_mlgst(ds, mdl_clgst, self.lsgstStrings[0], minProbClip=1e-4,
                                                  probClipInterval=(-1e2,1e2), cptp_penalty_factor=1.0,
                                                  spam_penalty_factor=1.0, verbosity=10) #uses both penalty factors w/verbosity > 0
        except ValueError: pass # ignore when assertions in customlm.py are disabled
        except AssertionError:
            pass # just ignore for now.  FUTURE: see what we can do in custom LM about scaling large jacobians...
        
        try:
            mdl_single_mlgst_cp = pygsti.do_mlgst(ds, mdl_clgst, self.lsgstStrings[0], minProbClip=1e-4,
                                                  probClipInterval=(-1e2,1e2), cptp_penalty_factor=1.0,
                                                  verbosity=10)
        except ValueError: pass # ignore when assertions in customlm.py are disabled
        except AssertionError:
            pass # just ignore for now.  FUTURE: see what we can do in custom LM about scaling large jacobians...
        
        try:
            mdl_single_mlgst_sp = pygsti.do_mlgst(ds, mdl_clgst, self.lsgstStrings[0], minProbClip=1e-4,
                                                  probClipInterval=(-1e2,1e2), spam_penalty_factor=1.0,
                                                  verbosity=10)
        except ValueError: pass # ignore when assertions in customlm.py are disabled
        except AssertionError:
            pass # just ignore for now.  FUTURE: see what we can do in custom LM about scaling large jacobians...
            

        mdl_mlegst = pygsti.do_iterative_mlgst(ds, mdl_clgst, self.lsgstStrings, verbosity=0,
                                               minProbClip=1e-4, probClipInterval=(-1e2,1e2),
                                               memLimit=CM + 1024**3)
        maxLogL, all_gs_mlegst_tups = pygsti.do_iterative_mlgst(
            ds, mdl_clgst, [ [mdl.tup for mdl in gsList] for gsList in self.lsgstStrings],
            minProbClip=1e-4, probClipInterval=(-1e2,1e2), returnAll=True, returnMaxLogL=True)

        mdl_mlegst_verb = self.runSilent(pygsti.do_iterative_mlgst, ds, mdl_clgst, self.lsgstStrings, verbosity=10,
                                             minProbClip=1e-4, probClipInterval=(-1e2,1e2),
                                             memLimit=CM + 1024**3)
        self.assertAlmostEqual(mdl_mlegst.frobeniusdist(mdl_mlegst_verb),0, places=5)
        self.assertAlmostEqual(mdl_mlegst.frobeniusdist(all_gs_mlegst_tups[-1]),0,places=5)


        #Run internal checks on less max-L values (so it doesn't take forever)
        mdl_mlegst_chk = pygsti.do_iterative_mlgst(ds, mdl_clgst, self.lsgstStrings[0:2], verbosity=0,
                                                 minProbClip=1e-4, probClipInterval=(-1e2,1e2),
                                                 check=True)

        #Other option variations - just make sure they run at this point
        mdl_mlegst_chk_opts = pygsti.do_iterative_mlgst(ds, mdl_clgst, self.lsgstStrings[0:2], verbosity=0,
                                                       minProbClip=1e-4, probClipInterval=(-1e2,1e2),
                                                       circuitSetLabels=["Set1","Set2"], useFreqWeightedChiSq=True,
                                                       circuitWeightsDict={ (L('Gx'),): 2.0 } )

        aliased_list = [ pygsti.obj.Circuit( [ (x if x != L("Gx") else L("GA1")) for x in mdl]) for mdl in self.lsgstStrings[0] ]
        mdl_withA1 = mdl_clgst.copy(); mdl_withA1.operations["GA1"] = mdl_clgst.operations["Gx"]
        del mdl_withA1.operations["Gx"] # otherwise mdl_withA1 will have Gx params that we have no knowledge of!
        mdl_mlegst_chk_opts2 = pygsti.do_mlgst(ds, mdl_withA1, aliased_list, minProbClip=1e-4,
                                              probClipInterval=(-1e2,1e2), verbosity=10,
                                              opLabelAliases={ L('GA1'): (L('Gx'),) })

        #Other option variations - just make sure they run at this point
        mdl_mlegst_chk_opts3 = pygsti.do_iterative_mlgst(ds, mdl_clgst, self.lsgstStrings[0:2], verbosity=0,
                                                       minProbClip=1e-4, probClipInterval=(-1e2,1e2),
                                                       circuitSetLabels=["Set1","Set2"], useFreqWeightedChiSq=True,
                                                        circuitWeightsDict={ (L('Gx'),): 2.0 }, alwaysPerformMLE=True )

        #Forcing function used by linear response error bars
        forcingfn_grad = np.ones((1,mdl_clgst.num_params()), 'd')
        mdl_lsgst_chk_opts3 = pygsti.algorithms.core._do_mlgst_base(
            ds, mdl_clgst, self.lsgstStrings[0], verbosity=0,
            minProbClip=1e-4, probClipInterval=(-1e2,1e2),
            forcefn_grad=forcingfn_grad)
        with self.assertRaises(NotImplementedError):
            # Non-poisson picture needs support for a non-leastsq solver (not impl yet)
            mdl_lsgst_chk_opts4 = pygsti.algorithms.core._do_mlgst_base(
                ds, mdl_clgst, self.lsgstStrings[0], verbosity=0, poissonPicture=False, 
                minProbClip=1e-4, probClipInterval=(-1e2,1e2),
                forcefn_grad=forcingfn_grad) # non-poisson picture

        #Check with small but ok memlimit -- not anymore since new mem estimation uses current memory, making this non-robust
        #self.runSilent(pygsti.do_mlgst, ds, mdl_clgst, self.lsgstStrings[0], minProbClip=1e-6,
        #                probClipInterval=(-1e2,1e2), verbosity=4, memLimit=curMem+8500000) #invoke memory control

        #non-Poisson picture - should use (-1,-1) model for consistency?
        with self.assertRaises(NotImplementedError):
            # Non-poisson picture needs support for a non-leastsq solver (not impl yet)
            pygsti.do_mlgst(ds, mdl_clgst, self.lsgstStrings[0], minProbClip=1e-4,
                            probClipInterval=(-1e2,1e2), verbosity=0, poissonPicture=False)
            try:
                pygsti.do_mlgst(ds, mdl_clgst, self.lsgstStrings[0], minProbClip=1e-1, # 1e-1 b/c get inf Jacobians...
                                probClipInterval=(-1e2,1e2), verbosity=0, poissonPicture=False,
                                spam_penalty_factor=1.0, cptp_penalty_factor=1.0)
            except ValueError: pass # ignore when assertions in customlm.py are disabled
            except AssertionError:
                pass # just ignore for now.  FUTURE: see what we can do in custom LM about scaling large jacobians...



        #Check errors:
        with self.assertRaises(MemoryError):
            pygsti.do_mlgst(ds, mdl_clgst, self.lsgstStrings[0], minProbClip=1e-4,
                            probClipInterval=(-1e2,1e2),verbosity=0, memLimit=1)


        # 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_mlegst,compare_files + "/mle_gst.model", "Saved MLE-GST Model")

        mdl_mle_compare = pygsti.io.load_model(compare_files + "/mle_gst.model")
        mdl_mlegst_go = pygsti.gaugeopt_to_target(mdl_mlegst, mdl_mle_compare, {'spam':1.0}, checkJac=True)

        self.assertAlmostEqual( mdl_mlegst_go.frobeniusdist(mdl_mle_compare), 0, places=4)
Esempio n. 19
0
    def test_MC2GST(self):

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

        mdl_lgst = pygsti.do_lgst(ds, self.fiducials, self.fiducials, self.model, svdTruncateTo=4, verbosity=0)
        mdl_lgst_go = pygsti.gaugeopt_to_target(mdl_lgst,self.model, {'spam':1.0, 'gates': 1.0}, checkJac=True)
        mdl_clgst = pygsti.contract(mdl_lgst_go, "CPTP")
        CM = pygsti.baseobjs.profiler._get_mem_usage()

        mdl_single_lsgst = pygsti.do_mc2gst(ds, mdl_clgst, self.lsgstStrings[0], minProbClipForWeighting=1e-4,
                                           probClipInterval=(-1e6,1e6), regularizeFactor=1e-3,
                                           verbosity=0) #uses regularizeFactor

        mdl_single_lsgst_cp = pygsti.do_mc2gst(ds, mdl_clgst, self.lsgstStrings[0], minProbClipForWeighting=1e-4,
                                           probClipInterval=(-1e6,1e6), cptp_penalty_factor=1.0,
                                           verbosity=0) #uses cptp_penalty_factor

        mdl_single_lsgst_sp = pygsti.do_mc2gst(ds, mdl_clgst, self.lsgstStrings[0], minProbClipForWeighting=1e-4,
                                              probClipInterval=(-1e6,1e6), spam_penalty_factor=1.0,
                                              verbosity=0) #uses spam_penalty_factor

        mdl_single_lsgst_cpsp = pygsti.do_mc2gst(ds, mdl_clgst, self.lsgstStrings[0], minProbClipForWeighting=1e-4,
                                                probClipInterval=(-1e6,1e6), cptp_penalty_factor=1.0,
                                                spam_penalty_factor=1.0, verbosity=0) #uses both penalty factors

        mdl_single_lsgst_cpsp = self.runSilent(pygsti.do_mc2gst, ds, mdl_clgst, self.lsgstStrings[0], minProbClipForWeighting=1e-4,
                                              probClipInterval=(-1e6,1e6), cptp_penalty_factor=1.0,
                                              spam_penalty_factor=1.0, verbosity=10) #uses both penalty factors w/verbosity high
        mdl_single_lsgst_cp = self.runSilent(pygsti.do_mc2gst, ds, mdl_clgst, self.lsgstStrings[0], minProbClipForWeighting=1e-4,
                                            probClipInterval=(-1e6,1e6), cptp_penalty_factor=1.0,
                                            verbosity=10) #uses cptp_penalty_factor w/verbosity high
        mdl_single_lsgst_sp = self.runSilent(pygsti.do_mc2gst, ds, mdl_clgst, self.lsgstStrings[0], minProbClipForWeighting=1e-4,
                                            probClipInterval=(-1e6,1e6), spam_penalty_factor=1.0,
                                            verbosity=10) #uses spam_penalty_factor w/verbosity high


        
        mdl_lsgst = pygsti.do_iterative_mc2gst(ds, mdl_clgst, self.lsgstStrings, verbosity=0,
                                             minProbClipForWeighting=1e-6, probClipInterval=(-1e6,1e6),
                                             memLimit=CM + 1024**3)
        all_minErrs, all_gs_lsgst_tups = pygsti.do_iterative_mc2gst(
            ds, mdl_clgst, [ [mdl.tup for mdl in gsList] for gsList in self.lsgstStrings],
            minProbClipForWeighting=1e-6, probClipInterval=(-1e6,1e6), returnAll=True, returnErrorVec=True)
        mdl_lsgst_verb = self.runSilent(pygsti.do_iterative_mc2gst, ds, mdl_clgst, self.lsgstStrings, verbosity=10,
                                             minProbClipForWeighting=1e-6, probClipInterval=(-1e6,1e6),
                                             memLimit=CM + 1024**3)
        mdl_lsgst_reg = self.runSilent(pygsti.do_iterative_mc2gst,ds, mdl_clgst,
                                      self.lsgstStrings, verbosity=10,
                                      minProbClipForWeighting=1e-6,
                                      probClipInterval=(-1e6,1e6),
                                      regularizeFactor=10, memLimit=CM + 1024**3)
        self.assertAlmostEqual(mdl_lsgst.frobeniusdist(mdl_lsgst_verb),0)
        self.assertAlmostEqual(mdl_lsgst.frobeniusdist(all_gs_lsgst_tups[-1]),0)


        #Run internal checks on less max-L values (so it doesn't take forever)
        mdl_lsgst_chk = pygsti.do_iterative_mc2gst(ds, mdl_clgst, self.lsgstStrings[0:2], verbosity=0,
                                                 minProbClipForWeighting=1e-6, probClipInterval=(-1e6,1e6),
                                                 check=True, check_jacobian=True)
        mdl_lsgst_chk_verb = self.runSilent(pygsti.do_iterative_mc2gst, ds, mdl_clgst, self.lsgstStrings[0:2], verbosity=10,
                                                      minProbClipForWeighting=1e-6, probClipInterval=(-1e6,1e6),
                                                      check=True, check_jacobian=True, memLimit=CM + 1024**3)

        #Other option variations - just make sure they run at this point
        mdl_lsgst_chk_opts = pygsti.do_iterative_mc2gst(ds, mdl_clgst, self.lsgstStrings[0:2], verbosity=0,
                                                      minProbClipForWeighting=1e-6, probClipInterval=(-1e6,1e6),
                                                      useFreqWeightedChiSq=True, circuitSetLabels=["Set1","Set2"],
                                                      circuitWeightsDict={ ('Gx',): 2.0 } )

        aliased_list = [ pygsti.obj.Circuit( [ (x if x != L("Gx") else L("GA1")) for x in mdl]) for mdl in self.lsgstStrings[0] ]
        mdl_withA1 = mdl_clgst.copy(); mdl_withA1.operations["GA1"] = mdl_clgst.operations["Gx"]
        del mdl_withA1.operations["Gx"] # otherwise mdl_withA1 will have Gx params that we have no knowledge of!
        mdl_lsgst_chk_opts2 = pygsti.do_mc2gst(ds, mdl_withA1, aliased_list, minProbClipForWeighting=1e-6,
                                              probClipInterval=(-1e2,1e2), verbosity=10,
                                              opLabelAliases={ L('GA1'): (L('Gx'),) })

        
        #Check with small but ok memlimit -- not anymore since new mem estimation uses current memory, making this non-robust
        #self.runSilent(pygsti.do_mc2gst,ds, mdl_clgst, self.lsgstStrings[0], minProbClipForWeighting=1e-6,
        #                 probClipInterval=(-1e6,1e6), regularizeFactor=1e-3,
        #                 verbosity=10, memLimit=CM + 1024**3)


        #Check errors:
        with self.assertRaises(MemoryError):
            pygsti.do_mc2gst(ds, mdl_clgst, self.lsgstStrings[0], minProbClipForWeighting=1e-6,
                             probClipInterval=(-1e6,1e6), regularizeFactor=1e-3,
                             verbosity=0, memLimit=1)

        with self.assertRaises(AssertionError):
            pygsti.do_mc2gst(ds, mdl_clgst, self.lsgstStrings[0], minProbClipForWeighting=1e-6,
                             probClipInterval=(-1e6,1e6), regularizeFactor=1e-3,
                             verbosity=0, cptp_penalty_factor=1.0) #can't specify both cptp_penalty_factor and regularizeFactor


        # 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 + "/lsgst.model", "Saved LSGST Model")
            pygsti.io.write_model(mdl_lsgst_reg,compare_files + "/lsgst_reg.model", "Saved LSGST Model w/Regularization")

        mdl_lsgst_compare = pygsti.io.load_model(compare_files + "/lsgst.model")
        mdl_lsgst_reg_compare = pygsti.io.load_model(compare_files + "/lsgst_reg.model")

        mdl_lsgst_go = pygsti.gaugeopt_to_target(mdl_lsgst, mdl_lsgst_compare, {'spam':1.0}, checkJac=True)

        mdl_lsgst_reg_go = pygsti.gaugeopt_to_target(mdl_lsgst_reg, mdl_lsgst_reg_compare, {'spam':1.0}, checkJac=True)

        self.assertAlmostEqual( mdl_lsgst_go.frobeniusdist(mdl_lsgst_compare), 0, places=4)
        self.assertAlmostEqual( mdl_lsgst_reg_go.frobeniusdist(mdl_lsgst_reg_compare), 0, places=4)

        # RUN BELOW LINES TO SEED SAVED GATESET FILES
        if os.environ.get('PYGSTI_REGEN_REF_FILES','no').lower() in ("yes","1","true"):
            mdl_lsgst_go = pygsti.gaugeopt_to_target(mdl_lsgst, self.model, {'spam':1.0})
            pygsti.io.write_model(mdl_lsgst_go,compare_files + "/analysis.model", "Saved LSGST Analysis Model")
            print("DEBUG: analysis.model = "); print(mdl_lgst_go)
Esempio n. 20
0
    def test_std_lists_and_structs(self):
        gateLabels = [L('Gx'), L('Gy')]
        strs = pygsti.construction.gatestring_list([('Gx', ), ('Gy', ),
                                                    ('Gx', 'Gx')])
        germs = pygsti.construction.gatestring_list([('Gx', 'Gy'),
                                                     ('Gy', 'Gy')])
        testFidPairs = [(0, 1)]
        testFidPairsDict = {
            (L('Gx'), L('Gy')): [(0, 0), (0, 1)],
            (L('Gy'), L('Gy')): [(0, 0)]
        }

        # LSGST
        maxLens = [1, 2]
        lsgstLists = pygsti.construction.make_lsgst_lists(
            std1Q_XY.gs_target,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="whole germ powers")  #also try a GateSet as first arg
        lsgstStructs = pygsti.construction.make_lsgst_structs(
            std1Q_XY.gs_target,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="whole germ powers")  #also try a GateSet as first arg
        self.assertEqual(set(lsgstLists[-1]), set(lsgstStructs[-1].allstrs))

        lsgstLists2 = pygsti.construction.make_lsgst_lists(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="truncated germ powers")
        lsgstStructs2 = pygsti.construction.make_lsgst_structs(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="truncated germ powers")
        self.assertEqual(set(lsgstLists2[-1]), set(lsgstStructs2[-1].allstrs))

        lsgstLists3 = pygsti.construction.make_lsgst_lists(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="length as exponent")
        lsgstStructs3 = pygsti.construction.make_lsgst_structs(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="length as exponent")
        self.assertEqual(set(lsgstLists3[-1]), set(lsgstStructs3[-1].allstrs))

        maxLens = [1, 2]
        lsgstLists4 = pygsti.construction.make_lsgst_lists(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="whole germ powers",
            nest=False)
        lsgstStructs4 = pygsti.construction.make_lsgst_structs(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="whole germ powers",
            nest=False)
        self.assertEqual(set(lsgstLists4[-1]), set(lsgstStructs4[-1].allstrs))

        lsgstLists5 = pygsti.construction.make_lsgst_lists(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=testFidPairs,
            truncScheme="whole germ powers")
        lsgstStructs5 = pygsti.construction.make_lsgst_structs(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=testFidPairs,
            truncScheme="whole germ powers")
        self.assertEqual(set(lsgstLists5[-1]), set(lsgstStructs5[-1].allstrs))

        lsgstLists6 = pygsti.construction.make_lsgst_lists(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=testFidPairsDict,
            truncScheme="whole germ powers")
        lsgstStructs6 = pygsti.construction.make_lsgst_structs(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=testFidPairsDict,
            truncScheme="whole germ powers")
        self.assertEqual(set(lsgstLists6[-1]), set(lsgstStructs6[-1].allstrs))

        lsgstExpList = pygsti.construction.make_lsgst_experiment_list(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="whole germ powers")
        lsgstExpListb = pygsti.construction.make_lsgst_experiment_list(
            std1Q_XY.gs_target,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="whole germ powers")  # with GateSet as first arg

        with self.assertRaises(ValueError):
            pygsti.construction.make_lsgst_lists(gateLabels,
                                                 strs,
                                                 strs,
                                                 germs,
                                                 maxLens,
                                                 fidPairs=None,
                                                 truncScheme="foobar")
        with self.assertRaises(ValueError):
            pygsti.construction.make_lsgst_structs(gateLabels,
                                                   strs,
                                                   strs,
                                                   germs,
                                                   maxLens,
                                                   fidPairs=None,
                                                   truncScheme="foobar")

        lsgstLists7 = pygsti.construction.make_lsgst_lists(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="whole germ powers",
            keepFraction=0.5,
            keepSeed=1234)
        lsgstStructs7 = pygsti.construction.make_lsgst_structs(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=None,
            truncScheme="whole germ powers",
            keepFraction=0.5,
            keepSeed=1234)
        self.assertEqual(set(lsgstLists7[-1]), set(lsgstStructs7[-1].allstrs))

        lsgstLists8 = pygsti.construction.make_lsgst_lists(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=testFidPairs,
            truncScheme="whole germ powers",
            keepFraction=0.7,
            keepSeed=1234)
        lsgstStructs8 = pygsti.construction.make_lsgst_structs(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            fidPairs=testFidPairs,
            truncScheme="whole germ powers",
            keepFraction=0.7,
            keepSeed=1234)
        self.assertEqual(set(lsgstLists8[-1]), set(lsgstStructs8[-1].allstrs))

        # empty max-lengths ==> no output
        lsgstStructs9 = pygsti.construction.make_lsgst_structs(
            gateLabels, strs, strs, germs, [])
        self.assertEqual(len(lsgstStructs9), 0)

        # checks against datasets
        ds = pygsti.objects.DataSet(
            outcomeLabels=['0', '1'])  # a dataset that is missing
        ds.add_count_dict(('Gx', ), {
            '0': 10,
            '1': 90
        })  # almost all our strings...
        ds.done_adding_data()
        lgst_strings = pygsti.construction.list_lgst_gatestrings(
            strs, strs, gateLabels)
        lsgstStructs10 = pygsti.construction.make_lsgst_structs(
            gateLabels,
            strs,
            strs,
            germs,
            maxLens,
            dscheck=ds,
            actionIfMissing="drop",
            verbosity=4)
        self.assertEqual([pygsti.obj.GateString(('Gx', ))],
                         lsgstStructs10[-1].allstrs)

        with self.assertRaises(ValueError):
            pygsti.construction.make_lsgst_structs(
                gateLabels, strs, strs, germs, maxLens,
                dscheck=ds)  #missing sequences
        with self.assertRaises(ValueError):
            pygsti.construction.make_lsgst_structs(
                gateLabels,
                strs,
                strs,
                germs,
                maxLens,
                dscheck=ds,
                actionIfMissing="foobar")  #invalid action

        # ELGST
        maxLens = [1, 2]
        elgstLists = pygsti.construction.make_elgst_lists(
            gateLabels, germs, maxLens, truncScheme="whole germ powers")

        maxLens = [1, 2]
        elgstLists2 = pygsti.construction.make_elgst_lists(
            gateLabels,
            germs,
            maxLens,
            truncScheme="whole germ powers",
            nest=False,
            includeLGST=False)
        elgstLists2b = pygsti.construction.make_elgst_lists(
            std1Q_XY.gs_target,
            germs,
            maxLens,
            truncScheme="whole germ powers",
            nest=False,
            includeLGST=False)  #with a GateSet as first arg

        elgstExpLists = pygsti.construction.make_elgst_experiment_list(
            gateLabels, germs, maxLens, truncScheme="whole germ powers")

        with self.assertRaises(ValueError):
            pygsti.construction.make_elgst_lists(gateLabels,
                                                 germs,
                                                 maxLens,
                                                 truncScheme="foobar")
Esempio n. 21
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(CalcMethods2QTestCase, cls).setUpClass()

        #Change to test_packages directory (since setUp hasn't been called yet...)
        origDir = os.getcwd()
        os.chdir(os.path.abspath(os.path.dirname(__file__)))
        os.chdir('..')  # The test_packages directory

        #Note: std is a 2Q model
        cls.maxLengths = [1]
        #cls.germs = std.germs_lite
        cls.germs = pygsti.construction.circuit_list([
            (gl, ) for gl in std.target_model().operations
        ])
        cls.mdl_datagen = std.target_model().depolarize(op_noise=0.1,
                                                        spam_noise=0.001)
        cls.listOfExperiments = pygsti.construction.make_lsgst_experiment_list(
            std.target_model(), std.prepStrs, std.effectStrs, cls.germs,
            cls.maxLengths)

        #RUN BELOW FOR DATAGEN (UNCOMMENT to regenerate)
        #ds = pygsti.construction.generate_fake_data(cls.mdl_datagen, cls.listOfExperiments,
        #                                            nSamples=1000, sampleError="multinomial", seed=1234)
        #ds.save(compare_files + "/calcMethods2Q.dataset")

        cls.ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files +
                                        "/calcMethods2Q.dataset")
        cls.advOpts = {'tolerance': 1e-2}

        #Reduced model GST dataset
        cls.nQubits = 2
        cls.mdl_redmod_datagen = pc.build_nqnoise_model(cls.nQubits,
                                                        geometry="line",
                                                        maxIdleWeight=1,
                                                        maxhops=1,
                                                        extraWeight1Hops=0,
                                                        extraGateWeight=1,
                                                        sparse=False,
                                                        sim_type="matrix",
                                                        verbosity=1,
                                                        gateNoise=(1234, 0.01),
                                                        prepNoise=(456, 0.01),
                                                        povmNoise=(789, 0.01))

        #Create a reduced set of fiducials and germs
        opLabels = list(cls.mdl_redmod_datagen.operations.keys())
        fids1Q = std1Q_XY.fiducials[0:2]  # for speed
        cls.redmod_fiducials = []
        for i in range(cls.nQubits):
            cls.redmod_fiducials.extend(
                pygsti.construction.manipulate_circuit_list(
                    fids1Q, [((L('Gx'), ), (L('Gx', i), )),
                             ((L('Gy'), ), (L('Gy', i), ))]))
        #print(redmod_fiducials, "Fiducials")

        cls.redmod_germs = pygsti.construction.circuit_list([
            (gl, ) for gl in opLabels
        ])
        cls.redmod_maxLs = [1]
        expList = pygsti.construction.make_lsgst_experiment_list(
            cls.mdl_redmod_datagen, cls.redmod_fiducials, cls.redmod_fiducials,
            cls.redmod_germs, cls.redmod_maxLs)

        #RUN BELOW FOR DATAGEN (UNCOMMENT to regenerate)
        #redmod_ds = pygsti.construction.generate_fake_data(cls.mdl_redmod_datagen, expList, 1000, "round", seed=1234)
        #redmod_ds.save(compare_files + "/calcMethods2Q_redmod.dataset")

        cls.redmod_ds = pygsti.objects.DataSet(fileToLoadFrom=compare_files +
                                               "/calcMethods2Q_redmod.dataset")

        #print(len(expList)," reduced model sequences")

        #Random starting points - little kick so we don't get hung up at start
        np.random.seed(1234)
        cls.rand_start18 = np.random.random(18) * 1e-6
        cls.rand_start206 = np.random.random(206) * 1e-6
        cls.rand_start228 = np.random.random(228) * 1e-6

        os.chdir(origDir)  # return to original directory
Esempio n. 22
0
def Ls(*args):
    """ Convert args to a tuple to Labels """
    return tuple([L(x) for x in args])
Esempio n. 23
0
    def test_ondemand_probabilities(self):
        #First create a "sparse" dataset
        # # Columns = 0 count, 1 count
        dataset_txt = \
"""# Test Sparse format data set
{}    0:0  1:100
Gx    0:10 1:90 2:0
GxGy  0:40 1:60
Gx^4  0:100
"""
        with open(temp_files + "/SparseDataset.txt", 'w') as f:
            f.write(dataset_txt)

        ds = pygsti.io.load_dataset(temp_files + "/SparseDataset.txt",
                                    recordZeroCnts=False)
        self.assertEqual(ds.get_outcome_labels(), [('0', ), ('1', ), ('2', )])
        self.assertEqual(ds[()].outcomes,
                         [('1', )])  # only nonzero count is 1-count
        self.assertEqual(
            ds[()]['2'],
            0)  # but we can query '2' since it's a valid outcome label

        gstrs = list(ds.keys())
        raw_dict, elIndices, outcome_lookup, ntotal = std1Q_XYI.target_model(
        ).simplify_circuits(gstrs, ds)

        print(
            "Raw circuit -> elabels dict:\n", "\n".join(
                ["%s: %s" % (str(k), str(v)) for k, v in raw_dict.items()]))
        print(
            "\nElement indices lookup (orig opstr index -> element indices):\n",
            elIndices)
        print(
            "\nOutcome lookup (orig opstr index -> list of outcome for each element):\n",
            outcome_lookup)
        print("\ntotal elements = ", ntotal)

        self.assertEqual(raw_dict[('rho0', )], [L('Mdefault_1')])
        self.assertEqual(raw_dict[(
            'rho0',
            'Gx',
        )], [L('Mdefault_0'), L('Mdefault_1')])
        self.assertEqual(raw_dict[('rho0', 'Gx', 'Gy')],
                         [L('Mdefault_0'), L('Mdefault_1')])
        self.assertEqual(raw_dict[('rho0', ) + ('Gx', ) * 4],
                         [L('Mdefault_0')])

        self.assertEqual(
            elIndices,
            collections.OrderedDict([(0, slice(0, 1, None)),
                                     (1, slice(1, 3, None)),
                                     (2, slice(3, 5, None)),
                                     (3, slice(5, 6, None))]))

        self.assertEqual(
            outcome_lookup,
            collections.OrderedDict([(0, [('1', )]), (1, [('0', ), ('1', )]),
                                     (2, [('0', ), ('1', )]), (3, [('0', )])]))

        self.assertEqual(ntotal, 6)

        #A sparse dataset loading test using the more common format:
        dataset_txt2 = \
"""## Columns = 0 count, 1 count
{} 0 100
Gx 10 90
GxGy 40 60
Gx^4 100 0
"""

        with open(temp_files + "/SparseDataset2.txt", 'w') as f:
            f.write(dataset_txt2)

        ds = pygsti.io.load_dataset(temp_files + "/SparseDataset2.txt",
                                    recordZeroCnts=True)
        self.assertEqual(ds.get_outcome_labels(), [('0', ), ('1', )])
        self.assertEqual(ds[()].outcomes, [
            ('0', ), ('1', )
        ])  # both outcomes even though only nonzero count is 1-count
        with self.assertRaises(KeyError):
            ds[(
            )]['2']  # *can't* query '2' b/c it's NOT a valid outcome label here
Esempio n. 24
0
 def test_doperation(self):
     dg = self.fwdsim.doperation(L('Gx'), flat=False)
     dgflat = self.fwdsim.doperation(L('Gx'), flat=True)
Esempio n. 25
0
    def test_confidenceRegion(self):

        res = pygsti.obj.Results()
        res.init_dataset(self.ds)
        res.init_circuits(self.gss)

        #Add estimate for hessian-based CI --------------------------------------------------
        res.add_estimate(stdxyi.target_model(), stdxyi.target_model(),
                         [self.model]*len(self.maxLengthList), parameters={'objective': 'logl'},
                         estimate_key="default")

        est = res.estimates['default']
        est.add_confidence_region_factory('final iteration estimate', 'final')
        self.assertWarns(est.add_confidence_region_factory, 'final iteration estimate','final') #overwrites former
        self.assertTrue( est.has_confidence_region_factory('final iteration estimate', 'final'))

        cfctry = est.get_confidence_region_factory('final iteration estimate', 'final')
        self.assertFalse( cfctry.can_construct_views() ) # b/c no hessian or LR enabled yet...
        cfctry.compute_hessian(approximate=True)
        cfctry.compute_hessian()
        self.assertTrue( cfctry.has_hessian() )
        self.assertFalse( cfctry.can_construct_views() ) # b/c hessian isn't projected yet...

        mdl_dummy = cfctry.get_model() # test method
        s = pickle.dumps(cfctry) # test pickle
        pickle.loads(s)

        cfctry.project_hessian('std')
        cfctry.project_hessian('none')
        cfctry.project_hessian('optimal gate CIs')
        cfctry.project_hessian('intrinsic error')
        with self.assertRaises(ValueError):
            cfctry.project_hessian(95.0, 'normal', 'FooBar') #bad hessianProjection

        self.assertTrue( cfctry.can_construct_views() )

        ci_std = cfctry.view( 95.0, 'normal', 'std')
        ci_noproj = cfctry.view( 95.0, 'normal', 'none')
        ci_intrinsic = cfctry.view( 95.0, 'normal', 'intrinsic error')
        ci_opt = cfctry.view( 95.0, 'normal', 'optimal gate CIs')

        with self.assertRaises(ValueError):
            cfctry.view(95.0, 'foobar') #bad region type

        self.assertWarns(cfctry.view, 0.95, 'normal', 'none') # percentage < 1.0


        #Add estimate for linresponse-based CI --------------------------------------------------
        res.add_estimate(stdxyi.target_model(), stdxyi.target_model(),
                         [self.model]*len(self.maxLengthList), parameters={'objective': 'logl'},
                         estimate_key="linresponse")

        estLR = res.estimates['linresponse']

        #estLR.add_confidence_region_factory('final iteration estimate', 'final') #Could do this, but use alt. method for more coverage
        with self.assertRaises(KeyError):
            estLR.get_confidence_region_factory('final iteration estimate', 'final') #won't create by default
        cfctryLR = estLR.get_confidence_region_factory('final iteration estimate', 'final', createIfNeeded=True) #now it will
        self.assertTrue( estLR.has_confidence_region_factory('final iteration estimate', 'final'))

        #cfctryLR = estLR.get_confidence_region_factory('final iteration estimate', 'final') #done by 'get' call above
        self.assertFalse( cfctryLR.can_construct_views() ) # b/c no hessian or LR enabled yet...
        cfctryLR.enable_linear_response_errorbars() #parent results object is used to automatically populate params

        #self.assertTrue( cfctryLR.can_construct_views() )
        ci_linresponse = cfctryLR.view( 95.0, 'normal', None)

        mdl_dummy = cfctryLR.get_model() # test method
        s = pickle.dumps(cfctryLR) # test pickle
        pickle.loads(s)


        #Add estimate for with bad objective ---------------------------------------------------------
        res.add_estimate(stdxyi.target_model(), stdxyi.target_model(),
                         [self.model]*len(self.maxLengthList), parameters={'objective': 'foobar'},
                         estimate_key="foo")
        est = res.estimates['foo']
        est.add_confidence_region_factory('final iteration estimate', 'final')
        with self.assertRaises(ValueError): # bad objective
            est.get_confidence_region_factory('final iteration estimate', 'final').compute_hessian()



        # Now test each of the views we created above ------------------------------------------------
        for ci_cur in (ci_std, ci_noproj, ci_opt, ci_intrinsic, ci_linresponse):

            s = pickle.dumps(ci_cur) # test pickle
            pickle.loads(s)

            #linear response CI doesn't support profile likelihood intervals
            if ci_cur is not ci_linresponse: # (profile likelihoods not implemented in this case)
                ar_of_intervals_Gx = ci_cur.get_profile_likelihood_confidence_intervals(L("Gx"))
                ar_of_intervals_rho0 = ci_cur.get_profile_likelihood_confidence_intervals(L("rho0"))
                ar_of_intervals_M0 = ci_cur.get_profile_likelihood_confidence_intervals(L("Mdefault"))
                ar_of_intervals = ci_cur.get_profile_likelihood_confidence_intervals()

                with self.assertRaises(ValueError):
                    ci_cur.get_profile_likelihood_confidence_intervals("foobar") #invalid label

            def fnOfGate_float(mx,b):
                return float(mx[0,0])
            def fnOfGate_complex(mx,b):
                return complex(mx[0,0] + 1.0j)
            def fnOfGate_0D(mx,b):
                return np.array( float(mx[0,0]) )
            def fnOfGate_1D(mx,b):
                return mx[0,:]
            def fnOfGate_2D(mx,b):
                return mx[:,:]
            def fnOfGate_2D_complex(mx,b):
                return np.array(mx[:,:] + 1j*mx[:,:],'complex')
            def fnOfGate_3D(mx,b):
                return np.zeros( (2,2,2), 'd') #just to test for error

            fns = (fnOfGate_float, fnOfGate_0D, fnOfGate_1D,
                   fnOfGate_2D, fnOfGate_3D)
            if ci_cur is not ci_linresponse: # complex functions not supported by linresponse CIs
                fns += (fnOfGate_complex, fnOfGate_2D_complex)

            for fnOfOp in fns:
                FnClass = gsf.opfn_factory(fnOfOp)
                FnObj = FnClass(self.model, 'Gx')
                if fnOfOp is fnOfGate_3D:
                    with self.assertRaises(ValueError):
                        df = ci_cur.get_fn_confidence_interval(FnObj, verbosity=0)
                else:
                    df = ci_cur.get_fn_confidence_interval(FnObj, verbosity=0)
                    df, f0 = self.runSilent(ci_cur.get_fn_confidence_interval,
                                            FnObj, returnFnVal=True, verbosity=4)

            ##SHORT-CIRCUIT linear reponse here to reduce run time
            if ci_cur is ci_linresponse: continue

            def fnOfVec_float(v,b):
                return float(v[0])
            def fnOfVec_0D(v,b):
                return np.array( float(v[0]) )
            def fnOfVec_1D(v,b):
                return np.array(v[:])
            def fnOfVec_2D(v,b):
                return np.dot(v.T,v)
            def fnOfVec_3D(v,b):
                return np.zeros( (2,2,2), 'd') #just to test for error

            for fnOfVec in (fnOfVec_float, fnOfVec_0D, fnOfVec_1D, fnOfVec_2D, fnOfVec_3D):
                FnClass = gsf.vecfn_factory(fnOfVec)
                FnObj = FnClass(self.model, 'rho0', 'prep')
                if fnOfVec is fnOfVec_3D:
                    with self.assertRaises(ValueError):
                        df = ci_cur.get_fn_confidence_interval(FnObj, verbosity=0)
                else:
                    df = ci_cur.get_fn_confidence_interval(FnObj, verbosity=0)
                    df, f0 = self.runSilent(ci_cur.get_fn_confidence_interval,
                                            FnObj, returnFnVal=True, verbosity=4)

            for fnOfVec in (fnOfVec_float, fnOfVec_0D, fnOfVec_1D, fnOfVec_2D, fnOfVec_3D):
                FnClass = gsf.vecfn_factory(fnOfVec)
                FnObj = FnClass(self.model, 'Mdefault:0', 'effect')
                if fnOfVec is fnOfVec_3D:
                    with self.assertRaises(ValueError):
                        df = ci_cur.get_fn_confidence_interval(FnObj, verbosity=0)
                else:
                    df = ci_cur.get_fn_confidence_interval(FnObj, verbosity=0)
                    df, f0 = self.runSilent(ci_cur.get_fn_confidence_interval,
                                            FnObj, returnFnVal=True, verbosity=4)


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

            for fnOfSpam in (fnOfSpam_float, fnOfSpam_0D, fnOfSpam_1D, fnOfSpam_2D, fnOfSpam_3D):
                FnClass = gsf.spamfn_factory(fnOfSpam)
                FnObj = FnClass(self.model)
                if fnOfSpam is fnOfSpam_3D:
                    with self.assertRaises(ValueError):
                        df = ci_cur.get_fn_confidence_interval(FnObj, verbosity=0)
                else:
                    df = ci_cur.get_fn_confidence_interval(FnObj, verbosity=0)
                    df, f0 = self.runSilent(ci_cur.get_fn_confidence_interval,
                                            FnObj, returnFnVal=True, verbosity=4)


            def fnOfGateSet_float(mdl):
                return float( mdl.operations['Gx'][0,0] )
            def fnOfGateSet_0D(mdl):
                return np.array( mdl.operations['Gx'][0,0]  )
            def fnOfGateSet_1D(mdl):
                return np.array( mdl.operations['Gx'][0,:] )
            def fnOfGateSet_2D(mdl):
                return np.array( mdl.operations['Gx'] )
            def fnOfGateSet_3D(mdl):
                return np.zeros( (2,2,2), 'd') #just to test for error

            for fnOfGateSet in (fnOfGateSet_float, fnOfGateSet_0D, fnOfGateSet_1D, fnOfGateSet_2D, fnOfGateSet_3D):
                FnClass = gsf.modelfn_factory(fnOfGateSet)
                FnObj = FnClass(self.model)
                if fnOfGateSet is fnOfGateSet_3D:
                    with self.assertRaises(ValueError):
                        df = ci_cur.get_fn_confidence_interval(FnObj, verbosity=0)
                else:
                    df = ci_cur.get_fn_confidence_interval(FnObj, verbosity=0)
                    df, f0 = self.runSilent(ci_cur.get_fn_confidence_interval,
                                            FnObj, returnFnVal=True, verbosity=4)
Esempio n. 26
0
    def test_direct_core(self):
        gs = directx.gateset_with_lgst_gatestring_estimates(
            self.strs, self.ds, self.prepStrs, self.effectStrs, self.tgt, includeTargetGates=True,
            gateStringLabels=None, svdTruncateTo=4, verbosity=10)

        gs = directx.gateset_with_lgst_gatestring_estimates(
            self.strs, self.ds, self.prepStrs, self.effectStrs, self.tgt, includeTargetGates=False,
            gateStringLabels=[L('G0'),L('G1'),L('G2'),L('G3'),L('G4'),L('G5')], svdTruncateTo=4, verbosity=10)
        self.assertEqual(set(gs.gates.keys()), set([L('G0'),L('G1'),L('G2'),L('G3'),L('G4'),L('G5')]))

        aliases = {'Gy2': ('Gy',)}
        gs = directx.gateset_with_lgst_gatestring_estimates(
            [pygsti.obj.GateString(('Gy2',))], self.ds, self.prepStrs, self.effectStrs, self.tgt, includeTargetGates=True,
            gateStringLabels=None, svdTruncateTo=4, verbosity=10, gateLabelAliases=aliases)
Esempio n. 27
0
    def test_3Q(self):

        #only test when reps are fast (b/c otherwise this test is slow!)
        try:
            from pygsti.objects import fastreplib
        except ImportError:
            warnings.warn("Skipping test_3Q b/c no fastreps!")
            return

        nQubits = 3
        print("Constructing Target LinearOperator Set")
        target_model = build_XYCNOT_cloudnoise_model(nQubits,
                                                     geometry="line",
                                                     maxIdleWeight=1,
                                                     maxhops=1,
                                                     extraWeight1Hops=0,
                                                     extraGateWeight=1,
                                                     sparse=True,
                                                     sim_type="map",
                                                     verbosity=1)
        #print("nElements test = ",target_model.num_elements())
        #print("nParams test = ",target_model.num_params())
        #print("nNonGaugeParams test = ",target_model.num_nongauge_params())

        print("Constructing Datagen LinearOperator Set")
        mdl_datagen = build_XYCNOT_cloudnoise_model(nQubits,
                                                    geometry="line",
                                                    maxIdleWeight=1,
                                                    maxhops=1,
                                                    extraWeight1Hops=0,
                                                    extraGateWeight=1,
                                                    sparse=True,
                                                    verbosity=1,
                                                    roughNoise=(1234, 0.1),
                                                    sim_type="map")

        mdl_test = mdl_datagen
        print(
            "Constructed model with %d op-blks, dim=%d, and nParams=%d.  Norm(paramvec) = %g"
            % (len(mdl_test.operation_blks), mdl_test.dim,
               mdl_test.num_params(), np.linalg.norm(mdl_test.to_vector())))

        opLabels = target_model.get_primitive_op_labels()
        line_labels = tuple(range(nQubits))
        fids1Q = std1Q_XY.fiducials
        fiducials = []
        for i in range(nQubits):
            fiducials.extend(
                pygsti.construction.manipulate_circuit_list(
                    fids1Q, [((L('Gx'), ), (L('Gx', i), )),
                             ((L('Gy'), ), (L('Gy', i), ))],
                    line_labels=line_labels))
        print(len(fiducials), "Fiducials")
        prep_fiducials = meas_fiducials = fiducials
        #TODO: add fiducials for 2Q pairs (edges on graph)

        germs = pygsti.construction.circuit_list([(gl, ) for gl in opLabels],
                                                 line_labels=line_labels)
        maxLs = [1]
        expList = pygsti.construction.make_lsgst_experiment_list(
            mdl_datagen, prep_fiducials, meas_fiducials, germs, maxLs)
        self.assertTrue(Circuit((), line_labels) in expList)

        ds = pygsti.construction.generate_fake_data(mdl_datagen,
                                                    expList,
                                                    1000,
                                                    "multinomial",
                                                    seed=1234)
        print("Created Dataset with %d strings" % len(ds))

        logL = pygsti.tools.logl(mdl_datagen, ds, expList)
        max_logL = pygsti.tools.logl_max(mdl_datagen, ds, expList)
        twoDeltaLogL = 2 * (max_logL - logL)
        chi2 = pygsti.tools.chi2(mdl_datagen, ds, expList)

        dof = ds.get_degrees_of_freedom()
        nParams = mdl_datagen.num_params()
        print("Datagen 2DeltaLogL = 2(%g-%g) = %g" %
              (logL, max_logL, twoDeltaLogL))
        print("Datagen chi2 = ", chi2)
        print("Datagen expected DOF = ", dof)
        print("nParams = ", nParams)
        print("Expected 2DeltaLogL or chi2 ~= %g-%g =%g" %
              (dof, nParams, dof - nParams))
        #print("EXIT"); exit()
        return

        results = pygsti.do_long_sequence_gst(
            ds,
            target_model,
            prep_fiducials,
            meas_fiducials,
            germs,
            maxLs,
            verbosity=5,
            advancedOptions={
                'maxIterations': 2
            })  #keep this short; don't care if it doesn't converge.
        print("DONE!")