pyqrack

Submodules

Attributes

Qrack

Classes

Pauli

Enum where members are also (and must be) ints

NeuronActivationFn

Enum where members are also (and must be) ints

QuimbCircuitType

Enum where members are also (and must be) ints

QrackAceBackend

A back end for elided quantum error correction

QrackNearCliffordQecBackend

A back end for near-Clifford quantum error correction

QrackCircuit

Class that exposes the QCircuit class of Qrack

QrackNeuron

Class that exposes the QNeuron class of Qrack

QrackNeuronTorch

Torch wrapper for QrackNeuron

QrackNeuronTorchFunction

Static forward/backward/apply functions for QrackNeuronTorch

QrackNeuronTorchLayer

Torch layer wrapper for QrackNeuron (with maximally expressive set of neurons between inputs and outputs)

QrackSimulator

Interface for all the Qrack functionality.

QrackStabilizer

Interface for pure-stabilizer Qrack functionality.

QrackSystem

Functions

quantize_by_range(data, feature_indices, bits)

Discretize selected features of a dataset into binary variables using numpy.linspace binning.

Package Contents

class pyqrack.Pauli

Bases: enum.IntEnum

Enum where members are also (and must be) ints

PauliI = 0
PauliX = 1
PauliY = 3
PauliZ = 2
class pyqrack.NeuronActivationFn

Bases: enum.IntEnum

Enum where members are also (and must be) ints

Sigmoid = 0
ReLU = 1
GeLU = 2
Generalized_Logistic = 3
LeakyReLU = 4
class pyqrack.QuimbCircuitType

Bases: enum.IntEnum

Enum where members are also (and must be) ints

Circuit = 0
CircuitDense = 1
CircuitMPS = 3
class pyqrack.QrackAceBackend(qubit_count=1, long_range_columns=4, long_range_rows=4, is_transpose=False, is_schmidt_decompose_multi=False, is_stabilizer_hybrid=False, is_binary_decision_tree=False, is_gpu=True, is_host_pointer=True if os.environ.get('PYQRACK_HOST_POINTER_DEFAULT_ON') else False, is_near_clifford_tableau_writer=False, noise=0, to_clone=None)

A back end for elided quantum error correction

This back end uses elided repetition code on a nearest-neighbor topology to emulate a utility-scale superconducting chip quantum computer in very little memory.4

The backend was originally designed assuming an (orbifolded) 2D qubit grid like 2019 Sycamore. However, it quickly became apparent that users can basically design their own connectivity topologies, without breaking the concept. (Not all will work equally well.)

Consider distributing the different “patches” to different GPUs with self.sim[sim_id].set_device(gpu_id)! (If you have 3+ patches, maybe your discrete GPU can do multiple patches in the time it takes an Intel HD to do one patch worth of work!)

sim

Array of simulators corresponding to “patches” between boundary rows.

Type:

QrackSimulator

long_range_columns

How many ideal rows between QEC boundary rows?

Type:

int

is_transpose

Rows are long if False, columns are long if True

Type:

bool

long_range_columns = 4
long_range_rows = 4
is_transpose = False
_coupling_map = None
_qubits = []
sim = []
clone()
num_qubits()
get_row_length()
get_column_length()
_factor_width(width, is_transpose=False)
_ct_pair_prob(q1, q2)
_cz_shadow(q1, q2)
_qec_x(c)
_qec_h(t)
_qec_s(t)
_qec_adjs(t)
_anti_cz_shadow(c, t)
_cx_shadow(c, t)
_anti_cx_shadow(c, t)
_cy_shadow(c, t)
_anti_cy_shadow(c, t)
_unpack(lq)
static _get_qb_lhv_indices(hq)
static _get_lhv_bloch_angles(sim)
_get_bloch_angles(hq)
_rotate_to_bloch(hq, delta_azimuth, delta_inclination)
static _rotate_lhv_to_bloch(sim, delta_azimuth, delta_inclination)
_correct(lq, phase=False, skip_rotation=False)
apply_magnetic_bias(q, b)
u(lq, th, ph, lm)
r(p, th, lq)
h(lq)
s(lq)
adjs(lq)
x(lq)
y(lq)
z(lq)
t(lq)
adjt(lq)
_get_gate(pauli, anti, sim_id)
_get_connected(i, is_row)
_apply_coupling(pauli, anti, qb1, lhv1, hq1, qb2, lhv2, hq2, lq1_lr)
_cpauli(lq1, lq2, anti, pauli)
cx(lq1, lq2)
cy(lq1, lq2)
cz(lq1, lq2)
acx(lq1, lq2)
acy(lq1, lq2)
acz(lq1, lq2)
mcx(lq1, lq2)
mcy(lq1, lq2)
mcz(lq1, lq2)
macx(lq1, lq2)
macy(lq1, lq2)
macz(lq1, lq2)
swap(lq1, lq2)
iswap(lq1, lq2)
adjiswap(lq1, lq2)
prob(lq)
m(lq)
force_m(lq, result)
m_all()
measure_shots(q, s)
_apply_op(operation)
_add_sample_measure(sample_qubits, sample_clbits, num_samples)

Generate data samples from current statevector.

Taken almost straight from the terra source code.

Parameters:
  • measure_params (list) – List of (qubit, clbit) values for measure instructions to sample.

  • num_samples (int) – The number of data samples to generate.

Returns:

A list of data values in hex format.

Return type:

list

run_qiskit_circuit(experiment, shots=1)
static get_qiskit_basis_gates()
get_logical_coupling_map()
create_noise_model(x=0.25, y=0.25)
class pyqrack.QrackNearCliffordQecBackend(qubit_count=1, code_len=5, layers_per_qec_round=0, is_eager=True, to_clone=None)

A back end for near-Clifford quantum error correction

This back end uses repetition code on a near-Clifford simulator to emulate a utility-scale superconducting chip quantum computer in very little memory.

sim

Array of simulators corresponding to “patches” between boundary rows.

Type:

QrackSimulator

n_qubits = 1
code_len = 5
layers = 0
is_eager = True
a
b = [0]
c = [False]
sim
_correct_bit(lq)
_correct_phase(lq)
_correct(lq, b, p)
_prop_nc(lq1, lq2)
clone()
num_qubits()
rz(th, lq)
h(lq)
s(lq)
adjs(lq)
x(lq)
y(lq)
z(lq)
t(lq)
adjt(lq)
cx(lq1, lq2)
cy(lq1, lq2)
cz(lq1, lq2)
acx(lq1, lq2)
acy(lq1, lq2)
acz(lq1, lq2)
mcx(lq1, lq2)
mcy(lq1, lq2)
mcz(lq1, lq2)
macx(lq1, lq2)
macy(lq1, lq2)
macz(lq1, lq2)
swap(lq1, lq2)
iswap(lq1, lq2)
adjiswap(lq1, lq2)
m(lq)
force_m(lq, result)
m_all()
_apply_op(operation)
_add_sample_measure(sample_qubits, sample_clbits)

Generate data samples from current statevector.

Taken almost straight from the terra source code.

Parameters:
  • measure_params (list) – List of (qubit, clbit) values for measure instructions to sample.

  • num_samples (int) – The number of data samples to generate.

Returns:

A list of data values in hex format.

Return type:

list

run_qiskit_circuit(experiment, shots=1)
static get_qiskit_basis_gates()
class pyqrack.QrackCircuit(is_collapse=True, is_near_clifford=False, clone_cid=-1, is_inverse=False, past_light_cone=[])

Class that exposes the QCircuit class of Qrack

QrackCircuit allows the user to specify a unitary circuit, before running it. Upon running the state, the result is a QrackSimulator state. Currently, measurement is not supported, but measurement can be run on the resultant QrackSimulator.

cid

Qrack ID of this circuit

Type:

int

__del__()
static _ulonglong_byref(a)
static _double_byref(a)
static _complex_byref(a)
static _mtrx_to_u4(m)
static _u3_to_mtrx(params)
static _u4_to_mtrx(params)
static _make_mtrx_unitary(m)
clone()

Make a new circuit that is an exact clone of this circuit

Raises:

RuntimeError – QrackCircuit C++ library raised an exception.

inverse()

Make a new circuit that is the exact inverse of this circuit

Raises:

RuntimeError – QrackCircuit C++ library raised an exception.

