# Source Code Documentation¶

## pyquil.device¶

class pyquil.device.AbstractDevice[source]

Bases: abc.ABC

get_isa(oneq_type='Xhalves', twoq_type='CZ')[source]

Construct an ISA suitable for targeting by compilation.

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

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

Construct a Specs object required by compilation

Return type: Specs
qubit_topology()[source]

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

Return type: Graph
qubits()[source]

A sorted list of qubits in the device topology.

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

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. name – name of the device raw – raw JSON response from the server with additional information about this device.
get_isa(oneq_type='Xhalves', twoq_type='CZ')[source]

Construct an ISA suitable for targeting by compilation.

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

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

Construct a Specs object required by compilation

isa
qubit_topology()[source]

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

Return type: Graph
qubits()[source]

A sorted list of qubits in the device topology.

class pyquil.device.Edge(targets, type, dead)

Bases: tuple

Create new instance of Edge(targets, type, dead)

dead

Alias for field number 2

targets

Alias for field number 0

type

Alias for field number 1

pyquil.device.EdgeSpecs

alias of pyquil.device._QubitQubitSpecs

class pyquil.device.ISA[source]

Bases: pyquil.device._ISA

Basic Instruction Set Architecture specification.

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

Create new instance of _ISA(qubits, edges)

static from_dict(d)[source]

Re-create the ISA from a dictionary representation.

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

Create a JSON-serializable representation of the ISA.

The dictionary representation is of the form:

{
"1Q": {
"0": {
"type": "Xhalves"
},
"1": {
"type": "Xhalves",
},
...
},
"2Q": {
"1-4": {
"type": "CZ"
},
"1-5": {
"type": "CZ"
},
...
},
...
}

Returns: A dictionary representation of self. Dict[str, Any]
class pyquil.device.NxDevice(topology)[source]

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

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

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

Construct an ISA suitable for targeting by compilation.

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

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

Construct a Specs object required by compilation

qubit_topology()[source]

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

qubits()[source]

A sorted list of qubits in the device topology.

Return type: List[int]
class pyquil.device.Qubit(id, type, dead)

Bases: tuple

Create new instance of Qubit(id, type, dead)

dead

Alias for field number 2

id

Alias for field number 0

type

Alias for field number 1

pyquil.device.QubitSpecs

alias of pyquil.device._QubitSpecs

class pyquil.device.Specs[source]

Bases: pyquil.device._Specs

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

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

Create new instance of _Specs(qubits_specs, edges_specs)

T1s()[source]

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

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

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

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

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

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

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

Returns: A dictionary of reset fidelities, normalized to unity.
fBellStates()[source]

Get a dictionary of 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. Dict[tuple(int, int), float]
fCPHASEs()[source]

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

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

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

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

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

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

Re-create the Specs from a dictionary representation.

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

Create a JSON-serializable representation of the device Specs.

The dictionary representation is of the form:

{
'1Q': {
"0": {
"f1QRB": 0.99,
"T1": 20e-6,
...
},
"1": {
"f1QRB": 0.989,
"T1": 19e-6,
...
},
...
},
'2Q': {
"1-4": {
"fBellState": 0.93,
"fCZ": 0.92,
"fCPHASE": 0.91
},
"1-5": {
"fBellState": 0.9,
"fCZ": 0.89,
"fCPHASE": 0.88
},
...
},
...
}

Returns: A dctionary representation of self. Dict[str, Any]
pyquil.device.THETA = Parameter('theta')

Used as the symbolic parameter in RZ, CPHASE gates.

pyquil.device.gates_in_isa(isa)[source]

Generate the full gateset associated with an ISA.

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

Generate an ISA object from a NetworkX graph.

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

Construct a NetworkX qubit topology from an ISA object.

Parameters: isa (ISA) – The ISA. Graph
pyquil.device.specs_from_graph(graph)[source]

Generate a Specs object from a NetworkX graph with placeholder values for the actual specs.

Parameters: graph (Graph) – The graph

## pyquil.gates¶

pyquil.gates.I(qubit)[source]

Produces the I instruction.

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

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

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

Produces the X instruction.

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

This gate is a single qubit X-gate.

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

Produces the Y instruction.

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

This gate is a single qubit Y-gate.

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

Produces the Z instruction.

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

This gate is a single qubit Z-gate.

