Source Code Documentation¶
pyquil.api¶
Module for facilitating connections to the QVM / QPU.

class
pyquil.api.
QVMConnection
(device=None, endpoint=None, gate_noise=None, measurement_noise=None, random_seed=None, compiler_endpoint=None)[source]¶ Bases:
object
Represents a connection to the QVM.

expectation
(prep_prog, operator_programs=None)[source]¶ Calculate the expectation value of operators given a state prepared by prep_program.
Note: If the execution of quil_program
is nondeterministic, 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 differentexpectation
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: Returns: Expectation values of the operators.
Return type: List[float]

get_version_info
()[source]¶ Return version information for the QVM.
Returns: Dictionary with version information

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 aPauliSum
then the returned value is a singlefloat
, otherwise the returned value is a list offloat``s, one for each ``PauliTerm
in the list.Note: If the execution of
quil_program
is nondeterministic, 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 differentexpectation
calls will then generally be different.Parameters: Returns: If
pauli_terms
is a PauliSum return its expectation value. Otherwise return a list of expectation values.Return type: floatList[float]

run
(quil_program, classical_addresses: List[int] = None, trials=1)[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 – The classical memory to retrieve. Specified as a list of
integers that index into a readout register named
ro
. This function–and particularly this argument–are included for backwards compatibility and will be removed in the future.  trials (int) – Number of shots to collect.
Returns: A list of dictionaries of bits. Each dictionary corresponds to the values in classical_addresses.
Return type:

run_and_measure
(quil_program, qubits, trials=1)[source]¶ Run a Quil program once to determine the final wavefunction, and measure multiple times.
Note: If the execution of
quil_program
is nondeterministic, 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 differentrun_and_measure
calls generally sample different bitstring distributions.Parameters: Returns: A list of a list of bits.
Return type:

wavefunction
(quil_program)[source]¶ Simulate a Quil program and get the wavefunction back.
Note: If the execution of quil_program
is nondeterministic, 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 differentwavefunction
calls will generally be different.Parameters: quil_program (Program) – A Quil program. Returns: A Wavefunction object representing the state of the QVM. Return type: Wavefunction


class
pyquil.api.
LocalQVMCompiler
(endpoint: str, device: pyquil.device.AbstractDevice)[source]¶ Bases:
pyquil.api._qac.AbstractCompiler

get_version_info
() → dict[source]¶ Return version information for this compiler and its dependencies.
Returns: Dictionary of version information.


class
pyquil.api.
QVMCompiler
(endpoint: str, device: pyquil.device.AbstractDevice)[source]¶ Bases:
pyquil.api._qac.AbstractCompiler

get_version_info
() → dict[source]¶ Return version information for this compiler and its dependencies.
Returns: Dictionary of version information.


class
pyquil.api.
QPUCompiler
(endpoint: str, device: pyquil.device.AbstractDevice)[source]¶ Bases:
pyquil.api._qac.AbstractCompiler

get_version_info
() → dict[source]¶ Return version information for this compiler and its dependencies.
Returns: Dictionary of version information.


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]

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 nonfaulttolerant 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 nonfaulttolerant 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]

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 nonfaulttolerant 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]


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 inself._raw
–isa
andnoise_model
– which should conform to the dictionary format required by the.from_dict()
methods forISA
andNoiseModel
, 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 onequbit gates to target
 twoq_type – The family of twoqubit gates to target

isa
¶

class
pyquil.api.
ForestConnection
(sync_endpoint=None, compiler_endpoint=None, forest_cloud_endpoint=None)[source]¶ Bases:
object

pyquil.api.
pyquil_protect
(func, log_filename='pyquil_error.log')[source]¶ A decorator that sets up an error context, captures errors, and tears down the context.

class
pyquil.api.
WavefunctionSimulator
(connection: pyquil.api._base_connection.ForestConnection = None, random_seed: Optional[int] = 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 aPauliSum
then the returned value is a singlefloat
, otherwise the returned value is an array of values, one for eachPauliTerm
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 nondeterministic then the final wavefunction from which the expectation value is calculated only represents a stochastically generated sample and the wavefunctions returned by differentwavefunction
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 callingsample_bitstrings
on the resulting object.For a large wavefunction and a lowmedium 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 nondeterministic then the final wavefunction from which the returned bitstrings are sampled itself only represents a stochastically generated sample and the outcomes sampled from differentrun_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))

wavefunction
(quil_program: pyquil.quil.Program) → 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 nondeterministic then the final wavefunction only represents a stochastically generated sample and the wavefunctions returned by differentwavefunction
calls will generally be different.Parameters: quil_program – A Quil program. Returns: A Wavefunction object representing the state of the QVM.


class
pyquil.api.
QuantumComputer
(*, name: str, qam: pyquil.api._qam.QAM, device: pyquil.device.AbstractDevice, compiler: pyquil.api._qac.AbstractCompiler, symmetrize_readout: bool = False)[source]¶ Bases:
object

compile
(program: pyquil.quil.Program, to_native_gates: bool = True, optimize: bool = True) → rpcq._base.Message[source]¶

qubit_topology
() → <module 'networkx.classes.graph' from '/home/docs/checkouts/readthedocs.org/user_builds/pyquil/envs/v2.0.0/lib/python3.6/sitepackages/networkx/classes/graph.py'>[source]¶

