INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Produces the RY gate:: | def RY(angle, qubit):
"""Produces the RY gate::
RY(phi) = [[cos(phi / 2), -sin(phi / 2)],
[sin(phi / 2), cos(phi / 2)]]
This gate is a single qubit Y-rotation.
:param angle: The angle to rotate around the y-axis on the bloch sphere.
:param qubit: The qubit apply the gate to... |
Produces the RZ gate:: | def RZ(angle, qubit):
"""Produces the RZ gate::
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.
:param angle: The angle to rotate around the z-axis on the bloch sphere.
:param qubit: The qubit a... |
Produces the PHASE gate:: | def PHASE(angle, qubit):
"""Produces the PHASE gate::
PHASE(phi) = [[1, 0],
[0, exp(1j * phi)]]
This is the same as the RZ gate.
:param angle: The angle to rotate around the z-axis on the bloch sphere.
:param qubit: The qubit apply the gate to.
:returns: A Gate objec... |
Produces a controlled - NOT ( controlled - X ) gate:: | def CNOT(control, target):
"""Produces a controlled-NOT (controlled-X) gate::
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.
:param control: Th... |
Produces a doubly - controlled NOT gate:: | def CCNOT(control1, control2, target):
"""Produces a doubly-controlled NOT gate::
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],
[... |
Produces a controlled - phase gate that phases the |00 > state:: | def CPHASE00(angle, control, target):
"""Produces a controlled-phase gate that phases the ``|00>`` state::
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.
:param angle... |
Produces a controlled - SWAP gate. This gate conditionally swaps the state of two qubits:: | def CSWAP(control, target_1, target_2):
"""Produces a controlled-SWAP gate. This gate conditionally swaps the state of two qubits::
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],
... |
Produces an ISWAP gate:: | def ISWAP(q1, q2):
"""Produces an ISWAP gate::
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 1 state and a -i phase to q2 when it is in... |
Produces a parameterized SWAP gate:: | def PSWAP(angle, q1, q2):
"""Produces a parameterized SWAP gate::
PSWAP(phi) = [[1, 0, 0, 0],
[0, 0, exp(1j * phi), 0],
[0, exp(1j * phi), 0, 0],
[0, 0, 0, 1]]
:pa... |
Produce a MEASURE instruction. | def MEASURE(qubit, classical_reg):
"""
Produce a MEASURE instruction.
:param qubit: The qubit to measure.
:param classical_reg: The classical register to measure into, or None.
:return: A Measurement instance.
"""
qubit = unpack_qubit(qubit)
if classical_reg is None:
address = N... |
Produce a TRUE instruction. | def TRUE(classical_reg):
"""
Produce a TRUE instruction.
:param classical_reg: A classical register to modify.
:return: An instruction object representing the equivalent MOVE.
"""
warn("`TRUE a` has been deprecated. Use `MOVE a 1` instead.")
if isinstance(classical_reg, int):
classi... |
Produce a FALSE instruction. | def FALSE(classical_reg):
"""
Produce a FALSE instruction.
:param classical_reg: A classical register to modify.
:return: An instruction object representing the equivalent MOVE.
"""
warn("`FALSE a` has been deprecated. Use `MOVE a 0` instead.")
if isinstance(classical_reg, int):
cla... |
Produce an AND instruction. | def AND(classical_reg1, classical_reg2):
"""
Produce an AND instruction.
NOTE: The order of operands was reversed in pyQuil <=1.9 .
:param classical_reg1: The first classical register, which gets modified.
:param classical_reg2: The second classical register or immediate value.
:return: A Clas... |
Produce an inclusive OR instruction. | def IOR(classical_reg1, classical_reg2):
"""
Produce an inclusive OR instruction.
:param classical_reg1: The first classical register, which gets modified.
:param classical_reg2: The second classical register or immediate value.
:return: A ClassicalOr instance.
"""
left, right = unpack_reg_... |
Produce an exclusive OR instruction. | def XOR(classical_reg1, classical_reg2):
"""
Produce an exclusive OR instruction.
:param classical_reg1: The first classical register, which gets modified.
:param classical_reg2: The second classical register or immediate value.
:return: A ClassicalOr instance.
"""
left, right = unpack_reg_... |
Produce a MOVE instruction. | def MOVE(classical_reg1, classical_reg2):
"""
Produce a MOVE instruction.
:param classical_reg1: The first classical register, which gets modified.
:param classical_reg2: The second classical register or immediate value.
:return: A ClassicalMove instance.
"""
left, right = unpack_reg_val_pa... |
Produce an EXCHANGE instruction. | def EXCHANGE(classical_reg1, classical_reg2):
"""
Produce an EXCHANGE instruction.
:param classical_reg1: The first classical register, which gets modified.
:param classical_reg2: The second classical register, which gets modified.
:return: A ClassicalExchange instance.
"""
left = unpack_cl... |
Produce a LOAD instruction. | def LOAD(target_reg, region_name, offset_reg):
"""
Produce a LOAD instruction.
:param target_reg: LOAD storage target.
:param region_name: Named region of memory to load from.
:param offset_reg: Offset into region of memory to load from. Must be a MemoryReference.
:return: A ClassicalLoad insta... |
Produce an ADD instruction. | def ADD(classical_reg, right):
"""
Produce an ADD instruction.
:param classical_reg: Left operand for the arithmetic operation. Also serves as the store target.
:param right: Right operand for the arithmetic operation.
:return: A ClassicalAdd instance.
"""
left, right = unpack_reg_val_pair(... |
Produce a SUB instruction. | def SUB(classical_reg, right):
"""
Produce a SUB instruction.
:param classical_reg: Left operand for the arithmetic operation. Also serves as the store target.
:param right: Right operand for the arithmetic operation.
:return: A ClassicalSub instance.
"""
left, right = unpack_reg_val_pair(c... |
Produce a MUL instruction. | def MUL(classical_reg, right):
"""
Produce a MUL instruction.
:param classical_reg: Left operand for the arithmetic operation. Also serves as the store target.
:param right: Right operand for the arithmetic operation.
:return: A ClassicalMul instance.
"""
left, right = unpack_reg_val_pair(c... |
Produce an DIV instruction. | def DIV(classical_reg, right):
"""
Produce an DIV instruction.
:param classical_reg: Left operand for the arithmetic operation. Also serves as the store target.
:param right: Right operand for the arithmetic operation.
:return: A ClassicalDiv instance.
"""
left, right = unpack_reg_val_pair(... |
Produce an EQ instruction. | def EQ(classical_reg1, classical_reg2, classical_reg3):
"""
Produce an EQ instruction.
:param classical_reg1: Memory address to which to store the comparison result.
:param classical_reg2: Left comparison operand.
:param classical_reg3: Right comparison operand.
:return: A ClassicalEqual instan... |
Produce an LT instruction. | def LT(classical_reg1, classical_reg2, classical_reg3):
"""
Produce an LT instruction.
:param classical_reg1: Memory address to which to store the comparison result.
:param classical_reg2: Left comparison operand.
:param classical_reg3: Right comparison operand.
:return: A ClassicalLessThan ins... |
Produce an LE instruction. | def LE(classical_reg1, classical_reg2, classical_reg3):
"""
Produce an LE instruction.
:param classical_reg1: Memory address to which to store the comparison result.
:param classical_reg2: Left comparison operand.
:param classical_reg3: Right comparison operand.
:return: A ClassicalLessEqual in... |
Produce an GT instruction. | def GT(classical_reg1, classical_reg2, classical_reg3):
"""
Produce an GT instruction.
:param classical_reg1: Memory address to which to store the comparison result.
:param classical_reg2: Left comparison operand.
:param classical_reg3: Right comparison operand.
:return: A ClassicalGreaterThan ... |
Produce an GE instruction. | def GE(classical_reg1, classical_reg2, classical_reg3):
"""
Produce an GE instruction.
:param classical_reg1: Memory address to which to store the comparison result.
:param classical_reg2: Left comparison operand.
:param classical_reg3: Right comparison operand.
:return: A ClassicalGreaterEqual... |
Evaluate an if statement within a @magicquil block. | def _if_statement(test, if_function, else_function) -> None:
"""
Evaluate an if statement within a @magicquil block.
If the test value is a Quil Addr then unwind it into quil code equivalent to an if then statement using jumps. Both
sides of the if statement need to be evaluated and placed into separat... |
Rewrite a function so that any if/ else branches are intercepted and their behavior can be overridden. This is accomplished using 3 steps: | def _rewrite_function(f):
"""
Rewrite a function so that any if/else branches are intercepted and their behavior can be overridden. This is
accomplished using 3 steps:
1. Get the source of the function and then rewrite the AST using _IfTransformer
2. Do some small fixups to the tree to make sure
... |
Decorator to enable a more convenient syntax for writing quil programs. With this decorator there is no need to keep track of a Program object and regular Python if/ else branches can be used for classical control flow. | def magicquil(f):
"""
Decorator to enable a more convenient syntax for writing quil programs. With this decorator there is no need to
keep track of a Program object and regular Python if/else branches can be used for classical control flow.
Example usage:
@magicquil
def fast_reset(q1):... |
Helper function to peruse through a program s qubits. | def _what_type_of_qubit_does_it_use(program):
"""Helper function to peruse through a program's qubits.
This function will also enforce the condition that a Program uses either all placeholders
or all instantiated qubits to avoid accidentally mixing the two. This function will warn
if your program doesn... |
Takes a program which contains qubit placeholders and provides a mapping to the integers 0 through N - 1. | def get_default_qubit_mapping(program):
"""
Takes a program which contains qubit placeholders and provides a mapping to the integers
0 through N-1.
The output of this function is suitable for input to :py:func:`address_qubits`.
:param program: A program containing qubit placeholders
:return: A... |
Takes a program which contains placeholders and assigns them all defined values. | def address_qubits(program, qubit_mapping=None):
"""
Takes a program which contains placeholders and assigns them all defined values.
Either all qubits must be defined or all undefined. If qubits are
undefined, you may provide a qubit mapping to specify how placeholders get mapped
to actual qubits.... |
Helper function to either get the appropriate label for a given placeholder or generate a new label and update the mapping. | def _get_label(placeholder, label_mapping, label_i):
"""Helper function to either get the appropriate label for a given placeholder or generate
a new label and update the mapping.
See :py:func:`instantiate_labels` for usage.
"""
if placeholder in label_mapping:
return label_mapping[placehol... |
Takes an iterable of instructions which may contain label placeholders and assigns them all defined values. | def instantiate_labels(instructions):
"""
Takes an iterable of instructions which may contain label placeholders and assigns
them all defined values.
:return: list of instructions with all label placeholders assigned to real labels.
"""
label_i = 1
result = []
label_mapping = dict()
... |
Implicitly declare a register named ro for backwards compatibility with Quil 1. | def implicitly_declare_ro(instructions: List[AbstractInstruction]):
"""
Implicitly declare a register named ``ro`` for backwards compatibility with Quil 1.
There used to be one un-named hunk of classical memory. Now there are variables with
declarations. Instead of::
MEASURE 0 [0]
You mus... |
Insert pauli noise channels between each item in the list of programs. This noise channel is implemented as a single noisy identity gate acting on the provided qubits. This method does not rely on merge_programs and so avoids the inclusion of redundant Kraus Pragmas that would occur if merge_programs was called directl... | def merge_with_pauli_noise(prog_list: Iterable, probabilities: List, qubits: List):
"""
Insert pauli noise channels between each item in the list of programs.
This noise channel is implemented as a single noisy identity gate acting on the provided qubits.
This method does not rely on merge_programs and ... |
Merges a list of pyQuil programs into a single one by appending them in sequence. If multiple programs in the list contain the same gate and/ or noisy gate definition with identical name this definition will only be applied once. If different definitions with the same name appear multiple times in the program list each... | def merge_programs(prog_list):
"""
Merges a list of pyQuil programs into a single one by appending them in sequence.
If multiple programs in the list contain the same gate and/or noisy gate definition
with identical name, this definition will only be applied once. If different definitions
with the s... |
Returns a sorted list of classical addresses found in the MEASURE instructions in the program. | def get_classical_addresses_from_program(program) -> Dict[str, List[int]]:
"""
Returns a sorted list of classical addresses found in the MEASURE instructions in the program.
:param Program program: The program from which to get the classical addresses.
:return: A mapping from memory region names to lis... |
Move all the DECLARE statements to the top of the program. Return a fresh obejct. | def percolate_declares(program: Program) -> Program:
"""
Move all the DECLARE statements to the top of the program. Return a fresh obejct.
:param program: Perhaps jumbled program.
:return: Program with DECLAREs all at the top and otherwise the same sorted contents.
"""
declare_program = Program... |
Ensure that a program is valid ProtoQuil otherwise raise a ValueError. Protoquil is a subset of Quil which excludes control flow and classical instructions. | def validate_protoquil(program: Program) -> None:
"""
Ensure that a program is valid ProtoQuil, otherwise raise a ValueError.
Protoquil is a subset of Quil which excludes control flow and classical instructions.
:param program: The Quil program to validate.
"""
valid_instruction_types = tuple([... |
Ensure that a program is supported Quil which can run on any QPU otherwise raise a ValueError. We support a global RESET before any gates and MEASUREs on each qubit after any gates on that qubit. PRAGMAs and DECLAREs are always allowed and a final HALT instruction is allowed. | def validate_supported_quil(program: Program) -> None:
"""
Ensure that a program is supported Quil which can run on any QPU, otherwise raise a ValueError.
We support a global RESET before any gates, and MEASUREs on each qubit after any gates
on that qubit. PRAGMAs and DECLAREs are always allowed, and a ... |
Copy all the members that live on a Program object. | def copy_everything_except_instructions(self):
"""
Copy all the members that live on a Program object.
:return: a new Program
"""
new_prog = Program()
new_prog._defined_gates = self._defined_gates.copy()
if self.native_quil_metadata is not None:
new_p... |
Perform a shallow copy of this program. | def copy(self):
"""
Perform a shallow copy of this program.
QuilAtom and AbstractInstruction objects should be treated as immutable to avoid
strange behavior when performing a copy.
:return: a new Program
"""
new_prog = self.copy_everything_except_instructions()... |
Mutates the Program object by appending new instructions. | def inst(self, *instructions):
"""
Mutates the Program object by appending new instructions.
This function accepts a number of different valid forms, e.g.
>>> p = Program()
>>> p.inst(H(0)) # A single instruction
>>> p.inst(H(0), H(1)) # Multiple instruction... |
Add a gate to the program. | def gate(self, name, params, qubits):
"""
Add a gate to the program.
.. note::
The matrix elements along each axis are ordered by bitstring. For two qubits the order
is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index,
i.e... |
Define a new static gate. | def defgate(self, name, matrix, parameters=None):
"""
Define a new static gate.
.. note::
The matrix elements along each axis are ordered by bitstring. For two qubits the order
is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index,
... |
Overload a static ideal gate with a noisy one defined in terms of a Kraus map. | def define_noisy_gate(self, name, qubit_indices, kraus_ops):
"""
Overload a static ideal gate with a noisy one defined in terms of a Kraus map.
.. note::
The matrix elements along each axis are ordered by bitstring. For two qubits the order
is ``00, 01, 10, 11``, where ... |
For this program define a classical bit flip readout error channel parametrized by p00 and p11. This models the effect of thermal noise that corrupts the readout signal ** after ** it has interrogated the qubit. | def define_noisy_readout(self, qubit, p00, p11):
"""
For this program define a classical bit flip readout error channel parametrized by
``p00`` and ``p11``. This models the effect of thermal noise that corrupts the readout
signal **after** it has interrogated the qubit.
:param i... |
Measures many qubits into their specified classical bits in the order they were entered. If no qubit/ register pairs are provided measure all qubits present in the program into classical addresses of the same index. | def measure_all(self, *qubit_reg_pairs):
"""
Measures many qubits into their specified classical bits, in the order
they were entered. If no qubit/register pairs are provided, measure all qubits present in
the program into classical addresses of the same index.
:param Tuple qubi... |
While a classical register at index classical_reg is 1 loop q_program | def while_do(self, classical_reg, q_program):
"""
While a classical register at index classical_reg is 1, loop q_program
Equivalent to the following construction:
.. code::
WHILE [c]:
instr...
=>
LABEL @START
JUMP-UNLE... |
If the classical register at index classical reg is 1 run if_program else run else_program. | def if_then(self, classical_reg, if_program, else_program=None):
"""
If the classical register at index classical reg is 1, run if_program, else run
else_program.
Equivalent to the following construction:
.. code::
IF [c]:
instrA...
ELSE:... |
DECLARE a quil variable | def declare(self, name, memory_type='BIT', memory_size=1, shared_region=None, offsets=None):
"""DECLARE a quil variable
This adds the declaration to the current program and returns a MemoryReference to the
base (offset = 0) of the declared memory.
.. note::
This function re... |
Converts the Quil program to a readable string. | def _out(self, allow_placeholders):
"""
Converts the Quil program to a readable string.
:param allow_placeholders: Whether to complain if the program contains placeholders.
"""
return '\n'.join(itertools.chain(
(dg.out() for dg in self._defined_gates),
(i... |
Returns all of the qubit indices used in this program including gate applications and allocated qubits. e. g. | def get_qubits(self, indices=True):
"""
Returns all of the qubit indices used in this program, including gate applications and
allocated qubits. e.g.
>>> p = Program()
>>> p.inst(("H", 1))
>>> p.get_qubits()
{1}
>>> q = p.alloc()
... |
Creates the conjugate transpose of the Quil program. The program must not contain any irreversible actions ( measurement control flow qubit allocation ). | def dagger(self, inv_dict=None, suffix="-INV"):
"""
Creates the conjugate transpose of the Quil program. The program must not
contain any irreversible actions (measurement, control flow, qubit allocation).
:return: The Quil program's inverse
:rtype: Program
"""
... |
Assigns all placeholder labels to actual values and implicitly declares the ro register for backwards compatibility. | def _synthesize(self):
"""
Assigns all placeholder labels to actual values and implicitly declares the ``ro``
register for backwards compatibility.
Changed in 1.9: Either all qubits must be defined or all undefined. If qubits are
undefined, this method will not help you. You mus... |
A decorator that sets up an error context captures errors and tears down the context. | def pyquil_protect(func, log_filename="pyquil_error.log"):
"""
A decorator that sets up an error context, captures errors, and tears down the context.
"""
def pyquil_protect_wrapper(*args, **kwargs):
global global_error_context
old_error_context = global_error_context
global_er... |
A decorator that logs a call into the global error context. | def _record_call(func):
"""
A decorator that logs a call into the global error context.
This is probably for internal use only.
"""
@wraps(func)
def wrapper(*args, **kwargs):
global global_error_context
# log a call as about to take place
if global_error_context is not... |
Handle an error generated in a routine decorated with the pyQuil error handler. | def generate_report(self, exception, trace):
"""
Handle an error generated in a routine decorated with the pyQuil error handler.
:param exception: Exception object that generated this error.
:param trace: inspect.trace object from the frame that caught the error.
:return: ErrorR... |
Implements | def ucc_circuit(theta):
"""
Implements
exp(-i theta X_{0}Y_{1})
:param theta: rotation parameter
:return: pyquil.Program
"""
generator = sX(0) * sY(1)
initial_prog = Program().inst(X(1), X(0))
# compiled program
program = initial_prog + exponentiate(float(theta) * generator) ... |
Evaluate the Hamiltonian bny operator averaging | def objective_fun(theta, hamiltonian=None,
quantum_resource=QVMConnection(sync_endpoint='http://localhost:5000')):
"""
Evaluate the Hamiltonian bny operator averaging
:param theta:
:param hamiltonian:
:return:
"""
if hamiltonian is None:
# Hamiltonian is Identity
... |
Check that this program is a series of quantum gates with terminal MEASURE instructions ; pop MEASURE instructions. | def _make_ram_program(program):
"""
Check that this program is a series of quantum gates with terminal MEASURE instructions; pop
MEASURE instructions.
:param program: The program
:return: A new program with MEASURE instructions removed.
"""
new_prog = program.copy_everything_except_instruct... |
Perform a sequence of gates contained within a program. | def do_program(self, program: Program) -> 'AbstractQuantumSimulator':
"""
Perform a sequence of gates contained within a program.
:param program: The program
:return: self
"""
for gate in program:
if not isinstance(gate, Gate):
raise ValueErro... |
Helper function that iterates over the program and looks for a JumpTarget that has a Label matching the input label. | def find_label(self, label: Label):
"""
Helper function that iterates over the program and looks for a JumpTarget that has a
Label matching the input label.
:param label: Label object to search for in program
:return: Program index where ``label`` is found
"""
fo... |
Implements a QAM - like transition. | def transition(self):
"""
Implements a QAM-like transition.
This function assumes ``program`` and ``program_counter`` instance variables are set
appropriately, and that the wavefunction simulator and classical memory ``ram`` instance
variables are in the desired QAM input state.... |
Execute a program on the QVM. | def execute(self, program: Program):
"""
Execute a program on the QVM.
Note that the QAM is stateful. Subsequent calls to :py:func:`execute` will not
automatically reset the wavefunction or the classical RAM. If this is desired,
consider starting your program with ``RESET``.
... |
Retrieve an instance of the appropriate AbstractBenchmarker subclass for a given endpoint. | def get_benchmarker(endpoint: str = None, timeout: float = 10):
"""
Retrieve an instance of the appropriate AbstractBenchmarker subclass for a given endpoint.
:param endpoint: Benchmarking sequence server address. Defaults to the setting in the user's
pyQuil config.
:param timeout:... |
r Given a circuit that consists only of elements of the Clifford group return its action on a PauliTerm. | def apply_clifford_to_pauli(self, clifford, pauli_in):
r"""
Given a circuit that consists only of elements of the Clifford group,
return its action on a PauliTerm.
In particular, for Clifford C, and Pauli P, this returns the PauliTerm
representing CPC^{\dagger}.
:param ... |
Construct a randomized benchmarking experiment on the given qubits decomposing into gateset. If interleaver is not provided the returned sequence will have the form | def generate_rb_sequence(self, depth, gateset, seed=None, interleaver=None):
"""
Construct a randomized benchmarking experiment on the given qubits, decomposing into
gateset. If interleaver is not provided, the returned sequence will have the form
C_1 C_2 ... C_(depth-1) C_inv ,
... |
Get a qubit from an object. | def unpack_qubit(qubit):
"""
Get a qubit from an object.
:param qubit: An int or Qubit.
:return: A Qubit instance
"""
if isinstance(qubit, integer_types):
return Qubit(qubit)
elif isinstance(qubit, Qubit):
return qubit
elif isinstance(qubit, QubitPlaceholder):
re... |
Get the address for a classical register. | def unpack_classical_reg(c):
"""
Get the address for a classical register.
:param c: A list of length 2, a pair, a string (to be interpreted as name[0]), or a MemoryReference.
:return: The address as a MemoryReference.
"""
if isinstance(c, list) or isinstance(c, tuple):
if len(c) > 2 or... |
Formats a particular parameter. Essentially the same as built - in formatting except using i instead of j for the imaginary number. | def format_parameter(element):
"""
Formats a particular parameter. Essentially the same as built-in formatting except using 'i' instead of 'j' for
the imaginary number.
:param element: {int, float, long, complex, Parameter} Formats a parameter for Quil output.
"""
if isinstance(element, integer... |
Apply substitute to all elements of an array a and return the resulting array. | def substitute_array(a, d):
"""
Apply ``substitute`` to all elements of an array ``a`` and return the resulting array.
:param Union[np.array,List] a: The expression array to substitute.
:param Dict[Parameter,Union[int,float]] d: Numerical substitutions for parameters.
:return: An array of partially... |
Recursively converts an expression to a string taking into account precedence and associativity for placing parenthesis | def _expression_to_string(expression):
"""
Recursively converts an expression to a string taking into account precedence and associativity for placing
parenthesis
:param Expression expression: expression involving parameters
:return: string such as '%x*(%y-4)'
:rtype: str
"""
if isinsta... |
Determine which parameters are contained in this expression. | def _contained_parameters(expression):
"""
Determine which parameters are contained in this expression.
:param Expression expression: expression involving parameters
:return: set of parameters contained in this expression
:rtype: set
"""
if isinstance(expression, BinaryExp):
return ... |
Check to see if there exists a rational number r = p/ q in reduced form for which the difference between element/ np. pi and r is small and q < = 8. | def _check_for_pi(element):
"""
Check to see if there exists a rational number r = p/q
in reduced form for which the difference between element/np.pi
and r is small and q <= 8.
:param element: float
:return element: pretty print string if true, else standard representation.
"""
frac = F... |
Add generic damping and dephasing noise to a program. | def add_noise_to_program(prog, T1=30e-6, T2=30e-6, gate_time_1q=50e-9, gate_time_2q=150e-09,
ro_fidelity=0.95):
"""
Add generic damping and dephasing noise to a program.
.. warning::
This function is deprecated. Please use :py:func:`add_decoherence_noise` instead.
:pa... |
All bitstrings in lexicographical order as a 2d np. ndarray. | def all_bitstrings(n_bits):
"""All bitstrings in lexicographical order as a 2d np.ndarray.
This should be the same as ``np.array(list(itertools.product([0,1], repeat=n_bits)))``
but faster.
"""
n_bitstrings = 2 ** n_bits
out = np.zeros(shape=(n_bitstrings, n_bits), dtype=np.int8)
tf = np.a... |
Lifts input k - qubit gate on adjacent qubits starting from qubit i to complete Hilbert space of dimension 2 ** num_qubits. | def qubit_adjacent_lifted_gate(i, matrix, n_qubits):
"""
Lifts input k-qubit gate on adjacent qubits starting from qubit i
to complete Hilbert space of dimension 2 ** num_qubits.
Ex: 1-qubit gate, lifts from qubit i
Ex: 2-qubit gate, lifts from qubits (i+1, i)
Ex: 3-qubit gate, lifts from qubit... |
Generate the permutation matrix that permutes two single - particle Hilbert spaces into adjacent positions. | def two_swap_helper(j, k, num_qubits, qubit_map):
"""
Generate the permutation matrix that permutes two single-particle Hilbert
spaces into adjacent positions.
ALWAYS swaps j TO k. Recall that Hilbert spaces are ordered in decreasing
qubit index order. Hence, j > k implies that j is to the left of ... |
Generate the permutation matrix that permutes an arbitrary number of single - particle Hilbert spaces into adjacent positions. | def permutation_arbitrary(qubit_inds, n_qubits):
"""
Generate the permutation matrix that permutes an arbitrary number of
single-particle Hilbert spaces into adjacent positions.
Transposes the qubit indices in the order they are passed to a
contiguous region in the complete Hilbert space, in increa... |
Lift a unitary matrix to act on the specified qubits in a full n_qubits - qubit Hilbert space. | def lifted_gate_matrix(matrix: np.ndarray, qubit_inds: List[int], n_qubits: int):
"""
Lift a unitary matrix to act on the specified qubits in a full ``n_qubits``-qubit
Hilbert space.
For 1-qubit gates, this is easy and can be achieved with appropriate kronning of identity
matrices. For 2-qubit gate... |
Lift a pyquil: py: class: Gate in a full n_qubits - qubit Hilbert space. | def lifted_gate(gate: Gate, n_qubits: int):
"""
Lift a pyquil :py:class:`Gate` in a full ``n_qubits``-qubit Hilbert space.
This function looks up the matrix form of the gate and then dispatches to
:py:func:`lifted_gate_matrix` with the target qubits.
:param gate: A gate
:param n_qubits: The to... |
Return the unitary of a pyQuil program. | def program_unitary(program, n_qubits):
"""
Return the unitary of a pyQuil program.
:param program: A program consisting only of :py:class:`Gate`.:
:return: a unitary corresponding to the composition of the program's gates.
"""
umat = np.eye(2 ** n_qubits)
for instruction in program:
... |
Takes a PauliSum object along with a list of qubits and returns a matrix corresponding the tensor representation of the object. | def lifted_pauli(pauli_sum: Union[PauliSum, PauliTerm], qubits: List[int]):
"""
Takes a PauliSum object along with a list of
qubits and returns a matrix corresponding the tensor representation of the
object.
Useful for generating the full Hamiltonian after a particular fermion to
pauli transfor... |
Takes a PauliSum object along with a list of qubits and returns a matrix corresponding the tensor representation of the object. | def tensor_up(pauli_sum: Union[PauliSum, PauliTerm], qubits: List[int]):
"""
Takes a PauliSum object along with a list of
qubits and returns a matrix corresponding the tensor representation of the
object.
This is the same as :py:func:`lifted_pauli`. Nick R originally wrote this functionality
an... |
Take a TensorProductState along with a list of qubits and return a matrix corresponding to the tensored - up representation of the states density operator form. | def lifted_state_operator(state: TensorProductState, qubits: List[int]):
"""Take a TensorProductState along with a list of qubits and return a matrix
corresponding to the tensored-up representation of the states' density operator form.
Developer note: Quil and the QVM like qubits to be ordered such that qu... |
Create an abbreviated string representation of a Program. | def _abbrev_program(program: Program, max_len=10):
"""Create an abbreviated string representation of a Program.
This will join all instructions onto a single line joined by '; '. If the number of
instructions exceeds ``max_len``, some will be excluded from the string representation.
"""
program_lin... |
Convenience method to save pyquil. operator_estimation objects as a JSON file. | def to_json(fn, obj):
"""Convenience method to save pyquil.operator_estimation objects as a JSON file.
See :py:func:`read_json`.
"""
with open(fn, 'w') as f:
json.dump(obj, f, cls=OperatorEncoder, indent=2, ensure_ascii=False)
return fn |
Convenience method to read pyquil. operator_estimation objects from a JSON file. | def read_json(fn):
"""Convenience method to read pyquil.operator_estimation objects from a JSON file.
See :py:func:`to_json`.
"""
with open(fn) as f:
return json.load(f, object_hook=_operator_object_hook) |
Prepare the index - th SIC basis state. | def _one_q_sic_prep(index, qubit):
"""Prepare the index-th SIC basis state."""
if index == 0:
return Program()
theta = 2 * np.arccos(1 / np.sqrt(3))
zx_plane_rotation = Program([
RX(-pi / 2, qubit),
RZ(theta - pi, qubit),
RX(-pi / 2, qubit),
])
if index == 1:
... |
Prepare the index - th eigenstate of the pauli operator given by label. | def _one_q_pauli_prep(label, index, qubit):
"""Prepare the index-th eigenstate of the pauli operator given by label."""
if index not in [0, 1]:
raise ValueError(f'Bad Pauli index: {index}')
if label == 'X':
if index == 0:
return Program(RY(pi / 2, qubit))
else:
... |
Prepare a one qubit state. | def _one_q_state_prep(oneq_state: _OneQState):
"""Prepare a one qubit state.
Either SIC[0-3], X[0-1], Y[0-1], or Z[0-1].
"""
label = oneq_state.label
if label == 'SIC':
return _one_q_sic_prep(oneq_state.index, oneq_state.qubit)
elif label in ['X', 'Y', 'Z']:
return _one_q_pauli_... |
Generate gate sequence to measure in the eigenbasis of a Pauli operator assuming we are only able to measure in the Z eigenbasis. ( Note: The unitary operations of this Program are essentially the Hermitian conjugates of those in: py: func: _one_q_pauli_prep ) | def _local_pauli_eig_meas(op, idx):
"""
Generate gate sequence to measure in the eigenbasis of a Pauli operator, assuming
we are only able to measure in the Z eigenbasis. (Note: The unitary operations of this
Program are essentially the Hermitian conjugates of those in :py:func:`_one_q_pauli_prep`)
... |
Construct a graph where an edge signifies two experiments are diagonal in a TPB. | def construct_tpb_graph(experiments: TomographyExperiment):
"""
Construct a graph where an edge signifies two experiments are diagonal in a TPB.
"""
g = nx.Graph()
for expt in experiments:
assert len(expt) == 1, 'already grouped?'
expt = expt[0]
if expt not in g:
... |
Group experiments that are diagonal in a shared tensor product basis ( TPB ) to minimize number of QPU runs using a graph clique removal algorithm. | def group_experiments_clique_removal(experiments: TomographyExperiment) -> TomographyExperiment:
"""
Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number
of QPU runs, using a graph clique removal algorithm.
:param experiments: a tomography experiment
:return... |
Construct a PauliTerm operator by taking the non - identity single - qubit operator at each qubit position. | def _max_weight_operator(ops: Iterable[PauliTerm]) -> Union[None, PauliTerm]:
"""Construct a PauliTerm operator by taking the non-identity single-qubit operator at each
qubit position.
This function will return ``None`` if the input operators do not share a natural tensor
product basis.
For exampl... |
Construct a TensorProductState by taking the single - qubit state at each qubit position. | def _max_weight_state(states: Iterable[TensorProductState]) -> Union[None, TensorProductState]:
"""Construct a TensorProductState by taking the single-qubit state at each
qubit position.
This function will return ``None`` if the input states are not compatible
For example, the max_weight_state of ["(+... |
Given an input TomographyExperiment provide a dictionary indicating which ExperimentSettings share a tensor product basis | def _max_tpb_overlap(tomo_expt: TomographyExperiment):
"""
Given an input TomographyExperiment, provide a dictionary indicating which ExperimentSettings
share a tensor product basis
:param tomo_expt: TomographyExperiment, from which to group ExperimentSettings that share a tpb
and can be run to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.