Example #1
0
    def test_parameter_counting(self):
        #XY Model: SPAM=True
        n = stdxy.target_model().num_params
        self.assertEqual(n,44) # 2*16 + 3*4 = 44

        n = stdxy.target_model().num_nongauge_params
        self.assertEqual(n,28) # full 16 gauge params

        #XY Model: SPAM=False
        tst = stdxy.target_model()
        del tst.preps['rho0']
        del tst.povms['Mdefault']
        n = tst.num_params
        self.assertEqual(n,32) # 2*16 = 32

        n = tst.num_nongauge_params
        self.assertEqual(n,18) # gates are all unital & TP => only 14 gauge params (2 casimirs)


        #XYI Model: SPAM=True
        n = stdxyi.target_model().num_params
        self.assertEqual(n,60) # 3*16 + 3*4 = 60

        n = stdxyi.target_model().num_nongauge_params
        self.assertEqual(n,44) # full 16 gauge params: SPAM gate + 3 others

        #XYI Model: SPAM=False
        tst = stdxyi.target_model()
        del tst.preps['rho0']
        del tst.povms['Mdefault']
        n = tst.num_params
        self.assertEqual(n,48) # 3*16 = 48

        n = tst.num_nongauge_params
        self.assertEqual(n,34) # gates are all unital & TP => only 14 gauge params (2 casimirs)

        #XYI Model: SP0=False
        tst = stdxyi.target_model()
        tst.preps['rho0'] = pygsti.modelmembers.states.TPState(tst.preps['rho0'])
        n = tst.num_params
        self.assertEqual(n,59) # 3*16 + 2*4 + 3 = 59

        n = tst.num_nongauge_params
        self.assertEqual(n,44) # 15 gauge params (minus one b/c can't change rho?)

        #XYI Model: G0=SP0=False
        tst.operations['Gi'] = pygsti.modelmembers.operations.FullTPOp(tst.operations['Gi'])
        tst.operations['Gx'] = pygsti.modelmembers.operations.FullTPOp(tst.operations['Gx'])
        tst.operations['Gy'] = pygsti.modelmembers.operations.FullTPOp(tst.operations['Gy'])
        n = tst.num_params
        self.assertEqual(n,47) # 3*12 + 2*4 + 3 = 47

        n = tst.num_nongauge_params
        self.assertEqual(n,35) # full 12 gauge params of single 4x3 gate
Example #2
0
    def test_clifford_compilations(self):

        # Tests the Clifford compilations hard-coded into the various std models. Perhaps this can be
        # automated to run over all the std models that contain a Clifford compilation?

        from pygsti.modelpacks.legacy import std1Q_Cliffords
        target_model = std1Q_Cliffords.target_model()
        clifford_group = rb.group.construct_1q_clifford_group()

        from pygsti.modelpacks.legacy import std1Q_XY
        target_model = std1Q_XY.target_model()
        clifford_compilation = std1Q_XY.clifford_compilation
        compiled_cliffords = pygsti.models.modelconstruction.create_explicit_alias_model(
            target_model, clifford_compilation)

        for key in list(compiled_cliffords.operations.keys()):
            self.assertLess(
                np.sum(
                    abs(compiled_cliffords.operations[key] -
                        clifford_group.matrix(key))), 10**(-10))

        from pygsti.modelpacks.legacy import std1Q_XYI
        target_model = std1Q_XYI.target_model()
        clifford_compilation = std1Q_XYI.clifford_compilation
        compiled_cliffords = pygsti.models.modelconstruction.create_explicit_alias_model(
            target_model, clifford_compilation)

        for key in list(compiled_cliffords.operations.keys()):
            self.assertLess(
                np.sum(
                    abs(compiled_cliffords.operations[key] -
                        clifford_group.matrix(key))), 10**(-10))