run
(executable: Union[rpcq.messages.BinaryExecutableResponse, rpcq.messages.PyQuilExecutableResponse]) → numpy.ndarray[source]¶ Run a quil executable.
Parameters: executable – The program to run. You are responsible for compiling this first. Returns: A numpy array of shape (trials, len(roregister)) that contains 0s and 1s

run_and_measure
(program: pyquil.quil.Program, trials: int) → Dict[int, numpy.ndarray][source]¶ Run the provided state preparation program and measure all qubits.
This will measure all the qubits on this QuantumComputer, not just qubits that are used in the program.
The returned data is a dictionary keyed by qubit index because qubits for a given QuantumComputer may be noncontiguous and nonzeroindexed. To turn this dictionary into a 2d numpy array of bitstrings, consider:
bitstrings = qc.run_and_measure(...) bitstring_array = np.vstack(bitstrings[q] for q in sorted(qc.qubits())).T bitstring_array.shape # (trials, len(qc.qubits()))
Note
In contrast to
QVMConnection.run_and_measure
, this method simulates noise correctly for noisy QVMs. However, this method is slower fortrials > 1
. For faster noisefree simulation, considerWavefunctionSimulator.run_and_measure
.Parameters:  program – The state preparation program to run and then measure.
 trials – The number of times to run the program.
Returns: A dictionary keyed by qubit index where the corresponding value is a 1D array of measured bits.

