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)¶ Bases:
object
Represents a connection to the QVM.

expectation
(prep_prog, operator_programs=None, needs_compilation=False, isa=None)¶ 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.Parameters: Returns: Expectation value of the operators.
Return type:

expectation_async
(prep_prog, operator_programs=None, needs_compilation=False, isa=None)¶ 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)¶ 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

ping
()¶

run
(quil_program, classical_addresses, trials=1, needs_compilation=False, isa=None)¶ Run a Quil program multiple times, accumulating the values deposited in a list of classical addresses.
Parameters: Returns: A list of lists of bits. Each sublist corresponds to the values in classical_addresses.
Return type:

run_and_measure
(quil_program, qubits, trials=1, needs_compilation=False, isa=None)¶ 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:

run_and_measure_async
(quil_program, qubits, trials=1, needs_compilation=False, isa=None)¶ 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, trials=1, needs_compilation=False, isa=None)¶ 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)¶ 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)¶ 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.
 classical_addresses (listrange) – 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 tuple whose first element is a Wavefunction object, and whose second element is the list of classical bits corresponding to the classical addresses.
Return type:

wavefunction_async
(quil_program, classical_addresses=None, needs_compilation=False, isa=None)¶ 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)¶ Bases:
object
Represents a connection to the QPU (Quantum Processing Unit)

get_job
(job_id)¶ 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, trials=1, needs_compilation=True, isa=None)¶ 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 (listrange) – 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:

run_and_measure
(quil_program, qubits, trials=1, needs_compilation=True, isa=None)¶ 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 (listrange) – 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:

run_and_measure_async
(quil_program, qubits, trials, needs_compilation=True, isa=None)¶ 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, trials=1, needs_compilation=True, isa=None)¶ 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)¶ 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)¶ Bases:
object
Represents a connection to the Quil compiler.

compile
(quil_program)¶ Sends a Quil program to the Forest compiler and returns the resulting compiled Program.
Parameters: quil_program (Program) – Quil program to be compiled. Returns: The compiled Program object. Return type: Program

compile_async
(quil_program)¶ 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.

get_job
(job_id)¶ 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)¶ 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)¶ 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
()¶ 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
()¶

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

gate_depth
()¶ 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
()¶ 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]

get
()¶

is_compiling
()¶ Is the job actively compiling?

is_done
()¶ Has the job completed yet?

is_queued
()¶ Is the job still in the Forest queue?

is_queued_for_compilation
()¶ Is the job still in the Forest compilation queue?

is_running
()¶ Is the job currently running?

job_id
¶ Job id :rtype: str

multiqubit_gate_depth
()¶ 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
()¶ 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
()¶ 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
()¶ 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


pyquil.api.
get_devices
(async_endpoint='https://job.rigetti.com/beta', api_key=None, user_id=None, as_dict=False)¶ 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: SetDict
pyquil.device¶

class
pyquil.device.
Device
(name, raw)¶ Bases:
object
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.

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 recalibrating
 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
_QubitQubitSpecs

class
pyquil.device.
ISA
¶ Bases:
pyquil.device._ISA
Basic Instruction Set Architecture specification.
Variables: 
static
from_dict
(d)¶ Recreate the ISA from a dictionary representation.
Parameters: d (Dict[str,Any]) – The dictionary representation. Returns: The restored ISA. Return type: ISA

to_dict
()¶ 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.
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
_QubitSpecs

class
pyquil.device.
Specs
¶ 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
()¶ 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
()¶ 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
()¶ 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]