Example #3
0
    def setUpClass(cls):
        super(RBTheoryWeightedInfidelityTester, cls).setUpClass()
        cls.target_model = std1Q_XY.target_model()
        cls.mdl = cls.target_model.copy()

        depol_strength_X = 1e-3
        depol_strength_Y = 3e-3

        lx = 1. - depol_strength_X
        depmap_X = np.array([[1., 0., 0., 0.], [0., lx, 0., 0.],
                             [0., 0., lx, 0.], [0, 0., 0., lx]])
        ly = 1. - depol_strength_Y
        depmap_Y = np.array([[1., 0., 0., 0.], [0., ly, 0., 0.],
                             [0., 0., ly, 0.], [0, 0., 0., ly]])
        cls.mdl.operations['Gx'] = np.dot(depmap_X,
                                          cls.target_model.operations['Gx'])
        cls.mdl.operations['Gy'] = np.dot(depmap_Y,
                                          cls.target_model.operations['Gy'])

        Gx_weight = 1
        Gy_weight = 2
        cls.weights = {'Gx': Gx_weight, 'Gy': Gy_weight}
        GxAGI = ot.average_gate_infidelity(cls.mdl.operations['Gx'],
                                           cls.target_model.operations['Gx'])
        GyAGI = ot.average_gate_infidelity(cls.mdl.operations['Gy'],
                                           cls.target_model.operations['Gy'])
        cls.expected_AGI = (Gx_weight * GxAGI +
                            Gy_weight * GyAGI) / (Gx_weight + Gy_weight)
        GxAEI = ot.entanglement_infidelity(cls.mdl.operations['Gx'],
                                           cls.target_model.operations['Gx'])
        GyAEI = ot.entanglement_infidelity(cls.mdl.operations['Gy'],
                                           cls.target_model.operations['Gy'])
        cls.expected_EI = (Gx_weight * GxAEI +
                           Gy_weight * GyAEI) / (Gx_weight + Gy_weight)
Example #4
0
 def setUpClass(cls):
     cls.target_model = std1Q_XY.target_model()
     cls.prepStrs = std1Q_XY.fiducials
     cls.measStrs = std1Q_XY.fiducials
     cls.germs = std1Q_XY.germs
     cls.maxLens = [1, 4]
     super(EvalTree1QBase, cls).setUpClass()
Example #5
0
    def setUpClass(cls):
        return  # SKIP TESTS
        super(RBTheoryXYModelTester, cls).setUpClass()
        cls.target_model = std1Q_XY.target_model()
        cls.mdl = cls.target_model.depolarize(op_noise=1e-3)

        cls.clifford_group = rb.group.construct_1q_clifford_group()
        cls.clifford_compilation = std1Q_XY.clifford_compilation
Example #6
0
    def setUpClass(cls):
        super(RBTheoryZrotModelTester, cls).setUpClass()
        cls.target_model = std1Q_XY.target_model()
        cls.mdl = cls.target_model.copy()

        Zrot_unitary = np.array([[1., 0.], [0., np.exp(-1j * 0.01)]])
        Zrot_channel = ot.unitary_to_pauligate(Zrot_unitary)

        for key in cls.target_model.operations.keys():
            cls.mdl.operations[key] = np.dot(Zrot_channel, cls.target_model.operations[key])
Example #7
0
 def test_lsgst_experiment_list(self):
     maxLens = [1, 2]
     lsgstExpList = stdlists.make_lsgst_experiment_list(
         self.opLabels,
         self.strs,
         self.strs,
         self.germs,
         maxLens,
         fidPairs=None,
         truncScheme="whole germ powers")
     lsgstExpListb = stdlists.make_lsgst_experiment_list(
         std1Q_XY.target_model(),
         self.strs,
         self.strs,
         self.germs,
         maxLens,
         fidPairs=None,
         truncScheme="whole germ powers")  # with Model as first arg