past_light_cone(q)

Make a new circuit with just this circuits’ past light cone for certain qubits.

Parameters:

q – list of qubit indices to include at beginning of past light cone

Raises:

RuntimeError – QrackCircuit C++ library raised an exception.

get_qubit_count()

Get count of qubits in circuit

Raises:

RuntimeError – QrackCircuit C++ library raised an exception.

swap(q1, q2)

Add a ‘Swap’ gate to the circuit

Parameters:
  • q1 – qubit index #1

  • q2 – qubit index #2

Raises:

RuntimeError – QrackCircuit C++ library raised an exception.

mtrx(m, q)

Operation from matrix.

Applies arbitrary operation defined by the given matrix.

Parameters:
  • m – row-major complex list representing the operator.

  • q – the qubit number on which the gate is applied to.

Raises:
  • ValueError – 2x2 matrix ‘m’ in QrackCircuit.mtrx() must contain at least 4 elements.

  • RuntimeError – QrackSimulator raised an exception.

ucmtrx(c, m, q, p)

Multi-controlled single-target-qubit gate

Specify a controlled gate by its control qubits, its single-qubit matrix “payload,” the target qubit, and the permutation of qubits that activates the gate.

Parameters:
  • c – list of controlled qubits

  • m – row-major complex list representing the operator.

  • q – target qubit

  • p – permutation of target qubits

Raises:
  • ValueError – 2x2 matrix ‘m’ in QrackCircuit.ucmtrx() must contain at least 4 elements.

  • RuntimeError – QrackSimulator raised an exception.

run(qsim)

Run circuit on simulator

Run the encoded circuit on a specific simulator. The result will remain in this simulator.

Parameters:

qsim – QrackSimulator on which to run circuit

Raises:

RuntimeError – QrackCircuit raised an exception.

out_to_file(filename)

Output optimized circuit to file

Outputs the (optimized) circuit to a file named according to the “filename” parameter.

Parameters:

filename – Name of file

out_to_string()

Output optimized circuit to string

Outputs the (optimized) circuit to a string.

to_qiskit_circuit()

Convert to a Qiskit circuit

Outputs a Qiskit circuit from a QrackCircuit.

Raises:

RuntimeErorr – Before trying to string_to_qiskit_circuit() with QrackCircuit, you must install Qiskit, numpy, and math!

static in_from_file(filename)

Read in optimized circuit from file

Reads in an (optimized) circuit from a file named according to the “filename” parameter.

Parameters:

filename – Name of file

static file_gate_count(filename)

File gate count

Return the count of gates in a QrackCircuit file

Parameters:

filename – Name of file

static file_to_qiskit_circuit(filename)

Convert an output file to a Qiskit circuit

Reads in an (optimized) circuit from a file named according to the “filename” parameter and outputs a Qiskit circuit.

Parameters:

filename – Name of file

Raises:

RuntimeErorr – Before trying to file_to_qiskit_circuit() with QrackCircuit, you must install Qiskit, numpy, and math!

static string_to_qiskit_circuit(circ_string)

Convert an output string to a Qiskit circuit

Reads in an (optimized) circuit from a string parameter and outputs a Qiskit circuit.

Parameters:

circ_string – String representation of circuit

Raises:

RuntimeErorr – Before trying to string_to_qiskit_circuit() with QrackCircuit, you must install Qiskit, numpy, and math!

static in_from_qiskit_circuit(circ)

Read a Qiskit circuit into a QrackCircuit

Reads in a circuit from a Qiskit QuantumCircuit

Parameters:

circ – Qiskit circuit

Raises:

RuntimeErorr – Before trying to file_to_qiskit_circuit() with QrackCircuit, you must install Qiskit, numpy, and math!

static file_to_quimb_circuit(filename, circuit_type=QuimbCircuitType.Circuit, psi0=None, gate_opts=None, tags=None, psi0_dtype='complex128', psi0_tag='PSI0', bra_site_ind_id='b{}')

Convert an output file to a Quimb circuit

Reads in an (optimized) circuit from a file named according to the “filename” parameter and outputs a Quimb circuit.

