コード例 #1
0
    def test_circuitsim_stabilizer_1Qcheck(self):
        from pygsti.modelpacks import smq1Q_XYI as stdChk

        maxLengths = [1, 2, 4]
        listOfExperiments = pygsti.circuits.create_lsgst_circuits(
            stdChk.target_model(), stdChk.prep_fiducials(),
            stdChk.meas_fiducials(), stdChk.germs(), maxLengths)
        #listOfExperiments = pygsti.circuits.to_circuits([ ('Gcnot','Gxi') ])
        #listOfExperiments = pygsti.circuits.to_circuits([ ('Gxi','Gcphase','Gxi','Gix') ])

        mdl_normal = stdChk.target_model()
        self.assertTrue(mdl_normal._evotype == "densitymx")

        mdl_clifford = stdChk.target_model("static clifford",
                                           evotype='stabilizer')
        mdl_clifford.sim = "map"  # only map sim works for stabilizer evotype
        #print(mdl_clifford['Gcnot'])
        #mdl_clifford.set_all_parameterizations('static unitary') # reduces dim...
        #self.assertTrue(mdl_clifford._evotype == "statevec")
        #mdl_clifford.set_all_parameterizations('clifford')
        self.assertTrue(mdl_clifford._evotype == "stabilizer")

        for opstr in listOfExperiments:
            #print(str(opstr))
            p_normal = mdl_normal.probabilities(opstr)
            p_clifford = mdl_clifford.probabilities(opstr)
            #p_clifford = bprobs[opstr]
            for outcm in p_normal.keys():
                if abs(p_normal[outcm] - p_clifford[outcm]) > 1e-8:
                    print(str(opstr), " ERR: \n", p_normal, "\n", p_clifford)
                    self.assertTrue(False)
        print("Done checking %d sequences!" % len(listOfExperiments))
コード例 #2
0
    def test_stdgst_prunedpath(self):
        # Using term-based (path integral) calculation with path pruning
        # This performs a map-based unitary evolution along each path.
        target_model = std.target_model("static unitary", evotype='statevec')
        target_model.set_all_parameterizations("H+S")
        target_model.sim = pygsti.forwardsims.TermForwardSimulator(
            mode='pruned',
            max_order=3,
            desired_perr=0.01,
            allowed_perr=0.1,
            max_paths_per_outcome=1000,
            perr_heuristic='meanscaled',
            max_term_stages=5)
        target_model.from_vector(
            1e-10 * np.ones(target_model.num_params)
        )  # to seed term calc (starting with perfect zeros causes trouble)
        results = pygsti.run_long_sequence_gst(self.ds,
                                               target_model,
                                               std.prep_fiducials(),
                                               std.meas_fiducials(),
                                               std.germs(),
                                               self.maxLengths,
                                               verbosity=3)

        #RUN BELOW LINES TO SAVE GATESET (SAVE)
        if regenerate_references():
            pygsti.serialization.json.dump(
                results.estimates[results.name].models['go0'],
                open(compare_files + "/test1Qcalc_std_prunedpath.model", 'w'))

        print("MISFIT nSigma = ",
              results.estimates[results.name].misfit_sigma())
        self.assertAlmostEqual(results.estimates[results.name].misfit_sigma(),
                               1,
                               delta=1.0)
コード例 #3
0
    def test_stdgst_map(self):
        # Using map-based calculation
        target_model = std.target_model()
        target_model.set_all_parameterizations("CPTP")
        target_model.sim = 'map'
        results = pygsti.run_long_sequence_gst(self.ds,
                                               target_model,
                                               std.prep_fiducials(),
                                               std.meas_fiducials(),
                                               std.germs(),
                                               self.maxLengths,
                                               verbosity=4)

        print("MISFIT nSigma = ",
              results.estimates[results.name].misfit_sigma())
        self.assertAlmostEqual(results.estimates[results.name].misfit_sigma(),
                               1.0,
                               delta=2.0)
        mdl_compare = pygsti.serialization.json.load(
            open(compare_files + "/test1Qcalc_std_exact.model"))

        gsEstimate = results.estimates[results.name].models['go0'].copy()
        gsEstimate.set_all_parameterizations("full")
        gsEstimate = pygsti.algorithms.gaugeopt_to_target(
            gsEstimate, mdl_compare)
        self.assertAlmostEqual(gsEstimate.frobeniusdist(mdl_compare),
                               0,
                               places=0)