run_symmetrized_readout
(program: pyquil.quil.Program, trials: int) → numpy.ndarray[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 bitstringc
is the same as the probability ofnot(b)
being mistaken fornot(c)
A more general symmetrization would guarantee that the probability of
b
being mistaken forc
depends only on which bit ofc
are different fromb
. 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 anX
gate prior to anyMEASURE
instruction and then flip the measured classical bit back.See
run()
for this function’s parameter descriptions.


pyquil.api.
list_quantum_computers
(connection: pyquil.api._base_connection.ForestConnection = None, qpus: bool = True, qvms: bool = True) → List[str][source]¶ List the names of available quantum computers
Parameters:  connection – An optional :py:class:ForestConnection` object. If not specified,
the default values for URL endpoints will be used, and your API key
will be read from ~/.pyquil_config. If you deign to change any
of these parameters, pass your own
ForestConnection
object.  qpus – Whether to include QPU’s in the list.
 qvms – Whether to include QVM’s in the list.
 connection – An optional :py:class:ForestConnection` object. If not specified,
the default values for URL endpoints will be used, and your API key
will be read from ~/.pyquil_config. If you deign to change any
of these parameters, pass your own

pyquil.api.
get_qc
(name: str, *, as_qvm: bool = None, noisy: bool = None, connection: pyquil.api._base_connection.ForestConnection = None) → pyquil.api._quantum_computer.QuantumComputer[source]¶ Get a quantum computer.
A quantum computer is an object of type
QuantumComputer
and can be backed either by a QVM simulator (“Quantum/Quil Virtual Machine”) or a physical Rigetti QPU (“Quantum Processing Unit”) made of superconducting qubits.You can choose the quantum computer to target through a combination of its name and optional flags. There are multiple ways to get the same quantum computer. The following are equivalent:
>>> qc = get_qc("Aspen012QAnoisyqvm") >>> qc = get_qc("Aspen012QA", as_qvm=True, noisy=True)
and will construct a simulator of the 8qagave chip with a noise model based on device characteristics. We also provide a means for constructing generic quantum simulators that are not related to a given piece of Rigetti hardware:
>>> qc = get_qc("9qsquareqvm") >>> qc = get_qc("9qsquare", as_qvm=True)
Finally, you can get request a QVM with “no” topology of a given number of qubits (technically, it’s a fully connected graph among the given number of qubits) with:
>>> qc = get_qc("5qqvm") # or "6qqvm", or "34qqvm", ...
These lessrealistic, fullyconnected QVMs will also be more lenient on what types of programs they will
run
. Specifically, you do not need to do any compilation. For the other, realistic QVMs you must useqc.compile()
orqc.compiler.native_quil_to_executable()
prior toqc.run()
.Redundant flags are acceptable, but conflicting flags will raise an exception:
>>> qc = get_qc("9qsquareqvm") # qc is fully specified by its name >>> qc = get_qc("9qsquareqvm", as_qvm=True) # redundant, but ok >>> qc = get_qc("9qsquareqvm", as_qvm=False) # Error!
Use
list_quantum_computers()
to retrieve a list of known qc names.This method is provided as a convenience to quickly construct and use QVM’s and QPU’s. Power users may wish to have more control over the specification of a quantum computer (e.g. custom noise models, bespoke topologies, etc.). This is possible by constructing a
QuantumComputer
object by hand. Please refer to the documentation onQuantumComputer
for more information.Parameters:  name – The name of the desired quantum computer. This should correspond to a name
returned by
list_quantum_computers()
. Names ending in “qvm” will return a QVM. Names ending in “noisyqvm” will return a QVM with a noise model. Otherwise, we will return a QPU with the given name.  as_qvm – An optional flag to force construction of a QVM (instead of a QPU). If
specified and set to
True
, a QVMbacked quantum computer will be returned regardless of the name’s suffix  noisy – An optional flag to force inclusion of a noise model. If
specified and set to
True
, a quantum computer with a noise model will be returned regardless of the name’s suffix. The noise model for QVM’s based on a real QPU is an empirically parameterized model based on real device noise characteristics. The generic QVM noise model is simple T1 and T2 noise plus readout error. Seedecoherance_noise_with_asymmetric_ro()
.  connection – An optional :py:class:ForestConnection` object. If not specified,
the default values for URL endpoints, ping time, and status time will be used. Your
user id and API key will be read from ~/.pyquil_config. If you deign to change any
of these parameters, pass your own
ForestConnection
object.
Returns:  name – The name of the desired quantum computer. This should correspond to a name
returned by

class
pyquil.api.
QAM
[source]¶ Bases:
abc.ABC
The platonic ideal of this class is as a generic interface describing how a classical computer interacts with a live quantum computer. Eventually, it will turn into a thin layer over the QPU and QVM’s “QPI” interfaces.
The reality is that neither the QPU nor the QVM currently support a fullon QPI interface, and so the undignified job of this class is to collect enough state that it can convincingly pretend to be a QPIcompliant quantum computer.

load
(executable)[source]¶ Initialize a QAM into a fresh state.
Parameters: executable – Load a compiled executable onto the QAM.

read_from_memory_region
(*, region_name: str)[source]¶ Reads from a memory region named region_name on the QAM.
This is a shim over the eventual API and only can return memory from a region named “ro” of type
BIT
.Parameters: region_name – The string naming the declared memory region. Returns: A list of values of the appropriate type.

read_memory
(*, region_name: str)[source]¶ Reads from a memory region named region_name on the QAM.
This is a shim over the eventual API and only can return memory from a region named “ro” of type
BIT
.Parameters: region_name – The string naming the declared memory region. Returns: A list of values of the appropriate type.

write_memory
(*, region_name: str, offset: int = 0, value=None)[source]¶ Writes a value into a memory region on the QAM at a specified offset.
Parameters:  region_name – Name of the declared memory region on the QAM.
 offset – Integer offset into the memory region to write to.
 value – Value to store at the indicated location.


class
pyquil.api.
QVM
(connection: pyquil.api._base_connection.ForestConnection, noise_model=None, gate_noise=None, measurement_noise=None, random_seed=None, requires_executable=False)[source]¶ Bases:
pyquil.api._qam.QAM

get_version_info
()[source]¶ Return version information for the QVM.
Returns: Dictionary with version information

load
(executable)[source]¶ Initialize a QAM and load a program to be executed with a call to
run()
.If
QVM.requires_executable
is set toTrue
, this function will only loadPyQuilExecutableResponse
executables. This more closely follows the behavior ofQPU
. However, the quantum simulator doesn’t actually need a compiled binary executable, so if this flag is set toFalse
we also acceptProgram
objects.Parameters: executable – An executable. See the above note for acceptable types.


class
pyquil.api.
QPU
(endpoint: str, user: str = 'pyquiluser')[source]¶ Bases:
pyquil.api._qam.QAM

get_version_info
() → dict[source]¶ Return version information for this QPU’s execution engine and its dependencies.
Returns: Dictionary of version information.

run
()[source]¶ Run a pyquil program on the QPU.
This formats the classified data from the QPU server by stacking measured bits into an array of shape (trials, classical_addresses). The mapping of qubit to classical address is backed out from MEASURE instructions in the program, so only do measurements where there is a 1to1 mapping between qubits and classical addresses.
Returns: The QPU object itself.


class
pyquil.api.
BenchmarkConnection
(endpoint=None)[source]¶ Bases:
pyquil.api._qac.AbstractBenchmarker
Represents a connection to a server that generates benchmarking data.

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: Returns: A PauliTerm corresponding to pauli_in * clifford * pauli_in^{dagger}

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.


class
pyquil.api.
LocalBenchmarkConnection
(endpoint=None)[source]¶ Bases:
pyquil.api._qac.AbstractBenchmarker
Represents a connection to a locallyrunning server that generates randomized benchmarking data.

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: Returns: A PauliTerm corresponding to pauli_in * clifford * pauli_in^{dagger}

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 – A positive integer used to seed the PRNG.
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.


pyquil.api.
get_benchmarker
(endpoint: str = None)[source]¶ Retrieve an instance of the appropriate AbstractBenchmarker subclass for a given endpoint.
Parameters: endpoint – Benchmarking sequence server address. Defaults to the setting in the user’s pyQuil config. Returns: Instance of an AbstractBenchmarker subclass, connected to the given endpoint.
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 onequbit gates to target
 twoq_type – The family of twoqubit gates to target


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 inself._raw
–isa
andnoise_model
– which should conform to the dictionary format required by the.from_dict()
methods forISA
andNoiseModel
, 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 onequbit gates to target
 twoq_type – The family of twoqubit gates to target

isa
¶

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: 
static
from_dict
(d)[source]¶ Recreate 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 JSONserializable representation of the ISA.
The dictionary representation is of the form:
{ "1Q": { "0": { "type": "Xhalves" }, "1": { "type": "Xhalves", "dead": True }, ... }, "2Q": { "14": { "type": "CZ" }, "15": { "type": "CZ" }, ... }, ... }
Returns: A dictionary representation of self. Return type: Dict[str, Any]

static

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 viaget_devices()
. Instead, the user is responsible for constructing a NetworkX graph which represents a chip topology.
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 onequbit gates to target
 twoq_type – The family of twoqubit gates to target


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 qubitqubit 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 singlequbit 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]

fActiveResets
()[source]¶ Get a dictionary of singlequbit active reset fidelities (normalized to unity) from the specs, keyed by qubit index.
Returns: A dictionary of reset fidelities, normalized to unity.

fBellStates
()[source]¶ Get a dictionary of twoqubit Bell state fidelities (normalized to unity) from the specs, keyed by targets (qubitqubit 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 (qubitqubit 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 (qubitqubit pairs).
Returns: A dictionary of CZ fidelities, normalized to unity. Return type: Dict[tuple(int, int), float]

fROs
()[source]¶ Get a dictionary of singlequbit 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]¶ Recreate 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 JSONserializable representation of the device Specs.
The dictionary representation is of the form:
{ '1Q': { "0": { "f1QRB": 0.99, "T1": 20e6, ... }, "1": { "f1QRB": 0.989, "T1": 19e6, ... }, ... }, '2Q': { "14": { "fBellState": 0.93, "fCZ": 0.92, "fCPHASE": 0.91 }, "15": { "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 1qubit gate. Currently ‘Xhalves’
 twoq_type – The type of 2qubit gate. One of ‘CZ’ or ‘CPHASE’.
pyquil.gates¶

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.
X
(qubit)[source]¶ Produces the X instruction.
 X = [[0, 1],
 [1, 0]]
This gate is a single qubit Xgate.
Parameters: qubit – The qubit apply the gate to. Returns: A Gate object.

pyquil.gates.
Y
(qubit)[source]¶ Produces the Y instruction.
 Y = [[0, 0  1j],
 [0 + 1j, 0]]
This gate is a single qubit Ygate.
Parameters: 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 Zgate.
Parameters: qubit – The qubit apply the gate to. Returns: A Gate object.

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.
S
(qubit)[source]¶ Produces the S instruction.
 S = [[1, 0],
 [0, 1j]]
This gate is a single qubit Sgate.
Parameters: 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 Tgate. It is the same as RZ(pi/4).
Parameters: qubit – The qubit apply the gate to. Returns: A Gate object.

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 zaxis on the bloch sphere.
 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 Xrotation.
Parameters:  angle – The angle to rotate around the xaxis on the bloch sphere.
 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 Yrotation.
Parameters:  angle – The angle to rotate around the yaxis on the bloch sphere.
 qubit – The qubit apply the gate to.
Returns: A Gate object.

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 Zrotation.
Parameters:  angle – The angle to rotate around the zaxis 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 controlledZ gate instruction.
Parameters:  control – The control qubit.
 target – The target qubit. The target qubit has an Zgate applied to it if the control qubit is in the excited state.
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 controllednot gate instruction.
Parameters:  control – The control qubit.
 target – The target qubit. The target qubit has an Xgate applied to it if the control qubit is in the excited state.
Returns: A Gate object.

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 controlledcontrollednot gate instruction.
Parameters:  control1 – The first control qubit.
 control2 – The second control qubit.
 target – The target qubit. The target qubit has an Xgate applied to it if both control qubits are in the excited state.
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.
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.
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.
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.
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.
 target1 – The first target qubit.
 target2 – The second target qubit. The two target states are swapped if the control is in the excited state.

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.
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.
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.
RESET
(qubit_index=None)[source]¶ Reset all qubits or just a specific qubit at qubit_index.
Parameters: qubit_index (Optional[int]) – The address of the qubit to reset. If None, reset all qubits. Returns: A Reset or ResetQubit Quil AST expression corresponding to a global or targeted reset, respectively. Return type: Union[Reset, ResetQubit]

pyquil.gates.
NOP
= <pyquil.quilbase.Nop object>¶ This instruction applies no operation at that timestep. Typically these are ignored in errormodels.
Returns: A Nop object.

pyquil.gates.
HALT
= <pyquil.quilbase.Halt object>¶ This instruction ends the program.
Returns: A Halt 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.
TRUE
(classical_reg)[source]¶ Produce a TRUE instruction.
Parameters: classical_reg – A classical register to modify. Returns: An instruction object representing the equivalent MOVE.

pyquil.gates.
FALSE
(classical_reg)[source]¶ Produce a FALSE instruction.
Parameters: classical_reg – A classical register to modify. Returns: An instruction object representing the equivalent MOVE.

pyquil.gates.
NOT
(classical_reg)[source]¶ Produce a NOT instruction.
Parameters: classical_reg – A classical register to modify. Returns: A ClassicalNot instance.

pyquil.gates.
AND
(classical_reg1, classical_reg2)[source]¶ Produce an AND instruction.
NOTE: The order of operands was reversed in pyQuil <=1.9 .
Parameters:  classical_reg1 – The first classical register, which gets modified.
 classical_reg2 – The second classical register or immediate value.
Returns: A ClassicalAnd instance.

pyquil.gates.
OR
(classical_reg1, classical_reg2)[source]¶ Produce an OR instruction.
NOTE: Deprecated. Use IOR instead.
Parameters:  classical_reg1 – The first classical register.
 classical_reg2 – The second classical register, which gets modified.
Returns: A ClassicalOr instance.

pyquil.gates.
MOVE
(classical_reg1, classical_reg2)[source]¶ Produce a MOVE instruction.
Parameters:  classical_reg1 – The first classical register, which gets modified.
 classical_reg2 – The second classical register or immediate value.
Returns: A ClassicalMove instance.

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.
IOR
(classical_reg1, classical_reg2)[source]¶ Produce an inclusive OR instruction.
Parameters:  classical_reg1 – The first classical register, which gets modified.
 classical_reg2 – The second classical register or immediate value.
Returns: A ClassicalOr instance.

pyquil.gates.
XOR
(classical_reg1, classical_reg2)[source]¶ Produce an exclusive OR instruction.
Parameters:  classical_reg1 – The first classical register, which gets modified.
 classical_reg2 – The second classical register or immediate value.
Returns: A ClassicalOr instance.

pyquil.gates.
NEG
(classical_reg)[source]¶ Produce a NEG instruction.
Parameters: classical_reg – A classical memory address to modify. Returns: A ClassicalNeg instance.

pyquil.gates.
ADD
(classical_reg, right)[source]¶ Produce an ADD instruction.
Parameters:  classical_reg – Left operand for the arithmetic operation. Also serves as the store target.
 right – Right operand for the arithmetic operation.
Returns: A ClassicalAdd instance.

pyquil.gates.
SUB
(classical_reg, right)[source]¶ Produce a SUB instruction.
Parameters:  classical_reg – Left operand for the arithmetic operation. Also serves as the store target.
 right – Right operand for the arithmetic operation.
Returns: A ClassicalSub instance.

pyquil.gates.
MUL
(classical_reg, right)[source]¶ Produce a MUL instruction.
Parameters:  classical_reg – Left operand for the arithmetic operation. Also serves as the store target.
 right – Right operand for the arithmetic operation.
Returns: A ClassicalMul instance.

pyquil.gates.
DIV
(classical_reg, right)[source]¶ Produce an DIV instruction.
Parameters:  classical_reg – Left operand for the arithmetic operation. Also serves as the store target.
 right – Right operand for the arithmetic operation.
Returns: A ClassicalDiv instance.

pyquil.gates.
EQ
(classical_reg1, classical_reg2, classical_reg3)[source]¶ Produce an EQ instruction.
Parameters:  classical_reg1 – Memory address to which to store the comparison result.
 classical_reg2 – Left comparison operand.
 classical_reg3 – Right comparison operand.
Returns: A ClassicalEqual instance.

pyquil.gates.
GT
(classical_reg1, classical_reg2, classical_reg3)[source]¶ Produce an GT instruction.
Parameters:  classical_reg1 – Memory address to which to store the comparison result.
 classical_reg2 – Left comparison operand.
 classical_reg3 – Right comparison operand.
Returns: A ClassicalGreaterThan instance.

pyquil.gates.
GE
(classical_reg1, classical_reg2, classical_reg3)[source]¶ Produce an GE instruction.
Parameters:  classical_reg1 – Memory address to which to store the comparison result.
 classical_reg2 – Left comparison operand.
 classical_reg3 – Right comparison operand.
Returns: A ClassicalGreaterEqual instance.

pyquil.gates.
LE
(classical_reg1, classical_reg2, classical_reg3)[source]¶ Produce an LE instruction.
Parameters:  classical_reg1 – Memory address to which to store the comparison result.
 classical_reg2 – Left comparison operand.
 classical_reg3 – Right comparison operand.
Returns: A ClassicalLessEqual instance.

pyquil.gates.
LT
(classical_reg1, classical_reg2, classical_reg3)[source]¶ Produce an LT instruction.
Parameters:  classical_reg1 – Memory address to which to store the comparison result.
 classical_reg2 – Left comparison operand.
 classical_reg3 – Right comparison operand.
Returns: A ClassicalLessThan instance.

pyquil.gates.
LOAD
(target_reg, region_name, offset_reg)[source]¶ Produce a LOAD instruction.
Parameters:  target_reg – LOAD storage target.
 region_name – Named region of memory to load from.
 offset_reg – Offset into region of memory to load from. Must be a MemoryReference.
Returns: A ClassicalLoad instance.

pyquil.gates.
STORE
(region_name, offset_reg, source)[source]¶ Produce a STORE instruction.
Parameters:  region_name – Named region of memory to store to.
 offset_reg – Offset into memory region. Must be a MemoryReference.
 source – Source data. Can be either a MemoryReference or a constant.
Returns: A ClassicalStore instance.
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], # elementwise real part of matrix [0, 0]], [[0, 1], # elementwise 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 JSONable pair of real matrices (as nested lists) representing the elementwise 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]¶ Recreate 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=3e05, T2=3e05, gate_time_1q=5e08, gate_time_2q=1.5e07, ro_fidelity=0.95)[source]¶ Add generic damping and dephasing noise to a program.
This highlevel function is provided as a convenience to investigate the effects of a generic noise model on a program. For more finegrained 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 nearterm 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 onequbit gates, namely RX(+pi/2) and RX(pi/2). By default, this is 50 ns.
 gate_time_2q (float) – The duration of the twoqubit gates, namely CZ. By default, this is 150 ns.
 ro_fidelity (Union[Dict[int,float],float]) – The readout assignment fidelity \(F = (p(00) + p(11))/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 bykraus_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 ‘noisyfied’ 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:

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 thatp[i,j,...,k]
gives the estimated probability of bitstringij...k
.Returns: z_moments
, an np.array with one length2 axis per qubit which contains the expectations of all monomials in{I, Z_0, Z_1, ..., Z_{n1}}
. 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: 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 thatp[i,j,...,k]
gives the estimated probability of bitstringij...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 noisyreadoutcorrected estimated probabilities for each measured bitstring, i.e.,p[i,j,...,k]
gives the estimated probability of bitstringij...k
.Return type: np.array
 p (np.array) – An array that enumerates bitstring probabilities. When
flattened out

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 thatp[i,j,...,k]
gives the estimated probability of bitstringij...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 noisyreadoutcorrected estimated probabilities for each measured bitstring, i.e.,p[i,j,...,k]
gives the estimated probability of bitstringij...k
.Return type: np.array
 p (np.array) – An array that enumerates bitstring probabilities. When
flattened out

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: 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 onestep damping probability. Returns: A list [k1, k2] of the Kraus operators that parametrize the map. Return type: list

pyquil.noise.
decoherence_noise_with_asymmetric_ro
(gates: Sequence[pyquil.quilbase.Gate], p00=0.975, p11=0.911)[source]¶ Similar to :py:func`_decoherence_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 onestep 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 bitstringij...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: 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.
pauli_kraus_map
(probabilities)[source]¶ Generate the Kraus operators corresponding to a pauli channel.
Params listfloats probabilities: The 4^num_qubits list of probabilities specifying the desired pauli channel. There should be either 4 or 16 probabilities specified in the order I, X, Y, Z for 1 qubit or II, IX, IY, IZ, XI, XX, XY, etc for 2 qubits.
For example:
The ddimensional depolarizing channel \Delta parameterized as \Delta(\rho) = p \rho + [(1p)/d] I is specified by the list of probabilities [p + (1p)/d, (1p)/d, (1p)/d), ... , (1p)/d)]
Returns: A list of the 4^num_qubits Kraus operators that parametrize the map. Return type: list
pyquil.parser¶
Module for parsing Quil programs from text into PyQuil objects
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.

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)


