コード例 #1
0
 def do_sample(self, samples, circuit, *args, **kwargs) -> QubitWaveFunction:
     n_qubits = self.n_qubits
     if "pyquil_backend" in kwargs:
         pyquil_backend = kwargs["pyquil_backend"]
         if isinstance(pyquil_backend, dict):
             qc = get_qc(**pyquil_backend)
         else:
             qc = get_qc(pyquil_backend)
     else:
         qc = get_qc('{}q-qvm'.format(str(n_qubits)))
     p = circuit
     p.wrap_in_numshots_loop(samples)
     stacked = qc.run(p, memory_map=self.resolver)
     return self.convert_measurements(stacked)
コード例 #2
0
def main():
    noisy_qc = apply_noise(get_qc("3q-qvm"))
    em_qc = apply_em(get_qc("3q-qvm"))

    lengths = np.arange(2, 100, 5)

    em_data = run_with_qc(em_qc, lengths)
    noisy_data = run_with_qc(noisy_qc, lengths)

    plt.xlabel('Circuit depth')
    plt.ylabel('Fidelity')
    plt.plot(lengths, noisy_data, 'o-', label="Only Noise")
    plt.plot(lengths, em_data, 'o-', label="Noise + EM")
    plt.legend()
    plt.show()
コード例 #3
0
ファイル: vqe.py プロジェクト: maghamalyan/em-pyquil
def main():
    noisy_qc = apply_noise(get_qc("3q-qvm"))
    em_qc = apply_em(get_qc("3q-qvm"))

    angle_range = np.linspace(0.0, 2 * np.pi, 20)

    noisy_data = run_with_qc(noisy_qc, angle_range)
    em_data = run_with_qc(em_qc, angle_range)

    plt.xlabel('Angle [radians]')
    plt.ylabel('Expectation value')
    plt.plot(angle_range, noisy_data, label="Only Noise")
    plt.plot(angle_range, em_data, label="EM + Noise")
    plt.legend()
    plt.show()
コード例 #4
0
def test_qc_joint_calibration(forest):
    # noise model with 95% symmetrized readout fidelity per qubit
    noise_model = asymmetric_ro_model([0, 1], 0.945, 0.955)
    qc = get_qc("2q-qvm")
    qc.qam.noise_model = noise_model

    # |01> state program
    p = Program()
    p += RESET()
    p += X(0)
    p.wrap_in_numshots_loop(10000)

    # ZZ experiment
    sz = ExperimentSetting(
        in_state=sZ(0) * sZ(1), out_operator=sZ(0) * sZ(1), additional_expectations=[[0], [1]]
    )
    e = Experiment(settings=[sz], program=p)

    results = qc.experiment(e)

    # ZZ expectation value for state |01> with 95% RO fid on both qubits is about -0.81
    assert np.isclose(results[0].expectation, -0.81, atol=0.01)
    assert results[0].total_counts == 40000
    # Z0 expectation value for state |01> with 95% RO fid on both qubits is about -0.9
    assert np.isclose(results[0].additional_results[0].expectation, -0.9, atol=0.01)
    assert results[0].additional_results[1].total_counts == 40000
    # Z1 expectation value for state |01> with 95% RO fid on both qubits is about 0.9
    assert np.isclose(results[0].additional_results[1].expectation, 0.9, atol=0.01)
    assert results[0].additional_results[1].total_counts == 40000
コード例 #5
0
    def execute(self, options=execute_options):
        """
		Executes the classifier protocol, including
			* preprocessing
			* data encoding
			* data processing
			* postprocessing

		Returns:
			label: float
				Value between 0 and 1 representing the output
				of the binary classifier.
		"""

        # Set up connection
        forest_cxn = get_qc('9q-generic-qvm')

        nruns = options['nruns']

        # Compile circuit
        qnn_wrapped_circuit = self.qcircuit.wrap_in_numshots_loop(nruns)
        qnn_native_circuit = forest_cxn.compiler.\
          quil_to_native_quil(qnn_wrapped_circuit)
        qnn_circuit_executable = forest_cxn.compiler.\
          native_quil_to_executable(qnn_native_circuit)

        # Execute circuit
        result = forest_cxn.run(qnn_circuit_executable)

        # Postprocess the measurement outcomes
        output = self.classical_post(result)

        return output
