Compilation¶
Parent class for all |
|
Parent class for compiler passes which operates on groups of cycles with matching markers. |
|
Parent class for compiler passes which accept a fixed number of cycles at a time. |
|
Parent class used by |
|
An exception inside of the True-Q™ compiler. |
|
Pass which adds randomly chosen Pauli gates before all measurements in the circuit. |
|
Iterates through a |
|
Pass that searches |
|
A pass which ensures that any |
|
Pass that takes two Cycles, and moves gates preferentially to one side. |
|
Pass that marks cycles which contain multi-qubit gates if none of the existing cycles in the circuit have been marked with non-zero values. |
|
Pass that takes two cycles, finds compatabile labels and gates, then merges them to a single gate as much as is possible. |
|
A |
|
An |
|
An |
|
An |
|
A |
|
An |
|
An |
|
An |
|
Checks to see if each gate is present in the provided list of |
|
A |
|
This pass tracks phase accumulation on each qubit throughout a circuit, and compiles this phase information into parametric gates. |
|
Pass which performs Randomized Compilation on groups of cycles with matching marker values by adding gates on either side of the cycles, chosen using the provided |
|
Pass which relabels all the labels and keys in a |
|
Pass which accepts one cycle and returns the cycle if it contains any operations. |
|
Pass that removes single qubit identity gates from |
|
An |
|
Compiles an arbitrary |
CompilationError¶
-
class
trueq.compilation.
CompilationError
¶ An exception inside of the True-Q™ compiler.
Compiler¶
-
class
trueq.compilation.
Compiler
(passes)¶ Substitutes cycles in a
Circuit
using a series ofPass
es.In classical computing this would formally be called a Peephole Optimizer.
An instance of this class stores a list of
Pass
objects which define rules for how to decompose, replace, or removeGate
s (or more generally,Operation
s), while possibly also adding or removing cycles.A simple example is the
RemoveId
pass, which accepts 1 cycle at a time, and removes any identity gates from the cycle, before returning it.In general building a compiler which knows all possible simplification rules would result in an overly complex and rigid tool, and would be difficult to generalize for all hardware implementations. By making the compiler itself very small, and allowing custom rules (passes in this case), very complex compilation instructions can be expressed in a simple and readable fashion.
Each
Pass
object iterates through a circuit in its own way; in the example above, the circuit is iterated over 1 cycle at a time. In general, passes operate on collections of cycles at a time, up to the entire circuit at once. There are two pre-builtPass
child classes which define common methods for iterating over a circuit:NCyclePass
Iterates over a fixed
N
cycles at a time, the majority of default passes are subclassed off of this.
MarkerPass
Iterates over groups of cycles with matching markers.
An example of iteration is merging multiple single qubit gates into a single operation (which is done by the
Merge
pass). This requires multiple cycles to be operated on at any given time, in this case this operation can be performed with a fixed number (2) of cycles at a time. The pass looks for single qubit gates in both of the cycles, and computes the single equivalentGate
, which is put back instead of the two original gates.Here is an example of a set of passes which converts a circuit of
Gate
s into a circuit ofNativeGate
s as defined in aConfig
:from trueq.compilation import * import trueq as tq factories = tq.Config.basic().factories.values() Compiler( [ Justify(), Native2Q(factories=factories), Merge(), RemoveId(), Native1Q(factories=factories), Justify(), ] )
Compiler([Justify, Native2Q, Merge, RemoveId, Native1Q, Justify])
This set of passes performs these operations:
Justify
Move gates preferentially to one side of the circuit. For example, if a circuit contains an
X90
gate at the beginning and 10 empty cycles,Justify
would move theX90
gate to the end of the circuit.Native2Q
Convert all two qubit operations found in the circuit into
NativeGate
s which can be run on hardware as specified by the config object. This pass does NOT decompose the single qubit gates, so in the process it adds single qubit gate objects to some cycles.Merge
This simplifies any neighboring single qubit operations and reduces them to a single gate. Changing the default settings can enable it to merge multi-qubit gates together as well.
RemoveId
Since the merge step may have introduced single qubit gates which could be identity gates, this pass removes all identity gates.
Native1Q
This converts all one-qubit operations into
NativeGate
s which can be run on hardware as specified by the config object.Justify
To leave everything in the ground state for as long as possible, this pass ensures everything is moved as far forward in the circuit as possible.
- Parameters
passes (
list
) – A list ofPass
es, see above.
-
compile
(circ)¶ Sequentially applies all of the passes in the compiler to a given
Circuit
orCircuitCollection
, a newCircuit
orCircuitCollection
instance is returned.- Parameters
circ (
Circuit
|CircuitCollection
) – A circuit that the pass list should be applied to.- Return type
-
static
from_config
(config, passes=None)¶ Get a
Compiler
which can transpile from arbitrary True-Q™ representation of circuits, into a representation which is compatable with a given config.By default, this performs a standard set of passes, and can be used as a template for more advanced compiler definitions. See
trueq.compilation.Compiler.DEFAULT_PASSES
for a list of the default passes which are applied.- Parameters
config (
trueq.Config
) – Atrueq.Config
which has 2-qubit gates defined.passes (
tuple
|None
) – A tuple oftrueq.compilation.base.Pass
to be applied in order. These must be uninstantiated classes which must acceptfactories
as a keyword argument, seetrueq.compilation.Compiler.DEFAULT_PASSES
for an example. IfNone
is provided, then the default list is used.
-
static
basic
(entangler=Gate.cx, mode='ZXZXZ', passes=None)¶ Get a
Compiler
which is built from a standardConfig
.By default, this performs a standard set of passes, and a config as defined by
trueq.Config.basic()
. Seetrueq.compilation.Compiler.DEFAULT_PASSES
for a list of the default passes which are applied.- Parameters
entangler (
trueq.Gate
) – A two-qubit gate.mode (
str
) – The single qubit decomposition mode, defaults to'ZXZXZ'
, seetrueq.math.decomposition.QubitMode
for more details.passes (
tuple
|None
) – A tuple oftrueq.compilation.base.Pass
to be applied in order. These must be uninstantiated classes which must acceptfactories
as a keyword argument, seetrueq.compilation.Compiler.DEFAULT_PASSES
for an example. IfNone
is provided, then the default list is used.
-
DEFAULT_PASSES
= (<class 'trueq.compilation.two_qubit.Native2Q'>, <class 'trueq.compilation.common.Justify'>, <class 'trueq.compilation.common.Merge'>, <class 'trueq.compilation.common.RemoveId'>, <class 'trueq.compilation.common.RemoveEmptyCycle'>, <class 'trueq.compilation.one_qubit.Native1Q'>, functools.partial(<class 'trueq.compilation.common.RemoveId'>, marker=None), <class 'trueq.compilation.common.InvolvingRestrictions'>, <class 'trueq.compilation.common.RemoveEmptyCycle'>)¶ This is the default set of compiler passes.
Changing this default list changes the behavior of the interfaces to Qiskit, Cirq, and PyQuil, and altering it may break the interface conversions completely.
CompilePaulis¶
-
class
trueq.compilation.
CompilePaulis
(factories=None, **_)¶ Pass which adds randomly chosen Pauli gates before all measurements in the circuit. Additionally updates the circuit key with the
compiled_pauli
entry with the appropriate Pauli string.Note
If the circuit’s key already contains a
compiled_pauli
entry, this entry will be updated to account for the new random Paulis which have been inserted.
count_streaks¶
-
class
trueq.compilation.
count_streaks
(circuit)¶ Iterates through a
Circuit
, finding all multi-qubit gates and counting the number of times that there are repeated operations on the same pair of qubits.Repeated operations on a pair of qubits can often be merged and do not require extra swaps to map a circuit onto a specific chip topology. Therefore we want to count “streaks”, where a “streak” on a pair of qubits is a series of cycles in a circuit where the qubit pair of interest do not interact with any other qubits.
For example, given a circuit of 6 cnot gates, where there are 2 cnots in a row on
(0, 1)
followed by a cnot on(1, 2)
, then 3 more cnots in a row on(0, 1)
.On labels (0, 1) there is 1 streak of 2 in a row and 1 of 3 in a row. On labels (1, 2) there is 1 streak of length 1.
import trueq as tq circ = tq.Circuit({(0, 1): tq.Gate.cx}) circ.append({(0, 1): tq.Gate.cx}) circ.append({(1, 2): tq.Gate.cx}) circ.append({(0, 1): tq.Gate.cx}) circ.append({(1, 0): tq.Gate.cx}) circ.append({(0, 1): tq.Gate.cx}) circ.draw() tq.compilation.count_streaks(circ)
{frozenset({0, 1}): {2: 1, 3: 1}, frozenset({1, 2}): {1: 1}}
This function returns a nested dictionary whose keys are pairs of qubits that have a multi-qubit gate acting on them, and the values are the numbers of streaks of each length. In the above example,
(0, 1)
has a value of`{2: 1, 3: 1}`
, meaning it found 1 streak of length 2 and 1 streak of length 3.Note that single qubit operations will not break a streak, and operations may happen in parallel and those will be counted as independent streaks.
The keys of the dictionary can be used to define the connectivity graph of the circuit itself, and are useful for validation of matching circuit topology to chip topology.
- Parameters
circuit (
trueq.Circuit
) – The circuit of which to calculate the topology and streaks.- Return type
dict
CycleSandwich¶
-
class
trueq.compilation.
CycleSandwich
(target, before=None, after=None, ignore_marker=True, ignore_id=True, **_)¶ Pass that searches
Circuit
s for a specificCycle
and when found, sandwiches it between two other (optional) cycles.import trueq as tq old_circuit = tq.Circuit({(0, 1): tq.Gate.cx}) # every time a the target cycle is found, add the before and after cycles as # appropriate target = tq.Cycle({(0, 1): tq.Gate.cx}) before = tq.Cycle({0: tq.Gate.from_generators("Z", 4)}) after = tq.Cycle({1: tq.Gate.from_generators("X", -8.2)}) sandwich = tq.compilation.CycleSandwich(target, before=before, after=after) sandwich.apply(old_circuit)
True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".Circuit- Key:
- No key present in circuit.
- Marker 0
Compilation tools may only recompile cycles with equal markers.(0): Gate(Z)- Name:
-
- Gate(Z)
- Generators:
-
- 'Z': 4.0
- Matrix:
-
-
1.00 -0.03j 1.00 0.03j
-
- Marker 0
Compilation tools may only recompile cycles with equal markers.(0, 1): Gate.cx- Name:
-
- Gate.cx
- Aliases:
-
- Gate.cx
- Gate.cnot
- Likeness:
-
- CNOT
- Generators:
-
- 'IX': 90.0
- 'ZI': 90.0
- 'ZX': -90.0
- Matrix:
-
-
1.00 1.00 1.00 1.00
-
- Marker 0
Compilation tools may only recompile cycles with equal markers.(1): Gate(X)- Name:
-
- Gate(X)
- Generators:
-
- 'X': -8.2
- Matrix:
-
-
1.00 0.07j 0.07j 1.00
-
Note
This pass makes deep copies of
before
andafter
.- Parameters
target (
Cycle
) – Which cycle to match on.before (
Cycle
) – A cycle to place immediately before every occurrence of the provided target.after (
Cycle
) – A cycle to place immediately after every occurrence of the provided target.ignore_marker (
bool
) – Whether to apply this pass when the target and a cycle have differing values oftrueq.Cycle.marker
. Default isTrue
.ignore_id (
bool
) – Whether to treat all identity gates as though they are not present when comparing cycles. Default isTrue
.
InvolvingRestrictions¶
-
class
trueq.compilation.
InvolvingRestrictions
(factories, **_)¶ A pass which ensures that any
NativeGate
which is defined from a list ofGateFactory
s obeys the involving restrictions of theGateFactory
s.Returns a list of
Cycle
s, whose length will not exceed the number of operations inside the original cycle.Satisfying the involving restrictions is done through a greedy algorithm, and there is no guarantee that the final number of cycles will be optimal.
Cycles retain their marker, and marked cycles will be broken into pieces as neccessary.
import trueq as tq # an example config with no initial restrictions config = tq.Config.basic(entangler=tq.Gate.cx) # adding a restriction on cx on (0, 1) so that it can not be at the # same time as gates on qubit (2, ) config.cx.involving[(0, 1)] = (2, ) circuit = tq.Circuit([{(0, 1): tq.Gate.cx, (2, 3): tq.Gate.cx, 7: tq.Gate.x}]) passes = (tq.compilation.Native2Q, tq.compilation.InvolvingRestrictions) tq.compile(config, circuit, passes)
True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".Circuit- Key:
- No key present in circuit.
- Marker 0
Compilation tools may only recompile cycles with equal markers.(0, 1): cx()- Name:
-
- cx()
- Aliases:
-
- Gate.cx
- Gate.cnot
- Likeness:
-
- CNOT
- Generators:
-
- 'IX': 90.0
- 'ZI': 90.0
- 'ZX': -90.0
- Matrix:
-
-
1.00 1.00 1.00 1.00
-
(2, 3): cx()- Name:
-
- cx()
- Aliases:
-
- Gate.cx
- Gate.cnot
- Likeness:
-
- CNOT
- Generators:
-
- 'IX': 90.0
- 'ZI': 90.0
- 'ZX': -90.0
- Matrix:
-
-
1.00 1.00 1.00 1.00
-
(7): Gate.x- Name:
-
- Gate.x
- Aliases:
-
- Gate.x
- Gate.cliff1
- Generators:
-
- 'X': 180.0
- Matrix:
-
-
1.00 1.00
-
Justify¶
-
class
trueq.compilation.
Justify
(marker=None, **_)¶ Pass that takes two Cycles, and moves gates preferentially to one side.
This method is inherently limited, because it only deals with 2 Cycles at a time, it can encounter “traffic jams”, IE: If you have two Cycles on qubit 0, followed by a series of empty cycles, the first Cycles Gate cannot move because of the second Cycle, but then the second cycle’s Gate will iteratively progress forward through the empty Cycles. This can be combated by repeating the Justify several times.
This class only jusifies when neighboring cycles have matching markers.
Returns 2 Cycles.
import trueq as tq circuit = tq.Circuit() circuit.append({0: tq.Gate.id, 1: tq.Gate.x}) circuit.append({0: tq.Gate.id}) circuit.append({0: tq.Gate.id}) circuit.draw() pat = tq.compilation.Justify() pat.apply(circuit).draw()
0 1 Key: Labels: (0,) Name: Gate.id Aliases: Gate.id Gate.i Gate.cliff0 Locally Equivalent: Identity Generators: I: 0.00 1.00 1.00 ID Labels: (1,) Name: Gate.x Aliases: Gate.x Gate.cliff1 Generators: X: 180.00 1.00 1.00 X Labels: (0,) Name: Gate.id Aliases: Gate.id Gate.i Gate.cliff0 Locally Equivalent: Identity Generators: I: 0.00 1.00 1.00 ID Labels: (0,) Name: Gate.id Aliases: Gate.id Gate.i Gate.cliff0 Locally Equivalent: Identity Generators: I: 0.00 1.00 1.00 ID 0 1 Key: Labels: (0,) Name: Gate.id Aliases: Gate.id Gate.i Gate.cliff0 Locally Equivalent: Identity Generators: I: 0.00 1.00 1.00 ID Labels: (0,) Name: Gate.id Aliases: Gate.id Gate.i Gate.cliff0 Locally Equivalent: Identity Generators: I: 0.00 1.00 1.00 ID Labels: (0,) Name: Gate.id Aliases: Gate.id Gate.i Gate.cliff0 Locally Equivalent: Identity Generators: I: 0.00 1.00 1.00 ID Labels: (1,) Name: Gate.x Aliases: Gate.x Gate.cliff1 Generators: X: 180.00 1.00 1.00 X - Parameters
marker (
int
|None
) – The cycle marker where this pass will be applied. ifNone
then this pass is applied to all cycles regardless of cycle marker.
MarkCycles¶
-
class
trueq.compilation.
MarkCycles
(marker=None, **_)¶ Pass that marks cycles which contain multi-qubit gates if none of the existing cycles in the circuit have been marked with non-zero values. By default, markers are start at
1
and increment up for every cycle containing a multi-qubit gate found.- Parameters
marker (
int
|None
) – The marker to be added to cycles containing multi-qubit gates. IfNone
then markers are incremented from1
for each cycle found.
Merge¶
-
class
trueq.compilation.
Merge
(n_labels=1, marker=None, **_)¶ Pass that takes two cycles, finds compatabile labels and gates, then merges them to a single gate as much as is possible.
Gates are automatically split into the smallest number of individual gates possible. For example, if the merging results in a two qubit gate that turns out to be the kronecker product of two single qubit gates, then it will automatically be broken apart into the two single qubit gates.
This class will only merge gates if adjacent cycles have the same marker.
Returns 2
Cycle
s.import trueq as tq # Make a circuit containing 4 x gates in a row, and merge them together circuit = tq.Circuit() for _ in range(4): circuit.append({0: tq.Gate.x}) pat = tq.compilation.Merge() pat.apply(circuit)
True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".Circuit- Key:
- No key present in circuit.
- Marker 0
Compilation tools may only recompile cycles with equal markers.empty - Marker 0
Compilation tools may only recompile cycles with equal markers.empty - Marker 0
Compilation tools may only recompile cycles with equal markers.empty - Marker 0
Compilation tools may only recompile cycles with equal markers.(0): Gate.id- Name:
-
- Gate.id
- Aliases:
-
- Gate.id
- Gate.i
- Gate.cliff0
- Likeness:
-
- Identity
- Generators:
-
- 'I': 0
- Matrix:
-
-
1.00 1.00
-
- Parameters
n_labels (
int
) – How many labels to merge at any given time, if only single qubit merging is desired, thenn_labels=1
, merging two qubit operations would ben_labels=2
etc. This defaults to single qubit reductions.marker (
int
|None
) – The cycle marker where this pass will be applied. ifNone
then this pass is applied to all cycles regardless of cycle marker.
MarkerPass¶
-
class
trueq.compilation.base.
MarkerPass
(factories=None, **_)¶ Parent class for compiler passes which operates on groups of cycles with matching markers.
The
_apply()
method is implemented to invoke the new abstract method_apply_cycles()
on every consecutive list of cycles in the circuit with an equal marker.-
abstract
_apply_cycles
(cycles)¶ Accepts any number of
Cycle
s and returns a list of cycles.Cycles returned by this function are put back into the original circuit in place of the cycles passed.
There is no restriction on the number of returned cycles.
- Parameters
cycles (
list
) – A list ofCycle
s which are to be altered by this pass.- Return type
list
-
abstract
Native1Q¶
-
class
trueq.compilation.
Native1Q
(factories, mode='ZXZXZ', **_)¶ A
NCyclePass
which iteratively attempts to decompose one-qubit gates into gates which are performable by the given list ofGateFactory
s.Advanced Users:
This pass combines
Parallel
andTryInOrder
to attempt various one-qubit decomposition methods across one-qubit gates in a given cycle. In particular, every one-qubit gate will attempt to be decomposed, in order, by the following replacements, using right-justification if decomposition lengths are ragged:NativeExact
-See if the gate appears exactly as seen inside of the list of
GateFactory
s.
Native1QUGates
-Decompose single qubit gates into
U
gates if they are defined inside of theGateFactory
s.
Native1QMode
-Decompose single qubit gates into the mode allowed by the
GateFactory
s.
Native1QRRZ
-Decompose single qubit gates into
R
andZ
gates, as long as the list ofGateFactory
s defines the correct gates.
- Parameters
factories (
Iterable
) – The iterable ofGateFactory
objects containing target one-qubit gates.mode (
str
) – The single qubit decomposition mode, defaults to'ZXZXZ'
, seetrueq.math.decomposition.QubitMode
for more details.
Native1QRRZ¶
-
class
trueq.compilation.
Native1QRRZ
(factories)¶ An
OperationReplacement
which decomposes single qubit gates into3
gates \(R(\theta) R(\phi) Z(\gamma)\), where theR
gates are defined by \(Z(\theta) X(90) Z(-\theta)\) in time.This will return either
1
or3
dictionaries.Will throw a
CompilationError
if noGateFactory
can be found in the list which can build either anR
gate orZ
gate. AGateFactory
forR
can be found inr_factory
.- Parameters
factories (
iterable
) – A iterable containingGateFactory
s which may contain anR
andZ
gates as defined above.
Native1QMode¶
-
class
trueq.compilation.
Native1QMode
(factories, mode='ZXZXZ', **_)¶ An
OperationReplacement
which expands arbitrary single qubit gates into the decomposition mode provided in a givenConfig
.Basics of operation:
When decomposing a single qubit gate on a given label, this looks through the list of
GateFactory
objects to find one which applies to that qubit. If the found factories are sufficient to build arbitrary single qubit gates according to the target mode. This list of factories is cached against the label.Next, these factories are combined with
QubitMode
to decompose into3
or5
dictionaries ofNativeGate
s.
Returns
1
,3
, or5
dictionaries.- Parameters
factories (
Iterable
) – The iterable ofGateFactory
objects containing target one-qubit gates.mode (
str
) – The single qubit decomposition mode, defaults to'ZXZXZ'
, seetrueq.math.decomposition.QubitMode
for more details.
Native1QUGates¶
-
class
trueq.compilation.
Native1QUGates
(factories, **_)¶ An
OperationReplacement
which decomposes single qubit gates intoU1
,U2
, orU3
gates found inside of the provided list ofGateFactory
s.This will return a list containing
1
dictionary.- Parameters
factories (
iterable
) – A list ofGateFactory
s potentially containing factories which representU
gates as defined inu1_factory
,u2_factory
,u3_factory
.
Native2Q¶
-
class
trueq.compilation.
Native2Q
(factories, max_depth=3, **_)¶ A
NCyclePass
which iteratively attempts to decompose two-qubit gates into gates which are performable by the given list ofGateFactory
s.Advanced Users:
This pass combines
Parallel
andTryInOrder
to attempt various two-qubit decomposition methods across two-qubit gates in a given cycle. In particular, every two-qubit gate will attempt to be decomposed, in order, by the following replacements, using right-justification if decomposition lengths are ragged:NativeExact
-See if the gate appears exactly as seen inside of the factory list.
Native2QKAK
-See if the gate is equivalent to a gate inside of the factory list up to single qubit operations.
Native2QCX
-If a
CX
equivalent gate is found in the factory list, build the target gate using a known analytic decomposition.
Native2QFastDecomp
-Use a numerical method to find a decomposition, a very general method.
Walking through an example:
Lets start with a cycle which only contains a single Haar random
SU(4)
, with a factory list that contains aCZ
gate.Each operation is passed to the
TryInOrder
one at a time, theTryInOrder
pass will run through its list of replacements, starting withNativeExact
until no errors occur.Since the target gate is Haar random and the factory list only defines a
CZ
, the first few replacements will fail. The first one which will successfully decompose the random gate in this case will be theNative2QCX
, as the factory list defines aCZ
which is locally equivalent toCX
.This decomposition is then passed back up to the
Native2Q
pass (which is a subclass ofParallel
), where it has no other cycles to be combined with, so it is simply returned as is.See
Parallel
for more details on how cycles are combined in general.- Parameters
factories (
Iterable
) – The iterable ofGateFactory
objects containing target two-qubit gates.max_depth (
int
) – The maximum depth passed to the final numerical decomposition methodNative2QFastDecomp
.
Native2QCX¶
-
class
trueq.compilation.
Native2QCX
(factories, **_)¶ An
OperationReplacement
which decomposes anySU(4)
into a gate which is locally equivalent toCNOT
, as long as such a gate exists inside of the givenConfig
.The decomposition methods inside of this
OperationReplacement
are based on:https://arxiv.org/abs/quant-ph/0307177
This pass accepts
1
operation, and will return either5
or7
dictionaries, seeNative2QKAK
if only3
dictionaries are expected.If the target gate is locally equivalent to a gate of the form
trueq.Gate.from_generators("XX", theta, "YY", phi)
for anyphi
ortheta
, then the restrictions on the config defined gate relax from being locally equivalent to aCNOT
to any gate of the formtrueq.Gate.from_generators("XX", 90, "YY", phi)
, which includes iSWAP gates.- Parameters
factories (
tuple
) – The tuple ofGateFactory
objects.
Native2QFastDecomp¶
-
class
trueq.compilation.
Native2QFastDecomp
(depth, factories, tol=1e-08, **_)¶ An
OperationReplacement
which attempts to decompose the provided gate up to a given depth using gates found in the provided list ofGateFactory
s.This is only successful if the provided gate can be decomposed in exactly the depth specified and the decomposition has a process infidelity which is smaller than the
tol
parameter.- Parameters
depth (
int
) – The number of two qubit gates from the factory list which to decompose each gate into.factories (
tuple
) – The tuple ofGateFactory
objects.tol (
float
) – The minimum process infidelity allowed for the decomposition to be considered successful.
Native2QKAK¶
-
class
trueq.compilation.
Native2QKAK
(factories, **_)¶ An
OperationReplacement
which checks if a given operation is a two-qubit gate that is equal to some staticGateFactory
in the provided list ofGateFactory
s up to single qubit operations, and if so, switch theGate
with aNativeGate
built from the factory list plus the approriate single qubit gates.- Parameters
factories (
Iterable
) – The iterable ofGateFactory
objects containing target gates.
NativeExact¶
-
class
trueq.compilation.
NativeExact
(factories)¶ Checks to see if each gate is present in the provided list of
GateFactory
s exactly as defined, and if so, switch theGate
with aNativeGate
from the list.- Parameters
factories (
Iterable
) – An iterable ofGateFactory
s which may be used by the replacement.
NCyclePass¶
-
class
trueq.compilation.base.
NCyclePass
(factories=None, **_)¶ Parent class for compiler passes which accept a fixed number of cycles at a time.
This is a convenience parent class which contains the logic of passing a fixed number of cycles
n_input_cycles
at a time to a child class defined method_apply_cycles()
, then taking the returned cycles and re-inserting them into a circuit.The
_apply()
method is implemented to invoke the new abstract method_apply_cycles()
on every consecutive list of cycles with length equal ton_input_cycles
, starting from the beginning of the circuit. At each invocation, the output of_apply_cycles()
is inserted into the circuit before calling it on the next subset of cycles. There is no restriction on the number cycles returned by implementations of_apply_cycles()
.To demonstrate how this class iterates over cycles, here is an implementation of a pass which takes two cycles at a time, prints the gates, and returns the cycles unaltered:
from trueq.compilation.base import NCyclePass from trueq import Gate class Passthrough(NCyclePass): n_input_cycles = 2 def _apply_cycles(self, cycles): print([gate for cycle in cycles for _, gate in cycle]) return cycles Passthrough().apply([{0: Gate.i}, {0: Gate.x}, {0: Gate.y}, {0: Gate.z}])
[Gate.id, Gate.x] [Gate.x, Gate.y] [Gate.y, Gate.z]
True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".Circuit- Key:
- No key present in circuit.
- Marker 0
Compilation tools may only recompile cycles with equal markers.(0): Gate.id- Name:
-
- Gate.id
- Aliases:
-
- Gate.id
- Gate.i
- Gate.cliff0
- Likeness:
-
- Identity
- Generators:
-
- 'I': 0
- Matrix:
-
-
1.00 1.00
-
- Marker 0
Compilation tools may only recompile cycles with equal markers.(0): Gate.x- Name:
-
- Gate.x
- Aliases:
-
- Gate.x
- Gate.cliff1
- Generators:
-
- 'X': 180.0
- Matrix:
-
-
1.00 1.00
-
- Marker 0
Compilation tools may only recompile cycles with equal markers.(0): Gate.y- Name:
-
- Gate.y
- Aliases:
-
- Gate.y
- Gate.cliff2
- Generators:
-
- 'Y': 180.0
- Matrix:
-
-
-1.00j 1.00j
-
- Marker 0
Compilation tools may only recompile cycles with equal markers.(0): Gate.z- Name:
-
- Gate.z
- Aliases:
-
- Gate.z
- Gate.cliff3
- Generators:
-
- 'Z': 180.0
- Matrix:
-
-
1.00 -1.00
-
The circuit in this example has four cycles, each with a single gate. The first two cycles which are passed are the ones containing
I
andX
gates. These are printed, and get put back into the circuit without being altered. The pass then increments forward one index and passes the cycles containingX
andY
. It is important to note that this increments by one, notn_input_cycles
at a time.-
abstract
_apply_cycles
(cycles)¶ Accepts
n_input_cycles
number ofCycle
s and returns a list of cycles.Cycles returned by this function are put back into the original circuit in place of the cycles passed.
There is no restriction on the number of returned cycles.
- Parameters
cycles (
list
) – A list containingn_input_cycles
which are to be altered by this pass.- Return type
list
-
abstract property
n_input_cycles
¶ The number of cycles
_apply_cycles()
expects.- Type
int
OperationReplacement¶
-
class
trueq.compilation.base.
OperationReplacement
¶ Parent class used by
Pass
es which manipulates a singleOperation
s at a time.The
apply()
accepts a label and operation, and returns a list containing dictionaries. This differs from aPass
in that it only operates on a single operation at a time, whereasPass
es operate on a cycles or circuits.-
abstract
apply
(labels, operation)¶ This accepts labels and an
Operation
and returns a list of dictionaries, where the dictionary keys are labels and the values areOperation
s.The returned list may contain any number of dictionaries.
- Parameters
labels (
tuple
) – A tuple containing the qubit labels which the operation acts on.operation (
trueq.Operation
) – The operation to be altered by the replacement.
- Returns
A list of dictionaries, where the keys are labels, and the values are
trueq.Operation
s.- Return type
list
-
abstract
Parallel¶
-
class
trueq.compilation.
Parallel
(replacements=None, **_)¶ A
NCyclePass
that splits a cycle into individual operations, passes the operations to providedOperationReplacement
s in parallel, and recombines the output into a list of cycles.Note that this pass is not implemented in parallel across cpu cores currently.
Each operation in the input cycle is split and passed to each
OperationReplacement
based upon a dictionary lookup, this dictionary lookup has keys which are labels, and the values are the targetOperationReplacement
. If the given labels are not found in the lookup dictionary, then the operation is passed unaltered to the output cycles. The lookup dictionary can optionally have aNone
key, which signifies a default pass which should be used if the labels are not present in the dictionary.This returns a list of cycles, where the number of cycles is decided by the
OperationReplacement
s provided, and all cycles returned are joined such that they are justified to the latest possible cycle in time.All output cycles maintain the marker of the input cycle.
- Parameters
replacements (
dict
|OperationReplacement
) – Optional, either a dictionary mapping labels toOperationReplacement
s, or just a singleOperationReplacement
, which is applied to all labels.
Pass¶
-
class
trueq.compilation.base.
Pass
(factories=None, **_)¶ Parent class for all
Compiler
passes that manipulate and return an alteredCircuit
.A pass accepts a circuit to its
apply()
function. This circuit will then be operated on, and some (potentially new) circuit is returned.
PhaseTrack¶
-
class
trueq.compilation.
PhaseTrack
(factories, virtual=None, include_final_virtual=False, **_)¶ This pass tracks phase accumulation on each qubit throughout a circuit, and compiles this phase information into parametric gates.
For example, if a device tunes up two gate pulses, \(X90\) and \(XX90\) (the maximally entangling Molmer-Sorensen gate), and implements single-qubit Z-rotations virtually, then this pass will accumulate phases on each qubit based on \(Z(\theta)\) gates it finds, and respectively replace \(X90\) and \(XX90\) gates with parameterized \(X90(\phi)\) gates (i.e. 90 degree nutations about a vector in the X-Y plane) and parameterized \(XX90(\phi_1, \phi_2)\) gates (i.e. the \(XX90\) gate which has been individually phase updated on each qubit). Therefore, pulse sequences can be programmed directly by looping through cycles in a circuit, choosing the pulse shape based on the gate names, and choosing pulse phases based on the parameters of the gates.
See Phase Tracking with the Compiler for detailed usage examples.
Note
This pass may not output a circuit that implements the same unitary as the input because it may be off by z-rotations (as in the example above) prior to measurement. It will, however, produce the same bitstring statistics because a z-rotation prior to a measurement along the z-axis will not affect bitstring populations.
- Parameters
factories (
Iterable
) – An iterable ofGateFactory
s that contains all the gate factories of interest.virtual (
None
|GateFactory
) – The factory of the virtual gate. By default, the factory list wil be searched for a single-qubit Z-rotation, which will be defined as the virtual gate.include_final_virtual (
bool
) – Whether to apply the cumulative virtual gates prior to preparations, measurements, or at the end of the circuit.
RCCycle¶
-
class
trueq.compilation.
RCCycle
(twirl, **_)¶ Pass which performs Randomized Compilation on groups of cycles with matching marker values by adding gates on either side of the cycles, chosen using the provided
Twirl
.Use of this class requires a Randomized Compilation license.
Note
Cycles containing twirling gates are inserted before and after blocks of cycles which have non-zero markers. The inserted cycles will have the default marker
0
.Multiple cycles in a row which all contain the same marker value are twirled around as a group, twirls are not inserted between the cycles.
No twirling gates are added around groups of cycles containing
Meas
orPrep
operations.- Parameters
twirl (
trueq.Twirl
) – The twirl which will be applied during randomized compilation.
Relabel¶
-
class
trueq.compilation.
Relabel
(permutation, **_)¶ Pass which relabels all the labels and keys in a
Circuit
.This searches through and relabels/reorders entries in the following key entries:
analyze_decays
compiled_pauli
cycle
measurement_basis
targeted_errors
twirl
Note that this does not function when the circuit has results present.
import trueq as tq old_circ = tq.Circuit([{0: tq.Gate.x, 1: tq.Gate.y, 2: tq.Gate.z}]) # Swapping the labels on qubit 0 and 1, 2 stays permutation = {0: 1, 1: 0, 2: 2} pat = tq.compilation.Relabel(permutation) pat.apply(old_circ)
True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".Circuit- Key:
- No key present in circuit.
- Marker 0
Compilation tools may only recompile cycles with equal markers.(0): Gate.y- Name:
-
- Gate.y
- Aliases:
-
- Gate.y
- Gate.cliff2
- Generators:
-
- 'Y': 180.0
- Matrix:
-
-
-1.00j 1.00j
-
(1): Gate.x- Name:
-
- Gate.x
- Aliases:
-
- Gate.x
- Gate.cliff1
- Generators:
-
- 'X': 180.0
- Matrix:
-
-
1.00 1.00
-
(2): Gate.z- Name:
-
- Gate.z
- Aliases:
-
- Gate.z
- Gate.cliff3
- Generators:
-
- 'Z': 180.0
- Matrix:
-
-
1.00 -1.00
-
- Parameters
permutation (
dict
) – A dictionary where the keys are the current label and the values are the new labels.
RemoveEmptyCycle¶
-
class
trueq.compilation.
RemoveEmptyCycle
(marker=0, **_)¶ Pass which accepts one cycle and returns the cycle if it contains any operations.
- Parameters
marker (
int
|None
) – The cycle marker where this pass will be applied. ifNone
then this pass is applied to all cycles regardless of cycle marker.
RemoveId¶
-
class
trueq.compilation.
RemoveId
(marker=0, **_)¶ Pass that removes single qubit identity gates from
1
Cycle
.Returns a list containing 1
Cycle
.import trueq as tq # Make a circuit containing 4 id gates in a row circuit = tq.Circuit() for _ in range(4): circuit.append({0: tq.Gate.id}) # remove all identity gates pat = tq.compilation.RemoveId() pat.apply(circuit)
True-Q formatting will not be loaded without trusting this notebook or rerunning the affected cells. Notebooks can be marked as trusted by clicking "File -> Trust Notebook".Circuit- Key:
- No key present in circuit.
- Marker 0
Compilation tools may only recompile cycles with equal markers.empty - Marker 0
Compilation tools may only recompile cycles with equal markers.empty - Marker 0
Compilation tools may only recompile cycles with equal markers.empty - Marker 0
Compilation tools may only recompile cycles with equal markers.empty - Parameters
marker (
int
|None
) – The cycle marker where this pass will be applied. ifNone
then this pass is applied to all cycles regardless of cycle marker.
TryInOrder¶
-
class
trueq.compilation.
TryInOrder
(replacements=None, **_)¶ An
OperationReplacement
where a list ofOperationReplacement
s is stored, and each is attempted in order until noCompilationError
is raised.All replacements in
TryInOrder
must beOperationReplacement
s.- Parameters
replacements (
list
) – Optional, a list ofOperationReplacement
s to be applied in order until one succeeds.
-
append
(replacement)¶ Append a replacement to the list of existing replacements.
- Parameters
replacement (
OperationReplacement
) – The replacement to be appended.
-
apply
(label, operation)¶ This accepts labels and an
Operation
and returns a list of dictionaries, where the dictionary keys are labels and the values areOperation
s.The returned list may contain any number of dictionaries.
- Parameters
labels (
tuple
) – A tuple containing the qubit labels which the operation acts on.operation (
trueq.Operation
) – The operation to be altered by the replacement.
- Returns
A list of dictionaries, where the keys are labels, and the values are
trueq.Operation
s.- Return type
list
compile¶
-
trueq.
compile
(config, circuit, passes=None)¶ Compiles an arbitrary
Circuit
into a representation which is compatible with a givenConfig
.By default, this performs a standard set of passes, and can be used as a template for more advanced compiler definitions. See
trueq.compilation.Compiler.DEFAULT_PASSES
for a list of the default passes which are applied.- Parameters
config (
trueq.Config
) – Atrueq.Config
which has 2-qubit gates defined.circuit (
trueq.Circuit
) – A circuit which will be compiled into the config compatable format.passes (
tuple
) – A tuple ofPass
to be applied in order. These must be uninstantiated classes which must accept aconfig
as a keyword argument, seetrueq.compilation.Compiler.DEFAULT_PASSES
for an example. IfNone
is provided, then this default list is used.