コード例 #4
0
    def test_stdgst_terms(self):
        # Using term-based (path integral) calculation
        # This performs a map-based unitary evolution along each path.
        target_model = std.target_model("static unitary", evotype='statevec')
        target_model.set_all_parameterizations("H+S")
        target_model.sim = pygsti.forwardsims.TermForwardSimulator(
            mode='taylor-order', max_order=1)
        target_model._print_gpindices()
        target_model.from_vector(
            1e-10 * np.ones(target_model.num_params)
        )  # to seed term calc (starting with perfect zeros causes trouble)
        results = pygsti.run_long_sequence_gst(self.ds,
                                               target_model,
                                               std.prep_fiducials(),
                                               std.meas_fiducials(),
                                               std.germs(),
                                               self.maxLengths,
                                               verbosity=4)

        #RUN BELOW LINES TO SAVE GATESET (SAVE)
        if regenerate_references():
            pygsti.serialization.json.dump(
                results.estimates[results.name].models['go0'],
                open(compare_files + "/test1Qcalc_std_terms.model", 'w'))

        print("MISFIT nSigma = ",
              results.estimates[results.name].misfit_sigma())
        self.assertAlmostEqual(results.estimates[results.name].misfit_sigma(),
                               1,
                               delta=1.0)
        mdl_compare = pygsti.serialization.json.load(
            open(compare_files + "/test1Qcalc_std_terms.model"))

        # can't easily gauge opt b/c term-based models can't be converted to "full"
        #mdl_compare.set_all_parameterizations("full")
        #
        #gsEstimate = results.estimates[results.name].models['go0'].copy()
        #gsEstimate.set_all_parameterizations("full")
        #gsEstimate = pygsti.algorithms.gaugeopt_to_target(gsEstimate, mdl_compare)
        #self.assertAlmostEqual( gsEstimate.frobeniusdist(mdl_compare), 0, places=0)

        #A direct vector comparison works if python (&numpy?) versions are identical, but
        # gauge freedoms make this incorrectly fail in other cases - so just check sigmas
        print("VEC DIFF = ",
              (results.estimates[results.name].models['go0'].to_vector() -
               mdl_compare.to_vector()))
        self.assertAlmostEqual(np.linalg.norm(
            results.estimates[results.name].models['go0'].to_vector() -
            mdl_compare.to_vector()),
                               0,
                               places=1)
コード例 #5
0
    def test_MPI_probs(self):
        comm = self.ralloc.comm

        #Create some model
        mdl = std.target_model()
        mdl.kick(0.1, seed=1234)

        #Get some operation sequences
        maxLengths = [1, 2, 4]
        circuits = pygsti.circuits.create_lsgst_circuits(
            list(std.target_model().operations.keys()), std.prep_fiducials(),
            std.meas_fiducials(), std.germs(), maxLengths)

        #Check all-spam-label bulk probabilities
        def compare_prob_dicts(a, b, indices=None):
            for opstr in circuits:
                for outcome in a[opstr].keys():
                    if indices is None:
                        assert (np.linalg.norm(a[opstr][outcome] -
                                               b[opstr][outcome]) < 1e-6)
                    else:
                        for i in indices:
                            assert (np.linalg.norm(a[opstr][outcome][i] -
                                                   b[opstr][outcome][i]) <
                                    1e-6)

        # non-split tree => automatically adjusts wrt_block_size to accomodate
        #                    the number of processors
        serial = mdl.sim.bulk_probs(circuits, clip_to=(-1e6, 1e6))
        parallel = mdl.sim.bulk_probs(circuits,
                                      clip_to=(-1e6, 1e6),
                                      resource_alloc=self.ralloc)
        if comm is None or comm.rank == 0:  # output is only given on root proc
            compare_prob_dicts(serial, parallel)

        serial = mdl.sim.bulk_dprobs(circuits)
        parallel = mdl.sim.bulk_dprobs(circuits, resource_alloc=self.ralloc)
        if comm is None or comm.rank == 0:  # output is only given on root proc
            compare_prob_dicts(serial, parallel)

        serial = mdl.sim.bulk_hprobs(circuits)
        parallel = mdl.sim.bulk_hprobs(circuits, resource_alloc=self.ralloc)
        if comm is None or comm.rank == 0:  # output is only given on root proc
            compare_prob_dicts(serial, parallel, (0, 1, 2))