class
pyquil.paulis.
PauliTerm
(op, index, coefficient=1.0)[source]¶ Bases:
object
A term is a product of Pauli operators operating on different qubits.

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

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
¶

classmethod

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: Returns: True if pauli_two object commutes with pauli_list, False otherwise
Return type:

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.
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 SuzukiTrotter 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: Returns: List of tuples corresponding to the coefficient and operator type: o=0 is A and o=1 is B.
Return type:

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:

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 SuzukiTrotter 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:
pyquil.quil¶
Module for creating and defining Quil programs.

class
pyquil.quil.
Program
(*instructions)[source]¶ Bases:
object

copy
()[source]¶ Perform a shallow copy of this program.
QuilAtom and AbstractInstruction objects should be treated as immutable to avoid strange behavior when performing a copy.
Returns: a new Program

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

declare
(name, memory_type='BIT', memory_size=1, shared_region=None, offsets=None)[source]¶ DECLARE a quil variable
This adds the declaration to the current program and returns a MemoryReference to the base (offset = 0) of the declared memory.
Note
This function returns a MemoryReference and cannot be chained like some of the other Program methods. Consider using
inst(DECLARE(...))
if you would like to chain methods, but please be aware that you must create your own MemoryReferences later on.Parameters:  name – Name of the declared variable
 memory_type – Type of the declared variable
 memory_size – Number of array elements in the declared memory.
 shared_region – You can declare a variable that shares its underlying memory with another region. This allows aliasing. For example, you can interpret an array of measured bits as an integer.
 offsets – If you are using