Parameters: qubit – The qubit apply the gate to. A Gate object.
pyquil.gates.H(qubit)[source]
H = (1 / sqrt(2)) * [[1, 1],
[1, -1]]

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

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

Produces the S instruction.

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

This gate is a single qubit S-gate.

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

Produces the T instruction.

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

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

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

Produces the PHASE instruction.

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

This is the same as the RZ gate.

Parameters: angle – The angle to rotate around the z-axis on the bloch sphere. qubit – The qubit apply the gate to. A Gate object.
pyquil.gates.RX(angle, qubit)[source]

Produces the RX instruction.

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

This gate is a single qubit X-rotation.

Parameters: angle – The angle to rotate around the x-axis on the bloch sphere. qubit – The qubit apply the gate to. A Gate object.
pyquil.gates.RY(angle, qubit)[source]

Produces the RY instruction.

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

This gate is a single qubit Y-rotation.

Parameters: angle – The angle to rotate around the y-axis on the bloch sphere. qubit – The qubit apply the gate to. A Gate object.
pyquil.gates.RZ(angle, qubit)[source]

Produces the RZ instruction.

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

This gate is a single qubit Z-rotation.

Parameters: angle – The angle to rotate around the z-axis on the bloch sphere. qubit – The qubit apply the gate to. A Gate object.
pyquil.gates.CZ(control, target)[source]

Produces a CZ instruction.

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

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

Parameters: control – The control qubit. target – The target qubit. The target qubit has an Z-gate applied to it if the control qubit is in the excited state. A Gate object.
pyquil.gates.CNOT(control, target)[source]

Produces a CNOT instruction.

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

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

Parameters: control – The control qubit. target – The target qubit. The target qubit has an X-gate applied to it if the control qubit is in the excited state. A Gate object.
pyquil.gates.CCNOT(control1, control2, target)[source]

Produces a CCNOT instruction.

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

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

Parameters: control1 – The first control qubit. control2 – The second control qubit. target – The target qubit. The target qubit has an X-gate applied to it if both control qubits are in the excited state. A Gate object.
pyquil.gates.CPHASE00(angle, control, target)[source]

Produces a CPHASE00 instruction.

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

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

Parameters: angle – The input phase angle to apply when both qubits are in the ground state. control – Qubit 1. target – Qubit 2. A Gate object.
pyquil.gates.CPHASE01(angle, control, target)[source]

Produces a CPHASE01 instruction.

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

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

Parameters: angle – The input phase angle to apply when q1 is in the excited state and q2 is in the ground state. control – Qubit 1. target – Qubit 2. A Gate object.
pyquil.gates.CPHASE10(angle, control, target)[source]

Produces a CPHASE10 instruction.

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

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

Parameters: angle – The input phase angle to apply when q2 is in the excited state and q1 is in the ground state. control – Qubit 1. target – Qubit 2. A Gate object.
pyquil.gates.CPHASE(angle, control, target)[source]

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

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

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

Parameters: angle – The input phase angle to apply when both qubits are in the excited state. control – Qubit 1. target – Qubit 2. A Gate object.
pyquil.gates.SWAP(q1, q2)[source]

Produces a SWAP instruction.

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

This gate swaps the state of two qubits.

Parameters: q1 – Qubit 1. q2 – Qubit 2. A Gate object.
pyquil.gates.CSWAP(control, target_1, target_2)[source]
CSWAP = [[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1]]

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

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

Produces an ISWAP instruction.

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

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

Parameters: q1 – Qubit 1. q2 – Qubit 2. A Gate object.
pyquil.gates.PSWAP(angle, q1, q2)[source]

Produces a PSWAP instruction.

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

This is a parameterized swap gate.

Parameters: angle – The angle of the phase to apply to the swapped states. This phase is applied to q1 when it is in the excited state and to q2 when it is in the ground state. q1 – Qubit 1. q2 – Qubit 2. A Gate object.
pyquil.gates.WAIT = <pyquil.quilbase.Wait object>

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

Returns: A Wait object.
pyquil.gates.RESET(qubit_index=None)[source]

Reset all qubits or just a specific qubit at qubit_index.

Parameters: qubit_index (Optional[int]) – The address of the qubit to reset. If None, reset all qubits. A Reset or ResetQubit Quil AST expression corresponding to a global or targeted reset, respectively. Union[Reset, ResetQubit]
pyquil.gates.NOP = <pyquil.quilbase.Nop object>

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