コード例 #6
0
def PrintAllDataToFiles(data_type, max_qubits, *args):
    '''
	This function prints all data samples to files, for either Quantum or Classical Data
	for all number of qubits between 2 and max_qubits.
	'''
    N_sample_trials = [
        10, 20, 30, 40, 50, 80, 100, 200, 300, 400, 500, 600, 700, 1000, 2000,
        3000, 4000, 5000, 6000, 8000, 10000
    ]

    for N_qubits in range(2, max_qubits):
        for N_samples in N_sample_trials:
            if data_type == 'Quantum_Data':
                qc = get_qc('%iq-qvm' % N_qubits, as_qvm=True)
                circuit_choice = args[0]

                print(
                    'Quantum Data is printing for %i qubits on qc %s using circuit choice %s'
                    % (N_qubits, qc.name, circuit_choice))
                PrintDataToFiles('Quantum_Data', N_samples, qc, circuit_choice,
                                 N_qubits)

            elif data_type == 'Bernoulli_Data':
                qc = None
                circuit_choice = None
                print('Bernoulli Data is printing for %i qubits' % N_qubits)
                PrintDataToFiles('Bernoulli_Data', N_samples, qc,
                                 circuit_choice, N_qubits)
コード例 #7
0
def maxcut_qaoa(graph,
                steps=1,
                rand_seed=None,
                connection=None,
                samples=None,
                initial_beta=None,
                initial_gamma=None,
                minimizer_kwargs=None,
                vqe_option=None):

    if not isinstance(graph, nx.Graph) and isinstance(graph, list):
        maxcut_graph = nx.Graph()
        for edge in graph:
            maxcut_graph.add_edge(*edge)
        graph = maxcut_graph.copy()
        nx.draw(graph)

    cost_operators = []
    driver_operators = []

    #Creates cost hamiltonian from weights + nodes, adds accountability for weights from original rigetti QAOA code
    for i, j in graph.edges():
        weight = graph.get_edge_data(i, j)['weight'] / largest_weight
        cost_operators.append(
            PauliTerm("Z", i, weight) * PauliTerm("Z", j) +
            PauliTerm("I", 0, -weight))

    #creates driver hamiltonian
    for i in graph.nodes():
        driver_operators.append(PauliSum([PauliTerm("X", i, -1.0)]))

    if connection is None:
        connection = get_qc(f"{len(graph.nodes)}q-qvm")

    if minimizer_kwargs is None:
        minimizer_kwargs = {
            'method': 'Nelder-Mead',
            'options': {
                'ftol': 1.0e-2,
                'xtol': 1.0e-2,
                'disp': False
            }
        }
    if vqe_option is None:
        vqe_option = {'disp': print, 'return_all': True, 'samples': samples}

    qaoa_inst = QAOA(connection,
                     list(graph.nodes()),
                     steps=steps,
                     cost_ham=cost_operators,
                     ref_ham=driver_operators,
                     store_basis=True,
                     rand_seed=rand_seed,
                     init_betas=initial_beta,
                     init_gammas=initial_gamma,
                     minimizer=minimize,
                     minimizer_kwargs=minimizer_kwargs,
                     vqe_options=vqe_option)

    return qaoa_inst
コード例 #8
0
    def do_sample(self, samples, circuit, *args,
                  **kwargs) -> QubitWaveFunction:
        """
        Helper function, sampling an individual circuit.

        Parameters
        ----------
        samples: int:
            the number of samples of measurement to make.
        circuit:
            the circuit to sample.
        args
        kwargs

        Returns
        -------
        QubitWaveFunction:
            the result of sampled measurement, as a tequila wavefunction.
        """

        n_qubits = self.n_qubits
        p = circuit

        if self.device is None:
            qc = get_qc('{}q-qvm'.format(str(n_qubits)))
            p.wrap_in_numshots_loop(samples)
        else:
            qc = self.device
            p = qc.compile(p)
            p.attributes['num_shots'] = samples
        stacked = qc.run(p, memory_map=self.resolver)
        return self.convert_measurements(stacked)
コード例 #9
0
    def __init__(self,
                 group=None,
                 target=None,
                 name=None,
                 args=(),
                 kwargs=None):
        threading.Thread.__init__(self, group=group, target=target, name=name)
        self.setDaemon(True)
        self.args = args
        self.kwargs = kwargs
        self.queue = Queue()
        # record sim or not here!
        self.simulator = sim
        self.qc = get_qc("9q-square-qvm")
        self.qubits = None

        self.QCS = os.path.isfile("/home/forest/.forest_config")

        if self.QCS:
            self.ExistingQVM = True
        else:
            try:
                requests.get("http://localhost:5000/")
            except requests.exceptions.ConnectionError:
                self.ExistingQVM = False
            else:
                self.ExistingQVM = True

            if not self.ExistingQVM:
                self.compprocess = sp.Popen(["quilc", "-S"], close_fds=True)
                self.servprocess = sp.Popen(["qvm", "-S"], close_fds=True)