Example #8
0
 def test_lsgst_experiment_list(self):
     maxLens = [1, 2]
     lsgstExpList = gstcircuits.create_lsgst_circuits(
         self.opLabels,
         self.strs,
         self.strs,
         self.germs,
         maxLens,
         fid_pairs=None,
         trunc_scheme="whole germ powers")
     lsgstExpListb = gstcircuits.create_lsgst_circuits(
         std1Q_XY.target_model(),
         self.strs,
         self.strs,
         self.germs,
         maxLens,
         fid_pairs=None,
         trunc_scheme="whole germ powers")  # with Model as first arg
     self.assertEqual(set(lsgstExpList), set(lsgstExpListb))
Example #9
0
    def test_elgst_lists_structs(self):
        # ELGST
        maxLens = [1, 2]
        elgstLists = stdlists.make_elgst_lists(self.opLabels,
                                               self.germs,
                                               maxLens,
                                               truncScheme="whole germ powers")

        maxLens = [1, 2]
        elgstLists2 = stdlists.make_elgst_lists(
            self.opLabels,
            self.germs,
            maxLens,
            truncScheme="whole germ powers",
            nest=False,
            includeLGST=False)
        elgstLists2b = stdlists.make_elgst_lists(
            std1Q_XY.target_model(),
            self.germs,
            maxLens,
            truncScheme="whole germ powers",
            nest=False,
            includeLGST=False)  # with a Model as first arg
Example #10
0
    def test_elgst_lists_structs(self):
        # ELGST
        maxLens = [1, 2]
        elgstLists = gstcircuits.create_elgst_lists(
            self.opLabels,
            self.germs,
            maxLens,
            trunc_scheme="whole germ powers")

        maxLens = [1, 2]
        elgstLists2 = gstcircuits.create_elgst_lists(
            self.opLabels,
            self.germs,
            maxLens,
            trunc_scheme="whole germ powers",
            nest=False,
            include_lgst=False)
        elgstLists2b = gstcircuits.create_elgst_lists(
            std1Q_XY.target_model(),
            self.germs,
            maxLens,
            trunc_scheme="whole germ powers",
            nest=False,
            include_lgst=False)  # with a Model as first arg
Example #11
0
    def test_rpe_demo(self):

        #Declare the particular RPE instance we are interested in
        #(X and Y pi/2 rotations)
        rpeconfig_inst = rpeconfig_GxPi2_GyPi2_00
        
        
        #Declare a variety of relevant parameters
        target_model = Std1Q_XY.target_model()
        target_model.set_all_parameterizations('TP')
        maxLengths_1024 = [1,2,4,8,16,32,64,128,256,512,1024]
        
        stringListsRPE = RPEConstr.make_rpe_angle_string_list_dict(10,rpeconfig_inst)
        
        angleList = ['alpha','epsilon','theta']
        
        numStrsD = {}
        numStrsD['RPE'] = [6*i for i in np.arange(1,12)]
        
        #Create noisy model
        mdl_real = target_model.rotate(rotate=[0.01,0.01,0])
        
        #Extract noisy model angles
        true_alpha = RPE.extract_alpha(mdl_real,rpeconfig_inst)
        true_epsilon = RPE.extract_epsilon(mdl_real,rpeconfig_inst)
        true_theta = RPE.extract_theta(mdl_real,rpeconfig_inst)
        
        #Load pre-simulated dataset
