INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Takes a list of polygons and return an array of their normals. Normals point towards the viewer for a face with its vertices in counterclockwise order following the right hand rule. Uses three points equally spaced around the polygon. This normal of course might not make sense for polygons with more than three points n... | def _generate_normals(polygons):
"""
Takes a list of polygons and return an array of their normals.
Normals point towards the viewer for a face with its vertices in
counterclockwise order, following the right hand rule.
Uses three points equally spaced around the polygon.
This normal of course m... |
Shade * color * using normal vectors given by * normals *. * color * can also be an array of the same length as * normals *. | def _shade_colors(color, normals, lightsource=None):
"""
Shade *color* using normal vectors given by *normals*.
*color* can also be an array of the same length as *normals*.
"""
if lightsource is None:
# chosen for backwards-compatibility
lightsource = LightSource(azdeg=225, altdeg=1... |
Gets the unique backends that are available. | def get_unique_backends():
"""Gets the unique backends that are available.
Returns:
list: Unique available backends.
Raises:
QiskitError: No backends available.
"""
backends = IBMQ.backends()
unique_hardware_backends = []
unique_names = []
for back in backends:
... |
Monitor a single IBMQ backend. | def backend_monitor(backend):
"""Monitor a single IBMQ backend.
Args:
backend (IBMQBackend): Backend to monitor.
Raises:
QiskitError: Input is not a IBMQ backend.
"""
if not isinstance(backend, IBMQBackend):
raise QiskitError('Input variable is not of type IBMQBackend.')
... |
Gives overview information on all the IBMQ backends that are available. | def backend_overview():
"""Gives overview information on all the IBMQ
backends that are available.
"""
unique_hardware_backends = get_unique_backends()
_backends = []
# Sort backends by operational or not
for idx, back in enumerate(unique_hardware_backends):
if back.status().operatio... |
Returns the Instruction object corresponding to the op for the node else None | def op(self):
"""Returns the Instruction object corresponding to the op for the node else None"""
if 'type' not in self.data_dict or self.data_dict['type'] != 'op':
raise QiskitError("The node %s is not an op node" % (str(self)))
return self.data_dict.get('op') |
Returns ( Register int ) tuple where the int is the index of the wire else None | def wire(self):
"""
Returns (Register, int) tuple where the int is the index of
the wire else None
"""
if self.data_dict['type'] not in ['in', 'out']:
raise QiskitError('The node %s is not an input/output node' % str(self))
return self.data_dict.get('wire') |
Check if DAG nodes are considered equivalent e. g. as a node_match for nx. is_isomorphic. | def semantic_eq(node1, node2):
"""
Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.
Args:
node1 (DAGNode): A node to compare.
node2 (DAGNode): The other node to compare.
Return:
Bool: If node1 == node2
... |
Generates constant - sampled SamplePulse. | def constant(duration: int, amp: complex, name: str = None) -> SamplePulse:
"""Generates constant-sampled `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Complex pulse am... |
Generates zero - sampled SamplePulse. | def zero(duration: int, name: str = None) -> SamplePulse:
"""Generates zero-sampled `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
name: Name of pulse.
"""
return _sampled_zero_pulse(duration, name=name) |
Generates square wave SamplePulse. | def square(duration: int, amp: complex, period: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
"""Generates square wave `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be grea... |
Generates sawtooth wave SamplePulse. | def sawtooth(duration: int, amp: complex, period: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
"""Generates sawtooth wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
perio... |
Generates triangle wave SamplePulse. | def triangle(duration: int, amp: complex, period: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
"""Generates triangle wave `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must b... |
Generates cosine wave SamplePulse. | def cos(duration: int, amp: complex, freq: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
"""Generates cosine wave `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater than... |
Generates sine wave SamplePulse. | def sin(duration: int, amp: complex, freq: float = None,
phase: float = 0, name: str = None) -> SamplePulse:
"""Generates sine wave `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt. If `None` ... |
r Generates unnormalized gaussian SamplePulse. | def gaussian(duration: int, amp: complex, sigma: float, name: str = None) -> SamplePulse:
r"""Generates unnormalized gaussian `SamplePulse`.
Centered at `duration/2` and zeroed at `t=-1` to prevent large initial discontinuity.
Applies `left` sampling strategy to generate discrete pulse from continuous fun... |
r Generates unnormalized gaussian derivative SamplePulse. | def gaussian_deriv(duration: int, amp: complex, sigma: float, name: str = None) -> SamplePulse:
r"""Generates unnormalized gaussian derivative `SamplePulse`.
Applies `left` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater tha... |
Generates gaussian square SamplePulse. | def gaussian_square(duration: int, amp: complex, sigma: float,
risefall: int, name: str = None) -> SamplePulse:
"""Generates gaussian square `SamplePulse`.
Centered at `duration/2` and zeroed at `t=-1` and `t=duration+1` to prevent
large initial/final discontinuities.
Applies `left... |
r Generates Y - only correction DRAG SamplePulse for standard nonlinear oscillator ( SNO ) [ 1 ]. | def drag(duration: int, amp: complex, sigma: float, beta: float, name: str = None) -> SamplePulse:
r"""Generates Y-only correction DRAG `SamplePulse` for standard nonlinear oscillator (SNO) [1].
Centered at `duration/2` and zeroed at `t=-1` to prevent large initial discontinuity.
Applies `left` sampling s... |
Return a new circuit that has been optimized. | def run(self, dag):
"""Return a new circuit that has been optimized."""
diagonal_1q_gates = (RZGate, ZGate, TGate, SGate, TdgGate, SdgGate, U1Gate)
diagonal_2q_gates = (CzGate, CrzGate, Cu1Gate, RZZGate)
nodes_to_remove = set()
for measure in dag.op_nodes(Measure):
p... |
Plots the gate map of a device. | def plot_gate_map(backend, figsize=None,
plot_directed=False,
label_qubits=True,
qubit_size=24,
line_width=4,
font_size=12,
qubit_color=None,
line_color=None,
font_color='w'):
... |
Compute distance. | def dist_real(self):
"""Compute distance.
"""
x0, y0 = self.ax.transAxes.transform( # pylint: disable=invalid-name
(0, 0))
x1, y1 = self.ax.transAxes.transform( # pylint: disable=invalid-name
(1, 1))
value = x1 - x0 if self.x else y1 - y0
return ... |
Distance abs | def dist_abs(self):
"""Distance abs
"""
bounds = self.ax.get_xlim() if self.x else self.ax.get_ylim()
return bounds[0] - bounds[1] |
Print the node data with indent. | def to_string(self, indent):
"""Print the node data, with indent."""
ind = indent * ' '
print(ind, 'qreg')
self.children[0].to_string(indent + 3) |
Return the Basic Aer backends in BACKENDS that are effectively available ( as some of them might depend on the presence of an optional dependency or on the existence of a binary ). | def _verify_backends(self):
"""
Return the Basic Aer backends in `BACKENDS` that are
effectively available (as some of them might depend on the presence
of an optional dependency or on the existence of a binary).
Returns:
dict[str:BaseBackend]: a dict of Basic Aer ba... |
Return an instance of a backend from its class. | def _get_backend_instance(self, backend_cls):
"""
Return an instance of a backend from its class.
Args:
backend_cls (class): Backend class.
Returns:
BaseBackend: a backend instance.
Raises:
QiskitError: if the backend could not be instantiated... |
Return a list of qubits as ( QuantumRegister index ) pairs. | def qubits(self):
"""Return a list of qubits as (QuantumRegister, index) pairs."""
return [(v, i) for k, v in self.qregs.items() for i in range(v.size)] |
Return a list of bits as ( ClassicalRegister index ) pairs. | def clbits(self):
"""Return a list of bits as (ClassicalRegister, index) pairs."""
return [(v, i) for k, v in self.cregs.items() for i in range(v.size)] |
Rename a classical or quantum register throughout the circuit. | def rename_register(self, regname, newname):
"""Rename a classical or quantum register throughout the circuit.
regname = existing register name string
newname = replacement register name string
"""
if regname == newname:
return
if newname in self.qregs or new... |
Remove all operation nodes with the given name. | def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.named_nodes(opname):
self.remove_op_node(n) |
Add all wires in a quantum register. | def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qreg... |
Add all wires in a classical register. | def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
sel... |
Add a qubit or bit to the circuit. | def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (tuple): (Register,int) containing a register instance and index
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
... |
Verify that the condition is valid. | def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid regi... |
Check the values of a list of ( qu ) bit arguments. | def _check_bits(self, args, amap):
"""Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list): (register,idx) tuples
amap (dict): a dictionary keyed on (register,idx) tuples
Raises:
D... |
Return a list of bits in the given condition. | def _bits_in_condition(self, cond):
"""Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int)
Returns:
list[(ClassicalRegister, idx)]: list of bits
"""
all_bits = []
if cond is not No... |
Add a new operation node to the graph and assign properties. | def _add_op_node(self, op, qargs, cargs, condition=None):
"""Add a new operation node to the graph and assign properties.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list): list of quantum wires to attach to.
cargs (list): list of classi... |
Apply an operation to the output of the circuit. | def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):
"""Apply an operation to the output of the circuit.
Args:
op (Instruction): the operation associated with the DAG node
qargs (list[tuple]): qubits that op will be applied to
cargs (list[tuple... |
Check that wiremap neither fragments nor leaves duplicate registers. | def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by edge_map.
2. There are... |
Check that the wiremap is consistent. | def _check_wiremap_validity(self, wire_map, keymap, valmap):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from (register,idx) in keymap to
(regist... |
Use the wire_map dict to change the condition tuple s creg name. | def _map_condition(self, wire_map, condition):
"""Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from wires to wires
condition (tuple): (ClassicalRegister,int)
Returns:
tuple(ClassicalRegister,int): new condition... |
Add dag at the end of self using edge_map. | def extend_back(self, dag, edge_map=None):
"""Add `dag` at the end of `self`, using `edge_map`.
"""
edge_map = edge_map or {}
for qreg in dag.qregs.values():
if qreg.name not in self.qregs:
self.add_qreg(QuantumRegister(qreg.size, qreg.name))
edge_... |
Apply the input circuit to the output of this circuit. | def compose_back(self, input_circuit, edge_map=None):
"""Apply the input circuit to the output of this circuit.
The two bases must be "compatible" or an exception occurs.
A subset of input qubits of the input circuit are mapped
to a subset of output qubits of this circuit.
Args... |
Return the circuit depth. Returns: int: the circuit depth Raises: DAGCircuitError: if not a directed acyclic graph | def depth(self):
"""Return the circuit depth.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
"""
if not nx.is_directed_acyclic_graph(self._multi_graph):
raise DAGCircuitError("not a DAG")
depth... |
Check that a list of wires is compatible with a node to be replaced. | def _check_wires_list(self, wires, node):
"""Check that a list of wires is compatible with a node to be replaced.
- no duplicate names
- correct length for operation
Raise an exception otherwise.
Args:
wires (list[register, index]): gives an order for (qu)bits
... |
Return predecessor and successor dictionaries. | def _make_pred_succ_maps(self, node):
"""Return predecessor and successor dictionaries.
Args:
node (DAGNode): reference to multi_graph node
Returns:
tuple(dict): tuple(predecessor_map, successor_map)
These map from wire (Register, int) to predecessor (su... |
Map all wires of the input circuit. | def _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,
wire_map):
"""Map all wires of the input circuit.
Map all wires of the input circuit to predecessor and
successor nodes in self, keyed on wires in self.
Args:
pred_map (dict): com... |
Yield nodes in topological order. | def topological_nodes(self):
"""
Yield nodes in topological order.
Returns:
generator(DAGNode): node in topological order
"""
return nx.lexicographical_topological_sort(self._multi_graph,
key=lambda x: str(x.qargs)) |
Replace one node with dag. | def substitute_node_with_dag(self, node, input_dag, wires=None):
"""Replace one node with dag.
Args:
node (DAGNode): node to substitute
input_dag (DAGCircuit): circuit that will substitute the node
wires (list[(Register, index)]): gives an order for (qu)bits
... |
Iterator for node values. | def edges(self, nodes=None):
"""Iterator for node values.
Yield:
node: the node.
"""
for source_node, dest_node, edge_data in self._multi_graph.edges(nodes, data=True):
yield source_node, dest_node, edge_data |
Deprecated. Use op_nodes (). | def get_op_nodes(self, op=None, data=False):
"""Deprecated. Use op_nodes()."""
warnings.warn('The method get_op_nodes() is being replaced by op_nodes().'
'Returning a list of node_ids/(node_id, data) tuples is '
'also deprecated, op_nodes() returns a list of ... |
Get the list of op nodes in the dag. | def op_nodes(self, op=None):
"""Get the list of "op" nodes in the dag.
Args:
op (Type): Instruction subclass op nodes to return. if op=None, return
all op nodes.
Returns:
list[DAGNode]: the list of node ids containing the given op.
"""
nod... |
Deprecated. Use gate_nodes (). | def get_gate_nodes(self, data=False):
"""Deprecated. Use gate_nodes()."""
warnings.warn('The method get_gate_nodes() is being replaced by gate_nodes().'
'Returning a list of node_ids/(node_id, data) tuples is also '
'deprecated, gate_nodes() returns a list of ... |
Get the list of gate nodes in the dag. | def gate_nodes(self):
"""Get the list of gate nodes in the dag.
Returns:
list: the list of node ids that represent gates.
"""
nodes = []
for node in self.op_nodes():
if isinstance(node.op, Gate):
nodes.append(node)
return nodes |
Deprecated. Use named_nodes (). | def get_named_nodes(self, *names):
"""Deprecated. Use named_nodes()."""
warnings.warn('The method get_named_nodes() is being replaced by named_nodes()',
'Returning a list of node_ids is also deprecated, named_nodes() '
'returns a list of DAGNodes ',
... |
Get the set of op nodes with the given name. | def named_nodes(self, *names):
"""Get the set of "op" nodes with the given name."""
named_nodes = []
for node in self._multi_graph.nodes():
if node.type == 'op' and node.op.name in names:
named_nodes.append(node)
return named_nodes |
Deprecated. Use twoQ_gates (). | def get_2q_nodes(self):
"""Deprecated. Use twoQ_gates()."""
warnings.warn('The method get_2q_nodes() is being replaced by twoQ_gates()',
'Returning a list of data_dicts is also deprecated, twoQ_gates() '
'returns a list of DAGNodes.',
Dep... |
Get list of 2 - qubit gates. Ignore snapshot barriers and the like. | def twoQ_gates(self):
"""Get list of 2-qubit gates. Ignore snapshot, barriers, and the like."""
two_q_gates = []
for node in self.gate_nodes():
if len(node.qargs) == 2:
two_q_gates.append(node)
return two_q_gates |
Deprecated. Use threeQ_or_more_gates (). | def get_3q_or_more_nodes(self):
"""Deprecated. Use threeQ_or_more_gates()."""
warnings.warn('The method get_3q_or_more_nodes() is being replaced by'
' threeQ_or_more_gates()',
'Returning a list of (node_id, data) tuples is also deprecated, '
... |
Get list of 3 - or - more - qubit gates: ( id data ). | def threeQ_or_more_gates(self):
"""Get list of 3-or-more-qubit gates: (id, data)."""
three_q_gates = []
for node in self.gate_nodes():
if len(node.qargs) >= 3:
three_q_gates.append(node)
return three_q_gates |
Returns list of the predecessors of a node as DAGNodes. | def predecessors(self, node):
"""Returns list of the predecessors of a node as DAGNodes."""
if isinstance(node, int):
warnings.warn('Calling predecessors() with a node id is deprecated,'
' use a DAGNode instead',
DeprecationWarning, 2)
... |
Returns list of the predecessors of a node that are connected by a quantum edge as DAGNodes. | def quantum_predecessors(self, node):
"""Returns list of the predecessors of a node that are
connected by a quantum edge as DAGNodes."""
predecessors = []
for predecessor in self.predecessors(node):
if isinstance(self._multi_graph.get_edge_data(predecessor, node, key=0)['wir... |
Returns set of the ancestors of a node as DAGNodes. | def ancestors(self, node):
"""Returns set of the ancestors of a node as DAGNodes."""
if isinstance(node, int):
warnings.warn('Calling ancestors() with a node id is deprecated,'
' use a DAGNode instead',
DeprecationWarning, 2)
no... |
Returns list of the successors of a node that are connected by a quantum edge as DAGNodes. | def quantum_successors(self, node):
"""Returns list of the successors of a node that are
connected by a quantum edge as DAGNodes."""
if isinstance(node, int):
warnings.warn('Calling quantum_successors() with a node id is deprecated,'
' use a DAGNode instead'... |
Remove an operation node n. | def remove_op_node(self, node):
"""Remove an operation node n.
Add edges from predecessors to successors.
"""
if isinstance(node, int):
warnings.warn('Calling remove_op_node() with a node id is deprecated,'
' use a DAGNode instead',
... |
Remove all of the ancestor operation nodes of node. | def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
if isinstance(node, int):
warnings.warn('Calling remove_ancestors_of() with a node id is deprecated,'
' use a DAGNode instead',
DeprecationWarnin... |
Remove all of the descendant operation nodes of node. | def remove_descendants_of(self, node):
"""Remove all of the descendant operation nodes of node."""
if isinstance(node, int):
warnings.warn('Calling remove_descendants_of() with a node id is deprecated,'
' use a DAGNode instead',
Deprecation... |
Remove all of the non - ancestors operation nodes of node. | def remove_nonancestors_of(self, node):
"""Remove all of the non-ancestors operation nodes of node."""
if isinstance(node, int):
warnings.warn('Calling remove_nonancestors_of() with a node id is deprecated,'
' use a DAGNode instead',
Deprec... |
Remove all of the non - descendants operation nodes of node. | def remove_nondescendants_of(self, node):
"""Remove all of the non-descendants operation nodes of node."""
if isinstance(node, int):
warnings.warn('Calling remove_nondescendants_of() with a node id is deprecated,'
' use a DAGNode instead',
... |
Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit. | def layers(self):
"""Yield a shallow view on a layer of this DAGCircuit for all d layers of this circuit.
A layer is a circuit whose gates act on disjoint qubits, i.e.
a layer has depth 1. The total number of layers equals the
circuit depth d. The layers are indexed from 0 to d-1 with t... |
Yield a layer for all gates of this circuit. | def serial_layers(self):
"""Yield a layer for all gates of this circuit.
A serial layer is a circuit with one gate. The layers have the
same structure as in layers().
"""
for next_node in self.topological_op_nodes():
new_layer = DAGCircuit()
for qreg in s... |
Yield layers of the multigraph. | def multigraph_layers(self):
"""Yield layers of the multigraph."""
predecessor_count = dict() # Dict[node, predecessors not visited]
cur_layer = [node for node in self.input_map.values()]
yield cur_layer
next_layer = []
while cur_layer:
for node in cur_layer:... |
Return a set of non - conditional runs of op nodes with the given names. | def collect_runs(self, namelist):
"""Return a set of non-conditional runs of "op" nodes with the given names.
For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
would produce the tuple of cx nodes as an element of the set returned
from a call to collect_runs(["cx"]). If i... |
Iterator for nodes that affect a given wire | def nodes_on_wire(self, wire, only_ops=False):
"""
Iterator for nodes that affect a given wire
Args:
wire (tuple(Register, index)): the wire to be looked at.
only_ops (bool): True if only the ops nodes are wanted
otherwise all nodes are returned.
... |
Count the occurrences of operation names. | def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.topological_op_nodes():
name = node.name
if name not in op_dict:
op_dict[name] ... |
Return a dictionary of circuit properties. | def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
... |
Generate a TomographyBasis object. | def tomography_basis(basis, prep_fun=None, meas_fun=None):
"""
Generate a TomographyBasis object.
See TomographyBasis for further details.abs
Args:
prep_fun (callable) optional: the function which adds preparation
gates to a circuit.
meas_fun (callable) optional: the functi... |
Add state preparation gates to a circuit. | def __pauli_prep_gates(circuit, qreg, op):
"""
Add state preparation gates to a circuit.
"""
bas, proj = op
if bas not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"preparation")
if bas == "X":
if proj == 1:
... |
Add state measurement gates to a circuit. | def __pauli_meas_gates(circuit, qreg, op):
"""
Add state measurement gates to a circuit.
"""
if op not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"measurement")
if op == "X":
circuit.u2(0., np.pi, qreg) # H
elif ... |
Add state preparation gates to a circuit. | def __sic_prep_gates(circuit, qreg, op):
"""
Add state preparation gates to a circuit.
"""
bas, proj = op
if bas != 'S':
raise QiskitError('Not in SIC basis!')
theta = -2 * np.arctan(np.sqrt(2))
if proj == 1:
circuit.u3(theta, np.pi, 0.0, qreg)
elif proj == 2:
c... |
Generate a dictionary of tomography experiment configurations. | def tomography_set(meas_qubits,
meas_basis='Pauli',
prep_qubits=None,
prep_basis=None):
"""
Generate a dictionary of tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state ... |
Generate a dictionary of process tomography experiment configurations. | def process_tomography_set(meas_qubits, meas_basis='Pauli',
prep_qubits=None, prep_basis='SIC'):
"""
Generate a dictionary of process tomography experiment configurations.
This returns a data structure that is used by other tomography functions
to generate state and process t... |
Add tomography measurement circuits to a QuantumProgram. | def create_tomography_circuits(circuit, qreg, creg, tomoset):
"""
Add tomography measurement circuits to a QuantumProgram.
The quantum program must contain a circuit 'name', which is treated as a
state preparation circuit for state tomography, or as teh circuit being
measured for process tomography... |
Return a results dict for a state or process tomography experiment. | def tomography_data(results, name, tomoset):
"""
Return a results dict for a state or process tomography experiment.
Args:
results (Result): Results from execution of a process tomography
circuits on a backend.
name (string): The name of the circuit being reconstructed.
... |
Compute the marginal counts for a subset of measured qubits. | def marginal_counts(counts, meas_qubits):
"""
Compute the marginal counts for a subset of measured qubits.
Args:
counts (dict): the counts returned from a backend ({str: int}).
meas_qubits (list[int]): the qubits to return the marginal
counts distribution fo... |
Reconstruct a density matrix or process - matrix from tomography data. | def fit_tomography_data(tomo_data, method='wizard', options=None):
"""
Reconstruct a density matrix or process-matrix from tomography data.
If the input data is state_tomography_data the returned operator will
be a density matrix. If the input data is process_tomography_data the
returned operator w... |
Reconstruct a state from unconstrained least - squares fitting. | def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None):
"""
Reconstruct a state from unconstrained least-squares fitting.
Args:
tomo_data (list[dict]): state or process tomography data.
weights (list or array or None): weights to use for least squares
fitting. The def... |
Returns a projectors. | def __projector(op_list, basis):
"""Returns a projectors.
"""
ret = 1
# list is from qubit 0 to 1
for op in op_list:
label, eigenstate = op
ret = np.kron(basis[label][eigenstate], ret)
return ret |
Reconstruct a matrix through linear inversion. | def __tomo_linear_inv(freqs, ops, weights=None, trace=None):
"""
Reconstruct a matrix through linear inversion.
Args:
freqs (list[float]): list of observed frequences.
ops (list[np.array]): list of corresponding projectors.
weights (list[float] or array_like):
weights to... |
Returns the nearest positive semidefinite operator to an operator. | def __wizard(rho, epsilon=None):
"""
Returns the nearest positive semidefinite operator to an operator.
This method is based on reference [1]. It constrains positivity
by setting negative eigenvalues to zero and rescaling the positive
eigenvalues.
Args:
rho (array_like): the input oper... |
Create the circuits to rotate to points in phase space Args: circuit ( QuantumCircuit ): The circuit to be appended with tomography state preparation and/ or measurements. phis ( np. matrix [[ complex ]] ): phis thetas ( np. matrix [[ complex ]] ): thetas qubits ( list [ int ] ): a list of the qubit indexes of qreg to ... | def build_wigner_circuits(circuit, phis, thetas, qubits,
qreg, creg):
"""Create the circuits to rotate to points in phase space
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
... |
Get the value of the Wigner function from measurement results. | def wigner_data(q_result, meas_qubits, labels, shots=None):
"""Get the value of the Wigner function from measurement results.
Args:
q_result (Result): Results from execution of a state tomography
circuits on a backend.
meas_qubits (list[int]): a list of the qubit ind... |
Add state preparation gates to a circuit. | def prep_gate(self, circuit, qreg, op):
"""
Add state preparation gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add a preparation to.
qreg (tuple(QuantumRegister,int)): quantum register to apply
preparation to.
op (tuple(str, int)... |
Add measurement gates to a circuit. | def meas_gate(self, circuit, qreg, op):
"""
Add measurement gates to a circuit.
Args:
circuit (QuantumCircuit): circuit to add measurement to.
qreg (tuple(QuantumRegister,int)): quantum register being measured.
op (str): the basis label for the measurement.
... |
A text - based job status checker | def _text_checker(job, interval, _interval_set=False, quiet=False, output=sys.stdout):
"""A text-based job status checker
Args:
job (BaseJob): The job to check.
interval (int): The interval at which to check.
_interval_set (bool): Was interval time set by user?
quiet (bool): If ... |
Monitor the status of a IBMQJob instance. | def job_monitor(job, interval=None, monitor_async=False, quiet=False, output=sys.stdout):
"""Monitor the status of a IBMQJob instance.
Args:
job (BaseJob): Job to monitor.
interval (int): Time interval between status queries.
monitor_async (bool): Monitor asyncronously (in Jupyter only)... |
Compute Euler angles for a single - qubit gate. | def euler_angles_1q(unitary_matrix):
"""Compute Euler angles for a single-qubit gate.
Find angles (theta, phi, lambda) such that
unitary_matrix = phase * Rz(phi) * Ry(theta) * Rz(lambda)
Args:
unitary_matrix (ndarray): 2x2 unitary matrix
Returns:
tuple: (theta, phi, lambda) Euler ... |
Return the gate u1 u2 or u3 implementing U with the fewest pulses. | def simplify_U(theta, phi, lam):
"""Return the gate u1, u2, or u3 implementing U with the fewest pulses.
The returned gate implements U exactly, not up to a global phase.
Args:
theta, phi, lam: input Euler rotation angles for a general U gate
Returns:
Gate: one of IdGate, U1Gate, U2Ga... |
Decompose a two - qubit gate over SU ( 2 ) + CNOT using the KAK decomposition. | def two_qubit_kak(unitary):
"""Decompose a two-qubit gate over SU(2)+CNOT using the KAK decomposition.
Args:
unitary (Operator): a 4x4 unitary operator to decompose.
Returns:
QuantumCircuit: a circuit implementing the unitary over SU(2)+CNOT
Raises:
QiskitError: input not a un... |
Extends dag with virtual qubits that are in layout but not in the circuit yet. | def run(self, dag):
"""
Extends dag with virtual qubits that are in layout but not in the circuit yet.
Args:
dag (DAGCircuit): DAG to extend.
Returns:
DAGCircuit: An extended DAG.
Raises:
TranspilerError: If there is not layout in the proper... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.