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 o...
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._initi...
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"] ...
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) ...
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._...
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 simulato...
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_option...
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.c...
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:: { ...
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) + ...
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, dtyp...
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_ten...
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_unitar...
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 bac...
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) ...
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[ab...
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()...
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:: { ...
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_q...
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(...
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(sel...
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 b...
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 broadcas...
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 ...
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 interv...
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 ...
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 ...
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]: ...
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] ...
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, 'aco...
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 twic...
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 enum...
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 (bo...
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 ...
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]], []), ...
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 ...
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 i...
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 n...
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 ...
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): ...
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, _...
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, CompositeGat...
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 ...
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. ...
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...
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: ...
Evolve a quantum state by the operator.
def _evolve_subsystem(self, state, qargs): """Evolve a quantum state by the operator. Args: state (QuantumState): The input statevector or density matrix. qargs (list): a list of QuantumState subsystem positions to apply the operator on. Retur...
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 ve...
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 co...
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` d...
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 l...
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_partitio...
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 =...
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 += si...
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...
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 o...
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 c...
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 c...
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 f...
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 postprocessin...
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: ...
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: ...
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)...
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. """ i...
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. ""...
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: ...
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 i...
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 val...
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...
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: ...
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: ...
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. """ ...
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] / ...
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 n...
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: matp...
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...
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 fi...
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 mat...
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...
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....
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. ...
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 i...
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 a...
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- coordinat...