shared_region
, this allows you to share only a part of the parent region. The offset is given by an array type and the number of elements of that type. For example,DECLARE targetbit BIT SHARING realregion OFFSET 1 REAL 4 BIT
will let you use targetbit to poke into the fourth bit of the second real from the leading edge of realregion.
Returns: a MemoryReference to the start of the declared memory region, ie a memory reference to
name[0]
.

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 bitstring01
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 (arraylike) – List of lists or Numpy 2d array.
 parameters (list) – list of parameters that are used in this gate
Returns: The Program instance.
Return type:

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 bitstring01
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 (tuplelist) – The qubits it acts on.
 kraus_ops (tuplelist) – The Kraus operators.
Returns: The Program instance
Return type:

define_noisy_readout
(qubit, p00, p11)[source]¶ For this program define a classical bit flip readout error channel parametrized by
p00
andp11
. This models the effect of thermal noise that corrupts the readout signal after it has interrogated the qubit.Parameters: Returns: The Program with an appended READOUTPOVM Pragma.
Return type:

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 bitstring01
indicates that qubit 0 is in the state 1. See also the related documentation section in the QVM Overview.Parameters: Returns: The Program instance
Return type:

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
objectReturns: 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... => JUMPWHEN @THEN [c] instrB... JUMP @END LABEL @THEN instrA... LABEL @END
Parameters: Returns: The Quil Program with the branching instructions added.
Return type:

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, Pragmas, and final global RESETs. It may not contain classical instructions or 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: Returns: The Quil Program with the appropriate measure instruction appended, e.g. MEASURE 0 [1]
Return type:

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