コード例 #6
0
    def test_MPI_products(self):
        comm = self.ralloc.comm

        #Create some model
        mdl = std.target_model()

        mdl.kick(0.1, seed=1234)

        #Get some operation sequences
        maxLengths = [1, 2, 4, 8]
        gstrs = pygsti.circuits.create_lsgst_circuits(std.target_model(),
                                                      std.fiducials(),
                                                      std.fiducials(),
                                                      std.germs(), maxLengths)

        #Check bulk products

        #bulk_product - no parallelization unless layout is split
        serial = mdl.sim.bulk_product(gstrs, scale=False)
        parallel = mdl.sim.bulk_product(gstrs,
                                        scale=False,
                                        resource_alloc=self.ralloc)
        assert (np.linalg.norm(serial - parallel) < 1e-6)

        serial_scl, sscale = mdl.sim.bulk_product(gstrs, scale=True)
        parallel, pscale = mdl.sim.bulk_product(gstrs,
                                                scale=True,
                                                resource_alloc=self.ralloc)
        assert (np.linalg.norm(serial_scl * sscale[:, None, None] -
                               parallel * pscale[:, None, None]) < 1e-6)

        #bulk_dproduct - no split tree => parallel by col
        serial = mdl.sim.bulk_dproduct(gstrs, scale=False)
        parallel = mdl.sim.bulk_dproduct(gstrs,
                                         scale=False,
                                         resource_alloc=self.ralloc)
        assert (np.linalg.norm(serial - parallel) < 1e-6)

        serial_scl, sscale = mdl.sim.bulk_dproduct(gstrs, scale=True)
        parallel, pscale = mdl.sim.bulk_dproduct(gstrs,
                                                 scale=True,
                                                 resource_alloc=self.ralloc)
        assert (np.linalg.norm(serial_scl * sscale[:, None, None, None] -
                               parallel * pscale[:, None, None, None]) < 1e-6)
コード例 #7
0
    def test_stdgst_matrix(self):
        # Using matrix-based calculations
        target_model = std.target_model()
        target_model.set_all_parameterizations("CPTP")
        target_model.sim = 'matrix'  # the default for 1Q, so we could remove this line
        results = pygsti.run_long_sequence_gst(self.ds,
                                               target_model,
                                               std.prep_fiducials(),
                                               std.meas_fiducials(),
                                               std.germs(),
                                               self.maxLengths,
                                               verbosity=4)

        #CHECK that copy gives identical models - this is checked by other
        # unit tests but here we're using a true "GST model" - so do it again:
        print("CHECK COPY")
        mdl = results.estimates[results.name].models['go0']
        mdl_copy = mdl.copy()
        print(mdl.strdiff(mdl_copy))
        self.assertAlmostEqual(mdl.frobeniusdist(mdl_copy), 0, places=2)

        #RUN BELOW LINES TO SAVE GATESET (SAVE)
        if regenerate_references():
            pygsti.serialization.json.dump(
                results.estimates[results.name].models['go0'],
                open(compare_files + "/test1Qcalc_std_exact.model", 'w'))

        print("MISFIT nSigma = ",
              results.estimates[results.name].misfit_sigma())
        self.assertAlmostEqual(results.estimates[results.name].misfit_sigma(),
                               1.0,
                               delta=2.0)
        mdl_compare = pygsti.serialization.json.load(
            open(compare_files + "/test1Qcalc_std_exact.model"))

        #gauge opt before compare
        gsEstimate = results.estimates[results.name].models['go0'].copy()
        gsEstimate.set_all_parameterizations("full")
        gsEstimate = pygsti.algorithms.gaugeopt_to_target(
            gsEstimate, mdl_compare)
        print(gsEstimate.strdiff(mdl_compare))
        self.assertAlmostEqual(gsEstimate.frobeniusdist(mdl_compare),
                               0,
                               places=1)
