INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Calculate the purity of a quantum state.
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)))
Return the corresponding OPENQASM string.
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) +...
Run the pass on the DAG and write the discovered commutation relations into the property_set.
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...
Creates a backend widget.
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'...
Updates the monitor info Called from another thread.
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_...
Generates a jobs_pending progress bar widget.
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...
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
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...
Run one pass of cx cancellation on the circuit
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: ...
Return a single backend matching the specified filtering.
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:...
Return the shape for bipartite matrix
def _bipartite_shape(self): """Return the shape for bipartite matrix""" return (self._input_dim, self._output_dim, self._input_dim, self._output_dim)
Return the conjugate of the QuantumChannel.
def conjugate(self): """Return the conjugate of the QuantumChannel.""" return Choi(np.conj(self._data), self.input_dims(), self.output_dims())
Return the transpose of the QuantumChannel.
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)) ...
Return the composition channel self∘other.
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...
The matrix power of the channel.
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...
Evolve a quantum state by the QuantumChannel.
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...
Return the tensor product channel.
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 ...
Get the number and size of unique registers from bit_labels list.
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...
Truncate long floats
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...
Return LaTeX string representation of circuit.
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...
Get depth information for the circuit.
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...
Get height width & scale attributes for the beamer page.
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...
Returns an array of strings containing \\ LaTeX for this circuit.
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. ...
Get the index number for a quantum bit Args: qubit ( tuple ): The tuple of the bit of the form ( register_name bit_number ) Returns: int: The index in the bit list Raises: VisualizationError: If the bit isn t found
def _get_qubit_index(self, qubit): """Get the index number for a quantum bit Args: qubit (tuple): The tuple of the bit of the form (register_name, bit_number) Returns: int: The index in the bit list Raises: VisualizationError: If the bi...
Loads the QObj schema for use in future validations.
def _load_schema(file_path, name=None): """Loads the QObj schema for use in future validations. Caches schema in _SCHEMAS module attribute. Args: file_path(str): Path to schema. name(str): Given name for schema. Defaults to file_path filename without schema. Return: sc...
Generate validator for JSON schema.
def _get_validator(name, schema=None, check_schema=True, validator_class=None, **validator_kwargs): """Generate validator for JSON schema. Args: name (str): Name for validator. Will be validator key in `_VALIDATORS` dict. schema (dict): JSON schema `dict`. If not ...
Load all default schemas into _SCHEMAS.
def _load_schemas_and_validators(): """Load all default schemas into `_SCHEMAS`.""" schema_base_path = os.path.join(os.path.dirname(__file__), '../..') for name, path in _DEFAULT_SCHEMA_PATHS.items(): _load_schema(os.path.join(schema_base_path, path), name) _get_validator(name)
Validates JSON dict against a schema.
def validate_json_against_schema(json_dict, schema, err_msg=None): """Validates JSON dict against a schema. Args: json_dict (dict): JSON to be validated. schema (dict or str): JSON schema dictionary or the name of one of the standards schemas in Qisk...
Return a cascading explanation of the validation error.
def _format_causes(err, level=0): """Return a cascading explanation of the validation error. Returns a cascading explanation of the validation error in the form of:: <validator> failed @ <subfield_path> because of: <validator> failed @ <subfield_path> because of: ... ...
Return the corresponding OPENQASM string.
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" return ",".join([self.children[j].qasm(prec) for j in range(self.size())])
Majority gate.
def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c)
Unmajority gate.
def unmajority(p, a, b, c): """Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b)
Returns a dict of DAGNode: Barrier objects where the barrier needs to be inserted where the corresponding DAGNode appears in the main DAG
def _collect_potential_merges(dag, barriers): """ Returns a dict of DAGNode : Barrier objects, where the barrier needs to be inserted where the corresponding DAGNode appears in the main DAG """ # if only got 1 or 0 barriers then can't merge if len(barriers) < 2: ...
Draw a quantum circuit to different formats ( set by output parameter ): 0. text: ASCII art TextDrawing that can be printed in the console. 1. latex: high - quality images but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies
def circuit_drawer(circuit, scale=0.7, filename=None, style=None, output='text', interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, ...
Draws a circuit using ascii art. Args: circuit ( QuantumCircuit ): Input circuit filename ( str ): optional filename to write the result line_length ( int ): Optional. Breaks the circuit drawing to this length. This useful when the drawing does not fit in the console. If None ( default ) it will try to guess the consol...
def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False, plotbarriers=True, justify=None, vertically_compressed=True): """ Draws a circuit using ascii art. Args: circuit (QuantumCircuit): Input circuit filename (str): optional filename t...
Draw a quantum circuit based on latex ( Qcircuit package )
def _latex_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based ...
Convert QuantumCircuit to LaTeX string.
def _generate_latex_source(circuit, filename=None, scale=0.7, style=None, reverse_bits=False, plot_barriers=True, justify=None): """Convert QuantumCircuit to LaTeX string. Args: circuit (QuantumCircuit): input circuit scale (float): image sc...
Draw a quantum circuit based on matplotlib. If %matplotlib inline is invoked in a Jupyter notebook it visualizes a circuit inline. We recommend %config InlineBackend. figure_format = svg for the inline visualization.
def _matplotlib_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): ...
Return a random quantum state from the uniform ( Haar ) measure on state space.
def random_state(dim, seed=None): """ Return a random quantum state from the uniform (Haar) measure on state space. Args: dim (int): the dim of the state spaxe seed (int): Optional. To set a random seed. Returns: ndarray: state(2**num) a random quantum state. """ i...
Return a random dim x dim unitary Operator from the Haar measure.
def random_unitary(dim, seed=None): """ Return a random dim x dim unitary Operator from the Haar measure. Args: dim (int): the dim of the state space. seed (int): Optional. To set a random seed. Returns: Operator: (dim, dim) unitary operator. Raises: QiskitError: i...
Generate a random density matrix rho.
def random_density_matrix(length, rank=None, method='Hilbert-Schmidt', seed=None): """ Generate a random density matrix rho. Args: length (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. method (...
Return a normally distributed complex random matrix.
def __ginibre_matrix(nrow, ncol=None, seed=None): """ Return a normally distributed complex random matrix. Args: nrow (int): number of rows in output matrix. ncol (int): number of columns in output matrix. seed (int): Optional. To set a random seed. Returns: ndarray: A c...
Generate a random density matrix from the Hilbert - Schmidt metric.
def __random_density_hs(N, rank=None, seed=None): """ Generate a random density matrix from the Hilbert-Schmidt metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Option...
Generate a random density matrix from the Bures metric.
def __random_density_bures(N, rank=None, seed=None): """ Generate a random density matrix from the Bures metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Optional. To ...
Return the corresponding OPENQASM string.
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" string = "" for children in self.children: string += " " + children.qasm(prec) + "\n" return string
Return a list of custom gate names in this gate body.
def calls(self): """Return a list of custom gate names in this gate body.""" lst = [] for children in self.children: if children.type == "custom_unitary": lst.append(children.name) return lst
Return the corresponding OPENQASM string.
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" if self.value == pi: return "pi" return ccode(self.value, precision=prec)
gate sdg a { u1 ( - pi/ 2 ) a ; }
def _define(self): """ gate sdg a { u1(-pi/2) a; } """ definition = [] q = QuantumRegister(1, "q") rule = [ (U1Gate(-pi/2), [q[0]], []) ] for inst in rule: definition.append(inst) self.definition = definition
Return the composition channel self∘other.
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...
The matrix power of the channel.
def power(self, n): """The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Chi: the matrix power of the SuperOp converted to a Chi channel. Raises: QiskitError: if the input and output dimen...
Return the QuantumChannel self + other.
def add(self, other): """Return the QuantumChannel self + other. Args: other (QuantumChannel): a quantum channel. Returns: Chi: the linear addition self + other as a Chi object. Raises: QiskitError: if other is not a QuantumChannel subclass, or ...
Return the QuantumChannel self + other.
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Chi: the scalar multiplication other * self as a Chi object. Raises: QiskitError: if other is not a valid scalar. """ ...
Return the tensor product channel.
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 ...
Return the conjugate of the QuantumChannel.
def conjugate(self): """Return the conjugate of the QuantumChannel.""" return SuperOp( np.conj(self._data), self.input_dims(), self.output_dims())
Return the transpose of the QuantumChannel.
def transpose(self): """Return the transpose of the QuantumChannel.""" return SuperOp( np.transpose(self._data), input_dims=self.output_dims(), output_dims=self.input_dims())
Return the composition channel self∘other.
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...
Return the compose of a QuantumChannel with itself n times.
def power(self, n): """Return the compose of a QuantumChannel with itself n times. Args: n (int): compute the matrix power of the superoperator matrix. Returns: SuperOp: the n-times composition channel as a SuperOp object. Raises: QiskitError: if th...
Return the QuantumChannel self + other.
def add(self, other): """Return the QuantumChannel self + other. Args: other (QuantumChannel): a quantum channel. Returns: SuperOp: the linear addition self + other as a SuperOp object. Raises: QiskitError: if other cannot be converted to a channel ...
Return the QuantumChannel self + other.
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: SuperOp: the scalar multiplication other * self as a SuperOp object. Raises: QiskitError: if other is not a valid scalar. ...
Evolve a quantum state by the QuantumChannel.
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...
Return the composition channel.
def _compose_subsystem(self, other, qargs, front=False): """Return the composition channel.""" # Compute tensor contraction indices from qargs input_dims = list(self.input_dims()) output_dims = list(self.output_dims()) if front: num_indices = len(self.input_dims()) ...
Evolve a quantum state by the operator.
def _evolve_subsystem(self, state, qargs): """Evolve a quantum state by the operator. Args: state (QuantumState): The input statevector or density matrix. qargs (list): a list of QuantumState subsystem positions to apply the operator on. Retur...
Convert a QuantumCircuit or Instruction to a SuperOp.
def _instruction_to_superop(cls, instruction): """Convert a QuantumCircuit or Instruction to a SuperOp.""" # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an identity superoperator of the ...
Update the current Operator by apply an instruction.
def _append_instruction(self, obj, qargs=None): """Update the current Operator by apply an instruction.""" if isinstance(obj, Instruction): chan = None if obj.name == 'reset': # For superoperator evolution we can simulate a reset as # a non-unitary...
Return a circuit with a barrier before last measurements.
def run(self, dag): """Return a circuit with a barrier before last measurements.""" # Collect DAG nodes which are followed only by barriers or other measures. final_op_types = ['measure', 'barrier'] final_ops = [] for candidate_node in dag.named_nodes(*final_op_types): ...
Convert a list of circuits into a qobj.
def circuits_to_qobj(circuits, qobj_header=None, qobj_id=None, backend_name=None, config=None, shots=None, max_credits=None, basis_gates=None, coupling_map=None, seed=None, memory=None): """Convert a list of circuits into a qobj. ...
Expand 3 + qubit gates using their decomposition rules.
def run(self, dag): """Expand 3+ qubit gates using their decomposition rules. Args: dag(DAGCircuit): input dag Returns: DAGCircuit: output dag with maximum node degrees of 2 Raises: QiskitError: if a 3q+ gate is not decomposable """ fo...
Expand a given gate into its decomposition.
def run(self, dag): """Expand a given gate into its decomposition. Args: dag(DAGCircuit): input dag Returns: DAGCircuit: output dag where gate was expanded. """ # Walk through the DAG and expand each non-basis node for node in dag.op_nodes(self.ga...
Apply u2 to q.
def unitary(self, obj, qubits, label=None): """Apply u2 to q.""" if isinstance(qubits, QuantumRegister): qubits = qubits[:] return self.append(UnitaryGate(obj, label=label), qubits, [])
Calculate a subcircuit that implements this unitary.
def _define(self): """Calculate a subcircuit that implements this unitary.""" if self.num_qubits == 1: q = QuantumRegister(1, "q") angles = euler_angles_1q(self.to_matrix()) self.definition = [(U3Gate(*angles), [q[0]], [])] if self.num_qubits == 2: ...
Validate if the value is of the type of the schema s model.
def check_type(self, value, attr, data): """Validate if the value is of the type of the schema's model. Assumes the nested schema is a ``BaseSchema``. """ if self.many and not is_collection(value): raise self._not_expected_type( value, Iterable, fields=[self]...
Validate if it s a list of valid item - field values.
def check_type(self, value, attr, data): """Validate if it's a list of valid item-field values. Check if each element in the list can be validated by the item-field passed during construction. """ super().check_type(value, attr, data) errors = [] for idx, v in e...
Plot the directed acyclic graph ( dag ) to represent operation dependencies in a quantum circuit.
def dag_drawer(dag, scale=0.7, filename=None, style='color'): """Plot the directed acyclic graph (dag) to represent operation dependencies in a quantum circuit. Note this function leverages `pydot <https://github.com/erocarrera/pydot>`_ (via `nxpd <https://github.com/chebee7i/nxpd`_) to generate th...
Set the absolute tolerence parameter for float comparisons.
def _atol(self, atol): """Set the absolute tolerence parameter for float comparisons.""" # NOTE: that this overrides the class value so applies to all # instances of the class. max_tol = self.__class__.MAX_TOL if atol < 0: raise QiskitError("Invalid atol: must be non-...
Set the relative tolerence parameter for float comparisons.
def _rtol(self, rtol): """Set the relative tolerence parameter for float comparisons.""" # NOTE: that this overrides the class value so applies to all # instances of the class. max_tol = self.__class__.MAX_TOL if rtol < 0: raise QiskitError("Invalid rtol: must be non-...
Reshape input and output dimensions of operator.
def _reshape(self, input_dims=None, output_dims=None): """Reshape input and output dimensions of operator. Arg: input_dims (tuple): new subsystem input dimensions. output_dims (tuple): new subsystem output dimensions. Returns: Operator: returns self with res...
Return tuple of input dimension for specified subsystems.
def input_dims(self, qargs=None): """Return tuple of input dimension for specified subsystems.""" if qargs is None: return self._input_dims return tuple(self._input_dims[i] for i in qargs)
Return tuple of output dimension for specified subsystems.
def output_dims(self, qargs=None): """Return tuple of output dimension for specified subsystems.""" if qargs is None: return self._output_dims return tuple(self._output_dims[i] for i in qargs)
Make a copy of current operator.
def copy(self): """Make a copy of current operator.""" # pylint: disable=no-value-for-parameter # The constructor of subclasses from raw data should be a copy return self.__class__(self.data, self.input_dims(), self.output_dims())
Return the compose of a operator with itself n times.
def power(self, n): """Return the compose of a operator with itself n times. Args: n (int): the number of times to compose with self (n>0). Returns: BaseOperator: the n-times composed operator. Raises: QiskitError: if the input and output dimensions...
Check if input dimension corresponds to qubit subsystems.
def _automatic_dims(cls, dims, size): """Check if input dimension corresponds to qubit subsystems.""" if dims is None: dims = size elif np.product(dims) != size: raise QiskitError("dimensions do not match size.") if isinstance(dims, (int, np.integer)): ...
Perform a contraction using Numpy. einsum
def _einsum_matmul(cls, tensor, mat, indices, shift=0, right_mul=False): """Perform a contraction using Numpy.einsum Args: tensor (np.array): a vector or matrix reshaped to a rank-N tensor. mat (np.array): a matrix reshaped to a rank-2M tensor. indices (list): tensor...
Override _deserialize for customizing the exception raised.
def _deserialize(self, value, attr, data): """Override ``_deserialize`` for customizing the exception raised.""" try: return super()._deserialize(value, attr, data) except ValidationError as ex: if 'deserialization_schema_selector' in ex.messages[0]: ex.me...
Override _serialize for customizing the exception raised.
def _serialize(self, value, key, obj): """Override ``_serialize`` for customizing the exception raised.""" try: return super()._serialize(value, key, obj) except TypeError as ex: if 'serialization_schema_selector' in str(ex): raise ValidationError('Data fr...
Check if at least one of the possible choices validates the value.
def check_type(self, value, attr, data): """Check if at least one of the possible choices validates the value. Possible choices are assumed to be ``ModelTypeValidator`` fields. """ for field in self.choices: if isinstance(field, ModelTypeValidator): try: ...
Return the state fidelity between two quantum states.
def state_fidelity(state1, state2): """Return the state fidelity between two quantum states. Either input may be a state vector, or a density matrix. The state fidelity (F) for two density matrices is defined as:: F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2 For a pure state and m...
Apply real scalar function to singular values of a matrix.
def _funm_svd(a, func): """Apply real scalar function to singular values of a matrix. Args: a (array_like): (N, N) Matrix at which to evaluate the function. func (callable): Callable object that evaluates a scalar function f. Returns: ndarray: funm (N, N) Value of the matrix functi...
If dag is mapped to coupling_map the property is_swap_mapped is set to True ( or to False otherwise ).
def run(self, dag): """ If `dag` is mapped to `coupling_map`, the property `is_swap_mapped` is set to True (or to False otherwise). Args: dag (DAGCircuit): DAG to map. """ if self.layout is None: if self.property_set["layout"]: sel...
Take a statevector snapshot of the internal simulator representation. Works on all qubits and prevents reordering ( like barrier ).
def snapshot(self, label, snapshot_type='statevector', qubits=None, params=None): """Take a statevector snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). For other types of snapshots use the Sn...
Assemble a QasmQobjInstruction
def assemble(self): """Assemble a QasmQobjInstruction""" instruction = super().assemble() instruction.label = self._label instruction.snapshot_type = self._snapshot_type return instruction
Special case. Return self.
def inverse(self): """Special case. Return self.""" return Snapshot(self.num_qubits, self.num_clbits, self.params[0], self.params[1])
Set snapshot label to name
def label(self, name): """Set snapshot label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None. """ if isinstance(name, str): self._label = name else: raise TypeError('...
Return True if completely - positive trace - preserving ( CPTP ).
def is_cptp(self, atol=None, rtol=None): """Return True if completely-positive trace-preserving (CPTP).""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_cp_helper(choi, atol, rtol) and self._is_tp_helper( choi, atol, rtol)
Test if a channel is completely - positive ( CP )
def is_tp(self, atol=None, rtol=None): """Test if a channel is completely-positive (CP)""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_tp_helper(choi, atol, rtol)
Test if Choi - matrix is completely - positive ( CP )
def is_cp(self, atol=None, rtol=None): """Test if Choi-matrix is completely-positive (CP)""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_cp_helper(choi, atol, rtol)
Return True if QuantumChannel is a unitary channel.
def is_unitary(self, atol=None, rtol=None): """Return True if QuantumChannel is a unitary channel.""" try: op = self.to_operator() return op.is_unitary(atol=atol, rtol=rtol) except QiskitError: return False
Try to convert channel to a unitary representation Operator.
def to_operator(self): """Try to convert channel to a unitary representation Operator.""" mat = _to_operator(self.rep, self._data, *self.dim) return Operator(mat, self.input_dims(), self.output_dims())
Convert to a Kraus or UnitaryGate circuit instruction.
def to_instruction(self): """Convert to a Kraus or UnitaryGate circuit instruction. If the channel is unitary it will be added as a unitary gate, otherwise it will be added as a kraus simulator instruction. Returns: Instruction: A kraus instruction for the channel. ...
Test if a channel is completely - positive ( CP )
def _is_cp_helper(self, choi, atol, rtol): """Test if a channel is completely-positive (CP)""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol return is_positive_semidefinite_matrix(choi, rtol=rtol, atol=atol)
Test if Choi - matrix is trace - preserving ( TP )
def _is_tp_helper(self, choi, atol, rtol): """Test if Choi-matrix is trace-preserving (TP)""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol # Check if the partial trace is the identity matrix d_in, d_out = self.dim mat = np....
Format input state so it is statevector or density matrix
def _format_state(self, state, density_matrix=False): """Format input state so it is statevector or density matrix""" state = np.array(state) shape = state.shape ndim = state.ndim if ndim > 2: raise QiskitError('Input state is not a vector or matrix.') # Flatt...