pop
()[source]¶ Pops off the last instruction.
Returns: The instruction that was popped. Return type: tuple

reset
(qubit_index=None)[source]¶ Reset all qubits or just a specific qubit at qubit_index.
Parameters: qubit_index (Optional[int]) – The address of the qubit to reset. If None, reset all qubits. Returns: The Quil Program with the appropriate reset instruction appended, e.g. RESET 0 Return type: Program

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 JUMPUNLESS @END [c] instr... JUMP @START LABEL @END
Parameters: Returns: The Quil Program with the loop instructions added.
Return type:

wrap_in_numshots_loop
(shots: int)[source]¶ Wraps a Quil program in a loop that reruns the same program many times.
Note: this function is a prototype of what will exist in the future when users will be responsible for writing this loop instead of having it happen automatically.
Parameters: shots – Number of iterations to loop through.


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 dictionarylike object that maps from
QubitPlaceholder
toQubit
orint
(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) → Dict[str, List[int]][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 mapping from memory region names to lists of offsets appearing in the program.

pyquil.quil.
get_default_qubit_mapping
(program)[source]¶ Takes a program which contains qubit placeholders and provides a mapping to the integers 0 through N1.
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 N1.

pyquil.quil.
implicitly_declare_ro
(instructions: List[pyquil.quilbase.AbstractInstruction])[source]¶ Implicitly declare a register named
ro
for backwards compatibility with Quil 1.There used to be one unnamed hunk of classical memory. Now there are variables with declarations. Instead of:
MEASURE 0 [0]
You must now measure into a named register, idiomatically:
MEASURE 0 ro[0]
The
MEASURE
instruction will emit this (with a deprecation warning) if you’re still using bare integers for classical addresses. However, you must also declare memory in the new scheme:DECLARE ro BIT[8] MEASURE 0 ro[0]
This method will determine if you are in “backwards compatibility mode” and will declare a readout
ro
register for you. If you program contains any DECLARE commands or if it does not have any MEASURE x ro[x], this will not do anything.This behavior is included for backwards compatibility and will be removed in future releases of PyQuil. Please DECLARE all memory including
ro
.

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. If multiple programs in the list contain the same gate and/or noisy gate definition with identical name, this definition will only be applied once. If different definitions with the same name appear multiple times in the program list, each will be applied once in the order of last occurrence.
Parameters: prog_list (list) – A list of pyquil programs Returns: a single pyQuil program Return type: Program

pyquil.quil.
merge_with_pauli_noise
(prog_list: Iterable, probabilities: List, qubits: List)[source]¶ Insert pauli noise channels between each item in the list of programs. This noise channel is implemented as a single noisy identity gate acting on the provided qubits. This method does not rely on merge_programs and so avoids the inclusion of redundant Kraus Pragmas that would occur if merge_programs was called directly on programs with distinct noisy gate definitions.
Parameters:  prog_list – an iterable such as a program or a list of programs. If a program is provided, a single noise gate will be applied after each gate in the program. If a list of programs is provided, the noise gate will be applied after each program.
 probabilities – The 4^num_qubits list of probabilities specifying the desired pauli channel. There should be either 4 or 16 probabilities specified in the order I, X, Y, Z or II, IX, IY, IZ, XI, XX, XY, etc respectively.
 qubits – a list of the qubits that the noisy gate should act on.
Returns: A single program with noisy gates inserted between each element of the program list.
Return type:

pyquil.quil.
percolate_declares
(program: pyquil.quil.Program) → pyquil.quil.Program[source]¶ Move all the DECLARE statements to the top of the program. Return a fresh obejct.
Parameters: program – Perhaps jumbled program. Returns: Program with DECLAREs all at the top and otherwise the same sorted contents.

pyquil.quil.
validate_protoquil
(program: pyquil.quil.Program) → None[source]¶ Ensure that a program is valid ProtoQuil, otherwise raise a ValueError. Protoquil allows a global RESET before any gates, and MEASUREs on each qubit after any gates on that qubit. Pragmas are always allowed, and a final Halt instruction is allowed.
Parameters: program – The Quil program to validate.
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.

class
pyquil.quilbase.
ArithmeticBinaryOp
(left, right)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
The abstract class for binary arithmetic classical instructions.

class
pyquil.quilbase.
ClassicalAdd
(left, right)[source]¶ Bases:
pyquil.quilbase.ArithmeticBinaryOp
The ADD instruction.

op
= 'ADD'¶


class
pyquil.quilbase.
ClassicalAnd
(left, right)[source]¶ Bases:
pyquil.quilbase.LogicalBinaryOp
WARNING: The operand order for ClassicalAnd has changed. In pyQuil versions <= 1.9, AND had signature
AND %source %targetNow, AND has signature
AND %target %source
op
= 'AND'¶


class
pyquil.quilbase.
ClassicalComparison
(target, left, right)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
Abstract class for ternary comparison instructions.

class
pyquil.quilbase.
ClassicalConvert
(left, right)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
The CONVERT instruction.

op
= 'CONVERT'¶


class
pyquil.quilbase.
ClassicalDiv
(left, right)[source]¶ Bases:
pyquil.quilbase.ArithmeticBinaryOp
The DIV instruction.

op
= 'DIV'¶


class
pyquil.quilbase.
ClassicalEqual
(target, left, right)[source]¶ Bases:
pyquil.quilbase.ClassicalComparison
The EQ comparison instruction.

op
= 'EQ'¶


class
pyquil.quilbase.
ClassicalExchange
(left, right)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
The EXCHANGE instruction.

op
= 'EXCHANGE'¶


class
pyquil.quilbase.
ClassicalExclusiveOr
(left, right)[source]¶ Bases:
pyquil.quilbase.LogicalBinaryOp
The XOR instruction.

op
= 'XOR'¶


class
pyquil.quilbase.
ClassicalFalse
(target)[source]¶ Bases:
pyquil.quilbase.ClassicalMove
Deprecated class.

class
pyquil.quilbase.
ClassicalGreaterEqual
(target, left, right)[source]¶ Bases:
pyquil.quilbase.ClassicalComparison
The GE comparison instruction.

op
= 'GE'¶


class
pyquil.quilbase.
ClassicalGreaterThan
(target, left, right)[source]¶ Bases:
pyquil.quilbase.ClassicalComparison
The GT comparison instruction.

op
= 'GT'¶


class
pyquil.quilbase.
ClassicalInclusiveOr
(left, right)[source]¶ Bases:
pyquil.quilbase.LogicalBinaryOp
The IOR instruction.

op
= 'IOR'¶


class
pyquil.quilbase.
ClassicalLessEqual
(target, left, right)[source]¶ Bases:
pyquil.quilbase.ClassicalComparison
The LE comparison instruction.

op
= 'LE'¶


class
pyquil.quilbase.
ClassicalLessThan
(target, left, right)[source]¶ Bases:
pyquil.quilbase.ClassicalComparison
The LT comparison instruction.

op
= 'LT'¶


class
pyquil.quilbase.
ClassicalLoad
(target, left, right)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
The LOAD instruction.

op
= 'LOAD'¶


class
pyquil.quilbase.
ClassicalMove
(left, right)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
The MOVE instruction.
 WARNING: In pyQuil 2.0, the order of operands is as MOVE <target> <source>.
 In pyQuil 1.9, the order of operands was MOVE <source> <target>. These have reversed.

op
= 'MOVE'¶

class
pyquil.quilbase.
ClassicalMul
(left, right)[source]¶ Bases:
pyquil.quilbase.ArithmeticBinaryOp
The MUL instruction.

op
= 'MUL'¶


class
pyquil.quilbase.
ClassicalNeg
(target)[source]¶ Bases:
pyquil.quilbase.UnaryClassicalInstruction
The NEG instruction.

op
= 'NEG'¶


class
pyquil.quilbase.
ClassicalNot
(target)[source]¶ Bases:
pyquil.quilbase.UnaryClassicalInstruction
The NOT instruction.

op
= 'NOT'¶


class
pyquil.quilbase.
ClassicalOr
(left, right)[source]¶ Bases:
pyquil.quilbase.ClassicalInclusiveOr
Deprecated class.

class
pyquil.quilbase.
ClassicalStore
(target, left, right)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
The STORE instruction.

op
= 'STORE'¶


class
pyquil.quilbase.
ClassicalSub
(left, right)[source]¶ Bases:
pyquil.quilbase.ArithmeticBinaryOp
The SUB instruction.

op
= 'SUB'¶


class
pyquil.quilbase.
ClassicalTrue
(target)[source]¶ Bases:
pyquil.quilbase.ClassicalMove
Deprecated class.

class
pyquil.quilbase.
Declare
(name, memory_type, memory_size=1, shared_region=None, offsets=None)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
A DECLARE directive.
This is printed in Quil as:
DECLARE <name> <memorytype> (SHARING <othername> (OFFSET <amount> <type>)* )?

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 (arraylike) – {list, nparray, np.matrix} The matrix defining this gate.
 parameters (list) – list of parameters that are used in this gate

class
pyquil.quilbase.
Gate
(name, params, qubits)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
This is the pyQuil object for a quantum gate instruction.

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).