Returns: A Nop object.
pyquil.gates.HALT = <pyquil.quilbase.Halt object>

This instruction ends the program.

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

Produce a MEASURE instruction.

Parameters: qubit – The qubit to measure. classical_reg – The classical register to measure into, or None. A Measurement instance.
pyquil.gates.TRUE(classical_reg)[source]

Produce a TRUE instruction.

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

Produce a FALSE instruction.

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

Produce a NOT instruction.

Parameters: classical_reg – A classical register to modify. A ClassicalNot instance.
pyquil.gates.AND(classical_reg1, classical_reg2)[source]

Produce an AND instruction.

NOTE: The order of operands was reversed in pyQuil <=1.9 .

Parameters: classical_reg1 – The first classical register, which gets modified. classical_reg2 – The second classical register or immediate value. A ClassicalAnd instance.
pyquil.gates.OR(classical_reg1, classical_reg2)[source]

Produce an OR instruction.

Parameters: classical_reg1 – The first classical register. classical_reg2 – The second classical register, which gets modified. A ClassicalOr instance.
pyquil.gates.MOVE(classical_reg1, classical_reg2)[source]

Produce a MOVE instruction.

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

Produce an EXCHANGE instruction.

Parameters: classical_reg1 – The first classical register, which gets modified. classical_reg2 – The second classical register, which gets modified. A ClassicalExchange instance.
pyquil.gates.IOR(classical_reg1, classical_reg2)[source]

Produce an inclusive OR instruction.

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

Produce an exclusive OR instruction.

Parameters: classical_reg1 – The first classical register, which gets modified. classical_reg2 – The second classical register or immediate value. A ClassicalOr instance.
pyquil.gates.NEG(classical_reg)[source]

Produce a NEG instruction.

Parameters: classical_reg – A classical memory address to modify. A ClassicalNeg instance.
pyquil.gates.ADD(classical_reg, right)[source]

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

Produce a SUB instruction.

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

Produce a MUL instruction.

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

Produce an DIV instruction.

Parameters: classical_reg – Left operand for the arithmetic operation. Also serves as the store target. right – Right operand for the arithmetic operation. A ClassicalDiv instance.
pyquil.gates.EQ(classical_reg1, classical_reg2, classical_reg3)[source]

Produce an EQ instruction.

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

Produce an GT instruction.

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

Produce an GE instruction.

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

Produce an LE instruction.

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

Produce an LT instruction.

Parameters: classical_reg1 – Memory address to which to store the comparison result. classical_reg2 – Left comparison operand. classical_reg3 – Right comparison operand. A ClassicalLessThan instance.
pyquil.gates.LOAD(target_reg, region_name, offset_reg)[source]

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

Produce a STORE instruction.

Parameters: region_name – Named region of memory to store to. offset_reg – Offset into memory region. Must be a MemoryReference. source – Source data. Can be either a MemoryReference or a constant. A ClassicalStore instance.
pyquil.gates.CONVERT(classical_reg1, classical_reg2)[source]

Produce a CONVERT instruction.

Parameters: classical_reg1 – MemoryReference to store to. classical_reg2 – MemoryReference to read from. A ClassicalCONVERT instance.
class pyquil.gates.Gate(name, params, qubits)[source]

This is the pyQuil object for a quantum gate instruction.

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

## pyquil.noise¶

Module for creating and verifying noisy gate and readout definitions.

pyquil.noise.INFINITY = inf

Used for infinite coherence times.

class pyquil.noise.KrausModel[source]

Bases: pyquil.noise._KrausModel

Encapsulate a single gate’s noise model.

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

Create new instance of _KrausModel(gate, params, targets, kraus_ops, fidelity)

static from_dict(d)[source]

Recreate a KrausModel from the dictionary representation.

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

Create a dictionary representation of a KrausModel.

For example:

{
"gate": "RX",
"params": np.pi,
"targets": [0],
"kraus_ops": [            # In this example single Kraus op = ideal RX(pi) gate
[[[0,   0],           # element-wise real part of matrix
[0,   0]],
[[0, -1],           # element-wise imaginary part of matrix
[-1, 0]]]
],
"fidelity": 1.0
}

Returns: A JSON compatible dictionary representation. Dict[str,Any]
static unpack_kraus_matrix(m)[source]

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

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

