Source Code Documentation

pyquil.api

Module for facilitating connections to the QVM / QPU.

class pyquil.api.QVMConnection(device=None, sync_endpoint='https://api.rigetti.com', async_endpoint='https://job.rigetti.com/beta', api_key=None, user_id=None, use_queue=False, ping_time=0.1, status_time=2, gate_noise=None, measurement_noise=None, random_seed=None)[source]

Bases: object

Represents a connection to the QVM.

expectation(prep_prog, operator_programs=None, needs_compilation=False, isa=None)[source]

Calculate the expectation value of operators given a state prepared by prep_program.

Note:If the execution of quil_program is non-deterministic, i.e., if it includes measurements and/or noisy quantum gates, then the final wavefunction from which the expectation values are computed itself only represents a stochastically generated sample. The expectations returned from different expectation calls will then generally be different.

To measure the expectation of a PauliSum, you probably want to do something like this:

progs, coefs = hamiltonian.get_programs()
expect_coeffs = np.array(cxn.expectation(prep_program, operator_programs=progs))
return np.real_if_close(np.dot(coefs, expect_coeffs))
Parameters:
  • prep_prog (Program) – Quil program for state preparation.
  • operator_programs (list) – A list of Programs, each specifying an operator whose expectation to compute. Default is a list containing only the empty Program.
  • needs_compilation (bool) – If True, preprocesses the job with the compiler.
  • isa (ISA) – If set, compiles to this target ISA.
Returns:

Expectation values of the operators.

Return type:

List[float]

expectation_async(prep_prog, operator_programs=None, needs_compilation=False, isa=None)[source]

Similar to expectation except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

get_job(job_id)[source]

Given a job id, return information about the status of the job

Parameters:job_id (str) – job id
Returns:Job object with the status and potentially results of the job
Return type:Job
pauli_expectation(prep_prog, pauli_terms)[source]

Calculate the expectation value of Pauli operators given a state prepared by prep_program.

If pauli_terms is a PauliSum then the returned value is a single float, otherwise the returned value is a list of float``s, one for each ``PauliTerm in the list.

Note:

If the execution of quil_program is non-deterministic, i.e., if it includes measurements and/or noisy quantum gates, then the final wavefunction from which the expectation values are computed itself only represents a stochastically generated sample. The expectations returned from different expectation calls will then generally be different.

Parameters:
  • prep_prog (Program) – Quil program for state preparation.
  • pauli_terms (Sequence[PauliTerm]|PauliSum) – A list of PauliTerms or a PauliSum.
Returns:

If pauli_terms is a PauliSum return its expectation value. Otherwise return a list of expectation values.

Return type:

float|List[float]

ping()[source]
run(quil_program, classical_addresses=None, trials=1, needs_compilation=False, isa=None)[source]

Run a Quil program multiple times, accumulating the values deposited in a list of classical addresses.

Parameters:
  • quil_program (Program) – A Quil program.
  • classical_addresses (list|range) – A list of addresses.
  • trials (int) – Number of shots to collect.
  • needs_compilation (bool) – If True, preprocesses the job with the compiler.
  • isa (ISA) – If set, compiles to this target ISA.
Returns:

A list of lists of bits. Each sublist corresponds to the values in classical_addresses.

Return type:

list

run_and_measure(quil_program, qubits, trials=1, needs_compilation=False, isa=None)[source]

Run a Quil program once to determine the final wavefunction, and measure multiple times.

Note:

If the execution of quil_program is non-deterministic, i.e., if it includes measurements and/or noisy quantum gates, then the final wavefunction from which the returned bitstrings are sampled itself only represents a stochastically generated sample and the outcomes sampled from different run_and_measure calls generally sample different bitstring distributions.

Parameters:
  • quil_program (Program) – A Quil program.
  • qubits (list|range) – A list of qubits.
  • trials (int) – Number of shots to collect.
  • needs_compilation (bool) – If True, preprocesses the job with the compiler.
  • isa (ISA) – If set, compiles to this target ISA.
Returns:

A list of a list of bits.

Return type:

list

run_and_measure_async(quil_program, qubits, trials=1, needs_compilation=False, isa=None)[source]

Similar to run_and_measure except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

run_async(quil_program, classical_addresses=None, trials=1, needs_compilation=False, isa=None)[source]

Similar to run except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

wait_for_job(job_id, ping_time=None, status_time=None)[source]

Wait for the results of a job and periodically print status

Parameters:
  • job_id – Job id
  • ping_time – How often to poll the server. Defaults to the value specified in the constructor. (0.1 seconds)
  • status_time – How often to print status, set to False to never print status. Defaults to the value specified in the constructor (2 seconds)
Returns:

Completed Job

wavefunction(quil_program, classical_addresses=None, needs_compilation=False, isa=None)[source]

Simulate a Quil program and get the wavefunction back.

Note:

If the execution of quil_program is non-deterministic, i.e., if it includes measurements and/or noisy quantum gates, then the final wavefunction from which the returned bitstrings are sampled itself only represents a stochastically generated sample and the wavefunctions returned by different wavefunction calls will generally be different.

Parameters:
  • quil_program (Program) – A Quil program.
  • classical_addresses (list|range) – An optional list of classical addresses.
  • needs_compilation – If True, preprocesses the job with the compiler.
  • isa – If set, compiles to this target ISA.
Returns:

A Wavefunction object representing the state of the QVM.

Return type:

Wavefunction

wavefunction_async(quil_program, classical_addresses=None, needs_compilation=False, isa=None)[source]

Similar to wavefunction except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

class pyquil.api.QPUConnection(device=None, async_endpoint='https://job.rigetti.com/beta', api_key=None, user_id=None, ping_time=0.1, status_time=2, device_name=None)[source]

Bases: object

Represents a connection to the QPU (Quantum Processing Unit)

get_job(job_id)[source]

Given a job id, return information about the status of the job

Parameters:job_id (str) – job id
Returns:Job object with the status and potentially results of the job
Return type:Job
run(quil_program, classical_addresses=None, trials=1, needs_compilation=True, isa=None)[source]

Run a pyQuil program on the QPU and return the values stored in the classical registers designated by the classical_addresses parameter. The program is repeated according to the number of trials provided to the run method. This functionality is in beta.

It is important to note that our QPUs currently only allow a single set of simultaneous readout pulses on all qubits in the QPU at the end of the program. This means that missing or duplicate MEASURE instructions do not change the pulse program, but instead only contribute to making a less rich or richer mapping, respectively, between classical and qubit addresses.

Parameters:
  • quil_program (Program) – Pyquil program to run on the QPU
  • classical_addresses (list|range) – Classical register addresses to return
  • trials (int) – Number of times to run the program (a.k.a. number of shots)
  • needs_compilation (bool) – If True, preprocesses the job with the compiler.
  • isa (ISA) – If set, specifies a custom ISA to compile to. If left unset, Forest uses the default ISA associated to this QPU device.
Returns:

A list of a list of classical registers (each register contains a bit)

Return type:

list

run_and_measure(quil_program, qubits, trials=1, needs_compilation=True, isa=None)[source]

Similar to run, except for how MEASURE operations are dealt with. With run, users are expected to include MEASURE operations in the program if they want results back. With run_and_measure, users provide a pyquil program that does not have MEASURE instructions, and also provide a list of qubits to measure. All qubits in this list will be measured at the end of the program, and their results stored in corresponding classical registers.

Parameters:
  • quil_program (Program) – Pyquil program to run on the QPU
  • qubits (list|range) – The list of qubits to measure
  • trials (int) – Number of times to run the program (a.k.a. number of shots)
  • needs_compilation (bool) – If True, preprocesses the job with the compiler.
  • isa (ISA) – If set, specifies a custom ISA to compile to. If left unset, Forest uses the default ISA associated to this QPU device.
Returns:

A list of a list of classical registers (each register contains a bit)

Return type:

list

run_and_measure_async(quil_program, qubits, trials, needs_compilation=True, isa=None)[source]

Similar to run_and_measure except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

run_async(quil_program, classical_addresses=None, trials=1, needs_compilation=True, isa=None)[source]

Similar to run except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

wait_for_job(job_id, ping_time=None, status_time=None)[source]

Wait for the results of a job and periodically print status

Parameters:
  • job_id – Job id
  • ping_time – How often to poll the server. Defaults to the value specified in the constructor. (0.1 seconds)
  • status_time – How often to print status, set to False to never print status. Defaults to the value specified in the constructor (2 seconds)
Returns:

Completed Job

class pyquil.api.CompilerConnection(device=None, sync_endpoint='https://api.rigetti.com', async_endpoint='https://job.rigetti.com/beta', api_key=None, user_id=None, use_queue=False, ping_time=0.1, status_time=2, isa_source=None, specs_source=None)[source]

Bases: object

Represents a connection to the Quil compiler.

apply_clifford_to_pauli(clifford, pauli_in)[source]

Given a circuit that consists only of elements of the Clifford group, return its action on a PauliTerm.

In particular, for Clifford C, and Pauli P, this returns the PauliTerm representing PCP^{dagger}.

Parameters:
  • clifford (Program) – A Program that consists only of Clifford operations.
  • pauli_in (PauliTerm) – A PauliTerm to be acted on by clifford via conjugation.
Returns:

A PauliTerm corresponding to pauli_in * clifford * pauli_in^{dagger}

compile(quil_program, isa=None)[source]

Sends a Quil program to the Forest compiler and returns the resulting compiled Program.

Parameters:
  • quil_program (Program) – Quil program to be compiled.
  • isa (ISA) – An optional ISA to target. This takes precedence over the device or isa_source arguments to this object’s constructor. If this is not specified, you must have provided one of the aforementioned constructor arguments.
Returns:

The compiled Program object.

Return type:

Program

compile_async(quil_program, isa=None)[source]

Similar to compile except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

generate_rb_sequence(depth, gateset, seed=None)[source]

Construct a randomized benchmarking experiment on the given qubits, decomposing into gateset.

The JSON payload that is parsed is a list of lists of indices, or Nones. In the former case, they are the index of the gate in the gateset.

Parameters:
  • depth (int) – The number of Clifford gates to include in the randomized benchmarking experiment. This is different than the number of gates in the resulting experiment.
  • gateset (list) – A list of pyquil gates to decompose the Clifford elements into. These must generate the clifford group on the qubits of interest. e.g. for one qubit [RZ(np.pi/2), RX(np.pi/2)].
  • seed (int) – A positive integer that seeds the random generation of the gate sequence.
