docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
A decorator for generating SamplePulse from python callable. Args: func (callable): A function describing pulse envelope. Raises: PulseError: when invalid function is specified.
def functional_pulse(func): @functools.wraps(func) def to_pulse(duration, *args, name=None, **kwargs): if isinstance(duration, int) and duration > 0: samples = func(duration, *args, **kwargs) samples = np.asarray(samples, dtype=np.complex128) return SamplePulse(samples=samples, name=name) raise PulseError('The first argument must be an integer value representing duration.') return to_pulse
159,170
Create a DAG node out of a parsed AST op node. Args: name (str): operation name to apply to the dag. params (list): op parameters qargs (list(QuantumRegister, int)): qubits to attach to Raises: QiskitError: if encountering a non-basis opaque gate
def _create_dag_op(self, name, params, qargs): if name == "u0": op_class = U0Gate elif name == "u1": op_class = U1Gate elif name == "u2": op_class = U2Gate elif name == "u3": op_class = U3Gate elif name == "x": op_class = XGate elif name == "y": op_class = YGate elif name == "z": op_class = ZGate elif name == "t": op_class = TGate elif name == "tdg": op_class = TdgGate elif name == "s": op_class = SGate elif name == "sdg": op_class = SdgGate elif name == "swap": op_class = SwapGate elif name == "rx": op_class = RXGate elif name == "ry": op_class = RYGate elif name == "rz": op_class = RZGate elif name == "rzz": op_class = RZZGate elif name == "id": op_class = IdGate elif name == "h": op_class = HGate elif name == "cx": op_class = CnotGate elif name == "cy": op_class = CyGate elif name == "cz": op_class = CzGate elif name == "ch": op_class = CHGate elif name == "crz": op_class = CrzGate elif name == "cu1": op_class = Cu1Gate elif name == "cu3": op_class = Cu3Gate elif name == "ccx": op_class = ToffoliGate elif name == "cswap": op_class = FredkinGate else: raise QiskitError("unknown operation for ast node name %s" % name) op = op_class(*params) self.dag.apply_operation_back(op, qargs, [], condition=self.condition)
159,183
Create empty schedule. Args: *schedules: Child Schedules of this parent Schedule. May either be passed as the list of schedules, or a list of (start_time, schedule) pairs name: Name of this schedule Raises: PulseError: If timeslots intercept.
def __init__(self, *schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]], name: str = None): self._name = name try: timeslots = [] children = [] for sched_pair in schedules: # recreate as sequence starting at 0. if not isinstance(sched_pair, (list, tuple)): sched_pair = (0, sched_pair) # convert to tuple sched_pair = tuple(sched_pair) insert_time, sched = sched_pair sched_timeslots = sched.timeslots if insert_time: sched_timeslots = sched_timeslots.shift(insert_time) timeslots.append(sched_timeslots.timeslots) children.append(sched_pair) self._timeslots = TimeslotCollection(*itertools.chain(*timeslots)) self._children = tuple(children) except PulseError as ts_err: raise PulseError('Child schedules {0} overlap.'.format(schedules)) from ts_err
159,185
Return duration of supplied channels. Args: *channels: Supplied channels
def ch_duration(self, *channels: List[Channel]) -> int: return self.timeslots.ch_duration(*channels)
159,186
Return minimum start time for supplied channels. Args: *channels: Supplied channels
def ch_start_time(self, *channels: List[Channel]) -> int: return self.timeslots.ch_start_time(*channels)
159,187
Return maximum start time for supplied channels. Args: *channels: Supplied channels
def ch_stop_time(self, *channels: List[Channel]) -> int: return self.timeslots.ch_stop_time(*channels)
159,188
Iterable for flattening Schedule tree. Args: time: Shifted time due to parent Yields: Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts at and the flattened `ScheduleComponent`.
def _instructions(self, time: int = 0) -> Iterable[Tuple[int, 'Instruction']]: for insert_time, child_sched in self.children: yield from child_sched._instructions(time + insert_time)
159,189
Truncate small values of a complex array. Args: array (array_like): array to truncte small values. epsilon (float): threshold. Returns: np.array: A new operator with small values set to zero.
def chop(array, epsilon=1e-10): ret = np.array(array) if np.isrealobj(ret): ret[abs(ret) < epsilon] = 0.0 else: ret.real[abs(ret.real) < epsilon] = 0.0 ret.imag[abs(ret.imag) < epsilon] = 0.0 return ret
159,209
Construct the outer product of two vectors. The second vector argument is optional, if absent the projector of the first vector will be returned. Args: vector1 (ndarray): the first vector. vector2 (ndarray): the (optional) second vector. Returns: np.array: The matrix |v1><v2|.
def outer(vector1, vector2=None): if vector2 is None: vector2 = np.array(vector1).conj() else: vector2 = np.array(vector2).conj() return np.outer(vector1, vector2)
159,210
Calculate the concurrence. Args: state (np.array): a quantum state (1x4 array) or a density matrix (4x4 array) Returns: float: concurrence. Raises: Exception: if attempted on more than two qubits.
def concurrence(state): rho = np.array(state) if rho.ndim == 1: rho = outer(state) if len(state) != 4: raise Exception("Concurrence is only defined for more than two qubits") YY = np.fliplr(np.diag([-1, 1, 1, -1])) A = rho.dot(YY).dot(rho.conj()).dot(YY) w = la.eigh(A, eigvals_only=True) w = np.sqrt(np.maximum(w, 0)) return max(0.0, w[-1] - np.sum(w[0:-1]))
159,213
Compute the Shannon entropy of a probability vector. The shannon entropy of a probability vector pv is defined as $H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$. Args: pvec (array_like): a probability vector. base (int): the base of the logarith Returns: float: The Shannon entropy H(pvec).
def shannon_entropy(pvec, base=2): # pylint: disable=missing-docstring if base == 2: def logfn(x): return - x * np.log2(x) elif base == np.e: def logfn(x): return - x * np.log(x) else: def logfn(x): return -x * np.log(x) / np.log(base) h = 0. for x in pvec: if 0 < x < 1: h += logfn(x) return h
159,214
Compute the von-Neumann entropy of a quantum state. Args: state (array_like): a density matrix or state vector. Returns: float: The von-Neumann entropy S(rho).
def entropy(state): rho = np.array(state) if rho.ndim == 1: return 0 evals = np.maximum(np.linalg.eigvalsh(state), 0.) return shannon_entropy(evals, base=np.e)
159,215
Compute the mutual information of a bipartite state. Args: state (array_like): a bipartite state-vector or density-matrix. d0 (int): dimension of the first subsystem. d1 (int or None): dimension of the second subsystem. Returns: float: The mutual information S(rho_A) + S(rho_B) - S(rho_AB).
def mutual_information(state, d0, d1=None): if d1 is None: d1 = int(len(state) / d0) mi = entropy(partial_trace(state, [0], dimensions=[d0, d1])) mi += entropy(partial_trace(state, [1], dimensions=[d0, d1])) mi -= entropy(state) return mi
159,216
Compute the entanglement of formation of quantum state. The input quantum state must be either a bipartite state vector, or a 2-qubit density matrix. Args: state (array_like): (N) array_like or (4,4) array_like, a bipartite quantum state. d0 (int): the dimension of the first subsystem. d1 (int or None): the dimension of the second subsystem. Returns: float: The entanglement of formation.
def entanglement_of_formation(state, d0, d1=None): state = np.array(state) if d1 is None: d1 = int(len(state) / d0) if state.ndim == 2 and len(state) == 4 and d0 == 2 and d1 == 2: return __eof_qubit(state) elif state.ndim == 1: # trace out largest dimension if d0 < d1: tr = [1] else: tr = [0] state = partial_trace(state, tr, dimensions=[d0, d1]) return entropy(state) else: print('Input must be a state-vector or 2-qubit density matrix.') return None
159,217
Compute the Entanglement of Formation of a 2-qubit density matrix. Args: rho ((array_like): (4,4) array_like, input density matrix. Returns: float: The entanglement of formation.
def __eof_qubit(rho): c = concurrence(rho) c = 0.5 + 0.5 * np.sqrt(1 - c * c) return shannon_entropy([c, 1 - c])
159,218
Create a union (and also shift if desired) of all input `Schedule`s. Args: *schedules: Schedules to take the union of name: Name of the new schedule. Defaults to first element of `schedules`
def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]], name: str = None) -> Schedule: if name is None and schedules: sched = schedules[0] if isinstance(sched, (list, tuple)): name = sched[1].name else: name = sched.name return Schedule(*schedules, name=name)
159,219
Create a flattened schedule. Args: schedule: Schedules to flatten name: Name of the new schedule. Defaults to first element of `schedules`
def flatten(schedule: ScheduleComponent, name: str = None) -> Schedule: if name is None: name = schedule.name return Schedule(*schedule.instructions, name=name)
159,220
Return schedule shifted by `time`. Args: schedule: The schedule to shift time: The time to shift by name: Name of shifted schedule. Defaults to name of `schedule`
def shift(schedule: ScheduleComponent, time: int, name: str = None) -> Schedule: if name is None: name = schedule.name return union((time, schedule), name=name)
159,221
Return a new schedule with the `child` schedule inserted into the `parent` at `start_time`. Args: parent: Schedule to be inserted into time: Time to be inserted defined with respect to `parent` child: Schedule to insert name: Name of the new schedule. Defaults to name of parent
def insert(parent: ScheduleComponent, time: int, child: ScheduleComponent, name: str = None) -> Schedule: return union(parent, (time, child), name=name)
159,222
r"""Return a new schedule with by appending `child` to `parent` at the last time of the `parent` schedule's channels over the intersection of the parent and child schedule's channels. $t = \textrm{max}({x.stop\_time |x \in parent.channels \cap child.channels})$ Args: parent: The schedule to be inserted into child: The schedule to insert name: Name of the new schedule. Defaults to name of parent
def append(parent: ScheduleComponent, child: ScheduleComponent, name: str = None) -> Schedule: r common_channels = set(parent.channels) & set(child.channels) insertion_time = parent.ch_stop_time(*common_channels) return insert(parent, insertion_time, child, name=name)
159,223
Base class for backends. This method should initialize the module and its configuration, and raise an exception if a component of the module is not available. Args: configuration (BackendConfiguration): backend configuration provider (BaseProvider): provider responsible for this backend Raises: FileNotFoundError if backend executable is not available. QiskitError: if there is no name in the configuration
def __init__(self, configuration, provider=None): self._configuration = configuration self._provider = provider
159,225
Start the progress bar. Parameters: iterations (int): Number of iterations.
def start(self, iterations): self.touched = True self.iter = int(iterations) self.t_start = time.time()
159,229
Estimate the remaining time left. Parameters: completed_iter (int): Number of iterations completed. Returns: est_time: Estimated time remaining.
def time_remaining_est(self, completed_iter): if completed_iter: t_r_est = (time.time() - self.t_start) / \ completed_iter*(self.iter-completed_iter) else: t_r_est = 0 date_time = datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=t_r_est) time_string = "%02d:%02d:%02d:%02d" % \ (date_time.day - 1, date_time.hour, date_time.minute, date_time.second) return time_string
159,230
Run the CommutativeCancellation pass on a dag Args: dag (DAGCircuit): the DAG to be optimized. Returns: DAGCircuit: the optimized DAG. Raises: TranspilerError: when the 1 qubit rotation gates are not found
def run(self, dag): q_gate_list = ['cx', 'cy', 'cz', 'h', 'x', 'y', 'z'] # Gate sets to be cancelled cancellation_sets = defaultdict(lambda: []) for wire in dag.wires: wire_name = "{0}[{1}]".format(str(wire[0].name), str(wire[1])) wire_commutation_set = self.property_set['commutation_set'][wire_name] for com_set_idx, com_set in enumerate(wire_commutation_set): if com_set[0].type in ['in', 'out']: continue for node in com_set: num_qargs = len(node.qargs) if num_qargs == 1 and node.name in q_gate_list: cancellation_sets[(node.name, wire_name, com_set_idx)].append(node) if num_qargs == 1 and node.name in ['u1', 'rz', 't', 's']: cancellation_sets[('z_rotation', wire_name, com_set_idx)].append(node) elif num_qargs == 2 and node.qargs[0] == wire: second_op_name = "{0}[{1}]".format(str(node.qargs[1][0].name), str(node.qargs[1][1])) q2_key = (node.name, wire_name, second_op_name, self.property_set['commutation_set'][(node, second_op_name)]) cancellation_sets[q2_key].append(node) for cancel_set_key in cancellation_sets: set_len = len(cancellation_sets[cancel_set_key]) if ((set_len) > 1 and cancel_set_key[0] in q_gate_list): gates_to_cancel = cancellation_sets[cancel_set_key] for c_node in gates_to_cancel[:(set_len // 2) * 2]: dag.remove_op_node(c_node) elif((set_len) > 1 and cancel_set_key[0] == 'z_rotation'): run = cancellation_sets[cancel_set_key] run_qarg = run[0].qargs[0] total_angle = 0.0 # lambda for current_node in run: if (current_node.condition is not None or len(current_node.qargs) != 1 or current_node.qargs[0] != run_qarg): raise TranspilerError("internal error") if current_node.name in ['u1', 'rz']: current_angle = float(current_node.op.params[0]) elif current_node.name == 't': current_angle = sympy.pi / 4 elif current_node.name == 's': current_angle = sympy.pi / 2 # Compose gates total_angle = current_angle + total_angle # Replace the data of the first node in the run new_op = U1Gate(total_angle) new_qarg = (QuantumRegister(1, 'q'), 0) new_dag = DAGCircuit() new_dag.add_qreg(new_qarg[0]) new_dag.apply_operation_back(new_op, [new_qarg]) dag.substitute_node_with_dag(run[0], new_dag) # Delete the other nodes in the run for current_node in run[1:]: dag.remove_op_node(current_node) return dag
159,234
Return a list of QuantumCircuit object(s) from a qobj Args: qobj (Qobj): The Qobj object to convert to QuantumCircuits Returns: list: A list of QuantumCircuit objects from the qobj
def _experiments_to_circuits(qobj): if qobj.experiments: circuits = [] for x in qobj.experiments: quantum_registers = [QuantumRegister(i[1], name=i[0]) for i in x.header.qreg_sizes] classical_registers = [ClassicalRegister(i[1], name=i[0]) for i in x.header.creg_sizes] circuit = QuantumCircuit(*quantum_registers, *classical_registers, name=x.header.name) qreg_dict = {} creg_dict = {} for reg in quantum_registers: qreg_dict[reg.name] = reg for reg in classical_registers: creg_dict[reg.name] = reg for i in x.instructions: instr_method = getattr(circuit, i.name) qubits = [] try: for qubit in i.qubits: qubit_label = x.header.qubit_labels[qubit] qubits.append( qreg_dict[qubit_label[0]][qubit_label[1]]) except Exception: # pylint: disable=broad-except pass clbits = [] try: for clbit in i.memory: clbit_label = x.header.clbit_labels[clbit] clbits.append( creg_dict[clbit_label[0]][clbit_label[1]]) except Exception: # pylint: disable=broad-except pass params = [] try: params = i.params except Exception: # pylint: disable=broad-except pass if i.name in ['snapshot']: instr_method( i.label, snapshot_type=i.snapshot_type, qubits=qubits, params=params) elif i.name == 'initialize': instr_method(params, qubits) else: instr_method(*params, *qubits, *clbits) circuits.append(circuit) return circuits return None
159,235
Dissasemble a qobj and return the circuits, run_config, and user header Args: qobj (Qobj): The input qobj object to dissasemble Returns: circuits (list): A list of quantum circuits run_config (dict): The dist of the run config user_qobj_header (dict): The dict of any user headers in the qobj
def disassemble(qobj): run_config = qobj.config.to_dict() user_qobj_header = qobj.header.to_dict() circuits = _experiments_to_circuits(qobj) return circuits, run_config, user_qobj_header
159,236
Calculate the Hamming distance between two bit strings Args: str1 (str): First string. str2 (str): Second string. Returns: int: Distance between strings. Raises: VisualizationError: Strings not same length
def hamming_distance(str1, str2): if len(str1) != len(str2): raise VisualizationError('Strings not same length.') return sum(s1 != s2 for s1, s2 in zip(str1, str2))
159,237
Return quaternion for rotation about given axis. Args: angle (float): Angle in radians. axis (str): Axis for rotation Returns: Quaternion: Quaternion for axis rotation. Raises: ValueError: Invalid input axis.
def quaternion_from_axis_rotation(angle, axis): out = np.zeros(4, dtype=float) if axis == 'x': out[1] = 1 elif axis == 'y': out[2] = 1 elif axis == 'z': out[3] = 1 else: raise ValueError('Invalid axis input.') out *= math.sin(angle/2.0) out[0] = math.cos(angle/2.0) return Quaternion(out)
159,239
Generate a quaternion from a set of Euler angles. Args: angles (array_like): Array of Euler angles. order (str): Order of Euler rotations. 'yzy' is default. Returns: Quaternion: Quaternion representation of Euler rotation.
def quaternion_from_euler(angles, order='yzy'): angles = np.asarray(angles, dtype=float) quat = quaternion_from_axis_rotation(angles[0], order[0])\ * (quaternion_from_axis_rotation(angles[1], order[1]) * quaternion_from_axis_rotation(angles[2], order[2])) quat.normalize(inplace=True) return quat
159,240
Normalizes a Quaternion to unit length so that it represents a valid rotation. Args: inplace (bool): Do an inplace normalization. Returns: Quaternion: Normalized quaternion.
def normalize(self, inplace=False): if inplace: nrm = self.norm() self.data /= nrm return None nrm = self.norm() data_copy = np.array(self.data, copy=True) data_copy /= nrm return Quaternion(data_copy)
159,243
Prepare received data for representation. Args: data (dict): values to represent (ex. {'001' : 130}) number_to_keep (int): number of elements to show individually. Returns: dict: processed data to show.
def process_data(data, number_to_keep): result = dict() if number_to_keep != 0: data_temp = dict(Counter(data).most_common(number_to_keep)) data_temp['rest'] = sum(data.values()) - sum(data_temp.values()) data = data_temp labels = data values = np.array([data[key] for key in labels], dtype=float) pvalues = values / sum(values) for position, label in enumerate(labels): result[label] = round(pvalues[position], 5) return result
159,246
Create new model. Args: valid_value_types (tuple): valid types as values.
def __init__(self, valid_value_types, **kwargs): # pylint: disable=missing-param-doc super(DictParameters, self).__init__(**kwargs) self.valid_value_types = valid_value_types
159,253
Two Registers are the same if they are of the same type (i.e. quantum/classical), and have the same name and size. Args: other (Register): other Register Returns: bool: are self and other equal.
def __eq__(self, other): res = False if type(self) is type(other) and \ self.name == other.name and \ self.size == other.size: res = True return res
159,260
Create a new gate. Args: name (str): the Qobj name of the gate num_qubits (int): the number of qubits the gate acts on. params (list): a list of parameters. label (str or None): An optional label for the gate [Default: None]
def __init__(self, name, num_qubits, params, label=None): self._label = label super().__init__(name, num_qubits, 0, params)
159,263
Create new snapshot command. Args: name (str): Snapshot name which is used to identify the snapshot in the output. snap_type (str): Type of snapshot, e.g., β€œstate” (take a snapshot of the quantum state). The types of snapshots offered are defined in a separate specification document for simulators.
def __init__(self, name: str, snap_type: str): self._type = snap_type self._channel = SnapshotChannel() Command.__init__(self, duration=0, name=name) Instruction.__init__(self, self, self._channel, name=name)
159,278
Left sample a continuous function. Args: continuous_pulse: Continuous pulse function to sample. duration: Duration to sample for. *args: Continuous pulse function args. **kwargs: Continuous pulse function kwargs.
def left_sample(continuous_pulse: Callable, duration: int, *args, **kwargs) -> np.ndarray: times = np.arange(duration) return continuous_pulse(times, *args, **kwargs)
159,283
Add a list of data points to bloch sphere. Args: points (array_like): Collection of data points. meth (str): Type of points to plot, use 'm' for multicolored, 'l' for points connected with a line.
def add_points(self, points, meth='s'): if not isinstance(points[0], (list, np.ndarray)): points = [[points[0]], [points[1]], [points[2]]] points = np.array(points) if meth == 's': if len(points[0]) == 1: pnts = np.array([[points[0][0]], [points[1][0]], [points[2][0]]]) pnts = np.append(pnts, points, axis=1) else: pnts = points self.points.append(pnts) self.point_style.append('s') elif meth == 'l': self.points.append(points) self.point_style.append('l') else: self.points.append(points) self.point_style.append('m')
159,314
Add a list of vectors to Bloch sphere. Args: vectors (array_like): Array with vectors of unit length or smaller.
def add_vectors(self, vectors): if isinstance(vectors[0], (list, np.ndarray)): for vec in vectors: self.vectors.append(vec) else: self.vectors.append(vectors)
159,315
Saves Bloch sphere to file of type ``format`` in directory ``dirc``. Args: name (str): Name of saved image. Must include path and format as well. i.e. '/Users/Paul/Desktop/bloch.png' This overrides the 'format' and 'dirc' arguments. output (str): Format of output image. dirc (str): Directory for output images. Defaults to current working directory.
def save(self, name=None, output='png', dirc=None): self.render() if dirc: if not os.path.isdir(os.getcwd() + "/" + str(dirc)): os.makedirs(os.getcwd() + "/" + str(dirc)) if name is None: if dirc: self.fig.savefig(os.getcwd() + "/" + str(dirc) + '/bloch_' + str(self.savenum) + '.' + output) else: self.fig.savefig(os.getcwd() + '/bloch_' + str(self.savenum) + '.' + output) else: self.fig.savefig(name) self.savenum += 1 if self.fig: plt.close(self.fig)
159,325
Connects boxes and elements using wire_char and setting proper connectors. Args: wire_char (char): For example 'β•‘' or 'β”‚'. where (list["top", "bot"]): Where the connector should be set. label (string): Some connectors have a label (see cu1, for example).
def connect(self, wire_char, where, label=None): if 'top' in where and self.top_connector: self.top_connect = self.top_connector[wire_char] if 'bot' in where and self.bot_connector: self.bot_connect = self.bot_connector[wire_char] if label: self.top_format = self.top_format[:-1] + (label if label else "")
159,332
In multi-bit elements, the label is centered vertically. Args: input_length (int): Rhe amount of wires affected. order (int): Which middle element is this one?
def center_label(self, input_length, order): location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1 top_limit = order * 2 + 2 bot_limit = top_limit + 2 if top_limit <= location_in_the_box < bot_limit: if location_in_the_box == top_limit: self.top_connect = self.label elif location_in_the_box == top_limit + 1: self.mid_content = self.label else: self.bot_connect = self.label
159,336
Given a layer, replace the Nones in it with EmptyWire elements. Args: layer (list): The layer that contains Nones. first_clbit (int): The first wire that is classic. Returns: list: The new layer, with no Nones.
def fillup_layer(layer, first_clbit): for nones in [i for i, x in enumerate(layer) if x is None]: layer[nones] = EmptyWire('═') if nones >= first_clbit else EmptyWire('─') return layer
159,347
Creates a layer with BreakWire elements. Args: layer_length (int): The length of the layer to create arrow_char (char): The char used to create the BreakWire element. Returns: list: The new layer.
def fillup_layer(layer_length, arrow_char): breakwire_layer = [] for _ in range(layer_length): breakwire_layer.append(BreakWire(arrow_char)) return breakwire_layer
159,349
Creates a layer with InputWire elements. Args: names (list): List of names for the wires. Returns: list: The new layer
def fillup_layer(names): # pylint: disable=arguments-differ longest = max([len(name) for name in names]) inputs_wires = [] for name in names: inputs_wires.append(InputWire(name.rjust(longest))) return inputs_wires
159,350
Dumps the ascii art in the file. Args: filename (str): File to dump the ascii art. encoding (str): Optional. Default "utf-8".
def dump(self, filename, encoding="utf8"): with open(filename, mode='w', encoding=encoding) as text_file: text_file.write(self.single_string())
159,354
Returns a list of names for each wire. Args: with_initial_value (bool): Optional (Default: True). If true, adds the initial value to the name. Returns: List: The list of wire names.
def wire_names(self, with_initial_value=True): qubit_labels = self._get_qubit_labels() clbit_labels = self._get_clbit_labels() if with_initial_value: qubit_labels = ['%s: |0>' % qubit for qubit in qubit_labels] clbit_labels = ['%s: 0 ' % clbit for clbit in clbit_labels] else: qubit_labels = ['%s: ' % qubit for qubit in qubit_labels] clbit_labels = ['%s: ' % clbit for clbit in clbit_labels] return qubit_labels + clbit_labels
159,356
Given a list of wires, creates a list of lines with the text drawing. Args: wires (list): A list of wires with instructions. vertically_compressed (bool): Default is `True`. It merges the lines so the drawing will take less vertical room. Returns: list: A list of lines with the text drawing.
def draw_wires(wires, vertically_compressed=True): lines = [] bot_line = None for wire in wires: # TOP top_line = '' for instruction in wire: top_line += instruction.top if bot_line is None: lines.append(top_line) else: if vertically_compressed: lines.append(TextDrawing.merge_lines(lines.pop(), top_line)) else: lines.append(TextDrawing.merge_lines(lines[-1], top_line, icod="bot")) # MID mid_line = '' for instruction in wire: mid_line += instruction.mid lines.append(TextDrawing.merge_lines(lines[-1], mid_line, icod="bot")) # BOT bot_line = '' for instruction in wire: bot_line += instruction.bot lines.append(TextDrawing.merge_lines(lines[-1], bot_line, icod="bot")) return lines
159,357
Merges two lines (top and bot) in the way that the overlapping make senses. Args: top (str): the top line bot (str): the bottom line icod (top or bot): in case of doubt, which line should have priority? Default: "top". Returns: str: The merge of both lines.
def merge_lines(top, bot, icod="top"): ret = "" for topc, botc in zip(top, bot): if topc == botc: ret += topc elif topc in 'β”Όβ•ͺ' and botc == " ": ret += "β”‚" elif topc == " ": ret += botc elif topc in '┬β•₯' and botc in " β•‘β”‚" and icod == "top": ret += topc elif topc in '┬' and botc == " " and icod == "bot": ret += 'β”‚' elif topc in 'β•₯' and botc == " " and icod == "bot": ret += 'β•‘' elif topc in '┬│' and botc == "═": ret += 'β•ͺ' elif topc in '┬│' and botc == "─": ret += 'β”Ό' elif topc in 'β””β”˜β•‘β”‚β–‘' and botc == " " and icod == "top": ret += topc elif topc in '─═' and botc == " " and icod == "top": ret += topc elif topc in '─═' and botc == " " and icod == "bot": ret += botc elif topc in "β•‘β•₯" and botc in "═": ret += "╬" elif topc in "β•‘β•₯" and botc in "─": ret += "β•«" elif topc in '╫╬' and botc in " ": ret += "β•‘" elif topc == 'β””' and botc == "β”Œ": ret += "β”œ" elif topc == 'β”˜' and botc == "┐": ret += "─" elif botc in "β”β”Œ" and icod == 'top': ret += "┬" elif topc in "β”˜β””" and botc in "─" and icod == 'top': ret += "β”΄" else: ret += botc return ret
159,360
When the elements of the layer have different widths, sets the width to the max elements. Args: layer (list): A list of elements.
def normalize_width(layer): instructions = [instruction for instruction in filter(lambda x: x is not None, layer)] longest = max([instruction.length for instruction in instructions]) for instruction in instructions: instruction.layer_width = longest
159,361
Sets the qubit to the element Args: qubit (qbit): Element of self.qregs. element (DrawElement): Element to set in the qubit
def set_qubit(self, qubit, element): self.qubit_layer[self.qregs.index(qubit)] = element
159,365
Sets the clbit to the element Args: clbit (cbit): Element of self.cregs. element (DrawElement): Element to set in the clbit
def set_clbit(self, clbit, element): self.clbit_layer[self.cregs.index(clbit)] = element
159,366
Sets the multi clbit box. Args: creg (string): The affected classical register. label (string): The label for the multi clbit box. top_connect (char): The char to connect the box on the top.
def set_cl_multibox(self, creg, label, top_connect='β”΄'): clbit = [bit for bit in self.cregs if bit[0] == creg] self._set_multibox("cl", clbit, label, top_connect=top_connect)
159,368
Connects the elements in the layer using wire_char. Args: wire_char (char): For example 'β•‘' or 'β”‚'.
def connect_with(self, wire_char): if len([qbit for qbit in self.qubit_layer if qbit is not None]) == 1: # Nothing to connect return for label, affected_bits in self.connections: if not affected_bits: continue affected_bits[0].connect(wire_char, ['bot']) for affected_bit in affected_bits[1:-1]: affected_bit.connect(wire_char, ['bot', 'top']) affected_bits[-1].connect(wire_char, ['top'], label) if label: for affected_bit in affected_bits: affected_bit.right_fill = len(label) + len(affected_bit.mid)
159,369
Checks if internet connection exists to host via specified port. If any exception is raised while trying to open a socket this will return false. Args: hostname (str): Hostname to connect to. port (int): Port to connect to Returns: bool: Has connection or not
def _has_connection(hostname, port): try: host = socket.gethostbyname(hostname) socket.create_connection((host, port), 2) return True except Exception: # pylint: disable=broad-except return False
159,377
The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: PTM: the matrix power of the SuperOp converted to a PTM channel. Raises: QiskitError: if the input and output dimensions of the QuantumChannel are not equal, or the power is not an integer.
def power(self, n): if n > 0: return super().power(n) return PTM(SuperOp(self).power(n))
159,380
Internal function that updates the status of a HTML job monitor. Args: job_var (BaseJob): The job to keep track of. interval (int): The status check interval status (widget): HTML ipywidget for output ot screen header (str): String representing HTML code for status. _interval_set (bool): Was interval set by user?
def _html_checker(job_var, interval, status, header, _interval_set=False): job_status = job_var.status() job_status_name = job_status.name job_status_msg = job_status.value status.value = header % (job_status_msg) while job_status_name not in ['DONE', 'CANCELLED']: time.sleep(interval) job_status = job_var.status() job_status_name = job_status.name job_status_msg = job_status.value if job_status_name == 'ERROR': break else: if job_status_name == 'QUEUED': job_status_msg += ' (%s)' % job_var.queue_position() if not _interval_set: interval = max(job_var.queue_position(), 2) else: if not _interval_set: interval = 2 status.value = header % (job_status_msg) status.value = header % (job_status_msg)
159,381
Continuous constant pulse. Args: times: Times to output pulse for. amp: Complex pulse amplitude.
def constant(times: np.ndarray, amp: complex) -> np.ndarray: return np.full(len(times), amp, dtype=np.complex_)
159,383
Continuous square wave. Args: times: Times to output wave for. amp: Pulse amplitude. Wave range is [-amp, amp]. period: Pulse period, units of dt. phase: Pulse phase.
def square(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray: x = times/period+phase/np.pi return amp*(2*(2*np.floor(x) - np.floor(2*x)) + 1).astype(np.complex_)
159,384
Continuous triangle wave. Args: times: Times to output wave for. amp: Pulse amplitude. Wave range is [-amp, amp]. period: Pulse period, units of dt. phase: Pulse phase.
def triangle(times: np.ndarray, amp: complex, period: float, phase: float = 0) -> np.ndarray: return amp*(-2*np.abs(sawtooth(times, 1, period, (phase-np.pi/2)/2)) + 1).astype(np.complex_)
159,385
Continuous cosine wave. Args: times: Times to output wave for. amp: Pulse amplitude. freq: Pulse frequency, units of 1/dt. phase: Pulse phase.
def cos(times: np.ndarray, amp: complex, freq: float, phase: float = 0) -> np.ndarray: return amp*np.cos(2*np.pi*freq*times+phase).astype(np.complex_)
159,386
Continuous unnormalized gaussian derivative pulse. Args: times: Times to output pulse for. amp: Pulse amplitude at `center`. center: Center (mean) of pulse. sigma: Width (standard deviation) of pulse. ret_gaussian: Return gaussian with which derivative was taken with.
def gaussian_deriv(times: np.ndarray, amp: complex, center: float, sigma: float, ret_gaussian: bool = False) -> np.ndarray: gauss, x = gaussian(times, amp=amp, center=center, sigma=sigma, ret_x=True) gauss_deriv = -x/sigma*gauss if ret_gaussian: return gauss_deriv, gauss return gauss_deriv
159,389
r"""Continuous gaussian square pulse. Args: times: Times to output pulse for. amp: Pulse amplitude. center: Center of the square pulse component. width: Width of the square pulse component. sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse. zeroed_width: Subtract baseline of gaussian square pulse to enforce $\OmegaSquare(center \pm zeroed_width/2)=0$.
def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float, sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray: r square_start = center-width/2 square_stop = center+width/2 if zeroed_width: zeroed_width = min(width, zeroed_width) gauss_zeroed_width = zeroed_width-width else: gauss_zeroed_width = None funclist = [functools.partial(gaussian, amp=amp, center=square_start, sigma=sigma, zeroed_width=gauss_zeroed_width, rescale_amp=True), functools.partial(gaussian, amp=amp, center=square_stop, sigma=sigma, zeroed_width=gauss_zeroed_width, rescale_amp=True), functools.partial(constant, amp=amp)] condlist = [times <= square_start, times >= square_stop] return np.piecewise(times.astype(np.complex_), condlist, funclist)
159,390
The default pass manager that maps to the coupling map. Args: basis_gates (list[str]): list of basis gate names supported by the target. coupling_map (CouplingMap): coupling map to target in mapping. initial_layout (Layout or None): initial layout of virtual qubits on physical qubits seed_transpiler (int or None): random seed for stochastic passes. Returns: PassManager: A pass manager to map and optimize.
def default_pass_manager(basis_gates, coupling_map, initial_layout, seed_transpiler): pass_manager = PassManager() pass_manager.property_set['layout'] = initial_layout pass_manager.append(Unroller(basis_gates)) # Use the trivial layout if no layout is found pass_manager.append(TrivialLayout(coupling_map), condition=lambda property_set: not property_set['layout']) # if the circuit and layout already satisfy the coupling_constraints, use that layout # otherwise layout on the most densely connected physical qubit subset pass_manager.append(CheckMap(coupling_map)) pass_manager.append(DenseLayout(coupling_map), condition=lambda property_set: not property_set['is_swap_mapped']) # Extend the the dag/layout with ancillas using the full coupling map pass_manager.append(FullAncillaAllocation(coupling_map)) pass_manager.append(EnlargeWithAncilla()) # Circuit must only contain 1- or 2-qubit interactions for swapper to work pass_manager.append(Unroll3qOrMore()) # Swap mapper pass_manager.append(LegacySwap(coupling_map, trials=20, seed=seed_transpiler)) # Expand swaps pass_manager.append(Decompose(SwapGate)) # Change CX directions pass_manager.append(CXDirection(coupling_map)) # Unroll to the basis pass_manager.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx'])) # Simplify single qubit gates and CXs simplification_passes = [Optimize1qGates(), CXCancellation(), RemoveResetInZeroState()] pass_manager.append(simplification_passes + [Depth(), FixedPoint('depth')], do_while=lambda property_set: not property_set['depth_fixed_point']) return pass_manager
159,392
The default pass manager without a coupling map. Args: basis_gates (list[str]): list of basis gate names to unroll to. Returns: PassManager: A passmanager that just unrolls, without any optimization.
def default_pass_manager_simulator(basis_gates): pass_manager = PassManager() pass_manager.append(Unroller(basis_gates)) pass_manager.append([RemoveResetInZeroState(), Depth(), FixedPoint('depth')], do_while=lambda property_set: not property_set['depth_fixed_point']) return pass_manager
159,393
Test if this circuit has the register r. Args: register (Register): a quantum or classical register. Returns: bool: True if the register is contained in this circuit.
def has_register(self, register): has_reg = False if (isinstance(register, QuantumRegister) and register in self.qregs): has_reg = True elif (isinstance(register, ClassicalRegister) and register in self.cregs): has_reg = True return has_reg
159,397
How many non-entangled subcircuits can the circuit be factored to. Args: unitary_only (bool): Compute only unitary part of graph. Returns: int: Number of connected components in circuit.
def num_connected_components(self, unitary_only=False): # Convert registers to ints (as done in depth). reg_offset = 0 reg_map = {} if unitary_only: regs = self.qregs else: regs = self.qregs+self.cregs for reg in regs: reg_map[reg.name] = reg_offset reg_offset += reg.size # Start with each qubit or cbit being its own subgraph. sub_graphs = [[bit] for bit in range(reg_offset)] num_sub_graphs = len(sub_graphs) # Here we are traversing the gates and looking to see # which of the sub_graphs the gate joins together. for instr, qargs, cargs in self.data: if unitary_only: args = qargs num_qargs = len(args) else: args = qargs+cargs num_qargs = len(args) + (1 if instr.control else 0) if num_qargs >= 2 and instr.name not in ['barrier', 'snapshot']: graphs_touched = [] num_touched = 0 # Controls necessarily join all the cbits in the # register that they use. if instr.control and not unitary_only: creg = instr.control[0] creg_int = reg_map[creg.name] for coff in range(creg.size): temp_int = creg_int+coff for k in range(num_sub_graphs): if temp_int in sub_graphs[k]: graphs_touched.append(k) num_touched += 1 break for item in args: reg_int = reg_map[item[0].name]+item[1] for k in range(num_sub_graphs): if reg_int in sub_graphs[k]: if k not in graphs_touched: graphs_touched.append(k) num_touched += 1 break # If the gate touches more than one subgraph # join those graphs together and return # reduced number of subgraphs if num_touched > 1: connections = [] for idx in graphs_touched: connections.extend(sub_graphs[idx]) _sub_graphs = [] for idx in range(num_sub_graphs): if idx not in graphs_touched: _sub_graphs.append(sub_graphs[idx]) _sub_graphs.append(connections) sub_graphs = _sub_graphs num_sub_graphs -= (num_touched-1) # Cannot go lower than one so break if num_sub_graphs == 1: break return num_sub_graphs
159,416
Assign parameters to values yielding a new circuit. Args: value_dict (dict): {parameter: value, ...} Raises: QiskitError: If value_dict contains parameters not present in the circuit Returns: QuantumCircuit: copy of self with assignment substitution.
def bind_parameters(self, value_dict): new_circuit = self.copy() if value_dict.keys() > self.parameters: raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format( [str(p) for p in value_dict.keys() - self.parameters])) for parameter, value in value_dict.items(): new_circuit._bind_parameter(parameter, value) # clear evaluated expressions for parameter in value_dict: del new_circuit._parameter_table[parameter] return new_circuit
159,417
Map all gates that can be executed with the current layout. Args: layout (Layout): Map from virtual qubit index to physical qubit index. gates (list): Gates to be mapped. coupling_map (CouplingMap): CouplingMap for target device topology. Returns: tuple: mapped_gates (list): ops for gates that can be executed, mapped onto layout. remaining_gates (list): gates that cannot be executed on the layout.
def _map_free_gates(layout, gates, coupling_map): blocked_qubits = set() mapped_gates = [] remaining_gates = [] for gate in gates: # Gates without a partition (barrier, snapshot, save, load, noise) may # still have associated qubits. Look for them in the qargs. if not gate['partition']: qubits = [n for n in gate['graph'].nodes() if n.type == 'op'][0].qargs if not qubits: continue if blocked_qubits.intersection(qubits): blocked_qubits.update(qubits) remaining_gates.append(gate) else: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) continue qubits = gate['partition'][0] if blocked_qubits.intersection(qubits): blocked_qubits.update(qubits) remaining_gates.append(gate) elif len(qubits) == 1: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) elif coupling_map.distance(*[layout[q] for q in qubits]) == 1: mapped_gate = _transform_gate_for_layout(gate, layout) mapped_gates.append(mapped_gate) else: blocked_qubits.update(qubits) remaining_gates.append(gate) return mapped_gates, remaining_gates
159,421
Initialize a LookaheadSwap instance. Arguments: coupling_map (CouplingMap): CouplingMap of the target backend. initial_layout (Layout): The initial layout of the DAG to analyze.
def __init__(self, coupling_map, initial_layout=None): super().__init__() self._coupling_map = coupling_map self.initial_layout = initial_layout self.requires.append(BarrierBeforeFinalMeasurements())
159,427
Run one pass of the lookahead mapper on the provided DAG. Args: dag (DAGCircuit): the directed acyclic graph to be mapped Returns: DAGCircuit: A dag mapped to be compatible with the coupling_map in the property_set. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG
def run(self, dag): coupling_map = self._coupling_map ordered_virtual_gates = list(dag.serial_layers()) if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits()) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self._coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") mapped_gates = [] layout = self.initial_layout.copy() gates_remaining = ordered_virtual_gates.copy() while gates_remaining: best_step = _search_forward_n_swaps(layout, gates_remaining, coupling_map) layout = best_step['layout'] gates_mapped = best_step['gates_mapped'] gates_remaining = best_step['gates_remaining'] mapped_gates.extend(gates_mapped) # Preserve input DAG's name, regs, wire_map, etc. but replace the graph. mapped_dag = _copy_circuit_metadata(dag, coupling_map) for node in mapped_gates: mapped_dag.apply_operation_back(op=node.op, qargs=node.qargs, cargs=node.cargs) return mapped_dag
159,428
Create coupling graph. By default, the generated coupling has no nodes. Args: couplinglist (list or None): An initial coupling graph, specified as an adjacency list containing couplings, e.g. [[0,1], [0,2], [1,2]].
def __init__(self, couplinglist=None): # the coupling map graph self.graph = nx.DiGraph() # a dict of dicts from node pairs to distances self._dist_matrix = None # a sorted list of physical qubits (integers) in this coupling map self._qubit_list = None if couplinglist is not None: for source, target in couplinglist: self.add_edge(source, target)
159,429
Returns the undirected distance between physical_qubit1 and physical_qubit2. Args: physical_qubit1 (int): A physical qubit physical_qubit2 (int): Another physical qubit Returns: int: The undirected distance Raises: CouplingError: if the qubits do not exist in the CouplingMap
def distance(self, physical_qubit1, physical_qubit2): if physical_qubit1 not in self.physical_qubits: raise CouplingError("%s not in coupling graph" % (physical_qubit1,)) if physical_qubit2 not in self.physical_qubits: raise CouplingError("%s not in coupling graph" % (physical_qubit2,)) if self._dist_matrix is None: self._compute_distance_matrix() return self._dist_matrix[physical_qubit1, physical_qubit2]
159,436
Returns the shortest undirected path between physical_qubit1 and physical_qubit2. Args: physical_qubit1 (int): A physical qubit physical_qubit2 (int): Another physical qubit Returns: List: The shortest undirected path Raises: CouplingError: When there is no path between physical_qubit1, physical_qubit2.
def shortest_undirected_path(self, physical_qubit1, physical_qubit2): try: return nx.shortest_path(self.graph.to_undirected(as_view=True), source=physical_qubit1, target=physical_qubit2) except nx.exception.NetworkXNoPath: raise CouplingError( "Nodes %s and %s are not connected" % (str(physical_qubit1), str(physical_qubit2)))
159,437
Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not defined, `bit` will be mapped to a new physical bit (extending the length of the layout by one.) Args: virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'), 2). physical_bit (int): A physical bit. For example, 3.
def add(self, virtual_bit, physical_bit=None): if physical_bit is None: physical_candidate = len(self) while physical_candidate in self._p2v: physical_candidate += 1 physical_bit = physical_candidate self[virtual_bit] = physical_bit
159,468
Swaps the map between left and right. Args: left (tuple or int): Item to swap with right. right (tuple or int): Item to swap with left. Raises: LayoutError: If left and right have not the same type.
def swap(self, left, right): if type(left) is not type(right): raise LayoutError('The method swap only works with elements of the same type.') temp = self[left] self[left] = self[right] self[right] = temp
159,469
Creates a trivial ("one-to-one") Layout with the registers in `regs`. Args: *regs (Registers): registers to include in the layout. Returns: Layout: A layout with all the `regs` in the given order.
def generate_trivial_layout(*regs): layout = Layout() for reg in regs: layout.add_register(reg) return layout
159,471
Converts a list of integers to a Layout mapping virtual qubits (index of the list) to physical qubits (the list values). Args: int_list (list): A list of integers. *qregs (QuantumRegisters): The quantum registers to apply the layout to. Returns: Layout: The corresponding Layout object. Raises: LayoutError: Invalid input layout.
def from_intlist(int_list, *qregs): if not all((isinstance(i, int) for i in int_list)): raise LayoutError('Expected a list of ints') if len(int_list) != len(set(int_list)): raise LayoutError('Duplicate values not permitted; Layout is bijective.') n_qubits = sum(reg.size for reg in qregs) # Check if list is too short to cover all qubits if len(int_list) < n_qubits: err_msg = 'Integer list length must equal number of qubits in circuit.' raise LayoutError(err_msg) out = Layout() main_idx = 0 for qreg in qregs: for idx in range(qreg.size): out[(qreg, idx)] = int_list[main_idx] main_idx += 1 if main_idx != len(int_list): for int_item in int_list[main_idx:]: out[int_item] = None return out
159,472
Populates a Layout from a list containing virtual qubits---(QuantumRegister, int) tuples---, or None. Args: tuple_list (list): e.g.: [qr[0], None, qr[2], qr[3]] Returns: Layout: the corresponding Layout object Raises: LayoutError: If the elements are not (Register, integer) or None
def from_tuplelist(tuple_list): out = Layout() for physical, virtual in enumerate(tuple_list): if virtual is None: continue elif Layout.is_virtual(virtual): if virtual in out._v2p: raise LayoutError('Duplicate values not permitted; Layout is bijective.') out[virtual] = physical else: raise LayoutError("The list should contain elements of the form" " (Register, integer) or None") return out
159,473
Return a new schedule with `schedule` inserted within `self` at `start_time`. Args: start_time: time to be inserted schedule: schedule to be inserted
def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent': return ops.insert(self, start_time, schedule)
159,482
Checks if the attribute name is in the list of attributes to protect. If so, raises TranspilerAccessError. Args: name (string): the attribute name to check Raises: TranspilerAccessError: when name is the list of attributes to protect.
def _check_if_fenced(self, name): if name in object.__getattribute__(self, '_attributes_to_fence'): raise TranspilerAccessError("The fenced %s has the property %s protected" % (type(object.__getattribute__(self, '_wrapped')), name))
159,489
The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Stinespring: the matrix power of the SuperOp converted to a Stinespring channel. Raises: QiskitError: if the input and output dimensions of the QuantumChannel are not equal, or the power is not an integer.
def power(self, n): if n > 0: return super().power(n) return Stinespring(SuperOp(self).power(n))
159,495
Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Stinespring: the scalar multiplication other * self as a Stinespring object. Raises: QiskitError: if other is not a valid scalar.
def multiply(self, other): if not isinstance(other, Number): raise QiskitError("other is not a number") # If the number is complex or negative we need to convert to # general Stinespring representation so we first convert to # the Choi representation if isinstance(other, complex) or other < 1: # Convert to Choi-matrix return Stinespring(Choi(self).multiply(other)) # If the number is real we can update the Kraus operators # directly num = np.sqrt(other) stine_l, stine_r = self._data stine_l = num * self._data[0] stine_r = None if self._data[1] is not None: stine_r = num * self._data[1] return Stinespring((stine_l, stine_r), self.input_dims(), self.output_dims())
159,496
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. Returns: QuantumState: the output quantum state. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions.
def _evolve(self, state, qargs=None): # If subsystem evolution we use the SuperOp representation if qargs is not None: return SuperOp(self)._evolve(state, qargs) # Otherwise we compute full evolution directly state = self._format_state(state) if state.shape[0] != self._input_dim: raise QiskitError( "QuantumChannel input dimension is not equal to state dimension." ) if state.ndim == 1 and self._data[1] is None and \ self._data[0].shape[0] // self._output_dim == 1: # If the shape of the stinespring operator is equal to the output_dim # evolution of a state vector psi -> stine.psi return np.dot(self._data[0], state) # Otherwise we always return a density matrix state = self._format_state(state, density_matrix=True) stine_l, stine_r = self._data if stine_r is None: stine_r = stine_l din, dout = self.dim dtr = stine_l.shape[0] // dout shape = (dout, dtr, din) return np.einsum('iAB,BC,jAC->ij', np.reshape(stine_l, shape), state, np.reshape(np.conjugate(stine_r), shape))
159,497
Return the tensor product channel. Args: other (QuantumChannel): a quantum channel subclass. reverse (bool): If False return self βŠ— other, if True return if True return (other βŠ— self) [Default: False] Returns: Stinespring: the tensor product channel as a Stinespring object. Raises: QiskitError: if other cannot be converted to a channel.
def _tensor_product(self, other, reverse=False): # Convert other to Stinespring if not isinstance(other, Stinespring): other = Stinespring(other) # Tensor stinespring ops sa_l, sa_r = self._data sb_l, sb_r = other._data # Reshuffle tensor dimensions din_a, dout_a = self.dim din_b, dout_b = other.dim dtr_a = sa_l.shape[0] // dout_a dtr_b = sb_l.shape[0] // dout_b if reverse: shape_in = (dout_b, dtr_b, dout_a, dtr_a, din_b * din_a) shape_out = (dout_b * dtr_b * dout_a * dtr_a, din_b * din_a) else: shape_in = (dout_a, dtr_a, dout_b, dtr_b, din_a * din_b) shape_out = (dout_a * dtr_a * dout_b * dtr_b, din_a * din_b) # Compute left stinepsring op if reverse: input_dims = self.input_dims() + other.input_dims() output_dims = self.output_dims() + other.output_dims() sab_l = np.kron(sb_l, sa_l) else: input_dims = other.input_dims() + self.input_dims() output_dims = other.output_dims() + self.output_dims() sab_l = np.kron(sa_l, sb_l) # Reravel indicies sab_l = np.reshape( np.transpose(np.reshape(sab_l, shape_in), (0, 2, 1, 3, 4)), shape_out) # Compute right stinespring op if sa_r is None and sb_r is None: sab_r = None else: if sa_r is None: sa_r = sa_l elif sb_r is None: sb_r = sb_l if reverse: sab_r = np.kron(sb_r, sa_r) else: sab_r = np.kron(sa_r, sb_r) # Reravel indicies sab_r = np.reshape( np.transpose(np.reshape(sab_r, shape_in), (0, 2, 1, 3, 4)), shape_out) return Stinespring((sab_l, sab_r), input_dims, output_dims)
159,498
Create a new command. Args: duration (int): Duration of this command. name (str): Name of this command. Raises: PulseError: when duration is not number of points.
def __init__(self, duration: int = None, name: str = None): if isinstance(duration, int): self._duration = duration else: raise PulseError('Pulse duration should be integer.') if name: self._name = name else: self._name = 'p%d' % Command.pulseIndex Command.pulseIndex += 1
159,499
Two Commands are the same if they are of the same type and have the same duration and name. Args: other (Command): other Command. Returns: bool: are self and other equal.
def __eq__(self, other): if type(self) is type(other) and \ self._duration == other._duration and \ self._name == other._name: return True return False
159,500
Runs the BasicSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG
def run(self, dag): new_dag = DAGCircuit() if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits()) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self.coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") current_layout = self.initial_layout.copy() for layer in dag.serial_layers(): subdag = layer['graph'] for gate in subdag.twoQ_gates(): physical_q0 = current_layout[gate.qargs[0]] physical_q1 = current_layout[gate.qargs[1]] if self.coupling_map.distance(physical_q0, physical_q1) != 1: # Insert a new layer with the SWAP(s). swap_layer = DAGCircuit() path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1) for swap in range(len(path) - 2): connected_wire_1 = path[swap] connected_wire_2 = path[swap + 1] qubit_1 = current_layout[connected_wire_1] qubit_2 = current_layout[connected_wire_2] # create qregs for qreg in current_layout.get_registers(): if qreg not in swap_layer.qregs.values(): swap_layer.add_qreg(qreg) # create the swap operation swap_layer.apply_operation_back(SwapGate(), qargs=[qubit_1, qubit_2], cargs=[]) # layer insertion edge_map = current_layout.combine_into_edge_map(self.initial_layout) new_dag.compose_back(swap_layer, edge_map) # update current_layout for swap in range(len(path) - 2): current_layout.swap(path[swap], path[swap + 1]) edge_map = current_layout.combine_into_edge_map(self.initial_layout) new_dag.extend_back(subdag, edge_map) return new_dag
159,501
Takes (QuantumRegister, int) tuples and converts them into an integer array. Args: items (list): List of tuples of (QuantumRegister, int) to convert. qregs (dict): List of )QuantumRegister, int) tuples. Returns: ndarray: Array of integers.
def regtuple_to_numeric(items, qregs): sizes = [qr.size for qr in qregs.values()] reg_idx = np.cumsum([0]+sizes) regint = {} for ind, qreg in enumerate(qregs.values()): regint[qreg] = ind out = np.zeros(len(items), dtype=np.int32) for idx, val in enumerate(items): out[idx] = reg_idx[regint[val[0]]]+val[1] return out
159,503
Converts gate tuples into a nested list of integers. Args: gates (list): List of (QuantumRegister, int) pairs representing gates. qregs (dict): List of )QuantumRegister, int) tuples. Returns: list: Nested list of integers for gates.
def gates_to_idx(gates, qregs): sizes = [qr.size for qr in qregs.values()] reg_idx = np.cumsum([0]+sizes) regint = {} for ind, qreg in enumerate(qregs.values()): regint[qreg] = ind out = np.zeros(2*len(gates), dtype=np.int32) for idx, gate in enumerate(gates): out[2*idx] = reg_idx[regint[gate[0][0]]]+gate[0][1] out[2*idx+1] = reg_idx[regint[gate[1][0]]]+gate[1][1] return out
159,504
Run the StochasticSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG
def run(self, dag): if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits()) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self.coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") self.input_layout = self.initial_layout.copy() self.qregs = dag.qregs if self.seed is None: self.seed = np.random.randint(0, np.iinfo(np.int32).max) self.rng = np.random.RandomState(self.seed) logger.debug("StochasticSwap RandomState seeded with seed=%s", self.seed) new_dag = self._mapper(dag, self.coupling_map, trials=self.trials) # self.property_set["layout"] = self.initial_layout return new_dag
159,506
Two channels are the same if they are of the same type, and have the same index. Args: other (Channel): other Channel Returns: bool: are self and other equal.
def __eq__(self, other): if type(self) is type(other) and \ self._index == other._index: return True return False
159,510
r"""Make the Pauli object. Note that, for the qubit index: - Order of z, x vectors is q_0 ... q_{n-1}, - Order of pauli label is q_{n-1} ... q_0 E.g., - z and x vectors: z = [z_0 ... z_{n-1}], x = [x_0 ... x_{n-1}] - a pauli is $P_{n-1} \otimes ... \otimes P_0$ Args: z (numpy.ndarray): boolean, z vector x (numpy.ndarray): boolean, x vector label (str): pauli label
def __init__(self, z=None, x=None, label=None): r if label is not None: a = Pauli.from_label(label) self._z = a.z self._x = a.x else: self._init_from_bool(z, x)
159,513
r"""Take pauli string to construct pauli. The qubit index of pauli label is q_{n-1} ... q_0. E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$ Args: label (str): pauli label Returns: Pauli: the constructed pauli Raises: QiskitError: invalid character in the label
def from_label(cls, label): r z = np.zeros(len(label), dtype=np.bool) x = np.zeros(len(label), dtype=np.bool) for i, char in enumerate(label): if char == 'X': x[-i - 1] = True elif char == 'Z': z[-i - 1] = True elif char == 'Y': z[-i - 1] = True x[-i - 1] = True elif char != 'I': raise QiskitError("Pauli string must be only consisted of 'I', 'X', " "'Y' or 'Z' but you have {}.".format(char)) return cls(z=z, x=x)
159,514
Construct pauli from boolean array. Args: z (numpy.ndarray): boolean, z vector x (numpy.ndarray): boolean, x vector Returns: Pauli: self Raises: QiskitError: if z or x are None or the length of z and x are different.
def _init_from_bool(self, z, x): if z is None: raise QiskitError("z vector must not be None.") if x is None: raise QiskitError("x vector must not be None.") if len(z) != len(x): raise QiskitError("length of z and x vectors must be " "the same. (z: {} vs x: {})".format(len(z), len(x))) z = _make_np_bool(z) x = _make_np_bool(x) self._z = z self._x = x return self
159,515
Return True if all Pauli terms are equal. Args: other (Pauli): other pauli Returns: bool: are self and other equal.
def __eq__(self, other): res = False if len(self) == len(other): if np.all(self._z == other.z) and np.all(self._x == other.x): res = True return res
159,518
r""" Multiply two Paulis and track the phase. $P_3 = P_1 \otimes P_2$: X*Y Args: p1 (Pauli): pauli 1 p2 (Pauli): pauli 2 Returns: Pauli: the multiplied pauli complex: the sign of the multiplication, 1, -1, 1j or -1j
def sgn_prod(p1, p2): r phase = Pauli._prod_phase(p1, p2) new_pauli = p1 * p2 return new_pauli, phase
159,521
Update partial or entire z. Args: z (numpy.ndarray or list): to-be-updated z indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitError: when updating whole z, the number of qubits must be the same.
def update_z(self, z, indices=None): z = _make_np_bool(z) if indices is None: if len(self._z) != len(z): raise QiskitError("During updating whole z, you can not " "change the number of qubits.") self._z = z else: if not isinstance(indices, list) and not isinstance(indices, np.ndarray): indices = [indices] for p, idx in enumerate(indices): self._z[idx] = z[p] return self
159,525
Update partial or entire x. Args: x (numpy.ndarray or list): to-be-updated x indices (numpy.ndarray or list or optional): to-be-updated qubit indices Returns: Pauli: self Raises: QiskitError: when updating whole x, the number of qubits must be the same.
def update_x(self, x, indices=None): x = _make_np_bool(x) if indices is None: if len(self._x) != len(x): raise QiskitError("During updating whole x, you can not change " "the number of qubits.") self._x = x else: if not isinstance(indices, list) and not isinstance(indices, np.ndarray): indices = [indices] for p, idx in enumerate(indices): self._x[idx] = x[p] return self
159,526
Append pauli at the end. Args: paulis (Pauli): the to-be-inserted or appended pauli pauli_labels (list[str]): the to-be-inserted or appended pauli label Returns: Pauli: self
def append_paulis(self, paulis=None, pauli_labels=None): return self.insert_paulis(None, paulis=paulis, pauli_labels=pauli_labels)
159,528
Delete pauli at the indices. Args: indices(list[int]): the indices of to-be-deleted paulis Returns: Pauli: self
def delete_qubits(self, indices): if not isinstance(indices, list): indices = [indices] self._z = np.delete(self._z, indices) self._x = np.delete(self._x, indices) return self
159,529