Bases: pyquil.noise._NoiseModel

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

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

Create new instance of _NoiseModel(gates, assignment_probs)

static from_dict(d)[source]

Re-create the noise model from a dictionary representation.

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

Return all defined noisy gates of a particular gate name.

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

Create a JSON serializable representation of the noise model.

For example:

{
"gates": [
# list of embedded dictionary representations of KrausModels here [...]
]
"assignment_probs": {
"0": [[.8, .1],
[.2, .9]],
"1": [[.9, .4],
[.1, .6]],
}
}

Returns: A dictionary representation of self. Dict[str,Any]
exception pyquil.noise.NoisyGateUndefined[source]

Bases: Exception

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

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

Add generic damping and dephasing noise to a program.

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

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

The default noise parameters

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

are currently typical for near-term devices.

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

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

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

Parameters: kraus_ops (list) – The Kraus operators. gate_matrix (numpy.ndarray) – The unitary gate. A list of transformed Kraus operators.
pyquil.noise.apply_noise_model(prog, noise_model)[source]

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

Parameters: prog (Program) – A Quil Program object. noise_model (NoiseModel) – A NoiseModel, either generated from an ISA or from a simple decoherence model. A new program translated to a noisy gateset and with noisy readout as described by the noisemodel. Program
pyquil.noise.bitstring_probs_to_z_moments(p)[source]

Convert between bitstring probabilities and joint Z moment expectations.

Parameters: p (np.array) – An array that enumerates bitstring probabilities. When flattened out p = [p_00...0, p_00...1, ...,p_11...1]. The total number of elements must therefore be a power of 2. The canonical shape has a separate axis for each qubit, such that p[i,j,...,k] gives the estimated probability of bitstring ij...k. 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_moments[j_0,j_1,...,j_m]  np.array
pyquil.noise.combine_kraus_maps(k1, k2)[source]

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

Parameters: k1 (list) – The list of Kraus operators that are applied second. k2 (list) – The list of Kraus operators that are applied first. A combinatorially generated list of composed Kraus operators.
pyquil.noise.correct_bitstring_probs(p, assignment_probabilities)[source]

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

Parameters: p (np.array) – An array that enumerates bitstring probabilities. When flattened out p = [p_00...0, p_00...1, ...,p_11...1]. The total number of elements must therefore be a power of 2. The canonical shape has a separate axis for each qubit, such that p[i,j,...,k] gives the estimated probability of bitstring ij...k. assignment_probabilities (List[np.array]) – A list of assignment probability matrices per qubit. Each assignment probability matrix is expected to be of the form: [[p00 p01] [p10 p11]]  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. np.array
pyquil.noise.corrupt_bitstring_probs(p, assignment_probabilities)[source]

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

Parameters: p (np.array) – An array that enumerates bitstring probabilities. When flattened out p = [p_00...0, p_00...1, ...,p_11...1]. The total number of elements must therefore be a power of 2. The canonical shape has a separate axis for each qubit, such that p[i,j,...,k] gives the estimated probability of bitstring ij...k. assignment_probabilities (List[np.array]) – A list of assignment probability matrices per qubit. Each assignment probability matrix is expected to be of the form: [[p00 p01] [p10 p11]]  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. np.array
pyquil.noise.damping_after_dephasing(T1, T2, gate_time)[source]

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

Parameters: T1 (float) – The amplitude damping time T2 (float) – The dephasing time gate_time (float) – The gate duration. A list of Kraus operators.
pyquil.noise.damping_kraus_map(p=0.1)[source]

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

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

Similar to :py:func_decoherence_noise_model, but with asymmetric readout.

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

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

Generate the Kraus operators corresponding to a dephasing channel.

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

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

[[p00 p01]
[p10 p11]]

Parameters: q (int) – The index of the qubit. trials (int) – The number of samples for each state preparation. cxn (Union[QVMConnection,QPUConnection]) – The quantum abstract machine to sample from. p0 (Program) – A header program to prepend to the state preparation programs. The assignment probability matrix np.array
pyquil.noise.estimate_bitstring_probs(results)[source]

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

Parameters: results (np.array) – A 2d array where the outer axis iterates over shots and the inner axis over bits. 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. np.array
pyquil.noise.get_noisy_gate(gate_name, params)[source]

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