Parameters:
  • filename – Name of file

  • circuit_type – “QuimbCircuitType” enum value specifying type of Quimb circuit

  • psi0 – The initial state, assumed to be |00000….0> if not given. The state is always copied and the tag PSI0 added

  • gate_opts – Default keyword arguments to supply to each gate_TN_1D() call during the circuit

  • tags – Tag(s) to add to the initial wavefunction tensors (whether these are propagated to the rest of the circuit’s tensors

  • psi0_dtype – Ensure the initial state has this dtype.

  • psi0_tag – Ensure the initial state has this tag.

  • bra_site_ind_id – Use this to label ‘bra’ site indices when creating certain (mostly internal) intermediate tensor networks.

Raises:

RuntimeErorr – Before trying to file_to_quimb_circuit() with QrackCircuit, you must install quimb, Qiskit, numpy, and math!

static file_to_tensorcircuit(filename, inputs=None, circuit_params=None, binding_params=None)

Convert an output file to a TensorCircuit circuit

Reads in an (optimized) circuit from a file named according to the “filename” parameter and outputs a TensorCircuit circuit.

Parameters:
  • filename – Name of file

  • inputs – pass-through to tensorcircuit.Circuit.from_qiskit

  • circuit_params – pass-through to tensorcircuit.Circuit.from_qiskit

  • binding_params – pass-through to tensorcircuit.Circuit.from_qiskit

Raises:

RuntimeErorr – Before trying to file_to_quimb_circuit() with QrackCircuit, you must install TensorCircuit, Qiskit, numpy, and math!

static in_from_tensorcircuit(tcirc, enable_instruction=False, enable_inputs=False)

Convert a TensorCircuit circuit to a QrackCircuit

Accepts a TensorCircuit circuit and outputs an equivalent QrackCircuit

Parameters:
  • tcirc – TensorCircuit circuit

  • enable_instruction – whether to also export measurement and reset instructions

  • enable_inputs – whether to also export the inputs

Raises:

RuntimeErorr – Before trying to in_from_tensorcircuit() with QrackCircuit, you must install TensorCircuit, Qiskit, numpy, and math!

class pyqrack.QrackNeuron(simulator, controls, target, activation_fn=NeuronActivationFn.Sigmoid, alpha=1.0, _init=True, _isTorch=False)

Class that exposes the QNeuron class of Qrack

This model of a “quantum neuron” is based on the concept of a “uniformly controlled” rotation of a single output qubit around the Pauli Y axis, and has been developed by others. In our case, the primary relevant gate could also be called a single-qubit-target multiplexer.

(See https://arxiv.org/abs/quant-ph/0407010 for an introduction to “uniformly controlled gates.)

QrackNeuron is meant to be interchangeable with a single classical neuron, as in conventional neural net software. It differs from classical neurons in conventional neural nets, in that the “synaptic cleft” is modelled as a single qubit. Hence, this neuron can train and predict in superposition.

nid

Qrack ID of this neuron

Type:

int

simulator

Simulator instance for all synaptic clefts of the neuron

Type:

QrackSimulator

controls

Indices of all “control” qubits, for neuron input

Type:

list(int)

target

Index of “target” qubit, for neuron output

Type:

int

activation_fn

Activation function choice

Type:

NeuronActivationFn

alpha

Activation function parameter, if required

Type:

float

angles

(or c_double) Memory for neuron prediction angles

Type:

list[ctypes.c_float]

_get_error()
_throw_if_error()
simulator
controls
target
activation_fn
alpha = 1.0
angles = None
nid
__del__()
clone()

Clones this neuron.

Create a new, independent neuron instance with identical angles, inputs, output, and tolerance, for the same QrackSimulator.

Raises:

RuntimeError – QrackNeuron C++ library raised an exception.

static _ulonglong_byref(a)
static _real1_byref(a)
set_simulator(s, controls=None, target=None)

Set the neuron simulator

Set the simulator used by this neuron

Parameters:
  • s (QrackSimulator) – The simulator to use

  • controls (list[int]) – The control qubit IDs to use

  • target (int) – The output qubit ID to use

Raises:

RuntimeError – QrackSimulator raised an exception.

set_qubit_ids(controls, target=None)

Set the neuron qubit identifiers

Set the control and target qubits within the simulator

Parameters:
  • controls (list[int]) – The control qubit IDs to use

  • target (int) – The output qubit ID to use

Raises:

RuntimeError – QrackSimulator raised an exception.

set_angles(a)

Directly sets the neuron parameters.

Set all synaptic parameters of the neuron directly, by a list enumerated over the integer permutations of input qubits.

Parameters:

a (list(double)) – List of input permutation angles

Raises:
  • ValueError – Angles ‘a’ in QrackNeuron.set_angles() must contain at least (2 ** len(self.controls)) elements.

  • RuntimeError – QrackSimulator raised an exception.

get_angles()

Directly gets the neuron parameters.

Get all synaptic parameters of the neuron directly, as a list enumerated over the integer permutations of input qubits.

Raises:

RuntimeError – QrackNeuron C++ library raised an exception.

set_alpha(a)

Set the neuron ‘alpha’ parameter.

To enable nonlinear activation, QrackNeuron has an ‘alpha’ parameter that is applied as a power to its angles, before learning and prediction. This makes the activation function sharper (or less sharp).

set_activation_fn(f)

Sets the activation function of this QrackNeuron

Nonlinear activation functions can be important to neural net applications, like DNN. The available activation functions are enumerated in NeuronActivationFn.

predict(e=True, r=True)

Predict based on training

“Predict” the anticipated output, based on input and training. By default, “predict()” will initialize the output qubit as by resetting to |0> and then acting a Hadamard gate. From that state, the method amends the output qubit upon the basis of the state of its input qubits, applying a rotation around Pauli Y axis according to the angle learned for the input.

Parameters:
  • e (bool) – If False, predict the opposite

  • r (bool) – If True, start by resetting the output to 50/50

Raises:

RuntimeError – QrackNeuron C++ library raised an exception.

unpredict(e=True)

Uncompute a prediction

Uncompute a ‘prediction’ of the anticipated output, based on input and training.

Parameters:

e (bool) – If False, unpredict the opposite

Raises:

RuntimeError – QrackNeuron C++ library raised an exception.

learn_cycle(e=True)

Run a learning cycle

A learning cycle consists of predicting a result, saving the classical outcome, and uncomputing the prediction.

Parameters:

e (bool) – If False, predict the opposite

Raises:

RuntimeError – QrackNeuron C++ library raised an exception.

learn(eta, e=True, r=True)

Learn from current qubit state

“Learn” to associate current inputs with output. Based on input qubit states and volatility ‘eta,’ the input state synaptic parameter is updated to prefer the “e” (“expected”) output.

Parameters:
  • eta (double) – Training volatility, 0 to 1

  • e (bool) – If False, predict the opposite

  • r (bool) – If True, start by resetting the output to 50/50

Raises:

RuntimeError – QrackNeuron C++ library raised an exception.

learn_permutation(eta, e=True, r=True)

Learn from current classical state

Learn to associate current inputs with output, under the assumption that the inputs and outputs are “classical.” Based on input qubit states and volatility ‘eta,’ the input state angle is updated to prefer the “e” (“expected”) output.

Parameters:
  • eta (double) – Training volatility, 0 to 1

  • e (bool) – If False, predict the opposite

  • r (bool) – If True, start by resetting the output to 50/50

Raises:

RuntimeError – QrackNeuron C++ library raised an exception.

static quantile_bounds(vec, bits)

Calculate vector quantile bounds

This is a static helper method to calculate the quantile bounds of 2 ** bits worth of quantiles.

Parameters:
  • vec – numerical vector

  • bits – log2() of quantile count

Returns:

Quantile (n + 1) bounds for n-quantile division, including minimum and maximum values

static discretize(vec, bounds)

Discretize vector by quantile bounds

This is a static helper method to discretize a numerical vector according to quantile bounds calculated by the quantile_bounds(vec, bits) static method.

Parameters:
  • vec – numerical vector

  • bounds – (n + 1) n-quantile bounds including extrema

Returns:

Discretized bit-row vector, least-significant first

static flatten_and_transpose(arr)

Flatten and transpose feature matrix

This is a static helper method to convert a multi-feature bit-row matrix to an observation-row matrix with flat feature columns.

Parameters:

arr – bit-row matrix

Returns:

Observation-row matrix with flat feature columns

static bin_endpoints_average(bounds)

Bin endpoints average

This is a static helper method that accepts the output bins from quantile_bounds() and returns the average points between the bin endpoints. (This is NOT always necessarily the best heuristic for how to convert binned results back to numerical results, but it is often a reasonable way.)

Parameters:

bounds – (n + 1) n-quantile bounds including extrema

Returns:

List of average points between the bin endpoints

class pyqrack.QrackNeuronTorch(neuron, x)

Bases: nn.Module if _IS_TORCH_AVAILABLE else object

Torch wrapper for QrackNeuron

neuron

QrackNeuron backing this torch wrapper

Type:

QrackNeuron

neuron
weights
forward()
class pyqrack.QrackNeuronTorchFunction

Bases: Function if _IS_TORCH_AVAILABLE else object

Static forward/backward/apply functions for QrackNeuronTorch

static _apply(angles, neuron)
static forward(ctx, x, neuron)
static _backward(angles, neuron, simulator)
static backward(ctx, grad_output)
class pyqrack.QrackNeuronTorchLayer(input_qubits, output_qubits, hidden_qubits=None, lowest_combo_count=0, highest_combo_count=2, activation=int(NeuronActivationFn.Generalized_Logistic), parameters=None, post_init_fn=dummy_post_init_fn, **kwargs)

Bases: nn.Module if _IS_TORCH_AVAILABLE else object

Torch layer wrapper for QrackNeuron (with maximally expressive set of neurons between inputs and outputs)

simulator

Prototype simulator that batching copies to use with QrackNeuron instances. (You may customize or overwrite the initialization or reference, before calling forward(x).)

Type:

QrackSimulator

simulators

In-flight copies of prototype simulator corresponding to batch count

Type:

list[QrackSimulator]

input_indices

simulator qubit indices used as QrackNeuron inputs

Type:

list[int], read-only

output_indices

simulator qubit indices used as QrackNeuron outputs

Type:

list[int], read-only

hidden_indices

simulator qubit indices used as QrackNeuron hidden inputs (in maximal superposition)

Type:

list[int], read-only

neurons

QrackNeuronTorch wrappers (for PyQrack QrackNeurons) in this layer, corresponding to weights

Type:

ModuleList[QrackNeuronTorch]

weights

List of tensors corresponding one-to-one with weights of list of neurons

Type:

ParameterList

apply_fn

Corresponds to QrackNeuronTorchFunction.apply(x, neuron_wrapper) (or override with a custom implementation)

Type:

Callable[Tensor, QrackNeuronTorch]

post_init_fn

Function that is applied after forward(x) state initialization, before inference. (As the function depends on nothing but the simulator, it’s differentiable.)

Type:

Callable[QrackSimulator]

simulator
simulators = []
input_indices
hidden_indices
output_indices
activation
dtype
apply_fn
post_init_fn
neurons
forward(x)
class pyqrack.QrackSimulator(qubit_count=-1, clone_sid=-1, is_schmidt_decompose_multi=False, is_stabilizer_hybrid=False, is_binary_decision_tree=False, is_gpu=True, is_host_pointer=True if os.environ.get('PYQRACK_HOST_POINTER_DEFAULT_ON') else False, is_sparse=False, is_near_clifford_tableau_writer=False, noise=0, pyzx_circuit=None, qiskit_circuit=None)

Interface for all the Qrack functionality.

sid

Corresponding simulator id.

Type:

int

_get_error()
_throw_if_error()
sid = None
is_pure_stabilizer = False
__del__()
static _int_byref(a)
static _ulonglong_byref(a)
static _longlong_byref(a)
static _double_byref(a)
static _complex_byref(a)
static _real1_byref(a)
static _bool_byref(a)
static _qrack_complex_byref(a)
static _to_ubyte(nv, v)
static _to_ulonglong(m, v)
static _pairwise(it)
seed(s)
set_concurrency(p)

Set the CPU parallel thread count

set_device(d)

Set the GPU device ID

set_device_list(d)

Set the GPU device ID

clone()
x(q)

Applies X gate.

Applies the Pauli “X” operator to the qubit at position “q.” The Pauli “X” operator is equivalent to a logical “NOT.”

Parameters:

q – the qubit number on which the gate is applied to.

Raises:

RuntimeError – QrackSimulator raised an exception.

y(q)

Applies Y gate.

Applies the Pauli “Y” operator to the qubit at “q.” The Pauli “Y” operator is equivalent to a logical “NOT” with permutation phase.

Parameters:

q – the qubit number on which the gate is applied to.

Raises:

RuntimeError – QrackSimulator raised an exception.

z(q)

Applies Z gate.

Applies the Pauli “Z” operator to the qubit at “q.” The Pauli “Z” operator flips the phase of |1>

Parameters:

q – the qubit number on which the gate is applied to.

Raises:

RuntimeError – QrackSimulator raised an exception.

h(q)

Applies H gate.

Applies the Hadarmard operator to the qubit at “q.”

Parameters:

q – the qubit number on which the gate is applied to.

Raises:

RuntimeError – QrackSimulator raised an exception.

s(q)

Applies S gate.

Applies the 1/4 phase rotation to the qubit at “q.”

Parameters:

q – the qubit number on which the gate is applied to.

Raises:

RuntimeError – QrackSimulator raised an exception.

t(q)

Applies T gate.

Applies the 1/8 phase rotation to the qubit at “q.”

Parameters:

q – the qubit number on which the gate is applied to.

Raises:

RuntimeError – QrackSimulator raised an exception.

adjs(q)

Adjoint of S gate

Applies the gate equivalent to the inverse of S gate.

Parameters:

q – the qubit number on which the gate is applied to.

Raises:

RuntimeError – QrackSimulator raised an exception.

adjt(q)

Adjoint of T gate

Applies the gate equivalent to the inverse of T gate.

Parameters:

q – the qubit number on which the gate is applied to.

Raises:

RuntimeError – QrackSimulator raised an exception.

u(q, th, ph, la)

General unitary gate.

Applies a gate guaranteed to be unitary. Spans all possible single bit unitary gates.

U(theta, phi, lambda) = RZ(phi + pi/2)RX(theta)RZ(lambda - pi/2)

Parameters:
  • q – the qubit number on which the gate is applied to.

  • th – theta

  • ph – phi

  • la – lambda

Raises:

RuntimeError – QrackSimulator raised an exception.

mtrx(m, q)

Operation from matrix.

Applies arbitrary operation defined by the given matrix.

Parameters:
  • m – row-major complex list representing the operator.

  • q – the qubit number on which the gate is applied to.

Raises:
  • ValueError – 2x2 matrix ‘m’ in QrackSimulator.mtrx() must contain at least 4 elements.

  • RuntimeError – QrackSimulator raised an exception.

r(b, ph, q)

Rotation gate.

Rotate the qubit along the given pauli basis by the given angle.

Parameters:
  • b – Pauli basis

  • ph – rotation angle

  • q – the qubit number on which the gate is applied to

Raises:

RuntimeError – QrackSimulator raised an exception.

exp(b, ph, q)

Arbitrary exponentiation

exp(b, theta) = e^{i*theta*[b_0 . b_1 …]} where . is the tensor product.

Parameters:
  • b – Pauli basis

  • ph – coefficient of exponentiation

  • q – the qubit number on which the gate is applied to

Raises:

RuntimeError – QrackSimulator raised an exception.

mcx(c, q)

Multi-controlled X gate

If all controlled qubits are |1> then the target qubit is flipped.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

mcy(c, q)

Multi-controlled Y gate

If all controlled qubits are |1> then the Pauli “Y” gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

mcz(c, q)

Multi-controlled Z gate

If all controlled qubits are |1> then the Pauli “Z” gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

mch(c, q)

Multi-controlled H gate

If all controlled qubits are |1> then the Hadarmard gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

mcs(c, q)

Multi-controlled S gate

If all controlled qubits are |1> then the “S” gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

mct(c, q)

Multi-controlled T gate

If all controlled qubits are |1> then the “T” gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

mcadjs(c, q)

Multi-controlled adjs gate

If all controlled qubits are |1> then the adjs gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

mcadjt(c, q)

Multi-controlled adjt gate

If all controlled qubits are |1> then the adjt gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

mcu(c, q, th, ph, la)

Multi-controlled arbitraty unitary

If all controlled qubits are |1> then the unitary gate described by parameters is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

  • th – theta

  • ph – phi

  • la – lambda

Raises:

RuntimeError – QrackSimulator raised an exception.

mcmtrx(c, m, q)

Multi-controlled arbitrary operator

If all controlled qubits are |1> then the arbitrary operation by parameters is applied to the target qubit.

Parameters:
  • c – list of controlled qubits

  • m – row-major complex list representing the operator.

  • q – target qubit

Raises:
  • ValueError – 2x2 matrix ‘m’ in QrackSimulator.mcmtrx() must contain at least 4 elements.

  • RuntimeError – QrackSimulator raised an exception.

macx(c, q)

Anti multi-controlled X gate

If all controlled qubits are |0> then the target qubit is flipped.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

macy(c, q)

Anti multi-controlled Y gate

If all controlled qubits are |0> then the Pauli “Y” gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

macz(c, q)

Anti multi-controlled Z gate

If all controlled qubits are |0> then the Pauli “Z” gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

mach(c, q)

Anti multi-controlled H gate

If all controlled qubits are |0> then the Hadarmard gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

macs(c, q)

Anti multi-controlled S gate

If all controlled qubits are |0> then the “S” gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

mact(c, q)

Anti multi-controlled T gate

If all controlled qubits are |0> then the “T” gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

macadjs(c, q)

Anti multi-controlled adjs gate

If all controlled qubits are |0> then the adjs gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

macadjt(c, q)

Anti multi-controlled adjt gate

If all controlled qubits are |0> then the adjt gate is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

macu(c, q, th, ph, la)

Anti multi-controlled arbitraty unitary

If all controlled qubits are |0> then the unitary gate described by parameters is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • q – target qubit.

  • th – theta

  • ph – phi

  • la – lambda

Raises:

RuntimeError – QrackSimulator raised an exception.

macmtrx(c, m, q)

Anti multi-controlled arbitraty operator

If all controlled qubits are |0> then the arbitrary operation by parameters is applied to the target qubit.

Parameters:
  • c – list of controlled qubits.

  • m – row-major complex matrix which defines the operator.

  • q – target qubit.

Raises:
  • ValueError – 2x2 matrix ‘m’ in QrackSimulator.macmtrx() must contain at least 4 elements.

  • RuntimeError – QrackSimulator raised an exception.

ucmtrx(c, m, q, p)

Multi-controlled arbitrary operator with arbitrary controls

If all control qubits match ‘p’ permutation by bit order, then the arbitrary operation by parameters is applied to the target qubit.

Parameters:
  • c – list of control qubits

  • m – row-major complex list representing the operator.

  • q – target qubit

  • p – permutation of list of control qubits

Raises:
  • ValueError – 2x2 matrix ‘m’ in QrackSimulator.ucmtrx() must contain at least 4 elements.

  • RuntimeError – QrackSimulator raised an exception.

multiplex1_mtrx(c, q, m)

Multiplex gate

A multiplex gate with a single target and an arbitrary number of controls.

Parameters:
  • c – list of controlled qubits.

  • m – row-major complex matrix which defines the operator.

  • q – target qubit.

Raises:
  • ValueError – Multiplex matrix ‘m’ in QrackSimulator.multiplex1_mtrx() must contain at least 4 elements.

  • RuntimeError – QrackSimulator raised an exception.

mx(q)

Multi X-gate

Applies the Pauli “X” operator on all qubits.

Parameters:

q – list of qubits to apply X on.

Raises:

RuntimeError – QrackSimulator raised an exception.

my(q)

Multi Y-gate

Applies the Pauli “Y” operator on all qubits.

Parameters:

q – list of qubits to apply Y on.

Raises:

RuntimeError – QrackSimulator raised an exception.

mz(q)

Multi Z-gate

Applies the Pauli “Z” operator on all qubits.

Parameters:

q – list of qubits to apply Z on.

Raises:

RuntimeError – QrackSimulator raised an exception.

mcr(b, ph, c, q)

Multi-controlled arbitrary rotation.

If all controlled qubits are |1> then the arbitrary rotation by parameters is applied to the target qubit.

Parameters:
  • b – Pauli basis

  • ph – coefficient of exponentiation.

  • c – list of controlled qubits.

  • q – the qubit number on which the gate is applied to.

Raises:

RuntimeError – QrackSimulator raised an exception.

mcexp(b, ph, cs, q)

Multi-controlled arbitrary exponentiation

If all controlled qubits are |1> then the target qubit is exponentiated an pauli basis basis with coefficient.

Parameters:
  • b – Pauli basis

  • ph – coefficient of exponentiation.

  • q – the qubit number on which the gate is applied to.

Raises:

RuntimeError – QrackSimulator raised an exception.

swap(qi1, qi2)

Swap Gate

Swaps the qubits at two given positions.

Parameters:
  • qi1 – First position of qubit.

  • qi2 – Second position of qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

iswap(qi1, qi2)

Swap Gate with phase.

Swaps the qubits at two given positions. If the bits are different then there is additional phase of i.

Parameters:
  • qi1 – First position of qubit.

  • qi2 – Second position of qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

adjiswap(qi1, qi2)

Swap Gate with phase.

Swaps the qubits at two given positions. If the bits are different then there is additional phase of -i.

Parameters:
  • qi1 – First position of qubit.

  • qi2 – Second position of qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

fsim(th, ph, qi1, qi2)

Fsim gate.

The 2-qubit “fSim” gate Useful in the simulation of particles with fermionic statistics

Parameters:
  • qi1 – First position of qubit.

  • qi2 – Second position of qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

cswap(c, qi1, qi2)

Controlled-swap Gate

Swaps the qubits at two given positions if the control qubits are |1>

Parameters:
  • c – list of controlled qubits.

  • qi1 – First position of qubit.

  • qi2 – Second position of qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

acswap(c, qi1, qi2)

Anti controlled-swap Gate

Swaps the qubits at two given positions if the control qubits are |0>

Parameters:
  • c – list of controlled qubits.

  • qi1 – First position of qubit.

  • qi2 – Second position of qubit.

Raises:

RuntimeError – QrackSimulator raised an exception.

m(q)

Measurement gate

Measures the qubit at “q” and returns Boolean value. This operator is not unitary & is probabilistic in nature.

Parameters:

q – qubit to measure

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Measurement result.

force_m(q, r)

Force-Measurement gate

Acts as if the measurement is applied and the result obtained is r

Parameters:
  • q – qubit to measure

  • r – the required result

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Measurement result.

m_all()

Measure-all gate

Measures measures all qubits. This operator is not unitary & is probabilistic in nature.

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Measurement result of all qubits.

measure_pauli(b, q)

Pauli Measurement gate

Measures the qubit at “q” with the given pauli basis. This operator is not unitary & is probabilistic in nature.

Parameters:
  • b – Pauli basis

  • q – qubit to measure

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Measurement result.

measure_shots(q, s)

Multi-shot measurement operator

Measures the qubit at “q” with the given pauli basis. This operator is not unitary & is probabilistic in nature.

Parameters:
  • q – list of qubits to measure

  • s – number of shots

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

list of measurement result.

reset_all()

Reset gate

Resets all qubits to |0>

Raises:

RuntimeError – QrackSimulator raised an exception.

static _split_longs(a)

Split operation

Splits the given integer into 64 bit numbers.

Parameters:

a – number to split

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

list of split numbers.

static _split_longs_2(a, m)

Split simultanoues operation

Splits 2 integers into same number of 64 bit numbers.

Parameters:
  • a – first number to split

  • m – second number to split

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

pair of lists of split numbers.

add(a, q)

Add integer to qubit

Adds the given integer to the given set of qubits.

Parameters:
  • a – first number to split

  • q – list of qubits to add the number

Raises:

RuntimeError – QrackSimulator raised an exception.

sub(a, q)

Subtract integer to qubit

Subtracts the given integer to the given set of qubits.

Parameters:
  • a – first number to split

  • q – list of qubits to subtract the number

Raises:

RuntimeError – QrackSimulator raised an exception.

adds(a, s, q)

Signed Addition integer to qubit

Signed Addition of the given integer to the given set of qubits, if there is an overflow the resultant will become negative.

Parameters:
  • a – number to add

  • s – qubit to store overflow

  • q – list of qubits to add the number

Raises:

RuntimeError – QrackSimulator raised an exception.

subs(a, s, q)

Subtract integer to qubit

Subtracts the given integer to the given set of qubits, if there is an overflow the resultant will become negative.

Parameters:
  • a – number to subtract

  • s – qubit to store overflow

  • q – list of qubits to subtract the number

Raises:

RuntimeError – QrackSimulator raised an exception.

mul(a, q, o)

Multiplies integer to qubit

Multiplies the given integer to the given set of qubits. Carry register is required for maintaining the unitary nature of operation and must be as long as the input qubit register.

Parameters:
  • a – number to multiply

  • q – list of qubits to multiply the number

  • o – carry register

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot mul()! (Create a QrackSimulator instead.)

div(a, q, o)

Divides qubit by integer

‘Divides’ the given qubits by the integer. (This is rather the adjoint of mul().) Carry register is required for maintaining the unitary nature of operation.

Parameters:
  • a – integer to divide by

  • q – qubits to divide

  • o – carry register

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot div()! (Create a QrackSimulator instead.)

muln(a, m, q, o)

Modulo Multiplication

Modulo Multiplication of the given integer to the given set of qubits Out-of-place register is required to store the resultant.

Parameters:
  • a – number to multiply

  • m – modulo number

  • q – list of qubits to multiply the number

  • o – carry register

Raises:

RuntimeError – QrackSimulator raised an exception.

divn(a, m, q, o)

Modulo Division

‘Modulo Division’ of the given set of qubits by the given integer (This is rather the adjoint of muln().) Out-of-place register is required to retrieve the resultant.

Parameters:
  • a – integer by which qubit will be divided

  • m – modulo integer

  • q – qubits to divide

  • o – carry register

Raises:

RuntimeError – QrackSimulator raised an exception.

pown(a, m, q, o)

Modulo Power

Raises the qubit to the power a to which mod m is applied to. Out-of-place register is required to store the resultant.

Parameters:
  • a – number in power

  • m – modulo number

  • q – list of qubits to exponentiate

  • o – out-of-place register

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot pown()! (Create a QrackSimulator instead.)

mcadd(a, c, q)

Controlled-add

Adds the given integer to the given set of qubits if all controlled qubits are |1>.

Parameters:
  • a – number to add.

  • c – list of controlled qubits.

  • q – list of qubits to add the number

Raises:

RuntimeError – QrackSimulator raised an exception.

mcsub(a, c, q)

Controlled-subtract

Subtracts the given integer to the given set of qubits if all controlled qubits are |1>.

Parameters:
  • a – number to subtract.

  • c – list of controlled qubits.

  • q – list of qubits to add the number

Raises:

RuntimeError – QrackSimulator raised an exception.

mcmul(a, c, q, o)

Controlled-multiply

Multiplies the given integer to the given set of qubits if all controlled qubits are |1>. Carry register is required for maintaining the unitary nature of operation.

Parameters:
  • a – number to multiply

  • c – list of controlled qubits.

  • q – list of qubits to add the number

  • o – carry register

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot mcmul()! (Create a QrackSimulator instead.)

mcdiv(a, c, q, o)

Controlled-divide.

‘Divides’ the given qubits by the integer if all controlled qubits are |1>. (This is rather the adjoint of mcmul().) Carry register is required for maintaining the unitary nature of operation.

Parameters:
  • a – number to divide by

  • c – list of controlled qubits.

  • q – qubits to divide

  • o – carry register

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot mcdiv()! (Create a QrackSimulator instead.)

mcmuln(a, c, m, q, o)

Controlled-modulo multiplication

Modulo multiplication of the given integer to the given set of qubits if all controlled qubits are |1>. Out-of-place register is required to store the resultant.

Parameters:
  • a – number to multiply

  • c – list of controlled qubits.

  • m – modulo number

  • q – list of qubits to add the number

  • o – out-of-place output register

Raises:

RuntimeError – QrackSimulator raised an exception.

mcdivn(a, c, m, q, o)

Controlled-divide.

Modulo division of the given qubits by the given number if all controlled qubits are |1>. (This is rather the adjoint of mcmuln().) Out-of-place register is required to retrieve the resultant.

Parameters:
  • a – number to divide by

  • c – list of controlled qubits.

  • m – modulo number

  • q – qubits to divide

  • o – carry register

Raises:

RuntimeError – QrackSimulator raised an exception.

mcpown(a, c, m, q, o)

Controlled-modulo Power

Raises the qubit to the power a to which mod m is applied to if all the controlled qubits are set to |1>. Out-of-place register is required to store the resultant.

Parameters:
  • a – number in power

  • c – control qubits

  • m – modulo number

  • q – list of qubits to exponentiate

  • o – out-of-place register

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot mcpown()! (Create a QrackSimulator instead.)

lda(qi, qv, t)

Load Accumalator

Quantum counterpart for LDA from MOS-6502 assembly. t must be of the length 2 ** len(qi). It loads each list entry index of t into the qi register and each list entry value into the qv register.

Parameters:
  • qi – qubit register for index

  • qv – qubit register for value

  • t – list of values

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot lda()! (Create a QrackSimulator instead.)

adc(s, qi, qv, t)

Add with Carry

Quantum counterpart for ADC from MOS-6502 assembly. t must be of the length 2 ** len(qi).

Parameters:
  • qi – qubit register for index

  • qv – qubit register for value

  • t – list of values

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot adc()! (Create a QrackSimulator instead.)

sbc(s, qi, qv, t)

Subtract with Carry

Quantum counterpart for SBC from MOS-6502 assembly. t must be of the length 2 ** len(qi)

Parameters:
  • qi – qubit register for index

  • qv – qubit register for value

  • t – list of values

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot sbc()! (Create a QrackSimulator instead.)

hash(q, t)

Hash function

Replicates the behaviour of LDA without the index register. For the operation to be unitary, the entries present in t must be unique, and the length of t must be 2 ** len(qi).

Parameters:
  • q – qubit register for value

  • t – list of values

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot hash()! (Create a QrackSimulator instead.)

qand(qi1, qi2, qo)

Logical AND

Logical AND of 2 qubits whose result is stored in the target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

qor(qi1, qi2, qo)

Logical OR

Logical OR of 2 qubits whose result is stored in the target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

qxor(qi1, qi2, qo)

Logical XOR

Logical exlusive-OR of 2 qubits whose result is stored in the target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

qnand(qi1, qi2, qo)

Logical NAND

Logical NAND of 2 qubits whose result is stored in the target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

qnor(qi1, qi2, qo)

Logical NOR

Logical NOR of 2 qubits whose result is stored in the target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

qxnor(qi1, qi2, qo)

Logical XOR

Logical exlusive-NOR of 2 qubits whose result is stored in the target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

cland(ci, qi, qo)

Classical AND

Logical AND with one qubit and one classical bit whose result is stored in target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

clor(ci, qi, qo)

Classical OR

Logical OR with one qubit and one classical bit whose result is stored in target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

clxor(ci, qi, qo)

Classical XOR

Logical exlusive-OR with one qubit and one classical bit whose result is stored in target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

clnand(ci, qi, qo)

Classical NAND

Logical NAND with one qubit and one classical bit whose result is stored in target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

clnor(ci, qi, qo)

Classical NOR

Logical NOR with one qubit and one classical bit whose result is stored in target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

clxnor(ci, qi, qo)

Classical XNOR

Logical exlusive-NOR with one qubit and one classical bit whose result is stored in target qubit.

Parameters:
  • qi1 – qubit 1

  • qi2 – qubit 2

  • qo – target qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

qft(qs)

Quantum Fourier Transform

Applies Quantum Fourier Transform on the list of qubits provided.

Parameters:

qs – list of qubits

Raises:

RuntimeError – QrackSimulator raised an exception.

iqft(qs)

Inverse-quantum Fourier Transform

Applies Inverse-quantum Fourier Transform on the list of qubits provided.

Parameters:

qs – list of qubits

Raises:

RuntimeError – QrackSimulator raised an exception.

allocate_qubit(qid)

Allocate Qubit

Allocate 1 new qubit with the given qubit ID.

Parameters:

qid – qubit id

Raises:

RuntimeError – QrackSimulator raised an exception.

release(q)

Release Qubit

Release qubit given by the given qubit ID.

Parameters:

q – qubit id

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

If the qubit was in |0> state with small tolerance.

num_qubits()

Get Qubit count

Returns the qubit count of the simulator.

Parameters:

q – qubit id

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Qubit count of the simulator

compose(other, q)

Compose qubits

Compose quantum description of given qubit with the current system.

Parameters:

q – qubit id

Raises:

RuntimeError – QrackSimulator raised an exception.

decompose(q)

Decompose system

Factorize a set of contiguous bits with minimal fidelity loss.

Parameters:

q – qubit id

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Decomposed subsystem simulator.

dispose(q)

Dispose qubits

Factorize a set of contiguous bits with minimal fidelity loss, and discard the separable bits.

Parameters:

q – qubit

Raises:

RuntimeError – QrackSimulator raised an exception.

dump_ids()

Dump all IDs

Dump all IDs from the selected simulator ID into the callback.

Returns:

List of ids

dump_ids_callback()

C callback function

dump()

Dump state vector

Dump state vector from the selected simulator ID into the callback.

Returns:

State vector list

dump_callback(i)

C callback function

in_ket(ket)

Set state vector

Set state vector for the selected simulator ID. Warning: State vector is not always the internal representation leading to sub-optimal performance of the method.

Parameters:

ket – the state vector to which simulator will be set

Raises:

RuntimeError – QrackSimulator raised an exception.

out_ket()

Get state vector

Returns the raw state vector of the simulator. Warning: State vector is not always the internal representation leading to sub-optimal performance of the method.

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

list representing the state vector.

out_probs()

Get basis dimension probabilities

Returns the probabilities of each basis dimension in the state vector of the simulator.

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

list representing the basis dimension probabilities.

out_rdm(q)

Get reduced density matrix

Returns the raw reduced density matrix of the simulator, for the qubit list. Warning: State vector or is not always the internal representation leading to sub-optimal performance of the method.

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

flat list structure representing the reduced density matrix.

highest_prob_perm()

Get the permutation (bit string) with the highest probability

Returns the single highest-probability bit string in the Hilbert space

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Highest probability dimension index

highest_n_prob_perm(n)

Get the top n permutations (bit strings) with the highest probability

Returns the top n highest-probability bit strings in the Hilbert space

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Top n highest probability dimension indices

prob_all(q)

Probabilities of all subset permutations

Get the probabilities of all permutations of the subset.

Parameters:

q – list of qubit ids

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

list representing the state vector.

prob(q)

Probability of |1>

Get the probability that a qubit is in the |1> state.

Parameters:

q – qubit id

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

probability of qubit being in |1>

prob_rdm(q)

Probability of |1>, (tracing out the reduced density matrix without stabilizer ancillary qubits)

Get the probability that a qubit is in the |1> state.

Parameters:

q – qubit id

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

probability of qubit being in |1>

prob_perm(q, c)

Probability of permutation

Get the probability that the qubit IDs in “q” have the truth values in “c”, directly corresponding by list index.

Parameters:
  • q – list of qubit ids

  • c – list of qubit truth values bools

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

probability that each qubit in “q[i]” has corresponding truth value in “c[i]”, at once

prob_perm_rdm(q, c, r=True)

Probability of permutation, (tracing out the reduced density matrix without stabilizer ancillary qubits)

Get the probability that the qubit IDs in “q” have the truth values in “c”, directly corresponding by list index.

Parameters:
  • q – list of qubit ids

  • c – list of qubit truth values bools

  • r – round Rz gates down from T^(1/2)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

probability that each qubit in “q[i]” has corresponding truth value in “c[i]”, at once

permutation_expectation(q)

Permutation expectation value

Get the permutation expectation value, based upon the order of input qubits.

Parameters:

q – qubits, from low to high

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

permutation_expectation_rdm(q, r=True)

Permutation expectation value, (tracing out the reduced density matrix without stabilizer ancillary qubits)

Get the permutation expectation value, based upon the order of input qubits.

Parameters:
  • q – qubits, from low to high

  • r – round Rz gates down from T^(1/2)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

factorized_expectation(q, c)

Factorized expectation value

Get the factorized expectation value, where each entry in “c” is an expectation value for corresponding “q” being false, then true, repeated for each in “q”.

Parameters:
  • q – qubits, from low to high

  • c – qubit falsey/truthy values, from low to high

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

factorized_expectation_rdm(q, c, r=True)

Factorized expectation value, (tracing out the reduced density matrix without stabilizer ancillary qubits)

Get the factorized expectation value, where each entry in “c” is an expectation value for corresponding “q” being false, then true, repeated for each in “q”.

Parameters:
  • q – qubits, from low to high

  • c – qubit falsey/truthy values, from low to high

  • r – round Rz gates down from T^(1/2)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

factorized_expectation_fp(q, c)

Factorized expectation value (floating-point)

Get the factorized expectation value, where each entry in “c” is an expectation value for corresponding “q” being false, then true, repeated for each in “q”.

Parameters:
  • q – qubits, from low to high

  • c – qubit falsey/truthy values, from low to high

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

factorized_expectation_fp_rdm(q, c, r=True)

Factorized expectation value, (tracing out the reduced density matrix without stabilizer ancillary qubits)

Get the factorized expectation value, where each entry in “c” is an expectation value for corresponding “q” being false, then true, repeated for each in “q”.

Parameters:
  • q – qubits, from low to high

  • c – qubit falsey/truthy values, from low to high

  • r – round Rz gates down from T^(1/2)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

unitary_expectation(q, b)

3-parameter unitary tensor product expectation value

Get the single-qubit (3-parameter) operator expectation value for the array of qubits and bases.

Parameters:
  • q – qubits, from low to high

  • b – 3-parameter, single-qubit, unitary bases (flat over wires)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

matrix_expectation(q, b)

Single-qubit operator tensor product expectation value

Get the single-qubit (3-parameter) operator expectation value for the array of qubits and bases.

Parameters:
  • q – qubits, from low to high

  • b – single-qubit (2x2) operator unitary bases (flat over wires)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

unitary_expectation_eigenval(q, b, e)

3-parameter unitary tensor product expectation value

Get the single-qubit (3-parameter) operator expectation value for the array of qubits and bases.

Parameters:
  • q – qubits, from low to high

  • b – 3-parameter, single-qubit, unitary bases (flat over wires)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

matrix_expectation_eigenval(q, b, e)

Single-qubit operator tensor product expectation value

Get the single-qubit (3-parameter) operator expectation value for the array of qubits and bases.

Parameters:
  • q – qubits, from low to high

  • b – single-qubit (2x2) operator unitary bases (flat over wires)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

pauli_expectation(q, b)

Pauli tensor product expectation value

Get the Pauli tensor product expectation value, where each entry in “b” is a Pauli observable for corresponding “q”, as the product for each in “q”.

Parameters:
  • q – qubits, from low to high

  • b – qubit Pauli bases

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Expectation value

variance(q)

Variance of probabilities of all subset permutations

Get the overall variance of probabilities of all permutations of the subset.

Parameters:

q – list of qubit ids

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

float variance

variance_rdm(q, r=True)

Permutation variance, (tracing out the reduced density matrix without stabilizer ancillary qubits)

Get the permutation variance, based upon the order of input qubits.

Parameters:
  • q – qubits, from low to high

  • r – round Rz gates down from T^(1/2)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

variance

factorized_variance(q, c)

Factorized variance

Get the factorized variance, where each entry in “c” is an variance for corresponding “q” being false, then true, repeated for each in “q”.

Parameters:
  • q – qubits, from low to high

  • c – qubit falsey/truthy values, from low to high

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

variance

factorized_variance_rdm(q, c, r=True)

Factorized variance, (tracing out the reduced density matrix without stabilizer ancillary qubits)

Get the factorized variance, where each entry in “c” is an variance for corresponding “q” being false, then true, repeated for each in “q”.

Parameters:
  • q – qubits, from low to high

  • c – qubit falsey/truthy values, from low to high

  • r – round Rz gates down from T^(1/2)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

variance

factorized_variance_fp(q, c)

Factorized variance (floating-point)

Get the factorized variance, where each entry in “c” is an variance for corresponding “q” being false, then true, repeated for each in “q”.

Parameters:
  • q – qubits, from low to high

  • c – qubit falsey/truthy values, from low to high

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

variance

factorized_variance_fp_rdm(q, c, r=True)

Factorized variance, (tracing out the reduced density matrix without stabilizer ancillary qubits)

Get the factorized variance, where each entry in “c” is an variance for corresponding “q” being false, then true, repeated for each in “q”.

Parameters:
  • q – qubits, from low to high

  • c – qubit falsey/truthy values, from low to high

  • r – round Rz gates down from T^(1/2)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

variance

unitary_variance(q, b)

3-parameter unitary tensor product variance

Get the single-qubit (3-parameter) operator variance for the array of qubits and bases.

Parameters:
  • q – qubits, from low to high

  • b – 3-parameter, single-qubit, unitary bases (flat over wires)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

variance

matrix_variance(q, b)

Single-qubit operator tensor product variance

Get the single-qubit (3-parameter) operator variance for the array of qubits and bases.

Parameters:
  • q – qubits, from low to high

  • b – single-qubit (2x2) operator unitary bases (flat over wires)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

variance

unitary_variance_eigenval(q, b, e)

3-parameter unitary tensor product variance

Get the single-qubit (3-parameter) operator variance for the array of qubits and bases.

Parameters:
  • q – qubits, from low to high

  • b – 3-parameter, single-qubit, unitary bases (flat over wires)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

variance

matrix_variance_eigenval(q, b, e)

Single-qubit operator tensor product variance

Get the single-qubit (3-parameter) operator variance for the array of qubits and bases.

Parameters:
  • q – qubits, from low to high

  • b – single-qubit (2x2) operator unitary bases (flat over wires)

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

variance

pauli_variance(q, b)

Pauli tensor product variance

Get the Pauli tensor product variance, where each entry in “b” is a Pauli observable for corresponding “q”, as the product for each in “q”.

Parameters:
  • q – qubits, from low to high

  • b – qubit Pauli bases

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

variance

joint_ensemble_probability(b, q)

Ensemble probability

Find the joint probability for all specified qubits under the respective Pauli basis transformations.

Parameters:
  • b – pauli basis

  • q – specified qubits

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Variance

phase_parity(la, q)

Phase to odd parity

Applies e^(i*la) phase factor to all combinations of bits with odd parity, based upon permutations of qubits.

Parameters:
  • la – phase

  • q – specified qubits

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot phase_parity()! (Create a QrackSimulator instead.)

phase_root_n(n, q)

Phase to root n

Applies -2 * math.pi / (2**N) phase rotation to each qubit.

Parameters:
  • n – Phase root

  • q – specified qubits

Raises:
  • RuntimeError – QrackSimulator raised an exception.

  • RuntimeError – QrackStabilizer cannot phase_root_n()! (Create a QrackSimulator instead.)

try_separate_1qb(qi1)

Manual seperation

Exposes manual control for schmidt decomposition which attempts to decompose the qubit with possible performance improvement

Parameters:

qi1 – qubit to be decomposed

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

State of the qubit.

try_separate_2qb(qi1, qi2)

Manual two-qubits seperation

two-qubits counterpart of try_separate_1qb.

Parameters:
  • qi1 – first qubit to be decomposed

  • qi2 – second qubit to be decomposed

Raises:

Runtimeerror – QrackSimulator raised an exception.

Returns:

State of both the qubits.

try_separate_tolerance(qs, t)

Manual multi-qubits seperation

Multi-qubits counterpart of try_separate_1qb.

Parameters:
  • qs – list of qubits to be decomposed

  • t – allowed tolerance

Raises:

Runtimeerror – QrackSimulator raised an exception.

Returns:

State of all the qubits.

separate(qs)

Force manual multi-qubits seperation

Force separation as per try_separate_tolerance.

Parameters:

qs – list of qubits to be decomposed

Raises:

Runtimeerror – QrackSimulator raised an exception.

get_unitary_fidelity()

Get fidelity estimate

When using “Schmidt decomposition rounding parameter” (“SDRP”) approximate simulation, QrackSimulator() can make an excellent estimate of its overall fidelity at any time, tested against a nearest-neighbor variant of quantum volume circuits.

Resetting the fidelity calculation to 1.0 happens automatically when calling mall are can be done manually with reset_unitary_fidelity().

Raises:

RuntimeError – QrackSimulator raised an exception.

Returns:

Fidelity estimate

reset_unitary_fidelity()

Reset fidelity estimate

When using “Schmidt decomposition rounding parameter” (“SDRP”) approximate simulation, QrackSimulator() can make an excellent estimate of its overall fidelity at any time, tested against a nearest-neighbor variant of quantum volume circuits.

Resetting the fidelity calculation to 1.0 happens automatically when calling m_all or can be done manually with reset_unitary_fidelity().

Raises:

RuntimeError – QrackSimulator raised an exception.

set_sdrp(sdrp)

Set “Schmidt decomposition rounding parameter”

When using “Schmidt decomposition rounding parameter” (“SDRP”) approximate simulation, QrackSimulator() can make an excellent estimate of its overall fidelity at any time, tested against a nearest-neighbor variant of quantum volume circuits.

Resetting the fidelity calculation to 1.0 happens automatically when calling m_all or can be done manually with reset_unitary_fidelity().

Raises:

RuntimeError – QrackSimulator raised an exception.

set_ncrp(ncrp)

Set “Near-Clifford rounding parameter”

When using “near-Clifford rounding parameter” (“NCRP”) approximate simulation, QrackSimulator() can make an excellent estimate of its overall fidelity after measurement, tested against a nearest-neighbor variant of quantum volume circuits.

Resetting the fidelity calculation to 1.0 happens automatically when calling m_all or can be done manually with reset_unitary_fidelity().

Raises:

RuntimeError – QrackSimulator raised an exception.

set_sprp(sprp)

Set “sparse probability rounding parameter”

When using sparse simulation, any amplitude with probability less than or equal to “SPRP” will be truncated out of the sparse representation.

Raises:

RuntimeError – QrackSimulator raised an exception.

set_reactive_separate(irs)

Set reactive separation option

If reactive separation is available, then this method turns it off/on. Note that reactive separation is on by default.

Parameters:

irs – is aggresively separable

Raises:

RuntimeError – QrackSimulator raised an exception.

set_t_injection(iti)

Set t-injection option

If t-injection is available, then this method turns it off/on. Note that t-injection is on by default.

Parameters:

iti – use “reverse t-injection gadget”

Raises:

RuntimeError – QrackSimulator raised an exception.

set_use_exact_near_clifford(enc)

Set option to use exact near-Clifford simulation

If t-injection is available, this method turns exact near-Clifford simulation off/on. (Default is on.) Approximate methods are faster.

Parameters:

enc – “on/off” for exact near-Clifford simulation

Raises:

RuntimeError – QrackSimulator raised an exception.

set_noise_parameter(np)

Set noise parameter option

If noisy simulation is on, then this set the depolarization parameter per qubit per gate. (Default is 0.01.)

Parameters:

np – depolarizing noise parameter

Raises:

RuntimeError – QrackSimulator raised an exception.

set_ace_max_qb(qb)

Set “automatic circuit elision” (ACE) max qubits

If isSchmidtDecompose=True, maximum entangled subsytem size of this simulator will be capped to ‘qb’, and entangling gates that would exceed that size are replaced with gate shadows.

Parameters:

qb – maximum subsystem qubits

Raises:

RuntimeError – QrackSimulator raised an exception.

set_sparse_ace_max_mb(mb)

Set sparse “automatic circuit elision” (ACE) max memory

If isSchmidtDecompose=True, isSparse=True, and isOpenCL=False, maximum subsytem size memory MB of this simulator will be capped to ‘mb’, and entangling gates that would exceed that size are replaced with gate shadows.

Parameters:

mb – maximum subsystem memory in MB

Raises:

RuntimeError – QrackSimulator raised an exception.

normalize()

Normalize the state

This should never be necessary to use unless decompose() is “abused.” (“Abusing” decompose() might lead to efficient entanglement-breaking channels, though.)

Raises:

RuntimeError – QrackSimulator raised an exception.

out_to_file(filename)

Output state to file (stabilizer only!)

Outputs the hybrid stabilizer state to file.

Parameters:

filename – Name of file

in_from_file(is_binary_decision_tree=False, is_gpu=True, is_host_pointer=True if os.environ.get('PYQRACK_HOST_POINTER_DEFAULT_ON') else False, is_sparse=False, is_near_clifford_tableau_writer=False, noise=0)

Input state from file (stabilizer only!)

Reads in a hybrid stabilizer state from file.

Parameters:

filename – Name of file

lossy_out_to_file(f, p=6, b=4)
lossy_in_from_file(f)
file_to_qiskit_circuit(is_hardware_encoded=False)

Convert an output state file to a Qiskit circuit

Reads in an (optimized) circuit from a file named according to the “filename” parameter and outputs a Qiskit circuit.

Parameters:

filename – Name of file

Raises:

RuntimeErorr – Before trying to file_to_qiskit_circuit() with QrackCircuit, you must install Qiskit, numpy, and math!

_reorder_qubits(mapping)

Reorders qubits in the circuit according to the given mapping using SWAP gates. (Thanks to “Elara,” an OpenAI GPT, for this implementation)

Parameters: - circuit (QuantumCircuit): The circuit to modify. - mapping (dict): Dictionary mapping internal qubit indices to logical qubit indices.

Returns: - QuantumCircuit: The modified circuit with qubits reordered.

file_to_optimized_qiskit_circuit()

Convert an output state file to a Qiskit circuit

Reads in a circuit from a file named according to the “filename” parameter and outputs a ‘hyper-optimized’ Qiskit circuit that favors maximum reduction in gate count and depth at the potential expense of additional non-Clifford gates. (Ancilla qubits are left included in the output, though they probably have no gates.)

Parameters:

filename – Name of file

Raises:

RuntimeErorr – Before trying to file_to_qiskit_circuit() with QrackCircuit, you must install Qiskit, numpy, and math!

_apply_pyzx_op(gate)
run_pyzx_gates(gates)

PYZX Gates

Converts PYZX gates to QRackSimulator and immediately executes them.

Parameters:

gates – list of PYZX gates

Raises:

RuntimeError – QrackSimulator raised an exception.

_apply_op(operation)
_add_sample_measure(sample_qubits, sample_clbits, num_samples)

Generate data samples from current statevector.

Taken almost straight from the terra source code.

Parameters:
  • measure_params (list) – List of (qubit, clbit) values for measure instructions to sample.

  • num_samples (int) – The number of data samples to generate.

Returns:

A list of data values in hex format.

Return type:

list

run_qiskit_circuit(experiment, shots=1)
static get_qiskit_basis_gates()
class pyqrack.QrackStabilizer(qubit_count=-1, clone_sid=-1, pyzx_circuit=None, qiskit_circuit=None)

Bases: pyqrack.qrack_simulator.QrackSimulator

Interface for pure-stabilizer Qrack functionality.

Like QrackSimulator with isTensorNetwork=True, QrackStabilizer does not implement a general ALU or phase parity operations. Unlike isTensorNetwork=True, QrackStabilizer does implement compose(), decompose(), and dispose() Even if your operation is non-Clifford in full generality, QrackStabilizer will attempt to reduce it to a Clifford case. Hence, QrackStabilizer inherits the full interface of QrackSimulator (via Qrack::QInterface).

sid

Corresponding simulator id.

Type:

int

sid = None
is_tensor_network = False
is_pure_stabilizer = True
set_stochastic(s)
set_major_quadrant(q)
flip_quadrant(q)
set_quadrant(q, b)
class pyqrack.QrackSystem
fppow = 5
pyqrack.Qrack
pyqrack.quantize_by_range(data, feature_indices, bits)

Discretize selected features of a dataset into binary variables using numpy.linspace binning.

Parameters:
  • data (np.ndarray) – Input data of shape (n_samples, n_features).

  • feature_indices (list[int]) – Indices of features to discretize.

  • bits (int) – Number of bits to represent each discretized feature (e.g., 2 bits = 4 quantiles).

Returns:

Transformed data with selected features replaced by binary bit columns.

Return type:

np.ndarray