fBellStates
()¶ 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
()¶ 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
()¶ 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
()¶ 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)¶ Recreate the Specs from a dictionary representation.
Parameters: Any] d (Dict[str,) – The dictionary representation. Returns: The restored Specs. Return type: Specs

to_dict
()¶ 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.gates¶
A lovely bunch of gates and instructions for programming with. This module is used to provide Pythonic sugar for Quil instructions.

pyquil.gates.
AND
(classical_reg1, classical_reg2)¶ 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.
CCNOT
(*qubits)¶

pyquil.gates.
CNOT
(*qubits)¶

pyquil.gates.
CPHASE
(*params)¶

pyquil.gates.
CPHASE00
(*params)¶

pyquil.gates.
CPHASE01
(*params)¶

pyquil.gates.
CPHASE10
(*params)¶

pyquil.gates.
CSWAP
(*qubits)¶

pyquil.gates.
CZ
(*qubits)¶

pyquil.gates.
EXCHANGE
(classical_reg1, classical_reg2)¶ 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.
FALSE
(classical_reg)¶ Produce a FALSE instruction.
Parameters: classical_reg – A classical register to modify. Returns: A ClassicalFalse instance.

pyquil.gates.
H
(*qubits)¶

pyquil.gates.
I
(*qubits)¶

pyquil.gates.
ISWAP
(*qubits)¶

pyquil.gates.
MEASURE
(qubit, classical_reg=None)¶ 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.
MOVE
(classical_reg1, classical_reg2)¶ Produce a MOVE instruction.
Parameters:  classical_reg1 – The first classical register.
 classical_reg2 – The second classical register, which gets modified.
Returns: A ClassicalMove instance.

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

pyquil.gates.
OR
(classical_reg1, classical_reg2)¶ 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.
PHASE
(*params)¶

pyquil.gates.
PSWAP
(*params)¶

pyquil.gates.
RX
(*params)¶

pyquil.gates.
RY
(*params)¶

pyquil.gates.
RZ
(*params)¶

pyquil.gates.
S
(*qubits)¶

pyquil.gates.
SWAP
(*qubits)¶

pyquil.gates.
T
(*qubits)¶

pyquil.gates.
TRUE
(classical_reg)¶ Produce a TRUE instruction.
Parameters: classical_reg – A classical register to modify. Returns: A ClassicalTrue instance.

pyquil.gates.
X
(*qubits)¶

pyquil.gates.
Y
(*qubits)¶

pyquil.gates.
Z
(*qubits)¶
pyquil.noise¶
Module for creating and verifying noisy gate and readout definitions.

class
pyquil.noise.
KrausModel
¶ 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)¶ 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
()¶ 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)¶ 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
¶ 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)¶ 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)¶ 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
()¶ 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]

pyquil.noise.
add_decoherence_noise
(prog, T1=3e05, T2=3e05, gate_time_1q=5e08, gate_time_2q=1.5e07, ro_fidelity=0.95)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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.
dephasing_kraus_map
(p=0.1)¶ 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)¶ 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)¶ 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.parametric¶
Module for creating and defining parametric programs.

class
pyquil.parametric.
ParametricProgram
(program_constructor)¶ Bases:
object
Note
Experimental
A class representing Programs with changeable gate parameters.

fuse
(other)¶ 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)¶ 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)¶ 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.paulis¶
Module for working with Pauli algebras.

pyquil.paulis.
ID
()¶ The identity Pauli Term.

class
pyquil.paulis.
PauliSum
(terms)¶ Bases:
object
A sum of one or more PauliTerms.

get_programs
()¶ Get a Pyquil Program corresponding to each term in the PauliSum and a coefficient for each program
Returns: (programs, coefficients)

get_qubits
()¶ 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
()¶ Simplifies the sum of Pauli operators according to Pauli algebra rules.


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

copy
()¶ Properly creates a new PauliTerm, with a completely new dictionary of operators

classmethod
from_list
(terms_list, coefficient=1.0)¶ 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
()¶ Gets all the qubits that this PauliTerm operates on.

id
()¶  Returns the unique identifier string for the PauliTerm (ignoring the coefficient).
 Used in the simplify method of PauliSum.
Returns: The unique identifier for this term. Return type: string

program
¶


exception
pyquil.paulis.
UnequalLengthWarning
(*args, **kwargs)¶ Bases:
exceptions.Warning

pyquil.paulis.
ZERO
()¶ The zero Pauli Term.

pyquil.paulis.
check_commutation
(pauli_list, pauli_two)¶ 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)¶ 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)¶ 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: Program

pyquil.paulis.
exponentiate
(term)¶ 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)¶ 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.
is_identity
(term)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ 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)¶ Bases:
object

dagger
(inv_dict=None, suffix='INV')¶ 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)¶ 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: Returns: The Program instance.
Return type:

define_noisy_gate
(name, qubit_indices, kraus_ops)¶ 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_index, p00, p11)¶ 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)¶ 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
()¶ 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
Returns: A set of all the qubit indices used in this program Return type: set

if_then
(classical_reg, if_program, else_program=None)¶ 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)¶ 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
()¶ 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)¶ 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)¶ Measures many qubits into their specified classical bits, in the order they were entered.
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
()¶ Prevent a noisy gate definition from being applied to the immediately following Gate instruction.
Returns: Program