Parameters: gate_name (str) – The Quil gate name params (Tuple[float]) – The gate parameters. A tuple (matrix, noisy_name) with the representation of the ideal gate matrix and a proposed name for the noisy version. Tuple[np.array, str]
pyquil.noise.pauli_kraus_map(probabilities)[source]

Generate the Kraus operators corresponding to a pauli channel.

Params list|floats probabilities:
The 4^num_qubits list of probabilities specifying the desired pauli channel.

There should be either 4 or 16 probabilities specified in the order I, X, Y, Z for 1 qubit or II, IX, IY, IZ, XI, XX, XY, etc for 2 qubits.

For example:

The d-dimensional depolarizing channel \Delta parameterized as
\Delta(\rho) = p \rho + [(1-p)/d] I
is specified by the list of probabilities
[p + (1-p)/d, (1-p)/d,  (1-p)/d), ... , (1-p)/d)]

Returns: A list of the 4^num_qubits Kraus operators that parametrize the map. list
pyquil.noise.tensor_kraus_maps(k1, k2)[source]

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

Parameters: k1 (list) – The Kraus operators for the first qubit. k2 (list) – The Kraus operators for the second qubit. A list of tensored Kraus operators.

## pyquil.parser¶

Module for parsing Quil programs from text into PyQuil objects

pyquil.parser.parse(quil)[source]

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

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

Parse a raw Quil program and return a PyQuil program.

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

## pyquil.paulis¶

Module for working with Pauli algebras.

pyquil.paulis.HASH_PRECISION = 1000000.0

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

pyquil.paulis.ID()[source]

The identity Pauli Term.

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

Bases: object

A sum of one or more PauliTerms.

Parameters: terms (Sequence) – A Sequence of PauliTerms.
get_programs()[source]

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

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

The support of all the operators in the PauliSum object.

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

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

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

Bases: object

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

Create a new Pauli Term with a Pauli operator at a particular index and a leading coefficient.

Parameters: op (string) – The Pauli operator as a string “X”, “Y”, “Z”, or “I” index (int) – The qubit index that that operator is applied to. coefficient (float) – The coefficient multiplying the operator, e.g. 1.5 * Z_1
copy()[source]

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

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

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

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

Gets all the qubits that this PauliTerm operates on.

id(sort_ops=True)[source]

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

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

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

Return a frozenset of operations in this term.

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

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

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

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

Bases: Warning

pyquil.paulis.ZERO()[source]

The zero Pauli Term.

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

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

Parameters: pauli_list (list) – A list of PauliTerm objects pauli_two_term (PauliTerm) – A PauliTerm object True if pauli_two object commutes with pauli_list, False otherwise bool
pyquil.paulis.commuting_sets(pauli_terms)[source]

Gather the Pauli terms of pauli_terms variable into commuting sets

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

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

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

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

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

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

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

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

Explicitly include numpy integer dtypes (for python 3).

pyquil.paulis.is_identity(term)[source]

Check if Pauli Term is a scalar multiple of identity

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

Tests to see if a PauliTerm or PauliSum is zero.

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

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

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

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

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

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

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

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

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

Generate trotterization coefficients for a given number of Trotter steps.

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

Parameters: trotter_order (int) – order of Suzuki-Trotter approximation trotter_steps (int) – number of steps in the approximation List of tuples corresponding to the coefficient and operator type: o=0 is A and o=1 is B. list
pyquil.paulis.term_with_coeff(term, coeff)[source]

Change the coefficient of a PauliTerm.

Parameters: term (PauliTerm) – A PauliTerm object coeff (Number) – The coefficient to set on the PauliTerm A new PauliTerm that duplicates term but sets coeff PauliTerm
pyquil.paulis.trotterize(first_pauli_term, second_pauli_term, trotter_order=1, trotter_steps=1)[source]

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

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

## pyquil.quilbase¶

Contains the core pyQuil objects that correspond to Quil instructions.

class pyquil.quilbase.AbstractInstruction[source]

Bases: object

Abstract class for representing single instructions.

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

The abstract class for binary arithmetic classical instructions.

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

op = 'ADD'
class pyquil.quilbase.ClassicalAnd(left, right)[source]

WARNING: The operand order for ClassicalAnd has changed. In pyQuil versions <= 1.9, AND had signature

AND %source %target

Now, AND has signature

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

Abstract class for ternary comparison instructions.

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

The CONVERT instruction.