#        N=100
#        DS = gst.construction.generate_fake_data(mdl_real,stringListsRPE['totalStrList'],N,sampleError='binomial',seed=1)
        DS = gst.io.load_dataset(compare_files + '/rpe_test_ds.txt')
        
        #Analyze dataset
        resultsRPE = RPE.analyze_rpe_data(DS,mdl_real,stringListsRPE,rpeconfig_inst)
    
        PhiFunErrorListCorrect = np.array([1.4647120176458639e-08, 5.466086847039087e-09, 2.811838817340373e-09, 9.295340015064157e-09, 1.4896280285670027e-08, 1.4897848815698111e-08, 4.269122493016919e-09, 1.4897576120637135e-08, 1.4897610849801124e-08, 6.193216574995608e-09, 1.4469989279702888e-08])
        alphaErrorListCorrect= np.array([0.05000352128724339, 0.09825031832409103, 0.02500687294425541, 0.012575500499770742, 0.012523502109159201, 0.0044641536173215535, 0.0007474956215971496, 0.00018069665046693828, 0.00027322234186732963, 0.00020451259672338296, 3.198565800954789e-05])
        epsilonErrorListCorrect  = np.array([0.18811777239515082, 0.009964509397691668, 0.004957204616348632, 0.007362158521305728, 0.00010888027730326932, 0.0015920480408759818, 0.001403238695757869, 0.0004870373015233298, 0.0001929699810709895, 3.411170328226909e-05, 2.723356656519904e-05]) 
        thetaErrorListCorrect= np.array([0.018281791956737087, 0.015230174647994477, 0.0018336710008779447, 0.004525418577473875, 0.0047631900047339125, 0.002627347622582976, 0.0030228260649800788, 0.002591470061459089, 0.0027097752869584, 0.002733081374122569, 0.0027947590038843876])

        PhiFunErrorList =  resultsRPE['PhiFunErrorList']
        alphaErrorList =  resultsRPE['alphaErrorList']
        epsilonErrorList =  resultsRPE['epsilonErrorList']
        thetaErrorList =  resultsRPE['thetaErrorList']
        
        assert np.linalg.norm(PhiFunErrorListCorrect-PhiFunErrorList) < 1e-8
        assert np.linalg.norm(alphaErrorListCorrect-alphaErrorList) < 1e-8
        assert np.linalg.norm(epsilonErrorListCorrect-epsilonErrorList) < 1e-8
        assert np.linalg.norm(thetaErrorListCorrect-thetaErrorList) < 1e-8
        
        
        # again, with consistency checks
#       We are currently not testing the consistency check. -KMR 2/26/18

#        dummy_k_list = [ 1 ] #EGN: not sure what this should really be...
#        resultsRPE_2 = RPE.analyze_rpe_data(DS,mdl_real,stringListsRPE,rpeconfig_inst,
#                                            do_consistency_check=True, k_list=dummy_k_list)



#        with self.assertRaises(ValueError):
#            RPE.analyze_rpe_data(DS,mdl_real,stringListsRPE,rpeconfig_inst,
#                                 do_consistency_check=True) #no k_list given
        



        #Print results
        print('alpha_true - pi/2 =',true_alpha-np.pi/2)
        print('epsilon_true - pi/2 =',true_epsilon-np.pi/2)
        print('theta_true =',true_theta)
        print()
        print('alpha_true - alpha_est_final =',resultsRPE['alphaErrorList'][-1])
        print('epsilon_true - epsilon_est_final =',resultsRPE['epsilonErrorList'][-1])
        print('theta_true - theta_est_final =',resultsRPE['thetaErrorList'][-1])