コード例 #10
0
def maxcut_qaoa_weighted(graph, steps=1, rand_seed=None, connection=None, samples=None,
                initial_beta=None, initial_gamma=None, minimizer_kwargs=None,
                vqe_option=None):
    """
    Max cut set up method

    :param graph: Graph definition. Either networkx or list of tuples
    :param steps: (Optional. Default=1) Trotterization order for the QAOA algorithm.
    :param rand_seed: (Optional. Default=None) random seed when beta and gamma angles
        are not provided.
    :param connection: (Optional) connection to the QVM. Default is None.
    :param samples: (Optional. Default=None) VQE option. Number of samples
        (circuit preparation and measurement) to use in operator averaging.
    :param initial_beta: (Optional. Default=None) Initial guess for beta parameters.
    :param initial_gamma: (Optional. Default=None) Initial guess for gamma parameters.
    :param minimizer_kwargs: (Optional. Default=None). Minimizer optional arguments.  If None set to
        ``{'method': 'Nelder-Mead', 'options': {'ftol': 1.0e-2, 'xtol': 1.0e-2, 'disp': False}``
    :param vqe_option: (Optional. Default=None). VQE optional arguments.  If None set to
        ``vqe_option = {'disp': print_fun, 'return_all': True, 'samples': samples}``

    """
    if not isinstance(graph, nx.Graph) and isinstance(graph, list):
        maxcut_graph = nx.Graph()
        maxcut_graph.add_weighted_edges_from(graph)
#        for edge in graph:
#            maxcut_graph.add_edge(*edge)
        graph = maxcut_graph.copy()

    cost_operators = []
    driver_operators = []
    for i, j, w in graph.edges(data=True):
        print(i,j,w)
        value=w["weight"]
        cost_operators.append(value*PauliTerm("Z", i, 0.5)*PauliTerm("Z", j) + PauliTerm("I", 0, -0.5))
    for i in graph.nodes():
        driver_operators.append(PauliSum([PauliTerm("X", i, -1.0)]))

    if connection is None:
        connection = get_qc(f"{len(graph.nodes)}q-qvm")

    if minimizer_kwargs is None:
        minimizer_kwargs = {'method': 'Nelder-Mead',
                            'options': {'ftol': 1.0e-2, 'xtol': 1.0e-2,
                                        'disp': False}}
    if vqe_option is None:
        vqe_option = {'disp': print, 'return_all': True,
                      'samples': samples}

    qaoa_inst = QAOA(connection, list(graph.nodes()), steps=steps, cost_ham=cost_operators,
                     ref_ham=driver_operators, store_basis=True,
                     rand_seed=rand_seed,
                     init_betas=initial_beta,
                     init_gammas=initial_gamma,
                     minimizer=minimize,
                     minimizer_kwargs=minimizer_kwargs,
                     vqe_options=vqe_option)

    return qaoa_inst
コード例 #11
0
    def generate_rigetti(self):
        import pyquil
        from pyquil.quil import Program
        from pyquil.gates import H, RZ, RX, RY, CNOT, MEASURE, RESET
        from pyquil.api import get_qc
        self.rigetti_circuits_list=[]
        print("Creating Pyquil program list...")
        self.logfile.write("Creating Pyquil program list...")
        for circuit in self.circuits_list:
            p = pyquil.Program(RESET()) #compressed program
            ro = p.declare('ro', memory_type='BIT', memory_size=self.num_qubits)
            for gate in circuit.gates:
                if gate.name in "H":
                    p.inst(pyquil.gates.H(gate.qubits[0]))
                elif gate.name in "RZ":
                    p.inst(pyquil.gates.RZ(gate.angles[0],gate.qubits[0]))
                elif gate.name in "RX":
                    p.inst(pyquil.gates.RX(gate.angles[0],gate.qubits[0]))
                elif gate.name in "CNOT":
                    p.inst(pyquil.gates.CNOT(gate.qubits[0],gate.qubits[1]))
            for i in range(self.num_qubits):
                p.inst(pyquil.gates.MEASURE(i,ro[i]))
            p.wrap_in_numshots_loop(self.shots)
            self.rigetti_circuits_list.append(p)

        if "y" in self.compile:
            qc=get_qc(self.device_choice)
            if self.JZ != 0 and self.JX==self.JY==0 and self.h_ext!=0 and self.ext_dir=="X" and self.auto_ds_compile=="y":
                #TFIM
                print("TFIM detected, enabling DS compiler")
                self.logfile.write("TFIM detected, enabling DS compiler")
                temp=[]
                for circuit in self.rigetti_circuits_list:
                    temp.append(ds_compile(circuit,self.backend,self.shots))
                self.rigetti_circuits_list=temp

            elif self.default_compiler in "ds":
                temp=[]
                print("Compiling circuits...")
                self.logfile.write("Compiling circuits...")
                for circuit in self.rigetti_circuits_list:
                    temp.append(ds_compile(circuit,self.backend,self.shots))
                self.rigetti_circuits_list=temp
                print("Circuits compiled successfully")
                self.logfile.write("Circuits compiled successfully")
            elif self.default_compiler in "native":
                temp=[]
                print("Transpiling circuits...")
                self.logfile.write("Transpiling circuits...")
                for circuit in self.rigetti_circuits_list:
                    circ = qc.compile(circuit)
                    temp.append(circ)
                self.rigetti_circuits_list=temp
                print("Circuits transpiled successfully")
                self.logfile.write("Circuits transpiled successfully")

        print("Pyquil program list created successfully")
        self.logfile.write("Pyquil program list created successfully")
