INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Apply a reset instruction to a qubit.
def _add_qasm_reset(self, qubit): """Apply a reset instruction to a qubit. Args: qubit (int): the qubit being rest This is done by doing a simulating a measurement outcome and projecting onto the outcome state while renormalizing. """ # get measure outcome outcome, probability = self._get_measure_outcome(qubit) # update quantum state if outcome == '0': update = [[1 / np.sqrt(probability), 0], [0, 0]] self._add_unitary_single(update, qubit) else: update = [[0, 1 / np.sqrt(probability)], [0, 0]] self._add_unitary_single(update, qubit)
Validate an initial statevector
def _validate_initial_statevector(self): """Validate an initial statevector""" # If initial statevector isn't set we don't need to validate if self._initial_statevector is None: return # Check statevector is correct length for number of qubits length = len(self._initial_statevector) required_dim = 2 ** self._number_of_qubits if length != required_dim: raise BasicAerError('initial statevector is incorrect length: ' + '{} != {}'.format(length, required_dim))
Set the backend options for all experiments in a qobj
def _set_options(self, qobj_config=None, backend_options=None): """Set the backend options for all experiments in a qobj""" # Reset default options self._initial_statevector = self.DEFAULT_OPTIONS["initial_statevector"] self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"] if backend_options is None: backend_options = {} # Check for custom initial statevector in backend_options first, # then config second if 'initial_statevector' in backend_options: self._initial_statevector = np.array(backend_options['initial_statevector'], dtype=complex) elif hasattr(qobj_config, 'initial_statevector'): self._initial_statevector = np.array(qobj_config.initial_statevector, dtype=complex) if self._initial_statevector is not None: # Check the initial statevector is normalized norm = np.linalg.norm(self._initial_statevector) if round(norm, 12) != 1: raise BasicAerError('initial statevector is not normalized: ' + 'norm {} != 1'.format(norm)) # Check for custom chop threshold # Replace with custom options if 'chop_threshold' in backend_options: self._chop_threshold = backend_options['chop_threshold'] elif hasattr(qobj_config, 'chop_threshold'): self._chop_threshold = qobj_config.chop_threshold
Set the initial statevector for simulation
def _initialize_statevector(self): """Set the initial statevector for simulation""" if self._initial_statevector is None: # Set to default state of all qubits in |0> self._statevector = np.zeros(2 ** self._number_of_qubits, dtype=complex) self._statevector[0] = 1 else: self._statevector = self._initial_statevector.copy() # Reshape to rank-N tensor self._statevector = np.reshape(self._statevector, self._number_of_qubits * [2])
Return the current statevector in JSON Result spec format
def _get_statevector(self): """Return the current statevector in JSON Result spec format""" vec = np.reshape(self._statevector, 2 ** self._number_of_qubits) # Expand complex numbers vec = np.stack([vec.real, vec.imag], axis=1) # Truncate small values vec[abs(vec) < self._chop_threshold] = 0.0 return vec
Determine if measure sampling is allowed for an experiment
def _validate_measure_sampling(self, experiment): """Determine if measure sampling is allowed for an experiment Args: experiment (QobjExperiment): a qobj experiment. """ # If shots=1 we should disable measure sampling. # This is also required for statevector simulator to return the # correct final statevector without silently dropping final measurements. if self._shots <= 1: self._sample_measure = False return # Check for config flag if hasattr(experiment.config, 'allows_measure_sampling'): self._sample_measure = experiment.config.allows_measure_sampling # If flag isn't found do a simple test to see if a circuit contains # no reset instructions, and no gates instructions after # the first measure. else: measure_flag = False for instruction in experiment.instructions: # If circuit contains reset operations we cannot sample if instruction.name == "reset": self._sample_measure = False return # If circuit contains a measure option then we can # sample only if all following operations are measures if measure_flag: # If we find a non-measure instruction # we cannot do measure sampling if instruction.name not in ["measure", "barrier", "id", "u0"]: self._sample_measure = False return elif instruction.name == "measure": measure_flag = True # If we made it to the end of the circuit without returning # measure sampling is allowed self._sample_measure = True
Run qobj asynchronously.
def run(self, qobj, backend_options=None): """Run qobj asynchronously. Args: qobj (Qobj): payload of the experiment backend_options (dict): backend options Returns: BasicAerJob: derived from BaseJob Additional Information: backend_options: Is a dict of options for the backend. It may contain * "initial_statevector": vector_like The "initial_statevector" option specifies a custom initial initial statevector for the simulator to be used instead of the all zero state. This size of this vector must be correct for the number of qubits in all experiments in the qobj. Example:: backend_options = { "initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2), } """ self._set_options(qobj_config=qobj.config, backend_options=backend_options) job_id = str(uuid.uuid4()) job = BasicAerJob(self, job_id, self._run_job, qobj) job.submit() return job
Run experiments in qobj
def _run_job(self, job_id, qobj): """Run experiments in qobj Args: job_id (str): unique id for the job. qobj (Qobj): job description Returns: Result: Result object """ self._validate(qobj) result_list = [] self._shots = qobj.config.shots self._memory = getattr(qobj.config, 'memory', False) self._qobj_config = qobj.config start = time.time() for experiment in qobj.experiments: result_list.append(self.run_experiment(experiment)) end = time.time() result = {'backend_name': self.name(), 'backend_version': self._configuration.backend_version, 'qobj_id': qobj.qobj_id, 'job_id': job_id, 'results': result_list, 'status': 'COMPLETED', 'success': True, 'time_taken': (end - start), 'header': qobj.header.as_dict()} return Result.from_dict(result)
Run an experiment ( circuit ) and return a single experiment result.
def run_experiment(self, experiment): """Run an experiment (circuit) and return a single experiment result. Args: experiment (QobjExperiment): experiment from qobj experiments list Returns: dict: A result dictionary which looks something like:: { "name": name of this experiment (obtained from qobj.experiment header) "seed": random seed used for simulation "shots": number of shots used in the simulation "data": { "counts": {'0x9: 5, ...}, "memory": ['0x9', '0xF', '0x1D', ..., '0x9'] }, "status": status string for the simulation "success": boolean "time_taken": simulation time of this single experiment } Raises: BasicAerError: if an error occurred. """ start = time.time() self._number_of_qubits = experiment.config.n_qubits self._number_of_cmembits = experiment.config.memory_slots self._statevector = 0 self._classical_memory = 0 self._classical_register = 0 self._sample_measure = False # Validate the dimension of initial statevector if set self._validate_initial_statevector() # Get the seed looking in circuit, qobj, and then random. if hasattr(experiment.config, 'seed'): seed = experiment.config.seed elif hasattr(self._qobj_config, 'seed'): seed = self._qobj_config.seed else: # For compatibility on Windows force dyte to be int32 # and set the maximum value to be (2 ** 31) - 1 seed = np.random.randint(2147483647, dtype='int32') self._local_random.seed(seed=seed) # Check if measure sampling is supported for current circuit self._validate_measure_sampling(experiment) # List of final counts for all shots memory = [] # Check if we can sample measurements, if so we only perform 1 shot # and sample all outcomes from the final state vector if self._sample_measure: shots = 1 # Store (qubit, cmembit) pairs for all measure ops in circuit to # be sampled measure_sample_ops = [] else: shots = self._shots for _ in range(shots): self._initialize_statevector() # Initialize classical memory to all 0 self._classical_memory = 0 self._classical_register = 0 for operation in experiment.instructions: conditional = getattr(operation, 'conditional', None) if isinstance(conditional, int): conditional_bit_set = (self._classical_register >> conditional) & 1 if not conditional_bit_set: continue elif conditional is not None: mask = int(operation.conditional.mask, 16) if mask > 0: value = self._classical_memory & mask while (mask & 0x1) == 0: mask >>= 1 value >>= 1 if value != int(operation.conditional.val, 16): continue # Check if single gate if operation.name in ('U', 'u1', 'u2', 'u3'): params = getattr(operation, 'params', None) qubit = operation.qubits[0] gate = single_gate_matrix(operation.name, params) self._add_unitary_single(gate, qubit) # Check if CX gate elif operation.name in ('id', 'u0'): pass elif operation.name in ('CX', 'cx'): qubit0 = operation.qubits[0] qubit1 = operation.qubits[1] gate = cx_gate_matrix() self._add_unitary_two(gate, qubit0, qubit1) # Check if reset elif operation.name == 'reset': qubit = operation.qubits[0] self._add_qasm_reset(qubit) # Check if barrier elif operation.name == 'barrier': pass # Check if measure elif operation.name == 'measure': qubit = operation.qubits[0] cmembit = operation.memory[0] cregbit = operation.register[0] if hasattr(operation, 'register') else None if self._sample_measure: # If sampling measurements record the qubit and cmembit # for this measurement for later sampling measure_sample_ops.append((qubit, cmembit)) else: # If not sampling perform measurement as normal self._add_qasm_measure(qubit, cmembit, cregbit) elif operation.name == 'bfunc': mask = int(operation.mask, 16) relation = operation.relation val = int(operation.val, 16) cregbit = operation.register cmembit = operation.memory if hasattr(operation, 'memory') else None compared = (self._classical_register & mask) - val if relation == '==': outcome = (compared == 0) elif relation == '!=': outcome = (compared != 0) elif relation == '<': outcome = (compared < 0) elif relation == '<=': outcome = (compared <= 0) elif relation == '>': outcome = (compared > 0) elif relation == '>=': outcome = (compared >= 0) else: raise BasicAerError('Invalid boolean function relation.') # Store outcome in register and optionally memory slot regbit = 1 << cregbit self._classical_register = \ (self._classical_register & (~regbit)) | (int(outcome) << cregbit) if cmembit is not None: membit = 1 << cmembit self._classical_memory = \ (self._classical_memory & (~membit)) | (int(outcome) << cmembit) else: backend = self.name() err_msg = '{0} encountered unrecognized operation "{1}"' raise BasicAerError(err_msg.format(backend, operation.name)) # Add final creg data to memory list if self._number_of_cmembits > 0: if self._sample_measure: # If sampling we generate all shot samples from the final statevector memory = self._add_sample_measure(measure_sample_ops, self._shots) else: # Turn classical_memory (int) into bit string and pad zero for unused cmembits outcome = bin(self._classical_memory)[2:] memory.append(hex(int(outcome, 2))) # Add data data = {'counts': dict(Counter(memory))} # Optionally add memory list if self._memory: data['memory'] = memory # Optionally add final statevector if self.SHOW_FINAL_STATE: data['statevector'] = self._get_statevector() # Remove empty counts and memory for statevector simulator if not data['counts']: data.pop('counts') if 'memory' in data and not data['memory']: data.pop('memory') end = time.time() return {'name': experiment.header.name, 'seed': seed, 'shots': self._shots, 'data': data, 'status': 'DONE', 'success': True, 'time_taken': (end - start), 'header': experiment.header.as_dict()}
Semantic validations of the qobj which cannot be done via schemas.
def _validate(self, qobj): """Semantic validations of the qobj which cannot be done via schemas.""" n_qubits = qobj.config.n_qubits max_qubits = self.configuration().n_qubits if n_qubits > max_qubits: raise BasicAerError('Number of qubits {} '.format(n_qubits) + 'is greater than maximum ({}) '.format(max_qubits) + 'for "{}".'.format(self.name())) for experiment in qobj.experiments: name = experiment.header.name if experiment.config.memory_slots == 0: logger.warning('No classical registers in circuit "%s", ' 'counts will be empty.', name) elif 'measure' not in [op.name for op in experiment.instructions]: logger.warning('No measurements in circuit "%s", ' 'classical register will remain all zeros.', name)
Apply an arbitrary 1 - qubit unitary matrix.
def _add_unitary_single(self, gate, qubit): """Apply an arbitrary 1-qubit unitary matrix. Args: gate (matrix_like): a single qubit gate matrix qubit (int): the qubit to apply gate to """ # Convert to complex rank-2 tensor gate_tensor = np.array(gate, dtype=complex) # Compute einsum index string for 1-qubit matrix multiplication indexes = einsum_matmul_index([qubit], self._number_of_qubits) # Apply matrix multiplication self._unitary = np.einsum(indexes, gate_tensor, self._unitary, dtype=complex, casting='no')
Apply a two - qubit unitary matrix.
def _add_unitary_two(self, gate, qubit0, qubit1): """Apply a two-qubit unitary matrix. Args: gate (matrix_like): a the two-qubit gate matrix qubit0 (int): gate qubit-0 qubit1 (int): gate qubit-1 """ # Convert to complex rank-4 tensor gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2]) # Compute einsum index string for 2-qubit matrix multiplication indexes = einsum_matmul_index([qubit0, qubit1], self._number_of_qubits) # Apply matrix multiplication self._unitary = np.einsum(indexes, gate_tensor, self._unitary, dtype=complex, casting='no')
Validate an initial unitary matrix
def _validate_initial_unitary(self): """Validate an initial unitary matrix""" # If initial unitary isn't set we don't need to validate if self._initial_unitary is None: return # Check unitary is correct length for number of qubits shape = np.shape(self._initial_unitary) required_shape = (2 ** self._number_of_qubits, 2 ** self._number_of_qubits) if shape != required_shape: raise BasicAerError('initial unitary is incorrect shape: ' + '{} != 2 ** {}'.format(shape, required_shape))
Set the backend options for all experiments in a qobj
def _set_options(self, qobj_config=None, backend_options=None): """Set the backend options for all experiments in a qobj""" # Reset default options self._initial_unitary = self.DEFAULT_OPTIONS["initial_unitary"] self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"] if backend_options is None: backend_options = {} # Check for custom initial statevector in backend_options first, # then config second if 'initial_unitary' in backend_options: self._initial_unitary = np.array(backend_options['initial_unitary'], dtype=complex) elif hasattr(qobj_config, 'initial_unitary'): self._initial_unitary = np.array(qobj_config.initial_unitary, dtype=complex) if self._initial_unitary is not None: # Check the initial unitary is actually unitary shape = np.shape(self._initial_unitary) if len(shape) != 2 or shape[0] != shape[1]: raise BasicAerError("initial unitary is not a square matrix") iden = np.eye(len(self._initial_unitary)) u_dagger_u = np.dot(self._initial_unitary.T.conj(), self._initial_unitary) norm = np.linalg.norm(u_dagger_u - iden) if round(norm, 10) != 0: raise BasicAerError("initial unitary is not unitary") # Check the initial statevector is normalized # Check for custom chop threshold # Replace with custom options if 'chop_threshold' in backend_options: self._chop_threshold = backend_options['chop_threshold'] elif hasattr(qobj_config, 'chop_threshold'): self._chop_threshold = qobj_config.chop_threshold
Set the initial unitary for simulation
def _initialize_unitary(self): """Set the initial unitary for simulation""" self._validate_initial_unitary() if self._initial_unitary is None: # Set to identity matrix self._unitary = np.eye(2 ** self._number_of_qubits, dtype=complex) else: self._unitary = self._initial_unitary.copy() # Reshape to rank-N tensor self._unitary = np.reshape(self._unitary, self._number_of_qubits * [2, 2])
Return the current unitary in JSON Result spec format
def _get_unitary(self): """Return the current unitary in JSON Result spec format""" unitary = np.reshape(self._unitary, 2 * [2 ** self._number_of_qubits]) # Expand complex numbers unitary = np.stack((unitary.real, unitary.imag), axis=-1) # Truncate small values unitary[abs(unitary) < self._chop_threshold] = 0.0 return unitary
Run experiments in qobj.
def _run_job(self, job_id, qobj): """Run experiments in qobj. Args: job_id (str): unique id for the job. qobj (Qobj): job description Returns: Result: Result object """ self._validate(qobj) result_list = [] start = time.time() for experiment in qobj.experiments: result_list.append(self.run_experiment(experiment)) end = time.time() result = {'backend_name': self.name(), 'backend_version': self._configuration.backend_version, 'qobj_id': qobj.qobj_id, 'job_id': job_id, 'results': result_list, 'status': 'COMPLETED', 'success': True, 'time_taken': (end - start), 'header': qobj.header.as_dict()} return Result.from_dict(result)
Run an experiment ( circuit ) and return a single experiment result.
def run_experiment(self, experiment): """Run an experiment (circuit) and return a single experiment result. Args: experiment (QobjExperiment): experiment from qobj experiments list Returns: dict: A result dictionary which looks something like:: { "name": name of this experiment (obtained from qobj.experiment header) "seed": random seed used for simulation "shots": number of shots used in the simulation "data": { "unitary": [[[0.0, 0.0], [1.0, 0.0]], [[1.0, 0.0], [0.0, 0.0]]] }, "status": status string for the simulation "success": boolean "time taken": simulation time of this single experiment } Raises: BasicAerError: if the number of qubits in the circuit is greater than 24. Note that the practical qubit limit is much lower than 24. """ start = time.time() self._number_of_qubits = experiment.header.n_qubits # Validate the dimension of initial unitary if set self._validate_initial_unitary() self._initialize_unitary() for operation in experiment.instructions: # Check if single gate if operation.name in ('U', 'u1', 'u2', 'u3'): params = getattr(operation, 'params', None) qubit = operation.qubits[0] gate = single_gate_matrix(operation.name, params) self._add_unitary_single(gate, qubit) elif operation.name in ('id', 'u0'): pass # Check if CX gate elif operation.name in ('CX', 'cx'): qubit0 = operation.qubits[0] qubit1 = operation.qubits[1] gate = cx_gate_matrix() self._add_unitary_two(gate, qubit0, qubit1) # Check if barrier elif operation.name == 'barrier': pass else: backend = self.name() err_msg = '{0} encountered unrecognized operation "{1}"' raise BasicAerError(err_msg.format(backend, operation.name)) # Add final state to data data = {'unitary': self._get_unitary()} end = time.time() return {'name': experiment.header.name, 'shots': 1, 'data': data, 'status': 'DONE', 'success': True, 'time_taken': (end - start), 'header': experiment.header.as_dict()}
Semantic validations of the qobj which cannot be done via schemas. Some of these may later move to backend schemas. 1. No shots 2. No measurements in the middle
def _validate(self, qobj): """Semantic validations of the qobj which cannot be done via schemas. Some of these may later move to backend schemas. 1. No shots 2. No measurements in the middle """ n_qubits = qobj.config.n_qubits max_qubits = self.configuration().n_qubits if n_qubits > max_qubits: raise BasicAerError('Number of qubits {} '.format(n_qubits) + 'is greater than maximum ({}) '.format(max_qubits) + 'for "{}".'.format(self.name())) if hasattr(qobj.config, 'shots') and qobj.config.shots != 1: logger.info('"%s" only supports 1 shot. Setting shots=1.', self.name()) qobj.config.shots = 1 for experiment in qobj.experiments: name = experiment.header.name if getattr(experiment.config, 'shots', 1) != 1: logger.info('"%s" only supports 1 shot. ' 'Setting shots=1 for circuit "%s".', self.name(), name) experiment.config.shots = 1 for operation in experiment.instructions: if operation.name in ['measure', 'reset']: raise BasicAerError('Unsupported "%s" instruction "%s" ' + 'in circuit "%s" ', self.name(), operation.name, name)
Determine if obj is a bit
def _is_bit(obj): """Determine if obj is a bit""" # If there is a bit type this could be replaced by isinstance. if isinstance(obj, tuple) and len(obj) == 2: if isinstance(obj[0], Register) and isinstance(obj[1], int) and obj[1] < len(obj[0]): return True return False
Recursively converts the integers tuples and ranges in a_list for a qu/ clbit from the bits. E. g. bits [ item_in_a_list ]
def _convert_to_bits(a_list, bits): """ Recursively converts the integers, tuples and ranges in a_list for a qu/clbit from the bits. E.g. bits[item_in_a_list]""" new_list = [] for item in a_list: if isinstance(item, (int, slice)): # eg. circuit.h(2) # eg. circuit.h(slice(0, 2)) try: new_list.append(bits[item]) except IndexError: raise QiskitError("The integer param is out of range") elif isinstance(item, list): # eg. circuit.h([0, 2]) new_list.append(_convert_to_bits(item, bits)) elif isinstance(item, range): # eg. circuit.h(range(0, 2)) new_list.append(_convert_to_bits([index for index in item], bits)) else: new_list.append(item) return new_list
Convert gate arguments to [ qu|cl ] bits from integers slices ranges etc. For example circuit. h ( 0 ) - > circuit. h ( QuantumRegister ( 2 ) [ 0 ] )
def _to_bits(nqbits, ncbits=0, func=None): """Convert gate arguments to [qu|cl]bits from integers, slices, ranges, etc. For example circuit.h(0) -> circuit.h(QuantumRegister(2)[0]) """ if func is None: return functools.partial(_to_bits, nqbits, ncbits) @functools.wraps(func) def wrapper(self, *args): qbits = self.qubits() cbits = self.clbits() nparams = len(args) - nqbits - ncbits params = args[:nparams] qb_args = args[nparams:nparams + nqbits] cl_args = args[nparams + nqbits:] args = list(params) + _convert_to_bits(qb_args, qbits) + _convert_to_bits(cl_args, cbits) return func(self, *args) return wrapper
Decorator for expanding an operation across a whole register or register subset. Args: n_bits ( int ): the number of register bit arguments the decorated function takes func ( function ): used for decorators with keyword args broadcastable ( list ( bool )): list of bool for which register args can be broadcast from 1 bit to the max size of the rest of the args. Defaults to all True if not specified.
def _op_expand(n_bits, func=None, broadcastable=None): """Decorator for expanding an operation across a whole register or register subset. Args: n_bits (int): the number of register bit arguments the decorated function takes func (function): used for decorators with keyword args broadcastable (list(bool)): list of bool for which register args can be broadcast from 1 bit to the max size of the rest of the args. Defaults to all True if not specified. Return: type: partial function object """ if func is None: return functools.partial(_op_expand, n_bits, broadcastable=broadcastable) @functools.wraps(func) def wrapper(self, *args): params = args[0:-n_bits] if len(args) > n_bits else tuple() rargs = args[-n_bits:] if broadcastable is None: blist = [True] * len(rargs) else: blist = broadcastable if not all([_is_bit(arg) for arg in rargs]): rarg_size = [1] * n_bits for iarg, arg in enumerate(rargs): if isinstance(arg, Register): rarg_size[iarg] = len(arg) elif isinstance(arg, list) and all([_is_bit(bit) for bit in arg]): rarg_size[iarg] = len(arg) elif _is_bit(arg): rarg_size[iarg] = 1 else: raise QiskitError('operation arguments must be qubits/cbits') broadcast_size = max(rarg_size) expanded_rargs = [] for arg, broadcast in zip(rargs, blist): if isinstance(arg, Register): arg = [(arg, i) for i in range(len(arg))] elif isinstance(arg, tuple): arg = [arg] # now we should have a list of qubits if isinstance(arg, list) and len(arg) == 1 and broadcast: arg = arg * broadcast_size if len(arg) != broadcast_size: raise QiskitError('register size error') expanded_rargs.append(arg) rargs = expanded_rargs if all([isinstance(arg, list) for arg in rargs]): if all(rargs): instructions = InstructionSet() for irargs in zip(*rargs): instructions.add(func(self, *params, *irargs), [i for i in irargs if isinstance(i[0], QuantumRegister)], [i for i in irargs if isinstance(i[0], ClassicalRegister)]) return instructions else: raise QiskitError('empty control or target argument') return func(self, *params, *rargs) return wrapper
Return a Numpy. array for the U3 gate.
def to_matrix(self): """Return a Numpy.array for the U3 gate.""" lam = self.params[0] lam = float(lam) return numpy.array([[1, 0], [0, numpy.exp(1j * lam)]], dtype=complex)
Pick a layout by assigning n circuit qubits to device qubits 0.. n - 1.
def run(self, dag): """ Pick a layout by assigning n circuit qubits to device qubits 0, .., n-1. Args: dag (DAGCircuit): DAG to find layout for. Raises: TranspilerError: if dag wider than self.coupling_map """ num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()]) if num_dag_qubits > self.coupling_map.size(): raise TranspilerError('Number of qubits greater than device.') self.property_set['layout'] = Layout.generate_trivial_layout(*dag.qregs.values())
Check if self has overlap with interval.
def has_overlap(self, interval: 'Interval') -> bool: """Check if self has overlap with `interval`. Args: interval: interval to be examined Returns: bool: True if self has overlap with `interval` otherwise False """ if self.begin < interval.end and interval.begin < self.end: return True return False
Return a new interval shifted by time from self
def shift(self, time: int) -> 'Interval': """Return a new interval shifted by `time` from self Args: time: time to be shifted Returns: Interval: interval shifted by `time` """ return Interval(self._begin + time, self._end + time)
Return a new Timeslot shifted by time.
def shift(self, time: int) -> 'Timeslot': """Return a new Timeslot shifted by `time`. Args: time: time to be shifted """ return Timeslot(self.interval.shift(time), self.channel)
Return earliest start time in this collection.
def ch_start_time(self, *channels: List[Channel]) -> int: """Return earliest start time in this collection. Args: *channels: Channels over which to obtain start_time. """ intervals = list(itertools.chain(*(self._table[chan] for chan in channels if chan in self._table))) if intervals: return min((interval.begin for interval in intervals)) return 0
Return maximum time of timeslots over all channels.
def ch_stop_time(self, *channels: List[Channel]) -> int: """Return maximum time of timeslots over all channels. Args: *channels: Channels over which to obtain stop time. """ intervals = list(itertools.chain(*(self._table[chan] for chan in channels if chan in self._table))) if intervals: return max((interval.end for interval in intervals)) return 0
Return if self is mergeable with timeslots.
def is_mergeable_with(self, timeslots: 'TimeslotCollection') -> bool: """Return if self is mergeable with `timeslots`. Args: timeslots: TimeslotCollection to be checked """ for slot in timeslots.timeslots: for interval in self._table[slot.channel]: if slot.interval.has_overlap(interval): return False return True
Return a new TimeslotCollection merged with a specified timeslots
def merged(self, timeslots: 'TimeslotCollection') -> 'TimeslotCollection': """Return a new TimeslotCollection merged with a specified `timeslots` Args: timeslots: TimeslotCollection to be merged """ slots = [Timeslot(slot.interval, slot.channel) for slot in self.timeslots] slots.extend([Timeslot(slot.interval, slot.channel) for slot in timeslots.timeslots]) return TimeslotCollection(*slots)
Return a new TimeslotCollection shifted by time.
def shift(self, time: int) -> 'TimeslotCollection': """Return a new TimeslotCollection shifted by `time`. Args: time: time to be shifted by """ slots = [Timeslot(slot.interval.shift(time), slot.channel) for slot in self.timeslots] return TimeslotCollection(*slots)
Return the correspond floating point number.
def real(self, nested_scope=None): """Return the correspond floating point number.""" op = self.children[0].name expr = self.children[1] dispatch = { 'sin': sympy.sin, 'cos': sympy.cos, 'tan': sympy.tan, 'asin': sympy.asin, 'acos': sympy.acos, 'atan': sympy.atan, 'exp': sympy.exp, 'ln': sympy.log, 'sqrt': sympy.sqrt } if op in dispatch: arg = expr.real(nested_scope) return dispatch[op](arg) else: raise NodeException("internal error: undefined external")
Report on GitHub that the specified branch is failing to build at the specified commit. The method will open an issue indicating that the branch is failing. If there is an issue already open it will add a comment avoiding to report twice about the same failure.
def report(self, branch, commit, infourl=None): """Report on GitHub that the specified branch is failing to build at the specified commit. The method will open an issue indicating that the branch is failing. If there is an issue already open, it will add a comment avoiding to report twice about the same failure. Args: branch (str): branch name to report about. commit (str): commit hash at which the build fails. infourl (str): URL with extra info about the failure such as the build logs. """ issue_number = self._get_report_issue_number() if issue_number: self._report_as_comment(issue_number, branch, commit, infourl) else: self._report_as_issue(branch, commit, infourl)
Sort rho data
def process_data(rho): """ Sort rho data """ result = dict() num = int(np.log2(len(rho))) labels = list(map(lambda x: x.to_label(), pauli_group(num))) values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))), pauli_group(num))) for position, label in enumerate(labels): result[label] = values[position] return result
Create a paulivec representation.
def iplot_state_paulivec(rho, figsize=None, slider=False, show_legend=False): """ Create a paulivec representation. Graphical representation of the input array. Args: rho (array): State vector or density matrix. figsize (tuple): Figure size in pixels. slider (bool): activate slider show_legend (bool): show legend of graph content """ # HTML html_template = Template(""" <p> <div id="paulivec_$divNumber"></div> </p> """) # JavaScript javascript_template = Template(""" <script> requirejs.config({ paths: { qVisualization: "https://qvisualization.mybluemix.net/q-visualizations" } }); require(["qVisualization"], function(qVisualizations) { qVisualizations.plotState("paulivec_$divNumber", "paulivec", $executions, $options); }); </script> """) rho = _validate_input_state(rho) # set default figure size if none given if figsize is None: figsize = (7, 5) options = {'width': figsize[0], 'height': figsize[1], 'slider': int(slider), 'show_legend': int(show_legend)} # Process data and execute div_number = str(time.time()) div_number = re.sub('[.]', '', div_number) data_to_plot = [] rho_data = process_data(rho) data_to_plot.append(dict( data=rho_data )) html = html_template.substitute({ 'divNumber': div_number }) javascript = javascript_template.substitute({ 'divNumber': div_number, 'executions': data_to_plot, 'options': options }) display(HTML(html + javascript))
Plot the quantum state.
def iplot_state(quantum_state, method='city', figsize=None): """Plot the quantum state. Args: quantum_state (ndarray): statevector or density matrix representation of a quantum state. method (str): Plotting method to use. figsize (tuple): Figure size in pixels. Raises: VisualizationError: if the input is not a statevector or density matrix, or if the state is not an multi-qubit quantum state. """ warnings.warn("iplot_state is deprecated, and will be removed in \ the 0.9 release. Use the iplot_state_ * functions \ instead.", DeprecationWarning) rho = _validate_input_state(quantum_state) if method == "city": iplot_state_city(rho, figsize=figsize) elif method == "paulivec": iplot_state_paulivec(rho, figsize=figsize) elif method == "qsphere": iplot_state_qsphere(rho, figsize=figsize) elif method == "bloch": iplot_bloch_multivector(rho, figsize=figsize) elif method == "hinton": iplot_state_hinton(rho, figsize=figsize) else: raise VisualizationError('Invalid plot state method.')
Apply RZZ to circuit.
def rzz(self, theta, qubit1, qubit2): """Apply RZZ to circuit.""" return self.append(RZZGate(theta), [qubit1, qubit2], [])
Apply Fredkin to circuit.
def cswap(self, ctl, tgt1, tgt2): """Apply Fredkin to circuit.""" return self.append(FredkinGate(), [ctl, tgt1, tgt2], [])
gate cswap a b c { cx c b ; ccx a b c ; cx c b ; }
def _define(self): """ gate cswap a,b,c { cx c,b; ccx a,b,c; cx c,b; } """ definition = [] q = QuantumRegister(3, "q") rule = [ (CnotGate(), [q[2], q[1]], []), (ToffoliGate(), [q[0], q[1], q[2]], []), (CnotGate(), [q[2], q[1]], []) ] for inst in rule: definition.append(inst) self.definition = definition
Extract readout and CNOT errors and compute swap costs.
def _initialize_backend_prop(self): """ Extract readout and CNOT errors and compute swap costs. """ backend_prop = self.backend_prop for ginfo in backend_prop.gates: if ginfo.gate == 'cx': for item in ginfo.parameters: if item.name == 'gate_error': g_reliab = 1.0 - item.value break else: g_reliab = 1.0 swap_reliab = -math.log(pow(g_reliab, 3)) self.swap_graph.add_edge(ginfo.qubits[0], ginfo.qubits[1], weight=swap_reliab) self.swap_graph.add_edge(ginfo.qubits[1], ginfo.qubits[0], weight=swap_reliab) self.cx_errors[(ginfo.qubits[0], ginfo.qubits[1])] = g_reliab self.gate_list.append((ginfo.qubits[0], ginfo.qubits[1])) idx = 0 for q in backend_prop.qubits: for nduv in q: if nduv.name == 'readout_error': self.readout_errors[idx] = 1.0 - nduv.value self.available_hw_qubits.append(idx) idx += 1 for edge in self.cx_errors: self.gate_cost[edge] = self.cx_errors[edge] * self.readout_errors[edge[0]] *\ self.readout_errors[edge[1]] self.swap_paths, swap_costs_temp = nx.algorithms.shortest_paths.dense.\ floyd_warshall_predecessor_and_distance(self.swap_graph, weight='weight') for i in swap_costs_temp: self.swap_costs[i] = {} for j in swap_costs_temp[i]: if (i, j) in self.cx_errors: self.swap_costs[i][j] = self.cx_errors[(i, j)] elif (j, i) in self.cx_errors: self.swap_costs[i][j] = self.cx_errors[(j, i)] else: best_reliab = 0.0 for n in self.swap_graph.neighbors(j): if (n, j) in self.cx_errors: reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(n, j)] else: reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(j, n)] if reliab > best_reliab: best_reliab = reliab self.swap_costs[i][j] = best_reliab
Program graph has virtual qubits as nodes. Two nodes have an edge if the corresponding virtual qubits participate in a 2 - qubit gate. The edge is weighted by the number of CNOTs between the pair.
def _create_program_graph(self, dag): """ Program graph has virtual qubits as nodes. Two nodes have an edge if the corresponding virtual qubits participate in a 2-qubit gate. The edge is weighted by the number of CNOTs between the pair. """ idx = 0 for q in dag.qubits(): self.qarg_to_id[q[0].name + str(q[1])] = idx idx += 1 for gate in dag.twoQ_gates(): qid1 = self._qarg_to_id(gate.qargs[0]) qid2 = self._qarg_to_id(gate.qargs[1]) min_q = min(qid1, qid2) max_q = max(qid1, qid2) edge_weight = 1 if self.prog_graph.has_edge(min_q, max_q): edge_weight = self.prog_graph[min_q][max_q]['weight'] + 1 self.prog_graph.add_edge(min_q, max_q, weight=edge_weight) return idx
If there is an edge with one endpoint mapped return it. Else return in the first edge
def _select_next_edge(self): """ If there is an edge with one endpoint mapped, return it. Else return in the first edge """ for edge in self.pending_program_edges: q1_mapped = edge[0] in self.prog2hw q2_mapped = edge[1] in self.prog2hw assert not (q1_mapped and q2_mapped) if q1_mapped or q2_mapped: return edge return self.pending_program_edges[0]
Select best remaining CNOT in the hardware for the next program edge.
def _select_best_remaining_cx(self): """ Select best remaining CNOT in the hardware for the next program edge. """ candidates = [] for gate in self.gate_list: chk1 = gate[0] in self.available_hw_qubits chk2 = gate[1] in self.available_hw_qubits if chk1 and chk2: candidates.append(gate) best_reliab = 0 best_item = None for item in candidates: if self.gate_cost[item] > best_reliab: best_reliab = self.gate_cost[item] best_item = item return best_item
Select the best remaining hardware qubit for the next program qubit.
def _select_best_remaining_qubit(self, prog_qubit): """ Select the best remaining hardware qubit for the next program qubit. """ reliab_store = {} for hw_qubit in self.available_hw_qubits: reliab = 1 for n in self.prog_graph.neighbors(prog_qubit): if n in self.prog2hw: reliab *= self.swap_costs[self.prog2hw[n]][hw_qubit] reliab *= self.readout_errors[hw_qubit] reliab_store[hw_qubit] = reliab max_reliab = 0 best_hw_qubit = None for hw_qubit in reliab_store: if reliab_store[hw_qubit] > max_reliab: max_reliab = reliab_store[hw_qubit] best_hw_qubit = hw_qubit return best_hw_qubit
Main run method for the noise adaptive layout.
def run(self, dag): """Main run method for the noise adaptive layout.""" self._initialize_backend_prop() num_qubits = self._create_program_graph(dag) if num_qubits > len(self.swap_graph): raise TranspilerError('Number of qubits greater than device.') for end1, end2, _ in sorted(self.prog_graph.edges(data=True), key=lambda x: x[2]['weight'], reverse=True): self.pending_program_edges.append((end1, end2)) while self.pending_program_edges: edge = self._select_next_edge() q1_mapped = edge[0] in self.prog2hw q2_mapped = edge[1] in self.prog2hw if (not q1_mapped) and (not q2_mapped): best_hw_edge = self._select_best_remaining_cx() self.prog2hw[edge[0]] = best_hw_edge[0] self.prog2hw[edge[1]] = best_hw_edge[1] self.available_hw_qubits.remove(best_hw_edge[0]) self.available_hw_qubits.remove(best_hw_edge[1]) elif not q1_mapped: best_hw_qubit = self._select_best_remaining_qubit(edge[0]) self.prog2hw[edge[0]] = best_hw_qubit self.available_hw_qubits.remove(best_hw_qubit) else: best_hw_qubit = self._select_best_remaining_qubit(edge[1]) self.prog2hw[edge[1]] = best_hw_qubit self.available_hw_qubits.remove(best_hw_qubit) new_edges = [x for x in self.pending_program_edges if not (x[0] in self.prog2hw and x[1] in self.prog2hw)] self.pending_program_edges = new_edges for qid in self.qarg_to_id.values(): if qid not in self.prog2hw: self.prog2hw[qid] = self.available_hw_qubits[0] self.available_hw_qubits.remove(self.prog2hw[qid]) layout = Layout() for q in dag.qubits(): pid = self._qarg_to_id(q) hwid = self.prog2hw[pid] layout[(q[0], q[1])] = hwid self.property_set['layout'] = layout
Return a list of instructions for this CompositeGate.
def instruction_list(self): """Return a list of instructions for this CompositeGate. If the CompositeGate itself contains composites, call this method recursively. """ instruction_list = [] for instruction in self.data: if isinstance(instruction, CompositeGate): instruction_list.extend(instruction.instruction_list()) else: instruction_list.append(instruction) return instruction_list
Invert this gate.
def inverse(self): """Invert this gate.""" self.data = [gate.inverse() for gate in reversed(self.data)] self.inverse_flag = not self.inverse_flag return self
Add controls to this gate.
def q_if(self, *qregs): """Add controls to this gate.""" self.data = [gate.q_if(qregs) for gate in self.data] return self
Add classical control register.
def c_if(self, classical, val): """Add classical control register.""" self.data = [gate.c_if(classical, val) for gate in self.data] return self
Return True if operator is a unitary matrix.
def is_unitary(self, atol=None, rtol=None): """Return True if operator is a unitary matrix.""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol return is_unitary_matrix(self._data, rtol=rtol, atol=atol)
Return the conjugate of the operator.
def conjugate(self): """Return the conjugate of the operator.""" return Operator( np.conj(self.data), self.input_dims(), self.output_dims())
Return the transpose of the operator.
def transpose(self): """Return the transpose of the operator.""" return Operator( np.transpose(self.data), self.input_dims(), self.output_dims())
Return the matrix power of the operator.
def power(self, n): """Return the matrix power of the operator. Args: n (int): the power to raise the matrix to. Returns: BaseOperator: the n-times composed operator. Raises: QiskitError: if the input and output dimensions of the operator are not equal, or the power is not a positive integer. """ if not isinstance(n, int): raise QiskitError("Can only take integer powers of Operator.") if self.input_dims() != self.output_dims(): raise QiskitError("Can only power with input_dims = output_dims.") # Override base class power so we can implement more efficiently # using Numpy.matrix_power return Operator( np.linalg.matrix_power(self.data, n), self.input_dims(), self.output_dims())
Return the operator self + other.
def add(self, other): """Return the operator self + other. Args: other (Operator): an operator object. Returns: Operator: the operator self + other. Raises: QiskitError: if other is not an operator, or has incompatible dimensions. """ if not isinstance(other, Operator): other = Operator(other) if self.dim != other.dim: raise QiskitError("other operator has different dimensions.") return Operator(self.data + other.data, self.input_dims(), self.output_dims())
Return the operator self + other.
def multiply(self, other): """Return the operator self + other. Args: other (complex): a complex number. Returns: Operator: the operator other * self. Raises: QiskitError: if other is not a valid complex number. """ if not isinstance(other, Number): raise QiskitError("other is not a number") return Operator(other * self.data, self.input_dims(), self.output_dims())
Return the tensor shape of the matrix operator
def _shape(self): """Return the tensor shape of the matrix operator""" return tuple(reversed(self.output_dims())) + tuple( reversed(self.input_dims()))
Evolve a quantum state by the operator.
def _evolve(self, state, qargs=None): """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. Returns: QuantumState: the output quantum state. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions. """ state = self._format_state(state) if qargs is None: if state.shape[0] != self._input_dim: raise QiskitError( "Operator input dimension is not equal to state dimension." ) if state.ndim == 1: # Return evolved statevector return np.dot(self.data, state) # Return evolved density matrix return np.dot( np.dot(self.data, state), np.transpose(np.conj(self.data))) # Subsystem evolution return self._evolve_subsystem(state, qargs)
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. Returns: QuantumState: the output quantum state. Raises: QiskitError: if the operator dimension does not match the specified QuantumState subsystem dimensions. """ mat = np.reshape(self.data, self._shape) # Hack to assume state is a N-qubit state until a proper class for states # is in place state_size = len(state) state_dims = self._automatic_dims(None, state_size) if self.input_dims() != len(qargs) * (2,): raise QiskitError( "Operator input dimensions are not compatible with state subsystem dimensions." ) if state.ndim == 1: # Return evolved statevector tensor = np.reshape(state, state_dims) indices = [len(state_dims) - 1 - qubit for qubit in qargs] tensor = self._einsum_matmul(tensor, mat, indices) return np.reshape(tensor, state_size) # Return evolved density matrix tensor = np.reshape(state, 2 * state_dims) indices = [len(state_dims) - 1 - qubit for qubit in qargs] right_shift = len(state_dims) # Left multiply by operator tensor = self._einsum_matmul(tensor, mat, indices) # Right multiply by adjoint operator # We implement the transpose by doing left multiplication instead of right # in the _einsum_matmul function tensor = self._einsum_matmul( tensor, np.conj(mat), indices, shift=right_shift) return np.reshape(tensor, [state_size, state_size])
Format input state so it is statevector or density matrix
def _format_state(self, state): """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.') # Flatten column-vector to vector if ndim == 2: if shape[1] != 1 and shape[1] != shape[0]: raise QiskitError('Input state is not a vector or matrix.') if shape[1] == 1: # flatten colum-vector to vector state = np.reshape(state, shape[0]) return state
Convert a QuantumCircuit or Instruction to an Operator.
def _instruction_to_operator(cls, instruction): """Convert a QuantumCircuit or Instruction to an Operator.""" # Convert circuit to an instruction if isinstance(instruction, QuantumCircuit): instruction = instruction.to_instruction() # Initialize an identity operator of the correct size of the circuit op = Operator(np.eye(2 ** instruction.num_qubits)) op._append_instruction(instruction) return op
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): mat = None if hasattr(obj, 'to_matrix'): # If instruction is a gate first we see if it has a # `to_matrix` definition and if so use that. try: mat = obj.to_matrix() except QiskitError: pass if mat is not None: # Perform the composition and inplace update the current state # of the operator op = self.compose(mat, qargs=qargs) self._data = op.data else: # If the instruction doesn't have a matrix defined we use its # circuit decomposition definition if it exists, otherwise we # cannot compose this gate and raise an error. if obj.definition is None: raise QiskitError('Cannot apply Instruction: {}'.format(obj.name)) for instr, qregs, cregs in obj.definition: if cregs: raise QiskitError( 'Cannot apply instruction with classical registers: {}'.format( instr.name)) # Get the integer position of the flat register new_qargs = [tup[1] for tup in qregs] self._append_instruction(instr, qargs=new_qargs) else: raise QiskitError('Input is not an instruction.')
Map a DAGCircuit onto a CouplingGraph using swap gates.
def run(self, dag): """Map a DAGCircuit onto a CouplingGraph using swap gates. Args: dag (DAGCircuit): input DAG circuit Returns: DAGCircuit: object containing a circuit equivalent to circuit_graph that respects couplings in coupling_map, and a layout dict mapping qubits of circuit_graph into qubits of coupling_map. The layout may differ from the initial_layout if the first layer of gates cannot be executed on the initial_layout. Raises: TranspilerError: if there was any error during the mapping or with the parameters. """ if dag.width() > self.coupling_map.size(): raise TranspilerError("Not enough qubits in CouplingGraph") # Schedule the input circuit layerlist = list(dag.layers()) if self.initial_layout is None and self.property_set["layout"]: self.initial_layout = self.property_set["layout"] if self.initial_layout is not None: # update initial_layout from a user given dict{(regname,idx): (regname,idx)} # to an expected dict{(reg,idx): (reg,idx)} virtual_qubits = self.initial_layout.get_virtual_bits() self.initial_layout = {(v[0].name, v[1]): ('q', self.initial_layout[v]) for v in virtual_qubits} device_register = QuantumRegister(self.coupling_map.size(), 'q') initial_layout = {(dag.qregs[k[0]], k[1]): (device_register, v[1]) for k, v in self.initial_layout.items()} # Check the input layout circ_qubits = dag.qubits() coup_qubits = [(QuantumRegister(self.coupling_map.size(), 'q'), wire) for wire in self.coupling_map.physical_qubits] qubit_subset = [] for k, v in initial_layout.items(): qubit_subset.append(v) if k not in circ_qubits: raise TranspilerError("initial_layout qubit %s[%d] not in input " "DAGCircuit" % (k[0].name, k[1])) if v not in coup_qubits: raise TranspilerError("initial_layout qubit %s[%d] not in input " "CouplingGraph" % (v[0].name, v[1])) else: # Supply a default layout qubit_subset = [(QuantumRegister(self.coupling_map.size(), 'q'), wire) for wire in self.coupling_map.physical_qubits] qubit_subset = qubit_subset[0:dag.width()] initial_layout = {a: b for a, b in zip(dag.qubits(), qubit_subset)} # Find swap circuit to preceed to each layer of input circuit layout = initial_layout.copy() # Construct an empty DAGCircuit with one qreg "q" # and the same set of cregs as the input circuit dagcircuit_output = DAGCircuit() dagcircuit_output.name = dag.name dagcircuit_output.add_qreg(QuantumRegister(self.coupling_map.size(), "q")) for creg in dag.cregs.values(): dagcircuit_output.add_creg(creg) # Make a trivial wire mapping between the subcircuits # returned by swap_mapper_layer_update and the circuit # we are building identity_wire_map = {} q = QuantumRegister(self.coupling_map.size(), 'q') for j in range(self.coupling_map.size()): identity_wire_map[(q, j)] = (q, j) for creg in dag.cregs.values(): for j in range(creg.size): identity_wire_map[(creg, j)] = (creg, j) first_layer = True # True until first layer is output # Iterate over layers for i, layer in enumerate(layerlist): # Attempt to find a permutation for this layer success_flag, best_circ, best_d, best_layout, trivial_flag \ = self.layer_permutation(layer["partition"], layout, qubit_subset) # If this fails, try one gate at a time in this layer if not success_flag: serial_layerlist = list(layer["graph"].serial_layers()) # Go through each gate in the layer for j, serial_layer in enumerate(serial_layerlist): success_flag, best_circ, best_d, best_layout, trivial_flag \ = self.layer_permutation(serial_layer["partition"], layout, qubit_subset) # Give up if we fail again if not success_flag: raise TranspilerError("swap_mapper failed: " + "layer %d, sublayer %d" % (i, j)) # If this layer is only single-qubit gates, # and we have yet to see multi-qubit gates, # continue to the next inner iteration if trivial_flag and first_layer: continue # Update the record of qubit positions for each inner iteration layout = best_layout # Update the QASM dagcircuit_output.compose_back( self.swap_mapper_layer_update(j, first_layer, best_layout, best_d, best_circ, serial_layerlist), identity_wire_map) # Update initial layout if first_layer: initial_layout = layout first_layer = False else: # Update the record of qubit positions for each iteration layout = best_layout # Update the QASM dagcircuit_output.compose_back( self.swap_mapper_layer_update(i, first_layer, best_layout, best_d, best_circ, layerlist), identity_wire_map) # Update initial layout if first_layer: initial_layout = layout first_layer = False # If first_layer is still set, the circuit only has single-qubit gates # so we can use the initial layout to output the entire circuit if first_layer: layout = initial_layout for i, layer in enumerate(layerlist): dagcircuit_output.compose_back(layer["graph"], layout) return dagcircuit_output
Find a swap circuit that implements a permutation for this layer.
def layer_permutation(self, layer_partition, layout, qubit_subset): """Find a swap circuit that implements a permutation for this layer. The goal is to swap qubits such that qubits in the same two-qubit gates are adjacent. Based on Sergey Bravyi's algorithm. The layer_partition is a list of (qu)bit lists and each qubit is a tuple (qreg, index). The layout is a dict mapping qubits in the circuit to qubits in the coupling graph and represents the current positions of the data. The qubit_subset is the subset of qubits in the coupling graph that we have chosen to map into. The coupling is a CouplingGraph. TRIALS is the number of attempts the randomized algorithm makes. Returns: success_flag, best_circ, best_d, best_layout, trivial_flag If success_flag is True, then best_circ contains a DAGCircuit with the swap circuit, best_d contains the depth of the swap circuit, and best_layout contains the new positions of the data qubits after the swap circuit has been applied. The trivial_flag is set if the layer has no multi-qubit gates. """ if self.seed is None: self.seed = np.random.randint(0, np.iinfo(np.int32).max) rng = np.random.RandomState(self.seed) rev_layout = {b: a for a, b in layout.items()} gates = [] for layer in layer_partition: if len(layer) > 2: raise TranspilerError("Layer contains >2 qubit gates") elif len(layer) == 2: gates.append(tuple(layer)) # Can we already apply the gates? dist = sum([self.coupling_map.distance(layout[g[0]][1], layout[g[1]][1]) for g in gates]) if dist == len(gates): circ = DAGCircuit() circ.add_qreg(QuantumRegister(self.coupling_map.size(), "q")) return True, circ, 0, layout, bool(gates) # Begin loop over trials of randomized algorithm n = self.coupling_map.size() best_d = sys.maxsize # initialize best depth best_circ = None # initialize best swap circuit best_layout = None # initialize best final layout QR = QuantumRegister(self.coupling_map.size(), "q") for _ in range(self.trials): trial_layout = layout.copy() rev_trial_layout = rev_layout.copy() # SWAP circuit constructed this trial trial_circ = DAGCircuit() trial_circ.add_qreg(QR) # Compute Sergey's randomized distance xi = {} for i in self.coupling_map.physical_qubits: xi[(QR, i)] = {} for i in self.coupling_map.physical_qubits: i = (QR, i) for j in self.coupling_map.physical_qubits: j = (QR, j) scale = 1 + rng.normal(0, 1 / n) xi[i][j] = scale * self.coupling_map.distance(i[1], j[1]) ** 2 xi[j][i] = xi[i][j] # Loop over depths d up to a max depth of 2n+1 d = 1 # Circuit for this swap slice circ = DAGCircuit() circ.add_qreg(QR) # Identity wire-map for composing the circuits identity_wire_map = {(QR, j): (QR, j) for j in range(n)} while d < 2 * n + 1: # Set of available qubits qubit_set = set(qubit_subset) # While there are still qubits available while qubit_set: # Compute the objective function min_cost = sum([xi[trial_layout[g[0]]][trial_layout[g[1]]] for g in gates]) # Try to decrease objective function progress_made = False # Loop over edges of coupling graph for e in self.coupling_map.get_edges(): e = [(QR, edge) for edge in e] # Are the qubits available? if e[0] in qubit_set and e[1] in qubit_set: # Try this edge to reduce the cost new_layout = trial_layout.copy() new_layout[rev_trial_layout[e[0]]] = e[1] new_layout[rev_trial_layout[e[1]]] = e[0] rev_new_layout = rev_trial_layout.copy() rev_new_layout[e[0]] = rev_trial_layout[e[1]] rev_new_layout[e[1]] = rev_trial_layout[e[0]] # Compute the objective function new_cost = sum([xi[new_layout[g[0]]][new_layout[g[1]]] for g in gates]) # Record progress if we succceed if new_cost < min_cost: progress_made = True min_cost = new_cost opt_layout = new_layout rev_opt_layout = rev_new_layout opt_edge = e # Were there any good choices? if progress_made: qubit_set.remove(opt_edge[0]) qubit_set.remove(opt_edge[1]) trial_layout = opt_layout rev_trial_layout = rev_opt_layout circ.apply_operation_back( SwapGate(), [(opt_edge[0][0], opt_edge[0][1]), (opt_edge[1][0], opt_edge[1][1])], []) else: break # We have either run out of qubits or failed to improve # Compute the coupling graph distance_qubits dist = sum([self.coupling_map.distance(trial_layout[g[0]][1], trial_layout[g[1]][1]) for g in gates]) # If all gates can be applied now, we are finished # Otherwise we need to consider a deeper swap circuit if dist == len(gates): trial_circ.compose_back(circ, identity_wire_map) break # Increment the depth d += 1 # Either we have succeeded at some depth d < dmax or failed dist = sum([self.coupling_map.distance(trial_layout[g[0]][1], trial_layout[g[1]][1]) for g in gates]) if dist == len(gates): if d < best_d: best_circ = trial_circ best_layout = trial_layout best_d = min(best_d, d) if best_circ is None: return False, None, None, None, False return True, best_circ, best_d, best_layout, False
Update the QASM string for an iteration of swap_mapper.
def swap_mapper_layer_update(self, i, first_layer, best_layout, best_d, best_circ, layer_list): """Update the QASM string for an iteration of swap_mapper. i = layer number first_layer = True if this is the first layer with multi-qubit gates best_layout = layout returned from swap algorithm best_d = depth returned from swap algorithm best_circ = swap circuit returned from swap algorithm layer_list = list of circuit objects for each layer Return DAGCircuit object to append to the output DAGCircuit. """ layout = best_layout dagcircuit_output = DAGCircuit() QR = QuantumRegister(self.coupling_map.size(), 'q') dagcircuit_output.add_qreg(QR) # Identity wire-map for composing the circuits identity_wire_map = {(QR, j): (QR, j) for j in range(self.coupling_map.size())} # If this is the first layer with multi-qubit gates, # output all layers up to this point and ignore any # swap gates. Set the initial layout. if first_layer: # Output all layers up to this point for j in range(i + 1): dagcircuit_output.compose_back(layer_list[j]["graph"], layout) # Otherwise, we output the current layer and the associated swap gates. else: # Output any swaps if best_d > 0: dagcircuit_output.compose_back(best_circ, identity_wire_map) # Output this layer dagcircuit_output.compose_back(layer_list[i]["graph"], layout) return dagcircuit_output
Return the correspond floating point number.
def real(self, nested_scope=None): """Return the correspond floating point number.""" operation = self.children[0].operation() expr = self.children[1].real(nested_scope) return operation(expr)
Return the correspond symbolic number.
def sym(self, nested_scope=None): """Return the correspond symbolic number.""" operation = self.children[0].operation() expr = self.children[1].sym(nested_scope) return operation(expr)
Separate a bitstring according to the registers defined in the result header.
def _separate_bitstring(bitstring, creg_sizes): """Separate a bitstring according to the registers defined in the result header.""" substrings = [] running_index = 0 for _, size in reversed(creg_sizes): substrings.append(bitstring[running_index: running_index + size]) running_index += size return ' '.join(substrings)
Format a single bitstring ( memory ) from a single shot experiment.
def format_counts_memory(shot_memory, header=None): """ Format a single bitstring (memory) from a single shot experiment. - The hexadecimals are expanded to bitstrings - Spaces are inserted at register divisions. Args: shot_memory (str): result of a single experiment. header (dict): the experiment header dictionary containing useful information for postprocessing. creg_sizes are a nested list where the inner element is a list of creg name, creg size pairs. memory_slots is an integers specifying the number of total memory_slots in the experiment. Returns: dict: a formatted memory """ if shot_memory.startswith('0x'): shot_memory = _hex_to_bin(shot_memory) if header: creg_sizes = header.get('creg_sizes', None) memory_slots = header.get('memory_slots', None) if memory_slots: shot_memory = _pad_zeros(shot_memory, memory_slots) if creg_sizes and memory_slots: shot_memory = _separate_bitstring(shot_memory, creg_sizes) return shot_memory
Convert nested list of shape (... 2 ) to complex numpy array with shape (... )
def _list_to_complex_array(complex_list): """Convert nested list of shape (..., 2) to complex numpy array with shape (...) Args: complex_list (list): List to convert. Returns: np.ndarray: Complex numpy aray Raises: QiskitError: If inner most array of input nested list is not of length 2. """ arr = np.asarray(complex_list, dtype=np.complex_) if not arr.shape[-1] == 2: raise QiskitError('Inner most nested list is not of length 2.') return arr[..., 0] + 1j*arr[..., 1]
Format an experiment result memory object for measurement level 0.
def format_level_0_memory(memory): """ Format an experiment result memory object for measurement level 0. Args: memory (list): Memory from experiment with `meas_level==1`. `avg` or `single` will be inferred from shape of result memory. Returns: np.ndarray: Measurement level 0 complex numpy array Raises: QiskitError: If the returned numpy array does not have 2 (avg) or 3 (single) indicies. """ formatted_memory = _list_to_complex_array(memory) # infer meas_return from shape of returned data. if not 2 <= len(formatted_memory.shape) <= 3: raise QiskitError('Level zero memory is not of correct shape.') return formatted_memory
Format an experiment result memory object for measurement level 1.
def format_level_1_memory(memory): """ Format an experiment result memory object for measurement level 1. Args: memory (list): Memory from experiment with `meas_level==1`. `avg` or `single` will be inferred from shape of result memory. Returns: np.ndarray: Measurement level 1 complex numpy array Raises: QiskitError: If the returned numpy array does not have 1 (avg) or 2 (single) indicies. """ formatted_memory = _list_to_complex_array(memory) # infer meas_return from shape of returned data. if not 1 <= len(formatted_memory.shape) <= 2: raise QiskitError('Level one memory is not of correct shape.') return formatted_memory
Format an experiment result memory object for measurement level 2.
def format_level_2_memory(memory, header=None): """ Format an experiment result memory object for measurement level 2. Args: memory (list): Memory from experiment with `meas_level==2` and `memory==True`. header (dict): the experiment header dictionary containing useful information for postprocessing. Returns: list[str]: List of bitstrings """ memory_list = [] for shot_memory in memory: memory_list.append(format_counts_memory(shot_memory, header)) return memory_list
Format a single experiment result coming from backend to present to the Qiskit user.
def format_counts(counts, header=None): """Format a single experiment result coming from backend to present to the Qiskit user. Args: counts (dict): counts histogram of multiple shots header (dict): the experiment header dictionary containing useful information for postprocessing. Returns: dict: a formatted counts """ counts_dict = {} for key, val in counts.items(): key = format_counts_memory(key, header) counts_dict[key] = val return counts_dict
Format statevector coming from the backend to present to the Qiskit user.
def format_statevector(vec, decimals=None): """Format statevector coming from the backend to present to the Qiskit user. Args: vec (list): a list of [re, im] complex numbers. decimals (int): the number of decimals in the statevector. If None, no rounding is done. Returns: list[complex]: a list of python complex numbers. """ num_basis = len(vec) vec_complex = np.zeros(num_basis, dtype=complex) for i in range(num_basis): vec_complex[i] = vec[i][0] + 1j * vec[i][1] if decimals: vec_complex = np.around(vec_complex, decimals=decimals) return vec_complex
Format unitary coming from the backend to present to the Qiskit user.
def format_unitary(mat, decimals=None): """Format unitary coming from the backend to present to the Qiskit user. Args: mat (list[list]): a list of list of [re, im] complex numbers decimals (int): the number of decimals in the statevector. If None, no rounding is done. Returns: list[list[complex]]: a matrix of complex numbers """ num_basis = len(mat) mat_complex = np.zeros((num_basis, num_basis), dtype=complex) for i, vec in enumerate(mat): mat_complex[i] = format_statevector(vec, decimals) return mat_complex
Decorator to ensure that a submit has been performed before calling the method.
def requires_submit(func): """ Decorator to ensure that a submit has been performed before calling the method. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs): if self._future is None: raise JobError("Job not submitted yet!. You have to .submit() first!") return func(self, *args, **kwargs) return _wrapper
Submit the job to the backend for execution.
def submit(self): """Submit the job to the backend for execution. Raises: QobjValidationError: if the JSON serialization of the Qobj passed during construction does not validate against the Qobj schema. JobError: if trying to re-submit the job. """ if self._future is not None: raise JobError("We have already submitted the job!") validate_qobj_against_schema(self._qobj) self._future = self._executor.submit(self._fn, self._job_id, self._qobj)
Gets the status of the job by querying the Python s future
def status(self): """Gets the status of the job by querying the Python's future Returns: qiskit.providers.JobStatus: The current JobStatus Raises: JobError: If the future is in unexpected state concurrent.futures.TimeoutError: if timeout occurred. """ # The order is important here if self._future.running(): _status = JobStatus.RUNNING elif self._future.cancelled(): _status = JobStatus.CANCELLED elif self._future.done(): _status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR else: # Note: There is an undocumented Future state: PENDING, that seems to show up when # the job is enqueued, waiting for someone to pick it up. We need to deal with this # state but there's no public API for it, so we are assuming that if the job is not # in any of the previous states, is PENDING, ergo INITIALIZING for us. _status = JobStatus.INITIALIZING return _status
Whether lo_freq is within the LoRange.
def includes(self, lo_freq: float) -> bool: """Whether `lo_freq` is within the `LoRange`. Args: lo_freq: LO frequency to be checked Returns: bool: True if lo_freq is included in this range, otherwise False """ if self._lb <= lo_freq <= self._ub: return True return False
Create a bloch sphere representation.
def iplot_bloch_multivector(rho, figsize=None): """ Create a bloch sphere representation. Graphical representation of the input array, using as much bloch spheres as qubit are required. Args: rho (array): State vector or density matrix figsize (tuple): Figure size in pixels. """ # HTML html_template = Template(""" <p> <div id="content_$divNumber" style="position: absolute; z-index: 1;"> <div id="bloch_$divNumber"></div> </div> </p> """) # JavaScript javascript_template = Template(""" <script> requirejs.config({ paths: { qVisualization: "https://qvisualization.mybluemix.net/q-visualizations" } }); data = $data; dataValues = []; for (var i = 0; i < data.length; i++) { // Coordinates var x = data[i][0]; var y = data[i][1]; var z = data[i][2]; var point = {'x': x, 'y': y, 'z': z}; dataValues.push(point); } require(["qVisualization"], function(qVisualizations) { // Plot figure qVisualizations.plotState("bloch_$divNumber", "bloch", dataValues, $options); }); </script> """) rho = _validate_input_state(rho) if figsize is None: options = {} else: options = {'width': figsize[0], 'height': figsize[1]} # Process data and execute num = int(np.log2(len(rho))) bloch_data = [] for i in range(num): pauli_singles = [Pauli.pauli_single(num, i, 'X'), Pauli.pauli_single(num, i, 'Y'), Pauli.pauli_single(num, i, 'Z')] bloch_state = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))), pauli_singles)) bloch_data.append(bloch_state) div_number = str(time.time()) div_number = re.sub('[.]', '', div_number) html = html_template.substitute({ 'divNumber': div_number }) javascript = javascript_template.substitute({ 'data': bloch_data, 'divNumber': div_number, 'options': options }) display(HTML(html + javascript))
Parallel execution of a mapping of values to the function task. This is functionally equivalent to::
def parallel_map(task, values, task_args=tuple(), task_kwargs={}, # pylint: disable=W0102 num_processes=CPU_COUNT): """ Parallel execution of a mapping of `values` to the function `task`. This is functionally equivalent to:: result = [task(value, *task_args, **task_kwargs) for value in values] On Windows this function defaults to a serial implementation to avoid the overhead from spawning processes in Windows. Args: task (func): Function that is to be called for each value in ``values``. values (array_like): List or array of values for which the ``task`` function is to be evaluated. task_args (list): Optional additional arguments to the ``task`` function. task_kwargs (dict): Optional additional keyword argument to the ``task`` function. num_processes (int): Number of processes to spawn. Returns: result: The result list contains the value of ``task(value, *task_args, **task_kwargs)`` for each value in ``values``. Raises: QiskitError: If user interrupts via keyboard. Events: terra.parallel.start: The collection of parallel tasks are about to start. terra.parallel.update: One of the parallel task has finished. terra.parallel.finish: All the parallel tasks have finished. """ if len(values) == 1: return [task(values[0], *task_args, **task_kwargs)] Publisher().publish("terra.parallel.start", len(values)) nfinished = [0] def _callback(_): nfinished[0] += 1 Publisher().publish("terra.parallel.done", nfinished[0]) # Run in parallel if not Win and not in parallel already if platform.system() != 'Windows' and num_processes > 1 \ and os.getenv('QISKIT_IN_PARALLEL') == 'FALSE': os.environ['QISKIT_IN_PARALLEL'] = 'TRUE' try: pool = Pool(processes=num_processes) async_res = [pool.apply_async(task, (value,) + task_args, task_kwargs, _callback) for value in values] while not all([item.ready() for item in async_res]): for item in async_res: item.wait(timeout=0.1) pool.terminate() pool.join() except KeyboardInterrupt: pool.terminate() pool.join() Publisher().publish("terra.parallel.finish") raise QiskitError('Keyboard interrupt in parallel_map.') Publisher().publish("terra.parallel.finish") os.environ['QISKIT_IN_PARALLEL'] = 'FALSE' return [ar.get() for ar in async_res] # Cannot do parallel on Windows , if another parallel_map is running in parallel, # or len(values) == 1. results = [] for _, value in enumerate(values): result = task(value, *task_args, **task_kwargs) results.append(result) _callback(0) Publisher().publish("terra.parallel.finish") return results
Embed default qubit LO frequencies from backend and format them to list object. If configured lo frequency is the same as default this method returns None.
def get_qubit_los(self, user_lo_config): """Embed default qubit LO frequencies from backend and format them to list object. If configured lo frequency is the same as default, this method returns `None`. Args: user_lo_config (LoConfig): A dictionary of LOs to format. Returns: list: A list of qubit LOs. Raises: PulseError: when LO frequencies are missing. """ try: _q_los = self.default_qubit_los.copy() except KeyError: raise PulseError('Qubit default frequencies not exist.') for channel, lo_freq in user_lo_config.qubit_lo_dict().items(): _q_los[channel.index] = lo_freq if _q_los == self.default_qubit_los: return None return _q_los
Embed default meas LO frequencies from backend and format them to list object. If configured lo frequency is the same as default this method returns None.
def get_meas_los(self, user_lo_config): """Embed default meas LO frequencies from backend and format them to list object. If configured lo frequency is the same as default, this method returns `None`. Args: user_lo_config (LoConfig): A dictionary of LOs to format. Returns: list: A list of meas LOs. Raises: PulseError: when LO frequencies are missing. """ try: _m_los = self.default_meas_los.copy() except KeyError: raise PulseError('Default measurement frequencies not exist.') for channel, lo_freq in user_lo_config.meas_lo_dict().items(): _m_los[channel.index] = lo_freq if _m_los == self.default_meas_los: return None return _m_los
Expand all op nodes to the given basis.
def run(self, dag): """Expand all op nodes to the given basis. Args: dag(DAGCircuit): input dag Raises: QiskitError: if unable to unroll given the basis due to undefined decomposition rules (such as a bad basis) or excessive recursion. Returns: DAGCircuit: output unrolled dag """ # Walk through the DAG and expand each non-basis node for node in dag.op_nodes(): basic_insts = ['measure', 'reset', 'barrier', 'snapshot'] if node.name in basic_insts: # TODO: this is legacy behavior.Basis_insts should be removed that these # instructions should be part of the device-reported basis. Currently, no # backend reports "measure", for example. continue if node.name in self.basis: # If already a base, ignore. continue # TODO: allow choosing other possible decompositions rule = node.op.definition if not rule: raise QiskitError("Cannot unroll the circuit to the given basis, %s. " "No rule to expand instruction %s." % (str(self.basis), node.op.name)) # hacky way to build a dag on the same register as the rule is defined # TODO: need anonymous rules to address wires by index decomposition = DAGCircuit() decomposition.add_qreg(rule[0][1][0][0]) for inst in rule: decomposition.apply_operation_back(*inst) unrolled_dag = self.run(decomposition) # recursively unroll ops dag.substitute_node_with_dag(node, unrolled_dag) return dag
Create a Q sphere representation.
def iplot_state_qsphere(rho, figsize=None): """ Create a Q sphere representation. Graphical representation of the input array, using a Q sphere for each eigenvalue. Args: rho (array): State vector or density matrix. figsize (tuple): Figure size in pixels. """ # HTML html_template = Template(""" <p> <div id="content_$divNumber" style="position: absolute; z-index: 1;"> <div id="qsphere_$divNumber"></div> </div> </p> """) # JavaScript javascript_template = Template(""" <script> requirejs.config({ paths: { qVisualization: "https://qvisualization.mybluemix.net/q-visualizations" } }); require(["qVisualization"], function(qVisualizations) { data = $data; qVisualizations.plotState("qsphere_$divNumber", "qsphere", data, $options); }); </script> """) rho = _validate_input_state(rho) if figsize is None: options = {} else: options = {'width': figsize[0], 'height': figsize[1]} qspheres_data = [] # Process data and execute num = int(np.log2(len(rho))) # get the eigenvectors and eigenvalues weig, stateall = linalg.eigh(rho) for _ in range(2**num): # start with the max probmix = weig.max() prob_location = weig.argmax() if probmix > 0.001: # print("The " + str(k) + "th eigenvalue = " + str(probmix)) # get the max eigenvalue state = stateall[:, prob_location] loc = np.absolute(state).argmax() # get the element location closes to lowest bin representation. for j in range(2**num): test = np.absolute(np.absolute(state[j]) - np.absolute(state[loc])) if test < 0.001: loc = j break # remove the global phase angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi) angleset = np.exp(-1j*angles) state = angleset*state state.flatten() spherepoints = [] for i in range(2**num): # get x,y,z points element = bin(i)[2:].zfill(num) weight = element.count("1") number_of_divisions = n_choose_k(num, weight) weight_order = bit_string_index(element) angle = weight_order * 2 * np.pi / number_of_divisions zvalue = -2 * weight / num + 1 xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle) yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle) # get prob and angle - prob will be shade and angle color prob = np.real(np.dot(state[i], state[i].conj())) angles = (np.angle(state[i]) + 2 * np.pi) % (2 * np.pi) qpoint = { 'x': xvalue, 'y': yvalue, 'z': zvalue, 'prob': prob, 'phase': angles } spherepoints.append(qpoint) # Associate all points to one sphere sphere = { 'points': spherepoints, 'eigenvalue': probmix } # Add sphere to the spheres array qspheres_data.append(sphere) weig[prob_location] = 0 div_number = str(time.time()) div_number = re.sub('[.]', '', div_number) html = html_template.substitute({ 'divNumber': div_number }) javascript = javascript_template.substitute({ 'data': qspheres_data, 'divNumber': div_number, 'options': options }) display(HTML(html + javascript))
Return the number of combinations for n choose k.
def n_choose_k(n, k): """Return the number of combinations for n choose k. Args: n (int): the total number of options . k (int): The number of elements. Returns: int: returns the binomial coefficient """ if n == 0: return 0 return reduce(lambda x, y: x * y[0] / y[1], zip(range(n - k + 1, n + 1), range(1, k + 1)), 1)
Return the index of a string of 0s and 1s.
def bit_string_index(text): """Return the index of a string of 0s and 1s.""" n = len(text) k = text.count("1") if text.count("0") != n - k: raise VisualizationError("s must be a string of 0 and 1") ones = [pos for pos, char in enumerate(text) if char == "1"] return lex_index(n, k, ones)
Return the lex index of a combination..
def lex_index(n, k, lst): """Return the lex index of a combination.. Args: n (int): the total number of options . k (int): The number of elements. lst (list): list Returns: int: returns int index for lex order Raises: VisualizationError: if length of list is not equal to k """ if len(lst) != k: raise VisualizationError("list should have length k") comb = list(map(lambda x: n - 1 - x, lst)) dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)]) return int(dualm)
Plot a hinton diagram for the quanum state.
def plot_state_hinton(rho, title='', figsize=None): """Plot a hinton diagram for the quanum state. Args: rho (ndarray): Numpy array for state vector or density matrix. title (str): a string that represents the plot title figsize (tuple): Figure size in inches. Returns: matplotlib.Figure: The matplotlib.Figure of the visualization Raises: ImportError: Requires matplotlib. """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') rho = _validate_input_state(rho) if figsize is None: figsize = (8, 5) num = int(np.log2(len(rho))) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize) max_weight = 2 ** np.ceil(np.log(np.abs(rho).max()) / np.log(2)) datareal = np.real(rho) dataimag = np.imag(rho) column_names = [bin(i)[2:].zfill(num) for i in range(2**num)] row_names = [bin(i)[2:].zfill(num) for i in range(2**num)] lx = len(datareal[0]) # Work out matrix dimensions ly = len(datareal[:, 0]) # Real ax1.patch.set_facecolor('gray') ax1.set_aspect('equal', 'box') ax1.xaxis.set_major_locator(plt.NullLocator()) ax1.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(datareal): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(w) / max_weight) rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax1.add_patch(rect) ax1.set_xticks(np.arange(0, lx+0.5, 1)) ax1.set_yticks(np.arange(0, ly+0.5, 1)) ax1.set_yticklabels(row_names, fontsize=14) ax1.set_xticklabels(column_names, fontsize=14, rotation=90) ax1.autoscale_view() ax1.invert_yaxis() ax1.set_title('Real[rho]', fontsize=14) # Imaginary ax2.patch.set_facecolor('gray') ax2.set_aspect('equal', 'box') ax2.xaxis.set_major_locator(plt.NullLocator()) ax2.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(dataimag): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(w) / max_weight) rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax2.add_patch(rect) if np.any(dataimag != 0): ax2.set_xticks(np.arange(0, lx+0.5, 1)) ax2.set_yticks(np.arange(0, ly+0.5, 1)) ax2.set_yticklabels(row_names, fontsize=14) ax2.set_xticklabels(column_names, fontsize=14, rotation=90) ax2.autoscale_view() ax2.invert_yaxis() ax2.set_title('Imag[rho]', fontsize=14) if title: fig.suptitle(title, fontsize=16) plt.tight_layout() plt.close(fig) return fig
Plot the Bloch sphere.
def plot_bloch_vector(bloch, title="", ax=None, figsize=None): """Plot the Bloch sphere. Plot a sphere, axes, the Bloch vector, and its projections onto each axis. Args: bloch (list[double]): array of three elements where [<x>, <y>, <z>] title (str): a string that represents the plot title ax (matplotlib.Axes): An Axes to use for rendering the bloch sphere figsize (tuple): Figure size in inches. Has no effect is passing `ax`. Returns: Figure: A matplotlib figure instance if `ax = None`. Raises: ImportError: Requires matplotlib. """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') if figsize is None: figsize = (5, 5) B = Bloch(axes=ax) B.add_vectors(bloch) B.render(title=title) if ax is None: fig = B.fig fig.set_size_inches(figsize[0], figsize[1]) plt.close(fig) return fig return None
Plot the Bloch sphere.
def plot_bloch_multivector(rho, title='', figsize=None): """Plot the Bloch sphere. Plot a sphere, axes, the Bloch vector, and its projections onto each axis. Args: rho (ndarray): Numpy array for state vector or density matrix. title (str): a string that represents the plot title figsize (tuple): Has no effect, here for compatibility only. Returns: Figure: A matplotlib figure instance if `ax = None`. Raises: ImportError: Requires matplotlib. """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') rho = _validate_input_state(rho) num = int(np.log2(len(rho))) width, height = plt.figaspect(1/num) fig = plt.figure(figsize=(width, height)) for i in range(num): ax = fig.add_subplot(1, num, i + 1, projection='3d') pauli_singles = [ Pauli.pauli_single(num, i, 'X'), Pauli.pauli_single(num, i, 'Y'), Pauli.pauli_single(num, i, 'Z') ] bloch_state = list( map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))), pauli_singles)) plot_bloch_vector(bloch_state, "qubit " + str(i), ax=ax, figsize=figsize) fig.suptitle(title, fontsize=16) plt.close(fig) return fig
Plot the cityscape of quantum state.
def plot_state_city(rho, title="", figsize=None, color=None, alpha=1): """Plot the cityscape of quantum state. Plot two 3d bar graphs (two dimensional) of the real and imaginary part of the density matrix rho. Args: rho (ndarray): Numpy array for state vector or density matrix. title (str): a string that represents the plot title figsize (tuple): Figure size in inches. color (list): A list of len=2 giving colors for real and imaginary components of matrix elements. alpha (float): Transparency value for bars Returns: matplotlib.Figure: The matplotlib.Figure of the visualization Raises: ImportError: Requires matplotlib. ValueError: When 'color' is not a list of len=2. """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') rho = _validate_input_state(rho) num = int(np.log2(len(rho))) # get the real and imag parts of rho datareal = np.real(rho) dataimag = np.imag(rho) # get the labels column_names = [bin(i)[2:].zfill(num) for i in range(2**num)] row_names = [bin(i)[2:].zfill(num) for i in range(2**num)] lx = len(datareal[0]) # Work out matrix dimensions ly = len(datareal[:, 0]) xpos = np.arange(0, lx, 1) # Set up a mesh of positions ypos = np.arange(0, ly, 1) xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25) xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(lx*ly) dx = 0.5 * np.ones_like(zpos) # width of bars dy = dx.copy() dzr = datareal.flatten() dzi = dataimag.flatten() if color is None: color = ["#648fff", "#648fff"] else: if len(color) != 2: raise ValueError("'color' must be a list of len=2.") if color[0] is None: color[0] = "#648fff" if color[1] is None: color[1] = "#648fff" # set default figure size if figsize is None: figsize = (15, 5) fig = plt.figure(figsize=figsize) ax1 = fig.add_subplot(1, 2, 1, projection='3d') x = [0, max(xpos)+0.5, max(xpos)+0.5, 0] y = [0, 0, max(ypos)+0.5, max(ypos)+0.5] z = [0, 0, 0, 0] verts = [list(zip(x, y, z))] fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0]) for idx, cur_zpos in enumerate(zpos): if dzr[idx] > 0: zorder = 2 else: zorder = 0 b1 = ax1.bar3d(xpos[idx], ypos[idx], cur_zpos, dx[idx], dy[idx], dzr[idx], alpha=alpha, zorder=zorder) b1.set_facecolors(fc1[6*idx:6*idx+6]) pc1 = Poly3DCollection(verts, alpha=0.15, facecolor='k', linewidths=1, zorder=1) if min(dzr) < 0 < max(dzr): ax1.add_collection3d(pc1) ax2 = fig.add_subplot(1, 2, 2, projection='3d') fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1]) for idx, cur_zpos in enumerate(zpos): if dzi[idx] > 0: zorder = 2 else: zorder = 0 b2 = ax2.bar3d(xpos[idx], ypos[idx], cur_zpos, dx[idx], dy[idx], dzi[idx], alpha=alpha, zorder=zorder) b2.set_facecolors(fc2[6*idx:6*idx+6]) pc2 = Poly3DCollection(verts, alpha=0.2, facecolor='k', linewidths=1, zorder=1) if min(dzi) < 0 < max(dzi): ax2.add_collection3d(pc2) ax1.set_xticks(np.arange(0.5, lx+0.5, 1)) ax1.set_yticks(np.arange(0.5, ly+0.5, 1)) max_dzr = max(dzr) min_dzr = min(dzr) if max_dzr != min_dzr: ax1.axes.set_zlim3d(np.min(dzr), np.max(dzr)+1e-9) else: if min_dzr == 0: ax1.axes.set_zlim3d(np.min(dzr), np.max(dzr)+1e-9) else: ax1.axes.set_zlim3d(auto=True) ax1.zaxis.set_major_locator(MaxNLocator(5)) ax1.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45) ax1.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5) ax1.set_zlabel("Real[rho]", fontsize=14) for tick in ax1.zaxis.get_major_ticks(): tick.label.set_fontsize(14) ax2.set_xticks(np.arange(0.5, lx+0.5, 1)) ax2.set_yticks(np.arange(0.5, ly+0.5, 1)) min_dzi = np.min(dzi) max_dzi = np.max(dzi) if min_dzi != max_dzi: eps = 0 ax2.zaxis.set_major_locator(MaxNLocator(5)) ax2.axes.set_zlim3d(np.min(dzi), np.max(dzi)+eps) else: if min_dzi == 0: ax2.set_zticks([0]) eps = 1e-9 ax2.axes.set_zlim3d(np.min(dzi), np.max(dzi)+eps) else: ax2.axes.set_zlim3d(auto=True) ax2.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45) ax2.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5) ax2.set_zlabel("Imag[rho]", fontsize=14) for tick in ax2.zaxis.get_major_ticks(): tick.label.set_fontsize(14) plt.suptitle(title, fontsize=16) plt.tight_layout() plt.close(fig) return fig
Plot the paulivec representation of a quantum state.
def plot_state_paulivec(rho, title="", figsize=None, color=None): """Plot the paulivec representation of a quantum state. Plot a bargraph of the mixed state rho over the pauli matrices Args: rho (ndarray): Numpy array for state vector or density matrix title (str): a string that represents the plot title figsize (tuple): Figure size in inches. color (list or str): Color of the expectation value bars. Returns: matplotlib.Figure: The matplotlib.Figure of the visualization Raises: ImportError: Requires matplotlib. """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') rho = _validate_input_state(rho) if figsize is None: figsize = (7, 5) num = int(np.log2(len(rho))) labels = list(map(lambda x: x.to_label(), pauli_group(num))) values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))), pauli_group(num))) numelem = len(values) if color is None: color = "#648fff" ind = np.arange(numelem) # the x locations for the groups width = 0.5 # the width of the bars fig, ax = plt.subplots(figsize=figsize) ax.grid(zorder=0, linewidth=1, linestyle='--') ax.bar(ind, values, width, color=color, zorder=2) ax.axhline(linewidth=1, color='k') # add some text for labels, title, and axes ticks ax.set_ylabel('Expectation value', fontsize=14) ax.set_xticks(ind) ax.set_yticks([-1, -0.5, 0, 0.5, 1]) ax.set_xticklabels(labels, fontsize=14, rotation=70) ax.set_xlabel('Pauli', fontsize=14) ax.set_ylim([-1, 1]) ax.set_facecolor('#eeeeee') for tick in ax.xaxis.get_major_ticks()+ax.yaxis.get_major_ticks(): tick.label.set_fontsize(14) ax.set_title(title, fontsize=16) plt.close(fig) return fig
Return the index of a string of 0s and 1s.
def bit_string_index(s): """Return the index of a string of 0s and 1s.""" n = len(s) k = s.count("1") if s.count("0") != n - k: raise VisualizationError("s must be a string of 0 and 1") ones = [pos for pos, char in enumerate(s) if char == "1"] return lex_index(n, k, ones)
Map a phase of a complexnumber to a color in ( r g b ).
def phase_to_color_wheel(complex_number): """Map a phase of a complexnumber to a color in (r,g,b). complex_number is phase is first mapped to angle in the range [0, 2pi] and then to a color wheel with blue at zero phase. """ angles = np.angle(complex_number) angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6) color_map = { 0: (0, 0, 1), # blue, 1: (0.5, 0, 1), # blue-violet 2: (1, 0, 1), # violet 3: (1, 0, 0.5), # red-violet, 4: (1, 0, 0), # red 5: (1, 0.5, 0), # red-oranage, 6: (1, 1, 0), # orange 7: (0.5, 1, 0), # orange-yellow 8: (0, 1, 0), # yellow, 9: (0, 1, 0.5), # yellow-green, 10: (0, 1, 1), # green, 11: (0, 0.5, 1) # green-blue, } return color_map[angle_round]
Plot the qsphere representation of a quantum state.
def plot_state_qsphere(rho, figsize=None): """Plot the qsphere representation of a quantum state. Args: rho (ndarray): State vector or density matrix representation. of quantum state. figsize (tuple): Figure size in inches. Returns: Figure: A matplotlib figure instance. Raises: ImportError: Requires matplotlib. """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') rho = _validate_input_state(rho) if figsize is None: figsize = (7, 7) num = int(np.log2(len(rho))) # get the eigenvectors and eigenvalues we, stateall = linalg.eigh(rho) for _ in range(2**num): # start with the max probmix = we.max() prob_location = we.argmax() if probmix > 0.001: # get the max eigenvalue state = stateall[:, prob_location] loc = np.absolute(state).argmax() # get the element location closes to lowest bin representation. for j in range(2**num): test = np.absolute(np.absolute(state[j]) - np.absolute(state[loc])) if test < 0.001: loc = j break # remove the global phase angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi) angleset = np.exp(-1j*angles) # print(state) # print(angles) state = angleset*state # print(state) state.flatten() # start the plotting fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection='3d') ax.axes.set_xlim3d(-1.0, 1.0) ax.axes.set_ylim3d(-1.0, 1.0) ax.axes.set_zlim3d(-1.0, 1.0) ax.set_aspect("equal") ax.axes.grid(False) # Plot semi-transparent sphere u = np.linspace(0, 2 * np.pi, 25) v = np.linspace(0, np.pi, 25) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k', alpha=0.05, linewidth=0) # wireframe # Get rid of the panes ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the spines ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the ticks ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) d = num for i in range(2**num): # get x,y,z points element = bin(i)[2:].zfill(num) weight = element.count("1") zvalue = -2 * weight / d + 1 number_of_divisions = n_choose_k(d, weight) weight_order = bit_string_index(element) # if weight_order >= number_of_divisions / 2: # com_key = compliment(element) # weight_order_temp = bit_string_index(com_key) # weight_order = np.floor( # number_of_divisions / 2) + weight_order_temp + 1 angle = weight_order * 2 * np.pi / number_of_divisions xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle) yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle) ax.plot([xvalue], [yvalue], [zvalue], markerfacecolor=(.5, .5, .5), markeredgecolor=(.5, .5, .5), marker='o', markersize=10, alpha=1) # get prob and angle - prob will be shade and angle color prob = np.real(np.dot(state[i], state[i].conj())) colorstate = phase_to_color_wheel(state[i]) a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue], mutation_scale=20, alpha=prob, arrowstyle="-", color=colorstate, lw=10) ax.add_artist(a) # add weight lines for weight in range(d + 1): theta = np.linspace(-2 * np.pi, 2 * np.pi, 100) z = -2 * weight / d + 1 r = np.sqrt(1 - z**2) x = r * np.cos(theta) y = r * np.sin(theta) ax.plot(x, y, z, color=(.5, .5, .5)) # add center point ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5), markeredgecolor=(.5, .5, .5), marker='o', markersize=10, alpha=1) we[prob_location] = 0 else: break plt.tight_layout() plt.close(fig) return fig
Plot the quantum state.
def plot_state(quantum_state, method='city', figsize=None): """Plot the quantum state. Args: quantum_state (ndarray): statevector or density matrix representation of a quantum state. method (str): Plotting method to use. figsize (tuple): Figure size in inches, Returns: matplotlib.Figure: The matplotlib.Figure of the visualization Raises: ImportError: Requires matplotlib. VisualizationError: if the input is not a statevector or density matrix, or if the state is not an multi-qubit quantum state. """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed.') warnings.warn("plot_state is deprecated, and will be removed in \ the 0.9 release. Use the plot_state_ * functions \ instead.", DeprecationWarning) # Check if input is a statevector, and convert to density matrix rho = _validate_input_state(quantum_state) fig = None if method == 'city': fig = plot_state_city(rho, figsize=figsize) elif method == "paulivec": fig = plot_state_paulivec(rho, figsize=figsize) elif method == "qsphere": fig = plot_state_qsphere(rho, figsize=figsize) elif method == "bloch": plot_bloch_multivector(rho, figsize=figsize) elif method == "hinton": fig = plot_state_hinton(rho, figsize=figsize) return fig
Generates shaded facecolors for shaded bars. This is here to work around a Matplotlib bug where alpha does not work in Bar3D. Args: x ( array_like ): The x - coordinates of the anchor point of the bars. y ( array_like ): The y - coordinates of the anchor point of the bars. z ( array_like ): The z - coordinates of the anchor point of the bars. dx ( array_like ): Width of bars. dy ( array_like ): Depth of bars. dz ( array_like ): Height of bars. color ( array_like ): sequence of valid color specifications optional Returns: list: Shaded colors for bars.
def generate_facecolors(x, y, z, dx, dy, dz, color): """Generates shaded facecolors for shaded bars. This is here to work around a Matplotlib bug where alpha does not work in Bar3D. Args: x (array_like): The x- coordinates of the anchor point of the bars. y (array_like): The y- coordinates of the anchor point of the bars. z (array_like): The z- coordinates of the anchor point of the bars. dx (array_like): Width of bars. dy (array_like): Depth of bars. dz (array_like): Height of bars. color (array_like): sequence of valid color specifications, optional Returns: list: Shaded colors for bars. """ cuboid = np.array([ # -z ( (0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0), ), # +z ( (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1), ), # -y ( (0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1), ), # +y ( (0, 1, 0), (0, 1, 1), (1, 1, 1), (1, 1, 0), ), # -x ( (0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0), ), # +x ( (1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 0, 1), ), ]) # indexed by [bar, face, vertex, coord] polys = np.empty(x.shape + cuboid.shape) # handle each coordinate separately for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]: p = p[..., np.newaxis, np.newaxis] dp = dp[..., np.newaxis, np.newaxis] polys[..., i] = p + dp * cuboid[..., i] # collapse the first two axes polys = polys.reshape((-1,) + polys.shape[2:]) facecolors = [] if len(color) == len(x): # bar colors specified, need to expand to number of faces for c in color: facecolors.extend([c] * 6) else: # a single color specified, or face colors specified explicitly facecolors = list(mcolors.to_rgba_array(color)) if len(facecolors) < len(x): facecolors *= (6 * len(x)) normals = _generate_normals(polys) return _shade_colors(facecolors, normals)