Example #12
0
    def setUp(self):
        std.target_model()._check_paramvec()
        super(CodecsTestCase, self).setUp()
        self.model = std.target_model()

        self.germs = pygsti.construction.circuit_list([('Gx', ), ('Gy', )
                                                       ])  #abridged for speed
        self.fiducials = std.fiducials
        self.maxLens = [1, 2]
        self.opLabels = list(self.model.operations.keys())

        self.lsgstStrings = pygsti.construction.make_lsgst_lists(
            self.opLabels, self.fiducials, self.fiducials, self.germs,
            self.maxLens)

        self.datagen_gateset = self.model.depolarize(op_noise=0.05,
                                                     spam_noise=0.1)
        test = self.datagen_gateset.copy()
        self.ds = pygsti.construction.generate_fake_data(
            self.datagen_gateset,
            self.lsgstStrings[-1],
            nSamples=1000,
            sampleError='binomial',
            seed=100)

        #Make an model with instruments
        E = self.datagen_gateset.povms['Mdefault']['0']
        Erem = self.datagen_gateset.povms['Mdefault']['1']
        Gmz_plus = np.dot(E, E.T)
        Gmz_minus = np.dot(Erem, Erem.T)
        self.mdl_withInst = self.datagen_gateset.copy()
        self.mdl_withInst.instruments['Iz'] = pygsti.obj.Instrument({
            'plus':
            Gmz_plus,
            'minus':
            Gmz_minus
        })
        self.mdl_withInst.instruments['Iztp'] = pygsti.obj.TPInstrument({
            'plus':
            Gmz_plus,
            'minus':
            Gmz_minus
        })

        self.results = self.runSilent(pygsti.do_long_sequence_gst, self.ds,
                                      std.target_model(), self.fiducials,
                                      self.fiducials, self.germs, self.maxLens)

        #make a confidence region factory
        estLbl = "default"
        crfact = self.results.estimates[estLbl].add_confidence_region_factory(
            'go0', 'final')
        crfact.compute_hessian(comm=None)
        crfact.project_hessian('std')

        #create a Workspace object
        self.ws = pygsti.report.create_standard_report(
            self.results,
            None,
            title="GST Codec TEST Report",
            confidenceLevel=95)
        std.target_model()._check_paramvec()

        #create miscellaneous other objects
        self.miscObjects = []
        self.miscObjects.append(
            pygsti.objects.labeldicts.OutcomeLabelDict([(('0', ), 90),
                                                        (('1', ), 10)]))
Example #13
0
    def test_json(self):

        #basic types
        s = json.dumps(range(10))
        x = json.loads(s)
        s = json.dumps(4 + 3.0j)
        x = json.loads(s)
        s = json.dumps(np.array([1, 2, 3, 4], 'd'))
        x = json.loads(s)
        s = json.dumps(testObj)
        x = json.loads(s)

        #string list
        s = json.dumps(self.lsgstStrings)
        x = json.loads(s)
        self.assertEqual(x, self.lsgstStrings)

        # DataSet
        s = json.dumps(self.ds)
        x = json.loads(s)
        self.assertEqual(list(x.keys()), list(self.ds.keys()))
        self.assertEqual(x[('Gx', )].as_dict(), self.ds[('Gx', )].as_dict())

        # Model
        s = json.dumps(self.datagen_gateset)
        with open(temp_files + "/model.json", 'w') as f:
            json.dump(self.datagen_gateset, f)
        with open(temp_files + "/model.json", 'r') as f:
            x = json.load(f)
        s = json.dumps(self.mdl_withInst)
        x = json.loads(s)
        self.assertAlmostEqual(self.mdl_withInst.frobeniusdist(x), 0)

        #print(s)
        x._check_paramvec(True)
        self.assertAlmostEqual(self.datagen_gateset.frobeniusdist(x), 0)

        # Results (containing confidence region)
        std.target_model()._check_paramvec()
        print("target_model = ", id(std.target_model()))
        print("rho0 parent = ", id(std.target_model().preps['rho0'].parent))

        #import bpdb; bpdb.set_trace()
        with open(temp_files + "/results.json", 'w') as f:
            json.dump(self.results, f)
        print("mdl_target2 = ", id(std.target_model()))
        print("rho0 parent2 = ", id(std.target_model().preps['rho0'].parent))
        std.target_model()._check_paramvec()
        with open(temp_files + "/results.json", 'r') as f:
            x = json.load(f)
        self.assertEqual(list(x.estimates.keys()),
                         list(self.results.estimates.keys()))
        self.assertEqual(
            list(x.estimates['default'].confidence_region_factories.keys()),
            list(self.results.estimates['default'].confidence_region_factories.
                 keys()))

        # Workspace
        s = json.dumps(self.ws)
        x = json.loads(s)
        #TODO: comparison (?)

        #Misc other objects
        for obj in self.miscObjects:
            s = json.dumps(obj)
            x = json.loads(s)
