Search is not available for this dataset
text stringlengths 75 104k |
|---|
def assemble_schedules(schedules, qobj_id=None, qobj_header=None, run_config=None):
"""Assembles a list of schedules into a qobj which can be run on the backend.
Args:
schedules (list[Schedule]): schedules to assemble
qobj_id (int): identifier for the generated qobj
qobj_header (QobjHead... |
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_l... |
def _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,
paramet... |
def _expand_parameters(circuits, run_config):
"""Verifies that there is a single common set of parameters shared between
all circuits and all parameter binds in the run_config. Returns an expanded
list of circuits (if parameterized) with all parameters bound, and a copy of
the run_config with parameter_... |
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) |
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_te... |
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 states... |
def input(self, data):
"""Set the input text data."""
self.data = data
self.lexer.input(data) |
def pop(self):
"""Pop a PLY lexer off the stack."""
self.lexer = self.stack.pop()
self.filename = self.lexer.qasm_file
self.lineno = self.lexer.qasm_line |
def push(self, filename):
"""Push a PLY lexer on the stack to parse filename."""
self.lexer.qasm_file = self.filename
self.lexer.qasm_line = self.lineno
self.stack.append(self.lexer)
self.__mklexer__(filename) |
def t_INCLUDE(self, t):
'include'
#
# Now eat up the next two tokens which must be
# 1 - the name of the include file, and
# 2 - a terminating semicolon
#
# Then push the current lexer onto the stack, create a new one from
# the include file, and push it o... |
def t_ID(self, t):
r'[a-z][a-zA-Z0-9_]*'
t.type = self.reserved.get(t.value, 'ID')
if t.type == 'ID':
t.value = node.Id(t.value, self.lineno, self.filename)
return t |
def t_newline(self, t):
r'\n+'
self.lineno += len(t.value)
t.lexer.lineno = self.lineno |
def create_from(cls, backend):
"""
Create device specification with values in backend configuration.
Args:
backend(Backend): backend configuration
Returns:
DeviceSpecification: created device specification
Raises:
PulseError: when an invalid ba... |
def run(self, dag):
"""iterate over each block and replace it with an equivalent Unitary
on the same wires.
"""
new_dag = DAGCircuit()
for qreg in dag.qregs.values():
new_dag.add_qreg(qreg)
for creg in dag.cregs.values():
new_dag.add_creg(creg)
... |
def _block_qargs_to_indices(self, block_qargs, global_index_map):
"""
Map each qubit in block_qargs to its wire position among the block's wires.
Args:
block_qargs (list): list of qubits that a block acts on
global_index_map (dict): mapping from each qubit in the
... |
def get_bound_method(self, instruction):
"""Get conversion method for instruction."""
try:
return self._bound_instructions[type(instruction)]
except KeyError:
raise PulseError('Qobj conversion method for %s is not found.' % instruction) |
def convert_acquire(self, shift, instruction):
"""Return converted `AcquireInstruction`.
Args:
shift(int): Offset time.
instruction (AcquireInstruction): acquire instruction.
Returns:
dict: Dictionary of required parameters.
"""
meas_level = s... |
def convert_frame_change(self, shift, instruction):
"""Return converted `FrameChangeInstruction`.
Args:
shift(int): Offset time.
instruction (FrameChangeInstruction): frame change instruction.
Returns:
dict: Dictionary of required parameters.
"""
... |
def convert_persistent_value(self, shift, instruction):
"""Return converted `PersistentValueInstruction`.
Args:
shift(int): Offset time.
instruction (PersistentValueInstruction): persistent value instruction.
Returns:
dict: Dictionary of required parameters.
... |
def convert_drive(self, shift, instruction):
"""Return converted `PulseInstruction`.
Args:
shift(int): Offset time.
instruction (PulseInstruction): drive instruction.
Returns:
dict: Dictionary of required parameters.
"""
command_dict = {
... |
def convert_snapshot(self, shift, instruction):
"""Return converted `Snapshot`.
Args:
shift(int): Offset time.
instruction (Snapshot): snapshot instruction.
Returns:
dict: Dictionary of required parameters.
"""
command_dict = {
'na... |
def _update_annotations(discretized_pulse: Callable) -> Callable:
"""Update annotations of discretized continuous pulse function with duration.
Args:
discretized_pulse: Discretized decorated continuous pulse.
"""
undecorated_annotations = list(discretized_pulse.__annotations__.items())
deco... |
def _update_docstring(discretized_pulse: Callable, sampler_inst: Callable) -> Callable:
"""Update annotations of discretized continuous pulse function.
Args:
discretized_pulse: Discretized decorated continuous pulse.
sampler_inst: Applied sampler.
"""
wrapped_docstring = pydoc.render_do... |
def sampler(sample_function: Callable) -> Callable:
"""Sampler decorator base method.
Samplers are used for converting an continuous function to a discretized pulse.
They operate on a function with the signature:
`def f(times: np.ndarray, *args, **kwargs) -> np.ndarray`
Where `times` is a nump... |
def filter_backends(backends, filters=None, **kwargs):
"""Return the backends matching the specified filtering.
Filter the `backends` list by their `configuration` or `status`
attributes, or from a boolean callable. The criteria for filtering can
be specified via `**kwargs` or as a callable via `filter... |
def resolve_backend_name(name, backends, deprecated, aliased):
"""Resolve backend name from a deprecated name or an alias.
A group will be resolved in order of member priorities, depending on
availability.
Args:
name (str): name of backend to resolve
backends (list[BaseBackend]): list ... |
def dag_to_circuit(dag):
"""Build a ``QuantumCircuit`` object from a ``DAGCircuit``.
Args:
dag (DAGCircuit): the input dag.
Return:
QuantumCircuit: the circuit representing the input dag.
"""
qregs = collections.OrderedDict()
for qreg in dag.qregs.values():
qreg_tmp = Q... |
def make_dict_observable(matrix_observable):
"""Convert an observable in matrix form to dictionary form.
Takes in a diagonal observable as a matrix and converts it to a dictionary
form. Can also handle a list sorted of the diagonal elements.
Args:
matrix_observable (list): The observable to be... |
def update_symtab(self, obj):
"""Update a node in the symbol table.
Everything in the symtab must be a node with these attributes:
name - the string name of the object
type - the string type of the object
line - the source line where the type was first found
file - the s... |
def verify_declared_bit(self, obj):
"""Verify a qubit id against the gate prototype."""
# We are verifying gate args against the formal parameters of a
# gate prototype.
if obj.name not in self.current_symtab:
raise QasmError("Cannot find symbol '" + obj.name
... |
def verify_exp_list(self, obj):
"""Verify each expression in a list."""
# A tad harder. This is a list of expressions each of which could be
# the head of a tree. We need to recursively walk each of these and
# ensure that any Id elements resolve to the current stack.
#
... |
def verify_as_gate(self, obj, bitlist, arglist=None):
"""Verify a user defined gate call."""
if obj.name not in self.global_symtab:
raise QasmError("Cannot find gate definition for '" + obj.name
+ "', line", str(obj.line), 'file', obj.file)
g_sym = self.gl... |
def verify_reg(self, obj, object_type):
"""Verify a register."""
# How to verify:
# types must match
# indexes must be checked
if obj.name not in self.global_symtab:
raise QasmError('Cannot find definition for', object_type, "'"
+ obj... |
def verify_reg_list(self, obj, object_type):
"""Verify a list of registers."""
# We expect the object to be a bitlist or an idlist, we don't care.
# We will iterate it and ensure everything in it is declared as a bit,
# and throw if not.
for children in obj.children:
... |
def id_tuple_list(self, id_node):
"""Return a list of (name, index) tuples for this id node."""
if id_node.type != "id":
raise QasmError("internal error, id_tuple_list")
bit_list = []
try:
g_sym = self.current_symtab[id_node.name]
except KeyError:
... |
def verify_distinct(self, list_of_nodes):
"""Check that objects in list_of_nodes represent distinct (qu)bits.
list_of_nodes is a list containing nodes of type id, indexed_id,
primary_list, or id_list. We assume these are all the same type
'qreg' or 'creg'.
This method raises an ... |
def p_statement(self, program):
"""
statement : decl
| quantum_op ';'
| format ';'
| ignore
| quantum_op error
| format error
"""
if len(program) > 2:
if program[2] != ... |
def p_indexed_id(self, program):
"""
indexed_id : id '[' NNINTEGER ']'
| id '[' NNINTEGER error
| id '[' error
"""
if len(program) == 4:
raise QasmError("Expecting an integer index; received",
str(prog... |
def p_gate_id_list_0(self, program):
"""
gate_id_list : id
"""
program[0] = node.IdList([program[1]])
self.update_symtab(program[1]) |
def p_gate_id_list_1(self, program):
"""
gate_id_list : gate_id_list ',' id
"""
program[0] = program[1]
program[0].add_child(program[3])
self.update_symtab(program[3]) |
def p_bit_list_0(self, program):
"""
bit_list : id
"""
program[0] = node.IdList([program[1]])
program[1].is_bit = True
self.update_symtab(program[1]) |
def p_bit_list_1(self, program):
"""
bit_list : bit_list ',' id
"""
program[0] = program[1]
program[0].add_child(program[3])
program[3].is_bit = True
self.update_symtab(program[3]) |
def p_decl(self, program):
"""
decl : qreg_decl ';'
| creg_decl ';'
| qreg_decl error
| creg_decl error
| gate_decl
"""
if len(program) > 2:
if program[2] != ';':
raise QasmError("Missing ';' i... |
def p_qreg_decl(self, program):
"""
qreg_decl : QREG indexed_id
"""
program[0] = node.Qreg([program[2]])
if program[2].name in self.external_functions:
raise QasmError("QREG names cannot be reserved words. "
+ "Received '" + program[2].n... |
def p_creg_decl(self, program):
"""
creg_decl : CREG indexed_id
"""
program[0] = node.Creg([program[2]])
if program[2].name in self.external_functions:
raise QasmError("CREG names cannot be reserved words. "
+ "Received '" + program[2].n... |
def p_gate_decl_1(self, program):
"""
gate_decl : GATE id gate_scope '(' ')' bit_list gate_body
"""
program[0] = node.Gate([program[2], program[6], program[7]])
if program[2].name in self.external_functions:
raise QasmError("GATE names cannot be reserved words. "
... |
def p_gate_body_0(self, program):
"""
gate_body : '{' '}'
"""
if program[2] != '}':
raise QasmError("Missing '}' in gate definition; received'"
+ str(program[2].value) + "'")
program[0] = node.GateBody(None) |
def p_unitary_op_0(self, program):
"""
unitary_op : U '(' exp_list ')' primary
"""
program[0] = node.UniversalUnitary([program[3], program[5]])
self.verify_reg(program[5], 'qreg')
self.verify_exp_list(program[3]) |
def p_unitary_op_1(self, program):
"""
unitary_op : CX primary ',' primary
"""
program[0] = node.Cnot([program[2], program[4]])
self.verify_reg(program[2], 'qreg')
self.verify_reg(program[4], 'qreg')
self.verify_distinct([program[2], program[4]]) |
def p_unitary_op_2(self, program):
"""
unitary_op : id primary_list
"""
program[0] = node.CustomUnitary([program[1], program[2]])
self.verify_as_gate(program[1], program[2])
self.verify_reg_list(program[2], 'qreg')
self.verify_distinct([program[2]]) |
def p_unitary_op_3(self, program):
"""
unitary_op : id '(' ')' primary_list
"""
program[0] = node.CustomUnitary([program[1], program[4]])
self.verify_as_gate(program[1], program[4])
self.verify_reg_list(program[4], 'qreg')
self.verify_distinct([program[4]]) |
def p_unitary_op_4(self, program):
"""
unitary_op : id '(' exp_list ')' primary_list
"""
program[0] = node.CustomUnitary([program[1], program[3], program[5]])
self.verify_as_gate(program[1], program[5], arglist=program[3])
self.verify_reg_list(program[5], 'qreg')
... |
def p_gate_op_0(self, program):
"""
gate_op : U '(' exp_list ')' id ';'
"""
program[0] = node.UniversalUnitary([program[3], program[5]])
self.verify_declared_bit(program[5])
self.verify_exp_list(program[3]) |
def p_gate_op_1(self, program):
"""
gate_op : CX id ',' id ';'
"""
program[0] = node.Cnot([program[2], program[4]])
self.verify_declared_bit(program[2])
self.verify_declared_bit(program[4])
self.verify_distinct([program[2], program[4]]) |
def p_gate_op_2(self, program):
"""
gate_op : id id_list ';'
"""
program[0] = node.CustomUnitary([program[1], program[2]])
# To verify:
# 1. id is declared as a gate in global scope
# 2. everything in the id_list is declared as a bit in local scope
self.ve... |
def p_gate_op_3(self, program):
"""
gate_op : id '(' ')' id_list ';'
"""
program[0] = node.CustomUnitary([program[1], program[4]])
self.verify_as_gate(program[1], program[4])
self.verify_bit_list(program[4])
self.verify_distinct([program[4]]) |
def p_gate_op_4(self, program):
"""
gate_op : id '(' exp_list ')' id_list ';'
"""
program[0] = node.CustomUnitary([program[1], program[3], program[5]])
self.verify_as_gate(program[1], program[5], arglist=program[3])
self.verify_bit_list(program[5])
self.verify_exp... |
def p_gate_op_5(self, program):
"""
gate_op : BARRIER id_list ';'
"""
program[0] = node.Barrier([program[2]])
self.verify_bit_list(program[2])
self.verify_distinct([program[2]]) |
def p_opaque_0(self, program):
"""
opaque : OPAQUE id gate_scope bit_list
"""
# TODO: Review Opaque function
program[0] = node.Opaque([program[2], program[4]])
if program[2].name in self.external_functions:
raise QasmError("OPAQUE names cannot be reserved w... |
def p_opaque_1(self, program):
"""
opaque : OPAQUE id gate_scope '(' ')' bit_list
"""
program[0] = node.Opaque([program[2], program[6]])
self.pop_scope()
self.update_symtab(program[0]) |
def p_measure(self, program):
"""
measure : MEASURE primary ASSIGN primary
"""
program[0] = node.Measure([program[2], program[4]])
self.verify_reg(program[2], 'qreg')
self.verify_reg(program[4], 'creg') |
def p_barrier(self, program):
"""
barrier : BARRIER primary_list
"""
program[0] = node.Barrier([program[2]])
self.verify_reg_list(program[2], 'qreg')
self.verify_distinct([program[2]]) |
def p_reset(self, program):
"""
reset : RESET primary
"""
program[0] = node.Reset([program[2]])
self.verify_reg(program[2], 'qreg') |
def p_if(self, program):
"""
if : IF '(' id MATCHES NNINTEGER ')' quantum_op
if : IF '(' id error
if : IF '(' id MATCHES error
if : IF '(' id MATCHES NNINTEGER error
if : IF error
"""
if len(program) == 3:
raise QasmError("Ill-formed IF stateme... |
def p_unary_6(self, program):
"""
unary : id '(' expression ')'
"""
# note this is a semantic check, not syntactic
if program[1].name not in self.external_functions:
raise QasmError("Illegal external function call: ",
str(program[1].name... |
def p_expression_1(self, program):
"""
expression : '-' expression %prec negative
| '+' expression %prec positive
"""
program[0] = node.Prefix([node.UnaryOperator(program[1]), program[2]]) |
def p_expression_0(self, program):
"""
expression : expression '*' expression
| expression '/' expression
| expression '+' expression
| expression '-' expression
| expression '^' expression
"""
program[0] = n... |
def find_column(self, input_, token):
"""Compute the column.
Input is the input text string.
token is a token instance.
"""
if token is None:
return 0
last_cr = input_.rfind('\n', 0, token.lexpos)
if last_cr < 0:
last_cr = 0
column... |
def get_tokens(self):
"""Returns a generator of the tokens."""
try:
while True:
token = self.lexer.token()
if not token:
break
yield token
except QasmError as e:
print('Exception tokenizing qasm file:',... |
def parse_debug(self, val):
"""Set the parse_deb field."""
if val is True:
self.parse_deb = True
elif val is False:
self.parse_deb = False
else:
raise QasmError("Illegal debug value '" + str(val)
+ "' must be True or False."... |
def parse(self, data):
"""Parse some data."""
self.parser.parse(data, lexer=self.lexer, debug=self.parse_deb)
if self.qasm is None:
raise QasmError("Uncaught exception in parser; "
+ "see previous messages for details.")
return self.qasm |
def run(self, data):
"""Parser runner.
To use this module stand-alone.
"""
ast = self.parser.parse(data, debug=True)
self.parser.parse(data, debug=True)
ast.to_string(0) |
def get_tokens(self):
"""Returns a generator of the tokens."""
if self._filename:
with open(self._filename) as ifile:
self._data = ifile.read()
with QasmParser(self._filename) as qasm_p:
return qasm_p.get_tokens() |
def parse(self):
"""Parse the data."""
if self._filename:
with open(self._filename) as ifile:
self._data = ifile.read()
with QasmParser(self._filename) as qasm_p:
qasm_p.parse_debug(False)
return qasm_p.parse(self._data) |
def crz(self, theta, ctl, tgt):
"""Apply crz from ctl to tgt with angle theta."""
return self.append(CrzGate(theta), [ctl, tgt], []) |
def basis_state(str_state, num):
"""
Return a basis state ndarray.
Args:
str_state (string): a string representing the state.
num (int): the number of qubits
Returns:
ndarray: state(2**num) a quantum state with basis basis state.
Raises:
QiskitError: if the dimensi... |
def projector(state, flatten=False):
"""
maps a pure state to a state matrix
Args:
state (ndarray): the number of qubits
flatten (bool): determine if state matrix of column work
Returns:
ndarray: state_mat(2**num, 2**num) if flatten is false
ndarray: state_mat(4**num) ... |
def purity(state):
"""Calculate the purity of a quantum state.
Args:
state (ndarray): a quantum state
Returns:
float: purity.
"""
rho = np.array(state)
if rho.ndim == 1:
return 1.0
return np.real(np.trace(rho.dot(rho))) |
def qasm(self, prec=15):
"""Return the corresponding OPENQASM string."""
string = "gate " + self.name
if self.arguments is not None:
string += "(" + self.arguments.qasm(prec) + ")"
string += " " + self.bitlist.qasm(prec) + "\n"
string += "{\n" + self.body.qasm(prec) +... |
def run(self, dag):
"""
Run the pass on the DAG, and write the discovered commutation relations
into the property_set.
"""
# Initiate the commutation set
self.property_set['commutation_set'] = defaultdict(list)
# Build a dictionary to keep track of the gates on e... |
def backend_widget(backend):
"""Creates a backend widget.
"""
config = backend.configuration().to_dict()
props = backend.properties().to_dict()
name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()),
layout=widgets.Layout())
n_qubits = config['n_qubits'... |
def update_backend_info(self, interval=60):
"""Updates the monitor info
Called from another thread.
"""
my_thread = threading.currentThread()
current_interval = 0
started = False
all_dead = False
stati = [None]*len(self._backends)
while getattr(my_thread, "do_run", True) and not all_... |
def generate_jobs_pending_widget():
"""Generates a jobs_pending progress bar widget.
"""
pbar = widgets.IntProgress(
value=0,
min=0,
max=50,
description='',
orientation='horizontal', layout=widgets.Layout(max_width='180px'))
pbar.style.bar_color = '#71cddd'
p... |
def run(self, dag):
"""
Flips the cx nodes to match the directed coupling map.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: The rearranged dag for the coupling map
Raises:
TranspilerError: If the circuit cannot be mapped just by fl... |
def run(self, dag):
"""
Run one pass of cx cancellation on the circuit
Args:
dag (DAGCircuit): the directed acyclic graph to run on.
Returns:
DAGCircuit: Transformed DAG.
"""
cx_runs = dag.collect_runs(["cx"])
for cx_run in cx_runs:
... |
def get_backend(self, name=None, **kwargs):
"""Return a single backend matching the specified filtering.
Args:
name (str): name of the backend.
**kwargs (dict): dict used for filtering.
Returns:
BaseBackend: a backend matching the filtering.
Raises:... |
def _bipartite_shape(self):
"""Return the shape for bipartite matrix"""
return (self._input_dim, self._output_dim, self._input_dim,
self._output_dim) |
def conjugate(self):
"""Return the conjugate of the QuantumChannel."""
return Choi(np.conj(self._data), self.input_dims(), self.output_dims()) |
def transpose(self):
"""Return the transpose of the QuantumChannel."""
# Make bipartite matrix
d_in, d_out = self.dim
data = np.reshape(self._data, (d_in, d_out, d_in, d_out))
# Swap input and output indicies on bipartite matrix
data = np.transpose(data, (1, 0, 3, 2))
... |
def compose(self, other, qargs=None, front=False):
"""Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(s... |
def power(self, n):
"""The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
Choi: the matrix power of the SuperOp converted to a Choi channel.
Raises:
QiskitError: if the input and output dim... |
def _evolve(self, state, qargs=None):
"""Evolve a quantum state by the QuantumChannel.
Args:
state (QuantumState): The input statevector or density matrix.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Retu... |
def _tensor_product(self, other, reverse=False):
"""Return the tensor product channel.
Args:
other (QuantumChannel): a quantum channel.
reverse (bool): If False return self ⊗ other, if True return
if True return (other ⊗ self) [Default: False
... |
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register na... |
def _truncate_float(matchobj, format_str='0.2g'):
"""Truncate long floats
Args:
matchobj (re.Match): contains original float
format_str (str): format specifier
Returns:
str: returns truncated float
"""
if matchobj.group(0):
return format(float(matchobj.group(0)), form... |
def latex(self, aliases=None):
"""Return LaTeX string representation of circuit.
This method uses the LaTeX Qconfig package to create a graphical
representation of the circuit.
Returns:
string: for writing to a LaTeX file.
"""
self._initialize_latex_array(al... |
def _get_image_depth(self):
"""Get depth information for the circuit.
Returns:
int: number of columns in the circuit
int: total size of columns in the circuit
"""
max_column_widths = []
for layer in self.ops:
# store the max width for the l... |
def _get_beamer_page(self):
"""Get height, width & scale attributes for the beamer page.
Returns:
tuple: (height, width, scale) desirable page attributes
"""
# PIL python package limits image size to around a quarter gigabyte
# this means the beamer image should be l... |
def _build_latex_array(self, aliases=None):
"""Returns an array of strings containing \\LaTeX for this circuit.
If aliases is not None, aliases contains a dict mapping
the current qubits in the circuit to new qubit names.
We will deduce the register names and sizes from aliases.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.