コード例 #12
0
def PrintCircuitParamsToFile(random_seed, circuit_choice):
    quantum_computers = [
        get_qc('%iq-qvm' % N_qubits, as_qvm=True) for N_qubits in range(2, 7)
    ]
    for qc in quantum_computers:
        device_name = qc.name
        qubits = qc.qubits()
        N_qubits = len(qubits)
        circuit_params = NetworkParams(qc, random_seed)
        np.savez('data/Parameters_%iQbs_%sCircuit_%sDevice.npz' % (N_qubits, circuit_choice, device_name),\
           J = circuit_params['J'], b = circuit_params['b'], gamma = circuit_params['gamma'], delta = circuit_params['delta'])
コード例 #13
0
    def retrieve_device(self, device):
        """
        return an initialized pyquil quantum computer (or None)
        Parameters
        ----------
        device:
            pyquil.api.QuantumComputer, or arguments that can pass to pyquil.get_qc

        Returns
        -------
        pyquil.api.QuantumComputer
            an instantiated device object for pyquil simulation or execution.
        """
        use_device_noise = (self.noise == 'device')
        if device is None:
            return None
        if isinstance(device, str):
            try:
                back = get_qc(device, noisy=use_device_noise)
                return back
            except:
                try:
                    back = get_qc(device, as_qvm=True, noisy=use_device_noise)
                    return back
                except:
                    raise TequilaException(
                        'could not obtain device from string; received {}'.
                        format(device))
        elif isinstance(device, pyquil.api.QuantumComputer):
            return device
        elif isinstance(device, dict):
            try:
                return get_qc(**device)
            except:
                raise TequilaException(
                    'could not initialize device from dict; received {}'.
                    format(device))
        else:
            raise TequilaException(
                'Uninterpretable object {} of type {} passed to check_device!'.
                format(device, type(device)))
コード例 #14
0
def rigetti_ising_qubo(G, func, optimizer, comp, p):
        qc = get_qc(comp)
        h, J = func(G)
        with suppress_stdout():
                x, energ, z = ising(h, J, num_steps=p, connection=qc, minimizer_kwargs = {'method': optimizer})
        """
        possible methods: COBYLA, SLSQP, TNC, CG, BFGS, Powell, Nelder-Mead, L-BFGS-B
        """
        file = open('ref_quil.txt', 'w')
        file.write(z.out())
        file.close()
        return x
コード例 #15
0
ファイル: simulator.py プロジェクト: wugaxp/qe-forest
def get_forest_connection(device_name):
    '''Get a connection to a forest backend

    Args:
        device_name (string): the device to connect to

    Returns:
        A connection to either a pyquil simulator or a QPU
    '''
    if device_name == 'wavefunction-simulator':
        return WavefunctionSimulator()
    else:
        return get_qc(device_name)
コード例 #16
0
def get_forest_connection(device_name: str, seed=None):
    """Get a connection to a forest backend

    Args:
        device_name: the device to connect to

    Returns:
        A connection to either a pyquil simulator or a QPU
    """
    if device_name == "wavefunction-simulator":
        return WavefunctionSimulator(random_seed=seed)
    else:
        return get_qc(device_name)
コード例 #17
0
def test_vqe_on_QVM():
    p0 = [3.1, -1.5, 0, 0]  # make it easier when sampling
    qvm = get_qc("2q-qvm")
    cost_fun = PrepareAndMeasureOnQVM(prepare_ansatz=prepare_ansatz,
                                      make_memory_map=lambda p: {"params": p},
                                      hamiltonian=hamiltonian,
                                      qvm=qvm,
                                      scalar_cost_function=True,
                                      nshots=4,
                                      base_numshots=50)
    out = minimize(cost_fun, p0, tol=1e-2, method="Cobyla")
    assert np.allclose(out['fun'], -1.3, rtol=1.1)
    assert out['success']
コード例 #18
0
ファイル: qae_engine.py プロジェクト: mridunanda/quantum
    def setup_forest_cxn(self, *args, **kwargs):
        """
        Sets up Forest connection to simulator or quantum device.
        Enter arguments for get_qc.

        :raises: NotImplementedError
        """
        try:
            self.forest_cxn = get_qc(*args, **kwargs)
            
            if isinstance(self.forest_cxn.qam, QVM):
                self.cxn_type = "QVM"
            elif isinstance(self.forest_cxn.qam, QPU):
                self.cxn_type = "QPU"
                self.compile_program = True
        except: 
            raise NotImplementedError("This qvm/qpu specification is invalid. Please see args for get_qc.")