コード例 #8
0
    def run_fills(self, sim, natoms, nparams):
        comm = self.ralloc.comm

        #Create some model
        mdl = std.target_model()
        mdl.kick(0.1, seed=1234)

        #Get some operation sequences
        maxLengths = [1]
        circuits = pygsti.circuits.create_lsgst_circuits(
            list(std.target_model().operations.keys()), std.prep_fiducials(),
            std.meas_fiducials(), std.germs(), maxLengths)
        nP = mdl.num_params

        if sim == 'map':
            mdl.sim = pygsti.forwardsims.MapForwardSimulator(
                num_atoms=natoms, param_blk_sizes=(nparams, nparams))
        elif sim == 'matrix':
            mdl.sim = pygsti.forwardsims.MatrixForwardSimulator(
                num_atoms=natoms, param_blk_sizes=(nparams, nparams))
        else:
            raise RuntimeError(
                "Improper sim type passed by test_fills_generator")

        serial_layout = mdl.sim.create_layout(circuits,
                                              array_types=('E', 'EP', 'EPP'),
                                              derivative_dimension=nP)

        nE = serial_layout.num_elements
        nC = len(circuits)

        vp_serial = np.empty(nE, 'd')
        vdp_serial = np.empty((nE, nP), 'd')
        vhp_serial = np.empty((nE, nP, nP), 'd')

        mdl.sim.bulk_fill_probs(vp_serial, serial_layout)
        mdl.sim.bulk_fill_dprobs(vdp_serial, serial_layout)
        mdl.sim.bulk_fill_hprobs(vhp_serial, serial_layout)

        #Note: when there are multiple atoms, the serial_layout returned above may not preserve
        # the original circuit ordering, i.e., serial_layout.circuits != circuits.  The global
        # layout does have this property, and so we use it to avoid having to lookup which circuit
        # is which index in serial_layout.  No gathering is needed, since there only 1 processor.
        global_serial_layout = serial_layout.global_layout

        #Use a parallel layout to compute the same probabilities & their derivatives
        local_layout = mdl.sim.create_layout(circuits,
                                             array_types=('E', 'EP', 'EPP'),
                                             derivative_dimension=nP,
                                             resource_alloc=self.ralloc)

        vp_local = local_layout.allocate_local_array('e', 'd')
        vdp_local = local_layout.allocate_local_array('ep', 'd')
        vhp_local = local_layout.allocate_local_array('epp', 'd')

        mdl.sim.bulk_fill_probs(vp_local, local_layout)
        mdl.sim.bulk_fill_dprobs(vdp_local, local_layout)
        mdl.sim.bulk_fill_hprobs(vhp_local, local_layout)

        #Gather data to produce arrays for the "global" layout (global_parallel_layout should be the same on all procs)
        # but only on proc 0
        global_parallel_layout = local_layout.global_layout
        vp_global_parallel = local_layout.gather_local_array('e', vp_local)
        vdp_global_parallel = local_layout.gather_local_array('ep', vdp_local)
        vhp_global_parallel = local_layout.gather_local_array('epp', vhp_local)

        #Free the local arrays when we're done with them (they could be shared mem)
        local_layout.free_local_array(vp_local)
        local_layout.free_local_array(vdp_local)
        local_layout.free_local_array(vhp_local)

        #Compare the two, but note that different layouts may order the elements differently,
        # so we can't just compare the arrays directly - we have to use the layout to map
        # circuit index -> element indices:
        if comm is None or comm.rank == 0:
            for i, opstr in enumerate(circuits):
                assert (np.linalg.norm(vp_global_parallel[
                    global_parallel_layout.indices_for_index(i)] - vp_serial[
                        global_serial_layout.indices_for_index(i)]) < 1e-6)
                assert (np.linalg.norm(vdp_global_parallel[
                    global_parallel_layout.indices_for_index(i)] - vdp_serial[
                        global_serial_layout.indices_for_index(i)]) < 1e-6)
                assert (np.linalg.norm(vhp_global_parallel[
                    global_parallel_layout.indices_for_index(i)] - vhp_serial[
                        global_serial_layout.indices_for_index(i)]) < 1e-6)
