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 non-deterministic, i.e., if it includes measurements and/or noisy quantum gates, then the final wavefunction from which the expectation values are computed itself only represents a stochastically generated sample. The expectations returned from different expectation calls will then generally be different.

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

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

Expectation values of the operators.

Return type:

List[float]

expectation_async(prep_prog, operator_programs=None, needs_compilation=False, isa=None)

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
pauli_expectation(prep_prog, pauli_terms)

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

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

Note:

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

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

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

Return type:

float|List[float]

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

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

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

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

Return type:

list

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

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

Note:

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

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

A list of a list of bits.

Return type:

list

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

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

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

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 non-deterministic, i.e., if it includes measurements and/or noisy quantum gates, then the final wavefunction from which the returned bitstrings are sampled itself only represents a stochastically generated sample and the wavefunctions returned by different wavefunction calls will generally be different.

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

A 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

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=None, 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 (list|range) – Classical register addresses to return
  • trials (int) – Number of times to run the program (a.k.a. number of shots)
  • needs_compilation (bool) – If True, preprocesses the job with the compiler.
  • isa (ISA) – If set, specifies a custom ISA to compile to. If left unset, Forest uses the default ISA associated to this QPU device.
Returns:

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

Return type:

list

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

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

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

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

Return type:

list

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

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

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

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.

apply_clifford_to_pauli(clifford, pauli_in)

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

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

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

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

compile(quil_program, isa=None)

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

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

The compiled Program object.

Return type:

Program

compile_async(quil_program, isa=None)

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

generate_rb_sequence(depth, gateset)

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)].
Returns:

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

get_job(job_id)

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 non-fault-tolerant 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 non-fault-tolerant QPU programs with a low gate volume have a higher chance of succeeding. This is a less sensitive measure than gate depth.

Return type:Optional[int]
get()
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 non-fault-tolerant 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

topological_swaps()

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

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

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

Returns:Set or Dictionary (keyed by device name) of all available devices.
Return type:Set|Dict

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 in self._rawisa and noise_model – which should conform to the dictionary format required by the .from_dict() methods for ISA and NoiseModel, respectively.

Variables:
  • _raw (dict) – Raw JSON response from the server with additional information about the device.
  • isa (ISA) – The instruction set architecture (ISA) for the device.
  • noise_model (NoiseModel) – The noise model for the device.
is_online()

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

Return type:bool
is_retuning()

Whether or not the device is currently retuning.

Return type:bool
status

Returns a string describing the device’s status

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

Bases: tuple

dead

Alias for field number 2

targets

Alias for field number 0

type

Alias for field number 1

pyquil.device.EdgeSpecs

alias of _QubitQubitSpecs

class pyquil.device.ISA

Bases: pyquil.device._ISA

Basic Instruction Set Architecture specification.

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

Re-create the ISA from a dictionary representation.

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

Create a JSON-serializable representation of the ISA.

The dictionary representation is of the form:

{
    "1Q": {
        "0": {
            "type": "Xhalves"
        },
        "1": {
            "type": "Xhalves",
            "dead": True
        },
        ...
    },
    "2Q": {
        "1-4": {
            "type": "CZ"
        },
        "1-5": {
            "type": "CZ"
        },
        ...
    },
    ...
}
Returns:A dictionary representation of self.
Return type:Dict[str, Any]
class pyquil.device.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 qubit-qubit 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 single-qubit randomized benchmarking fidelities (normalized to unity) from the specs, keyed by qubit index.

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

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

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

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

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

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

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

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

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

Re-create the Specs from a dictionary representation.

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

Create a JSON-serializable representation of the device Specs.

The dictionary representation is of the form:

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

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.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],           # element-wise real part of matrix
          [0,   0]],
          [[0, -1],           # element-wise imaginary part of matrix
          [-1, 0]]]
    ],
    "fidelity": 1.0
}
Returns:A JSON compatible dictionary representation.
Return type:Dict[str,Any]
static unpack_kraus_matrix(m)

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

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

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)

Re-create the noise model from a dictionary representation.

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

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]
exception pyquil.noise.NoisyGateUndefined

Bases: Exception

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

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

Add generic damping and dephasing noise to a program.

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

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

The default noise parameters

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

are currently typical for near-term devices.

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

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

A new program with noisy operators.

pyquil.noise.append_kraus_to_gate(kraus_ops, gate_matrix)

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

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

A list of transformed Kraus operators.

pyquil.noise.apply_noise_model(prog, noise_model)

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

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

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

Return type:

Program

pyquil.noise.bitstring_probs_to_z_moments(p)

Convert between bitstring probabilities and joint Z moment expectations.

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

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

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

A combinatorially generated list of composed Kraus operators.