コード例 #19
0
def PrintKernel(N_kernel_samples, kernel_choice, max_qubits):
    #print the required kernel out to a file, for all binary strings
    devices = [
        get_qc('%iq-qvm' % N_qubits, as_qvm=True)
        for N_qubits in range(2, max_qubits)
    ]

    for qc in devices:
        N_qubits = len(qc.qubits())
        print('This is qubit:', N_qubits)
        #The number of samples, N_samples = infinite if the exact kernel is being computed
        _, _, kernel_approx_dict, _ = KernelAllBinaryStrings(
            qc, N_kernel_samples, kernel_choice)

        KernelDictToFile(N_qubits, N_kernel_samples, kernel_approx_dict,
                         kernel_choice)
    return
コード例 #20
0
ファイル: backends.py プロジェクト: mtreinish/qiskit-mori
def create_backend(device_name, provider):
    try:
        dev = api.get_qc(device_name)
    except Exception:
        return None
    n_qubits = int(len(dev.qubits()))
    basis_gates = ''
    gates = [models.GateConfig()]
    if isinstance(dev.qam, api.QPU):
        simulator = False
    else:
        simulator = True
    max_shots = 1024
    conf = models.BackendConfiguration(device_name, '0.0.1', n_qubits,
                                       basis_gates, gates, False, simulator,
                                       False, False, False, max_shots)
    return MoriBackend(conf, provider, dev)
def test_vqe_on_QVM_QubitPlaceholders():
    qubit_mapping = {q0: 0, q1: 1}
    p0 = [3.1, -1.5, 0, 0]  # make it easier when sampling
    qvm = get_qc("2q-qvm")
    cost_fun = PrepareAndMeasureOnQVM(prepare_ansatz=prepare_ansatz,
                                      make_memory_map=lambda p: {"params": p},
                                      hamiltonian=hamiltonian,
                                      qvm=qvm,
                                      scalar_cost_function=True,
                                      base_numshots=50,
                                      nshots=4,
                                      enable_logging=True,
                                      qubit_mapping=qubit_mapping)
    out = scipy.optimize.minimize(cost_fun, p0, tol=1e-2, method="Cobyla")
    print(out)
    print(cost_fun.log)
    assert np.allclose(out['fun'], -4, rtol=1.1)
    assert out['success']
コード例 #22
0
    def __init__(self,
                 prepare_ansatz: Program,
                 make_memory_map: Callable[[Iterable], dict],
                 hamiltonian: PauliSum,
                 qvm: Union[QuantumComputer, str],
                 scalar_cost_function: bool = True,
                 nshots: int = 1,
                 base_numshots: int = 100,
                 qubit_mapping: Dict[QubitPlaceholder, Union[Qubit, int]] = None,
                 enable_logging: bool = False,
                 hamiltonian_is_diagonal: bool =False):

        self.scalar = scalar_cost_function
        self.nshots = nshots
        self.make_memory_map = make_memory_map

        if isinstance(qvm, str):
            qvm = get_qc(qvm)
        self.qvm = qvm

        if qubit_mapping is not None:
            prepare_ansatz = address_qubits(prepare_ansatz, qubit_mapping)
            ham = address_qubits_hamiltonian(hamiltonian, qubit_mapping)
        else:
            ham = hamiltonian

        if not hamiltonian_is_diagonal:
            self.hams = commuting_decomposition(ham)
        else:
            self.hams = [ham]

        self.exes = []
        for ham in self.hams:
            # need a different program for each of the self commuting hams
            p = prepare_ansatz.copy()
            append_measure_register(p,
                                    qubits=ham.get_qubits(),
                                    trials=base_numshots,
                                    ham=ham)
            self.exes.append(qvm.compile(p))

        if enable_logging:
            self.log = []
コード例 #23
0
    def check_device(self, device):
        """
        Verify if a device is valid.
        Parameters
        ----------
        device:
            a pyquil.api.QuantumComputer, a string which picks one out, or a dictionary that can pass to get_qc.
        Returns
        -------
        None

        """
        if device is None:
            return
        if isinstance(device, str):
            d = device
            if '-qvm' in d.lower():
                d = d[:-4]
            if '-noisy' in d.lower():
                d = d[:-6]
            if d in pyquil.list_quantum_computers():
                return
            else:
                try:
                    get_qc(d)
                    return
                except:
                    try:
                        get_qc(d, as_qvm=True)
                        return
                    except:
                        raise TequilaException(
                            'could not obtain device from string; received {}'.
                            format(device))

        elif isinstance(device, dict):
            try:
                get_qc(**device)
                return
            except:
                raise TequilaException(
                    'could not initialize device from dict; received {}'.
                    format(device))
        elif isinstance(device, pyquil.api.QuantumComputer):
            return

        else:
            raise TequilaException(
                'Uninterpretable object {} of type {} passed to check_device!'.
                format(device, type(device)))