コード例 #9
0
 def test_creation(self):
     gst.GateSetTomographyDesign(smq1Q_XYI.processor_spec(),
                                 smq1Q_XYI.prep_fiducials(),
                                 smq1Q_XYI.meas_fiducials(),
                                 smq1Q_XYI.germs(), [1, 2])
コード例 #10
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.03,
                                                        spam_noise=0.001)
        cls.listOfExperiments = pygsti.circuits.create_lsgst_circuits(
            std.target_model(), std.prep_fiducials(), std.meas_fiducials(),
            std.germs(), cls.maxLengths)

        #RUN BELOW FOR DATAGEN (SAVE)
        if regenerate_references():
            ds = pygsti.data.simulate_data(cls.mdl_datagen,
                                           cls.listOfExperiments,
                                           num_samples=1000,
                                           sample_error="multinomial",
                                           seed=1234)
            ds.save(compare_files + "/calcMethods1Q.dataset")

        #DEBUG TEST- was to make sure data files have same info -- seemed ultimately unnecessary
        #ds_swp = pygsti.objects.DataSet(file_to_load_from=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.read_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.data.DataSet(file_to_load_from=compare_files +
                                     "/calcMethods1Q.dataset")

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

        #Create a reduced set of fiducials and germs
        op_labels = [L('Gx', 0), L('Gy', 0)]  # 1Q gate labels
        fids1Q = std1Q_XY.fiducials[
            1:2]  # for speed, just take 1 non-empty fiducial
        cls.redmod_fiducials = [
            Circuit([], line_labels=(0, ))
        ]  # special case for empty fiducial (need to change line label)
        for i in range(cls.nQubits):
            cls.redmod_fiducials.extend(
                pygsti.circuits.manipulate_circuits(fids1Q,
                                                    [((L('Gx'), ),
                                                      (L('Gx', i), )),
                                                     ((L('Gy'), ),
                                                      (L('Gy', i), ))]))
        #print(redmod_fiducials, "Fiducials")

        cls.redmod_germs = pygsti.circuits.to_circuits([(gl, )
                                                        for gl in op_labels])
        cls.redmod_maxLs = [1]
        expList = pygsti.circuits.create_lsgst_circuits(
            op_labels, cls.redmod_fiducials, cls.redmod_fiducials,
            cls.redmod_germs, cls.redmod_maxLs)

        #RUN BELOW FOR DATAGEN (SAVE)
        if regenerate_references():
            redmod_ds = pygsti.data.simulate_data(cls.mdl_redmod_datagen,
                                                  expList,
                                                  1000,
                                                  "round",
                                                  seed=1234)
            redmod_ds.save(compare_files + "/calcMethods1Q_redmod.dataset")

        cls.redmod_ds = pygsti.data.DataSet(file_to_load_from=compare_files +
                                            "/calcMethods1Q_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_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.circuits.Circuit((('Gxpi2', 0), ('Gypi2', 0)))
        # now Circuit adds qubit labels... pygsti.circuits.Circuit(layer_labels=('Gx','Gy'), num_lines=1) # 1-qubit circuit
        cls.circuit3 = pygsti.circuits.Circuit(layer_labels=[('Gxpi', 0),
                                                             ('Gypi', 1),
                                                             ('Gcnot', 1, 2)],
                                               num_lines=3)  # 3-qubit circuit

        os.chdir(origDir)  # return to original directory