out
()¶ Converts the Quil program to a readable string.
Returns: String form of a program Return type: string

while_do
(classical_reg, q_program)¶ 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:


pyquil.quil.
merge_programs
(prog_list)¶ 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.quil.
shift_quantum_gates
(program, shift_offset)¶ Shifts a quantum gates in a quil program so that all qubit indices change by a certain offset :param program: a pyquil Program :param shift_offset: integer :return: pyquil Program with shifted qubit indices
pyquil.quilbase¶
Contains the core pyQuil objects that correspond to Quil instructions.

class
pyquil.quilbase.
AbstractInstruction
¶ Bases:
object
Abstract class for representing single instructions.

out
()¶


class
pyquil.quilbase.
BinaryClassicalInstruction
(left, right)¶ Bases:
pyquil.quilbase.AbstractInstruction
The abstract class for binary classical instructions.

out
()¶


class
pyquil.quilbase.
ClassicalAnd
(left, right)¶ Bases:
pyquil.quilbase.BinaryClassicalInstruction

op
= 'AND'¶


class
pyquil.quilbase.
ClassicalExchange
(left, right)¶ Bases:
pyquil.quilbase.BinaryClassicalInstruction

op
= 'EXCHANGE'¶


class
pyquil.quilbase.
ClassicalFalse
(target)¶ Bases:
pyquil.quilbase.UnaryClassicalInstruction

op
= 'FALSE'¶


class
pyquil.quilbase.
ClassicalMove
(left, right)¶ Bases:
pyquil.quilbase.BinaryClassicalInstruction

op
= 'MOVE'¶


class
pyquil.quilbase.
ClassicalNot
(target)¶ Bases:
pyquil.quilbase.UnaryClassicalInstruction

op
= 'NOT'¶


class
pyquil.quilbase.
ClassicalOr
(left, right)¶ Bases:
pyquil.quilbase.BinaryClassicalInstruction

op
= 'OR'¶


class
pyquil.quilbase.
ClassicalTrue
(target)¶ Bases:
pyquil.quilbase.UnaryClassicalInstruction

op
= 'TRUE'¶


class
pyquil.quilbase.
DefGate
(name, matrix, parameters=None)¶ Bases:
pyquil.quilbase.AbstractInstruction
A DEFGATE directive.
Parameters: 
get_constructor
()¶ Returns: A function that constructs this gate on variable qubit indices. E.g. mygate.get_constructor()(1) applies the gate to qubit 1.


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

out
()¶


class
pyquil.quilbase.
Halt
¶ Bases:
pyquil.quilbase.SimpleInstruction
The HALT instruction.

op
= 'HALT'¶


class
pyquil.quilbase.
Jump
(target)¶ Bases:
pyquil.quilbase.AbstractInstruction
Representation of an unconditional jump instruction (JUMP).

out
()¶


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

out
()¶


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

out
()¶


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

op
= 'JUMPUNLESS'¶


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

op
= 'JUMPWHEN'¶


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

out
()¶


class
pyquil.quilbase.
Nop
¶ Bases:
pyquil.quilbase.SimpleInstruction
The RESET instruction.

op
= 'NOP'¶


class
pyquil.quilbase.
Pragma
(command, args=(), freeform_string='')¶ Bases:
pyquil.quilbase.AbstractInstruction
A PRAGMA instruction.
This is printed in QUIL as:
PRAGMA <command> <arg1> <arg2> ... <argn> "<freeform_string>"

out
()¶


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

out
()¶


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

op
= 'RESET'¶


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

out
()¶


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

out
()¶


class
pyquil.quilbase.
Wait
¶ 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)¶ Bases:
object
A placeholder for a parameter value.
Arithmetic operations:+*/
Logical: abs, max, <, >, <=, >=, !=, ==Arbitrary functions are not supportedParameters:  value (float) – A value to initialize to. Defaults to 0.0
 func (function) – An initial function to determine the final parameterized value.

value
()¶ 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)¶ 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, classical_addresses)¶ 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
()¶ 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)¶

plot
(qubit_subset=None)¶ 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)¶ 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)¶ 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
()¶ Returns an array of probabilities in lexicographical order

sample_bitstrings
(n_samples)¶ 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)¶ 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

pyquil.wavefunction.
get_bitstring_from_index
(index, qubit_num)¶ 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