_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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 checked
Returns:
bool: True if lo_freq is included in this range, otherwise False
"""
if self._lb <= lo_freq <= self._ub:
return True
return False | 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)
if figsize is None:
options = {}
else:
options = {'width': figsize[0], 'height': figsize[1]}
# Process data and execute
num = int(np.log2(len(rho)))
bloch_data = []
for i in range(num):
pauli_singles = [Pauli.pauli_single(num, i, 'X'), Pauli.pauli_single(num, i, 'Y'),
Pauli.pauli_single(num, i, 'Z')]
bloch_state = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_singles))
bloch_data.append(bloch_state)
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'data': bloch_data,
'divNumber': div_number,
'options': options
})
display(HTML(html + javascript)) | 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 = self.default_qubit_los.copy()
except KeyError:
raise PulseError('Qubit default frequencies not exist.')
for channel, lo_freq in user_lo_config.qubit_lo_dict().items():
_q_los[channel.index] = lo_freq
if _q_los == self.default_qubit_los:
return None
return _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()
except KeyError:
raise PulseError('Default measurement frequencies not exist.')
for channel, lo_freq in user_lo_config.meas_lo_dict().items():
_m_los[channel.index] = lo_freq
if _m_los == self.default_meas_los:
return None
return _m_los | 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:
raise QiskitError("Cannot unroll the circuit to the given basis, %s. "
"No rule to expand instruction %s." %
(str(self.basis), node.op.name))
# hacky way to build a dag on the same register as the rule is defined
# TODO: need anonymous rules to address wires by index
decomposition = DAGCircuit()
decomposition.add_qreg(rule[0][1][0][0])
for inst in rule:
decomposition.apply_operation_back(*inst)
unrolled_dag = self.run(decomposition) # recursively unroll ops
dag.substitute_node_with_dag(node, unrolled_dag)
return dag | 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
state.flatten()
spherepoints = []
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
number_of_divisions = n_choose_k(num, weight)
weight_order = bit_string_index(element)
angle = weight_order * 2 * np.pi / number_of_divisions
zvalue = -2 * weight / num + 1
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
angles = (np.angle(state[i]) + 2 * np.pi) % (2 * np.pi)
qpoint = {
'x': xvalue,
'y': yvalue,
'z': zvalue,
'prob': prob,
'phase': angles
}
spherepoints.append(qpoint)
# Associate all points to one sphere
sphere = {
'points': spherepoints,
'eigenvalue': probmix
}
# Add sphere to the spheres array
qspheres_data.append(sphere)
weig[prob_location] = 0
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'data': qspheres_data,
'divNumber': div_number,
'options': options
})
display(HTML(html + javascript)) | 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:
return 0
return reduce(lambda x, y: x * y[0] / y[1],
zip(range(n - k + 1, n + 1),
range(1, k + 1)), 1) | 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
"""
if len(lst) != k:
raise VisualizationError("list should have length k")
comb = list(map(lambda x: n - 1 - x, lst))
dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])
return int(dualm) | 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:
figsize = (7, 5)
num = int(np.log2(len(rho)))
labels = list(map(lambda x: x.to_label(), pauli_group(num)))
values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
pauli_group(num)))
numelem = len(values)
if color is None:
color = "#648fff"
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
fig, ax = plt.subplots(figsize=figsize)
ax.grid(zorder=0, linewidth=1, linestyle='--')
ax.bar(ind, values, width, color=color, zorder=2)
ax.axhline(linewidth=1, color='k')
# add some text for labels, title, and axes ticks
ax.set_ylabel('Expectation value', fontsize=14)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=14, rotation=70)
ax.set_xlabel('Pauli', fontsize=14)
ax.set_ylim([-1, 1])
ax.set_facecolor('#eeeeee')
for tick in ax.xaxis.get_major_ticks()+ax.yaxis.get_major_ticks():
tick.label.set_fontsize(14)
ax.set_title(title, fontsize=16)
plt.close(fig)
return fig | 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:
unique_hardware_backends.append(back)
unique_names.append(back.name())
if not unique_hardware_backends:
raise QiskitError('No backends available.')
return unique_hardware_backends | 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':
raise QiskitError("The node %s is not an op node" % (str(self)))
return self.data_dict.get('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.
amp: Complex pulse amplitude.
name: Name of pulse.
"""
return _sampled_constant_pulse(duration, amp, name=name) | 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 zero.
name: Name of pulse.
"""
return _sampled_zero_pulse(duration, name=name) | 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].
period: Pulse period, units of dt. If `None` defaults to single cycle.
phase: Pulse phase.
name: Name of pulse.
"""
if period is None:
period = duration
return _sampled_square_pulse(duration, amp, period, phase=phase, name=name) | 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 single cycle.
phase: Pulse phase.
name: Name of pulse.
"""
if period is None:
period = duration
return _sampled_sawtooth_pulse(duration, amp, period, phase=phase, name=name) | 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].
period: Pulse period, units of dt. If `None` defaults to single cycle.
phase: Pulse phase.
name: Name of pulse.
"""
if period is None:
period = duration
return _sampled_triangle_pulse(duration, amp, period, phase=phase, name=name) | 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.
freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle.
phase: Pulse phase.
name: Name of pulse.
"""
if freq is None:
freq = 1/duration
return _sampled_cos_pulse(duration, amp, freq, phase=phase, name=name) | 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.
phase: Pulse phase.
name: Name of pulse.
"""
if freq is None:
freq = 1/duration
return _sampled_sin_pulse(duration, amp, freq, phase=phase, name=name) | 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.
amp: Pulse amplitude at `duration/2`.
sigma: Width (standard deviation) of pulse.
name: Name of pulse.
"""
center = duration/2
zeroed_width = duration + 2
return _sampled_gaussian_pulse(duration, amp, center, sigma,
zeroed_width=zeroed_width, rescale_amp=True, name=name) | 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 amplitude at `center`.
sigma: Width (standard deviation) of pulse.
name: Name of pulse.
"""
center = duration/2
return _sampled_gaussian_deriv_pulse(duration, amp, center, sigma, name=name) | 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
square portion of pulse will be `duration-2*risefall`.
name: Name of pulse.
"""
center = duration/2
width = duration-2*risefall
zeroed_width = duration + 2
return _sampled_gaussian_square_pulse(duration, amp, center, width, sigma,
zeroed_width=zeroed_width, name=name) | 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))
x1, y1 = self.ax.transAxes.transform( # pylint: disable=invalid-name
(1, 1))
value = x1 - x0 if self.x else y1 - y0
return value | python | {
"resource": ""
} |
q268422 | Qreg.to_string | test | def to_string(self, indent):
"""Print the node data, with indent."""
ind = indent * ' '
print(ind, 'qreg')
self.children[0].to_string(indent + 3) | 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 can be instantiated.
try:
backend_instance = backend_cls(provider=self)
except Exception as err:
raise QiskitError('Backend %s could not be instantiated: %s' %
(backend_cls, err))
return backend_instance | 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
self.qregs[newname] = reg
self.qregs.pop(regname, None)
for node in self._multi_graph.nodes():
if node.type == "in" or node.type == "out":
if node.name and regname in node.name:
node.name = newname
elif node.type == "op":
qa = []
for a in node.qargs:
if a[0] == regname:
a = (newname, a[1])
qa.append(a)
node.qargs = qa
ca = []
for a in node.cargs:
if a[0] == regname:
a = (newname, a[1])
ca.append(a)
node.cargs = ca
if node.condition is not None:
if node.condition[0] == regname:
node.condition = (newname, node.condition[1])
# eX = edge, d= data
for _, _, edge_data in self._multi_graph.edges(data=True):
if regname in edge_data['name']:
edge_data['name'] = re.sub(regname, newname, edge_data['name']) | python | {
"resource": ""
} |
q268425 | DAGCircuit.remove_all_ops_named | test | 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) | 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:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
for j in range(qreg.size):
self._add_wire((qreg, j)) | 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:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
for j in range(creg.size):
self._add_wire((creg, j)) | 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
self.input_map[wire] = inp_node
self.output_map[wire] = outp_node
self._multi_graph.add_node(inp_node)
self._multi_graph.add_node(outp_node)
self._multi_graph.add_edge(inp_node,
outp_node)
self._multi_graph.adj[inp_node][outp_node][0]["name"] \
= "%s[%s]" % (wire[0].name, wire[1])
self._multi_graph.adj[inp_node][outp_node][0]["wire"] \
= wire
else:
raise DAGCircuitError("duplicate wire %s" % (wire,)) | 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
"""
# Verify creg exists
if condition is not None and condition[0].name not in self.cregs:
raise DAGCircuitError("invalid creg in condition for %s" % name) | 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
"""
all_bits = []
if cond is not None:
all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])
return all_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,
"qargs": qargs,
"cargs": cargs,
"condition": condition
}
# Add a new operation node to the graph
self._max_node_id += 1
new_node = DAGNode(data_dict=node_properties, nid=self._max_node_id)
self._multi_graph.add_node(new_node)
self._id_to_node[self._max_node_id] = new_node | 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)
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
self._add_op_node(op, qargs, cargs, condition)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
al = [qargs, all_cbits]
for q in itertools.chain(*al):
ie = list(self._multi_graph.predecessors(self.output_map[q]))
if len(ie) != 1:
raise DAGCircuitError("output node has multiple in-edges")
self._multi_graph.add_edge(ie[0], self._id_to_node[self._max_node_id],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
self._multi_graph.remove_edge(ie[0], self.output_map[q])
self._multi_graph.add_edge(self._id_to_node[self._max_node_id], self.output_map[q],
name="%s[%s]" % (q[0].name, q[1]), wire=q)
return self._id_to_node[self._max_node_id] | 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 and strings here are awkward (due to
# self.qregs/self.cregs still keying on string.
add_regs = set()
reg_frag_chk = {}
for v in keyregs.values():
reg_frag_chk[v] = {j: False for j in range(len(v))}
for k in edge_map.keys():
if k[0].name in keyregs:
reg_frag_chk[k[0]][k[1]] = True
for k, v in reg_frag_chk.items():
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("edge_map fragments reg %s" % k)
elif s == set([False]):
if k in self.qregs.values() or k in self.cregs.values():
raise DAGCircuitError("unmapped duplicate reg %s" % k)
else:
# Add registers that appear only in keyregs
add_regs.add(k)
else:
if valreg:
# If mapping to a register not in valregs, add it.
# (k,0) exists in edge_map because edge_map doesn't
# fragment k
if not edge_map[(k, 0)][0].name in valregs:
size = max(map(lambda x: x[1],
filter(lambda x: x[0] == edge_map[(k, 0)][0],
edge_map.values())))
qreg = QuantumRegister(size + 1, edge_map[(k, 0)][0].name)
add_regs.add(qreg)
return add_regs | 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, k[1])
vname = "%s[%d]" % (v[0].name, v[1])
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % kname)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % vname)
if type(k) is not type(v):
raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
(kname, vname)) | 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
# fragmented by the wire_map (this must have been checked
# elsewhere)
bit0 = (condition[0], 0)
new_condition = (wire_map.get(bit0, bit0)[0], condition[1])
return new_condition | 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 dag.cregs.values():
if creg.name not in self.cregs:
self.add_creg(ClassicalRegister(creg.size, creg.name))
edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])
self.compose_back(dag, edge_map) | 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 mapped wire should already exist
if m_wire not in self.output_map:
raise DAGCircuitError("wire %s[%d] not in self" % (m_wire[0].name, m_wire[1]))
if nd.wire not in input_circuit.wires:
raise DAGCircuitError("inconsistent wire type for %s[%d] in input_circuit"
% (nd.wire[0].name, nd.wire[1]))
elif nd.type == "out":
# ignore output nodes
pass
elif nd.type == "op":
condition = self._map_condition(edge_map, nd.condition)
self._check_condition(nd.name, condition)
m_qargs = list(map(lambda x: edge_map.get(x, x), nd.qargs))
m_cargs = list(map(lambda x: edge_map.get(x, x), nd.cargs))
self.apply_operation_back(nd.op, m_qargs, m_cargs, condition)
else:
raise DAGCircuitError("bad node type %s" % nd.type) | 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):
raise DAGCircuitError("duplicate wires")
wire_tot = len(node.qargs) + len(node.cargs)
if node.condition is not None:
wire_tot += node.condition[0].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d"
% (wire_tot, 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
self._multi_graph.in_edges(nbunch=node, data=True)}
succ_map = {e[2]['wire']: e[1] for e in
self._multi_graph.out_edges(nbunch=node, data=True)}
return pred_map, succ_map | 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]]
else:
# Otherwise, use the corresponding output nodes of self
# and compute the predecessor.
full_succ_map[w] = self.output_map[w]
full_pred_map[w] = self._multi_graph.predecessors(
self.output_map[w])[0]
if len(list(self._multi_graph.predecessors(self.output_map[w]))) != 1:
raise DAGCircuitError("too many predecessors for %s[%d] "
"output node" % (w[0], w[1]))
return full_pred_map, full_succ_map | python | {
"resource": ""
} |
q268441 | DAGCircuit.topological_nodes | test | 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)) | python | {
"resource": ""
} |
q268442 | DAGCircuit.edges | test | 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 | 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.
"""
nodes = []
for node in self._multi_graph.nodes():
if node.type == "op":
if op is None or isinstance(node.op, op):
nodes.append(node)
return nodes | 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():
if isinstance(node.op, Gate):
nodes.append(node)
return 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():
if node.type == 'op' and node.op.name in names:
named_nodes.append(node)
return named_nodes | python | {
"resource": ""
} |
q268446 | DAGCircuit.twoQ_gates | test | 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 | 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 DAGNode instead',
DeprecationWarning, 2)
node = self._id_to_node[node]
return self._multi_graph.predecessors(node) | 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):
if isinstance(self._multi_graph.get_edge_data(predecessor, node, key=0)['wire'][0],
QuantumRegister):
predecessors.append(predecessor)
return predecessors | 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 DAGNode instead',
DeprecationWarning, 2)
node = self._id_to_node[node]
return nx.ancestors(self._multi_graph, node) | 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 = []
for successor in self.successors(node):
if isinstance(self._multi_graph.get_edge_data(
node, successor, key=0)['wire'][0],
QuantumRegister):
successors.append(successor)
return 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 type was wrongly provided.' % node.type)
pred_map, succ_map = self._make_pred_succ_maps(node)
# remove from graph and map
self._multi_graph.remove_node(node)
for w in pred_map.keys():
self._multi_graph.add_edge(pred_map[w], succ_map[w],
name="%s[%s]" % (w[0].name, w[1]), wire=w) | 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',
DeprecationWarning, 2)
node = self._id_to_node[node]
anc = nx.ancestors(self._multi_graph, node)
# TODO: probably better to do all at once using
# multi_graph.remove_nodes_from; same for related functions ...
for anc_node in anc:
if anc_node.type == "op":
self.remove_op_node(anc_node) | 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 = self._id_to_node[node]
desc = nx.descendants(self._multi_graph, node)
for desc_node in desc:
if desc_node.type == "op":
self.remove_op_node(desc_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 = self._id_to_node[node]
anc = nx.ancestors(self._multi_graph, node)
comp = list(set(self._multi_graph.nodes()) - set(anc))
for n in comp:
if n.type == "op":
self.remove_op_node(n) | 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 = self._id_to_node[node]
dec = nx.descendants(self._multi_graph, node)
comp = list(set(self._multi_graph.nodes()) - set(dec))
for n in comp:
if n.type == "op":
self.remove_op_node(n) | 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 = [
op_node.qargs
for op_node in op_nodes
if op_node.name not in {"barrier", "snapshot", "save", "load", "noise"}
]
# Now add the edges to the multi_graph
# By default we just wire inputs to the outputs.
wires = {self.input_map[wire]: self.output_map[wire]
for wire in self.wires}
# Wire inputs to op nodes, and op nodes to outputs.
for op_node in op_nodes:
args = self._bits_in_condition(op_node.condition) \
+ op_node.cargs + op_node.qargs
arg_ids = (self.input_map[(arg[0], arg[1])] for arg in args)
for arg_id in arg_ids:
wires[arg_id], wires[op_node] = op_node, wires[arg_id]
# Add wiring to/from the operations and between unused inputs & outputs.
new_layer._multi_graph.add_edges_from(wires.items())
yield {"graph": new_layer, "partition": 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 layer
support_list = []
# Operation data
op = copy.copy(next_node.op)
qa = copy.copy(next_node.qargs)
ca = copy.copy(next_node.cargs)
co = copy.copy(next_node.condition)
_ = self._bits_in_condition(co)
# Add node to new_layer
new_layer.apply_operation_back(op, qa, ca, co)
# Add operation to partition
if next_node.name not in ["barrier",
"snapshot", "save", "load", "noise"]:
support_list.append(list(qa))
l_dict = {"graph": new_layer, "partition": support_list}
yield l_dict | 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):
multiplicity = self._multi_graph.number_of_edges(node, successor)
if successor in predecessor_count:
predecessor_count[successor] -= multiplicity
else:
predecessor_count[successor] = \
self._multi_graph.in_degree(successor) - multiplicity
if predecessor_count[successor] == 0:
next_layer.append(successor)
del predecessor_count[successor]
yield next_layer
cur_layer = next_layer
next_layer = [] | 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]
nodes_seen[node] = True
s = list(self._multi_graph.successors(node))
while len(s) == 1 and \
s[0].type == "op" and \
s[0].name in namelist:
group.append(s[0])
nodes_seen[s[0]] = True
s = list(self._multi_graph.successors(s[0]))
if len(group) >= 1:
group_list.append(tuple(group))
return set(group_list) | 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
if current_node.type == 'op' or not only_ops:
yield current_node
# find the adjacent node that takes the wire being looked at as input
for node, edges in self._multi_graph.adj[current_node].items():
if any(wire == edge['wire'] for edge in edges.values()):
current_node = node
more_nodes = True
break | 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
if name not in op_dict:
op_dict[name] = 1
else:
op_dict[name] += 1
return op_dict | 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(),
"bits": self.num_cbits(),
"factors": self.num_tensor_factors(),
"operations": self.count_ops()}
return summary | 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
gates to a circuit.
Returns:
TomographyBasis: A tomography basis.
"""
ret = TomographyBasis(basis)
ret.prep_fun = prep_fun
ret.meas_fun = meas_fun
return ret | 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 "
"measurement")
if op == "X":
circuit.u2(0., np.pi, qreg) # H
elif op == "Y":
circuit.u2(0., 0.5 * np.pi, qreg) | 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
if not isinstance(prep_qubits, list):
raise QiskitError('prep_qubits argument must be a list')
if len(prep_qubits) != len(meas_qubits):
raise QiskitError('meas_qubits and prep_qubitsare different length')
if isinstance(meas_basis, str):
if meas_basis.lower() == 'pauli':
meas_basis = PAULI_BASIS
if isinstance(prep_basis, str):
if prep_basis.lower() == 'pauli':
prep_basis = PAULI_BASIS
elif prep_basis.lower() == 'sic':
prep_basis = SIC_BASIS
circuits = []
circuit_labels = []
# add meas basis configs
if prep_basis is None:
# State Tomography
for meas_product in product(meas_basis.keys(), repeat=num_of_qubits):
meas = dict(zip(meas_qubits, meas_product))
circuits.append({'meas': meas})
# Make label
label = '_meas_'
for qubit, op in meas.items():
label += '%s(%d)' % (op[0], qubit)
circuit_labels.append(label)
return {'qubits': meas_qubits,
'circuits': circuits,
'circuit_labels': circuit_labels,
'meas_basis': meas_basis}
# Process Tomography
num_of_s = len(list(prep_basis.values())[0])
plst_single = [(b, s)
for b in prep_basis.keys()
for s in range(num_of_s)]
for plst_product in product(plst_single, repeat=num_of_qubits):
for meas_product in product(meas_basis.keys(),
repeat=num_of_qubits):
prep = dict(zip(prep_qubits, plst_product))
meas = dict(zip(meas_qubits, meas_product))
circuits.append({'prep': prep, 'meas': meas})
# Make label
label = '_prep_'
for qubit, op in prep.items():
label += '%s%d(%d)' % (op[0], op[1], qubit)
label += '_meas_'
for qubit, op in meas.items():
label += '%s(%d)' % (op[0], qubit)
circuit_labels.append(label)
return {'qubits': meas_qubits,
'circuits': circuits,
'circuit_labels': circuit_labels,
'prep_basis': prep_basis,
'meas_basis': meas_basis} | 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 experiments.
prep_basis (tomography_basis or str): The qubit preparation basis.
The default value is 'SIC'.
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", "prep_basus", circuits".
```
{
'qubits': qubits (list[ints]),
'meas_basis': meas_basis (tomography_basis),
'prep_basis': prep_basis (tomography_basis),
'circuit_labels': (list[string]),
'circuits': (list[dict]) # prep and meas configurations
}
```
"""
return tomography_set(meas_qubits, meas_basis=meas_basis,
prep_qubits=prep_qubits, prep_basis=prep_basis) | 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:
For a tomography set specifying state tomography of qubit-0 prepared
by a circuit 'circ' this would return:
```
['circ_meas_X(0)', 'circ_meas_Y(0)', 'circ_meas_Z(0)']
```
For process tomography of the same circuit with preparation in the
SIC-POVM basis it would return:
```
[
'circ_prep_S0(0)_meas_X(0)', 'circ_prep_S0(0)_meas_Y(0)',
'circ_prep_S0(0)_meas_Z(0)', 'circ_prep_S1(0)_meas_X(0)',
'circ_prep_S1(0)_meas_Y(0)', 'circ_prep_S1(0)_meas_Z(0)',
'circ_prep_S2(0)_meas_X(0)', 'circ_prep_S2(0)_meas_Y(0)',
'circ_prep_S2(0)_meas_Z(0)', 'circ_prep_S3(0)_meas_X(0)',
'circ_prep_S3(0)_meas_Y(0)', 'circ_prep_S3(0)_meas_Z(0)'
]
```
"""
if not isinstance(circuit, QuantumCircuit):
raise QiskitError('Input circuit must be a QuantumCircuit object')
dics = tomoset['circuits']
labels = tomography_circuit_names(tomoset, circuit.name)
tomography_circuits = []
for label, conf in zip(labels, dics):
tmp = circuit
# Add prep circuits
if 'prep' in conf:
prep = QuantumCircuit(qreg, creg, name='tmp_prep')
for qubit, op in conf['prep'].items():
tomoset['prep_basis'].prep_gate(prep, qreg[qubit], op)
prep.barrier(qreg[qubit])
tmp = prep + tmp
# Add measurement circuits
meas = QuantumCircuit(qreg, creg, name='tmp_meas')
for qubit, op in conf['meas'].items():
meas.barrier(qreg[qubit])
tomoset['meas_basis'].meas_gate(meas, qreg[qubit], op)
meas.measure(qreg[qubit], creg[qubit])
tmp = tmp + meas
# Add label to the circuit
tmp.name = label
tomography_circuits.append(tmp)
logger.info('>> created tomography circuits for "%s"', circuit.name)
return tomography_circuits | 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():
circuit[c] = {}
circuit[c]['meas'] = [(meas[meas_qubits[k]], int(c[-1 - k]))
for k in range(len(meas_qubits))]
if prep:
circuit[c]['prep'] = [prep[prep_qubits[k]]
for k in range(len(prep_qubits))]
data.append({'counts': counts, 'shots': shots, 'circuit': circuit})
ret = {'data': data, 'meas_basis': tomoset['meas_basis']}
if prep:
ret['prep_basis'] = tomoset['prep_basis']
return ret | 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 strings for summing outcomes of other qubits
rgx = [
reduce(lambda x, y: (key[qs.index(y)] if y in qs else '\\d') + x,
range(num_of_qubits), '') for key in meas_keys
]
# build the return list
meas_counts = []
for m in rgx:
c = 0
for key, val in counts.items():
if match(m, key):
c += val
meas_counts.append(c)
# return as counts dict on measured qubits only
return dict(zip(meas_keys, meas_counts)) | 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 eigenvalues to zero.
The default value is 0
- 'leastsq': Fitting without positive-semidefinite constraint.
Options:
- 'trace': Same as for 'wizard' method.
- 'beta': Same as for 'wizard' method.
Raises:
Exception: if the `method` parameter is not valid.
"""
if isinstance(method, str) and method.lower() in ['wizard', 'leastsq']:
# get options
trace = __get_option('trace', options)
beta = __get_option('beta', options)
# fit state
rho = __leastsq_fit(tomo_data, trace=trace, beta=beta)
if method == 'wizard':
# Use wizard method to constrain positivity
epsilon = __get_option('epsilon', options)
rho = __wizard(rho, epsilon=epsilon)
return rho
else:
raise Exception('Invalid reconstruction method "%s"' % method) | 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:
op_prep = __projector(projectors['prep'],
tomo_data['prep_basis'])
op = np.kron(op_prep.conj(), op)
ops.append(op)
# Convert counts to frequencies
counts = np.array(counts)
shots = np.array(shots)
freqs = counts / shots
# Use hedged frequencies to calculate least squares fitting weights
if weights is None:
if beta is None:
beta = 0.50922
K = len(keys)
freqs_hedged = (counts + beta) / (shots + K * beta)
weights = np.sqrt(shots / (freqs_hedged * (1 - freqs_hedged)))
return __tomo_linear_inv(freqs, ops, weights, trace=trace) | 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:
label, eigenstate = op
ret = np.kron(basis[label][eigenstate], ret)
return ret | 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
if weights is not None:
W = np.array(weights)
if W.ndim == 1:
W = np.diag(W)
# Get basis S matrix
S = np.array([vectorize(m).conj()
for m in ops]).reshape(len(ops), ops[0].size)
if weights is not None:
S = np.dot(W, S) # W.S
# get frequencies vec
v = np.array(freqs) # |f>
if weights is not None:
v = np.dot(W, freqs) # W.|f>
Sdg = S.T.conj() # S^*.W^*
inv = np.linalg.pinv(np.dot(Sdg, S)) # (S^*.W^*.W.S)^-1
# linear inversion of freqs
ret = devectorize(np.dot(inv, np.dot(Sdg, v)))
# renormalize to input trace value
if trace is not None:
ret = trace * ret / np.trace(ret)
return ret | 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) # v eigenvecrors v[0] < v[1] <...
for j in range(dim):
if v[j] < epsilon:
tmp = v[j]
v[j] = 0.
# redistribute loop
x = 0.
for k in range(j + 1, dim):
x += tmp / (dim - (j + 1))
v[k] = v[k] + tmp / (dim - (j + 1))
for j in range(dim):
rho_wizard = rho_wizard + v[j] * outer(w[:, j])
return rho_wizard | 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):
parity = np.kron(parity, p)
w = [0] * len(labels)
wpt = 0
counts = [marginal_counts(q_result.get_counts(circ), meas_qubits)
for circ in labels]
for entry in counts:
x = [0] * dim
for i in range(dim):
if bin(i)[2:].zfill(num) in entry:
x[i] = float(entry[bin(i)[2:].zfill(num)])
if shots is None:
shots = np.sum(x)
for i in range(dim):
w[wpt] = w[wpt] + (x[i] / shots) * parity[i]
wpt += 1
return w | 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 the measurement.
"""
if self.meas_fun is None:
pass
else:
self.meas_fun(circuit, qreg, op) | 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 not _interval_set:
interval = 2
# Adjust length of message so there are no artifacts
if len(msg) < msg_len:
msg += ' ' * (msg_len - len(msg))
elif len(msg) > msg_len:
msg_len = len(msg)
if msg != prev_msg and not quiet:
print('\r%s: %s' % ('Job Status', msg), end='', file=output)
prev_msg = msg
if not quiet:
print('', file=output) | 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
style = "font-size:16px;"
header = "<p style='{style}'>Job Status: %s </p>".format(
style=style)
status = widgets.HTML(value=header % job.status().value)
display(status)
thread = threading.Thread(target=_html_checker, args=(job, interval,
status, header))
thread.start()
else:
_text_checker(job, interval, _interval_set,
quiet=quiet, output=output)
else:
if monitor_async:
raise QiskitError(
'monitor_async only available in Jupyter notebooks.')
_text_checker(job, interval, _interval_set, quiet=quiet, output=output) | 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 + phimlambda) / 2.0
lamb = (phiplambda - phimlambda) / 2.0
else:
if abs(U[0, 0]) < _CUTOFF_PRECISION:
lamb = -phimlambda
else:
lamb = phiplambda
# Check the solution
Rzphi = np.array([[np.exp(-1j*phi/2.0), 0],
[0, np.exp(1j*phi/2.0)]], dtype=complex)
Rytheta = np.array([[np.cos(theta/2.0), -np.sin(theta/2.0)],
[np.sin(theta/2.0), np.cos(theta/2.0)]], dtype=complex)
Rzlambda = np.array([[np.exp(-1j*lamb/2.0), 0],
[0, np.exp(1j*lamb/2.0)]], dtype=complex)
V = np.dot(Rzphi, np.dot(Rytheta, Rzlambda))
if la.norm(V - U) > _CUTOFF_PRECISION:
raise QiskitError("euler_angles_1q: incorrect result")
return theta, phi, lamb | 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 rotation is pi/2 or -pi/2 mod 2*pi, so the gate is a u2
if isinstance(gate, U3Gate):
# theta = pi/2 + 2*k*pi
if abs((gate.params[0] - math.pi / 2) % (2.0 * math.pi)) < _CUTOFF_PRECISION:
gate = U2Gate(gate.params[1],
gate.params[2] + (gate.params[0] - math.pi / 2))
# theta = -pi/2 + 2*k*pi
if abs((gate.params[0] + math.pi / 2) % (2.0 * math.pi)) < _CUTOFF_PRECISION:
gate = U2Gate(gate.params[1] + math.pi,
gate.params[2] - math.pi + (gate.params[0] + math.pi / 2))
# u1 and lambda is 0 mod 4*pi so gate is nop
if isinstance(gate, U1Gate) and abs(gate.params[0] % (4.0 * math.pi)) < _CUTOFF_PRECISION:
gate = IdGate()
return gate | 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"
" \"layout\" parameter to run")
layout_virtual_qubits = self.layout.get_virtual_bits().keys()
new_qregs = set(virtual_qubit[0] for virtual_qubit in layout_virtual_qubits
if virtual_qubit not in dag.wires)
for qreg in new_qregs:
dag.add_qreg(qreg)
return dag | 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']
T2 = str(round(t2_info['value'], # pylint: disable=invalid-name
5))+' ' + t2_info['unit']
# pylint: disable=invalid-name
U1 = str(round(gate_data[0]['parameters'][0]['value'], 5))
# pylint: disable=invalid-name
U2 = str(round(gate_data[1]['parameters'][0]['value'], 5))
# pylint: disable=invalid-name
U3 = str(round(gate_data[2]['parameters'][0]['value'], 5))
readout_error = round(readout_info['value'], 5)
qubit_html += "<tr><td><font style='font-weight:bold'>%s</font></td><td>%s</td>"
qubit_html += "<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>"
qubit_html = qubit_html % (name, freq, T1, T2, U1, U2, U3, readout_error)
qubit_html += qubit_footer
qubit_widget = widgets.HTML(value=qubit_html)
out = widgets.VBox([update_date_widget,
qubit_widget])
return out | 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',
align_items='center',
min_height='400px'))
tabs = widgets.Tab(layout=widgets.Layout(max_height='620px'))
tabs.children = [year, month, week]
tabs.set_title(0, 'Year')
tabs.set_title(1, 'Month')
tabs.set_title(2, 'Week')
tabs.selected_index = 1
_build_job_history(tabs, backend)
return tabs | 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:
continue
nz_bins = []
nz_idx = []
for ind, val in enumerate(binned_jobs):
if val != 0:
nz_idx.append(ind)
nz_bins.append(val)
total_jobs = sum(binned_jobs)
colors = ['#003f5c', '#ffa600', '#374c80', '#ff764a',
'#7a5195', '#ef5675', '#bc5090']
if interval == 'year':
labels = ['{}-{}'.format(str(bins[b].year)[2:], bins[b].month) for b in nz_idx]
else:
labels = ['{}-{}'.format(bins[b].month, bins[b].day) for b in nz_idx]
fig, ax = plt.subplots(1, 1, figsize=(5, 5)) # pylint: disable=invalid-name
ax.pie(nz_bins[::-1], labels=labels, colors=colors, textprops={'fontsize': 14},
rotatelabels=True, counterclock=False)
ax.add_artist(Circle((0, 0), 0.7, color='white', zorder=1))
ax.text(0, 0, total_jobs, horizontalalignment='center',
verticalalignment='center', fontsize=26)
fig.tight_layout()
return fig | 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.
nop (int): Data points for interpolation.
size (tuple): Size of figure.
"""
from qiskit.tools.visualization import pulse_drawer
return pulse_drawer(self._samples, self.duration, **kwargs) | python | {
"resource": ""
} |
q268486 | cu3 | test | def cu3(self, theta, phi, lam, ctl, tgt):
"""Apply cu3 from ctl to tgt with angle theta, phi, lam."""
return self.append(Cu3Gate(theta, phi, lam), [ctl, tgt], []) | 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)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
return qc | 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
2: heavy optimization
pass_manager (PassManager):
The pass manager to use for a custom pipeline of transpiler passes.
If this arg is present, all other args will be ignored and the
pass manager will be used directly (Qiskit will not attempt to
auto-select a pass manager based on transpile options).
seed_mapper (int):
DEPRECATED in 0.8: use ``seed_transpiler`` kwarg instead
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: in case of bad inputs to transpiler or errors in passes
"""
# Deprecation matter
if seed_mapper:
warnings.warn("seed_mapper has been deprecated and will be removed in the "
"0.9 release. Instead use seed_transpiler to set the seed "
"for all stochastic parts of the.", DeprecationWarning)
seed_transpiler = seed_mapper
# transpiling schedules is not supported yet.
if isinstance(circuits, Schedule) or \
(isinstance(circuits, list) and all(isinstance(c, Schedule) for c in circuits)):
return circuits
# Get TranspileConfig(s) to configure the circuit transpilation job(s)
circuits = circuits if isinstance(circuits, list) else [circuits]
transpile_configs = _parse_transpile_args(circuits, backend, basis_gates, coupling_map,
backend_properties, initial_layout,
seed_transpiler, optimization_level,
pass_manager)
# Transpile circuits in parallel
circuits = parallel_map(_transpile_circuit, list(zip(circuits, transpile_configs)))
if len(circuits) == 1:
return circuits[0]
return circuits | 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,
transpile_config.coupling_map,
transpile_config.initial_layout,
transpile_config.seed_transpiler)
else:
pass_manager = default_pass_manager_simulator(transpile_config.basis_gates)
return pass_manager.run(circuit) | 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).
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
seed_mapper (int):
DEPRECATED in 0.8: use ``seed_transpiler`` kwarg instead
config (dict):
DEPRECATED in 0.8: use run_config instead
circuits (QuantumCircuit or list[QuantumCircuit]):
DEPRECATED in 0.8: use ``experiments`` kwarg 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
Note: for now, these keyword arguments will both be copied to the
Qobj config, and passed to backend.run()
Returns:
BaseJob: returns job instance derived from BaseJob
Raises:
QiskitError: if the execution cannot be interpreted as either circuits or schedules
"""
if circuits is not None:
experiments = circuits
warnings.warn("the `circuits` arg in `execute()` has been deprecated. "
"please use `experiments`, which can handle both circuit "
"and pulse Schedules", DeprecationWarning)
# transpiling the circuits using given transpile options
experiments = transpile(experiments,
basis_gates=basis_gates,
coupling_map=coupling_map,
backend_properties=backend_properties,
initial_layout=initial_layout,
seed_transpiler=seed_transpiler,
optimization_level=optimization_level,
backend=backend,
pass_manager=pass_manager,
seed_mapper=seed_mapper, # deprecated
)
# assembling the circuits into a qobj to be run on the backend
qobj = assemble(experiments,
qobj_id=qobj_id,
qobj_header=qobj_header,
shots=shots,
memory=memory,
max_credits=max_credits,
seed_simulator=seed_simulator,
default_qubit_los=default_qubit_los,
default_meas_los=default_meas_los,
schedule_los=schedule_los,
meas_level=meas_level,
meas_return=meas_return,
memory_slots=memory_slots,
memory_slot_size=memory_slot_size,
rep_time=rep_time,
parameter_binds=parameter_binds,
backend=backend,
config=config, # deprecated
seed=seed, # deprecated
run_config=run_config
)
# executing the circuits on the backend and returning the job
return backend.run(qobj, **run_config) | python | {
"resource": ""
} |
q268491 | Qubit.drive | test | def drive(self) -> DriveChannel:
"""Return the primary drive channel of this qubit."""
if self._drives:
return self._drives[0]
else:
raise PulseError("No drive channels in q[%d]" % self._index) | python | {
"resource": ""
} |
q268492 | Qubit.control | test | def control(self) -> ControlChannel:
"""Return the primary control channel of this qubit."""
if self._controls:
return self._controls[0]
else:
raise PulseError("No control channels in q[%d]" % self._index) | python | {
"resource": ""
} |
q268493 | Qubit.measure | test | def measure(self) -> MeasureChannel:
"""Return the primary measure channel of this qubit."""
if self._measures:
return self._measures[0]
else:
raise PulseError("No measurement channels in q[%d]" % self._index) | python | {
"resource": ""
} |
q268494 | Qubit.acquire | test | def acquire(self) -> AcquireChannel:
"""Return the primary acquire channel of this qubit."""
if self._acquires:
return self._acquires[0]
else:
raise PulseError("No acquire channels in q[%d]" % self._index) | 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):
circ.h(q[j])
circ.u1(math.pi/float(2**(j)), q[j]).inverse() | 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
if config:
warnings.warn('config is not used anymore. Set all configs in '
'run_config.', DeprecationWarning)
run_config = run_config or config
if seed:
warnings.warn('seed is deprecated in favor of seed_simulator.', DeprecationWarning)
seed_simulator = seed_simulator or seed
# Get RunConfig(s) that will be inserted in Qobj to configure the run
experiments = experiments if isinstance(experiments, list) else [experiments]
qobj_id, qobj_header, run_config = _parse_run_args(backend, qobj_id, qobj_header,
shots, memory, max_credits, seed_simulator,
default_qubit_los, default_meas_los,
schedule_los, meas_level, meas_return,
memory_slots, memory_slot_size, rep_time,
parameter_binds, **run_config)
# assemble either circuits or schedules
if all(isinstance(exp, QuantumCircuit) for exp in experiments):
# If circuits are parameterized, bind parameters and remove from run_config
bound_experiments, run_config = _expand_parameters(circuits=experiments,
run_config=run_config)
return assemble_circuits(circuits=bound_experiments, qobj_id=qobj_id,
qobj_header=qobj_header, run_config=run_config)
elif all(isinstance(exp, Schedule) for exp in experiments):
return assemble_schedules(schedules=experiments, qobj_id=qobj_id,
qobj_header=qobj_header, run_config=run_config)
else:
raise QiskitError("bad input to assemble() function; "
"must be either circuits or schedules") | 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 qiskit_logger.handlers:
qiskit_logger.removeHandler(handler) | 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)
if figsize is None:
options = {}
else:
options = {'width': figsize[0], 'height': figsize[1]}
# Process data and execute
div_number = str(time.time())
div_number = re.sub('[.]', '', div_number)
# Process data and execute
real = []
imag = []
for xvalue in rho:
row_real = []
col_imag = []
for value_real in xvalue.real:
row_real.append(float(value_real))
real.append(row_real)
for value_imag in xvalue.imag:
col_imag.append(float(value_imag))
imag.append(col_imag)
html = html_template.substitute({
'divNumber': div_number
})
javascript = javascript_template.substitute({
'divNumber': div_number,
'executions': [{'data': real}, {'data': imag}],
'options': options
})
display(HTML(html + javascript)) | 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)
s2 = SuperOp(channel2)
# Check inputs are CPTP
if require_cptp:
# Only check SuperOp if we didn't already check unitary inputs
if is_cptp1 is None:
is_cptp1 = s1.is_cptp()
if not is_cptp1:
raise QiskitError('channel1 is not CPTP')
if is_cptp2 is None:
is_cptp2 = s2.is_cptp()
if not is_cptp2:
raise QiskitError('channel2 is not CPTP')
# Check dimensions match
input_dim1, output_dim1 = s1.dim
input_dim2, output_dim2 = s2.dim
if input_dim1 != output_dim1 or input_dim2 != output_dim2:
raise QiskitError('Input channels must have same size input and output dimensions.')
if input_dim1 != input_dim2:
raise QiskitError('Input channels have different dimensions.')
# Compute process fidelity
fidelity = np.trace(s1.compose(s2.adjoint()).data) / (input_dim1 ** 2)
return fidelity | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.