Example #14
0
def create_nqubit_gateset(nQubits, geometry="line", maxIdleWeight=1, maxhops=0,
                          extraWeight1Hops=0, extraGateWeight=0, sparse=False,
                          gateNoise=None, prepNoise=None, povmNoise=None, verbosity=0):
    # noise can be either a seed or a random array that is long enough to use

    printer = pygsti.obj.VerbosityPrinter.build_printer(verbosity)
    printer.log("Creating a %d-qubit %s model" % (nQubits,geometry))

    mdl = pygsti.obj.ExplicitOpModel() # no preps/POVMs
    # TODO: sparse prep & effect vecs... acton(...) analogue?

    #Full preps & povms -- maybe another option
    ##Create initial model with std prep & POVM
    #eLbls = []; eExprs = []
    #formatStr = '0' + str(nQubits) + 'b'
    #for i in range(2**nQubits):
    #    eLbls.append( format(i,formatStr))
    #    eExprs.append( str(i) )    
    #Qlbls = tuple( ['Q%d' % i for i in range(nQubits)] )
    #mdl = pygsti.construction.build_explicit_model(
    #    [2**nQubits], [Qlbls], [], [], 
    #    effectLabels=eLbls, effectExpressions=eExprs)
    printer.log("Created initial model")

    qubitGraph = QubitGraph(nQubits, geometry)
    printer.log("Created qubit graph:\n"+str(qubitGraph))

    printer.log("Creating Idle:")
    mdl.operations['Gi'] = create_global_idle(qubitGraph, maxIdleWeight, sparse, printer-1)
     
    #1Q gates: X(pi/2) & Y(pi/2) on each qubit
    Gx = std1Q_XY.target_model().operations['Gx']
    Gy = std1Q_XY.target_model().operations['Gy'] 
    weight_maxhops_tuples_1Q = [(1,maxhops+extraWeight1Hops)] + \
                               [ (1+x,maxhops) for x in range(1,extraGateWeight+1) ]
    for i in range(nQubits):
        printer.log("Creating 1Q X(pi/2) gate on qubit %d!!" % i)
        mdl.operations["Gx%d"%i] = create_composed_gate(
            Gx, (i,), qubitGraph, weight_maxhops_tuples_1Q,
            idle_noise=mdl.operations['Gi'], loc_noise_type="manylittle",
            sparse=sparse, verbosity=printer-1)

        printer.log("Creating 1Q Y(pi/2) gate on qubit %d!!" % i)
        mdl.operations["Gy%d"%i] = create_composed_gate(
            Gy, (i,), qubitGraph, weight_maxhops_tuples_1Q,
            idle_noise=mdl.operations['Gi'], loc_noise_type="manylittle",
            sparse=sparse, verbosity=printer-1)
        
    #2Q gates: CNOT gates along each graph edge
    Gcnot = std2Q_XYICNOT.target_model().operations['Gcnot']
    weight_maxhops_tuples_2Q = [(1,maxhops+extraWeight1Hops),(2,maxhops)] + \
                               [ (2+x,maxhops) for x in range(1,extraGateWeight+1) ]
    for i,j in qubitGraph.edges(): #note: all edges have i<j so "control" of CNOT is always lower index (arbitrary)
        printer.log("Creating CNOT gate between qubits %d and %d!!" % (i,j))
        mdl.operations["Gc%dt%d"% (i,j)] = create_composed_gate(
            Gcnot, (i,j), qubitGraph, weight_maxhops_tuples_2Q,
            idle_noise=mdl.operations['Gi'], loc_noise_type="manylittle",
            sparse=sparse, verbosity=printer-1)


    #Insert noise on gates
    vecNoSpam = mdl.to_vector()
    assert( _np.linalg.norm(vecNoSpam)/len(vecNoSpam) < 1e-6 )
    if gateNoise is not None:
        if isinstance(gateNoise,tuple): # use as (seed, strength)
            seed,strength = gateNoise
            rndm = _np.random.RandomState(seed)
            vecNoSpam += _np.abs(rndm.random_sample(len(vecNoSpam))*strength) #abs b/c some params need to be positive
        else: #use as a vector
            vecNoSpam += gateNoise[0:len(vecNoSpam)]
        mdl.from_vector(vecNoSpam)

        
    #SPAM
    basis1Q = pygsti.obj.Basis("pp",2)
    prepFactors = [ pygsti.obj.TPSPAMVec(pygsti.construction.basis_build_vector("0", basis1Q))
                    for i in range(nQubits)]
    if prepNoise is not None:
        if isinstance(prepNoise,tuple): # use as (seed, strength)
            seed,strength = prepNoise
            rndm = _np.random.RandomState(seed)
            depolAmts = _np.abs(rndm.random_sample(nQubits)*strength)
        else:
            depolAmts = prepNoise[0:nQubits]
        for amt,vec in zip(depolAmts,prepFactors): vec.depolarize(amt) 
    mdl.preps['rho0'] = pygsti.obj.TensorProdSPAMVec('prep',prepFactors)
    
    factorPOVMs = []
    for i in range(nQubits):
        effects = [ (l,pygsti.construction.basis_build_vector(l, basis1Q)) for l in ["0","1"] ]
        factorPOVMs.append( pygsti.obj.TPPOVM(effects) )
    if povmNoise is not None:
        if isinstance(povmNoise,tuple): # use as (seed, strength)
            seed,strength = povmNoise
            rndm = _np.random.RandomState(seed)
            depolAmts = _np.abs(rndm.random_sample(nQubits)*strength)
        else:
            depolAmts = povmNoise[0:nQubits]
        for amt,povm in zip(depolAmts,factorPOVMs): povm.depolarize(amt) 
    mdl.povms['Mdefault'] = pygsti.obj.TensorProdPOVM( factorPOVMs )
        
    printer.log("DONE! - returning Model with dim=%d and gates=%s" % (mdl.dim, list(mdl.operations.keys())))
    return mdl