pyquil.noise.correct_bitstring_probs(p, assignment_probabilities)

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

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

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

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

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

Return type:

np.array

pyquil.noise.corrupt_bitstring_probs(p, assignment_probabilities)

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

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

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

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

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

Return type:

np.array

pyquil.noise.damping_after_dephasing(T1, T2, gate_time)

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

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

A list of Kraus operators.

pyquil.noise.damping_kraus_map(p=0.1)

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

Parameters:p (float) – The one-step damping probability.
Returns:A list [k1, k2] of the Kraus operators that parametrize the map.
Return type:list
pyquil.noise.dephasing_kraus_map(p=0.1)

Generate the Kraus operators corresponding to a dephasing channel.

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

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 bitstring ij...k.
Return type:np.array
pyquil.noise.get_noisy_gate(gate_name, params)

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

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

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

Return type:

Tuple[np.array, str]

pyquil.noise.tensor_kraus_maps(k1, k2)

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

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

A list of tensored Kraus operators.

pyquil.parametric

Module for creating and defining parametric programs.

class pyquil.parametric.ParametricProgram(program_constructor)

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(sort_ops=True)

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

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)

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

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

Bases: 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:
  • pauli_list (list) – A list of PauliTerm objects
  • pauli_two_term (PauliTerm) – A PauliTerm object
Returns:

True if pauli_two object commutes with pauli_list, False otherwise

Return type:

bool

pyquil.paulis.commuting_sets(pauli_terms)

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:Function
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.simplify_pauli_sum(pauli_sum)
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 Suzuki-Trotter approximation to exp(A + B) results in the following [(0.5/trotter_steps, 0), (1/trotteri_steps, 1), (0.5/trotter_steps, 0)] * trotter_steps.

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

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

Return type:

list

pyquil.paulis.term_with_coeff(term, coeff)

Change the coefficient of a PauliTerm.

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

A new PauliTerm that duplicates term but sets coeff

Return type:

PauliTerm

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

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

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

Quil program

Return type:

Program

pyquil.quil

Module for creating and defining Quil programs.

class pyquil.quil.Program(*instructions)

Bases: object

alloc()

Get a new qubit.

Returns:A qubit.
Return type:Qubit
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 bitstring 01 indicates that qubit 0 is in the state 1. See also the related documentation section in the QVM Overview.

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

The Program instance.

Return type:

Program

define_noisy_gate(name, qubit_indices, kraus_ops)

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

Note

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

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

The Program instance

Return type:

Program

define_noisy_readout(qubit, p00, p11)

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

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

The Program with an appended READOUT-POVM Pragma.

Return type:

Program

defined_gates

A list of defined gates on the program.

gate(name, params, qubits)

Add a gate to the program.

Note

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

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

The Program instance

Return type:

Program

get_qubits(indices=True)

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

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

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

Equivalent to the following construction:

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

The Quil Program with the branching instructions added.

Return type:

Program

inst(*instructions)

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:
  • qubit_index (int) – The address of the qubit to measure.
  • classical_reg (int) – The address of the classical bit to store the result.
Returns:

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

Return type:

Program

measure_all(*qubit_reg_pairs)

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

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

Returns:Program
out()

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

pop()

Pops off the last instruction.

Returns:The instruction that was popped.
Return type:tuple
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
  JUMP-UNLESS @END [c]
  instr...
  JUMP @START
  LABEL @END
Parameters:
  • classical_reg (int) – The classical register to check
  • q_program (Program) – The Quil program to loop.
Returns:

The Quil Program with the loop instructions added.

Return type:

Program

pyquil.quil.address_qubits(program, qubit_mapping=None)

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

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

This function will also instantiate any label placeholders.

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

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

pyquil.quil.get_classical_addresses_from_program(program)

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

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

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

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

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

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)

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

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

pyquil.quilbase

Contains the core pyQuil objects that correspond to Quil instructions.

class pyquil.quilbase.AbstractInstruction

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

Prints a readable Quil string representation of this gate.

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

Bases: pyquil.quilbase.AbstractInstruction

This is the pyQuil object for a quantum gate instruction.

get_qubits(indices=True)
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 JUMP-UNLESS instruction.

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

Bases: pyquil.quilbase.JumpConditional

The JUMP-WHEN instruction.

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

Bases: pyquil.quilbase.AbstractInstruction

This is the pyQuil object for a Quil measurement instruction.

get_qubits(indices=True)
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 supported
Parameters:
  • value (float) – A value to initialize to. Defaults to 0.0
  • func (function) – An initial function to determine the final parameterized value.
value()

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 bitstring 01 indicates that qubit 0 is in the state 1. See also the related documentation section in the QVM Overview.

static from_bit_packed_string(coef_string, classical_addresses)

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