コード例 #24
0
def estimate_gradient(f_h: float,
                      precision: int,
                      gradient_max: int = 1,
                      n_measurements: int = 50,
                      qc: QuantumComputer = None) -> float:
    """
    Estimate the gradient using function evaluation at perturbation, h.

    :param f_h: Oracle output at perturbation h.
    :param precision: Bit precision of gradient.
    :param gradient_max: OOM estimate of largest gradient value.
    :param n_measurements: Number of times to measure system.
    :param qc: The QuantumComputer object.
    :return: Decimal estimate of gradient.
    """

    # scale f_h by range of values gradient can take on
    f_h *= 1. / gradient_max

    # generate gradient program
    perturbation_sign = np.sign(f_h)
    p_gradient = gradient_program(f_h, precision)

    # run gradient program
    if qc is None:
        qc = get_qc(f"{len(p_gradient.get_qubits())}q-qvm")

    p_gradient.wrap_in_numshots_loop(n_measurements)
    executable = qc.compiler.native_quil_to_executable(p_gradient)
    measurements = qc.run(executable)

    # summarize measurements
    bf_estimate = perturbation_sign * measurements_to_bf(measurements)
    bf_explicit = '{0:.16f}'.format(bf_estimate)
    deci_estimate = binary_float_to_decimal_float(bf_explicit)

    # rescale gradient
    deci_estimate *= gradient_max

    return deci_estimate
コード例 #25
0
def test_qc_calibration_1q(forest):
    # noise model with 95% symmetrized readout fidelity per qubit
    noise_model = asymmetric_ro_model([0], 0.945, 0.955)
    qc = get_qc("1q-qvm")
    qc.qam.noise_model = noise_model

    # bell state program (doesn't matter)
    p = Program()
    p += RESET()
    p += H(0)
    p += CNOT(0, 1)
    p.wrap_in_numshots_loop(10000)

    # Z experiment
    sz = ExperimentSetting(in_state=sZ(0), out_operator=sZ(0))
    e = Experiment(settings=[sz], program=p)

    results = qc.calibrate(e)

    # Z expectation value should just be 1 - 2 * readout_error
    np.isclose(results[0].expectation, 0.9, atol=0.01)
    assert results[0].total_counts == 20000
コード例 #26
0
def test_qaoa_on_qvm():
    # ham = PauliSum.from_compact_str("(-1.0)*Z0*Z1 + 0.8*Z0 + (-0.5)*Z1")
    term1 = PauliTerm("Z", 0, -1) * PauliTerm("Z", 1)
    term2 = PauliTerm("Z", 0, 0.8)
    term3 = PauliTerm("Z", 1, -0.5)
    ham = PauliSum([term1, term2, term3])
    params = FourierParams.linear_ramp_from_hamiltonian(ham, n_steps=10, q=2)
    p0 = params.raw()
    qvm = get_qc("2q-qvm")
    with local_qvm():
        cost_fun = QAOACostFunctionOnQVM(ham,
                                         params,
                                         qvm,
                                         scalar_cost_function=True,
                                         nshots=4,
                                         base_numshots=50)
        out = minimize(cost_fun,
                       p0,
                       tol=2e-1,
                       method="Cobyla",
                       options={"maxiter": 100})
    assert np.allclose(out["fun"], -1.3, rtol=1.1)
    assert out["success"]
    print(out)