Example #15
0
    def test_lsgst_lists_structs(self):
        maxLens = [1, 2]
        lsgstLists = gstcircuits.create_lsgst_circuit_lists(
            std1Q_XY.target_model(),
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=None,
            trunc_scheme="whole germ powers")  # also try a Model as first arg
        self.assertEqual(
            lsgstLists[-1][26]._str, 'GxGx(Gx)^2GxGx'
        )  # ensure that (.)^2 appears in string (*not* expanded)

        lsgstLists2 = gstcircuits.create_lsgst_circuit_lists(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=None,
            trunc_scheme="truncated germ powers")
        self.assertEqual(set(lsgstLists[-1]), set(lsgstLists2[-1]))

        lsgstLists3 = gstcircuits.create_lsgst_circuit_lists(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=None,
            trunc_scheme="length as exponent")
        lsgstStructs3 = gstcircuits.make_lsgst_structs(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=None,
            trunc_scheme="length as exponent")
        self.assertEqual(set(lsgstLists3[-1]), set(lsgstStructs3[-1]))

        maxLens = [1, 2]
        lsgstLists4 = gstcircuits.create_lsgst_circuit_lists(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=None,
            trunc_scheme="whole germ powers",
            nest=False)
        lsgstStructs4 = gstcircuits.make_lsgst_structs(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=None,
            trunc_scheme="whole germ powers",
            nest=False)
        self.assertEqual(set(lsgstLists4[-1]), set(lsgstStructs4[-1]))

        lsgstLists5 = gstcircuits.create_lsgst_circuit_lists(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=self.testFidPairs,
            trunc_scheme="whole germ powers")
        lsgstStructs5 = gstcircuits.make_lsgst_structs(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=self.testFidPairs,
            trunc_scheme="whole germ powers")
        self.assertEqual(set(lsgstLists5[-1]), set(lsgstStructs5[-1]))

        lsgstLists6 = gstcircuits.create_lsgst_circuit_lists(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=self.testFidPairsDict,
            trunc_scheme="whole germ powers")
        lsgstStructs6 = gstcircuits.make_lsgst_structs(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=self.testFidPairsDict,
            trunc_scheme="whole germ powers")
        self.assertEqual(set(lsgstLists6[-1]), set(lsgstStructs6[-1]))

        lsgstLists7 = gstcircuits.create_lsgst_circuit_lists(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=None,
            trunc_scheme="whole germ powers",
            keep_fraction=0.5,
            keep_seed=1234)
        lsgstStructs7 = gstcircuits.make_lsgst_structs(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=None,
            trunc_scheme="whole germ powers",
            keep_fraction=0.5,
            keep_seed=1234)
        self.assertEqual(set(lsgstLists7[-1]), set(lsgstStructs7[-1]))

        lsgstLists8 = gstcircuits.create_lsgst_circuit_lists(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=self.testFidPairs,
            trunc_scheme="whole germ powers",
            keep_fraction=0.7,
            keep_seed=1234)
        lsgstStructs8 = gstcircuits.make_lsgst_structs(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fid_pairs=self.testFidPairs,
            trunc_scheme="whole germ powers",
            keep_fraction=0.7,
            keep_seed=1234)
        self.assertEqual(set(lsgstLists8[-1]), set(lsgstStructs8[-1]))

        # empty max-lengths ==> no output
        lsgstStructs9 = gstcircuits.make_lsgst_structs(self.opLabels,
                                                       self.strs,
                                                       self.strs,
                                                       self.germs, [],
                                                       include_lgst=False)
        self.assertEqual(len(lsgstStructs9), 0)

        # checks against data
        lgst_strings = cc.create_lgst_circuits(self.strs, self.strs,
                                               self.opLabels)
        lsgstStructs10 = gstcircuits.make_lsgst_structs(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            dscheck=self.ds,
            action_if_missing="drop",
            verbosity=4)
        self.assertEqual([Circuit(('Gx', ))], list(lsgstStructs10[-1]))