Returns:

A list of pyquil programs. Each pyquil program is a circuit that represents an element of the Clifford group. When these programs are composed, the resulting Program will be the randomized benchmarking experiment of the desired depth. e.g. if the return programs are called cliffords then sum(cliffords, Program()) will give the randomized benchmarking experiment, which will compose to the identity program.

get_job(job_id)[source]

Given a job id, return information about the status of the job

Parameters:job_id (str) – job id
Returns:Job object with the status and potentially results of the job
Return type:Job
wait_for_job(job_id, ping_time=None, status_time=None)[source]

Wait for the results of a job and periodically print status

Parameters:
  • job_id – Job id
  • ping_time – How often to poll the server. Defaults to the value specified in the constructor. (0.1 seconds)
  • status_time – How often to print status, set to False to never print status. Defaults to the value specified in the constructor (2 seconds)
Returns:

Completed Job

class pyquil.api.Job(raw, machine)[source]

Bases: object

Represents the current status of a Job in the Forest queue.

Job statuses are initially QUEUED when QVM/QPU resources are not available They transition to RUNNING when they have been started Finally they are marked as FINISHED, ERROR, or CANCELLED once completed

compiled_quil()[source]

If the Quil program associated with the Job was compiled (e.g., to translate it to the QPU’s natural gateset) return this compiled program.

Return type:Optional[Program]
decode()[source]
estimated_time_left_in_queue()[source]

If the job is queued, this will return how much time left (in seconds) is estimated before execution.

gate_depth()[source]

If the job has metadata and this contains the gate depth, return this, otherwise None. The gate depth is a measure of how long a quantum program takes. On a non-fault-tolerant QPU programs with a low gate depth have a higher chance of succeeding.

Return type:Optional[int]
gate_volume()[source]

If the job has metadata and this contains the gate volume, return this, otherwise None. On a non-fault-tolerant QPU programs with a low gate volume have a higher chance of succeeding. This is a less sensitive measure than gate depth.

Return type:Optional[int]
get()[source]
is_compiling()[source]

Is the job actively compiling?

is_done()[source]

Has the job completed yet?

is_queued()[source]

Is the job still in the Forest queue?

is_queued_for_compilation()[source]

Is the job still in the Forest compilation queue?

is_running()[source]

Is the job currently running?

job_id

Job id :rtype: str

multiqubit_gate_depth()[source]

If the job has metadata and this contains the multiqubit gate depth, return this, otherwise None. The multiqubit gate depth is a measure of how inaccurately a quantum program will behave on nonideal hardware. On a non-fault-tolerant QPU programs with a low gate depth have a higher chance of succeeding.

Return type:Optional[int]
position_in_queue()[source]

If the job is queued, this will return how many other jobs are ahead of it. If the job is not queued, this will return None

program_fidelity()[source]

If the job has metadata and this contains a job program fidelity estimate, return this, otherwise None. This is a number between 0 and 1; a higher value means more likely odds of a meaningful answer.

Return type:Optional[float]
result()[source]

The result of the job if available throws ValueError is result is not available yet throws ApiError if server returned an error indicating program execution was not successful or if the job was cancelled

running_time()[source]

For how long was the job running? :return: Running time, seconds :rtype: Optional[float]

time_in_queue()[source]

For how long was the job in the Forest queue? :return: Time in queue, seconds :rtype: Optional[float]

topological_swaps()[source]

If the program could not be mapped directly to the QPU because of missing links in the two-qubit gate connectivity graph, the compiler must insert topological swap gates. Return the number of such topological swaps.

Return type:Optional[int]
pyquil.api.get_devices(async_endpoint='https://job.rigetti.com/beta', api_key=None, user_id=None, as_dict=False)[source]

Get a list of currently available devices. The arguments for this method are the same as those for QPUConnection. Note that this method will only work for accounts that have QPU access.

Returns:Set or Dictionary (keyed by device name) of all available devices.
Return type:Set|Dict
class pyquil.api.Device(name, raw)[source]

Bases: pyquil.device.AbstractDevice

A device (quantum chip) that can accept programs.

Only devices that are online will actively be accepting new programs. In addition to the self._raw attribute, two other attributes are optionally constructed from the entries in self._rawisa and noise_model – which should conform to the dictionary format required by the .from_dict() methods for ISA and NoiseModel, respectively.

Variables:
  • _raw (dict) – Raw JSON response from the server with additional information about the device.
  • isa (ISA) – The instruction set architecture (ISA) for the device.
  • noise_model (NoiseModel) – The noise model for the device.
get_isa(oneq_type='Xhalves', twoq_type='CZ') → pyquil.device.ISA[source]

Construct an ISA suitable for targeting by compilation.

This will raise an exception if the requested ISA is not supported by the device.

Parameters:
  • oneq_type – The family of one-qubit gates to target
  • twoq_type – The family of two-qubit gates to target
is_online()[source]

Whether or not the device is online and accepting new programs.

Return type:bool
is_retuning()[source]

Whether or not the device is currently retuning.

Return type:bool
isa
qubit_topology() → networkx.classes.graph.Graph[source]

The connectivity of qubits in this device given as a NetworkX graph.

status

Returns a string describing the device’s status

  • online: The device is online and ready for use
  • retuning : The device is not accepting new jobs because it is re-calibrating
  • offline: The device is not available for use, potentially because you don’t have the right permissions.
class pyquil.api.ForestConnection(sync_endpoint='https://api.rigetti.com', async_endpoint='https://job.rigetti.com/beta', api_key=None, user_id=None, use_queue=False, ping_time=0.1, status_time=2)[source]

Bases: object

class pyquil.api.WavefunctionSimulator(connection: pyquil.api._base_connection.ForestConnection = None, random_seed=None)[source]

Bases: object

expectation(prep_prog: pyquil.quil.Program, pauli_terms: Union[pyquil.paulis.PauliSum, List[pyquil.paulis.PauliTerm]]) → Union[float, numpy.ndarray][source]

Calculate the expectation value of Pauli operators given a state prepared by prep_program.

If pauli_terms is a PauliSum then the returned value is a single float, otherwise the returned value is an array of values, one for each PauliTerm in the list.

Note

If your program contains measurements or noisy gates, this method may not do what you want. If the execution of quil_program is non-deterministic then the final wavefunction from which the expectation value is calculated only represents a stochastically generated sample and the wavefunctions returned by different wavefunction calls will generally be different.

Parameters:
  • prep_prog – A program that prepares the state on which we measure the expectation.
  • pauli_terms – A Pauli representation of a quantum operator.
Returns:

Either a float or array floats depending on pauli_terms.

run_and_measure(quil_program: pyquil.quil.Program, qubits: List[int] = None, trials: int = 1) → numpy.ndarray[source]

Run a Quil program once to determine the final wavefunction, and measure multiple times.

Alternatively, consider using wavefunction and calling sample_bitstrings on the resulting object.

For a large wavefunction and a low-medium number of trials, use this function. On the other hand, if you’re sampling a small system many times you might want to use Wavefunction.sample_bitstrings.

Note

If your program contains measurements or noisy gates, this method may not do what you want. If the execution of quil_program is non-deterministic then the final wavefunction from which the returned bitstrings are sampled itself only represents a stochastically generated sample and the outcomes sampled from different run_and_measure calls generally sample different bitstring distributions.

Parameters:
  • quil_program – The program to run and measure
  • qubits – An optional list of qubits to measure. The order of this list is respected in the returned bitstrings. If not provided, all qubits used in the program will be measured and returned in their sorted order.
  • trials (int) – Number of times to sample from the prepared wavefunction.
Returns:

An array of measurement results (0 or 1) of shape (trials, len(qubits))

run_and_measure_async(quil_program, qubits=None, trials=1)[source]

Similar to run_and_measure except that it returns a job id and doesn’t wait for the program to be executed.

See https://go.rigetti.com/connections for reasons to use this method.

wait_for_job(job_id, ping_time=None, status_time=None) → pyquil.api.job.Job[source]

For async functions, wait for the specified job to be done and return the completed job.

Parameters:
  • job_id – The id of the job returned by _async methods.
  • ping_time – An optional time in seconds to poll for job completion.
  • status_time – An optional time in seconds to print the status of a job.
Returns:

The completed job.

wavefunction(quil_program: pyquil.quil.Program, classical_addresses: Iterable[int] = None) → pyquil.wavefunction.Wavefunction[source]

Simulate a Quil program and return the wavefunction.

Note

If your program contains measurements or noisy gates, this method may not do what you want. If the execution of quil_program is non-deterministic then the final wavefunction only represents a stochastically generated sample and the wavefunctions returned by different wavefunction calls will generally be different.

Parameters:
  • quil_program – A Quil program.
  • classical_addresses – An optional list of classical addresses to return in addition of the quantum wavefunction.
Returns:

A Wavefunction object representing the state of the QVM.

wavefunction_async(quil_program, classical_addresses=None)[source]

Similar to wavefunction except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

class pyquil.api.QAM[source]

Bases: abc.ABC

run(quil_program: pyquil.quil.Program, classical_addresses: Iterable[int], trials: int) → numpy.ndarray[source]

Run a Quil program on the QVM multiple times and return the values stored in the classical registers designated by the classical_addresses parameter.

Parameters:
  • quil_program – A program to run
  • classical_addresses – Classical register addresses to return
  • trials (int) – Number of times to repeatedly run the program. This is sometimes called the number of shots.
Returns:

An array of bitstrings of shape (trials, len(classical_addresses))

run_async(quil_program: pyquil.quil.Program, classical_addresses: Iterable[int], trials: int)[source]

Similar to run except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

wait_for_job(job_id, ping_time=None, status_time=None) → pyquil.api.job.Job[source]

For async functions, wait for the specified job to be done and return the completed job.

Parameters:
  • job_id – The id of the job returned by _async methods.
  • ping_time – An optional time in seconds to poll for job completion.
  • status_time – An optional time in seconds to print the status of a job.
Returns:

The completed job.

class pyquil.api.QVM(connection: pyquil.api._base_connection.ForestConnection, noise_model=None, gate_noise=None, measurement_noise=None, random_seed=None)[source]

Bases: pyquil.api._qam.QAM