コード例 #27
0
    def run_circuits(self):
        import glob
        if "y" in self.plot_flag:
            import matplotlib.pyplot as plt
        if self.backend in "ibm":
            import qiskit as qk
            from qiskit.tools.monitor import job_monitor
            from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout
            from qiskit import Aer, IBMQ, execute
            from qiskit.providers.aer import noise
            from qiskit.providers.aer.noise import NoiseModel
            from qiskit.circuit import quantumcircuit
            from qiskit.circuit import Instruction
            ## Show available backends
            provider = qk.IBMQ.get_provider(group='open')
            provider.backends()

            #choose the device you would like to run on
            device = provider.get_backend(self.device_choice)

            #gather fidelity statistics on this device if you want to create a noise model for the simulator
            properties = device.properties()
            coupling_map = device.configuration().coupling_map

            #TO RUN ON THE SIMULATOR
            #create a noise model to use for the qubits of the simulator
            noise_model = NoiseModel.from_backend(device)
            # Get the basis gates for the noise model
            basis_gates = noise_model.basis_gates

            # Select the QasmSimulator from the Aer provider
            simulator = Aer.get_backend('qasm_simulator')

            #To run on the quantum computer, assign a quantum computer of your choice as the backend
            backend = provider.get_backend(self.device_choice)

            #CHOOSE TO RUN ON QUANTUM COMPUTER OR SIMULATOR
            if self.QCQS in ["QC"]:
                #quantum computer execution
                job = qk.execute(self.ibm_circuits_list,
                                 backend=backend,
                                 shots=self.shots)
                job_monitor(job)

            elif self.QCQS in ["QS"]:
                #simulator execution
                if self.noise_choice in ["y"]:
                    print("Running noisy simulator job...")
                    with open(self.namevar, 'a') as tempfile:
                        tempfile.write("Running noisy simulator job...\n")
                    result_noise = execute(self.ibm_circuits_list,
                                           simulator,
                                           noise_model=noise_model,
                                           coupling_map=coupling_map,
                                           basis_gates=basis_gates,
                                           shots=self.shots).result()
                    print("Noisy simulator job successful")
                    with open(self.namevar, 'a') as tempfile:
                        tempfile.write("Noisy simulator job successful\n")
                elif self.noise_choice in ["n"]:
                    print("Running noiseless simulator job...")
                    with open(self.namevar, 'a') as tempfile:
                        tempfile.write("Running noiseless simulator job...\n")
                    result_noise = execute(self.ibm_circuits_list,
                                           simulator,
                                           coupling_map=coupling_map,
                                           basis_gates=basis_gates,
                                           shots=self.shots).result()
                    print("Noiseless simulator job successful")
                    with open(self.namevar, 'a') as tempfile:
                        tempfile.write("Noiseless simulator job successful\n")
                else:
                    print(
                        "Please enter either y or n for the simulator noise query"
                    )
                    with open(self.namevar, 'a') as tempfile:
                        tempfile.write(
                            "Please enter either y or n for the simulator noise query\n"
                        )
            else:
                print("Please enter either QC or QS")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Please enter either QC or QS\n")

            #Post Processing Depending on Choice
            self.result_out_list = []
            if self.QCQS in ["QS"]:
                #SIMULATOR POST PROCESSING
                for j in range(self.num_qubits):
                    avg_mag_sim = []
                    temp = []
                    i = 1
                    print("Post-processing qubit {} data".format(j + 1))
                    with open(self.namevar, 'a') as tempfile:
                        tempfile.write(
                            "Post-processing qubit {} data\n".format(j + 1))
                    for c in self.ibm_circuits_list:
                        result_dict = result_noise.get_counts(c)
                        temp.append(
                            self.average_magnetization(result_dict, self.shots,
                                                       j))
                        if i % (self.steps + 1) == 0:
                            avg_mag_sim.append(temp)
                            temp = []
                        i += 1
                    # time_vec=np.linspace(0,total_t,steps)
                    # time_vec=time_vec*JX/H_BAR
                    if "y" in self.plot_flag:
                        plt.figure()
                        plt.plot(range(self.steps + 1), avg_mag_sim[0])
                        plt.xlabel("Simulation Timestep")
                        plt.ylabel("Average Magnetization")
                        plt.savefig(
                            "data/Simulator_result_qubit{}.png".format(j + 1))
                        plt.close()
                    self.result_out_list.append(avg_mag_sim[0])
                    existing = glob.glob(
                        "data/Spin {} Average Magnetization Data, Qubits={}, num_*.txt"
                        .format(j + 1, self.num_qubits))
                    np.savetxt(
                        "data/Spin {} Average Magnetization Data, Qubits={}, num_{}.txt"
                        .format(j + 1, self.num_qubits,
                                len(existing) + 1), avg_mag_sim[0])
                self.result_matrix = np.stack(self.result_out_list)
                print("Done")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Done\n")

            elif self.QCQS in ["QC"]:
                #QUANTUM COMPUTER POST PROCESSING
                for j in range(self.num_qubits):
                    results = job.result()
                    avg_mag_qc = []
                    temp = []
                    i = 1
                    print("Post-processing qubit {} data".format(j + 1))
                    with open(self.namevar, 'a') as tempfile:
                        tempfile.write(
                            "Post-processing qubit {} data\n".format(j + 1))
                    for c in self.ibm_circuits_list:
                        result_dict = results.get_counts(c)
                        temp.append(
                            self.average_magnetization(result_dict, self.shots,
                                                       j))
                        if i % (self.steps + 1) == 0:
                            avg_mag_qc.append(temp)
                            temp = []
                        i += 1

                    # QC
                    if "y" in self.plot_flag:
                        plt.figure()
                        plt.plot(range(self.steps + 1), avg_mag_qc[0])
                        plt.xlabel("Simulation Timestep")
                        plt.ylabel("Average Magnetization")
                        plt.savefig("data/QC_result_qubit{}.png".format(j + 1))
                        plt.close()
                    self.result_out_list.append(avg_mag_qc[0])
                    existing = glob.glob(
                        "data/Spin {} Average Magnetization Data, Qubits={}, num_*.txt"
                        .format(j + 1, self.num_qubits))
                    np.savetxt(
                        "data/Spin {} Average Magnetization Data, Qubits={}, num_{}.txt"
                        .format(j + 1, self.num_qubits,
                                len(existing) + 1), avg_mac_qc[0])
                self.result_matrix = np.stack(self.result_out_list)
                print("Done")
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write("Done\n")
        elif "rigetti" in self.backend:
            import pyquil
            from pyquil.quil import Program
            from pyquil.gates import H, RX, RZ, CZ, RESET, MEASURE
            from pyquil.api import get_qc
            print("Running Pyquil programs...")
            with open(self.namevar, 'a') as tempfile:
                tempfile.write("Running Pyquil programs...\n")
            if self.QCQS in ["QS"]:
                qc = get_qc(self.device_choice, as_qvm=True)
            else:
                qc = get_qc(self.device_choice)
            results_list = []
            first_ind = 0
            #each circuit represents one timestep
            for circuit in self.rigetti_circuits_list:
                temp = qc.run(circuit)
                results_list.append(temp)

            for i in range(self.num_qubits):
                print("Post-processing qubit {} data...".format(i + 1))
                with open(self.namevar, 'a') as tempfile:
                    tempfile.write(
                        "Post-Processing qubit {} data...\n".format(i + 1))
                qubit_specific_row = np.zeros(len(results_list))
                for j in range(len(self.rigetti_circuits_list)):
                    results = results_list[j]

                    summation = 0
                    for array in results:
                        summation += (1 - 2 * array[i])

                    summation = summation / len(
                        results)  #average over the number of shots

                    qubit_specific_row[j] = summation
                if first_ind == 0:
                    self.result_matrix = qubit_specific_row
                    first_ind += 1
                else:
                    self.result_matrix = np.vstack(
                        (self.result_matrix, qubit_specific_row))
                if "y" in self.plot_flag:
                    plt.figure()
                    xaxis = np.linspace(0, self.steps, num=self.steps + 1)
                    plt.plot(qubit_specific_row)
                    plt.xlabel("Simulation Timestep")
                    plt.ylabel("Average Magnetization")
                    plt.savefig("data/Result_qubit{}.png".format(i + 1))
                    plt.close()
                existing = glob.glob(
                    "data/Spin {} Average Magnetization Data, Qubits={}, num_*.txt"
                    .format(i + 1, self.num_qubits))
                np.savetxt(
                    "data/Spin {} Average Magnetization Data, Qubits={}, num_{}.txt"
                    .format(i + 1, self.num_qubits,
                            len(existing) + 1), qubit_specific_row)
            print("Done")
            with open(self.namevar, 'a') as tempfile:
                tempfile.write("Done\n")