Example #16
0
    def test_lsgst_lists_structs(self):
        maxLens = [1, 2]
        lsgstLists = stdlists.make_lsgst_lists(
            std1Q_XY.target_model(),
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fidPairs=None,
            truncScheme="whole germ powers")  # also try a Model as first arg
        lsgstStructs = stdlists.make_lsgst_structs(
            std1Q_XY.target_model(),
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fidPairs=None,
            truncScheme="whole germ powers")  # also try a Model as first arg
        self.assertEqual(set(lsgstLists[-1]), set(lsgstStructs[-1].allstrs))

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

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

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

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

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

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

        lsgstLists8 = stdlists.make_lsgst_lists(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fidPairs=self.testFidPairs,
            truncScheme="whole germ powers",
            keepFraction=0.7,
            keepSeed=1234)
        lsgstStructs8 = stdlists.make_lsgst_structs(
            self.opLabels,
            self.strs,
            self.strs,
            self.germs,
            maxLens,
            fidPairs=self.testFidPairs,
            truncScheme="whole germ powers",
            keepFraction=0.7,
            keepSeed=1234)
        self.assertEqual(set(lsgstLists8[-1]), set(lsgstStructs8[-1].allstrs))
        # TODO assert correctness

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

        # checks against datasets
        lgst_strings = cc.list_lgst_circuits(self.strs, self.strs,
                                             self.opLabels)
        lsgstStructs10 = stdlists.make_lsgst_structs(self.opLabels,
                                                     self.strs,
                                                     self.strs,
                                                     self.germs,
                                                     maxLens,
                                                     dscheck=self.ds,
                                                     actionIfMissing="drop",
                                                     verbosity=4)
        self.assertEqual([Circuit(('Gx', ))], lsgstStructs10[-1].allstrs)