_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q268400 | LoRange.includes | test | def includes(self, lo_freq: float) -> bool:
"""Whether `lo_freq` is within the `LoRange`.
Args:
lo_freq: LO frequency to be | python | {
"resource": ""
} |
q268401 | iplot_bloch_multivector | test | def iplot_bloch_multivector(rho, figsize=None):
""" Create a bloch sphere representation.
Graphical representation of the input array, using as much bloch
spheres as qubit are required.
Args:
rho (array): State vector or density matrix
figsize (tuple): Figure size in pixels.
"""
# HTML
html_template = Template("""
<p>
<div id="content_$divNumber" style="position: absolute; z-index: 1;">
<div id="bloch_$divNumber"></div>
</div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
data = $data;
dataValues = [];
for (var i = 0; i < data.length; i++) {
// Coordinates
var x = data[i][0];
var y = data[i][1];
var z = data[i][2];
var point = {'x': x,
'y': y,
'z': z};
dataValues.push(point);
}
require(["qVisualization"], function(qVisualizations) {
// Plot figure
qVisualizations.plotState("bloch_$divNumber",
"bloch",
dataValues,
$options);
});
</script>
""")
rho = _validate_input_state(rho)
| python | {
"resource": ""
} |
q268402 | LoConfigConverter.get_qubit_los | test | def get_qubit_los(self, user_lo_config):
"""Embed default qubit LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of qubit LOs.
Raises:
PulseError: when LO frequencies are missing.
"""
try:
_q_los | python | {
"resource": ""
} |
q268403 | LoConfigConverter.get_meas_los | test | def get_meas_los(self, user_lo_config):
"""Embed default meas LO frequencies from backend and format them to list object.
If configured lo frequency is the same as default, this method returns `None`.
Args:
user_lo_config (LoConfig): A dictionary of LOs to format.
Returns:
list: A list of meas LOs.
Raises:
PulseError: when LO frequencies are missing.
"""
try:
_m_los = self.default_meas_los.copy() | python | {
"resource": ""
} |
q268404 | Unroller.run | test | def run(self, dag):
"""Expand all op nodes to the given basis.
Args:
dag(DAGCircuit): input dag
Raises:
QiskitError: if unable to unroll given the basis due to undefined
decomposition rules (such as a bad basis) or excessive recursion.
Returns:
DAGCircuit: output unrolled dag
"""
# Walk through the DAG and expand each non-basis node
for node in dag.op_nodes():
basic_insts = ['measure', 'reset', 'barrier', 'snapshot']
if node.name in basic_insts:
# TODO: this is legacy behavior.Basis_insts should be removed that these
# instructions should be part of the device-reported basis. Currently, no
# backend reports "measure", for example.
continue
if node.name in self.basis: # If already a base, ignore.
continue
# TODO: allow choosing other possible decompositions
rule = node.op.definition
if not rule:
| python | {
"resource": ""
} |
q268405 | iplot_state_qsphere | test | def iplot_state_qsphere(rho, figsize=None):
""" Create a Q sphere representation.
Graphical representation of the input array, using a Q sphere for each
eigenvalue.
Args:
rho (array): State vector or density matrix.
figsize (tuple): Figure size in pixels.
"""
# HTML
html_template = Template("""
<p>
<div id="content_$divNumber" style="position: absolute; z-index: 1;">
<div id="qsphere_$divNumber"></div>
</div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
require(["qVisualization"], function(qVisualizations) {
data = $data;
qVisualizations.plotState("qsphere_$divNumber",
"qsphere",
data,
$options);
});
</script>
""")
rho = _validate_input_state(rho)
if figsize is None:
options = {}
else:
options = {'width': figsize[0], 'height': figsize[1]}
qspheres_data = []
# Process data and execute
num = int(np.log2(len(rho)))
# get the eigenvectors and eigenvalues
weig, stateall = linalg.eigh(rho)
for _ in range(2**num):
# start with the max
probmix = weig.max()
prob_location = weig.argmax()
if probmix > 0.001:
# print("The " + str(k) + "th eigenvalue = " + str(probmix))
# get the max eigenvalue
state = stateall[:, prob_location]
loc = np.absolute(state).argmax()
# get the element location closes to lowest bin representation.
for j in range(2**num):
test = np.absolute(np.absolute(state[j]) -
np.absolute(state[loc]))
if test < 0.001:
loc = j
break
# remove the global phase
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j*angles)
state = angleset*state
| python | {
"resource": ""
} |
q268406 | n_choose_k | test | def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
| python | {
"resource": ""
} |
q268407 | lex_index | test | def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is not equal to k
"""
| python | {
"resource": ""
} |
q268408 | plot_state_paulivec | test | def plot_state_paulivec(rho, title="", figsize=None, color=None):
"""Plot the paulivec representation of a quantum state.
Plot a bargraph of the mixed state rho over the pauli matrices
Args:
rho (ndarray): Numpy array for state vector or density matrix
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list or str): Color of the expectation value bars.
Returns:
matplotlib.Figure: The matplotlib.Figure of the visualization
Raises:
ImportError: Requires matplotlib.
"""
if not HAS_MATPLOTLIB:
raise ImportError('Must have Matplotlib installed.')
rho = _validate_input_state(rho)
if figsize is None:
| python | {
"resource": ""
} |
q268409 | get_unique_backends | test | 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:
if back.name() not in unique_names and not back.configuration().simulator:
| python | {
"resource": ""
} |
q268410 | DAGNode.op | test | 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':
| python | {
"resource": ""
} |
q268411 | constant | test | 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.
| python | {
"resource": ""
} |
q268412 | zero | test | def zero(duration: int, name: str = None) -> SamplePulse:
"""Generates zero-sampled `SamplePulse`.
Args:
duration: Duration of pulse. Must be greater than | python | {
"resource": ""
} |
q268413 | square | test | 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 greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
| python | {
"resource": ""
} |
q268414 | sawtooth | test | 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].
period: Pulse period, units of dt. If `None` defaults to | python | {
"resource": ""
} |
q268415 | triangle | test | 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 be greater than zero.
amp: Pulse amplitude. Wave range is [-amp, amp].
| python | {
"resource": ""
} |
q268416 | cos | test | 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 zero.
amp: Pulse amplitude.
| python | {
"resource": ""
} |
q268417 | sin | test | 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` defaults to single cycle.
| python | {
"resource": ""
} |
q268418 | gaussian | test | 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 function.
Integrated area under curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$
Args:
duration: Duration of pulse. Must be greater than zero.
| python | {
"resource": ""
} |
q268419 | gaussian_deriv | test | 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 than zero.
amp: Pulse | python | {
"resource": ""
} |
q268420 | gaussian_square | test | 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` sampling strategy to generate discrete pulse from continuous function.
Args:
duration: Duration of pulse. Must be greater than zero.
amp: Pulse amplitude.
sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
risefall: Number of samples over which pulse rise and fall happen. Width of
| python | {
"resource": ""
} |
q268421 | _GraphDist.dist_real | test | def dist_real(self):
"""Compute distance.
"""
x0, y0 = self.ax.transAxes.transform( # pylint: disable=invalid-name
(0, 0))
| python | {
"resource": ""
} |
q268422 | Qreg.to_string | test | def to_string(self, indent):
"""Print the node data, with indent."""
ind = indent * ' '
| python | {
"resource": ""
} |
q268423 | BasicAerProvider._get_backend_instance | test | 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.
"""
# Verify that the backend | python | {
"resource": ""
} |
q268424 | DAGCircuit.rename_register | test | 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 newname in self.cregs:
raise DAGCircuitError("duplicate register name %s" % newname)
if regname not in self.qregs and regname not in self.cregs:
raise DAGCircuitError("no register named %s" % regname)
if regname in self.qregs:
reg = self.qregs[regname]
reg.name = newname
self.qregs[newname] = reg
self.qregs.pop(regname, None)
if regname in self.cregs:
reg = self.cregs[regname]
reg.name = newname | python | {
"resource": ""
} |
q268425 | DAGCircuit.remove_all_ops_named | test | def remove_all_ops_named(self, opname):
"""Remove all operation nodes | python | {
"resource": ""
} |
q268426 | DAGCircuit.add_qreg | test | 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:
| python | {
"resource": ""
} |
q268427 | DAGCircuit.add_creg | test | 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:
| python | {
"resource": ""
} |
q268428 | DAGCircuit._add_wire | test | 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
"""
if wire not in self.wires:
self.wires.append(wire)
self._max_node_id += 1
input_map_wire = self.input_map[wire] = self._max_node_id
self._max_node_id += 1
output_map_wire = self._max_node_id
wire_name = "%s[%s]" % (wire[0].name, wire[1])
inp_node = DAGNode(data_dict={'type': 'in', 'name': wire_name, 'wire': wire},
nid=input_map_wire)
outp_node = DAGNode(data_dict={'type': 'out', 'name': wire_name, 'wire': wire},
nid=output_map_wire)
self._id_to_node[input_map_wire] = inp_node
self._id_to_node[output_map_wire] = outp_node
| python | {
"resource": ""
} |
q268429 | DAGCircuit._check_condition | test | 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 register
| python | {
"resource": ""
} |
q268430 | DAGCircuit._bits_in_condition | test | 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
| python | {
"resource": ""
} |
q268431 | DAGCircuit._add_op_node | test | 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 classical wires to attach to.
condition (tuple or None): optional condition (ClassicalRegister, int)
"""
node_properties = {
"type": "op",
"op": op,
"name": op.name,
| python | {
"resource": ""
} |
q268432 | DAGCircuit.apply_operation_back | test | 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]): cbits that op will be applied to
condition (tuple or None): optional condition (ClassicalRegister, int)
Returns:
DAGNode: the current max node
Raises:
DAGCircuitError: if a leaf node is connected to multiple outputs
"""
qargs = qargs or []
cargs = cargs or []
all_cbits = self._bits_in_condition(condition)
all_cbits.extend(cargs)
self._check_condition(op.name, condition)
| python | {
"resource": ""
} |
q268433 | DAGCircuit._check_edgemap_registers | test | 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 no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in edge_map.
Args:
edge_map (dict): map from (reg,idx) in keyregs to (reg,idx) in valregs
keyregs (dict): a map from register names to Register objects
valregs (dict): a map from register names to Register objects
valreg (bool): if False the method ignores valregs and does not
add regs for bits in the edge_map image that don't appear in valregs
Returns:
set(Register): the set of regs to add to self
Raises:
DAGCircuitError: if the wiremap fragments, or duplicates exist
"""
# FIXME: some mixing of objects | python | {
"resource": ""
} |
q268434 | DAGCircuit._check_wiremap_validity | test | 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
(register,idx) in valmap
keymap (dict): a map whose keys are wire_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid
"""
for k, v in wire_map.items():
kname = "%s[%d]" % (k[0].name, | python | {
"resource": ""
} |
q268435 | DAGCircuit._map_condition | test | 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
"""
if condition is None:
new_condition = None
else:
# Map the register name, using fact that registers must not be
| python | {
"resource": ""
} |
q268436 | DAGCircuit.extend_back | test | 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_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])
for creg in | python | {
"resource": ""
} |
q268437 | DAGCircuit.compose_back | test | 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:
input_circuit (DAGCircuit): circuit to append
edge_map (dict): map {(Register, int): (Register, int)}
from the output wires of input_circuit to input wires
of self.
Raises:
DAGCircuitError: if missing, duplicate or incosistent wire
"""
edge_map = edge_map or {}
# Check the wire map for duplicate values
if len(set(edge_map.values())) != len(edge_map):
raise DAGCircuitError("duplicates in wire_map")
add_qregs = self._check_edgemap_registers(edge_map,
input_circuit.qregs,
self.qregs)
for qreg in add_qregs:
self.add_qreg(qreg)
add_cregs = self._check_edgemap_registers(edge_map,
input_circuit.cregs,
self.cregs)
for creg in add_cregs:
self.add_creg(creg)
self._check_wiremap_validity(edge_map, input_circuit.input_map,
self.output_map)
# Compose
for nd in input_circuit.topological_nodes():
if nd.type == "in":
# if in wire_map, get new name, else use existing name
m_wire = edge_map.get(nd.wire, nd.wire)
# the | python | {
"resource": ""
} |
q268438 | DAGCircuit._check_wires_list | test | 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
in the input circuit that is replacing the node.
node (DAGNode): a node in the dag
Raises:
DAGCircuitError: if check doesn't pass.
"""
if len(set(wires)) != len(wires):
| python | {
"resource": ""
} |
q268439 | DAGCircuit._make_pred_succ_maps | test | 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 (successor)
nodes of n.
"""
pred_map = {e[2]['wire']: e[0] for e in
| python | {
"resource": ""
} |
q268440 | DAGCircuit._full_pred_succ_maps | test | 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): comes from _make_pred_succ_maps
succ_map (dict): comes from _make_pred_succ_maps
input_circuit (DAGCircuit): the input circuit
wire_map (dict): the map from wires of input_circuit to wires of self
Returns:
tuple: full_pred_map, full_succ_map (dict, dict)
Raises:
DAGCircuitError: if more than one predecessor for output nodes
"""
full_pred_map = {}
full_succ_map = {}
for w in input_circuit.input_map:
# If w is wire mapped, find the corresponding predecessor
# of the node
if w in wire_map:
full_pred_map[wire_map[w]] = pred_map[wire_map[w]]
full_succ_map[wire_map[w]] = succ_map[wire_map[w]]
| python | {
"resource": ""
} |
q268441 | DAGCircuit.topological_nodes | test | def topological_nodes(self):
"""
Yield nodes in topological order.
Returns:
generator(DAGNode): node in topological order
"""
| python | {
"resource": ""
} |
q268442 | DAGCircuit.edges | test | def edges(self, nodes=None):
"""Iterator for node values.
Yield:
node: the node.
"""
for | python | {
"resource": ""
} |
q268443 | DAGCircuit.op_nodes | test | 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.
""" | python | {
"resource": ""
} |
q268444 | DAGCircuit.gate_nodes | test | 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():
| python | {
"resource": ""
} |
q268445 | DAGCircuit.named_nodes | test | def named_nodes(self, *names):
"""Get the set of "op" nodes with the given name."""
named_nodes = []
for node in self._multi_graph.nodes():
| python | {
"resource": ""
} |
q268446 | DAGCircuit.twoQ_gates | test | def twoQ_gates(self):
"""Get list of 2-qubit gates. Ignore snapshot, barriers, and the like."""
| python | {
"resource": ""
} |
q268447 | DAGCircuit.predecessors | test | 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 | python | {
"resource": ""
} |
q268448 | DAGCircuit.quantum_predecessors | test | 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):
| python | {
"resource": ""
} |
q268449 | DAGCircuit.ancestors | test | 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 | python | {
"resource": ""
} |
q268450 | DAGCircuit.quantum_successors | test | 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',
DeprecationWarning, 2)
node = self._id_to_node[node]
successors = []
| python | {
"resource": ""
} |
q268451 | DAGCircuit.remove_op_node | test | 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',
DeprecationWarning, 2)
node = self._id_to_node[node]
if node.type != 'op':
raise DAGCircuitError('The method remove_op_node only works on op node types. An "%s" '
'node | python | {
"resource": ""
} |
q268452 | DAGCircuit.remove_ancestors_of | test | 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',
| python | {
"resource": ""
} |
q268453 | DAGCircuit.remove_descendants_of | test | 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',
DeprecationWarning, 2)
node = | python | {
"resource": ""
} |
q268454 | DAGCircuit.remove_nonancestors_of | test | 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',
DeprecationWarning, 2)
node = | python | {
"resource": ""
} |
q268455 | DAGCircuit.remove_nondescendants_of | test | 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',
DeprecationWarning, 2)
node = | python | {
"resource": ""
} |
q268456 | DAGCircuit.layers | test | 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 the
earliest layer at index 0. The layers are constructed using a
greedy algorithm. Each returned layer is a dict containing
{"graph": circuit graph, "partition": list of qubit lists}.
TODO: Gates that use the same cbits will end up in different
layers as this is currently implemented. This may not be
the desired behavior.
"""
graph_layers = self.multigraph_layers()
try:
next(graph_layers) # Remove input nodes
except StopIteration:
return
def add_nodes_from(layer, nodes):
""" Convert DAGNodes into a format that can be added to a
multigraph and then add to graph"""
layer._multi_graph.add_nodes_from(nodes)
for graph_layer in graph_layers:
# Get the op nodes from the layer, removing any input and output nodes.
op_nodes = [node for node in graph_layer if node.type == "op"]
# Stop yielding once there are no more op_nodes in a layer.
if not op_nodes:
return
# Construct a shallow copy of self
new_layer = DAGCircuit()
new_layer.name = self.name
for creg in self.cregs.values():
new_layer.add_creg(creg)
for qreg in self.qregs.values():
new_layer.add_qreg(qreg)
add_nodes_from(new_layer, self.input_map.values())
add_nodes_from(new_layer, self.output_map.values())
add_nodes_from(new_layer, op_nodes)
# The quantum registers that have an operation in this layer.
support_list = [
| python | {
"resource": ""
} |
q268457 | DAGCircuit.serial_layers | test | 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 self.qregs.values():
new_layer.add_qreg(qreg)
for creg in self.cregs.values():
new_layer.add_creg(creg)
# Save the support of the operation we add to the | python | {
"resource": ""
} |
q268458 | DAGCircuit.multigraph_layers | test | 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:
# Count multiedges with multiplicity.
for successor in self._multi_graph.successors(node):
| python | {
"resource": ""
} |
q268459 | DAGCircuit.collect_runs | test | 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 instead the cx nodes were
"cx q[0],q[1]; cx q[1],q[0];", the method would still return the
pair in a tuple. The namelist can contain names that are not
in the circuit's basis.
Nodes must have only one successor to continue the run.
"""
group_list = []
# Iterate through the nodes of self in topological order
# and form tuples containing sequences of gates
# on the same qubit(s).
topo_ops = list(self.topological_op_nodes())
nodes_seen = dict(zip(topo_ops, [False] * len(topo_ops)))
for node in topo_ops:
if node.name in namelist and node.condition is None \
and not nodes_seen[node]:
group = [node]
| python | {
"resource": ""
} |
q268460 | DAGCircuit.nodes_on_wire | test | 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.
Yield:
DAGNode: the successive ops on the given wire
Raises:
DAGCircuitError: if the given wire doesn't exist in the DAG
"""
current_node = self.input_map.get(wire, None)
if not current_node:
raise DAGCircuitError('The given wire %s is not present in the circuit'
% str(wire))
more_nodes = True
while more_nodes:
more_nodes = False
# allow user to just get ops on the wire - not the input/output nodes
| python | {
"resource": ""
} |
q268461 | DAGCircuit.count_ops | test | 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
| python | {
"resource": ""
} |
q268462 | DAGCircuit.properties | test | def properties(self):
"""Return a dictionary of circuit properties."""
summary = {"size": self.size(),
"depth": self.depth(),
"width": self.width(),
| python | {
"resource": ""
} |
q268463 | tomography_basis | test | 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 function which adds measurement
| python | {
"resource": ""
} |
q268464 | __pauli_meas_gates | test | 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 "
| python | {
"resource": ""
} |
q268465 | tomography_set | test | 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 and process tomography circuits, and extract tomography
data from results after execution on a backend.
Quantum State Tomography:
Be default it will return a set for performing Quantum State
Tomography where individual qubits are measured in the Pauli basis.
A custom measurement basis may also be used by defining a user
`tomography_basis` and passing this in for the `meas_basis` argument.
Quantum Process Tomography:
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
meas_qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
prep_qubits (list or None): The qubits being prepared. If None then
meas_qubits will be used for process tomography experiments.
prep_basis (tomography_basis or None): The optional qubit preparation
basis. If no basis is specified state tomography will be performed
instead of process tomography. A built in basis may be specified by
'SIC' or 'Pauli' (SIC basis recommended for > 2 qubits).
Returns:
dict: A dict of tomography configurations that can be parsed by
`create_tomography_circuits` and `tomography_data` functions
for implementing quantum tomography experiments. This output contains
fields "qubits", "meas_basis", "circuits". It may also optionally
contain a field "prep_basis" for process tomography experiments.
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
# optionally for process tomography experiments:
'prep_basis': prep_basis (tomography_basis)
}
```
Raises:
QiskitError: if the Qubits argument is not a list.
"""
if not isinstance(meas_qubits, list):
raise QiskitError('Qubits argument must be a list')
num_of_qubits = len(meas_qubits)
if prep_qubits is None:
prep_qubits = meas_qubits
| python | {
"resource": ""
} |
q268466 | process_tomography_set | test | 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 tomography circuits, and extract tomography
data from results after execution on a backend.
A quantum process tomography set is created by specifying a preparation
basis along with a measurement basis. The preparation basis may be a
user defined `tomography_basis`, or one of the two built in basis 'SIC'
or 'Pauli'.
- SIC: Is a minimal symmetric informationally complete preparation
basis for 4 states for each qubit (4 ^ number of qubits total
preparation states). These correspond to the |0> state and the 3
other vertices of a tetrahedron on the Bloch-sphere.
- Pauli: Is a tomographically overcomplete preparation basis of the six
eigenstates of the 3 Pauli operators (6 ^ number of qubits
total preparation states).
Args:
meas_qubits (list): The qubits being measured.
meas_basis (tomography_basis or str): The qubit measurement basis.
The default value is 'Pauli'.
prep_qubits (list or None): The qubits being prepared. If None then
meas_qubits will be used for process tomography | python | {
"resource": ""
} |
q268467 | create_tomography_circuits | test | 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. This function then appends the circuit
with a set of measurements specified by the input `tomography_set`,
optionally it also prepends the circuit with state preparation circuits if
they are specified in the `tomography_set`.
For n-qubit tomography with a tomographically complete set of preparations
and measurements this results in $4^n 3^n$ circuits being added to the
quantum program.
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
qreg (QuantumRegister): the quantum register containing qubits to be
measured.
creg (ClassicalRegister): the classical register containing bits to
store measurement outcomes.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of quantum tomography circuits for the input circuit.
Raises:
QiskitError: if circuit is not a valid QuantumCircuit
Example:
| python | {
"resource": ""
} |
q268468 | tomography_data | test | 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.
tomoset (tomography_set): the dict of tomography configurations.
Returns:
list: A list of dicts for the outcome of each process tomography
measurement circuit.
"""
labels = tomography_circuit_names(tomoset, name)
circuits = tomoset['circuits']
data = []
prep = None
for j, _ in enumerate(labels):
counts = marginal_counts(results.get_counts(labels[j]),
tomoset['qubits'])
shots = sum(counts.values())
meas = circuits[j]['meas']
prep = circuits[j].get('prep', None)
meas_qubits = sorted(meas.keys())
if prep:
prep_qubits = sorted(prep.keys())
circuit = {}
for c in counts.keys():
| python | {
"resource": ""
} |
q268469 | marginal_counts | test | 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 for.
Returns:
dict: A counts dict for the meas_qubits.abs
Example: if `counts = {'00': 10, '01': 5}`
`marginal_counts(counts, [0])` returns `{'0': 15, '1': 0}`.
`marginal_counts(counts, [0])` returns `{'0': 10, '1': 5}`.
"""
# pylint: disable=cell-var-from-loop
# Extract total number of qubits from count keys
num_of_qubits = len(list(counts.keys())[0])
# keys for measured qubits only
qs = sorted(meas_qubits, reverse=True)
meas_keys = count_keys(len(qs))
# get regex match | python | {
"resource": ""
} |
q268470 | fit_tomography_data | test | 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 will be a Choi-matrix in the column-vectorization
convention.
Args:
tomo_data (dict): process tomography measurement data.
method (str): the fitting method to use.
Available methods:
- 'wizard' (default)
- 'leastsq'
options (dict or None): additional options for fitting method.
Returns:
numpy.array: The fitted operator.
Available methods:
- 'wizard' (Default): The returned operator will be constrained to be
positive-semidefinite.
Options:
- 'trace': the trace of the returned operator.
The default value is 1.
- 'beta': hedging parameter for computing frequencies from
zero-count data. The default value is 0.50922.
- 'epsilon: threshold for truncating small | python | {
"resource": ""
} |
q268471 | __leastsq_fit | test | 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 default is standard deviation from a binomial
distribution.
trace (float or None): trace of returned operator. The default is 1.
beta (float or None): hedge parameter (>=0) for computing frequencies
from zero-count data. The default value is 0.50922.
Returns:
numpy.array: A numpy array of the reconstructed operator.
"""
if trace is None:
trace = 1. # default to unit trace
data = tomo_data['data']
keys = data[0]['circuit'].keys()
# Get counts and shots
counts = []
shots = []
ops = []
for dat in data:
for key in keys:
counts.append(dat['counts'][key])
shots.append(dat['shots'])
projectors = dat['circuit'][key]
op = __projector(projectors['meas'], tomo_data['meas_basis'])
if 'prep' in projectors:
| python | {
"resource": ""
} |
q268472 | __projector | test | def __projector(op_list, basis):
"""Returns a projectors.
"""
ret = 1
# list is from qubit 0 to 1
for op in op_list:
| python | {
"resource": ""
} |
q268473 | __tomo_linear_inv | test | 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 be used for weighted fitting.
trace (float or None): trace of returned operator.
Returns:
numpy.array: A numpy array of the reconstructed operator.
"""
# get weights matrix | python | {
"resource": ""
} |
q268474 | __wizard | test | 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 operator.
epsilon(float or None): threshold (>=0) for truncating small
eigenvalues values to zero.
Returns:
numpy.array: A positive semidefinite numpy array.
"""
if epsilon is None:
epsilon = 0. # default value
dim = len(rho)
rho_wizard = np.zeros([dim, dim])
v, w = np.linalg.eigh(rho) | python | {
"resource": ""
} |
q268475 | wigner_data | test | 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 indexes measured.
labels (list[str]): a list of names of the circuits
shots (int): number of shots
Returns:
list: The values of the Wigner function at measured points in
phase space
"""
num = len(meas_qubits)
dim = 2**num
p = [0.5 + 0.5 * np.sqrt(3), 0.5 - 0.5 * np.sqrt(3)]
parity = 1
for i in range(num):
| python | {
"resource": ""
} |
q268476 | TomographyBasis.meas_gate | test | 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 | python | {
"resource": ""
} |
q268477 | _text_checker | test | 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 True, do not print status messages.
output (file): The file like object to write status messages to.
By default this is sys.stdout.
"""
status = job.status()
msg = status.value
prev_msg = msg
msg_len = len(msg)
if not quiet:
print('\r%s: %s' % ('Job Status', msg), end='', file=output)
while status.name not in ['DONE', 'CANCELLED', 'ERROR']:
time.sleep(interval)
status = job.status()
msg = status.value
if status.name == 'QUEUED':
msg += ' (%s)' % job.queue_position()
if not _interval_set:
interval = max(job.queue_position(), 2)
else:
if | python | {
"resource": ""
} |
q268478 | job_monitor | test | 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).
quiet (bool): If True, do not print status messages.
output (file): The file like object to write status messages to.
By default this is sys.stdout.
Raises:
QiskitError: When trying to run async outside of Jupyter
ImportError: ipywidgets not available for notebook.
"""
if interval is None:
_interval_set = False
interval = 2
else:
_interval_set = True
if _NOTEBOOK_ENV:
if monitor_async:
try:
import ipywidgets as widgets # pylint: disable=import-error
except ImportError:
raise ImportError('These functions need ipywidgets. '
'Run "pip install ipywidgets" before.')
from qiskit.tools.jupyter.jupyter_magics import _html_checker # pylint: disable=C0412
| python | {
"resource": ""
} |
q268479 | euler_angles_1q | test | 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 angles of SU(2)
Raises:
QiskitError: if unitary_matrix not 2x2, or failure
"""
if unitary_matrix.shape != (2, 2):
raise QiskitError("euler_angles_1q: expected 2x2 matrix")
phase = la.det(unitary_matrix)**(-1.0/2.0)
U = phase * unitary_matrix # U in SU(2)
# OpenQASM SU(2) parameterization:
# U[0, 0] = exp(-i(phi+lambda)/2) * cos(theta/2)
# U[0, 1] = -exp(-i(phi-lambda)/2) * sin(theta/2)
# U[1, 0] = exp(i(phi-lambda)/2) * sin(theta/2)
# U[1, 1] = exp(i(phi+lambda)/2) * cos(theta/2)
# Find theta
if abs(U[0, 0]) > _CUTOFF_PRECISION:
theta = 2 * math.acos(abs(U[0, 0]))
else:
theta = 2 * math.asin(abs(U[1, 0]))
# Find phi and lambda
phase11 = 0.0
phase10 = 0.0
if abs(math.cos(theta/2.0)) > _CUTOFF_PRECISION:
phase11 = U[1, 1] / math.cos(theta/2.0)
if abs(math.sin(theta/2.0)) > _CUTOFF_PRECISION:
phase10 = U[1, 0] / math.sin(theta/2.0)
phiplambda = 2 * math.atan2(np.imag(phase11), np.real(phase11))
phimlambda = 2 * math.atan2(np.imag(phase10), np.real(phase10))
phi = 0.0
if abs(U[0, 0]) > _CUTOFF_PRECISION and abs(U[1, 0]) > _CUTOFF_PRECISION:
phi = (phiplambda | python | {
"resource": ""
} |
q268480 | simplify_U | test | 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, U2Gate, U3Gate.
"""
gate = U3Gate(theta, phi, lam)
# Y rotation is 0 mod 2*pi, so the gate is a u1
if abs(gate.params[0] % (2.0 * math.pi)) < _CUTOFF_PRECISION:
gate = U1Gate(gate.params[0] + gate.params[1] + gate.params[2])
# Y | python | {
"resource": ""
} |
q268481 | EnlargeWithAncilla.run | test | 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 property set or not set at init time.
"""
self.layout = self.layout or self.property_set['layout']
if self.layout is None:
raise TranspilerError("EnlargeWithAncilla requires property_set[\"layout\"] or"
| python | {
"resource": ""
} |
q268482 | qubits_tab | test | def qubits_tab(backend):
"""The qubits properties widget
Args:
backend (IBMQbackend): The backend.
Returns:
VBox: A VBox widget.
"""
props = backend.properties().to_dict()
header_html = "<div><font style='font-weight:bold'>{key}</font>: {value}</div>"
header_html = header_html.format(key='last_update_date',
value=props['last_update_date'])
update_date_widget = widgets.HTML(value=header_html)
qubit_html = "<table>"
qubit_html += """<style>
table {
border-collapse: collapse;
width: auto;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even) {background-color: #f6f6f6;}
</style>"""
qubit_html += "<tr><th></th><th>Frequency</th><th>T1</th><th>T2</th>"
qubit_html += "<th>U1 gate error</th><th>U2 gate error</th><th>U3 gate error</th>"
qubit_html += "<th>Readout error</th></tr>"
qubit_footer = "</table>"
for qub in range(len(props['qubits'])):
name = 'Q%s' % qub
qubit_data = props['qubits'][qub]
gate_data = props['gates'][3*qub:3*qub+3]
t1_info = qubit_data[0]
t2_info = qubit_data[1]
freq_info = qubit_data[2]
readout_info = qubit_data[3]
freq = str(round(freq_info['value'], 5))+' '+freq_info['unit']
T1 = str(round(t1_info['value'], # pylint: disable=invalid-name
5))+' ' + t1_info['unit']
| python | {
"resource": ""
} |
q268483 | job_history | test | def job_history(backend):
"""Widget for displaying job history
Args:
backend (IBMQbackend): The backend.
Returns:
Tab: A tab widget for history images.
"""
year = widgets.Output(layout=widgets.Layout(display='flex-inline',
align_items='center',
min_height='400px'))
month = widgets.Output(layout=widgets.Layout(display='flex-inline',
align_items='center',
min_height='400px'))
week = widgets.Output(layout=widgets.Layout(display='flex-inline',
| python | {
"resource": ""
} |
q268484 | plot_job_history | test | def plot_job_history(jobs, interval='year'):
"""Plots the job history of the user from the given list of jobs.
Args:
jobs (list): A list of jobs with type IBMQjob.
interval (str): Interval over which to examine.
Returns:
fig: A Matplotlib figure instance.
"""
def get_date(job):
"""Returns a datetime object from a IBMQJob instance.
Args:
job (IBMQJob): A job.
Returns:
dt: A datetime object.
"""
return datetime.datetime.strptime(job.creation_date(),
'%Y-%m-%dT%H:%M:%S.%fZ')
current_time = datetime.datetime.now()
if interval == 'year':
bins = [(current_time - datetime.timedelta(days=k*365/12))
for k in range(12)]
elif interval == 'month':
bins = [(current_time - datetime.timedelta(days=k)) for k in range(30)]
elif interval == 'week':
bins = [(current_time - datetime.timedelta(days=k)) for k in range(7)]
binned_jobs = [0]*len(bins)
if interval == 'year':
for job in jobs:
for ind, dat in enumerate(bins):
date = get_date(job)
if date.month == dat.month:
binned_jobs[ind] += 1
break
else:
continue
else:
for job in jobs:
for ind, dat in enumerate(bins):
date = get_date(job)
if date.day == dat.day and date.month == dat.month:
binned_jobs[ind] += 1
break
else:
| python | {
"resource": ""
} |
q268485 | SamplePulse.draw | test | def draw(self, **kwargs):
"""Plot the interpolated envelope of pulse.
Keyword Args:
dt (float): Time interval of samples.
interp_method (str): Method of interpolation
(set `None` for turn off the interpolation).
filename (str): Name required to save pulse image.
interactive (bool): When set true show the circuit in a new window
(this depends on the matplotlib backend being used supporting this).
dpi (int): Resolution of saved image.
| python | {
"resource": ""
} |
q268486 | cu3 | test | def cu3(self, theta, phi, lam, ctl, tgt):
"""Apply cu3 from ctl to tgt with angle theta, phi, lam."""
| python | {
"resource": ""
} |
q268487 | build_bell_circuit | test | def build_bell_circuit():
"""Returns a circuit putting 2 qubits in the Bell state."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
| python | {
"resource": ""
} |
q268488 | transpile | test | def transpile(circuits,
backend=None,
basis_gates=None, coupling_map=None, backend_properties=None,
initial_layout=None, seed_transpiler=None,
optimization_level=None,
pass_manager=None,
seed_mapper=None): # deprecated
"""transpile one or more circuits, according to some desired
transpilation targets.
All arguments may be given as either singleton or list. In case of list,
the length must be equal to the number of circuits being transpiled.
Transpilation is done in parallel using multiprocessing.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]):
Circuit(s) to transpile
backend (BaseBackend):
If set, transpiler options are automatically grabbed from
backend.configuration() and backend.properties().
If any other option is explicitly set (e.g. coupling_map), it
will override the backend's.
Note: the backend arg is purely for convenience. The resulting
circuit may be run on any backend as long as it is compatible.
basis_gates (list[str]):
List of basis gate names to unroll to.
e.g:
['u1', 'u2', 'u3', 'cx']
If None, do not unroll.
coupling_map (CouplingMap or list):
Coupling map (perhaps custom) to target in mapping.
Multiple formats are supported:
a. CouplingMap instance
b. list
Must be given as an adjacency matrix, where each entry
specifies all two-qubit interactions supported by backend
e.g:
[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]
backend_properties (BackendProperties):
properties returned by a backend, including information on gate
errors, readout errors, qubit coherence times, etc. For a backend
that provides this information, it can be obtained with:
``backend.properties()``
initial_layout (Layout or dict or list):
Initial position of virtual qubits on physical qubits.
If this layout makes the circuit compatible with the coupling_map
constraints, it will be used.
The final layout is not guaranteed to be the same, as the transpiler
may permute qubits through swaps or other means.
Multiple formats are supported:
a. Layout instance
b. dict
virtual to physical:
{qr[0]: 0,
qr[1]: 3,
qr[2]: 5}
physical to virtual:
{0: qr[0],
3: qr[1],
5: qr[2]}
c. list
virtual to physical:
[0, 3, 5] # virtual qubits are ordered (in addition to named)
physical to virtual:
[qr[0], None, None, qr[1], None, qr[2]]
seed_transpiler (int):
sets random seed for the stochastic parts of the transpiler
optimization_level (int):
How much optimization to perform on the circuits.
Higher levels generate more optimized circuits,
at the expense of longer transpilation time.
0: no optimization
1: light optimization
| python | {
"resource": ""
} |
q268489 | _transpile_circuit | test | def _transpile_circuit(circuit_config_tuple):
"""Select a PassManager and run a single circuit through it.
Args:
circuit_config_tuple (tuple):
circuit (QuantumCircuit): circuit to transpile
transpile_config (TranspileConfig): configuration dictating how to transpile
Returns:
QuantumCircuit: transpiled circuit
"""
circuit, transpile_config = circuit_config_tuple
# if the pass manager is not already selected, choose an appropriate one.
if transpile_config.pass_manager:
pass_manager = transpile_config.pass_manager
elif transpile_config.coupling_map:
pass_manager = default_pass_manager(transpile_config.basis_gates,
| python | {
"resource": ""
} |
q268490 | execute | test | def execute(experiments, backend,
basis_gates=None, coupling_map=None, # circuit transpile options
backend_properties=None, initial_layout=None,
seed_transpiler=None, optimization_level=None, pass_manager=None,
qobj_id=None, qobj_header=None, shots=1024, # common run options
memory=False, max_credits=10, seed_simulator=None,
default_qubit_los=None, default_meas_los=None, # schedule run options
schedule_los=None, meas_level=2, meas_return='avg',
memory_slots=None, memory_slot_size=100, rep_time=None, parameter_binds=None,
seed=None, seed_mapper=None, # deprecated
config=None, circuits=None,
**run_config):
"""Execute a list of circuits or pulse schedules on a backend.
The execution is asynchronous, and a handle to a job instance is returned.
Args:
experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]):
Circuit(s) or pulse schedule(s) to execute
backend (BaseBackend):
Backend to execute circuits on.
Transpiler options are automatically grabbed from
backend.configuration() and backend.properties().
If any other option is explicitly set (e.g. coupling_map), it
will override the backend's.
basis_gates (list[str]):
List of basis gate names to unroll to.
e.g:
['u1', 'u2', 'u3', 'cx']
If None, do not unroll.
coupling_map (CouplingMap or list):
Coupling map (perhaps custom) to target in mapping.
Multiple formats are supported:
a. CouplingMap instance
b. list
Must be given as an adjacency matrix, where each entry
specifies all two-qubit interactions supported by backend
e.g:
[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]
backend_properties (BackendProperties):
Properties returned by a backend, including information on gate
errors, readout errors, qubit coherence times, etc. For a backend
that provides this information, it can be obtained with:
``backend.properties()``
initial_layout (Layout or dict or list):
Initial position of virtual qubits on physical qubits.
If this layout makes the circuit compatible with the coupling_map
constraints, it will be used.
The final layout is not guaranteed to be the same, as the transpiler
may permute qubits through swaps or other means.
Multiple formats are supported:
a. Layout instance
b. dict
virtual to physical:
{qr[0]: 0,
qr[1]: 3,
qr[2]: 5}
physical to virtual:
{0: qr[0],
3: qr[1],
5: qr[2]}
c. list
virtual to physical:
[0, 3, 5] # virtual qubits are ordered (in addition to named)
physical to virtual:
[qr[0], None, None, qr[1], None, qr[2]]
seed_transpiler (int):
Sets random seed for the stochastic parts of the transpiler
optimization_level (int):
How much optimization to perform on the circuits.
Higher levels generate more optimized circuits,
at the expense of longer transpilation time.
0: no optimization
1: light optimization
2: heavy optimization
pass_manager (PassManager):
The pass manager to use during transpilation. If this arg is present,
auto-selection of pass manager based on the transpile options will be
turned off and this pass manager will be used directly.
qobj_id (str):
String identifier to annotate the Qobj
qobj_header (QobjHeader or dict):
User input that will be inserted in Qobj header, and will also be
copied to the corresponding Result header. Headers do not affect the run.
shots (int):
Number of repetitions of each circuit, for sampling. Default: 2014
memory (bool):
If True, per-shot measurement bitstrings are returned as well
(provided the backend supports it). For OpenPulse jobs, only
measurement level 2 supports this option. Default: False
max_credits (int):
Maximum credits to spend on job. Default: 10
seed_simulator (int):
Random seed to control sampling, for when backend is a simulator
default_qubit_los (list):
List of default qubit lo frequencies
default_meas_los (list):
List of default meas lo frequencies
schedule_los (None or list[Union[Dict[PulseChannel, float], LoConfig]] or
Union[Dict[PulseChannel, float], LoConfig]):
Experiment LO configurations
meas_level (int):
Set the appropriate level of the measurement output for pulse experiments.
meas_return (str):
Level of measurement data for the backend to return
For `meas_level` 0 and 1:
"single" returns information from every shot.
"avg" returns average measurement output (averaged over number of shots).
| python | {
"resource": ""
} |
q268491 | Qubit.drive | test | def drive(self) -> DriveChannel:
"""Return the primary drive channel of this qubit."""
| python | {
"resource": ""
} |
q268492 | Qubit.control | test | def control(self) -> ControlChannel:
"""Return the primary control channel of this qubit."""
| python | {
"resource": ""
} |
q268493 | Qubit.measure | test | def measure(self) -> MeasureChannel:
"""Return the primary measure channel of this qubit."""
| python | {
"resource": ""
} |
q268494 | Qubit.acquire | test | def acquire(self) -> AcquireChannel:
"""Return the primary acquire channel of this qubit."""
| python | {
"resource": ""
} |
q268495 | input_state | test | def input_state(circ, q, n):
"""n-qubit input state for QFT that produces output 1."""
for j in range(n):
| python | {
"resource": ""
} |
q268496 | assemble | test | def assemble(experiments,
backend=None,
qobj_id=None, qobj_header=None, # common run options
shots=1024, memory=False, max_credits=None, seed_simulator=None,
default_qubit_los=None, default_meas_los=None, # schedule run options
schedule_los=None, meas_level=2, meas_return='avg',
memory_slots=None, memory_slot_size=100, rep_time=None, parameter_binds=None,
config=None, seed=None, # deprecated
**run_config):
"""Assemble a list of circuits or pulse schedules into a Qobj.
This function serializes the payloads, which could be either circuits or schedules,
to create Qobj "experiments". It further annotates the experiment payload with
header and configurations.
Args:
experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]):
Circuit(s) or pulse schedule(s) to execute
backend (BaseBackend):
If set, some runtime options are automatically grabbed from
backend.configuration() and backend.defaults().
If any other option is explicitly set (e.g. rep_rate), it
will override the backend's.
If any other options is set in the run_config, it will
also override the backend's.
qobj_id (str):
String identifier to annotate the Qobj
qobj_header (QobjHeader or dict):
User input that will be inserted in Qobj header, and will also be
copied to the corresponding Result header. Headers do not affect the run.
shots (int):
Number of repetitions of each circuit, for sampling. Default: 2014
memory (bool):
If True, per-shot measurement bitstrings are returned as well
(provided the backend supports it). For OpenPulse jobs, only
measurement level 2 supports this option. Default: False
max_credits (int):
Maximum credits to spend on job. Default: 10
seed_simulator (int):
Random seed to control sampling, for when backend is a simulator
default_qubit_los (list):
List of default qubit lo frequencies
default_meas_los (list):
List of default meas lo frequencies
schedule_los (None or list[Union[Dict[PulseChannel, float], LoConfig]] or
Union[Dict[PulseChannel, float], LoConfig]):
Experiment LO configurations
meas_level (int):
Set the appropriate level of the measurement output for pulse experiments.
meas_return (str):
Level of measurement data for the backend to return
For `meas_level` 0 and 1:
"single" returns information from every shot.
"avg" returns average measurement output (averaged over number of shots).
memory_slots (int):
Number of classical memory slots used in this job.
memory_slot_size (int):
Size of each memory slot if the output is Level 0.
rep_time (int): repetition time of the experiment in μs.
The delay between experiments will be rep_time.
Must be from the list provided by the device.
parameter_binds (list[dict{Parameter: Value}]):
List of Parameter bindings over which the set of experiments will be
executed. Each list element (bind) should be of the form
{Parameter1: value1, Parameter2: value2, ...}. All binds will be
executed across all experiments, e.g. if parameter_binds is a
length-n list, and there are m experiments, a total of m x n
experiments will be run (one for each experiment/bind pair).
seed (int):
DEPRECATED in 0.8: use ``seed_simulator`` kwarg instead
config (dict):
DEPRECATED in 0.8: use run_config instead
run_config (dict):
extra arguments used to configure the run (e.g. for Aer configurable backends)
Refer to the backend documentation for details on these arguments
Returns:
Qobj: a qobj which can be run on a backend. Depending on the type of input,
this will be either a QasmQobj or a PulseQobj.
Raises:
QiskitError: if the input cannot be interpreted as either circuits or schedules
"""
# deprecation matter
| python | {
"resource": ""
} |
q268497 | unset_qiskit_logger | test | def unset_qiskit_logger():
"""Remove the handlers for the 'qiskit' logger."""
qiskit_logger = logging.getLogger('qiskit')
for handler in | python | {
"resource": ""
} |
q268498 | iplot_state_hinton | test | def iplot_state_hinton(rho, figsize=None):
""" Create a hinton representation.
Graphical representation of the input array using a 2D city style
graph (hinton).
Args:
rho (array): Density matrix
figsize (tuple): Figure size in pixels.
"""
# HTML
html_template = Template("""
<p>
<div id="hinton_$divNumber"></div>
</p>
""")
# JavaScript
javascript_template = Template("""
<script>
requirejs.config({
paths: {
qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
}
});
require(["qVisualization"], function(qVisualizations) {
qVisualizations.plotState("hinton_$divNumber",
"hinton",
$executions,
$options);
});
</script>
""")
rho = _validate_input_state(rho)
| python | {
"resource": ""
} |
q268499 | process_fidelity | test | def process_fidelity(channel1, channel2, require_cptp=True):
"""Return the process fidelity between two quantum channels.
This is given by
F_p(E1, E2) = Tr[S2^dagger.S1])/dim^2
where S1 and S2 are the SuperOp matrices for channels E1 and E2,
and dim is the dimension of the input output statespace.
Args:
channel1 (QuantumChannel or matrix): a quantum channel or unitary matrix.
channel2 (QuantumChannel or matrix): a quantum channel or unitary matrix.
require_cptp (bool): require input channels to be CPTP [Default: True].
Returns:
array_like: The state fidelity F(state1, state2).
Raises:
QiskitError: if inputs channels do not have the same dimensions,
have different input and output dimensions, or are not CPTP with
`require_cptp=True`.
"""
# First we must determine if input is to be interpreted as a unitary matrix
# or as a channel.
# If input is a raw numpy array we will interpret it as a unitary matrix.
is_cptp1 = None
is_cptp2 = None
if isinstance(channel1, (list, np.ndarray)):
channel1 = Operator(channel1)
if require_cptp:
is_cptp1 = channel1.is_unitary()
if isinstance(channel2, (list, np.ndarray)):
channel2 = Operator(channel2)
if require_cptp:
is_cptp2 = channel2.is_unitary()
# Next we convert inputs SuperOp objects
# This works for objects that also have a `to_operator` or `to_channel` method
s1 = SuperOp(channel1) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.