class
pyquil.quilbase.
JumpConditional
(target, condition)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
Abstract representation of an conditional jump instruction.

class
pyquil.quilbase.
JumpTarget
(label)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
Representation of a target that can be jumped to.

class
pyquil.quilbase.
JumpUnless
(target, condition)[source]¶ Bases:
pyquil.quilbase.JumpConditional
The JUMPUNLESS instruction.

op
= 'JUMPUNLESS'¶


class
pyquil.quilbase.
JumpWhen
(target, condition)[source]¶ Bases:
pyquil.quilbase.JumpConditional
The JUMPWHEN instruction.

op
= 'JUMPWHEN'¶


class
pyquil.quilbase.
LogicalBinaryOp
(left, right)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
The abstract class for binary logical classical instructions.

class
pyquil.quilbase.
Measurement
(qubit, classical_reg=None)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
This is the pyQuil object for a Quil measurement instruction.

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>"

class
pyquil.quilbase.
RawInstr
(instr_str)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
A raw instruction represented as a string.

class
pyquil.quilbase.
Reset
[source]¶ Bases:
pyquil.quilbase.SimpleInstruction
The RESET instruction.

op
= 'RESET'¶


class
pyquil.quilbase.
ResetQubit
(qubit)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
This is the pyQuil object for a Quil targeted reset instruction.

class
pyquil.quilbase.
SimpleInstruction
[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
Abstract class for simple instructions with no arguments.

class
pyquil.quilbase.
UnaryClassicalInstruction
(target)[source]¶ Bases:
pyquil.quilbase.AbstractInstruction
The abstract class for unary classical instructions.

class
pyquil.quilbase.
Wait
[source]¶ Bases:
pyquil.quilbase.SimpleInstruction
The WAIT instruction.

op
= 'WAIT'¶

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

class
pyquil.wavefunction.
Wavefunction
(amplitude_vector)[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 bitstring01
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)[source]¶ From a bit packed string, unpacks to get the wavefunction :param bytes coef_string: :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

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

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

static