repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/C2QA/bosonic-qiskit
C2QA
from math import sqrt, pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import oracle_simple import composed_gates def get_circuit(n, oracles): """ Build the circuit composed by the oracle black box and the other quantum gates. :param n: The number of qubits (not including the ancillas) :param oracles: A list of black box (quantum) oracles; each of them selects a specific state :returns: The proper quantum circuit :rtype: qiskit.QuantumCircuit """ cr = ClassicalRegister(n) ## Testing if n > 3: #anc = QuantumRegister(n - 1, 'anc') # n qubits for the real number # n - 1 qubits for the ancillas qr = QuantumRegister(n + n - 1) qc = QuantumCircuit(qr, cr) else: # We don't need ancillas qr = QuantumRegister(n) qc = QuantumCircuit(qr, cr) ## /Testing print("Number of qubits is {0}".format(len(qr))) print(qr) # Initial superposition for j in range(n): qc.h(qr[j]) # The length of the oracles list, or, in other words, how many roots of the function do we have m = len(oracles) # Grover's algorithm is a repetition of an oracle box and a diffusion box. # The number of repetitions is given by the following formula. print("n is ", n) r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2)) print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r)) oracle_t1 = oracle_simple.OracleSimple(n, 5) oracle_t2 = oracle_simple.OracleSimple(n, 0) for j in range(r): for i in range(len(oracles)): oracles[i].get_circuit(qr, qc) diffusion(n, qr, qc) for j in range(n): qc.measure(qr[j], cr[j]) return qc, len(qr) def diffusion(n, qr, qc): """ The Grover diffusion operator. Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit. """ for j in range(n): qc.h(qr[j]) # D matrix, flips state |000> only (instead of flipping all the others) for j in range(n): qc.x(qr[j]) # 0..n-2 control bits, n-1 target, n.. if n > 3: composed_gates.n_controlled_Z_circuit( qc, [qr[j] for j in range(n - 1)], qr[n - 1], [qr[j] for j in range(n, n + n - 1)]) else: composed_gates.n_controlled_Z_circuit( qc, [qr[j] for j in range(n - 1)], qr[n - 1], None) for j in range(n): qc.x(qr[j]) for j in range(n): qc.h(qr[j])
https://github.com/C2QA/bosonic-qiskit
C2QA
import math import qiskit from c2qa.circuit import CVCircuit from c2qa.kraus import PhotonLossNoisePass from c2qa.parameterized_unitary_gate import ParameterizedUnitaryGate def discretize_circuits( circuit: CVCircuit, segments_per_gate: int = 10, keep_state: bool = True, qubit:qiskit.circuit.quantumcircuit.QubitSpecifier = None, cbit: qiskit.circuit.quantumcircuit.QubitSpecifier = None, sequential_subcircuit: bool = False,): """ Discretize gates into a circuit into segments where each segment ends an indiviudal circuit. Useful for incrementally applying noise or animating the circuit. Args: circuit (CVCircuit): circuit to simulate and plot segments_per_gate (int, optional): Number of segments to split each gate into. Defaults to 10. keep_state (bool, optional): True if each gate segments builds on the previous gegment's state vector. False if each segment starts over from the beginning of the circuit. If True, it requires sequential simulation of each segment. qubit ([QubitSpecifier]): Qubit to measure, if performing Hadamard measure for use with cat states. Defaults to None. cbit ([QubitSpecifier]): Classical bit to measure into, if performing Hadamard measure for use with cat states. Defaults to None. sequential_subcircuit (bool, optional): boolean flag to animate subcircuits as one gate (False) or as sequential gates (True). Defautls to False. Returns: [list]: List of discretized Qiskit circuit """ sim_circuits = [] # Each segment will have its own circuit to simulate # base_circuit is copied each gate iteration to build circuit segments to simulate base_circuit = circuit.copy() base_circuit.data.clear() # Is this safe -- could we copy without data? for inst, qargs, cargs in circuit.data: # TODO - get qubit & cbit for measure instead of using parameters # qubit = xxx # cbit = yyy segments = __to_segments(inst, segments_per_gate, keep_state, sequential_subcircuit) for segment in segments: sim_circuit = base_circuit.copy() sim_circuit.append(instruction=segment, qargs=qargs, cargs=cargs) if qubit and cbit: # sim_circuit.barrier() sim_circuit.h(qubit) sim_circuit.measure(qubit, cbit) sim_circuits.append(sim_circuit) # Start with current circuit for the next segment base_circuit = sim_circuit return sim_circuits def discretize_single_circuit( circuit: CVCircuit, segments_per_gate: int = 10, epsilon: float = None, sequential_subcircuit: bool = False, statevector_per_segment: bool = False, statevector_label: str = "segment_", noise_passes = None ): """ Discretize gates into a circuit into segments within a single output circuit. Useful for incrementally applying noise or animating the circuit. Args: circuit (CVCircuit): circuit to simulate and plot segments_per_gate (int, optional): Number of segments to split each gate into. Defaults to 10. epsilon (float, optional): float value used to discretize, must specify along with kappa kappa (float, optional): float phton loss rate to determine discretization sice, must specify along with epsilon sequential_subcircuit (bool, optional): boolean flag to animate subcircuits as one gate (False) or as sequential gates (True). Defaults to False. statevector_per_segment (bool, optional): boolean flag to save a statevector per gate segment. True will call Qiskit save_statevector after each segment is simulated, creating statevectors labeled "segment_*" that can used after simulation. Defaults to False. statevector_label (str, optional): String prefix to use for the statevector saved after each segment noise_passes (list of Qiskit noise passes, optional): noise passes to apply Returns: discretized Qiskit circuit """ # discretized is a copy of the circuit as a whole. Each gate segment be added to simulate discretized = circuit.copy() discretized.data.clear() # Is this safe -- could we copy without data? if noise_passes: if not isinstance(noise_passes, list): noise_passes = [noise_passes] segment_count = 0 for inst, qargs, cargs in circuit.data: num_segments = segments_per_gate qargs_indices = [qubit._index for qubit in qargs] # FIXME -- is there a public API to get the qubit's index in Qiskit v1.0+? if noise_passes and not (isinstance(inst, qiskit.circuit.instruction.Instruction) and inst.name == "initialize"): # Don't discretize instructions initializing system state: noise_pass = None for current in noise_passes: if isinstance(current, PhotonLossNoisePass) and current.applies_to_instruction(inst, qargs_indices): noise_pass = current break if epsilon is not None and noise_pass is not None: # FIXME - which of the qumodes' loss rates and QumodeRegister's cutoff should we use? photon_loss_rate = noise_pass.photon_loss_rates_sec[0] num_segments = math.ceil((photon_loss_rate * noise_pass.duration_to_sec(inst) * circuit.get_qmr_cutoff(0)) / epsilon) segments = __to_segments(inst=inst, segments_per_gate=num_segments, keep_state=True, sequential_subcircuit=sequential_subcircuit) for segment in segments: discretized.append(instruction=segment, qargs=qargs, cargs=cargs) if statevector_per_segment: discretized.save_statevector(label=f"{statevector_label}{segment_count}") segment_count += 1 return discretized, segment_count def __to_segments(inst: qiskit.circuit.instruction.Instruction, segments_per_gate: int, keep_state: bool, sequential_subcircuit: bool): """Split the instruction into segments_per_gate segments""" if isinstance(inst, ParameterizedUnitaryGate): # print(f"Discretizing ParameterizedUnitaryGate {inst.name}") segments = __discretize_parameterized(inst, segments_per_gate, keep_state) # FIXME -- how to identify a gate that was made with QuantumCircuit.to_gate()? elif isinstance(inst.definition, qiskit.QuantumCircuit) and inst.name != "initialize" and inst.label != "cv_gate_from_matrix" and len(inst.decompositions) == 0: # Don't animate subcircuits initializing system state # print(f"Discretizing QuantumCircuit {inst.name}") segments = __discretize_subcircuit(inst.definition, segments_per_gate, keep_state, sequential_subcircuit) elif isinstance(inst, qiskit.circuit.instruction.Instruction) and inst.name != "initialize" and inst.label != "cv_gate_from_matrix" and len(inst.params) > 0: # Don't animate instructions initializing system state # print(f"Discretizing Instruction {inst.name}") segments = __discretize_instruction(inst, segments_per_gate, keep_state) else: # Else just "discretize" the instruction as a single segment # print(f"NOT discretizing {inst.name}") segments = [inst] return segments def __discretize_parameterized(inst: qiskit.circuit.instruction.Instruction, segments_per_gate: int, keep_state: bool, discretized_param_indices: list = []): """Split ParameterizedUnitaryGate into multiple segments""" segments = [] for index in range(1, segments_per_gate + 1): params = inst.calculate_segment_params( current_step=index, total_steps=segments_per_gate, keep_state=keep_state, ) duration, unit = inst.calculate_segment_duration( current_step=index, total_steps=segments_per_gate, keep_state=keep_state, ) # print(f"Discretized params {params} duration {duration} unit {unit}") segments.append( ParameterizedUnitaryGate( inst.op_func, params=params, cutoffs=inst.cutoffs, num_qubits=inst.num_qubits, label=inst.label, duration=duration, unit=unit, ) ) return segments def __discretize_subcircuit(subcircuit: qiskit.QuantumCircuit, segments_per_gate: int, keep_state: bool, sequential_subcircuit: bool): """Create a list of circuits where the entire subcircuit is converted into segments (vs a single instruction).""" segments = [] sub_segments = [] for inst, qargs, cargs in subcircuit.data: sub_segments.append((__to_segments(inst, segments_per_gate, keep_state, sequential_subcircuit), qargs, cargs)) if sequential_subcircuit: # Sequentially animate each gate within the subcircuit subcircuit_copy = subcircuit.copy() subcircuit_copy.data.clear() # Is this safe -- could we copy without data? for sub_segment in sub_segments: gates, gate_qargs, gate_cargs = sub_segment for gate in gates: subcircuit_copy.append(gate, gate_qargs, gate_cargs) segments.append(subcircuit) else: # Animate the subcircuit as one gate for segment in range(segments_per_gate): subcircuit_copy = subcircuit.copy() subcircuit_copy.data.clear() # Is this safe -- could we copy without data? for sub_segment, qargs, cargs in sub_segments: subcircuit_copy.append(sub_segment[segment], qargs, cargs) segments.append(subcircuit_copy) return segments def __discretize_instruction(inst: qiskit.circuit.instruction.Instruction, segments_per_gate: int, keep_state: bool): """Split Qiskit Instruction into multiple segments""" segments = [] for index in range(1, segments_per_gate + 1): params = inst.calculate_segment_params( current_step=index, total_steps=segments_per_gate, keep_state=keep_state, ) duration, unit = inst.calculate_segment_duration( current_step=index, total_steps=segments_per_gate, keep_state=keep_state, ) segments.append( qiskit.circuit.instruction.Instruction( name=inst.name, num_qubits=inst.num_qubits, num_clbits = inst.num_clbits, params=params, duration=duration, unit=unit, label=inst.label, ) ) return segments
https://github.com/C2QA/bosonic-qiskit
C2QA
import warnings import qiskit from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit import Gate from qiskit.circuit.library import UnitaryGate from qiskit.circuit.parameter import ParameterExpression class ParameterizedUnitaryGate(Gate): """UnitaryGate sublcass that stores the operator matrix for later reference by animation utility.""" def __init__( self, op_func, params, num_qubits, cutoffs, label=None, duration=100, unit="ns", discretized_param_indices: list = [] ): """Initialize ParameterizedUnitaryGate Args: op_func (function): function to build operator matrix params (List): List of parameters to pass to op_func to build operator matrix (supports instances of Qiskit Parameter to be bound later) num_qubits (int): Number of qubits in the operator -- this would likely equate to (num_qubits_per_qumode * num_qumodes + num_ancilla). label (string, optional): Gate name. Defaults to None. duration (int, optional): Duration of gate used for noise modeling. Defaults to 100. unit (string, optional): Unit of duration (only supports those allowed by Qiskit). discretized_param_indices (list): list of int indices into self.params for parameters to be discretized. An empty list will discretize all params. """ super().__init__(name=label, num_qubits=num_qubits, params=params, label=label) self.op_func = op_func self._parameterized = any( isinstance(param, ParameterExpression) and param.parameters for param in params ) self.duration = duration self.unit = unit self.discretized_param_indices = discretized_param_indices self.cutoffs = cutoffs def __array__(self, dtype=None): """Call the operator function to build the array using the bound parameter values.""" # return self.op_func(*map(complex, self.params)).toarray() values = [] # Add parameters for op_func call for param in self.params: if isinstance(param, ParameterExpression): # if param.is_real(): # values.append(float(param)) # else: # values.append(complex(param)) values.append( complex(param) ) # just cast everything to complex to avoid errors in Ubuntu/MacOS vs Windows else: values.append(param) # Add cutoff for each parameter values.extend(self.cutoffs) # Conver array to tupple values = tuple(values) return self.op_func(*values).toarray() def _define(self): try: mat = self.to_matrix() q = QuantumRegister(self.num_qubits) qc = QuantumCircuit(q, name=self.name) rules = [ (UnitaryGate(mat, self.label), [i for i in q], []), ] for instr, qargs, cargs in rules: qc._append(instr, qargs, cargs) self.definition = qc except: # warnings.warn("Unable to define gate, setting definition to None to prevent serialization errors for parameterized unitary gates.") self.definition = None def validate_parameter(self, parameter): """Gate parameters should be int, float, or ParameterExpression""" if isinstance(parameter, complex) or ( isinstance(parameter, ParameterExpression) and not parameter.is_real() ): return parameter elif isinstance(parameter, str): # accept strings as-is return parameter elif isinstance(parameter, list): return parameter else: return super().validate_parameter(parameter) def calculate_matrix( self, current_step: int = 1, total_steps: int = 1, keep_state: bool = False ): """Calculate the operator matrix by executing the selected function. Increment the parameters based upon the current and total steps. Args: current_step (int, optional): Current step within total_steps. Defaults to 1. total_steps (int, optional): Total steps to increment parameters. Defaults to 1. Returns: ndarray: operator matrix """ if self.is_parameterized(): raise NotImplementedError( "Unable to calculate incremental operator matrices for parameterized gate" ) values = self.calculate_segment_params(current_step, total_steps, keep_state) # if self.inverse: # result = scipy.sparse.linalg.inv(self.op_func(*values)) # else: # result = self.op_func(*values) result = self.op_func(*values) if hasattr(result, "toarray"): result = result.toarray() return result def __calculate_segment_params( self, current_step: int = 1, total_steps: int = 1, keep_state: bool = False ): """ Calculate the parameters at the current step. Return a tuples of the values. Args: current_step (int): 0-based current step index of the discretization total_steps (int): total number of discretization steps keep_state (bool): true if the state should be kept between discretization steps (i.e., if the discretization value should be 1/total_steps vs current_step/total_steps) Returns: discretized parameter values as tuple """ if keep_state: param_fraction = 1 / total_steps else: param_fraction = current_step / total_steps values = [] for index, param in enumerate(self.params): if not hasattr(self, "discretized_param_indices") or len(self.discretized_param_indices) == 0 or index in self.discretized_param_indices: values.append(param * param_fraction) else: values.append(param) return tuple(values) def __calculate_segment_duration( self, current_step: int = 1, total_steps: int = 1, keep_state: bool = False ): """Calculate the duration at the current step. Return a tuple of the (duration, unit).""" frame_duration = None if self.duration: if keep_state: fraction = 1 / total_steps else: fraction = current_step / total_steps frame_duration = self.duration * fraction return frame_duration, self.unit # Monkey patch Qiskit Instruction to support animating base Qiskit Instruction qiskit.circuit.instruction.Instruction.calculate_segment_params = __calculate_segment_params qiskit.circuit.instruction.Instruction.calculate_segment_duration = __calculate_segment_duration
https://github.com/C2QA/bosonic-qiskit
C2QA
from qiskit import QuantumRegister class QumodeRegister: """Wrapper to QisKit QuantumRegister to represent multiple qubits per qumode. Implements __getitem__ to make QumodeRegister appear to work just like QuantumRegister with instances of CVCircuit. """ def __init__( self, num_qumodes: int, num_qubits_per_qumode: int = 2, name: str = None ): """Initialize QumodeRegister Args: num_qumodes (int): total number of qumodes num_qubits_per_qumode (int, optional): Number of qubits representing each qumode. Defaults to 2. name (str, optional): Name of register. Defaults to None. """ self.size = num_qumodes * num_qubits_per_qumode self.num_qumodes = num_qumodes self.num_qubits_per_qumode = num_qubits_per_qumode self.cutoff = QumodeRegister.calculate_cutoff(num_qubits_per_qumode) # Aggregate the QuantumRegister representing these qumodes as # extending the class confuses QisKit when overriding __getitem__(). # It doesn't expect a list of Qubit back when indexing a single value # (i.e., qmr[0] is represented by multiple qubits). self.qreg = QuantumRegister(size=self.size, name=name) @staticmethod def calculate_cutoff(num_qubits_per_qumode: int): return 2**num_qubits_per_qumode def get_qumode_index(self, qubit): """Get the qumode index for the given qubit in this register""" qubit_index = self.qreg.index(qubit) return qubit_index // self.num_qubits_per_qumode def __iter__(self): """Iterate over the list of lists representing the qubits for each qumode in the register""" return QumodeIterator(self) def __getitem__(self, key): """Return a list of QisKit Qubit for each indexed qumode Args: key (slice or int): index into qumode register Raises: ValueError: if slice or int not provided Returns: list: ;ost pf qubits from QuantumRegister representing qumode """ start = None stop = self.size step = None if isinstance(key, slice): start_index = key.start if key.start else 0 stop_index = key.stop if key.stop else self.size start = self.num_qubits_per_qumode * start_index stop = ( self.num_qubits_per_qumode * stop_index ) + self.num_qubits_per_qumode step = (key.step * self.num_qubits_per_qumode) if key.step else None elif isinstance(key, int): start = self.num_qubits_per_qumode * key stop = start + self.num_qubits_per_qumode else: raise ValueError("Must provide slice or int.") return self.qreg[start:stop:step] def __len__(self): """The length of a QumodeRegister is the number of qumodes (not the num_qumodes * num_qubits_per_qumode)""" return self.num_qumodes def __contains__(self, qubit): """Return true if this QumodeRegister contains the given qubit. This allows callers to use `in` python syntax.""" return qubit in self.qreg class QumodeIterator: """Iterate over the list of lists representing the qubits for each qumode in the register""" def __init__(self, register: QumodeRegister): self._index = 0 self._register = register def __iter__(self): return self def __next__(self): if self._index < self._register.num_qumodes: next = self._register[self._index] self._index += 1 return next else: raise StopIteration
https://github.com/C2QA/bosonic-qiskit
C2QA
import json import logging import numpy as np import warnings from functools import wraps from typing import Any, Callable, Optional, Tuple, Union from qiskit import IBMQ, QuantumCircuit, assemble from qiskit.circuit import Barrier, Gate, Instruction, Measure from qiskit.circuit.library import UGate, U3Gate, CXGate from qiskit.providers.ibmq import AccountProvider, IBMQProviderError from qiskit.providers.ibmq.job import IBMQJob def get_provider() -> AccountProvider: with warnings.catch_warnings(): warnings.simplefilter('ignore') ibmq_logger = logging.getLogger('qiskit.providers.ibmq') current_level = ibmq_logger.level ibmq_logger.setLevel(logging.ERROR) # get provider try: provider = IBMQ.get_provider() except IBMQProviderError: provider = IBMQ.load_account() ibmq_logger.setLevel(current_level) return provider def get_job(job_id: str) -> Optional[IBMQJob]: try: job = get_provider().backends.retrieve_job(job_id) return job except Exception: pass return None def circuit_to_json(qc: QuantumCircuit) -> str: class _QobjEncoder(json.encoder.JSONEncoder): def default(self, obj: Any) -> Any: if isinstance(obj, np.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder) def circuit_to_dict(qc: QuantumCircuit) -> dict: qobj = assemble(qc) return qobj.to_dict() def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]: try: job_id = job.job_id() if isinstance(job, IBMQJob) else job download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url'] result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url'] return download_url, result_url except Exception: return None, None def cached(key_function: Callable) -> Callable: def _decorator(f: Any) -> Callable: f.__cache = {} @wraps(f) def _decorated(*args: Any, **kwargs: Any) -> int: key = key_function(*args, **kwargs) if key not in f.__cache: f.__cache[key] = f(*args, **kwargs) return f.__cache[key] return _decorated return _decorator def gate_key(gate: Gate) -> Tuple[str, int]: return gate.name, gate.num_qubits @cached(gate_key) def gate_cost(gate: Gate) -> int: if isinstance(gate, (UGate, U3Gate)): return 1 elif isinstance(gate, CXGate): return 10 elif isinstance(gate, (Measure, Barrier)): return 0 return sum(map(gate_cost, (g for g, _, _ in gate.definition.data))) def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int: print('Computing cost...') circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction): circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') return sum(map(gate_cost, (g for g, _, _ in circuit_data))) def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool: circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction) and circuit.definition is not None: circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') for g, _, _ in circuit_data: if isinstance(g, (Barrier, Measure)): continue elif isinstance(g, Gate): if g.num_qubits > 1: return True elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g): return True return False
https://github.com/C2QA/bosonic-qiskit
C2QA
from pathlib import Path import numpy import pytest import qiskit import c2qa def __build_subcircuit(): # Define Hamiltonian parameters omega_R = 2 omega_Q = 5 chi = 0.1 # Set number of qubits per qumode num_qubits_per_qumode = 3 # Choose alpha for coherent state alpha = 1 # Choose total animation time total_time = 1*2*numpy.pi/omega_R # Create new circuit qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(1) U_JC = c2qa.CVCircuit(qmr,qbr) # Append U_R U_JC.cv_r(-omega_R*total_time, qmr[0]) # Append U_Q U_JC.rz(omega_Q*total_time,qbr[0]) # Append U_\chi -- KS: this needs to be updated to reflect naming conventions in manuscript U_JC.cv_c_r(-chi*total_time/2, qmr[0], qbr[0]) # Compile this circuit into a single parameterized gate U_JC = U_JC.to_gate(label='U_JC') # Instantiate the circuit and initialize the qubit to the '0' state. circuit_0 = c2qa.CVCircuit(qmr,qbr) circuit_0.initialize([1,0], qbr) # Squeeze so we can visually see rotation circuit_0.cv_sq(0.5, qmr[0]) # Now initialize the qumode in a coherent state # cutoff = 2**num_qubits_per_qumode # coeffs = [numpy.exp(-numpy.abs(alpha)**2/2)*alpha**n/(numpy.sqrt(numpy.math.factorial(n))) for n in range(0,cutoff)] # circuit_0.cv_initialize(coeffs,qmr[0]) # Append time evolution unitary circuit_0.append(U_JC,qmr[0] + [qbr[0]]) # circuit_0.assign_parameters({dt : total_time}) # dt = total_time # # Append U_R # circuit_0.cv_r(-omega_R*dt,qmr[0]) # # Append U_Q # circuit_0.rz(omega_Q*dt,qbr[0]) # # Append U_\chi -- KS: this needs to be updated to reflect naming conventions in manuscript # circuit_0.cv_c_r(-chi*dt/2,qmr[0],qbr[0]) # Compile this circuit into a single parameterized gate # U_JC = U_JC.to_gate(label='U_JC') # # Now repeat the above steps for a qubit initialized to the '1' state: # circuit_1 = c2qa.CVCircuit(qmr,qbr) # circuit_1.initialize([0,1], qbr) # circuit_1.cv_d(alpha,qmr[0]) # circuit_1.append(U_JC,qmr[0] + [qbr[0]]) # circuit_1 = circuit_1.assign_parameters({dt : total_time}) return circuit_0 def test_animate_subcircuit_one_gate(capsys): """ Test animating a circuit with a composite gate built from another circuit. Composite gate borrowed from Jaynes-Cummings model tutorial """ with capsys.disabled(): circuit = __build_subcircuit() # Animate wigner function of each circuit c2qa.animate.animate_wigner(circuit,file="tests/composite_gate.gif", animation_segments = 20) def test_animate_subcircuit_sequential(capsys): """ Test animating a circuit with a composite gate built from another circuit. Composite gate borrowed from Jaynes-Cummings model tutorial """ with capsys.disabled(): circuit = __build_subcircuit() # Animate wigner function of each circuit c2qa.animate.animate_wigner(circuit,file="tests/sequential_subcircuit.gif", animation_segments = 20, sequential_subcircuit = True) def test_animate_parameterized(capsys): with capsys.disabled(): a = qiskit.circuit.Parameter("𝛼") qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=4) qbr = qiskit.QuantumRegister(1) cbr = qiskit.ClassicalRegister(1) minimal_circuit = c2qa.CVCircuit(qmr, qbr, cbr) minimal_circuit.h(qbr[0]) minimal_circuit.cv_c_d(1j * a, qmr[0], qbr[0]) bound_circuit = minimal_circuit.assign_parameters({a: 2}) wigner_filename = "tests/animate_parameterized.apng" c2qa.animate.animate_wigner( bound_circuit, qubit=qbr[0], cbit=cbr[0], file=wigner_filename, axes_min=-8, axes_max=8, animation_segments=5, processes=1, shots=25, ) assert Path(wigner_filename).is_file() def test_animate_gif(capsys): with capsys.disabled(): __animate_with_cbit("tests/displacement.gif") def test_animate_apng(capsys): with capsys.disabled(): __animate_with_cbit("tests/displacement.apng") def __animate_with_cbit(filename: str): qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=4) qr = qiskit.QuantumRegister(size=1) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) dist = 3 circuit.initialize([1, 0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) c2qa.animate.animate_wigner( circuit, qubit=qr[0], cbit=cr[0], file=filename, axes_min=-8, axes_max=8, animation_segments=5, processes=1, shots=25, ) assert Path(filename).is_file() def __animate_without_cbit(filename: str, trace: bool = False): qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=4) qr = qiskit.QuantumRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr) dist = 3 circuit.initialize([1, 0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) c2qa.animate.animate_wigner( circuit, qubit=qr[0], file=filename, axes_min=-8, axes_max=8, animation_segments=5, processes=1, shots=25, trace=trace, ) assert Path(filename).is_file() def test_animate_with_trace(capsys): with capsys.disabled(): __animate_without_cbit("tests/animate_with_trace.gif", True) def test_animate_without_trace(capsys): with capsys.disabled(): __animate_without_cbit("tests/animate_without_trace.gif", False) @pytest.mark.skip(reason="GitHub actions build environments do not have ffmpeg") def test_calibration_animate_mp4(capsys): with capsys.disabled(): qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=6) qr = qiskit.QuantumRegister(size=1) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) dist = 3 circuit.initialize([1, 0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) circuit.cv_d(1j * dist, qmr[0]) circuit.cv_c_d(-dist, qmr[0], qr[0]) circuit.cv_d(-1j * dist, qmr[0]) c2qa.animate.animate_wigner( circuit, qubit=qr[0], cbit=cr[0], file="tests/displacement.mp4", axes_min=-8, axes_max=8, animation_segments=48, shots=128, )
https://github.com/C2QA/bosonic-qiskit
C2QA
from qiskit import QuantumCircuit from . import circuit_constructor, circuit_eq def test_circuit_constructor(): gates_list = ["h", "hs", "hs", "i", "i", "h"] result = circuit_constructor(gates_list) result_dag = circuit_constructor(gates_list, True) expected = QuantumCircuit(6) expected.h(0) _ = expected.s(1), expected.h(1) _ = expected.s(2), expected.h(2) expected.h(5) expected_dag = QuantumCircuit(6) expected_dag.h(0) _ = expected_dag.h(1), expected_dag.sdg(1) _ = expected_dag.h(2), expected_dag.sdg(2) expected_dag.h(5) assert circuit_eq(result, expected) assert circuit_eq(result_dag, expected_dag)
https://github.com/C2QA/bosonic-qiskit
C2QA
import c2qa import pytest import qiskit import math import numpy import random def test_cv_c_d(capsys): """The cv_c_d gate should discretize all params (i.e., default behavior)""" with capsys.disabled(): num_qumodes = 2 num_qubits_per_qumode = 2 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) qr = qiskit.QuantumRegister(2) circuit = c2qa.CVCircuit(qmr, qr) theta = random.random() beta = -theta circuit.cv_c_d(theta=theta, beta=beta, qumode=qmr[0], qubit=qr[0]) gate = circuit.data[0].operation total_steps = 2 discretized_params = gate.calculate_segment_params(current_step=1, total_steps=total_steps, keep_state=True) print(f"Original theta={theta}") print(f"Discretized params {discretized_params}") assert discretized_params[0] == (theta / total_steps) assert discretized_params[1] == (beta / total_steps) def test_cv_c_schwinger(capsys): """The cv_c_schwinger gate should discretize the first param, but the others not""" with capsys.disabled(): num_qumodes = 2 num_qubits_per_qumode = 2 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) qr = qiskit.QuantumRegister(2) circuit = c2qa.CVCircuit(qmr, qr) beta = random.random() theta_1 = random.random() phi_1 = random.random() theta_2 = random.random() phi_2 = random.random() circuit.cv_c_schwinger([beta, theta_1, phi_1, theta_2, phi_2], qmr[0], qmr[1], qr[0]) gate = circuit.data[0].operation total_steps = 2 discretized_params = gate.calculate_segment_params(current_step=1, total_steps=total_steps, keep_state=True) print(f"Original params {(beta, theta_1, phi_1, theta_2, phi_2)}") print(f"Discretized params {discretized_params}") assert discretized_params[0] == (beta / total_steps) assert discretized_params[1] == theta_1 assert discretized_params[2] == phi_1 assert discretized_params[3] == theta_2 assert discretized_params[4] == phi_2 @pytest.mark.skip(reason="Enable and test manually with debug breakpoint in__calculate_segment_params to ensure only first param is discretized") def test_cv_c_schwinger_animate(capsys): """The cv_c_schwinger gate should discretize the first param, but the others not""" with capsys.disabled(): num_qumodes = 2 num_qubits_per_qumode = 2 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) qr = qiskit.QuantumRegister(2) circuit = c2qa.CVCircuit(qmr, qr) beta = random.random() theta_1 = random.random() phi_1 = random.random() theta_2 = random.random() phi_2 = random.random() circuit.cv_c_schwinger([beta, theta_1, phi_1, theta_2, phi_2], qmr[0], qmr[1], qr[0]) c2qa.animate.animate_wigner( circuit, file="tests/test_cv_c_schwinger_animate.gif", axes_min=-8, axes_max=8, animation_segments=2, shots=1, ) def test_discretize_with_pershot_statevector(capsys): with capsys.disabled(): qmr = c2qa.QumodeRegister(1, 3) creg = qiskit.ClassicalRegister(3) circ = c2qa.CVCircuit(qmr, creg) circ.cv_initialize(7, qmr[0]) circ.cv_delay(duration=100, qumode=qmr[0], unit="ns") circ.cv_measure(qmr[0], creg) noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=0.02, circuit=circ, time_unit="ns") state, result, fock_counts = c2qa.util.simulate(circ, noise_passes=noise_pass, discretize=True, shots=2, per_shot_state_vector=True) assert result.success def test_accumulated_counts_cv_c_r(capsys): def simulate_test(discretize: bool): qmr = c2qa.QumodeRegister(1, 3) anc = qiskit.circuit.AncillaRegister(1) cr = qiskit.circuit.ClassicalRegister(1) circ = c2qa.CVCircuit(qmr, anc, cr) circ.initialize([1, 0], anc[0]) # Ancilla in |g> circ.cv_initialize(3, qmr[0]) # Qumode in |3> # Photon number parity circuit circ.h(anc[0]) circ.cv_c_r(numpy.pi / 2, qmr[0], anc[0], duration=1, unit="µs") circ.h(anc[0]) circ.measure(anc[0], cr[0]) # Simulate noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=0.1, circuit=circ, time_unit="µs") state, result, fock_counts = c2qa.util.simulate(circ, noise_passes=noise_pass, discretize=discretize, shots=3000) print("##############") print(f"Result counts: {result.get_counts()}") print(f"Fock counts: {fock_counts}") assert result.success with capsys.disabled(): print() print("NOT DISCRETIZED") simulate_test(discretize=False) print() print("DISCRETIZED") simulate_test(discretize=True) def test_accumulated_counts_cv_d(capsys): def simulate_test(discretize: bool): num_qumodes = 1 num_qubits_per_qumode = 4 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) circuit = c2qa.CVCircuit(qmr) circuit.cv_initialize(3, qmr[0]) circuit.cv_d(1.5, qmr[0], duration=100, unit="ns") photon_loss_rate = 0.02 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit) state, result, fock_counts = c2qa.util.simulate(circuit, noise_passes=noise_pass, discretize=discretize, shots=200) print("##############") print(f"Result counts: {result.get_counts()}") print(f"Fock counts: {fock_counts}") assert result.success with capsys.disabled(): print() print("NOT DISCRETIZED") simulate_test(discretize=False) print() print("DISCRETIZED") simulate_test(discretize=True) def test_manual_vs_auto_discretize(capsys): def simulate_test(manually_discretize: bool): qmr = c2qa.QumodeRegister(1, 3) anc = qiskit.circuit.AncillaRegister(1) cr = qiskit.circuit.ClassicalRegister(1) circ = c2qa.CVCircuit(qmr, anc, cr) circ.initialize([1, 0], anc[0]) # Ancilla in |g> circ.cv_initialize(3, qmr[0]) # Qumode in |3> # Photon number parity circuit circ.h(anc[0]) if manually_discretize: for _ in range(10): # Manually discretize cv_c_r gate circ.cv_c_r(numpy.pi/20, qmr[0], anc[0], duration=0.1, unit="µs") else: circ.cv_c_r(numpy.pi/2, qmr[0], anc[0], duration=1, unit="µs") circ.h(anc[0]) circ.measure(anc[0], cr[0]) # Simulate noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=0.1, circuit=circ, time_unit="µs") return c2qa.util.simulate(circ, noise_passes=noise_pass, shots=3000, discretize=(not manually_discretize)) with capsys.disabled(): min_percent_diff = 99999 max_percent_diff = 0 for i in range(20): print() print(f"Test {i}") print("Manual Discretization") _, result_man, _ = simulate_test(manually_discretize=True) counts_man = result_man.get_counts() print(counts_man) print("Auto Discretization") _, result_auto, _ = simulate_test(manually_discretize=False) counts_auto = result_auto.get_counts() print(counts_auto) assert result_man.success assert result_auto.success for key in counts_man: max_value = max(counts_man[key], counts_auto[key]) min_value = min(counts_man[key], counts_auto[key]) diff = max_value - min_value percent_diff = diff / max_value * 100 min_percent_diff = min(percent_diff, min_percent_diff) max_percent_diff = max(percent_diff, max_percent_diff) print(f"Key '{key}' percent difference {percent_diff}") assert math.isclose(counts_man[key], counts_auto[key], rel_tol=0.25) print(f"Min percent diff {min_percent_diff}") print(f"Max percent diff {max_percent_diff}")
https://github.com/C2QA/bosonic-qiskit
C2QA
import random import c2qa import numpy import qiskit def count_nonzero(statevector: qiskit.quantum_info.Statevector): """Re-implement numpy.count_nonzero using numpy.isclose().""" nonzero = len(statevector.data) for state in statevector.data: if numpy.isclose(state, 0): nonzero -= 1 return nonzero def create_conditional(num_qumodes: int = 2, num_qubits_per_qumode: int = 2): qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) qr = qiskit.QuantumRegister(2) circuit = c2qa.CVCircuit(qmr, qr) for qumode in range(num_qumodes): circuit.cv_initialize(0, qmr[qumode]) circuit.initialize([0, 1], qr[1]) # qr[0] will init to zero return circuit, qmr, qr def create_unconditional(num_qumodes: int = 2, num_qubits_per_qumode: int = 3): qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) circuit = c2qa.CVCircuit(qmr) for qumode in range(num_qumodes): circuit.cv_initialize(0, qmr[qumode]) return circuit, qmr def assert_changed(state, result): assert result.success # print() # print(circuit.draw("text")) # print(state) # TODO - better understand what the state vector results should be assert count_nonzero(state) > 1 def assert_unchanged(state, result): assert result.success # print() # print(circuit.draw("text")) # print(state) # TODO - better understand what the state vector results should be assert count_nonzero(state) == 1 def test_no_gates(): circuit, qmr = create_unconditional() state, result, fock_counts = c2qa.util.simulate(circuit) assert_unchanged(state, result) def test_beamsplitter_once(): circuit, qmr = create_unconditional() phi = random.random() circuit.cv_bs(phi, qmr[0], qmr[1]) state, result, fock_counts = c2qa.util.simulate(circuit) # TODO - Beam splitter gate does not change state vector # Both Strawberry Fields & FockWits are the same, too. # assert_changed(state, result) assert_unchanged(state, result) def test_conditional_beamsplitter(): circuit, qmr, qr = create_conditional() theta = random.random() circuit.cv_c_bs(theta, qmr[0], qmr[1], qr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) # TODO - Beam splitter gate does not change state vector # Both Strawberry Fields & FockWits are the same, too. # assert_changed(state, result) assert_unchanged(state, result) def test_conditional_schwinger(): circuit, qmr, qr = create_conditional() beta = random.random() theta_1 = random.random() phi_1 = random.random() theta_2 = random.random() phi_2 = random.random() circuit.cv_c_schwinger([beta, theta_1, phi_1, theta_2, phi_2], qmr[0], qmr[1], qr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_unchanged(state, result) def test_beamsplitter_twice(): circuit, qmr = create_unconditional() phi = random.random() circuit.cv_bs(phi, qmr[0], qmr[1]) circuit.cv_bs(-phi, qmr[0], qmr[1]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_unchanged(state, result) def test_conditonal_displacement(): circuit, qmr, qr = create_conditional() alpha = random.random() circuit.cv_c_d(alpha, qmr[0], qr[0]) circuit.cv_c_d(-alpha, qmr[0], qr[0]) circuit.cv_c_d(-alpha, qmr[0], qr[1]) circuit.cv_c_d(alpha, qmr[0], qr[1]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_unchanged(state, result) def test_conditonal_squeezing(): circuit, qmr, qr = create_conditional() alpha = random.random() circuit.cv_c_sq(alpha, qmr[0], qr[0]) circuit.cv_c_sq(-alpha, qmr[0], qr[0]) circuit.cv_c_sq(-alpha, qmr[0], qr[1]) circuit.cv_c_sq(alpha, qmr[0], qr[1]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_unchanged(state, result) def test_displacement_once(capsys): with capsys.disabled(): circuit, qmr = create_unconditional() # alpha = random.random() alpha = 1 circuit.cv_d(alpha, qmr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_changed(state, result) def test_cv_delay(): circuit, qmr = create_unconditional() circuit.cv_delay(100,qmr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) def test_displacement_twice(): circuit, qmr = create_unconditional() alpha = random.random() circuit.cv_d(alpha, qmr[0]) circuit.cv_d(-alpha, qmr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_unchanged(state, result) def test_displacement_calibration(capsys): with capsys.disabled(): qmr = c2qa.QumodeRegister(1, 2) qr = qiskit.QuantumRegister(1) cr = qiskit.ClassicalRegister(1) circuit = c2qa.CVCircuit(qmr, qr, cr) # qr[0] and cr[0] will init to zero circuit.cv_initialize(0, qmr[0]) alpha = numpy.sqrt(numpy.pi) circuit.h(qr[0]) circuit.cv_c_d(alpha, qmr[0], qr[0]) circuit.cv_d(1j * alpha, qmr[0]) circuit.cv_c_d(-alpha, qmr[0], qr[0]) circuit.cv_d(-1j * alpha, qmr[0]) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) assert result.success state = result.get_statevector(circuit) counts = result.get_counts(circuit) assert state.dim > 0 assert counts # print() # print(circuit.draw("text")) # print(state) # print(counts.int_outcomes()) def test_rotation_once(): circuit, qmr = create_unconditional() theta = random.random() circuit.cv_r(theta, qmr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) # TODO - Rotation gate does not change state vector. # Both Strawberry Fields & FockWits are the same, too. # assert_changed(state, result) assert_unchanged(state, result) def test_rotation_twice(): circuit, qmr = create_unconditional() theta = random.random() circuit.cv_r(theta, qmr[0]) circuit.cv_r(-theta, qmr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_unchanged(state, result) def test_squeezing_once(): circuit, qmr = create_unconditional() z = random.random() circuit.cv_sq(z, qmr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_changed(state, result) def test_squeezing_twice(): circuit, qmr = create_unconditional() z = random.random() circuit.cv_sq(z, qmr[0]) circuit.cv_sq(-z, qmr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_unchanged(state, result) def test_two_mode_squeezing_once(): circuit, qmr = create_unconditional() z = random.random() circuit.cv_sq2(z, qmr[0], qmr[1]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_changed(state, result) def test_two_mode_squeezing_twice(): circuit, qmr = create_unconditional() z = random.random() circuit.cv_sq2(z, qmr[0], qmr[1]) circuit.cv_sq2(-z, qmr[0], qmr[1]) state, result, fock_counts = c2qa.util.simulate(circuit) assert_unchanged(state, result) def test_gates(): """Verify that we can use the gates, not that they are actually working.""" # ===== Constants ===== alpha = 1 phi = numpy.pi / 2 z = 1 circuit, qmr, qr = create_conditional() # Basic Gaussian Operations on a Resonator circuit.cv_bs(phi, qmr[0], qmr[1]) circuit.cv_d(alpha, qmr[0]) circuit.cv_r(phi, qmr[0]) circuit.cv_sq(z, qmr[0]) circuit.cv_sq2(z, qmr[0], qmr[1]) # Hybrid qubit-cavity gates circuit.cv_c_d(alpha, qmr[0], qr[0]) circuit.cv_c_d(alpha, qmr[1], qr[0]) circuit.cv_c_sq(z, qmr[0], qr[0]) circuit.cv_c_sq(z, qmr[1], qr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) assert result.success def test_snap(): circuit, qmr = create_unconditional() phi = random.random() n = 1 circuit.cv_snap(phi, n, qmr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) def test_eswap(): circuit, qmr = create_unconditional() phi = random.random() circuit.cv_eswap(phi, qmr[0], qmr[1]) state, result, fock_counts = c2qa.util.simulate(circuit) def test_multiboson_sampling(capsys): with capsys.disabled(): num_qubits=1 num_qumodes=2 num_qubits_per_qumode=2 qmrA = c2qa.QumodeRegister(num_qumodes = num_qumodes, num_qubits_per_qumode = num_qubits_per_qumode,name="qmrA_initial") qmrB = c2qa.QumodeRegister(num_qumodes = num_qumodes, num_qubits_per_qumode = num_qubits_per_qumode,name="qmrB_initial") qbr = qiskit.QuantumRegister(size=num_qubits,name='qbr_initial') circuit = c2qa.CVCircuit(qmrA, qmrB, qbr) circuit.cv_c_multiboson_sampling([0,1,2,3], qmrA[0], qbr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) assert result.success
https://github.com/C2QA/bosonic-qiskit
C2QA
import numpy import qiskit import qiskit_aer import scipy.linalg import c2qa # Define parameters num_qubits_per_qumode = 2 cutoff = 2**num_qubits_per_qumode alpha = numpy.sqrt(numpy.pi) def displacement_operator(arg): """Create displacement operator matrix""" a = numpy.diag(numpy.sqrt(range(1, cutoff)), k=1) a_dag = a.conj().T return scipy.linalg.expm((arg * a_dag) - (numpy.conjugate(arg) * a)) def displacemnt_gate(circuit, arg, qumode): circuit.unitary(displacement_operator(arg), qumode) def conditional_displacement_gate(circuit, arg_0, arg_1, qbit, qumode): """Append a conditional displacement to the circuit Displace by arg_0 if qbit is 0, by arg_1 if qbit is 1.""" op_0 = displacement_operator(arg_0) op_1 = displacement_operator(arg_1) circuit.append( qiskit.circuit.library.UnitaryGate(op_0).control(num_ctrl_qubits=1, ctrl_state=0), [qbit] + qumode, ) circuit.append( qiskit.circuit.library.UnitaryGate(op_1).control(num_ctrl_qubits=1, ctrl_state=1), [qbit] + qumode, ) def qumode_initialize(circuit, fock_state, qumode): """Initialize the qumode to a Fock state.""" value = numpy.zeros((cutoff,)) value[fock_state] = 1 circuit.initialize(value, qumode) def run_displacement_calibration(enable_measure): """ Run the simulation that has different state vector results on Windows vs Linux. - Create the qumode register as a QuantumRegiser where n qubits represent a qumode. - Create a QuantumRegister(1) to represent the control qubit. - Initialize the qubits. - Simulate the circuit. """ # Instantiate QisKit registers & circuit qmr = qiskit.QuantumRegister(num_qubits_per_qumode) # qumode register qr = qiskit.QuantumRegister(1) cr = qiskit.ClassicalRegister(1) circuit = qiskit.QuantumCircuit(qmr, qr, cr) # Initialize the qumode Fock state # qr[0] and cr[0] will init to zero qumode_initialize(circuit, 0, qmr[0:]) circuit.h(qr[0]) conditional_displacement_gate(circuit, alpha, -alpha, qr[0], qmr[0:]) displacemnt_gate(circuit, 1j * alpha, qmr[0:]) conditional_displacement_gate(circuit, -alpha, alpha, qr[0], qmr[0:]) displacemnt_gate(circuit, -1j * alpha, qmr[0:]) circuit.h(qr[0]) circuit.save_statevector() if enable_measure: circuit.measure(qr[0], cr[0]) backend = qiskit_aer.AerSimulator() circuit = qiskit.transpile(circuit, backend) job = backend.run(circuit) result = job.result() state = result.get_statevector(circuit) counts = result.get_counts(circuit) assert state.dim > 0 assert counts # print(state) # print(counts.int_outcomes()) def test_displacement_calibration(capsys): with capsys.disabled(): run_displacement_calibration(False) run_displacement_calibration(True)
https://github.com/C2QA/bosonic-qiskit
C2QA
import math from pathlib import Path import pytest import random import c2qa import numpy as np import qiskit import qiskit_aer.noise as noise from qiskit_aer.noise.noiseerror import NoiseError from qiskit_aer.noise.passes.relaxation_noise_pass import RelaxationNoisePass from qiskit.visualization import plot_histogram def test_noise_model(capsys): with capsys.disabled(): num_qumodes = 1 num_qubits_per_qumode = 2 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) qr = qiskit.QuantumRegister(2) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) for qumode in range(num_qumodes): circuit.cv_initialize(0, qmr[qumode]) circuit.initialize([0, 1], qr[1]) # qr[0] will init to zero alpha = random.random() circuit.cv_c_d(alpha, qmr[0], qr[0]) circuit.cv_c_d(-alpha, qmr[0], qr[0]) circuit.cv_c_d(-alpha, qmr[0], qr[1]) circuit.cv_c_d(alpha, qmr[0], qr[1]) photon_loss_rate = 1000000 # per second time = 5.0 # seconds kraus_operators = c2qa.kraus.calculate_kraus( photon_loss_rates=[photon_loss_rate, photon_loss_rate], time=time, circuit=circuit, op_qubits=[0, 1, 2], qumode_qubit_indices=[0, 1] ) print("kraus") print(kraus_operators) state, result, fock_counts = c2qa.util.simulate(circuit) def test_kraus_operators(capsys): with capsys.disabled(): num_qumodes = 1 num_qubits_per_qumode = 2 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) qr = qiskit.QuantumRegister(2) circuit = c2qa.CVCircuit(qmr, qr) photon_loss_rate = 1000000 # per second time = 1.0 # seconds kraus_operators = c2qa.kraus.calculate_kraus( photon_loss_rates=[photon_loss_rate, photon_loss_rate], time=time, circuit=circuit, op_qubits=[0, 1, 2], qumode_qubit_indices=[0, 1] ) kraus = qiskit.quantum_info.operators.channel.Kraus(kraus_operators) assert kraus.is_cp(), "Is not completely positive" print() print("Kraus Operators") accum = 0j for index, op in enumerate(kraus_operators): print(f"op {index}") print(op) op_dag = np.transpose(np.conj(op)) print(f"op_dag {index}") print(op_dag) op_dot = np.dot(op_dag, op) print(f"op_dot {index}") print(op_dot) accum += op_dot print() print("Sum") print(accum) is_identity = (accum.shape[0] == accum.shape[1]) and np.allclose( accum, np.eye(accum.shape[0]) ) print(f"Sum is identity {is_identity}") assert is_identity, "Sum is not identity" assert kraus.is_tp(), "Is not trace preserving" assert kraus.is_cptp(), "Is not CPTP" def test_beamsplitter_kraus_operators(capsys): with capsys.disabled(): num_qumodes = 2 qubits_per_mode = 2 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=qubits_per_mode) circuit = c2qa.CVCircuit(qmr) circuit.cv_initialize(2, qmr[0]) circuit.cv_bs(1, qmr[1], qmr[0], duration=100, unit="ns") photon_loss_rate = 1000000 # per second time = 1.0 # seconds kraus_operators = c2qa.kraus.calculate_kraus( photon_loss_rates=[photon_loss_rate, photon_loss_rate], time=time, circuit=circuit, op_qubits=[2, 3, 0, 1], qumode_qubit_indices=[0, 1, 2, 3] ) kraus = qiskit.quantum_info.operators.channel.Kraus(kraus_operators) assert kraus.is_cp(), "Is not completely positive" print() print("Kraus Operators") accum = 0j for index, op in enumerate(kraus_operators): print(f"op {index}") print(op) op_dag = np.transpose(np.conj(op)) print(f"op_dag {index}") print(op_dag) op_dot = np.dot(op_dag, op) print(f"op_dot {index}") print(op_dot) accum += op_dot print() print("Sum") print(accum) is_identity = (accum.shape[0] == accum.shape[1]) and np.allclose( accum, np.eye(accum.shape[0]) ) print(f"Sum is identity {is_identity}") assert is_identity, "Sum is not identity" assert kraus.is_tp(), "Is not trace preserving" assert kraus.is_cptp(), "Is not CPTP" def test_invalid_photon_loss_rate_length(capsys): with pytest.raises(Exception), capsys.disabled(): num_qumodes = 2 qubits_per_mode = 2 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=qubits_per_mode) init_circuit = c2qa.CVCircuit(qmr) init_circuit.cv_initialize(2, qmr[0]) init_circuit.cv_bs(1, qmr[1], qmr[0], duration=100, unit="ns") photon_loss_rates = [1,2,3] # Should only have two loss rates time_unit = "ns" # Should raise Exception for not having proper number of loss rates c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rates, circuit=init_circuit, time_unit=time_unit) def test_valid_photon_loss_rate_length(capsys): with capsys.disabled(): num_qumodes = 2 qubits_per_mode = 2 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=qubits_per_mode) init_circuit = c2qa.CVCircuit(qmr) init_circuit.cv_initialize(2, qmr[0]) init_circuit.cv_bs(1, qmr[1], qmr[0], duration=100, unit="ns") photon_loss_rates = [1,2] # Should only have two loss rates time_unit = "ns" # Should not raise exception as has proper number of loss rates c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rates, circuit=init_circuit, time_unit=time_unit) def test_noise_with_beamsplitter(capsys): with capsys.disabled(): num_qumodes = 2 qubits_per_mode = 2 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=qubits_per_mode) init_circuit = c2qa.CVCircuit(qmr) init_circuit.cv_initialize(2, qmr[0]) init_circuit.cv_bs(1, qmr[1], qmr[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=init_circuit, time_unit=time_unit) state, result, fock_counts = c2qa.util.simulate(init_circuit, noise_passes=noise_pass) def test_noise_with_beamsplitter_diff_cutoff(capsys): with capsys.disabled(): qmr1 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qmr2 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=3) init_circuit = c2qa.CVCircuit(qmr1, qmr2) init_circuit.cv_initialize(2, qmr1[0]) init_circuit.cv_initialize(2, qmr2[0]) init_circuit.cv_bs(1, qmr1[0], qmr2[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=init_circuit, time_unit=time_unit) state, result, fock_counts = c2qa.util.simulate(init_circuit, noise_passes=noise_pass) @pytest.mark.skip(reason="This test takes nearly 30 minutes to pass on Github...") def test_noise_with_cbs_diff_cutoff(capsys): with capsys.disabled(): qmr1 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qmr2 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=3) qbr = qiskit.QuantumRegister(1) init_circuit = c2qa.CVCircuit(qmr1, qmr2, qbr) init_circuit.cv_initialize(2, qmr1[0]) init_circuit.cv_initialize(2, qmr2[0]) init_circuit.cv_c_bs(1, qmr1[0], qmr2[0], qbr[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=init_circuit, time_unit=time_unit) state, result, fock_counts = c2qa.util.simulate(init_circuit, noise_passes=noise_pass) def test_noise_with_sq2_diff_cutoff(capsys): with capsys.disabled(): qmr1 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qmr2 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=3) init_circuit = c2qa.CVCircuit(qmr1, qmr2) init_circuit.cv_initialize(2, qmr1[0]) init_circuit.cv_initialize(2, qmr2[0]) init_circuit.cv_sq2(1, qmr1[0], qmr2[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=init_circuit, time_unit=time_unit) state, result, fock_counts = c2qa.util.simulate(init_circuit, noise_passes=noise_pass) def test_noise_with_cnd_beamsplitter(capsys): with capsys.disabled(): num_qumodes = 2 qubits_per_mode = 2 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=qubits_per_mode) qbr = qiskit.QuantumRegister(size=num_qubits) init_circuit = c2qa.CVCircuit(qmr, qbr) init_circuit.cv_initialize(2, qmr[0]) init_circuit.cv_c_bs(1, qmr[1], qmr[0], qbr[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=init_circuit, time_unit=time_unit) state, result, fock_counts = c2qa.util.simulate(init_circuit, noise_passes=noise_pass) def test_photon_loss_pass_with_conditional(capsys): with capsys.disabled(): num_qumodes = 1 qubits_per_mode = 2 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=qubits_per_mode) qbr = qiskit.QuantumRegister(size=num_qubits) init_circuit = c2qa.CVCircuit(qmr, qbr) init_circuit.cv_initialize(2, qmr[0]) init_circuit.cv_c_d(1, qmr[0], qbr[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=init_circuit, time_unit=time_unit) state, result, fock_counts = c2qa.util.simulate(init_circuit, noise_passes=noise_pass) def test_photon_loss_pass_delay_without_unit(capsys): with capsys.disabled(): num_qumodes = 1 qubits_per_mode = 2 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=qubits_per_mode) qbr = qiskit.QuantumRegister(size=num_qubits) fail_circuit = c2qa.CVCircuit(qmr, qbr) fail_circuit.cv_initialize(2, qmr[0]) fail_circuit.delay(duration=100) #, unit="ns") fail_circuit.cv_c_d(1, qmr[0], qbr[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=fail_circuit, time_unit=time_unit) state, result, fock_counts = c2qa.util.simulate(fail_circuit, noise_passes=noise_pass) assert result.success def test_photon_loss_pass_delay_with_unit(capsys): with capsys.disabled(): num_qumodes = 1 qubits_per_mode = 2 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=qubits_per_mode) qbr = qiskit.QuantumRegister(size=num_qubits) pass_circuit = c2qa.CVCircuit(qmr, qbr) pass_circuit.cv_initialize(2, qmr[0]) pass_circuit.delay(duration=100, unit="ns") pass_circuit.cv_c_d(1, qmr[0], qbr[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=pass_circuit, time_unit=time_unit) state, result, fock_counts = c2qa.util.simulate(pass_circuit, noise_passes=noise_pass) assert result.success def test_animate_photon_loss_pass(capsys): with capsys.disabled(): num_qumodes = 1 num_qubits_per_qumode = 4 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) circuit = c2qa.CVCircuit(qmr) circuit.cv_initialize(3, qmr[0]) circuit.cv_d(0, qmr[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit) wigner_filename = "tests/test_animate_photon_loss_pass.gif" c2qa.animate.animate_wigner( circuit, animation_segments=10, file=wigner_filename, noise_passes=noise_pass, ) assert Path(wigner_filename).is_file() def test_animate_photon_loss_pass_with_epsilon(capsys): with capsys.disabled(): num_qumodes = 1 num_qubits_per_qumode = 4 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) circuit = c2qa.CVCircuit(qmr) circuit.cv_initialize(3, qmr[0]) circuit.cv_d(0, qmr[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit) wigner_filename = "tests/test_animate_photon_loss_pas_with_epsilon.gif" c2qa.animate.animate_wigner( circuit, discretize_epsilon=0.1, file=wigner_filename, noise_passes=noise_pass, ) assert Path(wigner_filename).is_file() @pytest.mark.skip(reason="GitHub actions build environments do not have ffmpeg") def test_photon_loss_pass_no_displacement(capsys): with capsys.disabled(): num_qumodes = 1 num_qubits_per_qumode = 4 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) circuit = c2qa.CVCircuit(qmr) circuit.cv_initialize(3, qmr[0]) circuit.cv_d(0, qmr[0], duration=100, unit="ns") photon_loss_rate = 0.01 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit) # state, result, fock_counts = c2qa.util.simulate(circuit, noise_passes=noise_pass) wigner_filename = "tests/test_photon_loss_pass_no_displacement.mp4" c2qa.animate.animate_wigner( circuit, animation_segments=200, file=wigner_filename, noise_passes=noise_pass, ) @pytest.mark.skip(reason="GitHub actions build environments do not have ffmpeg") def test_photon_loss_pass_slow_displacement(capsys): with capsys.disabled(): num_qumodes = 1 num_qubits_per_qumode = 4 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) circuit = c2qa.CVCircuit(qmr) circuit.cv_initialize(3, qmr[0]) circuit.cv_d(1.5, qmr[0], duration=100, unit="ns") photon_loss_rate = 0.02 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit) # state, result, fock_counts = c2qa.util.simulate(circuit, noise_passes=noise_pass) wigner_filename = "tests/test_photon_loss_pass_slow_displacement.mp4" c2qa.animate.animate_wigner( circuit, animation_segments=200, file=wigner_filename, noise_passes=noise_pass, # draw_grid=True ) @pytest.mark.skip(reason="GitHub actions build environments do not have ffmpeg") def test_photon_loss_pass_slow_conditional_displacement(capsys): with capsys.disabled(): num_qumodes = 1 num_qubits_per_qumode = 4 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(size=num_qubits) circuit = c2qa.CVCircuit(qmr, qbr) circuit.cv_initialize(3, qmr[0]) circuit.cv_c_d(1, qmr[0], qbr[0], duration=100, unit="ns") photon_loss_rate = 0.02 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit) # state, result, fock_counts = c2qa.util.simulate(circuit, noise_passes=noise_pass) wigner_filename = "tests/test_photon_loss_pass_slow_conditional_displacement.mp4" c2qa.animate.animate_wigner( circuit, animation_segments=200, file=wigner_filename, noise_passes=noise_pass, ) def test_photon_loss_instruction(capsys): with capsys.disabled(): num_qumodes = 2 num_qubits_per_qumode = 2 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(size=num_qubits) circuit = c2qa.CVCircuit(qmr, qbr) circuit.cv_initialize(1, qmr[0]) circuit.cv_initialize(1, qmr[1]) circuit.cv_d(1, qmr[0], duration=100, unit="ns") circuit.cv_c_d(1, qmr[1], qbr[0], duration=100, unit="ns") photon_loss_rate = 0.02 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit, instructions=["cD"]) state, result, fock_counts = c2qa.util.simulate(circuit, noise_passes=noise_pass) assert result.success def test_photon_loss_qumode(capsys): with capsys.disabled(): num_qumodes = 2 num_qubits_per_qumode = 2 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(size=num_qubits) circuit = c2qa.CVCircuit(qmr, qbr) circuit.cv_initialize(1, qmr[0]) circuit.cv_d(1, qmr[0], duration=100, unit="ns") circuit.cv_c_d(1, qmr[1], qbr[0], duration=100, unit="ns") photon_loss_rate = 0.02 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit, qumodes=qmr[1]) state, result, fock_counts = c2qa.util.simulate(circuit, noise_passes=noise_pass) assert result.success def test_photon_loss_instruction_qumode(capsys): with capsys.disabled(): num_qumodes = 2 num_qubits_per_qumode = 2 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(size=num_qubits) circuit = c2qa.CVCircuit(qmr, qbr) circuit.cv_initialize(1, qmr[0]) circuit.cv_d(1, qmr[0], duration=100, unit="ns") circuit.cv_c_d(1, qmr[1], qbr[0], duration=100, unit="ns") photon_loss_rate = 0.02 time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit, instructions=["cD"], qumodes=qmr[0]) state, result, fock_counts = c2qa.util.simulate(circuit, noise_passes=noise_pass) assert result.success def test_photon_loss_and_phase_damping(capsys): with capsys.disabled(): state_a, result_a, fock_counts = _build_photon_loss_and_amp_damping_circuit(0.0) print(state_a) assert result_a.success state_b, result_b, fock_counts = _build_photon_loss_and_amp_damping_circuit(1.0) print(state_b) assert result_b.success assert not allclose(state_a, state_b) def _build_photon_loss_and_amp_damping_circuit(amp_damp = 0.3, photon_loss_rate = 0.01): num_qumodes = 1 qubits_per_mode = 2 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=qubits_per_mode) qbr = qiskit.QuantumRegister(size=num_qubits) circuit = c2qa.CVCircuit(qmr, qbr) circuit.cv_initialize(2, qmr[0]) circuit.x(qbr[0]) circuit.cv_d(1, qmr[0], duration=100, unit="ns") # Initialize phase damping NoiseModel noise_model = noise.NoiseModel() phase_error = noise.amplitude_damping_error(amp_damp) noise_model.add_quantum_error(phase_error, ["x"], [circuit.get_qubit_index(qbr[0])]) # Initialize PhotonLossNoisePass noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit="ns") return c2qa.util.simulate(circuit, noise_model=noise_model, noise_passes=noise_pass) def allclose(a, b) -> bool: """Convert SciPy sparse matrices to ndarray and test with Numpy""" # If a and b are SciPy sparse matrices, they'll have a "toarray()" function if hasattr(a, "toarray"): a = a.toarray() if hasattr(b, "toarray"): b = b.toarray() return np.allclose(a, b) def test_relaxation_noise_pass(capsys): with capsys.disabled(): num_qumodes = 1 num_qubits_per_qumode = 2 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(size=num_qubits) circuit = c2qa.CVCircuit(qmr, qbr) circuit.cv_initialize(3, qmr[0]) circuit.cv_c_d(1, qmr[0], qbr[0], duration=100, unit="ns") t1s = np.ones(circuit.num_qubits).tolist() t2s = np.ones(circuit.num_qubits).tolist() noise_pass = RelaxationNoisePass(t1s, t2s) filename = "tests/test_relaxation_noise_pass.gif" c2qa.animate.animate_wigner( circuit, animation_segments=200, file=filename, noise_passes=noise_pass, ) assert Path(filename).is_file() def test_relaxation_and_photon_loss_noise_passes(capsys): with capsys.disabled(): num_qumodes = 1 num_qubits_per_qumode = 2 num_qubits = 1 qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(size=num_qubits) circuit = c2qa.CVCircuit(qmr, qbr) circuit.cv_initialize(3, qmr[0]) circuit.cv_c_d(1, qmr[0], qbr[0], duration=100, unit="ns") noise_passes = [] t1s = np.ones(circuit.num_qubits).tolist() t2s = np.ones(circuit.num_qubits).tolist() noise_passes.append(RelaxationNoisePass(t1s, t2s)) photon_loss_rate = 0.02 noise_passes.append(c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit="ns")) filename = "tests/test_relaxation_and_photon_loss_noise_passes.gif" c2qa.animate.animate_wigner( circuit, animation_segments=200, file=filename, noise_passes=noise_passes, ) assert Path(filename).is_file() def test_multi_qumode_loss_probability(capsys): with capsys.disabled(): num_qumodes = 2 num_qubits_per_qumode = 2 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) circuit = c2qa.CVCircuit(qmr) circuit.cv_initialize(1, qmr[0]) circuit.cv_initialize(1, qmr[1]) circuit.cv_bs(np.pi/4, qmr[0], qmr[1], duration=100, unit="ns") circuit.cv_bs(-np.pi/4, qmr[0], qmr[1], duration=100, unit="ns") photon_loss_rate = 10000000 noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rate, circuit) fifty_fifty = False print() for i in range(20): print("----------------------") print(f"Iteration {i}") state_vector, result, fock_counts = c2qa.util.simulate(circuit, noise_passes=noise_pass) # plot_histogram(result.get_counts(circuit), filename=f"tests/test_manual_validate_beamsplitter-{i}.png") occupation, fock_states = c2qa.util.stateread(state_vector, 0, num_qumodes, 2**num_qubits_per_qumode,verbose=True) for qumode_state, qubit_state, amplitude in fock_states: # print(f"{qumode_state} {qubit_state} {amplitude}") qumode1 = qumode_state[0] qumode2 = qumode_state[1] probability = amplitude**2 if (qumode1 == 1 and qumode2 == 0) or (qumode1 == 0 and qumode1 == 1) and math.isclose(probability, 0.5, 0.03): fifty_fifty = True assert fifty_fifty
https://github.com/C2QA/bosonic-qiskit
C2QA
from pathlib import Path import c2qa import numpy import qiskit def assert_changed(state, result): assert result.success # print() # print(circuit.draw("text")) # print(state) # TODO - better understand what the state vector results should be assert count_nonzero(state) > 1 def count_nonzero(statevector: qiskit.quantum_info.Statevector): """Re-implement numpy.count_nonzero using numpy.isclose().""" nonzero = len(statevector.data) for state in statevector.data: if numpy.isclose(state, 0): nonzero -= 1 return nonzero def create_conditional(num_qumodes: int = 2, num_qubits_per_qumode: int = 2): qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) qr = qiskit.QuantumRegister(2) circuit = c2qa.CVCircuit(qmr, qr) for qumode in range(num_qumodes): circuit.cv_initialize(0, qmr[qumode]) circuit.initialize([0, 1], qr[1]) # qr[0] will init to zero return circuit, qmr, qr def test_parameterized_displacement(capsys): with capsys.disabled(): circuit, qmr, qr = create_conditional() alpha = qiskit.circuit.Parameter("alpha") circuit.cv_d(alpha, qmr[0]) bound_circuit = circuit.assign_parameters({alpha: 3.14}) state, result, fock_counts = c2qa.util.simulate(bound_circuit) assert_changed(state, result) def test_complex_literals(capsys): with capsys.disabled(): # a = qiskit.circuit.Parameter('𝛼') qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=4) qbr = qiskit.QuantumRegister(1) minimal_circuit = c2qa.CVCircuit(qmr, qbr) minimal_circuit.h(qbr[0]) minimal_circuit.cv_c_d(1j * 1, qmr[0], qbr[0]) # bound_circuit = minimal_circuit.assign_parameters({a: 1}) c2qa.util.simulate(minimal_circuit) def test_complex_parameters(capsys): with capsys.disabled(): a = qiskit.circuit.Parameter("𝛼") qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=4) qbr = qiskit.QuantumRegister(1) minimal_circuit = c2qa.CVCircuit(qmr, qbr) minimal_circuit.h(qbr[0]) minimal_circuit.cv_c_d(1j * a, qmr[0], qbr[0]) bound_circuit = minimal_circuit.assign_parameters({a: 1}) c2qa.util.simulate(bound_circuit) def test_complex_parameters_float(capsys): with capsys.disabled(): a = qiskit.circuit.Parameter("𝛼") qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=4) qbr = qiskit.QuantumRegister(1) minimal_circuit = c2qa.CVCircuit(qmr, qbr) minimal_circuit.h(qbr[0]) minimal_circuit.cv_c_d(1j * a, qmr[0], qbr[0]) bound_circuit = minimal_circuit.assign_parameters({a: 2}) c2qa.util.simulate(bound_circuit)
https://github.com/C2QA/bosonic-qiskit
C2QA
import qiskit import qiskit_aer def test_qiskit(): """Verify we can do a simple QisKit circuit without our custom gates.""" qr = qiskit.QuantumRegister(6) cr = qiskit.ClassicalRegister(6) circuit = qiskit.circuit.QuantumCircuit(qr, cr) circuit.cx(qr[0:1], qr[2]) circuit.save_statevector() backend = qiskit_aer.AerSimulator() job = backend.run(circuit) result = job.result() state = result.get_statevector(circuit) assert result.success print(state) def test_initialize(capsys): with capsys.disabled(): # Successful with Qiskit v0.34.2, raises error with v0.35+ qr = qiskit.QuantumRegister(1) circuit = qiskit.circuit.QuantumCircuit(qr) circuit.initialize([0, 1], qr[0])
https://github.com/C2QA/bosonic-qiskit
C2QA
# Copyright 2022-2023 Ohad Lev. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0, # or in the root directory of this package("LICENSE.txt"). # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for `util.py` module.""" import unittest from datetime import datetime from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from sat_circuits_engine.util import flatten_circuit, timestamp class UtilTest(unittest.TestCase): def test_timestamp(self): """Test for the `timestamp` function.""" self.assertEqual(timestamp(datetime(2022, 12, 3, 17, 0, 45, 0)), "D03.12.22_T17.00.45") def test_flatten_circuit(self): """Test for the `flatten_circuit` function.""" bits_1 = 2 bits_2 = 3 qreg_1 = QuantumRegister(bits_1) qreg_2 = QuantumRegister(bits_2) creg_1 = ClassicalRegister(bits_1) creg_2 = ClassicalRegister(bits_2) circuit = QuantumCircuit(qreg_1, qreg_2, creg_1, creg_2) self.assertEqual(circuit.num_qubits, bits_1 + bits_2) self.assertEqual(circuit.num_clbits, bits_1 + bits_2) self.assertEqual(len(circuit.qregs), 2) self.assertEqual(len(circuit.cregs), 2) flat_circuit = flatten_circuit(circuit) self.assertEqual(flat_circuit.num_qubits, bits_1 + bits_2) self.assertEqual(flat_circuit.num_clbits, bits_1 + bits_2) self.assertEqual(len(flat_circuit.qregs), 1) self.assertEqual(len(flat_circuit.cregs), 1) if __name__ == "__main__": unittest.main()
https://github.com/C2QA/bosonic-qiskit
C2QA
from pathlib import Path import c2qa import numpy import qiskit def test_plot_zero(capsys): with capsys.disabled(): qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=4) qr = qiskit.QuantumRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr) # dist = numpy.sqrt(numpy.pi) / numpy.sqrt(2) dist = 1.0 # qr[0] will init to zero circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) trace = c2qa.util.trace_out_qubits(circuit, state) c2qa.wigner.plot_wigner(circuit, trace, file="tests/zero.png", trace=False) def test_plot_one(capsys): with capsys.disabled(): qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qr = qiskit.QuantumRegister(size=1) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) # qr[0] and cr[0] will init to zero circuit.cv_initialize(1, qmr[0]) state, result, fock_counts = c2qa.util.simulate(circuit) # print("Qumode initialized to one:") # print(state) c2qa.wigner.plot_wigner(circuit, state, file="tests/one.png") def test_plot_wigner_projection(capsys): with capsys.disabled(): qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=4) qr = qiskit.QuantumRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr) # dist = numpy.sqrt(numpy.pi) / numpy.sqrt(2) dist = 1.0 # qr[0] will init to zero circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) # circuit.cv_d(dist, qmr[0]) c2qa.wigner.plot_wigner_projection(circuit, qr[0], file="tests/interference.png") def test_cat_state_wigner_plot(capsys): with capsys.disabled(): num_qubits_per_qumode = 4 dist = 2 qmr = c2qa.QumodeRegister( num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode ) qr = qiskit.QuantumRegister(size=1) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) circuit.initialize([1, 0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) # conditional_state_vector=True will return two state vectors, one for 0 and 1 classical register value state, result, fock_counts = c2qa.util.simulate(circuit, conditional_state_vector=True) even_state = state["0x0"] odd_state = state["0x1"] wigner_filename = "tests/cat_wigner_even.png" c2qa.wigner.plot_wigner( circuit, even_state, file=wigner_filename, trace=True, axes_min=-6, axes_max=6, ) assert Path(wigner_filename).is_file() wigner_filename = "tests/cat_wigner_odd.png" c2qa.wigner.plot_wigner( circuit, odd_state, file=wigner_filename, trace=True, axes_min=-6, axes_max=6, ) assert Path(wigner_filename).is_file() # # Need to recreate circuit state prior to measure collapsing qubit state for projections # qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode) # qr = qiskit.QuantumRegister(size=1) # cr = qiskit.ClassicalRegister(size=1) # circuit = c2qa.CVCircuit(qmr, qr, cr) # circuit.initialize(state) # wigner_filename = "tests/repeat_projection_wigner.png" # c2qa.wigner.plot_wigner_projection(circuit, qr[0], file=wigner_filename) # assert Path(wigner_filename).is_file() def test_wigner_mle(capsys): with capsys.disabled(): num_qubits_per_qumode = 4 dist = 2 qmr = c2qa.QumodeRegister( num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode ) qr = qiskit.QuantumRegister(size=1) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) circuit.initialize([1, 0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) circuit.h(qr[0]) state, result, fock_counts = c2qa.util.simulate(circuit, per_shot_state_vector=True) wigner = c2qa.wigner.wigner_mle(state) assert wigner is not None print(wigner) def test_plot_wigner_snapshot(capsys): with capsys.disabled(): num_qubits_per_qumode = 4 dist = 2 qmr = c2qa.QumodeRegister( num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode ) qr = qiskit.QuantumRegister(size=1) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) circuit.initialize([1, 0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.cv_snapshot() circuit.h(qr[0]) circuit.cv_snapshot() circuit.cv_c_d(dist, qmr[0], qr[0]) circuit.cv_snapshot() circuit.h(qr[0]) circuit.cv_snapshot() state, result, fock_counts = c2qa.util.simulate(circuit) c2qa.wigner.plot_wigner_snapshot(circuit, result, "tests") def test_plot_zero_contour(capsys): with capsys.disabled(): data = numpy.zeros((200, 200)).tolist() filename = "tests/test_plot_zero_contour.png" c2qa.wigner.plot(data, file=filename) assert Path(filename).is_file()
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import qiskit import numpy as np import c2qa.util as util import matplotlib.pyplot as plt import matplotlib numberofmodes=5 numberofqubits=numberofmodes numberofqubitspermode=3 cutoff=2**numberofqubitspermode qmr = c2qa.QumodeRegister(num_qumodes=numberofmodes, num_qubits_per_qumode=numberofqubitspermode) qbr = qiskit.QuantumRegister(size=numberofqubits) cbr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qbr, cbr) sm = [0,0,1,0,0] for i in range(qmr.num_qumodes): circuit.cv_initialize(sm[i], qmr[i]) def bch(circuit, qm, qb, U, dt): arg = np.sqrt((U/4)*dt) circuit.cv_c_rx(arg, qm, qb) circuit.cv_c_r(arg, qm, qb) circuit.cv_c_rx(-arg, qm, qb) circuit.cv_c_r(-arg, qm, qb) def eiht(circuit, qma, qmb, qba, qbb, J, U, mu, dt): circuit.cv_bs(-J*dt, qmb, qma) circuit.cv_r(-((U/2)+mu)*dt, qma) circuit.cv_r(-((U/2)+mu)*dt, qmb) bch(circuit, qma, qba, U/2, dt) bch(circuit, qmb, qbb, U/2, dt) return circuit def trotterise_BH(circuit, numberofmodes, numberofqubits, qmr, qbr, cutoff, N, J, U, mu, dt): occs=[np.zeros((N,numberofmodes)),np.zeros((N,numberofqubits))] # Trotterise. i*dt corresponds to the timestep i, of length from the previous timestep dt. for i in range(N): print("dt+1", i*dt) # Trotterise according to the brickwork format to make depth of circuit 2 and not number of timesteps (because each site needs to be part of a gate with the site to the left and a gate with the site to the right. for j in range(0,numberofmodes-1,2): eiht(circuit, qmr[j+1], qmr[j], qbr[j], qbr[j+1], J, U, mu, dt) for j in range(1,numberofmodes-1,2): eiht(circuit, qmr[j+1], qmr[j], qbr[j], qbr[j+1], J, U, mu, dt) stateop, result, fock_counts = c2qa.util.simulate(circuit) occupation = util.stateread(stateop, qbr.size, numberofmodes, 4,verbose=False) occs[0][i]=np.array(list(occupation[0][0])) occs[1][i]=np.array(list(occupation[0][1])) return occs dt=0.1 N=10 J=1 U=0.1 mu=1 occupations = trotterise_BH(circuit, numberofmodes, numberofqubits, qmr, qbr, cutoff, N, J, U, mu, dt) plt.pcolormesh(np.arange(numberofmodes+1)-numberofmodes//2-0.5,np.arange(N+1)*dt,occupations[0],cmap=matplotlib.cm.Blues,linewidth=0,rasterized=True) plt.title("$J=1$, $U=0.1$, $\mu=1$") plt.xlabel("Modes") plt.ylabel("Time") cbar = plt.colorbar() cbar.ax.get_yaxis().labelpad = 15 cbar.set_label("Mode occupation", rotation=270) plt.rcParams["figure.figsize"] = (6,3) plt.tight_layout() plt.savefig("BH.pdf")
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Import packages that will be used import c2qa import numpy as np import matplotlib.pyplot as plt from qiskit import ClassicalRegister, visualization, AncillaRegister from qiskit_aer.noise import NoiseModel, amplitude_damping_error from qiskit.quantum_info import state_fidelity, Statevector from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.operators.predicates import is_unitary_matrix from math import pi, ceil from scipy.optimize import curve_fit # LaTeX typesetting for plt plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) plt.rcParams['text.usetex'] = True plt.rc('text.latex', preamble=r'\usepackage{amssymb}') plt.rc('text.latex', preamble=r'\usepackage{amsmath}') ## Demonstration of amplitude damping circuit # Define how many qumodes we want, and how many qubits we should use to represent each. Our basis will consist of Fock states |0> to |7> num_qumodes = 1 num_qubits_per_qumode = 3 # The photon number which the Hilbert space truncates at is 2 ** num_qubits_per_qumode = 8 # Create circuit qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) cr = ClassicalRegister(num_qumodes * num_qubits_per_qumode) circ = c2qa.CVCircuit(qmr, cr) # To illustrate photon loss, first initialize the qumode in Fock state |7> circ.cv_initialize(7, qmr[0]) # Now apply a delay gate and specify gate duration and units gate_duration = 1 time_unit = "ms" circ.cv_delay(duration=gate_duration, qumode=qmr[0], unit=time_unit) # Now set a loss rate -- make it large enough such that we can actually see the loss photon_loss_rate = 0.5 # This is a loss rate in units of 1/ms noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circ, time_unit=time_unit) # To see the loss, we can make a measurement on the qumode and visualise counts with a histogram circ.cv_measure(qmr[0], cr) # Use noise pass with simulate _, _, counts = c2qa.util.simulate(circ, noise_passes=noise_pass) # Visualise photon loss using a histogram visualization.plot_histogram(counts) ## Demonstration of photon parity measurement circuit # Create new circuit with 1 qumode, 1 ancilla qubit, and 1 classical register for anc readout. qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) anc = AncillaRegister(1) cr = ClassicalRegister(1) circ = c2qa.CVCircuit(qmr, anc, cr) circ.initialize([1, 0], anc[0]) # Initialize ancilla qubit in |0> state # Initialize qumode in either odd parity or even parity Fock state #circ.cv_initialize(2, qmr) # |2> Fock state circ.cv_initialize(3, qmr) # |3> Fock state # Apply hadamard on ancilla qubit circ.h(anc[0]) # Apply controlled phase space rotation gate on qumode circ.cv_c_r(pi/2, qmr[0], anc[0]) # Apply unconditional phase space rotation gate to correct global phase circ.cv_r(-pi/2, qmr[0]) # Apply hadamard on ancilla qubit again, and measure the ancilla qubit. circ.h(anc[0]) circ.cv_measure(anc, cr) _, _, counts = c2qa.util.simulate(circ) # Measurement will return 0 for even parity and 1 for odd parity print(counts) # Create empty matrix empty = np.zeros((2**num_qubits_per_qumode, 2**num_qubits_per_qumode)) ## Defining our theoretical operation for U_odd # Map logical 1's photon loss state |1> back to logical 1. (i.e. |2><1|, where fock_input = <1|, and fock_output = |2>) u_odd = c2qa.util.fockmap(matrix=empty, fock_input=[1], fock_output=[2]) # Map logical 0's photon loss state |3> to logical 0 u_odd = c2qa.util.fockmap(u_odd, fock_input=[3, 3], fock_output=[0, 4], amplitude=[1/np.sqrt(2), 1/np.sqrt(2)]) # Mappings to satisfy unitary condition u_odd = c2qa.util.fockmap(u_odd, [5, 6, 7], [5, 6, 7]) u_odd = c2qa.util.fockmap(u_odd, [2, 0], [3, 1]) u_odd = c2qa.util.fockmap(u_odd, [4, 4], [0, 4], 1/np.sqrt(2) * np.array([1, -1])) # Check that our matrix is indeed unitary assert(is_unitary_matrix(u_odd)) ## Defining our theoretical operation for U_even. # We will delay the building of the gate until we have the value we need for kt def u_even(kt): # Map logical 1 back to logical 1 u_even = c2qa.util.fockmap(empty, 2, 2) # Map logical 0's error state to logical 0 u_even = c2qa.util.fockmap(u_even, [0, 0, 4, 4], [0, 4, 0, 4], 1/np.sqrt(1 + kt**2) * np.array([1, kt, -kt, 1])) # Mappings to satisfy unitary condition u_even = c2qa.util.fockmap(u_even, [1, 3, 5, 6, 7], [1, 3, 5, 6, 7]) # Check that our matrix is indeed unitary assert(is_unitary_matrix(u_even)) return u_even # Initialize new circuit qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) cr = ClassicalRegister(num_qumodes * num_qubits_per_qumode) circ = c2qa.CVCircuit(qmr, cr) # Initialize qumode in |1_L> error state circ.cv_initialize([0, 1], qmr) # Append the u_odd matrix to circuit and measure circ.cv_gate_from_matrix(u_odd, qmr[0]) circ.cv_measure(qmr[0], cr) _, _, counts = c2qa.util.simulate(circ) # We measure |2> Fock state, demonstrating recovery of the logical 1 state print(counts) ## Run this block to load in the functions we need for the simulation # Runs circuit simulation def error_correction_experiment(encoding: str, corrections: int, shots: int, additional_snapshots: int=10, total_circuit_time: int=1, apply_noise: bool=True, return_circuit: bool=False, had_damp: bool=False, identity: bool=False): multiplier = total_circuit_time total_circuit_time = int(total_circuit_time * 1000) # Code works with microsecond units, but input is in milliseconds if corrections > 333: raise ValueError("Please restrict number of correction procedures to 333 or less") photon_loss_rate = 0.0005 num_qumodes = 1 num_qubits_per_qumode = 3 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) anc = AncillaRegister(1) cr = ClassicalRegister(1) circuit = c2qa.CVCircuit(qmr, anc, cr) ### 1. State Preparation perf_0 = np.array([1/np.sqrt(2), 0, 0, 0, 1/np.sqrt(2), 0, 0, 0]) perf_1 = np.array([0, 0, 1, 0, 0, 0, 0, 0]) if encoding == 'logi0': perf_state = perf_0 elif encoding == 'logi1': perf_state = perf_1 elif encoding == 'logi_xplus': perf_state = (perf_0 + perf_1)/np.sqrt(2) elif encoding == 'logi_xminus': perf_state = (perf_0 - perf_1)/np.sqrt(2) elif encoding == 'logi_yplus': perf_state = (perf_0 + 1j * perf_1)/np.sqrt(2) elif encoding == 'logi_yminus': perf_state = (perf_0 - 1j * perf_1)/np.sqrt(2) else: raise ValueError("Please input a valid state for the encoding") # Convert type to list perf_state = list(perf_state) #print(perf_state, "cv_initialzed this") # Initialize state circuit.cv_initialize(perf_state, qmr[0]) ### 2. Using instructions stored in schedule, add snapshots, noise, and parity check + recovery operations schedule = _circuit_scheduler(corrections * multiplier, additional_snapshots * multiplier, total_circuit_time) schedule_copy = list(schedule.items()) #print(schedule) adjustment = 0 # For calculating duration timing snapshot_counter = 0 # For tracking number of snapshots taken corr_position = [] # For tracking positions at which corrections were finished u_iden = c2qa.util.fockmap(empty, [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7]) for index, (key, value) in enumerate(list(schedule.items())): # Instruction at 0µs should always be to take snapshot if (key == '0') & (value == 'snapshot'): circuit.save_statevector(label='snapshot_{}'.format(snapshot_counter), pershot=True) snapshot_counter += 1 continue elif (key != '0'): pass else: raise Exception("Something seems to have gone wrong here") # Calculate delay gate durations using prevkey. Adjustment to duration timing is needed depending on previous instruction prevkey, prevvalue = schedule_copy[index - 1] delay_dur = int(key) - int(prevkey) + adjustment #print(delay_dur, key, value) adjustment = 0 # Apply noise circuit.cv_delay(duration=delay_dur, qumode=qmr[0], unit="µs") # Apply snapshot only procedure if (value == 'snapshot'): # Don't take duplicate snapshots if (prevvalue == 'correction') & (int(key) == (int(prevkey) + 3)): pass else: circuit.save_statevector(label='snapshot_{}'.format(snapshot_counter), pershot=True) snapshot_counter += 1 # Apply snapshot, parity check, recovery, snapshot elif value == 'correction': # Find previous corr position, and determine kt_dur with that information while index > 0: k, v = list(schedule.items())[index-1] # Break loop if we iterated till start of dictionary if (v == 'snapshot') & (k == '0'): kt_dur = int(key) - int(k) break # Skip all snapshot instructions elif v == 'snapshot': index -= 1 # Find either snapshot+corr or corr instruction and extract kt_dur elif v != 'snapshot': kt_dur = int(key) - int(k) break #print(kt_dur) kt = photon_loss_rate * (kt_dur + 3) adjustment = -3 # Parity check circuit.initialize([1, 0], anc[0]) circuit.h(anc[0]) circuit.cv_delay(duration=1, qumode=qmr[0], unit="µs") # Manually discretize gates by splitting 0.5µs pi/2 rotation into five 0.1µs pi/10 rotations for _ in range(5): circuit.cv_c_r(pi/10, qmr[0], anc[0], duration=0.1, unit="µs") for _ in range(5): circuit.cv_r(-pi/10, qmr[0], duration=0.1, unit="µs") # circuit.cv_c_r(pi/2, qmr[0], anc[0], duration=0.5, unit="µs") # circuit.cv_r(-pi/2, qmr[0], anc[0], duration=0.5, unit="µs") circuit.cv_delay(duration=1, qumode=qmr[0], unit="µs") circuit.h(anc[0]) circuit.measure(anc[0], cr[0]) # Apply recovery operation, without or with u_even if identity: with circuit.if_test((cr[0], 1), label='Recovery op') as else_: circuit.cv_gate_from_matrix(u_odd, qmr[0], duration=0.1, unit="ns") #u_odd circuit.reset(anc[0]) with else_: circuit.cv_gate_from_matrix(u_iden, qmr[0], duration=0.1, unit="ns") #u_iden else: with circuit.if_test((cr[0], 1), label='Recovery op') as else_: circuit.cv_gate_from_matrix(u_odd, qmr[0], duration=0.1, unit="ns") #u_odd circuit.reset(anc[0]) with else_: circuit.cv_gate_from_matrix(u_even(kt), qmr[0], duration=0.1, unit="ns") #u_even(kt) circuit.save_statevector(label='snapshot_{}'.format(snapshot_counter), pershot=True) snapshot_counter += 1 corr_position.append(int(key) + 3) # Apply snapshot, parity check, recovery, followed by another snapshot else: circuit.save_statevector(label='snapshot_{}'.format(snapshot_counter), pershot=True) snapshot_counter += 1 adjustment = -3 # Find previous corr position, and determine kt_dur with that information while index > 0: k, v = list(schedule.items())[index-1] # Break loop if we iterated till start of dictionary if (v == 'snapshot') & (k == '0'): kt_dur = int(key) - int(k) break # Skip all snapshot instructions elif v == 'snapshot': index -= 1 # Find either snapshot+corr or corr instruction and extract kt_dur elif v != 'snapshot': kt_dur = int(key) - int(k) break #print(kt_dur) kt = photon_loss_rate * (kt_dur + 3) # Parity check circuit.initialize([1, 0], anc[0]) circuit.h(anc[0]) circuit.cv_delay(duration=1, qumode=qmr[0], unit="µs") # Manually discretize gates by splitting 0.5µs pi/2 rotation into five 0.1µs pi/10 rotations for _ in range(5): # Manually discretize cv_c_r gate by splitting one 1µs pi rotation into ten 0.1µs pi/10 rotations circuit.cv_c_r(pi/10, qmr[0], anc[0], duration=0.1, unit="µs") for _ in range(5): circuit.cv_r(-pi/10, qmr[0], duration=0.1, unit="µs") # circuit.cv_c_r(pi/2, qmr[0], anc[0], duration=0.5, unit="µs") # circuit.cv_r(-pi/2, qmr[0], anc[0], duration=0.5, unit="µs") circuit.cv_delay(duration=1, qumode=qmr[0], unit="µs") circuit.h(anc[0]) circuit.measure(anc[0], cr[0]) if identity: # Recovery operation with circuit.if_test((cr[0], 1), label='Recovery op') as else_: circuit.cv_gate_from_matrix(u_odd, qmr[0], duration=0.1, unit="ns") #u_odd circuit.reset(anc[0]) with else_: circuit.cv_gate_from_matrix(u_iden, qmr[0], duration=0.1, unit="ns") #u_even(kt) else: # Recovery operation with circuit.if_test((cr[0], 1), label='Recovery op') as else_: circuit.cv_gate_from_matrix(u_odd, qmr[0], duration=0.1, unit="ns") #u_odd circuit.reset(anc[0]) with else_: circuit.cv_gate_from_matrix(u_even(kt), qmr[0], duration=0.1, unit="ns") #u_even(kt) circuit.save_statevector(label='snapshot_{}'.format(snapshot_counter), pershot=True) snapshot_counter += 1 corr_position.append(int(key) + 3) # Final delay gate finalkey, finalvalue = schedule_copy[-1] if finalvalue != 'snapshot': final_gate_delay = total_circuit_time - int(finalkey) - 3 else: final_gate_delay = total_circuit_time - int(finalkey) circuit.cv_delay(duration=final_gate_delay, qumode=qmr[0], unit="µs") if return_circuit: return circuit ### 3. Define noise parameters # Noise pass for qumode photon loss noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit="µs") # Noise model for hadamard amplitude damping T1 = 10 # In µs hgate_duration = 1 # In µs error = amplitude_damping_error(1 - np.exp(-hgate_duration / T1)) noise_model = NoiseModel() index, _ = circuit.find_bit(anc[0]) noise_model.add_quantum_error(error, ['h'], [index]) ### 4. Simulate circuit if apply_noise: if had_damp: state, result, _ = c2qa.util.simulate(circuit, shots=shots, per_shot_state_vector=True, return_fockcounts=False, noise_passes=noise_pass, noise_model=noise_model) else: state, result, _ = c2qa.util.simulate(circuit, shots=shots, per_shot_state_vector=True, return_fockcounts=False, noise_passes=noise_pass) elif not apply_noise: state, result, _ = c2qa.util.simulate(circuit, shots=shots, per_shot_state_vector=True, return_fockcounts=False) ### 5. Process data # Find fidelity and photon probability at each snapshot, across all shots traced_density_matrices = _state_traceout(circuit, state, result, snapshot_counter) expectation_list_tuple, fidelity_list, probability_list_tuple = _state_processor(encoding, perf_state, traced_density_matrices) # Find exact timing of each snapshot (we have to recalculate because no. of snapshots can change due to scheduling conflicts) snapshot_times = _snapshot_timings(schedule, total_circuit_time) return expectation_list_tuple, fidelity_list, probability_list_tuple, snapshot_times, corr_position#, circuit, schedule, snapshot_counter # Trace out qubit for both sets of statevectors def _state_traceout(circuit, state, result, actual_snapshots): # Process snapshot and final statevectors traced_snapshot_density_matrices = [] for i in range(actual_snapshots): snapshot_list = result.data()['snapshot_{}'.format(i)] traced_snapshots = [] for statevector in snapshot_list: traced_snapshots.append(c2qa.util.trace_out_qubits(circuit, statevector)) traced_snapshot_density_matrices.append(traced_snapshots) traced_final_density_matrices = [] for i in state: traced_final_density_matrices.append(c2qa.util.trace_out_qubits(circuit, i)) traced_density_matrices = traced_snapshot_density_matrices + [traced_final_density_matrices] return traced_density_matrices # Takes traced matrices and finds expectation, fidelity, and photon probability def _state_processor(encoding, perf_state, traced_density_matrices): #print(perf_state, "compute fidelity with this") perf_0 = [1/np.sqrt(2), 0, 0, 0, 1/np.sqrt(2), 0, 0, 0] perf_1 = [0, 0, 1, 0, 0, 0, 0, 0] err = [1/np.sqrt(2), 0, 0, 0, -1/np.sqrt(2), 0, 0, 0] # Bring into qubit space projector = Operator(np.outer([1, 0], perf_0) + np.outer([0, 1], perf_1)) # Z expectation if (encoding == 'logi0') or (encoding == 'logi1'): pauli = np.array([[1, 0], [0, -1]]) # X expectation elif (encoding == 'logi_xplus') or (encoding == 'logi_xminus'): #projector = Operator(np.outer([1/np.sqrt(2), 1/np.sqrt(2)], (perf_0 + perf_1)/np.sqrt(2)) + np.outer([1/np.sqrt(2), -1/np.sqrt(2)], (perf_0 - perf_1)/np.sqrt(2))) pauli = np.array([[0, 1], [1, 0]]) # Y expectation elif (encoding == 'logi_yplus') or (encoding == 'logi_yminus'): #projector = Operator(np.outer([1/np.sqrt(2), 1j/np.sqrt(2)], (perf_0 + 1j * perf_1)/np.sqrt(2)) + np.outer([1/np.sqrt(2), 1j/np.sqrt(2)], (perf_0 - 1j * perf_1)/np.sqrt(2))) pauli = np.array([[0, -1j], [1j, 0]]) # Compute from each density matrix 1) Pauli expectation, 2) fidelity, 3) probability of measuring photon number expectation_list, exp_prob_list, fidelity_list, probability_listA, probability_listB = [], [], [], [], [] for density_matrix_list in traced_density_matrices: cycle_list_expectation, cycle_list_exp_prob, cycle_list_fid, cycle_list_probA, cycle_list_probB = [], [], [], [], [] for matrix in density_matrix_list: #print(matrix.trace()) # Pauli Expectation qubit_space_projected_state = matrix.evolve(projector) projection_prob = qubit_space_projected_state.trace() expectation = (qubit_space_projected_state/projection_prob).expectation_value(pauli) cycle_list_exp_prob.append(projection_prob) cycle_list_expectation.append(expectation) # Fid cycle_list_fid.append(round(state_fidelity(matrix, Statevector(perf_state)), 6)) # Photon meas prob cycle_list_probA.append(list(matrix.probabilities(decimals=5))) # Photon number fid0 = round(state_fidelity(matrix, perf_0), 6) fiderr = round(state_fidelity(matrix, err), 6) cycle_list_probB.append([fid0, fiderr]) # w/ respect to specific states # Avg photon num #cycle_list_avg_photon.append(c2qa.util.qumode_avg_photon_num(matrix)) expectation_list.append(cycle_list_expectation) exp_prob_list.append(cycle_list_exp_prob) fidelity_list.append(cycle_list_fid) probability_listA.append(cycle_list_probA) probability_listB.append(cycle_list_probB) #avg_photon_list.append(cycle_list_avg_photon) return (expectation_list, exp_prob_list), fidelity_list, (probability_listA, probability_listB) # Function used to determine order and timing in which snapshots and corrections are done. def _circuit_scheduler(corrections, snapshots, total_time=1000): # Schedule snapshots if snapshots == 0: pass else: snapshot_schedule = {"{}".format(round(i * (total_time/snapshots))): 'snapshot' for i in range(snapshots)} # Schedule corrections corr_interval = total_time/(1 + corrections) correction_schedule = {"{}".format(int((i + 1) * corr_interval)): 'correction' for i in range(corrections)} # If no corrections, return snapshot_schedule if corrections == 0: return snapshot_schedule # If no snapshots, return correction_schedule with 1 snapshot at start elif snapshots == 0: correction_schedule = {**{'0' : 'snapshot'}, **correction_schedule} return correction_schedule else: pass # Merge the two dicts from above. If duplicate keys exist then concatenate values together. try: unsorted_merged_schedule = {**snapshot_schedule, **correction_schedule} for key, value in list(snapshot_schedule.items()): if key in list(correction_schedule.keys()): unsorted_merged_schedule[key] = '{}'.format(value + '+' + correction_schedule[key]) else: pass except: print("_circuit_scheduler() has an error") # Sort merged dicts merged_schedule = {key:value for key, value in sorted(unsorted_merged_schedule.items(), key=lambda item: int(item[0]))} # Ensure that all corrections happen at least 3µs before each snapshot # but if two successive corrections happen within 3µs of each other, drop the second correction DictItems = list(merged_schedule.items()) unsorted_cleaned_schedule = dict(merged_schedule) for index, (key, value) in enumerate(DictItems): # index == 0 case if index == 0: nextkey, _ = DictItems[index + 1] if (value == 'correction') & (int(key) + 3 > int(nextkey)): unsorted_cleaned_schedule['{}'.format(str(int(nextkey) - 3))] = unsorted_cleaned_schedule.pop('{}'.format(key)) # index != 0 case else: # Automatically break loop when we get to last element of dictionary try: nextkey, _ = DictItems[index + 1] prevkey, _ = DictItems[index - 1] except: break if (value == 'correction') & (int(key) + 3 > int(nextkey)) & (int(prevkey) < int(key) - 3): unsorted_cleaned_schedule['{}'.format(str(int(nextkey) - 3))] = unsorted_cleaned_schedule.pop('{}'.format(key)) elif (value == 'correction') & (int(key) + 3 > int(nextkey)): unsorted_cleaned_schedule.pop('{}'.format(key)) print("Due to scheduling conflicts, a correction scheduled at {}µs will be dropped".format(key)) # Sort overall_schedule cleaned_schedule = {key:value for key, value in sorted(unsorted_cleaned_schedule.items(), key=lambda item: int(item[0]))} return cleaned_schedule # Function for extracting snapshot timings (in ms) def _snapshot_timings(schedule, total_circuit_time): timings = [] sch_copy = list(schedule.items()) prevkey, prevvalue = 0, 0 # Just so that first iteration doesn't throw an error for index, (key, value) in enumerate(list(schedule.items())): if index != 0: prevkey, prevvalue = sch_copy[index - 1] if value == 'snapshot': if (prevvalue == 'correction') & (int(key) == (int(prevkey) + 3)): pass else: timings.append(int(key)/1000) elif value =='correction': timings.append((int(key) + 3)/1000) else: timings.append(int(key)/1000) timings.append((int(key) + 3)/1000) timings.append(total_circuit_time/1000) return timings # Function for extracting positions where corrections were done def correction_positions(corr_positions, correction_avg_fidelity, correction_snapshot_timings): corr_time = [key/1000 for key in corr_positions] corr_fid = [correction_avg_fidelity[correction_snapshot_timings.index(timing)] for timing in corr_time] return corr_time, corr_fid # Function for fitting exponential curve def curve_fitter(x, y, sign=1): popt, pcov = curve_fit(lambda x, b: sign * np.exp(-x/b), x, y) sigma = np.sqrt(np.diag(pcov)) lifetime = round(popt[0], 2) uncertainty = round(sigma[0], 3) return lifetime, uncertainty ### Adjust these parameters ### num_corr = 1 # per ms, number of correction circuits applied additional_snaps = 2 # per ms, number of additional snapshots taken in between each correction circuit noise_only_circ_time = 12 # ms, total duration of noise-only circuit correction_circ_time = 12 # ms, total duration of correction circuit shots = 1000 # Number of times circuit is repeated encoding=['logi0', 'logi1', 'logi_xplus', 'logi_xminus'] # Input 'logi0', 'logi1', 'logi_xplus', 'logi_xminus', 'logi_yplus', or 'logi_yminus' ## ### If you wish to generate the circuit diagram for a particular simulation, uncomment these lines. ### # noise_circuit = error_correction_experiment(encoding[0], 0, shots, 10, noise_only_circ_time, return_circuit=True) # correction_circuit = error_correction_experiment(encoding[0], num_corr, shots, additional_snaps, correction_circ_time, return_circuit=True) # noise_circuit.draw() # correction_circuit.draw() ## For pyplot formatting # For formatting graphs encoding_format = {'logi0': r'$0_L$', 'logi1': r'$1_L$', 'logi_xplus': r'$+_L$', 'logi_xminus':r'$-_L$', 'logi_yplus':r'$+i_L$', 'logi_yminus': r'$-i_L$'} # Colors for plotting colors= ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'] # Labels for logical states logical_label = [r'$\lvert 0_L \rangle = (\lvert 0 \rangle + \lvert 4 \rangle)/\sqrt{2}$', r'$\lvert E_2 \rangle = (\lvert 0 \rangle - \lvert 4 \rangle)/\sqrt{2}$', r'$\lvert 1_L \rangle$'] # Run simulation with and without correction. Disable u_even noise_only_simulation_list = [] correction_simulation_list = [] for i in encoding: noise_only_simulation_list.append(error_correction_experiment(i, 0, shots, additional_snaps, noise_only_circ_time)) correction_simulation_list.append(error_correction_experiment(i, num_corr, shots, additional_snaps, correction_circ_time, identity=True)) ## Fidelity visualisation index = encoding.index('logi1') value = 'logi1' _, noise_only_fid, _, noise_only_snapshot_timings, _ = noise_only_simulation_list[index] _, correction_fid, _, correction_snapshot_timings, corr_position_times = correction_simulation_list[index] noise_only_avg_fid = [round(np.average(cycle), 4) for cycle in noise_only_fid] noise_only_avg_fid_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in noise_only_fid] correction_avg_fid = [round(np.average(cycle), 4) for cycle in correction_fid] correction_avg_fid_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in correction_fid] # Find correction positions x, y = correction_positions(corr_position_times, correction_avg_fid, correction_snapshot_timings) # Fit fidelity data using an exponential decay function noise_only_lifetime, noise_lifetime_uncertainty = curve_fitter(noise_only_snapshot_timings, noise_only_avg_fid) correction_lifetime_perf, correction_lifetime_uncertainty = curve_fitter(x, y) # Round values to 2 decimal places noise_lifetime_uncertainty = round(noise_lifetime_uncertainty, 2) correction_lifetime_uncertainty = round (correction_lifetime_uncertainty, 2) # Plot fidelity data w/ uncertainty plt.figure(figsize=(15,6)) plt.errorbar(noise_only_snapshot_timings, noise_only_avg_fid, yerr=noise_only_avg_fid_error, label=r'No corrections, ' + '\n' + r'$\tau = $' + str(noise_only_lifetime) + r'ms $\pm$' + str(noise_lifetime_uncertainty) + r'ms', marker='o', color='#5BCEFA', capsize=3, ecolor='#2a6278', linestyle='None') plt.errorbar(correction_snapshot_timings, correction_avg_fid, yerr=correction_avg_fid_error, label=str(num_corr) + r' corrections/ms,' + '\n' + r'$\tau = $' + str(correction_lifetime_perf) + r'ms $\pm$' + str(correction_lifetime_uncertainty) + r'ms', marker='o', color='#F5A9B8', capsize=3, ecolor='#9c6b75') # Plot curve fits w/ uncertainty noise_curve_timing = np.linspace(0, noise_only_circ_time, 100) plt.plot(noise_curve_timing, np.exp(-noise_curve_timing/noise_only_lifetime)) plt.fill_between(noise_curve_timing, np.exp(-noise_curve_timing/(noise_only_lifetime + noise_lifetime_uncertainty)), np.exp(-noise_curve_timing/(noise_only_lifetime - noise_lifetime_uncertainty)), color='#5BCEFA', alpha=0.3) corr_curve_timing = np.linspace(0, correction_circ_time, 100) plt.plot(corr_curve_timing, np.exp(-corr_curve_timing/correction_lifetime_perf)) plt.fill_between(corr_curve_timing, np.exp(-corr_curve_timing/(correction_lifetime_perf + correction_lifetime_uncertainty)), np.exp(-corr_curve_timing/(correction_lifetime_perf - correction_lifetime_uncertainty)), color='#F5A9B8', alpha=0.3) # Plot correction positions label = 'Correction \n position' for i in x: plt.axvline(x=i, color='grey', label=label, linestyle="--") label = '' plt.xlabel("Time (ms)", size=20) plt.ylabel("State fidelity, averaged over {} shots".format(shots), size=20) plt.title(r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' state fidelity without error correction and with ' + str(num_corr) + r' correction(s)/ms ($\hat{U}_{\text{odd}}$ only)', size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) plt.legend(loc='upper right', fontsize=20) plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.show() ## Fidelity visualisation for index, value in enumerate(encoding): if value == 'logi1': continue _, noise_only_fid_other, _, noise_only_snapshot_timings, _ = noise_only_simulation_list[index] _, correction_fid_other, _, correction_snapshot_timings, corr_position_times = correction_simulation_list[index] noise_only_avg_fid_other = [round(np.average(cycle), 4) for cycle in noise_only_fid_other] noise_only_avg_fid_error_other = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in noise_only_fid_other] correction_avg_fid_other = [round(np.average(cycle), 4) for cycle in correction_fid_other] correction_avg_fid_error_other = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in correction_fid_other] # Find correction positions x, y = correction_positions(corr_position_times, correction_avg_fid_other, correction_snapshot_timings) # Plot fidelity data w/ uncertainty plt.figure(figsize=(15,6)) plt.errorbar(noise_only_snapshot_timings, noise_only_avg_fid_other, yerr=noise_only_avg_fid_error_other, label=r'No corrections', marker='o', color='#5BCEFA', capsize=3, ecolor='#2a6278') plt.errorbar(correction_snapshot_timings, correction_avg_fid_other, yerr=correction_avg_fid_error_other, label=str(num_corr) + r' corrections/ms', marker='o', color='#F5A9B8', capsize=3, ecolor='#9c6b75') # Plot an actual exponential decay as comparison noise_curve_timing = np.linspace(0, noise_only_circ_time, 100) plt.plot(noise_curve_timing, np.exp(-noise_curve_timing), label='Exponential curve') # Plot correction positions label = 'Correction \n position' for i in x: plt.axvline(x=i, color='grey', label=label, linestyle="--") label = '' plt.xlabel("Time (ms)", size=20) plt.ylabel("State fidelity, averaged over {} shots".format(shots), size=20) plt.title(r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' state fidelity without error correction and with ' + str(num_corr) + r' correction(s)/ms ($\hat{U}_{\text{odd}}$ only)', size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) plt.legend(loc='upper right', fontsize=20) plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.show() # Compute exponential fit across a variety of corrections/ms for |1_L> only value = 'logi1' _num_corr = [1, 2, 5, 10] _correction_circ_time = [12 for _ in _num_corr] #[(i + 1) * 8 for i in range(5)] _additional_snaps = 0 _shots = 1000 _encoding='logi1' # Colors for plotting colors= ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'] # Plot noise_only trial as simulated previously plt.figure(figsize=(15,6)) plt.scatter(noise_only_snapshot_timings, noise_only_avg_fid, marker='o', color='#1f77b4', zorder=3, alpha=0.6, linestyle='None', s= 50) plt.plot(noise_curve_timing, np.exp(-noise_curve_timing/noise_only_lifetime), label=r'0 corrections, ' + '\n' + r'$\tau$ = ' + str(noise_only_lifetime) + r'ms $\pm$' + str(noise_lifetime_uncertainty) + r'ms', color='#1f77b4') # Plot all other correction trials w/ lifetimes for index, _corrections in enumerate(_num_corr): # print(corrections, "Run starting") # Debug _, _correction_fid, _, _correction_snapshot_timings, _corr_position_times = error_correction_experiment(_encoding, _corrections, _shots, _additional_snaps, _correction_circ_time[index], identity=True) _correction_avg_fid = [round(np.average(cycle), 4) for cycle in _correction_fid] _x, _y = correction_positions(_corr_position_times, _correction_avg_fid, _correction_snapshot_timings) _lifetime, _lifetime_uncertainty = curve_fitter(_x, _y) _curve_timing = np.linspace(0, _correction_circ_time[index], 100) if _additional_snaps != 0: plt.plot(correction_snapshot_timings, correction_avg_fid, marker='o', color=colors[index + 1], alpha=0.2) plt.plot(_curve_timing, np.exp(- _curve_timing/_lifetime), label=str(_num_corr[index]) + r' corrections/ms, ' + '\n' + r'$\tau = $' + str(_lifetime) + r'ms $\pm$' + str(_lifetime_uncertainty) + r'ms', color=colors[index + 1]) plt.scatter(_x, _y, marker='s', color=colors[index + 1], zorder=3, alpha=0.6, linestyle='None', s= 50) plt.xlabel("Time (ms)", size=20) plt.ylabel("State fidelity, averaged over {} shots".format(shots), size=20) plt.title(r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + r' state fidelity for varying circuit parameters ($\hat{U}_{\text{odd}}$ only)', size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) plt.legend(fontsize=20, bbox_to_anchor=(1.32, 0.5), loc='right') plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.show() ### Adjust these parameters ### run = [(14, 0), (1, 1), (3, 4), (0, 12)] # Choose single shot to graph. Tuples are formatted as (noise_only_shot, correction_shot). ## # Plot photon probability for all initial encodings for index, value in enumerate(encoding): _, _, noise_only_prob_tuple, noise_only_snapshot_timings, _ = noise_only_simulation_list[index] _, _, correction_prob_tuple, correction_snapshot_timings, corr_position_times = correction_simulation_list[index] # Fock state probability visualization, single shot noise_only_prob, noise_only_prob_logical = noise_only_prob_tuple correction_prob, correction_prob_logical = correction_prob_tuple # Runs to plot run_noise, run_corr = run[index] noise_only_fock_prob = [i[run_noise] for i in noise_only_prob] correction_fock_prob = [i[run_corr] for i in correction_prob] noise_only_fock_prob_logical = [i[run_noise] for i in noise_only_prob_logical] correction_fock_prob_logical = [i[run_corr] for i in correction_prob_logical] # Ignore trajectories of Fock states with prob below a certain value. prob_truncation = 0.005 # Plot both graph in single image plt.figure(figsize=(15,10)) plt.suptitle('Trajectories of Fock state probability simulations with ' + r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' encoding', size=30) # plt.suptitle('No correction and ' + str(num_corr) + ' correction simulation, with ' +r'$\lvert$' + str(encoding_format.get(encoding)) + r'$\rangle$' + ' encoding', size=20) ## 1a. Noise only circuit plot (photon number) plt.subplot(2, 1, 1) plt.subplot(2, 1, 1).xaxis.set_tick_params(labelsize=20) plt.subplot(2, 1, 1).yaxis.set_tick_params(labelsize=20) n = len(noise_only_fock_prob[0]) # n, = noise_only_avg_prob[0].shape for index in range(n): trajectory = [value[index] for value in noise_only_fock_prob] # uncert = [value[index] for value in noise_only_fock_prob_error] if all(i <= prob_truncation for i in trajectory): continue state = index # Rename state |2> = |1_L> if index == 2: state=logical_label[2] plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3) else: plt.plot(noise_only_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index]) ## 1b. Noise only circuit plot (logical state) m = len(noise_only_fock_prob_logical[0]) for index in range(m): trajectory = [value[index] for value in noise_only_fock_prob_logical] if all(i <= prob_truncation for i in trajectory): continue plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3) # Subplot 1 formatting #plt.ylabel("Probability of measuring Fock state, averaged over over {} shots".format(shots)) plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20) plt.title(r"Without error correction", size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) ## 2a. Correction circuit plot (photon number) plt.subplot(2, 1, 2, sharex = plt.subplot(2, 1, 1)) plt.subplot(2, 1, 2).xaxis.set_tick_params(labelsize=20) plt.subplot(2, 1, 2).yaxis.set_tick_params(labelsize=20) n = len(correction_fock_prob[0]) # n, = correction_avg_prob[0].shape for index in range(n): trajectory = [value[index] for value in correction_fock_prob] # print(round(np.max(trajectory),4), round(np.median(trajectory),4), round(np.ptp(trajectory),4), index) ### debug # uncert = [value[index] for value in correction_fock_prob_error] if all(i <= prob_truncation for i in trajectory): continue state = index # Rename state |2> = |1_L> if index == 2: state=logical_label[2] plt.plot(correction_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3) else: plt.plot(correction_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index]) ## 1b. Correction circuit plot (logical state) m = len(correction_fock_prob_logical[0]) for index in range(m): trajectory = [value[index] for value in correction_fock_prob_logical] if all(i <= prob_truncation for i in trajectory): continue plt.plot(correction_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3) # Plot correction positions x, y = correction_positions(corr_position_times, correction_fock_prob, correction_snapshot_timings) label = 'Correction \n position' for i in x: plt.axvline(x=i, color='grey', label=label, linestyle="--") label = '' # Subplot 2 formatting plt.xlabel("Time (ms)", size=20) #plt.ylabel("Probability of measuring Fock state, averaged over {} shots".format(shots)) plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20) plt.title("With " + str(num_corr) + r" correction(s)/ms ($\hat{U}_{\text{odd}}$ only)", size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) # Remove duplicate labels leg1 = {l:h for h,l in zip(*plt.subplot(2, 1, 1).get_legend_handles_labels())} leg2 = {l:h for h,l in zip(*plt.subplot(2, 1, 2).get_legend_handles_labels())} plt.figlegend(*[*zip(*{**leg1, **leg2}.items())][::-1], bbox_to_anchor=(1.15, 0.5), loc = 'right', fontsize=20) plt.show() # Run simulation with and without correction. Enable u_even noise_only_simulation_list = [] correction_simulation_list = [] for i in encoding: noise_only_simulation_list.append(error_correction_experiment(i, 0, shots, additional_snaps, noise_only_circ_time)) correction_simulation_list.append(error_correction_experiment(i, num_corr, shots, additional_snaps, correction_circ_time)) ## Fidelity visualisation index = encoding.index('logi1') value = 'logi1' _, noise_only_fid, _, noise_only_snapshot_timings, _ = noise_only_simulation_list[index] _, correction_fid, _, correction_snapshot_timings, corr_position_times = correction_simulation_list[index] noise_only_avg_fid = [round(np.average(cycle), 4) for cycle in noise_only_fid] noise_only_avg_fid_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in noise_only_fid] correction_avg_fid = [round(np.average(cycle), 4) for cycle in correction_fid] correction_avg_fid_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in correction_fid] # Find correction positions x, y = correction_positions(corr_position_times, correction_avg_fid, correction_snapshot_timings) # Plot fidelity data w/ uncertainty plt.figure(figsize=(15,6)) plt.errorbar(noise_only_snapshot_timings, noise_only_avg_fid, yerr=noise_only_avg_fid_error, label=r'No corrections', marker='o', color='#5BCEFA', capsize=3, ecolor='#2a6278') plt.errorbar(correction_snapshot_timings, correction_avg_fid, yerr=correction_avg_fid_error, label=str(num_corr) + r' corrections/ms', marker='o', color='#F5A9B8', capsize=3, ecolor='#9c6b75') # Plot correction positions label = 'Correction \n position' for i in x: plt.axvline(x=i, color='grey', label=label, linestyle="--") label = '' # Plot previous logi1 lifetime plt.plot(noise_curve_timing, np.exp(-noise_curve_timing/correction_lifetime_perf), label=r'Simulation 1 result' + '\n' + r'$\tau = $' + str(correction_lifetime_perf) + r'ms') plt.xlabel("Time (ms)", size=20) plt.ylabel("State fidelity, averaged over {} shots".format(shots), size=20) plt.title(r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' state fidelity without error correction and with ' + str(num_corr) + r' correction(s)/ms ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)', size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) plt.legend(loc='upper right', fontsize=20) plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.show() ## Fidelity visualisation for index, value in enumerate(encoding): if value == 'logi1': continue _, noise_only_fid_other, _, noise_only_snapshot_timings, _ = noise_only_simulation_list[index] _, correction_fid_other, _, correction_snapshot_timings, corr_position_times = correction_simulation_list[index] noise_only_avg_fid_other = [round(np.average(cycle), 4) for cycle in noise_only_fid_other] noise_only_avg_fid_error_other = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in noise_only_fid_other] correction_avg_fid_other = [round(np.average(cycle), 4) for cycle in correction_fid_other] correction_avg_fid_error_other = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in correction_fid_other] # Find correction positions x, y = correction_positions(corr_position_times, correction_avg_fid_other, correction_snapshot_timings) # Plot fidelity data w/ uncertainty plt.figure(figsize=(15,6)) plt.errorbar(noise_only_snapshot_timings, noise_only_avg_fid_other, yerr=noise_only_avg_fid_error_other, label=r'No corrections', marker='o', color='#5BCEFA', capsize=3, ecolor='#2a6278') plt.errorbar(correction_snapshot_timings, correction_avg_fid_other, yerr=correction_avg_fid_error_other, label=str(num_corr) + r' corrections/ms', marker='o', color='#F5A9B8', capsize=3, ecolor='#9c6b75') # Plot an actual exponential decay as comparison noise_curve_timing = np.linspace(0, noise_only_circ_time, 100) plt.plot(noise_curve_timing, np.exp(-noise_curve_timing), label='Exponential curve') # Plot correction positions label = 'Correction \n position' for i in x: plt.axvline(x=i, color='grey', label=label, linestyle="--") label = '' plt.xlabel("Time (ms)", size=20) plt.ylabel("State fidelity, averaged over {} shots".format(shots), size=20) plt.title(r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' state fidelity without error correction and with ' + str(num_corr) + r' correction(s)/ms ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)', size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) plt.legend(loc='upper right', fontsize=20) plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.show() ### Adjust these parameters ### run = [(41, 24), (3, 3), _, _] # Choose single shot to graph. Tuples are formatted as (noise_only_shot, correction_shot). ## # Plot photon probability for all initial encodings for index, value in enumerate(encoding): if index not in [0, 1]: continue _, _, noise_only_prob_tuple, noise_only_snapshot_timings, _ = noise_only_simulation_list[index] _, _, correction_prob_tuple, correction_snapshot_timings, corr_position_times = correction_simulation_list[index] # Fock state probability visualization, single shot noise_only_prob, noise_only_prob_logical = noise_only_prob_tuple correction_prob, correction_prob_logical = correction_prob_tuple # Runs to plot run_noise, run_corr = run[index] noise_only_fock_prob = [i[run_noise] for i in noise_only_prob] correction_fock_prob = [i[run_corr] for i in correction_prob] noise_only_fock_prob_logical = [i[run_noise] for i in noise_only_prob_logical] correction_fock_prob_logical = [i[run_corr] for i in correction_prob_logical] # Ignore trajectories of Fock states with prob below a certain value. prob_truncation = 0.005 # Plot both graph in single image plt.figure(figsize=(15,10)) plt.suptitle('Trajectories of Fock state probability simulations with ' + r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' encoding', size=30) # plt.suptitle('No correction and ' + str(num_corr) + ' correction simulation, with ' +r'$\lvert$' + str(encoding_format.get(encoding)) + r'$\rangle$' + ' encoding', size=20) ## 1a. Noise only circuit plot (photon number) plt.subplot(2, 1, 1) plt.subplot(2, 1, 1).xaxis.set_tick_params(labelsize=20) plt.subplot(2, 1, 1).yaxis.set_tick_params(labelsize=20) n = len(noise_only_fock_prob[0]) # n, = noise_only_avg_prob[0].shape for index in range(n): trajectory = [value[index] for value in noise_only_fock_prob] # uncert = [value[index] for value in noise_only_fock_prob_error] if all(i <= prob_truncation for i in trajectory): continue state = index # Rename state |2> = |1_L> if index == 2: state=logical_label[2] plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3) else: plt.plot(noise_only_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index]) ## 1b. Noise only circuit plot (logical state) m = len(noise_only_fock_prob_logical[0]) for index in range(m): trajectory = [value[index] for value in noise_only_fock_prob_logical] if all(i <= prob_truncation for i in trajectory): continue plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3) # Subplot 1 formatting #plt.ylabel("Probability of measuring Fock state, averaged over over {} shots".format(shots)) plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20) plt.title(r"Without error correction", size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) ## 2a. Correction circuit plot (photon number) plt.subplot(2, 1, 2, sharex = plt.subplot(2, 1, 1)) plt.subplot(2, 1, 2).xaxis.set_tick_params(labelsize=20) plt.subplot(2, 1, 2).yaxis.set_tick_params(labelsize=20) n = len(correction_fock_prob[0]) # n, = correction_avg_prob[0].shape for index in range(n): trajectory = [value[index] for value in correction_fock_prob] # print(round(np.max(trajectory),4), round(np.median(trajectory),4), round(np.ptp(trajectory),4), index) ### debug # uncert = [value[index] for value in correction_fock_prob_error] if all(i <= prob_truncation for i in trajectory): continue state = index # Rename state |2> = |1_L> if index == 2: state=logical_label[2] plt.plot(correction_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3) else: plt.plot(correction_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index]) ## 1b. Correction circuit plot (logical state) m = len(correction_fock_prob_logical[0]) for index in range(m): trajectory = [value[index] for value in correction_fock_prob_logical] if all(i <= prob_truncation for i in trajectory): continue plt.plot(correction_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3) # Plot correction positions x, y = correction_positions(corr_position_times, correction_fock_prob, correction_snapshot_timings) label = 'Correction \n position' for i in x: plt.axvline(x=i, color='grey', label=label, linestyle="--") label = '' # Subplot 2 formatting plt.xlabel("Time (ms)", size=20) #plt.ylabel("Probability of measuring Fock state, averaged over {} shots".format(shots)) plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20) plt.title("With " + str(num_corr) + r" correction(s)/ms ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)", size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) # Remove duplicate labels leg1 = {l:h for h,l in zip(*plt.subplot(2, 1, 1).get_legend_handles_labels())} leg2 = {l:h for h,l in zip(*plt.subplot(2, 1, 2).get_legend_handles_labels())} plt.figlegend(*[*zip(*{**leg1, **leg2}.items())][::-1], bbox_to_anchor=(1.15, 0.5), loc = 'right', fontsize=20) plt.show() ### Adjust these parameters ### run = [_, _, (0, 3), (2, 8)] # Choose single shot to graph. Tuples are formatted as (noise_only_shot, correction_shot). ## # Plot photon probability for all initial encodings for index, value in enumerate(encoding): if index not in [2, 3]: continue _, _, noise_only_prob_tuple, noise_only_snapshot_timings, _ = noise_only_simulation_list[index] _, _, correction_prob_tuple, correction_snapshot_timings, corr_position_times = correction_simulation_list[index] # Fock state probability visualization, single shot noise_only_prob, noise_only_prob_logical = noise_only_prob_tuple correction_prob, correction_prob_logical = correction_prob_tuple # Runs to plot run_noise, run_corr = run[index] noise_only_fock_prob = [i[run_noise] for i in noise_only_prob] correction_fock_prob = [i[run_corr] for i in correction_prob] noise_only_fock_prob_logical = [i[run_noise] for i in noise_only_prob_logical] correction_fock_prob_logical = [i[run_corr] for i in correction_prob_logical] # Ignore trajectories of Fock states with prob below a certain value. prob_truncation = 0.005 # Plot both graph in single image plt.figure(figsize=(15,10)) plt.suptitle('Trajectories of Fock state probability simulations with ' + r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + ' encoding', size=30) # plt.suptitle('No correction and ' + str(num_corr) + ' correction simulation, with ' +r'$\lvert$' + str(encoding_format.get(encoding)) + r'$\rangle$' + ' encoding', size=20) ## 1a. Noise only circuit plot (photon number) plt.subplot(2, 1, 1) plt.subplot(2, 1, 1).xaxis.set_tick_params(labelsize=20) plt.subplot(2, 1, 1).yaxis.set_tick_params(labelsize=20) n = len(noise_only_fock_prob[0]) # n, = noise_only_avg_prob[0].shape for index in range(n): trajectory = [value[index] for value in noise_only_fock_prob] # uncert = [value[index] for value in noise_only_fock_prob_error] if all(i <= prob_truncation for i in trajectory): continue state = index # Rename state |2> = |1_L> if index == 2: state=logical_label[2] plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3) else: plt.plot(noise_only_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index]) ## 1b. Noise only circuit plot (logical state) m = len(noise_only_fock_prob_logical[0]) for index in range(m): trajectory = [value[index] for value in noise_only_fock_prob_logical] if all(i <= prob_truncation for i in trajectory): continue plt.plot(noise_only_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3) # Subplot 1 formatting #plt.ylabel("Probability of measuring Fock state, averaged over over {} shots".format(shots)) plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20) plt.title(r"Without error correction", size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) ## 2a. Correction circuit plot (photon number) plt.subplot(2, 1, 2, sharex = plt.subplot(2, 1, 1)) plt.subplot(2, 1, 2).xaxis.set_tick_params(labelsize=20) plt.subplot(2, 1, 2).yaxis.set_tick_params(labelsize=20) n = len(correction_fock_prob[0]) # n, = correction_avg_prob[0].shape for index in range(n): trajectory = [value[index] for value in correction_fock_prob] # print(round(np.max(trajectory),4), round(np.median(trajectory),4), round(np.ptp(trajectory),4), index) ### debug # uncert = [value[index] for value in correction_fock_prob_error] if all(i <= prob_truncation for i in trajectory): continue state = index # Rename state |2> = |1_L> if index == 2: state=logical_label[2] plt.plot(correction_snapshot_timings, trajectory, marker='s', label=r'$\lvert 2 \rangle =$ ' + str(state), color=colors[index], markersize = 8, linewidth = 3) else: plt.plot(correction_snapshot_timings, trajectory, marker='o', label=r'$\lvert$' + str(state) + r'$\rangle$', color=colors[index]) ## 1b. Correction circuit plot (logical state) m = len(correction_fock_prob_logical[0]) for index in range(m): trajectory = [value[index] for value in correction_fock_prob_logical] if all(i <= prob_truncation for i in trajectory): continue plt.plot(correction_snapshot_timings, trajectory, marker='s', label=str(logical_label[index]), color=colors[index+8], markersize = 8, linewidth = 3) # Plot correction positions x, y = correction_positions(corr_position_times, correction_fock_prob, correction_snapshot_timings) label = 'Correction \n position' for i in x: plt.axvline(x=i, color='grey', label=label, linestyle="--") label = '' # Subplot 2 formatting plt.xlabel("Time (ms)", size=20) #plt.ylabel("Probability of measuring Fock state, averaged over {} shots".format(shots)) plt.ylabel(r'$P(\lvert \psi \rangle$)', size=20) plt.title("With " + str(num_corr) + r" correction(s)/ms ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)", size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) # Remove duplicate labels leg1 = {l:h for h,l in zip(*plt.subplot(2, 1, 1).get_legend_handles_labels())} leg2 = {l:h for h,l in zip(*plt.subplot(2, 1, 2).get_legend_handles_labels())} plt.figlegend(*[*zip(*{**leg1, **leg2}.items())][::-1], bbox_to_anchor=(1.15, 0.5), loc = 'right', fontsize=20) plt.show() ### Adjust these parameters ### num_corr = 2 # per ms, number of correction circuits applied additional_snaps = 0 # per ms, number of additional snapshots taken in between each correction circuit noise_only_circ_time = 2 # ms, total duration of noise-only circuit correction_circ_time = 5 # ms, total duration of correction circuit shots = 1000 # Number of times circuit is repeated encoding=['logi_xplus', 'logi_yplus', 'logi1'] # Input 'logi0', 'logi1', 'logi_xplus', 'logi_xminus', 'logi_yplus', or 'logi_yminus' ## # Run simulation with and without correction. Enable u_even noise_only_simulation_list = [] correction_simulation_list = [] for i in encoding: noise_only_simulation_list.append(error_correction_experiment(i, 0, shots, 2, noise_only_circ_time)) correction_simulation_list.append(error_correction_experiment(i, num_corr, shots, additional_snaps, correction_circ_time)) # Backup chunk ## Pauli Expectation Value visualisation colors= ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'] label = 'Correction \n position' plt.figure(figsize=(15,6)) # Plot with correction for index, value in enumerate(encoding): if value in ['logi0', 'logi_xplus', 'logi_yplus']: sign = 1 else: sign = -1 # Plot without correction (noise_only_pauli_expectation, _), _, _, noise_only_snapshot_timings, _ = noise_only_simulation_list[index] noise_only_expectation_avg = [np.round(np.average(cycle), 4) for cycle in noise_only_pauli_expectation] noise_only_expectation_avg_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in noise_only_pauli_expectation] noise_only_lifetime, noise_lifetime_uncertainty = curve_fitter(noise_only_snapshot_timings, noise_only_expectation_avg, sign) plt.errorbar(noise_only_snapshot_timings, noise_only_expectation_avg, yerr=noise_only_expectation_avg_error, label=r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + r' no corrections,' + '\n' + r'$\tau$ = ' + str(noise_only_lifetime) + r'ms $\pm$' + str(round(noise_lifetime_uncertainty, 2)) + r'ms', marker='o', color=colors[-index - 1], capsize=3, ecolor='#2a6278') noise_curve_timing = np.linspace(0, noise_only_circ_time, 100) plt.plot(noise_curve_timing, sign * np.exp(-noise_curve_timing/noise_only_lifetime), alpha=0.5, color=colors[-index - 1]) # Plot with correction (correction_pauli_expectation, _), _, _, correction_snapshot_timings, corr_position_times = correction_simulation_list[index] correction_expectation_avg = [np.round(np.average(cycle), 4) for cycle in correction_pauli_expectation] correction_expectation_avg_error = [round(np.std(cycle)/np.sqrt(shots), 4) for cycle in correction_pauli_expectation] correction_lifetime, correction_lifetime_uncertainty = curve_fitter(correction_snapshot_timings, correction_expectation_avg, sign) plt.errorbar(correction_snapshot_timings, correction_expectation_avg, yerr=correction_expectation_avg_error, label=r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$ ' + str(num_corr) + r' corrections/ms,' + '\n' + r'$\tau$ = ' + str(correction_lifetime) + r'ms $\pm$' + str(round(correction_lifetime_uncertainty, 2)) + r'ms', marker='o', color=colors[index], capsize=3, ecolor='#9c6b75') corr_curve_timing = np.linspace(0, correction_circ_time, 100) plt.plot(corr_curve_timing, sign * np.exp(-corr_curve_timing/correction_lifetime), alpha=0.5, color=colors[index]) # Plot error correction positions x, y = correction_positions(corr_position_times, correction_pauli_expectation, correction_snapshot_timings) for i in x: plt.axvline(x=i, color='grey', label=label, linestyle="--") label = '' plt.xlabel("Time (ms)", size=20) plt.ylabel("Pauli expectation, averaged over {} shots".format(shots), size=20) plt.title(r'Pauli expectation for varying logical states ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)', size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) plt.legend(fontsize=20, bbox_to_anchor=(1.35, 0.5), loc='right') plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.show() ## All six states on separate charts encoding = ['logi_xplus', 'logi_xminus', 'logi_yplus', 'logi_yminus', 'logi0', 'logi1'] sign = [1, -1, 1, -1, 1, -1] for index, i in enumerate(encoding): noise_only_pauli_tuple, noise_only_fid, noise_only_prob, noise_only_snapshot_timings, _ = error_correction_experiment(i, 0, shots, 3, noise_only_circ_time) correction_pauli_tuple, correction_fid, correction_prob, correction_snapshot_timings, corr_position_times = error_correction_experiment(i, num_corr, shots, additional_snaps, correction_circ_time) ## Pauli operator decay visualization noise_only_pauli_expectation, _ = noise_only_pauli_tuple #[[matrix.real for matrix in cycle] for cycle in noise_only_pauli] correction_pauli_expectation, _ = correction_pauli_tuple # Compute average expectation and prob across all shots noise_only_expectation_avg = [np.round(np.average(cycle), 4) for cycle in noise_only_pauli_expectation] correction_expectation_avg = [np.round(np.average(cycle), 4) for cycle in correction_pauli_expectation] ## Expectation plots # Fit expectation data using an exponential decay function noise_only_lifetime, noise_lifetime_uncertainty = curve_fitter(noise_only_snapshot_timings, noise_only_expectation_avg, sign[index]) correction_lifetime, correction_lifetime_uncertainty = curve_fitter(correction_snapshot_timings, correction_expectation_avg, sign[index]) # Plot expectation data plt.figure(figsize=(15,6)) plt.plot(noise_only_snapshot_timings, noise_only_expectation_avg, label=r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$' + r' no corrections,' + '\n' + r'$\tau$ = ' + str(noise_only_lifetime) + r'ms $\pm$' + str(round(noise_lifetime_uncertainty, 2)) + r'ms', marker='o', color='#5BCEFA') plt.plot(correction_snapshot_timings, correction_expectation_avg, label=r'$\lvert$' + str(encoding_format.get(value)) + r'$\rangle$ ' + str(num_corr) + r' corrections/ms,' + '\n' + r'$\tau$ = ' + str(correction_lifetime) + r'ms $\pm$' + str(round(correction_lifetime_uncertainty, 2)) + r'ms', marker='o', color='#F5A9B8') # Plot expectation data curve fits noise_curve_timing = np.linspace(0, noise_only_circ_time, 100) plt.plot(noise_curve_timing, sign[index] * np.exp(-noise_curve_timing/noise_only_lifetime)) corr_curve_timing = np.linspace(0, correction_circ_time, 100) plt.plot(corr_curve_timing, sign[index] * np.exp(-corr_curve_timing/correction_lifetime)) # Plot correction positions x, y = correction_positions(corr_position_times, correction_expectation_avg, correction_snapshot_timings) label = 'Correction \n position' for i in x: plt.axvline(x=i, color='grey', label=label, linestyle="--") label = '' plt.xlabel("Time (ms)", size=20) plt.ylabel("Pauli expectation, averaged over {} shots".format(shots), size=20) plt.title(r'Pauli expectation for varying logical states ($\hat{U}_{\text{odd}}$ and $\hat{U}_{\text{even}}$)', size=20) plt.grid(color = 'lightgrey', linestyle = 'dashed', linewidth = 0.5) plt.legend(fontsize=20, bbox_to_anchor=(1.35, 0.5), loc='right') plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.show()
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import qiskit import numpy as np qmr = c2qa.QumodeRegister( num_qumodes=1, num_qubits_per_qumode=4 ) circuit = c2qa.CVCircuit(qmr) circuit.cv_initialize(0, qmr[0]) circuit.cv_initialize([1/np.sqrt(2),1/np.sqrt(2)], qmr[0]) qmr = c2qa.QumodeRegister( num_qumodes=1, num_qubits_per_qumode=4 ) qr = qiskit.QuantumRegister( size=1 ) cr = qiskit.ClassicalRegister( size = 1 ) circuit = c2qa.CVCircuit(qmr, qr, cr)
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import numpy as np import qiskit import qiskit.visualization qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=3) #create a qumoderegister with one qumode circuit = c2qa.CVCircuit(qmr) #create a CV circuit circuit.cv_initialize(4, qmr) #initialize the qumode in the state |4> #simulate and plot the wigner function (more about this in wigner_distribution.ipynb!) state,_,_ = c2qa.wigner.simulate(circuit) plot = c2qa.wigner.plot_wigner(circuit, state) #5 rings correspond to 4 quanta #try out different numbers and plot the wigner functions! #Intialize a qumode register. To map the number of quanta onto qubit states, the number of #classical bits needs to equal the number of qubits representing the qumode. num_qubits = 4 qureg = c2qa.QumodeRegister(1, num_qubits_per_qumode=num_qubits) creg = qiskit.ClassicalRegister(num_qubits) #Initialize circuit as a cuperposition of |0> and |2> circuit = c2qa.CVCircuit(qureg, creg, probe_measure=True) circuit.cv_initialize(1/np.sqrt(2)*np.array([1,0,1]), qureg[0]) #Use the cv_measure method to map the Fock number onto creg! circuit.cv_measure([qureg[0]], creg) #Simulation can use the Aer simulator or the build-in simulate method _, result, fock_counts = c2qa.util.simulate(circuit) #Convert the counts dictionary from binary to base-10 and plot histogram qiskit.visualization.plot_histogram(fock_counts)
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa from IPython.display import HTML import qiskit import qiskit.visualization from matplotlib import pyplot as plt import numpy as np n = 4 qreg = c2qa.QumodeRegister(1, num_qubits_per_qumode=n) creg = qiskit.ClassicalRegister(n) circuit = c2qa.CVCircuit(qreg, creg, probe_measure=True) #creating a coherent state with λ = (1+1i) using the displacement operator. #coherent states are sometimes referred to as "displaced ground states" Lambda = 1+1j circuit.cv_d(Lambda, qreg[0]) state, _, _ = c2qa.util.simulate(circuit) c2qa.wigner.plot_wigner(circuit, state) #The coherent state is displaced along the x axis by sqrt(2)*Re(λ), #and on the y axis by sqrt(2)*Im(λ) def measure_overlap(alpha1, alpha2): qreg = c2qa.QumodeRegister(1, num_qubits_per_qumode=5) circuit = c2qa.CVCircuit(qreg) circuit.cv_d(alpha1, qreg[0]) state1, _, _ = c2qa.util.simulate(circuit) circuit.clear() circuit.cv_d(alpha2, qreg[0]) state2, _, _ = c2qa.util.simulate(circuit) return state1.inner(state2) ds = np.linspace(0,4,10) overlaps = [] for d in ds: overlaps.append(measure_overlap(d/2, -d/2)) plt.plot(ds, overlaps, linestyle = "None", marker = "o") xlist = np.linspace(0,4,100) plt.plot(xlist, np.exp(-(xlist)**2/2)) qr = qiskit.QuantumRegister(1) qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=4) circuit = c2qa.CVCircuit(qmr, qr) animate_steps = 10 t0 = 0 tf = 1 osc_frequency = 6 #6 GHz oscillator #prepare initial state circuit.cv_d(1, qmr[0]) stepsize = (tf-t0)/animate_steps for t in range(animate_steps): circuit.cv_r(-osc_frequency*(stepsize), qmr[0]) anim = c2qa.animate.animate_wigner(circuit, qubit=qr[0], animation_segments=1); HTML(anim.to_html5_video())
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import qiskit import numpy as np from scipy.stats.contingency import margins from matplotlib import pyplot as plt qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode = 4) circuit = c2qa.CVCircuit(qmr) circuit.cv_initialize(5, qmr[0]) state, _, _ = c2qa.util.simulate(circuit) c2qa.wigner.plot_wigner(circuit, state) circuit.cv_initialize(1/np.sqrt(2)*np.array([1,0,0,0,1]), qmr[0]) state, _, _ = c2qa.util.simulate(circuit) c2qa.wigner.plot_wigner(circuit, state) qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode = 6) qbr = qiskit.QuantumRegister(1) cr = qiskit.ClassicalRegister(1) circuit = c2qa.CVCircuit(qmr, qbr, cr) circuit.initialize([1,0], qbr[0]) circuit.cv_initialize(0, qmr[0]) alpha = 2 circuit.h(qbr[0]) circuit.cv_c_d(alpha, qmr[0], qbr[0]) circuit.h(qbr[0]) circuit.measure(qbr, cr) state, _, _ = c2qa.util.simulate(circuit) c2qa.wigner.plot_wigner(circuit, state) #set the number of qubits for simulation. Try setting this to 4 and observe the result! n = 7 qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=n) circuit = c2qa.CVCircuit(qmr) #Parameter of the coherent state alpha = 1-1j #Prepare the coherent state by displacing the vacuum circuit.cv_d(alpha, qmr[0]) #Simulate the circuit state, _, _ = c2qa.util.simulate(circuit) #Get the wigner distribution in units with hbar=1 ax_min = -6 ax_max = 6 steps = 200 w = c2qa.wigner.wigner(state, axes_max= ax_max, axes_min= ax_min, axes_steps = steps) #Compute the marginals x_dist, y_dist = margins(w.T) #normalize the distributions x_dist *= (ax_max-ax_min)/200 y_dist *= (ax_max-ax_min)/200 #This cell is mostly plotting fig = plt.figure(figsize=(6,6)) gs = fig.add_gridspec(2, 2, width_ratios=(3, 1), height_ratios=(1, 3), left=0.1, right=0.9, bottom=0.1, top=0.9, wspace=0.05, hspace=0.05) ax = fig.add_subplot(gs[1,0]) ax_x = fig.add_subplot(gs[0,0]) ax_y = fig.add_subplot(gs[1,1]) absmax = max(np.max(w), np.abs(np.min(w))) color_levels = np.linspace(-absmax, absmax, 100) #Plot the wigner function of the coherent state in the main panel with a colormap xaxis = np.linspace(ax_min, ax_max, steps) yaxis = np.linspace(ax_min, ax_max, steps) cont = ax.contourf(xaxis, yaxis, w, color_levels, cmap = "RdBu_r") #compute the expected means and variance of the two distributions mux = np.sqrt(2)*np.real(alpha) muy = np.sqrt(2)*np.imag(alpha) sigma = .5 #plot the distributions against the (normalized) marginals of the wigner function ax_x.plot(xaxis, x_dist, label = r"$|\psi_\alpha(x)|^2$", c= "b") ax_x.plot(xaxis, 1/np.sqrt(2*np.pi*sigma)*np.exp(-(xaxis-mux)**2/(2*sigma)), c ="k", linestyle = "--", label="pred.") ax_y.plot(y_dist.T, yaxis, label = r"$|\phi_\alpha(p)|^2$", c = "r") ax_y.plot(1/np.sqrt(2*np.pi*sigma)*np.exp(-(yaxis-muy)**2/(2*sigma)), yaxis, c="k", linestyle = "--", label = "pred.") ax.set(xlabel=r"$\hat x$", ylabel=r"$\hat p$") ax_x.legend() ax_y.legend() ax_x.set_xticklabels([]); ax_y.set_yticklabels([]);
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import numpy as np import qiskit import qiskit.visualization import qiskit_aer from matplotlib import pyplot as plt from IPython.display import HTML #setup registers qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode = 6) qbr = qiskit.QuantumRegister(1) cr = qiskit.ClassicalRegister(1) #convenient labeling qbit = qbr[0] qumode = qmr[0] #The circuit is initalized to |0>|0> by default circuit = c2qa.CVCircuit(qmr, qbr, cr) #put the qubit into a superposition and then execute a controlled displacement of the cavity alpha = 2 circuit.h(qbr[0]) circuit.cv_c_d(alpha, qmr[0], qbr[0]) #apply a rotation around an angle pi/4 theta = np.pi/4 circuit.cv_r(theta, qmr[0]) #measure qubit in x basis to collapse into even or odd cat state circuit.measure_x(qbr, cr) #simulate and plot state, _, _ = c2qa.util.simulate(circuit) c2qa.wigner.plot_wigner(circuit, state) #the resulting plot is a cat state that is rotated 45 degrees circuit.clear() #reset #Initialize Fock state and displace by alpha alpha = 2 circuit.cv_initialize(3, qmr[0]) circuit.cv_d(alpha, qmr[0]) #Simulate and plot state, _, _ = c2qa.util.simulate(circuit) c2qa.wigner.plot_wigner(circuit, state) #Resulting state is a displaced Fock state circuit.clear() s = 1 circuit.cv_initialize(0, qmr[0]) circuit.cv_sq(s, qmr[0]) state, _, _ = c2qa.util.simulate(circuit) #the resulting plot is a coherent state which is squeezed in the position quadrature c2qa.wigner.plot_wigner(circuit, state) circuit.data.pop(1) #plot a momentum-squeezed state for comparison circuit.cv_sq(-s, qmr[0]) state, _, _ = c2qa.util.simulate(circuit) c2qa.wigner.plot_wigner(circuit, state) qmr = c2qa.QumodeRegister(2, num_qubits_per_qumode = 3) qbr = qiskit.QuantumRegister(12) circuit = c2qa.CVCircuit(qmr, qbr) circuit.cv_sq2(1, qmr[0], qmr[1]) _, result, fock_counts = c2qa.util.simulate(circuit) qiskit.visualization.plot_histogram(fock_counts) #Notice the correlation between the state of the two qumodes! They always have the same photon number qmr = c2qa.QumodeRegister(1, num_qubits_per_qumode=4) circuit = c2qa.CVCircuit(qmr) #Define the side lengths of the rectangle a = 2 b = 1 animate_steps = 4 #Execute the sequence of displacements circuit.cv_d(a, qmr[0]) circuit.cv_d(1j*b, qmr[0]) circuit.cv_d(-a, qmr[0]) circuit.cv_d(-1j*b, qmr[0]) #animate the result anim = c2qa.animate.animate_wigner(circuit, animation_segments=10); HTML(anim.to_html5_video()) qbr = qiskit.QuantumRegister(1) creg = qiskit.ClassicalRegister(1) def measure_phase(c): #choose a = b = sqrt(c) to get a square of area c shots = 1024 circuit = c2qa.CVCircuit(qmr, qbr, creg, probe_measure=True) circuit.h(qbr[0]) circuit.cv_c_d(np.sqrt(c)/2, qmr[0], qbr[0]) circuit.cv_d(1j*np.sqrt(c)/2, qmr[0]) circuit.cv_c_d(-np.sqrt(c)/2, qmr[0], qbr[0]) circuit.cv_d(-1j*np.sqrt(c)/2, qmr[0]) circuit.measure_x(qbr[0], creg[0]) state, result, fock_counts = c2qa.util.simulate(circuit) counts = result.get_counts(circuit) return (counts.get('0',0)-counts.get('1',0))/shots measure_phase(0) c_vals = np.linspace(0, 2*np.pi, 20) results = [] for c in c_vals: results.append(measure_phase(c)) plt.plot(c_vals, results, c = "b", linestyle = "None", marker = "o", label = "data") plt.plot(c_vals, np.cos(c_vals), c = "k", linestyle = "--", label =r"$\cos(area)$") plt.xlabel("area/4") plt.ylabel(r"$\langle \sigma_x \rangle$") plt.legend()
https://github.com/C2QA/bosonic-qiskit
C2QA
import scqubits as sc tmon = sc.Transmon( EJ = 31, EC = .8, ng = 0, ncut = 110 ) evals = tmon.eigenvals()[:5] omega = evals[1]-evals[0] osc = sc.Oscillator( E_osc = omega ) import numpy as np from matplotlib import pyplot as plt xlist = np.linspace(-np.pi,np.pi,100) mineng = min([tmon.potential(x) for x in xlist]) plt.plot(xlist, [(tmon.potential(x)-mineng)/omega for x in xlist], c = "blue", label = "qubit") plt.plot(xlist, [(x**2 * 31/2)/omega for x in xlist], c = "red", label = "qumode") plt.hlines([(n+.5) for n in range(5)], -1, 1, color="red") plt.hlines((evals-mineng)/omega, -1, 1, color="blue") plt.xlabel(r"$\varphi$") plt.ylabel(r"E/$\omega$") plt.ylim([0,6]) plt.legend()
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import math import c2qa import c2qa.util import c2qa.wigner import matplotlib.pyplot import numpy import qiskit import qiskit_aer def calibration_circuit(dist, num_qumodes = 1, num_qubits_per_qumode = 4): qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=num_qubits_per_qumode) qr = qiskit.QuantumRegister(size=1) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) circuit.initialize([1,0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) circuit.cv_d(1j * dist, qmr[0]) circuit.cv_c_d(-dist, qmr[0], qr[0]) circuit.cv_d(-1j * dist, qmr[0]) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) return circuit, qr[0], cr[0] circuit, _, _ = calibration_circuit(numpy.sqrt(numpy.pi) / numpy.sqrt(2)) state, result, fock_counts = c2qa.util.simulate(circuit) counts = result.get_counts(circuit) print("Simulated statevector:") print(state) print("Simulated result counts:") print(counts) # Plot Fock state Wigner function c2qa.wigner.plot_wigner(circuit, state) # Run the simulations backend = qiskit_aer.Aer.get_backend("qasm_simulator") up = numpy.linspace(numpy.sqrt(2), 2, 20) down = numpy.linspace(2, numpy.sqrt(2), 20) steps = [] for _ in range(2): steps.extend(up[0:19]) steps.extend(down[0:19]) x = [] y = [] for i, step in enumerate(steps): dist = numpy.sqrt(numpy.pi) / step circuit, _, _ = calibration_circuit(dist) state, result, fock_counts = c2qa.util.simulate(circuit, shots=32) counts = result.get_counts(circuit) x.append(i) y.append(counts.get("0", 0) - counts.get("1", 0)) print(f"{i}: {counts}") # Plot the results matplotlib.pyplot.scatter(x, y) matplotlib.pyplot.show() circuit, qubit, cbit = calibration_circuit(dist=numpy.sqrt(numpy.pi) / numpy.sqrt(2)) anim = c2qa.animate.animate_wigner(circuit, qubit=qubit, cbit=cbit, animation_segments=10, shots=10) from IPython.display import HTML HTML(anim.to_html5_video())
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import numpy as np import qiskit # Define Hamiltonian parameters omega_R = 2 omega_Q = 5 chi = 0.1 from qiskit.circuit import Parameter # Set number of qubits per qumode num_qubits_per_qumode = 3 # Define parameter dt dt = Parameter('dt') # Create new circuit qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(1) U_JC = c2qa.CVCircuit(qmr,qbr) # Append U_R U_JC.cv_r(-omega_R*dt,qmr[0]) # Append U_Q U_JC.rz(omega_Q*dt,qbr[0]) # Append U_\chi -- KS: this needs to be updated to reflect naming conventions in manuscript U_JC.cv_c_r(-chi*dt/2,qmr[0],qbr[0]) # Compile this circuit into a single parameterized gate U_JC = U_JC.to_gate(label='U_JC') qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(1) # Instantiate the circuit and initialize the qubit to the '+' state. circuit = c2qa.CVCircuit(qmr,qbr) circuit.initialize([1/np.sqrt(2), 1/np.sqrt(2)], qbr) # Append the time evolution unitary circuit.append(U_JC,qmr[0] + [qbr[0]]); # Draw the circuit circuit.decompose().draw(output='mpl') I_qumode = circuit.ops.get_eye(qmr.cutoff).toarray() sigmax = np.kron(np.array([[0, 1], [1, 0]]), I_qumode) sigmaz = np.kron(np.array([[1, 0], [0, -1]]), I_qumode) # First construct operator sigma^x. First, we need to retrieve the identity operator over the qumode. As its dimensionality is # dependent upon the cutoff, the easiest way to do this is to use tarray = np.linspace(0,3*2*np.pi/omega_Q,100) sigma_x_expectation = [] sigma_z_expectation = [] for tau in tarray: state, result, _ = c2qa.util.simulate(circuit.assign_parameters({dt : tau})) sigma_x_expectation.append(state.expectation_value(sigmax).real) sigma_z_expectation.append(state.expectation_value(sigmaz).real) import matplotlib.pyplot as plt fontsize = 20 plt.figure(figsize=(15,4)) plt.subplot(1,2,1) plt.plot(tarray/(2*np.pi/omega_Q),sigma_x_expectation,linewidth=2) plt.ylabel(r'$\langle\sigma^x\rangle$',fontsize=fontsize,usetex=True); plt.xlabel(r'$t$ $(2\pi/\omega_Q)$',fontsize=fontsize,usetex=True); plt.xlim([0,3]); plt.ylim([-1.05,1.05]); plt.subplot(1,2,2) plt.plot(tarray/(2*np.pi/omega_Q),sigma_z_expectation,linewidth=2,color='tab:red') plt.ylabel(r'$\langle\sigma^z\rangle$',fontsize=fontsize,usetex=True); plt.xlabel(r'$t$ $(2\pi/\omega_Q)$',fontsize=fontsize,usetex=True); plt.xlim([0,3]); plt.ylim([-1.05,1.05]); fockNumberList = [0,1,2,3,4] tarray = np.linspace(0,3*2*np.pi/omega_Q,100) plt.figure(figsize=(15,4)) plt.ylabel(r'$\langle\sigma^x\rangle$',fontsize=fontsize,usetex=True); plt.xlabel(r'$t$ $(2\pi/\omega_Q)$',fontsize=fontsize,usetex=True); plt.xlim([0,3]); plt.ylim([-1.05,1.05]); for fockNumber in fockNumberList: print("Time evolving for Fock state |" + str(fockNumber) + '>...') qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(1) # Instantiate the circuit and initialize the qubit to the '+' state. circuit = c2qa.CVCircuit(qmr,qbr) circuit.initialize([1/np.sqrt(2), 1/np.sqrt(2)], qbr) # Initialize the qumode circuit.cv_initialize(fockNumber,qmr[0]) circuit.append(U_JC,qmr[0] + [qbr[0]]); sigma_x_expectation = [] for tau in tarray: state, result, _ = c2qa.util.simulate(circuit.assign_parameters({dt : tau})) sigma_x_expectation.append(state.expectation_value(sigmax).real) plt.plot(tarray/(2*np.pi/omega_Q),sigma_x_expectation,linewidth=2, label = r'$|' + str(fockNumber) + r'\rangle $') plt.legend() # Choose alpha for coherent state alpha = 1 # Choose total animation time total_time = 1*2*np.pi/omega_R # First construct circuit_qubit0 qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(1) # Create new circuit qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=num_qubits_per_qumode) qbr = qiskit.QuantumRegister(1) U_JC = c2qa.CVCircuit(qmr,qbr) # Append U_R U_JC.cv_r(-omega_R*total_time,qmr[0]) # Append U_Q U_JC.rz(omega_Q*total_time,qbr[0]) # Append U_\chi -- KS: this needs to be updated to reflect naming conventions in manuscript U_JC.cv_c_r(-chi*total_time/2,qmr[0],qbr[0]) # Compile this circuit into a single parameterized gate U_JC = U_JC.to_gate(label='U_JC') # Instantiate the circuit and initialize the qubit to the '0' state. circuit_0 = c2qa.CVCircuit(qmr,qbr) circuit_0.initialize([1,0], qbr) # Now initialize the qumode in a coherent state cutoff = 2**num_qubits_per_qumode coeffs = [np.exp(-np.abs(alpha)**2/2)*alpha**n/(np.sqrt(np.math.factorial(n))) for n in range(0,cutoff)] circuit_0.cv_initialize(coeffs,qmr[0]) # Append time evolution unitary circuit_0.append(U_JC,qmr[0] + [qbr[0]]); # circuit_0.assign_parameters({dt : total_time}) # dt = total_time # # Append U_R # circuit_0.cv_r(-omega_R*dt,qmr[0]) # # Append U_Q # circuit_0.rz(omega_Q*dt,qbr[0]) # # Append U_\chi -- KS: this needs to be updated to reflect naming conventions in manuscript # circuit_0.cv_c_r(-chi*dt/2,qmr[0],qbr[0]) # Compile this circuit into a single parameterized gate # U_JC = U_JC.to_gate(label='U_JC') # # Now repeat the above steps for a qubit initialized to the '1' state: # circuit_1 = c2qa.CVCircuit(qmr,qbr) # circuit_1.initialize([0,1], qbr) # circuit_1.cv_d(alpha,qmr[0]) # circuit_1.append(U_JC,qmr[0] + [qbr[0]]); # circuit_1 = circuit_1.assign_parameters({dt : total_time}) # Animate wigner function of each circuit c2qa.animate.animate_wigner(circuit_0, animation_segments = 1000)
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Import packages that will be used import c2qa import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, ClassicalRegister from qiskit.circuit.library import RGate # To prepare a cat state, we first set our initial parameters: we need one qumode and one ancillary qubit. We will also # need to set a cutoff for our qumode. Nmodes=1 Nqubits = 1 cutoff = 2**4 # The photon number at which to truncate the Hilbert space. Our basis will consist of Fock states |0> to |cutoff-1> alpha = 3/np.sqrt(2) # Instantiate the Qumode register qmr = c2qa.QumodeRegister(num_qumodes=Nmodes, num_qubits_per_qumode=int(np.ceil(np.log2(cutoff)))) # Instantiate a Qubit and Classical register qbr = QuantumRegister(Nqubits) cbr = ClassicalRegister(Nqubits) # Initialize a CVCircuit, which includes both the qumode register as well as the qubit register circuit = c2qa.CVCircuit(qmr, qbr, cbr) # Compose cat state prep circuit circuit.h(qbr[0]) circuit.cv_c_d(alpha,qmr[0],qbr[0]) circuit.h(qbr[0]) circuit.measure(qbr[0],cbr[0]) # Now draw the circuit using Qiskit's draw() function # circuit.draw(scale=1, output = 'mpl', fold = 32, filename = 'figures/Catcircuit.png') # Now simulate the circuit to retrieve the final density matrix. stateop, _, _ = c2qa.util.simulate(circuit) # Use Bosonic Qiskit's built-in plot_wigner function, which traces out the qubit and displays the Wigner (phase-space) # representation of the qumode state. fig = c2qa.wigner.plot_wigner(circuit, stateop, dpi = 300) # We can also print out the occupancy of the modes and their complex amplitudes. c2qa.util.stateread(stateop,1,1,cutoff); # Let's first import the GKP parameters GKP_params = np.load('GKP_params.npz') # Set some initial parameters: Nmodes=1 # The number of qumodes Nqubits = 1 # The number of qubits cutoff = 2**5 # The qumode cutoff # Instantiate the Qumode register qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=int(np.ceil(np.log2(cutoff)))) # Instantiate a Qubit register qbr = QuantumRegister(Nqubits) # Initialize a CVCircuit, which includes both the qumode register as well as the qubit register circuit = c2qa.CVCircuit(qmr, qbr) # Now append gates to the circuit. Here, we append multiple layers, each with a single qubit RGate, followed by # a conditional displacement and an X gate (which together form the "echoed-conditional displacement" -- for more info, # see https://www.nature.com/articles/s41567-022-01776-9. for beta, phi, theta in zip(GKP_params['betas'], GKP_params['phis'], GKP_params['thetas']): circuit.append(RGate(theta,phi),[qbr[0]]) circuit.cv_c_d(beta/2,qmr[0],qbr[0]) circuit.x(qbr[0]) # Now draw the circuit using Qiskit's draw() function # circuit.draw(scale=0.6, output = 'mpl', fold = 32, filename = 'figures/GKPcircuit.png') # Now simulate the circuit to retrieve the final density matrix. stateop, _, _ = c2qa.util.simulate(circuit) # Use Bosonic Qiskit's built-in plot_wigner function, which traces out the qubit and displays the Wigner (phase-space) # representation of the qumode state. fig = c2qa.wigner.plot_wigner(circuit, stateop, dpi = 300) # Let's first define a function which constructs our approximation to e^{-iH*dt} def createU2U1(Nsites,Nbosons, cutoff, U, J, dt): from qiskit.converters import circuit_to_gate from qiskit.circuit import Parameter qmr = c2qa.QumodeRegister(num_qumodes=Nsites, num_qubits_per_qumode=int(np.ceil(np.log2(cutoff)))) circuit = c2qa.CVCircuit(qmr) # First apply U1: Apply beamsplitters in brickwork layout theta = -J*dt for i in range(0,len(qmr)-1,2): circuit.cv_bs(-theta,qmr[i],qmr[i+1]) for i in range(1,len(qmr)-1,2): circuit.cv_bs(-theta,qmr[i],qmr[i+1]) # Now apply U2: Use SNAP gate for each site and Fock state theta = (U/2)*dt for i in range(0,len(qmr)): # For each site for n in range(2,cutoff): # For each Fock state circuit.cv_snap(-theta*n*(n-1),n,qmr[i]) # Apply SNAP with phase proportional to n*(n-1) return circuit_to_gate(circuit,label = 'U2 U1') # Let's simulate a Bose-Hubbard model with Nsites for the simple case where we have Nbosons loaded into the lattice Nsites = 4 Nbosons = 4 cutoff = Nbosons + 1 # Initialize the qumode register qmr = c2qa.QumodeRegister(num_qumodes=Nsites, num_qubits_per_qumode=int(np.ceil(np.log2(cutoff)))) circuit = c2qa.CVCircuit(qmr) # Choose parameters J = 1 U = 0.1 dt = 0.2 t_array = np.arange(0,13*dt,dt) # Create U2U1, which carries out a single time step of length dt U2U1 = createU2U1(Nsites, Nbosons, cutoff, U, J, dt) # Initialize the left-most and right-most mode to each have two bosons initially circuit.cv_initialize(2, qmr[0]) circuit.cv_initialize(2, qmr[3]) # Loop through each time step and simulate occupancy_list = np.zeros((len(t_array),Nsites)) for i in range(0,len(t_array)): print('Timestep ' + str(int(i+1)) + '/' + str(len(t_array))) circuit.append(U2U1,qmr[:]) stateop, _, _ = c2qa.util.simulate(circuit) # Print out occupancy occupancy, _ = c2qa.util.stateread(stateop, 0, Nsites, cutoff, verbose=False,little_endian=True) occupancy_list[i,:]=np.array(occupancy[0]) occupancy_largeJ = occupancy_list plt.set_cmap("magma") fig = plt.figure(figsize = (4,8)) plt.pcolormesh([0,1,2,3],np.arange(0,len(t_array)),occupancy_largeJ,linewidth=0,rasterized=True,shading='auto') plt.title("$J=$" + str(J) + ", $U=$" + str(0.1)) plt.xticks([0,1,2,3]) plt.xlabel("Qumode") plt.ylabel("Time ($dt$)") plt.clim(0,2) cbar = plt.colorbar(orientation='vertical',ax=plt.gca()) cbar.ax.get_yaxis().labelpad = 20 cbar.set_ticks([0,0.5,1,1.5,2]) cbar.set_label("Mode occupation", rotation=270) plt.tight_layout() # As usual, first define how many qumodes we want, and how many qubits we should use to represent each (equivalent to choosing a cutoff) num_qumodes = 1 num_qubits_per_qumode = 4 qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode) circuit = c2qa.CVCircuit(qmr) # First initialize the qumode in Fock state |3> circuit.cv_initialize(3, qmr[0]) # Let's now apply a displacement gate. Bosonic Qiskit allows a user to specify the gate duration in user-specified units (which # will be used to calculate the loss probability at each time step). Let's go with a 100ns gate duration. circuit.cv_d(1.5, qmr[0], duration=100, unit="ns") # Now set a loss rate -- make it large enough such that we can actually see the loss photon_loss_rate = 0.02 # This is a loss rate in units of 1/ns time_unit = "ns" noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit) # The noise pass can then be passed into simulate state, result, _ = c2qa.util.simulate(circuit, noise_passes=noise_pass) # Alternatively, we can animate our circuit using the animate_wigner() function built-into bosonic qiskit. wigner_filename = "figures/photon_loss.mp4" c2qa.animate.animate_wigner( circuit, animation_segments=200, # file=wigner_filename, noise_passes=noise_pass )
https://github.com/C2QA/bosonic-qiskit
C2QA
# The C2QA pacakge is currently not published to PyPI. # To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import qiskit from qiskit import QuantumCircuit qmr0 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qr0 = qiskit.QuantumRegister(size=1) circuit0 = c2qa.CVCircuit(qmr0, qr0) # Initialize qubit circuit0.initialize([1,0], qr0[0]) # circuit0.initialize([0,1], qr0[0]) # Initialize the qumode to, for example, a Fock sate 1 circuit0.cv_initialize(1, qmr0[0]) # ... Your circuit here ... state0, _, _ = c2qa.util.simulate(circuit0) print(state0) # c2qa.util.trace_out_qumodes() performs a partial trace over the cavities, giving the reduced density matrix of the qubits print(c2qa.util.trace_out_qumodes(circuit0, state0)) # c2qa.util.trace_out_qubits() performs a partial trace over the qubits, giving the reduced density matrix of the cavities print(c2qa.util.trace_out_qubits(circuit0, state0))
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import qiskit from qiskit import QuantumCircuit from qiskit.circuit import Gate from math import pi qc = QuantumCircuit(2) qmr0 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qr0 = qiskit.QuantumRegister(size=1) circuit0 = c2qa.CVCircuit(qmr0, qr0) # Initialize your qubit (should have no effect on Fock state Wigner function) circuit0.initialize([1,0], qr0[0]) # circuit0.initialize([0,1], qr0[0]) # Initialize the qumode to a zero Fock sate circuit0.cv_initialize(0, qmr0[0]) # ... Your circtuit here ... state0, _, _ = c2qa.util.simulate(circuit0) print(state0) # c2qa.wigner.plot_wigner_function() will perform a partial trace to separate the qumode from the qubit state for you, the call below is to log its output as an example. print(c2qa.util.trace_out_qubits(circuit0, state0)) c2qa.wigner.plot_wigner(circuit0, state0) qmr1 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qr1 = qiskit.QuantumRegister(size=1) circuit1 = c2qa.CVCircuit(qmr1, qr1) # Initialize your qubit (should have no effect on Fock state Wigner function) circuit1.initialize([1,0], qr1[0]) # circuit1.initialize([0,1], qr1[0]) # Initialize the qumode to a one Fock sate circuit1.cv_initialize(1, qmr1[0]) # ... Your circtuit here ... state1, _, _ = c2qa.util.simulate(circuit1) print(state1) # c2qa.wigner.plot_wigner_function() will perform a partial trace to separate the qumode from the qubit state for you, the call below is to log its output as an example. print(c2qa.util.trace_out_qubits(circuit1, state1)) c2qa.wigner.plot_wigner(circuit1, state1) import numpy qmr2 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=2) qr2 = qiskit.QuantumRegister(size=1) circuit2 = c2qa.CVCircuit(qmr2, qr2) # Initialize your qubit (should have no effect on Fock state Wigner function) circuit2.initialize([1,0], qr2[0]) # circuit1.initialize([0,1], qr1[0]) # Initialize the qumode to a zero Fock sate (ie. the vaccuum) circuit2.cv_initialize(0, qmr2[0]) # Displace the vaccuum using the displacement gate # Displace the quasi-probability distribution along the position axis x with a real number # circuit2.cv_d(numpy.pi/2,qmr1[0]) # Displace the quasi-probability distribution along the momentum axis with an imaginary number circuit2.cv_d(numpy.pi/2*1j,qmr2[0]) state2, _, _ = c2qa.util.simulate(circuit2) print(state2) # c2qa.wigner.plot_wigner_function() will perform a partial trace to separate the qumode from the qubit state for you, the call below is to log its output as an example. print(c2qa.util.trace_out_qubits(circuit2, state2)) c2qa.wigner.plot_wigner(circuit2, state2) # Not the expected behavior of displacing the vaccuum, which should simply shift the quasi-probability distribution without distorting it. # Augment the number of qubits per mode qmr3 = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=6) qr3 = qiskit.QuantumRegister(size=1) circuit3 = c2qa.CVCircuit(qmr3, qr3) # Initialize your qubit (should have no effect on Fock state Wigner function) circuit3.initialize([1,0], qr3[0]) # circuit1.initialize([0,1], qr1[0]) # Initialize the qumode to a zero Fock sate (ie. the vaccuum) circuit3.cv_initialize(0, qmr3[0]) # Displace the vaccuum using the displacement gate # Displace the quasi-probability distribution along the position axis x with a real number # circuit2.cv_d(numpy.pi/2,qmr1[0]) # Displace the quasi-probability distribution along the momentum axis with an imaginary number circuit3.cv_d(numpy.pi/2*1j,qmr3[0]) state3, _, _ = c2qa.util.simulate(circuit3) occ =c2qa. util.stateread(state3, 1, 1, 6) print(state3) # c2qa.wigner.plot_wigner_function() will perform a partial trace to separate the qumode from the qubit state for you, the call below is to log its output as an example. print(c2qa.util.trace_out_qubits(circuit3, state3)) c2qa.wigner.plot_wigner(circuit3, state3) # This is the expected behavior of displacing the vaccuum: # a simple shift the quasi-probability distribution without distorting it, creating a coherent state. def cv_ecdX(qc, qbr, qmr, qm, alpha): qc.ry(-np.pi / 2, qbr[0]) qc.cv_ecd(alpha/2, qmr[qm], qbr[0]) qc.ry(np.pi / 2, qbr[0]) return qc def cv_ecdY(qc, qbr, qmr, qm, alpha): qc.rx(-np.pi / 2, qbr[0]) qc.cv_ecd(alpha/2, qmr[qm], qbr[0]) qc.rx(np.pi / 2, qbr[0]) return qc import numpy as np # Augment the number of qubits per mode qmr = c2qa.QumodeRegister(num_qumodes=2, num_qubits_per_qumode=6) qbr = qiskit.QuantumRegister(size=1) qc = c2qa.CVCircuit(qmr, qbr) # Initialize your qubit (should have no effect on Fock state Wigner function) qc.initialize([1,0], qbr[0]) # initialise in x (just h) or y eigenstate qc.h(qbr[0]) qc.rz(np.pi/2,qbr[0]) # Initialize the qumode to a zero Fock sate (ie. the vaccuum) qc.cv_initialize(0, qmr[0]) qc.cv_initialize(0, qmr[1]) alpha = 1j/2 qc = cv_ecdX(qc, qbr, qmr, 0, alpha) qc = cv_ecdY(qc, qbr, qmr, 1, alpha) qc = cv_ecdX(qc, qbr, qmr, 0, -alpha) qc = cv_ecdY(qc, qbr, qmr, 1, -alpha) alpha = 1/2 qc = cv_ecdX(qc, qbr, qmr, 0, alpha) qc = cv_ecdY(qc, qbr, qmr, 1, alpha) qc = cv_ecdX(qc, qbr, qmr, 0, -alpha) qc = cv_ecdY(qc, qbr, qmr, 1, -alpha) state, _, _ = c2qa.util.simulate(qc) # # c2qa.wigner.plot_wigner_function() will perform a partial trace to separate the qumode from the qubit state for you, the call below is to log its output as an example. # print(c2qa.util.trace_out_qubits(qc, state)) c2qa.wigner.plot_wigner(qc, state, method="iterative")
https://github.com/C2QA/bosonic-qiskit
C2QA
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa. import os import sys module_path = os.path.abspath(os.path.join("../..")) if module_path not in sys.path: sys.path.append(module_path) # Cheat to get MS Visual Studio Code Jupyter server to recognize Python venv module_path = os.path.abspath(os.path.join("../../venv/Lib/site-packages")) if module_path not in sys.path: sys.path.append(module_path) import c2qa import qiskit def build_circuit(dist = 2, num_qumodes = 1, num_qubits_per_qumode = 4): qmr = c2qa.QumodeRegister(num_qumodes=num_qumodes, num_qubits_per_qumode=num_qubits_per_qumode) qr = qiskit.QuantumRegister(size=1) cr = qiskit.ClassicalRegister(size=1) circuit = c2qa.CVCircuit(qmr, qr, cr) circuit.initialize([1,0], qr[0]) circuit.cv_initialize(0, qmr[0]) circuit.h(qr[0]) circuit.cv_c_d(dist, qmr[0], qr[0]) circuit.h(qr[0]) return circuit circuit = build_circuit() state, result, _ = c2qa.util.simulate(circuit) wigner = c2qa.wigner.wigner(state) c2qa.wigner.plot(wigner) circuit = build_circuit() states, result, _ = c2qa.util.simulate(circuit, per_shot_state_vector=True) wigner = c2qa.wigner.wigner_mle(states) c2qa.wigner.plot(wigner)
https://github.com/CQCL/pytket-qiskit
CQCL
# Copyright 2019 Cambridge Quantum Computing # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Methods to allow conversion between Qiskit and pytket circuit classes """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Instruction, Measure from qiskit.extensions.standard import * from pytket._circuit import Circuit, Op, OpType from pytket._routing import PhysicalCircuit from sympy import pi _known_qiskit_gate = { IdGate : OpType.noop, XGate : OpType.X, YGate : OpType.Y, ZGate : OpType.Z, SGate : OpType.S, SdgGate : OpType.Sdg, TGate : OpType.T, TdgGate : OpType.Tdg, HGate : OpType.H, RXGate : OpType.Rx, RYGate : OpType.Ry, RZGate : OpType.Rz, U1Gate : OpType.U1, U2Gate : OpType.U2, U3Gate : OpType.U3, CnotGate : OpType.CX, CyGate : OpType.CY, CzGate : OpType.CZ, CHGate : OpType.CH, SwapGate : OpType.SWAP, ToffoliGate : OpType.CCX, FredkinGate : OpType.CSWAP, CrzGate : OpType.CRz, Cu1Gate : OpType.CU1, Cu3Gate : OpType.CU3, Measure : OpType.Measure } _known_qiskit_gate_rev = {v : k for k, v in _known_qiskit_gate.items()} def qiskit_to_tk(qcirc: QuantumCircuit) -> Circuit : """Convert a :py:class:`qiskit.QuantumCircuit` to a :py:class:`Circuit`. :param qcirc: A circuit to be converted :type qcirc: QuantumCircuit :return: The converted circuit :rtype: Circuit """ tkc = Circuit() qregmap = {} for reg in qcirc.qregs : tk_reg = tkc.add_q_register(reg.name, len(reg)) qregmap.update({reg : tk_reg}) cregmap = {} for reg in qcirc.cregs : tk_reg = tkc.add_c_register(reg.name, len(reg)) cregmap.update({reg : tk_reg}) for i, qargs, cargs in qcirc.data : if i.control is not None : raise NotImplementedError("Cannot convert conditional gates from Qiskit to tket") optype = _known_qiskit_gate[type(i)] qubits = [qregmap[r][ind] for r, ind in qargs] bits = [cregmap[r][ind] for r, ind in cargs] if optype == OpType.Measure : tkc.add_measure(*qubits, *bits) continue params = [p/pi for p in i.params] tkc.add_gate(optype, params, qubits, []) return tkc def tk_to_qiskit(tkcirc: Circuit) -> QuantumCircuit : """Convert back :param tkcirc: A circuit to be converted :type tkcirc: Circuit :return: The converted circuit :rtype: QuantumCircuit """ tkc = tkcirc if isinstance(tkcirc, PhysicalCircuit) : tkc = tkcirc._get_circuit() qcirc = QuantumCircuit() qregmap = {} for _, reg in tkc.q_regs.items() : if reg.size() == 0 : continue name = reg.name if len(name) == 0 : name = None qis_reg = QuantumRegister(reg.size(), name) qregmap.update({reg : qis_reg}) qcirc.add_register(qis_reg) cregmap = {} for _, reg in tkc.c_regs.items() : if reg.size() == 0 : continue name = reg.name if len(name) == 0 : name = None qis_reg = ClassicalRegister(reg.size(), name) cregmap.update({reg : qis_reg}) qcirc.add_register(qis_reg) tempregmap = {} for command in tkc : op = command.op qubits = command.qubits qargs = [qregmap[q.reg][q.index] for q in qubits] if len(command.controls) != 0 : raise NotImplementedError("Cannot convert conditional gates from tket to Qiskit") if op.get_type() == OpType.Measure : bits = [_convert_bit(b, cregmap, qcirc, tempregmap) for b in command.bits] qcirc.measure(*qargs, *bits) continue params = [p * pi for p in op.get_params()] try : gatetype = _known_qiskit_gate_rev[op.get_type()] except KeyError as error : raise NotImplementedError("Cannot convert tket Op to Qiskit gate: " + op.get_name()) from error g = gatetype(*params) qcirc.append(g, qargs=qargs) return qcirc def _convert_bit(bit, cregmap, qcirc, tempregmap) : index = bit.index if bit.temp : if bit not in tempregmap : new_reg = ClassicalRegister(1, "temp"+str(index)) qcirc.add_register(new_reg) tempregmap.update({bit : new_reg}) return new_reg[0] return tempregmap[bit][0] return cregmap[bit.reg][index]
https://github.com/CQCL/pytket-qiskit
CQCL
# Copyright 2020-2024 Quantinuum # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional, List, Union, Any from qiskit.circuit.quantumcircuit import QuantumCircuit # type: ignore from qiskit.providers.backend import BackendV1 # type: ignore from qiskit.providers.models import QasmBackendConfiguration # type: ignore from qiskit.providers import Options # type: ignore from pytket.extensions.qiskit import AerStateBackend, AerUnitaryBackend from pytket.extensions.qiskit.qiskit_convert import qiskit_to_tk, _gate_str_2_optype_rev from pytket.extensions.qiskit.tket_job import TketJob, JobInfo from pytket.backends import Backend from pytket.passes import BasePass from pytket.predicates import ( NoClassicalControlPredicate, GateSetPredicate, CompilationUnit, ) from pytket.architecture import FullyConnected def _extract_basis_gates(backend: Backend) -> List[str]: for pred in backend.required_predicates: if type(pred) == GateSetPredicate: return [ _gate_str_2_optype_rev[optype] for optype in pred.gate_set if optype in _gate_str_2_optype_rev.keys() ] return [] class TketBackend(BackendV1): """Wraps a :py:class:`Backend` as a :py:class:`qiskit.providers.BaseBackend` for use within the Qiskit software stack. Each :py:class:`qiskit.circuit.quantumcircuit.QuantumCircuit` passed in will be converted to a :py:class:`Circuit` object. If a :py:class:`BasePass` is provided for ``comp_pass``, this is applied to the :py:class:`Circuit`. Then it is processed by the :py:class:`Backend`, wrapping the :py:class:`ResultHandle` s in a :py:class:`TketJob`, retrieving the results when called on the job object. The required predicates of the :py:class:`Backend` are presented to the Qiskit transpiler to enable it to perform the compilation in many cases. This may not always be possible due to unsupported gatesets or additional constraints that cannot be captured in Qiskit's transpiler, in which case a custom :py:class:`qiskit.transpiler.TranspilationPass` should be used to map into a tket- compatible gateset and set ``comp_pass`` to compile for the backend. To compile with tket only, set ``comp_pass`` and just use Qiskit to map into a tket-compatible gateset. In Qiskit Aqua, you should wrap the :py:class:`TketBackend` in a :py:class:`qiskit.aqua.QuantumInstance`, providing a custom :py:class:`qiskit.transpiler.PassManager` with a :py:class:`qiskit.transpiler.passes.Unroller`. For examples, see the `user manual <https://tket.quantinuum.com/user-manual/manual_backend.html#embedding-into- qiskit>`_ or the `Qiskit integration example <ht tps://github.com/CQCL/pytket/blob/main/examples/qiskit_integration. ipynb>`_. """ def __init__(self, backend: Backend, comp_pass: Optional[BasePass] = None): """Create a new :py:class:`TketBackend` from a :py:class:`Backend`. :param backend: The device or simulator to wrap up :type backend: Backend :param comp_pass: The (optional) tket compilation pass to apply to each circuit before submitting to the :py:class:`Backend`, defaults to None :type comp_pass: Optional[BasePass], optional """ arch = backend.backend_info.architecture if backend.backend_info else None coupling: Optional[List[List[Any]]] if isinstance(arch, FullyConnected): coupling = [ [n1.index[0], n2.index[0]] for n1 in arch.nodes for n2 in arch.nodes if n1 != n2 ] else: coupling = ( [[n.index[0], m.index[0]] for n, m in arch.coupling] if arch else None ) config = QasmBackendConfiguration( backend_name=("statevector_" if backend.supports_state else "") + "pytket/" + str(type(backend)), backend_version="0.0.1", n_qubits=len(arch.nodes) if arch and arch.nodes else 40, basis_gates=_extract_basis_gates(backend), gates=[], local=False, simulator=False, conditional=not any( ( type(pred) == NoClassicalControlPredicate for pred in backend.required_predicates ) ), open_pulse=False, memory=backend.supports_shots, max_shots=10000, coupling_map=coupling, max_experiments=10000, ) super().__init__(configuration=config, provider=None) self._backend = backend self._comp_pass = comp_pass @classmethod def _default_options(cls) -> Options: return Options(shots=None, memory=False) def run( self, run_input: Union[QuantumCircuit, List[QuantumCircuit]], **options: Any ) -> TketJob: if isinstance(run_input, QuantumCircuit): run_input = [run_input] n_shots = options.get("shots", None) circ_list = [] jobinfos = [] for qc in run_input: tk_circ = qiskit_to_tk(qc) if isinstance(self._backend, (AerStateBackend, AerUnitaryBackend)): tk_circ.remove_blank_wires() circ_list.append(tk_circ) jobinfos.append(JobInfo(qc.name, tk_circ.qubits, tk_circ.bits, n_shots)) if self._comp_pass: final_maps = [] compiled_list = [] for c in circ_list: cu = CompilationUnit(c) self._comp_pass.apply(cu) compiled_list.append(cu.circuit) final_maps.append(cu.final_map) circ_list = compiled_list else: final_maps = [None] * len(circ_list) # type: ignore handles = self._backend.process_circuits(circ_list, n_shots=n_shots) return TketJob(self, handles, jobinfos, final_maps)
https://github.com/CQCL/pytket-qiskit
CQCL
import qiskit from qiskit.dagcircuit import DAGCircuit from qiskit.providers import BaseBackend from qiskit.transpiler.basepasses import TransformationPass, BasePass from qiskit.converters import circuit_to_dag, dag_to_circuit from pytket._transform import Transform from pytket._routing import route, Architecture from pytket.qiskit import qiskit_to_tk, tk_to_qiskit class TketPass(TransformationPass): """The :math:`\\mathrm{t|ket}\\rangle` compiler to be plugged in to the Qiskit compilation sequence""" filecount = 0 def __init__(self,backend:BaseBackend, DROP_CONDS:bool=False,BOX_UNKNOWN:bool=True,name:str="T|KET>") : BasePass.__init__(self) self.DROP_CONDS=DROP_CONDS self.BOX_UNKNOWN=BOX_UNKNOWN self.name = name my_backend = None if isinstance(backend, BaseBackend): my_backend = backend else: raise RuntimeError("Requires BaseBackend instance") self.coupling_map = my_backend.configuration().to_dict().get('coupling_map', None) def process_circ(self, circ): num_qubits = circ.n_qubits if num_qubits == 1 or self.coupling_map == "all-to-all": coupling_map = None else: coupling_map = self.coupling_map # pre-routing optimise Transform.OptimisePhaseGadgets().apply(circ) circlay = list(range(num_qubits)) if coupling_map: directed_arc = Architecture(coupling_map) # route_ibm fnction that takes directed Arc, returns dag with cnots etc. circ, circlay = route(circ,directed_arc) circ.apply_boundary_map(circlay[0]) # post route optimise Transform.OptimisePostRouting().apply(circ) circ.remove_blank_wires() return circ, circlay def run(self, dag:DAGCircuit) -> DAGCircuit: """ Run one pass of optimisation on the circuit and route for the given backend. :param dag: The circuit to optimise and route :return: The modified circuit """ qc = dag_to_circuit(dag) circ = qiskit_to_tk(qc) circ, circlay = self.process_circ(circ) qc = tk_to_qiskit(circ) newdag = circuit_to_dag(qc) newdag.name = dag.name finlay = dict() for i, qi in enumerate(circlay): finlay[('q', i)] = ('q', qi) newdag.final_layout = finlay return newdag
https://github.com/CQCL/pytket-qiskit
CQCL
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/CQCL/pytket-qiskit
CQCL
# Copyright 2019 Cambridge Quantum Computing # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from qiskit import Aer from qiskit.compiler import assemble from qiskit.providers.aer.noise import NoiseModel from pytket.backends import Backend from pytket.qiskit import tk_to_qiskit from pytket.backends.ibm.ibm import _convert_bin_str from pytket._circuit import Circuit from pytket._transform import Transform from pytket._simulation import pauli_tensor_matrix, operator_matrix import numpy as np class AerBackend(Backend) : def __init__(self, noise_model:NoiseModel=None) : """Backend for running simulations on Qiskit Aer Qasm simulator. :param noise_model: Noise model to use in simulation, defaults to None. :type noise_model: NoiseModel, optional """ self._backend = Aer.get_backend('qasm_simulator') self.noise_model = noise_model def run(self, circuit:Circuit, shots:int, fit_to_constraints=True, seed:int=None) -> np.ndarray: """Run a circuit on Qiskit Aer Qasm simulator. :param circuit: The circuit to run :type circuit: Circuit :param shots: Number of shots (repeats) to run :type shots: int :param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True :type fit_to_constraints: bool, optional :param seed: random seed to for simulator :type seed: int :return: Table of shot results, each row is a shot, columns are ordered by qubit ordering. Values are 0 or 1, corresponding to qubit basis states. :rtype: numpy.ndarray """ c = circuit.copy() if fit_to_constraints : Transform.RebaseToQiskit().apply(c) qc = tk_to_qiskit(c) qobj = assemble(qc, shots=shots, seed_simulator=seed, memory=True) job = self._backend.run(qobj, noise_model=self.noise_model) shot_list = job.result().get_memory(qc) return np.asarray([_convert_bin_str(shot) for shot in shot_list]) def get_counts(self, circuit, shots, fit_to_constraints=True, seed=None) : """ Run the circuit on the backend and accumulate the results into a summary of counts :param circuit: The circuit to run :param shots: Number of shots (repeats) to run :param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True :param seed: Random seed to for simulator :return: Dictionary mapping bitvectors of results to number of times that result was observed (zero counts are omitted) """ c = circuit.copy() if fit_to_constraints : Transform.RebaseToQiskit().apply(c) qc = tk_to_qiskit(c) qobj = assemble(qc, shots=shots, seed_simulator=seed) job = self._backend.run(qobj, noise_model=self.noise_model) counts = job.result().get_counts(qc) return {tuple(_convert_bin_str(b)) : c for b, c in counts.items()} class AerStateBackend(Backend) : def __init__(self) : self._backend = Aer.get_backend('statevector_simulator') def get_state(self, circuit, fit_to_constraints=True) : """ Calculate the statevector for a circuit. :param circuit: circuit to calculate :return: complex numpy array of statevector """ c = circuit.copy() if fit_to_constraints : Transform.RebaseToQiskit().apply(c) qc = tk_to_qiskit(c) qobj = assemble(qc) job = self._backend.run(qobj) return np.asarray(job.result().get_statevector(qc, decimals=16)) def run(self, circuit, shots, fit_to_constraints=True) : raise Exception("Aer State Backend cannot currently generate shots. Use `get_state` instead.") def get_pauli_expectation_value(self, state_circuit, pauli, shots=1000) : state = self.get_state(state_circuit) pauli_op = pauli_tensor_matrix(pauli, state_circuit.n_qubits) return np.vdot(state, pauli_op.dot(state)) def get_operator_expectation_value(self, state_circuit, operator, shots=1000) : """ Calculates expectation value for an OpenFermion QubitOperator by summing over pauli expectations Note: This method is significantly faster using the ProjectQBackend than the AerStateBackend. """ state = self.get_state(state_circuit) n_qubits = state_circuit.n_qubits op_as_lists = [(list(p),c) for p,c in operator.terms.items()] op = operator_matrix(op_as_lists, n_qubits) return np.vdot(state, op.dot(state)) class AerUnitaryBackend(Backend) : def __init__(self) : self._backend = Aer.get_backend('unitary_simulator') def run(self, circuit, shots, fit_to_constraints=True) : raise Exception("Aer Unitary Backend cannot currently generate shots. Use `get_unitary` instead.") def get_unitary(self, circuit, fit_to_constraints=True) : """ Obtains the unitary for a given quantum circuit :param circuit: The circuit to inspect :type circuit: Circuit :param fit_to_constraints: Forces the circuit to be decomposed into the correct gate set, defaults to True :type fit_to_constraints: bool, optional :return: The unitary of the circuit. Qubits are ordered with qubit 0 as the least significant qubit """ c = circuit.copy() if fit_to_constraints : Transform.RebaseToQiskit().apply(c) qc = tk_to_qiskit(c) qobj = assemble(qc) job = self._backend.run(qobj) return job.result().get_unitary(qc)
https://github.com/CQCL/pytket-qiskit
CQCL
################################################################################ # © Copyright 2021-2022 Zapata Computing Inc. ################################################################################ import math import os from copy import deepcopy import pytest import qiskit from qeqiskit.backend import QiskitBackend from qeqiskit.conversions import export_to_qiskit from qiskit.providers.exceptions import QiskitBackendNotFoundError from zquantum.core.circuits import CNOT, Circuit, X from zquantum.core.interfaces.backend_test import QuantumBackendTests from zquantum.core.measurement import Measurements @pytest.fixture( params=[ { "device_name": "ibmq_qasm_simulator", "api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"), "retry_delay_seconds": 1, }, ] ) def backend(request): return QiskitBackend(**request.param) @pytest.fixture( params=[ { "device_name": "ibmq_qasm_simulator", "api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"), "readout_correction": True, "n_samples_for_readout_calibration": 1, "retry_delay_seconds": 1, }, { "device_name": "ibmq_qasm_simulator", "api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"), "readout_correction": True, "n_samples_for_readout_calibration": 1, "retry_delay_seconds": 1, "noise_inversion_method": "pseudo_inverse", }, ], ) def backend_with_readout_correction(request): return QiskitBackend(**request.param) class TestQiskitBackend(QuantumBackendTests): def x_cnot_circuit(self): return Circuit([X(0), CNOT(1, 2)]) def x_circuit(self): return Circuit([X(0)]) def test_transform_circuitset_to_ibmq_experiments(self, backend): circuit = self.x_cnot_circuit() circuitset = (circuit,) * 2 n_samples = [backend.max_shots + 1] * 2 ( experiments, n_samples_for_experiments, multiplicities, ) = backend.transform_circuitset_to_ibmq_experiments(circuitset, n_samples) assert multiplicities == [2, 2] assert n_samples_for_experiments == [ backend.max_shots, 1, backend.max_shots, 1, ] assert len(set([circuit.name for circuit in experiments])) == 4 def test_batch_experiments(self, backend): circuit = self.x_cnot_circuit() n_circuits = backend.batch_size + 1 experiments = (export_to_qiskit(circuit),) * n_circuits n_samples_for_ibmq_circuits = (10,) * n_circuits batches, n_samples_for_batches = backend.batch_experiments( experiments, n_samples_for_ibmq_circuits ) assert len(batches) == 2 assert len(batches[0]) == backend.batch_size assert len(batches[1]) == 1 assert n_samples_for_batches == [10, 10] def test_aggregate_measurements(self, backend): multiplicities = [3, 1] circuit = export_to_qiskit(self.x_cnot_circuit()) circuit.barrier(range(3)) circuit.add_register(qiskit.ClassicalRegister(3)) circuit.measure(range(3), range(3)) batches = [ [circuit.copy("circuit1"), circuit.copy("circuit2")], [circuit.copy("circuit3"), circuit.copy("circuit4")], ] jobs = [ backend.execute_with_retries( batch, 10, ) for batch in batches ] measurements_set = backend.aggregate_measurements( jobs, batches, multiplicities, ) assert ( measurements_set[0].bitstrings == [ (1, 0, 0), ] * 30 ) assert ( measurements_set[1].bitstrings == [ (1, 0, 0), ] * 10 ) assert len(measurements_set) == 2 def test_run_circuitset_and_measure(self, backend): # Given num_circuits = 10 circuit = self.x_circuit() n_samples = 100 # When measurements_set = backend.run_circuitset_and_measure( [circuit] * num_circuits, [n_samples] * num_circuits ) # Then assert len(measurements_set) == num_circuits for measurements in measurements_set: assert len(measurements.bitstrings) == n_samples counts = measurements.get_counts() assert max(counts, key=counts.get) == "1" def test_execute_with_retries(self, backend): # This test has a race condition where the IBMQ server might finish # executing the first job before the last one is submitted. The test # will still pass in the case, but will not actually perform a retry. # We can address in the future by using a mock provider. # Given circuit = export_to_qiskit(self.x_circuit()) n_samples = 10 num_jobs = backend.device.job_limit().maximum_jobs + 1 # When jobs = [ backend.execute_with_retries([circuit], n_samples) for _ in range(num_jobs) ] # Then # The correct number of jobs were submitted assert len(jobs) == num_jobs # Each job has a unique ID assert len(set([job.job_id() for job in jobs])) == num_jobs def test_execute_with_retries_timeout(self, backend): # This test has a race condition where the IBMQ server might finish # executing the first job before the last one is submitted, causing the # test to fail. We can address this in the future using a mock provider. # Given circuit = export_to_qiskit(self.x_cnot_circuit()) n_samples = 10 backend.retry_timeout_seconds = 0 # need large number here as + 1 was not enough num_jobs = backend.device.job_limit().maximum_jobs + int(10e20) # Then with pytest.raises(RuntimeError): # When for _ in range(num_jobs): backend.execute_with_retries([circuit], n_samples) @pytest.mark.skip(reason="test will always succeed.") def test_run_circuitset_and_measure_readout_correction_retries( self, backend_with_readout_correction ): # This test has a race condition where the IBMQ server might finish # executing the first job before the last one is submitted. The test # will still pass in the case, but will not actually perform a retry. # We can address in the future by using a mock provider. # Given circuit = self.x_cnot_circuit() n_samples = 10 num_circuits = ( backend_with_readout_correction.batch_size * backend_with_readout_correction.device.job_limit().maximum_jobs + 1 ) # When measurements_set = backend_with_readout_correction.run_circuitset_and_measure( [circuit] * num_circuits, [n_samples] * num_circuits ) # Then assert len(measurements_set) == num_circuits def test_run_circuitset_and_measure_split_circuits_and_jobs(self, backend): # Given num_circuits = 2 # Minimum number of circuits to require batching circuit = self.x_cnot_circuit() n_samples = backend.max_shots + 1 backend.batch_size = 2 # Verify that we are actually going to need multiple batches assert ( num_circuits * math.ceil(n_samples / backend.max_shots) > backend.batch_size ) # When measurements_set = backend.run_circuitset_and_measure( [circuit] * num_circuits, [n_samples] * num_circuits ) # Then assert len(measurements_set) == num_circuits for measurements in measurements_set: assert len(measurements.bitstrings) == n_samples or len( measurements.bitstrings ) == backend.max_shots * math.ceil(n_samples / backend.max_shots) # Then (since SPAM error could result in unexpected bitstrings, we make sure # the most common bitstring is the one we expect) counts = measurements.get_counts() assert max(counts, key=counts.get) == "100" def test_readout_correction_works_run_circuit_and_measure( self, backend_with_readout_correction ): # Given circuit = self.x_cnot_circuit() # When backend_with_readout_correction.run_circuit_and_measure(circuit, n_samples=1) # Then assert backend_with_readout_correction.readout_correction assert backend_with_readout_correction.readout_correction_filters is not None def test_readout_correction_for_distributed_circuit( self, backend_with_readout_correction ): # Given num_circuits = 10 circuit = self.x_circuit() + X(5) n_samples = 100 # When measurements_set = backend_with_readout_correction.run_circuitset_and_measure( [circuit] * num_circuits, [n_samples] * num_circuits ) # Then assert backend_with_readout_correction.readout_correction assert ( backend_with_readout_correction.readout_correction_filters.get(str([0, 5])) is not None ) assert len(measurements_set) == num_circuits for measurements in measurements_set: assert len(measurements.bitstrings) == n_samples counts = measurements.get_counts() assert max(counts, key=counts.get) == "11" @pytest.mark.parametrize( "counts, active_qubits", [ ({"100000000000000000001": 10}, [0, 20]), ({"100000000000000000100": 10}, [0, 18, 20]), ({"001000000000000000001": 10}, [2, 20]), ], ) def test_subset_readout_correction( self, counts, active_qubits, backend_with_readout_correction ): # Given copied_counts = deepcopy(counts) # When mitigated_counts = backend_with_readout_correction._apply_readout_correction( copied_counts, active_qubits ) # Then assert backend_with_readout_correction.readout_correction assert backend_with_readout_correction.readout_correction_filters.get( str(active_qubits) ) assert copied_counts == pytest.approx(mitigated_counts, 10e-5) def test_subset_readout_correction_with_unspecified_active_qubits( self, backend_with_readout_correction ): # Given counts = {"11": 10} # When mitigated_counts = backend_with_readout_correction._apply_readout_correction( counts ) # Then assert backend_with_readout_correction.readout_correction assert backend_with_readout_correction.readout_correction_filters.get( str([0, 1]) ) assert counts == pytest.approx(mitigated_counts, 10e-5) def test_must_define_n_samples_for_readout_calibration_for_readout_correction( self, backend_with_readout_correction ): # Given counts, active_qubits = ({"11": 10}, None) backend_with_readout_correction.n_samples_for_readout_calibration = None # When/Then with pytest.raises(TypeError): backend_with_readout_correction._apply_readout_correction( counts, active_qubits ) def test_subset_readout_correction_for_multiple_subsets( self, backend_with_readout_correction ): # Given counts_1, active_qubits_1 = ({"100000000000000000001": 10}, [0, 20]) counts_2, active_qubits_2 = ({"001000000000000000001": 10}, [2, 20]) # When mitigated_counts_1 = backend_with_readout_correction._apply_readout_correction( counts_1, active_qubits_1 ) mitigated_counts_2 = backend_with_readout_correction._apply_readout_correction( counts_2, active_qubits_2 ) # Then assert backend_with_readout_correction.readout_correction assert backend_with_readout_correction.readout_correction_filters.get( str(active_qubits_1) ) assert backend_with_readout_correction.readout_correction_filters.get( str(active_qubits_2) ) assert counts_1 == pytest.approx(mitigated_counts_1, 10e-5) assert counts_2 == pytest.approx(mitigated_counts_2, 10e-5) def test_device_that_does_not_exist(self): # Given/When/Then with pytest.raises(QiskitBackendNotFoundError): QiskitBackend("DEVICE DOES NOT EXIST") def test_run_circuitset_and_measure_n_samples(self, backend): # We override the base test because the qiskit integration may return # more samples than requested due to the fact that each circuit in a # batch must have the same number of measurements. # Given backend.number_of_circuits_run = 0 backend.number_of_jobs_run = 0 first_circuit = Circuit( [ X(0), X(0), X(1), X(1), X(2), ] ) second_circuit = Circuit( [ X(0), X(1), X(2), ] ) n_samples = [2, 3] # When measurements_set = backend.run_circuitset_and_measure( [first_circuit, second_circuit], n_samples ) counts = measurements_set[0].get_counts() assert max(counts, key=counts.get) == "001" counts = measurements_set[1].get_counts() assert max(counts, key=counts.get) == "111" assert len(measurements_set[0].bitstrings) >= n_samples[0] assert len(measurements_set[1].bitstrings) >= n_samples[1] assert backend.number_of_circuits_run == 2 @pytest.mark.parametrize("n_samples", [1, 2, 10]) def test_run_circuit_and_measure_correct_num_measurements_attribute( self, backend, n_samples ): # Overriding to reduce number of samples required # Given backend.number_of_circuits_run = 0 backend.number_of_jobs_run = 0 circuit = self.x_cnot_circuit() # When measurements = backend.run_circuit_and_measure(circuit, n_samples) # Then assert isinstance(measurements, Measurements) assert len(measurements.bitstrings) == n_samples assert backend.number_of_circuits_run == 1 assert backend.number_of_jobs_run == 1 def test_run_circuit_and_measure_correct_indexing(self, backend): # Overriding to reduce number of samples required # Given backend.number_of_circuits_run = 0 backend.number_of_jobs_run = 0 circuit = self.x_cnot_circuit() n_samples = 2 # qiskit only runs simulators, so we can use low n_samples measurements = backend.run_circuit_and_measure(circuit, n_samples) counts = measurements.get_counts() assert max(counts, key=counts.get) == "100" assert backend.number_of_circuits_run == 1 assert backend.number_of_jobs_run == 1
https://github.com/CQCL/pytket-qiskit
CQCL
# Copyright 2020-2024 Quantinuum # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from typing import Any import numpy as np import pytest from qiskit import QuantumCircuit # type: ignore from qiskit.primitives import BackendSampler # type: ignore from qiskit.providers import JobStatus # type: ignore from qiskit_algorithms import Grover, AmplificationProblem, AlgorithmError # type: ignore from qiskit_aer import Aer # type: ignore from pytket.extensions.qiskit import ( AerBackend, AerStateBackend, AerUnitaryBackend, IBMQEmulatorBackend, ) from pytket.extensions.qiskit.tket_backend import TketBackend from pytket.circuit import OpType from pytket.architecture import Architecture, FullyConnected from .mock_pytket_backend import MockShotBackend skip_remote_tests: bool = os.getenv("PYTKET_RUN_REMOTE_TESTS") is None REASON = "PYTKET_RUN_REMOTE_TESTS not set (requires IBM configuration)" def circuit_gen(measure: bool = False) -> QuantumCircuit: qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.x(2) if measure: qc.measure_all() return qc def test_samples() -> None: qc = circuit_gen(True) b = AerBackend() for comp in (None, b.default_compilation_pass()): tb = TketBackend(b, comp) job = tb.run(qc, shots=100, memory=True) shots = job.result().get_memory() assert all(((r[0] == "1" and r[1] == r[2]) for r in shots)) counts = job.result().get_counts() assert all(((r[0] == "1" and r[1] == r[2]) for r in counts.keys())) def test_state() -> None: qc = circuit_gen() b = AerStateBackend() for comp in (None, b.default_compilation_pass()): tb = TketBackend(b, comp) job = tb.run(qc) state = job.result().get_statevector() qb = Aer.get_backend("aer_simulator_statevector") qc1 = qc.copy() qc1.save_state() job2 = qb.run(qc1) state2 = job2.result().get_statevector() assert np.allclose(state, state2) def test_unitary() -> None: qc = circuit_gen() b = AerUnitaryBackend() for comp in (None, b.default_compilation_pass()): tb = TketBackend(b, comp) job = tb.run(qc) u = job.result().get_unitary() qb = Aer.get_backend("aer_simulator_unitary") qc1 = qc.copy() qc1.save_unitary() job2 = qb.run(qc1) u2 = job2.result().get_unitary() assert np.allclose(u, u2) def test_cancel() -> None: b = AerBackend() tb = TketBackend(b) qc = circuit_gen() job = tb.run(qc, shots=1024) job.cancel() assert job.status() in [JobStatus.CANCELLED, JobStatus.DONE] @pytest.mark.skipif(skip_remote_tests, reason=REASON) def test_qiskit_counts(brisbane_emulator_backend: IBMQEmulatorBackend) -> None: num_qubits = 2 qc = QuantumCircuit(num_qubits) qc.h(0) qc.cx(0, 1) qc.measure_all() s = BackendSampler( TketBackend( brisbane_emulator_backend, comp_pass=brisbane_emulator_backend.default_compilation_pass( optimisation_level=0 ), ) ) job = s.run([qc], shots=10) res = job.result() assert res.metadata[0]["shots"] == 10 assert all(n in range(4) for n in res.quasi_dists[0].keys()) def test_architectures() -> None: # https://github.com/CQCL/pytket-qiskit/issues/14 arch_list = [None, Architecture([(0, 1), (1, 2)]), FullyConnected(3)] qc = circuit_gen(True) for arch in arch_list: # without architecture b = MockShotBackend(arch=arch) tb = TketBackend(b, b.default_compilation_pass()) job = tb.run(qc, shots=100, memory=True) shots = job.result().get_memory() assert all(((r[0] == "1" and r[1] == r[2]) for r in shots)) counts = job.result().get_counts() assert all(((r[0] == "1" and r[1] == r[2]) for r in counts.keys())) def test_grover() -> None: # https://github.com/CQCL/pytket-qiskit/issues/15 b = MockShotBackend() backend = TketBackend(b, b.default_compilation_pass()) sampler = BackendSampler(backend) oracle = QuantumCircuit(2) oracle.cz(0, 1) def is_good_state(bitstr: Any) -> bool: return sum(map(int, bitstr)) == 2 problem = AmplificationProblem(oracle=oracle, is_good_state=is_good_state) grover = Grover(sampler=sampler) result = grover.amplify(problem) assert result.top_measurement == "11" def test_unsupported_gateset() -> None: # Working with gatesets that are unsupported by qiskit requires # providing a custom pass manager. b = MockShotBackend(gate_set={OpType.Rz, OpType.PhasedX, OpType.ZZMax}) backend = TketBackend(b, b.default_compilation_pass()) sampler = BackendSampler(backend) oracle = QuantumCircuit(2) oracle.cz(0, 1) def is_good_state(bitstr: Any) -> bool: return sum(map(int, bitstr)) == 2 problem = AmplificationProblem(oracle=oracle, is_good_state=is_good_state) grover = Grover(sampler=sampler) # Qiskit will attempt to rebase a Grover op into the MockShotBackend gateset. # However, Rz, PhasedX and ZZMax gateset isn't supported by qiskit. # (tested with qiskit 0.44.1) with pytest.raises(AlgorithmError) as e: result = grover.amplify(problem) err_msg = "Unable to translate" assert err_msg in str(e.getrepr()) # By skipping transpilation we can rely on the backend's default compilation pass to # rebase. sampler = BackendSampler(backend, skip_transpilation=True) grover = Grover(sampler=sampler) problem = AmplificationProblem(oracle=oracle, is_good_state=is_good_state) result = grover.amplify(problem) assert result.top_measurement == "11"
https://github.com/CQCL/pytket-qiskit
CQCL
# Copyright 2019-2024 Quantinuum # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from collections import Counter from typing import List, Set, Union from math import pi import pytest from sympy import Symbol import numpy as np from qiskit import ( # type: ignore QuantumCircuit, QuantumRegister, ClassicalRegister, transpile, ) from qiskit.quantum_info import SparsePauliOp, Statevector, Operator # type: ignore from qiskit.transpiler import PassManager # type: ignore from qiskit.circuit.library import RYGate, MCMT, XXPlusYYGate, PauliEvolutionGate, UnitaryGate, RealAmplitudes # type: ignore import qiskit.circuit.library.standard_gates as qiskit_gates # type: ignore from qiskit.circuit import Parameter from qiskit.synthesis import SuzukiTrotter # type: ignore from qiskit_aer import Aer # type: ignore from qiskit.transpiler.passes import BasisTranslator # type: ignore from qiskit.circuit.equivalence_library import StandardEquivalenceLibrary # type: ignore from qiskit_ibm_runtime.fake_provider import FakeGuadalupe # type: ignore from qiskit.circuit.parameterexpression import ParameterExpression # type: ignore from qiskit.circuit.library import TwoLocal from qiskit import transpile from pytket.circuit import ( Circuit, CircBox, Unitary1qBox, Unitary2qBox, Unitary3qBox, OpType, Qubit, Bit, CustomGateDef, reg_eq, StatePreparationBox, ) from pytket.extensions.qiskit import tk_to_qiskit, qiskit_to_tk, IBMQBackend from pytket.extensions.qiskit.backends import qiskit_aer_backend from pytket.extensions.qiskit.qiskit_convert import _gate_str_2_optype from pytket.extensions.qiskit.tket_pass import TketPass, TketAutoPass from pytket.extensions.qiskit.result_convert import qiskit_result_to_backendresult from pytket.passes import ( RebaseTket, DecomposeBoxes, FullPeepholeOptimise, SequencePass, CliffordSimp, ) from pytket.utils.results import ( compare_statevectors, permute_rows_cols_in_unitary, compare_unitaries, ) skip_remote_tests: bool = os.getenv("PYTKET_RUN_REMOTE_TESTS") is None REASON = "PYTKET_RUN_REMOTE_TESTS not set (requires IBM configuration)" # helper function for testing def _get_qiskit_statevector(qc: QuantumCircuit) -> np.ndarray: """Given a QuantumCircuit, use aer_simulator_statevector to compute its statevector, return the vector with its endianness adjusted""" back = Aer.get_backend("aer_simulator_statevector") qc.save_state() job = back.run(qc) return np.array(job.result().data()["statevector"].reverse_qargs().data) def test_parameterised_circuit_global_phase() -> None: pass_1 = BasisTranslator( StandardEquivalenceLibrary, target_basis=FakeGuadalupe().configuration().basis_gates, ) pass_2 = CliffordSimp() qc = QuantumCircuit(2) qc.ryy(Parameter("MyParam"), 0, 1) pm = PassManager(pass_1) qc = pm.run(qc) tket_qc = qiskit_to_tk(qc) pass_2.apply(tket_qc) qc_2 = tk_to_qiskit(tket_qc) assert type(qc_2.global_phase) == ParameterExpression def test_classical_barrier_error() -> None: c = Circuit(1, 1) c.add_barrier([0], [0]) with pytest.raises(NotImplementedError): tk_to_qiskit(c) def test_convert_circuit_with_complex_params() -> None: with pytest.raises(ValueError): qiskit_op = SparsePauliOp(["Z"], coeffs=[1.0j]) evolved_op = PauliEvolutionGate( qiskit_op, time=1, synthesis=SuzukiTrotter(reps=1) ) evolution_circ = QuantumCircuit(1) evolution_circ.append(evolved_op, [0]) tk_circ = qiskit_to_tk(evolution_circ) DecomposeBoxes().apply(tk_circ) def get_test_circuit(measure: bool, reset: bool = True) -> QuantumCircuit: qr = QuantumRegister(4) cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr, name="test_circuit") qc.h(qr[0]) qc.cx(qr[1], qr[0]) qc.h(qr[0]) qc.cx(qr[0], qr[3]) qc.barrier(qr[3]) if reset: qc.reset(qr[3]) qc.rx(pi / 2, qr[3]) qc.ry(0, qr[1]) qc.z(qr[2]) qc.ccx(qr[0], qr[1], qr[2]) qc.ch(qr[0], qr[1]) qc.cp(pi / 4, qr[0], qr[1]) qc.cry(pi / 4, qr[0], qr[1]) qc.crz(pi / 4, qr[1], qr[2]) qc.cswap(qr[1], qr[2], qr[3]) qc.cp(pi / 5, qr[2], qr[3]) qc.cu(pi / 4, pi / 5, pi / 6, 0, qr[3], qr[0]) qc.cy(qr[0], qr[1]) qc.cz(qr[1], qr[2]) qc.ecr(qr[0], qr[1]) qc.id(qr[2]) qc.iswap(qr[3], qr[0]) qc.mcx([qr[0], qr[1], qr[2]], qr[3]) qc.mcx([qr[1], qr[2], qr[3]], qr[0]) qc.p(pi / 4, qr[1]) qc.r(pi / 5, pi / 6, qr[2]) qc.rxx(pi / 3, qr[2], qr[3]) qc.ryy(pi / 3, qr[3], qr[2]) qc.rz(pi / 4, qr[0]) qc.rzz(pi / 5, qr[1], qr[2]) qc.s(qr[3]) qc.sdg(qr[0]) qc.swap(qr[1], qr[2]) qc.t(qr[3]) qc.tdg(qr[0]) qc.u(pi / 3, pi / 4, pi / 5, qr[0]) qc.p(pi / 2, qr[1]) qc.u(pi / 2, pi / 2, pi / 3, qr[2]) qc.u(pi / 2, pi / 3, pi / 4, qr[3]) qc.x(qr[0]) qc.y(qr[1]) if measure: qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[2], cr[2]) qc.measure(qr[3], cr[3]) return qc def test_convert() -> None: qc = get_test_circuit(False) tkc = qiskit_to_tk(qc) assert qc.name == tkc.name qc1 = tk_to_qiskit(tkc) assert qc1.name == tkc.name backend = Aer.get_backend("aer_simulator_statevector") qc.save_state() qc = transpile(qc, backend) job = backend.run([qc]) state0 = job.result().get_statevector(qc) qc1.save_state() qc1 = transpile(qc1, backend) job1 = backend.run([qc1]) state1 = job1.result().get_statevector(qc1) assert np.allclose(state0, state1, atol=1e-10) def test_symbolic() -> None: pi2 = Symbol("pi2") pi3 = Symbol("pi3") pi0 = Symbol("pi0") tkc = Circuit(3, 3, name="test").Ry(pi2, 1).Rx(pi3, 1).CX(1, 0) tkc.add_phase(Symbol("pi0") * 2) RebaseTket().apply(tkc) qc = tk_to_qiskit(tkc) tkc2 = qiskit_to_tk(qc) assert tkc2.free_symbols() == {pi2, pi3, pi0} tkc2.symbol_substitution({pi2: pi / 2, pi3: pi / 3, pi0: 0.1}) backend = Aer.get_backend("aer_simulator_statevector") qc = tk_to_qiskit(tkc2) assert qc.name == tkc.name qc.save_state() job = backend.run([qc]) state1 = job.result().get_statevector(qc) state0 = np.array( [ 0.41273953 - 0.46964269j, 0.0 + 0.0j, -0.0 + 0.0j, -0.49533184 + 0.60309882j, 0.0 + 0.0j, 0.0 + 0.0j, -0.0 + 0.0j, -0.0 + 0.0j, ] ) assert np.allclose(state0, state1, atol=1e-10) def test_measures() -> None: qc = get_test_circuit(True) backend = qiskit_aer_backend("aer_simulator") qc = transpile(qc, backend) job = backend.run([qc], seed_simulator=7) counts0 = job.result().get_counts(qc) tkc = qiskit_to_tk(qc) qc = tk_to_qiskit(tkc) qc = transpile(qc, backend) job = backend.run([qc], seed_simulator=7) counts1 = job.result().get_counts(qc) for result, count in counts1.items(): result_str = result.replace(" ", "") if counts0[result_str] != count: assert False def test_boxes() -> None: c = Circuit(2) c.S(0) c.H(1) c.CX(0, 1) cbox = CircBox(c) d = Circuit(3, name="d") d.add_circbox(cbox, [0, 1]) d.add_circbox(cbox, [1, 2]) u = np.asarray([[0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]]) ubox = Unitary2qBox(u) d.add_unitary2qbox(ubox, 0, 1) qsc = tk_to_qiskit(d) d1 = qiskit_to_tk(qsc) assert len(d1.get_commands()) == 3 DecomposeBoxes().apply(d) DecomposeBoxes().apply(d1) assert d == d1 def test_Unitary1qBox() -> None: c = Circuit(1) u = np.asarray([[0, 1], [1, 0]]) ubox = Unitary1qBox(u) c.add_unitary1qbox(ubox, 0) # Convert to qiskit qc = tk_to_qiskit(c) # Verify that unitary from simulator is correct back = Aer.get_backend("aer_simulator_unitary") qc.save_unitary() job = back.run(qc).result() a = job.get_unitary(qc) u1 = np.asarray(a) assert np.allclose(u1, u) def test_Unitary2qBox() -> None: c = Circuit(2) u = np.asarray([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) ubox = Unitary2qBox(u) c.add_unitary2qbox(ubox, 0, 1) # Convert to qiskit qc = tk_to_qiskit(c) # Verify that unitary from simulator is correct back = Aer.get_backend("aer_simulator_unitary") qc.save_unitary() job = back.run(qc).result() a = job.get_unitary(qc) u1 = permute_rows_cols_in_unitary(np.asarray(a), (1, 0)) # correct for endianness assert np.allclose(u1, u) def test_Unitary3qBox() -> None: c = Circuit(3) u = np.asarray( [ [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0], ] ) ubox = Unitary3qBox(u) c.add_unitary3qbox(ubox, 0, 1, 2) # Convert to qiskit qc = tk_to_qiskit(c) # Verify that unitary from simulator is correct back = Aer.get_backend("aer_simulator_unitary") qc.save_unitary() job = back.run(qc).result() a = job.get_unitary(qc) u1 = permute_rows_cols_in_unitary( np.asarray(a), (2, 1, 0) ) # correct for endianness assert np.allclose(u1, u) def test_gates_phase() -> None: c = Circuit(4).SX(0).V(1).V(2).Vdg(3).Phase(0.5) qc = tk_to_qiskit(c) qr = QuantumRegister(4, "q") qc_correct = QuantumCircuit(qr) qc_correct.sx(qr[0]) qc_correct.sx(qr[1]) qc_correct.sx(qr[2]) qc_correct.sxdg(qr[3]) qc_correct.global_phase = pi / 4 assert qc == qc_correct def test_tketpass() -> None: qc = get_test_circuit(False, False) tkpass = FullPeepholeOptimise() back = Aer.get_backend("aer_simulator_unitary") for _ in range(12): tkc = qiskit_to_tk(qc) tkpass.apply(tkc) qc1 = tk_to_qiskit(tkc) qc1.save_unitary() res = back.run(qc1).result() u1 = res.get_unitary(qc1) qispass = TketPass(tkpass) pm = PassManager(qispass) qc2 = pm.run(qc) qc2.save_unitary() res = back.run(qc2).result() u2 = res.get_unitary(qc2) assert np.allclose(u1, u2) @pytest.mark.timeout(None) @pytest.mark.skipif(skip_remote_tests, reason=REASON) def test_tketautopass(brisbane_backend: IBMQBackend) -> None: backends = [ Aer.get_backend("aer_simulator_statevector"), qiskit_aer_backend("aer_simulator"), Aer.get_backend("aer_simulator_unitary"), ] backends.append(brisbane_backend._backend) for back in backends: for o_level in range(3): tkpass = TketAutoPass( back, o_level, token=os.getenv("PYTKET_REMOTE_QISKIT_TOKEN") ) qc = get_test_circuit(True) pm = PassManager(passes=tkpass) pm.run(qc) def test_instruction() -> None: # TKET-446 op = SparsePauliOp(["XXI", "YYI", "ZZZ"], [0.3, 0.5, -0.4]) evo_instr = PauliEvolutionGate(op, time=1.2, synthesis=SuzukiTrotter(reps=1)) evolution_circ = QuantumCircuit(3) evolution_circ.append(evo_instr, [0, 1, 2]) tk_circ = qiskit_to_tk(evolution_circ) cmds = tk_circ.get_commands() assert len(cmds) == 1 assert cmds[0].op.type == OpType.CircBox def test_conditions() -> None: box_c = Circuit(2, 2) box_c.Z(0) box_c.Y(1, condition_bits=[0, 1], condition_value=1) box_c.Measure(0, 0, condition_bits=[0, 1], condition_value=0) box = CircBox(box_c) u = np.asarray([[0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]]) ubox = Unitary2qBox(u) c = Circuit(2, 2, name="c") b = c.add_c_register("b", 1) c.add_circbox( box, [Qubit(0), Qubit(1), Bit(0), Bit(1)], condition_bits=[b[0]], condition_value=1, ) c.add_unitary2qbox( ubox, Qubit(0), Qubit(1), condition_bits=[b[0]], condition_value=0 ) c2 = c.copy() qc = tk_to_qiskit(c) c1 = qiskit_to_tk(qc) assert len(c1.get_commands()) == 2 DecomposeBoxes().apply(c) DecomposeBoxes().apply(c1) assert c == c1 c2.Z(1, condition=reg_eq(b, 1)) qc = tk_to_qiskit(c2) c1 = qiskit_to_tk(qc) assert len(c1.get_commands()) == 3 # conversion loses rangepredicates so equality comparison not valid def test_condition_errors() -> None: with pytest.raises(Exception) as errorinfo: c = Circuit(2, 2) b = c.add_c_register("b", 2) c.X(Qubit(0), condition_bits=[b[0], Bit(0)], condition_value=1) tk_to_qiskit(c) assert "Conditions can only use a single register" in str(errorinfo.value) with pytest.raises(Exception) as errorinfo: c = Circuit(2, 2) c.X(0, condition_bits=[1, 0], condition_value=1) tk_to_qiskit(c) assert "Conditions must be an entire register in order" in str(errorinfo.value) def test_correction() -> None: checked_x = Circuit(2, 1) checked_x.CX(0, 1) checked_x.X(0) checked_x.CX(0, 1) checked_x.Measure(1, 0) x_box = CircBox(checked_x) c = Circuit() target = Qubit("t", 0) ancilla = Qubit("a", 0) success = Bit("s", 0) c.add_qubit(target) c.add_qubit(ancilla) c.add_bit(success) c.add_circbox(x_box, args=[target, ancilla, success]) c.add_circbox( x_box, args=[target, ancilla, success], condition_bits=[success], condition_value=0, ) comp_pass = SequencePass([DecomposeBoxes(), RebaseTket()]) comp_pass.apply(c) tk_to_qiskit(c) def test_cnx() -> None: qr = QuantumRegister(5) qc = QuantumCircuit(qr, name="cnx_circuit") qc.mcx([0, 1, 2, 3], 4) c = qiskit_to_tk(qc) cmds = c.get_commands() assert len(cmds) == 1 cmd = cmds[0] assert cmd.op.type == OpType.CnX assert len(cmd.qubits) == 5 qregname = qc.qregs[0].name assert cmd.qubits[4] == Qubit(qregname, 4) def test_gate_str_2_optype() -> None: samples = { "barrier": OpType.Barrier, "cx": OpType.CX, "mcx": OpType.CnX, "x": OpType.X, } print([(_gate_str_2_optype[key], val) for key, val in samples.items()]) assert all(_gate_str_2_optype[key] == val for key, val in samples.items()) def test_customgate() -> None: a = Symbol("a") def_circ = Circuit(2) def_circ.CZ(0, 1) def_circ.Rx(a, 1) gate_def = CustomGateDef.define("MyCRx", def_circ, [a]) circ = Circuit(3) circ.Rx(0.1, 0) circ.Rx(0.4, 2) circ.add_custom_gate(gate_def, [0.2], [0, 1]) qc1 = tk_to_qiskit(circ) newcirc = qiskit_to_tk(qc1) print(repr(newcirc)) qc2 = tk_to_qiskit(newcirc) correct_circ = Circuit(3).Rx(0.1, 0).Rx(0.4, 2).CZ(0, 1).Rx(0.2, 1) correct_qc = tk_to_qiskit(correct_circ) backend = Aer.get_backend("aer_simulator_statevector") states = [] for qc in (qc1, qc2, correct_qc): qc.save_state() qc = transpile(qc, backend) job = backend.run([qc]) states.append(job.result().get_statevector(qc)) assert compare_statevectors(states[0], states[1]) assert compare_statevectors(states[1], states[2]) def test_convert_result() -> None: # testing fix to register order bug TKET-752 qr1 = QuantumRegister(1, name="q1") qr2 = QuantumRegister(2, name="q2") cr = ClassicalRegister(5, name="z") cr2 = ClassicalRegister(2, name="b") qc = QuantumCircuit(qr1, qr2, cr, cr2) qc.x(qr1[0]) qc.x(qr2[1]) # check statevector simulator = Aer.get_backend("aer_simulator_statevector") qc1 = qc.copy() qc1.save_state() qisk_result = simulator.run(qc1, shots=10).result() tk_res = next(qiskit_result_to_backendresult(qisk_result)) state = tk_res.get_state([Qubit("q2", 1), Qubit("q1", 0), Qubit("q2", 0)]) correct_state = np.zeros(1 << 3, dtype=complex) correct_state[6] = 1 + 0j assert compare_statevectors(state, correct_state) # check measured qc.measure(qr1[0], cr[0]) qc.measure(qr2[1], cr2[0]) simulator = qiskit_aer_backend("aer_simulator") qisk_result = simulator.run(qc, shots=10).result() tk_res = next(qiskit_result_to_backendresult(qisk_result)) one_bits = [Bit("z", 0), Bit("b", 0)] zero_bits = [Bit("z", i) for i in range(1, 5)] + [Bit("b", 1)] assert tk_res.get_counts(one_bits) == Counter({(1, 1): 10}) assert tk_res.get_counts(zero_bits) == Counter({(0, 0, 0, 0, 0): 10}) def add_x( qbit: int, qr: QuantumRegister, circuits: List[Union[Circuit, QuantumCircuit]] ) -> None: """Add an x gate to each circuit in a list, each one being either a tket or qiskit circuit.""" for circ in circuits: if isinstance(circ, Circuit): circ.add_gate(OpType.X, [qbit]) else: circ.x(qr[qbit]) def add_cnry( param: float, qbits: List[int], qr: QuantumRegister, circuits: List[Union[Circuit, QuantumCircuit]], ) -> None: """Add a CnRy gate to each circuit in a list, each one being either a tket or qiskit circuit.""" assert len(qbits) >= 2 for circ in circuits: if isinstance(circ, Circuit): circ.add_gate(OpType.CnRy, param, qbits) else: # param was "raw", so needs an extra PI. new_ry_gate = RYGate(param * pi) new_gate = MCMT( gate=new_ry_gate, num_ctrl_qubits=len(qbits) - 1, num_target_qubits=1 ) circ.append(new_gate, [qr[nn] for nn in qbits]) def assert_tket_circuits_identical(circuits: List[Circuit]) -> None: """Apart from the circuit names and qubit labels, assert that all circuits in the list are identical (i.e., identical gates), not just equivalent (having the same unitary matrix).""" if len(circuits) <= 1: return circ_copies = [] for nn in range(len(circuits)): assert type(circuits[nn]) == Circuit circ = circuits[nn].copy() circ.name = "tk_circ_must_be_same_name" qbs = circ.qubits qubit_map = {qbs[mm]: Qubit("node", mm) for mm in range(len(qbs))} circ.rename_units(qubit_map) # type: ignore circ_copies.append(circ) for nn in range(1, len(circ_copies)): assert circ_copies[0] == circ_copies[nn] def assert_equivalence( circuits: List[Union[Circuit, QuantumCircuit]], require_qk_conversions_equality: bool = True, require_tk_equality: bool = True, ) -> None: """Given a list of circuits (either tket or qiskit), simulate them to calculate unitary matrices, and fail if they are not all almost equal. Also, (unless require_tk_equality is false), assert that all tket circuits are equal. If require_qk_conversions_equality is true, treat qk->tk conversions as if they were originally tk circuits and test for equality (rather than just equivalence), if require_tk_equality is true. """ assert len(circuits) >= 2 tk_circuits = [] # We want unique circuit names, otherwise it confuses the Qiskit backend. names: Set[str] = set() for nn in range(len(circuits)): if isinstance(circuits[nn], Circuit): if require_tk_equality: tk_circuits.append(circuits[nn]) # Of course, use the tket simulator directly once available. # But not yet, so need to convert to qiskit circuits. circuits[nn] = tk_to_qiskit(circuits[nn]) elif require_qk_conversions_equality and require_tk_equality: tk_circuits.append(qiskit_to_tk(circuits[nn])) names.add(circuits[nn].name) # type: ignore assert len(names) == len(circuits) assert_tket_circuits_identical(tk_circuits) backend = Aer.get_backend("aer_simulator_unitary") unitaries = [] for circ in circuits: assert isinstance(circ, QuantumCircuit) circ1 = circ.copy() circ1.save_unitary() circ1 = transpile(circ1, backend) job = backend.run(circ1) unitaries.append(job.result().get_unitary(circ1)) for nn in range(1, len(circuits)): # Default np.allclose is very lax here, so use strict tolerances assert np.allclose(unitaries[0], unitaries[nn], atol=1e-14, rtol=0.0) def qcirc_to_tcirc(qcirc: QuantumCircuit) -> Circuit: """Changes the name also, to avoid backend result clashes.""" tcirc = qiskit_to_tk(qcirc) tcirc.name = "new tket circ from " + qcirc.name return tcirc def test_cnry_conversion() -> None: """This is for TKET-991. Maintain parallel circuits, check equivalence at each stage. It would be good to subsume this as part of general randomised tests, where we add random gates in sequence.""" tcirc = Circuit(3, name="parallel tcirc") qr = QuantumRegister(3, "q") qcirc = QuantumCircuit(qr, name="parallel qcirc") add_x(0, qr, [tcirc, qcirc]) add_x(1, qr, [tcirc, qcirc]) # It seems like we can test tket circuits for equality, # but not equivalence (since a direct tket simulator, with a # circuit->unitary function, is not yet available in pytket. # When it is available, we should add it here). # # Amusingly enough, it seems like we can test Qiskit circuits # for equivalence, but not for equality! # # Note that loops tk->qk->tk and qk->tk->qk should preserve # equivalence, but need not preserve equality because of different # gate sets. assert_equivalence([tcirc, qcirc]) add_x(2, qr, [tcirc, qcirc]) assert_equivalence([tcirc, qcirc]) new_tcirc = qcirc_to_tcirc(qcirc) assert_equivalence([tcirc, qcirc, new_tcirc]) add_x(0, qr, [tcirc, qcirc, new_tcirc]) assert_equivalence([tcirc, qcirc, new_tcirc]) add_cnry(0.1, [0, 1], qr, [tcirc, qcirc, new_tcirc]) add_x(2, qr, [tcirc, qcirc, new_tcirc]) # Because adding the CnRy gate to Qiskit circuits involves # circ.append(new_gate, ...), # converting back to tket produces a CircBox rather than a CnRy gate. # So we cannot get tket equality, even though we have equivalence assert_equivalence([tcirc, qcirc, new_tcirc], require_qk_conversions_equality=False) add_x(0, qr, [qcirc, tcirc, new_tcirc]) assert_equivalence([tcirc, qcirc, new_tcirc], require_qk_conversions_equality=False) add_cnry(0.2, [1, 0, 2], qr, [tcirc, qcirc, new_tcirc]) assert_equivalence([tcirc, qcirc, new_tcirc], require_qk_conversions_equality=False) add_x(2, qr, [tcirc, qcirc, new_tcirc]) add_x(1, qr, [tcirc, qcirc, new_tcirc]) add_x(0, qr, [tcirc, qcirc, new_tcirc]) assert_equivalence([tcirc, qcirc, new_tcirc], require_qk_conversions_equality=False) new_tcirc = qcirc_to_tcirc(qcirc) assert_equivalence( [tcirc, qcirc, new_tcirc], require_qk_conversions_equality=False, # We've done qk->tk conversion to get new_tcirc, so # we do not expect equality between new_tcirc and tcirc. require_tk_equality=False, ) # pytket-extensions issue #72 def test_parameter_equality() -> None: param_a = Parameter("a") param_b = Parameter("b") circ = QuantumCircuit(2) circ.rx(param_a, 0) circ.ry(param_b, 1) circ.cx(0, 1) # fails with preserve_param_uuid=False # as Parameter uuid attribute is not preserved # and so fails equality check at assign_parameters pytket_circ = qiskit_to_tk(circ, preserve_param_uuid=True) final_circ = tk_to_qiskit(pytket_circ) assert final_circ.parameters == circ.parameters param_dict = dict(zip([param_a, param_b], [1, 2])) final_circ.assign_parameters(param_dict, inplace=True) assert len(final_circ.parameters) == 0 # https://github.com/CQCL/pytket-extensions/issues/275 def test_convert_multi_c_reg() -> None: c = Circuit() q0, q1 = c.add_q_register("q", 2) c.add_c_register("c", 2) [m0] = c.add_c_register("m", 1) c.add_gate(OpType.X, [], [q1], condition_bits=[m0], condition_value=1) c.CX(q0, q1) c.add_gate(OpType.TK1, [0.5, 0.5, 0.5], [q0]) qcirc = tk_to_qiskit(c) circ = qiskit_to_tk(qcirc) assert circ.get_commands()[0].args == [m0, q1] # test that tk_to_qiskit works after adding OpType.CRx and OpType.CRy def test_crx_and_cry() -> None: tk_circ = Circuit(2) tk_circ.CRx(0.5, 0, 1) tk_circ.CRy(0.2, 1, 0) qiskit_circ = tk_to_qiskit(tk_circ) ops_dict = qiskit_circ.count_ops() assert ops_dict["crx"] == 1 and ops_dict["cry"] == 1 # test that tk_to_qiskit works for gates which don't have # an exact substitution in qiskit e.g. ZZMax # See issue "Add support for ZZMax gate in converters" #486 def test_rebased_conversion() -> None: tket_circzz = Circuit(3) tket_circzz.V(0).H(1).Vdg(2) tket_circzz.CV(0, 2) tket_circzz.add_gate(OpType.ZZMax, [0, 1]) tket_circzz.add_gate(OpType.TK1, [0.1, 0.2, 0.3], [2]) tket_circzz.add_gate(OpType.PhasedISWAP, [0.25, -0.5], [0, 2]) qiskit_circzz = tk_to_qiskit(tket_circzz) tket_circzz2 = qiskit_to_tk(qiskit_circzz) u1 = tket_circzz.get_unitary() u2 = tket_circzz2.get_unitary() assert compare_unitaries(u1, u2) @pytest.mark.xfail(reason="PauliEvolutionGate with symbolic parameter not supported") def test_parametrized_evolution() -> None: operator = SparsePauliOp(["XXZ", "YXY"], coeffs=[1.0, 0.5]) * Parameter("x") evolved_circ_op = PauliEvolutionGate( operator, time=1, synthesis=SuzukiTrotter(reps=2, order=4) ) qc = QuantumCircuit(3) qc.append(evolved_circ_op, [0, 1, 2]) tk_qc: Circuit = qiskit_to_tk(qc) assert len(tk_qc.free_symbols()) == 1 def test_multicontrolled_gate_conversion() -> None: my_qc = QuantumCircuit(4) my_qc.append(qiskit_gates.YGate().control(3), [0, 1, 2, 3]) my_qc.append(qiskit_gates.RYGate(0.25).control(3), [0, 1, 2, 3]) my_qc.append(qiskit_gates.ZGate().control(3), [0, 1, 2, 3]) my_tkc = qiskit_to_tk(my_qc) my_tkc.add_gate(OpType.CnRy, [0.95], [0, 1, 2, 3]) my_tkc.add_gate(OpType.CnZ, [1, 2, 3, 0]) my_tkc.add_gate(OpType.CnY, [0, 1, 3, 2]) unitary_before = my_tkc.get_unitary() assert my_tkc.n_gates_of_type(OpType.CnY) == 2 assert my_tkc.n_gates_of_type(OpType.CnZ) == 2 assert my_tkc.n_gates_of_type(OpType.CnRy) == 2 my_new_qc = tk_to_qiskit(my_tkc) qiskit_ops = my_new_qc.count_ops() assert qiskit_ops["c3y"] and qiskit_ops["c3z"] and qiskit_ops["c3ry"] == 2 tcirc = qiskit_to_tk(my_new_qc) unitary_after = tcirc.get_unitary() assert compare_unitaries(unitary_before, unitary_after) def test_qcontrolbox_conversion() -> None: qr = QuantumRegister(3) qc = QuantumCircuit(qr) c2h_gate = qiskit_gates.HGate().control(2) qc.append(c2h_gate, qr) c = qiskit_to_tk(qc) assert c.n_gates == 1 assert c.n_gates_of_type(OpType.QControlBox) == 1 c3rx_gate = qiskit_gates.RXGate(0.7).control(3) c3rz_gate = qiskit_gates.RZGate(pi / 4).control(3) c2rzz_gate = qiskit_gates.RZZGate(pi / 3).control(2) qc2 = QuantumCircuit(4) qc2.append(c3rz_gate, [0, 1, 3, 2]) qc2.append(c3rx_gate, [0, 1, 2, 3]) qc2.append(c2rzz_gate, [0, 1, 2, 3]) tkc2 = qiskit_to_tk(qc2) assert tkc2.n_gates == 3 assert tkc2.n_gates_of_type(OpType.QControlBox) == 3 # Ensures that the tk_to_qiskit converter does not cancel redundant gates def test_tk_to_qiskit_redundancies() -> None: h_circ = Circuit(1).H(0).H(0) qc_h = tk_to_qiskit(h_circ) assert qc_h.count_ops()["h"] == 2 def test_ccx_conversion() -> None: # https://github.com/CQCL/pytket-qiskit/issues/117 c00 = QuantumCircuit(3) c00.ccx(0, 1, 2, 0) # 0 = "00" (little-endian) assert compare_unitaries( qiskit_to_tk(c00).get_unitary(), Circuit(3).X(0).X(1).CCX(0, 1, 2).X(0).X(1).get_unitary(), ) c10 = QuantumCircuit(3) c10.ccx(0, 1, 2, 1) # 1 = "10" (little-endian) assert compare_unitaries( qiskit_to_tk(c10).get_unitary(), Circuit(3).X(1).CCX(0, 1, 2).X(1).get_unitary(), ) c01 = QuantumCircuit(3) c01.ccx(0, 1, 2, 2) # 2 = "01" (little-endian) assert compare_unitaries( qiskit_to_tk(c01).get_unitary(), Circuit(3).X(0).CCX(0, 1, 2).X(0).get_unitary(), ) c11 = QuantumCircuit(3) c11.ccx(0, 1, 2, 3) # 3 = "11" (little-endian) assert compare_unitaries( qiskit_to_tk(c11).get_unitary(), Circuit(3).CCX(0, 1, 2).get_unitary(), ) def test_conditional_conversion() -> None: c = Circuit(1, 2, "conditional_circ") c.X(0, condition_bits=[0], condition_value=1) c_qiskit = tk_to_qiskit(c) c_tket = qiskit_to_tk(c_qiskit) assert c_tket.to_dict() == c.to_dict() def test_conditional_conversion_2() -> None: c = Circuit(1, 2, "conditional_circ_2") c.X(0, condition_bits=[1], condition_value=1) c_qiskit = tk_to_qiskit(c) c_tket = qiskit_to_tk(c_qiskit) assert c_tket.to_dict() == c.to_dict() # https://github.com/CQCL/pytket-qiskit/issues/100 def test_state_prep_conversion_array_or_list() -> None: # State prep with list of real amplitudes ghz_state_permuted = np.array([0, 0, 1 / np.sqrt(2), 0, 0, 0, 0, 1 / np.sqrt(2)]) qc_sp = QuantumCircuit(3) qc_sp.prepare_state(ghz_state_permuted) tk_sp = qiskit_to_tk(qc_sp) assert tk_sp.n_gates_of_type(OpType.StatePreparationBox) == 1 assert tk_sp.n_gates == 1 assert compare_statevectors(tk_sp.get_statevector(), ghz_state_permuted) # State prep with ndarray of complex amplitudes qc_sp2 = QuantumCircuit(2) complex_statvector = np.array([1 / np.sqrt(2), 0, -1.0j / np.sqrt(2), 0]) qc_sp2.initialize(complex_statvector, qc_sp2.qubits) tk_sp2 = qiskit_to_tk(qc_sp2) assert tk_sp2.n_gates_of_type(OpType.StatePreparationBox) == 1 assert tk_sp2.n_gates == 1 # test tket -> qiskit conversion converted_qiskit_qc = tk_to_qiskit(tk_sp2) assert converted_qiskit_qc.count_ops()["initialize"] == 1 tk_sp3 = qiskit_to_tk(converted_qiskit_qc) # check circuit decomposes as expected DecomposeBoxes().apply(tk_sp3) assert tk_sp3.n_gates_of_type(OpType.Reset) == 2 state_arr = 1 / np.sqrt(2) * np.array([1, 1, 0, 0]) sv = Statevector(state_arr) qc_2 = QuantumCircuit(2) qc_2.prepare_state(sv, [0, 1]) tkc_2 = qiskit_to_tk(qc_2) assert tkc_2.n_gates_of_type(OpType.StatePreparationBox) == 1 def test_state_prep_conversion_with_int() -> None: qc = QuantumCircuit(4) qc.prepare_state(7, qc.qubits) tkc7 = qiskit_to_tk(qc) assert tkc7.n_gates_of_type(OpType.X) == 3 qc_sv = _get_qiskit_statevector(qc.decompose()) assert compare_statevectors(tkc7.get_statevector(), qc_sv) int_statevector = Statevector.from_int(5, 8) qc_s = QuantumCircuit(3) qc_s.prepare_state(int_statevector) # unfortunately Aer doesn't support state_preparation # instructions so we decompose first d_qc_s = qc_s.decompose(reps=5) sv_int = _get_qiskit_statevector(d_qc_s) tkc_int = qiskit_to_tk(qc_s) tkc_int_sv = tkc_int.get_statevector() assert compare_statevectors(tkc_int_sv, sv_int) def test_state_prep_conversion_with_str() -> None: qc = QuantumCircuit(5) qc.initialize("rl+-1") tk_circ = qiskit_to_tk(qc) assert tk_circ.n_gates_of_type(OpType.Reset) == 5 assert tk_circ.n_gates_of_type(OpType.H) == 4 assert tk_circ.n_gates_of_type(OpType.X) == 2 qc_string_sp = QuantumCircuit(3) qc_string_sp.prepare_state("r-l") decomposed_qc = qc_string_sp.decompose(reps=4) qiskit_sv = _get_qiskit_statevector(decomposed_qc) tk_string_sp = qiskit_to_tk(qc_string_sp) assert tk_string_sp.n_gates_of_type(OpType.H) == 3 assert tk_string_sp.n_gates_of_type(OpType.Sdg) == 1 assert compare_statevectors(qiskit_sv, tk_string_sp.get_statevector()) sv_str = Statevector.from_label("rr+-") sv_qc = QuantumCircuit(4) sv_qc.prepare_state(sv_str) decomposed_sv_qc = sv_qc.decompose(reps=6) sv_array = _get_qiskit_statevector(decomposed_sv_qc) tkc_sv = qiskit_to_tk(sv_qc) assert compare_statevectors(sv_array, tkc_sv.get_statevector()) def test_conversion_to_tket_with_and_without_resets() -> None: test_state = 1 / np.sqrt(3) * np.array([1, 1, 0, 0, 0, 0, 1, 0]) tket_sp_reset = StatePreparationBox(test_state, with_initial_reset=True) tk_circ_reset = Circuit(3).add_gate(tket_sp_reset, [0, 1, 2]) qiskit_qc_init = tk_to_qiskit(tk_circ_reset) assert qiskit_qc_init.count_ops()["initialize"] == 1 tket_sp_no_reset = StatePreparationBox(test_state, with_initial_reset=False) tket_circ_no_reset = Circuit(3).add_gate(tket_sp_no_reset, [0, 1, 2]) tkc_sv = tket_circ_no_reset.get_statevector() qiskit_qc_sp = tk_to_qiskit(tket_circ_no_reset) assert qiskit_qc_sp.count_ops()["state_preparation"] == 1 decomp_qc = qiskit_qc_sp.decompose(reps=5) qiskit_state = _get_qiskit_statevector(decomp_qc) assert compare_statevectors(tkc_sv, qiskit_state) def test_unitary_gate() -> None: # https://github.com/CQCL/pytket-qiskit/issues/122 qkc = QuantumCircuit(3) for n in range(4): u = np.eye(1 << n, dtype=complex) gate = UnitaryGate(u) qkc.append(gate, list(range(n))) tkc = qiskit_to_tk(qkc) cmds = tkc.get_commands() assert len(cmds) == 3 assert cmds[0].op.type == OpType.Unitary1qBox assert cmds[1].op.type == OpType.Unitary2qBox assert cmds[2].op.type == OpType.Unitary3qBox def test_ccz_conversion() -> None: qc_ccz = QuantumCircuit(4) qc_ccz.append(qiskit_gates.CCZGate(), [0, 1, 2]) qc_ccz.append(qiskit_gates.CCZGate(), [3, 1, 0]) tkc_ccz = qiskit_to_tk(qc_ccz) assert tkc_ccz.n_gates_of_type(OpType.CnZ) == tkc_ccz.n_gates == 2 # bidirectional CnZ conversion already supported qc_ccz2 = tk_to_qiskit(tkc_ccz) assert qc_ccz2.count_ops()["ccz"] == 2 tkc_ccz2 = qiskit_to_tk(qc_ccz2) assert compare_unitaries(tkc_ccz.get_unitary(), tkc_ccz2.get_unitary()) def test_csx_conversion() -> None: qc_csx = QuantumCircuit(2) qc_csx.append(qiskit_gates.CSXGate(), [0, 1]) qc_csx.append(qiskit_gates.CSXGate(), [1, 0]) converted_tkc = qiskit_to_tk(qc_csx) assert converted_tkc.n_gates == 2 assert converted_tkc.n_gates_of_type(OpType.CSX) == 2 u1 = converted_tkc.get_unitary() new_tkc_csx = Circuit(2) new_tkc_csx.add_gate(OpType.CSX, [0, 1]).add_gate(OpType.CSX, [1, 0]) u2 = new_tkc_csx.get_unitary() assert compare_unitaries(u1, u2) converted_qc = tk_to_qiskit(new_tkc_csx) assert converted_qc.count_ops()["csx"] == 2 qc_c3sx = QuantumCircuit(4) qc_c3sx.append(qiskit_gates.C3SXGate(), [0, 1, 2, 3]) tkc_c3sx = qiskit_to_tk(qc_c3sx) assert tkc_c3sx.n_gates == tkc_c3sx.n_gates_of_type(OpType.QControlBox) == 1 def test_CS_and_CSdg() -> None: qiskit_qc = QuantumCircuit(2) qiskit_qc.append(qiskit_gates.CSGate(), [0, 1]) qiskit_qc.append(qiskit_gates.CSdgGate(), [0, 1]) qiskit_qc.append(qiskit_gates.CSGate(), [1, 0]) qiskit_qc.append(qiskit_gates.CSdgGate(), [1, 0]) tkc = qiskit_to_tk(qiskit_qc) assert tkc.n_gates_of_type(OpType.QControlBox) == 4 def test_failed_conversion_error() -> None: qc = QuantumCircuit(2) qc.append(XXPlusYYGate(0.1), [0, 1]) # add unsupported gate with pytest.raises( NotImplementedError, match=r"Conversion of qiskit's xx_plus_yy instruction" ): qiskit_to_tk(qc) # https://github.com/CQCL/pytket-qiskit/issues/200 def test_RealAmplitudes_numeric_params() -> None: qc = QuantumCircuit(3) params = [np.pi / 2] * 9 real_amps1 = RealAmplitudes(3, reps=2) real_amps2 = real_amps1.assign_parameters(params) qc.compose(real_amps2, qubits=[0, 1, 2], inplace=True) # Unitary operator of the qiskit circuit. Order reversed from little -> big endian. # The reversal means we can check it for equivalence with a tket unitary qiskit_unitary = Operator(qc.reverse_bits()).data converted_tkc = qiskit_to_tk(qc) assert converted_tkc.n_gates == 1 assert converted_tkc.n_gates_of_type(OpType.CircBox) == 1 circbox_op = converted_tkc.get_commands()[0].op assert isinstance(circbox_op, CircBox) assert circbox_op.get_circuit().name == "RealAmplitudes" DecomposeBoxes().apply(converted_tkc) assert converted_tkc.n_gates_of_type(OpType.CX) == 4 assert converted_tkc.n_gates_of_type(OpType.Ry) == 9 unitary1 = converted_tkc.get_unitary() qc2 = tk_to_qiskit(converted_tkc) tkc2 = qiskit_to_tk(qc2) unitary2 = tkc2.get_unitary() assert compare_unitaries(qiskit_unitary, unitary1) assert compare_unitaries(unitary1, unitary2) # https://github.com/CQCL/pytket-qiskit/issues/256 def test_symbolic_param_conv() -> None: qc = TwoLocal(1, "ry", "cz", reps=1, entanglement="linear") qc_transpiled = transpile( qc, basis_gates=["sx", "rz", "cx", "x"], optimization_level=3 ) tket_qc = qiskit_to_tk(qc_transpiled) CliffordSimp().apply(tket_qc) transformed_qc = tk_to_qiskit(tket_qc) qc_transpiled_again = transpile(transformed_qc, basis_gates=["sx", "rz", "cx", "x"]) qc_transpiled_again = qc_transpiled_again.assign_parameters( { qc_transpiled_again.parameters[i]: 0 for i in range(len(qc_transpiled_again.parameters)) } ) # https://github.com/CQCL/pytket-qiskit/issues/337 def test_nonregister_bits() -> None: c = Circuit(1).X(0).measure_all() c.rename_units({Bit(0): Bit(1)}) with pytest.raises(NotImplementedError): tk_to_qiskit(c)
https://github.com/mtreinish/qiskit-workshop
mtreinish
https://github.com/LauraGentini/QRL
LauraGentini
__author__ = 'QRL_team' from qiskit import * from qiskit.circuit.library import GroverOperator from qiskit.quantum_info import Statevector import numpy as np from math import ceil class GroverMazeLearner: """ Inits a quantum QLearner object for given environment. Environment must be discrete and of "maze type", with the last state as the goal """ def __init__(self, env): self.env = env # gym.make("FrozenLake-v0", is_slippery=False) # state and action spaces dims self.obs_dim = self.env.observation_space.n self.acts_dim = self.env.action_space.n # dim of qubits register needed to encode all actions self.acts_reg_dim = ceil(np.log2(self.acts_dim)) # optimal number of steps in original Grover's algorithm self.max_grover_steps = int(round( np.pi / (4 * np.arcsin(1. / np.sqrt(2 ** self.acts_reg_dim))) - 0.5)) # quality values self.state_vals = np.zeros(self.obs_dim) # grover steps taken self.grover_steps = np.zeros((self.obs_dim, self.acts_dim), dtype=int) # boolean flags to signal maximum amplitude amplification reached self.grover_steps_flag = np.zeros((self.obs_dim, self.acts_dim), dtype=bool) # learner hyperparms (eps still not used) self.hyperparams = {'k': -1, 'alpha': 0.05, 'gamma': 0.99, 'eps': 0.01, 'max_epochs': 1000, 'max_steps': 100 , 'graphics': True} # current state self.state = self.env.reset() # current action self.action = 0 # list of grover oracles self.grover_ops = self._init_grover_ops() # list of state-action circuits self.acts_circs = self._init_acts_circs() # qiskit simulator self.SIM = Aer.get_backend('qasm_simulator') def set_hyperparams(self, hyperdict): """ Set learner's hyperparameters :param hyperdict: a dict with same keys as self's :return: """ self.hyperparams = hyperdict def _init_acts_circs(self): """ Inits state-action circuits :return: list of qiskit circuits, initialized in full superposition """ circs = [QuantumCircuit(self.acts_reg_dim, name='|as_{}>'.format(i)) for i in range(self.obs_dim)] for c in circs: c.h(list(range(self.acts_reg_dim))) return circs def _update_statevals(self, reward, new_state): """ Bellman equation for state values update :param reward: instantaneous reward received by the agent :param new_state: state reached upon taking previous action :return: """ self.state_vals[self.state] += self.hyperparams['alpha']*(reward + self.hyperparams['gamma']*self.state_vals[new_state] - self.state_vals[self.state]) def _eval_grover_steps(self, reward, new_state): """ Choose how many grover step to take based on instantaneous reward and value of new state :param reward: the instantaneous reward received by the agent :param new_state: the new state visited by the agent :return: number of grover steps to be taken, if it exceeds the theoretical optimal number the latter is returned instead """ steps_num = int(self.hyperparams['k']*(reward + self.state_vals[new_state])) return min(steps_num, self.max_grover_steps) def _init_grover_ops(self): """ Inits grover oracles for the actions set :return: a list of qiskit instructions ready to be appended to circuit """ states_binars = [format(i, '0{}b'.format(self.acts_reg_dim)) for i in range(self.acts_dim)] targ_states = [Statevector.from_label(s) for s in states_binars] grops = [GroverOperator(oracle=ts) for ts in targ_states] return [g.to_instruction() for g in grops] def _run_grover(self): """ DEPRECATED :return: """ # deploy grover ops on acts_circs gsteps = self.grover_steps[self.state, self.action] circ = self.acts_circs[self.state] op = self.grover_ops[self.action] for _ in range(gsteps): circ.append(op, list(range(self.acts_reg_dim))) self.acts_circs[self.state] = circ def _run_grover_bool(self): """ Update state-action circuits based on evaluated steps :return: """ flag = self.grover_steps_flag[self.state, :] gsteps = self.grover_steps[self.state, self.action] circ = self.acts_circs[self.state] op = self.grover_ops[self.action] if not flag.any(): for _ in range(gsteps): circ.append(op, list(range(self.acts_reg_dim))) if gsteps >= self.max_grover_steps and not flag.any(): self.grover_steps_flag[self.state, self.action] = True self.acts_circs[self.state] = circ def _take_action(self): """ Measures the state-action circuit corresponding to current state and decides next action :return: action to be taken, int """ circ = self.acts_circs[self.state] circ_tomeasure = circ.copy() circ_tomeasure.measure_all() # circ_tomeasure = transpile(circ_tomeasure) # print(circ.draw()) job = execute(circ_tomeasure, backend=self.SIM, shots=1) result = job.result() counts = result.get_counts() action = int((list(counts.keys()))[0], 2) return action def train(self): """ groverize and measure action qstate -> take corresp action obtain: newstate, reward, terminationflag update stateval, grover_steps for epoch in epochs until max_epochs is reached :return: dictionary of trajectories """ traj_dict = {} # set initial max_steps optimal_steps = self.hyperparams['max_steps'] for epoch in range(self.hyperparams['max_epochs']): if epoch % 10 == 0: print("Processing epoch {} ...".format(epoch)) # reset env self.state = self.env.reset() # init list for traj traj = [self.state] if self.hyperparams['graphics']: self.env.render() for step in range(optimal_steps): print('Taking step {0}/{1}'.format(step, optimal_steps), end='\r') # print('STATE: ', self.state) # Select action self.action = self._take_action() # take action new_state, reward, done, _ = self.env.step(self.action) if new_state == self.state: reward -= 10 done = True if new_state == self.obs_dim - 1: reward += 99 # update optimal traj len optimal_steps = step + 1 elif not done: reward -= 1 # print('REWARD: ', reward) # update statevals and grover steps self._update_statevals(reward, new_state) self.grover_steps[self.state, self.action] = self._eval_grover_steps(reward, new_state) # amplify amplitudes with grover # self._run_grover() self._run_grover_bool() # render if curious if self.hyperparams['graphics']: self.env.render() # save transition traj.append(new_state) # quit epoch if done if done: break # move to new state self.state = new_state # print('STATE_VALS: ', self.state_vals) # print('GROVER_STEPS: ', self.grover_steps) traj_dict['epoch_{}'.format(epoch)] = traj # return trajectories return traj_dict
https://github.com/LauraGentini/QRL
LauraGentini
# General imports import numpy as np import matplotlib.pyplot as plt # Qiskit Circuit imports from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression from qiskit.circuit.library import TwoLocal # Qiskit imports import qiskit as qk from qiskit.utils import QuantumInstance # Qiskit Machine Learning imports import qiskit_machine_learning as qkml from qiskit_machine_learning.neural_networks import CircuitQNN from qiskit_machine_learning.connectors import TorchConnector # PyTorch imports import torch from torch import Tensor from torch.nn import MSELoss from torch.optim import LBFGS, SGD, Adam, RMSprop # OpenAI Gym import import gym # Fix seed for reproducibility seed = 42 np.random.seed(seed) torch.manual_seed(seed); # To get smooth animations on Jupyter Notebooks. # Note: these plotting function are taken from https://github.com/ageron/handson-ml2 import matplotlib as mpl import matplotlib.animation as animation mpl.rc('animation', html='jshtml') def update_scene(num, frames, patch): patch.set_data(frames[num]) return patch, def plot_animation(frames, repeat=False, interval=40): fig = plt.figure() patch = plt.imshow(frames[0]) plt.axis('off') anim = animation.FuncAnimation( fig, update_scene, fargs=(frames, patch), frames=len(frames), repeat=repeat, interval=interval) plt.close() return anim def encoding_circuit(inputs, num_qubits = 4, *args): """ Encode classical input data (i.e. the state of the enironment) on a quantum circuit. To be used inside the `parametrized_circuit` function. Args ------- inputs (list): a list containing the classical inputs. num_qubits (int): number of qubits in the quantum circuit. Return ------- qc (QuantumCircuit): quantum circuit with encoding gates. """ qc = qk.QuantumCircuit(num_qubits) # Encode data with a RX rotation for i in range(len(inputs)): qc.rx(inputs[i], i) return qc def parametrized_circuit(num_qubits = 4, reuploading = False, reps = 2, insert_barriers = True, meas = False): """ Create the Parameterized Quantum Circuit (PQC) for estimating Q-values. It implements the architecure proposed in Skolik et al. arXiv:2104.15084. Args ------- num_qubit (int): number of qubits in the quantum circuit. reuploading (bool): True if want to use data reuploading technique. reps (int): number of repetitions (layers) in the variational circuit. insert_barrirerd (bool): True to add barriers in between gates, for better drawing of the circuit. meas (bool): True to add final measurements on the qubits. Return ------- qc (QuantumCircuit): the full parametrized quantum circuit. """ qr = qk.QuantumRegister(num_qubits, 'qr') qc = qk.QuantumCircuit(qr) if meas: qr = qk.QuantumRegister(num_qubits, 'qr') cr = qk.ClassicalRegister(num_qubits, 'cr') qc = qk.QuantumCircuit(qr,cr) if not reuploading: # Define a vector containg Inputs as parameters (*not* to be optimized) inputs = qk.circuit.ParameterVector('x', num_qubits) # Encode classical input data qc.compose(encoding_circuit(inputs, num_qubits = num_qubits), inplace = True) if insert_barriers: qc.barrier() # Variational circuit qc.compose(TwoLocal(num_qubits, ['ry', 'rz'], 'cz', 'circular', reps=reps, insert_barriers= insert_barriers, skip_final_rotation_layer = True), inplace = True) if insert_barriers: qc.barrier() # Add final measurements if meas: qc.measure(qr,cr) elif reuploading: # Define a vector containg Inputs as parameters (*not* to be optimized) inputs = qk.circuit.ParameterVector('x', num_qubits) # Define a vector containng variational parameters θ = qk.circuit.ParameterVector('θ', 2 * num_qubits * reps) # Iterate for a number of repetitions for rep in range(reps): # Encode classical input data qc.compose(encoding_circuit(inputs, num_qubits = num_qubits), inplace = True) if insert_barriers: qc.barrier() # Variational circuit (does the same as TwoLocal from Qiskit) for qubit in range(num_qubits): qc.ry(θ[qubit + 2*num_qubits*(rep)], qubit) qc.rz(θ[qubit + 2*num_qubits*(rep) + num_qubits], qubit) if insert_barriers: qc.barrier() # Add entanglers (this code is for a circular entangler) qc.cz(qr[-1], qr[0]) for qubit in range(num_qubits-1): qc.cz(qr[qubit], qr[qubit+1]) if insert_barriers: qc.barrier() # Add final measurements if meas: qc.measure(qr,cr) return qc # Select the number of qubits num_qubits = 4 # Generate the Parametrized Quantum Circuit (note the flags reuploading and reps) qc = parametrized_circuit(num_qubits = num_qubits, reuploading = True, reps = 6) # Fetch the parameters from the circuit and divide them in Inputs (X) and Trainable Parameters (params) # The first four parameters are for the inputs X = list(qc.parameters)[: num_qubits] # The remaining ones are the trainable weights of the quantum neural network params = list(qc.parameters)[num_qubits:] qc.draw() # Select a quantum backend to run the simulation of the quantum circuit qi = QuantumInstance(qk.Aer.get_backend('statevector_simulator')) # Create a Quantum Neural Network object starting from the quantum circuit defined above qnn = CircuitQNN(qc, input_params=X, weight_params=params, quantum_instance = qi) # Connect to PyTorch initial_weights = (2*np.random.rand(qnn.num_weights) - 1) quantum_nn = TorchConnector(qnn, initial_weights) class encoding_layer(torch.nn.Module): def __init__(self, num_qubits = 4): super().__init__() # Define weights for the layer weights = torch.Tensor(num_qubits) self.weights = torch.nn.Parameter(weights) torch.nn.init.uniform_(self.weights, -1, 1) # <-- Initialization strategy def forward(self, x): """Forward step, as explained above.""" if not isinstance(x, Tensor): x = Tensor(x) x = self.weights * x x = torch.atan(x) return x class exp_val_layer(torch.nn.Module): def __init__(self, action_space = 2): super().__init__() # Define the weights for the layer weights = torch.Tensor(action_space) self.weights = torch.nn.Parameter(weights) torch.nn.init.uniform_(self.weights, 35, 40) # <-- Initialization strategy (heuristic choice) # Masks that map the vector of probabilities to <Z_0*Z_1> and <Z_2*Z_3> self.mask_ZZ_12 = torch.tensor([1.,-1.,-1.,1.,1.,-1.,-1.,1.,1.,-1.,-1.,1.,1.,-1.,-1.,1.], requires_grad = False) self.mask_ZZ_34 = torch.tensor([-1.,-1.,-1.,-1.,1.,1.,1.,1.,-1.,-1.,-1.,-1.,1.,1.,1.,1.], requires_grad = False) def forward(self, x): """Forward step, as described above.""" expval_ZZ_12 = self.mask_ZZ_12 * x expval_ZZ_34 = self.mask_ZZ_34 * x # Single sample if len(x.shape) == 1: expval_ZZ_12 = torch.sum(expval_ZZ_12) expval_ZZ_34 = torch.sum(expval_ZZ_34) out = torch.cat((expval_ZZ_12.unsqueeze(0), expval_ZZ_34.unsqueeze(0))) # Batch of samples else: expval_ZZ_12 = torch.sum(expval_ZZ_12, dim = 1, keepdim = True) expval_ZZ_34 = torch.sum(expval_ZZ_34, dim = 1, keepdim = True) out = torch.cat((expval_ZZ_12, expval_ZZ_34), 1) return self.weights * ((out + 1.) / 2.) # Classical trainable preprocessing encoding = encoding_layer() # Classical trainable postprocessing exp_val = exp_val_layer() # Stack the classical and quantum layers together model = torch.nn.Sequential(encoding, quantum_nn, exp_val) model.state_dict() # Load pre-trained weights (check if the file exists): # try: # model.load_state_dict(torch.load("./model_best_weights_6reps_longtrain.pth")) # except: # print("No pre-trained weights found. Looks like you have to train from scratch...") # Decomment and execute the following lines to create a fully classical neural network, instead of the quantum one # model = torch.nn.Sequential(torch.nn.Linear(4,32), # torch.nn.ELU(), # torch.nn.Linear(32,32), # torch.nn.ELU(), # torch.nn.Linear(32,2)) # Print the weights of the classical neural network # model.state_dict() # Print the total number of weights in the classical neural network # pytorch_total_params = sum(p.numel() for p in model.parameters()) env = gym.make("CartPole-v1") input_shape = [4] # == env.observation_space.shape n_outputs = 2 # == env.action_space.n from collections import deque replay_memory = deque(maxlen=2000) def epsilon_greedy_policy(state, epsilon=0): """Manages the transition from the *exploration* to *exploitation* phase""" if np.random.rand() < epsilon: return np.random.randint(n_outputs) else: with torch.no_grad(): Q_values = model(Tensor(state)).numpy() return np.argmax(Q_values[0]) def sample_experiences(batch_size): """Sample some past experiences from the replay memory""" indices = np.random.randint(len(replay_memory), size=batch_size) batch = [replay_memory[index] for index in indices] states, actions, rewards, next_states, dones = [ np.array([experience[field_index] for experience in batch]) for field_index in range(5)] return states, actions, rewards, next_states, dones def play_one_step(env, state, epsilon): """Perform one action in the environment and register the state of the system""" action = epsilon_greedy_policy(state, epsilon) next_state, reward, done, info = env.step(action) replay_memory.append((state, action, reward, next_state, done)) return next_state, reward, done, info def sequential_training_step(batch_size): """ Actual training routine. Implements the Deep Q-Learning algorithm. This implementation evaluates individual losses sequentially instead of using batches. This is due to an issue in the TorchConnector, which yields vanishing gradients if it is called with a batch of data (see https://github.com/Qiskit/qiskit-machine-learning/issues/100). Use this training for the quantum model. If using the classical model, you can use indifferently this implementation or the batched one below. """ # Sample past experiences experiences = sample_experiences(batch_size) states, actions, rewards, next_states, dones = experiences # Evaluates Target Q-values with torch.no_grad(): next_Q_values = model(Tensor(next_states)).numpy() max_next_Q_values = np.max(next_Q_values, axis=1) target_Q_values = (rewards + (1 - dones) * discount_rate * max_next_Q_values) # Accumulate Loss sequentially (if batching data, gradients of the parameters are vanishing) loss = 0. for j, state in enumerate(states): single_Q_value = model(Tensor(state)) Q_value = single_Q_value[actions[j]] loss += (target_Q_values[j] - Q_value)**2 # Evaluate the gradients and update the parameters optimizer.zero_grad() loss.backward() optimizer.step() def training_step(batch_size): """ This is exactly the same function as sequential_training_step, except that it evaluates loss with batch of data, instead of using a for loop. Can use this if training the classical model. """ # Sample past experiences experiences = sample_experiences(batch_size) states, actions, rewards, next_states, dones = experiences # Evaluate Target Q-values with torch.no_grad(): next_Q_values = model(Tensor(next_states)).numpy() max_next_Q_values = np.max(next_Q_values, axis=1) target_Q_values = (rewards + (1 - dones) * discount_rate * max_next_Q_values) target_Q_values = target_Q_values.reshape(-1, 1) mask = torch.nn.functional.one_hot(Tensor(actions).long(), n_outputs) # Evaluate the loss all_Q_values = model(Tensor(states)) Q_values = torch.sum(all_Q_values * mask, dim=1, keepdims=True) loss = loss_fn(Tensor(target_Q_values), Q_values) # Evaluate the gradients and update the parameters optimizer.zero_grad() loss.backward() optimizer.step() batch_size = 16 discount_rate = 0.99 optimizer = Adam(model.parameters(), lr=1e-2) rewards = [] best_score = 0 # We let the agent train for 2000 episodes for episode in range(2000): # Run enviroment simulation obs = env.reset() # 200 is the target score for considering the environment solved for step in range(200): # Manages the transition from exploration to exploitation epsilon = max(1 - episode / 1500, 0.01) obs, reward, done, info = play_one_step(env, obs, epsilon) if done: break rewards.append(step) # Saving best agent if step >= best_score: # torch.save(model.state_dict(), './new_model_best_weights.pth') # Save best weights best_score = step print("\rEpisode: {}, Steps : {}, eps: {:.3f}".format(episode, step + 1, epsilon), end="") # Start training only after some exploration experiences if episode > 20: sequential_training_step(batch_size) # DECOMMENT IF WANT TO LOAD PRETRAINED WEIGHTS # Load pre-trained weights (check if the file exists): # try: # model.load_state_dict(torch.load("./model_best_weights_6reps_longtrain.pth")) # except: # print("No pre-trained weights found. Looks like you have to train from scratch...") model.state_dict() plt.figure(figsize=(8, 4)) plt.plot(rewards) plt.xlabel("Episode", fontsize=14) plt.ylabel("Sum of rewards", fontsize=14) plt.show() import matplotlib.pyplot as plt import seaborn as sns sns.set_theme() # This file contains the sum of rewards from a previous successfull training run rewards_history = np.loadtxt("training_rewards2.txt") + 1 cmap = plt.get_cmap('tab20c') fig = plt.figure(figsize=(8,5)) plt.axhline([200], ls = 'dashed', c=cmap(9)) plt.text(-50,190, s='Max reward', c=cmap(8)) plt.text(-50,100, s='Exploration\nphase', c=cmap(12)) plt.text(1100,100, s='Exploitation\nphase', c=cmap(12)) plt.plot(rewards_history, c = cmap(4)) plt.xlabel("Episodes") plt.ylabel("Final reward") plt.tight_layout() plt.show() # Set the environment seed for reproducibility env.seed(42) state = env.reset() frames = [] for step in range(200): action = epsilon_greedy_policy(state) state, reward, done, info = env.step(action) if done: print("End at step:", step) break img = env.render(mode="rgb_array") frames.append(img) plot_animation(frames)
https://github.com/LauraGentini/QRL
LauraGentini
# General imports import numpy as np import matplotlib.pyplot as plt # Qiskit imports import qiskit as qk from qiskit.utils import QuantumInstance # Qiskit Machine Learning imports import qiskit_machine_learning as qkml from qiskit_machine_learning.neural_networks import CircuitQNN from qiskit_machine_learning.connectors import TorchConnector # PyTorch imports import torch from torch import Tensor # OpenAI Gym import import gym # Custom Deep Q-Learning code import from dqn_definitions import * # Fix seed for reproducibility seed = 42 np.random.seed(seed) torch.manual_seed(seed); # To get smooth animations on Jupyter Notebooks. # Note: these plotting function are taken from https://github.com/ageron/handson-ml2 import matplotlib as mpl import matplotlib.animation as animation mpl.rc('animation', html='jshtml') def update_scene(num, frames, patch): patch.set_data(frames[num]) return patch, def plot_animation(frames, repeat=False, interval=40): fig = plt.figure() patch = plt.imshow(frames[0]) plt.axis('off') anim = animation.FuncAnimation( fig, update_scene, fargs=(frames, patch), frames=len(frames), repeat=repeat, interval=interval) plt.close() return anim # Select the number of qubits (one qubit per state variable of the environment) num_qubits = 4 # Generate the Parametrized Quantum Circuit (note the reuploading and repetitions flags) qc = parametrized_circuit(num_qubits = num_qubits, reuploading = True, reps = 6) # Fetch the Parameters from the circuit and divide them in Inputs (X) and Trainable Parameters (params) # The first four parameters are for the inputs X = list(qc.parameters)[: num_qubits] # The remaining ones are the trainable weights of the quantum neural network params = list(qc.parameters)[num_qubits:] qc.draw() # Define the quantum instance to be used for simulating the quantum circuit qi = QuantumInstance(qk.Aer.get_backend('statevector_simulator')) # Create the QNN from the parametrized quantum circuit defined above qnn = CircuitQNN(qc, input_params=X, weight_params=params, quantum_instance = qi) # Interface the QNN with PyTorch initial_weights = (2*np.random.rand(qnn.num_weights) - 1) # <---Initialization weights at random quantum_nn = TorchConnector(qnn, initial_weights) env = gym.make("CartPole-v1") input_shape = [4] # == env.observation_space.shape n_outputs = 2 # == env.action_space.n # Classical trainable preprocessing (encoding) encoding = encoding_layer() # Classical trainable postprocessing exp_val = exp_val_layer() # Stack the classical and quantum layers together model = torch.nn.Sequential(encoding, quantum_nn, exp_val) # Load pre-trained weights (check if the file exists): try: model.load_state_dict(torch.load("./model_best_weights_6reps_longtrain.pth")) except: print("No pre-trained weights found. Looks like you have to train from scratch...") # Print the optimal weights of the agent model.state_dict() # Set the environment seed for reproducibility env.seed(42) # 200 is the target score for considering the environment solved max_reward = 200 # Run the quantum agent frames = [] state = env.reset() for step in range(max_reward): # Select action with torch.no_grad(): Q_values = model(Tensor(state)).numpy() action = np.argmax(Q_values) # Perform the action state, reward, done, info = env.step(action) if done: print("End at step:", step) break print(f"Step {step}, Q-values {Q_values}, Action {action}", end = "\r") img = env.render(mode="rgb_array") frames.append(img) plot_animation(frames) # Choose the number of shots used to estimate the expectation values in the QNN circuit n_shots = 1024 # Define the quantum instance for the qasm_simulator qi_qasm = QuantumInstance(qk.Aer.get_backend('qasm_simulator'), shots = n_shots) noisy_qnn = CircuitQNN(qc, input_params=X, weight_params=params, quantum_instance = qi_qasm) initial_weights = (2*np.random.rand(qnn.num_weights) - 1) noisy_quantum_nn = TorchConnector(noisy_qnn, initial_weights) # Exactly as before... encoding = encoding_layer() exp_val = exp_val_layer() noisy_model = torch.nn.Sequential(encoding, noisy_quantum_nn, exp_val) # Load pre-trained weights: try: noisy_model.load_state_dict(torch.load("./model_best_weights_6reps_longtrain.pth")) except: print("No pre-trained weights found. Looks like you have to train from scratch...") noisy_model.state_dict() env.seed(42) number_of_episodes = 5 print(f"Number of shots = {n_shots}") print("-----------------------") final_step = [] for i in range(number_of_episodes): state = env.reset() for step in range(200): print(f"\r Episode = {i}, Step = {step}", end = "") with torch.no_grad(): Q_values = noisy_model(Tensor(state[np.newaxis])).numpy() action = np.argmax(Q_values[0]) state, reward, done, info = env.step(action) # print(action, state, model(Tensor([state]))) if done: print(", End at step:", step) break final_step.append(step+1) final_steps = np.array(final_step) mean_score = np.mean(final_steps) std_score = np.std(final_steps) print(f"Mean reward = {mean_score} ± {std_score}") num_shots = [1024, 2048, 4096, 8192] mean_reward = [115.1, 191, 195, 199.7] std_reward = [49.9, 27.2, 10.9, 0.3] import seaborn as sns sns.set_theme() cmap = plt.get_cmap('tab20c') fig = plt.figure(figsize=(8,5)) plt.axhline([200], ls = 'dashed', c=cmap(9)) plt.text(6000,205, s='Max reward', c=cmap(8)) plt.axhline([195], ls = 'dashed', c=cmap(13)) plt.text(6000,175, s='Min reward for\nsolving environment', c=cmap(12)) plt.errorbar(num_shots, mean_reward, yerr=std_reward, fmt='o', c = cmap(4), capsize=5, ecolor = cmap(5)) plt.ylim([0,230]) plt.xticks([1024, 2048, 4096, 8192]) plt.xlabel("Number of shots") plt.ylabel("Final reward") plt.tight_layout() plt.show()
https://github.com/LauraGentini/QRL
LauraGentini
""" Python script containing functions definitions for the Quantum Deep-Q Learning approach, used in the DQN-analysis Jupyter Notebook. Prepared for Qiskit Hackathon Europe by: Stefano, Paolo, Jani & Laura, 2021. """ # General imports import numpy as np import matplotlib.pyplot as plt # Qiskit Circuit imports from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression from qiskit.circuit.library import TwoLocal # Qiskit imports import qiskit as qk from qiskit.utils import QuantumInstance # Qiskit Machine Learning imports import qiskit_machine_learning as qkml from qiskit_machine_learning.neural_networks import CircuitQNN from qiskit_machine_learning.connectors import TorchConnector # PyTorch imports import torch from torch import Tensor from torch.nn import MSELoss from torch.optim import LBFGS, SGD, Adam, RMSprop def encoding_circuit(inputs, num_qubits=4, *args): """ Encode classical input data (i.e. the state of the enironment) on a quantum circuit. To be used inside the `parametrized_circuit` function. Args ------- inputs (list): a list containing the classical inputs. num_qubits (int): number of qubits in the quantum circuit. Return ------- qc (QuantumCircuit): quantum circuit with encoding gates. """ qc = qk.QuantumCircuit(num_qubits) # Encode data with a RX rotation for i, data in enumerate(inputs): qc.rx(inputs[i], i) return qc def parametrized_circuit(num_qubits=4, reuploading=False, reps=2, insert_barriers=True, meas=False): """ Create the Parameterized Quantum Circuit (PQC) for estimating Q-values. It implements the architecure proposed in Skolik et al. arXiv:2104.15084. Args ------- num_qubit (int): number of qubits in the quantum circuit. reuploading (bool): True if want to use data reuploading technique. reps (int): number of repetitions (layers) in the variational circuit. insert_barrirerd (bool): True to add barriers in between gates, for better drawing of the circuit. meas (bool): True to add final measurements on the qubits. Return ------- qc (QuantumCircuit): the full parametrized quantum circuit. """ qr = qk.QuantumRegister(num_qubits, 'qr') qc = qk.QuantumCircuit(qr) if meas: qr = qk.QuantumRegister(num_qubits, 'qr') cr = qk.ClassicalRegister(num_qubits, 'cr') qc = qk.QuantumCircuit(qr, cr) if not reuploading: # Define a vector containg Inputs as parameters (*not* to be optimized) inputs = qk.circuit.ParameterVector('x', num_qubits) # Encode classical input data qc.compose(encoding_circuit( inputs, num_qubits=num_qubits), inplace=True) if insert_barriers: qc.barrier() # Variational circuit qc.compose(TwoLocal(num_qubits, ['ry', 'rz'], 'cz', 'circular', reps=reps, insert_barriers=insert_barriers, skip_final_rotation_layer=True), inplace=True) if insert_barriers: qc.barrier() # Add final measurements if meas: qc.measure(qr, cr) elif reuploading: # Define a vector containg Inputs as parameters (*not* to be optimized) inputs = qk.circuit.ParameterVector('x', num_qubits) # Define a vector containng variational parameters θ = qk.circuit.ParameterVector('θ', 2 * num_qubits * reps) # Iterate for a number of repetitions for rep in range(reps): # Encode classical input data qc.compose(encoding_circuit( inputs, num_qubits=num_qubits), inplace=True) if insert_barriers: qc.barrier() # Variational circuit (does the same as TwoLocal from Qiskit) for qubit in range(num_qubits): qc.ry(θ[qubit + 2*num_qubits*(rep)], qubit) qc.rz(θ[qubit + 2*num_qubits*(rep) + num_qubits], qubit) if insert_barriers: qc.barrier() # Add entanglers (this code is for a circular entangler) qc.cz(qr[-1], qr[0]) for qubit in range(num_qubits-1): qc.cz(qr[qubit], qr[qubit+1]) if insert_barriers: qc.barrier() # (Optional) Add final measurements if meas: qc.measure(qr, cr) return qc ################ # PyTorch Code # ################ class encoding_layer(torch.nn.Module): def __init__(self, num_qubits=4): super().__init__() # Define weights for the layer weights = torch.Tensor(num_qubits) self.weights = torch.nn.Parameter(weights) # Initialization strategy torch.nn.init.uniform_(self.weights, -1, 1) def forward(self, x): """Forward step, as explained above.""" if not isinstance(x, Tensor): x = Tensor(x) # if len(x.shape) == 1: # Not needed, may cause problems # x = torch.unsqueeze(x, 0) x = self.weights * x x = torch.atan(x) return x class exp_val_layer(torch.nn.Module): def __init__(self, action_space=2): super().__init__() # Define the weights for the layer weights = torch.Tensor(action_space) self.weights = torch.nn.Parameter(weights) # <-- Initialization strategy (heuristic choice) torch.nn.init.uniform_(self.weights, 35, 40) # Check that these masks take the vector of probabilities to <Z_0*Z_1> and <Z_2*Z_3> self.mask_ZZ_12 = torch.tensor( [1., -1., -1., 1., 1., -1., -1., 1., 1., -1., -1., 1., 1., -1., -1., 1.], requires_grad=False) self.mask_ZZ_34 = torch.tensor( [-1., -1., -1., -1., 1., 1., 1., 1., -1., -1., -1., -1., 1., 1., 1., 1.], requires_grad=False) def forward(self, x): """Forward step, as described above.""" expval_ZZ_12 = self.mask_ZZ_12 * x expval_ZZ_34 = self.mask_ZZ_34 * x if len(x.shape) == 1: # , dim = 1, keepdim = True) expval_ZZ_12 = torch.sum(expval_ZZ_12) # , dim = 1, keepdim = True) expval_ZZ_34 = torch.sum(expval_ZZ_34) out = torch.cat((expval_ZZ_12.unsqueeze(0), expval_ZZ_34.unsqueeze(0))) else: expval_ZZ_12 = torch.sum(expval_ZZ_12, dim=1, keepdim=True) expval_ZZ_34 = torch.sum(expval_ZZ_34, dim=1, keepdim=True) out = torch.cat((expval_ZZ_12, expval_ZZ_34), 1) return self.weights * ((out + 1.) / 2.) ################# # Training code # ################# def epsilon_greedy_policy(state, epsilon=0): """Manages the transition from the *exploration* to *exploitation* phase""" if np.random.rand() < epsilon: return np.random.randint(n_outputs) else: with torch.no_grad(): Q_values = model(Tensor(state[np.newaxis])).numpy() return np.argmax(Q_values[0]) def sample_experiences(batch_size): """Sample some past experiences from the replay memory""" indices = np.random.randint(len(replay_memory), size=batch_size) batch = [replay_memory[index] for index in indices] states, actions, rewards, next_states, dones = [ np.array([experience[field_index] for experience in batch]) for field_index in range(5)] return states, actions, rewards, next_states, dones def play_one_step(env, state, epsilon): """Perform one action in the environment and register the state of the system""" action = epsilon_greedy_policy(state, epsilon) next_state, reward, done, info = env.step(action) replay_memory.append((state, action, reward, next_state, done)) return next_state, reward, done, info def sequential_training_step(batch_size): """ Actual training routine. Implements the Deep Q-Learning algorithm. This implementation evaluates individual losses sequentially instead of using batches. This is due to an issue in the TorchConnector, which yields vanishing gradients if it is called with a batch of data (see https://github.com/Qiskit/qiskit-machine-learning/issues/100). Use this training for the quantum model. If using the classical model, you can use indifferently this implementation or the batched one below. """ # Sample past experiences experiences = sample_experiences(batch_size) states, actions, rewards, next_states, dones = experiences # Evaluates the Target Q-values with torch.no_grad(): next_Q_values = model(Tensor(next_states)).numpy() max_next_Q_values = np.max(next_Q_values, axis=1) target_Q_values = (rewards + (1 - dones) * discount_rate * max_next_Q_values) # Accumulate Loss (this is the only way it works. If batching data, gradients are vanishing) loss = 0. for j, state in enumerate(states): single_Q_value = model(Tensor(state)) Q_value = single_Q_value[actions[j]] loss += (target_Q_values[j] - Q_value)**2 # Evaluate the gradients and update the parameters optimizer.zero_grad() loss.backward() optimizer.step() def training_step(batch_size): """ This is exactly the same function as sequential_training_step, except that it evaluates loss with batch of data, instead of using a for loop. Can use this if training the classical model. """ # Sample past experiences experiences = sample_experiences(batch_size) states, actions, rewards, next_states, dones = experiences # Evaluate Target Q-values with torch.no_grad(): next_Q_values = model(Tensor(next_states)).numpy() max_next_Q_values = np.max(next_Q_values, axis=1) target_Q_values = (rewards + (1 - dones) * discount_rate * max_next_Q_values) target_Q_values = target_Q_values.reshape(-1, 1) mask = torch.nn.functional.one_hot(Tensor(actions).long(), n_outputs) # Evaluate the loss all_Q_values = model(Tensor(states)) Q_values = torch.sum(all_Q_values * mask, dim=1, keepdims=True) loss = loss_fn(Tensor(target_Q_values), Q_values) # Evaluate the gradients and update the parameters optimizer.zero_grad() loss.backward() optimizer.step()
https://github.com/LauraGentini/QRL
LauraGentini
__author__ = 'QRL_team' from qiskit import * from qiskit.circuit.library import GroverOperator from qiskit.quantum_info import Statevector import numpy as np from math import ceil from qttt import QTicTacToeEnv class GroverQuantumBoardLearner: """ Inits a quantum QLearner object. Chosen environment must be discrete! """ def __init__(self, env): self.env = env # in this approach we do not know in advance how many possible states are there, # they will be added during training self.obs_dim = 1 # number of possible actions extracted from env self.acts_dim = self.env.action_space.n # evaluate number of needed qubits to encode actions self.acts_reg_dim = ceil(np.log2(self.acts_dim)) # evaluate maximum number of grover steps self.max_grover_steps = int(round(np.pi/(4*np.arcsin(1./np.sqrt(2**self.acts_reg_dim))) - 0.5)) # state variable self.state = self.env.reset() # action variable self.action = 0 # init dictionary of quality values, str(state) is used for better comparison self.state_vals = {str(self.state): 0.} # init dict of grover steps for each state-action pair self.grover_steps = {str(self.state): np.zeros(self.acts_dim, dtype=int)} # init dict of flags to stop grover amplification, needed when acts_dim = 4 self.grover_steps_flag = {str(self.state): np.zeros(self.acts_dim, dtype=bool)} # learner hyperparameters self.hyperparams = {'k': -1, 'alpha': 0.05, 'gamma': 0.99} # grover oracles self.grover_ops = self._init_grover_ops() # state-action circuits self.acts_circs = self._init_acts_circs() self.SIM = Aer.get_backend('qasm_simulator') def set_hyperparams(self, hyperdict): """ Set new values for learner's hyperparameters :param hyperdict: :return: nthg """ self.hyperparams = hyperdict def _new_state_check(self, newstate): """ Checks if newstate was already observed :param newstate: :return: nthg """ if str(newstate) in self.state_vals.keys(): return else: self.state_vals[str(newstate)] = 0. self.grover_steps[str(newstate)] = np.zeros(self.acts_dim, dtype=int) self.grover_steps_flag[str(newstate)] = np.zeros(self.acts_dim, dtype=bool) self._append_new_circ(newstate) def _init_acts_circs(self): """ Creates the state-action circuits and inits them in full superposition :return: dict of said circuits, keys are strings of state vectors """ circs = {str(self.state): QuantumCircuit(self.acts_reg_dim)} for _, c in circs.items(): c.h(list(range(self.acts_reg_dim))) return circs def _append_new_circ(self, state): """ Inits a new state-action circuit :param state: :return: """ self.acts_circs[str(state)] = QuantumCircuit(self.acts_reg_dim) self.acts_circs[str(state)].h(list(range(self.acts_reg_dim))) def _update_statevals(self, reward, new_state): """ Bellman equation to update state values :param reward: the instantaneous reward received by the agent :param new_state: the new state visited by the agent :return: """ self.state_vals[str(self.state)] += self.hyperparams['alpha']\ * (reward + self.hyperparams['gamma']*self.state_vals[str(new_state)] - self.state_vals[str(self.state)]) def _eval_grover_steps(self, reward, new_state): """ Choose how many grover step to take based on instantaneous reward and value of new state :param reward: the instantaneous reward received by the agent :param new_state: the new state visited by the agent :return: number of grover steps to be taken, if it exceeds the theoretical optimal number the latter is returned instead """ steps_num = int(self.hyperparams['k']*(reward + self.state_vals[str(new_state)])) return min(steps_num, self.max_grover_steps) def _init_grover_ops(self): """ Inits grover oracles for the actions set :return: a list of qiskit instructions ready to be appended to circuit """ states_binars = [format(i, '0{}b'.format(self.acts_reg_dim)) for i in range(self.acts_dim)] targ_states = [Statevector.from_label(s) for s in states_binars] grops = [GroverOperator(oracle=ts) for ts in targ_states] return [g.to_instruction() for g in grops] def _run_grover(self): """ Deploy grover ops on acts_circs :return: """ gsteps = self.grover_steps[str(self.state)][self.action] circ = self.acts_circs[str(self.state)] op = self.grover_ops[self.action] for _ in range(gsteps): circ.append(op, list(range(self.acts_reg_dim))) self.acts_circs[str(self.state)] = circ def _run_grover_bool(self): """ Update state-action circuits based on evaluated steps :return: """ flag = self.grover_steps_flag[str(self.state)] gsteps = self.grover_steps[str(self.state)][self.action] circ = self.acts_circs[str(self.state)] op = self.grover_ops[self.action] if not flag.any(): for _ in range(gsteps): circ.append(op, list(range(self.acts_reg_dim))) if gsteps >= self.max_grover_steps and not flag.any(): self.grover_steps_flag[str(self.state)][self.action] = True self.acts_circs[str(self.state)] = circ def _take_action(self): """ Measures state-action circuit and chooses which action to take :return: int, chosen action """ action = self.acts_dim + 1 while action >= self.acts_dim: circ = self.acts_circs[str(self.state)] circ_tomeasure = circ.copy() circ_tomeasure.measure_all() # circ_tomeasure = transpile(circ_tomeasure) # print(circ.draw()) job = execute(circ_tomeasure, backend=self.SIM, shots=1) result = job.result() counts = result.get_counts() action = int((list(counts.keys()))[0], 2) return action # test if __name__ == "__main__": def train(env, pl1, pl2, hyperparams): traj_dict = {} stats = {"Pl1 wins": [], "Pl2 wins": [], "Draws": []} # set initial max_steps gamelen = hyperparams['game_length'] for epoch in range(hyperparams['max_epochs']): if epoch % 10 == 0: print("Processing epoch {} ...".format(epoch)) # reset env state = env.reset() # init list for traj traj = [state] if hyperparams['graphics']: env.render() for step in range(gamelen): print('\rTurn {0}/{1}'.format(step, gamelen)) # pl1 goes first, then pl2 for player in (pl1, pl2): player._new_state_check(state) player.state = state # Select action action = player._take_action() #self._run_grover_bool() player.action = action # take action new_state, reward, done = env.step(action) player._new_state_check(new_state) player.state = state # print('REWARD: ', reward) # update statevals and grover steps player._update_statevals(reward, new_state) player.grover_steps[str(state)][action] = player._eval_grover_steps(reward, new_state) # amplify amplitudes with zio grover # player._run_grover() player._run_grover_bool() # render if curious if hyperparams['graphics']: env.render() # save transition traj.append(new_state) state = new_state # measure and observe outcome final = env.collapse_board() print("Observed board state: ", final) winner = env.check_end(final) if winner == 1: stats["Pl1 wins"].append(epoch) pl1._new_state_check(state) pl1._update_statevals(100, state) pl2._new_state_check(state) pl2._update_statevals(-10, state) elif winner == 2: stats["Pl2 wins"].append(epoch) pl2._new_state_check(state) pl2._update_statevals(100, state) pl1._new_state_check(state) pl1._update_statevals(-10, state) else: stats["Draws"].append(epoch) pl1._new_state_check(state) pl1._update_statevals(-5, state) pl2._new_state_check(state) pl2._update_statevals(-5, state) traj_dict['epoch_{}'.format(epoch)] = traj # return trajectories return traj_dict, stats board_dim = 2 # game_length = 5 env = QTicTacToeEnv(board_dim) player_1 = GroverQuantumBoardLearner(env) player_2 = GroverQuantumBoardLearner(env) game_hyperparms = {'max_epochs': 100, 'game_length': 4, 'graphics': False} player_hyperparms = {'k': 0.1, 'alpha': 0.05, 'gamma': 0.99} player_1.set_hyperparams(player_hyperparms) player_2.set_hyperparams(player_hyperparms) game_trajectories, game_stats = train(env, player_1, player_2, game_hyperparms) # print(game_trajectories) print(game_stats) print(player_1.state_vals) print(player_1.grover_steps)
https://github.com/LauraGentini/QRL
LauraGentini
__author__ = 'QRL_team' import numpy as np from gym import spaces from itertools import permutations from qiskit import ( QuantumCircuit, execute, Aer) from qiskit.circuit.library import ( HGate, XGate, CXGate) class QTicTacToeEnv: def __init__(self, grid_size): """ Inits a QTTT environmen :param grid_size: linear size of the board """ # select simulators self.simulator = Aer.get_backend('qasm_simulator') self.statevec_sim = Aer.get_backend('statevector_simulator') # one qubit for each tile of the board self.qnum = grid_size ** 2 # init board circuit self.circuit = QuantumCircuit(self.qnum) # init moves dictionary self.moves = self._init_moves_dict() # init action space as a gym space obj, so that agents can interpret it self.action_space = spaces.Discrete(len(self.moves)) # init dictionary of possible final board configs self.endings_lookuptable = self._init_outcomes_dict() # not necessary, saves the moves self.status_id = "" def _init_moves_dict(self): """ Generates a dictionary with all possible moves. Possible moves are: place H or X on a chosen qubit; apply a CNOT at chosen quibits pair :return: a dict with int keys and tuples of (qubits, qiskit gates) as values """ mvs_dict = {} mv_indx = 0 for q in range(self.qnum): mvs_dict[mv_indx] = ([q], HGate()) mv_indx += 1 mvs_dict[mv_indx] = ([q], XGate()) mv_indx += 1 for (c, t) in permutations(list(range(self.qnum)), 2): mvs_dict[mv_indx] = ([c, t], CXGate()) mv_indx += 1 return mvs_dict def _win_check(self, board): """ Checks for game result :param board: string representing the final state of the board :return: winning player (1 or 2) or draw flag (0) """ d = int(np.sqrt(self.qnum)) # transofrm board string to rows, cols and diags rows = [board[i*d:(i+1)*d] for i in range(d)] cols = ["".join([rows[i][j] for i in range(d)]) for j in range(d)] diags = ["".join([rows[i][i] for i in range(d)]), "".join([rows[i][d-i-1] for i in range(d)])] winner = 0 # winning conditions for players 1 and 2 cond_1 = bin(0)[2:].zfill(d) cond_2 = bin(2**d - 1)[2:].zfill(d) # check each line and exit if both player win for line in [*rows, *cols, *diags]: if line == cond_1: if winner == 0 or winner == 1: winner = 1 elif winner == 2: return 0 # because both players won elif line == cond_2: if winner == 0 or winner == 2: winner = 2 elif winner == 1: return 0 # because both players won return winner def _init_outcomes_dict(self): """ Inits a dictionary with all possible endings :return: a dict whose keys are the winning player or a draw flag (0) and whose associated values are all the final board configs leading to such outcome """ out_dict = {1: [], 2: [], 0: []} # init all possible observed board states all_states = [bin(x)[2:].zfill(self.qnum) for x in range(2**self.qnum)] for state in all_states: winner = self._win_check(state) out_dict[winner].append(int(state, 2)) return out_dict def move(self, action): """ Take the action by appending the associated gate to the board circ. :param action: int, key of the moves dict :return: """ self.status_id += "{}-".format(action) self.circuit.append(self.moves[action][1], self.moves[action][0]) def _get_statevec(self): """ Quantumly observe the board, return the "percept" as the statevector of the board circuit :return: rounded state vec of the board """ job = execute(self.circuit, self.statevec_sim) result = job.result() output_state = result.get_statevector() return np.around(output_state, decimals=2) def collapse_board(self): """ Final move, measure the board and observe final state :return: final classical state of the board """ self.circuit.measure_all() job = execute(self.circuit, backend=self.simulator, shots=1) res = job.result() counts = res.get_counts() collapsed_state = int(list(counts.keys())[0][:self.qnum], 2) return collapsed_state def check_end(self, board_state): """ Check for ending :param board_state: classical board state after collapse :return: winning player (1 or 2) or draw flag (0) """ if board_state in self.endings_lookuptable[1]: print("\nPlayer 1 wins!!!\n") return 1 elif board_state in self.endings_lookuptable[2]: print("\nPlayer 2 wins!!!\n") return 2 else: print("\nIt's a draw!\n") return 0 def step(self, action): """ Perform the chosen action on the board :param action: int representing the chosen action :return: new_state of the board, reward (static), done=False """ self.move(action) new_state = self._get_statevec() reward = -0.1 return new_state, reward, False def reset(self): """ Resets the board :return: """ self.circuit = QuantumCircuit(self.qnum, self.qnum) self.circuit.h(list(range(self.qnum))) self.status_id = "" return self._get_statevec() def render(self): # TODO: devise a render function return 0
https://github.com/clausia/qiskit-fall-fest-peru-2022
clausia
from qiskit import QuantumRegister qubit1 = QuantumRegister(1) # el parámetro indica cuántos qubits queremos qubit2 = QuantumRegister(1, 'qreg') # se puede indicar un nombre al registro cuántico (parámetro opcional) print(qubit1) # al no especificar el nombre, le asigna uno con una numeración consecutiva print(qubit2) from qiskit import QuantumCircuit circuit = QuantumCircuit(qubit1) # crear un circuito cuántico con un qubit circuit.draw('mpl') # mostramos la representación gráfica del circuito circ = QuantumCircuit(3, 2) # circuito con 3 qubits y 2 bits clásicos circ.h(0) # aplicar compuerta H al qubit 0 circ.cx(0, 1) # aplicar compuerta CNOT a los qubits 0 y 1 circ.cx(0, 2) # aplicar compuerta CNOT a los qubits 0 y 2 circ.measure(0, 1) # medir el qubit 0 en el bit clásico 1 circ.measure(2, 0) # medir el qubit 2 en el bit clásico 0 circ.draw('mpl') # mostrar el circuito circ1 = QuantumCircuit(1) # circuito con 1 qubit circ1.x(0) # aplicar compuerta X al (único) qubit 0 circ1.draw('mpl') # mostrar el circuito from qiskit.quantum_info import Statevector from qiskit.visualization import array_to_latex circ1 = QuantumCircuit(1) # circuito con 1 qubit psi_0 = Statevector(circ1) # estado justo después de crear el circuito circ1.x(0) # aplicar compuerta X al (único) qubit 0 psi_1 = Statevector(circ1) # estado después aplicar la compuerta X display(circ1.draw('mpl')) # mostrar el circuito print("👉 Estado inicial:") print("➤ en forma de vector:") display(array_to_latex(psi_0.data)) print("➤ en forma de ket:") display(psi_0.draw('latex')) print() print("👉 Estado después de X:") print("➤ en forma de vector:") display(array_to_latex(psi_1.data)) print("➤ en forma de ket:") display(psi_1.draw('latex')) from qiskit.visualization import plot_bloch_multivector print("🔵 Estado inicial:") display(plot_bloch_multivector(psi_0)) print("🔵 Estado después de X:") display(plot_bloch_multivector(psi_1)) circ2 = QuantumCircuit(1) # circuito con 1 qubit psi_0 = Statevector(circ2) # estado justo después de crear el circuito circ2.y(0) # aplicar compuerta Y al (único) qubit 0 psi_1 = Statevector(circ2) # estado después aplicar la compuerta Y display(circ2.draw('mpl')) # mostrar el circuito print("👉 Estado inicial:") print("➤ en forma de vector:") display(array_to_latex(psi_0)) print("➤ en forma de ket:") display(psi_0.draw('latex')) print() print("👉 Estado después de Y:") print("➤ en forma de vector:") display(array_to_latex(psi_1)) print("➤ en forma de ket:") display(psi_1.draw('latex')) print("🔵 Estado inicial:") display(plot_bloch_multivector(psi_0)) print("🔵 Estado después de Y:") display(plot_bloch_multivector(psi_1)) circ3 = QuantumCircuit(1) # circuito con 1 qubit circ3.x(0) # obtener el estado |1> psi_0 = Statevector(circ3) # estado justo después de crear el circuito e iniciar el qubit en |1> circ3.z(0) # aplicar compuerta Z al (único) qubit en la posición 0 psi_1 = Statevector(circ3) # estado después aplicar la compuerta Z display(circ3.draw('mpl')) # mostrar el circuito print("👉 Estado inicial:") print("➤ en forma de vector:") display(array_to_latex(psi_0)) print("➤ en forma de ket:") display(psi_0.draw('latex')) print() print("👉 Estado después de Z:") print("➤ en forma de vector:") display(array_to_latex(psi_1)) print("➤ en forma de ket:") display(psi_1.draw('latex')) print() print("🔵 Estado inicial:") display(plot_bloch_multivector(psi_0)) print("🔵 Estado después de Z:") display(plot_bloch_multivector(psi_1)) import numpy as np circ4 = QuantumCircuit(1) # circuito con 1 qubit psi_0 = Statevector(circ4) # estado justo después de crear el circuito circ4.ry(np.pi/2, 0) # rotar pi/2 alrededor del eje y psi_1 = Statevector(circ4) # estado después de la primera rotación circ4.rz(np.pi/4, 0) # rotar pi/4 alrededor del eje z psi_2 = Statevector(circ4) # estado después de la segunda rotación circ4.rx(np.pi, 0) # rotar pi alrededor del eje x psi_3 = Statevector(circ4) # estado después de la tercera rotación display(circ4.draw('mpl')) # mostrar el circuito print("👉 Estado inicial:") print("➤ en forma de vector:") display(array_to_latex(psi_0)) print("➤ en forma de ket:") display(psi_0.draw('latex')) print() print("👉 Estado después rotación de pi/2 alrededor del eje y:") print("➤ en forma de vector:") display(array_to_latex(psi_1)) print("➤ en forma de ket:") display(psi_1.draw('latex')) print() print("👉 Estado después rotación de pi/4 alrededor del eje z:") print("➤ en forma de vector:") display(array_to_latex(psi_2)) print("➤ en forma de ket:") display(psi_2.draw('latex')) print() print("👉 Estado después rotación de pi alrededor del eje x:") print("➤ en forma de vector:") display(array_to_latex(psi_3)) print("➤ en forma de ket:") display(psi_3.draw('latex')) print() print("🔵 Estado inicial:") display(plot_bloch_multivector(psi_0)) print("🔵 Estado después rotación de pi/2 alrededor del eje y:") display(plot_bloch_multivector(psi_1)) print("🔵 Estado después rotación de pi/4 alrededor del eje z:") display(plot_bloch_multivector(psi_2)) print("🔵 Estado después rotación de pi alrededor del eje x:") display(plot_bloch_multivector(psi_3)) circ5 = QuantumCircuit(1) # circuito con 1 qubit psi_0 = Statevector(circ5) # estado justo después de crear el circuito circ5.h(0) # apliquemos H al estado |0>, quedamos en |+> psi_1 = Statevector(circ5) # estado justo después de aplicar H circ5.z(0) # aplicar compuerta Z al (único) qubit 0, quedamos en el estado |-> psi_2 = Statevector(circ5) # estado después aplicar la compuerta Z circ5.h(0) # aplicar compuerta H de nuevo, quedamos en el estado |1> psi_3 = Statevector(circ5) # estado después aplicar la compuerta Z display(circ5.draw('mpl')) # mostrar el circuito print("👉 Estado inicial:") print("➤ en forma de vector:") display(array_to_latex(psi_0)) print("➤ en forma de ket:") display(psi_0.draw('latex')) print() print("👉 Estado después de primera H:") print("➤ en forma de vector:") display(array_to_latex(psi_1)) print("➤ en forma de ket:") display(psi_1.draw('latex')) print() print("👉 Estado después de Z:") print("➤ en forma de vector:") display(array_to_latex(psi_2)) print("➤ en forma de ket:") display(psi_2.draw('latex')) print() print("👉 Estado después de segunda H:") print("➤ en forma de vector:") display(array_to_latex(psi_3)) print("➤ en forma de ket:") display(psi_3.draw('latex')) print() print("🔵 Estado inicial:") display(plot_bloch_multivector(psi_0)) print("🔵 Estado después de primera H:") display(plot_bloch_multivector(psi_1)) print("🔵 Estado después de Z:") display(plot_bloch_multivector(psi_2)) print("🔵 Estado después de segunda H:") display(plot_bloch_multivector(psi_3)) circ6 = QuantumCircuit(1) # circuito con 1 qubit circ6.h(0) # nos movemos al estado |+> psi_0 = Statevector(circ6) # estado justo después de crear el circuito y posicionarse en |+> circ6.s(0) # aplicar compuerta S, rotando pi/2 psi_1 = Statevector(circ6) # estado justo después de aplicar P circ6.tdg(0) # aplicar compuerta T† rotanfo -pi/4 psi_2 = Statevector(circ6) # estado después aplicar la compuerta S circ6.p(2*np.pi/3, 0) # aplicar compuerta P, rotando 2pi/3 psi_3 = Statevector(circ6) # estado después aplicar la compuerta T† display(circ5.draw('mpl')) # mostrar el circuito print("👉 Estado inicial |+>:") print("➤ en forma de vector:") display(array_to_latex(psi_0)) print("➤ en forma de ket:") display(psi_0.draw('latex')) print() print("👉 Estado después de S:") print("➤ en forma de vector:") display(array_to_latex(psi_1)) print("➤ en forma de ket:") display(psi_1.draw('latex')) print() print("👉 Estado después de T†:") print("➤ en forma de vector:") display(array_to_latex(psi_2)) print("➤ en forma de ket:") display(psi_2.draw('latex')) print() print("👉 Estado después de P(2*pi/3):") print("➤ en forma de vector:") display(array_to_latex(psi_3)) print("➤ en forma de ket:") display(psi_3.draw('latex')) print() print("🔵 Estado inicial |+>:") display(plot_bloch_multivector(psi_0)) print("🔵 Estado después de S:") display(plot_bloch_multivector(psi_1)) print("🔵 Estado después de T†:") display(plot_bloch_multivector(psi_2)) print("🔵 Estado después de P(2*pi/3):") display(plot_bloch_multivector(psi_3)) circ_u = QuantumCircuit(1) # circuito con 1 qubit psi_0 = Statevector(circ_u) # estado justo después de crear el circuito e iniciar el qubit en |1> circ_u.u(np.pi/3, np.pi/2, np.pi/5, 0) # aplicar compuerta U3 al (único) qubit en la posición 0 psi_1 = Statevector(circ_u) # estado después aplicar la compuerta U3 display(circ_u.draw('mpl')) # mostrar el circuito print("👉 Estado inicial:") print("➤ en forma de vector:") display(array_to_latex(psi_0)) print("➤ en forma de ket:") display(psi_0.draw('latex')) print() print("👉 Estado después de U3(pi/3, pi/8, pi/5):") print("➤ en forma de vector:") display(array_to_latex(psi_1)) print("➤ en forma de ket:") display(psi_1.draw('latex')) print() print("🔵 Estado inicial:") display(plot_bloch_multivector(psi_0)) print("🔵 Estado después de U3(pi/3, pi/8, pi/5):") display(plot_bloch_multivector(psi_1)) from qiskit.quantum_info import Operator circuit = QuantumCircuit(2) # circuito con 2 qubits circuit.h(0) # Hadamard en q0 circuit.id(1) # Identidad en q1 display(circuit.draw('mpl')) op = Operator(circuit) display(array_to_latex(op)) psi = Statevector(circuit) display(plot_bloch_multivector(psi)) circuit = QuantumCircuit(3) # circuito con 3 qubits circuit.rx(np.pi/4, 0) # Rx de pi/4 al q0 circuit.ry(3*np.pi/5, 1) # Ry de 3pi/5 al q1 circuit.h(2) # Hadamard al q2 display(circuit.draw('mpl')) op = Operator(circuit) display(array_to_latex(op)) psi = Statevector(circuit) print() display(plot_bloch_multivector(psi)) circ7 = QuantumCircuit(2) # circuito con 2 qubits circ7.x(0) # ponemos el control en |1> para que la compuerta sea aplicada circ7.cx(0, 1) # CNOT con q0 como control y q1 como objetivo print("Este es el caso para CNOT(0,1)|01> = |11>") display(circ7.draw('mpl')) op = Operator(circ7) display(array_to_latex(op)) psi = Statevector(circ7) print() display(plot_bloch_multivector(psi)) circ8 = QuantumCircuit(2) # circuito con 2 qubits circ8.x(1) # ponemos el control en |1> para que la compuerta sea aplicada circ8.cx(1, 0) # CNOT con q1 como control y q0 como objetivo print("Este es el caso para CNOT(1,0)|10> = |11>") display(circ8.draw('mpl')) op = Operator(circ8) display(array_to_latex(op)) psi = Statevector(circ8) print() display(plot_bloch_multivector(psi)) circ9 = QuantumCircuit(2) # circuito con 2 qubits circ9.cy(0, 1) # Y controlada, qubit control es q0, y objetivo es q1 circ9.cz(1, 0) # Z controlada, qubit control es q1, y objetivo es q0 circ9.cx(0, 1) # X controlada, qubit control es q0, y objetivo es q1 circ9.ch(0, 1) # H controlada, qubit control es q0, y objetivo es q1 circ9.crx(np.pi/8, 1, 0) # Rx controlada, ángulo de pi/8, qubit control es q1, y objetivo es q0 circ9.crz(3*np.pi/5, 0, 1) # Rz controlada, ángulo de 3pi/5, qubit control es q0, y objetivo es q1 circ9.cp(7*np.pi/9, 1, 0) # P controlada, ángulo de 7pi/9, qubit control es q1, y objetivo es q0 display(circ9.draw('mpl')) from qiskit.extensions import UnitaryGate matrix = [[1j, 0], [0 , 1,]] mi_gate = UnitaryGate(matrix, 'mi_gate') circ10 = QuantumCircuit(2) # circuito con 2 qubits circ10.append(mi_gate, [0]) # le agregamos al circuito la compuerta personalizada mi_gate_controlada = mi_gate.control(1) # hacemos la version controlada de mi_gate circ10.append(mi_gate_controlada, [0, 1]) # se indican los qubits, primero el control y luego el objetivo display(circ10.draw('mpl')) circ11 = QuantumCircuit(2) # circuito con 2 qubit circ11.x(0) # obtener el estado |01> psi_0 = Statevector(circ11) # estado justo después de crear el circuito e iniciar el qubit en |01> circ11.swap(0, 1) # aplicar compuerta SWAP a los dos quibits existentes psi_1 = Statevector(circ11) # estado después aplicar la compuerta Z display(circ11.draw('mpl')) # mostrar el circuito print("👉 Estado inicial:") print("➤ en forma de vector:") display(array_to_latex(psi_0)) print("➤ en forma de ket:") display(psi_0.draw('latex')) print() print("👉 Estado después de SWAP:") print("➤ en forma de vector:") display(array_to_latex(psi_1)) print("➤ en forma de ket:") display(psi_1.draw('latex')) print() print("🔵 Estado inicial:") display(plot_bloch_multivector(psi_0)) print("🔵 Estado después de SWAP:") display(plot_bloch_multivector(psi_1)) circ12 = QuantumCircuit(3) # circuito con 3 qubit circ12.x(1) # obtener el estado |010> circ12.x(2) # obtener el estado |110> psi_0 = Statevector(circ12) # estado justo después de crear el circuito e iniciar el qubit en |110> circ12.ccx(1, 2, 0) # aplicar compuerta CCX: control1, control2, objetivo psi_1 = Statevector(circ12) # estado después aplicar la compuerta Z display(circ12.draw('mpl')) # mostrar el circuito print("👉 Estado inicial:") print("➤ en forma de vector:") display(array_to_latex(psi_0)) print("➤ en forma de ket:") display(psi_0.draw('latex')) print() print("👉 Estado después de CCX(1, 2, 0):") print("➤ en forma de vector:") display(array_to_latex(psi_1)) print("➤ en forma de ket:") display(psi_1.draw('latex')) print() print("🔵 Estado inicial:") display(plot_bloch_multivector(psi_0)) print("🔵 Estado después de CCX(1, 2, 0):") display(plot_bloch_multivector(psi_1)) circ13 = QuantumCircuit(3) # circuito con 3 qubit circ13.x(2) # obtener el estado |100> circ13.x(1) # obtener el estado |110> psi_0 = Statevector(circ13) # estado justo después de crear el circuito e iniciar el qubit en |110> circ13.cswap(2, 0, 1) # aplicar compuerta CCX: control1, objetivo1, objetivo2 psi_1 = Statevector(circ13) # estado después aplicar la compuerta Z display(circ13.draw('mpl')) # mostrar el circuito print("👉 Estado inicial:") print("➤ en forma de vector:") display(array_to_latex(psi_0)) print("➤ en forma de ket:") display(psi_0.draw('latex')) print() print("👉 Estado después de SWAP(2, 0, 1):") print("➤ en forma de vector:") display(array_to_latex(psi_1)) print("➤ en forma de ket:") display(psi_1.draw('latex')) print() print("🔵 Estado inicial:") display(plot_bloch_multivector(psi_0)) print("🔵 Estado después de SWAP(2, 0, 1):") display(plot_bloch_multivector(psi_1)) # Crear una comperta a partir de un circuito qc1 = QuantumCircuit(2) # estos dos quits serán los objetivos qc1.x(0) qc1.h(1) custom = qc1.to_gate().control(2) # se indica que debe ser controlada con dos qubits # Aplicar esa compuerta a otro circuito qc2 = QuantumCircuit(4) qc2.append(custom, [0, 3, 1, 2]) # primeros 2 son control, el resto a los que se aplica la compuerta qc2.draw('mpl') circ_bell_1 = QuantumCircuit(2) # circuito con 2 qubits circ_bell_1.barrier() circ_bell_1.h(0) # aplicar compuerta H al qubit 0 circ_bell_1.cx(0,1) # aplicar compuerta CNOT psi_bell_1 = Statevector(circ_bell_1) # estado final display(circ_bell_1.draw('mpl')) # mostrar el circuito print("👉 Estado de Bell 1:") print("➤ en forma de vector:") display(array_to_latex(psi_bell_1)) print("➤ en forma de ket:") display(psi_bell_1.draw('latex')) circ_bell_2 = QuantumCircuit(2) # circuito con 2 qubits circ_bell_2.x(0) # aplicar compuerta X al qubit 0 circ_bell_2.barrier() circ_bell_2.h(0) # aplicar compuerta H al qubit 0 circ_bell_2.cx(0,1) # aplicar compuerta CNOT psi_bell_2 = Statevector(circ_bell_2) # estado final display(circ_bell_2.draw('mpl')) # mostrar el circuito print("👉 Estado de Bell 2:") print("➤ en forma de vector:") display(array_to_latex(psi_bell_2)) print("➤ en forma de ket:") display(psi_bell_2.draw('latex')) circ_bell_3 = QuantumCircuit(2) # circuito con 2 qubits circ_bell_3.x(1) # aplicar compuerta X al qubit 1 circ_bell_3.barrier() circ_bell_3.h(0) # aplicar compuerta H al qubit 0 circ_bell_3.cx(0,1) # aplicar compuerta CNOT psi_bell_3 = Statevector(circ_bell_3) # estado final display(circ_bell_3.draw('mpl')) # mostrar el circuito print("👉 Estado de Bell 2:") print("➤ en forma de vector:") display(array_to_latex(psi_bell_3)) print("➤ en forma de ket:") display(psi_bell_3.draw('latex')) circ_bell_4 = QuantumCircuit(2) # circuito con 2 qubits circ_bell_4.x(0) # aplicar compuerta X al qubit 0 circ_bell_4.x(1) # aplicar compuerta X al qubit 1 circ_bell_4.barrier() circ_bell_4.h(0) # aplicar compuerta H al qubit 0 circ_bell_4.cx(0,1) # aplicar compuerta CNOT psi_bell_4 = Statevector(circ_bell_4) # estado final display(circ_bell_4.draw('mpl')) # mostrar el circuito print("👉 Estado de Bell 2:") print("➤ en forma de vector:") display(array_to_latex(psi_bell_4)) print("➤ en forma de ket:") display(psi_bell_4.draw('latex')) circ_ghz = QuantumCircuit(3, 3) # circuito con 3 qubits y 3 bits clásicos circ_ghz.h(0) # aplicar compuerta H al qubit 0 circ_ghz.cx(0, 1) # aplicar compuerta CNOT a los qubits 0 y 1 circ_ghz.cx(0, 2) # aplicar compuerta CNOT a los qubits 0 y 2 circ_ghz.barrier() circ_ghz.measure([0,1,2], [0,1,2]) # medir los 3 qubits en los 3 bits clásicos circ_ghz.draw('mpl') # mostrar el circuito from qiskit import execute, Aer simulator = Aer.get_backend('aer_simulator') job = execute(circ_ghz, simulator, shots=1) # ejecutar el circuito una sola vez counts = job.result().get_counts(circ_ghz) # obtener los resultados de la ejecución print(counts) from qiskit.tools.visualization import plot_histogram job = execute(circ_ghz, simulator, shots=1000) # ejecutar el circuito 1000 veces counts = job.result().get_counts(circ_ghz) # obtener los resultados de la ejecución print(counts) plot_histogram(counts, title='Conteos del estado GHZ') # mostrar los resultados en forma de histograma Aer.backends() # incrementar la cantidad de 'shots' reduce la variación en el muestreo shots = 10000 # Método de simulación: Stabilizer sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer') job_stabilizer = sim_stabilizer.run(circ_ghz, shots=shots) #también se puede usar el método 'run' del backend counts_stabilizer = job_stabilizer.result().get_counts(0) # Método de simulación: Statevector sim_statevector = Aer.get_backend('aer_simulator_statevector') job_statevector = sim_statevector.run(circ_ghz, shots=shots) counts_statevector = job_statevector.result().get_counts(0) # Método de simulación: Density Matrix sim_density = Aer.get_backend('aer_simulator_density_matrix') job_density = sim_density.run(circ_ghz, shots=shots) counts_density = job_density.result().get_counts(0) # Método de simulación: Matrix Product State sim_mps = Aer.get_backend('aer_simulator_matrix_product_state') job_mps = sim_mps.run(circ_ghz, shots=shots) counts_mps = job_mps.result().get_counts(0) plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps], title='Conteos para diferentes métodos de simulación', legend=['stabilizer', 'statevector', 'density_matrix', 'matrix_product_state']) from qiskit import IBMQ #IBMQ.save_account('TOKEN') # guardar tu cuenta en tu disco duro IBMQ.load_account() # cargar cuenta desde el disco duro IBMQ.providers() # listar todos los proveedores disponibles (para tu cuenta) provider = IBMQ.get_provider(hub='ibm-q') # obtenemos un proveedor provider.backends() provider = IBMQ.get_provider(hub='ibm-q') # obtenemos un proveedor backend = provider.get_backend('ibmq_qasm_simulator') # obtenemos un backend, en este ejemplo estamos usando # un simulador, pero uno que se encuentra en la nube, # es decir, la ejecución no ocurrirá en nuestra máquina local # esto para obtener un resultado de manera rápida, # más adelante veremos cómo ejecutar en un dispositivo real circuit = QuantumCircuit(3, 3) # creamos un circuito de 3 qubits y 3 registros clásicos circuit.x(0) # aplicamos algunas compuertas circuit.x(1) circuit.ccx(0, 1, 2) circuit.cx(0, 1) circuit.barrier() circuit.measure([0, 1, 2], [0, 1, 2]) # agregamos mediciones a los 3 qubits display(circuit.draw('mpl')) # mostramos el circuito job = backend.run(circuit) # mandamos ejecutar el circuito al backend en la nube, # recuerda, este aún es un simulador, pero no local # esta línea de código puede tardarse varios segundos, o # incluso minutos dependiendo de la saturación de la red result = job.result() # la ejecución nos regresa un 'job' counts = result.get_counts() # al que le podemos pedir los conteos print(counts) # imprimimos los conteos # obtenemos todos los backends que no sean simuladores y que estén en línea provider.backends(simulator=False, operational=True) # obtenemos todos los backends con más de 3 qubits, que no sean simuladores y que estén en línea provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True) from qiskit.providers.ibmq import least_busy devices = provider.backends(simulator=False, operational=True) least_busy_device = least_busy(devices) # de la lista de dispositivos, averiguar cual es el menos ocupado least_busy_device from qiskit.compiler import transpile circuit = QuantumCircuit(3, 3) # creamos un circuito de 3 qubits y 3 registros clásicos circuit.x(0) # aplicamos algunas compuertas circuit.x(1) circuit.ccx(0, 1, 2) circuit.cx(0, 1) circuit.barrier() circuit.measure([0, 1, 2], [0, 1, 2]) # agregamos mediciones a los 3 qubits display(circuit.draw('mpl')) # mostramos el circuito circuit = transpile(circuit, least_busy_device) # transpilamos el circuito para el backend en específico display(circuit.draw('mpl')) # mostramos el circuito transpilado job = least_busy_device.run(circuit) # mandamos ejecutar el circuito al backend en la nube # guardado en la variable 'least_busy_device' # esta línea de código puede tardarse hasta varios minutos # dependiendo de la cantidad de 'jobs' encolados result = job.result() # la ejecución nos regresa un 'job' counts = result.get_counts() # al que le podemos pedir los conteos print(counts) # imprimimos los conteos least_busy_device.status() # su estado actual # creamos un circuito para probar circuit = QuantumCircuit(3, 3) for i in range(10): circuit.x(0) circuit.x(1) circuit.ccx(0, 1, 2) circuit.cx(0, 1) circuit.barrier() circuit.measure_all() display(circuit.draw('mpl')) from qiskit.providers.jobstatus import JobStatus from time import sleep from IPython.display import clear_output circuit = transpile(circuit, least_busy_device) # transpilamos el circuito para el backend en específico job = least_busy_device.run(circuit) # creamos el 'job' al solicitar la ejecución del circuito print("Identificador del job:\t", job.job_id()) # obtenemos el identificador del 'job' print("Job creado el:\t\t", job.creation_date()) # preguntamos la fecha de creacion del 'job' print() tt = 0 # tiempo transcurrido (en segundos) job_status = job.status() # preguntamos por el estatus del 'job' while job_status.name not in ["DONE", "CANCELLED", "ERROR"]: try: job_status = job.status() # preguntamos por el estatus del 'job' nuevamente if job_status is JobStatus.RUNNING: print("\rEl job sigue ejecutándose, tt = " + str(tt) + " s", end="") tt += 1 sleep(1) except IBMApiError as ex: print("Algo malo sucedió!: {}".format(ex)) print() print("\n\t>>> El job ha terminado su ejecución") print("\n\n") print("Resultado:\t", job.result().get_counts()) # resultado de la ejecución en el dispositivo real
https://github.com/clausia/qiskit-fall-fest-peru-2022
clausia
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit A = QuantumRegister(1, 'a') B = QuantumRegister(1, 'b') CarryIn = QuantumRegister(1, 'cin-sum') cero = QuantumRegister(1, 'aux-cout') adder = QuantumCircuit(A, B, CarryIn, cero) adder.ccx(0, 1, 3) adder.cx(0, 1) adder.ccx(1, 2, 3) adder.cx(1, 2) adder.cx(0, 1) adder.draw('mpl') inicializacion = QuantumCircuit(4) inicializacion.x(0) # a = 1 inicializacion.x(2) # cin = 1 inicializacion.barrier() inicializacion.draw('mpl') suma = inicializacion.compose(adder) suma.barrier() suma.add_register(ClassicalRegister(2, 'res')) suma.measure([2, 3], [0, 1]) suma.draw('mpl') from qiskit import execute, Aer from qiskit.tools.visualization import plot_histogram job = execute(suma, Aer.get_backend('aer_simulator'), shots=1000) counts = job.result().get_counts(suma) print(counts) plot_histogram(counts, title='Conteos del resultado de la suma') inicializacion2 = QuantumCircuit(4) inicializacion2.x(0) # a = 1 inicializacion2.x(1) # b = 1 inicializacion2.x(2) # cin = 1 inicializacion2.barrier() suma2 = inicializacion2.compose(adder) suma2.barrier() suma2.add_register(ClassicalRegister(2, 'res')) suma2.measure([2, 3], [0, 1]) display(suma2.draw('mpl')) job = execute(suma2, Aer.get_backend('aer_simulator'), shots=1) # con una sola ejecución es suficiente counts2 = job.result().get_counts(suma2) print(counts2) plot_histogram(counts2, title='Conteos del resultado de la suma2') inicializacion3 = QuantumCircuit(4) inicializacion3.h(0) # a y b en estado de Bell inicializacion3.cx(0, 1) inicializacion3.h(2) # estado en superposión: ( |0> + |1> ) / sqrt(2) inicializacion3.barrier() suma3 = inicializacion3.compose(adder) # el 'adder' es el mismo suma3.barrier() suma3.add_register(ClassicalRegister(2, 'res')) suma3.measure([2, 3], [0, 1]) display(suma3.draw('mpl')) job = execute(suma3, Aer.get_backend('aer_simulator'), shots=1000) # en este caso si necesitamos multiples shots counts3 = job.result().get_counts(suma3) print(counts3) plot_histogram(counts3, title='Conteos del resultado de la suma3') from qiskit.circuit.library.arithmetic.adders import CDKMRippleCarryAdder qiskit_adder = CDKMRippleCarryAdder(3, 'full', 'Sumador completo') operando1 = QuantumRegister(3, 'o1') # primer número a sumar operando2 = QuantumRegister(3, 'o2') # segundo número a sumar aux = QuantumRegister(2, 'a') # acarreo de entrada y de salida cr = ClassicalRegister(4) # para almacenar el resultado en bits clásicos circ = QuantumCircuit(operando1, operando2, aux, cr) circ.x([operando1[0], operando1[1]]) # 3 en binario: 011 circ.x([operando2[0], operando2[2]]) # 5 en binario: 101 # El orden esperado por la clase 'CDKMRippleCarryAdder' es: carry_in - 1er operando - 2do operando - carry_out circ.append(qiskit_adder, [aux[0]] + operando1[0:3] + operando2[0:3] + [aux[1]]) circ.measure(operando2[0:3] + [aux[1]], cr) # esta clase escribe el resultado en el 2do operando y en el carry_out display(circ.draw('mpl')) job = execute(circ, Aer.get_backend('aer_simulator'), shots=1000) counts = job.result().get_counts(circ) print(counts) # resultado es 8 en binario: 1000 plot_histogram(counts, title='Conteos del ejemplo con CDKMRippleCarryAdder') from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qr_alice = QuantumRegister(2, name="alicia") # dos qubits de Alicia qr_bob = QuantumRegister(1, name="bob") # un qubit de Bob crz = ClassicalRegister(1, name="crz") # 2 bits clasicos crx = ClassicalRegister(1, name="crx") # en 2 diferentes registros circuito_teleportacion = QuantumCircuit(qr_alice, qr_bob, crz, crx) circuito_teleportacion.draw('mpl') def crear_estado_bell(circ, a, b): circ.h(a) # poner el qubit a en el estado |+> circ.cx(a, b) # CNOT con control el qubit a y objetivo el qubit b crear_estado_bell(circuito_teleportacion, 1, 2) # circuito, qubit a, qubit b circuito_teleportacion.draw('mpl') def compuertas_alicia(circ, psi, a): circ.barrier() circ.cx(psi, a) circ.h(psi) compuertas_alicia(circuito_teleportacion, 0, 1) circuito_teleportacion.draw('mpl') def mediciones_y_envio(circ, psi, a): circ.barrier() circ.measure(psi, 0) circ.measure(a, 1) mediciones_y_envio(circuito_teleportacion, 0, 1) circuito_teleportacion.draw('mpl') def compuertas_bob(circ, b, crz, crx): circ.barrier() circ.x(b).c_if(crx, 1) circ.z(b).c_if(crz, 1) compuertas_bob(circuito_teleportacion, 2, crz, crx) circuito_teleportacion.draw('mpl') from qiskit.quantum_info import random_statevector from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex # generamos un estado aleatorio (el que enviará Alicia Bob y al ser aleatorio ella no lo conoce) psi = random_statevector(2) # veamos que de que estado se trata display(array_to_latex(psi, prefix="|\\psi\\rangle =")) plot_bloch_multivector(psi) from qiskit.extensions import Initialize # crear una instruccion de inicializacion que coloque al qubit en el estado que generamos aleatoriamente instruccion_inicializacion = Initialize(psi) instruccion_inicializacion.label = "init" # El protocolo completo: # Configuración inicial qr_alice = QuantumRegister(2, name="alicia") # dos qubits de Alicia qr_bob = QuantumRegister(1, name="bob") # un qubit de Bob crz = ClassicalRegister(1, name="crz") # 2 bits clasicos crx = ClassicalRegister(1, name="crx") # en 2 diferentes registros circuito_teleportacion = QuantumCircuit(qr_alice, qr_bob, crz, crx) # Paso 0 # Iniciar el qubit a enviar circuito_teleportacion.append(instruccion_inicializacion, [0]) circuito_teleportacion.barrier() # Paso 1 # Crear el par entrelazado crear_estado_bell(circuito_teleportacion, 1, 2) # circuito, qubit a, qubit b # Paso 2 # "Enviar" q1 a Alicia y q2 a Bob compuertas_alicia(circuito_teleportacion, 0, 1) # Paso 3 # Alicia envia sus bits clásicos a Bob mediciones_y_envio(circuito_teleportacion, 0, 1) # Paso 4 # Bob decodifica su qubit compuertas_bob(circuito_teleportacion, 2, crz, crx) circuito_teleportacion.draw('mpl') sim = Aer.get_backend('aer_simulator') circuito_teleportacion.save_statevector() out_vector = sim.run(circuito_teleportacion).result().get_statevector() display(plot_bloch_multivector(out_vector)) out_vector.draw('latex') reverso_instruccion_inicializacion = instruccion_inicializacion.gates_to_uncompute() qr_alice = QuantumRegister(2, name="alicia") # dos qubits de Alicia qr_bob = QuantumRegister(1, name="bob") # un qubit de Bob crz = ClassicalRegister(1, name="crz") # 2 bits clasicos crx = ClassicalRegister(1, name="crx") # en 2 diferentes registros circuito_teleportacion = QuantumCircuit(qr_alice, qr_bob, crz, crx) # Paso 0 # Iniciar el qubit a enviar circuito_teleportacion.append(instruccion_inicializacion, [0]) circuito_teleportacion.barrier() # Paso 1 # Crear el par entrelazado crear_estado_bell(circuito_teleportacion, 1, 2) # circuito, qubit a, qubit b # Paso 2 # "Enviar" q1 a Alicia y q2 a Bob compuertas_alicia(circuito_teleportacion, 0, 1) # Paso 3 # Alicia envia sus bits clásicos a Bob mediciones_y_envio(circuito_teleportacion, 0, 1) # Paso 4 # Bob decodifica su qubit compuertas_bob(circuito_teleportacion, 2, crz, crx) circuito_teleportacion.append(reverso_instruccion_inicializacion, [2]) circuito_teleportacion.draw('mpl') cr_result = ClassicalRegister(1) circuito_teleportacion.add_register(cr_result) circuito_teleportacion.measure(2, 2) circuito_teleportacion.draw('mpl') from qiskit.result import marginal_counts from qiskit import transpile t_qc = transpile(circuito_teleportacion, sim) t_qc.save_statevector() counts = sim.run(t_qc).result().get_counts() qubit_counts = [marginal_counts(counts, [qubit]) for qubit in range(3)] plot_histogram(qubit_counts) n = 3 # cantidad de bits para la función f from qiskit import QuantumCircuit import numpy as np #--------------------- ## Oráculo Constante #--------------------- const_oraculo = QuantumCircuit(n+1) # +1 qubit que corresponde al segundo registro # en este caso, la entrada no tiene efecto en la salida, por lo que simplemente # configuramos aleatoriamente el qubit de salida en 0 o 1: output = np.random.randint(2) if output == 1: const_oraculo.x(n) # aplicar X al qubits de salida (un solo resultado para todas las entradas) const_oraculo.draw('mpl') #--------------------- ## Oráculo Balanceado #--------------------- balan_oraculo = QuantumCircuit(n+1) # podemos crear un oráculo balanceado usando CNOTs con cada qubit de entrada como control # y el bit de salida como objetivo. Podemos variar los estados de entrada que dan 0 o 1 # encerrando algunos de los controles con compuertas X. Primero elijamos una cadena binaria de # longitud n que dicte qué controles ajustar: b_str = "101" # agregar las compuertas X en la posción donde hay un 1 for qubit in range(len(b_str)): if b_str[qubit] == '1': balan_oraculo.x(qubit) balan_oraculo.barrier() # ahora, aplicamos las compuertas CNOT, usando cada qubit de entrada como control y el # qubit de salida como objetivo: for qubit in range(n): balan_oraculo.cx(qubit, n) balan_oraculo.barrier() # finalmente, aplicamos compuertas X para terminar de envolver los controles: for qubit in range(len(b_str)): if b_str[qubit] == '1': balan_oraculo.x(qubit) balan_oraculo.draw('mpl') dj_circuit = QuantumCircuit(n+1, n) # n+1=4 qubits, n=3 bits clásicos dj_circuit.x(n) # colocar el último qubits (segundo registro) en el estado |1> dj_circuit.barrier() dj_circuit.draw('mpl') # Aplicar las compuertas H al primer registro for qubit in range(n): dj_circuit.h(qubit) # Aplicar H al segundo registro, H|1> = |-> dj_circuit.h(n) dj_circuit.barrier() dj_circuit.draw('mpl') def dj_oraculo(dj_circuit, caso): if caso == 'balanceado': circuit_return = dj_circuit.compose(balan_oraculo) else: circuit_return = dj_circuit.compose(const_oraculo) circuit_return.barrier() return circuit_return # generemos un circuito con el oráculo constante dj_circ_constante = dj_oraculo(dj_circuit, 'constante') # generemos un circuito con el oráculo balanceado dj_circ_balanceado = dj_oraculo(dj_circuit, 'balanceado') dj_circ_balanceado.draw('mpl') #--------------------- ## Oráculo Balanceado #--------------------- # Aplicar nuevaente compuertas H al primer registro (en el circuito que ya tienen el oráculo) for qubit in range(n): dj_circ_balanceado.h(qubit) dj_circ_balanceado.barrier() dj_circ_balanceado.draw('mpl') #--------------------- ## Oráculo Constante #--------------------- # Aplicar nuevaente compuertas H al primer registro (en el circuito que ya tienen el oráculo) for qubit in range(n): dj_circ_constante.h(qubit) dj_circ_constante.barrier() dj_circ_constante.draw('mpl') #--------------------- ## Oráculo Balanceado #--------------------- # agregamos mediciones al primer registro for i in range(n): dj_circ_balanceado.measure(i, i) dj_circ_balanceado.draw('mpl') #--------------------- ## Oráculo Constante #--------------------- # agregamos mediciones al primer registro for i in range(n): dj_circ_constante.measure(i, i) dj_circ_constante.draw('mpl') from qiskit import Aer aer_sim = Aer.get_backend('aer_simulator') #--------------------- ## Oráculo Constante #--------------------- results = aer_sim.run(dj_circ_constante).result() respuesta = results.get_counts() plot_histogram(respuesta) #--------------------- ## Oráculo Balanceado #--------------------- results = aer_sim.run(dj_circ_balanceado).result() respuesta = results.get_counts() plot_histogram(respuesta) from qiskit import QuantumCircuit n = 2 grover_circuit = QuantumCircuit(n) def initialize_s(qc, qubits): # Aplicar una compuerta H a los 'qubits' in qc for q in qubits: # return qc grover_circuit = initialize_s(grover_circuit, [0,1]) grover_circuit.draw('mpl') grover_circuit.barrier() grover_circuit.cz(0,1) # oráculo grover_circuit.barrier() grover_circuit.draw('mpl') # operador de difusión (U_s) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) grover_circuit.draw('mpl') from qiskit import Aer from qiskit.visualization import array_to_latex # revisamos el estado al final del circuito sv_sim = Aer.get_backend('statevector_simulator') result = sv_sim.run(grover_circuit).result() statevec = result.get_statevector() array_to_latex(statevec, prefix="|\\psi\\rangle =") # agregamos las mediciones a todos los qubits grover_circuit.measure_all() grover_circuit.draw('mpl') # simulamos la ejecución del circuito qasm_sim = Aer.get_backend('qasm_simulator') result = qasm_sim.run(grover_circuit).result() counts = result.get_counts() plot_histogram(counts) # crear el oráculo qc = QuantumCircuit(3) qc.cz(0, 2) qc.cz(1, 2) oracle_ex3 = qc.to_gate() oracle_ex3.name = "U$_\omega$" # función para un difusor general def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Aplicar la transformación |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Aplicar la transformación |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Aplicar múltiples compuertas Z controladas qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # toffoli con multicontrol qc.h(nqubits-1) # Aplicar la transformación |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Aplicar la transformación |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # Regresar el difusor como compuerta U_s = qc.to_gate() U_s.name = "U$_s$" return U_s # Ejemplo para circuito de 3 qubits n = 3 grover_circuit = QuantumCircuit(n) grover_circuit = initialize_s(grover_circuit, [0, 1, 2]) grover_circuit.append(oracle_ex3, [0, 1, 2]) grover_circuit.append(diffuser(n), [0, 1, 2]) grover_circuit.measure_all() grover_circuit.draw('mpl') # simulamos la ejecución del circuito qasm_sim = Aer.get_backend('qasm_simulator') transpiled_grover_circuit = transpile(grover_circuit, qasm_sim) # necesario para transpilar las compuertas Uw y Us results = qasm_sim.run(transpiled_grover_circuit).result() counts = results.get_counts() plot_histogram(counts) from qiskit.algorithms import AmplificationProblem # el estado que se desea encontrar '11' good_state = ['11'] # especificar el oráculo que marca el estado '11' como la solución correcta oracle = QuantumCircuit(2) oracle.cz(0, 1) # definir el algorito de Grover problem = AmplificationProblem(oracle, is_good_state=good_state) # veamos el operador Grover que será usado para resolver el problema problem.grover_operator.decompose().draw(output='mpl') from qiskit.algorithms import Grover aer_simulator = Aer.get_backend('aer_simulator') grover = Grover(quantum_instance=aer_simulator) # definir una instancia de `Grover` con el problema result = grover.amplify(problem) print('tipo del resultado:', type(result)) print() print('¡Éxito!' if result.oracle_evaluation else '¡Falló!') print() print('Medición más grande:', result.top_measurement) plot_histogram(result.circuit_results) import matplotlib.pyplot as plt N = 35 a = 3 xvals = range(35) yvals = [np.mod(a**x, N) for x in xvals] fig, ax = plt.subplots() ax.plot(xvals, yvals, linewidth=1, linestyle='dotted', marker='x') ax.set(xlabel='$x$', ylabel='$%i^x$ mod $%i$' % (a, N), title="Ejemplo de función periódica") try: # graficar 'r' r = yvals[1:].index(1) + 1 plt.annotate('', xy=(0, 1), xytext=(r, 1), arrowprops=dict(arrowstyle='<->')) plt.annotate('$r=%i$' % r, xy=(r/3, 1.5)) except ValueError: print('No se pudo encontrar el período, revisa que a < N y no tengan factores comunes') ax.set(xlabel='Cantidad de aplicaciones de U', ylabel='Estado final del registro', title="Efecto de aplicaciones sucesivas de U") fig def c_amod15(a, power): # Multiplicación conrolada por a mod 15 if a not in [2,4,7,8,11,13]: raise ValueError("'a' debe ser 2,4,7,8,11 o 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a in [4, 11]: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) c_U = U.control() return c_U n_count = 8 # número de qubits de conteo a = 7 def qft_dagger(n): # QFT daga de n qubits, los prmero n qubits en circ qc = QuantumCircuit(n) for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc # Crear el circuito final # circuito con n_count qubits de conteo # más 4 qubits para que U actúe sobre ellos qc = QuantumCircuit(n_count + 4, n_count) # inicializar los qubits de conteo # en el estado |+> for q in range(n_count): qc.h(q) # y un registro auxiliar en el estado |1> qc.x(3+n_count) # aplicar las U controladas for q in range(n_count): qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) # aplicar QFT daga qc.append(qft_dagger(n_count), range(n_count)) # medir el circuito qc.measure(range(n_count), range(n_count)) qc.draw('mpl', fold=-1) # -1 significa 'no separar' aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) results = aer_sim.run(t_qc).result() counts = results.get_counts() plot_histogram(counts) import pandas as pd rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Salida del registro", "Fase"] df = pd.DataFrame(rows, columns=headers) print(df) from fractions import Fraction Fraction(0.666) # Obtener la fracción que más se asemeje a 0.666 # con denominador < 15 Fraction(0.666).limit_denominator(15) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Fase", "Fracción", "Suposición para r"] df = pd.DataFrame(rows, columns=headers) print(df) def a2jmodN(a, j, N): # Calcular a^{2^j} (mod N) con 'repeated squaring' for i in range(j): a = np.mod(a**2, N) return a a2jmodN(7, 2049, 53) N = 15 from numpy.random import randint np.random.seed(1) # Para hacer reproducibles los resultados a = randint(2, 15) print(a) # ahora, comprobamos que no es ya un factor no trivial de N from math import gcd # máximo común divisor b(greatest common divisor) gcd(a, N) def qpe_amod15(a): n_count = 8 qc = QuantumCircuit(4+n_count, n_count) for q in range(n_count): qc.h(q) # Inicializar qubits en el estado |+> qc.x(3+n_count) # un registro auxiliar en el estado |1> for q in range(n_count): # aplicar operaciones U controladas qc.append(c_amod15(a, 2**q), [q] + [i+n_count for i in range(4)]) qc.append(qft_dagger(n_count), range(n_count)) # aplicar la QFT inversa qc.measure(range(n_count), range(n_count)) # simular los resultados aer_sim = Aer.get_backend('aer_simulator') # Configurar 'memory=True' permite ver una lista de cada lectura secuencial t_qc = transpile(qc, aer_sim) result = aer_sim.run(t_qc, shots=1, memory=True).result() readings = result.get_memory() print("Lectura del registro: " + readings[0]) phase = int(readings[0],2)/(2**n_count) print("Fase correspondiente: %f" % phase) return phase # a partir de esta fase, podemos encontrar fácilmente una suposición para r: phase = qpe_amod15(a) # fase = s/r Fraction(phase).limit_denominator(15) # el denominador debería decirnos r (eso esperamos) frac = Fraction(phase).limit_denominator(15) s, r = frac.numerator, frac.denominator print(r) guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] print(guesses) a = 7 factor_found = False attempt = 0 while not factor_found: attempt += 1 print("Intento %i:" % attempt) phase = qpe_amod15(a) # fase = s/r frac = Fraction(phase).limit_denominator(N) # el denominador debería decirnos r (eso esperamos) r = frac.denominator print("Resultado: r = %i" % r) if phase != 0: # las suposiciones para los factores son gcd(x^{r/2} ±1 , 15) guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] print("Factores supuestos: %i and %i" % (guesses[0], guesses[1])) for guess in guesses: if guess not in [1,N] and (N % guess) == 0: # Check to see if guess is a factor print("*** Factor encontrado no trivial: %i ***" % guess) factor_found = True from qiskit.utils import QuantumInstance from qiskit.algorithms import Shor N = 15 backend = Aer.get_backend('aer_simulator') quantum_instance = QuantumInstance(backend, shots=1024) shor = Shor(quantum_instance=quantum_instance) result = shor.factor(N) print(f"La lista de factores de {N} calculada por el algoritmo de Shor es {result.factors[0]}.")
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
import matplotlib.pyplot as plt import numpy as np # Calculate a 100 keV electron-beam path in an egg white resist based on the paper found at https://onlinelibrary.wiley.com/doi/epdf/10.1002/admi.201601223 # Full-access paper title: 'Water-Based Photo- and Electron-Beam Lithography Using Egg White as a Resist' # Monte Carlo simulation # Constants energy_keV = 100 # Beam energy in keV dose_uC_cm2 = 3000 # Beam dose in microcoulombs per cm^2 for positive pattern thickness_nm = 100 # Resist thickness in nm electron_charge = 1.602e-19 # Charge of an electron in Coulombs area_cm2 = 1e-14 # Area in cm^2 for single electron simulation (arbitrarily small for simulation purposes) # Calculations for the number of electrons per area dose_C_cm2 = dose_uC_cm2 * 1e-6 # Convert microcoulombs to coulombs num_electrons = dose_C_cm2 / electron_charge # Calculate the number of electrons per cm^2 # Monte Carlo simulation parameters num_electrons_simulated = int(num_electrons * area_cm2) # Scale number of electrons to the simulation area penetration_depths = [] # To store penetration depths # Define penetration depth function for the egg white resist # Assumption: Using a simple model where each interaction with the resist material reduces energy by a fixed amount # until energy falls below a threshold value, simulating the electron stopping in the resist. def simulate_electron_paths(num_electrons, energy_keV, thickness_nm): # Assuming simplistic linear penetration with energy reduction at each step # and a random scattering angle introducing some deviation in the path. paths = [] for _ in range(num_electrons): energy_remaining = energy_keV depth = 0 path = {'x': [0], 'z': [0]} # Start at origin while energy_remaining > 0 and depth < thickness_nm: # Simulate a step scattering_angle = np.random.uniform(-np.pi/4, np.pi/4) # Random angle within -45 to 45 degrees step_length = np.random.uniform(1, 5) # Random step length between 1 nm and 5 nm depth += step_length * np.cos(scattering_angle) # Increment depth based on step length and angle lateral_displacement = step_length * np.sin(scattering_angle) # Calculate lateral displacement # Update path path['x'].append(path['x'][-1] + lateral_displacement) path['z'].append(depth) # Reduce energy energy_remaining -= step_length * 0.1 # Arbitrary energy reduction per nm paths.append(path) return paths # Run the simulation electron_paths = simulate_electron_paths(num_electrons_simulated, energy_keV, thickness_nm) # Plot the results fig, ax = plt.subplots() plt.figure(figsize=(8,5), dpi=300) for path in electron_paths: ax.plot(path['x'], path['z']) ax.set_xlabel('Lateral Displacement (nm)', fontdict={'fontsize':14}) ax.set_ylabel('Penetration Depth (nm)', fontdict={'fontsize':14}) ax.set_title('Simulated Electron Paths in Egg White Resist', fontdict={'fontsize':20}) plt.show() # Adjusting plot parameters including title font size, axis font size, figure size, and dpi fig, ax = plt.subplots(figsize=(8, 5), dpi=300) for path in electron_paths: ax.plot(path['x'], -np.array(path['z'])) # Multiply the z values by -1 to flip the plot ax.set_xlabel('Lateral Displacement (nm)', fontsize=14) ax.set_ylabel('Penetration Depth (nm)', fontsize=14) ax.set_title('Simulated Electron Paths in Egg White Resist', fontsize=20) plt.show() # Try with 250 nm resist thickness # Constants energy_keV = 100 # Beam energy in keV dose_uC_cm2 = 3000 # Beam dose in microcoulombs per cm^2 for positive pattern thickness_nm = 250 # Resist thickness in nm electron_charge = 1.602e-19 # Charge of an electron in Coulombs area_cm2 = 1e-14 # Area in cm^2 for single electron simulation (arbitrarily small for simulation purposes) # Calculations for the number of electrons per area dose_C_cm2 = dose_uC_cm2 * 1e-6 # Convert microcoulombs to coulombs num_electrons = dose_C_cm2 / electron_charge # Calculate the number of electrons per cm^2 # Monte Carlo simulation parameters num_electrons_simulated = int(num_electrons * area_cm2) # Scale number of electrons to the simulation area penetration_depths = [] # To store penetration depths # Define penetration depth function for the egg white resist # Assumption: Using a simple model where each interaction with the resist material reduces energy by a fixed amount # until energy falls below a threshold value, simulating the electron stopping in the resist. def simulate_electron_paths(num_electrons, energy_keV, thickness_nm): # Assuming simplistic linear penetration with energy reduction at each step # and a random scattering angle introducing some deviation in the path. paths = [] for _ in range(num_electrons): energy_remaining = energy_keV depth = 0 path = {'x': [0], 'z': [0]} # Start at origin while energy_remaining > 0 and depth < thickness_nm: # Simulate a step scattering_angle = np.random.uniform(-np.pi/4, np.pi/4) # Random angle within -45 to 45 degrees step_length = np.random.uniform(1, 5) # Random step length between 1 nm and 5 nm depth += step_length * np.cos(scattering_angle) # Increment depth based on step length and angle lateral_displacement = step_length * np.sin(scattering_angle) # Calculate lateral displacement # Update path path['x'].append(path['x'][-1] + lateral_displacement) path['z'].append(depth) # Reduce energy energy_remaining -= step_length * 0.1 # Arbitrary energy reduction per nm paths.append(path) return paths # Run the simulation electron_paths = simulate_electron_paths(num_electrons_simulated, energy_keV, thickness_nm) # Plot results fig, ax = plt.subplots(figsize=(8, 5), dpi=300) for path in electron_paths: ax.plot(path['x'], -np.array(path['z'])) # Multiply the z values by -1 to flip the plot ax.set_xlabel('Lateral Displacement (nm)', fontsize=14) ax.set_ylabel('Penetration Depth (nm)', fontsize=14) ax.set_title('Simulated Electron Paths in Egg White Resist', fontsize=20) plt.show() # Try with 250 nm resist thickness # Constants energy_keV = 100 # Beam energy in keV dose_uC_cm2 = 3000 # Beam dose in microcoulombs per cm^2 for positive pattern thickness_nm = 250 # Resist thickness in nm electron_charge = 1.602e-19 # Charge of an electron in Coulombs area_cm2 = 1e-14 # Area in cm^2 for single electron simulation (arbitrarily small for simulation purposes) # Calculations for the number of electrons per area dose_C_cm2 = dose_uC_cm2 * 1e-6 # Convert microcoulombs to coulombs num_electrons = dose_C_cm2 / electron_charge # Calculate the number of electrons per cm^2 # Monte Carlo simulation parameters num_electrons_simulated = int(num_electrons * area_cm2) # Scale number of electrons to the simulation area penetration_depths = [] # To store penetration depths x_range_nm = (-150, 150) # X-axis range for plotting # Define penetration depth function for the egg white resist # Assumption: Using a simple model where each interaction with the resist material reduces energy by a fixed amount # until energy falls below a threshold value, simulating the electron stopping in the resist. def simulate_electron_paths(num_electrons, energy_keV, thickness_nm): # Assuming simplistic linear penetration with energy reduction at each step # and a random scattering angle introducing some deviation in the path. paths = [] for _ in range(num_electrons): energy_remaining = energy_keV depth = 0 path = {'x': [0], 'z': [0]} # Start at origin while energy_remaining > 0 and depth < thickness_nm: # Simulate a step scattering_angle = np.random.uniform(-np.pi/4, np.pi/4) # Random angle within -45 to 45 degrees step_length = np.random.uniform(1, 5) # Random step length between 1 nm and 5 nm depth += step_length * np.cos(scattering_angle) # Increment depth based on step length and angle lateral_displacement = step_length * np.sin(scattering_angle) # Calculate lateral displacement # Update path path['x'].append(path['x'][-1] + lateral_displacement) path['z'].append(depth) # Reduce energy energy_remaining -= step_length * 0.1 # Arbitrary energy reduction per nm paths.append(path) return paths # Run the simulation electron_paths = simulate_electron_paths(num_electrons_simulated, energy_keV, thickness_nm) # Plot results fig, ax = plt.subplots(figsize=(8, 5), dpi=300) for path in electron_paths: ax.plot(path['x'], -np.array(path['z'])) # Multiply the z values by -1 to flip the plot plt.xlim(x_range_nm) ax.set_xlabel('Lateral Displacement (nm)', fontsize=14) ax.set_ylabel('Penetration Depth (nm)', fontsize=14) ax.set_title('Simulated Electron Paths in Egg White Resist', fontsize=20) plt.show() # Try with a beam spot size of 2 nm, x-axis range of -150 nm to 150 nm, and 250 nm resist thickness # Constants for simulation electron_energy_keV = 100 # Electron energy in keV beam_dose_uSv_per_cm2 = 3000 # Beam dose in micro Sieverts per square centimeter beam_spot_size_nm = 2 # Beam spot size in nm resist_thickness_nm = 250 # Resist thickness in nm # Conversion factors and constants keV_to_Joule = 1.60218e-16 # Conversion from keV to Joules (1eV = 1.60218e-19 J) uSv_to_Joule_per_kg = 1e-6 # Conversion from micro Sieverts to Joules per kg (1 Sv = 1 J/kg) density_g_cm3 = 1.35 # Assumed density for egg white in g/cm^3 (value assumed for organic materials) density_kg_m3 = density_g_cm3 * 1e3 # Convert density to kg/m^3 # Assuming a spherical beam spot for volume calculation, which is an approximation for the Monte Carlo point source beam_radius_m = beam_spot_size_nm * 1e-9 / 2 # Convert nm to m and calculate radius beam_area_m2 = np.pi * (beam_radius_m ** 2) # Area of the beam spot in square meters # Calculate total energy deposited per beam spot total_energy_J = (beam_dose_uSv_per_cm2 * uSv_to_Joule_per_kg * density_kg_m3 * beam_area_m2) energy_per_electron_J = electron_energy_keV * keV_to_Joule number_of_electrons = total_energy_J / energy_per_electron_J # Calculate the number of electrons # Monte Carlo simulation parameters number_of_simulated_electrons = 1000 # Number of electrons to simulate for plotting max_depth_nm = resist_thickness_nm # Maximum penetration depth in nm x_range_nm = (-150, 150) # X-axis range for plotting # Generate random electron paths paths = [] for _ in range(number_of_simulated_electrons): # For simplicity, assume each electron travels straight down with some lateral dispersion depth = np.random.uniform(0, max_depth_nm) x_dispersion = np.random.normal(0, beam_spot_size_nm / 2) # Assume Gaussian spread around the beam spot size paths.append((x_dispersion, depth)) # Plotting the electron paths plt.figure(figsize=(6, 6), dpi=300) for path in paths: plt.plot([path[0], path[0]], [0, -path[1]], 'b') # Plot each path as a blue line # Set the plot limits and labels plt.xlim(x_range_nm) plt.ylim(-resist_thickness_nm, 0) plt.xlabel('Lateral Position (nm)', fontsize=14) plt.ylabel('Depth (nm)', fontsize=14) plt.title('Simulated Electron Beam Penetration in Egg White Resist', fontsize=20) plt.gca().set_aspect('equal', adjustable='box') plt.show()
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
%load_ext autoreload %autoreload 2 import qiskit_metal as metal from qiskit_metal import designs, draw from qiskit_metal import MetalGUI, Dict design = designs.DesignPlanar() design.overwrite_enabled = True gui = MetalGUI(design) from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket q1options = dict( connection_pads=dict( # pin connectors a = dict(loc_W=+1,loc_H=+1), b = dict(loc_W=-1,loc_H=+1), c = dict(loc_W=+1,loc_H=-1), d = dict(loc_W=-1,loc_H=-1) ) ) q1 = TransmonPocket(design, options = q1options) # this line only creates the object in memory and executes its __init__(), but does not "implement" gui.rebuild() # this updates the QComponent tables by running make() gui.autoscale() q1.default_options q1.options design.rename_component(q1.id,'Q1') q1.options.pos_x='-1.5mm' q2 = design.copy_qcomponent(q1, 'Q2') q2.options.pos_x='1.5mm' from qiskit_metal.qlibrary.tlines.meandered import RouteMeander options = Dict( total_length = '8mm', pin_inputs = Dict( start_pin = Dict( component = 'Q1', pin = 'a'), end_pin = Dict( component = 'Q2', pin = 'b')), ) cpw = RouteMeander(design, options=options) gui.rebuild() gui.autoscale() cpw.options.fillet = '90um' cpw.options.lead.start_straight = '90um' gui.rebuild() gui.autoscale() design.net_info design.delete_component('Q2') cpw.delete() design.net_info # from qiskit_metal.qlibrary.user_components.my429_qcomponents import MyQComponent1 import sys sys.path.append('../../resources') from my429_qcomponents import MyQComponent1 myQC = MyQComponent1(design, 'myQC') gui.rebuild() # this is need to actually make() the component gui.autoscale() options = Dict( total_length = '4mm', pin_inputs = Dict( start_pin = Dict( component = 'Q1', pin = 'a'), end_pin = Dict( component = myQC.name, pin = 'in')), fillet = '90um', lead = Dict( start_straight = '90um') ) cpw = RouteMeander(design, options=options) gui.rebuild() gui.autoscale() cpw.delete() myQC.delete() # from qiskit_metal.qlibrary.user_components.my429_qcomponents import MyQComponent2 from my429_qcomponents import MyQComponent2 opt_myqc = Dict(width='1mm', height='0.01mm', pos_x='0.1mm') myQC = MyQComponent2(design, 'myQC', options=opt_myqc) cpw = RouteMeander(design, options=options) gui.rebuild() # this is need to actually make() the component gui.autoscale() myQC.options cpw.delete() myQC.delete() opt_myqc.gap = '8um' opt_myqc.height = '20um' # from qiskit_metal.qlibrary.user_components.my429_qcomponents import MyQComponent4 from my429_qcomponents import MyQComponent4 myQC = MyQComponent4(design, options=opt_myqc) #opt_myqc defined earlier options = Dict( total_length = '4mm', pin_inputs = Dict( start_pin = Dict( component = 'Q1', pin = 'a'), end_pin = Dict( component = myQC.name, #updating this pin = 'in')), fillet = '90um', lead = Dict( start_straight = '90um') ) cpw = RouteMeander(design, options=options) gui.rebuild() # this is need to actually make() the component gui.autoscale() myQC.options
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
from qiskit_metal import draw, Dict from qiskit_metal.toolbox_metal import math_and_overrides from qiskit_metal.qlibrary.core import QComponent import qiskit_metal as metal design = metal.designs.DesignPlanar() from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket ?TransmonPocket face = draw.shapely.geometry.Point(0, 0).buffer(1) eye = draw.shapely.geometry.Point(0, 0).buffer(0.2) eye_l = draw.translate(eye, -0.4, 0.4) eye_r = draw.translate(eye, 0.4, 0.4) smile = draw.shapely.geometry.Point(0, 0).buffer(0.8) cut_sq = draw.shapely.geometry.box(-1, -0.3, 1, 1) smile = draw.subtract(smile, cut_sq) face = draw.subtract(face, smile) face = draw.subtract(face, eye_r) face = draw.subtract(face, eye_l) face face.exterior face.interiors[0] big_square = draw.rectangle(10,10,0,0) cut_rectangle = draw.rectangle(12,1,0,0) multi_poly = draw.subtract(big_square, cut_rectangle) multi_poly type(multi_poly) ?metal.qgeometries.QGeometryTables.add_qgeometry import numpy as np from qiskit_metal import draw, Dict from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket class TransmonPocketCL(TransmonPocket): # pylint: disable=invalid-name """ The base `TransmonPocketCL` class Inherits `TransmonPocket` class Description: Create a standard pocket transmon qubit for a ground plane, with two pads connected by a junction (see drawing below). Connector lines can be added using the `connection_pads` dictionary. Each connector line has a name and a list of default properties. This is a child of TransmonPocket, see TransmonPocket for the variables and description of that class. :: _________________ | | |_______________| ^ ________x________ | N | | | |_______________| .. image:: Component_Qubit_Transmon_Pocket_CL.png Charge Line: * make_CL (bool): If a chargeline should be included. * cl_gap (string): The cpw dielectric gap of the charge line. * cl_width (string): The cpw width of the charge line. * cl_length (string): The length of the charge line 'arm' coupling the the qubit pocket. Measured from the base of the 90 degree bend. * cl_ground_gap (string): How much ground is present between the charge line and the qubit pocket. * cl_pocket_edge (string): What side of the pocket the charge line is. -180 to +180 from the 'west edge', will round to the nearest 90. * cl_off_center (string): Distance from the center axis the qubit pocket is referenced to """ component_metadata = Dict(short_name='Q', _qgeometry_table_poly='True') """Component metadata""" default_options = Dict( make_CL=True, cl_gap='6um', # the cpw dielectric gap of the charge line cl_width='10um', # the cpw trace width of the charge line # the length of the charge line 'arm' coupling the the qubit pocket. cl_length='20um', # Measured from the base of the 90 degree bend cl_ground_gap= '6um', # how much ground between the charge line and the qubit pocket # -180 to +180 from the 'left edge', will round to the nearest 90. cl_pocket_edge='0', cl_off_center= '100um', # distance from the center axis the qubit pocket is built on ) """Default drawing options""" def make(self): """Define the way the options are turned into QGeometry.""" super().make() if self.options.make_CL == True: self.make_charge_line() ##################################################################### def make_charge_line(self): """Creates the charge line if the user has charge line option to TRUE """ # Grab option values name = 'Charge_Line' p = self.p cl_arm = draw.box(0, 0, -p.cl_width, p.cl_length) cl_cpw = draw.box(0, 0, -8 * p.cl_width, p.cl_width) cl_metal = draw.unary_union([cl_arm, cl_cpw]) cl_etcher = draw.buffer(cl_metal, p.cl_gap) port_line = draw.LineString([(-8 * p.cl_width, 0), (-8 * p.cl_width, p.cl_width)]) polys = [cl_metal, cl_etcher, port_line] # Move the charge line to the side user requested cl_rotate = 0 if (abs(p.cl_pocket_edge) > 135) or (abs(p.cl_pocket_edge) < 45): polys = draw.translate( polys, -(p.pocket_width / 2 + p.cl_ground_gap + p.cl_gap), -(p.pad_gap + p.pad_height) / 2) if (abs(p.cl_pocket_edge) > 135): p.cl_rotate = 180 else: polys = draw.translate( polys, -(p.pocket_height / 2 + p.cl_groundGap + p.cl_gap), -(p.pad_width) / 2) cl_rotate = 90 if (p.cl_pocket_edge < 0): cl_rotate = -90 # Rotate it to the pockets orientation polys = draw.rotate(polys, p.orientation + cl_rotate, origin=(0, 0)) # Move to the final position polys = draw.translate(polys, p.pos_x, p.pos_y) [cl_metal, cl_etcher, port_line] = polys # Generating pins points = list(draw.shapely.geometry.shape(port_line).coords) self.add_pin(name, points, p.cl_width) # TODO: chip # Adding to element table self.add_qgeometry('poly', dict(cl_metal=cl_metal)) self.add_qgeometry('poly', dict(cl_etcher=cl_etcher), subtract=True) gui = metal.MetalGUI(design) my_transmon_cl = TransmonPocketCL(design,'my_transmon_cl',options=dict(connection_pads=dict(a=dict(),b=dict(loc_W=-1)))) gui.rebuild() my_transmon_cl.options gui.main_window.close()
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from qiskit_metal import draw, Dict from qiskit_metal.toolbox_metal import math_and_overrides from qiskit_metal.qlibrary.core import QComponent dir(QComponent) class MyQComponent(QComponent): """ Use this class as a template for your components - have fun Description: Options: """ # Edit these to define your own tempate options for creation # Default drawing options default_options = Dict(width='500um', height='300um', pos_x='0um', pos_y='0um', orientation='0', layer='1') """Default drawing options""" # Name prefix of component, if user doesn't provide name component_metadata = Dict(short_name='component', _qgeometry_table_poly='True') """Component metadata""" def make(self): """Convert self.options into QGeometry.""" p = self.parse_options() # Parse the string options into numbers # EDIT HERE - Replace the following with your code # Create some raw geometry # Use autocompletion for the `draw.` module (use tab key) rect = draw.rectangle(p.width, p.height, p.pos_x, p.pos_y) rect = draw.rotate(rect, p.orientation) rect = draw.translate(rect,p.pos_x,p.pos_y) geom = {'my_polygon': rect} self.add_qgeometry('poly', geom, layer=p.layer, subtract=False) draw.rectangle(1,2,0,0) draw.rotate(draw.rectangle(1,2,0,0), 45) face = draw.shapely.geometry.Point(0, 0).buffer(1) eye = draw.shapely.geometry.Point(0, 0).buffer(0.2) eye_l = draw.translate(eye, -0.4, 0.4) eye_r = draw.translate(eye, 0.4, 0.4) smile = draw.shapely.geometry.Point(0, 0).buffer(0.8) cut_sq = draw.shapely.geometry.box(-1, -0.3, 1, 1) smile = draw.subtract(smile, cut_sq) face = draw.subtract(face, smile) face = draw.subtract(face, eye_r) face = draw.subtract(face, eye_l) face import qiskit_metal as metal ?metal.qlibrary.core.QComponent.add_qgeometry ?metal.qlibrary.core.QComponent.add_pin from qiskit_metal import draw, Dict from qiskit_metal.toolbox_metal import math_and_overrides from qiskit_metal.qlibrary.core import QComponent class MySimpleGapCapacitor(QComponent): """ Inherits 'QComponent' class. Description: A simple CPW style gap capacitor, with endcap islands each coupled to their own cpw transmission line that ends in a pin. Options: * cpw_width: width of the cpw trace of the transmission line * cpw_gap: dielectric gap of the cpw transmission line * cap_width: width of the gap capacitor (size of the charge islands) * cap_gap: dielectric space between the two islands * pos_x/_y: position of the capacitor on chip * orientation: 0-> is parallel to x-axis, with orientation (in degrees) counterclockwise. * layer: the layer number for the layout """ # Edit these to define your own tempate options for creation # Default drawing options default_options = Dict(cpw_width='15um', cpw_gap='9um', cap_width='35um', cap_gap='3um', pos_x='0um', pos_y='0um', orientation='0', layer='1') """Default drawing options""" # Name prefix of component, if user doesn't provide name component_metadata = Dict(short_name='component', _qgeometry_table_poly='True', _qgeometry_table_path='True') """Component metadata""" def make(self): """Convert self.options into QGeometry.""" p = self.parse_options() # Parse the string options into numbers pad = draw.rectangle(p.cpw_width, p.cap_width, 0, 0) pad_left = draw.translate(pad,-(p.cpw_width+p.cap_gap)/2,0) pad_right = draw.translate(pad,(p.cpw_width+p.cap_gap)/2,0) pad_etch = draw.rectangle(2*p.cpw_gap+2*p.cpw_width+p.cap_gap,2*p.cpw_gap+p.cap_width) cpw_left = draw.shapely.geometry.LineString([[-(p.cpw_width+p.cap_gap/2),0],[-(p.cpw_width*3 +p.cap_gap/2),0]]) cpw_right = draw.shapely.geometry.LineString([[(p.cpw_width+p.cap_gap/2),0],[(p.cpw_width*3 +p.cap_gap/2),0]]) geom_list = [pad_left,pad_right,cpw_left,cpw_right,pad_etch] geom_list = draw.rotate(geom_list,p.orientation) geom_list = draw.translate(geom_list,p.pos_x,p.pos_y) [pad_left,pad_right,cpw_left,cpw_right,pad_etch] = geom_list self.add_qgeometry('path', {'cpw_left':cpw_left, 'cpw_right':cpw_right}, layer=p.layer, width = p.cpw_width) self.add_qgeometry('path', {'cpw_left_etch':cpw_left, 'cpw_right_etch':cpw_right}, layer=p.layer, width = p.cpw_width+2*p.cpw_gap, subtract=True) self.add_qgeometry('poly', {'pad_left':pad_left, 'pad_right':pad_right}, layer=p.layer) self.add_qgeometry('poly', {'pad_etch':pad_etch}, layer=p.layer, subtract=True) self.add_pin('cap_left', cpw_left.coords, width = p.cpw_width, gap = p.cpw_gap, input_as_norm=True) self.add_pin('cap_right', cpw_right.coords, width = p.cpw_width, gap = p.cpw_gap, input_as_norm=True) design = metal.designs.DesignPlanar() gui = metal.MetalGUI(design) my_cap = MySimpleGapCapacitor(design,'my_cap') gui.rebuild() design.overwrite_enabled = True gui.main_window.close()
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
%load_ext autoreload %autoreload 2 import qiskit_metal as metal from qiskit_metal import designs, MetalGUI from qiskit_metal import Dict, Headings design = designs.DesignPlanar() gui = MetalGUI(design) from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket from qiskit_metal.qlibrary.tlines.meandered import RouteMeander design.overwrite_enabled = True N_x =4 N_y =3 design.chips.main.size.size_x = str((N_x+1) * 3)+'mm' design.chips.main.size.size_y = str((N_y+1) * 3)+'mm' design.chips.main.size.center_x = str((N_x-1) * 1.5)+'mm' design.chips.main.size.center_y = str((N_y-0.5) * 1.5)+'mm' #Loop to generate and draw the qubits for x in range(N_x): for y in range(N_y): options = dict(pos_x= str(x*3000)+'um', pos_y = str(y*3000 + (x%2)*1500)+'um', orientation = "-90", connection_pads = dict( B0 = dict(loc_W=-1, loc_H=-1, pad_width='75um'), B1 = dict(loc_W=-1, loc_H=+1, pad_width='120um'), B2 = dict(loc_W=+1, loc_H=-1, pad_width='120um'), B3 = dict(loc_w = +1, loc_H = +1, pad_width='90um'))) obj=TransmonPocket(design,'Q_'+str(x)+'_'+str(y),options) gui.rebuild() gui.autoscale() for x in range(N_x): for y in range(N_y): #"upward" connection, avoids drawing connectors for 'top' row. Changes connector length by +/-50um to avoid frequency collisions if y<(N_y-1): connectorAD = RouteMeander(design,'CU_'+str(x)+'_'+str(y),options = dict(total_length = str(7+(y%2)*0.5)+'mm', fillet = "99um",lead=dict( start_straight='0.5mm', end_straight='0.25mm'), meander = dict(asymmetry='-700um'), pin_inputs = dict( start_pin=dict( component ='Q_'+str(x)+'_'+str(y), pin = 'B0'), end_pin=dict( component='Q_'+str(x)+'_'+str(y+1), pin='B3')))) #"sideways" connection, avoids drawing for far right col, and for top qubit in odd col. Changes connector length by +/- 25um #to avoid frequency collisions if x<(N_x-1) and (not(x%2 and y==(N_y-1))): connectorBC = RouteMeander(design,'CS_'+str(x)+'_'+str(y),options= dict(total_length = str(6+(y%2)*0.5)+'mm', fillet = "99um",lead=Dict( start_straight='0.3mm', end_straight='0.25mm'), meander = Dict(asymmetry='-200um'), pin_inputs = Dict( start_pin=Dict( component ='Q_'+str(x)+'_'+str(y), pin = 'B1'), end_pin=Dict( component='Q_'+str(x+1)+'_'+str(y+(x%2)), pin='B2')))) gui.rebuild() gui.autoscale() gui.screenshot() from qiskit_metal.analyses.quantization import LOManalysis c1 = LOManalysis(design, "q3d") c1.sim.setup c1.sim.setup.name = 'LOM' c1.sim.setup.max_passes = 14 #To change multiple settings use the following method: #c1.sim.setup_update(name = 'LOM', max_passes = 14) c1.sim.setup c1.sim.run(components=['Q_0_0'], open_terminations=[('Q_0_0', 'B0'), ('Q_0_0', 'B1'), ('Q_0_0', 'B2'), ('Q_0_0', 'B3')]) c1.setup.junctions = Dict({'Lj': 12.31, 'Cj': 2}) c1.setup.freq_readout = 6.6 c1.setup.freq_bus = [6.0, 6.2,6.4] c1.run_lom() c1.sim.close() chip_gds = design.renderers.gds chip_gds.options['no_cheese']['buffer'] = '50um' chip_gds.options['path_filename'] = '../../resources/Fake_Junctions.GDS' chip_gds.export_to_gds("NxN_Chip.gds") gui.main_window.close()
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
%load_ext autoreload %autoreload 2 import qiskit_metal as metal from qiskit_metal import designs, draw from qiskit_metal import MetalGUI, Dict, open_docs %metal_heading Welcome to Qiskit Metal! from qiskit_metal.qlibrary.qubits.transmon_pocket_6 import TransmonPocket6 from qiskit_metal.qlibrary.qubits.transmon_cross_fl import TransmonCrossFL from qiskit_metal.qlibrary.couplers.tunable_coupler_01 import TunableCoupler01 from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal.qlibrary.tlines.pathfinder import RoutePathfinder from qiskit_metal.qlibrary.tlines.anchored_path import RouteAnchors from qiskit_metal.qlibrary.lumped.cap_n_interdigital import CapNInterdigital from qiskit_metal.qlibrary.couplers.cap_n_interdigital_tee import CapNInterdigitalTee from qiskit_metal.qlibrary.couplers.coupled_line_tee import CoupledLineTee from qiskit_metal.qlibrary.terminations.launchpad_wb import LaunchpadWirebond from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled design = metal.designs.DesignPlanar() gui = metal.MetalGUI(design) design.overwrite_enabled = True design.chips.main design.chips.main.size.size_x = '11mm' design.chips.main.size.size_y = '9mm' TransmonPocket6.get_template_options(design) options = dict( pad_width = '425 um', pocket_height = '650um', connection_pads=dict( readout = dict(loc_W=0, loc_H=-1, pad_width = '80um', pad_gap = '50um'), bus_01 = dict(loc_W=-1, loc_H=-1, pad_width = '60um', pad_gap = '10um'), bus_02 = dict(loc_W=-1, loc_H=+1, pad_width = '60um', pad_gap = '10um'), bus_03 = dict(loc_W=0, loc_H=+1, pad_width = '90um', pad_gap = '30um'), bus_04 = dict(loc_W=+1, loc_H=+1, pad_width = '60um', pad_gap = '10um'), bus_05 = dict(loc_W=+1, loc_H=-1, pad_width = '60um', pad_gap = '10um') )) q_main = TransmonPocket6(design,'Q_Main', options = dict( pos_x='0mm', pos_y='-1mm', gds_cell_name ='FakeJunction_01', hfss_inductance ='14nH', **options)) gui.rebuild() gui.autoscale() TransmonCrossFL.get_template_options(design) Q1 = TransmonCrossFL(design, 'Q1', options = dict(pos_x = '-2.75mm', pos_y='-1.8mm', connection_pads = dict( bus_01 = dict(connector_location = '180',claw_length ='95um'), readout = dict(connector_location = '0')), fl_options = dict())) Q2 = TransmonCrossFL(design, 'Q2', options = dict(pos_x = '-2.75mm', pos_y='-1.2mm', orientation = '180', connection_pads = dict( bus_02 = dict(connector_location = '0',claw_length ='95um'), readout = dict(connector_location = '180')), fl_options = dict())) tune_c_Q12 = TunableCoupler01(design,'Tune_C_Q12', options = dict(pos_x = '-2.81mm', pos_y = '-1.5mm', orientation=90, c_width='500um')) gui.rebuild() gui.autoscale() Q3 = TransmonPocket6(design,'Q3', options = dict( pos_x='-3mm', pos_y='0.5mm', gds_cell_name ='FakeJunction_01', hfss_inductance ='14nH', connection_pads = dict( bus_03 = dict(loc_W=0, loc_H=-1, pad_width = '80um', pad_gap = '15um'), bus_q3_q4 = dict(loc_W=1, loc_H=-1, pad_width = '80um', pad_gap = '15um'), readout = dict(loc_W=0, loc_H=1, pad_width = '80um', pad_gap = '50um')))) Q4 = TransmonPocket6(design,'Q4', options = dict( pos_x='0mm', pos_y='1mm', gds_cell_name ='FakeJunction_01', hfss_inductance ='14nH', connection_pads = dict( bus_04 = dict(loc_W=0, loc_H=-1, pad_width = '80um', pad_gap = '15um'), bus_q3_q4 = dict(loc_W=-1, loc_H=-1, pad_width = '80um', pad_gap = '15um'), bus_q4_q5 = dict(loc_W=1, loc_H=-1, pad_width = '80um', pad_gap = '15um'), readout = dict(loc_W=0, loc_H=1, pad_width = '80um', pad_gap = '50um')))) Q5 = TransmonPocket6(design,'Q5', options = dict( pos_x='3mm', pos_y='0.5mm', gds_cell_name ='FakeJunction_01', hfss_inductance ='14nH', connection_pads = dict( bus_05 = dict(loc_W=0, loc_H=-1, pad_width = '80um', pad_gap = '15um'), bus_q4_q5 = dict(loc_W=-1, loc_H=-1, pad_width = '80um', pad_gap = '15um'), readout = dict(loc_W=0, loc_H=1, pad_width = '80um', pad_gap = '50um')))) from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" bus_01 = RouteMeander(design,'Bus_01', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='bus_01'), end_pin=Dict( component='Q1', pin='bus_01') ), lead=Dict( start_straight='125um', end_straight = '225um' ), meander=Dict( asymmetry = '1305um'), fillet = "99um", total_length = '6mm')) bus_02 = RouteMeander(design,'Bus_02', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='bus_02'), end_pin=Dict( component='Q2', pin='bus_02') ), lead=Dict( start_straight='325um', end_straight = '125um' ), meander=Dict( asymmetry = '450um'), fillet = "99um", total_length = '6.4mm')) gui.rebuild() bus_03 = RouteMeander(design,'Bus_03', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='bus_03'), end_pin=Dict( component='Q3', pin='bus_03') ), lead=Dict( start_straight='225um', end_straight = '25um' ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '6.8mm')) #To help set the right spacing, jogs can be used to set some initially controlled routing paths from collections import OrderedDict jogs_start = OrderedDict() jogs_start[0] = ["L", '250um'] jogs_start[1] = ["R", '200um'] jogs_end = OrderedDict() jogs_end[0] = ["L", '600um'] bus_04 = RouteMeander(design,'Bus_04', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='bus_04'), end_pin=Dict( component='Q4', pin='bus_04') ), lead=Dict( start_straight='225um', #end_straight = '25um', start_jogged_extension=jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '150um'), fillet = "99um", total_length = '7.2mm')) bus_05 = RouteMeander(design,'Bus_05', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='bus_05'), end_pin=Dict( component='Q5', pin='bus_05') ), lead=Dict( start_straight='225um', end_straight = '25um' ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '7.6mm')) gui.rebuild() bus_q3_q4 = RouteMeander(design,'Bus_Q3_Q4', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q3', pin='bus_q3_q4'), end_pin=Dict( component='Q4', pin='bus_q3_q4') ), lead=Dict( start_straight='125um', end_straight = '125um' ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '6.4mm')) bus_q4_q5 = RouteMeander(design,'Bus_Q4_Q5', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q4', pin='bus_q4_q5'), end_pin=Dict( component='Q5', pin='bus_q4_q5') ), lead=Dict( start_straight='125um', end_straight = '25um' ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '6.8mm')) gui.rebuild() launch_qmain_read = LaunchpadWirebond(design, 'Launch_QMain_Read', options = dict(pos_x = '2mm', pos_y ='-4mm', orientation = '90')) launch_q1_fl = LaunchpadWirebond(design, 'Launch_Q1_FL', options = dict(pos_x = '0mm', pos_y ='-4mm', orientation = '90', trace_width = '5um', trace_gap = '3um',)) launch_q1_read = LaunchpadWirebondCoupled(design, 'Launch_Q1_Read', options = dict(pos_x = '-2mm', pos_y ='-4mm', orientation = '90')) launch_tcoup_fl = LaunchpadWirebond(design, 'Launch_TuneC_FL', options = dict(pos_x = '-4mm', pos_y ='-4mm', orientation = '90', trace_width = '5um', trace_gap = '3um',)) launch_tcoup_read = LaunchpadWirebondCoupled(design, 'Launch_TuneC_Read', options = dict(pos_x = '-5mm', pos_y ='-3mm', orientation = '0')) launch_q2_read = LaunchpadWirebondCoupled(design, 'Launch_Q2_Read', options = dict(pos_x = '-5mm', pos_y ='-1mm', orientation = '0')) launch_q2_fl = LaunchpadWirebond(design, 'Launch_Q2_FL', options = dict(pos_x = '-5mm', pos_y ='1mm', orientation = '0', trace_width = '5um', trace_gap = '3um',)) launch_nw = LaunchpadWirebond(design, 'Launch_NW',options = dict(pos_x = '-5mm', pos_y='3mm', orientation=0)) launch_ne = LaunchpadWirebond(design, 'Launch_NE',options = dict(pos_x = '5mm', pos_y='3mm', orientation=180)) gui.rebuild() #Main Readout read_q_main_cap = CapNInterdigital(design,'Read_Q_Main_Cap', options = dict(pos_x = '2mm', pos_y ='-3.5mm', orientation = '0')) jogs_end = OrderedDict() jogs_end[0] = ["L", '600um'] jogs_start = OrderedDict() jogs_start[0] = ["L", '250um'] read_q_main = RouteMeander(design,'Read_Q_Main', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q_Main', pin='readout'), end_pin=Dict( component='Read_Q_Main_Cap', pin='north_end') ), lead=Dict( start_straight='725um', end_straight = '625um', start_jogged_extension = jogs_start, end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '5.6mm')) read_q_main_cap_launch = RoutePathfinder(design, 'Read_Q_Main_Cap_Launch', options = dict(hfss_wire_bonds = True, pin_inputs = dict( start_pin=Dict( component='Read_Q_Main_Cap', pin='south_end'), end_pin=Dict( component='Launch_QMain_Read', pin='tie')), lead=Dict( start_straight='0um', end_straight = '0um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ))) gui.rebuild() #Crossmon's Readouts jogs_end = OrderedDict() jogs_end[0] = ["L", '600um'] jogs_start = OrderedDict() jogs_start[0] = ["L", '250um'] read_q1 = RouteMeander(design,'Read_Q1', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q1', pin='readout'), end_pin=Dict( component='Launch_Q1_Read', pin='tie') ), lead=Dict( start_straight='250um', end_straight = '25um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '6.8mm')) jogs_end = OrderedDict() jogs_end[0] = ["L", '600um'] jogs_start = OrderedDict() jogs_start[0] = ["L", '250um'] read_tunec = RouteMeander(design,'Read_TuneC', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Tune_C_Q12', pin='Control'), end_pin=Dict( component='Launch_TuneC_Read', pin='tie') ), lead=Dict( start_straight='1525um', end_straight = '125um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '50um'), fillet = "99um", total_length = '5.8mm')) jogs_end = OrderedDict() jogs_end[0] = ["L", '600um'] jogs_start = OrderedDict() jogs_start[0] = ["L", '250um'] read_q2 = RouteMeander(design,'Read_Q2', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q2', pin='readout'), end_pin=Dict( component='Launch_Q2_Read', pin='tie') ), lead=Dict( start_straight='350um', end_straight = '0um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '-450um'), fillet = "99um", total_length = '5.4mm')) gui.rebuild() #Crossmon flux lines flux_line_Q1 = RoutePathfinder(design,'Flux_Line_Q1', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q1', pin='flux_line'), end_pin=Dict( component='Launch_Q1_FL', pin='tie')), fillet = '99um', trace_width = '5um', trace_gap = '3um', #anchors = anchors )) jogs_start = OrderedDict() jogs_start[0] = ["L", '750um'] flux_line_tunec = RoutePathfinder(design,'Flux_Line_TuneC', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Tune_C_Q12', pin='Flux'), end_pin=Dict( component='Launch_TuneC_FL', pin='tie')), lead=Dict( start_straight='875um', end_straight = '350um', start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), fillet = '99um', trace_width = '5um', trace_gap = '3um', #anchors = anchors )) jogs_start = OrderedDict() jogs_start[0] = ["L", '525um'] jogs_start[1] = ["R", '625um'] flux_line_Q2 = RoutePathfinder(design,'Flux_Line_Q2', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q2', pin='flux_line'), end_pin=Dict( component='Launch_Q2_FL', pin='tie')), lead=Dict( start_straight='175um', end_straight = '150um', start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), fillet = '99um', trace_width = '5um', trace_gap = '3um', #anchors = anchors )) gui.rebuild() q3_read_T = CoupledLineTee(design,'Q3_Read_T', options=dict(pos_x = '-3mm', pos_y = '3mm', orientation = '0', coupling_length = '200um', open_termination = False)) #We use finger count to set the width of the gap capacitance, -> N*cap_width + (N-1)*cap_gap q4_read_T = CapNInterdigitalTee(design,'Q4_Read_T', options=dict(pos_x = '0mm', pos_y = '3mm', orientation = '0', finger_length = '0um', finger_count = '8')) q5_read_T = CapNInterdigitalTee(design,'Q5_Read_T', options=dict(pos_x = '3mm', pos_y = '3mm', orientation = '0', finger_length = '50um', finger_count = '11')) gui.rebuild() read_q3 = RouteMeander(design,'Read_Q3', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q3', pin='readout'), end_pin=Dict( component='Q3_Read_T', pin='second_end') ), lead=Dict( start_straight='150um', end_straight = '150um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '0um'), fillet = "99um", total_length = '5mm')) read_q4 = RouteMeander(design,'Read_Q4', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q4', pin='readout'), end_pin=Dict( component='Q4_Read_T', pin='second_end') ), lead=Dict( start_straight='125um', end_straight = '125um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '0um'), fillet = "99um", total_length = '5.8mm')) read_q5 = RouteMeander(design,'Read_Q5', options = dict(hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component='Q5', pin='readout'), end_pin=Dict( component='Q5_Read_T', pin='second_end') ), lead=Dict( start_straight='125um', end_straight = '125um', #start_jogged_extension = jogs_start, #end_jogged_extension = jogs_end ), meander=Dict( asymmetry = '0um'), fillet = "99um", total_length = '5.4mm')) gui.rebuild() mp_tl_01 = RoutePathfinder(design, 'ML_TL_01', options = dict(hfss_wire_bonds = True, pin_inputs = dict( start_pin=Dict( component='Launch_NW', pin='tie'), end_pin=Dict( component='Q3_Read_T', pin='prime_start')) )) mp_tl_02 = RoutePathfinder(design, 'ML_TL_02', options = dict(hfss_wire_bonds = True, pin_inputs = dict( start_pin=Dict( component='Q3_Read_T', pin='prime_end'), end_pin=Dict( component='Q4_Read_T', pin='prime_start')) )) mp_tl_03 = RoutePathfinder(design, 'ML_TL_03', options = dict(hfss_wire_bonds = True, pin_inputs = dict( start_pin=Dict( component='Q4_Read_T', pin='prime_end'), end_pin=Dict( component='Q5_Read_T', pin='prime_start')) )) mp_tl_04 = RoutePathfinder(design, 'ML_TL_04', options = dict(hfss_wire_bonds = True, pin_inputs = dict( start_pin=Dict( component='Q5_Read_T', pin='prime_end'), end_pin=Dict( component='Launch_NE', pin='tie')) )) gui.rebuild() from qiskit_metal.analyses.quantization import LOManalysis c1 = LOManalysis(design, "q3d") c1.sim.setup c1.sim.setup.name = 'Tune_Q_Main' c1.sim.setup.max_passes = 16 c1.sim.setup.min_converged_passes = 2 c1.sim.setup.percent_error = 0.05 c1.sim.setup c1.sim.run(name="Q_Main", components=['Q_Main'], open_terminations=[('Q_Main', 'readout'), ('Q_Main', 'bus_01'),('Q_Main', 'bus_02'),('Q_Main', 'bus_03'), ('Q_Main', 'bus_04'), ('Q_Main', 'bus_05')]) c1.sim.capacitance_matrix c1.setup.junctions = Dict({'Lj': 14, 'Cj': 2}) c1.setup.freq_readout = 7.0 c1.setup.freq_bus = [5.6, 5.7, 5.8, 5.9, 6.0] # list of the bus frequencies c1.run_lom() c1.lumped_oscillator_all c1.plot_convergence(); c1.plot_convergence_chi() c1.sim.close() from qiskit_metal.analyses.quantization import EPRanalysis eig_qb = EPRanalysis(design, "hfss") eig_qb.sim.renderer.options['wb_size'] = 5 em_p = eig_qb.sim.setup em_p.name = '3Modes' em_p.min_freq_ghz = 4 em_p.n_modes = 3 em_p.max_passes = 10 em_p.max_delta_f = 0.1 em_p.min_converged = 2 # Design variables can also be added in for direct simulation sweeps. em_p.vars = Dict({'Lj1': '13 nH', 'Cj1': '0 fF', 'Lj2': '15 nH', 'Cj2': '0 fF'}) eig_qb.sim.setup q_main.options.hfss_inductance Q5.options.hfss_inductance q_main.options.hfss_inductance = '13nH' Q5.options.hfss_inductance = '15nH' bus_05.options.total_length = '7.5mm' gui.rebuild() eig_qb.sim.run(name="QMain_Q5_Bus05", components=['Q_Main', 'Q5','Bus_05'], open_terminations=[]) eig_qb.sim.plot_convergences() eig_qb.del_junction() eig_qb.add_junction('jj1', 'Lj1', 'Cj1', rect='JJ_rect_Lj_Q_Main_rect_jj', line='JJ_Lj_Q_Main_rect_jj_') eig_qb.add_junction('jj2', 'Lj2', 'Cj2', rect='JJ_rect_Lj_Q5_rect_jj', line='JJ_Lj_Q5_rect_jj_') eig_qb.setup.sweep_variable = 'Lj1' eig_qb.setup eig_qb.run_epr() # (pyEPR allows to switch modes: eprd.set_mode(1)) eig_qb.sim.close() full_chip_gds = design.renderers.gds full_chip_gds.options full_chip_gds.options['path_filename'] ='../resources/Fake_Junctions.GDS' full_chip_gds.options['no_cheese']['buffer']='50um' full_chip_gds.export_to_gds('Full_Chip_01.gds') # gui.main_window.close()
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
%load_ext autoreload %autoreload 2 import qiskit_metal as metal from qiskit_metal import designs, draw from qiskit_metal import MetalGUI, Dict, open_docs %metal_heading Welcome to Qiskit Metal! design = designs.DesignPlanar() gui = MetalGUI(design) # Select a QComponent to create (The QComponent is a python class named `TransmonPocket`) from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket # Create a new qcomponent object q1 = TransmonPocket(design) gui.rebuild() # rebuild the design and plot # Delete all QComponents in our design, which in this case is just the transmon pocket "Pocket_1" design.delete_all_components() gui.rebuild() # rebuild the design and plot # Create a new qcomponent object with name 'Q1' q1 = TransmonPocket(design, 'Q1') gui.rebuild() # rebuild the design and plot q1 TransmonPocket.get_template_options(design) # Change options q1.options.pos_x = '2.0 mm' q1.options.pos_y = '2.0 mm' q1.options.pad_height = '250 um' q1.options.pad_width = '300 um' # Update the geoemtry and render to the gui, since we changed the options gui.rebuild() # Copy q1 and place the new Qcomponent ("q1_copy") at (-2,2): q1_copy = design.copy_qcomponent(q1, 'Q1_copy') q1_copy.options['pos_x']='-2.0mm' gui.rebuild() gui.autoscale() # Let's copy the two QComponents and change the y-coordinates of the copies to both be -2: newcopies = design.copy_multiple_qcomponents([q1, q1_copy], ['Q3', 'Q4'], [dict(pos_y='-2.0mm'), dict(pos_y='-2.0mm')]) gui.rebuild() gui.autoscale() design.delete_component('Q1') gui.rebuild() gui.autoscale() design._delete_component(3) gui.rebuild() gui.autoscale() design.rename_component(4,'Q_three') # rename "Q3" to "Q_three" design.rename_component(5,'Q_four') # rename "Q4" to "Q_four" design.overwrite_enabled = True gui.main_window.close()
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
%load_ext autoreload %autoreload 2 import qiskit_metal as metal from qiskit_metal import designs, MetalGUI from qiskit_metal import Dict, Headings design = designs.DesignPlanar() gui = MetalGUI(design) from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket from qiskit_metal.qlibrary.tlines.meandered import RouteMeander design.overwrite_enabled = True # We can vary how big we want the grid to be by changing N_x/N_y (number of qubits along the x/y axis). Be careful as very large arrays can take a fair bit of time to generate. We modify the chip size so it contains all of the qubits. N_x =20 N_y =20 design.chips.main.size.size_x = str((N_x+1) * 3)+'mm' design.chips.main.size.size_y = str((N_y+1) * 3)+'mm' design.chips.main.size.center_x = str((N_x-1) * 1.5)+'mm' design.chips.main.size.center_y = str((N_y-0.5) * 1.5)+'mm' # First we generate the qubits. We use some simple math to generate the offset pattern in order to make the bus resonators easier to connect. #Loop to generate and draw the qubits for x in range(N_x): for y in range(N_y): options = dict(pos_x= str(x*3000)+'um', pos_y = str(y*3000 + (x%2)*1500)+'um', orientation = "-90", connection_pads = dict( B0 = dict(loc_W=-1, loc_H=-1, pad_width='75um'), B1 = dict(loc_W=-1, loc_H=+1, pad_width='120um'), B2 = dict(loc_W=+1, loc_H=-1, pad_width='120um'), B3 = dict(loc_w = +1, loc_H = +1, pad_width='90um'))) obj=TransmonPocket(design,'Q_'+str(x)+'_'+str(y),options) gui.rebuild() gui.autoscale() # Next, we generate the route meanders. As we used consistent naming schemes for the qubits and pins, we can loop through them with out issue. We also have the length vary based on which qubit is being connected, such that no qubit should be connected to two resonators of the same frequency. for x in range(N_x): for y in range(N_y): #"upward" connection, avoids drawing connectors for 'top' row. Changes connector length by +/-50um to avoid frequency collisions if y<(N_y-1): connectorAD = RouteMeander(design,'CU_'+str(x)+'_'+str(y),options = dict(total_length = str(7+(y%2)*0.5)+'mm', fillet = "99um",lead=dict( start_straight='0.5mm', end_straight='0.25mm'), meander = dict(asymmetry='-700um'), pin_inputs = dict( start_pin=dict( component ='Q_'+str(x)+'_'+str(y), pin = 'B0'), end_pin=dict( component='Q_'+str(x)+'_'+str(y+1), pin='B3')))) #"sideways" connection, avoids drawing for far right col, and for top qubit in odd col. Changes connector length by +/- 25um #to avoid frequency collisions if x<(N_x-1) and (not(x%2 and y==(N_y-1))): connectorBC = RouteMeander(design,'CS_'+str(x)+'_'+str(y),options= dict(total_length = str(6+(y%2)*0.5)+'mm', fillet = "99um",lead=Dict( start_straight='0.3mm', end_straight='0.25mm'), meander = Dict(asymmetry='-200um'), pin_inputs = Dict( start_pin=Dict( component ='Q_'+str(x)+'_'+str(y), pin = 'B1'), end_pin=Dict( component='Q_'+str(x+1)+'_'+str(y+(x%2)), pin='B2')))) gui.rebuild() gui.autoscale() gui.screenshot() #QDesign registers GDS renderer during init of QDesign. a_gds = design.renderers.gds # An alternate way to invoke gds commands without using a_gds: # design.renderers.gds.export_to_gds() #Show the options for GDS a_gds.options a_gds.options.no_cheese # To add negative dots or 'cheese', simply enter the alternative code below. # a_gds.options.cheese a_gds.options['no_cheese']['view_in_file']['main'][1] = True # For the 'cheese' option, where there is a presence of negative dots simply use this code instead. # a_gds.options['cheese']['view_in_file']['main'][1] = True gui.rebuild() # Get a list of all the qcomponents in QDesign and then zoom on them. all_component_names = design.components.keys() gui.zoom_on_components(all_component_names) # Prepare to export GDS file with negative e-beam or direct-write masks for layer 1. # If there are 2 or more layers, simply add a comma and specify the layer numbers. a_gds.options['negative_mask'] = Dict(main=[1]) # Export GDS files with positive mask for layer 1. # a_gds.options['positive_mask'] = Dict(main=[1])
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
OJB-Quantum
import numpy as np import qiskit_metal as metal from qiskit_metal import designs, draw, MetalGUI, Dict, open_docs #design.overwrite_enabled = True #design.chips.main #design.chips.main.size.size_x = '11mm' #design.chips.main.size.size_y = '9mm' # To launch the qiskit metal GUI,use the method MetalGUI. design = designs.DesignPlanar() gui = MetalGUI(design) gui.screenshot() %metal_heading Connecting QPins with coplanar waveguides (CPWs) from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket # Allow running the same cell here multiple times to overwrite changes design.overwrite_enabled = True ## Custom options for all the transmons options = dict( # Some options we want to modify from the deafults # (see below for defaults) pad_width = '425 um', pocket_height = '650um', # Adding 4 connectors (see below for defaults) connection_pads=dict( a = dict(loc_W=+1,loc_H=+1), b = dict(loc_W=-1,loc_H=+1, pad_height='30um'), c = dict(loc_W=+1,loc_H=-1, pad_width='200um'), d = dict(loc_W=-1,loc_H=-1, pad_height='50um') ) ) ## Create 4 transmons q1 = TransmonPocket(design, 'Q1', options = dict( pos_x='+2.55mm', pos_y='+0.0mm', **options)) q2 = TransmonPocket(design, 'Q2', options = dict( pos_x='+0.0mm', pos_y='-0.9mm', orientation = '90', **options)) q3 = TransmonPocket(design, 'Q3', options = dict( pos_x='-2.55mm', pos_y='+0.0mm', **options)) q4 = TransmonPocket(design, 'Q4', options = dict( pos_x='+0.0mm', pos_y='+0.9mm', orientation = '90', **options)) ## Rebuild the design gui.rebuild() gui.autoscale() gui.toggle_docks(True) gui.screenshot() # Import the basic cpw QComponent from the QLibrary. It is a class called RouteMeander. We can see its default options using RouteMeander.get_template_options(design) from qiskit_metal.qlibrary.tlines.meandered import RouteMeander RouteMeander.get_template_options(design) options = Dict( meander=Dict( lead_start='0.1mm', lead_end='0.1mm', asymmetry='0 um') ) def connect(component_name: str, component1: str, pin1: str, component2: str, pin2: str, length: str, asymmetry='0 um', flip=False): """Connect two pins with a CPW.""" myoptions = Dict( pin_inputs=Dict( start_pin=Dict( component=component1, pin=pin1), end_pin=Dict( component=component2, pin=pin2)), lead=Dict( start_straight='0.13mm' ), total_length=length, fillet = '90um') myoptions.update(options) myoptions.meander.asymmetry = asymmetry myoptions.meander.lead_direction_inverted = 'true' if flip else 'false' return RouteMeander(design, component_name, myoptions) asym = 150 cpw1 = connect('cpw1', 'Q1', 'd', 'Q2', 'c', '6.0 mm', f'+{asym}um') cpw2 = connect('cpw2', 'Q3', 'c', 'Q2', 'a', '6.1 mm', f'-{asym}um', flip=True) cpw3 = connect('cpw3', 'Q3', 'a', 'Q4', 'b', '6.0 mm', f'+{asym}um') cpw4 = connect('cpw4', 'Q1', 'b', 'Q4', 'd', '6.1 mm', f'-{asym}um', flip=True) gui.rebuild() gui.autoscale() gui.toggle_docks(True) gui.highlight_components(['Q1','Q2','Q3','Q4','cpw1','cpw2','cpw3','cpw4']) gui.screenshot() design.components.keys() # We can access the created CPW from the design too. design.components.cpw2 # The design can have variables, which can be used in the component options. design.variables.cpw_width = '10um' design.variables.cpw_gap = '6um' gui.rebuild() # Ex: we can all qubit pads using the variables. cpw1.options.lead.end_straight = '100um' cpw2.options.lead.end_straight = '100um' cpw3.options.lead.end_straight = '100um' cpw4.options.lead.end_straight = '100um' # Set variables in the design design.variables.pad_width = '450 um' design.variables.cpw_width = '25 um' design.variables.cpw_gap = '12 um' # Assign variables to component options q1.options.pad_width = 'pad_width' q2.options.pad_width = 'pad_width' q3.options.pad_width = 'pad_width' q4.options.pad_width = 'pad_width' # Rebuild all compoinent and refresh the gui gui.rebuild() gui.autoscale() gui.screenshot() %metal_heading Render to GDS gds = design.renderers.gds gds.options.path_filename gds.options.path_filename = '../resources/Fake_Junctions.GDS' q1.options gds.options.path_filename = "../resources/Fake_Junctions.GDS" # Not sure what's going on here, however the GDS file is downloadable from the Qiskit Metal GUI. design.renderers.gds.export_to_gds("4-Transmon_design.gds") # Basic and crazy shapes. # See their source code to see how to get started on a few simple examples. from qiskit_metal.qlibrary.sample_shapes.n_square_spiral import NSquareSpiral # print(NSquareSpiral.get_template_options(design)) ops = { 'n': '10', 'width': '5um', 'radius': '100um', 'gap': '22um', 'pos_x': '0.65mm', 'pos_y': '2.2mm', 'orientation': '0', 'subtract': 'False'} NSquareSpiral(design, 'spiral', ops) NSquareSpiral(design, 'spiral_cut', {**ops, **dict(subtract=True, width='22um', gap='10um')}) gui.rebuild() # To see source, try ??NSquareSpiral. Go to the actual source file and edit it, copy it, or edit it in the GUI using the Edit Source button. from qiskit_metal.qlibrary.tlines.straight_path import RouteStraight # CpwStraightLine.get_template_options(design) myoptions = Dict( pin_inputs=Dict( start_pin=Dict( component='Q4', pin='c'), end_pin=Dict( component='spiral', pin='spiralPin')) ) RouteStraight(design, 'cpw_s1', myoptions); gui.rebuild() qcomponents = ['spiral', 'cpw_s1'] gui.highlight_components(qcomponents) gui.zoom_on_components(qcomponents) gui.screenshot() # N-Gon version. Orientation is in degrees. from qiskit_metal.qlibrary.sample_shapes.n_gon import NGon # display(NGon.get_template_options(design)) ops = { 'n': '6', 'radius': '250um', 'pos_x': '-0.85mm', 'pos_y': '2.0mm', 'orientation': '0', 'subtract': 'False', 'helper': 'False', 'chip': 'main', 'layer': '1'} NGon(design, 'ngon', ops) NGon(design, 'ngon_negative', {**ops, **dict(subtract=True, radius='350um')}) gui.rebuild() gui.zoom_on_components(['ngon_negative']) gui.screenshot() # Generate a circle with certain radius. from qiskit_metal.qlibrary.sample_shapes.circle_raster import CircleRaster display(CircleRaster.get_template_options(design)) ops = { 'radius': '10um', 'pos_x': '-1.5mm', 'pos_y': '2mm', 'resolution': '16', 'cap_style': 'round', 'subtract': 'False', 'helper': 'False', 'chip': 'main', 'layer': '1'} CircleRaster(design, 'CircleRaster', ops) gui.rebuild() gui.zoom_on_components(['CircleRaster']) gui.screenshot() # Generate a hollow rectangle. Orientation is in degrees. from qiskit_metal.qlibrary.sample_shapes.rectangle_hollow import RectangleHollow display(RectangleHollow.get_template_options(design)) ops = { 'width': '500um', 'height': '300um', 'pos_x': '-2.3mm', 'pos_y': '2mm', 'orientation': '0', 'subtract': 'False', 'helper': 'False', 'chip': 'main', 'layer': '1', 'inner': { 'width': '250um', 'height': '100um', 'offset_x': '40um', 'offset_y': '-20um', 'orientation': '15'}} RectangleHollow(design, 'RectangleHollow', ops) gui.rebuild() gui.zoom_on_components(['RectangleHollow']) gui.screenshot() gui.autoscale() gui.screenshot() # Return the boundry box of the geometry, for example: q1.qgeometry_bounds(). # The function returns a tuple containing (minx, miny, maxx, maxy) bound values for the bounds of the component as a whole. for name, qcomponent in design.components.items(): print(f"{name:10s} : {qcomponent.qgeometry_bounds()}") # We can get all the QGeometry of a QComponent. There are several kinds, such as path and poly. Let us look at all the polygons used to create qubit q1. q1.qgeometry_table('poly') q1.qgeometry_table('path') q1.qgeometry_table('junction') # Use this code to close the Qiskit Metal GUI. gui.main_window.close()
https://github.com/lynnlangit/learning-quantum
lynnlangit
# This cell is added by sphinx-gallery # It can be customized to whatever you like %matplotlib inline import pennylane as qml from pennylane import numpy as np dev1 = qml.device("default.qubit", wires=1) def circuit(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(dev1) def circuit(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=0) return qml.expval(qml.PauliZ(0)) print(circuit([0.54, 0.12])) dcircuit = qml.grad(circuit, argnum=0) print(dcircuit([0.54, 0.12])) @qml.qnode(dev1) def circuit2(phi1, phi2): qml.RX(phi1, wires=0) qml.RY(phi2, wires=0) return qml.expval(qml.PauliZ(0)) dcircuit = qml.grad(circuit2, argnum=[0, 1]) print(dcircuit(0.54, 0.12)) def cost(x): return circuit(x) init_params = np.array([0.011, 0.012]) print(cost(init_params)) # initialise the optimizer opt = qml.GradientDescentOptimizer(stepsize=0.4) # set the number of steps steps = 100 # set the initial parameter values params = init_params for i in range(steps): # update the circuit parameters params = opt.step(cost, params) if (i + 1) % 5 == 0: print("Cost after step {:5d}: {: .7f}".format(i + 1, cost(params))) print("Optimized rotation angles: {}".format(params))
https://github.com/lynnlangit/learning-quantum
lynnlangit
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import cirq import cirq_google # Using named qubits can be useful for abstract algorithms # as well as algorithms not yet mapped onto hardware. q0 = cirq.NamedQubit('source') q1 = cirq.NamedQubit('target') # Line qubits can be created individually q3 = cirq.LineQubit(3) # Or created in a range # This will create LineQubit(0), LineQubit(1), LineQubit(2) q0, q1, q2 = cirq.LineQubit.range(3) # Grid Qubits can also be referenced individually q4_5 = cirq.GridQubit(4,5) # Or created in bulk in a square # This will create 16 qubits from (0,0) to (3,3) qubits = cirq.GridQubit.square(4) print(cirq_google.Foxtail) # Example gates not_gate = cirq.CNOT pauli_z = cirq.Z # Using exponentiation to get square root gates sqrt_x_gate = cirq.X**0.5 # Some gates can also take parameters sqrt_sqrt_y = cirq.YPowGate(exponent=0.25) # Example operations q0, q1 = cirq.LineQubit.range(2) z_op = cirq.Z(q0) not_op = cirq.CNOT(q0, q1) sqrt_iswap_op = cirq.SQRT_ISWAP(q0, q1) circuit = cirq.Circuit() # You can create a circuit by appending to it circuit.append(cirq.H(q) for q in cirq.LineQubit.range(3)) # All of the gates are put into the same Moment since none overlap print(circuit) # We can also create a circuit directly as well: print(cirq.Circuit(cirq.SWAP(q, q+1) for q in cirq.LineQubit.range(3))) # Creates each gate in a separate moment. print(cirq.Circuit(cirq.Moment([cirq.H(q)]) for q in cirq.LineQubit.range(3))) q0 = cirq.GridQubit(0, 0) q1 = cirq.GridQubit(0, 1) q2 = cirq.GridQubit(0, 2) adjacent_op = cirq.CZ(q0, q1) nonadjacent_op = cirq.CZ(q0, q2) # This is an unconstrained circuit with no device free_circuit = cirq.Circuit() # Both operations are allowed: free_circuit.append(adjacent_op) free_circuit.append(nonadjacent_op) print('Unconstrained device:') print(free_circuit) print() # This is a circuit on the Foxtail device # only adjacent operations are allowed. print('Foxtail device:') foxtail_circuit = cirq.Circuit(device=cirq_google.Foxtail) foxtail_circuit.append(adjacent_op) try: # Not allowed, will throw exception foxtail_circuit.append(nonadjacent_op) except ValueError as e: print('Not allowed. %s' % e) # Create a circuit to generate a Bell State: # 1/sqrt(2) * ( |00⟩ + |11⟩ ) bell_circuit = cirq.Circuit() q0, q1 = cirq.LineQubit.range(2) bell_circuit.append(cirq.H(q0)) bell_circuit.append(cirq.CNOT(q0,q1)) # Initialize Simulator s=cirq.Simulator() print('Simulate the circuit:') results=s.simulate(bell_circuit) print(results) print() # For sampling, we need to add a measurement at the end bell_circuit.append(cirq.measure(q0, q1, key='result')) print('Sample the circuit:') samples=s.run(bell_circuit, repetitions=1000) # Print a histogram of results print(samples.histogram(key='result')) import matplotlib.pyplot as plt import sympy # Perform an X gate with variable exponent q = cirq.GridQubit(1,1) circuit = cirq.Circuit(cirq.X(q) ** sympy.Symbol('t'), cirq.measure(q, key='m')) # Sweep exponent from zero (off) to one (on) and back to two (off) param_sweep = cirq.Linspace('t', start=0, stop=2, length=200) # Simulate the sweep s = cirq.Simulator() trials = s.run_sweep(circuit, param_sweep, repetitions=1000) # Plot all the results x_data = [trial.params['t'] for trial in trials] y_data = [trial.histogram(key='m')[1] / 1000.0 for trial in trials] plt.scatter('t','p', data={'t': x_data, 'p': y_data}) print('Unitary of the X gate') print(cirq.unitary(cirq.X)) print('Unitary of SWAP operator on two qubits.') q0, q1 = cirq.LineQubit.range(2) print(cirq.unitary(cirq.SWAP(q0, q1))) print('Unitary of a sample circuit') print(cirq.unitary(cirq.Circuit(cirq.X(q0), cirq.SWAP(q0, q1)))) print(cirq.decompose(cirq.H(cirq.LineQubit(0)))) q0, q1, q2 = cirq.LineQubit.range(3) print(cirq.Circuit(cirq.decompose(cirq.TOFFOLI(q0, q1, q2)))) swap = cirq.SWAP(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)) print(cirq.Circuit(swap, device=cirq_google.Foxtail)) q=cirq.GridQubit(1, 1) optimizer=cirq.MergeSingleQubitGates() c=cirq.Circuit(cirq.X(q) ** 0.25, cirq.Y(q) ** 0.25, cirq.Z(q) ** 0.25) print(c) optimizer.optimize_circuit(c) print(c)
https://github.com/lynnlangit/learning-quantum
lynnlangit
try: import cirq except ImportError: print("installing cirq...") %pip install --quiet cirq print("installed cirq.") import cirq # One Qubit q = cirq.NamedQubit("a") # Create a Circuit A and NOT the qubit, then measure circuit = cirq.Circuit(cirq.X(q), cirq.measure(q, key='measured value') ) print("Circuit A:") print(circuit) print() # Simulate the circuit 10 times simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=10) print("Results of Circuit A:") print(result) # Two Qubits q0,q1 = cirq.LineQubit.range(2) # Create a Circuit B and NOT the qubit, use a controlled-X gate on the qubits, then measure ops = cirq.X(q0), cirq.CNOT(q0,q1),cirq.measure(q0, key='m'),cirq.measure(q1, key='n') circuit1 = cirq.Circuit(ops ) print("Circuit B:") print(circuit1) print() simulator = cirq.Simulator() result = simulator.run(circuit1, repetitions=10) print("Results of Circuit B:") print(result) qubit = cirq.NamedQubit("a") # Create a circuit which puts a qubit into superposition using H, then measure circuit = cirq.Circuit(cirq.H(qubit), cirq.measure(qubit, key='m') ) print("Circuit C:") print(circuit) # Simulate the circuit 10 times simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=10) print("Results:") print(result) import matplotlib.pyplot as plt qubit = cirq.NamedQubit("a") # Create a circuit which puts a qubit into superposition using H, then measure ops = [cirq.H(qubit), cirq.measure(qubit, key='m')] circuit = cirq.Circuit(ops) print("Circuit C:") print(circuit) # Simulate the circuit 100 times, plot results result = cirq.Simulator().run(circuit, repetitions=100) _ = cirq.vis.plot_state_histogram(result, plt.subplot()) a = cirq.NamedQubit("a") b = cirq.NamedQubit("b") c = cirq.NamedQubit("c") # Create a circuit which puts qubits into superposition using H, # Then entangle two qubits, then measure ops = [cirq.H(a), cirq.H(b), cirq.CNOT(b,c), cirq.H(b),cirq.measure(b)] circuit = cirq.Circuit(ops) print("Circuit D:\n") print(circuit) # Simulate the circuit 100 times, plot results result = cirq.Simulator().run(circuit, repetitions=100) _ = cirq.vis.plot_state_histogram(result, plt.subplot())
https://github.com/lynnlangit/learning-quantum
lynnlangit
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import cirq qubit = cirq.NamedQubit("myqubit") # creates an equal superposition of |0> and |1> when simulated circuit = cirq.Circuit(cirq.H(qubit)) # see the "myqubit" identifier at the left of the circuit print(circuit) # run simulation result = cirq.Simulator().simulate(circuit) print("result:") print(result) ## Programming Quantum Computers ## by Eric Johnston, Nic Harrigan and Mercedes Gimeno-Segovia ## O'Reilly Media ## ## More samples like this can be found at http://oreilly-qc.github.io import cirq ## This sample generates a single random bit. ## Example 2-1: Random bit # Set up the program def main(): qc = QPU() qc.reset(1) qc.had() # put it into a superposition of 0 and 1 qc.read() # read the result as a digital bit qc.draw() # draw the circuit result = qc.run() # run the circuit print(result) ###################################################################### ## The below class is a light interface, to convert the ## book's syntax into the syntax used by Cirq. class QPU: def __init__(self): self.circuit = cirq.Circuit() self.simulator = cirq.Simulator() self.qubits = None def reset(self, num_qubits): self.qubits = [cirq.GridQubit(i, 0) for i in range(num_qubits)] def mask_to_list(self, mask): return [q for i,q in enumerate(self.qubits) if (1 << i) & mask] def had(self, target_mask=~0): target = self.mask_to_list(target_mask) self.circuit.append(cirq.H.on_each(*target)) def read(self, target_mask=~0, key=None): if key is None: key = 'result' target = self.mask_to_list(target_mask) self.circuit.append(cirq.measure(*target, key=key)) def draw(self): print('Circuit:\n{}'.format(self.circuit)) def run(self): return self.simulator.simulate(self.circuit) if __name__ == '__main__': main()
https://github.com/lynnlangit/learning-quantum
lynnlangit
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/lynnlangit/learning-quantum
lynnlangit
try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import fractions import math import random import matplotlib.pyplot as plt import numpy as np import sympy from typing import Callable, List, Optional, Sequence, Union import cirq #import cirq_google print(cirq.google.Foxtail) # verify cirq, should print a circuit as shown belown # (0, 0)───(0, 1)───(0, 2)───(0, 3)───(0, 4)───(0, 5)───(0, 6)───(0, 7)───(0, 8)───(0, 9)───(0, 10) # │ │ │ │ │ │ │ │ │ │ │ # │ │ │ │ │ │ │ │ │ │ │ # (1, 0)───(1, 1)───(1, 2)───(1, 3)───(1, 4)───(1, 5)───(1, 6)───(1, 7)───(1, 8)───(1, 9)───(1, 10) def classical_order_finder(x: int, n: int) -> Optional[int]: # Make sure x is both valid and in Z_n. if x < 2 or x >= n or math.gcd(x, n) > 1: raise ValueError(f"Invalid x={x} for modulus n={n}.") # Determine the order. r, y = 1, x while y != 1: y = (x * y) % n r += 1 return r n = 15 # The multiplicative group is [1, 2, 4, 7, 8, 11, 13, 14]. x = 8 r = classical_order_finder(x, n) # Check that the order is indeed correct. print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}") class ModularExp(cirq.ArithmeticOperation): def __init__( self, target: Sequence[cirq.Qid], exponent: Union[int, Sequence[cirq.Qid]], base: int, modulus: int ) -> None: if len(target) < modulus.bit_length(): raise ValueError(f'Register with {len(target)} qubits is too small ' f'for modulus {modulus}') self.target = target self.exponent = exponent self.base = base self.modulus = modulus def registers(self) -> Sequence[Union[int, Sequence[cirq.Qid]]]: return self.target, self.exponent, self.base, self.modulus def with_registers( self, *new_registers: Union[int, Sequence['cirq.Qid']], ) -> cirq.ArithmeticOperation: if len(new_registers) != 4: raise ValueError(f'Expected 4 registers (target, exponent, base, ' f'modulus), but got {len(new_registers)}') target, exponent, base, modulus = new_registers if not isinstance(target, Sequence): raise ValueError( f'Target must be a qubit register, got {type(target)}') if not isinstance(base, int): raise ValueError( f'Base must be a classical constant, got {type(base)}') if not isinstance(modulus, int): raise ValueError( f'Modulus must be a classical constant, got {type(modulus)}') return ModularExp(target, exponent, base, modulus) def apply(self, *register_values: int) -> int: assert len(register_values) == 4 target, exponent, base, modulus = register_values if target >= modulus: return target return (target * base**exponent) % modulus def _circuit_diagram_info_( self, args: cirq.CircuitDiagramInfoArgs, ) -> cirq.CircuitDiagramInfo: assert args.known_qubits is not None wire_symbols: List[str] = [] t, e = 0, 0 for qubit in args.known_qubits: if qubit in self.target: if t == 0: if isinstance(self.exponent, Sequence): e_str = 'e' else: e_str = str(self.exponent) wire_symbols.append( f'ModularExp(t*{self.base}**{e_str} % {self.modulus})') else: wire_symbols.append('t' + str(t)) t += 1 if isinstance(self.exponent, Sequence) and qubit in self.exponent: wire_symbols.append('e' + str(e)) e += 1 return cirq.CircuitDiagramInfo(wire_symbols=tuple(wire_symbols)) n = 15 L = n.bit_length() # The target register has L qubits. target = cirq.LineQubit.range(L) # The exponent register has 2L + 3 qubits. exponent = cirq.LineQubit.range(L, 3 * L + 3) # Display the total number of qubits to factor this n. print(f"To factor n = {n} which has L = {L} bits, we need 3L + 3 = {3 * L + 3} qubits.") def make_order_finding_circuit(x: int, n: int) -> cirq.Circuit: L = n.bit_length() target = cirq.LineQubit.range(L) exponent = cirq.LineQubit.range(L, 3 * L + 3) return cirq.Circuit( cirq.X(target[L - 1]), cirq.H.on_each(*exponent), ModularExp(target, exponent, x, n), cirq.qft(*exponent, inverse=True), cirq.measure(*exponent, key='exponent'), ) n = 15 x = 7 circuit = make_order_finding_circuit(x, n) print(circuit) circuit = make_order_finding_circuit(x=5, n=6) res = cirq.sample(circuit, repetitions=8) print("Raw measurements:") print(res) print("\nInteger in exponent register:") print(res.data) def binary_labels(num_qubits): return [bin(x)[2:].zfill(num_qubits) for x in range(2 ** num_qubits)] # Refactor this plot to use this cell's output # q = cirq.LineQubit.range(3) # circuit = cirq.Circuit([cirq.H.on_each(*q), cirq.measure(*q)]) # result = cirq.Simulator().run(circuit, repetitions=100) # _ = cirq.vis.plot_state_histogram(result, plt.subplot(), title = 'Integer in exponent Register', xlabel = 'Integer', ylabel = 'Count', tick_label=binary_labels(3)) def process_measurement(result: cirq.Result, x: int, n: int) -> Optional[int]: # Read the output integer of the exponent register. exponent_as_integer = result.data["exponent"][0] exponent_num_bits = result.measurements["exponent"].shape[1] eigenphase = float(exponent_as_integer / 2**exponent_num_bits) # Run the continued fractions algorithm to determine f = s / r. f = fractions.Fraction.from_float(eigenphase).limit_denominator(n) if f.numerator == 0: return None r = f.denominator if x**r % n != 1: return None return r n = 6 x = 5 print(f"Finding the order of x = {x} modulo n = {n}\n") measurement = cirq.sample(circuit, repetitions=1) print("Raw measurements:") print(measurement) print("\nInteger in exponent register:") print(measurement.data) r = process_measurement(measurement, x, n) print("\nOrder r =", r) if r is not None: print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}") def quantum_order_finder(x: int, n: int) -> Optional[int]: if x < 2 or n <= x or math.gcd(x, n) > 1: raise ValueError(f'Invalid x={x} for modulus n={n}.') circuit = make_order_finding_circuit(x, n) measurement = cirq.sample(circuit) return process_measurement(measurement, x, n) def find_factor_of_prime_power(n: int) -> Optional[int]: for k in range(2, math.floor(math.log2(n)) + 1): c = math.pow(n, 1 / k) c1 = math.floor(c) if c1**k == n: return c1 c2 = math.ceil(c) if c2**k == n: return c2 return None def find_factor( n: int, order_finder: Callable[[int, int], Optional[int]] = quantum_order_finder, max_attempts: int = 30 ) -> Optional[int]: if sympy.isprime(n): print("n is prime!") return None if n % 2 == 0: return 2 c = find_factor_of_prime_power(n) if c is not None: return c for _ in range(max_attempts): x = random.randint(2, n - 1) c = math.gcd(x, n) if 1 < c < n: return c r = order_finder(x, n) if r is None: continue if r % 2 != 0: continue y = x**(r // 2) % n assert 1 < y < n c = math.gcd(y - 1, n) if 1 < c < n: return c print(f"Failed to find a non-trivial factor in {max_attempts} attempts.") # return None # test with non-prime numbers only n = 184572 p = find_factor(n, order_finder=classical_order_finder) q = n // p p * q == n print("If p * q == n is True, then this answer is correct.") print("The result of " + str(p) + " * " + str(q) + " = "+ str(n) + " is " + str(p * q == n)) # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
https://github.com/lynnlangit/learning-quantum
lynnlangit
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: import cirq except ImportError: print("installing cirq...") !pip install cirq --quiet print("installed cirq.") import cirq import random import matplotlib.pyplot as plt import numpy as np def make_quantum_teleportation_circuit(gate): """Returns a circuit for quantum teleportation. This circuit 'teleports' a random qubit state prepared by the input gate from Alice to Bob. """ circuit = cirq.Circuit() # Get the three qubits involved in the teleportation protocol. msg = cirq.NamedQubit("Message") alice = cirq.NamedQubit("Alice") bob = cirq.NamedQubit("Bob") # The input gate prepares the message to send. circuit.append(gate(msg)) # Create a Bell state shared between Alice and Bob. circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)]) # Bell measurement of the Message and Alice's entangled qubit. circuit.append([cirq.CNOT(msg, alice), cirq.H(msg), cirq.measure(msg, alice)]) # Uses the two classical bits from the Bell measurement to recover the # original quantum message on Bob's entangled qubit. circuit.append([cirq.CNOT(alice, bob), cirq.CZ(msg, bob)]) return circuit """Visualize the teleportation circuit.""" # Gate to put the message qubit in some state to send. gate = cirq.X ** 0.25 # Create the teleportation circuit. circuit = make_quantum_teleportation_circuit(gate) print("Teleportation circuit:\n") print(circuit) """Display the Bloch vector of the message qubit.""" message = cirq.Circuit(gate.on(cirq.NamedQubit("Message"))).final_state_vector() message_bloch_vector = cirq.bloch_vector_from_state_vector(message, index=0) print("Bloch vector of message qubit:") print(np.round(message_bloch_vector, 3)) """Simulate the teleportation circuit and get the final state of Bob's qubit.""" # Get a simulator. sim = cirq.Simulator() # Simulate the teleportation circuit. result = sim.simulate(circuit) # Get the Bloch vector of Bob's qubit. bobs_bloch_vector = cirq.bloch_vector_from_state_vector(result.final_state_vector, index=1) print("Bloch vector of Bob's qubit:") print(np.round(bobs_bloch_vector, 3)) # Verify they are the same state! np.testing.assert_allclose(bobs_bloch_vector, message_bloch_vector, atol=1e-7) def make_qft(qubits): """Generator for the QFT on a list of qubits. For four qubits, the answer is: ┌───────┐ ┌────────────┐ ┌───────┐ 0: ───H───@────────@───────────@─────────────────────────────────────── │ │ │ 1: ───────@^0.5────┼─────H─────┼──────@─────────@────────────────────── │ │ │ │ 2: ────────────────@^0.25──────┼──────@^0.5─────┼─────H────@─────────── │ │ │ 3: ────────────────────────────@^(1/8)──────────@^0.25─────@^0.5───H─── └───────┘ └────────────┘ └───────┘ """ # Your code here! def make_qft(qubits): """Generator for the QFT on a list of qubits.""" qreg = list(qubits) while len(qreg) > 0: q_head = qreg.pop(0) yield cirq.H(q_head) for i, qubit in enumerate(qreg): yield (cirq.CZ ** (1 / 2 ** (i + 1)))(qubit, q_head) """Visually check the QFT circuit.""" qubits = cirq.LineQubit.range(4) qft = cirq.Circuit(make_qft(qubits)) print(qft) """Use the built-in QFT in Cirq.""" qft_operation = cirq.qft(*qubits, without_reverse=True) qft_cirq = cirq.Circuit(qft_operation) print(qft_cirq) """Check equality of the 'manual' and 'built-in' QFTs.""" np.testing.assert_allclose(cirq.unitary(qft), cirq.unitary(qft_cirq)) def make_qft_inverse(qubits): """Generator for the inverse QFT on a list of qubits. For four qubits, the answer is: ┌────────┐ ┌──────────────┐ ┌────────┐ 0: ───H───@─────────@────────────@───────────────────────────────────────────×─── │ │ │ │ 1: ───────@^-0.5────┼──────H─────┼───────@──────────@────────────────────×───┼─── │ │ │ │ │ │ 2: ─────────────────@^-0.25──────┼───────@^-0.5─────┼──────H────@────────×───┼─── │ │ │ │ 3: ──────────────────────────────@^(-1/8)───────────@^-0.25─────@^-0.5───H───×─── └────────┘ └──────────────┘ └────────┘ """ # Your code here! def make_qft_inverse(qubits): """Generator for the inverse QFT on a list of qubits.""" qreg = list(qubits)[::-1] while len(qreg) > 0: q_head = qreg.pop(0) yield cirq.H(q_head) for i, qubit in enumerate(qreg): yield (cirq.CZ ** (-1 / 2 ** (i + 1)))(qubit, q_head) """Visually check the inverse QFT circuit.""" qubits = cirq.LineQubit.range(4) iqft = cirq.Circuit(make_qft_inverse(qubits)) print(iqft) """Use the built-in inverse QFT in Cirq.""" iqft_operation = cirq.qft(*qubits, inverse=True, without_reverse=True) iqft_cirq = cirq.Circuit(iqft_operation) print(iqft_cirq) """Check equality of the 'manual' and 'built-in' inverse QFTs.""" np.testing.assert_allclose(cirq.unitary(iqft), cirq.unitary(iqft_cirq)) """Set up the unitary and number of bits to use in phase estimation.""" # Value of θ which appears in the definition of the unitary U above. # Try different values. theta = 0.234 # Define the unitary U. U = cirq.Z ** (2 * theta) # Accuracy of the estimate for theta. Try different values. n_bits = 3 """Build the first part of the circuit for phase estimation.""" # Get qubits for the phase estimation circuit. qubits = cirq.LineQubit.range(n_bits) u_bit = cirq.NamedQubit('u') # Build the first part of the phase estimation circuit. phase_estimator = cirq.Circuit(cirq.H.on_each(*qubits)) for i, bit in enumerate(qubits): phase_estimator.append(cirq.ControlledGate(U).on(bit, u_bit) ** (2 ** (n_bits - i - 1))) print(phase_estimator) """Build the last part of the circuit (inverse QFT) for phase estimation.""" # Do the inverse QFT. phase_estimator.append(make_qft_inverse(qubits[::-1])) # Add measurements to the end of the circuit phase_estimator.append(cirq.measure(*qubits, key='m')) print(phase_estimator) """Set the input state of the eigenvalue register.""" # Add gate to change initial state to |1>. phase_estimator.insert(0, cirq.X(u_bit)) print(phase_estimator) """Simulate the circuit and convert from measured bit values to estimated θ values.""" # Simulate the circuit. sim = cirq.Simulator() result = sim.run(phase_estimator, repetitions=10) # Convert from output bitstrings to estimate θ values. theta_estimates = np.sum(2 ** np.arange(n_bits) * result.measurements['m'], axis=1) / 2**n_bits print(theta_estimates) def phase_estimation(theta, n_bits, n_reps=10, prepare_eigenstate_gate=cirq.X): """Runs the phase estimate algorithm for unitary U=Z^{2θ} with n_bits qubits.""" # Define qubit registers. qubits = cirq.LineQubit.range(n_bits) u_bit = cirq.NamedQubit('u') # Define the unitary U. U = cirq.Z ** (2 * theta) # Your code here! # ... # Gate to choose initial state for the u_bit. Placing X here chooses the |1> state. phase_estimator.insert(0, prepare_eigenstate_gate.on(u_bit)) # You code here! # theta_estimates = ... return theta_estimates def phase_estimation(theta, n_bits, n_reps=10, prepare_eigenstate_gate=cirq.X): # Define qubit registers. qubits = cirq.LineQubit.range(n_bits) u_bit = cirq.NamedQubit('u') # Define the unitary U. U = cirq.Z ** (2 * theta) # Start with Hadamards on every qubit. phase_estimator = cirq.Circuit(cirq.H.on_each(*qubits)) # Do the controlled powers of the unitary U. for i, bit in enumerate(qubits): phase_estimator.append(cirq.ControlledGate(U).on(bit, u_bit) ** (2 ** (n_bits - 1 - i))) # Do the inverse QFT. phase_estimator.append(make_qft_inverse(qubits[::-1])) # Add measurements. phase_estimator.append(cirq.measure(*qubits, key='m')) # Gate to choose initial state for the u_bit. Placing X here chooses the |1> state. phase_estimator.insert(0, prepare_eigenstate_gate.on(u_bit)) # Code to simulate measurements sim = cirq.Simulator() result = sim.run(phase_estimator, repetitions=n_reps) # Convert measurements into estimates of theta theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits return theta_estimates """Analyze convergence vs n_bits.""" # Set the value of theta. Try different values. theta = 0.123456 max_nvals = 16 nvals = np.arange(1, max_nvals, step=1) # Get the estimates at each value of n. estimates = [] for n in nvals: estimate = phase_estimation(theta=theta, n_bits=n, n_reps=1)[0] estimates.append(estimate) """Plot the results.""" plt.style.use("seaborn-whitegrid") plt.plot(nvals, estimates, "--o", label="Phase estimation") plt.axhline(theta, label="True value", color="black") plt.legend() plt.xlabel("Number of bits") plt.ylabel(r"$\theta$"); """Run phase estimation without starting in an eigenstate.""" # Value of theta. theta = 0.123456 # Number of qubits. n = 4 # Run phase estimation starting in the state H|0⟩ = |+⟩. res = phase_estimation(theta=theta, n_bits=n, n_reps=10, prepare_eigenstate_gate=cirq.H) print(res) """Get qubits to use in the circuit for Grover's algorithm.""" # Number of qubits n. nqubits = 2 # Get qubit registers. qubits = cirq.LineQubit.range(nqubits) ancilla = cirq.NamedQubit("Ancilla") def make_oracle(qubits, ancilla, xprime): """Implements the function {f(x) = 1 if x == x', f(x) = 0 if x != x'}.""" # For x' = (1, 1), the oracle is just a Toffoli gate. # For a general x', we negate the zero bits and implement a Toffoli. # Negate zero bits, if necessary. yield (cirq.X(q) for (q, bit) in zip(qubits, xprime) if not bit) # Do the Toffoli. yield (cirq.TOFFOLI(qubits[0], qubits[1], ancilla)) # Negate zero bits, if necessary. yield (cirq.X(q) for (q, bit) in zip(qubits, xprime) if not bit) def grover_iteration(qubits, ancilla, oracle): """Performs one round of the Grover iteration.""" circuit = cirq.Circuit() # Create an equal superposition over input qubits. circuit.append(cirq.H.on_each(*qubits)) # Put the output qubit in the |-⟩ state. circuit.append([cirq.X(ancilla), cirq.H(ancilla)]) # Query the oracle. circuit.append(oracle) # Construct Grover operator. circuit.append(cirq.H.on_each(*qubits)) circuit.append(cirq.X.on_each(*qubits)) circuit.append(cirq.H.on(qubits[1])) circuit.append(cirq.CNOT(qubits[0], qubits[1])) circuit.append(cirq.H.on(qubits[1])) circuit.append(cirq.X.on_each(*qubits)) circuit.append(cirq.H.on_each(*qubits)) # Measure the input register. circuit.append(cirq.measure(*qubits, key="result")) return circuit """Select a 'marked' bitstring x' at random.""" xprime = [random.randint(0, 1) for _ in range(nqubits)] print(f"Marked bitstring: {xprime}") """Create the circuit for Grover's algorithm.""" # Make oracle (black box) oracle = make_oracle(qubits, ancilla, xprime) # Embed the oracle into a quantum circuit implementing Grover's algorithm. circuit = grover_iteration(qubits, ancilla, oracle) print("Circuit for Grover's algorithm:") print(circuit) """Simulate the circuit for Grover's algorithm and check the output.""" # Helper function. def bitstring(bits): return "".join(str(int(b)) for b in bits) # Sample from the circuit a couple times. simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=10) # Look at the sampled bitstrings. frequencies = result.histogram(key="result", fold_func=bitstring) print('Sampled results:\n{}'.format(frequencies)) # Check if we actually found the secret value. most_common_bitstring = frequencies.most_common(1)[0][0] print("\nMost common bitstring: {}".format(most_common_bitstring)) print("Found a match? {}".format(most_common_bitstring == bitstring(xprime)))
https://github.com/lynnlangit/learning-quantum
lynnlangit
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. !pip install tensorflow==2.4.1 !pip install tensorflow-quantum # Update package resources to account for version changes. import importlib, pkg_resources importlib.reload(pkg_resources) import tensorflow as tf import tensorflow_quantum as tfq import cirq import sympy import numpy as np # visualization tools %matplotlib inline import matplotlib.pyplot as plt from cirq.contrib.svg import SVGCircuit a, b = sympy.symbols('a b') # Create two qubits q0, q1 = cirq.GridQubit.rect(1, 2) # Create a circuit on these qubits using the parameters you created above. circuit = cirq.Circuit( cirq.rx(a).on(q0), cirq.ry(b).on(q1), cirq.CNOT(control=q0, target=q1)) SVGCircuit(circuit) # Calculate a state vector with a=0.5 and b=-0.5. resolver = cirq.ParamResolver({a: 0.5, b: -0.5}) output_state_vector = cirq.Simulator().simulate(circuit, resolver).final_state_vector output_state_vector z0 = cirq.Z(q0) qubit_map={q0: 0, q1: 1} z0.expectation_from_state_vector(output_state_vector, qubit_map).real z0x1 = 0.5 * z0 + cirq.X(q1) z0x1.expectation_from_state_vector(output_state_vector, qubit_map).real # Rank 1 tensor containing 1 circuit. circuit_tensor = tfq.convert_to_tensor([circuit]) print(circuit_tensor.shape) print(circuit_tensor.dtype) # Rank 1 tensor containing 2 Pauli operators. pauli_tensor = tfq.convert_to_tensor([z0, z0x1]) pauli_tensor.shape batch_vals = np.array(np.random.uniform(0, 2 * np.pi, (5, 2)), dtype=np.float32) cirq_results = [] cirq_simulator = cirq.Simulator() for vals in batch_vals: resolver = cirq.ParamResolver({a: vals[0], b: vals[1]}) final_state_vector = cirq_simulator.simulate(circuit, resolver).final_state_vector cirq_results.append( [z0.expectation_from_state_vector(final_state_vector, { q0: 0, q1: 1 }).real]) print('cirq batch results: \n {}'.format(np.array(cirq_results))) tfq.layers.Expectation()(circuit, symbol_names=[a, b], symbol_values=batch_vals, operators=z0) # Parameters that the classical NN will feed values into. control_params = sympy.symbols('theta_1 theta_2 theta_3') # Create the parameterized circuit. qubit = cirq.GridQubit(0, 0) model_circuit = cirq.Circuit( cirq.rz(control_params[0])(qubit), cirq.ry(control_params[1])(qubit), cirq.rx(control_params[2])(qubit)) SVGCircuit(model_circuit) # The classical neural network layers. controller = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='elu'), tf.keras.layers.Dense(3) ]) controller(tf.constant([[0.0],[1.0]])).numpy() # This input is the simulated miscalibration that the model will learn to correct. circuits_input = tf.keras.Input(shape=(), # The circuit-tensor has dtype `tf.string` dtype=tf.string, name='circuits_input') # Commands will be either `0` or `1`, specifying the state to set the qubit to. commands_input = tf.keras.Input(shape=(1,), dtype=tf.dtypes.float32, name='commands_input') dense_2 = controller(commands_input) # TFQ layer for classically controlled circuits. expectation_layer = tfq.layers.ControlledPQC(model_circuit, # Observe Z operators = cirq.Z(qubit)) expectation = expectation_layer([circuits_input, dense_2]) # The full Keras model is built from our layers. model = tf.keras.Model(inputs=[circuits_input, commands_input], outputs=expectation) tf.keras.utils.plot_model(model, show_shapes=True, dpi=70) # The command input values to the classical NN. commands = np.array([[0], [1]], dtype=np.float32) # The desired Z expectation value at output of quantum circuit. expected_outputs = np.array([[1], [-1]], dtype=np.float32) random_rotations = np.random.uniform(0, 2 * np.pi, 3) noisy_preparation = cirq.Circuit( cirq.rx(random_rotations[0])(qubit), cirq.ry(random_rotations[1])(qubit), cirq.rz(random_rotations[2])(qubit) ) datapoint_circuits = tfq.convert_to_tensor([ noisy_preparation ] * 2) # Make two copied of this circuit datapoint_circuits.shape model([datapoint_circuits, commands]).numpy() optimizer = tf.keras.optimizers.Adam(learning_rate=0.05) loss = tf.keras.losses.MeanSquaredError() model.compile(optimizer=optimizer, loss=loss) history = model.fit(x=[datapoint_circuits, commands], y=expected_outputs, epochs=30, verbose=0) plt.plot(history.history['loss']) plt.title("Learning to Control a Qubit") plt.xlabel("Iterations") plt.ylabel("Error in Control") plt.show() def check_error(command_values, desired_values): """Based on the value in `command_value` see how well you could prepare the full circuit to have `desired_value` when taking expectation w.r.t. Z.""" params_to_prepare_output = controller(command_values).numpy() full_circuit = noisy_preparation + model_circuit # Test how well you can prepare a state to get expectation the expectation # value in `desired_values` for index in [0, 1]: state = cirq_simulator.simulate( full_circuit, {s:v for (s,v) in zip(control_params, params_to_prepare_output[index])} ).final_state_vector expt = cirq.Z(qubit).expectation_from_state_vector(state, {qubit: 0}).real print(f'For a desired output (expectation) of {desired_values[index]} with' f' noisy preparation, the controller\nnetwork found the following ' f'values for theta: {params_to_prepare_output[index]}\nWhich gives an' f' actual expectation of: {expt}\n') check_error(commands, expected_outputs) model([datapoint_circuits, commands]) # Define inputs. commands_input = tf.keras.layers.Input(shape=(1), dtype=tf.dtypes.float32, name='commands_input') circuits_input = tf.keras.Input(shape=(), # The circuit-tensor has dtype `tf.string` dtype=tf.dtypes.string, name='circuits_input') operators_input = tf.keras.Input(shape=(1,), dtype=tf.dtypes.string, name='operators_input') # Define classical NN. controller = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='elu'), tf.keras.layers.Dense(3) ]) dense_2 = controller(commands_input) # Since you aren't using a PQC or ControlledPQC you must append # your model circuit onto the datapoint circuit tensor manually. full_circuit = tfq.layers.AddCircuit()(circuits_input, append=model_circuit) expectation_output = tfq.layers.Expectation()(full_circuit, symbol_names=control_params, symbol_values=dense_2, operators=operators_input) # Contruct your Keras model. two_axis_control_model = tf.keras.Model( inputs=[circuits_input, commands_input, operators_input], outputs=[expectation_output]) # The operators to measure, for each command. operator_data = tfq.convert_to_tensor([[cirq.X(qubit)], [cirq.Z(qubit)]]) # The command input values to the classical NN. commands = np.array([[0], [1]], dtype=np.float32) # The desired expectation value at output of quantum circuit. expected_outputs = np.array([[1], [-1]], dtype=np.float32) optimizer = tf.keras.optimizers.Adam(learning_rate=0.05) loss = tf.keras.losses.MeanSquaredError() two_axis_control_model.compile(optimizer=optimizer, loss=loss) history = two_axis_control_model.fit( x=[datapoint_circuits, commands, operator_data], y=expected_outputs, epochs=30, verbose=1) plt.plot(history.history['loss']) plt.title("Learning to Control a Qubit") plt.xlabel("Iterations") plt.ylabel("Error in Control") plt.show() controller.predict(np.array([0,1]))
https://github.com/lynnlangit/learning-quantum
lynnlangit
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. !pip install tensorflow==2.4.1 !pip install tensorflow-quantum # Update package resources to account for version changes. import importlib, pkg_resources importlib.reload(pkg_resources) import tensorflow as tf import tensorflow_quantum as tfq import cirq import sympy import numpy as np import seaborn as sns import collections # visualization tools %matplotlib inline import matplotlib.pyplot as plt from cirq.contrib.svg import SVGCircuit (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # Rescale the images from [0,255] to the [0.0,1.0] range. x_train, x_test = x_train[..., np.newaxis]/255.0, x_test[..., np.newaxis]/255.0 print("Number of original training examples:", len(x_train)) print("Number of original test examples:", len(x_test)) def filter_36(x, y): keep = (y == 3) | (y == 6) x, y = x[keep], y[keep] y = y == 3 return x,y x_train, y_train = filter_36(x_train, y_train) x_test, y_test = filter_36(x_test, y_test) print("Number of filtered training examples:", len(x_train)) print("Number of filtered test examples:", len(x_test)) print(y_train[0]) plt.imshow(x_train[0, :, :, 0]) plt.colorbar() x_train_small = tf.image.resize(x_train, (4,4)).numpy() x_test_small = tf.image.resize(x_test, (4,4)).numpy() print(y_train[0]) plt.imshow(x_train_small[0,:,:,0], vmin=0, vmax=1) plt.colorbar() def remove_contradicting(xs, ys): mapping = collections.defaultdict(set) orig_x = {} # Determine the set of labels for each unique image: for x,y in zip(xs,ys): orig_x[tuple(x.flatten())] = x mapping[tuple(x.flatten())].add(y) new_x = [] new_y = [] for flatten_x in mapping: x = orig_x[flatten_x] labels = mapping[flatten_x] if len(labels) == 1: new_x.append(x) new_y.append(next(iter(labels))) else: # Throw out images that match more than one label. pass num_uniq_3 = sum(1 for value in mapping.values() if len(value) == 1 and True in value) num_uniq_6 = sum(1 for value in mapping.values() if len(value) == 1 and False in value) num_uniq_both = sum(1 for value in mapping.values() if len(value) == 2) print("Number of unique images:", len(mapping.values())) print("Number of unique 3s: ", num_uniq_3) print("Number of unique 6s: ", num_uniq_6) print("Number of unique contradicting labels (both 3 and 6): ", num_uniq_both) print() print("Initial number of images: ", len(xs)) print("Remaining non-contradicting unique images: ", len(new_x)) return np.array(new_x), np.array(new_y) x_train_nocon, y_train_nocon = remove_contradicting(x_train_small, y_train) THRESHOLD = 0.5 x_train_bin = np.array(x_train_nocon > THRESHOLD, dtype=np.float32) x_test_bin = np.array(x_test_small > THRESHOLD, dtype=np.float32) _ = remove_contradicting(x_train_bin, y_train_nocon) def convert_to_circuit(image): """Encode truncated classical image into quantum datapoint.""" values = np.ndarray.flatten(image) qubits = cirq.GridQubit.rect(4, 4) circuit = cirq.Circuit() for i, value in enumerate(values): if value: circuit.append(cirq.X(qubits[i])) return circuit x_train_circ = [convert_to_circuit(x) for x in x_train_bin] x_test_circ = [convert_to_circuit(x) for x in x_test_bin] SVGCircuit(x_train_circ[0]) bin_img = x_train_bin[0,:,:,0] indices = np.array(np.where(bin_img)).T indices x_train_tfcirc = tfq.convert_to_tensor(x_train_circ) x_test_tfcirc = tfq.convert_to_tensor(x_test_circ) class CircuitLayerBuilder(): def __init__(self, data_qubits, readout): self.data_qubits = data_qubits self.readout = readout def add_layer(self, circuit, gate, prefix): for i, qubit in enumerate(self.data_qubits): symbol = sympy.Symbol(prefix + '-' + str(i)) circuit.append(gate(qubit, self.readout)**symbol) demo_builder = CircuitLayerBuilder(data_qubits = cirq.GridQubit.rect(4,1), readout=cirq.GridQubit(-1,-1)) circuit = cirq.Circuit() demo_builder.add_layer(circuit, gate = cirq.XX, prefix='xx') SVGCircuit(circuit) def create_quantum_model(): """Create a QNN model circuit and readout operation to go along with it.""" data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid. readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1] circuit = cirq.Circuit() # Prepare the readout qubit. circuit.append(cirq.X(readout)) circuit.append(cirq.H(readout)) builder = CircuitLayerBuilder( data_qubits = data_qubits, readout=readout) # Then add layers (experiment by adding more). builder.add_layer(circuit, cirq.XX, "xx1") builder.add_layer(circuit, cirq.ZZ, "zz1") # Finally, prepare the readout qubit. circuit.append(cirq.H(readout)) return circuit, cirq.Z(readout) model_circuit, model_readout = create_quantum_model() # Build the Keras model. model = tf.keras.Sequential([ # The input is the data-circuit, encoded as a tf.string tf.keras.layers.Input(shape=(), dtype=tf.string), # The PQC layer returns the expected value of the readout gate, range [-1,1]. tfq.layers.PQC(model_circuit, model_readout), ]) y_train_hinge = 2.0*y_train_nocon-1.0 y_test_hinge = 2.0*y_test-1.0 def hinge_accuracy(y_true, y_pred): y_true = tf.squeeze(y_true) > 0.0 y_pred = tf.squeeze(y_pred) > 0.0 result = tf.cast(y_true == y_pred, tf.float32) return tf.reduce_mean(result) model.compile( loss=tf.keras.losses.Hinge(), optimizer=tf.keras.optimizers.Adam(), metrics=[hinge_accuracy]) print(model.summary()) EPOCHS = 3 BATCH_SIZE = 32 NUM_EXAMPLES = len(x_train_tfcirc) x_train_tfcirc_sub = x_train_tfcirc[:NUM_EXAMPLES] y_train_hinge_sub = y_train_hinge[:NUM_EXAMPLES] qnn_history = model.fit( x_train_tfcirc_sub, y_train_hinge_sub, batch_size=32, epochs=EPOCHS, verbose=1, validation_data=(x_test_tfcirc, y_test_hinge)) qnn_results = model.evaluate(x_test_tfcirc, y_test) def create_classical_model(): # A simple model based off LeNet from https://keras.io/examples/mnist_cnn/ model = tf.keras.Sequential() model.add(tf.keras.layers.Conv2D(32, [3, 3], activation='relu', input_shape=(28,28,1))) model.add(tf.keras.layers.Conv2D(64, [3, 3], activation='relu')) model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(tf.keras.layers.Dropout(0.25)) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(128, activation='relu')) model.add(tf.keras.layers.Dropout(0.5)) model.add(tf.keras.layers.Dense(1)) return model model = create_classical_model() model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), optimizer=tf.keras.optimizers.Adam(), metrics=['accuracy']) model.summary() model.fit(x_train, y_train, batch_size=128, epochs=1, verbose=1, validation_data=(x_test, y_test)) cnn_results = model.evaluate(x_test, y_test) def create_fair_classical_model(): # A simple model based off LeNet from https://keras.io/examples/mnist_cnn/ model = tf.keras.Sequential() model.add(tf.keras.layers.Flatten(input_shape=(4,4,1))) model.add(tf.keras.layers.Dense(2, activation='relu')) model.add(tf.keras.layers.Dense(1)) return model model = create_fair_classical_model() model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), optimizer=tf.keras.optimizers.Adam(), metrics=['accuracy']) model.summary() model.fit(x_train_bin, y_train_nocon, batch_size=128, epochs=20, verbose=2, validation_data=(x_test_bin, y_test)) fair_nn_results = model.evaluate(x_test_bin, y_test) qnn_accuracy = qnn_results[1] cnn_accuracy = cnn_results[1] fair_nn_accuracy = fair_nn_results[1] sns.barplot(["Quantum", "Classical, full", "Classical, fair"], [qnn_accuracy, cnn_accuracy, fair_nn_accuracy])
https://github.com/lynnlangit/learning-quantum
lynnlangit
# Importing Libraries import torch from torch import cat, no_grad, manual_seed from torch.utils.data import DataLoader from torchvision import transforms import torch.optim as optim from torch.nn import ( Module, Conv2d, Linear, Dropout2d, NLLLoss ) import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from qiskit_machine_learning.neural_networks import EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit import QuantumCircuit from qiskit.visualization import circuit_drawer # Imports for CIFAR-10s from torchvision.datasets import CIFAR10 from torchvision import transforms def prepare_data(X, labels_to_keep, batch_size): # Filtering out labels (originally 0-9), leaving only labels 0 and 1 filtered_indices = [i for i in range(len(X.targets)) if X.targets[i] in labels_to_keep] X.data = X.data[filtered_indices] X.targets = [X.targets[i] for i in filtered_indices] # Defining dataloader with filtered data loader = DataLoader(X, batch_size=batch_size, shuffle=True) return loader # Set seed for reproducibility manual_seed(42) # CIFAR-10 data transformation transform = transforms.Compose([ transforms.ToTensor(), # convert the images to tensors transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # Normalization usign mean and std. ]) labels_to_keep = [0, 1] batch_size = 1 # Preparing Train Data X_train = CIFAR10(root="./data", train=True, download=True, transform=transform) train_loader = prepare_data(X_train, labels_to_keep, batch_size) # Preparing Test Data X_test = CIFAR10(root="./data", train=False, download=True, transform=transform) test_loader = prepare_data(X_test, labels_to_keep, batch_size) print(f"Training dataset size: {len(train_loader.dataset)}") print(f"Test dataset size: {len(test_loader.dataset)}") # Defining and creating QNN def create_qnn(): feature_map = ZZFeatureMap(2) # ZZFeatureMap with 2 bits, entanglement between qubits based on the pairwise product of input features. ansatz = RealAmplitudes(2, reps=1) # parameters (angles, in the case of RealAmplitudes) that are adjusted during the training process to optimize the quantum model for a specific task. qc = QuantumCircuit(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, input_gradients=True, ) return qnn qnn = create_qnn() # Visualizing the QNN circuit circuit_drawer(qnn.circuit, output='mpl') # Defining torch NN module class Net(Module): def __init__(self, qnn): super().__init__() self.conv1 = Conv2d(3, 16, kernel_size=3, padding=1) self.conv2 = Conv2d(16, 32, kernel_size=3, padding=1) self.dropout = Dropout2d() self.fc1 = Linear(32 * 8 * 8, 64) self.fc2 = Linear(64, 2) # 2-dimensional input to QNN self.qnn = TorchConnector(qnn) self.fc3 = Linear(1, 1) # 1-dimensional output from QNN def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.qnn(x) x = self.fc3(x) return cat((x, 1 - x), -1) # Creating model model = Net(qnn) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) # Defining model, optimizer, and loss function optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = NLLLoss() # Starting training epochs = 10 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) # Move data to GPU optimizer.zero_grad(set_to_none=True) output = model(data) loss = loss_func(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss) / len(total_loss)) print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1])) # Plotting loss convergence plt.plot(loss_list) plt.title("Hybrid NN Training Convergence") plt.xlabel("Training Iterations") plt.ylabel("Neg. Log Likelihood Loss") plt.show() # Saving the model torch.save( model.state_dict(), "model_cifar10_10EPOCHS.pt") # Loading the model qnn_cifar10 = create_qnn() model_cifar10 = Net(qnn_cifar10) model_cifar10.load_state_dict(torch.load("model_cifar10.pt")) correct = 0 total = 0 model_cifar10.eval() with torch.no_grad(): for data, target in test_loader: output = model_cifar10(data) _, predicted = torch.max(output.data, 1) total += target.size(0) correct += (predicted == target).sum().item() # Calculating and print test accuracy test_accuracy = correct / total * 100 print(f"Test Accuracy: {test_accuracy:.2f}%") # Plotting predicted labels n_samples_show = 6 count = 0 fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3)) model_cifar10.eval() with no_grad(): for batch_idx, (data, target) in enumerate(test_loader): if count == n_samples_show: break output = model_cifar10(data) if len(output.shape) == 1: output = output.reshape(1, *output.shape) pred = output.argmax(dim=1, keepdim=True) axes[count].imshow(np.transpose(data[0].numpy(), (1, 2, 0))) axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title("Predicted {0}\n Actual {1}".format(pred.item(), target.item())) count += 1 plt.show()
https://github.com/lynnlangit/learning-quantum
lynnlangit
import numpy as np from qiskit.algorithms.linear_solvers.numpy_linear_solver import NumPyLinearSolver from qiskit.algorithms.linear_solvers.hhl import HHL matrix = np.array([[1, -1/3], [-1/3, 1]]) vector = np.array([1, 0]) naive_hhl_solution = HHL().solve(matrix, vector) classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) from qiskit.algorithms.linear_solvers.matrices.tridiagonal_toeplitz import TridiagonalToeplitz tridi_matrix = TridiagonalToeplitz(1, 1, -1 / 3) tridi_solution = HHL().solve(tridi_matrix, vector) print('classical state:', classical_solution.state) print('naive state:') print(naive_hhl_solution.state) print('tridiagonal state:') print(tridi_solution.state) print('classical Euclidean norm:', classical_solution.euclidean_norm) print('naive Euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal Euclidean norm:', tridi_solution.euclidean_norm) from qiskit.quantum_info import Statevector naive_sv = Statevector(naive_hhl_solution.state).data tridi_sv = Statevector(tridi_solution.state).data # Extract the right vector components. 1000 corresponds to the index 8 and 1001 corresponds to the index 9 naive_full_vector = np.array([naive_sv[8], naive_sv[9]]) tridi_full_vector = np.array([tridi_sv[8], tridi_sv[9]]) print('naive raw solution vector:', naive_full_vector) print('tridi raw solution vector:', tridi_full_vector) naive_full_vector = np.real(naive_full_vector) tridi_full_vector = np.real(tridi_full_vector) print('full naive solution vector:', naive_hhl_solution.euclidean_norm*naive_full_vector/np.linalg.norm(naive_full_vector)) print('full tridi solution vector:', tridi_solution.euclidean_norm*tridi_full_vector/np.linalg.norm(tridi_full_vector)) print('classical state:', classical_solution.state) from scipy.sparse import diags num_qubits = 2 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) # run the algorithms classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(num_qubits, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) print('classical euclidean norm:', classical_solution.euclidean_norm) print('naive euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal euclidean norm:', tridi_solution.euclidean_norm) from qiskit import transpile num_qubits = list(range(1,5)) a = 1 b = -1/3 i=1 # calculate the circuit depths for different number of qubits to compare the use of resources naive_depths = [] tridi_depths = [] for nb in num_qubits: matrix = diags([b, a, b], [-1, 0, 1], shape=(2**nb, 2**nb)).toarray() vector = np.array([1] + [0]*(2**nb -1)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(nb, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) naive_qc = transpile(naive_hhl_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) tridi_qc = transpile(tridi_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) naive_depths.append(naive_qc.depth()) tridi_depths.append(tridi_qc.depth()) i +=1 sizes = [str(2**nb)+"x"+str(2**nb) for nb in num_qubits] columns = ['size of the system', 'quantum_solution depth', 'tridi_solution depth'] data = np.array([sizes, naive_depths, tridi_depths]) row_format ="{:>23}" * (len(columns) + 2) for team, row in zip(columns, data): print(row_format.format(team, *row)) print('excess:', [naive_depths[i] - tridi_depths[i] for i in range(0, len(naive_depths))]) from qiskit.algorithms.linear_solvers.observables import AbsoluteAverage, MatrixFunctional num_qubits = 1 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) tridi_matrix = TridiagonalToeplitz(1, a, b) average_solution = HHL().solve(tridi_matrix, vector, AbsoluteAverage()) classical_average = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), AbsoluteAverage()) print('quantum average:', average_solution.observable) print('classical average:', classical_average.observable) print('quantum circuit results:', average_solution.circuit_results) observable = MatrixFunctional(1, 1 / 2) functional_solution = HHL().solve(tridi_matrix, vector, observable) classical_functional = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), observable) print('quantum functional:', functional_solution.observable) print('classical functional:', classical_functional.observable) print('quantum circuit results:', functional_solution.circuit_results) from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') hhl = HHL(1e-3, quantum_instance=backend) accurate_solution = hhl.solve(matrix, vector) classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) print(accurate_solution.euclidean_norm) print(classical_solution.euclidean_norm) from qiskit import QuantumRegister, QuantumCircuit import numpy as np t = 2 # This is not optimal; As an exercise, set this to the # value that will get the best results. See section 8 for solution. nqubits = 4 # Total number of qubits nb = 1 # Number of qubits representing the solution nl = 2 # Number of qubits representing the eigenvalues theta = 0 # Angle defining |b> a = 1 # Matrix diagonal b = -1/3 # Matrix off-diagonal # Initialize the quantum and classical registers qr = QuantumRegister(nqubits) # Create a Quantum Circuit qc = QuantumCircuit(qr) qrb = qr[0:nb] qrl = qr[nb:nb+nl] qra = qr[nb+nl:nb+nl+1] # State preparation. qc.ry(2*theta, qrb[0]) # QPE with e^{iAt} for qu in qrl: qc.h(qu) qc.p(a*t, qrl[0]) qc.p(a*t*2, qrl[1]) qc.u(b*t, -np.pi/2, np.pi/2, qrb[0]) # Controlled e^{iAt} on \lambda_{1}: params=b*t qc.p(np.pi/2,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Controlled e^{2iAt} on \lambda_{2}: params = b*t*2 qc.p(np.pi/2,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Inverse QFT qc.h(qrl[1]) qc.rz(-np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(-np.pi/4,qrl[0]) qc.h(qrl[0]) # Eigenvalue rotation t1=(-np.pi +np.pi/3 - 2*np.arcsin(1/3))/4 t2=(-np.pi -np.pi/3 + 2*np.arcsin(1/3))/4 t3=(np.pi -np.pi/3 - 2*np.arcsin(1/3))/4 t4=(np.pi +np.pi/3 + 2*np.arcsin(1/3))/4 qc.cx(qrl[1],qra[0]) qc.ry(t1,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t2,qra[0]) qc.cx(qrl[1],qra[0]) qc.ry(t3,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t4,qra[0]) qc.measure_all() print("Depth: %i" % qc.depth()) print("CNOTS: %i" % qc.count_ops()['cx']) qc.draw(fold=-1) from qiskit import BasicAer, ClassicalRegister, IBMQ from qiskit.compiler import transpile from qiskit.ignis.mitigation.measurement import (complete_meas_cal, # Measurement error mitigation functions CompleteMeasFitter, MeasurementFilter) provider = IBMQ.load_account() backend = provider.get_backend('ibmqx2') # calibrate using real hardware layout = [2,3,0,4] chip_qubits = 5 # Transpiled circuit for the real hardware qc_qa_cx = transpile(qc, backend=backend, initial_layout=layout) meas_cals, state_labels = complete_meas_cal(qubit_list=layout, qr=QuantumRegister(chip_qubits)) qcs = meas_cals + [qc_qa_cx] job = backend.run(qcs, shots=10)
https://github.com/lynnlangit/learning-quantum
lynnlangit
#!/usr/bin/env python # coding: utf-8 # # Solving linear systems of equations using HHL and its Qiskit implementation # In this tutorial, we introduce the HHL algorithm, derive the circuit, and implement it using Qiskit. We show how to run the HHL on a simulator and on a five qubit device. # ## Contents # 1. [Introduction](#introduction) # 2. [The HHL algorithm](#hhlalg) # 1. [Some mathematical background](#mathbackground) # 2. [Description of the HHL](#hhldescription) # 3. [Quantum Phase Estimation (QPE) within HHL](#qpe) # 4. [Non-exact QPE](#qpe2) # 3. [Example 1: 4-qubit HHL](#example1) # 4. [Qiskit Implementation](#implementation) # 1. [Running HHL on a simulator: general method](#implementationsim) # 2. [Running HHL on a real quantum device: optimised example](#implementationdev) # 5. [Problems](#problems) # 6. [References](#references) # ## 1. Introduction <a id='introduction'></a> # # Systems of linear equations arise naturally in many real-life applications in a wide range of areas, such as in the solution of Partial Differential Equations, the calibration of financial models, fluid simulation or numerical field calculation. The problem can be defined as, given a matrix $A\in\mathbb{C}^{N\times N}$ and a vector $\vec{b}\in\mathbb{C}^{N}$, find $\vec{x}\in\mathbb{C}^{N}$ satisfying $A\vec{x}=\vec{b}$ # # For example, take $N=2$, # # $$A = \begin{pmatrix}1 & -1/3\\-1/3 & 1 \end{pmatrix},\quad \vec{x}=\begin{pmatrix} x_{1}\\ x_{2}\end{pmatrix}\quad \text{and} \quad \vec{b}=\begin{pmatrix}1 \\ 0\end{pmatrix}$$ # # Then the problem can also be written as find $x_{1}, x_{2}\in\mathbb{C}$ such that # $$\begin{cases}x_{1} - \frac{x_{2}}{3} = 1 \\ -\frac{x_{1}}{3} + x_{2} = 0\end{cases} $$ # # A system of linear equations is called $s$-sparse if $A$ has at most $s$ non-zero entries per row or column. Solving an $s$-sparse system of size $N$ with a classical computer requires $\mathcal{ O }(Ns\kappa\log(1/\epsilon))$ running time using the conjugate gradient method <sup>[1](#conjgrad)</sup>. Here $\kappa$ denotes the condition number of the system and $\epsilon$ the accuracy of the approximation. # # The HHL is a quantum algorithm to estimate a function of the solution with running time complexity of $\mathcal{ O }(\log(N)s^{2}\kappa^{2}/\epsilon)$<sup>[2](#hhl)</sup> when $A$ is a Hermitian matrix under the assumptions of efficient oracles for loading the data, Hamiltonian simulation and computing a function of the solution. This is an exponential speed up in the size of the system, however one crucial remark to keep in mind is that the classical algorithm returns the full solution, while the HHL can only approximate functions of the solution vector. # ## 2. The HHL algorithm<a id='hhlalg'></a> # # ### A. Some mathematical background<a id='mathbackground'></a> # The first step towards solving a system of linear equations with a quantum computer is to encode the problem in the quantum language. By rescaling the system, we can assume $\vec{b}$ and $\vec{x}$ to be normalised and map them to the respective quantum states $|b\rangle$ and $|x\rangle$. Usually the mapping used is such that $i^{th}$ component of $\vec{b}$ (resp. $\vec{x}$) corresponds to the amplitude of the $i^{th}$ basis state of the quantum state $|b\rangle$ (resp. $|x\rangle$). From now on, we will focus on the rescaled problem # # $$ A|x\rangle=|b\rangle$$ # # Since $A$ is Hermitian, it has a spectral decomposition # $$ # A=\sum_{j=0}^{N-1}\lambda_{j}|u_{j}\rangle\langle u_{j}|,\quad \lambda_{j}\in\mathbb{ R } # $$ # where $|u_{j}\rangle$ is the $j^{th}$ eigenvector of $A$ with respective eigenvalue $\lambda_{j}$. Then, # $$ # A^{-1}=\sum_{j=0}^{N-1}\lambda_{j}^{-1}|u_{j}\rangle\langle u_{j}| # $$ # and the right hand side of the system can be written in the eigenbasis of $A$ as # $$ # |b\rangle=\sum_{j=0}^{N-1}b_{j}|u_{j}\rangle,\quad b_{j}\in\mathbb{ C } # $$ # It is useful to keep in mind that the goal of the HHL is to exit the algorithm with the readout register in the state # $$ # |x\rangle=A^{-1}|b\rangle=\sum_{j=0}^{N-1}\lambda_{j}^{-1}b_{j}|u_{j}\rangle # $$ # Note that here we already have an implicit normalisation constant since we are talking about a quantum state. # ### B. Description of the HHL algorithm <a id='hhldescription'></a> # # The algorithm uses three quantum registers, all of them set to $|0\rangle $ at the beginning of the algorithm. One register, which we will denote with the subindex $n_{l}$, is used to store a binary representation of the eigenvalues of $A$. A second register, denoted by $n_{b}$, contains the vector solution, and from now on $N=2^{n_{b}}$. There is an extra register, for the auxiliary qubits. These are qubits used as intermediate steps in the individual computations but will be ignored in the following description since they are set to $|0\rangle $ at the beginning of each computation and restored back to the $|0\rangle $ state at the end of the individual operation. # # The following is an outline of the HHL algorithm with a high-level drawing of the corresponding circuit. For simplicity all computations are assumed to be exact in the ensuing description, and a more detailed explanation of the non-exact case is given in Section [2.D.](#qpe2). # # <img src="images/hhlcircuit.png" width = "75%" height = "75%"> # # 1. Load the data $|b\rangle\in\mathbb{ C }^{N}$. That is, perform the transformation # $$ |0\rangle _{n_{b}} \mapsto |b\rangle _{n_{b}} $$ # 2. Apply Quantum Phase Estimation (QPE) with # $$ # U = e ^ { i A t } := \sum _{j=0}^{N-1}e ^ { i \lambda _ { j } t } |u_{j}\rangle\langle u_{j}| # $$ # The quantum state of the register expressed in the eigenbasis of $A$ is now # $$ # \sum_{j=0}^{N-1} b _ { j } |\lambda _ {j }\rangle_{n_{l}} |u_{j}\rangle_{n_{b}} # $$ # where $|\lambda _ {j }\rangle_{n_{l}}$ is the $n_{l}$-bit binary representation of $\lambda _ {j }$. # # 3. Add an auxiliary qubit and apply a rotation conditioned on $|\lambda_{ j }\rangle$, # $$ # \sum_{j=0}^{N-1} b _ { j } |\lambda _ { j }\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} \left( \sqrt { 1 - \frac { C^{2} } { \lambda _ { j } ^ { 2 } } } |0\rangle + \frac { C } { \lambda _ { j } } |1\rangle \right) # $$ # where $C$ is a normalisation constant, and, as expressed in the current form above, should be less than the smallest eigenvalue $\lambda_{min}$ in magnitude, i.e., $|C| < \lambda_{min}$. # # 4. Apply QPE$^{\dagger}$. Ignoring possible errors from QPE, this results in # $$ # \sum_{j=0}^{N-1} b _ { j } |0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} \left( \sqrt { 1 - \frac {C^{2} } { \lambda _ { j } ^ { 2 } } } |0\rangle + \frac { C } { \lambda _ { j } } |1\rangle \right) # $$ # # 5. Measure the auxiliary qubit in the computational basis. If the outcome is $1$, the register is in the post-measurement state # $$ # \left( \sqrt { \frac { 1 } { \sum_{j=0}^{N-1} \left| b _ { j } \right| ^ { 2 } / \left| \lambda _ { j } \right| ^ { 2 } } } \right) \sum _{j=0}^{N-1} \frac{b _ { j }}{\lambda _ { j }} |0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} # $$ # which up to a normalisation factor corresponds to the solution. # # 6. Apply an observable $M$ to calculate $F(x):=\langle x|M|x\rangle$. # ### C. Quantum Phase Estimation (QPE) within HHL <a id='qpe'></a> # # Quantum Phase Estimation is described in more detail in Chapter 3. However, since this quantum procedure is at the core of the HHL algorithm, we recall here the definition. Roughly speaking, it is a quantum algorithm which, given a unitary $U$ with eigenvector $|\psi\rangle_{m}$ and eigenvalue $e^{2\pi i\theta}$, finds $\theta$. We can formally define this as follows. # # **Definition:** Let $U\in\mathbb{ C }^{2^{m}\times 2^{m}}$ be unitary and let $|\psi\rangle_{m}\in\mathbb{ C }^{2^{m}}$ be one of its eigenvectors with respective eigenvalue $e^{2\pi i\theta}$. The **Quantum Phase Estimation** algorithm, abbreviated **QPE**, takes as inputs the unitary gate for $U$ and the state $|0\rangle_{n}|\psi\rangle_{m}$ and returns the state $|\tilde{\theta}\rangle_{n}|\psi\rangle_{m}$. Here $\tilde{\theta}$ denotes a binary approximation to $2^{n}\theta$ and the $n$ subscript denotes it has been truncated to $n$ digits. # $$ # \operatorname { QPE } ( U , |0\rangle_{n}|\psi\rangle_{m} ) = |\tilde{\theta}\rangle_{n}|\psi\rangle_{m} # $$ # # For the HHL we will use QPE with $U = e ^ { i A t }$, where $A$ is the matrix associated to the system we want to solve. In this case, # $$ # e ^ { i A t } = \sum_{j=0}^{N-1}e^{i\lambda_{j}t}|u_{j}\rangle\langle u_{j}| # $$ # Then, for the eigenvector $|u_{j}\rangle_{n_{b}}$, which has eigenvalue $e ^ { i \lambda _ { j } t }$, QPE will output $|\tilde{\lambda }_ { j }\rangle_{n_{l}}|u_{j}\rangle_{n_{b}}$. Where $\tilde{\lambda }_ { j }$ represents an $n_{l}$-bit binary approximation to $2^{n_l}\frac{\lambda_ { j }t}{2\pi}$. Therefore, if each $\lambda_{j}$ can be exactly represented with $n_{l}$ bits, # $$ # \operatorname { QPE } ( e ^ { i A t } , \sum_{j=0}^{N-1}b_{j}|0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} ) = \sum_{j=0}^{N-1}b_{j}|\lambda_{j}\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} # $$ # ### D. Non-exact QPE <a id='qpe2'></a> # # In reality, the quantum state of the register after applying QPE to the initial state is # $$ # \sum _ { j=0 }^{N-1} b _ { j } \left( \sum _ { l = 0 } ^ { 2 ^ { n_{l} } - 1 } \alpha _ { l | j } |l\rangle_{n_{l}} \right)|u_{j}\rangle_{n_{b}} # $$ # where # $$ # \alpha _ { l | j } = \frac { 1 } { 2 ^ { n_{l} } } \sum _ { k = 0 } ^ { 2^{n_{l}}- 1 } \left( e ^ { 2 \pi i \left( \frac { \lambda _ { j } t } { 2 \pi } - \frac { l } { 2 ^ { n_{l} } } \right) } \right) ^ { k } # $$ # # Denote by $\tilde{\lambda_{j}}$ the best $n_{l}$-bit approximation to $\lambda_{j}$, $1\leq j\leq N$. Then we can relabel the $n_{l}$-register so that $\alpha _ { l | j }$ denotes the amplitude of $|l + \tilde { \lambda } _ { j } \rangle_{n_{l}}$. So now, # $$ # \alpha _ { l | j } : = \frac { 1 } { 2 ^ { n_{l}} } \sum _ { k = 0 } ^ { 2 ^ { n_{l} } - 1 } \left( e ^ { 2 \pi i \left( \frac { \lambda _ { j } t } { 2 \pi } - \frac { l + \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } } \right) } \right) ^ { k } # $$ # If each $\frac { \lambda _ { j } t } { 2 \pi }$ can be represented exactly with $n_{l}$ binary bits, then $\frac { \lambda _ { j } t } { 2 \pi }=\frac { \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } }$ $\forall j$. Therefore in this case $\forall j$, $1\leq j \leq N$, it holds that $\alpha _ { 0 | j } = 1$ and $\alpha _ { l | j } = 0 \quad \forall l \neq 0$. Only in this case we can write that the state of the register after QPE is # $$ # \sum_{j=0}^{N-1} b _ { j } |\lambda _ {j }\rangle_{n_{l}} |u_{j}\rangle_{n_{b}} # $$ # Otherwise, $|\alpha _ { l | j }|$ is large if and only if $\frac { \lambda _ { j } t } { 2 \pi } \approx \frac { l + \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } }$ and the state of the register is # $$ # \sum _ { j=0 }^{N-1} \sum _ { l = 0 } ^ { 2 ^ { n_{l} } - 1 } \alpha _ { l | j } b _ { j }|l\rangle_{n_{l}} |u_{j}\rangle_{n_{b}} # $$ # ## 3. Example: 4-qubit HHL<a id='example1'></a> # # Let's take the small example from the introduction to illustrate the algorithm. That is, # $$A = \begin{pmatrix}1 & -1/3\\-1/3 & 1 \end{pmatrix}\quad \text{and} \quad |b\rangle=\begin{pmatrix}1 \\ 0\end{pmatrix}$$ # # We will use $n_{b}=1$ qubit to represent $|b\rangle$, and later the solution $|x\rangle$, $n_{l}=2$ qubits to store the binary representation of the eigenvalues and $1$ auxiliary qubit to store whether the conditioned rotation, hence the algorithm, was successful. # # For the purpose of illustrating the algorithm, we will cheat a bit and calculate the eigenvalues of $A$ to be able to choose $t$ to obtain an exact binary representation of the rescaled eigenvalues in the $n_{l}$-register. However, keep in mind that for the HHL algorithm implementation one does not need previous knowledge of the eigenvalues. Having said that, a short calculation will give # $$\lambda_{1} = 2/3\quad\text{and}\quad\lambda_{2}=4/3$$ # # Recall from the previous section that the QPE will output an $n_{l}$-bit ($2$-bit in this case) binary approximation to $\frac{\lambda_ { j }t}{2\pi}$. Therefore, if we set # $$t=2\pi\cdot \frac{3}{8}$$ # the QPE will give a $2$-bit binary approximation to # $$\frac{\lambda_ { 1 }t}{2\pi} = 1/4\quad\text{and}\quad\frac{\lambda_ { 2 }t}{2\pi}=1/2$$ # which is, respectively, # $$|01\rangle_{n_{l}}\quad\text{and}\quad|10\rangle_{n_{l}}$$ # # The eigenvectors are, respectively, # $$|u_{1}\rangle=\begin{pmatrix}1 \\ -1\end{pmatrix}\quad\text{and}\quad|u_{2}\rangle=\begin{pmatrix}1 \\ 1\end{pmatrix}$$ # Again, keep in mind that one does not need to compute the eigenvectors for the HHL implementation. In fact, a general Hermitian matrix $A$ of dimension $N$ can have up to $N$ different eigenvalues, therefore calculating them would take $\mathcal{O}(N)$ time and the quantum advantage would be lost. # # We can then write $|b\rangle$ in the eigenbasis of $A$ as # $$|b\rangle _{n_{b}}=\sum_{j=1}^{2}\frac{1}{\sqrt{2}}|u_{j}\rangle _{n_{b}}$$ # # Now we are ready to go through the different steps of the HHL algorithm. # # 1. State preparation in this example is trivial since $|b\rangle=|0\rangle$. # 2. Applying QPE will yield # $$ # \frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle # $$ # 3. Conditioned rotation with $C=1/8$ that is less than the smallest (rescaled) eigenvalue of $\frac {1} {4}$. Note, the contant $C$ here needs to be chosen such that it is less than the smallest (rescaled) eigenvalue of $\frac {1} {4}$ but as large as possible so that when the auxiliary qubit is measured, the probabilit of it being in the state $|1>$ is large. # $$\frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { (1/8)^{2} } {(1/4)^{2} } } |0\rangle + \frac { 1/8 } { 1/4 } |1\rangle \right) + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { (1/8)^{2} } {(1/2)^{2} } } |0\rangle + \frac { 1/8 } { 1/2 } |1\rangle \right) # $$ # $$ # =\frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { 1 } {4 } } |0\rangle + \frac { 1 } { 2 } |1\rangle \right) + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { 1 } {16 } } |0\rangle + \frac { 1 } { 4 } |1\rangle \right) # $$ # 4. After applying QPE$^{\dagger}$ the quantum computer is in the state # $$ # \frac{1}{\sqrt{2}}|00\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { 1 } {4 } } |0\rangle + \frac { 1 } { 2 } |1\rangle \right) + \frac{1}{\sqrt{2}}|00\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { 1 } {16 } } |0\rangle + \frac { 1 } { 4 } |1\rangle \right) # $$ # 5. On outcome $1$ when measuring the auxiliary qubit, the state is # $$ # \frac{\frac{1}{\sqrt{2}}|00\rangle|u_{1}\rangle\frac { 1 } { 2 } |1\rangle + \frac{1}{\sqrt{2}}|00\rangle|u_{2}\rangle\frac { 1 } { 4 } |1\rangle}{\sqrt{5/32}} # $$ # A quick calculation shows that # $$ # \frac{\frac{1}{2\sqrt{2}}|u_{1}\rangle+ \frac{1}{4\sqrt{2}}|u_{2}\rangle}{\sqrt{5/32}} = \frac{|x\rangle}{||x||} # $$ # 6. Without using extra gates, we can compute the norm of $|x\rangle$: it is the probability of measuring $1$ in the auxiliary qubit from the previous step. # $$ # P(|1\rangle) = \left(\frac{1}{2\sqrt{2}}\right)^{2} + \left(\frac{1}{4\sqrt{2}}\right)^{2} = \frac{5}{32} = ||x||^{2} # $$ # # # ## 4. Qiskit Implementation<a id='implementation'></a> # Now that we have analytically solved the problem from the example we are going to use it to illustrate how to run the HHL on a quantum simulator and on the real hardware. For the quantum simulator, Qiskit already provides an implementation of the HHL algorithm requiring only the matrix $A$ and $|b\rangle$ as inputs in the simplest example. Although we can give the algorithm a general Hermitian matrix and an arbitrary initial state as NumPy arrays, in these cases the quantum algorithm will not achieve an exponential speedup. This is because the default implementation is exact and therefore exponential in the number of qubits (there is no algorithm that can prepare exactly an arbitrary quantum state using polynomial resources in the number of qubits or that can perform exactly the operation $e^{iAt}$ for some general Hermitian matrix $A$ using polynomial resources in the number of qubits). If we know an efficient implementation for a particular problem, the matrix and/or the vector can be given as `QuantumCircuit` objects. Alternatively, there's already an efficient implementation for tridiagonal Toeplitz matrices and in the future there might be more. # # However,at the time of writing the existing quantum computers are noisy and can only run small circuits. Therefore, in Section [4.B.](#implementationdev) we will see an optimised circuit that can be used for a class of problems to which our example belongs and mention the existing procedures to deal with noise in quantum computers. # ## A. Running HHL on a simulator: general method<a id='implementationsim'></a> # The interface for all algorithms to solve the linear system problem is `LinearSolver`. The problem to be solved is only specified when the `solve()` method is called: # ```python # LinearSolver(...).solve(matrix, vector) # ``` # # The simplest implementation takes the matrix and the vector as NumPy arrays. Below we also create a `NumPyLinearSolver` (the classical algorithm) to validate our solutions. # In[1]: ###### see this link to setup Qiskit --> https://qiskit.org/textbook/ch-prerequisites/setting-the-environment.html ##### import numpy as np from qiskit.algorithms.linear_solvers.numpy_linear_solver import NumPyLinearSolver from qiskit.algorithms.linear_solvers.hhl import HHL matrix = np.array([[1, -1/3], [-1/3, 1]]) vector = np.array([1, 0]) naive_hhl_solution = HHL().solve(matrix, vector) # For the classical solver we need to rescale the right hand side (i.e. `vector / np.linalg.norm(vector)`) to take into account the renormalisation that occurs once `vector` is encoded in a quantum state within HHL. # In[2]: classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) # The `linear_solvers` package contains a folder called `matrices` intended to be a placeholder for efficient implementations of particular types of matrices. At the time of writing the only truly efficient implementation it contains (i.e. complexity scaling polynomially in the number of qubits) is the `TridiagonalToeplitz` class. Tridiagonal Toeplitz symmetric real matrices are of the following form # $$A = \begin{pmatrix}a & b & 0 & 0\\b & a & b & 0 \\ 0 & b & a & b \\ 0 & 0 & b & a \end{pmatrix}, a,b\in\mathbb{R}$$ # (note that in this setting we do not consider non symmetric matrices since the HHL algorithm assumes that the input matrix is Hermitian). # # Since the matrix $A$ from our example is of this form we can create an instance of `TridiagonalToeplitz(num_qubits, a, b)` and compare the results to solving the system with an array as input. # In[3]: from qiskit.algorithms.linear_solvers.matrices.tridiagonal_toeplitz import TridiagonalToeplitz tridi_matrix = TridiagonalToeplitz(1, 1, -1 / 3) tridi_solution = HHL().solve(tridi_matrix, vector) # Recall that the HHL algorithm can find a solution exponentially faster in the size of the system than their classical counterparts (i.e. logarithmic complexity instead of polynomial). However the cost for this exponential speedup is that we do not obtain the full solution vector. # Instead, we obtain a quantum state representing the vector $x$ and learning all the components of this vector would take a linear time in its dimension, diminishing any speedup obtained by the quantum algorithm. # # Therefore, we can only compute functions from $x$ (the so called observables) to learn information about the solution. # This is reflected in the `LinearSolverResult` object returned by `solve()`, which contains the following properties # - `state`: either the circuit that prepares the solution or the solution as a vector # - `euclidean_norm`: the euclidean norm if the algorithm knows how to calculate it # - `observable`: the (list of) calculated observable(s) # - `circuit_results`: the observable results from the (list of) circuit(s) # # Let's ignore `observable` and `circuit_results` for the time being and check the solutions we obtained before. # # First, `classical_solution` was the result from a classical algorithm, so if we call `.state` it will return an array: # In[4]: print('classical state:', classical_solution.state) # Our other two examples were quantum algorithms, hence we can only access to the quantum state. This is achieved by returning the quantum circuit that prepares the solution state: # In[5]: print('naive state:') print(naive_hhl_solution.state) print('tridiagonal state:') print(tridi_solution.state) # Recall that the Euclidean norm for a vector $\mathbf{x}=(x_1,\dots,x_N)$ is defined as $||\mathbf{x}||=\sqrt{\sum_{i=1}^N x_i^2}$. Therefore, the probability of measuring $1$ in the auxiliary qubit from Step $5$ in Section B is the squared norm of $\mathbf{x}$. This means that the HHL algorithm can always calculate the euclidean norm of the solution and we can compare the accuracy of the results: # In[6]: print('classical Euclidean norm:', classical_solution.euclidean_norm) print('naive Euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal Euclidean norm:', tridi_solution.euclidean_norm) # Comparing the solution vectors componentwise is more tricky, reflecting again the idea that we cannot obtain the full solution vector from the quantum algorithm. However, for educational purposes we can check that indeed the different solution vectors obtained are a good approximation at the vector component level as well. # # To do so first we need to use `Statevector` from the `quantum_info` package and extract the right vector components, i.e. those corresponding to the ancillary qubit (bottom in the circuits) being $1$ and the work qubits (the two middle in the circuits) being $0$. Thus, we are interested in the states `1000` and `1001`, corresponding to the first and second components of the solution vector respectively. # In[7]: from qiskit.quantum_info import Statevector naive_sv = Statevector(naive_hhl_solution.state).data tridi_sv = Statevector(tridi_solution.state).data # Extract the right vector components. 1000 corresponds to the index 8 and 1001 corresponds to the index 9 naive_full_vector = np.array([naive_sv[8], naive_sv[9]]) tridi_full_vector = np.array([tridi_sv[8], tridi_sv[9]]) print('naive raw solution vector:', naive_full_vector) print('tridi raw solution vector:', tridi_full_vector) # At a first glance it might seem that this is wrong because the components are complex numbers instead of reals. However note that the imaginary part is very small, most likely due to computer accuracy, and can be disregarded in this case. # In[8]: naive_full_vector = np.real(naive_full_vector) tridi_full_vector = np.real(tridi_full_vector) # Next, we will divide the vectors by their respective norms to suppress any constants coming from the different parts of the circuits. The full solution vector can then be recovered by multiplying these normalised vectors by the respective Euclidean norms calculated above: # In[9]: print('full naive solution vector:', naive_hhl_solution.euclidean_norm*naive_full_vector/np.linalg.norm(naive_full_vector)) print('full tridi solution vector:', tridi_solution.euclidean_norm*tridi_full_vector/np.linalg.norm(tridi_full_vector)) print('classical state:', classical_solution.state) # It should not come as a surprise that `naive_hhl_solution` is exact because all the default methods used are exact. However, `tridi_solution` is exact only in the $2\times 2$ system size case. For larger matrices it will be an approximation, as shown in the slightly larger example below. # In[10]: from scipy.sparse import diags num_qubits = 2 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) # run the algorithms classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(num_qubits, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) print('classical euclidean norm:', classical_solution.euclidean_norm) print('naive euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal euclidean norm:', tridi_solution.euclidean_norm) # We can also compare the difference in resources from the exact method and the efficient implementation. The $2\times 2$ system size is again special in that the exact algorithm requires less resources, but as we increase the system size, we can see that indeed the exact method scales exponentially in the number of qubits while `TridiagonalToeplitz` is polynomial. # In[11]: from qiskit import transpile num_qubits = list(range(1,5)) a = 1 b = -1/3 i=1 # calculate the circuit depths for different number of qubits to compare the use of resources naive_depths = [] tridi_depths = [] for nb in num_qubits: matrix = diags([b, a, b], [-1, 0, 1], shape=(2**nb, 2**nb)).toarray() vector = np.array([1] + [0]*(2**nb -1)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(nb, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) naive_qc = transpile(naive_hhl_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) tridi_qc = transpile(tridi_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) naive_depths.append(naive_qc.depth()) tridi_depths.append(tridi_qc.depth()) i +=1 # In[ ]: sizes = [str(2**nb)+"x"+str(2**nb) for nb in num_qubits] columns = ['size of the system', 'quantum_solution depth', 'tridi_solution depth'] data = np.array([sizes, naive_depths, tridi_depths]) row_format ="{:>23}" * (len(columns) + 2) for team, row in zip(columns, data): print(row_format.format(team, *row)) # The reason the implementation still seems to need exponential resources is because the current conditioned rotation implementation (step 3 from Section 2.B) is exact (i.e. needs exponential resources in $n_l$). Instead we can calculate how many more resources the default implementation needs compared to Tridiagonal - since they only differ in how they implement $e^{iAt}$: # In[13]: print('excess:', [naive_depths[i] - tridi_depths[i] for i in range(0, len(naive_depths))]) # In the near future the plan is to integrate `qiskit.circuit.library.arithmetics.PiecewiseChebyshev` to obtain a polynomial implementation of the conditioned rotation as well. # # Now we can return to the topic of observables and find out what the `observable` and `circuit_results` properties contain. # # The way to compute functions of the solution vector $\mathbf{x}$ is through giving the `.solve()` method a `LinearSystemObservable` as input. There are are two types of available `LinearSystemObservable` which can be given as input: # In[12]: from qiskit.algorithms.linear_solvers.observables import AbsoluteAverage, MatrixFunctional # For a vector $\mathbf{x}=(x_1,...,x_N)$, the `AbsoluteAverage` observable computes $|\frac{1}{N}\sum_{i=1}^{N}x_i|$. # In[13]: num_qubits = 1 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) tridi_matrix = TridiagonalToeplitz(1, a, b) average_solution = HHL().solve(tridi_matrix, vector, AbsoluteAverage()) classical_average = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), AbsoluteAverage()) print('quantum average:', average_solution.observable) print('classical average:', classical_average.observable) print('quantum circuit results:', average_solution.circuit_results) # The `MatrixFunctional` observable computes $\mathbf{x}^T B \mathbf{x}$ for a vector $\mathbf{x}$ and a tridiagonal symmetric Toeplitz matrix $B$. The class takes the main and off diagonal values of the matrix for its constuctor method. # In[14]: observable = MatrixFunctional(1, 1 / 2) functional_solution = HHL().solve(tridi_matrix, vector, observable) classical_functional = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), observable) print('quantum functional:', functional_solution.observable) print('classical functional:', classical_functional.observable) print('quantum circuit results:', functional_solution.circuit_results) # Therefore, `observable` contains the final value of the function on $\mathbf{x}$, while `circuit_results` contains the raw values obtained from the circuit and used to process the result of `observable`. # # This 'how to process the result' is better explained by looking at what arguments `.solve()` takes. The `solve()` method accepts up to five arguments: # ```python # def solve(self, matrix: Union[np.ndarray, QuantumCircuit], # vector: Union[np.ndarray, QuantumCircuit], # observable: Optional[Union[LinearSystemObservable, BaseOperator, # List[BaseOperator]]] = None, # post_rotation: Optional[Union[QuantumCircuit, List[QuantumCircuit]]] = None, # post_processing: Optional[Callable[[Union[float, List[float]]], # Union[float, List[float]]]] = None) \ # -> LinearSolverResult: # ``` # The first two are the matrix defining the linear system and the vector right hand side of the equation, which we have already covered. The remaining parameters concern the (list of) observable(s) to be computed out of the solution vector $x$, and can be specified in two different ways. One option is to give as the third and last parameter a (list of) `LinearSystemObservable`(s). Alternatively, we can give our own implementations of the `observable`, `post_rotation` and `post_processing`, where # - `observable` is the operator to compute the expected value of the observable and can be e.g. a `PauliSumOp` # - `post_rotation` is the circuit to be applied to the solution to extract information if additional gates are needed. # - `post_processing` is the function to compute the value of the observable from the calculated probabilities. # # In other words, there will be as many `circuit_results` as `post_rotation` circuits, and `post_processing` is telling the algorithm how to use the values we see when we print `circuit_results` to obtain the value we see when we print `observable`. # # Finally, the `HHL` class accepts the following parameters in its constructor method: # - error tolerance : the accuracy of the approximation of the solution, the default is `1e-2` # - expectation : how the expectation values are evaluated, the default is `PauliExpectation` # - quantum instance: the `QuantumInstance` or backend, the default is a `Statevector` simulation # In[15]: from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') hhl = HHL(1e-3, quantum_instance=backend) accurate_solution = hhl.solve(matrix, vector) classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) print(accurate_solution.euclidean_norm) print(classical_solution.euclidean_norm) # ## B. Running HHL on a real quantum device: optimised example<a id='implementationdev'></a> # In the previous section we ran the standard algorithm provided in Qiskit and saw that it uses $7$ qubits, has a depth of ~$100$ gates and requires a total of $54$ CNOT gates. These numbers are not feasible for the current available hardware, therefore we need to decrease these quantities. In particular, the goal will be to reduce the number of CNOTs by a factor of $5$ since they have worse fidelity than single-qubit gates. Furthermore, we can reduce the number of qubits to $4$ as was the original statement of the problem: the Qiskit method was written for a general problem and that is why it requires $3$ additional auxiliary qubits. # # However, solely decreasing the number of gates and qubits will not give a good approximation to the solution on real hardware. This is because there are two sources of errors: those that occur during the run of the circuit and readout errors. # # Qiskit provides a module to mitigate the readout errors by individually preparing and measuring all basis states, a detailed treatment on the topic can be found in the paper by Dewes et al.<sup>[3](#readouterr)</sup> To deal with the errors occurring during the run of the circuit, Richardson extrapolation can be used to calculate the error to the zero limit by running the circuit three times, each replacing each CNOT gate by $1$, $3$ and $5$ CNOTs respectively<sup>[4](#richardson)</sup>. The idea is that theoretically the three circuits should produce the same result, but in real hardware adding CNOTs means amplifying the error. Since we know that we have obtained results with an amplified error, and we can estimate by how much the error was amplified in each case, we can recombine the quantities to obtain a new result that is a closer approximation to the analytic solution than any of the previous obtained values. # # Below we give the optimised circuit that can be used for any problem of the form # $$A = \begin{pmatrix}a & b\\b & a \end{pmatrix}\quad \text{and} \quad |b\rangle=\begin{pmatrix}\cos(\theta) \\ \sin(\theta)\end{pmatrix},\quad a,b,\theta\in\mathbb{R}$$ # # The following optimisation was extracted from a work on the HHL for tridiagonal symmetric matrices<sup>[[5]](#tridi)</sup>, this particular circuit was derived with the aid of the UniversalQCompiler software<sup>[[6]](#qcompiler)</sup>. # # In[16]: from qiskit import QuantumRegister, QuantumCircuit import numpy as np t = 2 # This is not optimal; As an exercise, set this to the # value that will get the best results. See section 8 for solution. nqubits = 4 # Total number of qubits nb = 1 # Number of qubits representing the solution nl = 2 # Number of qubits representing the eigenvalues theta = 0 # Angle defining |b> a = 1 # Matrix diagonal b = -1/3 # Matrix off-diagonal # Initialize the quantum and classical registers qr = QuantumRegister(nqubits) # Create a Quantum Circuit qc = QuantumCircuit(qr) qrb = qr[0:nb] qrl = qr[nb:nb+nl] qra = qr[nb+nl:nb+nl+1] # State preparation. qc.ry(2*theta, qrb[0]) # QPE with e^{iAt} for qu in qrl: qc.h(qu) qc.p(a*t, qrl[0]) qc.p(a*t*2, qrl[1]) qc.u(b*t, -np.pi/2, np.pi/2, qrb[0]) # Controlled e^{iAt} on \lambda_{1}: params=b*t qc.p(np.pi/2,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Controlled e^{2iAt} on \lambda_{2}: params = b*t*2 qc.p(np.pi/2,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Inverse QFT qc.h(qrl[1]) qc.rz(-np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(-np.pi/4,qrl[0]) qc.h(qrl[0]) # Eigenvalue rotation t1=(-np.pi +np.pi/3 - 2*np.arcsin(1/3))/4 t2=(-np.pi -np.pi/3 + 2*np.arcsin(1/3))/4 t3=(np.pi -np.pi/3 - 2*np.arcsin(1/3))/4 t4=(np.pi +np.pi/3 + 2*np.arcsin(1/3))/4 qc.cx(qrl[1],qra[0]) qc.ry(t1,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t2,qra[0]) qc.cx(qrl[1],qra[0]) qc.ry(t3,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t4,qra[0]) qc.measure_all() print("Depth: %i" % qc.depth()) print("CNOTS: %i" % qc.count_ops()['cx']) qc.draw(fold=-1) # The code below takes as inputs our circuit, the real hardware backend and the set of qubits we want to use, and returns and instance that can be run on the specified device. Creating the circuits with $3$ and $5$ CNOTs is the same but calling the transpile method with the right quantum circuit. # # Real hardware devices need to be recalibrated regularly, and the fidelity of a specific qubit or gate can change over time. Furthermore, different chips have different connectivities. If we try to run a circuit that performs a two-qubit gate between two qubits that are not connected on the specified device, the transpiler will add SWAP gates. Therefore it is good practice to check with the IBM Quantum Experience webpage<sup>[[7]](#qexperience)</sup> before running the following code and choose a set of qubits with the right connectivity and lowest error rates at the given time. # In[17]: from qiskit import BasicAer, ClassicalRegister, IBMQ from qiskit.compiler import transpile from qiskit.ignis.mitigation.measurement import (complete_meas_cal, # Measurement error mitigation functions CompleteMeasFitter, MeasurementFilter) provider = IBMQ.load_account() backend = provider.get_backend('ibmqx2') # calibrate using real hardware layout = [2,3,0,4] chip_qubits = 5 # Transpiled circuit for the real hardware qc_qa_cx = transpile(qc, backend=backend, initial_layout=layout) # The next step is to create the extra circuits used to mitigate the readout errors<sup>[[3]](#readouterr)</sup>. # In[18]: meas_cals, state_labels = complete_meas_cal(qubit_list=layout, qr=QuantumRegister(chip_qubits)) qcs = meas_cals + [qc_qa_cx] job = backend.run(qcs, shots=10) # The following plot<sup>[[5]](#tridi)</sup>, shows the results from running the circuit above on real hardware for $10$ different initial states. The $x$-axis represents the angle $\theta$ defining the initial state in each case. The results where obtained after mitigating the readout error and then extrapolating the errors arising during the run of the circuit from the results with the circuits with $1$, $3$ and $5$ CNOTs. # # <img src="images/norm_public.png"> # # Compare to the results without error mitigation nor extrapolation from the CNOTs<sup>[5](#tridi)</sup>. # # <img src="images/noerrmit_public.png"> # ## 8. Problems<a id='problems'></a> # ##### Real hardware: # # 1. Set the time parameter for the optimised example. # # <details> # <summary> Solution (Click to expand)</summary> # t = 2.344915690192344 # # The best result is to set it so that the smallest eigenvalue can be represented exactly, since it's inverse will have the largest contribution in the solution # </details> # # 2. Create transpiled circuits for $3$ and $5$ CNOTs from a given circuit 'qc'. When creating the circuits you will have to add barriers so that these consecutive CNOT gates do not get cancelled when using the transpile() method. # 3. Run your circuits on the real hardware and apply a quadratic fit to the results to obtain the extrapolated value. # ## 9. References<a id='references'></a> # 1. J. R. Shewchuk. An Introduction to the Conjugate Gradient Method Without the Agonizing Pain. Technical Report CMU-CS-94-125, School of Computer Science, Carnegie Mellon University, Pittsburgh, Pennsylvania, March 1994.<a id='conjgrad'></a> # 2. A. W. Harrow, A. Hassidim, and S. Lloyd, “Quantum algorithm for linear systems of equations,” Phys. Rev. Lett. 103.15 (2009), p. 150502.<a id='hhl'></a> # 3. A. Dewes, F. R. Ong, V. Schmitt, R. Lauro, N. Boulant, P. Bertet, D. Vion, and D. Esteve, “Characterization of a two-transmon processor with individual single-shot qubit readout,” Phys. Rev. Lett. 108, 057002 (2012). <a id='readouterr'></a> # 4. N. Stamatopoulos, D. J. Egger, Y. Sun, C. Zoufal, R. Iten, N. Shen, and S. Woerner, “Option Pricing using Quantum Computers,” arXiv:1905.02666 . <a id='richardson'></a> # 5. A. Carrera Vazquez, A. Frisch, D. Steenken, H. S. Barowski, R. Hiptmair, and S. Woerner, “Enhancing Quantum Linear System Algorithm by Richardson Extrapolation,” (to be included).<a id='tridi'></a> # 6. R. Iten, O. Reardon-Smith, L. Mondada, E. Redmond, R. Singh Kohli, R. Colbeck, “Introduction to UniversalQCompiler,” arXiv:1904.01072 .<a id='qcompiler'></a> # 7. https://quantum-computing.ibm.com/ .<a id='qexperience'></a> # 8. D. Bucher, J. Mueggenburg, G. Kus, I. Haide, S. Deutschle, H. Barowski, D. Steenken, A. Frisch, "Qiskit Aqua: Solving linear systems of equations with the HHL algorithm" https://github.com/Qiskit/qiskit-tutorials/blob/master/legacy_tutorials/aqua/linear_systems_of_equations.ipynb
https://github.com/lynnlangit/learning-quantum
lynnlangit
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() import math import numpy as np from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit.algorithms import Shor N = 15 backend = Aer.get_backend('aer_simulator') quantum_instance = QuantumInstance(backend, shots=1024) shor = Shor(quantum_instance=quantum_instance) result = shor.factor(N) print(f"The list of factors of {N} as computed by the Shor's algorithm is {result.factors[0]}.") print(f'Computed of qubits for circuit: {4 * math.ceil(math.log(N, 2)) + 2}') print(f'Actual number of qubits of circuit: {shor.construct_circuit(N).num_qubits}') %qiskit_version_table %qiskit_copyright
https://github.com/lynnlangit/learning-quantum
lynnlangit
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/lynnlangit/learning-quantum
lynnlangit
## import qiskit.tools.jupyter ## %qiskit_version_table
https://github.com/lynnlangit/learning-quantum
lynnlangit
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Q account(s) provider = IBMQ.load_account() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi qreg_alice = QuantumRegister(1, 'alice') qreg_fiber = QuantumRegister(1, 'fiber') qreg_bob = QuantumRegister(1, 'bob') creg_ahad = ClassicalRegister(1, 'ahad') creg_aval = ClassicalRegister(1, 'aval') creg_fval = ClassicalRegister(1, 'fval') creg_bhad = ClassicalRegister(1, 'bhad') creg_bval = ClassicalRegister(1, 'bval') circuit = QuantumCircuit(qreg_alice, qreg_fiber, qreg_bob, creg_ahad, creg_aval, creg_fval, creg_bhad, creg_bval) circuit.reset(qreg_alice[0]) circuit.h(qreg_alice[0]) circuit.measure(qreg_alice[0], creg_ahad[0]) circuit.reset(qreg_alice[0]) circuit.h(qreg_alice[0]) circuit.measure(qreg_alice[0], creg_aval[0]) circuit.reset(qreg_alice[0]) circuit.x(qreg_alice[0]).c_if(creg_aval, 1) circuit.h(qreg_alice[0]).c_if(creg_ahad, 1) circuit.swap(qreg_alice[0], qreg_fiber[0]) circuit.barrier(qreg_alice[0], qreg_fiber[0], qreg_bob[0]) circuit.h(qreg_fiber[0]) circuit.measure(qreg_fiber[0], creg_fval[0]) circuit.reset(qreg_fiber[0]) circuit.x(qreg_fiber[0]).c_if(creg_fval, 1) circuit.h(qreg_fiber[0]) circuit.barrier(qreg_alice[0], qreg_fiber[0], qreg_bob[0]) circuit.reset(qreg_bob[0]) circuit.h(qreg_bob[0]) circuit.measure(qreg_bob[0], creg_bhad[0]) circuit.swap(qreg_fiber[0], qreg_bob[0]) circuit.h(qreg_bob[0]).c_if(creg_bhad, 1) circuit.measure(qreg_bob[0], creg_bval[0]) editor = CircuitComposer(circuit=circuit) editor
https://github.com/lynnlangit/learning-quantum
lynnlangit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from numpy import pi qreg_alice = QuantumRegister(1, 'alice') qreg_fiber = QuantumRegister(1, 'fiber') qreg_bob = QuantumRegister(1, 'bob') creg_ahad = ClassicalRegister(1, 'ahad') creg_aval = ClassicalRegister(1, 'aval') creg_fval = ClassicalRegister(1, 'fval') creg_bhad = ClassicalRegister(1, 'bhad') creg_bval = ClassicalRegister(1, 'bval') circuit = QuantumCircuit(qreg_alice, qreg_fiber, qreg_bob, creg_ahad, creg_aval, creg_fval, creg_bhad, creg_bval) circuit.reset(qreg_alice[0]) circuit.h(qreg_alice[0]) # HAD Alice's qubit circuit.measure(qreg_alice[0], creg_ahad[0]) # READ Alice's qubit value into Ahad circuit.reset(qreg_alice[0]) circuit.h(qreg_alice[0]) # HAD Alice's qubit circuit.measure(qreg_alice[0], creg_aval[0]) # READ Alice's qubit value into Aval circuit.reset(qreg_alice[0]) circuit.x(qreg_alice[0]).c_if(creg_aval, 1) # NOT Alice's qubit if Aval is 1 circuit.h(qreg_alice[0]).c_if(creg_ahad, 1) # HAD Alice's qubit if Ahad is 1 circuit.swap(qreg_alice[0], qreg_fiber[0]) # SWAP Alice's qubit value into Fiber qubit circuit.barrier(qreg_alice[0], qreg_fiber[0], qreg_bob[0]) # PREVENT transformations accross this source line circuit.h(qreg_fiber[0]) # HAD Fiber qubit circuit.measure(qreg_fiber[0], creg_fval[0]) # READ Fiber qubit value into Fval circuit.reset(qreg_fiber[0]) circuit.x(qreg_fiber[0]).c_if(creg_fval, 1) # NOT Fiber qubit if Fval is 1 circuit.h(qreg_fiber[0]) # HAD Fiber qubit circuit.barrier(qreg_alice[0], qreg_fiber[0], qreg_bob[0]) # PREVENT transformations accross this source line circuit.reset(qreg_bob[0]) circuit.h(qreg_bob[0]) # HAD Bob's qubit circuit.measure(qreg_bob[0], creg_bhad[0]) # READ Bob's qubit value into Bhad circuit.swap(qreg_fiber[0], qreg_bob[0]) # SWAP Fiber qubit value into Bob's qubit circuit.h(qreg_bob[0]).c_if(creg_bhad, 1) # HAD Bob's qubit if Bhad is 1 circuit.measure(qreg_bob[0], creg_bval[0]) # READ Bob's qubit value into Bval editor = CircuitComposer(circuit=circuit) editor
https://github.com/lynnlangit/learning-quantum
lynnlangit
from qiskit import QuantumCircuit, Aer, execute, IBMQ from qiskit.utils import QuantumInstance import numpy as np from qiskit.algorithms import Shor IBMQ.enable_account('ENTER API TOKEN HERE') # Enter your API token here provider = IBMQ.get_provider(hub='ibm-q') backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor = Shor(quantum_instance) result_dict = my_shor.factor(15) print(result_dict)
https://github.com/lynnlangit/learning-quantum
lynnlangit
try: import cirq except ImportError: print("installing cirq...") !pip install --quiet cirq print("installed cirq.") import fractions import math import random import matplotlib.pyplot as plt import numpy as np import sympy from typing import Callable, List, Optional, Sequence, Union import cirq #import cirq_google print(cirq.google.Foxtail) # verify cirq, should print a circuit as shown belown # (0, 0)───(0, 1)───(0, 2)───(0, 3)───(0, 4)───(0, 5)───(0, 6)───(0, 7)───(0, 8)───(0, 9)───(0, 10) # │ │ │ │ │ │ │ │ │ │ │ # │ │ │ │ │ │ │ │ │ │ │ # (1, 0)───(1, 1)───(1, 2)───(1, 3)───(1, 4)───(1, 5)───(1, 6)───(1, 7)───(1, 8)───(1, 9)───(1, 10) def classical_order_finder(x: int, n: int) -> Optional[int]: # Make sure x is both valid and in Z_n. if x < 2 or x >= n or math.gcd(x, n) > 1: raise ValueError(f"Invalid x={x} for modulus n={n}.") # Determine the order. r, y = 1, x while y != 1: y = (x * y) % n r += 1 return r n = 15 # The multiplicative group is [1, 2, 4, 7, 8, 11, 13, 14]. x = 8 r = classical_order_finder(x, n) # Check that the order is indeed correct. print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}") class ModularExp(cirq.ArithmeticOperation): def __init__( self, target: Sequence[cirq.Qid], exponent: Union[int, Sequence[cirq.Qid]], base: int, modulus: int ) -> None: if len(target) < modulus.bit_length(): raise ValueError(f'Register with {len(target)} qubits is too small ' f'for modulus {modulus}') self.target = target self.exponent = exponent self.base = base self.modulus = modulus def registers(self) -> Sequence[Union[int, Sequence[cirq.Qid]]]: return self.target, self.exponent, self.base, self.modulus def with_registers( self, *new_registers: Union[int, Sequence['cirq.Qid']], ) -> cirq.ArithmeticOperation: if len(new_registers) != 4: raise ValueError(f'Expected 4 registers (target, exponent, base, ' f'modulus), but got {len(new_registers)}') target, exponent, base, modulus = new_registers if not isinstance(target, Sequence): raise ValueError( f'Target must be a qubit register, got {type(target)}') if not isinstance(base, int): raise ValueError( f'Base must be a classical constant, got {type(base)}') if not isinstance(modulus, int): raise ValueError( f'Modulus must be a classical constant, got {type(modulus)}') return ModularExp(target, exponent, base, modulus) def apply(self, *register_values: int) -> int: assert len(register_values) == 4 target, exponent, base, modulus = register_values if target >= modulus: return target return (target * base**exponent) % modulus def _circuit_diagram_info_( self, args: cirq.CircuitDiagramInfoArgs, ) -> cirq.CircuitDiagramInfo: assert args.known_qubits is not None wire_symbols: List[str] = [] t, e = 0, 0 for qubit in args.known_qubits: if qubit in self.target: if t == 0: if isinstance(self.exponent, Sequence): e_str = 'e' else: e_str = str(self.exponent) wire_symbols.append( f'ModularExp(t*{self.base}**{e_str} % {self.modulus})') else: wire_symbols.append('t' + str(t)) t += 1 if isinstance(self.exponent, Sequence) and qubit in self.exponent: wire_symbols.append('e' + str(e)) e += 1 return cirq.CircuitDiagramInfo(wire_symbols=tuple(wire_symbols)) n = 15 L = n.bit_length() # The target register has L qubits. target = cirq.LineQubit.range(L) # The exponent register has 2L + 3 qubits. exponent = cirq.LineQubit.range(L, 3 * L + 3) # Display the total number of qubits to factor this n. print(f"To factor n = {n} which has L = {L} bits, we need 3L + 3 = {3 * L + 3} qubits.") def make_order_finding_circuit(x: int, n: int) -> cirq.Circuit: L = n.bit_length() target = cirq.LineQubit.range(L) exponent = cirq.LineQubit.range(L, 3 * L + 3) return cirq.Circuit( cirq.X(target[L - 1]), cirq.H.on_each(*exponent), ModularExp(target, exponent, x, n), cirq.qft(*exponent, inverse=True), cirq.measure(*exponent, key='exponent'), ) n = 15 x = 7 circuit = make_order_finding_circuit(x, n) print(circuit) circuit = make_order_finding_circuit(x=5, n=6) res = cirq.sample(circuit, repetitions=8) print("Raw measurements:") print(res) print("\nInteger in exponent register:") print(res.data) def binary_labels(num_qubits): return [bin(x)[2:].zfill(num_qubits) for x in range(2 ** num_qubits)] # Refactor this plot to use this cell's output # q = cirq.LineQubit.range(3) # circuit = cirq.Circuit([cirq.H.on_each(*q), cirq.measure(*q)]) # result = cirq.Simulator().run(circuit, repetitions=100) # _ = cirq.vis.plot_state_histogram(result, plt.subplot(), title = 'Integer in exponent Register', xlabel = 'Integer', ylabel = 'Count', tick_label=binary_labels(3)) def process_measurement(result: cirq.Result, x: int, n: int) -> Optional[int]: # Read the output integer of the exponent register. exponent_as_integer = result.data["exponent"][0] exponent_num_bits = result.measurements["exponent"].shape[1] eigenphase = float(exponent_as_integer / 2**exponent_num_bits) # Run the continued fractions algorithm to determine f = s / r. f = fractions.Fraction.from_float(eigenphase).limit_denominator(n) if f.numerator == 0: return None r = f.denominator if x**r % n != 1: return None return r n = 6 x = 5 print(f"Finding the order of x = {x} modulo n = {n}\n") measurement = cirq.sample(circuit, repetitions=1) print("Raw measurements:") print(measurement) print("\nInteger in exponent register:") print(measurement.data) r = process_measurement(measurement, x, n) print("\nOrder r =", r) if r is not None: print(f"x^r mod n = {x}^{r} mod {n} = {x**r % n}") def quantum_order_finder(x: int, n: int) -> Optional[int]: if x < 2 or n <= x or math.gcd(x, n) > 1: raise ValueError(f'Invalid x={x} for modulus n={n}.') circuit = make_order_finding_circuit(x, n) measurement = cirq.sample(circuit) return process_measurement(measurement, x, n) def find_factor_of_prime_power(n: int) -> Optional[int]: for k in range(2, math.floor(math.log2(n)) + 1): c = math.pow(n, 1 / k) c1 = math.floor(c) if c1**k == n: return c1 c2 = math.ceil(c) if c2**k == n: return c2 return None def find_factor( n: int, order_finder: Callable[[int, int], Optional[int]] = quantum_order_finder, max_attempts: int = 30 ) -> Optional[int]: if sympy.isprime(n): print("n is prime!") return None if n % 2 == 0: return 2 c = find_factor_of_prime_power(n) if c is not None: return c for _ in range(max_attempts): x = random.randint(2, n - 1) c = math.gcd(x, n) if 1 < c < n: return c r = order_finder(x, n) if r is None: continue if r % 2 != 0: continue y = x**(r // 2) % n assert 1 < y < n c = math.gcd(y - 1, n) if 1 < c < n: return c print(f"Failed to find a non-trivial factor in {max_attempts} attempts.") # return None # test with non-prime numbers only n = 184572 p = find_factor(n, order_finder=classical_order_finder) q = n // p p * q == n print("If p * q == n is True, then this answer is correct.") print("The result of " + str(p) + " * " + str(q) + " = "+ str(n) + " is " + str(p * q == n)) # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
https://github.com/lynnlangit/learning-quantum
lynnlangit
# Code blocks for qiskit notebook ## Block 1 - Setup import math import numpy as np from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit.algorithms import Shor ## Block 2 - Run N = 15 backend = Aer.get_backend('aer_simulator') quantum_instance = QuantumInstance(backend, shots=1024) shor = Shor(quantum_instance=quantum_instance) result = shor.factor(N) print(f"The list of factors of {N} as computed by the Shor's algorithm is {result.factors[0]}.") ## Block 3 - Eval Perf print(f'Computed of qubits for circuit: {4 * math.ceil(math.log(N, 2)) + 2}') print(f'Actual number of qubits of circuit: {shor.construct_circuit(N).num_qubits}') ## Block 4 - Version Info import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/lynnlangit/learning-quantum
lynnlangit
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() import math import numpy as np from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit.algorithms import Shor N = 15 backend = Aer.get_backend('aer_simulator') quantum_instance = QuantumInstance(backend, shots=1024) shor = Shor(quantum_instance=quantum_instance) result = shor.factor(N) print(f"The list of factors of {N} as computed by the Shor's algorithm is {result.factors[0]}.") print(f'Computed of qubits for circuit: {4 * math.ceil(math.log(N, 2)) + 2}') print(f'Actual number of qubits of circuit: {shor.construct_circuit(N).num_qubits}') %qiskit_version_table %qiskit_copyright
https://github.com/lynnlangit/learning-quantum
lynnlangit
# This cell is added by sphinx-gallery # It can be customized to whatever you like %matplotlib inline import pennylane as qml from pennylane import numpy as np dev1 = qml.device("default.qubit", wires=1) def circuit(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(dev1) def circuit(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=0) return qml.expval(qml.PauliZ(0)) print(circuit([0.54, 0.12])) dcircuit = qml.grad(circuit, argnum=0) print(dcircuit([0.54, 0.12])) @qml.qnode(dev1) def circuit2(phi1, phi2): qml.RX(phi1, wires=0) qml.RY(phi2, wires=0) return qml.expval(qml.PauliZ(0)) dcircuit = qml.grad(circuit2, argnum=[0, 1]) print(dcircuit(0.54, 0.12)) def cost(x): return circuit(x) init_params = np.array([0.011, 0.012]) print(cost(init_params)) # initialise the optimizer opt = qml.GradientDescentOptimizer(stepsize=0.4) # set the number of steps steps = 100 # set the initial parameter values params = init_params for i in range(steps): # update the circuit parameters params = opt.step(cost, params) if (i + 1) % 5 == 0: print("Cost after step {:5d}: {: .7f}".format(i + 1, cost(params))) print("Optimized rotation angles: {}".format(params))
https://github.com/lynnlangit/learning-quantum
lynnlangit
import numpy as np from qiskit.algorithms.linear_solvers.numpy_linear_solver import NumPyLinearSolver from qiskit.algorithms.linear_solvers.hhl import HHL matrix = np.array([[1, -1/3], [-1/3, 1]]) vector = np.array([1, 0]) naive_hhl_solution = HHL().solve(matrix, vector) classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) from qiskit.algorithms.linear_solvers.matrices.tridiagonal_toeplitz import TridiagonalToeplitz tridi_matrix = TridiagonalToeplitz(1, 1, -1 / 3) tridi_solution = HHL().solve(tridi_matrix, vector) print('classical state:', classical_solution.state) print('naive state:') print(naive_hhl_solution.state) print('tridiagonal state:') print(tridi_solution.state) print('classical Euclidean norm:', classical_solution.euclidean_norm) print('naive Euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal Euclidean norm:', tridi_solution.euclidean_norm) from qiskit.quantum_info import Statevector naive_sv = Statevector(naive_hhl_solution.state).data tridi_sv = Statevector(tridi_solution.state).data # Extract the right vector components. 1000 corresponds to the index 8 and 1001 corresponds to the index 9 naive_full_vector = np.array([naive_sv[8], naive_sv[9]]) tridi_full_vector = np.array([tridi_sv[8], tridi_sv[9]]) print('naive raw solution vector:', naive_full_vector) print('tridi raw solution vector:', tridi_full_vector) naive_full_vector = np.real(naive_full_vector) tridi_full_vector = np.real(tridi_full_vector) print('full naive solution vector:', naive_hhl_solution.euclidean_norm*naive_full_vector/np.linalg.norm(naive_full_vector)) print('full tridi solution vector:', tridi_solution.euclidean_norm*tridi_full_vector/np.linalg.norm(tridi_full_vector)) print('classical state:', classical_solution.state) from scipy.sparse import diags num_qubits = 2 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) # run the algorithms classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(num_qubits, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) print('classical euclidean norm:', classical_solution.euclidean_norm) print('naive euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal euclidean norm:', tridi_solution.euclidean_norm) from qiskit import transpile num_qubits = list(range(1,5)) a = 1 b = -1/3 i=1 # calculate the circuit depths for different number of qubits to compare the use of resources naive_depths = [] tridi_depths = [] for nb in num_qubits: matrix = diags([b, a, b], [-1, 0, 1], shape=(2**nb, 2**nb)).toarray() vector = np.array([1] + [0]*(2**nb -1)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(nb, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) naive_qc = transpile(naive_hhl_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) tridi_qc = transpile(tridi_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) naive_depths.append(naive_qc.depth()) tridi_depths.append(tridi_qc.depth()) i +=1 sizes = [str(2**nb)+"x"+str(2**nb) for nb in num_qubits] columns = ['size of the system', 'quantum_solution depth', 'tridi_solution depth'] data = np.array([sizes, naive_depths, tridi_depths]) row_format ="{:>23}" * (len(columns) + 2) for team, row in zip(columns, data): print(row_format.format(team, *row)) print('excess:', [naive_depths[i] - tridi_depths[i] for i in range(0, len(naive_depths))]) from qiskit.algorithms.linear_solvers.observables import AbsoluteAverage, MatrixFunctional num_qubits = 1 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) tridi_matrix = TridiagonalToeplitz(1, a, b) average_solution = HHL().solve(tridi_matrix, vector, AbsoluteAverage()) classical_average = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), AbsoluteAverage()) print('quantum average:', average_solution.observable) print('classical average:', classical_average.observable) print('quantum circuit results:', average_solution.circuit_results) observable = MatrixFunctional(1, 1 / 2) functional_solution = HHL().solve(tridi_matrix, vector, observable) classical_functional = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), observable) print('quantum functional:', functional_solution.observable) print('classical functional:', classical_functional.observable) print('quantum circuit results:', functional_solution.circuit_results) from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') hhl = HHL(1e-3, quantum_instance=backend) accurate_solution = hhl.solve(matrix, vector) classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) print(accurate_solution.euclidean_norm) print(classical_solution.euclidean_norm) from qiskit import QuantumRegister, QuantumCircuit import numpy as np t = 2 # This is not optimal; As an exercise, set this to the # value that will get the best results. See section 8 for solution. nqubits = 4 # Total number of qubits nb = 1 # Number of qubits representing the solution nl = 2 # Number of qubits representing the eigenvalues theta = 0 # Angle defining |b> a = 1 # Matrix diagonal b = -1/3 # Matrix off-diagonal # Initialize the quantum and classical registers qr = QuantumRegister(nqubits) # Create a Quantum Circuit qc = QuantumCircuit(qr) qrb = qr[0:nb] qrl = qr[nb:nb+nl] qra = qr[nb+nl:nb+nl+1] # State preparation. qc.ry(2*theta, qrb[0]) # QPE with e^{iAt} for qu in qrl: qc.h(qu) qc.p(a*t, qrl[0]) qc.p(a*t*2, qrl[1]) qc.u(b*t, -np.pi/2, np.pi/2, qrb[0]) # Controlled e^{iAt} on \lambda_{1}: params=b*t qc.p(np.pi/2,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Controlled e^{2iAt} on \lambda_{2}: params = b*t*2 qc.p(np.pi/2,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Inverse QFT qc.h(qrl[1]) qc.rz(-np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(-np.pi/4,qrl[0]) qc.h(qrl[0]) # Eigenvalue rotation t1=(-np.pi +np.pi/3 - 2*np.arcsin(1/3))/4 t2=(-np.pi -np.pi/3 + 2*np.arcsin(1/3))/4 t3=(np.pi -np.pi/3 - 2*np.arcsin(1/3))/4 t4=(np.pi +np.pi/3 + 2*np.arcsin(1/3))/4 qc.cx(qrl[1],qra[0]) qc.ry(t1,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t2,qra[0]) qc.cx(qrl[1],qra[0]) qc.ry(t3,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t4,qra[0]) qc.measure_all() print("Depth: %i" % qc.depth()) print("CNOTS: %i" % qc.count_ops()['cx']) qc.draw(fold=-1) from qiskit import BasicAer, ClassicalRegister, IBMQ from qiskit.compiler import transpile from qiskit.ignis.mitigation.measurement import (complete_meas_cal, # Measurement error mitigation functions CompleteMeasFitter, MeasurementFilter) provider = IBMQ.load_account() backend = provider.get_backend('ibmqx2') # calibrate using real hardware layout = [2,3,0,4] chip_qubits = 5 # Transpiled circuit for the real hardware qc_qa_cx = transpile(qc, backend=backend, initial_layout=layout) meas_cals, state_labels = complete_meas_cal(qubit_list=layout, qr=QuantumRegister(chip_qubits)) qcs = meas_cals + [qc_qa_cx] job = backend.run(qcs, shots=10)
https://github.com/lynnlangit/learning-quantum
lynnlangit
#!/usr/bin/env python # coding: utf-8 # # Solving linear systems of equations using HHL and its Qiskit implementation # In this tutorial, we introduce the HHL algorithm, derive the circuit, and implement it using Qiskit. We show how to run the HHL on a simulator and on a five qubit device. # ## Contents # 1. [Introduction](#introduction) # 2. [The HHL algorithm](#hhlalg) # 1. [Some mathematical background](#mathbackground) # 2. [Description of the HHL](#hhldescription) # 3. [Quantum Phase Estimation (QPE) within HHL](#qpe) # 4. [Non-exact QPE](#qpe2) # 3. [Example 1: 4-qubit HHL](#example1) # 4. [Qiskit Implementation](#implementation) # 1. [Running HHL on a simulator: general method](#implementationsim) # 2. [Running HHL on a real quantum device: optimised example](#implementationdev) # 5. [Problems](#problems) # 6. [References](#references) # ## 1. Introduction <a id='introduction'></a> # # Systems of linear equations arise naturally in many real-life applications in a wide range of areas, such as in the solution of Partial Differential Equations, the calibration of financial models, fluid simulation or numerical field calculation. The problem can be defined as, given a matrix $A\in\mathbb{C}^{N\times N}$ and a vector $\vec{b}\in\mathbb{C}^{N}$, find $\vec{x}\in\mathbb{C}^{N}$ satisfying $A\vec{x}=\vec{b}$ # # For example, take $N=2$, # # $$A = \begin{pmatrix}1 & -1/3\\-1/3 & 1 \end{pmatrix},\quad \vec{x}=\begin{pmatrix} x_{1}\\ x_{2}\end{pmatrix}\quad \text{and} \quad \vec{b}=\begin{pmatrix}1 \\ 0\end{pmatrix}$$ # # Then the problem can also be written as find $x_{1}, x_{2}\in\mathbb{C}$ such that # $$\begin{cases}x_{1} - \frac{x_{2}}{3} = 1 \\ -\frac{x_{1}}{3} + x_{2} = 0\end{cases} $$ # # A system of linear equations is called $s$-sparse if $A$ has at most $s$ non-zero entries per row or column. Solving an $s$-sparse system of size $N$ with a classical computer requires $\mathcal{ O }(Ns\kappa\log(1/\epsilon))$ running time using the conjugate gradient method <sup>[1](#conjgrad)</sup>. Here $\kappa$ denotes the condition number of the system and $\epsilon$ the accuracy of the approximation. # # The HHL is a quantum algorithm to estimate a function of the solution with running time complexity of $\mathcal{ O }(\log(N)s^{2}\kappa^{2}/\epsilon)$<sup>[2](#hhl)</sup> when $A$ is a Hermitian matrix under the assumptions of efficient oracles for loading the data, Hamiltonian simulation and computing a function of the solution. This is an exponential speed up in the size of the system, however one crucial remark to keep in mind is that the classical algorithm returns the full solution, while the HHL can only approximate functions of the solution vector. # ## 2. The HHL algorithm<a id='hhlalg'></a> # # ### A. Some mathematical background<a id='mathbackground'></a> # The first step towards solving a system of linear equations with a quantum computer is to encode the problem in the quantum language. By rescaling the system, we can assume $\vec{b}$ and $\vec{x}$ to be normalised and map them to the respective quantum states $|b\rangle$ and $|x\rangle$. Usually the mapping used is such that $i^{th}$ component of $\vec{b}$ (resp. $\vec{x}$) corresponds to the amplitude of the $i^{th}$ basis state of the quantum state $|b\rangle$ (resp. $|x\rangle$). From now on, we will focus on the rescaled problem # # $$ A|x\rangle=|b\rangle$$ # # Since $A$ is Hermitian, it has a spectral decomposition # $$ # A=\sum_{j=0}^{N-1}\lambda_{j}|u_{j}\rangle\langle u_{j}|,\quad \lambda_{j}\in\mathbb{ R } # $$ # where $|u_{j}\rangle$ is the $j^{th}$ eigenvector of $A$ with respective eigenvalue $\lambda_{j}$. Then, # $$ # A^{-1}=\sum_{j=0}^{N-1}\lambda_{j}^{-1}|u_{j}\rangle\langle u_{j}| # $$ # and the right hand side of the system can be written in the eigenbasis of $A$ as # $$ # |b\rangle=\sum_{j=0}^{N-1}b_{j}|u_{j}\rangle,\quad b_{j}\in\mathbb{ C } # $$ # It is useful to keep in mind that the goal of the HHL is to exit the algorithm with the readout register in the state # $$ # |x\rangle=A^{-1}|b\rangle=\sum_{j=0}^{N-1}\lambda_{j}^{-1}b_{j}|u_{j}\rangle # $$ # Note that here we already have an implicit normalisation constant since we are talking about a quantum state. # ### B. Description of the HHL algorithm <a id='hhldescription'></a> # # The algorithm uses three quantum registers, all of them set to $|0\rangle $ at the beginning of the algorithm. One register, which we will denote with the subindex $n_{l}$, is used to store a binary representation of the eigenvalues of $A$. A second register, denoted by $n_{b}$, contains the vector solution, and from now on $N=2^{n_{b}}$. There is an extra register, for the auxiliary qubits. These are qubits used as intermediate steps in the individual computations but will be ignored in the following description since they are set to $|0\rangle $ at the beginning of each computation and restored back to the $|0\rangle $ state at the end of the individual operation. # # The following is an outline of the HHL algorithm with a high-level drawing of the corresponding circuit. For simplicity all computations are assumed to be exact in the ensuing description, and a more detailed explanation of the non-exact case is given in Section [2.D.](#qpe2). # # <img src="images/hhlcircuit.png" width = "75%" height = "75%"> # # 1. Load the data $|b\rangle\in\mathbb{ C }^{N}$. That is, perform the transformation # $$ |0\rangle _{n_{b}} \mapsto |b\rangle _{n_{b}} $$ # 2. Apply Quantum Phase Estimation (QPE) with # $$ # U = e ^ { i A t } := \sum _{j=0}^{N-1}e ^ { i \lambda _ { j } t } |u_{j}\rangle\langle u_{j}| # $$ # The quantum state of the register expressed in the eigenbasis of $A$ is now # $$ # \sum_{j=0}^{N-1} b _ { j } |\lambda _ {j }\rangle_{n_{l}} |u_{j}\rangle_{n_{b}} # $$ # where $|\lambda _ {j }\rangle_{n_{l}}$ is the $n_{l}$-bit binary representation of $\lambda _ {j }$. # # 3. Add an auxiliary qubit and apply a rotation conditioned on $|\lambda_{ j }\rangle$, # $$ # \sum_{j=0}^{N-1} b _ { j } |\lambda _ { j }\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} \left( \sqrt { 1 - \frac { C^{2} } { \lambda _ { j } ^ { 2 } } } |0\rangle + \frac { C } { \lambda _ { j } } |1\rangle \right) # $$ # where $C$ is a normalisation constant, and, as expressed in the current form above, should be less than the smallest eigenvalue $\lambda_{min}$ in magnitude, i.e., $|C| < \lambda_{min}$. # # 4. Apply QPE$^{\dagger}$. Ignoring possible errors from QPE, this results in # $$ # \sum_{j=0}^{N-1} b _ { j } |0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} \left( \sqrt { 1 - \frac {C^{2} } { \lambda _ { j } ^ { 2 } } } |0\rangle + \frac { C } { \lambda _ { j } } |1\rangle \right) # $$ # # 5. Measure the auxiliary qubit in the computational basis. If the outcome is $1$, the register is in the post-measurement state # $$ # \left( \sqrt { \frac { 1 } { \sum_{j=0}^{N-1} \left| b _ { j } \right| ^ { 2 } / \left| \lambda _ { j } \right| ^ { 2 } } } \right) \sum _{j=0}^{N-1} \frac{b _ { j }}{\lambda _ { j }} |0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} # $$ # which up to a normalisation factor corresponds to the solution. # # 6. Apply an observable $M$ to calculate $F(x):=\langle x|M|x\rangle$. # ### C. Quantum Phase Estimation (QPE) within HHL <a id='qpe'></a> # # Quantum Phase Estimation is described in more detail in Chapter 3. However, since this quantum procedure is at the core of the HHL algorithm, we recall here the definition. Roughly speaking, it is a quantum algorithm which, given a unitary $U$ with eigenvector $|\psi\rangle_{m}$ and eigenvalue $e^{2\pi i\theta}$, finds $\theta$. We can formally define this as follows. # # **Definition:** Let $U\in\mathbb{ C }^{2^{m}\times 2^{m}}$ be unitary and let $|\psi\rangle_{m}\in\mathbb{ C }^{2^{m}}$ be one of its eigenvectors with respective eigenvalue $e^{2\pi i\theta}$. The **Quantum Phase Estimation** algorithm, abbreviated **QPE**, takes as inputs the unitary gate for $U$ and the state $|0\rangle_{n}|\psi\rangle_{m}$ and returns the state $|\tilde{\theta}\rangle_{n}|\psi\rangle_{m}$. Here $\tilde{\theta}$ denotes a binary approximation to $2^{n}\theta$ and the $n$ subscript denotes it has been truncated to $n$ digits. # $$ # \operatorname { QPE } ( U , |0\rangle_{n}|\psi\rangle_{m} ) = |\tilde{\theta}\rangle_{n}|\psi\rangle_{m} # $$ # # For the HHL we will use QPE with $U = e ^ { i A t }$, where $A$ is the matrix associated to the system we want to solve. In this case, # $$ # e ^ { i A t } = \sum_{j=0}^{N-1}e^{i\lambda_{j}t}|u_{j}\rangle\langle u_{j}| # $$ # Then, for the eigenvector $|u_{j}\rangle_{n_{b}}$, which has eigenvalue $e ^ { i \lambda _ { j } t }$, QPE will output $|\tilde{\lambda }_ { j }\rangle_{n_{l}}|u_{j}\rangle_{n_{b}}$. Where $\tilde{\lambda }_ { j }$ represents an $n_{l}$-bit binary approximation to $2^{n_l}\frac{\lambda_ { j }t}{2\pi}$. Therefore, if each $\lambda_{j}$ can be exactly represented with $n_{l}$ bits, # $$ # \operatorname { QPE } ( e ^ { i A t } , \sum_{j=0}^{N-1}b_{j}|0\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} ) = \sum_{j=0}^{N-1}b_{j}|\lambda_{j}\rangle_{n_{l}}|u_{j}\rangle_{n_{b}} # $$ # ### D. Non-exact QPE <a id='qpe2'></a> # # In reality, the quantum state of the register after applying QPE to the initial state is # $$ # \sum _ { j=0 }^{N-1} b _ { j } \left( \sum _ { l = 0 } ^ { 2 ^ { n_{l} } - 1 } \alpha _ { l | j } |l\rangle_{n_{l}} \right)|u_{j}\rangle_{n_{b}} # $$ # where # $$ # \alpha _ { l | j } = \frac { 1 } { 2 ^ { n_{l} } } \sum _ { k = 0 } ^ { 2^{n_{l}}- 1 } \left( e ^ { 2 \pi i \left( \frac { \lambda _ { j } t } { 2 \pi } - \frac { l } { 2 ^ { n_{l} } } \right) } \right) ^ { k } # $$ # # Denote by $\tilde{\lambda_{j}}$ the best $n_{l}$-bit approximation to $\lambda_{j}$, $1\leq j\leq N$. Then we can relabel the $n_{l}$-register so that $\alpha _ { l | j }$ denotes the amplitude of $|l + \tilde { \lambda } _ { j } \rangle_{n_{l}}$. So now, # $$ # \alpha _ { l | j } : = \frac { 1 } { 2 ^ { n_{l}} } \sum _ { k = 0 } ^ { 2 ^ { n_{l} } - 1 } \left( e ^ { 2 \pi i \left( \frac { \lambda _ { j } t } { 2 \pi } - \frac { l + \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } } \right) } \right) ^ { k } # $$ # If each $\frac { \lambda _ { j } t } { 2 \pi }$ can be represented exactly with $n_{l}$ binary bits, then $\frac { \lambda _ { j } t } { 2 \pi }=\frac { \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } }$ $\forall j$. Therefore in this case $\forall j$, $1\leq j \leq N$, it holds that $\alpha _ { 0 | j } = 1$ and $\alpha _ { l | j } = 0 \quad \forall l \neq 0$. Only in this case we can write that the state of the register after QPE is # $$ # \sum_{j=0}^{N-1} b _ { j } |\lambda _ {j }\rangle_{n_{l}} |u_{j}\rangle_{n_{b}} # $$ # Otherwise, $|\alpha _ { l | j }|$ is large if and only if $\frac { \lambda _ { j } t } { 2 \pi } \approx \frac { l + \tilde { \lambda } _ { j } } { 2 ^ { n_{l} } }$ and the state of the register is # $$ # \sum _ { j=0 }^{N-1} \sum _ { l = 0 } ^ { 2 ^ { n_{l} } - 1 } \alpha _ { l | j } b _ { j }|l\rangle_{n_{l}} |u_{j}\rangle_{n_{b}} # $$ # ## 3. Example: 4-qubit HHL<a id='example1'></a> # # Let's take the small example from the introduction to illustrate the algorithm. That is, # $$A = \begin{pmatrix}1 & -1/3\\-1/3 & 1 \end{pmatrix}\quad \text{and} \quad |b\rangle=\begin{pmatrix}1 \\ 0\end{pmatrix}$$ # # We will use $n_{b}=1$ qubit to represent $|b\rangle$, and later the solution $|x\rangle$, $n_{l}=2$ qubits to store the binary representation of the eigenvalues and $1$ auxiliary qubit to store whether the conditioned rotation, hence the algorithm, was successful. # # For the purpose of illustrating the algorithm, we will cheat a bit and calculate the eigenvalues of $A$ to be able to choose $t$ to obtain an exact binary representation of the rescaled eigenvalues in the $n_{l}$-register. However, keep in mind that for the HHL algorithm implementation one does not need previous knowledge of the eigenvalues. Having said that, a short calculation will give # $$\lambda_{1} = 2/3\quad\text{and}\quad\lambda_{2}=4/3$$ # # Recall from the previous section that the QPE will output an $n_{l}$-bit ($2$-bit in this case) binary approximation to $\frac{\lambda_ { j }t}{2\pi}$. Therefore, if we set # $$t=2\pi\cdot \frac{3}{8}$$ # the QPE will give a $2$-bit binary approximation to # $$\frac{\lambda_ { 1 }t}{2\pi} = 1/4\quad\text{and}\quad\frac{\lambda_ { 2 }t}{2\pi}=1/2$$ # which is, respectively, # $$|01\rangle_{n_{l}}\quad\text{and}\quad|10\rangle_{n_{l}}$$ # # The eigenvectors are, respectively, # $$|u_{1}\rangle=\begin{pmatrix}1 \\ -1\end{pmatrix}\quad\text{and}\quad|u_{2}\rangle=\begin{pmatrix}1 \\ 1\end{pmatrix}$$ # Again, keep in mind that one does not need to compute the eigenvectors for the HHL implementation. In fact, a general Hermitian matrix $A$ of dimension $N$ can have up to $N$ different eigenvalues, therefore calculating them would take $\mathcal{O}(N)$ time and the quantum advantage would be lost. # # We can then write $|b\rangle$ in the eigenbasis of $A$ as # $$|b\rangle _{n_{b}}=\sum_{j=1}^{2}\frac{1}{\sqrt{2}}|u_{j}\rangle _{n_{b}}$$ # # Now we are ready to go through the different steps of the HHL algorithm. # # 1. State preparation in this example is trivial since $|b\rangle=|0\rangle$. # 2. Applying QPE will yield # $$ # \frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle # $$ # 3. Conditioned rotation with $C=1/8$ that is less than the smallest (rescaled) eigenvalue of $\frac {1} {4}$. Note, the contant $C$ here needs to be chosen such that it is less than the smallest (rescaled) eigenvalue of $\frac {1} {4}$ but as large as possible so that when the auxiliary qubit is measured, the probabilit of it being in the state $|1>$ is large. # $$\frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { (1/8)^{2} } {(1/4)^{2} } } |0\rangle + \frac { 1/8 } { 1/4 } |1\rangle \right) + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { (1/8)^{2} } {(1/2)^{2} } } |0\rangle + \frac { 1/8 } { 1/2 } |1\rangle \right) # $$ # $$ # =\frac{1}{\sqrt{2}}|01\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { 1 } {4 } } |0\rangle + \frac { 1 } { 2 } |1\rangle \right) + \frac{1}{\sqrt{2}}|10\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { 1 } {16 } } |0\rangle + \frac { 1 } { 4 } |1\rangle \right) # $$ # 4. After applying QPE$^{\dagger}$ the quantum computer is in the state # $$ # \frac{1}{\sqrt{2}}|00\rangle|u_{1}\rangle\left( \sqrt { 1 - \frac { 1 } {4 } } |0\rangle + \frac { 1 } { 2 } |1\rangle \right) + \frac{1}{\sqrt{2}}|00\rangle|u_{2}\rangle\left( \sqrt { 1 - \frac { 1 } {16 } } |0\rangle + \frac { 1 } { 4 } |1\rangle \right) # $$ # 5. On outcome $1$ when measuring the auxiliary qubit, the state is # $$ # \frac{\frac{1}{\sqrt{2}}|00\rangle|u_{1}\rangle\frac { 1 } { 2 } |1\rangle + \frac{1}{\sqrt{2}}|00\rangle|u_{2}\rangle\frac { 1 } { 4 } |1\rangle}{\sqrt{5/32}} # $$ # A quick calculation shows that # $$ # \frac{\frac{1}{2\sqrt{2}}|u_{1}\rangle+ \frac{1}{4\sqrt{2}}|u_{2}\rangle}{\sqrt{5/32}} = \frac{|x\rangle}{||x||} # $$ # 6. Without using extra gates, we can compute the norm of $|x\rangle$: it is the probability of measuring $1$ in the auxiliary qubit from the previous step. # $$ # P(|1\rangle) = \left(\frac{1}{2\sqrt{2}}\right)^{2} + \left(\frac{1}{4\sqrt{2}}\right)^{2} = \frac{5}{32} = ||x||^{2} # $$ # # # ## 4. Qiskit Implementation<a id='implementation'></a> # Now that we have analytically solved the problem from the example we are going to use it to illustrate how to run the HHL on a quantum simulator and on the real hardware. For the quantum simulator, Qiskit already provides an implementation of the HHL algorithm requiring only the matrix $A$ and $|b\rangle$ as inputs in the simplest example. Although we can give the algorithm a general Hermitian matrix and an arbitrary initial state as NumPy arrays, in these cases the quantum algorithm will not achieve an exponential speedup. This is because the default implementation is exact and therefore exponential in the number of qubits (there is no algorithm that can prepare exactly an arbitrary quantum state using polynomial resources in the number of qubits or that can perform exactly the operation $e^{iAt}$ for some general Hermitian matrix $A$ using polynomial resources in the number of qubits). If we know an efficient implementation for a particular problem, the matrix and/or the vector can be given as `QuantumCircuit` objects. Alternatively, there's already an efficient implementation for tridiagonal Toeplitz matrices and in the future there might be more. # # However,at the time of writing the existing quantum computers are noisy and can only run small circuits. Therefore, in Section [4.B.](#implementationdev) we will see an optimised circuit that can be used for a class of problems to which our example belongs and mention the existing procedures to deal with noise in quantum computers. # ## A. Running HHL on a simulator: general method<a id='implementationsim'></a> # The interface for all algorithms to solve the linear system problem is `LinearSolver`. The problem to be solved is only specified when the `solve()` method is called: # ```python # LinearSolver(...).solve(matrix, vector) # ``` # # The simplest implementation takes the matrix and the vector as NumPy arrays. Below we also create a `NumPyLinearSolver` (the classical algorithm) to validate our solutions. # In[1]: ###### see this link to setup Qiskit --> https://qiskit.org/textbook/ch-prerequisites/setting-the-environment.html ##### import numpy as np from qiskit.algorithms.linear_solvers.numpy_linear_solver import NumPyLinearSolver from qiskit.algorithms.linear_solvers.hhl import HHL matrix = np.array([[1, -1/3], [-1/3, 1]]) vector = np.array([1, 0]) naive_hhl_solution = HHL().solve(matrix, vector) # For the classical solver we need to rescale the right hand side (i.e. `vector / np.linalg.norm(vector)`) to take into account the renormalisation that occurs once `vector` is encoded in a quantum state within HHL. # In[2]: classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) # The `linear_solvers` package contains a folder called `matrices` intended to be a placeholder for efficient implementations of particular types of matrices. At the time of writing the only truly efficient implementation it contains (i.e. complexity scaling polynomially in the number of qubits) is the `TridiagonalToeplitz` class. Tridiagonal Toeplitz symmetric real matrices are of the following form # $$A = \begin{pmatrix}a & b & 0 & 0\\b & a & b & 0 \\ 0 & b & a & b \\ 0 & 0 & b & a \end{pmatrix}, a,b\in\mathbb{R}$$ # (note that in this setting we do not consider non symmetric matrices since the HHL algorithm assumes that the input matrix is Hermitian). # # Since the matrix $A$ from our example is of this form we can create an instance of `TridiagonalToeplitz(num_qubits, a, b)` and compare the results to solving the system with an array as input. # In[3]: from qiskit.algorithms.linear_solvers.matrices.tridiagonal_toeplitz import TridiagonalToeplitz tridi_matrix = TridiagonalToeplitz(1, 1, -1 / 3) tridi_solution = HHL().solve(tridi_matrix, vector) # Recall that the HHL algorithm can find a solution exponentially faster in the size of the system than their classical counterparts (i.e. logarithmic complexity instead of polynomial). However the cost for this exponential speedup is that we do not obtain the full solution vector. # Instead, we obtain a quantum state representing the vector $x$ and learning all the components of this vector would take a linear time in its dimension, diminishing any speedup obtained by the quantum algorithm. # # Therefore, we can only compute functions from $x$ (the so called observables) to learn information about the solution. # This is reflected in the `LinearSolverResult` object returned by `solve()`, which contains the following properties # - `state`: either the circuit that prepares the solution or the solution as a vector # - `euclidean_norm`: the euclidean norm if the algorithm knows how to calculate it # - `observable`: the (list of) calculated observable(s) # - `circuit_results`: the observable results from the (list of) circuit(s) # # Let's ignore `observable` and `circuit_results` for the time being and check the solutions we obtained before. # # First, `classical_solution` was the result from a classical algorithm, so if we call `.state` it will return an array: # In[4]: print('classical state:', classical_solution.state) # Our other two examples were quantum algorithms, hence we can only access to the quantum state. This is achieved by returning the quantum circuit that prepares the solution state: # In[5]: print('naive state:') print(naive_hhl_solution.state) print('tridiagonal state:') print(tridi_solution.state) # Recall that the Euclidean norm for a vector $\mathbf{x}=(x_1,\dots,x_N)$ is defined as $||\mathbf{x}||=\sqrt{\sum_{i=1}^N x_i^2}$. Therefore, the probability of measuring $1$ in the auxiliary qubit from Step $5$ in Section B is the squared norm of $\mathbf{x}$. This means that the HHL algorithm can always calculate the euclidean norm of the solution and we can compare the accuracy of the results: # In[6]: print('classical Euclidean norm:', classical_solution.euclidean_norm) print('naive Euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal Euclidean norm:', tridi_solution.euclidean_norm) # Comparing the solution vectors componentwise is more tricky, reflecting again the idea that we cannot obtain the full solution vector from the quantum algorithm. However, for educational purposes we can check that indeed the different solution vectors obtained are a good approximation at the vector component level as well. # # To do so first we need to use `Statevector` from the `quantum_info` package and extract the right vector components, i.e. those corresponding to the ancillary qubit (bottom in the circuits) being $1$ and the work qubits (the two middle in the circuits) being $0$. Thus, we are interested in the states `1000` and `1001`, corresponding to the first and second components of the solution vector respectively. # In[7]: from qiskit.quantum_info import Statevector naive_sv = Statevector(naive_hhl_solution.state).data tridi_sv = Statevector(tridi_solution.state).data # Extract the right vector components. 1000 corresponds to the index 8 and 1001 corresponds to the index 9 naive_full_vector = np.array([naive_sv[8], naive_sv[9]]) tridi_full_vector = np.array([tridi_sv[8], tridi_sv[9]]) print('naive raw solution vector:', naive_full_vector) print('tridi raw solution vector:', tridi_full_vector) # At a first glance it might seem that this is wrong because the components are complex numbers instead of reals. However note that the imaginary part is very small, most likely due to computer accuracy, and can be disregarded in this case. # In[8]: naive_full_vector = np.real(naive_full_vector) tridi_full_vector = np.real(tridi_full_vector) # Next, we will divide the vectors by their respective norms to suppress any constants coming from the different parts of the circuits. The full solution vector can then be recovered by multiplying these normalised vectors by the respective Euclidean norms calculated above: # In[9]: print('full naive solution vector:', naive_hhl_solution.euclidean_norm*naive_full_vector/np.linalg.norm(naive_full_vector)) print('full tridi solution vector:', tridi_solution.euclidean_norm*tridi_full_vector/np.linalg.norm(tridi_full_vector)) print('classical state:', classical_solution.state) # It should not come as a surprise that `naive_hhl_solution` is exact because all the default methods used are exact. However, `tridi_solution` is exact only in the $2\times 2$ system size case. For larger matrices it will be an approximation, as shown in the slightly larger example below. # In[10]: from scipy.sparse import diags num_qubits = 2 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) # run the algorithms classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(num_qubits, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) print('classical euclidean norm:', classical_solution.euclidean_norm) print('naive euclidean norm:', naive_hhl_solution.euclidean_norm) print('tridiagonal euclidean norm:', tridi_solution.euclidean_norm) # We can also compare the difference in resources from the exact method and the efficient implementation. The $2\times 2$ system size is again special in that the exact algorithm requires less resources, but as we increase the system size, we can see that indeed the exact method scales exponentially in the number of qubits while `TridiagonalToeplitz` is polynomial. # In[11]: from qiskit import transpile num_qubits = list(range(1,5)) a = 1 b = -1/3 i=1 # calculate the circuit depths for different number of qubits to compare the use of resources naive_depths = [] tridi_depths = [] for nb in num_qubits: matrix = diags([b, a, b], [-1, 0, 1], shape=(2**nb, 2**nb)).toarray() vector = np.array([1] + [0]*(2**nb -1)) naive_hhl_solution = HHL().solve(matrix, vector) tridi_matrix = TridiagonalToeplitz(nb, a, b) tridi_solution = HHL().solve(tridi_matrix, vector) naive_qc = transpile(naive_hhl_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) tridi_qc = transpile(tridi_solution.state,basis_gates=['id', 'rz', 'sx', 'x', 'cx']) naive_depths.append(naive_qc.depth()) tridi_depths.append(tridi_qc.depth()) i +=1 # In[ ]: sizes = [str(2**nb)+"x"+str(2**nb) for nb in num_qubits] columns = ['size of the system', 'quantum_solution depth', 'tridi_solution depth'] data = np.array([sizes, naive_depths, tridi_depths]) row_format ="{:>23}" * (len(columns) + 2) for team, row in zip(columns, data): print(row_format.format(team, *row)) # The reason the implementation still seems to need exponential resources is because the current conditioned rotation implementation (step 3 from Section 2.B) is exact (i.e. needs exponential resources in $n_l$). Instead we can calculate how many more resources the default implementation needs compared to Tridiagonal - since they only differ in how they implement $e^{iAt}$: # In[13]: print('excess:', [naive_depths[i] - tridi_depths[i] for i in range(0, len(naive_depths))]) # In the near future the plan is to integrate `qiskit.circuit.library.arithmetics.PiecewiseChebyshev` to obtain a polynomial implementation of the conditioned rotation as well. # # Now we can return to the topic of observables and find out what the `observable` and `circuit_results` properties contain. # # The way to compute functions of the solution vector $\mathbf{x}$ is through giving the `.solve()` method a `LinearSystemObservable` as input. There are are two types of available `LinearSystemObservable` which can be given as input: # In[12]: from qiskit.algorithms.linear_solvers.observables import AbsoluteAverage, MatrixFunctional # For a vector $\mathbf{x}=(x_1,...,x_N)$, the `AbsoluteAverage` observable computes $|\frac{1}{N}\sum_{i=1}^{N}x_i|$. # In[13]: num_qubits = 1 matrix_size = 2 ** num_qubits # entries of the tridiagonal Toeplitz symmetric matrix a = 1 b = -1/3 matrix = diags([b, a, b], [-1, 0, 1], shape=(matrix_size, matrix_size)).toarray() vector = np.array([1] + [0]*(matrix_size - 1)) tridi_matrix = TridiagonalToeplitz(1, a, b) average_solution = HHL().solve(tridi_matrix, vector, AbsoluteAverage()) classical_average = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), AbsoluteAverage()) print('quantum average:', average_solution.observable) print('classical average:', classical_average.observable) print('quantum circuit results:', average_solution.circuit_results) # The `MatrixFunctional` observable computes $\mathbf{x}^T B \mathbf{x}$ for a vector $\mathbf{x}$ and a tridiagonal symmetric Toeplitz matrix $B$. The class takes the main and off diagonal values of the matrix for its constuctor method. # In[14]: observable = MatrixFunctional(1, 1 / 2) functional_solution = HHL().solve(tridi_matrix, vector, observable) classical_functional = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector), observable) print('quantum functional:', functional_solution.observable) print('classical functional:', classical_functional.observable) print('quantum circuit results:', functional_solution.circuit_results) # Therefore, `observable` contains the final value of the function on $\mathbf{x}$, while `circuit_results` contains the raw values obtained from the circuit and used to process the result of `observable`. # # This 'how to process the result' is better explained by looking at what arguments `.solve()` takes. The `solve()` method accepts up to five arguments: # ```python # def solve(self, matrix: Union[np.ndarray, QuantumCircuit], # vector: Union[np.ndarray, QuantumCircuit], # observable: Optional[Union[LinearSystemObservable, BaseOperator, # List[BaseOperator]]] = None, # post_rotation: Optional[Union[QuantumCircuit, List[QuantumCircuit]]] = None, # post_processing: Optional[Callable[[Union[float, List[float]]], # Union[float, List[float]]]] = None) \ # -> LinearSolverResult: # ``` # The first two are the matrix defining the linear system and the vector right hand side of the equation, which we have already covered. The remaining parameters concern the (list of) observable(s) to be computed out of the solution vector $x$, and can be specified in two different ways. One option is to give as the third and last parameter a (list of) `LinearSystemObservable`(s). Alternatively, we can give our own implementations of the `observable`, `post_rotation` and `post_processing`, where # - `observable` is the operator to compute the expected value of the observable and can be e.g. a `PauliSumOp` # - `post_rotation` is the circuit to be applied to the solution to extract information if additional gates are needed. # - `post_processing` is the function to compute the value of the observable from the calculated probabilities. # # In other words, there will be as many `circuit_results` as `post_rotation` circuits, and `post_processing` is telling the algorithm how to use the values we see when we print `circuit_results` to obtain the value we see when we print `observable`. # # Finally, the `HHL` class accepts the following parameters in its constructor method: # - error tolerance : the accuracy of the approximation of the solution, the default is `1e-2` # - expectation : how the expectation values are evaluated, the default is `PauliExpectation` # - quantum instance: the `QuantumInstance` or backend, the default is a `Statevector` simulation # In[15]: from qiskit import BasicAer backend = BasicAer.get_backend('qasm_simulator') hhl = HHL(1e-3, quantum_instance=backend) accurate_solution = hhl.solve(matrix, vector) classical_solution = NumPyLinearSolver().solve(matrix, vector / np.linalg.norm(vector)) print(accurate_solution.euclidean_norm) print(classical_solution.euclidean_norm) # ## B. Running HHL on a real quantum device: optimised example<a id='implementationdev'></a> # In the previous section we ran the standard algorithm provided in Qiskit and saw that it uses $7$ qubits, has a depth of ~$100$ gates and requires a total of $54$ CNOT gates. These numbers are not feasible for the current available hardware, therefore we need to decrease these quantities. In particular, the goal will be to reduce the number of CNOTs by a factor of $5$ since they have worse fidelity than single-qubit gates. Furthermore, we can reduce the number of qubits to $4$ as was the original statement of the problem: the Qiskit method was written for a general problem and that is why it requires $3$ additional auxiliary qubits. # # However, solely decreasing the number of gates and qubits will not give a good approximation to the solution on real hardware. This is because there are two sources of errors: those that occur during the run of the circuit and readout errors. # # Qiskit provides a module to mitigate the readout errors by individually preparing and measuring all basis states, a detailed treatment on the topic can be found in the paper by Dewes et al.<sup>[3](#readouterr)</sup> To deal with the errors occurring during the run of the circuit, Richardson extrapolation can be used to calculate the error to the zero limit by running the circuit three times, each replacing each CNOT gate by $1$, $3$ and $5$ CNOTs respectively<sup>[4](#richardson)</sup>. The idea is that theoretically the three circuits should produce the same result, but in real hardware adding CNOTs means amplifying the error. Since we know that we have obtained results with an amplified error, and we can estimate by how much the error was amplified in each case, we can recombine the quantities to obtain a new result that is a closer approximation to the analytic solution than any of the previous obtained values. # # Below we give the optimised circuit that can be used for any problem of the form # $$A = \begin{pmatrix}a & b\\b & a \end{pmatrix}\quad \text{and} \quad |b\rangle=\begin{pmatrix}\cos(\theta) \\ \sin(\theta)\end{pmatrix},\quad a,b,\theta\in\mathbb{R}$$ # # The following optimisation was extracted from a work on the HHL for tridiagonal symmetric matrices<sup>[[5]](#tridi)</sup>, this particular circuit was derived with the aid of the UniversalQCompiler software<sup>[[6]](#qcompiler)</sup>. # # In[16]: from qiskit import QuantumRegister, QuantumCircuit import numpy as np t = 2 # This is not optimal; As an exercise, set this to the # value that will get the best results. See section 8 for solution. nqubits = 4 # Total number of qubits nb = 1 # Number of qubits representing the solution nl = 2 # Number of qubits representing the eigenvalues theta = 0 # Angle defining |b> a = 1 # Matrix diagonal b = -1/3 # Matrix off-diagonal # Initialize the quantum and classical registers qr = QuantumRegister(nqubits) # Create a Quantum Circuit qc = QuantumCircuit(qr) qrb = qr[0:nb] qrl = qr[nb:nb+nl] qra = qr[nb+nl:nb+nl+1] # State preparation. qc.ry(2*theta, qrb[0]) # QPE with e^{iAt} for qu in qrl: qc.h(qu) qc.p(a*t, qrl[0]) qc.p(a*t*2, qrl[1]) qc.u(b*t, -np.pi/2, np.pi/2, qrb[0]) # Controlled e^{iAt} on \lambda_{1}: params=b*t qc.p(np.pi/2,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[0],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Controlled e^{2iAt} on \lambda_{2}: params = b*t*2 qc.p(np.pi/2,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(params,qrb[0]) qc.cx(qrl[1],qrb[0]) qc.ry(-params,qrb[0]) qc.p(3*np.pi/2,qrb[0]) # Inverse QFT qc.h(qrl[1]) qc.rz(-np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(np.pi/4,qrl[1]) qc.cx(qrl[0],qrl[1]) qc.rz(-np.pi/4,qrl[0]) qc.h(qrl[0]) # Eigenvalue rotation t1=(-np.pi +np.pi/3 - 2*np.arcsin(1/3))/4 t2=(-np.pi -np.pi/3 + 2*np.arcsin(1/3))/4 t3=(np.pi -np.pi/3 - 2*np.arcsin(1/3))/4 t4=(np.pi +np.pi/3 + 2*np.arcsin(1/3))/4 qc.cx(qrl[1],qra[0]) qc.ry(t1,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t2,qra[0]) qc.cx(qrl[1],qra[0]) qc.ry(t3,qra[0]) qc.cx(qrl[0],qra[0]) qc.ry(t4,qra[0]) qc.measure_all() print("Depth: %i" % qc.depth()) print("CNOTS: %i" % qc.count_ops()['cx']) qc.draw(fold=-1) # The code below takes as inputs our circuit, the real hardware backend and the set of qubits we want to use, and returns and instance that can be run on the specified device. Creating the circuits with $3$ and $5$ CNOTs is the same but calling the transpile method with the right quantum circuit. # # Real hardware devices need to be recalibrated regularly, and the fidelity of a specific qubit or gate can change over time. Furthermore, different chips have different connectivities. If we try to run a circuit that performs a two-qubit gate between two qubits that are not connected on the specified device, the transpiler will add SWAP gates. Therefore it is good practice to check with the IBM Quantum Experience webpage<sup>[[7]](#qexperience)</sup> before running the following code and choose a set of qubits with the right connectivity and lowest error rates at the given time. # In[17]: from qiskit import BasicAer, ClassicalRegister, IBMQ from qiskit.compiler import transpile from qiskit.ignis.mitigation.measurement import (complete_meas_cal, # Measurement error mitigation functions CompleteMeasFitter, MeasurementFilter) provider = IBMQ.load_account() backend = provider.get_backend('ibmqx2') # calibrate using real hardware layout = [2,3,0,4] chip_qubits = 5 # Transpiled circuit for the real hardware qc_qa_cx = transpile(qc, backend=backend, initial_layout=layout) # The next step is to create the extra circuits used to mitigate the readout errors<sup>[[3]](#readouterr)</sup>. # In[18]: meas_cals, state_labels = complete_meas_cal(qubit_list=layout, qr=QuantumRegister(chip_qubits)) qcs = meas_cals + [qc_qa_cx] job = backend.run(qcs, shots=10) # The following plot<sup>[[5]](#tridi)</sup>, shows the results from running the circuit above on real hardware for $10$ different initial states. The $x$-axis represents the angle $\theta$ defining the initial state in each case. The results where obtained after mitigating the readout error and then extrapolating the errors arising during the run of the circuit from the results with the circuits with $1$, $3$ and $5$ CNOTs. # # <img src="images/norm_public.png"> # # Compare to the results without error mitigation nor extrapolation from the CNOTs<sup>[5](#tridi)</sup>. # # <img src="images/noerrmit_public.png"> # ## 8. Problems<a id='problems'></a> # ##### Real hardware: # # 1. Set the time parameter for the optimised example. # # <details> # <summary> Solution (Click to expand)</summary> # t = 2.344915690192344 # # The best result is to set it so that the smallest eigenvalue can be represented exactly, since it's inverse will have the largest contribution in the solution # </details> # # 2. Create transpiled circuits for $3$ and $5$ CNOTs from a given circuit 'qc'. When creating the circuits you will have to add barriers so that these consecutive CNOT gates do not get cancelled when using the transpile() method. # 3. Run your circuits on the real hardware and apply a quadratic fit to the results to obtain the extrapolated value. # ## 9. References<a id='references'></a> # 1. J. R. Shewchuk. An Introduction to the Conjugate Gradient Method Without the Agonizing Pain. Technical Report CMU-CS-94-125, School of Computer Science, Carnegie Mellon University, Pittsburgh, Pennsylvania, March 1994.<a id='conjgrad'></a> # 2. A. W. Harrow, A. Hassidim, and S. Lloyd, “Quantum algorithm for linear systems of equations,” Phys. Rev. Lett. 103.15 (2009), p. 150502.<a id='hhl'></a> # 3. A. Dewes, F. R. Ong, V. Schmitt, R. Lauro, N. Boulant, P. Bertet, D. Vion, and D. Esteve, “Characterization of a two-transmon processor with individual single-shot qubit readout,” Phys. Rev. Lett. 108, 057002 (2012). <a id='readouterr'></a> # 4. N. Stamatopoulos, D. J. Egger, Y. Sun, C. Zoufal, R. Iten, N. Shen, and S. Woerner, “Option Pricing using Quantum Computers,” arXiv:1905.02666 . <a id='richardson'></a> # 5. A. Carrera Vazquez, A. Frisch, D. Steenken, H. S. Barowski, R. Hiptmair, and S. Woerner, “Enhancing Quantum Linear System Algorithm by Richardson Extrapolation,” (to be included).<a id='tridi'></a> # 6. R. Iten, O. Reardon-Smith, L. Mondada, E. Redmond, R. Singh Kohli, R. Colbeck, “Introduction to UniversalQCompiler,” arXiv:1904.01072 .<a id='qcompiler'></a> # 7. https://quantum-computing.ibm.com/ .<a id='qexperience'></a> # 8. D. Bucher, J. Mueggenburg, G. Kus, I. Haide, S. Deutschle, H. Barowski, D. Steenken, A. Frisch, "Qiskit Aqua: Solving linear systems of equations with the HHL algorithm" https://github.com/Qiskit/qiskit-tutorials/blob/master/legacy_tutorials/aqua/linear_systems_of_equations.ipynb
https://github.com/lynnlangit/learning-quantum
lynnlangit
import numpy as np v = np.array([1,2]) A = np.array([[2,3], [5,2]]) t = A@v print (t) import numpy as np v = np.array([1,2]) A = np.array([[2,3], [5,2], [1,1]]) t = A@v print (t) import numpy as np v = np.array([1,2]) A = np.array([[1,2], [2,1]]) t = A@v print (t) import numpy as np import matplotlib.pyplot as plt %matplotlib inline v = np.array([1,0]) A = np.array([[2,0], [0,2]]) t = A@v print (t) # Plot v and t vecs = np.array([t,v]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['blue'], scale=10) plt.quiver(*origin, *t, color=['orange'], scale=10) plt.show() import numpy as np import matplotlib.pyplot as plt %matplotlib inline v = np.array([1,0]) A = np.array([[0,-1], [1,0]]) t = A@v print (t) # Plot v and t vecs = np.array([v,t]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t, color=['blue'], scale=10) plt.show() import numpy as np import matplotlib.pyplot as plt %matplotlib inline v = np.array([1,0]) A = np.array([[2,1], [1,2]]) t = A@v print (t) # Plot v and t vecs = np.array([v,t]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t, color=['blue'], scale=10) plt.show() import numpy as np import matplotlib.pyplot as plt %matplotlib inline v = np.array([1,1]) A = np.array([[5,2], [3,1]]) b = np.array([-2,-6]) t = A@v + b print (t) # Plot v and t vecs = np.array([v,t]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=15) plt.quiver(*origin, *t, color=['blue'], scale=15) plt.show() import numpy as np import matplotlib.pyplot as plt %matplotlib inline v = np.array([1,0]) A = np.array([[2,0], [0,2]]) t1 = A@v print (t1) t2 = 2*v print (t2) fig = plt.figure() a=fig.add_subplot(1,1,1) # Plot v and t1 vecs = np.array([t1,v]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t1, color=['blue'], scale=10) plt.show() a=fig.add_subplot(1,2,1) # Plot v and t2 vecs = np.array([t2,v]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t2, color=['blue'], scale=10) plt.show() import numpy as np A = np.array([[2,0], [0,3]]) eVals, eVecs = np.linalg.eig(A) print(eVals) print(eVecs) vec1 = eVecs[:,0] lam1 = eVals[0] print('Matrix A:') print(A) print('-------') print('lam1: ' + str(lam1)) print ('v1: ' + str(vec1)) print ('Av1: ' + str(A@vec1)) print ('lam1 x v1: ' + str(lam1*vec1)) print('-------') vec2 = eVecs[:,1] lam2 = eVals[1] print('lam2: ' + str(lam2)) print ('v2: ' + str(vec2)) print ('Av2: ' + str(A@vec2)) print ('lam2 x v2: ' + str(lam2*vec2)) t1 = lam1*vec1 print (t1) t2 = lam2*vec2 print (t2) fig = plt.figure() a=fig.add_subplot(1,1,1) # Plot v and t1 vecs = np.array([t1,vec1]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t1, color=['blue'], scale=10) plt.show() a=fig.add_subplot(1,2,1) # Plot v and t2 vecs = np.array([t2,vec2]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t2, color=['blue'], scale=10) plt.show() import numpy as np A = np.array([[2,0], [0,2]]) eVals, eVecs = np.linalg.eig(A) print(eVals) print(eVecs) vec1 = eVecs[:,0] lam1 = eVals[0] print('Matrix A:') print(A) print('-------') print('lam1: ' + str(lam1)) print ('v1: ' + str(vec1)) print ('Av1: ' + str(A@vec1)) print ('lam1 x v1: ' + str(lam1*vec1)) print('-------') vec2 = eVecs[:,1] lam2 = eVals[1] print('lam2: ' + str(lam2)) print ('v2: ' + str(vec2)) print ('Av2: ' + str(A@vec2)) print ('lam2 x v2: ' + str(lam2*vec2)) # Plot the resulting vectors t1 = lam1*vec1 t2 = lam2*vec2 fig = plt.figure() a=fig.add_subplot(1,1,1) # Plot v and t1 vecs = np.array([t1,vec1]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t1, color=['blue'], scale=10) plt.show() a=fig.add_subplot(1,2,1) # Plot v and t2 vecs = np.array([t2,vec2]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t2, color=['blue'], scale=10) plt.show() import numpy as np A = np.array([[2,1], [1,2]]) eVals, eVecs = np.linalg.eig(A) print(eVals) print(eVecs) vec1 = eVecs[:,0] lam1 = eVals[0] print('Matrix A:') print(A) print('-------') print('lam1: ' + str(lam1)) print ('v1: ' + str(vec1)) print ('Av1: ' + str(A@vec1)) print ('lam1 x v1: ' + str(lam1*vec1)) print('-------') vec2 = eVecs[:,1] lam2 = eVals[1] print('lam2: ' + str(lam2)) print ('v2: ' + str(vec2)) print ('Av2: ' + str(A@vec2)) print ('lam2 x v2: ' + str(lam2*vec2)) # Plot the results t1 = lam1*vec1 t2 = lam2*vec2 fig = plt.figure() a=fig.add_subplot(1,1,1) # Plot v and t1 vecs = np.array([t1,vec1]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t1, color=['blue'], scale=10) plt.show() a=fig.add_subplot(1,2,1) # Plot v and t2 vecs = np.array([t2,vec2]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t2, color=['blue'], scale=10) plt.show() import numpy as np A = np.array([[3,2], [1,0]]) l, Q = np.linalg.eig(A) print(Q) L = np.diag(l) print (L) Qinv = np.linalg.inv(Q) print(Qinv) v = np.array([1,3]) t = A@v print(t) # Plot v and t vecs = np.array([v,t]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t, color=['blue'], scale=10) plt.show() import math import numpy as np import matplotlib.pyplot as plt %matplotlib inline t = (Q@(L@(Qinv)))@v # Plot v and t vecs = np.array([v,t]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=10) plt.quiver(*origin, *t, color=['blue'], scale=10) plt.show() import numpy as np import matplotlib.pyplot as plt %matplotlib inline t1 = Qinv@v t2 = L@t1 t3 = Q@t2 # Plot the transformations vecs = np.array([v,t1, t2, t3]) origin = [0], [0] plt.axis('equal') plt.grid() plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.quiver(*origin, *v, color=['orange'], scale=20) plt.quiver(*origin, *t1, color=['blue'], scale=20) plt.quiver(*origin, *t2, color=['red'], scale=20) plt.quiver(*origin, *t3, color=['magenta'], scale=20) plt.show() import numpy as np A = np.array([[1,2], [4,3]]) l, Q = np.linalg.eig(A) L = np.diag(l) print(L) B = np.array([[3,-3,6], [2,-2,4], [1,-1,2]]) lb, Qb = np.linalg.eig(B) Lb = np.diag(lb) print(Lb) import numpy as np A = np.array([[1,2], [4,3]]) l, Q = np.linalg.eig(A) L = np.diag(l) print(Q) Linv = np.linalg.inv(L) Qinv = np.linalg.inv(Q) print(Linv) print(Qinv) Ainv = (Q@(Linv@(Qinv))) print(Ainv) print(np.linalg.inv(A))
https://github.com/qiskit-community/qgss-2023
qiskit-community
# required imports: from qiskit.visualization import array_to_latex from qiskit.quantum_info import Statevector, random_statevector from qiskit.quantum_info.operators import Operator, Pauli from qiskit import QuantumCircuit from qiskit.circuit.library import HGate, CXGate import numpy as np ket0 = [[1],[0]] array_to_latex(ket0) bra0 = [1,0] array_to_latex(bra0) ket1 = # put your answer answer here for |1⟩ bra1 = # put answer here for ⟨1| from qc_grader.challenges.qgss_2023 import grade_lab1_ex1 grade_lab1_ex1([ket1, bra1]) sv_bra0 = Statevector(bra0) sv_bra0 sv_bra0.draw('latex') sv_eq = Statevector([1/2, 3/4, 4/5, 6/8]) sv_eq.draw('latex') sv_eq.is_valid() sv_valid = # create your statevector here from qc_grader.challenges.qgss_2023 import grade_lab1_ex2 grade_lab1_ex2(sv_valid) op_bra0 = Operator(bra0) op_bra0 op_ket0 = Operator(ket0) op_bra0.tensor(op_ket0) braket = np.dot(op_bra0,op_ket0) array_to_latex(braket) ketbra = np.outer(ket0,bra0) array_to_latex(ketbra) braket = np.dot(op_bra0,op_ket0) array_to_latex(braket) bra1ket0 = # put your answer for ⟨1|0⟩ here bra0ket1 = # put your answer for ⟨0|1⟩ here bra1ket1 = # put your answer for ⟨1|1⟩ here ket1bra0 = # put your answer for |1⟩⟨0| here ket0bra1 = # put your answer for |0⟩⟨1| here ket1bra1 = # put your answer for |1⟩⟨1| here from qc_grader.challenges.qgss_2023 import grade_lab1_ex3 grade_lab1_ex3([bra1ket0, bra0ket1, bra1ket1, ket1bra0, ket0bra1, ket1bra1]) # add or remove your answer from this list answer = ['a', 'b', 'c'] from qc_grader.challenges.qgss_2023 import grade_lab1_ex4 grade_lab1_ex4(answer) m1 = Operator([[1,1],[0,0]]) array_to_latex(m1) m3 = Operator([[0,1],[1,0]]) array_to_latex(m3) array_to_latex(m1@ket0) m2 = # create an operator for m2 here m4 = # create and operator for m4 here from qc_grader.challenges.qgss_2023 import grade_lab1_ex5 grade_lab1_ex5([m2, m4]) cnot = CXGate() array_to_latex(cnot) m3.is_unitary() random = Operator(np.array([[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, 0.44607116+0.50778085j, -0.14128434-0.1523741j ], [ 0.16855994+0.12151822j, 0.55868196+0.38038841j, -0.12151822+0.16855994j, -0.38038841+0.55868196j], [ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, -0.44607116-0.50778085j, 0.14128434+0.1523741j ], [ 0.16855994+0.12151822j, 0.55868196+0.38038841j, 0.12151822-0.16855994j, 0.38038841-0.55868196j]])) random.is_unitary() non_unitary_op = # create your operator here from qc_grader.challenges.qgss_2023 import grade_lab1_ex6 grade_lab1_ex6(non_unitary_op) pauli_x = Pauli('X') array_to_latex(pauli_x) pauli_y = Pauli('Y') array_to_latex(pauli_y) pauli_z = Pauli('Z') array_to_latex(pauli_z) op_x = Operator(pauli_x) op_x op_new = np.dot(op_x,ket0) array_to_latex(op_new) result = # do your operations here from qc_grader.challenges.qgss_2023 import grade_lab1_ex7 grade_lab1_ex7(result) hadamard = HGate() array_to_latex(hadamard) hop = Operator(hadamard) hop.is_unitary() bell = QuantumCircuit(2) bell.h(0) # apply an H gate to the circuit bell.cx(0,1) # apply a CNOT gate to the circuit bell.draw(output="mpl") bell_op = Operator(bell) array_to_latex(bell_op) ghz = QuantumCircuit(3) ############################## # add gates to your circuit here ############################## ghz.draw(output='mpl') from qc_grader.challenges.qgss_2023 import grade_lab1_ex8 grade_lab1_ex8(ghz) plus_state = Statevector.from_label("+") plus_state.draw('latex') plus_state plus_state.probabilities_dict() # run this cell multiple times to show collapsing into one state or the other res = plus_state.measure() res qc = QuantumCircuit(1,1) qc.h(0) qc.measure(0, 0) qc.draw(output="mpl") sv_bell = Statevector([np.sqrt(1/2), 0, 0, np.sqrt(1/2)]) sv_bell.draw('latex') sv_bell.probabilities_dict() sv_psi_plus = # create a statevector for |𝜓+⟩ here prob_psi_plus = # find the measurement probabilities for |𝜓+⟩ here sv_psi_minus = # create a statevector for |𝜓−⟩ here prob_psi_minus = # find the measurement probabilities for |𝜓−⟩ here sv_phi_minus = # create a statevector for |𝜙−⟩ here prob_phi_minus = # find the measurement probabilities for |𝜙−⟩ here from qc_grader.challenges.qgss_2023 import grade_lab1_ex9 grade_lab1_ex9([prob_psi_plus, prob_psi_minus, prob_phi_minus]) qft = QuantumCircuit(2) ############################## # add gates to your circuit here ############################## qft.draw(output='mpl') from qc_grader.challenges.qgss_2023 import grade_lab1_ex10 grade_lab1_ex10(qft) U = Operator(qft) array_to_latex(U)
https://github.com/qiskit-community/qgss-2023
qiskit-community
from qiskit.circuit import QuantumCircuit from qiskit.primitives import Estimator, Sampler from qiskit.quantum_info import SparsePauliOp from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt plt.style.use('dark_background') # optional # create excited |1> state qc_1 = QuantumCircuit(1) qc_1.x(0) qc_1.draw('mpl') # create superposition |+> state qc_plus = QuantumCircuit(1) qc_plus.h(0) qc_plus.draw('mpl') qc_1.measure_all() qc_plus.measure_all() sampler = Sampler() job_1 = sampler.run(qc_1) job_plus = sampler.run(qc_plus) job_1.result().quasi_dists job_plus.result().quasi_dists legend = ["Excited State", "Plus State"] # TODO: Excited State does not appear plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend) qc_1.remove_final_measurements() qc_plus.remove_final_measurements() # rotate into the X-basis qc_1.h(0) qc_plus.h(0) qc_1.measure_all() qc_plus.measure_all() sampler = Sampler() job_1 = sampler.run(qc_1) job_plus = sampler.run(qc_plus) plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend) qc2_1 = QuantumCircuit(1) qc2_1.x(0) qc2_plus = QuantumCircuit(1) qc2_plus.h(0) obsvs = list(SparsePauliOp(['Z', 'X'])) estimator = Estimator() job2_1 = estimator.run([qc2_1]*len(obsvs), observables=obsvs) job2_plus = estimator.run([qc2_plus]*len(obsvs), observables=obsvs) job2_1.result() # TODO: make this into module that outputs a nice table print(f' | <Z> | <X> ') print(f'----|------------------') print(f'|1> | {job2_1.result().values[0]} | {job2_1.result().values[1]}') print(f'|+> | {job2_plus.result().values[0]} | {job2_plus.result().values[1]}') obsv = # create operator for chsh witness from qc_grader.challenges.qgss_2023 import grade_lab2_ex1 grade_lab2_ex1(obsv) from qiskit.circuit import Parameter theta = Parameter('θ') qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.ry(theta, 0) qc.draw('mpl') angles = # create a parameterization of angles that will violate the inequality estimator = Estimator() job = estimator.run([qc]*len(angles), observables=[obsv]*len(angles), parameter_values=angles) exps = job.result().values plt.plot(angles, exps, marker='x', ls='-', color='green') plt.plot(angles, [2]*len(angles), ls='--', color='red', label='Classical Bound') plt.plot(angles, [-2]*len(angles), ls='--', color='red') plt.xlabel('angle (rad)') plt.ylabel('CHSH Witness') plt.legend(loc=4) from qc_grader.challenges.qgss_2023 import grade_lab2_ex2 grade_lab2_ex2(obsv, angles) from qiskit.circuit import ClassicalRegister, QuantumRegister theta = Parameter('θ') qr = QuantumRegister(1, 'q') qc = QuantumCircuit(qr) qc.ry(theta, 0) qc.draw('mpl') tele_qc = qc.copy() bell = QuantumRegister(2, 'Bell') alice = ClassicalRegister(2, 'Alice') bob = ClassicalRegister(1, 'Bob') tele_qc.add_register(bell, alice, bob) tele_qc.draw('mpl') # create Bell state with other two qubits tele_qc.barrier() tele_qc.h(1) tele_qc.cx(1, 2) tele_qc.barrier() tele_qc.draw('mpl') # alice operates on her qubits tele_qc.cx(0, 1) tele_qc.h(0) tele_qc.barrier() tele_qc.draw('mpl') tele_qc.measure([qr[0], bell[0]], alice) tele_qc.draw('mpl') graded_qc = tele_qc.copy() ############################## # add gates to graded_qc here ############################## graded_qc.draw('mpl') graded_qc.barrier() graded_qc.measure(bell[1], bob) graded_qc.draw('mpl') from qc_grader.challenges.qgss_2023 import grade_lab2_ex3 grade_lab2_ex3(graded_qc, theta, 5*np.pi/7) from qiskit_aer.primitives import Sampler angle = 5*np.pi/7 sampler = Sampler() qc.measure_all() job_static = sampler.run(qc.bind_parameters({theta: angle})) job_dynamic = sampler.run(graded_qc.bind_parameters({theta: angle})) print(f"Original Dists: {job_static.result().quasi_dists[0].binary_probabilities()}") print(f"Teleported Dists: {job_dynamic.result().quasi_dists[0].binary_probabilities()}") from qiskit.result import marginal_counts tele_counts = # marginalize counts legend = ['Original State', 'Teleported State'] plot_histogram([job_static.result().quasi_dists[0].binary_probabilities(), tele_counts], legend=legend) from qc_grader.challenges.qgss_2023 import grade_lab2_ex4 grade_lab2_ex4(tele_counts, job_dynamic.result()) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qgss-2023
qiskit-community
from qiskit import QuantumCircuit, Aer, execute import numpy as np from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt from math import gcd #QFT Circuit def qft(n): """Creates an n-qubit QFT circuit""" circuit = QuantumCircuit(n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(np.pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) qft_rotations(circuit, n) swap_registers(circuit, n) return circuit #Inverse Quantum Fourier Transform def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) return qc phase_register_size = 4 qpe4 = QuantumCircuit(phase_register_size+1, phase_register_size) ### Insert your code here ## Run this cell to simulate 'qpe4' and to plot the histogram of the result sim = Aer.get_backend('aer_simulator') shots = 2000 count_qpe4 = execute(qpe4, sim, shots=shots).result().get_counts() plot_histogram(count_qpe4, figsize=(9,5)) from qc_grader.challenges.qgss_2023 import grade_lab3_ex1 grade_lab3_ex1(count_qpe4) #Grab the highest probability measurement max_binary_counts = 0 max_binary_val = '' for key, item in count_qpe4.items(): if item > max_binary_counts: max_binary_counts = item max_binary_val = key ## Your function to convert a binary string to decimal goes here estimated_phase = # calculate the estimated phase phase_accuracy_window = # highest power of 2 (i.e. smallest decimal) this circuit can estimate from qc_grader.challenges.qgss_2023 import grade_lab3_ex2 grade_lab3_ex2([estimated_phase, phase_accuracy_window]) from qiskit_ibm_provider import IBMProvider from qiskit.compiler import transpile provider = IBMProvider() hub = "YOUR_HUB" group = "YOUR_GROUP" project = "YOUR_PROJECT" backend_name = "YOUR_BACKEND" backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}") # your code goes here from qc_grader.challenges.qgss_2023 import grade_lab3_ex3 grade_lab3_ex3([max_depth_qpe, min_depth_qpe]) shots = 2000 #OPTIONAL: Run the minimum depth qpe circuit job_min_qpe4 = backend.run(min_depth_qpe, sim, shots=shots) print(job_min_qpe4.job_id()) #Gather the count data count_min_qpe4 = job_min_qpe4.result().get_counts() plot_histogram(count_min_qpe4, figsize=(9,5)) #OPTIONAL: Run the maximum depth qpe circuit job_max_qpe4 = backend.run(max_depth_qpe, sim, shots=shots) print(job_max_qpe4.job_id()) #Gather the count data count_max_qpe4 = job_max_qpe4.result().get_counts() plot_histogram(count_max_qpe4, figsize=(9,5)) def qpe_circuit(register_size): # Your code goes here return qpe ## Run this cell to simulate 'qpe4' and to plot the histogram of the result reg_size = # Vary the register sizes qpe_check = qpe_circuit(reg_size) sim = Aer.get_backend('aer_simulator') shots = 10000 count_qpe4 = execute(qpe_check, sim, shots=shots).result().get_counts() plot_histogram(count_qpe4, figsize=(9,5)) # Process the count data to determine accuracy of the estimated phase required_register_size = #your answer here from qc_grader.challenges.qgss_2023 import grade_lab3_ex4 grade_lab3_ex4(required_register_size) ## Create 7mod15 gate N = 15 m = int(np.ceil(np.log2(N))) U_qc = QuantumCircuit(m) U_qc.x(range(m)) U_qc.swap(1, 2) U_qc.swap(2, 3) U_qc.swap(0, 3) U = U_qc.to_gate() U.name ='{}Mod{}'.format(7, N) ### your code goes here qcirc = QuantumCircuit(m) ## Run this cell to simulate 'qpe4' and to plot the histogram of the result sim = Aer.get_backend('aer_simulator') shots = 20000 input_1 = execute(qcirc, sim, shots=shots).result().get_counts() # save the count data for input 1 input_2 = # save the count data for input 2 input_5 = # save the count data for input 5 from qc_grader.challenges.qgss_2023 import grade_lab3_ex5 grade_lab3_ex5([input_1, input_2, input_5]) unitary_circ = QuantumCircuit(m) # Your code goes here sim = Aer.get_backend('unitary_simulator') unitary = execute(unitary_circ, sim).result().get_unitary() from qc_grader.challenges.qgss_2023 import grade_lab3_ex6 grade_lab3_ex6(unitary, unitary_circ) #This function will return a ControlledGate object which repeats the action # of U, 2^k times def cU_multi(k): sys_register_size = 4 circ = QuantumCircuit(sys_register_size) for _ in range(2**k): circ.append(U, range(sys_register_size)) U_multi = circ.to_gate() U_multi.name = '7Mod15_[2^{}]'.format(k) cU_multi = U_multi.control() return cU_multi # your code goes here shor_qpe = #Create the QuantumCircuit needed to run with 8 phase register qubits ## Run this cell to simulate 'shor_qpe' and to plot the histogram of the results sim = Aer.get_backend('aer_simulator') shots = 20000 shor_qpe_counts = execute(shor_qpe, sim, shots=shots).result().get_counts() plot_histogram(shor_qpe_counts, figsize=(9,5)) from qc_grader.challenges.qgss_2023 import grade_lab3_ex7 grade_lab3_ex7(shor_qpe_counts) from fractions import Fraction print(Fraction(0.666), '\n') print(Fraction(0.666).limit_denominator(15)) shor_qpe_fractions = # create a list of Fraction objects for each measurement outcome from qc_grader.challenges.qgss_2023 import grade_lab3_ex8 grade_lab3_ex8(shor_qpe_fractions) def shor_qpe(k): a = 7 #Step 1. Begin a while loop until a nontrivial guess is found ### Your code goes here ### #Step 2a. Construct a QPE circuit with m phase count qubits # to guess the phase phi = s/r using the function cU_multi() ### Your code goes here ### #Step 2b. Run the QPE circuit with a single shot, record the results # and convert the estimated phase bitstring to decimal ### Your code goes here ### #Step 3. Use the Fraction object to find the guess for r ### Your code goes here ### #Step 4. Now that r has been found, use the builtin greatest common deonominator # function to determine the guesses for a factor of N guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] #Step 5. For each guess in guesses, check if at least one is a non-trivial factor # i.e. (guess != 1 or N) and (N % guess == 0) ### Your code goes here ### #Step 6. If a nontrivial factor is found return the list 'guesses', otherwise # continue the while loop ### Your code goes here ### return guesses from qc_grader.challenges.qgss_2023 import grade_lab3_ex9 grade_lab3_ex9(shor_qpe)
https://github.com/qiskit-community/qgss-2023
qiskit-community
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def step_1_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits qc = QuantumCircuit(qr, cr) ####### your code goes here ####### return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = step_1_circuit(qr, cr) qc.draw("mpl") # Submit your circuit from qc_grader.challenges.qgss_2023 import grade_lab4_ex1 grade_lab4_ex1(qc) def step_2_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits # begin with the circuit from Step 1 qc = step_1_circuit(qr, cr) ####### your code goes here ####### return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = step_2_circuit(qr, cr) qc.draw("mpl") # Submit your circuit from qc_grader.challenges.qgss_2023 import grade_lab4_ex2 grade_lab4_ex2(qc) from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() counts from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def t_gate_ipe_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 3 bits qc = QuantumCircuit(qr, cr) ####### your code goes here ####### return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(3, "c") qc = QuantumCircuit(qr, cr) qc = t_gate_ipe_circuit(qr, cr) qc.draw("mpl") from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() counts # Submit your circuit from qc_grader.challenges.qgss_2023 import grade_lab4_ex3 grade_lab4_ex3(qc) from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits qc = QuantumCircuit(qr, cr) # Initialization q0, q1 = qr qc.h(q0) qc.x(q1) # Apply control-U operator as many times as needed to get the least significant phase bit u_angle = 2 * np.pi / 3 k = 1 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the first classical bit qc.h(q0) c0, c1 = cr qc.measure(q0, c0) # Reset and re-initialize the auxiliary qubit qc.reset(q0) qc.h(q0) # Apply phase correction conditioned on the first classical bit with qc.if_test((c0, 1)): qc.p(-np.pi / 2, q0) # Apply control-U operator as many times as needed to get the next phase bit k = 0 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the second classical bit qc.h(q0) qc.measure(q0, c1) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = u_circuit(qr, cr) qc.draw("mpl") from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() print(counts) success_probability = counts["01"] / counts.shots() print(f"Success probability: {success_probability}") from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 1 bits qc = QuantumCircuit(qr, cr) # Initialization q0, q1 = qr qc.h(q0) qc.x(q1) # Apply control-U operator as many times as needed to get the least significant phase bit u_angle = 2 * np.pi / 3 k = 1 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis qc.h(q0) (c0,) = cr qc.measure(q0, c0) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") qc = QuantumCircuit(qr, cr) qc = u_circuit(qr, cr) qc.draw("mpl") job = sim.run(qc, shots=15) result = job.result() counts = result.get_counts() print(counts) step1_bit: int ####### your code goes here ####### # Submit your result from qc_grader.challenges.qgss_2023 import grade_lab4_ex4 grade_lab4_ex4(step1_bit) from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits qc = QuantumCircuit(qr, cr) ####### your code goes here ####### return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = u_circuit(qr, cr) qc.draw("mpl") # Submit your result from qc_grader.challenges.qgss_2023 import grade_lab4_ex5 grade_lab4_ex5(qc) from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() print(counts) success_probability = counts["01"] / counts.shots() print(f"Success probability: {success_probability}") from qiskit.circuit import Gate def iterative_phase_estimation( qr: QuantumRegister, cr: ClassicalRegister, controlled_unitaries: list[Gate], state_prep: Gate, ) -> QuantumCircuit: qc = QuantumCircuit(qr, cr) ####### your code goes here ####### return qc from qiskit.circuit.library import CPhaseGate, XGate qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") s_angle = np.pi / 2 controlled_unitaries = [CPhaseGate(s_angle * 2**k) for k in range(2)] qc = iterative_phase_estimation(qr, cr, controlled_unitaries, XGate()) sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() counts from qiskit_ibm_provider import IBMProvider provider = IBMProvider() hub = "YOUR_HUB" group = "YOUR_GROUP" project = "YOUR_PROJECT" backend_name = "ibmq_manila" backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}") from qiskit import transpile qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = step_2_circuit(qr, cr) qc_transpiled = transpile(qc, backend) job = backend.run(qc_transpiled, shots=1000, dynamic=True) job_id = job.job_id() print(job_id) retrieve_job = provider.retrieve_job(job_id) retrieve_job.status() from qiskit.tools.visualization import plot_histogram counts = retrieve_job.result().get_counts() plot_histogram(counts)
https://github.com/qiskit-community/qgss-2023
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import SparsePauliOp def heisenberg_hamiltonian( length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0 ) -> SparsePauliOp: terms = [] for i in range(length - 1): if jx: terms.append(("XX", [i, i + 1], jx)) if jy: terms.append(("YY", [i, i + 1], jy)) if jz: terms.append(("ZZ", [i, i + 1], jz)) return SparsePauliOp.from_sparse_list(terms, num_qubits=length) def state_prep_circuit(num_qubits: int, layers: int = 1) -> QuantumCircuit: qubits = QuantumRegister(num_qubits, name="q") circuit = QuantumCircuit(qubits) circuit.h(qubits) for _ in range(layers): for i in range(0, num_qubits - 1, 2): circuit.cx(qubits[i], qubits[i + 1]) circuit.ry(0.1, qubits) for i in range(1, num_qubits - 1, 2): circuit.cx(qubits[i], qubits[i + 1]) circuit.ry(0.1, qubits) return circuit length = 5 hamiltonian = heisenberg_hamiltonian(length, 1.0, 1.0) circuit = state_prep_circuit(length, layers=2) print(hamiltonian) circuit.draw("mpl") from qiskit_aer.primitives import Estimator estimator = Estimator(approximation=True) job = estimator.run(circuit, hamiltonian, shots=None) result = job.result() exact_value = result.values[0] print(f"Exact energy: {exact_value}") from qiskit_ibm_runtime import QiskitRuntimeService hub = "ibm-q-internal" group = "deployed" project = "default" service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}") from qiskit_ibm_runtime import Estimator, Options, Session from qiskit.transpiler import CouplingMap backend = service.get_backend("simulator_statevector") # set simulation options simulator = { "basis_gates": ["id", "rz", "sx", "cx", "reset"], "coupling_map": list(CouplingMap.from_line(length + 1)), } shots = 10000 import math options = Options( simulator=simulator, resilience_level=0, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") from qiskit_aer.noise import NoiseModel, ReadoutError noise_model = NoiseModel() ##### your code here ##### print(noise_model) # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex1 grade_lab5_ex1(noise_model) options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=0, transpilation=dict(initial_layout=list(range(length))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=0, transpilation=dict(initial_layout=list(range(1, length + 1))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=1, transpilation=dict(initial_layout=list(range(1, length + 1))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") new_shots: int ##### your code here ##### # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex2 grade_lab5_ex2(new_shots) from qiskit_aer.noise import depolarizing_error noise_model = NoiseModel() ##### your code here ##### print(noise_model) # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex3 grade_lab5_ex3(noise_model) options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=1, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=2, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variances = result.metadata[0]["zne"]["noise_amplification"]["variance"] print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variances: {variances}")
https://github.com/qiskit-community/qgss-2023
qiskit-community
# required imports: from qiskit.visualization import array_to_latex from qiskit.quantum_info import Statevector, random_statevector from qiskit.quantum_info.operators import Operator, Pauli from qiskit import QuantumCircuit from qiskit.circuit.library import HGate, CXGate import numpy as np ket0 = [[1],[0]] array_to_latex(ket0) bra0 = [1,0] array_to_latex(bra0) ket1 = [[0], [1]] bra1 = [0, 1] from qc_grader.challenges.qgss_2023 import grade_lab1_ex1 grade_lab1_ex1([ket1, bra1]) sv_bra0 = Statevector(bra0) sv_bra0 sv_bra0.draw('latex') sv_eq = Statevector([1/2, 3/4, 4/5, 6/8]) sv_eq.draw('latex') sv_eq.is_valid() sv_valid = Statevector([1/2, 1/2, 1/2, 1/2]) from qc_grader.challenges.qgss_2023 import grade_lab1_ex2 grade_lab1_ex2(sv_valid) op_bra0 = Operator(bra0) op_bra0 op_ket0 = Operator(ket0) op_bra0.tensor(op_ket0) braket = np.dot(op_bra0,op_ket0) array_to_latex(braket) ketbra = np.outer(ket0,bra0) array_to_latex(ketbra) braket = np.dot(op_bra0,op_ket0) array_to_latex(braket) bra1ket0 = [0] bra0ket1 = [0] bra1ket1 = [1] ket1bra0 = [[0, 0], [1, 0]] ket0bra1 = [[0, 1], [0, 0]] ket1bra1 = [[0, 0], [0, 1]] from qc_grader.challenges.qgss_2023 import grade_lab1_ex3 grade_lab1_ex3([bra1ket0, bra0ket1, bra1ket1, ket1bra0, ket0bra1, ket1bra1]) answer = ['a'] from qc_grader.challenges.qgss_2023 import grade_lab1_ex4 grade_lab1_ex4(answer) m1 = Operator([[1,1],[0,0]]) array_to_latex(m1) m3 = Operator([[0,1],[1,0]]) array_to_latex(m3) array_to_latex(m1@ket0) m2 = Operator([[1, 0], [0, 1]]) m4 = Operator([[0, 0], [1, 1]]) from qc_grader.challenges.qgss_2023 import grade_lab1_ex5 grade_lab1_ex5([m2, m4]) cnot = CXGate() array_to_latex(cnot) m3.is_unitary() random = Operator(np.array([[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, 0.44607116+0.50778085j, -0.14128434-0.1523741j ], [ 0.16855994+0.12151822j, 0.55868196+0.38038841j, -0.12151822+0.16855994j, -0.38038841+0.55868196j], [ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, -0.44607116-0.50778085j, 0.14128434+0.1523741j ], [ 0.16855994+0.12151822j, 0.55868196+0.38038841j, 0.12151822-0.16855994j, 0.38038841-0.55868196j]])) random.is_unitary() non_unitary_op = Operator(np.array([0,1,2,3])) from qc_grader.challenges.qgss_2023 import grade_lab1_ex6 grade_lab1_ex6(non_unitary_op) pauli_x = Pauli('X') array_to_latex(pauli_x) pauli_y = Pauli('Y') array_to_latex(pauli_y) pauli_z = Pauli('Z') array_to_latex(pauli_z) op_x = Operator(pauli_x) op_x op_new = np.dot(op_x,ket0) array_to_latex(op_new) result = [[0.+0.j], [-1.+0.j]] from qc_grader.challenges.qgss_2023 import grade_lab1_ex7 grade_lab1_ex7(result) hadamard = HGate() array_to_latex(hadamard) hop = Operator(hadamard) hop.is_unitary() bell = QuantumCircuit(2) bell.h(0) # apply an H gate to the circuit bell.cx(0,1) # apply a CNOT gate to the circuit bell.draw(output="mpl") bell_op = Operator(bell) array_to_latex(bell_op) ghz = QuantumCircuit(3) ############################## # add gates to your circuit here ghz.h(0) ghz.cx(0, 1) ghz.cx(1, 2) ############################## ghz.draw(output='mpl') from qc_grader.challenges.qgss_2023 import grade_lab1_ex8 grade_lab1_ex8(ghz) plus_state = Statevector.from_label("+") plus_state.draw('latex') plus_state plus_state.probabilities_dict() # run this cell multiple times to show collapsing into one state or the other res = plus_state.measure() res qc = QuantumCircuit(1,1) qc.h(0) qc.measure(0, 0) qc.draw(output="mpl") sv_bell = Statevector([np.sqrt(1/2), 0, 0, np.sqrt(1/2)]) sv_bell.draw('latex') sv_bell.probabilities_dict() sv_psi_plus = Statevector([0, np.sqrt(1/2), np.sqrt(1/2), 0]) prob_psi_plus = {'01': 0.5000000000000001, '10': 0.5000000000000001} sv_psi_minus = Statevector([0, np.sqrt(1/2), -np.sqrt(1/2), 0]) prob_psi_minus = {'01': 0.5000000000000001, '10': 0.5000000000000001} sv_phi_minus = Statevector([np.sqrt(1/2), 0, 0, -np.sqrt(1/2)]) prob_phi_minus = {'00': 0.5000000000000001, '11': 0.5000000000000001} from qc_grader.challenges.qgss_2023 import grade_lab1_ex9 grade_lab1_ex9([prob_psi_plus, prob_psi_minus, prob_phi_minus]) qft = QuantumCircuit(2) ############################## # add gates to your circuit here qft.h(1) qft.cp(np.pi/2, 0, 1) qft.h(0) qft.swap(0, 1) ############################## qft.draw(output='mpl') from qc_grader.challenges.qgss_2023 import grade_lab1_ex10 grade_lab1_ex10(qft) U = Operator(qft) array_to_latex(U)
https://github.com/qiskit-community/qgss-2023
qiskit-community
%set_env QC_GRADE_ONLY=true from qiskit.circuit import QuantumCircuit from qiskit.primitives import Estimator, Sampler from qiskit.quantum_info import SparsePauliOp from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt plt.style.use('dark_background') # optional # create excited |1> state qc_1 = QuantumCircuit(1) qc_1.x(0) qc_1.draw('mpl') # create superposition |+> state qc_plus = QuantumCircuit(1) qc_plus.h(0) qc_plus.draw('mpl') qc_1.measure_all() qc_plus.measure_all() sampler = Sampler() job_1 = sampler.run(qc_1) job_plus = sampler.run(qc_plus) job_1.result().quasi_dists job_plus.result().quasi_dists legend = ["Excited State", "Plus State"] # TODO: Excited State does not appear plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend) qc_1.remove_final_measurements() qc_plus.remove_final_measurements() # rotate into the X-basis qc_1.h(0) qc_plus.h(0) qc_1.measure_all() qc_plus.measure_all() sampler = Sampler() job_1 = sampler.run(qc_1) job_plus = sampler.run(qc_plus) plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend) qc2_1 = QuantumCircuit(1) qc2_1.x(0) qc2_plus = QuantumCircuit(1) qc2_plus.h(0) obsvs = list(SparsePauliOp(['Z', 'X'])) estimator = Estimator() job2_1 = estimator.run([qc2_1]*len(obsvs), observables=obsvs) job2_plus = estimator.run([qc2_plus]*len(obsvs), observables=obsvs) job2_1.result() # TODO: make this into module that outputs a nice table print(f' | <Z> | <X> ') print(f'----|------------------') print(f'|1> | {job2_1.result().values[0]} | {job2_1.result().values[1]}') print(f'|+> | {job2_plus.result().values[0]} | {job2_plus.result().values[1]}') # this is a correct answer: obsv = SparsePauliOp('X').tensor(SparsePauliOp(['X', 'Z'], coeffs=[1, -1])) + SparsePauliOp('Z').tensor(SparsePauliOp(['X', 'Z'], coeffs=[1, 1])) from qc_grader.challenges.qgss_2023 import grade_lab2_ex1 grade_lab2_ex1(obsv) from qiskit.circuit import Parameter theta = Parameter('θ') qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.ry(theta, 0) qc.draw('mpl') # this is a correct answer num_params = 21 angles=[[angle] for angle in np.linspace(-np.pi, np.pi, num_params)] estimator = Estimator() job = estimator.run([qc]*len(angles), observables=[obsv]*len(angles), parameter_values=angles) exps = job.result().values plt.plot(angles, exps, marker='x', ls='-', color='green') plt.plot(angles, [2]*len(angles), ls='--', color='red', label='Classical Bound') plt.plot(angles, [-2]*len(angles), ls='--', color='red') plt.xlabel('angle (rad)') plt.ylabel('CHSH Witness') plt.legend(loc=4) from qc_grader.challenges.qgss_2023 import grade_lab2_ex2 grade_lab2_ex2(obsv, angles) from qiskit.circuit import ClassicalRegister, QuantumRegister theta = Parameter('θ') qr = QuantumRegister(1, 'q') qc = QuantumCircuit(qr) qc.ry(theta, 0) qc.draw('mpl') tele_qc = qc.copy() bell = QuantumRegister(2, 'Bell') alice = ClassicalRegister(2, 'Alice') bob = ClassicalRegister(1, 'Bob') tele_qc.add_register(bell, alice, bob) tele_qc.draw('mpl') # create Bell state with other two qubits tele_qc.barrier() tele_qc.h(1) tele_qc.cx(1, 2) tele_qc.barrier() tele_qc.draw('mpl') # alice operates on her qubits tele_qc.cx(0, 1) tele_qc.h(0) tele_qc.barrier() tele_qc.draw('mpl') tele_qc.measure([qr[0], bell[0]], alice) tele_qc.draw('mpl') # either pairs are correct # tele_qc.x(2).c_if(alice[1], 1) # tele_qc.z(2).c_if(alice[0], 1) with tele_qc.if_test((alice[1], 1)): tele_qc.x(2) with tele_qc.if_test((alice[0], 1)): tele_qc.z(2) tele_qc.draw('mpl') tele_qc.barrier() tele_qc.measure(bell[1], bob) tele_qc.draw('mpl') from qc_grader.challenges.qgss_2023 import grade_lab2_ex3 grade_lab2_ex3(tele_qc, theta, 5*np.pi/7) from qiskit_aer.primitives import Sampler angle = 5*np.pi/7 sampler = Sampler() qc.measure_all() job_static = sampler.run(qc.bind_parameters({theta: angle})) job_dynamic = sampler.run(tele_qc.bind_parameters({theta: angle})) print(f"Original Dists: {job_static.result().quasi_dists[0].binary_probabilities()}") print(f"Teleported Dists: {job_dynamic.result().quasi_dists[0].binary_probabilities()}") from qiskit.result import marginal_counts # this is correct tele_counts = marginal_counts(job_dynamic.result().quasi_dists[0].binary_probabilities(), indices=[2]) legend = ['Original State', 'Teleported State'] plot_histogram([job_static.result().quasi_dists[0].binary_probabilities(), tele_counts], legend=legend) from qc_grader.challenges.qgss_2023 import grade_lab2_ex4 grade_lab2_ex4(tele_counts, job_dynamic.result().quasi_dists[0]) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/qiskit-community/qgss-2023
qiskit-community
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def step_1_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits qc = QuantumCircuit(qr, cr) ####### your code goes here ####### ##1 Initialization q0, q1 = qr # apply Hadamard on the auxiliary qubit qc.h(q0) # put the system qubit into the |1> state qc.x(q1) ##2 Apply control-U operator as many times as needed to get the least significant phase bit # controlled-S is equivalent to CPhase with angle pi / 2 s_angle = np.pi / 2 # we want to apply controlled-S 2^k times k = 1 # calculate the angle of CPhase corresponding to 2^k applications of controlled-S cphase_angle = s_angle * 2**k # apply the controlled phase gate qc.cp(cphase_angle, q0, q1) ##3 Measure the auxiliary qubit in x-basis into the first classical bit # apply Hadamard to change to the X basis qc.h(q0) # measure the auxiliary qubit into the first classical bit c0, _ = cr qc.measure(q0, c0) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = step_1_circuit(qr, cr) qc.draw("mpl") # Submit your circuit from qc_grader.challenges.qgss_2023 import grade_lab4_ex1 grade_lab4_ex1(qc) def step_2_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits # begin with the circuit from Step 1 qc = step_1_circuit(qr, cr) ####### your code goes here ####### ##1 Reset and re-initialize the auxiliary qubit q0, q1 = qr # reset the auxiliary qubit qc.reset(q0) # apply Hadamard on the auxiiliary qubit qc.h(q0) ##2 Apply phase correction conditioned on the first classical bit c0, c1 = cr with qc.if_test((c0, 1)): qc.p(-np.pi / 2, q0) ##3 Apply control-U operator as many times as needed to get the next phase bit # controlled-S is equivalent to CPhase with angle pi / 2 s_angle = np.pi / 2 # we want to apply controlled-S 2^k times k = 0 # calculate the angle of CPhase corresponding to 2^k applications of controlled-S cphase_angle = s_angle * 2**k # apply the controlled phase gate qc.cp(cphase_angle, q0, q1) ##4 Measure the auxiliary qubit in x-basis into the second classical bit # apply Hadamard to change to the X basis qc.h(q0) # measure the auxiliary qubit into the first classical bit qc.measure(q0, c1) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = step_2_circuit(qr, cr) qc.draw("mpl") # Submit your circuit from qc_grader.challenges.qgss_2023 import grade_lab4_ex2 grade_lab4_ex2(qc) from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() counts from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def t_gate_ipe_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 3 bits qc = QuantumCircuit(qr, cr) ####### your code goes here ####### # Initialization q0, q1 = qr qc.h(q0) qc.x(q1) # Apply control-U operator as many times as needed to get the least significant phase bit t_angle = np.pi / 4 k = 2 cphase_angle = t_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the first classical bit qc.h(q0) c0, c1, c2 = cr qc.measure(q0, c0) # Reset and re-initialize the auxiliary qubit qc.reset(q0) qc.h(q0) # Apply phase correction conditioned on the first classical bit with qc.if_test((c0, 1)): qc.p(-np.pi / 2, q0) # Apply control-U operator as many times as needed to get the next phase bit k = 1 cphase_angle = t_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the second classical bit qc.h(q0) qc.measure(q0, c1) # Reset and re-initialize the auxiliary qubit qc.reset(q0) qc.h(q0) # Apply phase correction conditioned on the first and second classical bits with qc.if_test((c0, 1)): qc.p(-np.pi / 4, q0) with qc.if_test((c1, 1)): qc.p(-np.pi / 2, q0) # Apply control-U operator as many times as needed to get the next phase bit k = 0 cphase_angle = t_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the third classical bit qc.h(q0) qc.measure(q0, c2) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(3, "c") qc = QuantumCircuit(qr, cr) qc = t_gate_ipe_circuit(qr, cr) qc.draw("mpl") from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() counts # Submit your circuit from qc_grader.challenges.qgss_2023 import grade_lab4_ex3 grade_lab4_ex3(qc) from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits qc = QuantumCircuit(qr, cr) # Initialization q0, q1 = qr qc.h(q0) qc.x(q1) # Apply control-U operator as many times as needed to get the least significant phase bit u_angle = 2 * np.pi / 3 k = 1 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the first classical bit qc.h(q0) c0, c1 = cr qc.measure(q0, c0) # Reset and re-initialize the auxiliary qubit qc.reset(q0) qc.h(q0) # Apply phase correction conditioned on the first classical bit with qc.if_test((c0, 1)): qc.p(-np.pi / 2, q0) # Apply control-U operator as many times as needed to get the next phase bit k = 0 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the second classical bit qc.h(q0) qc.measure(q0, c1) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = u_circuit(qr, cr) qc.draw("mpl") from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() print(counts) success_probability = counts["01"] / counts.shots() print(f"Success probability: {success_probability}") from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 1 bits qc = QuantumCircuit(qr, cr) # Initialization q0, q1 = qr qc.h(q0) qc.x(q1) # Apply control-U operator as many times as needed to get the least significant phase bit u_angle = 2 * np.pi / 3 k = 1 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis qc.h(q0) (c0,) = cr qc.measure(q0, c0) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") qc = QuantumCircuit(qr, cr) qc = u_circuit(qr, cr) qc.draw("mpl") job = sim.run(qc, shots=15) result = job.result() counts = result.get_counts() print(counts) step1_bit: int ####### your code goes here ####### step1_bit = 1 if counts["1"] > counts["0"] else 0 print(step1_bit) # Submit your result from qc_grader.challenges.qgss_2023 import grade_lab4_ex4 grade_lab4_ex4(step1_bit) from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister import numpy as np def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit: # qr is a quantum register with 2 qubits # cr is a classical register with 2 bits qc = QuantumCircuit(qr, cr) ####### your code goes here ####### # Initialization q0, q1 = qr if step1_bit: qc.x(q0) qc.x(q1) # Measure the auxiliary qubit c0, c1 = cr qc.measure(q0, c0) # Reset and re-initialize the auxiliary qubit qc.reset(q0) qc.h(q0) # Apply phase correction conditioned on the first classical bit with qc.if_test((c0, 1)): qc.p(-np.pi / 2, q0) # Apply control-U operator as many times as needed to get the next phase bit u_angle = 2 * np.pi / 3 k = 0 cphase_angle = u_angle * 2**k qc.cp(cphase_angle, q0, q1) # Measure the auxiliary qubit in x-basis into the second classical bit qc.h(q0) qc.measure(q0, c1) return qc qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = u_circuit(qr, cr) qc.draw("mpl") # Submit your result from qc_grader.challenges.qgss_2023 import grade_lab4_ex5 grade_lab4_ex5(qc) from qiskit_aer import AerSimulator sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() print(counts) success_probability = counts["01"] / counts.shots() print(f"Success probability: {success_probability}") from qiskit.circuit import Gate def iterative_phase_estimation( qr: QuantumRegister, cr: ClassicalRegister, controlled_unitaries: list[Gate], state_prep: Gate, ) -> QuantumCircuit: qc = QuantumCircuit(qr, cr) ####### your code goes here ####### auxiliary_qubit = qr[0] system_qubits = qr[1:] qc.append(state_prep, system_qubits) for i in range(len(cr)): k = len(cr) - 1 - i qc.reset(auxiliary_qubit) qc.h(auxiliary_qubit) for j in range(i): with qc.if_test((cr[j], 1)): qc.p(-np.pi / 2 ** (i - j), auxiliary_qubit) qc.append(controlled_unitaries[k], qr) qc.h(auxiliary_qubit) qc.measure(auxiliary_qubit, cr[i]) return qc from qiskit.circuit.library import CPhaseGate, XGate qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") s_angle = np.pi / 2 controlled_unitaries = [CPhaseGate(s_angle * 2**k) for k in range(2)] qc = iterative_phase_estimation(qr, cr, controlled_unitaries, XGate()) sim = AerSimulator() job = sim.run(qc, shots=1000) result = job.result() counts = result.get_counts() counts from qiskit_ibm_provider import IBMProvider provider = IBMProvider() hub = "YOUR_HUB" group = "YOUR_GROUP" project = "YOUR_PROJECT" backend_name = "ibmq_manila" backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}") from qiskit import transpile qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") qc = QuantumCircuit(qr, cr) qc = step_2_circuit(qr, cr) qc_transpiled = transpile(qc, backend) job = backend.run(qc_transpiled, shots=1000, dynamic=True) job_id = job.job_id() print(job_id) retrieve_job = provider.retrieve_job(job_id) retrieve_job.status() from qiskit.tools.visualization import plot_histogram counts = retrieve_job.result().get_counts() plot_histogram(counts)
https://github.com/qiskit-community/qgss-2023
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import SparsePauliOp def heisenberg_hamiltonian( length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0 ) -> SparsePauliOp: terms = [] for i in range(length - 1): if jx: terms.append(("XX", [i, i + 1], jx)) if jy: terms.append(("YY", [i, i + 1], jy)) if jz: terms.append(("ZZ", [i, i + 1], jz)) return SparsePauliOp.from_sparse_list(terms, num_qubits=length) def state_prep_circuit(num_qubits: int, layers: int = 1) -> QuantumCircuit: qubits = QuantumRegister(num_qubits, name="q") circuit = QuantumCircuit(qubits) circuit.h(qubits) for _ in range(layers): for i in range(0, num_qubits - 1, 2): circuit.cx(qubits[i], qubits[i + 1]) circuit.ry(0.1, qubits) for i in range(1, num_qubits - 1, 2): circuit.cx(qubits[i], qubits[i + 1]) circuit.ry(0.1, qubits) return circuit length = 5 hamiltonian = heisenberg_hamiltonian(length, 1.0, 1.0) circuit = state_prep_circuit(length, layers=2) print(hamiltonian) circuit.draw("mpl") from qiskit_aer.primitives import Estimator estimator = Estimator(approximation=True) job = estimator.run(circuit, hamiltonian, shots=None) result = job.result() exact_value = result.values[0] print(f"Exact energy: {exact_value}") from qiskit_ibm_runtime import QiskitRuntimeService hub = "ibm-q-internal" group = "deployed" project = "default" service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}") from qiskit_ibm_runtime import Estimator, Options, Session from qiskit.transpiler import CouplingMap backend = service.get_backend("simulator_statevector") # set simulation options simulator = { "basis_gates": ["id", "rz", "sx", "cx", "reset"], "coupling_map": list(CouplingMap.from_line(length + 1)), } shots = 10000 import math options = Options( simulator=simulator, resilience_level=0, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") from qiskit_aer.noise import NoiseModel, ReadoutError noise_model = NoiseModel() ##### your code here ##### # add modest readout error on all qubits p0given1 = 0.05 p1given0 = 0.02 readout_error = ReadoutError( [ [1 - p1given0, p1given0], [p0given1, 1 - p0given1], ] ) noise_model.add_all_qubit_readout_error(readout_error) # add really bad readout error on qubit 0 p0given1 = 0.5 p1given0 = 0.2 readout_error = ReadoutError( [ [1 - p1given0, p1given0], [p0given1, 1 - p0given1], ] ) noise_model.add_readout_error(readout_error, [0]) print(noise_model) # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex1 grade_lab5_ex1(noise_model) options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=0, transpilation=dict(initial_layout=list(range(length))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=0, transpilation=dict(initial_layout=list(range(1, length + 1))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=1, transpilation=dict(initial_layout=list(range(1, length + 1))), ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") new_shots: int ##### your code here ##### new_shots = 20000 # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex2 grade_lab5_ex2(new_shots) from qiskit_aer.noise import depolarizing_error noise_model = NoiseModel() ##### your code here ##### noise_model.add_all_qubit_quantum_error(depolarizing_error(0.01, 2), ["cx"]) print(noise_model) # Submit your answer from qc_grader.challenges.qgss_2023 import grade_lab5_ex3 grade_lab5_ex3(noise_model) options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=1, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=2, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variances = result.metadata[0]["zne"]["noise_amplification"]["variance"] print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variances: {variances}") from qiskit_aer.noise import depolarizing_error, amplitude_damping_error noise_model = NoiseModel() ##### your code here ##### noise_model.add_all_qubit_quantum_error(amplitude_damping_error(0.01).tensor(amplitude_damping_error(0.05)), ["cx"]) print(noise_model) options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=1, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variance = result.metadata[0]["variance"] std = math.sqrt(variance / shots) print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variance: {variance}") print(f"Standard error: {std}") options = Options( simulator=dict(noise_model=noise_model, **simulator), resilience_level=2, ) with Session(service=service, backend=backend): estimator = Estimator(options=options) job = estimator.run(circuit, hamiltonian, shots=shots) result = job.result() experiment_value = result.values[0] error = abs(experiment_value - exact_value) variances = result.metadata[0]["zne"]["noise_amplification"]["variance"] print(f"Estimated energy: {experiment_value}") print(f"Energy error: {error}") print(f"Variances: {variances}")
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
import sys sys.path.append('/Users/kirais/Documents/GitHub/Qiskit-for-GameDev/pygame/') from qgame import CircuitGridModel, CircuitGridNode, MeasurementsHistogram from qgame import circuit_node_types as node_types from qiskit import QuantumCircuit circuit_grid_model = CircuitGridModel(4, 18) circuit_grid_model.set_node(0, 0, CircuitGridNode(node_types.ID)) circuit = circuit_grid_model.compute_circuit() print(circuit_grid_model) cx_gate = CircuitGridNode(node_types.CX, 1, ctrl_a=0) circuit_grid_model.set_node(1,1,cx_gate) print(circuit_grid_model) qasm_str = circuit_grid_model.create_qasm_for_circuit() qasm_str = 'OPENQASM 2.0;include "qelib1.inc";qreg q[4];creg c[4];id q;id q[0];rx(pi) q[1];' circuit = QuantumCircuit.from_qasm_str(qasm_str) circuit.draw() from qiskit import BasicAer, QuantumRegister, ClassicalRegister, QuantumCircuit, execute backend_sim = BasicAer.get_backend('qasm_simulator') qr = QuantumRegister(circuit.width(), 'q') cr = ClassicalRegister(circuit.width(), 'c') meas_circ = QuantumCircuit(qr, cr) meas_circ.barrier(qr) meas_circ.measure(qr, cr) circuit.draw() circuit.n_qubits meas_circ.draw() complete_circuit = circuit + meas_circ
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
# # Copyright 2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import numpy as np from qiskit import QuantumCircuit, QuantumRegister from model import circuit_node_types as node_types class CircuitGridModel(): """Grid-based model that is built when user interacts with circuit""" def __init__(self, max_wires, max_columns): self.max_wires = max_wires self.max_columns = max_columns self.nodes = np.empty((max_wires, max_columns), dtype = CircuitGridNode) def __str__(self): retval = '' for wire_num in range(self.max_wires): retval += '\n' for column_num in range(self.max_columns): # retval += str(self.nodes[wire_num][column_num]) + ', ' retval += str(self.get_node_gate_part(wire_num, column_num)) + ', ' return 'CircuitGridModel: ' + retval # def set_node(self, wire_num, column_num, node_type, radians=0, ctrl_a=-1, ctrl_b=-1, swap=-1): def set_node(self, wire_num, column_num, circuit_grid_node): self.nodes[wire_num][column_num] = \ CircuitGridNode(circuit_grid_node.node_type, circuit_grid_node.radians, circuit_grid_node.ctrl_a, circuit_grid_node.ctrl_b, circuit_grid_node.swap) # TODO: Decide whether to protect as shown below # if not self.nodes[wire_num][column_num]: # self.nodes[wire_num][column_num] = CircuitGridNode(node_type, radians) # else: # print('Node ', wire_num, column_num, ' not empty') def get_node(self, wire_num, column_num): return self.nodes[wire_num][column_num] def get_node_gate_part(self, wire_num, column_num): requested_node = self.nodes[wire_num][column_num] if requested_node and requested_node.node_type != node_types.EMPTY: # Node is occupied so return its gate return requested_node.node_type else: # Check for control nodes from gates in other nodes in this column nodes_in_column = self.nodes[:, column_num] for idx in range(self.max_wires): if idx != wire_num: other_node = nodes_in_column[idx] if other_node: if other_node.ctrl_a == wire_num or other_node.ctrl_b == wire_num: return node_types.CTRL elif other_node.swap == wire_num: return node_types.SWAP return node_types.EMPTY def get_gate_wire_for_control_node(self, control_wire_num, column_num): """Get wire for gate that belongs to a control node on the given wire""" gate_wire_num = -1 nodes_in_column = self.nodes[:, column_num] for wire_idx in range(self.max_wires): if wire_idx != control_wire_num: other_node = nodes_in_column[wire_idx] if other_node: if other_node.ctrl_a == control_wire_num or \ other_node.ctrl_b == control_wire_num: gate_wire_num = wire_idx print("Found gate: ", self.get_node_gate_part(gate_wire_num, column_num), " on wire: " , gate_wire_num) return gate_wire_num # def avail_gate_parts_for_node(self, wire_num, column_num): # retval = np.empty(0, dtype = np.int8) # node_gate_part = self.get_node_gate_part(wire_num, column_num) # if node_gate_part == node_types.EMPTY: # # No gate part in this node def compute_circuit(self): qr = QuantumRegister(self.max_wires, 'q') qc = QuantumCircuit(qr) for column_num in range(self.max_columns): for wire_num in range(self.max_wires): node = self.nodes[wire_num][column_num] if node: if node.node_type == node_types.IDEN: # Identity gate qc.iden(qr[wire_num]) elif node.node_type == node_types.X: if node.radians == 0: if node.ctrl_a != -1: if node.ctrl_b != -1: # Toffoli gate qc.ccx(qr[node.ctrl_a], qr[node.ctrl_b], qr[wire_num]) else: # Controlled X gate qc.cx(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-X gate qc.x(qr[wire_num]) else: # Rotation around X axis qc.rx(node.radians, qr[wire_num]) elif node.node_type == node_types.Y: if node.radians == 0: if node.ctrl_a != -1: # Controlled Y gate qc.cy(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Y gate qc.y(qr[wire_num]) else: # Rotation around Y axis qc.ry(node.radians, qr[wire_num]) elif node.node_type == node_types.Z: if node.radians == 0: if node.ctrl_a != -1: # Controlled Z gate qc.cz(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Z gate qc.z(qr[wire_num]) else: if node.ctrl_a != -1: # Controlled rotation around the Z axis qc.crz(node.radians, qr[node.ctrl_a], qr[wire_num]) else: # Rotation around Z axis qc.rz(node.radians, qr[wire_num]) elif node.node_type == node_types.S: # S gate qc.s(qr[wire_num]) elif node.node_type == node_types.SDG: # S dagger gate qc.sdg(qr[wire_num]) elif node.node_type == node_types.T: # T gate qc.t(qr[wire_num]) elif node.node_type == node_types.TDG: # T dagger gate qc.tdg(qr[wire_num]) elif node.node_type == node_types.H: if node.ctrl_a != -1: # Controlled Hadamard qc.ch(qr[node.ctrl_a], qr[wire_num]) else: # Hadamard gate qc.h(qr[wire_num]) elif node.node_type == node_types.SWAP: if node.ctrl_a != -1: # Controlled Swap qc.cswap(qr[node.ctrl_a], qr[wire_num], qr[node.swap]) else: # Swap gate qc.swap(qr[wire_num], qr[node.swap]) return qc class CircuitGridNode(): """Represents a node in the circuit grid""" def __init__(self, node_type, radians=0.0, ctrl_a=-1, ctrl_b=-1, swap=-1): self.node_type = node_type self.radians = radians self.ctrl_a = ctrl_a self.ctrl_b = ctrl_b self.swap = swap def __str__(self): string = 'type: ' + str(self.node_type) string += ', radians: ' + str(self.radians) if self.radians != 0 else '' string += ', ctrl_a: ' + str(self.ctrl_a) if self.ctrl_a != -1 else '' string += ', ctrl_b: ' + str(self.ctrl_b) if self.ctrl_b != -1 else '' return string
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pygame from qiskit import BasicAer, QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram from utils import load_image DEFAULT_NUM_SHOTS = 100 class MeasurementsHistogram(pygame.sprite.Sprite): """Displays a histogram with measurements""" def __init__(self, circuit, num_shots=DEFAULT_NUM_SHOTS): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.set_circuit(circuit, num_shots) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit, num_shots=DEFAULT_NUM_SHOTS): backend_sim = BasicAer.get_backend('qasm_simulator') qr = QuantumRegister(circuit.width(), 'q') cr = ClassicalRegister(circuit.width(), 'c') meas_circ = QuantumCircuit(qr, cr) meas_circ.barrier(qr) meas_circ.measure(qr, cr) complete_circuit = circuit + meas_circ job_sim = execute(complete_circuit, backend_sim, shots=num_shots) result_sim = job_sim.result() counts = result_sim.get_counts(complete_circuit) print(counts) histogram = plot_histogram(counts) histogram.savefig("utils/data/bell_histogram.png") self.image, self.rect = load_image('bell_histogram.png', -1) self.image.convert()
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pygame from qiskit import BasicAer, execute from qiskit.tools.visualization import plot_state_qsphere from utils import load_image class QSphere(pygame.sprite.Sprite): """Displays a qsphere""" def __init__(self, circuit): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.set_circuit(circuit) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circuit, decimals=3) qsphere = plot_state_qsphere(quantum_state) qsphere.savefig("utils/data/bell_qsphere.png") self.image, self.rect = load_image('bell_qsphere.png', -1) self.rect.inflate_ip(-100, -100) self.image.convert()
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pygame from qiskit import BasicAer, execute, ClassicalRegister from utils.colors import * from utils.fonts import ARIAL_30 from utils.states import comp_basis_states from copy import deepcopy #from utils.paddle import * class StatevectorGrid(pygame.sprite.Sprite): """Displays a statevector grid""" def __init__(self, circuit, qubit_num, num_shots): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.basis_states = comp_basis_states(circuit.width()) self.set_circuit(circuit, qubit_num, num_shots) # def update(self): # # Nothing yet # a = 1ot def set_circuit(self, circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() quantum_state = result_sim.get_statevector(circuit, decimals=3) # This square represent the probability of state after measurement self.image = pygame.Surface([(circuit.width()+1) * 50, 500]) self.image.convert() self.image.fill(BLACK) self.rect = self.image.get_rect() block_size = int(round(500 / 2 ** qubit_num)) x_offset = 50 y_offset = 15 self.paddle = pygame.Surface([10, block_size]) self.paddle.convert() for y in range(len(quantum_state)): text_surface = ARIAL_30.render("|"+self.basis_states[y]+">", False, (255, 255, 255)) self.image.blit(text_surface,(120, y * block_size + y_offset)) if abs(quantum_state[y]) > 0: #pygame.draw.rect(self.image, WHITE, rect, 0) self.paddle.fill(WHITE) self.paddle.set_alpha(int(round(abs(quantum_state[y])*255))) self.image.blit(self.paddle,(80,y * block_size)) def set_circuit_measure(self, circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('qasm_simulator') cr = ClassicalRegister(qubit_num) circuit2 = deepcopy(circuit) circuit2.add_register(cr) circuit2.measure(circuit2.qregs[0],circuit2.cregs[0]) job_sim = execute(circuit2, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) print(counts) #quantum_state = result_sim.get_statevector(circuit, decimals=3) # This square represent the probability of state after measurement self.image = pygame.Surface([(circuit.width()+1) * 50, 500]) self.image.convert() self.image.fill(BLACK) self.rect = self.image.get_rect() block_size = int(round(500 / 2 ** qubit_num)) x_offset = 50 y_offset = 15 self.paddle = pygame.Surface([10, block_size]) self.paddle.convert() self.paddle.fill(WHITE) #for y in range(len(quantum_state)): # text_surface = ARIAL_30.render(self.basis_states[y], False, (0, 0, 0)) # self.image.blit(text_surface,(120, y * block_size + y_offset)) # if abs(quantum_state[y]) > 0: #pygame.draw.rect(self.image, WHITE, rect, 0) #self.paddle.fill(WHITE) # self.paddle.set_alpha(int(round(abs(quantum_state[y])*255))) print(counts.keys()) print(int(list(counts.keys())[0],2)) self.image.blit(self.paddle,(80,int(list(counts.keys())[0],2) * block_size)) #pygame.time.wait(100) return int(list(counts.keys())[0],2)
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
#!/usr/bin/env python # # Copyright 2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pygame from qiskit import BasicAer, execute from utils.colors import * from utils.fonts import * from utils.states import comp_basis_states class UnitaryGrid(pygame.sprite.Sprite): """Displays a unitary matrix grid""" def __init__(self, circuit): pygame.sprite.Sprite.__init__(self) self.image = None self.rect = None self.basis_states = comp_basis_states(circuit.width()) self.set_circuit(circuit) # def update(self): # # Nothing yet # a = 1 def set_circuit(self, circuit): backend_unit_sim = BasicAer.get_backend('unitary_simulator') job_sim = execute(circuit, backend_unit_sim) result_sim = job_sim.result() unitary = result_sim.get_unitary(circuit, decimals=3) # print('unitary: ', unitary) self.image = pygame.Surface([100 + len(unitary) * 50, 100 + len(unitary) * 50]) self.image.convert() self.image.fill(WHITE) self.rect = self.image.get_rect() block_size = 30 x_offset = 50 y_offset = 50 for y in range(len(unitary)): text_surface = ARIAL_16.render(self.basis_states[y], False, (0, 0, 0)) self.image.blit(text_surface,(x_offset, (y + 1) * block_size + y_offset)) for x in range(len(unitary)): text_surface = ARIAL_16.render(self.basis_states[x], False, (0, 0, 0)) self.image.blit(text_surface, ((x + 1) * block_size + x_offset, y_offset)) rect = pygame.Rect((x + 1) * block_size + x_offset, (y + 1) * block_size + y_offset, abs(unitary[y][x]) * block_size, abs(unitary[y][x]) * block_size) if abs(unitary[y][x]) > 0: pygame.draw.rect(self.image, BLACK, rect, 1)
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
from qiskit import QuantumCircuit from circuit_grid import CircuitGridModel, CircuitGridNode import circuit_node_types as node_types from sympy import pi import logging id_gate = CircuitGridNode(node_types.ID) x_gate = CircuitGridNode(node_types.X, 1) y_gate = CircuitGridNode(node_types.Y, 1) z_gate = CircuitGridNode(node_types.Z, 1) h_gate = CircuitGridNode(node_types.H, 1) s_gate = CircuitGridNode(node_types.S, 1) sdg_gate = CircuitGridNode(node_types.SDG, 1) t_gate = CircuitGridNode(node_types.T, 1) tdg_gate = CircuitGridNode(node_types.TDG, 1) u1_gate = CircuitGridNode(node_types.U1, 1, theta=pi) u2_gate = CircuitGridNode(node_types.U2, 1, theta=pi, phi=pi) u3_gate = CircuitGridNode(node_types.U3, 1, theta=pi, phi=pi, lam=pi) rx_gate = CircuitGridNode(node_types.RX, 1, theta=pi) ry_gate = CircuitGridNode(node_types.RY, 1, theta=pi) rz_gate = CircuitGridNode(node_types.RZ, 1, theta=pi) cx_gate = CircuitGridNode(node_types.CX, 1, ctrl_a=0) cy_gate = CircuitGridNode(node_types.CY, 2, ctrl_a=1) cz_gate = CircuitGridNode(node_types.CZ, 3, ctrl_a=2) ch_gate = CircuitGridNode(node_types.CH, 4, ctrl_a=3) crz_gate = CircuitGridNode(node_types.CRZ, 1, theta=pi, ctrl_a=0) cu1_gate = CircuitGridNode(node_types.CU1, 1, theta=pi, ctrl_a=0) cu3_gate = CircuitGridNode(node_types.CU3, 1, theta=pi, phi=pi, lam=pi, ctrl_a=0) ccx_gate = CircuitGridNode(node_types.CCX, 2, ctrl_a=0, ctrl_b=1) swap_gate = CircuitGridNode(node_types.SWAP, 1, swap=2) cswap_gate = CircuitGridNode(node_types.CSWAP, 1, ctrl_a=0, swap=2) barrier = CircuitGridNode(node_types.BARRIER, 1) measure_z = CircuitGridNode(node_types.MEASURE_Z, 1) reset = CircuitGridNode(node_types.RESET, 1) _if = CircuitGridNode(node_types.IF, 1) gates = [ id_gate, x_gate, y_gate, z_gate, h_gate, s_gate, sdg_gate, t_gate, tdg_gate, u1_gate, u2_gate, u3_gate, rx_gate, ry_gate, rz_gate, cx_gate, cy_gate, cz_gate, ch_gate, crz_gate, cu1_gate, cu3_gate, ccx_gate, swap_gate, cswap_gate, barrier, measure_z, reset, _if ] for gate in gates: print(gate) for gate in gates: print(gate.qasm()) circuit_grid = CircuitGridModel(4,7) print(circuit_grid) print(gates[0]) for j in range(circuit_grid.circuit_depth): for i in range(circuit_grid.qubit_count): circuit_grid.set_node(i,j,gates[j*circuit_grid.qubit_count + i]) print(circuit_grid) qasm_str = circuit_grid.create_qasm_for_circuit() print(qasm_str) qc = QuantumCircuit.from_qasm_str(qasm_str) qc.draw()
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
import sys sys.path.append('/Users/kirais/Documents/GitHub/Qiskit-for-GameDev/pygame/') from qgame import CircuitGridModel, CircuitGridNode from qgame import circuit_node_types as node_types from qiskit import QuantumCircuit circuit_grid_model = CircuitGridModel(qubit_count=3, circuit_depth=6) print(circuit_grid_model) qasm_str = circuit_grid_model.create_qasm_for_circuit() print(qasm_str) circuit = QuantumCircuit.from_qasm_str(qasm_str) circuit.draw() print(CircuitGridNode(node_types.X)) circuit_grid_model.set_node(qubit_index=1,depth_index=0,circuit_grid_node=CircuitGridNode(node_types.X)) print(circuit_grid_model) qasm_str = circuit_grid_model.create_qasm_for_circuit() print(qasm_str) circuit = QuantumCircuit.from_qasm_str(qasm_str) circuit.draw() circuit_grid_model.set_node(0,1,CircuitGridNode(node_types.H)) circuit_grid_model.set_node(2,1,CircuitGridNode(node_types.H)) print(circuit_grid_model) qasm_str = circuit_grid_model.create_qasm_for_circuit() print(qasm_str) circuit = QuantumCircuit.from_qasm_str(qasm_str) circuit.draw() from qiskit import BasicAer, execute, ClassicalRegister def paddle_before_measurement(circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() state = result_sim.get_statevector(circuit, decimals=3) probability = (state*state).real return probability probability = paddle_before_measurement(circuit, 3, 1000) print(probability) from matplotlib import pyplot as plt from matplotlib.patches import Rectangle plt.figure(figsize=(20,1)) ax = plt.gca() for i in range(8): ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=probability[i], fc='k', ec='k')) # add statvector labels ax.text(0/8+1/40,-1,r"$\left|000\right\rangle$", fontsize=36) ax.text(1/8+1/40,-1,r"$\left|001\right\rangle$", fontsize=36) ax.text(2/8+1/40,-1,r"$\left|010\right\rangle$", fontsize=36) ax.text(3/8+1/40,-1,r"$\left|011\right\rangle$", fontsize=36) ax.text(4/8+1/40,-1,r"$\left|100\right\rangle$", fontsize=36) ax.text(5/8+1/40,-1,r"$\left|101\right\rangle$", fontsize=36) ax.text(6/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36) ax.text(7/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36) plt.axis('off') plt.show() from copy import deepcopy def paddle_after_measurement(circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('qasm_simulator') circuit.measure(circuit.qregs[0], circuit.cregs[0]) job_sim = execute(circuit, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) return int(list(counts.keys())[0], 2) result = paddle_after_measurement(circuit, 3, 100) print(result) from matplotlib import pyplot as plt from matplotlib.patches import Rectangle plt.figure(figsize=(20,1)) ax = plt.gca() for i in range(8): if i == result: ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=1, fc='k', ec='k')) else: ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=0, fc='k', ec='k')) # add statvector labels ax.text(0/8+1/40,-1,r"$\left|000\right\rangle$", fontsize=36) ax.text(1/8+1/40,-1,r"$\left|001\right\rangle$", fontsize=36) ax.text(2/8+1/40,-1,r"$\left|010\right\rangle$", fontsize=36) ax.text(3/8+1/40,-1,r"$\left|011\right\rangle$", fontsize=36) ax.text(4/8+1/40,-1,r"$\left|100\right\rangle$", fontsize=36) ax.text(5/8+1/40,-1,r"$\left|101\right\rangle$", fontsize=36) ax.text(6/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36) ax.text(7/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36) plt.axis('off') plt.show()
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
import sys sys.path.append('/Users/kirais/Documents/GitHub/Qiskit-for-GameDev/pygame/') from qgame import CircuitGridModel, CircuitGridNode from qgame import circuit_node_types as node_types from qiskit import QuantumCircuit circuit_grid_model = CircuitGridModel(qubit_count=3, circuit_depth=6) print(circuit_grid_model) qasm_str = circuit_grid_model.create_qasm_for_circuit() print(qasm_str) circuit = QuantumCircuit.from_qasm_str(qasm_str) circuit.draw() print(CircuitGridNode(node_types.X)) circuit_grid_model.set_node(qubit_index=1,depth_index=0,circuit_grid_node=CircuitGridNode(node_types.X)) print(circuit_grid_model) qasm_str = circuit_grid_model.create_qasm_for_circuit() print(qasm_str) circuit = QuantumCircuit.from_qasm_str(qasm_str) circuit.draw() circuit_grid_model.set_node(0,1,CircuitGridNode(node_types.H)) circuit_grid_model.set_node(2,1,CircuitGridNode(node_types.H)) print(circuit_grid_model) qasm_str = circuit_grid_model.create_qasm_for_circuit() print(qasm_str) circuit = QuantumCircuit.from_qasm_str(qasm_str) circuit.draw() from qiskit import BasicAer, execute, ClassicalRegister def paddle_before_measurement(circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('statevector_simulator') job_sim = execute(circuit, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() state = result_sim.get_statevector(circuit, decimals=3) probability = (state*state).real return probability probability = paddle_before_measurement(circuit, 3, 1000) print(probability) from matplotlib import pyplot as plt from matplotlib.patches import Rectangle plt.figure(figsize=(20,1)) ax = plt.gca() for i in range(8): ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=probability[i]+0.05, fc='k', ec='k')) # add statvector labels ax.text(0/8+1/40,-1,r"$\left|000\right\rangle$", fontsize=36) ax.text(1/8+1/40,-1,r"$\left|001\right\rangle$", fontsize=36) ax.text(2/8+1/40,-1,r"$\left|010\right\rangle$", fontsize=36) ax.text(3/8+1/40,-1,r"$\left|011\right\rangle$", fontsize=36) ax.text(4/8+1/40,-1,r"$\left|100\right\rangle$", fontsize=36) ax.text(5/8+1/40,-1,r"$\left|101\right\rangle$", fontsize=36) ax.text(6/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36) ax.text(7/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36) plt.axis('off') plt.show() from copy import deepcopy def paddle_after_measurement(circuit, qubit_num, shot_num): backend_sv_sim = BasicAer.get_backend('qasm_simulator') circuit.measure(circuit.qregs[0], circuit.cregs[0]) job_sim = execute(circuit, backend_sv_sim, shots=shot_num) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) return int(list(counts.keys())[0], 2) result = paddle_after_measurement(circuit, 3, 100) print(result) from matplotlib import pyplot as plt from matplotlib.patches import Rectangle plt.figure(figsize=(20,1)) ax = plt.gca() for i in range(8): if i == result: ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=1, fc='k', ec='k')) else: ax.add_patch(Rectangle((i/8, 0), 1/8, 1, alpha=0, fc='k', ec='k')) # add statvector labels ax.text(0/8+1/40,-1,r"$\left|000\right\rangle$", fontsize=36) ax.text(1/8+1/40,-1,r"$\left|001\right\rangle$", fontsize=36) ax.text(2/8+1/40,-1,r"$\left|010\right\rangle$", fontsize=36) ax.text(3/8+1/40,-1,r"$\left|011\right\rangle$", fontsize=36) ax.text(4/8+1/40,-1,r"$\left|100\right\rangle$", fontsize=36) ax.text(5/8+1/40,-1,r"$\left|101\right\rangle$", fontsize=36) ax.text(6/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36) ax.text(7/8+1/40,-1,r"$\left|110\right\rangle$", fontsize=36) plt.axis('off') plt.show()
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
# # Copyright 2019 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import numpy as np from qiskit import QuantumCircuit, QuantumRegister from model import circuit_node_types as node_types class CircuitGridModel(): """Grid-based model that is built when user interacts with circuit""" def __init__(self, max_wires, max_columns): self.max_wires = max_wires self.max_columns = max_columns self.nodes = np.empty((max_wires, max_columns), dtype = CircuitGridNode) def __str__(self): retval = '' for wire_num in range(self.max_wires): retval += '\n' for column_num in range(self.max_columns): # retval += str(self.nodes[wire_num][column_num]) + ', ' retval += str(self.get_node_gate_part(wire_num, column_num)) + ', ' return 'CircuitGridModel: ' + retval # def set_node(self, wire_num, column_num, node_type, radians=0, ctrl_a=-1, ctrl_b=-1, swap=-1): def set_node(self, wire_num, column_num, circuit_grid_node): self.nodes[wire_num][column_num] = \ CircuitGridNode(circuit_grid_node.node_type, circuit_grid_node.radians, circuit_grid_node.ctrl_a, circuit_grid_node.ctrl_b, circuit_grid_node.swap) # TODO: Decide whether to protect as shown below # if not self.nodes[wire_num][column_num]: # self.nodes[wire_num][column_num] = CircuitGridNode(node_type, radians) # else: # print('Node ', wire_num, column_num, ' not empty') def get_node(self, wire_num, column_num): return self.nodes[wire_num][column_num] def get_node_gate_part(self, wire_num, column_num): requested_node = self.nodes[wire_num][column_num] if requested_node and requested_node.node_type != node_types.EMPTY: # Node is occupied so return its gate return requested_node.node_type else: # Check for control nodes from gates in other nodes in this column nodes_in_column = self.nodes[:, column_num] for idx in range(self.max_wires): if idx != wire_num: other_node = nodes_in_column[idx] if other_node: if other_node.ctrl_a == wire_num or other_node.ctrl_b == wire_num: return node_types.CTRL elif other_node.swap == wire_num: return node_types.SWAP return node_types.EMPTY def get_gate_wire_for_control_node(self, control_wire_num, column_num): """Get wire for gate that belongs to a control node on the given wire""" gate_wire_num = -1 nodes_in_column = self.nodes[:, column_num] for wire_idx in range(self.max_wires): if wire_idx != control_wire_num: other_node = nodes_in_column[wire_idx] if other_node: if other_node.ctrl_a == control_wire_num or \ other_node.ctrl_b == control_wire_num: gate_wire_num = wire_idx print("Found gate: ", self.get_node_gate_part(gate_wire_num, column_num), " on wire: " , gate_wire_num) return gate_wire_num # def avail_gate_parts_for_node(self, wire_num, column_num): # retval = np.empty(0, dtype = np.int8) # node_gate_part = self.get_node_gate_part(wire_num, column_num) # if node_gate_part == node_types.EMPTY: # # No gate part in this node def compute_circuit(self): qr = QuantumRegister(self.max_wires, 'q') qc = QuantumCircuit(qr) for column_num in range(self.max_columns): for wire_num in range(self.max_wires): node = self.nodes[wire_num][column_num] if node: if node.node_type == node_types.IDEN: # Identity gate qc.iden(qr[wire_num]) elif node.node_type == node_types.X: if node.radians == 0: if node.ctrl_a != -1: if node.ctrl_b != -1: # Toffoli gate qc.ccx(qr[node.ctrl_a], qr[node.ctrl_b], qr[wire_num]) else: # Controlled X gate qc.cx(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-X gate qc.x(qr[wire_num]) else: # Rotation around X axis qc.rx(node.radians, qr[wire_num]) elif node.node_type == node_types.Y: if node.radians == 0: if node.ctrl_a != -1: # Controlled Y gate qc.cy(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Y gate qc.y(qr[wire_num]) else: # Rotation around Y axis qc.ry(node.radians, qr[wire_num]) elif node.node_type == node_types.Z: if node.radians == 0: if node.ctrl_a != -1: # Controlled Z gate qc.cz(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Z gate qc.z(qr[wire_num]) else: if node.ctrl_a != -1: # Controlled rotation around the Z axis qc.crz(node.radians, qr[node.ctrl_a], qr[wire_num]) else: # Rotation around Z axis qc.rz(node.radians, qr[wire_num]) elif node.node_type == node_types.S: # S gate qc.s(qr[wire_num]) elif node.node_type == node_types.SDG: # S dagger gate qc.sdg(qr[wire_num]) elif node.node_type == node_types.T: # T gate qc.t(qr[wire_num]) elif node.node_type == node_types.TDG: # T dagger gate qc.tdg(qr[wire_num]) elif node.node_type == node_types.H: if node.ctrl_a != -1: # Controlled Hadamard qc.ch(qr[node.ctrl_a], qr[wire_num]) else: # Hadamard gate qc.h(qr[wire_num]) elif node.node_type == node_types.SWAP: if node.ctrl_a != -1: # Controlled Swap qc.cswap(qr[node.ctrl_a], qr[wire_num], qr[node.swap]) else: # Swap gate qc.swap(qr[wire_num], qr[node.swap]) return qc class CircuitGridNode(): """Represents a node in the circuit grid""" def __init__(self, node_type, radians=0.0, ctrl_a=-1, ctrl_b=-1, swap=-1): self.node_type = node_type self.radians = radians self.ctrl_a = ctrl_a self.ctrl_b = ctrl_b self.swap = swap def __str__(self): string = 'type: ' + str(self.node_type) string += ', radians: ' + str(self.radians) if self.radians != 0 else '' string += ', ctrl_a: ' + str(self.ctrl_a) if self.ctrl_a != -1 else '' string += ', ctrl_b: ' + str(self.ctrl_b) if self.ctrl_b != -1 else '' return string
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
#!/usr/bin/env python3 from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, Aer, execute def run_qasm(qasm, backend_to_run="qasm_simulator"): qc = QuantumCircuit.from_qasm_str(qasm) backend = Aer.get_backend(backend_to_run) job_sim = execute(qc, backend) sim_result = job_sim.result() return sim_result.get_counts(qc)