run(quil_program: pyquil.quil.Program, classical_addresses: Iterable[int], trials: int) → numpy.ndarray[source]

Run a Quil program on the QVM multiple times and return the values stored in the classical registers designated by the classical_addresses parameter.

Parameters:
  • quil_program – A program to run
  • classical_addresses – Classical register addresses to return
  • trials (int) – Number of times to repeatedly run the program. This is sometimes called the number of shots.
Returns:

An array of bitstrings of shape (trials, len(classical_addresses))

run_async(quil_program, classical_addresses, trials)[source]

Similar to run except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

wait_for_job(job_id, ping_time=None, status_time=None) → pyquil.api.job.Job[source]

For async functions, wait for the specified job to be done and return the completed job.

Parameters:
  • job_id – The id of the job returned by _async methods.
  • ping_time – An optional time in seconds to poll for job completion.
  • status_time – An optional time in seconds to print the status of a job.
Returns:

The completed job.

class pyquil.api.QPU(connection: pyquil.api._base_connection.ForestConnection, device_name: str)[source]

Bases: pyquil.api._qam.QAM

run(quil_program: pyquil.quil.Program, classical_addresses: Iterable[int], trials: int) → numpy.ndarray[source]

Run a Quil program on the QPU multiple times and return the values stored in the classical registers designated by the classical_addresses parameter.

Note

Currently the QPU only allow a single set of simultaneous readout pulses on all qubits in the QPU at the end of the program. This means that missing or duplicate MEASURE instructions do not change the pulse program, but instead only contribute to making a less rich or richer mapping, respectively, between classical and qubit addresses.

Parameters:
  • quil_program – A program to run
  • classical_addresses – Classical register addresses to return
  • trials (int) – Number of times to repeatedly run the program. This is sometimes called the number of shots.
Returns:

An array of bitstrings of shape (trials, len(classical_addresses))

run_async(quil_program, classical_addresses, trials)[source]

Similar to run except that it returns a job id and doesn’t wait for the program to be executed. See https://go.rigetti.com/connections for reasons to use this method.

wait_for_job(job_id, ping_time=None, status_time=None) → pyquil.api.job.Job[source]

For async functions, wait for the specified job to be done and return the completed job.

Parameters:
  • job_id – The id of the job returned by _async methods.
  • ping_time – An optional time in seconds to poll for job completion.
  • status_time – An optional time in seconds to print the status of a job.
Returns:

The completed job.

class pyquil.api.QuantumComputer(*, name: str, qam: pyquil.api._qam.QAM, device: pyquil.device.AbstractDevice, symmetrize_readout=False)[source]

Bases: object

get_isa(oneq_type='Xhalves', twoq_type='CZ')[source]
qubit_topology()[source]
run(program, classical_addresses, trials, symmetrize_readout=None) → numpy.ndarray[source]

Run a quil program.

Parameters:
  • program – The program to run. You probably want to put MEASURE instructions in your program somewhere (like at the end) because qubits are not automatically measured
  • classical_addresses – The addresses of the classical bits to return. These don’t necessarily correspond to qubit indices; rather they are the second argument to any MEASURE instructions you’ve added to your program
  • trials – The number of times to run the program.
  • symmetrize_readout – Whether to apply readout error symmetrization. If not specified, the instance attribute symmetrize_readout will be used. See run_symmetrized_readout() for a complete description.
Returns:

A numpy array of shape (trials, len(classical_addresses)) that contains 0s and 1s

run_and_measure(program: pyquil.quil.Program, qubits: List[int], trials: int, symmetrize_readout=None)[source]

Run the provided state preparation program and measure all qubits contained in the program.

Note

In contrast to QVMConnection.run_and_measure, this method simulates noise correctly for noisy QVMs. However, this method is slower for trials > 1. For faster noise-free simulation, consider WavefunctionSimulator.run_and_measure.

Parameters:
  • program – The state preparation program to run and then measure.
  • qubits – Qubit indices to measure.
  • trials – The number of times to run the program.
  • symmetrize_readout – Whether to apply readout error symmetrization. If not specified, the class attribute symmetrize_readout will be used. See run_symmetrized_readout() for a complete description.
Returns:

A numpy array of shape (trials, len(qubits)) that contains 0s and 1s

run_async(program, classical_addresses, trials, symmetrize_readout=None) → str[source]

Queue a quil program for running, but return immediately with a job id.

Use QuantumComputer.wait_for_job() to get the actual job results, probably after queueing up a whole batch of jobs.

See run() for this function’s parameter descriptions.

Returns:a job id
run_symmetrized_readout(program, classical_addresses, trials)[source]

Run a quil program in such a way that the readout error is made collectively symmetric

This means the probability of a bitstring b being mistaken for a bitstring c is the same as the probability of not(b) being mistaken for not(c)

A more general symmetrization would guarantee that the probability of b being mistaken for c depends only on which bit of c are different from b. This would require choosing random subsets of bits to flip.

