quil.program
The quil.program module contains classes for constructing and representing a Quil program.
Examples
Source Mapping for Calibration Expansion
import inspect
from quil.program import Program
program_text = inspect.cleandoc(
"""
DEFCAL X 0:
Y 0
DEFCAL Y 0:
Z 0
X 0 # This instruction is index 0
Y 0 # This instruction is index 1
"""
)
# First, we parse the program and expand its calibrations
program = Program.parse(program_text)
expansion = program.expand_calibrations_with_source_map()
source_map = expansion.source_map()
# This is what we expect the expanded program to be. X and Y have each been replaced by Z.
expected_program_text = inspect.cleandoc(
"""
DEFCAL X 0:
Y 0
DEFCAL Y 0:
Z 0
Z 0 # This instruction is index 0
Z 0 # This instruction is index 1
"""
)
assert expansion.program().to_quil() == Program.parse(expected_program_text).to_quil()
# In order to discover _which_ calibration led to the first Z in the resulting program, we
# can interrogate the expansion source mapping.
#
# For instance, the X at index 0 should have been replaced with a Z at index 0.
# Here's how we can confirm that:
# First, we list the calibration expansion targets for that first instruction...
targets = source_map.list_targets_for_source_index(0)
# ...then we extract the expanded instruction.
# If the instruction had _not_ been expanded (i.e. there was no matching calibration), then `as_expanded()` would return `None`.
expanded = targets[0].as_expanded()
# This line shows how that `X 0` was expanded into instruction index 0 (only) within the expanded program.
# The end of the range is exclusive.
assert expanded.range() == range(0, 1)
# We can also map instructions in reverse: given an instruction index in the expanded program, we can find the source index.
# This is useful for understanding the provenance of instructions in the expanded program.
sources = source_map.list_sources_for_target_index(1)
# In this case, the instruction was expanded from the source program at index 1.
assert sources == [1]
Errors encountered related to a Program.
Error raised if the computed schedule is invalid.
Return the length of the longest path from an initial instruction (one with no prerequisite instructions) to a final instruction (one with no dependent instructions), where the length of a path is the number of gate instructions in the path.
Parameters
- gate_minimum_qubit_count: The minimum number of qubits in a gate for it to be counted in the depth.
Details about the expansion of a calibration.
The source of a calibration, either a [CalibrationIdentifier] or a
[MeasureCalibrationIdentifier].
Inherited Members
Inherited Members
A collection of Quil calibrations (DEFCAL instructions) with utility methods.
This exposes the semantics similar to [CalibrationSet] to Python users,
so see the documentation there for more information.
Given an instruction, return the instructions to which it is expanded if there is a match. Recursively calibrate instructions, returning an error if a calibration directly or indirectly expands into itself.
Return only the expanded instructions; for more information about the expansion process,
see [Self::expand_with_detail].
Returns the last-specified MeasureCalibrationDefinition that matches the target
qubit (if any), or otherwise the last-specified one that specified no qubit.
If multiple calibrations match the measurement, the precedence is as follows:
- Match fixed qubit.
- Match variable qubit.
- Match no qubit.
In the case of multiple calibrations with equal precedence, the last one wins.
Return the final calibration which matches the gate per the QuilT specification:
A calibration matches a gate if:
- It has the same name
- It has the same modifiers
- It has the same qubit count (any mix of fixed & variable)
- It has the same parameter count (both specified and unspecified)
- All fixed qubits in the calibration definition match those in the gate
- All specified parameters in the calibration definition match those in the gate
Insert a [CalibrationDefinition] into the set.
If a calibration with the same [signature][crate::instruction::CalibrationSignature] already exists in the set, it will be replaced and the old calibration will be returned.
Insert a [MeasureCalibrationDefinition] into the set.
If a calibration with the same [signature][crate::instruction::CalibrationSignature] already exists in the set, it will be replaced and the old calibration will be returned.
Append another [CalibrationSet] onto this one.
Calibrations with conflicting [CalibrationSignature]s are overwritten by the ones in the
given set.
Return True if the program has dynamic control flow, i.e. contains a conditional branch instruction.
False does not imply that there is only one basic block in the program.
Multiple basic blocks may have non-conditional control flow among them,
in which the execution order is deterministic and does not depend on program state.
This may be a sequence of basic blocks with fixed JUMPs or without explicit terminators.
The result of having expanded a certain instruction within a program.
calibration: The instruction has a matching Quil-T calibration and was expanded by it into other instructions, as described by aCalibrationExpansion.defgate_sequence: The instruction has a matchingDEFGATE ... AS SEQUENCEand was expanded by it into other instructions, as described by aDefGateSequenceExpansion.unmodified: The instruction was not expanded and is described by an integer, the index of the instruction within the resulting program's body instructions.
Inherited Members
Inherited Members
Inherited Members
A collection of Quil frames (DEFFRAME instructions) with utility methods.
Return a new FrameSet which describes only the given FrameIdentifiers.
A source map describing how instructions in a source program were expanded into a target program. Each entry describes an instruction index in the source program which were expanded accordingto either a calibration or a sequence gate definition.
Return all source ranges in the source map which were used to generate the target index.
This is O(n) where n is the number of first-level expansions performed,
which is at worst O(i) where i is the number of source instructions.
Given a particular calibration (DEFCAL or DEFCAL MEASURE), =
return the locations in the source which were expanded using that calibration.
This is O(n) where n is the number of first-level calibration expansions performed,
which is at worst O(i) where i is the number of source instructions.
Given a gate signature, return the locations in the source program which were expanded using that gate signature.
This is O(n) where n is the number of first-level sequence gate expansions performed,
which is at worst O(i) where i is the number of source instructions.
A source map entry, mapping a range of source instructions by index to an
InstructionTarget.
Note that both source_location and target_location are relative to the scope of expansion.
In the case of a nested expansion, both describe the location relative only to that
level of expansion and not the original program.
[DefGateSequenceExpansion] references data from [quil_rs::instruction::GateDefinition]s used to expand instructions.
As such, it is incompatible with Python's memory management,
so we define an owned type here.
A Quil Program instance describes a quantum program with metadata used in execution.
This contains not only instructions which are executed in turn on the quantum processor, but also the "headers" used to describe and manipulate those instructions, such as calibrations and frame definitions.
Parse a Program from a string.
Errors
Raises a ProgramError if the string isn't a valid Quil expression.
Expand any instructions in the program which have a matching calibration, leaving the others unchanged. Return the expanded copy of the program and a source mapping describing the expansions made.
Expand any instructions in the program which have a matching sequence gate definition, leaving the others unchanged. Note, the new program will drop any gate definitions which are no longer referenced in the program.
Recurses though each instruction while ensuring there is no cycle in the expansion graph (i.e. no sequence gate definitions expand directly or indirectly into itself).
Parameters
- predicate: If provided, only sequence gate definitions which match the predicate will be expanded. Defaults to expanding all sequence gate definitions.
Return the expanded copy of the program and a source mapping describing the expansions made.
Example
Expand any instructions in the program which have a matching sequence gate definition, leaving the others unchanged.
Recurses though each instruction while ensuring there is no cycle in the expansion graph (i.e. no sequence gate definitions expand directly or indirectly into itself).
Parameters
- predicate: If provided, only sequence gate definitions which match the predicate will be expanded. Defaults to expanding all sequence gate definitions.
Example
Below, we show the results of gate sequence expansion on a program that has two gate
sequence definitions. The first, seq1, has a matching calibration and we do not
want to expand it. The second, seq2, does not have a matching calibration and
we do want to expand it.
>>> quil = '''
... DEFCAL seq1 0 1:
... FENCE 0 1
... NONBLOCKING PULSE 0 "rf" drag_gaussian(duration: 6.000000000000001e-08, fwhm: 1.5000000000000002e-08, t0: 3.0000000000000004e-08, anh: -190000000.0, alpha: -1.6453719598238201, scale: 0.168265925924524, phase: 0.0, detuning: 0)
... NONBLOCKING PULSE 1 "rf" drag_gaussian(duration: 6.000000000000001e-08, fwhm: 1.5000000000000002e-08, t0: 3.0000000000000004e-08, anh: -190000000.0, alpha: -1.6453719598238201, scale: 0.168265925924524, phase: 0.0, detuning: 0)
... FENCE 0 1
...
... DEFGATE seq1() a b AS SEQUENCE:
... RX(pi/2) a
... RX(pi/2) b
...
... DEFGATE seq2(%theta, %psi, %phi) a AS SEQUENCE:
... RZ(%theta) a
... RX(pi/2) a
... RZ(%phi) a
...
... seq1 0 1
... seq2(1.5707963267948966, 3.141592653589793, 0) 0
... seq2(3.141592653589793, 0, 1.5707963267948966) 1
... '''
>>> program = Program.parse(quil);
>>> calibrated_gate_names = {calibration.identifier.name for calibration in program.calibrations.calibrations}
>>> expanded_program = program.expand_defgate_sequences(lambda name: name not in calibrated_gate_names)
>>>
>>> expected_quil = '''
... DEFCAL seq1 0 1:
... FENCE 0 1
... NONBLOCKING PULSE 0 "rf" drag_gaussian(duration: 6.000000000000001e-08, fwhm: 1.5000000000000002e-08, t0: 3.0000000000000004e-08, anh: -190000000.0, alpha: -1.6453719598238201, scale: 0.168265925924524, phase: 0.0, detuning: 0)
... NONBLOCKING PULSE 1 "rf" drag_gaussian(duration: 6.000000000000001e-08, fwhm: 1.5000000000000002e-08, t0: 3.0000000000000004e-08, anh: -190000000.0, alpha: -1.6453719598238201, scale: 0.168265925924524, phase: 0.0, detuning: 0)
... FENCE 0 1
...
... DEFGATE seq1 a b AS SEQUENCE:
... RX(pi/2) a
... RX(pi/2) b
...
... seq1 0 1
...
... RZ(1.5707963267948966) 0
... RX(pi/2) 0
... RZ(3.141592653589793) 0
... RX(pi/2) 0
... RZ(0) 0
...
... RZ(3.141592653589793) 1
... RX(pi/2) 1
... RZ(0) 1
... RX(pi/2) 1
... RZ(1.5707963267948966) 1
... '''
>>>
>>> expected_program = Program.parse(expected_quil)
>>>
>>> assert expanded_program == expected_program
Return a new Program containing only the instructions
for which predicate returns true.
Resolve TargetPlaceholders and QubitPlaceholders within the program.
The resolved values will remain unique to that placeholder
within the scope of the program.
If you provide target_resolver and/or qubit_resolver,
those will be used to resolve those values respectively.
If your resolver returns None for a particular placeholder,
it will not be replaced but will be left as a placeholder.
If you do not provide a resolver for a placeholder,
a default resolver will be used which will generate
a unique value for that placeholder within the scope of the program
using an auto-incrementing value (for qubit) or suffix (for target)
while ensuring that unique value is not already in use within the program.
Return the unitary of a program.
Errors
Returns an error if the program contains instructions other than Gates.
Add an instruction to the end of the program.
Note, parsing extern signatures is deferred here to maintain infallibility
of [Program::add_instruction]. This means that invalid PRAGMA EXTERN
instructions are still added to the [Program::extern_pragma_map];
duplicate PRAGMA EXTERN names are overwritten.
Creates a new conjugate transpose of the [Program] by reversing the order of gate
instructions and applying the DAGGER modifier to each.
Errors
Errors if any of the instructions in the program are not [Instruction::Gate]
Expand any instructions in the program which have a matching calibration, leaving the others unchanged. Return the expanded copy of the program.
Returns an error if any instruction expands into itself.
See [Program::expand_calibrations_with_source_map] for a version that returns a source mapping.
Simplify this program into a new [Program] which contains only instructions
and definitions which are executed; effectively, perform dead code removal.
Removes:
- All calibrations, following calibration expansion
- Frame definitions which are not used by any instruction such as
PULSEorCAPTURE - Waveform definitions which are not used by any instruction
PRAGMA EXTERNinstructions which are not used by anyCALLinstruction (see [Program::extern_pragma_map]).
When a valid program is simplified, it remains valid.
Note
If you need custom instruction handling during simplification,
use [InstructionHandler::simplify_program] instead.
Return a copy of the [Program] wrapped in a loop that repeats iterations times.
The loop is constructed by wrapping the body of the program in classical Quil instructions.
The given loop_count_reference must refer to an INTEGER memory region. The value at the
reference given will be set to iterations and decremented in the loop. The loop will
terminate when the reference reaches 0. For this reason your program should not itself
modify the value at the reference unless you intend to modify the remaining number of
iterations (i.e. to break the loop).
The given start_target and end_target will be used as the entry and exit points for the
loop, respectively. You should provide unique [Target]s that won't be used elsewhere in
the program.
If iterations is 0, then a copy of the program is returned without any changes.
Resolve [LabelPlaceholder]s and [QubitPlaceholder]s within the program using default resolvers.
See resolve_placeholders_with_custom_resolvers,
default_target_resolver,
and default_qubit_resolver for more information.
Return a copy of all of the instructions which constitute this [Program].
A Schedule is a DependencyGraph flattened into a linear sequence of instructions,
each of which is assigned a start time and duration.
A single item within a schedule, representing a single instruction within a basic block.
A time span, in seconds.