op = 'CONVERT'
out()[source]
class pyquil.quilbase.ClassicalDiv(left, right)[source]

The DIV instruction.

op = 'DIV'
class pyquil.quilbase.ClassicalEqual(target, left, right)[source]

The EQ comparison instruction.

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

The EXCHANGE instruction.

op = 'EXCHANGE'
out()[source]
class pyquil.quilbase.ClassicalExclusiveOr(left, right)[source]

The XOR instruction.

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

Deprecated class.

class pyquil.quilbase.ClassicalGreaterEqual(target, left, right)[source]

The GE comparison instruction.

op = 'GE'
class pyquil.quilbase.ClassicalGreaterThan(target, left, right)[source]

The GT comparison instruction.

op = 'GT'
class pyquil.quilbase.ClassicalInclusiveOr(left, right)[source]

The IOR instruction.

op = 'IOR'
class pyquil.quilbase.ClassicalLessEqual(target, left, right)[source]

The LE comparison instruction.

op = 'LE'
class pyquil.quilbase.ClassicalLessThan(target, left, right)[source]

The LT comparison instruction.

op = 'LT'
class pyquil.quilbase.ClassicalLoad(target, left, right)[source]

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

The MOVE instruction.

WARNING: In pyQuil 2.0, the order of operands is as MOVE <target> <source>.
In pyQuil 1.9, the order of operands was MOVE <source> <target>. These have reversed.
op = 'MOVE'
out()[source]
class pyquil.quilbase.ClassicalMul(left, right)[source]

The MUL instruction.

op = 'MUL'
class pyquil.quilbase.ClassicalNeg(target)[source]

The NEG instruction.

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

The NOT instruction.

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

Deprecated class.

class pyquil.quilbase.ClassicalStore(target, left, right)[source]

The STORE instruction.

op = 'STORE'
out()[source]
class pyquil.quilbase.ClassicalSub(left, right)[source]

The SUB instruction.

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

Deprecated class.

class pyquil.quilbase.Declare(name, memory_type, memory_size=1, shared_region=None, offsets=None)[source]

A DECLARE directive.

This is printed in Quil as:

DECLARE <name> <memory-type> (SHARING <other-name> (OFFSET <amount> <type>)* )?

asdict()[source]
out()[source]
class pyquil.quilbase.DefGate(name, matrix, parameters=None)[source]

A DEFGATE directive.

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

Prints a readable Quil string representation of this gate.

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

This is the pyQuil object for a quantum gate instruction.

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

The HALT instruction.

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

Representation of an unconditional jump instruction (JUMP).

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

Abstract representation of an conditional jump instruction.

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

Representation of a target that can be jumped to.

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

The JUMP-UNLESS instruction.

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

The JUMP-WHEN instruction.

op = 'JUMP-WHEN'
class pyquil.quilbase.LogicalBinaryOp(left, right)[source]

The abstract class for binary logical classical instructions.

out()[source]
class pyquil.quilbase.Measurement(qubit, classical_reg=None)[source]

This is the pyQuil object for a Quil measurement instruction.

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

The NOP instruction.

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

A PRAGMA instruction.

This is printed in QUIL as:

PRAGMA <command> <arg1> <arg2> ... <argn> "<freeform_string>"

out()[source]
class pyquil.quilbase.RawInstr(instr_str)[source]

A raw instruction represented as a string.

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

The RESET instruction.

op = 'RESET'
class pyquil.quilbase.ResetQubit(qubit)[source]

This is the pyQuil object for a Quil targeted reset instruction.

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

Abstract class for simple instructions with no arguments.

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

The abstract class for unary classical instructions.

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

The WAIT instruction.

op = 'WAIT'

## pyquil.wavefunction¶

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

class pyquil.wavefunction.Wavefunction(amplitude_vector)[source]

Bases: object

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

Note

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

Initializes a wavefunction

Parameters: amplitude_vector – A numpy array of complex amplitudes
static from_bit_packed_string(coef_string)[source]

From a bit packed string, unpacks to get the wavefunction :param bytes coef_string: :return:

get_outcome_probs()[source]

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

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

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

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

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

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

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

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

Returns an array of probabilities in lexicographical order

sample_bitstrings(n_samples)[source]

Sample bitstrings from the distribution defined by the wavefunction.

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

Constructs the groundstate wavefunction for a given number of qubits.

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

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