コード例 #28
0
ファイル: test_api.py プロジェクト: qfizik/pyquil
def test_get_qc_returns_remote_qvm_compiler(qvm: QVMConnection,
                                            compiler: QVMCompiler):
    with patch.dict("os.environ", {"COMPILER_URL": "tcp://192.168.0.0:5550"}):
        qc = get_qc("9q-square-qvm")
        assert isinstance(qc.compiler, QVMCompiler)
コード例 #29
0
without_elec = without_elec.sample(
    3
)  #Can't actually deal with many points, so only limiting to 3 (random) ones
distance_matrix = np.array(without_elec[['Latitude', 'Longitude']])

dist = pd.DataFrame(distances_dataset(
    without_elec.values,
    lambda u, v: geopy.distance.distance(u, v).kilometers),
                    index=without_elec.index,
                    columns=without_elec.index)

distance_matrix = np.array(dist)
print(distance_matrix)

qvm = api.get_qc('9q-qvm')  # QC Emulator
qvm.compiler.client.timeout = 240  # Adjust this for different sized distance matrix

starting_node = 0
reduced_number_of_nodes = len(distance_matrix)
number_of_qubits = reduced_number_of_nodes**2
qubits = list(
    range(number_of_qubits
          ))  # Just an index of the qubits being used (ie qubit #0, #1, etc)


def create_phase_separator():
    """
        Creates phase-separation operators (aka cost hamiltonian), which depend on the objective function.
        """
    cost_operators = []
コード例 #30
0
def test_get_qc_returns_remote_qvm_compiler():
    with patch.dict('os.environ', {"COMPILER_URL": "tcp://192.168.0.0:5555"}):
        qc = get_qc("9q-generic-qvm")
        assert isinstance(qc.compiler, QVMCompiler)