In a noisy device, the probability of accurately reading the 0 state might be higher than that of the 1 state. This makes correcting for readout more difficult. This function runs the program normally (trials//2) times. The other half of the time, it will insert an X gate prior to any MEASURE instruction and then flip the measured classical bit back.

See run() for this function’s parameter descriptions.

wait_for_job(job_id)[source]

pyquil.device

class pyquil.device.AbstractDevice[source]

Bases: abc.ABC

get_isa(oneq_type='Xhalves', twoq_type='CZ') → pyquil.device.ISA[source]

Construct an ISA suitable for targeting by compilation.

This will raise an exception if the requested ISA is not supported by the device.

Parameters:
  • oneq_type – The family of one-qubit gates to target
  • twoq_type – The family of two-qubit gates to target
qubit_topology() → networkx.classes.graph.Graph[source]

The connectivity of qubits in this device given as a NetworkX graph.

class pyquil.device.Device(name, raw)[source]

Bases: pyquil.device.AbstractDevice

A device (quantum chip) that can accept programs.

Only devices that are online will actively be accepting new programs. In addition to the self._raw attribute, two other attributes are optionally constructed from the entries in self._rawisa and noise_model – which should conform to the dictionary format required by the .from_dict() methods for ISA and NoiseModel, respectively.

Variables:
  • _raw (dict) – Raw JSON response from the server with additional information about the device.
  • isa (ISA) – The instruction set architecture (ISA) for the device.
  • noise_model (NoiseModel) – The noise model for the device.
get_isa(oneq_type='Xhalves', twoq_type='CZ') → pyquil.device.ISA[source]

Construct an ISA suitable for targeting by compilation.

This will raise an exception if the requested ISA is not supported by the device.

Parameters:
  • oneq_type – The family of one-qubit gates to target
  • twoq_type – The family of two-qubit gates to target
is_online()[source]

Whether or not the device is online and accepting new programs.

Return type:bool
is_retuning()[source]

Whether or not the device is currently retuning.

Return type:bool
isa
qubit_topology() → networkx.classes.graph.Graph[source]

The connectivity of qubits in this device given as a NetworkX graph.

status

Returns a string describing the device’s status

  • online: The device is online and ready for use
  • retuning : The device is not accepting new jobs because it is re-calibrating
  • offline: The device is not available for use, potentially because you don’t have the right permissions.
class pyquil.device.Edge(targets, type, dead)

Bases: tuple

dead

Alias for field number 2

targets

Alias for field number 0

type

Alias for field number 1

pyquil.device.EdgeSpecs

alias of pyquil.device._QubitQubitSpecs

class pyquil.device.ISA[source]

Bases: pyquil.device._ISA

Basic Instruction Set Architecture specification.

Variables:
  • qubits (Sequence[Qubit]) – The qubits associated with the ISA.
  • edges (Sequence[Edge]) – The multi-qubit gates.
static from_dict(d)[source]

Re-create the ISA from a dictionary representation.

Parameters:d (Dict[str,Any]) – The dictionary representation.
Returns:The restored ISA.
Return type:ISA
to_dict()[source]

Create a JSON-serializable representation of the ISA.

The dictionary representation is of the form:

{
    "1Q": {
        "0": {
            "type": "Xhalves"
        },
        "1": {
            "type": "Xhalves",
            "dead": True
        },
        ...
    },
    "2Q": {
        "1-4": {
            "type": "CZ"
        },
        "1-5": {
            "type": "CZ"
        },
        ...
    },
    ...
}
Returns:A dictionary representation of self.
Return type:Dict[str, Any]
class pyquil.device.NxDevice(topology: networkx.classes.graph.Graph)[source]

Bases: pyquil.device.AbstractDevice

A shim over the AbstractDevice API backed by a NetworkX graph.

A Device holds information about the physical device. Specifically, you might want to know about connectivity, available gates, performance specs, and more. This class implements the AbstractDevice API for devices not available via get_devices(). Instead, the user is responsible for constructing a NetworkX graph which represents a chip topology.

edges() → List[Tuple[int, int]][source]
get_isa(oneq_type='Xhalves', twoq_type='CZ')[source]

Construct an ISA suitable for targeting by compilation.

This will raise an exception if the requested ISA is not supported by the device.

Parameters:
  • oneq_type – The family of one-qubit gates to target
  • twoq_type – The family of two-qubit gates to target
qubit_topology()[source]

The connectivity of qubits in this device given as a NetworkX graph.

qubits() → List[int][source]
class pyquil.device.Qubit(id, type, dead)

Bases: tuple

dead

Alias for field number 2

id

Alias for field number 0

type

Alias for field number 1

pyquil.device.QubitSpecs

alias of pyquil.device._QubitSpecs

class pyquil.device.Specs[source]

Bases: pyquil.device._Specs

Basic specifications for the device, such as gate fidelities and coherence times.

Variables:
  • qubits_specs (List[QubitSpecs]) – The specs associated with individual qubits.
  • edges_specs (List[EdgesSpecs]) – The specs associated with edges, or qubit-qubit pairs.
T1s()[source]

Get a dictionary of T1s (in seconds) from the specs, keyed by qubit index.

Returns:A dictionary of T1s, in seconds.
Return type:Dict[int, float]
T2s()[source]

Get a dictionary of T2s (in seconds) from the specs, keyed by qubit index.

Returns:A dictionary of T2s, in seconds.
Return type:Dict[int, float]
f1QRBs()[source]

Get a dictionary of single-qubit randomized benchmarking fidelities (normalized to unity) from the specs, keyed by qubit index.

Returns:A dictionary of 1QRBs, normalized to unity.
Return type:Dict[int, float]
fBellStates()[source]

Get a dictionary of two-qubit Bell state fidelities (normalized to unity) from the specs, keyed by targets (qubit-qubit pairs).

Returns:A dictionary of Bell state fidelities, normalized to unity.
Return type:Dict[tuple(int, int), float]
fCPHASEs()[source]

Get a dictionary of CPHASE fidelities (normalized to unity) from the specs, keyed by targets (qubit-qubit pairs).

Returns:A dictionary of CPHASE fidelities, normalized to unity.
Return type:Dict[tuple(int, int), float]
fCZs()[source]

Get a dictionary of CZ fidelities (normalized to unity) from the specs, keyed by targets (qubit-qubit pairs).

Returns:A dictionary of CZ fidelities, normalized to unity.
Return type:Dict[tuple(int, int), float]
fROs()[source]

Get a dictionary of single-qubit readout fidelities (normalized to unity) from the specs, keyed by qubit index.

Returns:A dictionary of RO fidelities, normalized to unity.
Return type:Dict[int, float]
static from_dict(d)[source]

Re-create the Specs from a dictionary representation.

Parameters:Any] d (Dict[str,) – The dictionary representation.
Returns:The restored Specs.
Return type:Specs
to_dict()[source]

Create a JSON-serializable representation of the device Specs.

The dictionary representation is of the form:

{
    '1Q': {
        "0": {
            "f1QRB": 0.99,
            "T1": 20e-6,
            ...
        },
        "1": {
            "f1QRB": 0.989,
            "T1": 19e-6,
            ...
        },
        ...
    },
    '2Q': {
        "1-4": {
            "fBellState": 0.93,
            "fCZ": 0.92,
            "fCPHASE": 0.91
        },
        "1-5": {
            "fBellState": 0.9,
            "fCZ": 0.89,
            "fCPHASE": 0.88
        },
        ...
    },
    ...
}
Returns:A dctionary representation of self.
Return type:Dict[str, Any]
pyquil.device.THETA = Parameter('theta')

Used as the symbolic parameter in RZ, CPHASE gates.

pyquil.device.gates_in_isa(isa)[source]

Generate the full gateset associated with an ISA.

Parameters:isa (ISA) – The instruction set architecture for a QPU.
Returns:A sequence of Gate objects encapsulating all gates compatible with the ISA.
Return type:Sequence[Gate]
pyquil.device.isa_from_graph(graph: networkx.classes.graph.Graph, oneq_type='Xhalves', twoq_type='CZ') → pyquil.device.ISA[source]

Generate an ISA object from a NetworkX graph.

Parameters:
  • graph – The graph
  • oneq_type – The type of 1-qubit gate. Currently ‘Xhalves’
  • twoq_type – The type of 2-qubit gate. One of ‘CZ’ or ‘CPHASE’.
pyquil.device.isa_to_graph(isa: pyquil.device.ISA) → networkx.classes.graph.Graph[source]

Construct a NetworkX qubit topology from an ISA object.

This discards information about supported gates.

Parameters:isa – The ISA.

pyquil.gates

pyquil.gates.Y(qubit)[source]

Produces the Y instruction.

Y = [[0, 0 - 1j],
[0 + 1j, 0]]

This gate is a single qubit Y-gate.

Parameters:qubit – The qubit apply the gate to.
Returns:A Gate object.
pyquil.gates.CPHASE00(angle, control, target)[source]

Produces a CPHASE00 instruction.

CPHASE00(phi) = diag([exp(1j * phi), 1, 1, 1])

This gate applies to two qubit arguments to produce the variant of the controlled phase instruction that affects the state 00.

Parameters:
  • angle – The input phase angle to apply when both qubits are in the ground state.
  • control – Qubit 1.
  • target – Qubit 2.
Returns:

A Gate object.

pyquil.gates.CPHASE01(angle, control, target)[source]

Produces a CPHASE01 instruction.

CPHASE01(phi) = diag([1.0, exp(1j * phi), 1.0, 1.0])

This gate applies to two qubit arguments to produce the variant of the controlled phase instruction that affects the state 01.

Parameters:
  • angle – The input phase angle to apply when q1 is in the excited state and q2 is in the ground state.
  • control – Qubit 1.
  • target – Qubit 2.
Returns:

A Gate object.

pyquil.gates.CSWAP(control, target_1, target_2)[source]
CSWAP = [[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1]]

Produces a CSWAP instruction. This gate swaps the state of two qubits.

Parameters:
  • control – The control qubit.
  • target-1 – The first target qubit.
  • target-2 – The second target qubit. The two target states are swapped if the control is in the excited state.
pyquil.gates.PHASE(angle, qubit)[source]

Produces the PHASE instruction.

PHASE(phi) = [[1, 0],
[0, exp(1j * phi)]]

This is the same as the RZ gate.

Parameters:
  • angle – The angle to rotate around the z-axis on the bloch sphere.
  • qubit – The qubit apply the gate to.
Returns:

A Gate object.

pyquil.gates.T(qubit)[source]

Produces the T instruction.

T = [[1, 0],
[0, exp(1j * pi / 4)]]

This gate is a single qubit T-gate. It is the same as RZ(pi/4).

Parameters:qubit – The qubit apply the gate to.
Returns:A Gate object.
pyquil.gates.RX(angle, qubit)[source]

Produces the RX instruction.

RX(phi) = [[cos(phi / 2), -1j * sin(phi / 2)],
[-1j * sin(phi / 2), cos(phi / 2)]]

This gate is a single qubit X-rotation.

Parameters:
  • angle – The angle to rotate around the x-axis on the bloch sphere.
  • qubit – The qubit apply the gate to.
Returns:

A Gate object.

pyquil.gates.Z(qubit)[source]

Produces the Z instruction.

Z = [[1, 0],
[0, -1]]

This gate is a single qubit Z-gate.

Parameters:qubit – The qubit apply the gate to.
Returns:A Gate object.
pyquil.gates.RY(angle, qubit)[source]

Produces the RY instruction.

RY(phi) = [[cos(phi / 2), -sin(phi / 2)],
[sin(phi / 2), cos(phi / 2)]]

This gate is a single qubit Y-rotation.

Parameters:
  • angle – The angle to rotate around the y-axis on the bloch sphere.
  • qubit – The qubit apply the gate to.
Returns:

A Gate object.

pyquil.gates.CZ(control, target)[source]

Produces a CZ instruction.

CZ = [[1, 0, 0, 0],
[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]

This gate applies to two qubit arguments to produce the controlled-Z gate instruction.

Parameters:
  • control – The control qubit.
  • target – The target qubit. The target qubit has an Z-gate applied to it if the control qubit is in the excited state.
Returns:

A Gate object.

pyquil.gates.NOT(classical_reg)[source]

Produce a NOT instruction.

Parameters:classical_reg – A classical register to modify.
Returns:A ClassicalNot instance.
pyquil.gates.RZ(angle, qubit)[source]

Produces the RZ instruction.

RZ(phi) = [[cos(phi / 2) - 1j * sin(phi / 2), 0]
[0, cos(phi / 2) + 1j * sin(phi / 2)]]

This gate is a single qubit Z-rotation.

Parameters:
  • angle – The angle to rotate around the z-axis on the bloch sphere.
  • qubit – The qubit apply the gate to.
Returns:

A Gate object.

pyquil.gates.CNOT(control, target)[source]

Produces a CNOT instruction.

CNOT = [[1, 0, 0, 0],
[0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]

This gate applies to two qubit arguments to produce the controlled-not gate instruction.

Parameters:
  • control – The control qubit.
  • target – The target qubit. The target qubit has an X-gate applied to it if the control qubit is in the excited state.
Returns:

A Gate object.

pyquil.gates.X(qubit)[source]

Produces the X instruction.

X = [[0, 1],
[1, 0]]

This gate is a single qubit X-gate.

Parameters:qubit – The qubit apply the gate to.
Returns:A Gate object.
pyquil.gates.FALSE(classical_reg)[source]

Produce a FALSE instruction.

Parameters:classical_reg – A classical register to modify.
Returns:A ClassicalFalse instance.
pyquil.gates.S(qubit)[source]

Produces the S instruction.

S = [[1, 0],
[0, 1j]]

This gate is a single qubit S-gate.

Parameters:qubit – The qubit apply the gate to.
Returns:A Gate object.
pyquil.gates.SWAP(q1, q2)[source]

Produces a SWAP instruction.

SWAP = [[1, 0, 0, 0],
[0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]

This gate swaps the state of two qubits.

Parameters:
  • q1 – Qubit 1.
  • q2 – Qubit 2.
Returns:

A Gate object.

pyquil.gates.CPHASE10(angle, control, target)[source]

Produces a CPHASE10 instruction.

CPHASE10(phi) = diag([1, 1, exp(1j * phi), 1])

This gate applies to two qubit arguments to produce the variant of the controlled phase instruction that affects the state 10.

Parameters:
  • angle – The input phase angle to apply when q2 is in the excited state and q1 is in the ground state.
  • control – Qubit 1.
  • target – Qubit 2.
Returns:

A Gate object.

pyquil.gates.TRUE(classical_reg)[source]

Produce a TRUE instruction.

Parameters:classical_reg – A classical register to modify.
Returns:A ClassicalTrue instance.
pyquil.gates.WAIT = <pyquil.quilbase.Wait object>

This instruction tells the quantum computation to halt. Typically these is used while classical memory is being manipulated by a CPU in a hybrid classical/quantum algorithm.

Returns:A Wait object.
pyquil.gates.MEASURE(qubit, classical_reg=None)[source]

Produce a MEASURE instruction.

Parameters:
  • qubit – The qubit to measure.
  • classical_reg – The classical register to measure into, or None.
Returns:

A Measurement instance.

pyquil.gates.RESET = <pyquil.quilbase.Reset object>

This instruction resets all the qubits to the ground state.

Returns:A Reset object.
pyquil.gates.ISWAP(q1, q2)[source]

Produces an ISWAP instruction.

ISWAP = [[1, 0, 0, 0],
[0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]]

This gate swaps the state of two qubits, applying a -i phase to q1 when it is in the excited state and a -i phase to q2 when it is in the ground state.

Parameters:
  • q1 – Qubit 1.
  • q2 – Qubit 2.
Returns:

A Gate object.

pyquil.gates.HALT = <pyquil.quilbase.Halt object>

This instruction ends the program.

Returns:A Halt object.
pyquil.gates.EXCHANGE(classical_reg1, classical_reg2)[source]

Produce an EXCHANGE instruction.

Parameters:
  • classical_reg1 – The first classical register, which gets modified.
  • classical_reg2 – The second classical register, which gets modified.
Returns:

A ClassicalExchange instance.

pyquil.gates.CCNOT(control1, control2, target)[source]

Produces a CCNOT instruction.

CCNOT = [[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]

This gate applies to three qubit arguments to produce the controlled-controlled-not gate instruction.

Parameters:
  • control1 – The first control qubit.
  • control2 – The second control qubit.
  • target – The target qubit. The target qubit has an X-gate applied to it if both control qubits are in the excited state.
Returns:

A Gate object.

pyquil.gates.OR(classical_reg1, classical_reg2)[source]

Produce an OR instruction.

Parameters:
  • classical_reg1 – The first classical register.
  • classical_reg2 – The second classical register, which gets modified.
Returns:

A ClassicalOr instance.

pyquil.gates.H(qubit)[source]
H = (1 / sqrt(2)) * [[1, 1],
[1, -1]]

Produces the H instruction. This gate is a single qubit Hadamard gate.

Parameters:qubit – The qubit apply the gate to.
Returns:A Gate object.
pyquil.gates.AND(classical_reg1, classical_reg2)[source]

Produce an AND instruction.

Parameters:
  • classical_reg1 – The first classical register.
  • classical_reg2 – The second classical register, which gets modified.
Returns:

A ClassicalAnd instance.

pyquil.gates.PSWAP(angle, q1, q2)[source]

Produces a PSWAP instruction.

PSWAP(phi) = [[1, 0, 0, 0],
[0, 0, exp(1j * phi), 0], [0, exp(1j * phi), 0, 0], [0, 0, 0, 1]]

This is a parameterized swap gate.

Parameters:
  • angle – The angle of the phase to apply to the swapped states. This phase is applied to q1 when it is in the excited state and to q2 when it is in the ground state.
  • q1 – Qubit 1.
  • q2 – Qubit 2.
Returns:

A Gate object.

pyquil.gates.NOP = <pyquil.quilbase.Nop object>

This instruction applies no operation at that timestep. Typically these are ignored in error-models.

Returns:A Nop object.
pyquil.gates.I(qubit)[source]

Produces the I instruction.

I = [1, 0]
[0, 1]

This gate is a single qubit identity gate. Note that this gate is different that the NOP instruction as noise channels are typically still applied during the duration of identity gates. Identities will also block parallelization like any other gate.

Parameters:qubit – The qubit apply the gate to.
Returns:A Gate object.
pyquil.gates.CPHASE(angle, control, target)[source]

Produces a CPHASE instruction, which is a synonym for CPHASE11.

CPHASE(phi) = diag([1, 1, 1, exp(1j * phi)])

This gate applies to two qubit arguments to produce the variant of the controlled phase instruction that affects the state 11.

Parameters:
  • angle – The input phase angle to apply when both qubits are in the excited state.
  • control – Qubit 1.
  • target – Qubit 2.
Returns:

A Gate object.

pyquil.gates.MOVE(classical_reg1, classical_reg2)[source]

Produce a MOVE instruction.

Parameters:
  • classical_reg1 – The first classical register.
  • classical_reg2 – The second classical register, which gets modified.
Returns:

A ClassicalMove instance.

class pyquil.gates.Gate(name, params, qubits)[source]

Bases: pyquil.quilbase.AbstractInstruction

This is the pyQuil object for a quantum gate instruction.

get_qubits(indices=True)[source]
out()[source]

pyquil.noise

Module for creating and verifying noisy gate and readout definitions.

pyquil.noise.INFINITY = inf

Used for infinite coherence times.

class pyquil.noise.KrausModel[source]

Bases: pyquil.noise._KrausModel

Encapsulate a single gate’s noise model.

Variables:
  • gate (str) – The name of the gate.
  • params (Sequence[float]) – Optional parameters for the gate.
  • targets (Sequence[int]) – The target qubit ids.
  • kraus_ops (Sequence[np.array]) – The Kraus operators (must be square complex numpy arrays).
  • fidelity (float) – The average gate fidelity associated with the Kraus map relative to the ideal operation.
static from_dict(d)[source]

Recreate a KrausModel from the dictionary representation.

Parameters:d (dict) – The dictionary representing the KrausModel. See to_dict for an example.
Returns:The deserialized KrausModel.
Return type:KrausModel
to_dict()[source]

Create a dictionary representation of a KrausModel.

For example:

{
    "gate": "RX",
    "params": np.pi,
    "targets": [0],
    "kraus_ops": [            # In this example single Kraus op = ideal RX(pi) gate
        [[[0,   0],           # element-wise real part of matrix
          [0,   0]],
          [[0, -1],           # element-wise imaginary part of matrix
          [-1, 0]]]
    ],
    "fidelity": 1.0
}
Returns:A JSON compatible dictionary representation.
Return type:Dict[str,Any]
static unpack_kraus_matrix(m)[source]

Helper to optionally unpack a JSON compatible representation of a complex Kraus matrix.

Parameters:m (Union[list,np.array]) – The representation of a Kraus operator. Either a complex square matrix (as numpy array or nested lists) or a JSON-able pair of real matrices (as nested lists) representing the element-wise real and imaginary part of m.
Returns:A complex square numpy array representing the Kraus operator.
Return type:np.array
class pyquil.noise.NoiseModel[source]

Bases: pyquil.noise._NoiseModel

Encapsulate the QPU noise model containing information about the noisy gates.

Variables:
  • gates (Sequence[KrausModel]) – The tomographic estimates of all gates.
  • assignment_probs (Dict[int,np.array]) – The single qubit readout assignment probability matrices keyed by qubit id.
static from_dict(d)[source]

Re-create the noise model from a dictionary representation.

Parameters:d (Dict[str,Any]) – The dictionary representation.
Returns:The restored noise model.
Return type:NoiseModel
gates_by_name(name)[source]

Return all defined noisy gates of a particular gate name.

Parameters:name (str) – The gate name.
Returns:A list of noise models representing that gate.
Return type:Sequence[KrausModel]
to_dict()[source]

Create a JSON serializable representation of the noise model.

For example:

{
    "gates": [
        # list of embedded dictionary representations of KrausModels here [...]
    ]
    "assignment_probs": {
        "0": [[.8, .1],
              [.2, .9]],
        "1": [[.9, .4],
              [.1, .6]],
    }
}
Returns:A dictionary representation of self.
Return type:Dict[str,Any]
exception pyquil.noise.NoisyGateUndefined[source]

Bases: Exception

Raise when user attempts to use noisy gate outside of currently supported set.

pyquil.noise.add_decoherence_noise(prog, T1=3e-05, T2=3e-05, gate_time_1q=5e-08, gate_time_2q=1.5e-07, ro_fidelity=0.95)[source]

Add generic damping and dephasing noise to a program.

This high-level function is provided as a convenience to investigate the effects of a generic noise model on a program. For more fine-grained control, please investigate the other methods available in the pyquil.noise module.

In an attempt to closely model the QPU, noisy versions of RX(+-pi/2) and CZ are provided; I and parametric RZ are noiseless, and other gates are not allowed. To use this function, you need to compile your program to this native gate set.

The default noise parameters

  • T1 = 30 us
  • T2 = 30 us
  • 1q gate time = 50 ns
  • 2q gate time = 150 ns

are currently typical for near-term devices.

This function will define new gates and add Kraus noise to these gates. It will translate the input program to use the noisy version of the gates.

Parameters:
  • prog – A pyquil program consisting of I, RZ, CZ, and RX(+-pi/2) instructions
  • T1 (Union[Dict[int,float],float]) – The T1 amplitude damping time either globally or in a dictionary indexed by qubit id. By default, this is 30 us.
  • T2 (Union[Dict[int,float],float]) – The T2 dephasing time either globally or in a dictionary indexed by qubit id. By default, this is also 30 us.
  • gate_time_1q (float) – The duration of the one-qubit gates, namely RX(+pi/2) and RX(-pi/2). By default, this is 50 ns.
  • gate_time_2q (float) – The duration of the two-qubit gates, namely CZ. By default, this is 150 ns.
  • ro_fidelity (Union[Dict[int,float],float]) – The readout assignment fidelity \(F = (p(0|0) + p(1|1))/2\) either globally or in a dictionary indexed by qubit id.
Returns:

A new program with noisy operators.

pyquil.noise.append_kraus_to_gate(kraus_ops, gate_matrix)[source]

Follow a gate gate_matrix by a Kraus map described by kraus_ops.

Parameters:
  • kraus_ops (list) – The Kraus operators.
  • gate_matrix (numpy.ndarray) – The unitary gate.
Returns:

A list of transformed Kraus operators.

pyquil.noise.apply_noise_model(prog, noise_model)[source]

Apply a noise model to a program and generated a ‘noisy-fied’ version of the program.

Parameters:
  • prog (Program) – A Quil Program object.
  • noise_model (NoiseModel) – A NoiseModel, either generated from an ISA or from a simple decoherence model.
Returns:

A new program translated to a noisy gateset and with noisy readout as described by the noisemodel.

Return type:

Program

pyquil.noise.bitstring_probs_to_z_moments(p)[source]

Convert between bitstring probabilities and joint Z moment expectations.

Parameters:p (np.array) – An array that enumerates bitstring probabilities. When flattened out p = [p_00...0, p_00...1, ...,p_11...1]. The total number of elements must therefore be a power of 2. The canonical shape has a separate axis for each qubit, such that p[i,j,...,k] gives the estimated probability of bitstring ij...k.
Returns:z_moments, an np.array with one length-2 axis per qubit which contains the expectations of all monomials in {I, Z_0, Z_1, ..., Z_{n-1}}. The expectations of each monomial can be accessed via:
<Z_0^j_0 Z_1^j_1 ... Z_m^j_m> = z_moments[j_0,j_1,...,j_m]
Return type:np.array
pyquil.noise.combine_kraus_maps(k1, k2)[source]

Generate the Kraus map corresponding to the composition of two maps on the same qubits with k1 being applied to the state after k2.

Parameters:
  • k1 (list) – The list of Kraus operators that are applied second.
  • k2 (list) – The list of Kraus operators that are applied first.
Returns:

A combinatorially generated list of composed Kraus operators.

pyquil.noise.correct_bitstring_probs(p, assignment_probabilities)[source]

Given a 2d array of corrupted bitstring probabilities (outer axis iterates over shots, inner axis over bits) and a list of assignment probability matrices (one for each bit in the readout) compute the corrected probabilities.

Parameters:
  • p (np.array) – An array that enumerates bitstring probabilities. When flattened out p = [p_00...0, p_00...1, ...,p_11...1]. The total number of elements must therefore be a power of 2. The canonical shape has a separate axis for each qubit, such that p[i,j,...,k] gives the estimated probability of bitstring ij...k.
  • assignment_probabilities (List[np.array]) –

    A list of assignment probability matrices per qubit. Each assignment probability matrix is expected to be of the form:

    [[p00 p01]
     [p10 p11]]
    
Returns:

p_corrected an array with as many dimensions as there are qubits that contains the noisy-readout-corrected estimated probabilities for each measured bitstring, i.e., p[i,j,...,k] gives the estimated probability of bitstring ij...k.

Return type:

np.array

pyquil.noise.corrupt_bitstring_probs(p, assignment_probabilities)[source]

Given a 2d array of true bitstring probabilities (outer axis iterates over shots, inner axis over bits) and a list of assignment probability matrices (one for each bit in the readout, ordered like the inner axis of results) compute the corrupted probabilities.

Parameters:
  • p (np.array) – An array that enumerates bitstring probabilities. When flattened out p = [p_00...0, p_00...1, ...,p_11...1]. The total number of elements must therefore be a power of 2. The canonical shape has a separate axis for each qubit, such that p[i,j,...,k] gives the estimated probability of bitstring ij...k.
  • assignment_probabilities (List[np.array]) –

    A list of assignment probability matrices per qubit. Each assignment probability matrix is expected to be of the form:

    [[p00 p01]
     [p10 p11]]
    
Returns:

p_corrected an array with as many dimensions as there are qubits that contains the noisy-readout-corrected estimated probabilities for each measured bitstring, i.e., p[i,j,...,k] gives the estimated probability of bitstring ij...k.

Return type:

np.array

pyquil.noise.damping_after_dephasing(T1, T2, gate_time)[source]

Generate the Kraus map corresponding to the composition of a dephasing channel followed by an amplitude damping channel.

Parameters:
  • T1 (float) – The amplitude damping time
  • T2 (float) – The dephasing time
  • gate_time (float) – The gate duration.
Returns:

A list of Kraus operators.

pyquil.noise.damping_kraus_map(p=0.1)[source]

Generate the Kraus operators corresponding to an amplitude damping noise channel.

Parameters:p (float) – The one-step damping probability.
Returns:A list [k1, k2] of the Kraus operators that parametrize the map.
Return type:list
pyquil.noise.decoherance_noise_with_asymmetric_ro(isa: pyquil.device.ISA, p00=0.975, p11=0.911)[source]

Similar to :py:func`_decoherance_noise_model`, but with asymmetric readout.

For simplicity, we use the default values for T1, T2, gate times, et al. and only allow the specification of readout fidelities.

pyquil.noise.dephasing_kraus_map(p=0.1)[source]

Generate the Kraus operators corresponding to a dephasing channel.

Params float p:The one-step dephasing probability.
Returns:A list [k1, k2] of the Kraus operators that parametrize the map.
Return type:list
pyquil.noise.estimate_assignment_probs(q, trials, cxn, p0=None)[source]

Estimate the readout assignment probabilities for a given qubit q. The returned matrix is of the form:

[[p00 p01]
 [p10 p11]]
Parameters:
  • q (int) – The index of the qubit.
  • trials (int) – The number of samples for each state preparation.
  • cxn (Union[QVMConnection,QPUConnection]) – The quantum abstract machine to sample from.
  • p0 (Program) – A header program to prepend to the state preparation programs.
Returns:

The assignment probability matrix

Return type:

np.array

pyquil.noise.estimate_bitstring_probs(results)[source]

Given an array of single shot results estimate the probability distribution over all bitstrings.

Parameters:results (np.array) – A 2d array where the outer axis iterates over shots and the inner axis over bits.
Returns:An array with as many axes as there are qubit and normalized such that it sums to one. p[i,j,...,k] gives the estimated probability of bitstring ij...k.
Return type:np.array
pyquil.noise.get_noisy_gate(gate_name, params)[source]

Look up the numerical gate representation and a proposed ‘noisy’ name.

Parameters:
  • gate_name (str) – The Quil gate name
  • params (Tuple[float]) – The gate parameters.
Returns:

A tuple (matrix, noisy_name) with the representation of the ideal gate matrix and a proposed name for the noisy version.

Return type:

Tuple[np.array, str]

pyquil.noise.tensor_kraus_maps(k1, k2)[source]

Generate the Kraus map corresponding to the composition of two maps on different qubits.

Parameters:
  • k1 (list) – The Kraus operators for the first qubit.
  • k2 (list) – The Kraus operators for the second qubit.
Returns:

A list of tensored Kraus operators.

pyquil.parametric

Module for creating and defining parametric programs.

class pyquil.parametric.ParametricProgram(program_constructor)[source]

Bases: object

Note

Experimental

A class representing Programs with changeable gate parameters.

fuse(other)[source]

Note

Experimental

Fuse another program to this one.

Parameters:other – A Program or ParametricProgram.
Returns:A new ParametricProgram.
Return type:ParametricProgram
pyquil.parametric.argument_count(thing)[source]

Get the number of arguments a callable has.

Parameters:thing – A callable.
Returns:The number of arguments it takes.
Return type:int
pyquil.parametric.parametric(decorated_function)[source]

Note

Experimental

A decorator to change a function into a ParametricProgram.

Parameters:decorated_function – The function taking parameters producing a Program object.
Returns:a callable ParametricProgram
Return type:ParametricProgram

pyquil.parser

Module for parsing Quil programs from text into PyQuil objects

pyquil.parser.parse(quil)[source]

Parse a raw Quil program and return a corresponding list of PyQuil objects.

Parameters:quil (str) – a single or multiline Quil program
Returns:list of instructions
pyquil.parser.parse_program(quil)[source]

Parse a raw Quil program and return a PyQuil program.

Parameters:quil (str) – a single or multiline Quil program
Returns:PyQuil Program object

pyquil.paulis

Module for working with Pauli algebras.

pyquil.paulis.HASH_PRECISION = 1000000.0

The precision used when hashing terms to check equality. The simplify() method uses np.isclose() for coefficient comparisons to 0 which has its own default precision. We can’t use np.isclose() for hashing terms though.

pyquil.paulis.ID()[source]

The identity Pauli Term.

class pyquil.paulis.PauliSum(terms)[source]

Bases: object

A sum of one or more PauliTerms.

get_programs()[source]

Get a Pyquil Program corresponding to each term in the PauliSum and a coefficient for each program

Returns:(programs, coefficients)
get_qubits()[source]

The support of all the operators in the PauliSum object.

Returns:A list of all the qubits in the sum of terms.
Return type:list
simplify()[source]

Simplifies the sum of Pauli operators according to Pauli algebra rules.

class pyquil.paulis.PauliTerm(op, index, coefficient=1.0)[source]

Bases: object

A term is a product of Pauli operators operating on different qubits.

copy()[source]

Properly creates a new PauliTerm, with a completely new dictionary of operators

classmethod from_list(terms_list, coefficient=1.0)[source]

Allocates a Pauli Term from a list of operators and indices. This is more efficient than multiplying together individual terms.

Parameters:terms_list (list) – A list of tuples, e.g. [(“X”, 0), (“Y”, 1)]
Returns:PauliTerm
get_qubits()[source]

Gets all the qubits that this PauliTerm operates on.

id(sort_ops=True)[source]

Returns an identifier string for the PauliTerm (ignoring the coefficient).

Don’t use this to compare terms. This function will not work with qubits that aren’t sortable.

Parameters:sort_ops – Whether to sort operations by qubit. This is True by default for backwards compatibility but will change in pyQuil 2.0. Callers should never rely on comparing id’s for testing equality. See operations_as_set instead.
Returns:A string representation of this term’s operations.
Return type:string
operations_as_set()[source]

Return a frozenset of operations in this term.

Use this in place of id() if the order of operations in the term does not matter.

Returns:frozenset of strings representing Pauli operations
pauli_string(qubits=None)[source]

Return a string representation of this PauliTerm mod its phase, as a concatenation of the string representation of the >>> p = PauliTerm(“X”, 0) * PauliTerm(“Y”, 1, 1.j) >>> p.pauli_string() “XY” >>> p.pauli_string([0]) “X” >>> p.pauli_string([0, 2]) “XI”

Parameters:qubits (list) – The list of qubits to represent, given as ints. If None, defaults to all qubits in this PauliTerm.
Returns:The string representation of this PauliTerm, modulo its phase.
Return type:String
program
exception pyquil.paulis.UnequalLengthWarning(*args, **kwargs)[source]

Bases: Warning

pyquil.paulis.ZERO()[source]

The zero Pauli Term.

pyquil.paulis.check_commutation(pauli_list, pauli_two)[source]

Check if commuting a PauliTerm commutes with a list of other terms by natural calculation. Derivation similar to arXiv:1405.5749v2 fo the check_commutation step in the Raesi, Wiebe, Sanders algorithm (arXiv:1108.4318, 2011).

Parameters:
  • pauli_list (list) – A list of PauliTerm objects
  • pauli_two_term (PauliTerm) – A PauliTerm object
Returns:

True if pauli_two object commutes with pauli_list, False otherwise

Return type:

bool

pyquil.paulis.commuting_sets(pauli_terms)[source]

Gather the Pauli terms of pauli_terms variable into commuting sets

Uses algorithm defined in (Raeisi, Wiebe, Sanders, arXiv:1108.4318, 2011) to find commuting sets. Except uses commutation check from arXiv:1405.5749v2

Parameters:pauli_terms (PauliSum) – A PauliSum object
Returns:List of lists where each list contains a commuting set
Return type:list
pyquil.paulis.exponential_map(term)[source]

Creates map alpha -> exp(-1j*alpha*term) represented as a Program.

Parameters:term (PauliTerm) – Tests is a PauliTerm is the identity operator
Returns:Program
Return type:Function
pyquil.paulis.exponentiate(term)[source]

Creates a pyQuil program that simulates the unitary evolution exp(-1j * term)

Parameters:term (PauliTerm) – Tests is a PauliTerm is the identity operator
Returns:A Program object
Return type:Program
pyquil.paulis.exponentiate_commuting_pauli_sum(pauli_sum)[source]

Returns a function that maps all substituent PauliTerms and sums them into a program. NOTE: Use this function with care. Substituent PauliTerms should commute.

Parameters:pauli_sum (PauliSum) – PauliSum to exponentiate.
Returns:A function that parametrizes the exponential.
Return type:function
pyquil.paulis.integer_types = (<class 'int'>, <class 'numpy.int64'>, <class 'numpy.int32'>, <class 'numpy.int16'>, <class 'numpy.int8'>)

Explicitly include numpy integer dtypes (for python 3).

pyquil.paulis.is_identity(term)[source]

Check if Pauli Term is a scalar multiple of identity

Parameters:term (PauliTerm) – A PauliTerm object
Returns:True if the PauliTerm is a scalar multiple of identity, false otherwise
Return type:bool
pyquil.paulis.is_zero(pauli_object)[source]

Tests to see if a PauliTerm or PauliSum is zero.

Parameters:pauli_object – Either a PauliTerm or PauliSum
Returns:True if PauliTerm is zero, False otherwise
Return type:bool
pyquil.paulis.sI(q)[source]

A function that returns the identity operator on a particular qubit.

Parameters:qubit_index (int) – The index of the qubit
Returns:A PauliTerm object
Return type:PauliTerm
pyquil.paulis.sX(q)[source]

A function that returns the sigma_X operator on a particular qubit.

Parameters:qubit_index (int) – The index of the qubit
Returns:A PauliTerm object
Return type:PauliTerm
pyquil.paulis.sY(q)[source]

A function that returns the sigma_Y operator on a particular qubit.

Parameters:qubit_index (int) – The index of the qubit
Returns:A PauliTerm object
Return type:PauliTerm
pyquil.paulis.sZ(q)[source]

A function that returns the sigma_Z operator on a particular qubit.

Parameters:qubit_index (int) – The index of the qubit
Returns:A PauliTerm object
Return type:PauliTerm
pyquil.paulis.simplify_pauli_sum(pauli_sum)[source]
pyquil.paulis.suzuki_trotter(trotter_order, trotter_steps)[source]

Generate trotterization coefficients for a given number of Trotter steps.

U = exp(A + B) is approximated as exp(w1*o1)exp(w2*o2)… This method returns a list [(w1, o1), (w2, o2), … , (wm, om)] of tuples where o=0 corresponds to the A operator, o=1 corresponds to the B operator, and w is the coefficient in the exponential. For example, a second order Suzuki-Trotter approximation to exp(A + B) results in the following [(0.5/trotter_steps, 0), (1/trotteri_steps, 1), (0.5/trotter_steps, 0)] * trotter_steps.

Parameters:
  • trotter_order (int) – order of Suzuki-Trotter approximation
  • trotter_steps (int) – number of steps in the approximation
Returns:

List of tuples corresponding to the coefficient and operator type: o=0 is A and o=1 is B.

Return type:

list

pyquil.paulis.term_with_coeff(term, coeff)[source]

Change the coefficient of a PauliTerm.

Parameters:
  • term (PauliTerm) – A PauliTerm object
  • coeff (Number) – The coefficient to set on the PauliTerm
Returns:

A new PauliTerm that duplicates term but sets coeff

Return type:

PauliTerm

pyquil.paulis.trotterize(first_pauli_term, second_pauli_term, trotter_order=1, trotter_steps=1)[source]

Create a Quil program that approximates exp( (A + B)t) where A and B are PauliTerm operators.

Parameters:
  • first_pauli_term (PauliTerm) – PauliTerm denoted A
  • second_pauli_term (PauliTerm) – PauliTerm denoted B
  • trotter_order (int) – Optional argument indicating the Suzuki-Trotter approximation order–only accepts orders 1, 2, 3, 4.
  • trotter_steps (int) – Optional argument indicating the number of products to decompose the exponential into.
Returns:

Quil program

Return type:

Program

pyquil.quil

Module for creating and defining Quil programs.

class pyquil.quil.Program(*instructions)[source]

Bases: object

alloc()[source]

Get a new qubit.

Returns:A qubit.
Return type:Qubit
dagger(inv_dict=None, suffix='-INV')[source]

Creates the conjugate transpose of the Quil program. The program must not contain any irreversible actions (measurement, control flow, qubit allocation).

Returns:The Quil program’s inverse
Return type:Program
defgate(name, matrix, parameters=None)[source]

Define a new static gate.

Note

The matrix elements along each axis are ordered by bitstring. For two qubits the order is 00, 01, 10, 11, where the the bits are ordered in reverse by the qubit index, i.e., for qubits 0 and 1 the bitstring 01 indicates that qubit 0 is in the state 1. See also the related documentation section in the QVM Overview.

Parameters:
  • name (string) – The name of the gate.
  • matrix (array-like) – List of lists or Numpy 2d array.
  • parameters (list) – list of parameters that are used in this gate
Returns:

The Program instance.

Return type:

Program

define_noisy_gate(name, qubit_indices, kraus_ops)[source]

Overload a static ideal gate with a noisy one defined in terms of a Kraus map.

Note

The matrix elements along each axis are ordered by bitstring. For two qubits the order is 00, 01, 10, 11, where the the bits are ordered in reverse by the qubit index, i.e., for qubits 0 and 1 the bitstring 01 indicates that qubit 0 is in the state 1. See also the related documentation section in the QVM Overview.

Parameters:
  • name (str) – The name of the gate.
  • qubit_indices (tuple|list) – The qubits it acts on.
  • kraus_ops (tuple|list) – The Kraus operators.
Returns:

The Program instance

Return type:

Program

define_noisy_readout(qubit, p00, p11)[source]

For this program define a classical bit flip readout error channel parametrized by p00 and p11. This models the effect of thermal noise that corrupts the readout signal after it has interrogated the qubit.

Parameters:
  • qubit (int|QubitPlaceholder) – The qubit with noisy readout.
  • p00 (float) – The probability of obtaining the measurement result 0 given that the qubit is in state 0.
  • p11 (float) – The probability of obtaining the measurement result 1 given that the qubit is in state 1.
Returns:

The Program with an appended READOUT-POVM Pragma.

Return type:

Program

defined_gates

A list of defined gates on the program.

gate(name, params, qubits)[source]

Add a gate to the program.

Note

The matrix elements along each axis are ordered by bitstring. For two qubits the order is 00, 01, 10, 11, where the the bits are ordered in reverse by the qubit index, i.e., for qubits 0 and 1 the bitstring 01 indicates that qubit 0 is in the state 1. See also the related documentation section in the QVM Overview.

Parameters:
  • name (string) – The name of the gate.
  • params (list) – Parameters to send to the gate.
  • qubits (list) – Qubits that the gate operates on.
Returns:

The Program instance

Return type:

Program

get_qubits(indices=True)[source]

Returns all of the qubit indices used in this program, including gate applications and allocated qubits. e.g.

>>> p = Program()
>>> p.inst(("H", 1))
>>> p.get_qubits()
{1}
>>> q = p.alloc()
>>> p.inst(H(q))
>>> len(p.get_qubits())
2
Parameters:indices – Return qubit indices as integers intead of the wrapping Qubit object
Returns:A set of all the qubit indices used in this program
Return type:set
if_then(classical_reg, if_program, else_program=None)[source]

If the classical register at index classical reg is 1, run if_program, else run else_program.

Equivalent to the following construction:

IF [c]:
   instrA...
ELSE:
   instrB...
=>
  JUMP-WHEN @THEN [c]
  instrB...
  JUMP @END
  LABEL @THEN
  instrA...
  LABEL @END
Parameters:
  • classical_reg (int) – The classical register to check as the condition
  • if_program (Program) – A Quil program to execute if classical_reg is 1
  • else_program (Program) – A Quil program to execute if classical_reg is 0. This argument is optional and defaults to an empty Program.
Returns:

The Quil Program with the branching instructions added.

Return type:

Program

inst(*instructions)[source]

Mutates the Program object by appending new instructions.

This function accepts a number of different valid forms, e.g.

>>> p = Program()
>>> p.inst(H(0)) # A single instruction
>>> p.inst(H(0), H(1)) # Multiple instructions
>>> p.inst([H(0), H(1)]) # A list of instructions
>>> p.inst(H(i) for i in range(4)) # A generator of instructions
>>> p.inst(("H", 1)) # A tuple representing an instruction
>>> p.inst("H 0") # A string representing an instruction
>>> q = Program()
>>> p.inst(q) # Another program
It can also be chained:
>>> p = Program()
>>> p.inst(H(0)).inst(H(1))
Parameters:instructions – A list of Instruction objects, e.g. Gates
Returns:self for method chaining
instructions

Fill in any placeholders and return a list of quil AbstractInstructions.

is_protoquil()[source]

Protoquil programs may only contain gates, no classical instructions and no jumps.

Returns:True if the Program is Protoquil, False otherwise
measure(qubit_index, classical_reg=None)[source]

Measures a qubit at qubit_index and puts the result in classical_reg

Parameters:
  • qubit_index (int) – The address of the qubit to measure.
  • classical_reg (int) – The address of the classical bit to store the result.
Returns:

The Quil Program with the appropriate measure instruction appended, e.g. MEASURE 0 [1]

Return type:

Program

measure_all(*qubit_reg_pairs)[source]

Measures many qubits into their specified classical bits, in the order they were entered. If no qubit/register pairs are provided, measure all qubits present in the program into classical addresses of the same index.

Parameters:qubit_reg_pairs (Tuple) – Tuples of qubit indices paired with classical bits.
Returns:The Quil Program with the appropriate measure instructions appended, e.g.
MEASURE 0 [1]
MEASURE 1 [2]
MEASURE 2 [3]
Return type:Program
no_noise()[source]

Prevent a noisy gate definition from being applied to the immediately following Gate instruction.

Returns:Program
out()[source]

Serializes the Quil program to a string suitable for submitting to the QVM or QPU.

pop()[source]

Pops off the last instruction.

Returns:The instruction that was popped.
Return type:tuple
while_do(classical_reg, q_program)[source]

While a classical register at index classical_reg is 1, loop q_program

Equivalent to the following construction:

WHILE [c]:
   instr...
=>
  LABEL @START
  JUMP-UNLESS @END [c]
  instr...
  JUMP @START
  LABEL @END
Parameters:
  • classical_reg (int) – The classical register to check
  • q_program (Program) – The Quil program to loop.
Returns:

The Quil Program with the loop instructions added.

Return type:

Program

pyquil.quil.address_qubits(program, qubit_mapping=None)[source]

Takes a program which contains placeholders and assigns them all defined values.

Either all qubits must be defined or all undefined. If qubits are undefined, you may provide a qubit mapping to specify how placeholders get mapped to actual qubits. If a mapping is not provided, integers 0 through N are used.

This function will also instantiate any label placeholders.

Parameters:
  • program – The program.
  • qubit_mapping – A dictionary-like object that maps from QubitPlaceholder to Qubit or int (but not both).
Returns:

A new Program with all qubit and label placeholders assigned to real qubits and labels.

pyquil.quil.get_classical_addresses_from_program(program)[source]

Returns a sorted list of classical addresses found in the MEASURE instructions in the program.

Parameters:program (Program) – The program from which to get the classical addresses.
Returns:A list of integer classical addresses.
Return type:list
pyquil.quil.get_default_qubit_mapping(program)[source]

Takes a program which contains qubit placeholders and provides a mapping to the integers 0 through N-1.

The output of this function is suitable for input to address_qubits().

Parameters:program – A program containing qubit placeholders
Returns:A dictionary mapping qubit placeholder to an addressed qubit from 0 through N-1.
pyquil.quil.instantiate_labels(instructions)[source]

Takes an iterable of instructions which may contain label placeholders and assigns them all defined values.

Returns:list of instructions with all label placeholders assigned to real labels.
pyquil.quil.merge_programs(prog_list)[source]

Merges a list of pyQuil programs into a single one by appending them in sequence

Parameters:prog_list (list) – A list of pyquil programs
Returns:a single pyQuil program
Return type:Program

pyquil.quilbase

Contains the core pyQuil objects that correspond to Quil instructions.

class pyquil.quilbase.AbstractInstruction[source]

Bases: object

Abstract class for representing single instructions.

out()[source]
class pyquil.quilbase.BinaryClassicalInstruction(left, right)[source]

Bases: pyquil.quilbase.AbstractInstruction

The abstract class for binary classical instructions.

out()[source]
class pyquil.quilbase.ClassicalAnd(left, right)[source]

Bases: pyquil.quilbase.BinaryClassicalInstruction

op = 'AND'
class pyquil.quilbase.ClassicalExchange(left, right)[source]

Bases: pyquil.quilbase.BinaryClassicalInstruction

op = 'EXCHANGE'
class pyquil.quilbase.ClassicalFalse(target)[source]

Bases: pyquil.quilbase.UnaryClassicalInstruction

op = 'FALSE'
class pyquil.quilbase.ClassicalMove(left, right)[source]

Bases: pyquil.quilbase.BinaryClassicalInstruction

op = 'MOVE'
class pyquil.quilbase.ClassicalNot(target)[source]

Bases: pyquil.quilbase.UnaryClassicalInstruction

op = 'NOT'
class pyquil.quilbase.ClassicalOr(left, right)[source]

Bases: pyquil.quilbase.BinaryClassicalInstruction

op = 'OR'
class pyquil.quilbase.ClassicalTrue(target)[source]

Bases: pyquil.quilbase.UnaryClassicalInstruction

op = 'TRUE'
class pyquil.quilbase.DefGate(name, matrix, parameters=None)[source]

Bases: pyquil.quilbase.AbstractInstruction

A DEFGATE directive.

Parameters:
  • name (string) – The name of the newly defined gate.
  • matrix (array-like) – {list, nparray, np.matrix} The matrix defining this gate.
  • parameters (list) – list of parameters that are used in this gate
get_constructor()[source]
Returns:A function that constructs this gate on variable qubit indices. E.g. mygate.get_constructor()(1) applies the gate to qubit 1.
num_args()[source]
Returns:The number of qubit arguments the gate takes.
Return type:int
out()[source]

Prints a readable Quil string representation of this gate.

Returns:String representation of a gate
Return type:string
class pyquil.quilbase.Gate(name, params, qubits)[source]

Bases: pyquil.quilbase.AbstractInstruction

This is the pyQuil object for a quantum gate instruction.

get_qubits(indices=True)[source]
out()[source]
class pyquil.quilbase.Halt[source]

Bases: pyquil.quilbase.SimpleInstruction

The HALT instruction.

op = 'HALT'
class pyquil.quilbase.Jump(target)[source]

Bases: pyquil.quilbase.AbstractInstruction

Representation of an unconditional jump instruction (JUMP).

out()[source]
class pyquil.quilbase.JumpConditional(target, condition)[source]

Bases: pyquil.quilbase.AbstractInstruction

Abstract representation of an conditional jump instruction.

out()[source]
class pyquil.quilbase.JumpTarget(label)[source]

Bases: pyquil.quilbase.AbstractInstruction

Representation of a target that can be jumped to.

out()[source]
class pyquil.quilbase.JumpUnless(target, condition)[source]

Bases: pyquil.quilbase.JumpConditional

The JUMP-UNLESS instruction.

op = 'JUMP-UNLESS'
class pyquil.quilbase.JumpWhen(target, condition)[source]

Bases: pyquil.quilbase.JumpConditional

The JUMP-WHEN instruction.

op = 'JUMP-WHEN'
class pyquil.quilbase.Measurement(qubit, classical_reg=None)[source]

Bases: pyquil.quilbase.AbstractInstruction

This is the pyQuil object for a Quil measurement instruction.

get_qubits(indices=True)[source]
out()[source]
class pyquil.quilbase.Nop[source]

Bases: pyquil.quilbase.SimpleInstruction

The NOP instruction.

op = 'NOP'
class pyquil.quilbase.Pragma(command, args=(), freeform_string='')[source]

Bases: pyquil.quilbase.AbstractInstruction

A PRAGMA instruction.

This is printed in QUIL as:

PRAGMA <command> <arg1> <arg2> ... <argn> "<freeform_string>"
out()[source]
class pyquil.quilbase.RawInstr(instr_str)[source]

Bases: pyquil.quilbase.AbstractInstruction

A raw instruction represented as a string.

out()[source]
class pyquil.quilbase.Reset[source]

Bases: pyquil.quilbase.SimpleInstruction

The RESET instruction.

op = 'RESET'
class pyquil.quilbase.SimpleInstruction[source]

Bases: pyquil.quilbase.AbstractInstruction

Abstract class for simple instructions with no arguments.

out()[source]
class pyquil.quilbase.UnaryClassicalInstruction(target)[source]

Bases: pyquil.quilbase.AbstractInstruction

The abstract class for unary classical instructions.

out()[source]
class pyquil.quilbase.Wait[source]

Bases: pyquil.quilbase.SimpleInstruction

The WAIT instruction.

op = 'WAIT'

pyquil.slot

Contains Slot pyQuil placeholders for constructing Quil template programs.

class pyquil.slot.Slot(value=0.0, func=None)[source]

Bases: object

A placeholder for a parameter value.

Arithmetic operations: +-*/
Logical: abs, max, <, >, <=, >=, !=, ==
Arbitrary functions are not supported
Parameters:
  • value (float) – A value to initialize to. Defaults to 0.0
  • func (function) – An initial function to determine the final parameterized value.
value()[source]

Computes the value of this Slot parameter.

pyquil.wavefunction

Module containing the Wavefunction object and methods for working with wavefunctions.

class pyquil.wavefunction.Wavefunction(amplitude_vector, classical_memory=None)[source]

Bases: object

Encapsulate a wavefunction representing a quantum state as returned by the QVM.

Note

The elements of the wavefunction are ordered by bitstring. E.g., for two qubits the order is 00, 01, 10, 11, where the the bits are ordered in reverse by the qubit index, i.e., for qubits 0 and 1 the bitstring 01 indicates that qubit 0 is in the state 1. See also the related documentation section in the QVM Overview.

static from_bit_packed_string(coef_string, classical_addresses)[source]

From a bit packed string, unpacks to get the wavefunction and classical measurement results :param bytes coef_string: :param list classical_addresses: :return:

get_outcome_probs()[source]

Parses a wavefunction (array of complex amplitudes) and returns a dictionary of outcomes and associated probabilities.

Returns:A dict with outcomes as keys and probabilities as values.
Return type:dict
static ground(qubit_num)[source]
plot(qubit_subset=None)[source]

Plots a bar chart with bitstring on the x axis and probability on the y axis.

Parameters:qubit_subset (list) – Optional parameter used for plotting a subset of the Hilbert space.
pretty_print(decimal_digits=2)[source]

Returns a string repr of the wavefunction, ignoring all outcomes with approximately zero amplitude (up to a certain number of decimal digits) and rounding the amplitudes to decimal_digits.

Parameters:decimal_digits (int) – The number of digits to truncate to.
Returns:A dict with outcomes as keys and complex amplitudes as values.
Return type:str
pretty_print_probabilities(decimal_digits=2)[source]

Prints outcome probabilities, ignoring all outcomes with approximately zero probabilities (up to a certain number of decimal digits) and rounding the probabilities to decimal_digits.

Parameters:decimal_digits (int) – The number of digits to truncate to.
Returns:A dict with outcomes as keys and probabilities as values.
Return type:dict
probabilities()[source]

Returns an array of probabilities in lexicographical order

sample_bitstrings(n_samples)[source]

Sample bitstrings from the distribution defined by the wavefunction.

Parameters:n_samples – The number of bitstrings to sample
Returns:An array of shape (n_samples, n_qubits)
static zeros(qubit_num)[source]

Constructs the groundstate wavefunction for a given number of qubits.

Parameters:qubit_num (int) –
Returns:A Wavefunction in the ground state
Return type:Wavefunction
pyquil.wavefunction.get_bitstring_from_index(index, qubit_num)[source]

Returns the bitstring in lexical order that corresponds to the given index in 0 to 2^(qubit_num) :param int index: :param int qubit_num: :return: the bitstring :rtype: str