repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
import sys, math, logging import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError class HWEA: """ Class to implement a hardware efficient ansatz for the QAOA algorithm. Based on the community detection circuit implemented by Francois-Marie Le Régent. This ansatz uses the entangler+rotation block structure like that described in the paper by Nikolaj Moll et al. (http://iopscience.iop.org/article/10.1088/2058-9565/aab822) A HW efficient ansatz circuit can be generated with an instance of this class by calling its gen_circuit() method. Attributes ---------- nq : int number of qubits d : int number of layers to apply. Where a layer = rotation block + entangler block This is also the same as the "P" value often referenced for QAOA. parameters : str optional string which changes the rotation angles in the rotation block [optimal, random, seeded] seed : int a number to seed the number generator with barriers : bool should barriers be included in the generated circuit measure : bool should a classical register & measurement be added to the circuit regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qr : QuantumRegister Qiskit QuantumRegister holding all of the quantum bits cr : ClassicalRegister Qiskit ClassicalRegister holding all of the classical bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the hardware-efficient ansatz """ def __init__( self, width, depth, parameters="optimal", seed=None, barriers=False, measure=False, regname=None, ): # number of qubits self.nq = width # number of layers self.d = depth # set flags for circuit generation self.parameters = parameters self.seed = seed self.barriers = barriers self.measure = measure # Create a Quantum and Classical Register. if regname is None: self.qr = QuantumRegister(self.nq) self.cr = ClassicalRegister(self.nq) else: self.qr = QuantumRegister(self.nq, name=regname) self.cr = ClassicalRegister(self.nq, name="c" + regname) # It is easier for the circuit cutter to handle circuits # without measurement or classical registers if self.measure: self.circ = QuantumCircuit(self.qr, self.cr) else: self.circ = QuantumCircuit(self.qr) def get_noiseless_theta(self): """ Set the parameters to the optimal value which solves the community detection problem. This method returns a vector of length (1 + d)*2nq The first gate on the first qubit is a pi/2 rotation (Hadamard) After the entangler block, the first half of the qubits (round down for odd n_qubits) receive a pi rotation (X gate) Parameters ---------- nb_qubits : int Number of qubits in the circuit Returns ------- list vector of length 2*nq * (1+d) """ theta = np.zeros(2 * self.nq * (1 + self.d)) theta[0] = np.pi / 2 theta[2 * self.nq : 2 * self.nq + math.floor(self.nq / 2)] = np.pi return theta def get_random_theta(self): if self.parameters == "seeded": if self.seed is None: raise Exception("A valid seed must be provided") else: np.random.seed(self.seed) theta = np.random.uniform(-np.pi, np.pi, 4 * self.nq) return theta def gen_circuit(self): """ Create a circuit for the QAOA RyRz ansatz This methods generates a circuit with repeated layers of an entangler block sandwiched between parameterized rotation columns Returns ------- QuantumCircuit QuantumCircuit of size nb_qubits with no ClassicalRegister and no measurements QiskitError Prints the error in the circuit """ if self.parameters == "optimal": theta = self.get_noiseless_theta() elif self.parameters in ["random", "seeded"]: theta = self.get_random_theta() else: raise Exception("Unknown parameter option: {}".format(self.parameters)) try: # INITIAL PARAMETERIZER # layer 1 # theta = np.arange(len(theta)) # print(len(theta)) p_idx = 0 for i in range(self.nq): self.circ.u3(theta[i + p_idx], 0, 0, self.qr[i]) p_idx += self.nq # layer 2 for i in range(self.nq): self.circ.u3(0, 0, theta[i + p_idx], self.qr[i]) p_idx += self.nq if self.barriers: self.circ.barrier() # For each layer, d, execute an entangler followed by a parameterizer block for dd in range(self.d): # ENTANGLER for i in range(self.nq - 1): # qc.h(q[i+1]) self.circ.cx(self.qr[i], self.qr[i + 1]) # qc.h(q[i+1]) if self.barriers: self.circ.barrier() # PARAMETERIZER # layer 1 for i in range(self.nq): self.circ.u3(theta[i + p_idx], 0, 0, self.qr[i]) p_idx += self.nq # layer 2 for i in range(self.nq): self.circ.u3(0, 0, theta[i + p_idx], self.qr[i]) p_idx += self.nq # place measurements on the end of the circuit if self.measure: self.circ.barrier() self.circ.measure(self.qr, self.cr) return self.circ except QiskitError as ex: raise Exception("There was an error in the circuit!. Error = {}".format(ex))
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
import sys import math import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister class QFT: """ Class which generates the circuit to perform the Quantum Fourier Transform (or its inverse) as described in Mike & Ike Chapter 5. (Michael A Nielsen and Isaac L Chuang. Quantum computation and quantum information (10th anniv. version), 2010.) For another example see Figure 1 of Daniel E Browne 2007 New J. Phys. 9 146 A QFT or iQFT circuit can be generated with a given instance of the QFT class by calling the gen_circuit() method. Attributes ---------- width : int number of qubits inverse : bool Set to true to generate the inverse quantum fourier transform kvals : bool optional parameter that will change the angle of the controlled rotations so that when the circuit is printed it will display the same k values that are shown in Mike & Ike Chpt 5, Fig 5.1 (NOTE: the generated circuit will no longer be valid! This is for visualization purposes only.) barriers : bool should barriers be included in the generated circuit measure : bool should a classical register & measurement be added to the circuit regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qr : QuantumRegister Qiskit QuantumRegister holding all of the quantum bits cr : ClassicalRegister Qiskit ClassicalRegister holding all of the classical bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the uccsd circuit """ def __init__( self, width, approximation_degree, inverse=False, kvals=False, barriers=True, measure=False, regname=None, ): # number of qubits self.nq = width self.approximation_degree = approximation_degree # set flags for circuit generation self.inverse = inverse self.kvals = kvals self.barriers = barriers self.measure = measure # create a QuantumCircuit object if regname is None: self.qr = QuantumRegister(self.nq) self.cr = ClassicalRegister(self.nq) else: self.qr = QuantumRegister(self.nq, name=regname) self.cr = ClassicalRegister(self.nq, name="c" + regname) # Have the option to include measurement if desired if self.measure: self.circ = QuantumCircuit(self.qr, self.cr) else: self.circ = QuantumCircuit(self.qr) def inv_qft(self): """ Implement the inverse QFT on self.circ j ranges from nq-1 -> 0 k ranges from nq-1 -> j+1 For each j qubit, a controlled cu1 gate is applied with target=j, control=k (for each k). cu1 = 1 0 0 e^(-2pi*i / 2^(k-j+1)) """ for j in range(self.nq - 1, -1, -1): for k in range(self.nq - 1, j, -1): if self.kvals: self.circ.cu1(-1 * (k - j + 1), self.qr[k], self.qr[j]) else: self.circ.cu1( -1 * (2 * np.pi) / (2 ** (k - j + 1)), self.qr[k], self.qr[j] ) self.circ.h(self.qr[j]) if self.barriers: self.circ.barrier() def reg_qft(self): """ Implement the QFT on self.circ j ranges from 0 -> nq-1 k ranges from j+1 -> nq-1 For each j qubit, a controlled cu1 gate is applied with target=j, control=k (for each k). cu1 = 1 0 0 e^(2pi*i / 2^(k-j+1)) """ for j in range(self.nq): self.circ.h(self.qr[j]) for k in range(j + 1, self.nq): if self.kvals: self.circ.cu1(k - j + 1, self.qr[k], self.qr[j]) else: if k - j + 1 <= self.approximation_degree: self.circ.cu1( (2 * np.pi) / (2 ** (k - j + 1)), self.qr[k], self.qr[j] ) if self.barriers: self.circ.barrier() def gen_circuit(self): """ Create a circuit implementing the UCCSD ansatz Given the number of qubits and parameters, construct the ansatz as given in Whitfield et al. Returns ------- QuantumCircuit QuantumCircuit object of size nq with no ClassicalRegister and no measurements """ if self.inverse: self.inv_qft() else: self.reg_qft() if self.measure: self.circ.barrier() self.circ.measure(self.qr, self.cr) return self.circ
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
from qiskit import QuantumCircuit, QuantumRegister import sys import math import numpy as np class QWALK: """ Class to implement the Quantum Walk algorithm as described in Childs et al. (https://arxiv.org/abs/quant-ph/0209131) A circuit implementing the quantum walk can be generated for a given instance of a problem parameterized by N (i.e. # of vertices in a graph) by calling the gen_circuit() method. Attributes ---------- N : int number of vertices in the graph we want to perform the quantum walk on barriers : bool should barriers be included in the generated circuit regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qr : QuantumRegister Qiskit QuantumRegister holding all of the quantum bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the uccsd circuit """ def __init__(self, N, barriers=False, regname=None): # number of vertices self.N = N # set flags for circuit generation self.barriers = barriers self.k = self.gen_coloring() # NOTE: self.nq does not include the r and 0 ancilla register qubits # that are also added to the circuit. # self.nq = len(a) + len(b) # Where a and b are both 2n bitstrings as defined in Childs et al. self.nq = math.ceil(math.log2(self.N)) * 4 # create a QuantumCircuit object if regname is None: self.qr = QuantumRegister(self.nq) else: self.qr = QuantumRegister(self.nq, name=regname) self.circ = QuantumCircuit(self.qr) # Add the r and 0 ancilla registers self.ancR = QuantumRegister(1, "ancR") self.anc0 = QuantumRegister(1, "anc0") self.circ.add_register(self.ancR) self.circ.add_register(self.anc0) def gen_coloring(self): """ Generate a coloring for the graph k = poly(log(N)) """ self.k = 4 def Vc(self, c): """ Apply the Vc gate to the circuit """ def evolve_T(self, t): """ Simulate the evolution of exp(-iTt) """ def gen_circuit(self): """ Create a circuit implementing the quantum walk algorithm Returns ------- QuantumCircuit QuantumCircuit object of size nq with no ClassicalRegister and no measurements """ t = 1 for c in range(self.k): self.Vc(c) self.evolve_T(t) self.Vc(c) return self.circ
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
from .Qbit_original import Qbit from .cz_layer_generation import get_layers from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import math import sys import numpy as np class Qgrid: """ Class to implement the quantum supremacy circuits as found in https://www.nature.com/articles/s41567-018-0124-x and https://github.com/sboixo/GRCS. Each instance is a 2D array whose entries at Qbit objects. A supremacy circuit can be generated for a given instance by calling the gen_circuit() method. Attributes ---------- n : int number of rows in the grid m : int number of columns in the grid d : int depth of the supremacy circuit (excludes H-layer and measurement i.e. 1+d+1) regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qreg : QuantumRegister Qiskit QuantumRegister holding all of the qubits creg : ClassicalRegister Qiskit ClassicalRegister holding all of the classical bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the supremacy circuit grid : array n x m array holding Qbit objects cz_list : list List of the CZ-gate indices for each layer of the supremacy circuit mirror : bool Boolean indicating whether the cz layers should repeat exactly or in reverse order order : list list of indices indicting the order the cz layers should be placed singlegates : bool Boolean indicating whether to include single qubit gates in the circuit """ def __init__( self, n, m, d, order=None, singlegates=True, mirror=True, barriers=True, measure=False, regname=None, ): self.n = n self.m = m self.d = d if regname is None: self.qreg = QuantumRegister(n * m) self.creg = ClassicalRegister(n * m) else: self.qreg = QuantumRegister(n * m, name=regname) self.creg = ClassicalRegister(n * m, name="c" + regname) # It is easier to interface with the circuit cutter # if there is no Classical Register added to the circuit self.measure = measure if self.measure: self.circ = QuantumCircuit(self.qreg, self.creg) else: self.circ = QuantumCircuit(self.qreg) self.grid = self.make_grid(n, m) self.cz_list = get_layers(n, m) self.mirror = mirror self.barriers = barriers if order is None: # Default self.random = False # Use the default Google order (https://github.com/sboixo/GRCS) self.order = [0, 5, 1, 4, 2, 7, 3, 6] elif order == "random": # Random order self.random = True self.order = np.arange(len(self.cz_list)) if self.mirror is True: raise Exception( "Order cannot be random and mirror cannot be True simultaneously. Exiting." ) else: # Convert given order string to list of ints self.random = False self.order = [int(c) for c in order] self.singlegates = singlegates def make_grid(self, n, m): temp_grid = [] index_ctr = 0 for row in range(n): cur_row = [] for col in range(m): cur_row += [Qbit(index_ctr, None)] index_ctr += 1 temp_grid += [cur_row] return temp_grid def get_index(self, index1=None, index2=None): if index2 is None: return self.grid[index1[0]][index1[1]].index else: return self.grid[index1][index2].index def print_circuit(self): print(self.circ.draw(scale=0.6, output="text", reverse_bits=False)) def save_circuit(self): str_order = [str(i) for i in self.order] if self.mirror: str_order.append("m") fn = "supr_{}x{}x{}_order{}.txt".format( self.n, self.m, self.d, "".join(str_order) ) self.circ.draw( scale=0.8, filename=fn, output="text", reverse_bits=False, line_length=160 ) def hadamard_layer(self): for i in range(self.n): for j in range(self.m): self.circ.h(self.qreg[self.grid[i][j].h()]) def measure_circuit(self): self.circ.barrier() for i in range(self.n): for j in range(self.m): qubit_index = self.get_index(i, j) self.circ.measure(self.qreg[qubit_index], self.creg[qubit_index]) def apply_postCZ_gate(self, grid_loc, reserved_qubits): qb_index = self.get_index(grid_loc) if qb_index not in reserved_qubits: gate = self.grid[grid_loc[0]][grid_loc[1]].random_gate() if gate == "Y": # Apply a sqrt-Y gate to qubit at qb_index self.circ.ry(math.pi / 2, self.qreg[qb_index]) elif gate == "X": # Apply a sqrt-X gate to qubit at qb_index self.circ.rx(math.pi / 2, self.qreg[qb_index]) else: print("ERROR: unrecognized gate: {}".format(gate)) # successfully applied random gate return True else: # did not apply gate return False def apply_T(self, grid_loc, reserved_qubits): """ Apply a T gate on the specified qubit if it is not currently involved in a CZ gate grid_loc = [row_idx, col_idx] """ qb_index = self.get_index(grid_loc[0], grid_loc[1]) if qb_index not in reserved_qubits: self.circ.t(self.qreg[qb_index]) # successfully applied T gate return True else: # Currently involved in a CZ gate return False def gen_circuit(self): # print('Generating {}x{}, 1+{}+1 supremacy circuit'.format(self.n,self.m,self.d)) # Initialize with Hadamards self.hadamard_layer() # Iterate through CZ layers cz_idx = -1 nlayer = len(self.cz_list) for i in range(self.d): prev_idx = cz_idx if self.mirror is True: if (i // nlayer) % 2 == 0: cz_idx = self.order[i % nlayer] else: cz_idx = self.order[::-1][i % nlayer] elif self.random is True: cur_mod = i % nlayer if cur_mod == 0: random_order = np.random.permutation(self.order) cz_idx = random_order[cur_mod] else: cz_idx = random_order[cur_mod] else: cz_idx = self.order[i % nlayer] cur_CZs = self.cz_list[cz_idx] pre_CZs = self.cz_list[prev_idx] reserved_qubits = [] # Apply entangling CZ gates for cz in cur_CZs: ctrl = self.get_index(cz[0]) trgt = self.get_index(cz[1]) reserved_qubits += [ctrl, trgt] self.circ.cz(self.qreg[ctrl], self.qreg[trgt]) if i == 0 and self.singlegates: # Apply T gates on all first layer qubits not involved in a CZ for n in range(self.n): for m in range(self.m): self.apply_T([n, m], reserved_qubits) if i > 1 and self.singlegates: # Apply T gates to all qubits which had a X_1_2 or # Y_1_2 in the last cycle and are not involved in # a CZ this cycle for grid_loc in prev_nondiag_gates: self.apply_T(grid_loc, reserved_qubits) if i > 0 and self.singlegates: # Apply non-diagonal single qubit gates to qubits which # were involved in a CZ gate in the previous cycle prev_nondiag_gates = [] for cz in pre_CZs: for grid_loc in cz: success = self.apply_postCZ_gate(grid_loc, reserved_qubits) if success: prev_nondiag_gates.append(grid_loc) if self.barriers: self.circ.barrier() # End CZ-layers # Apply a layer of Hadamards before measurement self.hadamard_layer() # Measurement if self.measure: self.measure_circuit() return self.circ def gen_qasm(self): return self.circ.qasm()
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
from .Qbit_Sycamore import Qbit from .ABCD_layer_generation import get_layers from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import math import sys import numpy as np class Qgrid: """ Class to implement the quantum supremacy circuits as found in Arute, F., Arya, K., Babbush, R. et al. 'Quantum supremacy using a programmable superconducting processor'. Nature 574, 505–510 (2019) doi:10.1038/s41586-019-1666-5 (https://www.nature.com/articles/s41586-019-1666-5) Each instance is a 2D array whose entries at Qbit objects. A supremacy circuit can be generated for a given instance by calling the gen_circuit() method. Attributes ---------- n : int number of rows in the grid m : int number of columns in the grid d : int depth of the supremacy circuit (excludes measurement i.e. d+1) regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qreg : QuantumRegister Qiskit QuantumRegister holding all of the qubits creg : ClassicalRegister Qiskit ClassicalRegister holding all of the classical bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the supremacy circuit grid : array n x m array holding Qbit objects ABCD_layers : list List of qubit indices for 2-qubit gates for the A, B, C, and D layers of the supremacy circuit. order : list list of indices indicting the order the cz layers should be placed singlegates : bool Boolean indicating whether to include single qubit gates in the circuit """ def __init__( self, n, m, d, order=None, singlegates=True, barriers=True, measure=False, regname=None, ): self.n = n self.m = m self.d = d if regname is None: self.qreg = QuantumRegister(n * m) self.creg = ClassicalRegister(n * m) else: self.qreg = QuantumRegister(n * m, name=regname) self.creg = ClassicalRegister(n * m, name="c" + regname) # It is easier to interface with the circuit cutter # if there is no Classical Register added to the circuit self.measure = measure if self.measure: self.circ = QuantumCircuit(self.qreg, self.creg) else: self.circ = QuantumCircuit(self.qreg) self.grid = self.make_grid(n, m) self.ABCD_layers = get_layers(n, m) self.barriers = barriers self.singlegates = singlegates if order is None: # Use the default Google order for full supremacy circuit # In the Nature paper Supp Info. Table 3 shows that the # full supremacy circuit pattern is: ABCDCDAB # ABCD_layers = [layerA, layerB, layerC, layerD] self.order = [0, 1, 2, 3, 2, 3, 0, 1] else: # Convert given order string to list of ints self.order = [int(c) for c in order] def make_grid(self, n, m): temp_grid = [] index_ctr = 0 for row in range(n): cur_row = [] for col in range(m): cur_row += [Qbit(index_ctr, None)] index_ctr += 1 temp_grid += [cur_row] return temp_grid def get_index(self, index1=None, index2=None): if index2 is None: return self.grid[index1[0]][index1[1]].index else: return self.grid[index1][index2].index def print_circuit(self): print(self.circ.draw(scale=0.6, output="text", reverse_bits=False)) def save_circuit(self): str_order = [str(i) for i in self.order] if self.mirror: str_order.append("m") fn = "supr_{}x{}x{}_order{}.txt".format( self.n, self.m, self.d, "".join(str_order) ) self.circ.draw( scale=0.8, filename=fn, output="text", reverse_bits=False, line_length=160 ) def measure_circuit(self): self.circ.barrier() for i in range(self.n): for j in range(self.m): qubit_index = self.get_index(i, j) self.circ.measure(self.qreg[qubit_index], self.creg[qubit_index]) def apply_random_1q_gate(self, n, m): qb_index = self.get_index(n, m) gate = self.grid[n][m].random_gate() if gate == "X": # Apply a sqrt-X gate to qubit at qb_index self.circ.rx(math.pi / 2, self.qreg[qb_index]) elif gate == "Y": # Apply a sqrt-Y gate to qubit at qb_index self.circ.ry(math.pi / 2, self.qreg[qb_index]) elif gate == "W": # Apply a sqrt-W gate to qubit at qb_index # W = (X + Y) / sqrt(2) self.circ.z(self.qreg[qb_index]) else: Exception("ERROR: unrecognized gate: {}".format(gate)) def gen_circuit(self): """ Generate n*m depth d+1 Sycamore circuit """ # Iterate through d layers for i in range(self.d): # apply single qubit gates for n in range(self.n): for m in range(self.m): self.apply_random_1q_gate(n, m) # Apply entangling 2-qubit gates cur_q2s = self.ABCD_layers[self.order[i % len(self.order)]] for q2 in cur_q2s: ctrl = self.get_index(q2[0]) trgt = self.get_index(q2[1]) # The 2 qubit gate implemented by Google's Sycamore chip # is fSim(pi/2, pi/6) given in Eqn. 53 of the Nature Supp info self.circ.cz(self.qreg[ctrl], self.qreg[trgt]) if self.barriers: self.circ.barrier() # End d layers # Measurement if self.measure: self.measure_circuit() return self.circ def gen_qasm(self): return self.circ.qasm()
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
import sys from qiskit import Aer, execute from quantum_circuit_generator.generators import gen_hwea n = 6 circ = gen_hwea(n, 1) print(circ) simulator = Aer.get_backend("statevector_simulator") result = execute(circ, simulator).result() sv = result.get_statevector(circ) print(sv) # entanglement measure def sgn_star(n, i): if n == 2: return 1 i_binary = "{:b}".format(i) Ni = 0 for char in i_binary: if char == "1": Ni += 1 if i >= 0 and i <= 2 ** (n - 3) - 1: return (-1) ** Ni elif i >= 2 ** (n - 3) and i <= 2 ** (n - 2) - 1: return (-1) ** (n + Ni) else: print("i out of range for sgn*") sys.exit(2) def tau(a, n): istar = 0 for i in range(0, 2 ** (n - 2)): istar_term = sgn_star(n, i) * ( a[2 * i] * a[(2**n - 1) - 2 * i] - a[2 * i + 1] * a[(2**n - 2) - 2 * i] ) istar += istar_term return 2 * abs(istar) print(tau(sv, n))
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
""" Teague Tomesh - 3/25/2019 Implementation of the UCCSD ansatz for use in the VQE algorithm. Based on the description given in Whitfield et al. (https://arxiv.org/abs/1001.3855?context=physics.chem-ph) Adapted from a Scaffold implementation by Pranav Gokhale] (https://github.com/epiqc/ScaffCC) NOTE: Qiskit orders their circuits increasing from top -> bottom 0 --- 1 --- 2 --- Both Whitfield et al. and Barkoutsos et al. order increasing from bottom -> top p 3 --- q 2 --- r 1 --- s 0 --- Not a problem. Qubit index is what matters. Set reverse_bits = True when drawing Qiskit circuit. """ from qiskit import QuantumCircuit, QuantumRegister import sys import math import numpy as np class UCCSD: """ Class to implement the UCCSD ansatz as described in Whitfield et al. (https://arxiv.org/abs/1001.3855?context=physics.chem-ph) A UCCSD circuit can be generated for a given instance of the UCCSD class by calling the gen_circuit() method. Attributes ---------- width : int number of qubits parameters : str choice of parameters [random, seeded] seed : int a number to seed the number generator with barriers : bool should barriers be included in the generated circuit regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qr : QuantumRegister Qiskit QuantumRegister holding all of the quantum bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the uccsd circuit """ def __init__( self, width, parameters="random", seed=None, barriers=False, regname=None ): # number of qubits self.nq = width # set flags for circuit generation self.parameters = parameters self.seed = seed self.barriers = barriers # create a QuantumCircuit object # We do not include a ClassicalRegister in this circuit because # many different gates may need to be appended to this ansatz # to measure all of the terms in the Hamiltonian for an instance # VQE, but it is also easier for the circuit cutter to handle # circuits without measurement/classical registers. if regname is None: self.qr = QuantumRegister(self.nq) else: self.qr = QuantumRegister(self.nq, name=regname) self.circ = QuantumCircuit(self.qr) def M_d(self, i, p, q, r, s, dagger=False): """ See Double Excitation Operator circuit in Table A1 of Whitfield et al 2010 Y in Table A1 of Whitfield et al 2010 really means Rx(-pi/2) """ if dagger: angle = math.pi / 2 else: angle = -math.pi / 2 qr = self.circ.qregs[0] if i == 1: self.circ.h(qr[p]) self.circ.h(qr[q]) self.circ.h(qr[r]) self.circ.h(qr[s]) elif i == 2: self.circ.rx(angle, qr[p]) self.circ.rx(angle, qr[q]) self.circ.rx(angle, qr[r]) self.circ.rx(angle, qr[s]) elif i == 3: self.circ.h(qr[p]) self.circ.rx(angle, qr[q]) self.circ.h(qr[r]) self.circ.rx(angle, qr[s]) elif i == 4: self.circ.rx(angle, qr[p]) self.circ.h(qr[q]) self.circ.rx(angle, qr[r]) self.circ.h(qr[s]) elif i == 5: self.circ.rx(angle, qr[p]) self.circ.rx(angle, qr[q]) self.circ.h(qr[r]) self.circ.h(qr[s]) elif i == 6: self.circ.h(qr[p]) self.circ.h(qr[q]) self.circ.rx(angle, qr[r]) self.circ.rx(angle, qr[s]) elif i == 7: self.circ.rx(angle, qr[p]) self.circ.h(qr[q]) self.circ.h(qr[r]) self.circ.rx(angle, qr[s]) elif i == 8: self.circ.h(qr[p]) self.circ.rx(angle, qr[q]) self.circ.rx(angle, qr[r]) self.circ.h(qr[s]) def CNOTLadder(self, controlStartIndex, controlStopIndex): """ Applies a ladder of CNOTs, as in the dashed-CNOT notation at bottom of Table A1 of Whitfield et al 2010 Qubit indices increase from bottom to top """ qr = self.circ.qregs[0] if controlStopIndex > controlStartIndex: delta = 1 index = controlStartIndex + 1 controlStopIndex += 1 else: delta = -1 index = controlStartIndex while index is not controlStopIndex: self.circ.cx(qr[index], qr[index - 1]) index += delta def DoubleExcitationOperator(self, theta, p, q, r, s): """ Prerequisite: p > q > r > s """ qr = self.circ.qregs[0] for i in range(1, 9): if self.barriers: self.circ.barrier(qr) self.M_d(i, p, q, r, s, dagger=False) if self.barriers: self.circ.barrier(qr) self.CNOTLadder(p, q) self.circ.cx(qr[q], qr[r]) self.CNOTLadder(r, s) self.circ.rz(theta, qr[s]) # Rz(reg[s], Theta_p_q_r_s[p][q][r][s]); self.CNOTLadder(s, r) self.circ.cx(qr[q], qr[r]) self.CNOTLadder(q, p) if self.barriers: self.circ.barrier(qr) self.M_d(i, p, q, r, s, dagger=True) def SingleExcitationOperator(self, theta, p, q): """ Prerequisite: p > q See Single Excitation Operator circuit in Table A1 of Whitfield et al 2010 """ qr = self.circ.qregs[0] if self.barriers: self.circ.barrier(qr) self.circ.h(qr[p]) self.circ.h(qr[q]) self.CNOTLadder(p, q) self.circ.rz(theta, qr[q]) # Rz(reg[q], Theta_p_q[p][q]); self.CNOTLadder(q, p) if self.barriers: self.circ.barrier(qr) self.circ.h(qr[p]) self.circ.h(qr[q]) self.circ.rx(-math.pi / 2, qr[p]) self.circ.rx(-math.pi / 2, qr[q]) self.CNOTLadder(p, q) self.circ.rz(theta, qr[q]) # Rz(reg[q], Theta_p_q[p][q]); self.CNOTLadder(q, p) if self.barriers: self.circ.barrier(qr) self.circ.rx(-math.pi / 2, qr[p]) self.circ.rx(-math.pi / 2, qr[q]) def gen_circuit(self): """ Create a circuit implementing the UCCSD ansatz Given the number of qubits and parameters, construct the ansatz as given in Whitfield et al. Returns ------- QuantumCircuit QuantumCircuit object of size nq with no ClassicalRegister and no measurements """ # Ensure the # of parameters matches what is neede by the current value of # Nq, then set a counter, p_i=0, when the circuit is first initialized, and # every call to the single or double operator will take param[p_i] as its # parameter and then increment the value of p_i num_dbl = (self.nq**4 - 6 * self.nq**3 + 11 * self.nq**2 - 6 * self.nq) / 24 num_sgl = (self.nq**2 - self.nq) / 2 numparam = int(num_dbl + num_sgl) if self.parameters == "random": param = np.random.uniform(-np.pi, np.pi, numparam) elif self.parameters == "seeded": if self.seed is None: raise Exception("A valid seed must be provided") else: np.random.seed(self.seed) param = np.random.uniform(-np.pi, np.pi, numparam) else: raise Exception("Unknown parameter option") p_i = 0 # enumerate all Nq > p > q > r > s >= 0 and apply Double Excitation Operator for p in range(self.nq): for q in range(p): for r in range(q): for s in range(r): # print(p,q,r,s) # For the 4 qubit case this function is called a single time self.DoubleExcitationOperator(param[p_i], p, q, r, s) p_i += 1 # enumerate all Nq > p > q >= 0 and apply Single Excitation Operator for p in range(self.nq): for q in range(p): # print(p,q) self.SingleExcitationOperator(param[p_i], p, q) p_i += 1 return self.circ
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
import numpy as np import pytest from qiskit import Aer from qiskit.algorithms.gradients import ReverseEstimatorGradient from qiskit.circuit.library import TwoLocal from qiskit.primitives import Estimator from qiskit.quantum_info import SparsePauliOp np.random.seed(0) max_parallel_threads = 12 gpu = False method = "statevector_gpu" def generate_circuit(nqubits): ansatz = TwoLocal( nqubits, ["rx", "ry", "rz"], ["cx"], "linear", reps=3, flatten=True, ).decompose() params = np.random.rand(ansatz.num_parameters) return ansatz, params def execute_statevector(benchmark, circuit, params): backend_options = { "method": method, "precision": "double", "max_parallel_threads": max_parallel_threads, "fusion_enable": True, "fusion_threshold": 14, "fusion_max_qubit": 5, } circuit = circuit.bind_parameters(params) backend = Aer.get_backend("statevector_simulator") backend.set_options(**backend_options) def evalfunc(backend, circuit): backend.run(circuit).result() benchmark(evalfunc, backend, circuit) def execute_estimator(benchmark, circuit, obs, params): estimator = Estimator() def evalfunc(estimator, circuit, obs, params): estimator.run([circuit], [obs], [params]).result() benchmark(evalfunc, estimator, circuit, obs, params) def execute_gradient(benchmark, circuit, obs, params): estimator_grad = ReverseEstimatorGradient() def evalfunc(estimator_grad, circuit, obs, params): estimator_grad.run([circuit], [obs], [params]).result() benchmark(evalfunc, estimator_grad, circuit, obs, params) nqubits_list = range(4, 21) @pytest.mark.parametrize("nqubits", nqubits_list) def test_statevector(benchmark, nqubits): benchmark.group = "qiskit_statevector" circuit, params = generate_circuit(nqubits) execute_statevector(benchmark, circuit, params) # @pytest.mark.parametrize("nqubits", nqubits_list) # def test_estimator(benchmark, nqubits): # benchmark.group = "qiskit_estimator" # circuit, params = generate_circuit(nqubits) # obs = SparsePauliOp.from_list([("Z" * nqubits, 1)]) # execute_estimator(benchmark, circuit, obs, params) # @pytest.mark.parametrize("nqubits", nqubits_list) # def test_gradient(benchmark, nqubits): # benchmark.group = "qiskit_gradient" # circuit, params = generate_circuit(nqubits) # obs = SparsePauliOp.from_list([("Z" * nqubits, 1)]) # execute_gradient(benchmark, circuit, obs, params)
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
from qiskit.providers.jobstatus import JobStatus from qiskit.transpiler import CouplingMap from datetime import timedelta, datetime from pytz import timezone import time, subprocess, os, pickle, logging, qiskit_ibm_provider import qiskit_ibm_provider.hub_group_project from qiskit_ibm_runtime import IBMBackend from typing import List, Dict import numpy as np from qiskit_helper_functions.non_ibmq_functions import read_dict def get_backend_info(backends: List[IBMBackend]) -> Dict: """ Get the IBM device information: - Number of qubits - Average gate error - Current number of pending jobs """ backend_info = {} for backend in backends: if backend.simulator: average_gate_error = 0 else: properties = backend.properties(refresh=True).to_dict() backend_gate_errors = [] for gate in properties["gates"]: for parameter in gate["parameters"]: if parameter["name"] == "gate_error": backend_gate_errors.append(parameter["value"]) average_gate_error = np.mean(backend_gate_errors) backend_info[backend] = { "num_qubits": backend.num_qubits, "average_gate_error": average_gate_error, "num_pending_jobs": backend.status().pending_jobs, } return backend_info def check_jobs(token, hub, group, project, cancel_jobs): provider = qiskit_ibm_provider.IBMProvider(token=token) time_now = datetime.now(timezone("EST")) delta = timedelta( days=1, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0 ) time_delta = time_now - delta for x in provider.backends(): if "qasm" not in str(x): device = provider.get_backend(str(x)) properties = device.properties() num_qubits = len(properties.qubits) print( "%s: %d-qubit, max %d jobs * %d shots" % ( x, num_qubits, x.configuration().max_experiments, x.configuration().max_shots, ) ) jobs_to_cancel = [] print("QUEUED:") print_ctr = 0 for job in x.jobs(limit=50, status=JobStatus["QUEUED"]): if print_ctr < 5: print( job.creation_date(), job.status(), job.queue_position(), job.job_id(), "ETA:", job.queue_info().estimated_complete_time - time_now, ) jobs_to_cancel.append(job) print_ctr += 1 print("RUNNING:") for job in x.jobs(limit=5, status=JobStatus["RUNNING"]): print(job.creation_date(), job.status(), job.queue_position()) jobs_to_cancel.append(job) print("DONE:") for job in x.jobs( limit=5, status=JobStatus["DONE"], start_datetime=time_delta ): print( job.creation_date(), job.status(), job.error_message(), job.job_id() ) print("ERROR:") for job in x.jobs( limit=5, status=JobStatus["ERROR"], start_datetime=time_delta ): print( job.creation_date(), job.status(), job.error_message(), job.job_id() ) if cancel_jobs and len(jobs_to_cancel) > 0: for i in range(3): print("Warning!!! Cancelling jobs! %d seconds count down" % (3 - i)) time.sleep(1) for job in jobs_to_cancel: print( job.creation_date(), job.status(), job.queue_position(), job.job_id(), ) job.cancel() print("cancelled") print("-" * 100)
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
import random, pickle, os, copy, random, qiskit_aer, psutil from qiskit import QuantumCircuit from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.dagcircuit.dagcircuit import DAGCircuit from qiskit.quantum_info import Statevector import numpy as np from qiskit_helper_functions.conversions import dict_to_array def scrambled(orig): dest = orig[:] random.shuffle(dest) return dest def read_dict(filename): if os.path.isfile(filename): f = open(filename, "rb") file_content = {} while 1: try: file_content.update(pickle.load(f)) except EOFError: break f.close() else: file_content = {} return file_content def apply_measurement(circuit, qubits): measured_circuit = QuantumCircuit(circuit.num_qubits, len(qubits)) for circuit_inst, circuit_qubits, circuit_clbits in circuit.data: measured_circuit.append(circuit_inst, circuit_qubits, circuit_clbits) measured_circuit.barrier(qubits) measured_circuit.measure(qubits, measured_circuit.clbits) return measured_circuit def evaluate_circ(circuit, backend, options=None): circuit = copy.deepcopy(circuit) max_memory_mb = psutil.virtual_memory().total >> 20 max_memory_mb = int(max_memory_mb / 4 * 3) if backend == "statevector_simulator": simulator = qiskit_aer.StatevectorSimulator() result = simulator.run(circuits=[circuit]).result() statevector = result.get_statevector(circuit) prob_vector = Statevector(statevector).probabilities() return prob_vector elif backend == "noiseless_qasm_simulator": simulator = qiskit_aer.AerSimulator(max_memory_mb=max_memory_mb) if isinstance(options, dict) and "num_shots" in options: num_shots = options["num_shots"] else: num_shots = max(1024, 2**circuit.num_qubits) if isinstance(options, dict) and "memory" in options: memory = options["memory"] else: memory = False if circuit.num_clbits == 0: circuit.measure_all() result = simulator.run(circuit, shots=num_shots, memory=memory).result() if memory: qasm_memory = np.array(result.get_memory(circuit)) assert len(qasm_memory) == num_shots return qasm_memory else: noiseless_counts = result.get_counts(circuit) assert sum(noiseless_counts.values()) == num_shots noiseless_counts = dict_to_array( distribution_dict=noiseless_counts, force_prob=True ) return noiseless_counts else: raise NotImplementedError def circuit_stripping(circuit): # Remove all single qubit gates and barriers in the circuit dag = circuit_to_dag(circuit) stripped_dag = DAGCircuit() [stripped_dag.add_qreg(x) for x in circuit.qregs] for vertex in dag.topological_op_nodes(): if len(vertex.qargs) == 2 and vertex.op.name != "barrier": stripped_dag.apply_operation_back(op=vertex.op, qargs=vertex.qargs) return dag_to_circuit(stripped_dag) def dag_stripping(dag, max_gates): """ Remove all single qubit gates and barriers in the DAG Only leaves the first max_gates gates If max_gates is None, do all gates """ stripped_dag = DAGCircuit() [stripped_dag.add_qreg(dag.qregs[qreg_name]) for qreg_name in dag.qregs] vertex_added = 0 for vertex in dag.topological_op_nodes(): within_gate_count = max_gates is None or vertex_added < max_gates if vertex.op.name != "barrier" and len(vertex.qargs) == 2 and within_gate_count: stripped_dag.apply_operation_back(op=vertex.op, qargs=vertex.qargs) vertex_added += 1 return stripped_dag def _calc_exp_val(num_qubits: int, observable: str, state: int, prob: float) -> float: """Calculate the weighted eigen value of a state and its given prob Z|0> = |0> Z|1> = -|1> I|0> = |0> I|1> = |1> Args: num_qubits (int): _description_ observable (str): _description_ state_prob (Tuple[int, float]): _description_ Returns: float: _description_ """ eigenvals = {"Z": {"0": 1, "1": -1}, "I": {"0": 1, "1": 1}} bin_state = bin(state)[2:].zfill(num_qubits) eigenval = 1 for bit, base in zip(bin_state, observable): eigenval *= eigenvals[base][bit] return prob * eigenval def expectation_val(prob_vector: np.ndarray, observable: str) -> float: """Calculate the expectation value of a given probability vector Args: prob_vector (np.ndarray): input probability vector observable (str): Z or I observables Returns: float: expectation value """ num_qubits = len(observable) exp_val = 0 for state, prob in enumerate(prob_vector): exp_val += _calc_exp_val(num_qubits, observable, state, prob) return exp_val
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
from qiskit import QuantumCircuit from qiskit.circuit.library import CPhaseGate, HGate, TGate, XGate, YGate, ZGate from qiskit.converters import circuit_to_dag, dag_to_circuit import random, itertools class RandomCircuit(object): def __init__(self, width, depth, connection_degree, num_hadamards, seed) -> None: """ Generate a random benchmark circuit width: number of qubits depth: depth of the random circuit connection_degree: max number of direct contacts num_hadamards: number of H gates in the encoding layer. Overall number of solutions = 2^num_H """ super().__init__() random.seed(seed) self.width = width self.depth = depth self.num_hadamards = num_hadamards self.num_targets_ubs = [] for qubit in range(width): max_num_targets = self.width - 1 - qubit num_targets_ub = int(connection_degree * max_num_targets) if qubit < width - 1: num_targets_ub = max(num_targets_ub, 1) self.num_targets_ubs.append(num_targets_ub) # print('num_targets_ubs = {}'.format(self.num_targets_ubs)) def generate(self): entangled_circuit, num_targets = self.generate_entangled() """ Encode random solution states """ encoding_qubits = random.sample(range(self.width), self.num_hadamards) quantum_states = [["0"] for qubit in range(self.width)] for qubit in encoding_qubits: entangled_circuit.append(instruction=HGate(), qargs=[qubit]) quantum_states[qubit] = ["0", "1"] solution_states_strings = itertools.product(*quantum_states) solution_states = [] for binary_state in solution_states_strings: binary_state = "".join(binary_state[::-1]) state = int(binary_state, 2) solution_states.append(state) # print('%d 2q gates. %d tensor factors. %d depth.'%( # entangled_circuit.num_nonlocal_gates(), # entangled_circuit.num_unitary_factors(), # entangled_circuit.depth() # )) # print('num_targets = {}'.format(num_targets)) return entangled_circuit, solution_states def generate_entangled(self): left_circuit = QuantumCircuit(self.width, name="q") left_dag = circuit_to_dag(left_circuit) right_circuit = QuantumCircuit(self.width, name="q") right_dag = circuit_to_dag(right_circuit) qubit_targets = {qubit: set() for qubit in range(self.width)} while True: """ Apply a random two-qubit gate to either left_dag or right_dag """ random_control_qubit_idx = self.get_random_control(qubit_targets) random_target_qubit_idx = self.get_random_target( random_control_qubit_idx, qubit_targets ) dag_to_apply = random.choice([left_dag, right_dag]) random_control_qubit = dag_to_apply.qubits[random_control_qubit_idx] random_target_qubit = dag_to_apply.qubits[random_target_qubit_idx] dag_to_apply.apply_operation_back( op=CPhaseGate(theta=0.0), qargs=[random_control_qubit, random_target_qubit], cargs=[], ) qubit_targets[random_control_qubit_idx].add(random_target_qubit_idx) """ Apply a random 1-q gate to left_dag Apply its inverse to right_dag """ single_qubit_gate = random.choice( [HGate(), TGate(), XGate(), YGate(), ZGate()] ) random_qubit = left_dag.qubits[random.choice(range(self.width))] left_dag.apply_operation_back( op=single_qubit_gate, qargs=[random_qubit], cargs=[] ) right_dag.apply_operation_front( op=single_qubit_gate.inverse(), qargs=[random_qubit], cargs=[] ) """ Terminate when there is enough depth """ if left_dag.depth() + right_dag.depth() >= self.depth: break entangled_dag = left_dag.compose(right_dag, inplace=False) entangled_circuit = dag_to_circuit(entangled_dag) num_targets = [len(qubit_targets[qubit]) for qubit in range(self.width)] for qubit in range(self.width): assert num_targets[qubit] <= self.num_targets_ubs[qubit] return entangled_circuit, num_targets def get_random_control(self, qubit_targets): """ Get a random control qubit Prioritize the ones with spare targets Else choose from qubits with #targets>0 """ candidates = [] for qubit in qubit_targets: if len(qubit_targets[qubit]) < self.num_targets_ubs[qubit]: candidates.append(qubit) if len(candidates) > 0: return random.choice(candidates) else: candidates = [] for qubit, num_targets in enumerate(self.num_targets_ubs): if num_targets > 0: candidates.append(qubit) return random.choice(candidates) def get_random_target(self, control_qubit, qubit_targets): """ Get a random target qubit If the control qubit has exhausted its #targets, choose from existing targets Else prioritize the ones that have not been used """ if len(qubit_targets[control_qubit]) < self.num_targets_ubs[control_qubit]: candidates = [] for qubit in range(control_qubit + 1, self.width): if qubit not in qubit_targets[control_qubit]: candidates.append(qubit) return random.choice(candidates) else: return random.choice(list(qubit_targets[control_qubit]))
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # 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=cyclic-import """ ========= Schedules ========= .. currentmodule:: qiskit.pulse Schedules are Pulse programs. They describe instruction sequences for the control hardware. The Schedule is one of the most fundamental objects to this pulse-level programming module. A ``Schedule`` is a representation of a *program* in Pulse. Each schedule tracks the time of each instruction occuring in parallel over multiple signal *channels*. .. autosummary:: :toctree: ../stubs/ Schedule ScheduleBlock """ import abc import copy import functools import itertools import multiprocessing as mp import re import sys import warnings from typing import List, Tuple, Iterable, Union, Dict, Callable, Set, Optional, Any import numpy as np import rustworkx as rx from qiskit.circuit.parameter import Parameter from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse.channels import Channel from qiskit.pulse.exceptions import PulseError, UnassignedReferenceError from qiskit.pulse.instructions import Instruction, Reference from qiskit.pulse.utils import instruction_duration_validation from qiskit.pulse.reference_manager import ReferenceManager from qiskit.utils.multiprocessing import is_main_process Interval = Tuple[int, int] """An interval type is a tuple of a start time (inclusive) and an end time (exclusive).""" TimeSlots = Dict[Channel, List[Interval]] """List of timeslots occupied by instructions for each channel.""" class Schedule: """A quantum program *schedule* with exact time constraints for its instructions, operating over all input signal *channels* and supporting special syntaxes for building. Pulse program representation for the original Qiskit Pulse model [1]. Instructions are not allowed to overlap in time on the same channel. This overlap constraint is immediately evaluated when a new instruction is added to the ``Schedule`` object. It is necessary to specify the absolute start time and duration for each instruction so as to deterministically fix its execution time. The ``Schedule`` program supports some syntax sugar for easier programming. - Appending an instruction to the end of a channel .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) - Appending an instruction shifted in time by a given amount .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) << 30 - Merge two schedules .. code-block:: python sched1 = Schedule() sched1 += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) sched2 = Schedule() sched2 += Play(Gaussian(160, 0.1, 40), DriveChannel(1)) sched2 = sched1 | sched2 A :obj:`.PulseError` is immediately raised when the overlap constraint is violated. In the schedule representation, we cannot parametrize the duration of instructions. Thus we need to create a new schedule object for each duration. To parametrize an instruction's duration, the :class:`~qiskit.pulse.ScheduleBlock` representation may be used instead. References: [1]: https://arxiv.org/abs/2004.06755 """ # Prefix to use for auto naming. prefix = "sched" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, *schedules: Union["ScheduleComponent", Tuple[int, "ScheduleComponent"]], name: Optional[str] = None, metadata: Optional[dict] = None, ): """Create an empty schedule. Args: *schedules: Child Schedules of this parent Schedule. May either be passed as the list of schedules, or a list of ``(start_time, schedule)`` pairs. name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.Schedule.metadata` attribute. It will not be directly used in the schedule. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" self._name = name self._parameter_manager = ParameterManager() if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} self._duration = 0 # These attributes are populated by ``_mutable_insert`` self._timeslots = {} self._children = [] for sched_pair in schedules: try: time, sched = sched_pair except TypeError: # recreate as sequence starting at 0. time, sched = 0, sched_pair self._mutable_insert(time, sched) @classmethod def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "Schedule": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``schedule`` is used by default. Returns: New schedule object with name and metadata. Raises: PulseError: When `other_program` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None return cls(name=name, metadata=metadata) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Name of this Schedule""" return self._name @property def metadata(self) -> Dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def timeslots(self) -> TimeSlots: """Time keeping attribute.""" return self._timeslots @property def duration(self) -> int: """Duration of this schedule.""" return self._duration @property def start_time(self) -> int: """Starting time of this schedule.""" return self.ch_start_time(*self.channels) @property def stop_time(self) -> int: """Stopping time of this schedule.""" return self.duration @property def channels(self) -> Tuple[Channel]: """Returns channels that this schedule uses.""" return tuple(self._timeslots.keys()) @property def children(self) -> Tuple[Tuple[int, "ScheduleComponent"], ...]: """Return the child schedule components of this ``Schedule`` in the order they were added to the schedule. Notes: Nested schedules are returned as-is. If you want to collect only instructions, use py:meth:`~Schedule.instructions` instead. Returns: A tuple, where each element is a two-tuple containing the initial scheduled time of each ``NamedValue`` and the component itself. """ return tuple(self._children) @property def instructions(self) -> Tuple[Tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" def key(time_inst_pair): inst = time_inst_pair[1] return time_inst_pair[0], inst.duration, sorted(chan.name for chan in inst.channels) return tuple(sorted(self._instructions(), key=key)) @property def parameters(self) -> Set: """Parameters which determine the schedule behavior.""" return self._parameter_manager.parameters def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_stop_time(*channels) def ch_start_time(self, *channels: Channel) -> int: """Return the time of the start of the first instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return min(intervals[0][0] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def ch_stop_time(self, *channels: Channel) -> int: """Return maximum start time over supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return max(intervals[-1][1] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def _instructions(self, time: int = 0): """Iterable for flattening Schedule tree. Args: time: Shifted time due to parent. Yields: Iterable[Tuple[int, Instruction]]: Tuple containing the time each :class:`~qiskit.pulse.Instruction` starts at and the flattened :class:`~qiskit.pulse.Instruction` s. """ for insert_time, child_sched in self.children: yield from child_sched._instructions(time + insert_time) def shift(self, time: int, name: Optional[str] = None, inplace: bool = False) -> "Schedule": """Return a schedule shifted forward by ``time``. Args: time: Time to shift by. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_shift(time) return self._immutable_shift(time, name=name) def _immutable_shift(self, time: int, name: Optional[str] = None) -> "Schedule": """Return a new schedule shifted forward by `time`. Args: time: Time to shift by name: Name of the new schedule if call was mutable. Defaults to name of self """ shift_sched = Schedule.initialize_from(self, name) shift_sched.insert(time, self, inplace=True) return shift_sched def _mutable_shift(self, time: int) -> "Schedule": """Return this schedule shifted forward by `time`. Args: time: Time to shift by Raises: PulseError: if ``time`` is not an integer. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") timeslots = {} for chan, ch_timeslots in self._timeslots.items(): timeslots[chan] = [(ts[0] + time, ts[1] + time) for ts in ch_timeslots] _check_nonnegative_timeslot(timeslots) self._duration = self._duration + time self._timeslots = timeslots self._children = [(orig_time + time, child) for orig_time, child in self.children] return self def insert( self, start_time: int, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_insert(start_time, schedule) return self._immutable_insert(start_time, schedule, name=name) def _mutable_insert(self, start_time: int, schedule: "ScheduleComponent") -> "Schedule": """Mutably insert `schedule` into `self` at `start_time`. Args: start_time: Time to insert the second schedule. schedule: Schedule to mutably insert. """ self._add_timeslots(start_time, schedule) self._children.append((start_time, schedule)) self._parameter_manager.update_parameter_table(schedule) return self def _immutable_insert( self, start_time: int, schedule: "ScheduleComponent", name: Optional[str] = None, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new ``Schedule``. Defaults to name of ``self``. """ new_sched = Schedule.initialize_from(self, name) new_sched._mutable_insert(0, self) new_sched._mutable_insert(start_time, schedule) return new_sched def append( self, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False ) -> "Schedule": r"""Return a new schedule with ``schedule`` inserted at the maximum time over all channels shared between ``self`` and ``schedule``. .. math:: t = \textrm{max}(\texttt{x.stop_time} |\texttt{x} \in \texttt{self.channels} \cap \texttt{schedule.channels}) Args: schedule: Schedule to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ common_channels = set(self.channels) & set(schedule.channels) time = self.ch_stop_time(*common_channels) return self.insert(time, schedule, name=name, inplace=inplace) def filter( self, *filter_funcs: Callable, channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, time_ranges: Optional[Iterable[Tuple[int, int]]] = None, intervals: Optional[Iterable[Interval]] = None, check_subroutine: bool = True, ) -> "Schedule": """Return a new ``Schedule`` with only the instructions from this ``Schedule`` which pass though the provided filters; i.e. an instruction will be retained iff every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, the instruction type is contained in ``instruction_types``, and the period over which the instruction operates is *fully* contained in one specified in ``time_ranges`` or ``intervals``. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: Callable, channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, time_ranges: Optional[Iterable[Tuple[int, int]]] = None, intervals: Optional[Iterable[Interval]] = None, check_subroutine: bool = True, ) -> "Schedule": """Return a ``Schedule`` with only the instructions from this Schedule *failing* at least one of the provided filters. This method is the complement of py:meth:`~self.filter`, so that:: self.filter(args) | self.exclude(args) == self Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def _add_timeslots(self, time: int, schedule: "ScheduleComponent") -> None: """Update all time tracking within this schedule based on the given schedule. Args: time: The time to insert the schedule into self. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not np.issubdtype(type(time), np.integer): raise PulseError("Schedule start time must be an integer.") other_timeslots = _get_timeslots(schedule) self._duration = max(self._duration, time + schedule.duration) for channel in schedule.channels: if channel not in self._timeslots: if time == 0: self._timeslots[channel] = copy.copy(other_timeslots[channel]) else: self._timeslots[channel] = [ (i[0] + time, i[1] + time) for i in other_timeslots[channel] ] continue for idx, interval in enumerate(other_timeslots[channel]): if interval[0] + time >= self._timeslots[channel][-1][1]: # Can append the remaining intervals self._timeslots[channel].extend( [(i[0] + time, i[1] + time) for i in other_timeslots[channel][idx:]] ) break try: interval = (interval[0] + time, interval[1] + time) index = _find_insertion_index(self._timeslots[channel], interval) self._timeslots[channel].insert(index, interval) except PulseError as ex: raise PulseError( "Schedule(name='{new}') cannot be inserted into Schedule(name='{old}') at " "time {time} because its instruction on channel {ch} scheduled from time " "{t0} to {tf} overlaps with an existing instruction." "".format( new=schedule.name or "", old=self.name or "", time=time, ch=channel, t0=interval[0], tf=interval[1], ) ) from ex _check_nonnegative_timeslot(self._timeslots) def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"): """Delete the timeslots if present for the respective schedule component. Args: time: The time to remove the timeslots for the ``schedule`` component. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") for channel in schedule.channels: if channel not in self._timeslots: raise PulseError(f"The channel {channel} is not present in the schedule") channel_timeslots = self._timeslots[channel] other_timeslots = _get_timeslots(schedule) for interval in other_timeslots[channel]: if channel_timeslots: interval = (interval[0] + time, interval[1] + time) index = _interval_index(channel_timeslots, interval) if channel_timeslots[index] == interval: channel_timeslots.pop(index) continue raise PulseError( "Cannot find interval ({t0}, {tf}) to remove from " "channel {ch} in Schedule(name='{name}').".format( ch=channel, t0=interval[0], tf=interval[1], name=schedule.name ) ) if not channel_timeslots: self._timeslots.pop(channel) def _replace_timeslots(self, time: int, old: "ScheduleComponent", new: "ScheduleComponent"): """Replace the timeslots of ``old`` if present with the timeslots of ``new``. Args: time: The time to remove the timeslots for the ``schedule`` component. old: Instruction to replace. new: Instruction to replace with. """ self._remove_timeslots(time, old) self._add_timeslots(time, new) def _renew_timeslots(self): """Regenerate timeslots based on current instructions.""" self._timeslots.clear() for t0, inst in self.instructions: self._add_timeslots(t0, inst) def replace( self, old: "ScheduleComponent", new: "ScheduleComponent", inplace: bool = False, ) -> "Schedule": """Return a ``Schedule`` with the ``old`` instruction replaced with a ``new`` instruction. The replacement matching is based on an instruction equality check. .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) sched = pulse.Schedule() old = pulse.Play(pulse.Constant(100, 1.0), d0) new = pulse.Play(pulse.Constant(100, 0.1), d0) sched += old sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Only matches at the top-level of the schedule tree. If you wish to perform this replacement over all instructions in the schedule tree. Flatten the schedule prior to running:: .. code-block:: sched = pulse.Schedule() sched += pulse.Schedule(old) sched = sched.flatten() sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Args: old: Instruction to replace. new: Instruction to replace with. inplace: Replace instruction by mutably modifying this ``Schedule``. Returns: The modified schedule with ``old`` replaced by ``new``. Raises: PulseError: If the ``Schedule`` after replacements will has a timing overlap. """ from qiskit.pulse.parameter_manager import ParameterManager new_children = [] new_parameters = ParameterManager() for time, child in self.children: if child == old: new_children.append((time, new)) new_parameters.update_parameter_table(new) else: new_children.append((time, child)) new_parameters.update_parameter_table(child) if inplace: self._children = new_children self._parameter_manager = new_parameters self._renew_timeslots() return self else: try: new_sched = Schedule.initialize_from(self) for time, inst in new_children: new_sched.insert(time, inst, inplace=True) return new_sched except PulseError as err: raise PulseError( f"Replacement of {old} with {new} results in overlapping instructions." ) from err def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return self._parameter_manager.is_parameterized() def assign_parameters( self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True ) -> "Schedule": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from Parameters to either numeric values or another Parameter expression. inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) return self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) def get_parameters(self, parameter_name: str) -> List[Parameter]: """Get parameter object bound to this schedule by string name. Because different ``Parameter`` objects can have the same name, this method returns a list of ``Parameter`` s for the provided name. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ return self._parameter_manager.get_parameters(parameter_name) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.instructions) def __add__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def __or__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule which is the union of `self` and `other`.""" return self.insert(0, other) def __lshift__(self, time: int) -> "Schedule": """Return a new schedule which is shifted forward by ``time``.""" return self.shift(time) def __eq__(self, other: "ScheduleComponent") -> bool: """Test if two Schedule are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``Schedule``. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check, we consider Instruction is a subtype of schedule if not isinstance(other, (type(self), Instruction)): return False # 1. channel check if set(self.channels) != set(other.channels): return False # 2. size check if len(self.instructions) != len(other.instructions): return False # 3. instruction check return all( self_inst == other_inst for self_inst, other_inst in zip(self.instructions, other.instructions) ) def __repr__(self) -> str: name = format(self._name) if self._name else "" instructions = ", ".join([repr(instr) for instr in self.instructions[:50]]) if len(self.instructions) > 25: instructions += ", ..." return f'{self.__class__.__name__}({instructions}, name="{name}")' def _require_schedule_conversion(function: Callable) -> Callable: """A method decorator to convert schedule block to pulse schedule. This conversation is performed for backward compatibility only if all durations are assigned. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): from qiskit.pulse.transforms import block_to_schedule return function(block_to_schedule(self), *args, **kwargs) return wrapper class ScheduleBlock: """Time-ordered sequence of instructions with alignment context. :class:`.ScheduleBlock` supports lazy scheduling of context instructions, i.e. their timeslots is always generated at runtime. This indicates we can parametrize instruction durations as well as other parameters. In contrast to :class:`.Schedule` being somewhat static, :class:`.ScheduleBlock` is a dynamic representation of a pulse program. .. rubric:: Pulse Builder The Qiskit pulse builder is a domain specific language that is developed on top of the schedule block. Use of the builder syntax will improve the workflow of pulse programming. See :ref:`pulse_builder` for a user guide. .. rubric:: Alignment contexts A schedule block is always relatively scheduled. Instead of taking individual instructions with absolute execution time ``t0``, the schedule block defines a context of scheduling and instructions under the same context are scheduled in the same manner (alignment). Several contexts are available in :ref:`pulse_alignments`. A schedule block is instantiated with one of these alignment contexts. The default context is :class:`AlignLeft`, for which all instructions are left-justified, in other words, meaning they use as-soon-as-possible scheduling. If you need an absolute-time interval in between instructions, you can explicitly insert :class:`~qiskit.pulse.instructions.Delay` instructions. .. rubric:: Nested blocks A schedule block can contain other nested blocks with different alignment contexts. This enables advanced scheduling, where a subset of instructions is locally scheduled in a different manner. Note that a :class:`.Schedule` instance cannot be directly added to a schedule block. To add a :class:`.Schedule` instance, wrap it in a :class:`.Call` instruction. This is implicitly performed when a schedule is added through the :ref:`pulse_builder`. .. rubric:: Unsupported operations Because the schedule block representation lacks timeslots, it cannot perform particular :class:`.Schedule` operations such as :meth:`insert` or :meth:`shift` that require instruction start time ``t0``. In addition, :meth:`exclude` and :meth:`filter` methods are not supported because these operations may identify the target instruction with ``t0``. Except for these operations, :class:`.ScheduleBlock` provides full compatibility with :class:`.Schedule`. .. rubric:: Subroutine The timeslots-free representation offers much greater flexibility for writing pulse programs. Because :class:`.ScheduleBlock` only cares about the ordering of the child blocks we can add an undefined pulse sequence as a subroutine of the main program. If your program contains the same sequence multiple times, this representation may reduce the memory footprint required by the program construction. Such a subroutine is realized by the special compiler directive :class:`~qiskit.pulse.instructions.Reference` that is defined by a unique set of reference key strings to the subroutine. The (executable) subroutine is separately stored in the main program. Appended reference directives are resolved when the main program is executed. Subroutines must be assigned through :meth:`assign_references` before execution. .. rubric:: Program Scoping When you call a subroutine from another subroutine, or append a schedule block to another schedule block, the management of references and parameters can be a hard task. Schedule block offers a convenient feature to help with this by automatically scoping the parameters and subroutines. .. code-block:: from qiskit import pulse from qiskit.circuit.parameter import Parameter amp1 = Parameter("amp") with pulse.build() as sched1: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) print(sched1.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp),) The :meth:`~ScheduleBlock.scoped_parameters` method returns all :class:`~.Parameter` objects defined in the schedule block. The parameter name is updated to reflect its scope information, i.e. where it is defined. The outer scope is called "root". Since the "amp" parameter is directly used in the current builder context, it is prefixed with "root". Note that the :class:`Parameter` object returned by :meth:`~ScheduleBlock.scoped_parameters` preserves the hidden `UUID`_ key, and thus the scoped name doesn't break references to the original :class:`Parameter`. You may want to call this program from another program. In this example, the program is called with the reference key "grand_child". You can call a subroutine without specifying a substantial program (like ``sched1`` above which we will assign later). .. code-block:: amp2 = Parameter("amp") with pulse.build() as sched2: with pulse.align_right(): pulse.reference("grand_child") pulse.play(pulse.Constant(200, amp2), pulse.DriveChannel(0)) print(sched2.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp),) This only returns "root::amp" because the "grand_child" reference is unknown. Now you assign the actual pulse program to this reference. .. code-block:: sched2.assign_references({("grand_child", ): sched1}) print(sched2.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp), Parameter(root::grand_child::amp)) Now you get two parameters "root::amp" and "root::grand_child::amp". The second parameter name indicates it is defined within the referred program "grand_child". The program calling the "grand_child" has a reference program description which is accessed through :attr:`ScheduleBlock.references`. .. code-block:: print(sched2.references) .. parsed-literal:: ReferenceManager: - ('grand_child',): ScheduleBlock(Play(Constant(duration=100, amp=amp,... Finally, you may want to call this program from another program. Here we try a different approach to define subroutine. Namely, we call a subroutine from the root program with the actual program ``sched2``. .. code-block:: amp3 = Parameter("amp") with pulse.build() as main: pulse.play(pulse.Constant(300, amp3), pulse.DriveChannel(0)) pulse.call(sched2, name="child") print(main.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp), Parameter(root::child::amp), Parameter(root::child::grand_child::amp)) This implicitly creates a reference named "child" within the root program and assigns ``sched2`` to it. You get three parameters "root::amp", "root::child::amp", and "root::child::grand_child::amp". As you can see, each parameter name reflects the layer of calls from the root program. If you know the scope of a parameter, you can directly get the parameter object using :meth:`ScheduleBlock.search_parameters` as follows. .. code-block:: main.search_parameters("root::child::grand_child::amp") You can use a regular expression to specify the scope. The following returns the parameters defined within the scope of "ground_child" regardless of its parent scope. This is sometimes convenient if you want to extract parameters from a deeply nested program. .. code-block:: main.search_parameters("\\S::grand_child::amp") Note that the root program is only aware of its direct references. .. code-block:: print(main.references) .. parsed-literal:: ReferenceManager: - ('child',): ScheduleBlock(ScheduleBlock(ScheduleBlock(Play(Con... As you can see the main program cannot directly assign a subroutine to the "grand_child" because this subroutine is not called within the root program, i.e. it is indirectly called by "child". However, the returned :class:`.ReferenceManager` is a dict-like object, and you can still reach to "grand_child" via the "child" program with the following chained dict access. .. code-block:: main.references[("child", )].references[("grand_child", )] Note that :attr:`ScheduleBlock.parameters` and :meth:`ScheduleBlock.scoped_parameters()` still collect all parameters also from the subroutine once it's assigned. .. _UUID: https://docs.python.org/3/library/uuid.html#module-uuid """ __slots__ = ( "_parent", "_name", "_reference_manager", "_parameter_manager", "_alignment_context", "_blocks", "_metadata", ) # Prefix to use for auto naming. prefix = "block" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, name: Optional[str] = None, metadata: Optional[dict] = None, alignment_context=None ): """Create an empty schedule block. Args: name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.ScheduleBlock.metadata` attribute. It will not be directly used in the schedule. alignment_context (AlignmentKind): ``AlignmentKind`` instance that manages scheduling of instructions in this block. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager from qiskit.pulse.transforms import AlignLeft if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" # This points to the parent schedule object in the current scope. # Note that schedule block can be nested without referencing, e.g. .append(child_block), # and parent=None indicates the root program of the current scope. # The nested schedule block objects should not have _reference_manager and # should refer to the one of the root program. # This also means referenced program should be assigned to the root program, not to child. self._parent = None self._name = name self._parameter_manager = ParameterManager() self._reference_manager = ReferenceManager() self._alignment_context = alignment_context or AlignLeft() self._blocks = [] # get parameters from context self._parameter_manager.update_parameter_table(self._alignment_context) if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @classmethod def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "ScheduleBlock": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``block`` is used by default. Returns: New block object with name and metadata. Raises: PulseError: When ``other_program`` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None try: alignment_context = other_program.alignment_context except AttributeError: alignment_context = None return cls(name=name, metadata=metadata, alignment_context=alignment_context) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Return name of this schedule""" return self._name @property def metadata(self) -> Dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def alignment_context(self): """Return alignment instance that allocates block component to generate schedule.""" return self._alignment_context def is_schedulable(self) -> bool: """Return ``True`` if all durations are assigned.""" # check context assignment for context_param in self._alignment_context._context_params: if isinstance(context_param, ParameterExpression): return False # check duration assignment for elm in self.blocks: if isinstance(elm, ScheduleBlock): if not elm.is_schedulable(): return False else: try: if not isinstance(elm.duration, int): return False except UnassignedReferenceError: return False return True @property @_require_schedule_conversion def duration(self) -> int: """Duration of this schedule block.""" return self.duration @property def channels(self) -> Tuple[Channel]: """Returns channels that this schedule block uses.""" chans = set() for elm in self.blocks: if isinstance(elm, Reference): raise UnassignedReferenceError( f"This schedule contains unassigned reference {elm.ref_keys} " "and channels are ambiguous. Please assign the subroutine first." ) chans = chans | set(elm.channels) return tuple(chans) @property @_require_schedule_conversion def instructions(self) -> Tuple[Tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" return self.instructions @property def blocks(self) -> Tuple["BlockComponent", ...]: """Get the block elements added to self. .. note:: The sequence of elements is returned in order of addition. Because the first element is schedule first, e.g. FIFO, the returned sequence is roughly time-ordered. However, in the parallel alignment context, especially in the as-late-as-possible scheduling, or :class:`.AlignRight` context, the actual timing of when the instructions are issued is unknown until the :class:`.ScheduleBlock` is scheduled and converted into a :class:`.Schedule`. """ blocks = [] for elm in self._blocks: if isinstance(elm, Reference): elm = self.references.get(elm.ref_keys, None) or elm blocks.append(elm) return tuple(blocks) @property def parameters(self) -> Set[Parameter]: """Return unassigned parameters with raw names.""" # Need new object not to mutate parameter_manager.parameters out_params = set() out_params |= self._parameter_manager.parameters for subroutine in self.references.values(): if subroutine is None: continue out_params |= subroutine.parameters return out_params def scoped_parameters(self) -> Tuple[Parameter]: """Return unassigned parameters with scoped names. .. note:: If a parameter is defined within a nested scope, it is prefixed with all parent-scope names with the delimiter string, which is "::". If a reference key of the scope consists of multiple key strings, it will be represented by a single string joined with ",". For example, "root::xgate,q0::amp" for the parameter "amp" defined in the reference specified by the key strings ("xgate", "q0"). """ return tuple( sorted( _collect_scoped_parameters(self, current_scope="root").values(), key=lambda p: p.name, ) ) @property def references(self) -> ReferenceManager: """Return a reference manager of the current scope.""" if self._parent is not None: return self._parent.references return self._reference_manager @_require_schedule_conversion def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_duration(*channels) def append( self, block: "BlockComponent", name: Optional[str] = None, inplace: bool = True ) -> "ScheduleBlock": """Return a new schedule block with ``block`` appended to the context block. The execution time is automatically assigned when the block is converted into schedule. Args: block: ScheduleBlock to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise, return a new ``Schedule``. Returns: Schedule block with appended schedule. Raises: PulseError: When invalid schedule type is specified. """ if not isinstance(block, (ScheduleBlock, Instruction)): raise PulseError( f"Appended `schedule` {block.__class__.__name__} is invalid type. " "Only `Instruction` and `ScheduleBlock` can be accepted." ) if not inplace: schedule = copy.deepcopy(self) schedule._name = name or self.name schedule.append(block, inplace=True) return schedule if isinstance(block, Reference) and block.ref_keys not in self.references: self.references[block.ref_keys] = None elif isinstance(block, ScheduleBlock): block = copy.deepcopy(block) # Expose subroutines to the current main scope. # Note that this 'block' is not called. # The block is just directly appended to the current scope. if block.is_referenced(): if block._parent is not None: # This is an edge case: # If this is not a parent, block.references points to the parent's reference # where subroutine not referred within the 'block' may exist. # Move only references existing in the 'block'. # See 'test.python.pulse.test_reference.TestReference.test_appending_child_block' for ref in _get_references(block._blocks): self.references[ref.ref_keys] = block.references[ref.ref_keys] else: # Avoid using dict.update and explicitly call __set_item__ for validation. # Reference manager of appended block is cleared because of data reduction. for ref_keys, ref in block._reference_manager.items(): self.references[ref_keys] = ref block._reference_manager.clear() # Now switch the parent because block is appended to self. block._parent = self self._blocks.append(block) self._parameter_manager.update_parameter_table(block) return self def filter( self, *filter_funcs: List[Callable], channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` which pass though the provided filters; i.e. an instruction will be retained if every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, and the instruction type is contained in ``instruction_types``. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, filtering out some instructions may change the execution time of the remaining instructions. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that matches with filtering condition. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: List[Callable], channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` *failing* at least one of the provided filters. This method is the complement of py:meth:`~self.filter`, so that:: self.filter(args) + self.exclude(args) == self in terms of instructions included. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, excluding some instructions may change the execution time of the remaining instructions. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that do not match with at least one of filtering conditions. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def replace( self, old: "BlockComponent", new: "BlockComponent", inplace: bool = True, ) -> "ScheduleBlock": """Return a ``ScheduleBlock`` with the ``old`` component replaced with a ``new`` component. Args: old: Schedule block component to replace. new: Schedule block component to replace with. inplace: Replace instruction by mutably modifying this ``ScheduleBlock``. Returns: The modified schedule block with ``old`` replaced by ``new``. """ if not inplace: schedule = copy.deepcopy(self) return schedule.replace(old, new, inplace=True) if old not in self._blocks: # Avoid unnecessary update of reference and parameter manager return self # Temporarily copies references all_references = ReferenceManager() if isinstance(new, ScheduleBlock): new = copy.deepcopy(new) all_references.update(new.references) new._reference_manager.clear() new._parent = self for ref_key, subroutine in self.references.items(): if ref_key in all_references: warnings.warn( f"Reference {ref_key} conflicts with substituted program {new.name}. " "Existing reference has been replaced with new reference.", UserWarning, ) continue all_references[ref_key] = subroutine # Regenerate parameter table by regenerating elements. # Note that removal of parameters in old is not sufficient, # because corresponding parameters might be also used in another block element. self._parameter_manager.clear() self._parameter_manager.update_parameter_table(self._alignment_context) new_elms = [] for elm in self._blocks: if elm == old: elm = new self._parameter_manager.update_parameter_table(elm) new_elms.append(elm) self._blocks = new_elms # Regenerate reference table # Note that reference is attached to the outer schedule if nested. # Thus, this investigates all references within the scope. self.references.clear() root = self while root._parent is not None: root = root._parent for ref in _get_references(root._blocks): self.references[ref.ref_keys] = all_references[ref.ref_keys] return self def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return any(self.parameters) def is_referenced(self) -> bool: """Return True iff the current schedule block contains reference to subroutine.""" return len(self.references) > 0 def assign_parameters( self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True, ) -> "ScheduleBlock": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from Parameters to either numeric values or another Parameter expression. inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. Raises: PulseError: When the block is nested into another block. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) # Update parameters in the current scope self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) for subroutine in self._reference_manager.values(): # Also assigning parameters to the references associated with self. # Note that references are always stored in the root program. # So calling assign_parameters from nested block doesn't update references. if subroutine is None: continue subroutine.assign_parameters(value_dict=value_dict, inplace=True) return self def assign_references( self, subroutine_dict: Dict[Union[str, Tuple[str, ...]], "ScheduleBlock"], inplace: bool = True, ) -> "ScheduleBlock": """Assign schedules to references. It is only capable of assigning a schedule block to immediate references which are directly referred within the current scope. Let's see following example: .. code-block:: python from qiskit import pulse with pulse.build() as subroutine: pulse.delay(10, pulse.DriveChannel(0)) with pulse.build() as sub_prog: pulse.reference("A") with pulse.build() as main_prog: pulse.reference("B") In above example, the ``main_prog`` can refer to the subroutine "root::B" and the reference of "B" to program "A", i.e., "B::A", is not defined in the root namespace. This prevents breaking the reference "root::B::A" by the assignment of "root::B". For example, if a user could indirectly assign "root::B::A" from the root program, one can later assign another program to "root::B" that doesn't contain "A" within it. In this situation, a reference "root::B::A" would still live in the reference manager of the root. However, the subroutine "root::B::A" would no longer be used in the actual pulse program. To assign subroutine "A" to ``nested_prog`` as a nested subprogram of ``main_prog``, you must first assign "A" of the ``sub_prog``, and then assign the ``sub_prog`` to the ``main_prog``. .. code-block:: python sub_prog.assign_references({("A", ): nested_prog}, inplace=True) main_prog.assign_references({("B", ): sub_prog}, inplace=True) Alternatively, you can also write .. code-block:: python main_prog.assign_references({("B", ): sub_prog}, inplace=True) main_prog.references[("B", )].assign_references({"A": nested_prog}, inplace=True) Here :attr:`.references` returns a dict-like object, and you can mutably update the nested reference of the particular subroutine. .. note:: Assigned programs are deep-copied to prevent an unexpected update. Args: subroutine_dict: A mapping from reference key to schedule block of the subroutine. inplace: Set ``True`` to override this instance with new subroutine. Returns: Schedule block with assigned subroutine. Raises: PulseError: When reference key is not defined in the current scope. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_references(subroutine_dict, inplace=True) for key, subroutine in subroutine_dict.items(): if key not in self.references: unassigned_keys = ", ".join(map(repr, self.references.unassigned())) raise PulseError( f"Reference instruction with {key} doesn't exist " f"in the current scope: {unassigned_keys}" ) self.references[key] = copy.deepcopy(subroutine) return self def get_parameters(self, parameter_name: str) -> List[Parameter]: """Get parameter object bound to this schedule by string name. Note that we can define different parameter objects with the same name, because these different objects are identified by their unique uuid. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.get_parameters("amp") This returns a list of two parameters ``amp1`` and ``amp2``. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ matched = [p for p in self.parameters if p.name == parameter_name] return matched def search_parameters(self, parameter_regex: str) -> List[Parameter]: """Search parameter with regular expression. This method looks for the scope-aware parameters. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.search_parameters("root::sub::amp") This finds ``amp1`` with scoped name "root::sub::amp". Args: parameter_regex: Regular expression for scoped parameter name. Returns: Parameter objects that have corresponding name. """ pattern = re.compile(parameter_regex) return sorted( _collect_scoped_parameters(self, current_scope="root", filter_regex=pattern).values(), key=lambda p: p.name, ) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.blocks) def __eq__(self, other: "ScheduleBlock") -> bool: """Test if two ScheduleBlocks are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``ScheduleBlock``. This check is performed by converting the instruction representation into directed acyclic graph, in which execution order of every instruction is evaluated correctly across all channels. Also ``self`` and ``other`` should have the same alignment context. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check if not isinstance(other, type(self)): return False # 1. transformation check if self.alignment_context != other.alignment_context: return False # 2. size check if len(self) != len(other): return False # 3. instruction check with alignment from qiskit.pulse.transforms.dag import block_to_dag as dag if not rx.is_isomorphic_node_match(dag(self), dag(other), lambda x, y: x == y): return False return True def __repr__(self) -> str: name = format(self._name) if self._name else "" blocks = ", ".join([repr(instr) for instr in self.blocks[:50]]) if len(self.blocks) > 25: blocks += ", ..." return '{}({}, name="{}", transform={})'.format( self.__class__.__name__, blocks, name, repr(self.alignment_context) ) def __add__(self, other: "BlockComponent") -> "ScheduleBlock": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def _common_method(*classes): """A function decorator to attach the function to specified classes as a method. .. note:: For developer: A method attached through this decorator may hurt readability of the codebase, because the method may not be detected by a code editor. Thus, this decorator should be used to a limited extent, i.e. huge helper method. By using this decorator wisely, we can reduce code maintenance overhead without losing readability of the codebase. """ def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): return method(*args, **kwargs) for cls in classes: setattr(cls, method.__name__, wrapper) return method return decorator @_common_method(Schedule, ScheduleBlock) def draw( self, style: Optional[Dict[str, Any]] = None, backend=None, # importing backend causes cyclic import time_range: Optional[Tuple[int, int]] = None, time_unit: str = "dt", disable_channels: Optional[List[Channel]] = None, show_snapshot: bool = True, show_framechange: bool = True, show_waveform_info: bool = True, show_barrier: bool = True, plotter: str = "mpl2d", axis: Optional[Any] = None, ): """Plot the schedule. Args: style: Stylesheet options. This can be dictionary or preset stylesheet classes. See :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXStandard`, :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXSimple`, and :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXDebugging` for details of preset stylesheets. backend (Optional[BaseBackend]): Backend object to play the input pulse program. If provided, the plotter may use to make the visualization hardware aware. time_range: Set horizontal axis limit. Tuple `(tmin, tmax)`. time_unit: The unit of specified time range either `dt` or `ns`. The unit of `ns` is available only when `backend` object is provided. disable_channels: A control property to show specific pulse channel. Pulse channel instances provided as a list are not shown in the output image. show_snapshot: Show snapshot instructions. show_framechange: Show frame change instructions. The frame change represents instructions that modulate phase or frequency of pulse channels. show_waveform_info: Show additional information about waveforms such as their name. show_barrier: Show barrier lines. plotter: Name of plotter API to generate an output image. One of following APIs should be specified:: mpl2d: Matplotlib API for 2D image generation. Matplotlib API to generate 2D image. Charts are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as ``axis`` input. ``axis`` and ``style`` kwargs may depend on the plotter. axis: Arbitrary object passed to the plotter. If this object is provided, the plotters use a given ``axis`` instead of internally initializing a figure object. This object format depends on the plotter. See plotter argument for details. Returns: Visualization output data. The returned data type depends on the ``plotter``. If matplotlib family is specified, this will be a ``matplotlib.pyplot.Figure`` data. """ # pylint: disable=cyclic-import from qiskit.visualization import pulse_drawer return pulse_drawer( program=self, style=style, backend=backend, time_range=time_range, time_unit=time_unit, disable_channels=disable_channels, show_snapshot=show_snapshot, show_framechange=show_framechange, show_waveform_info=show_waveform_info, show_barrier=show_barrier, plotter=plotter, axis=axis, ) def _interval_index(intervals: List[Interval], interval: Interval) -> int: """Find the index of an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. Returns: The index of the interval. Raises: PulseError: If the interval does not exist. """ index = _locate_interval_index(intervals, interval) found_interval = intervals[index] if found_interval != interval: raise PulseError(f"The interval: {interval} does not exist in intervals: {intervals}") return index def _locate_interval_index(intervals: List[Interval], interval: Interval, index: int = 0) -> int: """Using binary search on start times, find an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. index: A running tally of the index, for recursion. The user should not pass a value. Returns: The index into intervals that new_interval would be inserted to maintain a sorted list of intervals. """ if not intervals or len(intervals) == 1: return index mid_idx = len(intervals) // 2 mid = intervals[mid_idx] if interval[1] <= mid[0] and (interval != mid): return _locate_interval_index(intervals[:mid_idx], interval, index=index) else: return _locate_interval_index(intervals[mid_idx:], interval, index=index + mid_idx) def _find_insertion_index(intervals: List[Interval], new_interval: Interval) -> int: """Using binary search on start times, return the index into `intervals` where the new interval belongs, or raise an error if the new interval overlaps with any existing ones. Args: intervals: A sorted list of non-overlapping Intervals. new_interval: The interval for which the index into intervals will be found. Returns: The index into intervals that new_interval should be inserted to maintain a sorted list of intervals. Raises: PulseError: If new_interval overlaps with the given intervals. """ index = _locate_interval_index(intervals, new_interval) if index < len(intervals): if _overlaps(intervals[index], new_interval): raise PulseError("New interval overlaps with existing.") return index if new_interval[1] <= intervals[index][0] else index + 1 return index def _overlaps(first: Interval, second: Interval) -> bool: """Return True iff first and second overlap. Note: first.stop may equal second.start, since Interval stop times are exclusive. """ if first[0] == second[0] == second[1]: # They fail to overlap if one of the intervals has duration 0 return False if first[0] > second[0]: first, second = second, first return second[0] < first[1] def _check_nonnegative_timeslot(timeslots: TimeSlots): """Test that a channel has no negative timeslots. Raises: PulseError: If a channel timeslot is negative. """ for chan, chan_timeslots in timeslots.items(): if chan_timeslots: if chan_timeslots[0][0] < 0: raise PulseError(f"An instruction on {chan} has a negative starting time.") def _get_timeslots(schedule: "ScheduleComponent") -> TimeSlots: """Generate timeslots from given schedule component. Args: schedule: Input schedule component. Raises: PulseError: When invalid schedule type is specified. """ if isinstance(schedule, Instruction): duration = schedule.duration instruction_duration_validation(duration) timeslots = {channel: [(0, duration)] for channel in schedule.channels} elif isinstance(schedule, Schedule): timeslots = schedule.timeslots else: raise PulseError(f"Invalid schedule type {type(schedule)} is specified.") return timeslots def _get_references(block_elms: List["BlockComponent"]) -> Set[Reference]: """Recursively get reference instructions in the current scope. Args: block_elms: List of schedule block elements to investigate. Returns: A set of unique reference instructions. """ references = set() for elm in block_elms: if isinstance(elm, ScheduleBlock): references |= _get_references(elm._blocks) elif isinstance(elm, Reference): references.add(elm) return references def _collect_scoped_parameters( schedule: ScheduleBlock, current_scope: str, filter_regex: Optional[re.Pattern] = None, ) -> Dict[Tuple[str, int], Parameter]: """A helper function to collect parameters from all references in scope-aware fashion. Parameter object is renamed with attached scope information but its UUID is remained. This means object is treated identically on the assignment logic. This function returns a dictionary of all parameters existing in the target program including its reference, which is keyed on the unique identifier consisting of scoped parameter name and parameter object UUID. This logic prevents parameter clash in the different scope. For example, when two parameter objects with the same UUID exist in different references, both of them appear in the output dictionary, even though they are technically the same object. This feature is particularly convenient to search parameter object with associated scope. Args: schedule: Schedule to get parameters. current_scope: Name of scope where schedule exist. filter_regex: Optional. Compiled regex to sort parameter by name. Returns: A dictionary of scoped parameter objects. """ parameters_out = {} for param in schedule._parameter_manager.parameters: new_name = f"{current_scope}{Reference.scope_delimiter}{param.name}" if filter_regex and not re.search(filter_regex, new_name): continue scoped_param = Parameter.__new__(Parameter, new_name, uuid=getattr(param, "_uuid")) scoped_param.__init__(new_name) unique_key = new_name, hash(param) parameters_out[unique_key] = scoped_param for sub_namespace, subroutine in schedule.references.items(): if subroutine is None: continue composite_key = Reference.key_delimiter.join(sub_namespace) full_path = f"{current_scope}{Reference.scope_delimiter}{composite_key}" sub_parameters = _collect_scoped_parameters( subroutine, current_scope=full_path, filter_regex=filter_regex ) parameters_out.update(sub_parameters) return parameters_out # These type aliases are defined at the bottom of the file, because as of 2022-01-18 they are # imported into other parts of Terra. Previously, the aliases were at the top of the file and used # forwards references within themselves. This was fine within the same file, but causes scoping # issues when the aliases are imported into different scopes, in which the `ForwardRef` instances # would no longer resolve. Instead, we only use forward references in the annotations of _this_ # file to reference the aliases, which are guaranteed to resolve in scope, so the aliases can all be # concrete. ScheduleComponent = Union[Schedule, Instruction] """An element that composes a pulse schedule.""" BlockComponent = Union[ScheduleBlock, Instruction] """An element that composes a pulse schedule block."""
https://github.com/fvarchon/qiskit-intros
fvarchon
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, Aer, execute from qiskit_aqua.algorithms import Grover from qiskit.ignis.verification.randomized_benchmarking import RBFitter from qiskit_chemistry import QiskitChemistry api_token = '' url = '' from qiskit import IBMQ IBMQ.save_account(api_token, url) IBMQ.load_accounts() IBMQ.backends() from qiskit.tools.jupyter import * %qiskit_backend_overview
https://github.com/fvarchon/qiskit-intros
fvarchon
# Your first Qiskit application from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(2) # qubits indexed as qr[0], qr[1] and qr[2] cr = ClassicalRegister(2) # classical bits indexed as cr[0], cr[1] and cr[2] circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr, cr) circuit.draw() circuit.draw(output='latex_source') print(circuit.qasm()) from qiskit import Aer, execute # pick a backend, in this case a simulator backend = Aer.get_backend('qasm_simulator') # start a simulation job on the backend job = execute(circuit, backend, shots=1000) # collect the job results and display them result = job.result() counts = result.get_counts(circuit) print(counts) from qiskit.tools.visualization import plot_histogram plot_histogram(counts) from qiskit import IBMQ IBMQ.load_accounts() IBMQ.backends() # OPTION 1: pick a specific backend backend = IBMQ.get_backend('ibmq_16_melbourne') # OPTION 2: pick the least busy backend from qiskit.providers.ibmq import least_busy backend = least_busy(IBMQ.backends(simulator=False)) # start a simulation job on the backend job = execute(circuit, backend, shots=1000) # collect the job results and display them result = job.result() counts = result.get_counts(circuit) print(counts) # OPTION 1: pick a specific backend backend = IBMQ.get_backend('ibmq_16_melbourne') # OPTION 2: pick the least busy backend from qiskit.providers.ibmq import least_busy backend = least_busy(IBMQ.backends(simulator=False)) # start a simulation job on the backend job = execute(circuit, backend, shots=1000) # monitor the job from qiskit.tools.monitor import job_monitor job_monitor(job) # collect the job results and display them result = job.result() counts = result.get_counts(circuit) print(counts) plot_histogram(counts) %qiskit_backend_monitor backend qr = QuantumRegister(7, 'q') qr = QuantumRegister(7, 'q') tpl_circuit = QuantumCircuit(qr) tpl_circuit.h(qr[3]) tpl_circuit.cx(qr[0], qr[6]) tpl_circuit.cx(qr[6], qr[0]) tpl_circuit.cx(qr[0], qr[1]) tpl_circuit.cx(qr[3], qr[1]) tpl_circuit.cx(qr[3], qr[0]) tpl_circuit.draw() from qiskit.transpiler import PassManager from qiskit.transpiler.passes import BasicSwap from qiskit.transpiler import transpile from qiskit.mapper import CouplingMap help(BasicSwap) coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] simulator = Aer.get_backend('qasm_simulator') coupling_map = CouplingMap(couplinglist=coupling) pass_manager = PassManager() pass_manager.append([BasicSwap(coupling_map=coupling_map)]) basic_circ = transpile(tpl_circuit, simulator, pass_manager=pass_manager) basic_circ.draw() IBMQ.backends() realdevice = IBMQ.get_backend('ibmq_16_melbourne') tpl_realdevice = transpile(tpl_circuit, backend = realdevice) tpl_realdevice.draw(line_length = 250)
https://github.com/fvarchon/qiskit-intros
fvarchon
# 30 qubits = 16 GB num_qubits = 32 memoryneeded_GB = 16 * 2 ** (num_qubits - 30) print(memoryneeded_GB) # qiskit imports from qiskit import Aer from qiskit import IBMQ, execute from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.tools.visualization import plot_histogram, plot_state_city from qiskit.tools.monitor import job_monitor nqubits = 3 qr = QuantumRegister(nqubits, 'q') cr = ClassicalRegister(nqubits, 'c') GHZ3_circuit = QuantumCircuit(qr, cr) GHZ3_circuit.h(qr[0]) GHZ3_circuit.cx(qr[0], qr[1]) GHZ3_circuit.cx(qr[1], qr[2]) GHZ3_circuit.barrier(qr) GHZ3_circuit.measure(qr, cr) GHZ3_circuit.draw(output = 'mpl') # Select the QasmSimulator from the Aer provider simulator = Aer.get_backend('qasm_simulator') # Execute and get counts result = execute(GHZ3_circuit, simulator, shots=2048).result() counts = result.get_counts(GHZ3_circuit) print(counts) plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state') # Execute and get memory result = execute(GHZ3_circuit, simulator, shots=10, memory=True).result() memory = result.get_memory(GHZ3_circuit) print(memory) IBMQ.load_accounts() IBMQ.backends() device = IBMQ.get_backend('ibmq_16_melbourne') job_device = execute(GHZ3_circuit, backend=device, shots=1024) job_monitor(job_device) result_device = job_device.result(timeout = 1800) counts_device = result_device.get_counts(GHZ3_circuit) plot_histogram(counts_device, title="Counts for 3-qubit GHZ state with a real device") from qiskit.providers.aer import noise device = IBMQ.get_backend('ibmq_16_melbourne') properties = device.properties() coupling_map = device.configuration().coupling_map print(properties) for qubit in properties.qubits: print(qubit) print('\n'.join(qubitprop.name + "=" + str(qubitprop.value) + " " + qubitprop.unit for qubitprop in qubit)) print() for gate in properties.gates: print('Gate = {}, Relevant Qubits = {}, Error = {}'.format( gate.gate, gate.qubits, gate.parameters[0].value, gate.parameters[0].unit )) print(coupling_map) import graphviz coupling_graph = graphviz.Graph() for edge in coupling_map: coupling_graph.edge('q'+str(edge[0]), 'q'+str(edge[1])) coupling_graph # List of gate times for ibmq_16_melbourne device # Note that the None parameter for u1, u2, u3 is because gate # times are the same for all qubits # Erick Winston gate_times = [ ('u1', None, 0), ('u2', None, 100), ('u3', None, 200), ('cx', [1, 0], 678), ('cx', [1, 2], 547), ('cx', [2, 3], 721), ('cx', [4, 3], 733), ('cx', [4, 10], 721), ('cx', [5, 4], 800), ('cx', [5, 6], 800), ('cx', [5, 9], 895), ('cx', [6, 8], 895), ('cx', [7, 8], 640), ('cx', [9, 8], 895), ('cx', [9, 10], 800), ('cx', [11, 10], 721), ('cx', [11, 3], 634), ('cx', [12, 2], 773), ('cx', [13, 1], 2286), ('cx', [13, 12], 1504), ('cx', [], 800) ] # Construct the noise model from backend properties # and custom gate times #noise_model = noise.device.basic_device_noise_model(properties, gate_times=gate_times) noise_model = noise.device.basic_device_noise_model(properties, gate_times = gate_times, temperature=10) print(noise_model) help(noise.device.basic_device_noise_model) # Get the basis gates for the noise model basis_gates = noise_model.basis_gates # Select the QasmSimulator from the Aer provider simulator = Aer.get_backend('qasm_simulator') # Execute noisy simulation and get corunts job_noise = execute(GHZ3_circuit, simulator, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates) result_noise = job_noise.result() counts_noise = result_noise.get_counts(GHZ3_circuit) plot_histogram(counts_noise, title="Counts for 3-qubit GHZ state with a simulation containing depolarizing noise model") nqubits = 3 qr = QuantumRegister(nqubits, 'q') cr = ClassicalRegister(nqubits, 'c') GHZ3_circuit = QuantumCircuit(qr, cr) GHZ3_circuit.h(qr[0]) GHZ3_circuit.cx(qr[0], qr[1]) GHZ3_circuit.cx(qr[1], qr[2]) GHZ3_circuit.barrier(qr) #GHZ3_circuit.measure(qr, cr) GHZ3_circuit.draw(output = 'mpl') simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(GHZ3_circuit, simulator).result() finalstate = result.get_statevector(GHZ3_circuit) print(finalstate) print() for statecoeff, statenum in zip(finalstate, range(2**len(qr))): print("({}) * |{}>".format(statecoeff, statenum)) plot_state_city(finalstate, title='3-qubit GHZ state') nqubits = 2 qr = QuantumRegister(nqubits, 'q') cz1 = QuantumCircuit(qr) cz1.h(qr[1]) cz1.cx(qr[0], qr[1]) cz1.h(qr[1]) cz1.draw(output = 'mpl') # Select the UnitarySimulator from the Aer provider simulator = Aer.get_backend('unitary_simulator') # Execute and get counts job_sim = execute(cz1, simulator) result = job_sim.result() unitary = result.get_unitary(cz1) print("Final Unitary:") print(unitary) nqubits = 2 qr = QuantumRegister(nqubits, 'q') cz2 = QuantumCircuit(qr) cz2.cz(qr[0], qr[1]) cz2.draw(output = 'mpl') # Select the UnitarySimulator from the Aer provider simulator = Aer.get_backend('unitary_simulator') # Execute and get counts job_sim = execute(cz2, simulator) result = job_sim.result() unitary = result.get_unitary(cz2) print("Final Unitary:") print(unitary)
https://github.com/fvarchon/qiskit-intros
fvarchon
from qiskit import execute from qiskit import transpiler help(execute) from qiskit import Aer, BasicAer backend = Aer.get_backend("qasm_simulator") help(backend) backend = BasicAer.get_backend("qasm_simulator") help(backend)
https://github.com/obliviateandsurrender/Quantum-Approximate-Thermalization
obliviateandsurrender
# Libraries Import import itertools import numpy as np from functools import reduce, partial from scipy.optimize import minimize import matplotlib.pyplot as plt %matplotlib inline # Qiskit from qiskit import BasicAer, QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import execute from qiskit.quantum_info import Pauli from qiskit.aqua import get_aer_backend, QuantumInstance, Operator from qiskit.aqua.components.initial_states import Custom backend = BasicAer.get_backend('qasm_simulator') class QAT: def __init__(self, num_qubit, temp, weights, qaoa_step=1): self.num_qubits = num_qubit self.num_system = num_qubit*2 self.T = temp self.weights = weights self.p = qaoa_step self.Hc = None self.Hm = None self.qr = None self.cr = None def pauli_x(self, qubit, coeff): return Operator([[coeff, Pauli(np.zeros(self.num_qubits), np.eye((self.num_qubits))[qubit])]]) def product_pauli_z(self, q1, q2, coeff): return Operator([[coeff, Pauli(np.eye((self.num_system))[q1], np.zeros(self.num_system)) * \ Pauli(np.eye((self.num_system))[q2], np.zeros(self.num_system))]]) def ising_hamiltonian(self): Hc = reduce(lambda x,y:x+y, [self.product_pauli_z(i,j, -self.weights[i,j]) for (i,j) in itertools.product(range(self.num_qubits), range(self.num_qubits))]) Hm = reduce(lambda x, y: x+y, [self.pauli_x(i, 1) for i in range(self.num_qubits)]) Hc.to_matrix(), Hm.to_matrix() return Hc, Hm def prepare_init_state(self): self.qr = QuantumRegister(self.num_system) self.cr = ClassicalRegister(self.num_qubits) circuit_init = QuantumCircuit(self.qr, self.cr) for i in range(self.num_qubits): circuit_init.rx( 2 * np.arctan(np.exp(- 1/self.T)), self.num_qubits+i) circuit_init.cx(self.num_qubits+i, i) return circuit_init def evolve(self, hamiltonian, angle, quantum_registers): return hamiltonian.evolve(None, angle, 'circuit', 1, quantum_registers=quantum_registers, expansion_mode='suzuki', expansion_order=3) def evaluate_circuit(self, beta_gamma, circuit_init): p = len(beta_gamma)//2 beta = beta_gamma[:p]; gamma = beta_gamma[p:] #print(self.Hc, self.Hm) circuit = circuit_init + reduce(lambda x,y: x+y, [self.evolve(self.Hc, beta[i], self.qr) + \ self.evolve(self.Hm, gamma[i], self.qr) for i in range(p)]) return np.real(self.Hc.eval("matrix", circuit, get_aer_backend('statevector_simulator'))[0]) def get_thermal_state(self): #print(self.ising_hamiltonian()) self.Hc, self.Hm = self.ising_hamiltonian() #print(self.Hc,self.Hm) circuit_init = self.prepare_init_state() beta_init = np.random.uniform(0, np.pi*2, self.p) gamma_init = np.random.uniform(0, np.pi*2, self.p) evaluate = partial(self.evaluate_circuit, circuit_init=circuit_init) result = minimize(evaluate, np.concatenate([beta_init, gamma_init]), method='L-BFGS-B') beta = result['x'][:self.p]; gamma = result['x'][self.p:] circuit = circuit_init + reduce(lambda x,y: x+y, [self.evolve(self.Hc, beta[i], self.qr) + \ self.evolve(self.Hm, gamma[i], self.qr) for i in range(p)]) return result["fun"], circuit def get_energy(self, spin_configuration): x = spin_configuration.reshape(-1, 1) return np.sum([[-self.weights[i,j] * x[i] * x[j] \ for j in range(self.num_qubits)] for i in range(self.num_qubits)]) def get_energy_distribution(self, thermal_state): for i in range(self.num_qubits): thermal_state.measure(self.qr[i], self.cr[i]) job = execute(thermal_state, backend, shots=1000) results = job.result().get_counts(thermal_state) list_spin_configs = np.array(np.concatenate([[list(spin_config)] *\ results[spin_config] \ for spin_config in results]), dtype="int") list_spin_configs[list_spin_configs == 0] = -1 list_energy = np.array([self.get_energy(spin_config) for spin_config in list_spin_configs]) return list_energy if __name__ == "__main__": weights = np.array([[0,1,0],[0,0,1],[0,0,1]]) p = 5 r = QAT(3, 1000, weights, p) cost, thermal_state = r.get_thermal_state() hist = plt.hist(r.get_energy_distribution(thermal_state), density=True)
https://github.com/cjsproject/qiskit_learning
cjsproject
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from os import environ #local environment variable to store the access token :) token = environ.get('ibmq_token') # Loading IBM Q account account = IBMQ.save_account(token, overwrite=True) provider = IBMQ.load_account() # quasm_sim simulator = Aer.get_backend('qasm_simulator') # circuit on q reg with 1 qubit circuit = QuantumCircuit(2, 2) # hadamard gate on qbit A circuit.h(0) # CNOT on qbit B controlled by A circuit.cx(0, 1) circuit.measure([0, 1], [0, 1]) job = execute(circuit, simulator, shots=1000) results = job.result() counts = results.get_counts(circuit) print(f"total count for 0 and 1 are: {counts}") circuit.draw() plot_histogram(counts)
https://github.com/cjsproject/qiskit_learning
cjsproject
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ, assemble from qiskit.visualization import * from os import environ #local environment variable to store the access token :) token = environ.get('ibmq_token') # Loading your IBM Q account(s) account = IBMQ.save_account(token, overwrite=True) provider = IBMQ.load_account() # quasm_sim not necessary simulator = Aer.get_backend('qasm_simulator') import numpy as np data = [0.1, 0.2, 0.3, 0.4] angles = [] """# normalize the datapoints if datapoints >= 1 max_val = max(digit_data[0]) norm_data = [] for i in A: temp_row = [] for j in i: temp_row.append(j/max_val) norm_data.append(temp_row) print(norm_data) """ # encode data as angular rotations on bloch sphere for i in data: angles.append(2*np.arcsin(np.sqrt(i))) print(data, angles, sep='\n') # circuit with 2 qubits, 2 cbits qc = QuantumCircuit(4, 4) # apply RY gate using theta for i in range(4): qc.ry(angles[i], i) # measure each qubit's output for i in range(4): qc.measure(i, i) qc.draw() # run simulation 100000 times, stores results in counts job = execute(qc, simulator, shots=100000) results = job.result() counts = results.get_counts(qc) plot_histogram(counts) # retrieving original data as the # expected value of each set of bits i.e # add probabilities of all outputs with their 4th bit set on bit4 = [] bit3 = [] bit2 = [] bit1 = [] # creating an array to access E(psi) more easily for i in counts: prob = counts[i]/100000 bit4.append([i[0], prob]) bit3.append([i[1], prob]) bit2.append([i[2], prob]) bit1.append([i[3], prob]) # array of bit's arrays... bits = [bit4, bit3, bit2, bit1] q_data = [] # finding the expected value of each bit, appending to array for nth_bit in bits: e_val = 0.0 for bit in nth_bit: # print(bit[0], bit[1]) if int(bit[0]) == 1: e_val += bit[1] # print('added') q_data.append(round(e_val, 2)) print(q_data, '\nData Retrieved, just backwards')
https://github.com/cjsproject/qiskit_learning
cjsproject
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ, assemble, extensions from qiskit.visualization import * from os import environ #local environment variable to store the access token :) token = environ.get('ibmq_token') # Loading your IBM Q account(s) account = IBMQ.save_account(token, overwrite=True) provider = IBMQ.load_account() # quasm_sim not necessary simulator = Aer.get_backend('qasm_simulator') import numpy as np from matplotlib.image import imread import matplotlib.pyplot as plt from sklearn.datasets import load_digits digits = load_digits() # load the list of lists into a list :) img_data = digits['images'] print(img_data[0]) # setting the figure parameters to the size of the input plt.rcParams['figure.figsize'] = [4, 4] # testing one input A = img_data[5] B = img_data[5] # displays image in grayscale display = plt.imshow(A) display.set_cmap('gray') # compress image to a 4x4 r=4 # approx image: Xapp = np.zeros((r,r)) for i in range(0, len(A), 2): for j in range(0, len(A), 2): sub_mat = np.zeros(r) sub_sum = 0 sub_sum += A[i][j] + A[i][j+1] + A[i+1][j] + A[i+1][j+1] Xapp[int(i/2)][int(j/2)] = sub_sum/4 print(np.array(Xapp)) plt.figure(1) img = plt.imshow(Xapp) img.set_cmap('gray') plt.show() # Not sure if the inaccurate representation is an accurate one :) ie new unitary imgmap vs original imgmap # perform full Singular Vector Decomposition (SVD) on compressed image U, S, VT = np.linalg.svd(Xapp, full_matrices=True) # take unitary parts for encoding new_unitary = np.matmul(U, VT) print(Xapp, new_unitary,sep='\n\n') display = plt.imshow(new_unitary) display.set_cmap('gray') # circuit 2^n = 64, so n=6 qc = QuantumCircuit(2, 2) # testing basic unitary identity = np.identity(4) print(len(new_unitary)) qc.unitary(new_unitary, [0, 1]) # measure qubit's output qc.measure([0, 1], [0, 1]) qc.draw() # run simulation 100000 times, stores results in counts job = execute(qc, simulator, shots=100000) results = job.result() counts = results.get_counts(qc) plot_histogram(counts) """ NOT SURE HOW TO DECODE YET :("""
https://github.com/cjsproject/qiskit_learning
cjsproject
import numpy as np from matplotlib.image import imread import matplotlib.pyplot as plt import torch from torchvision import transforms from torchvision.datasets import MNIST # the data is not normalized, and needs to be converted to a np array... digits = MNIST('data', train=True, download=False) # converting to np array and normalizing by val/max(arr) digits = digits.data.numpy() digits = digits/np.max(digits) #displaying image display = plt.imshow(digits[0]) display.set_cmap('gray') print(digits[0].shape) # grab 4x4 squares of the image im1 = digits[0] stride = 1 mat_sq = np.zeros([28,28,4,4]) for i in range(0, len(im1)-4, stride): for j in range(0, len(im1[i])-4, stride): cube = im1[i:i+4, j:j+4] mat_sq[i, j] = cube # creates a 2d collection of matrices, where each [i, j] index contains a 4x4 matrix print(mat_sq[14, 14]) display = plt.imshow(mat_sq[14, 14]) display.set_cmap('gray') # find SVD of each submatrix, make unitary and assign to uni uni = np.zeros([28,28,4,4]) for i in range(len(mat_sq)): for j in range(len(mat_sq[i])): U, S, VT = np.linalg.svd(mat_sq[i, j]) uni[i, j] = np.dot(U, VT) #print(f"U =\n{U}\n S =\n{S}\n VT=\n{VT}\n") test = uni[14,14] # comparing unitary, they aren't the same :( print(f"U*VT:\n{uni[14, 14]}\nOriginal:\n{mat_sq[14, 14]}") # try graham schmidt, they're just about the same! # seems to have detected an edge. Q, R = np.linalg.qr(mat_sq[14, 14]) print(f"Q:\n{Q}\nOriginal:\n{mat_sq[14, 14]}\nIs Q Unitary:\n{np.matmul(Q, Q.transpose(0, 1)).round()}") display = plt.imshow(Q) display.set_cmap('gray')
https://github.com/cjsproject/qiskit_learning
cjsproject
import numpy as np import matplotlib.pyplot as plt import seaborn as sns import sklearn from sklearn import datasets from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumRegister from qiskit import QuantumCircuit from qiskit import Aer, execute from math import pi,log from qiskit import * from qiskit.extensions import XGate, UnitaryGate import tensorflow as tf import cv2 #imported stuff from Weiwen's code import torch import torchvision from torchvision import datasets import torchvision.transforms as transforms import torch.nn as nn import shutil import os import time import sys from pathlib import Path import numpy as np import matplotlib.pyplot as plt import numpy as np from PIL import Image from skcuda.linalg import svd from matplotlib import cm import functools %matplotlib inline backend = Aer.get_backend('qasm_simulator') print = functools.partial(print, flush=True) interest_num = [3,6] ori_img_size = 28 #original image is 28x28 img_size = 4 #size to downsize to (set to 28 if no downsizing) # number of subprocesses to use for data loading num_workers = 0 # how many samples per batch to load batch_size = 1 inference_batch_size = 1 # Weiwen: modify the target classes starting from 0. Say, [3,6] -> [0,1] def modify_target(target): for j in range(len(target)): for idx in range(len(interest_num)): if target[j] == interest_num[idx]: target[j] = idx break new_target = torch.zeros(target.shape[0],2) for i in range(target.shape[0]): if target[i].item() == 0: new_target[i] = torch.tensor([1,0]).clone() else: new_target[i] = torch.tensor([0,1]).clone() return target,new_target def select_num(dataset,labels,interest_num): valid_labels = np.array([]) for num in interest_num: if valid_labels.size > 0: valid_labels += labels== num else: valid_labels = labels == num dataset = dataset[valid_labels] labels = labels[valid_labels] return (dataset,labels) def nomalizatied(ori,fig): row = fig['row'] col = fig['col'] transformed = [] for i in range(len(ori)): transform = np.resize(ori[i],(row,col)) transformed.append(transform) return transformed ################ Weiwen on 12-30-2020 ################ # Using torch to load MNIST data ###################################################### # convert data to torch.FloatTensor transform = transforms.Compose([transforms.Resize((ori_img_size,ori_img_size)), transforms.ToTensor()]) # Path to MNIST Dataset (train_data,train_labels),(test_data,test_labels) = tf.keras.datasets.mnist.load_data() (train_data,train_labels) = select_num(train_data,train_labels,interest_num) (test_data,test_labels) = select_num(test_data,test_labels,interest_num) #train_data = nomalizatied(train_data,{'row':4,'col':4}) #test_data = nomalizatied(test_data,{'row':4,'col':4}) train_data = train_data[:1000] train_labels = train_labels[:1000] train_data = torch.Tensor(train_data) # transform to torch tensor train_labels = torch.Tensor(train_labels) test_data = torch.Tensor(test_data) test_labels = torch.Tensor(test_labels) train = torch.utils.data.TensorDataset(train_data,train_labels) # create your datset test =torch.utils.data.TensorDataset(test_data,test_labels) u, s, v = svd(np.array(train_data[0:10]/255)) # prepare data loaders train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, num_workers=num_workers, shuffle=False, drop_last=True) test_loader = torch.utils.data.DataLoader(test, batch_size=inference_batch_size, num_workers=num_workers, shuffle=False, drop_last=True) class ToQuantumData(object): def __call__(self, input_vec): vec_len = len(input_vec) input_matrix = np.zeros((vec_len, vec_len)) input_matrix[0] = input_vec input_matrix = input_matrix.transpose() u, s, v = np.linalg.svd(input_matrix) output_matrix = np.dot(u, v) output_data = output_matrix[:, 0].view() return output_data class ToQuantumMatrix(object): def __call__(self, input_vec): vec_len = len(input_vec) input_matrix = np.zeros((vec_len, vec_len)) input_matrix[0] = input_vec #print('new input vec') input_matrix = input_matrix.transpose() #print(input_vec) u, s, v = np.linalg.svd(input_matrix) output_matrix = np.dot(u, v) return output_matrix def data_pre_pro(vector): # Converting classical data to quantum data trans_to_vector = ToQuantumData() trans_to_matrix = ToQuantumMatrix() #print("Classical Data: {}".format(vector)) #print("Quantum Data: {}".format(trans_to_vector(vector))) return trans_to_matrix(vector),trans_to_vector(vector) def PaddingNeeded(n): #check if n is a power of 2 num_decimal = np.log2(n) num_int = int(-(-num_decimal//1)) #round any decimal number up dims_needed = int(2**(num_int)) return dims_needed def pad_zeros(data): row = len(data) col = len(data[0]) dims = max(row,col) dims_needed = PaddingNeeded(dims) return np.pad(data,((0,dims_needed-row),(0,dims_needed-col)),'constant', constant_values=(0,0)) from tqdm import tqdm dataset = [] labels = [] # Use the first image from test loader as example for batch_idx, (data, target) in tqdm(enumerate(train_loader)): torch.set_printoptions(threshold=sys.maxsize) np.set_printoptions(threshold=sys.maxsize) data_grid = torchvision.utils.make_grid(data) #read the data from torch np_data = data_grid.numpy() #convert tensor to numpy array image = np.asarray(np_data[0] * 255, np.uint8) im = Image.fromarray(image,mode="L") im = im.resize((4,4),Image.BILINEAR) np_image = np.asarray(im)*1/255 #normalize the resized image data_pad = pad_zeros(np_image) #pad the data with zeros (if necessary) to make dimensionality a power of 2 np_1d = data_pad.ravel() #convert the padded data to 1-d array for encoding function quantum_matrix,quantum_data = data_pre_pro(np_1d) #convert the data to unitary matrix dataset.append(quantum_matrix) labels.append(quantum_data) for matrix in dataset: print(is_unitary(np.matrix(matrix))) train_labels_binary = train_labels == 3 train_labels_binary = np.array(train_labels_binary).astype('int') # 3 is Label 1, 6 is label 0 #------------------------------------------------------------------------------------------ #DATA ENCODING SECTION #------------------------------------------------------------------------------------------ def is_unitary(m): return np.allclose(np.eye(m.shape[0]), m.H * m) def quantum_encode(quantum_matrix): dims = len(quantum_matrix[0]) #dimensionality of data q=int(np.log2(dims)) # Number of qubits = log2(Dimensionality of data) (could be a decimal number) print(dims, 'classical bits encoded onto ', q, ' qubits') c=1 #one classical bit #Create quantum register and circuit inp = QuantumRegister(q,"in_qbit") circ = QuantumCircuit(inp) # Add classical register c_reg = ClassicalRegister(c,"reg") circ.add_register(c_reg) # From Listing 3: create auxiliary qubits #aux = QuantumRegister(1,"aux_qbit") #circ.add_register(aux) circ.append(UnitaryGate(quantum_matrix, label="Input"), inp[0:q]) return circ, q #encode the classicaL data into a quantum circuit (2^N parameters onto N qubits) circ, q= quantum_encode(quantum_matrix) print(circ) # Using StatevectorSimulator from the Aer provider simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() statevector = result.get_statevector(circ) print("Data to be encoded: \n {}\n".format(quantum_data)) print("Data read from the circuit: \n {}".format(statevector)) #All functions needed for the functionality of the circuit simulation def generate_and_save_images(model, epoch, test_input): # Notice `training` is set to False. # This is so all layers run in inference mode (batchnorm). predictions = model(test_input, training=False) fig = plt.figure(figsize=(4,4)) for i in range(predictions.shape[0]): plt.subplot(4, 4, i+1) dp = np.array((predictions[i] * 127.5) + 127.5).astype('uint8') plt.imshow(dp) plt.axis('off') #plt.savefig('image_at_epoch_{:04d}.png'.format(epoch)) plt.show() def ran_ang(): #return np.pi/2 return np.random.rand()*np.pi def single_qubit_unitary(circ_ident,qubit_index,values): circ_ident.ry(values[0],qubit_index) def dual_qubit_unitary(circ_ident,qubit_1,qubit_2,values): circ_ident.ryy(values[0],qubit_1,qubit_2) def controlled_dual_qubit_unitary(circ_ident,control_qubit,act_qubit,values): circ_ident.cry(values[0],control_qubit,act_qubit) #circ_ident.cry(values[0],act_qubit,control_qubit) def traditional_learning_layer(circ_ident,num_qubits,values,style="Dual",qubit_start=1,qubit_end=5): if style == "Dual": for qub in np.arange(qubit_start,qubit_end): single_qubit_unitary(circ_ident,qub,values[str(qub)]) for qub in np.arange(qubit_start,qubit_end-1): dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+","+str(qub+1)]) elif style =="Single": for qub in np.arange(qubit_start,qubit_end): single_qubit_unitary(circ_ident,qub,values[str(qub)]) elif style=="Controlled-Dual": for qub in np.arange(qubit_start,qubit_end): single_qubit_unitary(circ_ident,qub,values[str(qub)]) for qub in np.arange(qubit_start,qubit_end-1): dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+","+str(qub+1)]) for qub in np.arange(qubit_start,qubit_end-1): controlled_dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+"--"+str(qub+1)]) ''' def data_loading_circuit(circ_ident,num_qubits,values,qubit_start=1,qubit_end=5): k = 0 for qub in np.arange(qubit_start,qubit_end): circ_ident.ry(values[k],qub) k += 1 ''' def data_loading_circuit(circ_ident,quantum_matrix,qubit_start=1,qubit_end=5): circ_ident.append(UnitaryGate(quantum_matrix, label="Input"), circ_ident.qubits[qubit_start:qubit_end]) def quantum_encode(quantum_matrix): dims = len(quantum_matrix[0]) #dimensionality of data q=int(np.log2(dims)) # Number of qubits = log2(Dimensionality of data) (could be a decimal number) print(dims, 'classical bits encoded onto ', q, ' qubits') c=1 #one classical bit #Create quantum register and circuit inp = QuantumRegister(q,"in_qbit") circ = QuantumCircuit(inp) # Add classical register c_reg = ClassicalRegister(c,"reg") circ.add_register(c_reg) # From Listing 3: create auxiliary qubits #aux = QuantumRegister(1,"aux_qbit") #circ.add_register(aux) circ.append(UnitaryGate(quantum_matrix, label="Input"), inp[0:q]) return circ, q def swap_test(circ_ident,num_qubits): num_swap = num_qubits//2 for i in range(num_swap): circ_ident.cswap(0,i+1,i+num_swap+1) circ_ident.h(0) circ_ident.measure(0,0) def init_random_variables(q,style): trainable_variables = {} if style=="Single": for i in np.arange(1,q+1): trainable_variables[str(i)] = [ran_ang()] elif style=="Dual": for i in np.arange(1,q+1): trainable_variables[str(i)] = [ran_ang()] if i != q: trainable_variables[str(i)+","+str(i+1)] = [ran_ang()] elif style=="Controlled-Dual": for i in np.arange(1,q+1): trainable_variables[str(i)] = [ran_ang()] if i != q: trainable_variables[str(i)+","+str(i+1)] = [ran_ang()] trainable_variables[str(i)+"--"+str(i+1)] = [ran_ang()] return trainable_variables def get_probabilities(circ,counts=5000): job = execute(circ, backend, shots=counts) results = job.result().get_counts(circ) try: prob = results['0']/(results['1']+results['0']) prob = (prob-0.5) if prob <= 0.005: prob = 0.005 else: prob = prob*2 except: prob = 1 return prob # Define loss function. SWAP Test returns probability, so minmax probability is logical def cost_function(p,yreal,trimming): if yreal == 0: return -np.log(p) #return 1-p elif yreal == 1: return -np.log(1-p) #return p def generator_cost_function(p): return -np.log(p) def update_weights(init_value,lr,grad): while lr*grad > 2*np.pi: lr /= 10 print("Warning - Gradient taking steps that are very large. Drop learning rate") weight_update = lr*grad new_value = init_value print("Updating with a new value of " + str(weight_update)) if new_value-weight_update > 2*np.pi: new_value = (new_value-weight_update) - 2*np.pi elif new_value-weight_update < 0: new_value = (new_value-weight_update) + 2*np.pi else: new_value = new_value - weight_update return new_value # Define loss function. SWAP Test returns probability, so minmax probability is logical def cost_function(p,yreal,trimming): if yreal == 0: return -np.log(p) #return 1-p elif yreal == 1: return -np.log(1-p) #return p def generator_cost_function(p): return -np.log(p) def update_weights(init_value,lr,grad): while lr*grad > 2*np.pi: lr /= 10 print("Warning - Gradient taking steps that are very large. Drop learning rate") weight_update = lr*grad new_value = init_value print("Updating with a new value of " + str(weight_update)) if new_value-weight_update > 2*np.pi: new_value = (new_value-weight_update) - 2*np.pi elif new_value-weight_update < 0: new_value = (new_value-weight_update) + 2*np.pi else: new_value = new_value - weight_update return new_value QuantumCircuit(5,1).qubits # ------------------------------------------------------------------------------------ # We treat the first n qubits are the discriminators state. n is always defined as the # integer division floor of the qubit count. # This is due to the fact that a state will always be k qubits, therefore the # number of total qubits must be 2k+1. 2k as we need k for the disc, and k to represent # either the other learned quantum state, or k to represent a data point # then +1 to perform the SWAP test. Therefore, we know that we will always end up # with an odd number of qubits. We take the floor to solve for k. 1st k represents # disc, 2nd k represents the "loaded" state be it gen or real data # ------------------------------------------------------------------------------------ # Use different function calls to represent training a GENERATOR or training a DISCRIMINATOR # ------------------------------------------------------------------------------------ # THIS SECTION IS FOR THE ONLINE GENERATION OF QUANTUM CIRCUITS def disc_fake_training_circuit(trainable_variables,key,key_value,diff=False,fwd_diff = False,Sample=False): if Sample: z = q//2 circ = QuantumCircuit(q,z) else: circ = QuantumCircuit(q,c) circ.h(0) if diff == True and fwd_diff == True: trainable_variables[key][key_value] += par_shift if diff == True and fwd_diff == False: trainable_variables[key][key_value] -= par_shift traditional_learning_layer(circ,q,trainable_variables,style=layer_style,qubit_start=1,qubit_end=q//2 +1) traditional_learning_layer(circ,q,trainable_variables,style=layer_style,qubit_start=q//2 +1,qubit_end=q) if Sample: for qub in range(q//2): circ.measure(q//2 + 1 + qub,qub) else: swap_test(circ,q) if diff == True and fwd_diff == True: trainable_variables[key][key_value] -= par_shift if diff == True and fwd_diff == False: trainable_variables[key][key_value] += par_shift return circ def disc_real_training_circuit(training_variables,data,key,key_value,diff,fwd_diff): circ = QuantumCircuit(q,c) circ.h(0) if diff == True & fwd_diff == True: training_variables[key][key_value] += par_shift if diff == True & fwd_diff == False: training_variables[key][key_value] -= par_shift traditional_learning_layer(circ,q,training_variables,style=layer_style,qubit_start=1,qubit_end=q//2 +1) data_loading_circuit(circ,data,qubit_start=q//2+1,qubit_end=q) if diff == True & fwd_diff == True: training_variables[key][key_value] -= par_shift if diff == True & fwd_diff == False: training_variables[key][key_value] += par_shift swap_test(circ,q) return circ def generate_kl_divergence_hist(actual_data, epoch_results_data): plt.clf() # clears current figure sns.set() kl_div_vec = [] for kl_dim in range(actual_data.shape[1]): kl_div = kl_divergence(actual_data[:,kl_dim],epoch_results_data[:,kl_dim]) kl_div_vec.append(kl_div) return kl_div_vec def bin_data(dataset): bins = np.zeros(10) for point in dataset: indx = int(str(point).split('.')[-1][0]) # The shittest way imaginable to extract the first val aft decimal bins[indx] +=1 bins /= sum(bins) return bins def kl_divergence(p_dist, q_dist): p = bin_data(p_dist) q = bin_data(q_dist) kldiv = 0 for p_point,q_point in zip(p,q): kldiv += (np.sqrt(p_point) - np.sqrt(q_point))**2 kldiv = (1/np.sqrt(2))*kldiv**0.5 return kldiv #return sum(p[i] * log2(p[i]/q[i]) for i in range(len(p))) # ?... are we confident in this... # Checkpointing code def save_variables(train_var,epoch,number): with open(f"Epoch-{epoch}-Variables-numbers-{number}",'w') as file: file.write(str(train_var)) def load_variables(epoch,number): with open(f"Epoch-{epoch}-Variables-numbers-{number}",'r') as file: texts = file.read() return eval(texts) train_var_1 = load_variables(11,6) train_var_0 = load_variables(49,3) train_var_1 z = disc_real_training_circuit(train_var,quantum_matrix,'1',0,diff=False,fwd_diff=False) #z.append(UnitaryGate(quantum_matrix, label="Input"), z.qubits[10:20]) quantum_matrix dataset = np.array(dataset) labels = np.array(labels) train_labels_binary = train_labels_binary[:dataset.shape[0]] dataset = dataset[:5000] train_labels_binary = train_labels_binary[:5000] q=9# Number of qubits = Dimensionality of data = round up to even number = num qubits c=1 circ = QuantumCircuit(q,c) circ.h(0) layer_style = "Controlled-Dual" train_var_0 = init_random_variables(q//2,layer_style) train_var_1 = init_random_variables(q//2,layer_style) #train_var_2 = init_random_variables(q//2,layer_style) tracked_d_loss = [] tracked_d_loss1 = [] gradients = [] learning_rate=0.015 train_iter = 50 corr = 0 wrong= 0 loss_d_to_real = 0 print('Starting Training') print('-'*20) print("train_var_0 training") for epoch in range(train_iter): start = time.time() loss = [0,0] par_shift = 0.5*np.pi/((1+epoch)**0.5) for index,point in enumerate(dataset[train_labels_binary==0]): for key,value in train_var_0.items(): if str(q//2 + 1 ) in key: break for key_value in range(len(value)): forward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=True,fwd_diff=True))) backward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=True,fwd_diff=False))) df = 0.5*(forward_diff-backward_diff) train_var_0[key][key_value] -= df*learning_rate #print(f"Updated Variable {key}-({key_value}) by {-df*learning_rate}") print('Time for Epoch {} is {} sec'.format(epoch+1,time.time()-start)) print("-"*20) save_variables(train_var_0,epoch,3) for epoch in range(train_iter): start = time.time() loss = [0,0] par_shift = 0.5*np.pi/((1+epoch)**0.5) for index,point in enumerate(dataset[train_labels_binary==1]): for key,value in train_var_1.items(): if str(q//2 + 1 ) in key: break for key_value in range(len(value)): forward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=True,fwd_diff=True))) backward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=True,fwd_diff=False))) df = 0.5*(forward_diff-backward_diff) train_var_1[key][key_value] -= df*learning_rate print('Time for Epoch {} is {} sec'.format(epoch+1,time.time()-start)) print("-"*20) save_variables(train_var_1,epoch,6) def is_unitary(m): return np.allclose(np.eye(m.shape[0]), m.H * m) is_unitary(np.matrix(quantum_matrix[0])) corr = 0 wron = 0 for index,point in enumerate(dataset[train_labels_binary==1]): p1 = get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=False,fwd_diff=False)) p2 = get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=False,fwd_diff=False)) if p1<p2: corr +=1 else: wron+=1 acc = corr/(corr+wron) print(acc) corr wron 829
https://github.com/cjsproject/qiskit_learning
cjsproject
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from os import environ # Grab env var token = environ.get('ibmq_token') # Loading your IBM Q account(s) account = IBMQ.save_account(token, overwrite=True) provider = IBMQ.load_account() provider.backends() from qiskit.providers.ibmq import least_busy large_enough_devices = provider.backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator) backend = least_busy(large_enough_devices) print("The best backend is " + backend.name()) # quasm_sim not necessary #simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor # circuit with 2 qubits, 2 cbits circuit = QuantumCircuit(2, 2) # hadamard on A circuit.h(0) # CNOT on B controlled by A circuit.cx(0 , 1) circuit.measure([0, 1], [0, 1]) job = execute(circuit, backend, shots=1000) job_monitor(job) results = job.result() counts = results.get_counts(circuit) print(f"total count for 0 and 1 are: {counts}") circuit.draw() plot_histogram(counts)
https://github.com/cjsproject/qiskit_learning
cjsproject
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from os import environ print(environ.get('QISKIT_TOKEN')) # Loading your IBM Q account(s) provider = IBMQ.load_account() # quasm_sim simulator = Aer.get_backend('qasm_simulator') # circuit on q reg with 1 qubit circuit = QuantumCircuit(2, 2) # hadamard gate on qbit A circuit.h(0) # CNOT on qbit B controlled by A circuit.cx(0, 1) circuit.measure([0, 1], [0, 1]) job = execute(circuit, simulator, shots=1000) results = job.result() counts = results.get_counts(circuit) print(f"total count for 0 and 1 are: {counts}") circuit.draw() plot_histogram(counts)
https://github.com/cjsproject/qiskit_learning
cjsproject
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ, assemble from qiskit.visualization import * from os import environ #local environment variable to store the access token :) token = environ.get('ibmq_token') # Loading your IBM Q account(s) account = IBMQ.save_account(token, overwrite=True) provider = IBMQ.load_account() # quasm_sim not necessary simulator = Aer.get_backend('qasm_simulator') import numpy as np data = [0.1, 0.2, 0.3, 0.4] angles = [] # encode data as angular rotations on bloch sphere for i in data: angles.append(2*np.arcsin(np.sqrt(i))) print(data, angles, sep='\n') # circuit with 2 qubits, 2 cbits qc = QuantumCircuit(4, 4) # apply RY gate using theta for i in range(4): qc.ry(angles[i], i) # measure each qubit's output for i in range(4): qc.measure(i, i) qc.draw() # run simulation 100000 times, stores results in counts job = execute(qc, simulator, shots=100000) results = job.result() counts = results.get_counts(qc) plot_histogram(counts) # retrieving original data as the # expected value of each set of bits i.e # add probabilities of all outputs with their 4th bit set on bit4 = [] bit3 = [] bit2 = [] bit1 = [] # creating an array to access E(psi) more easily for i in counts: prob = counts[i]/100000 bit4.append([i[0], prob]) bit3.append([i[1], prob]) bit2.append([i[2], prob]) bit1.append([i[3], prob]) # array of bit's arrays... bits = [bit4, bit3, bit2, bit1] q_data = [] # finding the expected value of each bit, appending to array for nth_bit in bits: e_val = 0.0 for bit in nth_bit: # print(bit[0], bit[1]) if int(bit[0]) == 1: e_val += bit[1] # print('added') q_data.append(round(e_val, 2)) print(q_data, '\nData Retrieved, just backwards')
https://github.com/cjsproject/qiskit_learning
cjsproject
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ, assemble, extensions from qiskit.visualization import * from os import environ #local environment variable to store the access token :) token = environ.get('ibmq_token') # Loading your IBM Q account(s) account = IBMQ.save_account(token, overwrite=True) provider = IBMQ.load_account() # quasm_sim not necessary simulator = Aer.get_backend('qasm_simulator') import numpy as np from matplotlib.image import imread import matplotlib.pyplot as plt from sklearn.datasets import load_digits digits = load_digits() # load the list of lists into a list :) img_data = digits['images'] print(img_data[0]) # setting the figure parameters to the size of the input plt.rcParams['figure.figsize'] = [4, 4] # testing one input A = img_data[5] B = img_data[5] # displays image in grayscale display = plt.imshow(A) display.set_cmap('gray') # compress image to a 4x4 r=4 # approx image: Xapp = np.zeros((r,r)) for i in range(0, len(A), 2): for j in range(0, len(A), 2): sub_mat = np.zeros(r) sub_sum = 0 sub_sum += A[i][j] + A[i][j+1] + A[i+1][j] + A[i+1][j+1] Xapp[int(i/2)][int(j/2)] = sub_sum/4 print(np.array(Xapp)) plt.figure(1) img = plt.imshow(Xapp) img.set_cmap('gray') plt.show() # Not sure if the inaccurate representation is an accurate one :) ie new unitary imgmap vs original imgmap # perform full Singular Vector Decomposition (SVD) on compressed image U, S, VT = np.linalg.svd(Xapp, full_matrices=True) # take unitary parts for encoding new_unitary = np.matmul(U, VT) print(Xapp, new_unitary,sep='\n\n') display = plt.imshow(new_unitary) display.set_cmap('gray') # circuit 2^n = 64, so n=6 qc = QuantumCircuit(2, 2) # testing basic unitary identity = np.identity(4) print(len(new_unitary)) qc.unitary(new_unitary, [0, 1]) # measure qubit's output qc.measure([0, 1], [0, 1]) qc.draw() # run simulation 100000 times, stores results in counts job = execute(qc, simulator, shots=100000) results = job.result() counts = results.get_counts(qc) plot_histogram(counts) """ NOT SURE HOW TO DECODE YET :("""
https://github.com/cjsproject/qiskit_learning
cjsproject
import numpy as np from matplotlib.image import imread import matplotlib.pyplot as plt import torch from torchvision import transforms from torchvision.datasets import MNIST # the data is not normalized, and needs to be converted to a np array... digits = MNIST('data', train=True, download=False) # converting to np array and normalizing by val/max(arr) digits = digits.data.numpy() digits = digits/np.max(digits) #displaying image display = plt.imshow(digits[0]) display.set_cmap('gray') print(digits[0].shape) # grab 4x4 squares of the image im1 = digits[0] stride = 1 mat_sq = np.zeros([28,28,4,4]) for i in range(0, len(im1)-4, stride): for j in range(0, len(im1[i])-4, stride): cube = im1[i:i+4, j:j+4] mat_sq[i, j] = cube # creates a 2d collection of matrices, where each [i, j] index contains a 4x4 matrix print(mat_sq[14, 14]) display = plt.imshow(mat_sq[14, 14]) display.set_cmap('gray') # find SVD of each submatrix, make unitary and assign to uni uni = np.zeros([28,28,4,4]) for i in range(len(mat_sq)): for j in range(len(mat_sq[i])): U, S, VT = np.linalg.svd(mat_sq[i, j]) uni[i, j] = np.dot(U, VT) #print(f"U =\n{U}\n S =\n{S}\n VT=\n{VT}\n") test = uni[14,14] # comparing unitary, they aren't the same :( print(f"U*VT:\n{uni[14, 14]}\nOriginal:\n{mat_sq[14, 14]}") # try graham schmidt, they're just about the same! # seems to have detected an edge. Q, R = np.linalg.qr(mat_sq[14, 14]) print(f"Q:\n{Q}\nOriginal:\n{mat_sq[14, 14]}\nIs Q Unitary:\n{np.matmul(Q, Q.transpose(0, 1)).round()}") display = plt.imshow(Q) display.set_cmap('gray')
https://github.com/cjsproject/qiskit_learning
cjsproject
import numpy as np import matplotlib.pyplot as plt import seaborn as sns import sklearn from sklearn import datasets from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumRegister from qiskit import QuantumCircuit from qiskit import Aer, execute from math import pi,log from qiskit import * from qiskit.extensions import XGate, UnitaryGate import tensorflow as tf import cv2 #imported stuff from Weiwen's code import torch import torchvision from torchvision import datasets import torchvision.transforms as transforms import torch.nn as nn import shutil import os import time import sys from pathlib import Path import numpy as np import matplotlib.pyplot as plt import numpy as np from PIL import Image from skcuda.linalg import svd from matplotlib import cm import functools %matplotlib inline backend = Aer.get_backend('qasm_simulator') print = functools.partial(print, flush=True) interest_num = [3,6] ori_img_size = 28 #original image is 28x28 img_size = 4 #size to downsize to (set to 28 if no downsizing) # number of subprocesses to use for data loading num_workers = 0 # how many samples per batch to load batch_size = 1 inference_batch_size = 1 # Weiwen: modify the target classes starting from 0. Say, [3,6] -> [0,1] def modify_target(target): for j in range(len(target)): for idx in range(len(interest_num)): if target[j] == interest_num[idx]: target[j] = idx break new_target = torch.zeros(target.shape[0],2) for i in range(target.shape[0]): if target[i].item() == 0: new_target[i] = torch.tensor([1,0]).clone() else: new_target[i] = torch.tensor([0,1]).clone() return target,new_target def select_num(dataset,labels,interest_num): valid_labels = np.array([]) for num in interest_num: if valid_labels.size > 0: valid_labels += labels== num else: valid_labels = labels == num dataset = dataset[valid_labels] labels = labels[valid_labels] return (dataset,labels) def nomalizatied(ori,fig): row = fig['row'] col = fig['col'] transformed = [] for i in range(len(ori)): transform = np.resize(ori[i],(row,col)) transformed.append(transform) return transformed ################ Weiwen on 12-30-2020 ################ # Using torch to load MNIST data ###################################################### # convert data to torch.FloatTensor transform = transforms.Compose([transforms.Resize((ori_img_size,ori_img_size)), transforms.ToTensor()]) # Path to MNIST Dataset (train_data,train_labels),(test_data,test_labels) = tf.keras.datasets.mnist.load_data() (train_data,train_labels) = select_num(train_data,train_labels,interest_num) (test_data,test_labels) = select_num(test_data,test_labels,interest_num) #train_data = nomalizatied(train_data,{'row':4,'col':4}) #test_data = nomalizatied(test_data,{'row':4,'col':4}) train_data = train_data[:1000] train_labels = train_labels[:1000] train_data = torch.Tensor(train_data) # transform to torch tensor train_labels = torch.Tensor(train_labels) test_data = torch.Tensor(test_data) test_labels = torch.Tensor(test_labels) train = torch.utils.data.TensorDataset(train_data,train_labels) # create your datset test =torch.utils.data.TensorDataset(test_data,test_labels) u, s, v = svd(np.array(train_data[0:10]/255)) # prepare data loaders train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, num_workers=num_workers, shuffle=False, drop_last=True) test_loader = torch.utils.data.DataLoader(test, batch_size=inference_batch_size, num_workers=num_workers, shuffle=False, drop_last=True) class ToQuantumData(object): def __call__(self, input_vec): vec_len = len(input_vec) input_matrix = np.zeros((vec_len, vec_len)) input_matrix[0] = input_vec input_matrix = input_matrix.transpose() u, s, v = np.linalg.svd(input_matrix) output_matrix = np.dot(u, v) output_data = output_matrix[:, 0].view() return output_data class ToQuantumMatrix(object): def __call__(self, input_vec): vec_len = len(input_vec) input_matrix = np.zeros((vec_len, vec_len)) input_matrix[0] = input_vec #print('new input vec') input_matrix = input_matrix.transpose() #print(input_vec) u, s, v = np.linalg.svd(input_matrix) output_matrix = np.dot(u, v) return output_matrix def data_pre_pro(vector): # Converting classical data to quantum data trans_to_vector = ToQuantumData() trans_to_matrix = ToQuantumMatrix() #print("Classical Data: {}".format(vector)) #print("Quantum Data: {}".format(trans_to_vector(vector))) return trans_to_matrix(vector),trans_to_vector(vector) def PaddingNeeded(n): #check if n is a power of 2 num_decimal = np.log2(n) num_int = int(-(-num_decimal//1)) #round any decimal number up dims_needed = int(2**(num_int)) return dims_needed def pad_zeros(data): row = len(data) col = len(data[0]) dims = max(row,col) dims_needed = PaddingNeeded(dims) return np.pad(data,((0,dims_needed-row),(0,dims_needed-col)),'constant', constant_values=(0,0)) from tqdm import tqdm dataset = [] labels = [] # Use the first image from test loader as example for batch_idx, (data, target) in tqdm(enumerate(train_loader)): torch.set_printoptions(threshold=sys.maxsize) np.set_printoptions(threshold=sys.maxsize) data_grid = torchvision.utils.make_grid(data) #read the data from torch np_data = data_grid.numpy() #convert tensor to numpy array image = np.asarray(np_data[0] * 255, np.uint8) im = Image.fromarray(image,mode="L") im = im.resize((4,4),Image.BILINEAR) np_image = np.asarray(im)*1/255 #normalize the resized image data_pad = pad_zeros(np_image) #pad the data with zeros (if necessary) to make dimensionality a power of 2 np_1d = data_pad.ravel() #convert the padded data to 1-d array for encoding function quantum_matrix,quantum_data = data_pre_pro(np_1d) #convert the data to unitary matrix dataset.append(quantum_matrix) labels.append(quantum_data) for matrix in dataset: print(is_unitary(np.matrix(matrix))) train_labels_binary = train_labels == 3 train_labels_binary = np.array(train_labels_binary).astype('int') # 3 is Label 1, 6 is label 0 #------------------------------------------------------------------------------------------ #DATA ENCODING SECTION #------------------------------------------------------------------------------------------ def is_unitary(m): return np.allclose(np.eye(m.shape[0]), m.H * m) def quantum_encode(quantum_matrix): dims = len(quantum_matrix[0]) #dimensionality of data q=int(np.log2(dims)) # Number of qubits = log2(Dimensionality of data) (could be a decimal number) print(dims, 'classical bits encoded onto ', q, ' qubits') c=1 #one classical bit #Create quantum register and circuit inp = QuantumRegister(q,"in_qbit") circ = QuantumCircuit(inp) # Add classical register c_reg = ClassicalRegister(c,"reg") circ.add_register(c_reg) # From Listing 3: create auxiliary qubits #aux = QuantumRegister(1,"aux_qbit") #circ.add_register(aux) circ.append(UnitaryGate(quantum_matrix, label="Input"), inp[0:q]) return circ, q #encode the classicaL data into a quantum circuit (2^N parameters onto N qubits) circ, q= quantum_encode(quantum_matrix) print(circ) # Using StatevectorSimulator from the Aer provider simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() statevector = result.get_statevector(circ) print("Data to be encoded: \n {}\n".format(quantum_data)) print("Data read from the circuit: \n {}".format(statevector)) #All functions needed for the functionality of the circuit simulation def generate_and_save_images(model, epoch, test_input): # Notice `training` is set to False. # This is so all layers run in inference mode (batchnorm). predictions = model(test_input, training=False) fig = plt.figure(figsize=(4,4)) for i in range(predictions.shape[0]): plt.subplot(4, 4, i+1) dp = np.array((predictions[i] * 127.5) + 127.5).astype('uint8') plt.imshow(dp) plt.axis('off') #plt.savefig('image_at_epoch_{:04d}.png'.format(epoch)) plt.show() def ran_ang(): #return np.pi/2 return np.random.rand()*np.pi def single_qubit_unitary(circ_ident,qubit_index,values): circ_ident.ry(values[0],qubit_index) def dual_qubit_unitary(circ_ident,qubit_1,qubit_2,values): circ_ident.ryy(values[0],qubit_1,qubit_2) def controlled_dual_qubit_unitary(circ_ident,control_qubit,act_qubit,values): circ_ident.cry(values[0],control_qubit,act_qubit) #circ_ident.cry(values[0],act_qubit,control_qubit) def traditional_learning_layer(circ_ident,num_qubits,values,style="Dual",qubit_start=1,qubit_end=5): if style == "Dual": for qub in np.arange(qubit_start,qubit_end): single_qubit_unitary(circ_ident,qub,values[str(qub)]) for qub in np.arange(qubit_start,qubit_end-1): dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+","+str(qub+1)]) elif style =="Single": for qub in np.arange(qubit_start,qubit_end): single_qubit_unitary(circ_ident,qub,values[str(qub)]) elif style=="Controlled-Dual": for qub in np.arange(qubit_start,qubit_end): single_qubit_unitary(circ_ident,qub,values[str(qub)]) for qub in np.arange(qubit_start,qubit_end-1): dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+","+str(qub+1)]) for qub in np.arange(qubit_start,qubit_end-1): controlled_dual_qubit_unitary(circ_ident,qub,qub+1,values[str(qub)+"--"+str(qub+1)]) ''' def data_loading_circuit(circ_ident,num_qubits,values,qubit_start=1,qubit_end=5): k = 0 for qub in np.arange(qubit_start,qubit_end): circ_ident.ry(values[k],qub) k += 1 ''' def data_loading_circuit(circ_ident,quantum_matrix,qubit_start=1,qubit_end=5): circ_ident.append(UnitaryGate(quantum_matrix, label="Input"), circ_ident.qubits[qubit_start:qubit_end]) def quantum_encode(quantum_matrix): dims = len(quantum_matrix[0]) #dimensionality of data q=int(np.log2(dims)) # Number of qubits = log2(Dimensionality of data) (could be a decimal number) print(dims, 'classical bits encoded onto ', q, ' qubits') c=1 #one classical bit #Create quantum register and circuit inp = QuantumRegister(q,"in_qbit") circ = QuantumCircuit(inp) # Add classical register c_reg = ClassicalRegister(c,"reg") circ.add_register(c_reg) # From Listing 3: create auxiliary qubits #aux = QuantumRegister(1,"aux_qbit") #circ.add_register(aux) circ.append(UnitaryGate(quantum_matrix, label="Input"), inp[0:q]) return circ, q def swap_test(circ_ident,num_qubits): num_swap = num_qubits//2 for i in range(num_swap): circ_ident.cswap(0,i+1,i+num_swap+1) circ_ident.h(0) circ_ident.measure(0,0) def init_random_variables(q,style): trainable_variables = {} if style=="Single": for i in np.arange(1,q+1): trainable_variables[str(i)] = [ran_ang()] elif style=="Dual": for i in np.arange(1,q+1): trainable_variables[str(i)] = [ran_ang()] if i != q: trainable_variables[str(i)+","+str(i+1)] = [ran_ang()] elif style=="Controlled-Dual": for i in np.arange(1,q+1): trainable_variables[str(i)] = [ran_ang()] if i != q: trainable_variables[str(i)+","+str(i+1)] = [ran_ang()] trainable_variables[str(i)+"--"+str(i+1)] = [ran_ang()] return trainable_variables def get_probabilities(circ,counts=5000): job = execute(circ, backend, shots=counts) results = job.result().get_counts(circ) try: prob = results['0']/(results['1']+results['0']) prob = (prob-0.5) if prob <= 0.005: prob = 0.005 else: prob = prob*2 except: prob = 1 return prob # Define loss function. SWAP Test returns probability, so minmax probability is logical def cost_function(p,yreal,trimming): if yreal == 0: return -np.log(p) #return 1-p elif yreal == 1: return -np.log(1-p) #return p def generator_cost_function(p): return -np.log(p) def update_weights(init_value,lr,grad): while lr*grad > 2*np.pi: lr /= 10 print("Warning - Gradient taking steps that are very large. Drop learning rate") weight_update = lr*grad new_value = init_value print("Updating with a new value of " + str(weight_update)) if new_value-weight_update > 2*np.pi: new_value = (new_value-weight_update) - 2*np.pi elif new_value-weight_update < 0: new_value = (new_value-weight_update) + 2*np.pi else: new_value = new_value - weight_update return new_value # Define loss function. SWAP Test returns probability, so minmax probability is logical def cost_function(p,yreal,trimming): if yreal == 0: return -np.log(p) #return 1-p elif yreal == 1: return -np.log(1-p) #return p def generator_cost_function(p): return -np.log(p) def update_weights(init_value,lr,grad): while lr*grad > 2*np.pi: lr /= 10 print("Warning - Gradient taking steps that are very large. Drop learning rate") weight_update = lr*grad new_value = init_value print("Updating with a new value of " + str(weight_update)) if new_value-weight_update > 2*np.pi: new_value = (new_value-weight_update) - 2*np.pi elif new_value-weight_update < 0: new_value = (new_value-weight_update) + 2*np.pi else: new_value = new_value - weight_update return new_value QuantumCircuit(5,1).qubits # ------------------------------------------------------------------------------------ # We treat the first n qubits are the discriminators state. n is always defined as the # integer division floor of the qubit count. # This is due to the fact that a state will always be k qubits, therefore the # number of total qubits must be 2k+1. 2k as we need k for the disc, and k to represent # either the other learned quantum state, or k to represent a data point # then +1 to perform the SWAP test. Therefore, we know that we will always end up # with an odd number of qubits. We take the floor to solve for k. 1st k represents # disc, 2nd k represents the "loaded" state be it gen or real data # ------------------------------------------------------------------------------------ # Use different function calls to represent training a GENERATOR or training a DISCRIMINATOR # ------------------------------------------------------------------------------------ # THIS SECTION IS FOR THE ONLINE GENERATION OF QUANTUM CIRCUITS def disc_fake_training_circuit(trainable_variables,key,key_value,diff=False,fwd_diff = False,Sample=False): if Sample: z = q//2 circ = QuantumCircuit(q,z) else: circ = QuantumCircuit(q,c) circ.h(0) if diff == True and fwd_diff == True: trainable_variables[key][key_value] += par_shift if diff == True and fwd_diff == False: trainable_variables[key][key_value] -= par_shift traditional_learning_layer(circ,q,trainable_variables,style=layer_style,qubit_start=1,qubit_end=q//2 +1) traditional_learning_layer(circ,q,trainable_variables,style=layer_style,qubit_start=q//2 +1,qubit_end=q) if Sample: for qub in range(q//2): circ.measure(q//2 + 1 + qub,qub) else: swap_test(circ,q) if diff == True and fwd_diff == True: trainable_variables[key][key_value] -= par_shift if diff == True and fwd_diff == False: trainable_variables[key][key_value] += par_shift return circ def disc_real_training_circuit(training_variables,data,key,key_value,diff,fwd_diff): circ = QuantumCircuit(q,c) circ.h(0) if diff == True & fwd_diff == True: training_variables[key][key_value] += par_shift if diff == True & fwd_diff == False: training_variables[key][key_value] -= par_shift traditional_learning_layer(circ,q,training_variables,style=layer_style,qubit_start=1,qubit_end=q//2 +1) data_loading_circuit(circ,data,qubit_start=q//2+1,qubit_end=q) if diff == True & fwd_diff == True: training_variables[key][key_value] -= par_shift if diff == True & fwd_diff == False: training_variables[key][key_value] += par_shift swap_test(circ,q) return circ def generate_kl_divergence_hist(actual_data, epoch_results_data): plt.clf() # clears current figure sns.set() kl_div_vec = [] for kl_dim in range(actual_data.shape[1]): kl_div = kl_divergence(actual_data[:,kl_dim],epoch_results_data[:,kl_dim]) kl_div_vec.append(kl_div) return kl_div_vec def bin_data(dataset): bins = np.zeros(10) for point in dataset: indx = int(str(point).split('.')[-1][0]) # The shittest way imaginable to extract the first val aft decimal bins[indx] +=1 bins /= sum(bins) return bins def kl_divergence(p_dist, q_dist): p = bin_data(p_dist) q = bin_data(q_dist) kldiv = 0 for p_point,q_point in zip(p,q): kldiv += (np.sqrt(p_point) - np.sqrt(q_point))**2 kldiv = (1/np.sqrt(2))*kldiv**0.5 return kldiv #return sum(p[i] * log2(p[i]/q[i]) for i in range(len(p))) # ?... are we confident in this... # Checkpointing code def save_variables(train_var,epoch,number): with open(f"Epoch-{epoch}-Variables-numbers-{number}",'w') as file: file.write(str(train_var)) def load_variables(epoch,number): with open(f"Epoch-{epoch}-Variables-numbers-{number}",'r') as file: texts = file.read() return eval(texts) train_var_1 = load_variables(11,6) train_var_0 = load_variables(49,3) train_var_1 z = disc_real_training_circuit(train_var,quantum_matrix,'1',0,diff=False,fwd_diff=False) #z.append(UnitaryGate(quantum_matrix, label="Input"), z.qubits[10:20]) quantum_matrix dataset = np.array(dataset) labels = np.array(labels) train_labels_binary = train_labels_binary[:dataset.shape[0]] dataset = dataset[:5000] train_labels_binary = train_labels_binary[:5000] q=9# Number of qubits = Dimensionality of data = round up to even number = num qubits c=1 circ = QuantumCircuit(q,c) circ.h(0) layer_style = "Controlled-Dual" train_var_0 = init_random_variables(q//2,layer_style) train_var_1 = init_random_variables(q//2,layer_style) #train_var_2 = init_random_variables(q//2,layer_style) tracked_d_loss = [] tracked_d_loss1 = [] gradients = [] learning_rate=0.015 train_iter = 50 corr = 0 wrong= 0 loss_d_to_real = 0 print('Starting Training') print('-'*20) print("train_var_0 training") for epoch in range(train_iter): start = time.time() loss = [0,0] par_shift = 0.5*np.pi/((1+epoch)**0.5) for index,point in enumerate(dataset[train_labels_binary==0]): for key,value in train_var_0.items(): if str(q//2 + 1 ) in key: break for key_value in range(len(value)): forward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=True,fwd_diff=True))) backward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=True,fwd_diff=False))) df = 0.5*(forward_diff-backward_diff) train_var_0[key][key_value] -= df*learning_rate #print(f"Updated Variable {key}-({key_value}) by {-df*learning_rate}") print('Time for Epoch {} is {} sec'.format(epoch+1,time.time()-start)) print("-"*20) save_variables(train_var_0,epoch,3) for epoch in range(train_iter): start = time.time() loss = [0,0] par_shift = 0.5*np.pi/((1+epoch)**0.5) for index,point in enumerate(dataset[train_labels_binary==1]): for key,value in train_var_1.items(): if str(q//2 + 1 ) in key: break for key_value in range(len(value)): forward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=True,fwd_diff=True))) backward_diff = -np.log(get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=True,fwd_diff=False))) df = 0.5*(forward_diff-backward_diff) train_var_1[key][key_value] -= df*learning_rate print('Time for Epoch {} is {} sec'.format(epoch+1,time.time()-start)) print("-"*20) save_variables(train_var_1,epoch,6) def is_unitary(m): return np.allclose(np.eye(m.shape[0]), m.H * m) is_unitary(np.matrix(quantum_matrix[0])) corr = 0 wron = 0 for index,point in enumerate(dataset[train_labels_binary==1]): p1 = get_probabilities(disc_real_training_circuit(train_var_0,point,key,key_value,diff=False,fwd_diff=False)) p2 = get_probabilities(disc_real_training_circuit(train_var_1,point,key,key_value,diff=False,fwd_diff=False)) if p1<p2: corr +=1 else: wron+=1 acc = corr/(corr+wron) print(acc) corr wron 829
https://github.com/cjsproject/qiskit_learning
cjsproject
%matplotlib inline # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Q account(s) provider = IBMQ.load_account() provider.backends() from qiskit.providers.ibmq import least_busy large_enough_devices = provider.backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator) backend = least_busy(large_enough_devices) print("The best backend is " + backend.name()) # quasm_sim not necessary #simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor # circuit on q reg with 1 qubit circuit = QuantumCircuit(2, 2) # hadamard on A circuit.h(0) # CNOT on B controlled by A circuit.cx(0 , 1) circuit.measure([0, 1], [0, 1]) job = execute(circuit, backend, shots=1000) job_monitor(job) results = job.result() counts = results.get_counts(circuit) print(f"total count for 0 and 1 are: {counts}") circuit.draw() plot_histogram(counts)
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
""" Test Script """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qrx = QuantumRegister(1, 'q0') qry = QuantumRegister(1, 'q1') cr = ClassicalRegister(1, 'c') qc = QuantumCircuit(qrx, qry, cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.x(qry) qc.barrier() qc.h(qrx) qc.h(qry) qc.measure(qrx, cr) qc.draw("mpl") from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim = AerSimulator() job = execute(qc, backend = sim, shots = 1000) result = job.result() counts = result.get_counts(qc) print("Counts: ", counts) plot_histogram(counts)
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. """ Exception for errors raised by Qiskit Aer simulators backends. """ from qiskit import QiskitError class AerError(QiskitError): """Base class for errors raised by simulators.""" def __init__(self, *message): """Set the error message.""" super().__init__(*message) self.message = ' '.join(message) def __str__(self): """Return the message.""" return repr(self.message)
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 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. """ Compatibility classes for changes to save instruction return types. These subclasses include a `__getattr__` method that allows existing code which used numpy.ndarray attributes to continue functioning with a deprecation warning. Numpy functions that consumed these classes should already work due to them having an `__array__` method for implicit array conversion. """ import warnings import numpy as np import qiskit.quantum_info as qi def _forward_attr(attr): """Return True if attribute should be passed to legacy class""" # Pass Iterable magic methods on to the Numpy array. We can't pass # `__getitem__` (and consequently `__setitem__`, `__delitem__`) on because # `Statevector` implements them itself. if attr[:2] == '__' or attr in ['_data', '_op_shape']: return False return True def _deprecation_warning(instance, instances_name): class_name = instance.__class__.__name__ warnings.warn( f"The return type of saved {instances_name} has been changed from" f" a `numpy.ndarray` to a `qiskit.quantum_info.{class_name}` as" " of qiskit-aer 0.10. Accessing numpy array attributes is deprecated" " and will result in an error in a future release. To continue using" " saved result objects as arrays you can explicitly cast them using " " `np.asarray(object)`.", DeprecationWarning, stacklevel=3, ) class Statevector(qi.Statevector): """Aer result backwards compatibility wrapper for qiskit Statevector.""" def __getattr__(self, attr): if _forward_attr(attr) and hasattr(self._data, attr): _deprecation_warning(self, "statevectors") return getattr(self._data, attr) return getattr(super(), attr) def __eq__(self, other): return ( isinstance(self, type(other)) and self._op_shape == other._op_shape and np.allclose(self.data, other.data, rtol=self.rtol, atol=self.atol) ) def __bool__(self): # Explicit override to the default behaviour for Python objects to # prevent the new `__len__` from messing with it. return True # Magic methods for the iterable/collection interface that need forwarding, # but bypass `__getattr__`. `__getitem__` is defined by `Statevector`, so # that can't be forwarded (and consequently neither can `__setitem__` # without introducing an inconsistency). def __len__(self): _deprecation_warning(self, "statevectors") return self._data.__len__() def __iter__(self): _deprecation_warning(self, "statevectors") return self._data.__iter__() def __contains__(self, value): _deprecation_warning(self, "statevectors") return self._data.__contains__(value) def __reversed__(self): _deprecation_warning(self, "statevectors") return self._data.__reversed__() class DensityMatrix(qi.DensityMatrix): """Aer result backwards compatibility wrapper for qiskit DensityMatrix.""" def __getattr__(self, attr): if _forward_attr(attr) and hasattr(self._data, attr): _deprecation_warning(self, "density matrices") return getattr(self._data, attr) return getattr(super(), attr) def __eq__(self, other): return ( isinstance(self, type(other)) and self._op_shape == other._op_shape and np.allclose(self.data, other.data, rtol=self.rtol, atol=self.atol) ) def __len__(self): _deprecation_warning(self, "density matrices") return self._data.__len__() def __iter__(self): _deprecation_warning(self, "density matrices") return self._data.__iter__() def __contains__(self, value): _deprecation_warning(self, "density matrices") return self._data.__contains__(value) def __reversed__(self): _deprecation_warning(self, "density matrices") return self._data.__reversed__() def __getitem__(self, key): _deprecation_warning(self, "density matrices") return self._data.__getitem__(key) def __setitem__(self, key, value): _deprecation_warning(self, "density matrices") return self._data.__setitem__(key, value) class Operator(qi.Operator): """Aer result backwards compatibility wrapper for qiskit Operator.""" def __getattr__(self, attr): if _forward_attr(attr) and hasattr(self._data, attr): _deprecation_warning(self, "unitaries") return getattr(self._data, attr) return getattr(super(), attr) def __eq__(self, other): return ( isinstance(self, type(other)) and self._op_shape == other._op_shape and np.allclose(self.data, other.data, rtol=self.rtol, atol=self.atol) ) def __bool__(self): # Explicit override to the default behaviour for Python objects to # prevent the new `__len__` from messing with it. return True def __len__(self): _deprecation_warning(self, "unitaries") return self._data.__len__() def __iter__(self): _deprecation_warning(self, "unitaries") return self._data.__iter__() def __contains__(self, value): _deprecation_warning(self, "unitaries") return self._data.__contains__(value) def __reversed__(self): _deprecation_warning(self, "unitaries") return self._data.__reversed__() def __getitem__(self, key): _deprecation_warning(self, "unitaries") return self._data.__getitem__(key) def __setitem__(self, key, value): _deprecation_warning(self, "unitaries") return self._data.__setitem__(key, value) class SuperOp(qi.SuperOp): """Aer result backwards compatibility wrapper for qiskit SuperOp.""" def __getattr__(self, attr): if _forward_attr(attr) and hasattr(self._data, attr): _deprecation_warning(self, "superoperators") return getattr(self._data, attr) return getattr(super(), attr) def __eq__(self, other): return ( isinstance(self, type(other)) and self._op_shape == other._op_shape and np.allclose(self.data, other.data, rtol=self.rtol, atol=self.atol) ) def __bool__(self): # Explicit override to the default behaviour for Python objects to # prevent the new `__len__` from messing with it. return True def __len__(self): _deprecation_warning(self, "superoperators") return self._data.__len__() def __iter__(self): _deprecation_warning(self, "superoperators") return self._data.__iter__() def __contains__(self, value): _deprecation_warning(self, "superoperators") return self._data.__contains__(value) def __reversed__(self): _deprecation_warning(self, "superoperators") return self._data.__reversed__() def __getitem__(self, key): _deprecation_warning(self, "superoperators") return self._data.__getitem__(key) def __setitem__(self, key, value): _deprecation_warning(self, "superoperators") return self._data.__setitem__(key, value) class StabilizerState(qi.StabilizerState): """Aer result backwards compatibility wrapper for qiskit StabilizerState.""" def __deprecation_warning(self): warnings.warn( "The return type of saved stabilizers has been changed from" " a `dict` to a `qiskit.quantum_info.StabilizerState` as of qiskit-aer 0.10." " Accessing dict attributes is deprecated and will result in an" " error in a future release. Use the `.clifford.to_dict()` methods to access " " the stored Clifford operator and convert to a dictionary.", DeprecationWarning, stacklevel=3, ) def __getattr__(self, attr): if _forward_attr(attr) and hasattr(dict, attr): self.__deprecation_warning() return getattr(self._data.to_dict(), attr) return getattr(super(), attr) def __getitem__(self, item): if item in ["stabilizer", "destabilizer"]: warnings.warn( "The return type of saved stabilizers has been changed from" " a `dict` to a `qiskit.quantum_info.StabilizerState` as of qiskit-aer 0.10." " Accessing dict items is deprecated and will result in an" " error in a future release. Use the `.clifford.to_dict()` methods to access " " the stored Clifford operator and convert to a dictionary.", DeprecationWarning, stacklevel=2) return self._data.to_dict()[item] raise TypeError("'StabilizerState object is not subscriptable'") def __bool__(self): # Explicit override to the default behaviour for Python objects to # prevent the new `__len__` from messing with it. return True def __len__(self): self.__deprecation_warning() return self._data.to_dict().__len__() def __iter__(self): self.__deprecation_warning() return self._data.to_dict().__iter__() def __contains__(self, value): self.__deprecation_warning() return self._data.to_dict().__contains__(value) def __reversed__(self): self.__deprecation_warning() return self._data.to_dict().__reversed__() def _add(self, other): raise NotImplementedError(f"{type(self)} does not support addition") def _multiply(self, other): raise NotImplementedError(f"{type(self)} does not support scalar multiplication")
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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. """ Simulator command to snapshot internal simulator representation. """ import warnings from qiskit import QuantumCircuit from qiskit.circuit import CompositeGate from qiskit import QuantumRegister from qiskit.circuit import Instruction from qiskit.extensions.exceptions import ExtensionError class Snapshot(Instruction): """Simulator snapshot instruction.""" def __init__(self, label, snapshot_type='statevector', num_qubits=0, num_clbits=0, params=None): """Create new snapshot instruction. Args: label (str): the snapshot label for result data. snapshot_type (str): the type of the snapshot. num_qubits (int): the number of qubits for the snapshot type [Default: 0]. num_clbits (int): the number of classical bits for the snapshot type [Default: 0]. params (list or None): the parameters for snapshot_type [Default: None]. Raises: ExtensionError: if snapshot label is invalid. """ if not isinstance(label, str): raise ExtensionError('Snapshot label must be a string.') self._label = label self._snapshot_type = snapshot_type if params is None: params = [] super().__init__('snapshot', num_qubits, num_clbits, params) def assemble(self): """Assemble a QasmQobjInstruction""" instruction = super().assemble() instruction.label = self._label instruction.snapshot_type = self._snapshot_type return instruction def inverse(self): """Special case. Return self.""" return Snapshot(self.num_qubits, self.num_clbits, self.params[0], self.params[1]) @property def snapshot_type(self): """Return snapshot type""" return self._snapshot_type @property def label(self): """Return snapshot label""" return self._label @label.setter def label(self, name): """Set snapshot label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None. """ if isinstance(name, str): self._label = name else: raise TypeError('label expects a string') def snapshot(self, label, snapshot_type='statevector', qubits=None, params=None): """Take a statevector snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). For other types of snapshots use the Snapshot extension directly. Args: label (str): a snapshot label to report the result snapshot_type (str): the type of the snapshot. qubits (list or None): the qubits to apply snapshot to [Default: None]. params (list or None): the parameters for snapshot_type [Default: None]. Returns: QuantumCircuit: with attached command Raises: ExtensionError: malformed command """ # Convert label to string for backwards compatibility if not isinstance(label, str): warnings.warn( "Snapshot label should be a string, " "implicit conversion is depreciated.", DeprecationWarning) label = str(label) # If no qubits are specified we add all qubits so it acts as a barrier # This is needed for full register snapshots like statevector if isinstance(qubits, QuantumRegister): qubits = qubits[:] if not qubits: tuples = [] if isinstance(self, QuantumCircuit): for register in self.qregs: tuples.append(register) if not tuples: raise ExtensionError('no qubits for snapshot') qubits = [] for tuple_element in tuples: if isinstance(tuple_element, QuantumRegister): for j in range(tuple_element.size): qubits.append((tuple_element, j)) else: qubits.append(tuple_element) return self.append( Snapshot( label, snapshot_type=snapshot_type, num_qubits=len(qubits), params=params), qubits) # Add to QuantumCircuit and CompositeGate classes QuantumCircuit.snapshot = snapshot CompositeGate.snapshot = snapshot
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. """ Simulator command to snapshot internal simulator representation. """ from warnings import warn from qiskit import QuantumCircuit from .snapshot import Snapshot class SnapshotDensityMatrix(Snapshot): """Snapshot instruction for density matrix method of Qasm simulator.""" def __init__(self, label, num_qubits): """Create a density matrix state snapshot instruction. Args: label (str): the snapshot label. num_qubits (int): the number of qubits to snapshot. Raises: ExtensionError: if snapshot is invalid. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :class:`qiskit.providers.aer.library.SaveDensityMatrix` instruction. """ warn('The `SnapshotDensityMatrix` instruction has been deprecated as of' ' qiskit-aer 0.9. It has been superseded by the `SaveDensityMatrix`' ' instructions.', DeprecationWarning, stacklevel=2) super().__init__(label, snapshot_type='density_matrix', num_qubits=num_qubits) def snapshot_density_matrix(self, label, qubits=None): """Take a density matrix snapshot of simulator state. Args: label (str): a snapshot label to report the result qubits (list or None): the qubits to apply snapshot to. If None all qubits will be snapshot [Default: None]. Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :class:`qiskit.providers.aer.library.save_density_matrix` circuit method. """ warn('The `snapshot_density_matrix` circuit method has been deprecated as of' ' qiskit-aer 0.9 and will be removed in a future release.' ' It has been superseded by the `save_density_matrix`' ' circuit method.', DeprecationWarning, stacklevel=2) snapshot_register = Snapshot.define_snapshot_register(self, qubits=qubits) return self.append( SnapshotDensityMatrix(label, num_qubits=len(snapshot_register)), snapshot_register) QuantumCircuit.snapshot_density_matrix = snapshot_density_matrix
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. """ Simulator command to snapshot internal simulator representation. """ from warnings import warn import math import numpy from qiskit import QuantumCircuit from qiskit.circuit import Instruction from qiskit.extensions.exceptions import ExtensionError from qiskit.qobj import QasmQobjInstruction from qiskit.quantum_info.operators import Pauli, Operator from .snapshot import Snapshot class SnapshotExpectationValue(Snapshot): """Snapshot instruction for supported methods of Qasm simulator.""" def __init__(self, label, op, single_shot=False, variance=False): """Create an expectation value snapshot instruction. Args: label (str): the snapshot label. op (Operator): operator to snapshot. single_shot (bool): return list for each shot rather than average [Default: False] variance (bool): compute variance of values [Default: False] Raises: ExtensionError: if snapshot is invalid. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :class:`qiskit.providers.aer.library.SaveExpectationValue` and :class:`qiskit.providers.aer.library.SaveExpectationValueVariance` instructions. """ warn('The `SnapshotExpectationValue` instruction has been deprecated as of' ' qiskit-aer 0.9. It has been superseded by the `SaveExpectationValue` and' ' `SaveExpectationValueVariance` instructions.', DeprecationWarning, stacklevel=2) pauli_op = self._format_pauli_op(op) if pauli_op: # Pauli expectation value snapshot_type = 'expectation_value_pauli' params = pauli_op num_qubits = len(params[0][1]) else: snapshot_type = 'expectation_value_matrix' mat = self._format_single_matrix(op) if mat is not None: num_qubits = int(math.log2(len(mat))) if mat.shape != (2 ** num_qubits, 2 ** num_qubits): raise ExtensionError("Snapshot Operator is invalid.") qubits = list(range(num_qubits)) params = [[1., [[qubits, mat]]]] else: # If op doesn't match the previous cases we try passing # in the op as raw params params = op num_qubits = 0 for _, pair in params: num_qubits = max(num_qubits, *pair[0]) # HACK: we wrap param list in numpy array to make it validate # in terra params = [numpy.array(elt, dtype=object) for elt in params] if single_shot: snapshot_type += '_single_shot' elif variance: snapshot_type += '_with_variance' super().__init__(label, snapshot_type=snapshot_type, num_qubits=num_qubits, params=params) @staticmethod def _format_single_matrix(op): """Format op into Matrix op, return None if not Pauli op""" # This can be specified as list [[coeff, Pauli], ... ] if isinstance(op, numpy.ndarray): return op if isinstance(op, (Instruction, QuantumCircuit)): return Operator(op).data if hasattr(op, 'to_operator'): return op.to_operator().data return None @staticmethod def _format_pauli_op(op): """Format op into Pauli op, return None if not Pauli op""" # This can be specified as list [[coeff, Pauli], ... ] if isinstance(op, Pauli): return [[1., op.to_label()]] if not isinstance(op, (list, tuple)): return None pauli_op = [] for pair in op: if len(pair) != 2: return None coeff = complex(pair[0]) pauli = pair[1] if isinstance(pauli, Pauli): pauli_op.append([coeff, pauli.to_label()]) elif isinstance(pair[1], str): pauli_op.append([coeff, pauli]) else: return None return pauli_op def assemble(self): """Assemble a QasmQobjInstruction for snapshot_expectation_value.""" return QasmQobjInstruction(name=self.name, params=[x.tolist() for x in self.params], snapshot_type=self.snapshot_type, qubits=list(range(self.num_qubits)), label=self.label) def snapshot_expectation_value(self, label, op, qubits, single_shot=False, variance=False): """Take a snapshot of expectation value <O> of an Operator. Args: label (str): a snapshot label to report the result op (Operator): operator to snapshot qubits (list): the qubits to snapshot. single_shot (bool): return list for each shot rather than average [Default: False] variance (bool): compute variance of values [Default: False] Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :func:`qiskit.providers.aer.library.save_expectation_value` and :func:`qiskit.providers.aer.library.save_expectation_value_variance` circuit methods. """ warn('The `snapshot_expectation_value` circuit method has been deprecated as of' ' qiskit-aer 0.9 and will be removed in a future release.' ' It has been superseded by the `save_expectation_value`' ' and `save_expectation_value_variance` circuit methods.', DeprecationWarning, stacklevel=2) snapshot_register = Snapshot.define_snapshot_register(self, qubits=qubits) return self.append( SnapshotExpectationValue(label, op, single_shot=single_shot, variance=variance), snapshot_register) QuantumCircuit.snapshot_expectation_value = snapshot_expectation_value
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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 """ Simulator command to snapshot internal simulator representation. """ from warnings import warn from qiskit import QuantumCircuit from .snapshot import Snapshot class SnapshotProbabilities(Snapshot): """Snapshot instruction for all methods of Qasm simulator.""" def __init__(self, label, num_qubits, variance=False): """Create a probability snapshot instruction. Args: label (str): the snapshot label. num_qubits (int): the number of qubits to snapshot. variance (bool): compute variance of probabilities [Default: False] Raises: ExtensionError: if snapshot is invalid. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :class:`qiskit.providers.aer.library.SaveProbabilities` and :class:`qiskit.providers.aer.library.SaveProbabilitiesDict` instructions. """ warn('The `SnapshotProbabilities` instruction has been deprecated as of' ' qiskit-aer 0.9. It has been superseded by the `SaveProbabilities` and' ' `SaveProbabilitiesDict` instructions.', DeprecationWarning, stacklevel=2) snapshot_type = 'probabilities_with_variance' if variance else 'probabilities' super().__init__(label, snapshot_type=snapshot_type, num_qubits=num_qubits) def snapshot_probabilities(self, label, qubits, variance=False): """Take a probability snapshot of the simulator state. Args: label (str): a snapshot label to report the result qubits (list): the qubits to snapshot. variance (bool): compute variance of probabilities [Default: False] Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :func:`qiskit.providers.aer.library.save_probabilities` and :func:`qiskit.providers.aer.library.save_probabilities_dict` circuit methods. """ warn('The `snapshot_probabilities` circuit method has been deprecated as of' ' qiskit-aer 0.9. It has been superseded by the `save_probabilities`' ' and `save_probabilities_dict` circuit methods.', DeprecationWarning) snapshot_register = Snapshot.define_snapshot_register(self, qubits=qubits) return self.append( SnapshotProbabilities(label, num_qubits=len(snapshot_register), variance=variance), snapshot_register) QuantumCircuit.snapshot_probabilities = snapshot_probabilities
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. """ Simulator command to snapshot internal simulator representation. """ from warnings import warn from qiskit import QuantumCircuit from .snapshot import Snapshot class SnapshotStabilizer(Snapshot): """Snapshot instruction for stabilizer method of Qasm simulator.""" def __init__(self, label, num_qubits=0): """Create a stabilizer state snapshot instruction. Args: label (str): the snapshot label. num_qubits (int): the instruction barrier size [Default: 0]. Raises: ExtensionError: if snapshot is invalid. Additional Information: This snapshot is always performed on all qubits in a circuit. The number of qubits parameter specifies the size of the instruction as a barrier and should be set to the number of qubits in the circuit. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :class:`qiskit.providers.aer.library.SaveStabilizer` instruction. """ warn('The `SnapshotStabilizer` instruction will be deprecated in the' ' future. It has been superseded by the `save_stabilizer`' ' instructions.', DeprecationWarning, stacklevel=2) super().__init__(label, snapshot_type='stabilizer', num_qubits=num_qubits) def snapshot_stabilizer(self, label): """Take a stabilizer snapshot of the simulator state. Args: label (str): a snapshot label to report the result. Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. Additional Information: This snapshot is always performed on all qubits in a circuit. The number of qubits parameter specifies the size of the instruction as a barrier and should be set to the number of qubits in the circuit. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :func:`qiskit.providers.aer.library.save_stabilizer` circuit method. """ warn('The `snapshot_stabilizer` circuit method has been deprecated as of' ' qiskit-aer 0.9 and will be removed in a future release.' ' It has been superseded by the `save_stabilizer`' ' circuit method.', DeprecationWarning, stacklevel=2) snapshot_register = Snapshot.define_snapshot_register(self) return self.append( SnapshotStabilizer(label, num_qubits=len(snapshot_register)), snapshot_register) QuantumCircuit.snapshot_stabilizer = snapshot_stabilizer
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. """ Simulator command to snapshot internal simulator representation. """ from warnings import warn from qiskit import QuantumCircuit from .snapshot import Snapshot class SnapshotStatevector(Snapshot): """ Snapshot instruction for statevector snapshot type """ def __init__(self, label, num_qubits=0): """Create a statevector state snapshot instruction. Args: label (str): the snapshot label. num_qubits (int): the instruction barrier size [Default: 0]. Raises: ExtensionError: if snapshot is invalid. Additional Information: This snapshot is always performed on all qubits in a circuit. The number of qubits parameter specifies the size of the instruction as a barrier and should be set to the number of qubits in the circuit. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :class:`qiskit.providers.aer.library.SaveStatevector` instruction. """ warn('The `SnapshotStatevector` instruction will be deprecated in the' 'future. It has been superseded by the `SaveStatevector`' ' instructions.', DeprecationWarning, stacklevel=2) super().__init__(label, snapshot_type='statevector', num_qubits=num_qubits) def snapshot_statevector(self, label): """Take a statevector snapshot of the simulator state. Args: label (str): a snapshot label to report the result. Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. Additional Information: This snapshot is always performed on all qubits in a circuit. The number of qubits parameter specifies the size of the instruction as a barrier and should be set to the number of qubits in the circuit. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :class:`qiskit.providers.aer.library.save_statevector` circuit method. """ warn('The `snapshot_statevector` circuit method has been deprecated as of' ' qiskit-aer 0.9 and will be removed in a future release.' ' It has been superseded by the `save_statevector`' ' circuit method.', DeprecationWarning, stacklevel=2) # Statevector snapshot acts as a barrier across all qubits in the # circuit snapshot_register = Snapshot.define_snapshot_register(self) return self.append( SnapshotStatevector(label, num_qubits=len(snapshot_register)), snapshot_register) QuantumCircuit.snapshot_statevector = snapshot_statevector
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. """ Exception for errors raised by Qiskit Aer noise module. """ from qiskit import QiskitError class NoiseError(QiskitError): """Class for errors raised in qiskit_aer.noise package.""" def __init__(self, *message): """Set the error message.""" super().__init__(*message) self.message = ' '.join(message) def __str__(self): """Return the message.""" return repr(self.message)
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. """ Noise model class for Qiskit Aer simulators. """ import json import logging from typing import Optional from warnings import warn, catch_warnings, filterwarnings from numpy import ndarray from qiskit.circuit import Instruction, Delay from qiskit.providers.exceptions import BackendPropertyError from qiskit.providers.models import BackendProperties from qiskit.transpiler import PassManager from .device.models import _excited_population, _truncate_t2_value from .device.models import basic_device_gate_errors from .device.models import basic_device_readout_errors from .errors.quantum_error import QuantumError from .errors.readout_error import ReadoutError from .noiseerror import NoiseError from .passes import RelaxationNoisePass from ..backends.backend_utils import BASIS_GATES logger = logging.getLogger(__name__) class AerJSONEncoder(json.JSONEncoder): """ JSON encoder for NumPy arrays and complex numbers. This functions as the standard JSON Encoder but adds support for encoding: complex numbers z as lists [z.real, z.imag] ndarrays as nested lists. """ # pylint: disable=method-hidden,arguments-differ def default(self, obj): if isinstance(obj, ndarray): return obj.tolist() if isinstance(obj, complex): return [obj.real, obj.imag] if hasattr(obj, "to_dict"): return obj.to_dict() return super().default(obj) class QuantumErrorLocation(Instruction): """Instruction for referencing a multi-qubit error in a NoiseModel""" _directive = True def __init__(self, qerror): """Construct a new quantum error location instruction. Args: qerror (QuantumError): the quantum error to reference. """ super().__init__("qerror_loc", qerror.num_qubits, 0, [], label=qerror.id) class NoiseModel: """Noise model class for Qiskit Aer simulators. This class is used to represent noise model for the :class:`~qiskit.providers.aer.QasmSimulator`. It can be used to construct custom noise models for simulator, or to automatically generate a basic device noise model for an IBMQ backend. See the :mod:`~qiskit.providers.aer.noise` module documentation for additional information. **Example: Basic device noise model** An approximate :class:`NoiseModel` can be generated automatically from the properties of real device backends from the IBMQ provider using the :meth:`~NoiseModel.from_backend` method. .. code-block:: python from qiskit import IBMQ, Aer from qiskit.providers.aer.noise import NoiseModel provider = IBMQ.load_account() backend = provider.get_backend('ibmq_vigo') noise_model = NoiseModel.from_backend(backend) print(noise_model) **Example: Custom noise model** Custom noise models can be used by adding :class:`QuantumError` to circuit gate, reset or measure instructions, and :class:`ReadoutError` to measure instructions. .. code-block:: python import qiskit.providers.aer.noise as noise # Error probabilities prob_1 = 0.001 # 1-qubit gate prob_2 = 0.01 # 2-qubit gate # Depolarizing quantum errors error_1 = noise.depolarizing_error(prob_1, 1) error_2 = noise.depolarizing_error(prob_2, 2) # Add errors to noise model noise_model = noise.NoiseModel() noise_model.add_all_qubit_quantum_error(error_1, ['rz', 'sx', 'x']) noise_model.add_all_qubit_quantum_error(error_2, ['cx']) print(noise_model) """ # Checks for standard 1-3 qubit instructions _1qubit_instructions = set([ 'u1', 'u2', 'u3', 'u', 'p', 'r', 'rx', 'ry', 'rz', 'id', 'x', 'y', 'z', 'h', 's', 'sdg', 'sx', 'sxdg', 't', 'tdg']) _2qubit_instructions = set([ 'swap', 'cx', 'cy', 'cz', 'csx', 'cp', 'cu', 'cu1', 'cu2', 'cu3', 'rxx', 'ryy', 'rzz', 'rzx']) _3qubit_instructions = set(['ccx', 'cswap']) def __init__(self, basis_gates=None): """Initialize an empty noise model. Args: basis_gates (list[str] or None): Specify an initial basis_gates for the noise model. If None a default value of ['id', 'rz', 'sx', 'cx'] is used (Default: None). Additional Information: Errors added to the noise model will have their instruction appended to the noise model basis_gates if the instruction is in the :class:`~qiskit.providers.aer.QasmSimulator` basis_gates. If the instruction is not in the :class:`~qiskit.providers.aer.QasmSimulator` basis_gates it is assumed to be a label for a standard gate, and that gate should be added to the `NoiseModel` basis_gates either using the init method, or the :meth:`add_basis_gates` method. """ if basis_gates is None: # Default basis gates is id, rz, sx, cx so that all standard # non-identity instructions can be unrolled to rz, sx, cx, # and identities won't be unrolled self._basis_gates = set(['id', 'rz', 'sx', 'cx']) else: self._basis_gates = set( name for name, _ in self._instruction_names_labels(basis_gates)) # Store gates with a noise model defined self._noise_instructions = set() # Store qubits referenced in noise model. # These include gate qubits in local quantum and readout errors, # and both gate and noise qubits for non-local quantum errors. self._noise_qubits = set() # Default (all-qubit) quantum errors are stored as: # dict(str: QuantumError) # where they keys are the instruction str label self._default_quantum_errors = {} # Local quantum errors are stored as: # dict(str: dict(tuple: QuantumError)) # where the outer keys are the instruction str label and the # inner dict keys are the gate qubits self._local_quantum_errors = {} # Non-local quantum errors are stored as: # dict(str: dict(tuple: dict(tuple: QuantumError))) # where the outer keys are the instruction str label, the middle dict # keys are the gate qubits, and the inner most dict keys are # the noise qubits. self._nonlocal_quantum_errors = {} # Default (all-qubit) readout error is stored as a single # ReadoutError object since there may only be one defined. self._default_readout_error = None # Local readout errors are stored as: # dict(tuple: ReadoutError) # where the dict keys are the gate qubits. self._local_readout_errors = {} # Custom noise passes self._custom_noise_passes = [] @property def basis_gates(self): """Return basis_gates for compiling to the noise model.""" # Convert noise instructions to basis_gates string return sorted(self._basis_gates) @property def noise_instructions(self): """Return the set of noisy instructions for this noise model.""" return sorted(self._noise_instructions) @property def noise_qubits(self): """Return the set of noisy qubits for this noise model.""" return sorted(self._noise_qubits) @classmethod def from_backend(cls, backend, gate_error=True, readout_error=True, thermal_relaxation=True, temperature=0, gate_lengths=None, gate_length_units='ns', standard_gates=None, warnings=True): """Return a noise model derived from a devices backend properties. This function generates a noise model based on: * 1 and 2 qubit gate errors consisting of a :func:`depolarizing_error` followed by a :func:`thermal_relaxation_error`. * Single qubit :class:`ReadoutError` on all measurements. The Error error parameters are tuned for each individual qubit based on the :math:`T_1`, :math:`T_2`, frequency and readout error parameters for each qubit, and the gate error and gate time parameters for each gate obtained from the device backend properties. **Additional Information** The noise model includes the following errors: * If ``readout_error=True`` include single qubit readout errors on measurements. * If ``gate_error=True`` and ``thermal_relaxation=True`` include: * Single-qubit gate errors consisting of a :func:`depolarizing_error` followed by a :func:`thermal_relaxation_error` for the qubit the gate acts on. * Two-qubit gate errors consisting of a 2-qubit :func:`depolarizing_error` followed by single qubit :func:`thermal_relaxation_error` on each qubit participating in the gate. * If ``gate_error=True`` is ``True`` and ``thermal_relaxation=False``: * An N-qubit :func:`depolarizing_error` on each N-qubit gate. * If ``gate_error=False`` and ``thermal_relaxation=True`` include single-qubit :func:`thermal_relaxation_errors` on each qubits participating in a multi-qubit gate. For best practice in simulating a backend make sure that the circuit is compiled using the set of basis gates in the noise module by setting ``basis_gates=noise_model.basis_gates`` and using the device coupling map with ``coupling_map=backend.configuration().coupling_map`` **Specifying custom gate times** The ``gate_lengths`` kwarg can be used to specify custom gate times to add gate errors using the :math:`T_1` and :math:`T_2` values from the backend properties. This should be passed as a list of tuples ``gate_lengths=[(name, value), ...]`` where ``name`` is the gate name string, and ``value`` is the gate time in nanoseconds. If a custom gate is specified that already exists in the backend properties, the ``gate_lengths`` value will override the gate time value from the backend properties. If non-default values are used gate_lengths should be a list Args: backend (BackendV1): backend. gate_error (bool): Include depolarizing gate errors (Default: True). readout_error (Bool): Include readout errors in model (Default: True). thermal_relaxation (Bool): Include thermal relaxation errors (Default: True). temperature (double): qubit temperature in milli-Kelvin (mK) for thermal relaxation errors (Default: 0). gate_lengths (list): Custom gate times for thermal relaxation errors. Used to extend or override the gate times in the backend properties (Default: None)) gate_length_units (str): Time units for gate length values in gate_lengths. Can be 'ns', 'ms', 'us', or 's' (Default: 'ns'). standard_gates (bool): DEPRECATED, If true return errors as standard qobj gates. If false return as unitary qobj instructions (Default: None) warnings (bool): Display warnings (Default: True). Returns: NoiseModel: An approximate noise model for the device backend. Raises: NoiseError: If the input backend is not valid. """ backend_interface_version = getattr(backend, "version", None) if not isinstance(backend_interface_version, int): backend_interface_version = 0 if backend_interface_version == 2: raise NoiseError( "NoiseModel.from_backend does not currently support V2 Backends.") if backend_interface_version <= 1: properties = backend.properties() configuration = backend.configuration() basis_gates = configuration.basis_gates num_qubits = configuration.num_qubits dt = getattr(configuration, "dt", 0) if not properties: raise NoiseError('Qiskit backend {} does not have a ' 'BackendProperties'.format(backend)) elif isinstance(backend, BackendProperties): warn( 'Passing BackendProperties instead of a "backend" object ' 'has been deprecated as of qiskit-aer 0.10.0 and will be ' 'removed no earlier than 3 months from that release date. ' 'Duration dependent delay relaxation noise requires a ' 'backend object.', DeprecationWarning, stacklevel=2) properties = backend basis_gates = set() for prop in properties.gates: basis_gates.add(prop.gate) basis_gates = list(basis_gates) num_qubits = len(properties.qubits) dt = 0 # disable delay noise if dt is unknown else: raise NoiseError('{} is not a Qiskit backend or' ' BackendProperties'.format(backend)) noise_model = NoiseModel(basis_gates=basis_gates) # Add single-qubit readout errors if readout_error: for qubits, error in basic_device_readout_errors(properties): noise_model.add_readout_error(error, qubits, warnings=warnings) if standard_gates is not None: warn( '"standard_gates" option has been deprecated as of qiskit-aer 0.10.0' ' and will be removed no earlier than 3 months from that release date.', DeprecationWarning, stacklevel=2) # Add gate errors with catch_warnings(): filterwarnings( "ignore", category=DeprecationWarning, module="qiskit.providers.aer.noise.device.models" ) gate_errors = basic_device_gate_errors( properties, gate_error=gate_error, thermal_relaxation=thermal_relaxation, gate_lengths=gate_lengths, gate_length_units=gate_length_units, temperature=temperature, standard_gates=standard_gates, warnings=warnings) for name, qubits, error in gate_errors: noise_model.add_quantum_error(error, name, qubits, warnings=warnings) if thermal_relaxation: # Add delay errors via RelaxationNiose pass try: excited_state_populations = [ _excited_population( freq=properties.frequency(q), temperature=temperature ) for q in range(num_qubits)] except BackendPropertyError: excited_state_populations = None try: t1s = [properties.t1(q) for q in range(num_qubits)] t2s = [properties.t2(q) for q in range(num_qubits)] delay_pass = RelaxationNoisePass( t1s=t1s, t2s=[_truncate_t2_value(t1, t2) for t1, t2 in zip(t1s, t2s)], dt=dt, op_types=Delay, excited_state_populations=excited_state_populations ) noise_model._custom_noise_passes.append(delay_pass) except BackendPropertyError: # Device does not have the required T1 or T2 information # in its properties pass return noise_model def is_ideal(self): # pylint: disable=too-many-return-statements """Return True if the noise model has no noise terms.""" # Get default errors if self._default_quantum_errors: return False if self._default_readout_error: return False if self._local_quantum_errors: return False if self._local_readout_errors: return False if self._nonlocal_quantum_errors: return False if self._custom_noise_passes: return False return True def __repr__(self): """Noise model repr""" return "<NoiseModel on {}>".format(list(self._noise_instructions)) def __str__(self): """Noise model string representation""" # Check if noise model is ideal if self.is_ideal(): return "NoiseModel: Ideal" # Get default errors default_error_ops = [] for inst in self._default_quantum_errors: default_error_ops.append('{}'.format(inst)) if self._default_readout_error is not None: if 'measure' not in default_error_ops: default_error_ops.append('measure') # Get local errors local_error_ops = [] for inst, dic in self._local_quantum_errors.items(): for qubits in dic.keys(): local_error_ops.append((inst, qubits)) for qubits in self._local_readout_errors: tmp = ('measure', qubits) if tmp not in local_error_ops: local_error_ops.append(tmp) # Get nonlocal errors nonlocal_error_ops = [] for inst, dic in self._nonlocal_quantum_errors.items(): for qubits, errors in dic.items(): for noise_qubits in errors: nonlocal_error_ops.append((inst, qubits, noise_qubits)) output = "NoiseModel:" output += "\n Basis gates: {}".format(self.basis_gates) if self._noise_instructions: output += "\n Instructions with noise: {}".format( list(self._noise_instructions)) if self._noise_qubits: output += "\n Qubits with noise: {}".format( list(self._noise_qubits)) if default_error_ops: output += "\n All-qubits errors: {}".format(default_error_ops) if local_error_ops: output += "\n Specific qubit errors: {}".format( local_error_ops) if nonlocal_error_ops: output += "\n Non-local specific qubit errors: {}".format( nonlocal_error_ops) return output def __eq__(self, other): """Test if two noise models are equal.""" # This returns True if both noise models have: # the same basis_gates # the same noise_qubits # the same noise_instructions if (not isinstance(other, NoiseModel) or self.basis_gates != other.basis_gates or self.noise_qubits != other.noise_qubits or self.noise_instructions != other.noise_instructions): return False # Check default readout errors is equal if not self._readout_errors_equal(other): return False # Check quantum errors equal if not self._all_qubit_quantum_errors_equal(other): return False if not self._local_quantum_errors_equal(other): return False if not self._nonlocal_quantum_errors_equal(other): return False # If we made it here they are equal return True def reset(self): """Reset the noise model.""" self.__init__() def add_basis_gates(self, instructions, warnings=False): """Add additional gates to the noise model basis_gates. This should be used to add any gates that are identified by a custom gate label in the noise model. Args: instructions (list[str] or list[Instruction]): the instructions error applies to. warnings (bool): [DEPRECATED] display warning if instruction is not in QasmSimulator basis_gates (Default: False). """ for name, _ in self._instruction_names_labels(instructions): # If the instruction is in the default basis gates for the # AerSimulator we add it to the basis gates. if name in BASIS_GATES['automatic']: if name not in ['measure', 'reset', 'initialize', 'kraus', 'superop', 'roerror']: self._basis_gates.add(name) elif warnings: warn('"warnings" option has been deprecated as of qiskit-aer 0.10.0' ' and will be removed no earlier than 3 months from that release date.', DeprecationWarning, stacklevel=2) logger.warning( "Warning: Adding a gate \"%s\" to basis_gates which is " "not in AerSimulator basis_gates.", name) def add_all_qubit_quantum_error(self, error, instructions, warnings=True): """ Add a quantum error to the noise model that applies to all qubits. Args: error (QuantumError): the quantum error object. instructions (str or list[str] or Instruction or list[Instruction]): the instructions error applies to. warnings (bool): Display warning if appending to an instruction that already has an error (Default: True). Raises: NoiseError: if the input parameters are invalid. Additional Information: If the error object is ideal it will not be added to the model. """ # Format input as QuantumError if not isinstance(error, QuantumError): try: error = QuantumError(error) except NoiseError: raise NoiseError("Input is not a valid quantum error.") # Check if error is ideal and if so don't add to the noise model if error.ideal(): return # Add instructions for name, label in self._instruction_names_labels(instructions): self._check_number_of_qubits(error, name) if label in self._default_quantum_errors: new_error = self._default_quantum_errors[label].compose(error) self._default_quantum_errors[label] = new_error if warnings: logger.warning( "WARNING: all-qubit error already exists for " "instruction \"%s\", " "composing with additional error.", label) else: self._default_quantum_errors[label] = error # Check if a specific qubit error has been applied for this instruction if label in self._local_quantum_errors: local_qubits = self._keys2str( self._local_quantum_errors[label].keys()) if warnings: logger.warning( "WARNING: all-qubit error for instruction " "\"%s\" will not apply to qubits: " "%s as specific error already exists.", label, local_qubits) self._noise_instructions.add(label) self.add_basis_gates(name) def add_quantum_error(self, error, instructions, qubits, warnings=True): """ Add a quantum error to the noise model. Args: error (QuantumError): the quantum error object. instructions (str or list[str] or Instruction or list[Instruction]): the instructions error applies to. qubits (Sequence[int]): qubits instruction error applies to. warnings (bool): Display warning if appending to an instruction that already has an error (Default: True). Raises: NoiseError: if the input parameters are invalid. Additional Information: If the error object is ideal it will not be added to the model. """ # Error checking if not isinstance(error, QuantumError): try: error = QuantumError(error) except NoiseError: raise NoiseError("Input is not a valid quantum error.") try: qubits = tuple(qubits) except TypeError as ex: raise NoiseError("Qubits must be convertible to a tuple of integers") from ex # Check if error is ideal and if so don't add to the noise model if error.ideal(): return # Add noise qubits for qubit in qubits: self._noise_qubits.add(qubit) # Add instructions for name, label in self._instruction_names_labels(instructions): self._check_number_of_qubits(error, name) if not isinstance(label, str): raise NoiseError("Qobj invalid instructions.") # Check number of qubits is correct for standard instructions self._check_number_of_qubits(error, name) if label in self._local_quantum_errors: qubit_dict = self._local_quantum_errors[label] else: qubit_dict = {} # Convert qubits list to hashable string if error.num_qubits != len(qubits): raise NoiseError("Number of qubits ({}) does not match " " the error size ({})".format( len(qubits), error.num_qubits)) if qubits in qubit_dict: new_error = qubit_dict[qubits].compose(error) qubit_dict[qubits] = new_error if warnings: logger.warning( "WARNING: quantum error already exists for " "instruction \"%s\" on qubits %s " ", appending additional error.", label, qubits) else: qubit_dict[qubits] = error # Add updated dictionary self._local_quantum_errors[label] = qubit_dict # Check if all-qubit error is already defined for this instruction if label in self._default_quantum_errors: if warnings: logger.warning( "WARNING: Specific error for instruction \"%s\" " "on qubits %s overrides previously defined " "all-qubit error for these qubits.", label, qubits) self._noise_instructions.add(label) self.add_basis_gates(name) def add_nonlocal_quantum_error(self, error, instructions, qubits, noise_qubits, warnings=True): """ Add a non-local quantum error to the noise model (DEPRECATED). .. deprecated:: 0.9.0 Adding nonlocal noise to a noise model is deprecated and will be removed no earlier than 3 months from the qiskit-aer 0.9.0 release date. To add non-local noise to a circuit you should write a custom qiskit transpiler pass. Args: error (QuantumError): the quantum error object. instructions (str or list[str] or Instruction or list[Instruction]): the instructions error applies to. qubits (Sequence[int]): qubits instruction error applies to. noise_qubits (Sequence[int]): Specify the exact qubits the error should be applied to if different to the instruction qubits. warnings (bool): Display warning if appending to an instruction that already has an error (Default: True). Raises: NoiseError: if the input parameters are invalid. Additional Information: If the error object is ideal it will not be added to the model. """ warn('Adding nonlocal noise to a noise model is deprecated as of' ' qiskit-aer 0.9.0 and will be removed no earlier than 3' ' months from that release date. To add non-local noise to' ' a circuit you should write a custom qiskit transpiler pass.', DeprecationWarning) # Error checking if not isinstance(error, QuantumError): try: error = QuantumError(error) except NoiseError: raise NoiseError("Input is not a valid quantum error.") try: qubits = tuple(qubits) noise_qubits = tuple(noise_qubits) except TypeError as ex: raise NoiseError("Qubits must be convertible to a tuple of integers") from ex # Check if error is ideal and if so don't add to the noise model if error.ideal(): return # Add noise qubits for qubit in qubits: self._noise_qubits.add(qubit) for qubit in noise_qubits: self._noise_qubits.add(qubit) # Add instructions for name, label in self._instruction_names_labels(instructions): if label in self._nonlocal_quantum_errors: gate_qubit_dict = self._nonlocal_quantum_errors[label] else: gate_qubit_dict = {} if qubits in gate_qubit_dict: noise_qubit_dict = gate_qubit_dict[qubits] if noise_qubits in noise_qubit_dict: new_error = noise_qubit_dict[noise_qubits].compose(error) noise_qubit_dict[noise_qubits] = new_error else: noise_qubit_dict[noise_qubits] = error gate_qubit_dict[qubits] = noise_qubit_dict if warnings: logger.warning( "Warning: nonlocal error already exists for " "instruction \"%s\" on qubits %s." "Composing additional error.", label, qubits) else: gate_qubit_dict[qubits] = {noise_qubits: error} # Add updated dictionary self._nonlocal_quantum_errors[label] = gate_qubit_dict self._noise_instructions.add(label) self.add_basis_gates(name, warnings=False) def add_all_qubit_readout_error(self, error, warnings=True): """ Add a single-qubit readout error that applies measure on all qubits. Args: error (ReadoutError): the quantum error object. warnings (bool): Display warning if appending to an instruction that already has an error (Default: True) Raises: NoiseError: if the input parameters are invalid. Additional Information: If the error object is ideal it will not be added to the model. """ # Error checking if not isinstance(error, ReadoutError): try: error = ReadoutError(error) except NoiseError: raise NoiseError("Input is not a valid readout error.") # Check if error is ideal and if so don't add to the noise model if error.ideal(): return # Check number of qubits is correct for standard instructions if error.number_of_qubits != 1: raise NoiseError( "All-qubit readout errors must defined as single-qubit errors." ) if self._default_readout_error is not None: if warnings: logger.warning( "WARNING: all-qubit readout error already exists, " "overriding with new readout error.") self._default_readout_error = error # Check if a specific qubit error has been applied for this instruction if self._local_readout_errors: local_qubits = self._keys2str(self._local_readout_errors.keys()) if warnings: logger.warning( "WARNING: The all-qubit readout error will not " "apply to measure of qubits qubits: %s " "as specific readout errors already exist.", local_qubits) self._noise_instructions.add("measure") def add_readout_error(self, error, qubits, warnings=True): """ Add a readout error to the noise model. Args: error (ReadoutError): the quantum error object. qubits (list[int] or tuple[int]): qubits instruction error applies to. warnings (bool): Display warning if appending to an instruction that already has an error [Default: True] Raises: NoiseError: if the input parameters are invalid. Additional Information: If the error object is ideal it will not be added to the model. """ # Error checking if not isinstance(error, ReadoutError): try: error = ReadoutError(error) except NoiseError: raise NoiseError("Input is not a valid readout error.") try: qubits = tuple(qubits) except TypeError as ex: raise NoiseError("Qubits must be convertible to a tuple of integers") from ex # Check if error is ideal and if so don't add to the noise model if error.ideal(): return # Add noise qubits for qubit in qubits: self._noise_qubits.add(qubit) # Check error matches qubit size if error.number_of_qubits != len(qubits): raise NoiseError( "Number of qubits ({}) does not match the readout " "error size ({})".format(len(qubits), error.number_of_qubits)) # Check if we are overriding a previous error if qubits in self._local_readout_errors: if warnings: logger.warning( "WARNING: readout error already exists for qubits " "%s, overriding with new readout error.", qubits) self._local_readout_errors[qubits] = error # Check if all-qubit readout error is already defined if self._default_readout_error is not None: if warnings: logger.warning( "WARNING: Specific readout error on qubits " "%s overrides previously defined " "all-qubit readout error for these qubits.", qubits) self._noise_instructions.add("measure") def to_dict(self, serializable=False): """ Return the noise model as a dictionary. Args: serializable (bool): if `True`, return a dict containing only types that can be serializable by the stdlib `json` module. Returns: dict: a dictionary for a noise model. """ error_list = [] # Add default quantum errors for name, error in self._default_quantum_errors.items(): error_dict = error.to_dict() error_dict["operations"] = [name] error_list.append(error_dict) # Add specific qubit errors for name, qubit_dict in self._local_quantum_errors.items(): for qubits, error in qubit_dict.items(): error_dict = error.to_dict() error_dict["operations"] = [name] error_dict["gate_qubits"] = [qubits] error_list.append(error_dict) # Add non-local errors for name, qubit_dict in self._nonlocal_quantum_errors.items(): for qubits, noise_qubit_dict in qubit_dict.items(): for noise_qubits, error in noise_qubit_dict.items(): error_dict = error.to_dict() error_dict["operations"] = [name] error_dict["gate_qubits"] = [qubits] error_dict["noise_qubits"] = [noise_qubits] error_list.append(error_dict) # Add default readout error if self._default_readout_error is not None: error_dict = self._default_readout_error.to_dict() error_list.append(error_dict) # Add local readout error for qubits, error in self._local_readout_errors.items(): error_dict = error.to_dict() error_dict["gate_qubits"] = [qubits] error_list.append(error_dict) ret = {"errors": error_list} if serializable: ret = json.loads(json.dumps(ret, cls=AerJSONEncoder)) return ret @staticmethod def from_dict(noise_dict): """ Load NoiseModel from a dictionary. Args: noise_dict (dict): A serialized noise model. Returns: NoiseModel: the noise model. Raises: NoiseError: if dict cannot be converted to NoiseModel. """ warn('from_dict has been deprecated as of qiskit-aer 0.10.0' ' and will be removed no earlier than 3 months from that release date.', DeprecationWarning, stacklevel=2) # Return noise model noise_model = NoiseModel() # Get error terms errors = noise_dict.get('errors', []) for error in errors: error_type = error['type'] # Add QuantumError if error_type == 'qerror': noise_ops = tuple( zip(error['instructions'], error['probabilities'])) instruction_names = error['operations'] all_gate_qubits = error.get('gate_qubits', None) all_noise_qubits = error.get('noise_qubits', None) with catch_warnings(): filterwarnings("ignore", category=DeprecationWarning, module="qiskit.providers.aer.noise") qerror = QuantumError(noise_ops) qerror._id = error.get('id', None) or qerror.id if all_gate_qubits is not None: for gate_qubits in all_gate_qubits: # Load non-local quantum error if all_noise_qubits is not None: for noise_qubits in all_noise_qubits: noise_model.add_nonlocal_quantum_error( qerror, instruction_names, gate_qubits, noise_qubits, warnings=False) # Add local quantum error else: noise_model.add_quantum_error( qerror, instruction_names, gate_qubits, warnings=False) else: # Add all-qubit quantum error noise_model.add_all_qubit_quantum_error( qerror, instruction_names, warnings=False) # Add ReadoutError elif error_type == 'roerror': probabilities = error['probabilities'] all_gate_qubits = error.get('gate_qubits', None) roerror = ReadoutError(probabilities) # Add local readout error if all_gate_qubits is not None: for gate_qubits in all_gate_qubits: noise_model.add_readout_error( roerror, gate_qubits, warnings=False) # Add all-qubit readout error else: noise_model.add_all_qubit_readout_error( roerror, warnings=False) # Invalid error type else: raise NoiseError("Invalid error type: {}".format(error_type)) return noise_model def _instruction_names_labels(self, instructions): """Return two lists of instruction name strings and label strings.""" if not isinstance(instructions, (list, tuple)): instructions = [instructions] names_labels = [] for inst in instructions: # If instruction does not have a label we use the name # as the label if isinstance(inst, Instruction): name = inst.name label = getattr(inst, 'label', inst.name) names_labels.append((name, label)) elif isinstance(inst, str): names_labels.append((inst, inst)) else: raise NoiseError('Invalid instruction type {}'.format(inst)) return names_labels def _check_number_of_qubits(self, error, name): """ Check if error is corrected number of qubits for standard instruction. Args: error (QuantumError): the quantum error object. name (str): qobj instruction name to apply error to. Raises: NoiseError: If instruction and error qubit number do not match. """ def error_message(gate_qubits): msg = "{} qubit QuantumError".format(error.num_qubits) + \ " cannot be applied to {} qubit".format(gate_qubits) + \ " instruction \"{}\".".format(name) return msg if name in self._1qubit_instructions and error.num_qubits != 1: raise NoiseError(error_message(1)) if name in self._2qubit_instructions and error.num_qubits != 2: raise NoiseError(error_message(2)) if name in self._3qubit_instructions and error.num_qubits != 3: raise NoiseError(error_message(3)) def _keys2str(self, keys): """Convert dicitonary keys to comma seperated print string.""" tmp = "".join(["{}, ".format(key) for key in keys]) return tmp[:-2] def _readout_errors_equal(self, other): """Check two noise models have equal readout errors""" # Check default readout error is equal if self._default_readout_error != other._default_readout_error: return False # Check local readout errors are equal if sorted(self._local_readout_errors.keys()) != sorted( other._local_readout_errors.keys()): return False for key in self._local_readout_errors: if self._local_readout_errors[key] != other._local_readout_errors[ key]: return False return True def _all_qubit_quantum_errors_equal(self, other): """Check two noise models have equal local quantum errors""" if sorted(self._default_quantum_errors.keys()) != sorted( other._default_quantum_errors.keys()): return False for key in self._default_quantum_errors: if self._default_quantum_errors[ key] != other._default_quantum_errors[key]: return False return True def _local_quantum_errors_equal(self, other): """Check two noise models have equal local quantum errors""" if sorted(self._local_quantum_errors.keys()) != sorted( other._local_quantum_errors.keys()): return False for key in self._local_quantum_errors: inner_dict1 = self._local_quantum_errors[key] inner_dict2 = other._local_quantum_errors[key] if sorted(inner_dict1.keys()) != sorted(inner_dict2.keys()): return False for inner_key in inner_dict1: if inner_dict1[inner_key] != inner_dict2[inner_key]: return False if self._local_quantum_errors[key] != other._local_quantum_errors[ key]: return False return True def _nonlocal_quantum_errors_equal(self, other): """Check two noise models have equal non-local quantum errors""" if sorted(self._nonlocal_quantum_errors.keys()) != sorted( other._nonlocal_quantum_errors.keys()): return False for key in self._nonlocal_quantum_errors: inner_dict1 = self._nonlocal_quantum_errors[key] inner_dict2 = other._nonlocal_quantum_errors[key] if sorted(inner_dict1.keys()) != sorted(inner_dict2.keys()): return False for inner_key in inner_dict1: iinner_dict1 = inner_dict1[inner_key] iinner_dict2 = inner_dict2[inner_key] if sorted(iinner_dict1.keys()) != sorted(iinner_dict2.keys()): return False for iinner_key in iinner_dict1: if iinner_dict1[iinner_key] != iinner_dict2[iinner_key]: return False return True def _pass_manager(self) -> Optional[PassManager]: """ Return the pass manager that add custom noises defined as noise passes (stored in the _custom_noise_passes field). Note that the pass manager does not include passes to add other noises (stored in the different field). """ passes = [] passes.extend(self._custom_noise_passes) if len(passes) > 0: return PassManager(passes) return None
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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=invalid-name """ Simplified noise models for devices backends. """ import logging from warnings import warn, catch_warnings, filterwarnings from numpy import inf, exp, allclose import qiskit.quantum_info as qi from .parameters import readout_error_values from .parameters import gate_param_values from .parameters import thermal_relaxation_values from .parameters import _NANOSECOND_UNITS from ..errors.readout_error import ReadoutError from ..errors.standard_errors import depolarizing_error from ..errors.standard_errors import thermal_relaxation_error logger = logging.getLogger(__name__) def basic_device_readout_errors(properties): """ Return readout error parameters from a devices BackendProperties. Args: properties (BackendProperties): device backend properties Returns: list: A list of pairs ``(qubits, ReadoutError)`` for qubits with non-zero readout error values. """ errors = [] for qubit, value in enumerate(readout_error_values(properties)): if value is not None and not allclose(value, [0, 0]): probabilities = [[1 - value[0], value[0]], [value[1], 1 - value[1]]] errors.append(([qubit], ReadoutError(probabilities))) return errors def basic_device_gate_errors(properties, gate_error=True, thermal_relaxation=True, gate_lengths=None, gate_length_units='ns', temperature=0, standard_gates=None, warnings=True): """ Return QuantumErrors derived from a devices BackendProperties. If non-default values are used gate_lengths should be a list of tuples ``(name, qubits, value)`` where ``name`` is the gate name string, ``qubits`` is either a list of qubits or ``None`` to apply gate time to this gate one any set of qubits, and ``value`` is the gate time in nanoseconds. Args: properties (BackendProperties): device backend properties gate_error (bool): Include depolarizing gate errors (Default: True). thermal_relaxation (Bool): Include thermal relaxation errors (Default: True). gate_lengths (list): Override device gate times with custom values. If None use gate times from backend properties. (Default: None). gate_length_units (str): Time units for gate length values in gate_lengths. Can be 'ns', 'ms', 'us', or 's' (Default: 'ns'). temperature (double): qubit temperature in milli-Kelvin (mK) (Default: 0). standard_gates (bool): DEPRECATED, If true return errors as standard qobj gates. If false return as unitary qobj instructions (Default: None). warnings (bool): Display warnings (Default: True). Returns: list: A list of tuples ``(label, qubits, QuantumError)``, for gates with non-zero quantum error terms, where `label` is the label of the noisy gate, `qubits` is the list of qubits for the gate. """ if standard_gates is not None: warn( '"standard_gates" option has been deprecated as of qiskit-aer 0.10.0' ' and will be removed no earlier than 3 months from that release date.', DeprecationWarning, stacklevel=2) # Initilize empty errors depol_error = None relax_error = None # Generate custom gate time dict custom_times = {} relax_params = [] if thermal_relaxation: # If including thermal relaxation errors load # T1, T2, and frequency values from properties relax_params = thermal_relaxation_values(properties) # If we are specifying custom gate times include # them in the custom times dict if gate_lengths: for name, qubits, value in gate_lengths: # Convert all gate lengths to nanosecond units time = value * _NANOSECOND_UNITS[gate_length_units] if name in custom_times: custom_times[name].append((qubits, time)) else: custom_times[name] = [(qubits, time)] # Get the device gate parameters from properties device_gate_params = gate_param_values(properties) # Construct quantum errors errors = [] for name, qubits, gate_length, error_param in device_gate_params: # Check for custom gate time relax_time = gate_length # Override with custom value if name in custom_times: filtered = [ val for q, val in custom_times[name] if q is None or q == qubits ] if filtered: # get first value relax_time = filtered[0] # Get relaxation error if thermal_relaxation: relax_error = _device_thermal_relaxation_error( qubits, relax_time, relax_params, temperature, thermal_relaxation) # Get depolarizing error channel if gate_error: with catch_warnings(): filterwarnings( "ignore", category=DeprecationWarning, module="qiskit.providers.aer.noise.errors.errorutils" ) depol_error = _device_depolarizing_error( qubits, error_param, relax_error, standard_gates, warnings=warnings) # Combine errors if depol_error is None and relax_error is None: # No error for this gate pass elif depol_error is not None and relax_error is None: # Append only the depolarizing error errors.append((name, qubits, depol_error)) # Append only the relaxation error elif relax_error is not None and depol_error is None: errors.append((name, qubits, relax_error)) else: # Append a combined error of depolarizing error # followed by a relaxation error combined_error = depol_error.compose(relax_error) errors.append((name, qubits, combined_error)) return errors def _device_depolarizing_error(qubits, error_param, relax_error=None, standard_gates=True, warnings=True): """Construct a depolarizing_error for device""" # We now deduce the depolarizing channel error parameter in the # presence of T1/T2 thermal relaxation. We assume the gate error # parameter is given by e = 1 - F where F is the average gate fidelity, # and that this average gate fidelity is for the composition # of a T1/T2 thermal relaxation channel and a depolarizing channel. # For the n-qubit depolarizing channel E_dep = (1-p) * I + p * D, where # I is the identity channel and D is the completely depolarizing # channel. To compose the errors we solve for the equation # F = F(E_dep * E_relax) # = (1 - p) * F(I * E_relax) + p * F(D * E_relax) # = (1 - p) * F(E_relax) + p * F(D) # = F(E_relax) - p * (dim * F(E_relax) - 1) / dim # Hence we have that the depolarizing error probability # for the composed depolarization channel is # p = dim * (F(E_relax) - F) / (dim * F(E_relax) - 1) if relax_error is not None: relax_fid = qi.average_gate_fidelity(relax_error) relax_infid = 1 - relax_fid else: relax_fid = 1 relax_infid = 0 if error_param is not None and error_param > relax_infid: num_qubits = len(qubits) dim = 2 ** num_qubits error_max = dim / (dim + 1) # Check if reported error param is un-physical # The minimum average gate fidelity is F_min = 1 / (dim + 1) # So the maximum gate error is 1 - F_min = dim / (dim + 1) if error_param > error_max: if warnings: logger.warning( 'Device reported a gate error parameter greater' ' than maximum allowed value (%f > %f). Truncating to' ' maximum value.', error_param, error_max) error_param = error_max # Model gate error entirely as depolarizing error num_qubits = len(qubits) dim = 2 ** num_qubits depol_param = dim * (error_param - relax_infid) / (dim * relax_fid - 1) max_param = 4**num_qubits / (4**num_qubits - 1) if depol_param > max_param: if warnings: logger.warning( 'Device model returned a depolarizing error parameter greater' ' than maximum allowed value (%f > %f). Truncating to' ' maximum value.', depol_param, max_param) depol_param = min(depol_param, max_param) return depolarizing_error( depol_param, num_qubits, standard_gates=standard_gates) return None def _device_thermal_relaxation_error(qubits, gate_time, relax_params, temperature, thermal_relaxation=True): """Construct a thermal_relaxation_error for device""" # Check trivial case if not thermal_relaxation or gate_time is None or gate_time == 0: return None # Construct a tensor product of single qubit relaxation errors # for any multi qubit gates first = True error = None for qubit in qubits: t1, t2, freq = relax_params[qubit] t2 = _truncate_t2_value(t1, t2) population = _excited_population(freq, temperature) if first: error = thermal_relaxation_error(t1, t2, gate_time, population) first = False else: single = thermal_relaxation_error(t1, t2, gate_time, population) error = error.expand(single) return error def _truncate_t2_value(t1, t2): """Return t2 value truncated to 2 * t1 (for t2 > 2 * t1)""" new_t2 = t2 if t2 > 2 * t1: new_t2 = 2 * t1 warn("Device model returned an invalid T_2 relaxation time greater than" f" the theoretical maximum value 2 * T_1 ({t2} > 2 * {t1})." " Truncating to maximum value.", UserWarning) return new_t2 def _excited_population(freq, temperature): """Return excited state population""" population = 0 if freq != inf and temperature != 0: # Compute the excited state population from qubit # frequency and temperature # Boltzman constant kB = 8.617333262-5 (eV/K) # Planck constant h = 4.135667696e-15 (eV.s) # qubit temperature temperatue = T (mK) # qubit frequency frequency = f (GHz) # excited state population = 1/(1+exp((2*h*f*1e9)/(kb*T*1e-3))) exp_param = exp((95.9849 * freq) / abs(temperature)) population = 1 / (1 + exp_param) if temperature < 0: # negative temperate implies |1> is thermal ground population = 1 - population return population
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # 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. """ Noise model inserter module The goal of this module is to add QuantumError gates (Kraus gates) to a circuit based on a given noise model. """ import qiskit.compiler def insert_noise(circuits, noise_model, transpile=False): """Return a noisy version of a QuantumCircuit. Args: circuits (QuantumCircuit or list[QuantumCircuit]): Input noise-free circuits. noise_model (NoiseModel): The noise model containing the errors to add transpile (Boolean): Should the circuit be transpiled into the noise model basis gates Returns: QuantumCircuit: The new circuit with the Kraus noise instructions inserted. Additional Information: The noisy circuit return by this function will consist of the original circuit with ``Kraus`` instructions inserted after all instructions referenced in the ``noise_model``. The resulting circuit cannot be ran on a quantum computer but can be executed on the :class:`~qiskit.providers.aer.QasmSimulator`. """ is_circuits_list = isinstance(circuits, (list, tuple)) circuits = circuits if is_circuits_list else [circuits] result_circuits = [] nonlocal_errors = noise_model._nonlocal_quantum_errors local_errors = noise_model._local_quantum_errors default_errors = noise_model._default_quantum_errors for circuit in circuits: if transpile: transpiled_circuit = qiskit.compiler.transpile(circuit, basis_gates=noise_model.basis_gates) else: transpiled_circuit = circuit qubit_indices = {bit: index for index, bit in enumerate(transpiled_circuit.qubits)} result_circuit = transpiled_circuit.copy(name=transpiled_circuit.name + '_with_noise') result_circuit.data = [] for inst, qargs, cargs in transpiled_circuit.data: result_circuit.data.append((inst, qargs, cargs)) qubits = tuple(qubit_indices[q] for q in qargs) # Priority for error model used: # nonlocal error > local error > default error if inst.name in nonlocal_errors and qubits in nonlocal_errors[inst.name]: for noise_qubits, error in nonlocal_errors[inst.name][qubits].items(): result_circuit.append(error.to_instruction(), noise_qubits) elif inst.name in local_errors and qubits in local_errors[inst.name]: error = local_errors[inst.name][qubits] result_circuit.append(error.to_instruction(), qargs) elif inst.name in default_errors.keys(): error = default_errors[inst.name] result_circuit.append(error.to_instruction(), qargs) result_circuits.append(result_circuit) return result_circuits if is_circuits_list else result_circuits[0]
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# 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. """Contains functions used by the basic aer simulators. """ from string import ascii_uppercase, ascii_lowercase from typing import List, Optional import numpy as np import qiskit.circuit.library.standard_gates as gates from qiskit.exceptions import QiskitError # Single qubit gates supported by ``single_gate_params``. SINGLE_QUBIT_GATES = ("U", "u1", "u2", "u3", "rz", "sx", "x") def single_gate_matrix(gate: str, params: Optional[List[float]] = None): """Get the matrix for a single qubit. Args: gate: the single qubit gate name params: the operation parameters op['params'] Returns: array: A numpy array representing the matrix Raises: QiskitError: If a gate outside the supported set is passed in for the ``Gate`` argument. """ if params is None: params = [] if gate == "U": gc = gates.UGate elif gate == "u3": gc = gates.U3Gate elif gate == "u2": gc = gates.U2Gate elif gate == "u1": gc = gates.U1Gate elif gate == "rz": gc = gates.RZGate elif gate == "id": gc = gates.IGate elif gate == "sx": gc = gates.SXGate elif gate == "x": gc = gates.XGate else: raise QiskitError("Gate is not a valid basis gate for this simulator: %s" % gate) return gc(*params).to_matrix() # Cache CX matrix as no parameters. _CX_MATRIX = gates.CXGate().to_matrix() def cx_gate_matrix(): """Get the matrix for a controlled-NOT gate.""" return np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=complex) def einsum_matmul_index(gate_indices, number_of_qubits): """Return the index string for Numpy.einsum matrix-matrix multiplication. The returned indices are to perform a matrix multiplication A.B where the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and M <= N, and identity matrices are implied on the subsystems where A has no support on B. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Right indices for the N-qubit input and output tensor tens_r = ascii_uppercase[:number_of_qubits] # Combine indices into matrix multiplication string format # for numpy.einsum function return "{mat_l}{mat_r}, ".format( mat_l=mat_l, mat_r=mat_r ) + "{tens_lin}{tens_r}->{tens_lout}{tens_r}".format( tens_lin=tens_lin, tens_lout=tens_lout, tens_r=tens_r ) def einsum_vecmul_index(gate_indices, number_of_qubits): """Return the index string for Numpy.einsum matrix-vector multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: str: An indices string for the Numpy.einsum function. """ mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits) # Combine indices into matrix multiplication string format # for numpy.einsum function return f"{mat_l}{mat_r}, " + "{tens_lin}->{tens_lout}".format( tens_lin=tens_lin, tens_lout=tens_lout ) def _einsum_matmul_index_helper(gate_indices, number_of_qubits): """Return the index string for Numpy.einsum matrix multiplication. The returned indices are to perform a matrix multiplication A.v where the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and M <= N, and identity matrices are implied on the subsystems where A has no support on v. Args: gate_indices (list[int]): the indices of the right matrix subsystems to contract with the left matrix. number_of_qubits (int): the total number of qubits for the right matrix. Returns: tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for that may be combined into a Numpy.einsum function string. Raises: QiskitError: if the total number of qubits plus the number of contracted indices is greater than 26. """ # Since we use ASCII alphabet for einsum index labels we are limited # to 26 total free left (lowercase) and 26 right (uppercase) indexes. # The rank of the contracted tensor reduces this as we need to use that # many characters for the contracted indices if len(gate_indices) + number_of_qubits > 26: raise QiskitError("Total number of free indexes limited to 26") # Indices for N-qubit input tensor tens_in = ascii_lowercase[:number_of_qubits] # Indices for the N-qubit output tensor tens_out = list(tens_in) # Left and right indices for the M-qubit multiplying tensor mat_left = "" mat_right = "" # Update left indices for mat and output for pos, idx in enumerate(reversed(gate_indices)): mat_left += ascii_lowercase[-1 - pos] mat_right += tens_in[-1 - idx] tens_out[-1 - idx] = ascii_lowercase[-1 - pos] tens_out = "".join(tens_out) # Combine indices into matrix multiplication string format # for numpy.einsum function return mat_left, mat_right, tens_in, tens_out
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
import sys import os current_dir = os.getcwd() sys.path.append(current_dir) from quantum_circuit import QuantumCircuit # import qiskit.providers.fake_provider from qiskit.transpiler import CouplingMap import qiskit_ibm_runtime.fake_provider from Backend.backend import Backend class FakeBackend(Backend): def __init__(self, backend_name : str) -> None: self.backend = FakeBackend.get_ibm_fake_backend(backend_name=backend_name) @staticmethod def get_ibm_fake_backend_name_list() -> list[str]: ibm_dir = dir(qiskit_ibm_runtime.fake_provider) return [val for val in ibm_dir if '__' not in val and 'Fake' in val] @staticmethod def get_ibm_fake_backend(backend_name : str): try: return getattr(qiskit_ibm_runtime.fake_provider, backend_name)() except: pass fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list() for backend in fake_backend_name: backend = FakeBackend.get_ibm_fake_backend(backend) if backend is not None: try: if backend.name == backend_name: return backend except: pass return None @staticmethod def get_ibm_fake_backend_names_with_limit(min_qubit : int = 1, max_qubit: int = float('inf')) -> list[str]: limited_backend = [] fake_backend_name = FakeBackend.get_ibm_fake_backend_name_list() for backend in fake_backend_name: backend = FakeBackend.get_ibm_fake_backend(backend) if backend is not None: try: num_qubit = backend.num_qubits if num_qubit >= min_qubit and num_qubit <= max_qubit: limited_backend.append(backend.name) except: pass return limited_backend if __name__ == "__main__": print(FakeBackend.get_ibm_fake_backend_name_list()) backend = FakeBackend('fake_auckland') qc = QuantumCircuit(2) qc.x(0) qc.h(1) qc.measure_all() print(qc.draw()) job = backend.run(qc) print(job.result()) qc_transpile = backend.traspile_qiskit(qc)[0] print(qc_transpile.draw()) job = backend.run(qc_transpile) print(job.result())
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# 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. """Provider for a single IBM Quantum Experience account.""" import logging from typing import Dict, List, Optional, Any, Callable, Union from collections import OrderedDict import traceback import copy from qiskit.providers import ProviderV1 as Provider # type: ignore[attr-defined] from qiskit.providers.models import (QasmBackendConfiguration, PulseBackendConfiguration) from qiskit.circuit import QuantumCircuit from qiskit.transpiler import Layout from qiskit.providers.ibmq.runtime import runtime_job # pylint: disable=unused-import from qiskit.providers.ibmq import ibmqfactory # pylint: disable=unused-import from .api.clients import AccountClient from .ibmqbackend import IBMQBackend, IBMQSimulator from .credentials import Credentials from .ibmqbackendservice import IBMQBackendService, IBMQDeprecatedBackendService from .utils.json_decoder import decode_backend_configuration from .experiment import IBMExperimentService from .runtime.ibm_runtime_service import IBMRuntimeService from .exceptions import IBMQNotAuthorizedError, IBMQInputValueError from .runner_result import RunnerResult logger = logging.getLogger(__name__) class AccountProvider(Provider): """Provider for a single IBM Quantum Experience account. The account provider class provides access to the IBM Quantum Experience services available to this account. You can access a provider by enabling an account with the :meth:`IBMQ.enable_account()<IBMQFactory.enable_account>` method, which returns the default provider you have access to:: from qiskit import IBMQ provider = IBMQ.enable_account(<INSERT_IBM_QUANTUM_EXPERIENCE_TOKEN>) To select a different provider, use the :meth:`IBMQ.get_provider()<IBMQFactory.get_provider>` method and specify the hub, group, or project name of the desired provider. Each provider may offer different services. The main service, :class:`~qiskit.providers.ibmq.ibmqbackendservice.IBMQBackendService`, is available to all providers and gives access to IBM Quantum Experience devices and simulators. You can obtain an instance of a service using the :meth:`service()` method or as an attribute of this ``AccountProvider`` instance. For example:: backend_service = provider.service('backend') backend_service = provider.service.backend Since :class:`~qiskit.providers.ibmq.ibmqbackendservice.IBMQBackendService` is the main service, some of the backend-related methods are available through this class for convenience. The :meth:`backends()` method returns all the backends available to this account:: backends = provider.backends() The :meth:`get_backend()` method returns a backend that matches the filters passed as argument. An example of retrieving a backend that matches a specified name:: simulator_backend = provider.get_backend('ibmq_qasm_simulator') It is also possible to use the ``backend`` attribute to reference a backend. As an example, to retrieve the same backend from the example above:: simulator_backend = provider.backend.ibmq_qasm_simulator Note: The ``backend`` attribute can be used to autocomplete the names of backends available to this provider. To autocomplete, press ``tab`` after ``provider.backend.``. This feature may not be available if an error occurs during backend discovery. Also note that this feature is only available in interactive sessions, such as in Jupyter Notebook and the Python interpreter. """ def __init__(self, credentials: Credentials, factory: 'ibmqfactory.IBMQFactory') -> None: """AccountProvider constructor. Args: credentials: IBM Quantum Experience credentials. factory: IBM Quantum account. """ super().__init__() self.credentials = credentials self._factory = factory self._api_client = AccountClient(credentials, **credentials.connection_parameters()) # Initialize the internal list of backends. self.__backends: Dict[str, IBMQBackend] = {} self._backend = IBMQBackendService(self) self.backends = IBMQDeprecatedBackendService(self.backend) # type: ignore[assignment] # Initialize other services. self._experiment = IBMExperimentService(self) if credentials.experiment_url else None self._runtime = IBMRuntimeService(self) \ if credentials.runtime_url else None self._services = {'backend': self._backend, 'experiment': self._experiment, 'runtime': self._runtime} @property def _backends(self) -> Dict[str, IBMQBackend]: """Gets the backends for the provider, if not loaded. Returns: Dict[str, IBMQBackend]: the backends """ if not self.__backends: self.__backends = self._discover_remote_backends() return self.__backends @_backends.setter def _backends(self, value: Dict[str, IBMQBackend]) -> None: """Sets the value for the account's backends. Args: value: the backends """ self.__backends = value def backends( self, name: Optional[str] = None, filters: Optional[Callable[[List[IBMQBackend]], bool]] = None, **kwargs: Any ) -> List[IBMQBackend]: """Return all backends accessible via this provider, subject to optional filtering. Args: name: Backend name to filter by. filters: More complex filters, such as lambda functions. For example:: AccountProvider.backends(filters=lambda b: b.configuration().n_qubits > 5) kwargs: Simple filters that specify a ``True``/``False`` criteria in the backend configuration, backends status, or provider credentials. An example to get the operational backends with 5 qubits:: AccountProvider.backends(n_qubits=5, operational=True) Returns: The list of available backends that match the filter. """ # pylint: disable=method-hidden # pylint: disable=arguments-differ # This method is only for faking the subclassing of `BaseProvider`, as # `.backends()` is an abstract method. Upon initialization, it is # replaced by a `IBMQBackendService` instance. pass def _discover_remote_backends(self, timeout: Optional[float] = None) -> Dict[str, IBMQBackend]: """Return the remote backends available for this provider. Args: timeout: Maximum number of seconds to wait for the discovery of remote backends. Returns: A dict of the remote backend instances, keyed by backend name. """ ret = OrderedDict() # type: ignore[var-annotated] configs_list = self._api_client.list_backends(timeout=timeout) for raw_config in configs_list: # Make sure the raw_config is of proper type if not isinstance(raw_config, dict): logger.warning("An error occurred when retrieving backend " "information. Some backends might not be available.") continue try: decode_backend_configuration(raw_config) try: config = PulseBackendConfiguration.from_dict(raw_config) except (KeyError, TypeError): config = QasmBackendConfiguration.from_dict(raw_config) backend_cls = IBMQSimulator if config.simulator else IBMQBackend ret[config.backend_name] = backend_cls( configuration=config, provider=self, credentials=self.credentials, api_client=self._api_client) except Exception: # pylint: disable=broad-except logger.warning( 'Remote backend "%s" for provider %s could not be instantiated due to an ' 'invalid config: %s', raw_config.get('backend_name', raw_config.get('name', 'unknown')), repr(self), traceback.format_exc()) return ret def run_circuits( self, circuits: Union[QuantumCircuit, List[QuantumCircuit]], backend_name: str, shots: Optional[int] = None, initial_layout: Optional[Union[Layout, Dict, List]] = None, layout_method: Optional[str] = None, routing_method: Optional[str] = None, translation_method: Optional[str] = None, seed_transpiler: Optional[int] = None, optimization_level: int = 1, init_qubits: bool = True, rep_delay: Optional[float] = None, transpiler_options: Optional[dict] = None, measurement_error_mitigation: bool = False, use_measure_esp: Optional[bool] = None, **run_config: Dict ) -> 'runtime_job.RuntimeJob': """Execute the input circuit(s) on a backend using the runtime service. Note: This method uses the IBM Quantum runtime service which is not available to all accounts. Args: circuits: Circuit(s) to execute. backend_name: Name of the backend to execute circuits on. Transpiler options are automatically grabbed from backend configuration and properties unless otherwise specified. shots: Number of repetitions of each circuit, for sampling. If not specified, the backend default is used. initial_layout: Initial position of virtual qubits on physical qubits. layout_method: Name of layout selection pass ('trivial', 'dense', 'noise_adaptive', 'sabre'). Sometimes a perfect layout can be available in which case the layout_method may not run. routing_method: Name of routing pass ('basic', 'lookahead', 'stochastic', 'sabre') translation_method: Name of translation pass ('unroller', 'translator', 'synthesis') seed_transpiler: Sets random seed for the stochastic parts of the transpiler. optimization_level: How much optimization to perform on the circuits. Higher levels generate more optimized circuits, at the expense of longer transpilation time. If None, level 1 will be chosen as default. init_qubits: Whether to reset the qubits to the ground state for each shot. rep_delay: Delay between programs in seconds. Only supported on certain backends (``backend.configuration().dynamic_reprate_enabled`` ). If supported, ``rep_delay`` will be used instead of ``rep_time`` and must be from the range supplied by the backend (``backend.configuration().rep_delay_range``). Default is given by ``backend.configuration().default_rep_delay``. transpiler_options: Additional transpiler options. measurement_error_mitigation: Whether to apply measurement error mitigation. use_measure_esp: Whether to use excited state promoted (ESP) readout for measurements which are the final instruction on a qubit. ESP readout can offer higher fidelity than standard measurement sequences. See `here <https://arxiv.org/pdf/2008.08571.pdf>`_. **run_config: Extra arguments used to configure the circuit execution. Returns: Runtime job. """ inputs = copy.deepcopy(run_config) # type: Dict[str, Any] inputs['circuits'] = circuits inputs['optimization_level'] = optimization_level inputs['init_qubits'] = init_qubits inputs['measurement_error_mitigation'] = measurement_error_mitigation if shots: inputs['shots'] = shots if initial_layout: inputs['initial_layout'] = initial_layout if layout_method: inputs['layout_method'] = layout_method if routing_method: inputs['routing_method'] = routing_method if translation_method: inputs['translation_method'] = translation_method if seed_transpiler: inputs['seed_transpiler'] = seed_transpiler if rep_delay: inputs['rep_delay'] = rep_delay if transpiler_options: inputs['transpiler_options'] = transpiler_options if use_measure_esp is not None: inputs['use_measure_esp'] = use_measure_esp options = {'backend_name': backend_name} return self.runtime.run('circuit-runner', options=options, inputs=inputs, result_decoder=RunnerResult) def service(self, name: str) -> Any: """Return the specified service. Args: name: Name of the service. Returns: The specified service. Raises: IBMQInputValueError: If an unknown service name is specified. IBMQNotAuthorizedError: If the account is not authorized to use the service. """ if name not in self._services: raise IBMQInputValueError(f"Unknown service {name} specified.") if self._services[name] is None: raise IBMQNotAuthorizedError("You are not authorized to use this service.") return self._services[name] def services(self) -> Dict: """Return all available services. Returns: All services available to this provider. """ return {key: val for key, val in self._services.items() if val is not None} def has_service(self, name: str) -> bool: """Check if this provider has access to the service. Args: name: Name of the service. Returns: Whether the provider has access to the service. Raises: IBMQInputValueError: If an unknown service name is specified. """ if name not in self._services: raise IBMQInputValueError(f"Unknown service {name} specified.") if self._services[name] is None: return False return True @property def backend(self) -> IBMQBackendService: """Return the backend service. Returns: The backend service instance. """ return self._backend @property def experiment(self) -> IBMExperimentService: """Return the experiment service. Returns: The experiment service instance. Raises: IBMQNotAuthorizedError: If the account is not authorized to use the experiment service. """ if self._experiment: return self._experiment else: raise IBMQNotAuthorizedError("You are not authorized to use the experiment service.") @property def runtime(self) -> IBMRuntimeService: """Return the runtime service. Returns: The runtime service instance. Raises: IBMQNotAuthorizedError: If the account is not authorized to use the service. """ if self._runtime: return self._runtime else: raise IBMQNotAuthorizedError("You are not authorized to use the runtime service.") def __eq__( self, other: Any ) -> bool: if not isinstance(other, AccountProvider): return False return self.credentials == other.credentials def __repr__(self) -> str: credentials_info = "hub='{}', group='{}', project='{}'".format( self.credentials.hub, self.credentials.group, self.credentials.project) return "<{} for IBMQ({})>".format( self.__class__.__name__, credentials_info)
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # 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. """Module for interfacing with an IBM Quantum Experience Backend.""" import logging import warnings import copy from typing import Dict, List, Union, Optional, Any from datetime import datetime as python_datetime from qiskit.compiler import assemble from qiskit.circuit import QuantumCircuit, Parameter, Delay from qiskit.circuit.duration import duration_in_dt from qiskit.pulse import Schedule, LoConfig from qiskit.pulse.channels import PulseChannel from qiskit.qobj import QasmQobj, PulseQobj from qiskit.qobj.utils import MeasLevel, MeasReturnType from qiskit.providers.backend import BackendV1 as Backend from qiskit.providers.options import Options from qiskit.providers.jobstatus import JobStatus from qiskit.providers.models import (BackendStatus, BackendProperties, PulseDefaults, GateConfig) from qiskit.tools.events.pubsub import Publisher from qiskit.providers.models import (QasmBackendConfiguration, PulseBackendConfiguration) from qiskit.utils import deprecate_arguments from qiskit.providers.ibmq import accountprovider # pylint: disable=unused-import from .apiconstants import ApiJobStatus, API_JOB_FINAL_STATES from .api.clients import AccountClient from .api.exceptions import ApiError from .backendjoblimit import BackendJobLimit from .backendreservation import BackendReservation from .credentials import Credentials from .exceptions import (IBMQBackendError, IBMQBackendValueError, IBMQBackendApiError, IBMQBackendApiProtocolError, IBMQBackendJobLimitError) from .job import IBMQJob from .utils import validate_job_tags from .utils.converters import utc_to_local_all, local_to_utc from .utils.json_decoder import decode_pulse_defaults, decode_backend_properties from .utils.backend import convert_reservation_data from .utils.utils import api_status_to_job_status logger = logging.getLogger(__name__) class IBMQBackend(Backend): """Backend class interfacing with an IBM Quantum Experience device. You can run experiments on a backend using the :meth:`run()` method. The :meth:`run()` method takes one or more :class:`~qiskit.circuit.QuantumCircuit` or :class:`~qiskit.pulse.Schedule` and returns an :class:`~qiskit.providers.ibmq.job.IBMQJob` instance that represents the submitted job. Each job has a unique job ID, which can later be used to retrieve the job. An example of this flow:: from qiskit import IBMQ, assemble, transpile from qiskit.circuit.random import random_circuit provider = IBMQ.load_account() backend = provider.backend.ibmq_vigo qx = random_circuit(n_qubits=5, depth=4) transpiled = transpile(qx, backend=backend) job = backend.run(transpiled) retrieved_job = backend.retrieve_job(job.job_id()) Note: * Unlike :meth:`qiskit.execute`, the :meth:`run` method does not transpile the circuits/schedules for you, so be sure to do so before submitting them. * You should not instantiate the ``IBMQBackend`` class directly. Instead, use the methods provided by an :class:`AccountProvider` instance to retrieve and handle backends. Other methods return information about the backend. For example, the :meth:`status()` method returns a :class:`BackendStatus<qiskit.providers.models.BackendStatus>` instance. The instance contains the ``operational`` and ``pending_jobs`` attributes, which state whether the backend is operational and also the number of jobs in the server queue for the backend, respectively:: status = backend.status() is_operational = status.operational jobs_in_queue = status.pending_jobs It is also possible to see the number of remaining jobs you are able to submit to the backend with the :meth:`job_limit()` method, which returns a :class:`BackendJobLimit<qiskit.providers.ibmq.BackendJobLimit>` instance:: job_limit = backend.job_limit() """ qobj_warning_issued = False id_warning_issued = False def __init__( self, configuration: Union[QasmBackendConfiguration, PulseBackendConfiguration], provider: 'accountprovider.AccountProvider', credentials: Credentials, api_client: AccountClient ) -> None: """IBMQBackend constructor. Args: configuration: Backend configuration. provider: IBM Quantum Experience account provider credentials: IBM Quantum Experience credentials. api_client: IBM Quantum Experience client used to communicate with the server. """ super().__init__(provider=provider, configuration=configuration) self._api_client = api_client self._credentials = credentials self.hub = credentials.hub self.group = credentials.group self.project = credentials.project # Attributes used by caching functions. self._properties = None self._defaults = None @classmethod def _default_options(cls) -> Options: """Default runtime options.""" return Options(shots=4000, memory=False, qubit_lo_freq=None, meas_lo_freq=None, schedule_los=None, meas_level=MeasLevel.CLASSIFIED, meas_return=MeasReturnType.AVERAGE, memory_slots=None, memory_slot_size=100, rep_time=None, rep_delay=None, init_qubits=True, use_measure_esp=None, live_data_enabled=None) @deprecate_arguments({'qobj': 'circuits'}) def run( self, circuits: Union[QasmQobj, PulseQobj, QuantumCircuit, Schedule, List[Union[QuantumCircuit, Schedule]]], job_name: Optional[str] = None, job_share_level: Optional[str] = None, job_tags: Optional[List[str]] = None, experiment_id: Optional[str] = None, header: Optional[Dict] = None, shots: Optional[int] = None, memory: Optional[bool] = None, qubit_lo_freq: Optional[List[int]] = None, meas_lo_freq: Optional[List[int]] = None, schedule_los: Optional[Union[List[Union[Dict[PulseChannel, float], LoConfig]], Union[Dict[PulseChannel, float], LoConfig]]] = None, meas_level: Optional[Union[int, MeasLevel]] = None, meas_return: Optional[Union[str, MeasReturnType]] = None, memory_slots: Optional[int] = None, memory_slot_size: Optional[int] = None, rep_time: Optional[int] = None, rep_delay: Optional[float] = None, init_qubits: Optional[bool] = None, parameter_binds: Optional[List[Dict[Parameter, float]]] = None, use_measure_esp: Optional[bool] = None, live_data_enabled: Optional[bool] = None, **run_config: Dict ) -> IBMQJob: """Run on the backend. If a keyword specified here is also present in the ``options`` attribute/object, the value specified here will be used for this run. Args: circuits: An individual or a list of :class:`~qiskit.circuits.QuantumCircuit` or :class:`~qiskit.pulse.Schedule` objects to run on the backend. A :class:`~qiskit.qobj.QasmQobj` or a :class:`~qiskit.qobj.PulseQobj` object is also supported but is deprecated. job_name: Custom name to be assigned to the job. This job name can subsequently be used as a filter in the :meth:`jobs()` method. Job names do not need to be unique. job_share_level: Allows sharing a job at the hub, group, project, or global level. The possible job share levels are: ``global``, ``hub``, ``group``, ``project``, and ``none``. * global: The job is public to any user. * hub: The job is shared between the users in the same hub. * group: The job is shared between the users in the same group. * project: The job is shared between the users in the same project. * none: The job is not shared at any level. If the job share level is not specified, the job is not shared at any level. job_tags: Tags to be assigned to the job. The tags can subsequently be used as a filter in the :meth:`jobs()` function call. experiment_id: Used to add a job to an "experiment", which is a collection of jobs and additional metadata. The following arguments are NOT applicable if a Qobj is passed in. header: User input that will be attached to the job and will be copied to the corresponding result header. Headers do not affect the run. This replaces the old ``Qobj`` header. shots: Number of repetitions of each circuit, for sampling. Default: 4000 or ``max_shots`` from the backend configuration, whichever is smaller. memory: If ``True``, per-shot measurement bitstrings are returned as well (provided the backend supports it). For OpenPulse jobs, only measurement level 2 supports this option. qubit_lo_freq: List of default qubit LO frequencies in Hz. Will be overridden by ``schedule_los`` if set. meas_lo_freq: List of default measurement LO frequencies in Hz. Will be overridden by ``schedule_los`` if set. schedule_los: Experiment LO configurations, frequencies are given in Hz. meas_level: Set the appropriate level of the measurement output for pulse experiments. meas_return: Level of measurement data for the backend to return. For ``meas_level`` 0 and 1: * ``single`` returns information from every shot. * ``avg`` returns average measurement output (averaged over number of shots). memory_slots: Number of classical memory slots to use. memory_slot_size: Size of each memory slot if the output is Level 0. rep_time: Time per program execution in seconds. Must be from the list provided by the backend (``backend.configuration().rep_times``). Defaults to the first entry. rep_delay: Delay between programs in seconds. Only supported on certain backends (if ``backend.configuration().dynamic_reprate_enabled=True``). If supported, ``rep_delay`` will be used instead of ``rep_time`` and must be from the range supplied by the backend (``backend.configuration().rep_delay_range``). Default is given by ``backend.configuration().default_rep_delay``. init_qubits: Whether to reset the qubits to the ground state for each shot. Default: ``True``. parameter_binds: List of Parameter bindings over which the set of experiments will be executed. Each list element (bind) should be of the form {Parameter1: value1, Parameter2: value2, ...}. All binds will be executed across all experiments; e.g., if parameter_binds is a length-n list, and there are m experiments, a total of m x n experiments will be run (one for each experiment/bind pair). use_measure_esp: Whether to use excited state promoted (ESP) readout for measurements which are the terminal instruction to a qubit. ESP readout can offer higher fidelity than standard measurement sequences. See `here <https://arxiv.org/pdf/2008.08571.pdf>`_. Default: ``True`` if backend supports ESP readout, else ``False``. Backend support for ESP readout is determined by the flag ``measure_esp_enabled`` in ``backend.configuration()``. live_data_enabled (bool): Activate the live data in the backend, to receive data from the instruments. **run_config: Extra arguments used to configure the run. Returns: The job to be executed. Raises: IBMQBackendApiError: If an unexpected error occurred while submitting the job. IBMQBackendApiProtocolError: If an unexpected value received from the server. IBMQBackendValueError: - If an input parameter value is not valid. - If ESP readout is used and the backend does not support this. """ # pylint: disable=arguments-differ if job_share_level: warnings.warn("The `job_share_level` keyword is no longer supported " "and will be removed in a future release.", Warning, stacklevel=3) validate_job_tags(job_tags, IBMQBackendValueError) sim_method = None if self.configuration().simulator: sim_method = getattr(self.configuration(), 'simulation_method', None) measure_esp_enabled = getattr(self.configuration(), "measure_esp_enabled", False) # set ``use_measure_esp`` to backend value if not set by user if use_measure_esp is None: use_measure_esp = measure_esp_enabled if use_measure_esp and not measure_esp_enabled: raise IBMQBackendValueError( "ESP readout not supported on this device. Please make sure the flag " "'use_measure_esp' is unset or set to 'False'." ) if not self.configuration().simulator: self._deprecate_id_instruction(circuits) if isinstance(circuits, (QasmQobj, PulseQobj)): if not self.qobj_warning_issued: warnings.warn("Passing a Qobj to Backend.run is deprecated and will " "be removed in a future release. Please pass in circuits " "or pulse schedules instead.", DeprecationWarning, stacklevel=3) # need level 3 because of decorator self.qobj_warning_issued = True qobj = circuits if sim_method and not hasattr(qobj.config, 'method'): qobj.config.method = sim_method else: qobj_header = run_config.pop('qobj_header', None) header = header or qobj_header run_config_dict = self._get_run_config( qobj_header=header, shots=shots, memory=memory, qubit_lo_freq=qubit_lo_freq, meas_lo_freq=meas_lo_freq, schedule_los=schedule_los, meas_level=meas_level, meas_return=meas_return, memory_slots=memory_slots, memory_slot_size=memory_slot_size, rep_time=rep_time, rep_delay=rep_delay, init_qubits=init_qubits, use_measure_esp=use_measure_esp, **run_config) if parameter_binds: run_config_dict['parameter_binds'] = parameter_binds if sim_method and 'method' not in run_config_dict: run_config_dict['method'] = sim_method qobj = assemble(circuits, self, **run_config_dict) return self._submit_job(qobj, job_name, job_tags, experiment_id, live_data_enabled) def _get_run_config(self, **kwargs: Any) -> Dict: """Return the consolidated runtime configuration.""" run_config_dict = copy.copy(self.options.__dict__) for key, val in kwargs.items(): if val is not None: run_config_dict[key] = val if key not in self.options.__dict__ and not isinstance(self, IBMQSimulator): warnings.warn(f"{key} is not a recognized runtime" # type: ignore[unreachable] f" option and may be ignored by the backend.", stacklevel=4) return run_config_dict def _submit_job( self, qobj: Union[QasmQobj, PulseQobj], job_name: Optional[str] = None, job_tags: Optional[List[str]] = None, experiment_id: Optional[str] = None, live_data_enabled: Optional[bool] = None ) -> IBMQJob: """Submit the Qobj to the backend. Args: qobj: The Qobj to be executed. job_name: Custom name to be assigned to the job. This job name can subsequently be used as a filter in the ``jobs()``method. Job names do not need to be unique. job_tags: Tags to be assigned to the job. experiment_id: Used to add a job to an experiment. live_data_enabled: Used to activate/deactivate live data on the backend. Returns: The job to be executed. Events: ibmq.job.start: The job has started. Raises: IBMQBackendApiError: If an unexpected error occurred while submitting the job. IBMQBackendError: If an unexpected error occurred after submitting the job. IBMQBackendApiProtocolError: If an unexpected value is received from the server. IBMQBackendJobLimitError: If the job could not be submitted because the job limit has been reached. """ try: qobj_dict = qobj.to_dict() submit_info = self._api_client.job_submit( backend_name=self.name(), qobj_dict=qobj_dict, job_name=job_name, job_tags=job_tags, experiment_id=experiment_id, live_data_enabled=live_data_enabled) except ApiError as ex: if 'Error code: 3458' in str(ex): raise IBMQBackendJobLimitError('Error submitting job: {}'.format(str(ex))) from ex raise IBMQBackendApiError('Error submitting job: {}'.format(str(ex))) from ex # Error in the job after submission: # Transition to the `ERROR` final state. if 'error' in submit_info: raise IBMQBackendError( 'Error submitting job: {}'.format(str(submit_info['error']))) # Submission success. try: job = IBMQJob(backend=self, api_client=self._api_client, qobj=qobj, **submit_info) logger.debug('Job %s was successfully submitted.', job.job_id()) except TypeError as err: logger.debug("Invalid job data received: %s", submit_info) raise IBMQBackendApiProtocolError('Unexpected return value received from the server ' 'when submitting job: {}'.format(str(err))) from err Publisher().publish("ibmq.job.start", job) return job def properties( self, refresh: bool = False, datetime: Optional[python_datetime] = None ) -> Optional[BackendProperties]: """Return the backend properties, subject to optional filtering. This data describes qubits properties (such as T1 and T2), gates properties (such as gate length and error), and other general properties of the backend. The schema for backend properties can be found in `Qiskit/ibm-quantum-schemas <https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/backend_properties_schema.json>`_. Args: refresh: If ``True``, re-query the server for the backend properties. Otherwise, return a cached version. datetime: By specifying `datetime`, this function returns an instance of the :class:`BackendProperties<qiskit.providers.models.BackendProperties>` whose timestamp is closest to, but older than, the specified `datetime`. Returns: The backend properties or ``None`` if the backend properties are not currently available. Raises: TypeError: If an input argument is not of the correct type. """ # pylint: disable=arguments-differ if not isinstance(refresh, bool): raise TypeError("The 'refresh' argument needs to be a boolean. " "{} is of type {}".format(refresh, type(refresh))) if datetime and not isinstance(datetime, python_datetime): raise TypeError("'{}' is not of type 'datetime'.") if datetime: datetime = local_to_utc(datetime) if datetime or refresh or self._properties is None: api_properties = self._api_client.backend_properties(self.name(), datetime=datetime) if not api_properties: return None decode_backend_properties(api_properties) api_properties = utc_to_local_all(api_properties) backend_properties = BackendProperties.from_dict(api_properties) if datetime: # Don't cache result. return backend_properties self._properties = backend_properties return self._properties def status(self) -> BackendStatus: """Return the backend status. Note: If the returned :class:`~qiskit.providers.models.BackendStatus` instance has ``operational=True`` but ``status_msg="internal"``, then the backend is accepting jobs but not processing them. Returns: The status of the backend. Raises: IBMQBackendApiProtocolError: If the status for the backend cannot be formatted properly. """ api_status = self._api_client.backend_status(self.name()) try: return BackendStatus.from_dict(api_status) except TypeError as ex: raise IBMQBackendApiProtocolError( 'Unexpected return value received from the server when ' 'getting backend status: {}'.format(str(ex))) from ex def defaults(self, refresh: bool = False) -> Optional[PulseDefaults]: """Return the pulse defaults for the backend. The schema for default pulse configuration can be found in `Qiskit/ibm-quantum-schemas <https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/default_pulse_configuration_schema.json>`_. Args: refresh: If ``True``, re-query the server for the backend pulse defaults. Otherwise, return a cached version. Returns: The backend pulse defaults or ``None`` if the backend does not support pulse. """ if refresh or self._defaults is None: api_defaults = self._api_client.backend_pulse_defaults(self.name()) if api_defaults: decode_pulse_defaults(api_defaults) self._defaults = PulseDefaults.from_dict(api_defaults) else: self._defaults = None return self._defaults def job_limit(self) -> BackendJobLimit: """Return the job limit for the backend. The job limit information includes the current number of active jobs you have on the backend and the maximum number of active jobs you can have on it. Note: Job limit information for a backend is provider specific. For example, if you have access to the same backend via different providers, the job limit information might be different for each provider. If the method call was successful, you can inspect the job limit for the backend by accessing the ``maximum_jobs`` and ``active_jobs`` attributes of the :class:`BackendJobLimit<BackendJobLimit>` instance returned. For example:: backend_job_limit = backend.job_limit() maximum_jobs = backend_job_limit.maximum_jobs active_jobs = backend_job_limit.active_jobs If ``maximum_jobs`` is equal to ``None``, then there is no limit to the maximum number of active jobs you could have on the backend. Returns: The job limit for the backend, with this provider. Raises: IBMQBackendApiProtocolError: If an unexpected value is received from the server. """ api_job_limit = self._api_client.backend_job_limit(self.name()) try: job_limit = BackendJobLimit(**api_job_limit) if job_limit.maximum_jobs == -1: # Manually set `maximum` to `None` if backend has no job limit. job_limit.maximum_jobs = None return job_limit except TypeError as ex: raise IBMQBackendApiProtocolError( 'Unexpected return value received from the server when ' 'querying job limit data for the backend: {}.'.format(ex)) from ex def remaining_jobs_count(self) -> Optional[int]: """Return the number of remaining jobs that could be submitted to the backend. Note: The number of remaining jobs for a backend is provider specific. For example, if you have access to the same backend via different providers, the number of remaining jobs might be different for each. See :class:`BackendJobLimit<BackendJobLimit>` for the job limit information of a backend. If ``None`` is returned, there are no limits to the maximum number of active jobs you could have on the backend. Returns: The remaining number of jobs a user could submit to the backend, with this provider, before the maximum limit on active jobs is reached. Raises: IBMQBackendApiProtocolError: If an unexpected value is received from the server. """ job_limit = self.job_limit() if job_limit.maximum_jobs is None: return None return job_limit.maximum_jobs - job_limit.active_jobs def jobs( self, limit: int = 10, skip: int = 0, status: Optional[Union[JobStatus, str, List[Union[JobStatus, str]]]] = None, job_name: Optional[str] = None, start_datetime: Optional[python_datetime] = None, end_datetime: Optional[python_datetime] = None, job_tags: Optional[List[str]] = None, job_tags_operator: Optional[str] = "OR", experiment_id: Optional[str] = None, descending: bool = True, db_filter: Optional[Dict[str, Any]] = None ) -> List[IBMQJob]: """Return the jobs submitted to this backend, subject to optional filtering. Retrieve jobs submitted to this backend that match the given filters and paginate the results if desired. Note that the server has a limit for the number of jobs returned in a single call. As a result, this function might involve making several calls to the server. See also the `skip` parameter for more control over pagination. Args: limit: Number of jobs to retrieve. skip: Starting index for the job retrieval. status: Only get jobs with this status or one of the statuses. For example, you can specify `status=JobStatus.RUNNING` or `status="RUNNING"` or `status=["RUNNING", "ERROR"]` job_name: Filter by job name. The `job_name` is matched partially and `regular expressions <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions>`_ can be used. start_datetime: Filter by the given start date, in local time. This is used to find jobs whose creation dates are after (greater than or equal to) this local date/time. end_datetime: Filter by the given end date, in local time. This is used to find jobs whose creation dates are before (less than or equal to) this local date/time. job_tags: Filter by tags assigned to jobs. job_tags_operator: Logical operator to use when filtering by job tags. Valid values are "AND" and "OR": * If "AND" is specified, then a job must have all of the tags specified in ``job_tags`` to be included. * If "OR" is specified, then a job only needs to have any of the tags specified in ``job_tags`` to be included. experiment_id: Filter by job experiment ID. descending: If ``True``, return the jobs in descending order of the job creation date (newest first). If ``False``, return in ascending order. db_filter: A `loopback-based filter <https://loopback.io/doc/en/lb2/Querying-data.html>`_. This is an interface to a database ``where`` filter. Some examples of its usage are: Filter last five jobs with errors:: job_list = backend.jobs(limit=5, status=JobStatus.ERROR) Filter last five jobs with hub name ``ibm-q``:: filter = {'hubInfo.hub.name': 'ibm-q'} job_list = backend.jobs(limit=5, db_filter=filter) Returns: A list of jobs that match the criteria. Raises: IBMQBackendValueError: If a keyword value is not recognized. """ return self._provider.backend.jobs( limit=limit, skip=skip, backend_name=self.name(), status=status, job_name=job_name, start_datetime=start_datetime, end_datetime=end_datetime, job_tags=job_tags, job_tags_operator=job_tags_operator, experiment_id=experiment_id, descending=descending, db_filter=db_filter) def active_jobs(self, limit: int = 10) -> List[IBMQJob]: """Return the unfinished jobs submitted to this backend. Return the jobs submitted to this backend, with this provider, that are currently in an unfinished job status state. The unfinished :class:`JobStatus<qiskit.providers.jobstatus.JobStatus>` states include: ``INITIALIZING``, ``VALIDATING``, ``QUEUED``, and ``RUNNING``. Args: limit: Number of jobs to retrieve. Returns: A list of the unfinished jobs for this backend on this provider. """ # Get the list of api job statuses which are not a final api job status. active_job_states = list({api_status_to_job_status(status) for status in ApiJobStatus if status not in API_JOB_FINAL_STATES}) return self.jobs(status=active_job_states, limit=limit) def retrieve_job(self, job_id: str) -> IBMQJob: """Return a single job submitted to this backend. Args: job_id: The ID of the job to retrieve. Returns: The job with the given ID. Raises: IBMQBackendError: If job retrieval failed. """ job = self._provider.backend.retrieve_job(job_id) job_backend = job.backend() if self.name() != job_backend.name(): warnings.warn('Job {} belongs to another backend than the one queried. ' 'The query was made on backend {}, ' 'but the job actually belongs to backend {}.' .format(job_id, self.name(), job_backend.name())) raise IBMQBackendError('Failed to get job {}: ' 'job does not belong to backend {}.' .format(job_id, self.name())) return job def reservations( self, start_datetime: Optional[python_datetime] = None, end_datetime: Optional[python_datetime] = None ) -> List[BackendReservation]: """Return backend reservations. If start_datetime and/or end_datetime is specified, reservations with time slots that overlap with the specified time window will be returned. Some of the reservation information is only available if you are the owner of the reservation. Args: start_datetime: Filter by the given start date/time, in local timezone. end_datetime: Filter by the given end date/time, in local timezone. Returns: A list of reservations that match the criteria. """ start_datetime = local_to_utc(start_datetime) if start_datetime else None end_datetime = local_to_utc(end_datetime) if end_datetime else None raw_response = self._api_client.backend_reservations( self.name(), start_datetime, end_datetime) return convert_reservation_data(raw_response, self.name()) def configuration(self) -> Union[QasmBackendConfiguration, PulseBackendConfiguration]: """Return the backend configuration. Backend configuration contains fixed information about the backend, such as its name, number of qubits, basis gates, coupling map, quantum volume, etc. The schema for backend configuration can be found in `Qiskit/ibm-quantum-schemas <https://github.com/Qiskit/ibm-quantum-schemas/blob/main/schemas/backend_configuration_schema.json>`_. Returns: The configuration for the backend. """ return self._configuration def __repr__(self) -> str: credentials_info = '' if self.hub: credentials_info = "hub='{}', group='{}', project='{}'".format( self.hub, self.group, self.project) return "<{}('{}') from IBMQ({})>".format( self.__class__.__name__, self.name(), credentials_info) def _deprecate_id_instruction( self, circuits: Union[QasmQobj, PulseQobj, QuantumCircuit, Schedule, List[Union[QuantumCircuit, Schedule]]] ) -> None: """Raise a DeprecationWarning if any circuit contains an 'id' instruction. Additionally, if 'delay' is a 'supported_instruction', replace each 'id' instruction (in-place) with the equivalent ('sx'-length) 'delay' instruction. Args: circuits: The individual or list of :class:`~qiskit.circuits.QuantumCircuit` or :class:`~qiskit.pulse.Schedule` objects passed to :meth:`IBMQBackend.run()<IBMQBackend.run>`. Modified in-place. Returns: None """ if isinstance(circuits, PulseQobj): return id_support = 'id' in getattr(self.configuration(), 'basis_gates', []) delay_support = 'delay' in getattr(self.configuration(), 'supported_instructions', []) if not delay_support: return if isinstance(circuits, QasmQobj): circuit_has_id = any(instr.name == 'id' for experiment in circuits.experiments for instr in experiment.instructions) else: if not isinstance(circuits, List): circuits = [circuits] circuit_has_id = any(instr.name == 'id' for circuit in circuits if isinstance(circuit, QuantumCircuit) for instr, qargs, cargs in circuit.data) if not circuit_has_id: return if not self.id_warning_issued: if id_support and delay_support: warnings.warn("Support for the 'id' instruction has been deprecated " "from IBM hardware backends. Any 'id' instructions " "will be replaced with their equivalent 'delay' instruction. " "Please use the 'delay' instruction instead.", DeprecationWarning, stacklevel=4) else: warnings.warn("Support for the 'id' instruction has been removed " "from IBM hardware backends. Any 'id' instructions " "will be replaced with their equivalent 'delay' instruction. " "Please use the 'delay' instruction instead.", DeprecationWarning, stacklevel=4) self.id_warning_issued = True dt_in_s = self.configuration().dt if isinstance(circuits, QasmQobj): for experiment in circuits.experiments: for instr in experiment.instructions: if instr.name == 'id': sx_duration = self.properties().gate_length('sx', instr.qubits[0]) sx_duration_in_dt = duration_in_dt(sx_duration, dt_in_s) instr.name = 'delay' instr.params = [sx_duration_in_dt] else: for circuit in circuits: if isinstance(circuit, Schedule): continue for idx, (instr, qargs, cargs) in enumerate(circuit.data): if instr.name == 'id': sx_duration = self.properties().gate_length('sx', qargs[0].index) sx_duration_in_dt = duration_in_dt(sx_duration, dt_in_s) delay_instr = Delay(sx_duration_in_dt) circuit.data[idx] = (delay_instr, qargs, cargs) class IBMQSimulator(IBMQBackend): """Backend class interfacing with an IBM Quantum Experience simulator.""" @classmethod def _default_options(cls) -> Options: """Default runtime options.""" options = super()._default_options() options.update_options(noise_model=None, seed_simulator=None) return options def properties( self, refresh: bool = False, datetime: Optional[python_datetime] = None ) -> None: """Return ``None``, simulators do not have backend properties.""" return None @deprecate_arguments({'qobj': 'circuits'}) def run( # type: ignore[override] self, circuits: Union[QasmQobj, PulseQobj, QuantumCircuit, Schedule, List[Union[QuantumCircuit, Schedule]]], job_name: Optional[str] = None, job_share_level: Optional[str] = None, job_tags: Optional[List[str]] = None, experiment_id: Optional[str] = None, backend_options: Optional[Dict] = None, noise_model: Any = None, **kwargs: Dict ) -> IBMQJob: """Run a Qobj asynchronously. Args: circuits: An individual or a list of :class:`~qiskit.circuits.QuantumCircuit` or :class:`~qiskit.pulse.Schedule` objects to run on the backend. A :class:`~qiskit.qobj.QasmQobj` or a :class:`~qiskit.qobj.PulseQobj` object is also supported but is deprecated. job_name: Custom name to be assigned to the job. This job name can subsequently be used as a filter in the :meth:`jobs` method. Job names do not need to be unique. job_share_level: Allows sharing a job at the hub, group, project and global level (see :meth:`IBMQBackend.run()<IBMQBackend.run>` for more details). job_tags: Tags to be assigned to the jobs. The tags can subsequently be used as a filter in the :meth:`IBMQBackend.jobs()<IBMQBackend.jobs>` method. experiment_id: Used to add a job to an "experiment", which is a collection of jobs and additional metadata. backend_options: DEPRECATED dictionary of backend options for the execution. noise_model: Noise model. kwargs: Additional runtime configuration options. They take precedence over options of the same names specified in `backend_options`. Returns: The job to be executed. """ # pylint: disable=arguments-differ if job_share_level: warnings.warn("The `job_share_level` keyword is no longer supported " "and will be removed in a future release.", Warning, stacklevel=3) if backend_options is not None: warnings.warn("Use of `backend_options` is deprecated and will " "be removed in a future release." "You can now pass backend options as key-value pairs to the " "run() method. For example: backend.run(circs, shots=2048).", DeprecationWarning, stacklevel=2) backend_options = backend_options or {} run_config = copy.deepcopy(backend_options) if noise_model: try: noise_model = noise_model.to_dict() except AttributeError: pass run_config.update(kwargs) return super().run(circuits, job_name=job_name, job_tags=job_tags, experiment_id=experiment_id, noise_model=noise_model, **run_config) class IBMQRetiredBackend(IBMQBackend): """Backend class interfacing with an IBM Quantum Experience device no longer available.""" def __init__( self, configuration: Union[QasmBackendConfiguration, PulseBackendConfiguration], provider: 'accountprovider.AccountProvider', credentials: Credentials, api_client: AccountClient ) -> None: """IBMQRetiredBackend constructor. Args: configuration: Backend configuration. provider: IBM Quantum Experience account provider credentials: IBM Quantum Experience credentials. api_client: IBM Quantum Experience client used to communicate with the server. """ super().__init__(configuration, provider, credentials, api_client) self._status = BackendStatus( backend_name=self.name(), backend_version=self.configuration().backend_version, operational=False, pending_jobs=0, status_msg='This backend is no longer available.') @classmethod def _default_options(cls) -> Options: """Default runtime options.""" return Options() def properties( self, refresh: bool = False, datetime: Optional[python_datetime] = None ) -> None: """Return the backend properties.""" return None def defaults(self, refresh: bool = False) -> None: """Return the pulse defaults for the backend.""" return None def status(self) -> BackendStatus: """Return the backend status.""" return self._status def job_limit(self) -> None: """Return the job limits for the backend.""" return None def remaining_jobs_count(self) -> None: """Return the number of remaining jobs that could be submitted to the backend.""" return None def active_jobs(self, limit: int = 10) -> None: """Return the unfinished jobs submitted to this backend.""" return None def reservations( self, start_datetime: Optional[python_datetime] = None, end_datetime: Optional[python_datetime] = None ) -> List[BackendReservation]: return [] def run( # type: ignore[override] self, *args: Any, **kwargs: Any ) -> None: """Run a Qobj.""" # pylint: disable=arguments-differ raise IBMQBackendError('This backend ({}) is no longer available.'.format(self.name())) @classmethod def from_name( cls, backend_name: str, provider: 'accountprovider.AccountProvider', credentials: Credentials, api: AccountClient ) -> 'IBMQRetiredBackend': """Return a retired backend from its name.""" configuration = QasmBackendConfiguration( backend_name=backend_name, backend_version='0.0.0', n_qubits=1, basis_gates=[], simulator=False, local=False, conditional=False, open_pulse=False, memory=False, max_shots=1, gates=[GateConfig(name='TODO', parameters=[], qasm_def='TODO')], coupling_map=[[0, 1]], ) return cls(configuration, provider, credentials, api)
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 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. """IBM Quantum experiment service.""" import logging import json import copy from typing import Optional, List, Dict, Union, Tuple, Any, Type from datetime import datetime from collections import defaultdict from qiskit.providers.ibmq import accountprovider # pylint: disable=unused-import from qiskit.providers.exceptions import QiskitBackendNotFoundError from .constants import (ExperimentShareLevel, ResultQuality, RESULT_QUALITY_FROM_API, RESULT_QUALITY_TO_API) from .utils import map_api_error from .device_component import DeviceComponent from ..utils.converters import local_to_utc_str, utc_to_local from ..api.clients.experiment import ExperimentClient from ..api.exceptions import RequestsApiError from ..ibmqbackend import IBMQRetiredBackend from ..exceptions import IBMQApiError from ..credentials import store_preferences logger = logging.getLogger(__name__) class IBMExperimentService: """Provides experiment related services. This class is the main interface to invoke IBM Quantum experiment service, which allows you to create, delete, update, query, and retrieve experiments, experiment figures, and analysis results. The ``experiment`` attribute of :class:`~qiskit.providers.ibmq.accountprovider.AccountProvider` is an instance of this class, and the main syntax for using the service is ``provider.experiment.<action>``. For example:: from qiskit import IBMQ provider = IBMQ.load_account() # Retrieve all experiments. experiments = provider.experiment.experiments() # Retrieve experiments with filtering. experiment_filtered = provider.experiment.experiments(backend_name='ibmq_athens') # Retrieve a specific experiment using its ID. experiment = provider.experiment.experiment(EXPERIMENT_ID) # Upload a new experiment. new_experiment_id = provider.experiment.create_experiment( experiment_type="T1", backend_name="ibmq_athens", metadata={"qubits": 5} ) # Update an experiment. provider.experiment.update_experiment( experiment_id=EXPERIMENT_ID, share_level="Group" ) # Delete an experiment. provider.experiment.delete_experiment(EXPERIMENT_ID) Similar syntax applies to analysis results and experiment figures. """ _default_preferences = {"auto_save": False} def __init__( self, provider: 'accountprovider.AccountProvider' ) -> None: """IBMExperimentService constructor. Args: provider: IBM Quantum Experience account provider. """ super().__init__() self._provider = provider self._api_client = ExperimentClient(provider.credentials) self._preferences = copy.deepcopy(self._default_preferences) self._preferences.update(provider.credentials.preferences.get('experiments', {})) def backends(self) -> List[Dict]: """Return a list of backends that can be used for experiments. Returns: A list of backends. """ return self._api_client.experiment_devices() def create_experiment( self, experiment_type: str, backend_name: str, metadata: Optional[Dict] = None, experiment_id: Optional[str] = None, parent_id: Optional[str] = None, job_ids: Optional[List[str]] = None, tags: Optional[List[str]] = None, notes: Optional[str] = None, share_level: Optional[Union[str, ExperimentShareLevel]] = None, start_datetime: Optional[Union[str, datetime]] = None, json_encoder: Type[json.JSONEncoder] = json.JSONEncoder, **kwargs: Any ) -> str: """Create a new experiment in the database. Args: experiment_type: Experiment type. backend_name: Name of the backend the experiment ran on. metadata: Experiment metadata. experiment_id: Experiment ID. It must be in the ``uuid4`` format. One will be generated if not supplied. parent_id: The experiment ID of the parent experiment. The parent experiment must exist, must be on the same backend as the child, and an experiment cannot be its own parent. job_ids: IDs of experiment jobs. tags: Tags to be associated with the experiment. notes: Freeform notes about the experiment. share_level: The level at which the experiment is shared. This determines who can view the experiment (but not update it). This defaults to "private" for new experiments. Possible values include: - private: The experiment is only visible to its owner (default) - project: The experiment is shared within its project - group: The experiment is shared within its group - hub: The experiment is shared within its hub - public: The experiment is shared publicly regardless of provider start_datetime: Timestamp when the experiment started, in local time zone. json_encoder: Custom JSON encoder to use to encode the experiment. kwargs: Additional experiment attributes that are not supported and will be ignored. Returns: Experiment ID. Raises: IBMExperimentEntryExists: If the experiment already exits. IBMQApiError: If the request to the server failed. """ # pylint: disable=arguments-differ if kwargs: logger.info("Keywords %s are not supported by IBM Quantum experiment service " "and will be ignored.", kwargs.keys()) data = { 'type': experiment_type, 'device_name': backend_name, 'hub_id': self._provider.credentials.hub, 'group_id': self._provider.credentials.group, 'project_id': self._provider.credentials.project } data.update(self._experiment_data_to_api(metadata=metadata, experiment_id=experiment_id, parent_id=parent_id, job_ids=job_ids, tags=tags, notes=notes, share_level=share_level, start_dt=start_datetime)) with map_api_error(f"Experiment {experiment_id} already exists."): response_data = self._api_client.experiment_upload(json.dumps(data, cls=json_encoder)) return response_data['uuid'] def update_experiment( self, experiment_id: str, metadata: Optional[Dict] = None, job_ids: Optional[List[str]] = None, notes: Optional[str] = None, tags: Optional[List[str]] = None, share_level: Optional[Union[str, ExperimentShareLevel]] = None, end_datetime: Optional[Union[str, datetime]] = None, json_encoder: Type[json.JSONEncoder] = json.JSONEncoder, **kwargs: Any, ) -> None: """Update an existing experiment. Args: experiment_id: Experiment ID. metadata: Experiment metadata. job_ids: IDs of experiment jobs. notes: Freeform notes about the experiment. tags: Tags to be associated with the experiment. share_level: The level at which the experiment is shared. This determines who can view the experiment (but not update it). This defaults to "private" for new experiments. Possible values include: - private: The experiment is only visible to its owner (default) - project: The experiment is shared within its project - group: The experiment is shared within its group - hub: The experiment is shared within its hub - public: The experiment is shared publicly regardless of provider end_datetime: Timestamp for when the experiment ended, in local time. json_encoder: Custom JSON encoder to use to encode the experiment. kwargs: Additional experiment attributes that are not supported and will be ignored. Raises: IBMExperimentEntryNotFound: If the experiment does not exist. IBMQApiError: If the request to the server failed. """ # pylint: disable=arguments-differ if kwargs: logger.info("Keywords %s are not supported by IBM Quantum experiment service " "and will be ignored.", kwargs.keys()) data = self._experiment_data_to_api(metadata=metadata, job_ids=job_ids, tags=tags, notes=notes, share_level=share_level, end_dt=end_datetime) if not data: logger.warning("update_experiment() called with nothing to update.") return with map_api_error(f"Experiment {experiment_id} not found."): self._api_client.experiment_update(experiment_id, json.dumps(data, cls=json_encoder)) def _experiment_data_to_api( self, metadata: Optional[Dict] = None, experiment_id: Optional[str] = None, parent_id: Optional[str] = None, job_ids: Optional[List[str]] = None, tags: Optional[List[str]] = None, notes: Optional[str] = None, share_level: Optional[Union[str, ExperimentShareLevel]] = None, start_dt: Optional[Union[str, datetime]] = None, end_dt: Optional[Union[str, datetime]] = None, ) -> Dict: """Convert experiment data to API request data. Args: metadata: Experiment metadata. experiment_id: Experiment ID. parent_id: Parent experiment ID job_ids: IDs of experiment jobs. tags: Tags to be associated with the experiment. notes: Freeform notes about the experiment. share_level: The level at which the experiment is shared. start_dt: Experiment start time. end_dt: Experiment end time. Returns: API request data. """ data = {} # type: Dict[str, Any] if metadata: data['extra'] = metadata if experiment_id: data['uuid'] = experiment_id if parent_id: data['parent_experiment_uuid'] = parent_id if share_level: if isinstance(share_level, str): share_level = ExperimentShareLevel(share_level.lower()) data['visibility'] = share_level.value if tags: data['tags'] = tags if job_ids: data['jobs'] = job_ids if notes: data['notes'] = notes if start_dt: data['start_time'] = local_to_utc_str(start_dt) if end_dt: data['end_time'] = local_to_utc_str(end_dt) return data def experiment( self, experiment_id: str, json_decoder: Type[json.JSONDecoder] = json.JSONDecoder ) -> Dict: """Retrieve a previously stored experiment. Args: experiment_id: Experiment ID. json_decoder: Custom JSON decoder to use to decode the retrieved experiment. Returns: Retrieved experiment data. Raises: IBMExperimentEntryNotFound: If the experiment does not exist. IBMQApiError: If the request to the server failed. """ with map_api_error(f"Experiment {experiment_id} not found."): raw_data = self._api_client.experiment_get(experiment_id) return self._api_to_experiment_data(json.loads(raw_data, cls=json_decoder)) def experiments( self, limit: Optional[int] = 10, json_decoder: Type[json.JSONDecoder] = json.JSONDecoder, device_components: Optional[List[Union[str, DeviceComponent]]] = None, device_components_operator: Optional[str] = None, experiment_type: Optional[str] = None, experiment_type_operator: Optional[str] = None, backend_name: Optional[str] = None, tags: Optional[List[str]] = None, tags_operator: Optional[str] = "OR", start_datetime_after: Optional[datetime] = None, start_datetime_before: Optional[datetime] = None, hub: Optional[str] = None, group: Optional[str] = None, project: Optional[str] = None, exclude_public: Optional[bool] = False, public_only: Optional[bool] = False, exclude_mine: Optional[bool] = False, mine_only: Optional[bool] = False, parent_id: Optional[str] = None, sort_by: Optional[Union[str, List[str]]] = None, **filters: Any ) -> List[Dict]: """Retrieve all experiments, with optional filtering. By default, results returned are as inclusive as possible. For example, if you don't specify any filters, all experiments visible to you are returned. This includes your own experiments as well as those shared with you, from all providers you have access to (not just from the provider you used to invoke this experiment service). Args: limit: Number of experiments to retrieve. ``None`` indicates no limit. json_decoder: Custom JSON decoder to use to decode the retrieved experiments. device_components: Filter by device components. device_components_operator: Operator used when filtering by device components. Valid values are ``None`` and "contains": * If ``None``, an analysis result's device components must match exactly for it to be included. * If "contains" is specified, an analysis result's device components must contain at least the values specified by the `device_components` filter. experiment_type: Experiment type used for filtering. experiment_type_operator: Operator used when filtering by experiment type. Valid values are ``None`` and "like": * If ``None`` is specified, an experiment's type value must match exactly for it to be included. * If "like" is specified, an experiment's type value must contain the value specified by `experiment_type`. For example, ``experiment_type="foo", experiment_type_operator="like"`` will match both ``foo1`` and ``1foo``. backend_name: Backend name used for filtering. tags: Filter by tags assigned to experiments. tags_operator: Logical operator to use when filtering by job tags. Valid values are "AND" and "OR": * If "AND" is specified, then an experiment must have all of the tags specified in `tags` to be included. * If "OR" is specified, then an experiment only needs to have any of the tags specified in `tags` to be included. start_datetime_after: Filter by the given start timestamp, in local time. This is used to find experiments whose start date/time is after (greater than or equal to) this local timestamp. start_datetime_before: Filter by the given start timestamp, in local time. This is used to find experiments whose start date/time is before (less than or equal to) this local timestamp. hub: Filter by hub. group: Filter by hub and group. `hub` must also be specified if `group` is. project: Filter by hub, group, and project. `hub` and `group` must also be specified if `project` is. exclude_public: If ``True``, experiments with ``share_level=public`` (that is, experiments visible to all users) will not be returned. Cannot be ``True`` if `public_only` is ``True``. public_only: If ``True``, only experiments with ``share_level=public`` (that is, experiments visible to all users) will be returned. Cannot be ``True`` if `exclude_public` is ``True``. exclude_mine: If ``True``, experiments where I am the owner will not be returned. Cannot be ``True`` if `mine_only` is ``True``. mine_only: If ``True``, only experiments where I am the owner will be returned. Cannot be ``True`` if `exclude_mine` is ``True``. parent_id: Filter experiments by this parent experiment ID. sort_by: Specifies how the output should be sorted. This can be a single sorting option or a list of options. Each option should contain a sort key and a direction, separated by a semicolon. Valid sort keys are "start_datetime" and "experiment_type". Valid directions are "asc" for ascending or "desc" for descending. For example, ``sort_by=["experiment_type:asc", "start_datetime:desc"]`` will return an output list that is first sorted by experiment type in ascending order, then by start datetime by descending order. By default, experiments are sorted by ``start_datetime`` descending and ``experiment_id`` ascending. **filters: Additional filtering keywords that are not supported and will be ignored. Returns: A list of experiments. Each experiment is a dictionary containing the retrieved experiment data. Raises: ValueError: If an invalid parameter value is specified. IBMQApiError: If the request to the server failed. """ # pylint: disable=arguments-differ if filters: logger.info("Keywords %s are not supported by IBM Quantum experiment service " "and will be ignored.", filters.keys()) if limit is not None and (not isinstance(limit, int) or limit <= 0): # type: ignore raise ValueError(f"{limit} is not a valid `limit`, which has to be a positive integer.") pgh_text = ['project', 'group', 'hub'] pgh_val = [project, group, hub] for idx, val in enumerate(pgh_val): if val is not None and None in pgh_val[idx+1:]: raise ValueError(f"If {pgh_text[idx]} is specified, " f"{' and '.join(pgh_text[idx+1:])} must also be specified.") start_time_filters = [] if start_datetime_after: st_filter = 'ge:{}'.format(local_to_utc_str(start_datetime_after)) start_time_filters.append(st_filter) if start_datetime_before: st_filter = 'le:{}'.format(local_to_utc_str(start_datetime_before)) start_time_filters.append(st_filter) if exclude_public and public_only: raise ValueError('exclude_public and public_only cannot both be True') if exclude_mine and mine_only: raise ValueError('exclude_mine and mine_only cannot both be True') converted = self._filtering_to_api( tags=tags, tags_operator=tags_operator, sort_by=sort_by, sort_map={"start_datetime": "start_time", "experiment_type": "type"}, device_components=device_components, device_components_operator=device_components_operator, item_type=experiment_type, item_type_operator=experiment_type_operator ) experiments = [] marker = None while limit is None or limit > 0: with map_api_error(f"Request failed."): response = self._api_client.experiments( limit=limit, marker=marker, backend_name=backend_name, experiment_type=converted["type"], start_time=start_time_filters, device_components=converted["device_components"], tags=converted["tags"], hub=hub, group=group, project=project, exclude_public=exclude_public, public_only=public_only, exclude_mine=exclude_mine, mine_only=mine_only, parent_id=parent_id, sort_by=converted["sort_by"]) raw_data = json.loads(response, cls=json_decoder) marker = raw_data.get('marker') for exp in raw_data['experiments']: experiments.append(self._api_to_experiment_data(exp)) if limit: limit -= len(raw_data['experiments']) if not marker: # No more experiments to return. break return experiments def _api_to_experiment_data( self, raw_data: Dict, ) -> Dict: """Convert API response to experiment data. Args: raw_data: API response Returns: Converted experiment data. """ backend_name = raw_data['device_name'] try: backend = self._provider.get_backend(backend_name) except QiskitBackendNotFoundError: backend = IBMQRetiredBackend.from_name(backend_name=backend_name, provider=self._provider, credentials=self._provider.credentials, api=None) extra_data: Dict[str, Any] = {} self._convert_dt(raw_data.get('created_at', None), extra_data, 'creation_datetime') self._convert_dt(raw_data.get('start_time', None), extra_data, 'start_datetime') self._convert_dt(raw_data.get('end_time', None), extra_data, 'end_datetime') self._convert_dt(raw_data.get('updated_at', None), extra_data, 'updated_datetime') out_dict = { "experiment_type": raw_data['type'], "backend": backend, "experiment_id": raw_data['uuid'], "parent_id": raw_data.get('parent_experiment_uuid', None), "tags": raw_data.get("tags", None), "job_ids": raw_data['jobs'], "share_level": raw_data.get("visibility", None), "metadata": raw_data.get("extra", None), "figure_names": raw_data.get("plot_names", None), "notes": raw_data.get("notes", ""), "hub": raw_data.get("hub_id", ""), "group": raw_data.get("group_id", ""), "project": raw_data.get("project_id", ""), "owner": raw_data.get("owner", ""), **extra_data } return out_dict def _convert_dt( self, timestamp: Optional[str], data: Dict, field_name: str ) -> None: """Convert input timestamp. Args: timestamp: Timestamp to be converted. data: Data used to stored the converted timestamp. field_name: Name used to store the converted timestamp. """ if not timestamp: return data[field_name] = utc_to_local(timestamp) def delete_experiment(self, experiment_id: str) -> None: """Delete an experiment. Args: experiment_id: Experiment ID. Note: This method prompts for confirmation and requires a response before proceeding. Raises: IBMQApiError: If the request to the server failed. """ confirmation = input('\nAre you sure you want to delete the experiment? ' 'Results and plots for the experiment will also be deleted. [y/N]: ') if confirmation not in ('y', 'Y'): return try: self._api_client.experiment_delete(experiment_id) except RequestsApiError as api_err: if api_err.status_code == 404: logger.warning("Experiment %s not found.", experiment_id) else: raise IBMQApiError(f"Failed to process the request: {api_err}") from None def create_analysis_result( self, experiment_id: str, result_data: Dict, result_type: str, device_components: Optional[Union[List[Union[str, DeviceComponent]], str, DeviceComponent]] = None, tags: Optional[List[str]] = None, quality: Union[ResultQuality, str] = ResultQuality.UNKNOWN, verified: bool = False, result_id: Optional[str] = None, chisq: Optional[float] = None, json_encoder: Type[json.JSONEncoder] = json.JSONEncoder, **kwargs: Any, ) -> str: """Create a new analysis result in the database. Args: experiment_id: ID of the experiment this result is for. result_data: Result data to be stored. result_type: Analysis result type. device_components: Target device components, such as qubits. tags: Tags to be associated with the analysis result. quality: Quality of this analysis. verified: Whether the result quality has been verified. result_id: Analysis result ID. It must be in the ``uuid4`` format. One will be generated if not supplied. chisq: chi^2 decimal value of the fit. json_encoder: Custom JSON encoder to use to encode the analysis result. kwargs: Additional analysis result attributes that are not supported and will be ignored. Returns: Analysis result ID. Raises: IBMExperimentEntryExists: If the analysis result already exits. IBMQApiError: If the request to the server failed. """ # pylint: disable=arguments-differ if kwargs: logger.info("Keywords %s are not supported by IBM Quantum experiment service " "and will be ignored.", kwargs.keys()) components = [] if device_components: if not isinstance(device_components, list): device_components = [device_components] for comp in device_components: components.append(str(comp)) if isinstance(quality, str): quality = ResultQuality(quality.upper()) request = self._analysis_result_to_api( experiment_id=experiment_id, device_components=components, data=result_data, result_type=result_type, tags=tags, quality=quality, verified=verified, result_id=result_id, chisq=chisq ) with map_api_error(f"Analysis result {result_id} already exists."): response = self._api_client.analysis_result_upload( json.dumps(request, cls=json_encoder)) return response['uuid'] def update_analysis_result( self, result_id: str, result_data: Optional[Dict] = None, tags: Optional[List[str]] = None, quality: Union[ResultQuality, str] = None, verified: bool = None, chisq: Optional[float] = None, json_encoder: Type[json.JSONEncoder] = json.JSONEncoder, **kwargs: Any, ) -> None: """Update an existing analysis result. Args: result_id: Analysis result ID. result_data: Result data to be stored. quality: Quality of this analysis. verified: Whether the result quality has been verified. tags: Tags to be associated with the analysis result. chisq: chi^2 decimal value of the fit. json_encoder: Custom JSON encoder to use to encode the analysis result. kwargs: Additional analysis result attributes that are not supported and will be ignored. Raises: IBMExperimentEntryNotFound: If the analysis result does not exist. IBMQApiError: If the request to the server failed. """ # pylint: disable=arguments-differ if kwargs: logger.info("Keywords %s are not supported by IBM Quantum experiment service " "and will be ignored.", kwargs.keys()) if isinstance(quality, str): quality = ResultQuality(quality.upper()) request = self._analysis_result_to_api(data=result_data, tags=tags, quality=quality, verified=verified, chisq=chisq) with map_api_error(f"Analysis result {result_id} not found."): self._api_client.analysis_result_update( result_id, json.dumps(request, cls=json_encoder)) def _analysis_result_to_api( self, experiment_id: Optional[str] = None, device_components: Optional[List[str]] = None, data: Optional[Dict] = None, result_type: Optional[str] = None, tags: Optional[List[str]] = None, quality: Optional[ResultQuality] = None, verified: Optional[bool] = None, result_id: Optional[str] = None, chisq: Optional[float] = None, ) -> Dict: """Convert analysis result fields to server format. Args: experiment_id: ID of the experiment this result is for. data: Result data to be stored. result_type: Analysis result type. device_components: Target device components, such as qubits. tags: Tags to be associated with the analysis result. quality: Quality of this analysis. verified: Whether the result quality has been verified. result_id: Analysis result ID. It must be in the ``uuid4`` format. One will be generated if not supplied. chisq: chi^2 decimal value of the fit. Returns: API request data. """ out = {} # type: Dict[str, Any] if experiment_id: out["experiment_uuid"] = experiment_id if device_components: out["device_components"] = device_components if data: out["fit"] = data if result_type: out["type"] = result_type if tags: out["tags"] = tags if quality: out["quality"] = RESULT_QUALITY_TO_API[quality] if verified is not None: out["verified"] = verified if result_id: out["uuid"] = result_id if chisq: out["chisq"] = chisq return out def analysis_result( self, result_id: str, json_decoder: Type[json.JSONDecoder] = json.JSONDecoder ) -> Dict: """Retrieve a previously stored experiment. Args: result_id: Analysis result ID. json_decoder: Custom JSON decoder to use to decode the retrieved analysis result. Returns: Retrieved analysis result. Raises: IBMExperimentEntryNotFound: If the analysis result does not exist. IBMQApiError: If the request to the server failed. """ with map_api_error(f"Analysis result {result_id} not found."): raw_data = self._api_client.analysis_result_get(result_id) return self._api_to_analysis_result(json.loads(raw_data, cls=json_decoder)) def analysis_results( self, limit: Optional[int] = 10, json_decoder: Type[json.JSONDecoder] = json.JSONDecoder, device_components: Optional[List[Union[str, DeviceComponent]]] = None, device_components_operator: Optional[str] = None, experiment_id: Optional[str] = None, result_type: Optional[str] = None, result_type_operator: Optional[str] = None, backend_name: Optional[str] = None, quality: Optional[Union[List[Union[ResultQuality, str]], ResultQuality, str]] = None, verified: Optional[bool] = None, tags: Optional[List[str]] = None, tags_operator: Optional[str] = "OR", sort_by: Optional[Union[str, List[str]]] = None, **filters: Any ) -> List[Dict]: """Retrieve all analysis results, with optional filtering. Args: limit: Number of analysis results to retrieve. json_decoder: Custom JSON decoder to use to decode the retrieved analysis results. device_components: Filter by device components. device_components_operator: Operator used when filtering by device components. Valid values are ``None`` and "contains": * If ``None``, an analysis result's device components must match exactly for it to be included. * If "contains" is specified, an analysis result's device components must contain at least the values specified by the `device_components` filter. experiment_id: Experiment ID used for filtering. result_type: Analysis result type used for filtering. result_type_operator: Operator used when filtering by result type. Valid values are ``None`` and "like": * If ``None`` is specified, an analysis result's type value must match exactly for it to be included. * If "like" is specified, an analysis result's type value must contain the value specified by `result_type`. For example, ``result_type="foo", result_type_operator="like"`` will match both ``foo1`` and ``1foo``. backend_name: Backend name used for filtering. quality: Quality value used for filtering. If a list is given, analysis results whose quality value is in the list will be included. verified: Indicates whether this result has been verified.. tags: Filter by tags assigned to analysis results. This can be used with `tags_operator` for granular filtering. tags_operator: Logical operator to use when filtering by tags. Valid values are "AND" and "OR": * If "AND" is specified, then an analysis result must have all of the tags specified in `tags` to be included. * If "OR" is specified, then an analysis result only needs to have any of the tags specified in `tags` to be included. sort_by: Specifies how the output should be sorted. This can be a single sorting option or a list of options. Each option should contain a sort key and a direction. Valid sort keys are "creation_datetime", "device_components", and "result_type". Valid directions are "asc" for ascending or "desc" for descending. For example, ``sort_by=["result_type: asc", "creation_datetime:desc"]`` will return an output list that is first sorted by result type in ascending order, then by creation datetime by descending order. By default, analysis results are sorted by ``creation_datetime`` descending and ``result_id`` ascending. **filters: Additional filtering keywords that are not supported and will be ignored. Returns: A list of analysis results. Each analysis result is a dictionary containing the retrieved analysis result. Raises: ValueError: If an invalid parameter value is specified. IBMQApiError: If the request to the server failed. """ # pylint: disable=arguments-differ if filters: logger.info("Keywords %s are not supported by IBM Quantum experiment service " "and will be ignored.", filters.keys()) if limit is not None and (not isinstance(limit, int) or limit <= 0): # type: ignore raise ValueError(f"{limit} is not a valid `limit`, which has to be a positive integer.") quality = self._quality_filter_to_api(quality) converted = self._filtering_to_api( tags=tags, tags_operator=tags_operator, sort_by=sort_by, sort_map={"creation_datetime": "created_at", "device_components": "device_components", "result_type": "type"}, device_components=device_components, device_components_operator=device_components_operator, item_type=result_type, item_type_operator=result_type_operator ) results = [] marker = None while limit is None or limit > 0: with map_api_error("Request failed."): response = self._api_client.analysis_results( limit=limit, marker=marker, backend_name=backend_name, device_components=converted["device_components"], experiment_uuid=experiment_id, result_type=converted["type"], quality=quality, verified=verified, tags=converted["tags"], sort_by=converted["sort_by"] ) raw_data = json.loads(response, cls=json_decoder) marker = raw_data.get('marker') for result in raw_data['analysis_results']: results.append(self._api_to_analysis_result(result)) if limit: limit -= len(raw_data['analysis_results']) if not marker: # No more experiments to return. break return results def _quality_filter_to_api( self, quality: Optional[Union[List[Union[ResultQuality, str]], ResultQuality, str]] = None, ) -> Optional[Union[str, List[str]]]: """Convert quality filter to server format.""" if not quality: return None if not isinstance(quality, list): quality = [quality] api_quals = [] for qual in quality: if isinstance(qual, str): qual = ResultQuality(qual.upper()) api_qual = RESULT_QUALITY_TO_API[qual] if api_qual not in api_quals: api_quals.append(api_qual) if len(api_quals) == 1: return api_quals[0] if len(api_quals) == len(ResultQuality): return None return "in:" + ",".join(api_quals) def _filtering_to_api( self, tags: Optional[List[str]] = None, tags_operator: Optional[str] = "OR", sort_by: Optional[Union[str, List[str]]] = None, sort_map: Optional[Dict] = None, device_components: Optional[List[Union[str, DeviceComponent]]] = None, device_components_operator: Optional[str] = None, item_type: Optional[str] = None, item_type_operator: Optional[str] = None, ) -> Dict: """Convert filtering inputs to server format. Args: tags: Filtering by tags. tags_operator: Tags operator. sort_by: Specifies how the output should be sorted. sort_map: Sort key to API key mapping. device_components: Filter by device components. device_components_operator: Device component operator. item_type: Item type used for filtering. item_type_operator: Operator used when filtering by type. Returns: A dictionary of mapped filters. Raises: ValueError: If an input key is invalid. """ tags_filter = None if tags: if tags_operator.upper() == 'OR': tags_filter = 'any:' + ','.join(tags) elif tags_operator.upper() == 'AND': tags_filter = 'contains:' + ','.join(tags) else: raise ValueError('{} is not a valid `tags_operator`. Valid values are ' '"AND" and "OR".'.format(tags_operator)) sort_list = [] if sort_by: if not isinstance(sort_by, list): sort_by = [sort_by] for sorter in sort_by: key, direction = sorter.split(":") key = key.lower() if key not in sort_map: raise ValueError(f'"{key}" is not a valid sort key. ' f'Valid sort keys are {sort_map.keys()}') key = sort_map[key] if direction not in ["asc", "desc"]: raise ValueError(f'"{direction}" is not a valid sorting direction.' f'Valid directions are "asc" and "desc".') sort_list.append(f"{key}:{direction}") sort_by = ",".join(sort_list) if device_components: device_components = [str(comp) for comp in device_components] if device_components_operator: if device_components_operator != "contains": raise ValueError(f'{device_components_operator} is not a valid ' f'device_components_operator value. Valid values ' f'are ``None`` and "contains"') device_components = \ "contains:" + ','.join(device_components) # type: ignore if item_type and item_type_operator: if item_type_operator != "like": raise ValueError(f'"{item_type_operator}" is not a valid type operator value. ' f'Valid values are ``None`` and "like".') item_type = "like:" + item_type return {"tags": tags_filter, "sort_by": sort_by, "device_components": device_components, "type": item_type} def _api_to_analysis_result( self, raw_data: Dict, ) -> Dict: """Map API response to an AnalysisResult instance. Args: raw_data: API response data. Returns: Converted analysis result data. """ extra_data = {} chisq = raw_data.get('chisq', None) if chisq: extra_data['chisq'] = chisq backend_name = raw_data['device_name'] if backend_name: extra_data['backend_name'] = backend_name quality = raw_data.get('quality', None) if quality: quality = RESULT_QUALITY_FROM_API[quality] self._convert_dt(raw_data.get('created_at', None), extra_data, 'creation_datetime') self._convert_dt(raw_data.get('updated_at', None), extra_data, 'updated_datetime') out_dict = { "result_data": raw_data.get('fit', {}), "result_type": raw_data.get('type', None), "device_components": raw_data.get('device_components', []), "experiment_id": raw_data.get('experiment_uuid'), "result_id": raw_data.get('uuid', None), "quality": quality, "verified": raw_data.get('verified', False), "tags": raw_data.get('tags', []), "service": self, **extra_data } return out_dict def delete_analysis_result( self, result_id: str ) -> None: """Delete an analysis result. Args: result_id: Analysis result ID. Note: This method prompts for confirmation and requires a response before proceeding. Raises: IBMQApiError: If the request to the server failed. """ confirmation = input('\nAre you sure you want to delete the analysis result? [y/N]: ') if confirmation not in ('y', 'Y'): return try: self._api_client.analysis_result_delete(result_id) except RequestsApiError as api_err: if api_err.status_code == 404: logger.warning("Analysis result %s not found.", result_id) else: raise IBMQApiError(f"Failed to process the request: {api_err}") from None def create_figure( self, experiment_id: str, figure: Union[str, bytes], figure_name: Optional[str] = None, sync_upload: bool = True ) -> Tuple[str, int]: """Store a new figure in the database. Note: Currently only SVG figures are supported. Args: experiment_id: ID of the experiment this figure is for. figure: Name of the figure file or figure data to store. figure_name: Name of the figure. If ``None``, the figure file name, if given, or a generated name is used. sync_upload: If ``True``, the plot will be uploaded synchronously. Otherwise the upload will be asynchronous. Returns: A tuple of the name and size of the saved figure. Raises: IBMExperimentEntryExists: If the figure already exits. IBMQApiError: If the request to the server failed. """ if figure_name is None: if isinstance(figure, str): figure_name = figure else: figure_name = "figure_{}.svg".format(datetime.now().isoformat()) if not figure_name.endswith(".svg"): figure_name += ".svg" with map_api_error(f"Figure {figure_name} already exists."): response = self._api_client.experiment_plot_upload(experiment_id, figure, figure_name, sync_upload=sync_upload) return response['name'], response['size'] def update_figure( self, experiment_id: str, figure: Union[str, bytes], figure_name: str, sync_upload: bool = True ) -> Tuple[str, int]: """Update an existing figure. Args: experiment_id: Experiment ID. figure: Name of the figure file or figure data to store. figure_name: Name of the figure. sync_upload: If ``True``, the plot will be uploaded synchronously. Otherwise the upload will be asynchronous. Returns: A tuple of the name and size of the saved figure. Raises: IBMExperimentEntryNotFound: If the figure does not exist. IBMQApiError: If the request to the server failed. """ with map_api_error(f"Figure {figure_name} not found."): response = self._api_client.experiment_plot_update(experiment_id, figure, figure_name, sync_upload=sync_upload) return response['name'], response['size'] def figure( self, experiment_id: str, figure_name: str, file_name: Optional[str] = None ) -> Union[int, bytes]: """Retrieve an existing figure. Args: experiment_id: Experiment ID. figure_name: Name of the figure. file_name: Name of the local file to save the figure to. If ``None``, the content of the figure is returned instead. Returns: The size of the figure if `file_name` is specified. Otherwise the content of the figure in bytes. Raises: IBMExperimentEntryNotFound: If the figure does not exist. IBMQApiError: If the request to the server failed. """ with map_api_error(f"Figure {figure_name} not found."): data = self._api_client.experiment_plot_get(experiment_id, figure_name) if file_name: with open(file_name, 'wb') as file: num_bytes = file.write(data) return num_bytes return data def delete_figure( self, experiment_id: str, figure_name: str ) -> None: """Delete an experiment plot. Note: This method prompts for confirmation and requires a response before proceeding. Args: experiment_id: Experiment ID. figure_name: Name of the figure. Raises: IBMQApiError: If the request to the server failed. """ confirmation = input('\nAre you sure you want to delete the experiment plot? [y/N]: ') if confirmation not in ('y', 'Y'): return try: self._api_client.experiment_plot_delete(experiment_id, figure_name) except RequestsApiError as api_err: if api_err.status_code == 404: logger.warning("Figure %s not found.", figure_name) else: raise IBMQApiError(f"Failed to process the request: {api_err}") from None def device_components( self, backend_name: Optional[str] = None ) -> Union[Dict[str, List], List]: """Return the device components. Args: backend_name: Name of the backend whose components are to be retrieved. Returns: A list of device components if `backend_name` is specified. Otherwise a dictionary whose keys are backend names the values are lists of device components for the backends. Raises: IBMQApiError: If the request to the server failed. """ with map_api_error(f"No device components found for backend {backend_name}"): raw_data = self._api_client.device_components(backend_name) components = defaultdict(list) for data in raw_data: components[data['device_name']].append(data['type']) if backend_name: return components[backend_name] return dict(components) @property def preferences(self) -> Dict: """Return saved experiment preferences. Note: These are preferences passed to the applications that use this service and have no effect on the service itself. It is up to the application, such as ``qiskit-experiments`` to implement the preferences. Returns: Dict: The experiment preferences. """ return self._preferences def save_preferences(self, auto_save: bool = None) -> None: """Stores experiment preferences on disk. Note: These are preferences passed to the applications that use this service and have no effect on the service itself. For example, if ``auto_save`` is set to ``True``, it tells the application, such as ``qiskit-experiments``, that you prefer changes to be automatically saved. It is up to the application to implement the preferences. Args: auto_save: Automatically save the experiment. """ update_cred = False if auto_save is not None and auto_save != self._preferences["auto_save"]: self._preferences['auto_save'] = auto_save update_cred = True if update_cred: store_preferences( {self._provider.credentials.unique_id(): {'experiment': self.preferences}})
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2019, 2020. # # 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. """Job Manager used to manage jobs for IBM Quantum Experience.""" import logging import warnings from typing import List, Optional, Union, Any from concurrent import futures from qiskit.circuit import QuantumCircuit from qiskit.pulse import Schedule from qiskit.providers.ibmq.utils import validate_job_tags from qiskit.providers.ibmq.accountprovider import AccountProvider from .exceptions import IBMQJobManagerInvalidStateError from .utils import format_job_details, format_status_counts from .managedjobset import ManagedJobSet from ..ibmqbackend import IBMQBackend logger = logging.getLogger(__name__) class IBMQJobManager: """Job Manager for IBM Quantum Experience. The Job Manager is a higher level mechanism for handling :class:`jobs<qiskit.providers.ibmq.job.IBMQJob>` composed of multiple circuits or pulse schedules. It splits the experiments into multiple jobs based on backend restrictions. When the jobs are finished, it collects and presents the results in a unified view. You can use the :meth:`run()` method to submit multiple experiments with the Job Manager:: from qiskit import IBMQ, transpile from qiskit.providers.ibmq.managed import IBMQJobManager from qiskit.circuit.random import random_circuit provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') # Build a thousand circuits. circs = [] for _ in range(1000): circs.append(random_circuit(num_qubits=5, depth=4, measure=True)) # Need to transpile the circuits first. circs = transpile(circs, backend=backend) # Use Job Manager to break the circuits into multiple jobs. job_manager = IBMQJobManager() job_set_foo = job_manager.run(circs, backend=backend, name='foo') The :meth:`run()` method returns a :class:`ManagedJobSet` instance, which represents the set of jobs for the experiments. You can use the :class:`ManagedJobSet` methods, such as :meth:`statuses()<ManagedJobSet.statuses>`, :meth:`results()<ManagedJobSet.results>`, and :meth:`error_messages()<ManagedJobSet.error_messages>` to get a combined view of the jobs in the set. For example:: results = job_set_foo.results() results.get_counts(5) # Counts for experiment 5. The :meth:`job_set_id()<ManagedJobSet.job_set_id>` method of :class:`ManagedJobSet` returns the job set ID, which can be used to retrieve the job set later:: job_set_id = job_set_foo.job_set_id() retrieved_foo = job_manager.retrieve_job_set(job_set_id=job_set_id, provider=provider) """ def __init__(self) -> None: """IBMQJobManager constructor.""" self._job_sets = [] # type: List[ManagedJobSet] self._executor = futures.ThreadPoolExecutor() def run( self, experiments: Union[QuantumCircuit, Schedule, List[QuantumCircuit], List[Schedule]], backend: IBMQBackend, name: Optional[str] = None, max_experiments_per_job: Optional[int] = None, job_share_level: Optional[str] = None, job_tags: Optional[List[str]] = None, **run_config: Any ) -> ManagedJobSet: """Execute a set of circuits or pulse schedules on a backend. The circuits or schedules will be split into multiple jobs. Circuits or schedules in a job will be executed together in each shot. Args: experiments: Circuit(s) or pulse schedule(s) to execute. backend: Backend to execute the experiments on. name: Name for this set of jobs. Each job within the set will have a job name that consists of the set name followed by a suffix. If not specified, the current date and time is used. max_experiments_per_job: Maximum number of experiments to run in each job. If not specified, the default is to use the maximum allowed by the backend. If the specified value is greater the maximum allowed by the backend, the default is used. job_share_level: Allow sharing the jobs at the hub, group, project, or global level. The level can be one of: ``global``, ``hub``, ``group``, ``project``, and ``none``. job_tags: Tags to be assigned to the jobs. The tags can subsequently be used as a filter in the :meth:`IBMQBackend.jobs()<qiskit.providers.ibmq.ibmqbackend.IBMQBackend.jobs()>` function call. run_config: Configuration of the runtime environment. Some examples of these configuration parameters include: ``qobj_id``, ``qobj_header``, ``shots``, ``memory``, ``seed_simulator``, ``qubit_lo_freq``, ``meas_lo_freq``, ``qubit_lo_range``, ``meas_lo_range``, ``schedule_los``, ``meas_level``, ``meas_return``, ``meas_map``, ``memory_slot_size``, ``rep_time``, and ``parameter_binds``. Refer to the documentation on :func:`qiskit.compiler.assemble` for details on these arguments. Returns: A :class:`ManagedJobSet` instance representing the set of jobs for the experiments. Raises: IBMQJobManagerInvalidStateError: If an input parameter value is not valid. """ if not isinstance(experiments, list): experiments = list(experiments) if (any(isinstance(exp, Schedule) for exp in experiments) and not backend.configuration().open_pulse): raise IBMQJobManagerInvalidStateError( 'Pulse schedules found, but the backend does not support pulse schedules.') if job_share_level: warnings.warn("The `job_share_level` keyword is no longer supported " "and will be removed in a future release.", Warning, stacklevel=2) validate_job_tags(job_tags, IBMQJobManagerInvalidStateError) if not isinstance(backend, IBMQBackend): raise IBMQJobManagerInvalidStateError( "IBMQJobManager only supports IBMQBackend. " "{} is not an IBMQBackend.".format(backend)) experiment_list = self._split_experiments( experiments, backend=backend, max_experiments_per_job=max_experiments_per_job) job_set = ManagedJobSet(name=name) job_set.run(experiment_list, backend=backend, executor=self._executor, job_tags=job_tags, **run_config) self._job_sets.append(job_set) return job_set def _split_experiments( self, experiments: Union[List[QuantumCircuit], List[Schedule]], backend: IBMQBackend, max_experiments_per_job: Optional[int] = None ) -> List[Union[List[QuantumCircuit], List[Schedule]]]: """Split a list of experiments into sub-lists. Args: experiments: Experiments to be split. backend: Backend to execute the experiments on. max_experiments_per_job: Maximum number of experiments to run in each job. Returns: A list of sub-lists of experiments. """ if hasattr(backend.configuration(), 'max_experiments'): backend_max = backend.configuration().max_experiments chunk_size = backend_max if max_experiments_per_job is None \ else min(backend_max, max_experiments_per_job) elif max_experiments_per_job: chunk_size = max_experiments_per_job else: return [experiments] return [experiments[x:x + chunk_size] for x in range(0, len(experiments), chunk_size)] def report(self, detailed: bool = True) -> str: """Return a report on the statuses of all jobs managed by this Job Manager. Args: detailed: ``True`` if a detailed report is to be returned. ``False`` if a summary report is to be returned. Returns: A report on job statuses. """ job_set_statuses = [job_set.statuses() for job_set in self._job_sets] flat_status_list = [stat for stat_list in job_set_statuses for stat in stat_list] report = ["Summary report:"] report.extend(format_status_counts(flat_status_list)) if detailed: report.append("\nDetail report:") for i, job_set in enumerate(self._job_sets): report.append((" Job set name: {}, ID: {}".format( job_set.name(), job_set.job_set_id()))) report.extend(format_job_details( job_set_statuses[i], job_set.managed_jobs())) return '\n'.join(report) def job_sets(self, name: Optional[str] = None) -> List[ManagedJobSet]: """Return job sets being managed in this session, subject to optional filtering. Args: name: Name of the managed job sets. Returns: A list of managed job sets that match the filter. """ if name: return [job_set for job_set in self._job_sets if job_set.name() == name] return self._job_sets def retrieve_job_set( self, job_set_id: str, provider: AccountProvider, refresh: bool = False ) -> ManagedJobSet: """Retrieve a previously submitted job set. Args: job_set_id: Job set ID. provider: Provider used for this job set. refresh: If ``True``, re-query the server for the job set information. Otherwise return the cached value. Returns: Retrieved job set. Raises: IBMQJobManagerUnknownJobSet: If the job set cannot be found. IBMQJobManagerInvalidStateError: If jobs for this job set are found but have unexpected attributes. """ for index, mjs in enumerate(self._job_sets): if mjs.job_set_id() == job_set_id: if not refresh: return mjs del self._job_sets[index] break new_job_set = ManagedJobSet(short_id=job_set_id) new_job_set.retrieve_jobs(provider=provider) self._job_sets.append(new_job_set) return new_job_set
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 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. """Qiskit runtime service.""" import logging from typing import Dict, Callable, Optional, Union, List, Any, Type import json import warnings from qiskit.providers.exceptions import QiskitBackendNotFoundError from qiskit.providers.ibmq import accountprovider # pylint: disable=unused-import from .runtime_job import RuntimeJob from .runtime_program import RuntimeProgram, ParameterNamespace from .utils import RuntimeDecoder, to_base64_string from .exceptions import (QiskitRuntimeError, RuntimeDuplicateProgramError, RuntimeProgramNotFound, RuntimeJobNotFound) from .program.result_decoder import ResultDecoder from .runtime_options import RuntimeOptions from ..api.clients.runtime import RuntimeClient from ..api.exceptions import RequestsApiError from ..exceptions import IBMQNotAuthorizedError, IBMQInputValueError, IBMQProviderError from ..ibmqbackend import IBMQRetiredBackend from ..credentials import Credentials logger = logging.getLogger(__name__) class IBMRuntimeService: """Class for interacting with the Qiskit Runtime service. Qiskit Runtime is a new architecture offered by IBM Quantum that streamlines computations requiring many iterations. These experiments will execute significantly faster within its improved hybrid quantum/classical process. The Qiskit Runtime Service allows authorized users to upload their Qiskit quantum programs. A Qiskit quantum program, also called a runtime program, is a piece of Python code and its metadata that takes certain inputs, performs quantum and maybe classical processing, and returns the results. The same or other authorized users can invoke these quantum programs by simply passing in parameters. A sample workflow of using the runtime service:: from qiskit import IBMQ, QuantumCircuit from qiskit.providers.ibmq import RunnerResult provider = IBMQ.load_account() backend = provider.backend.ibmq_qasm_simulator # List all available programs. provider.runtime.pprint_programs() # Create a circuit. qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure_all() # Set the "circuit-runner" program parameters params = provider.runtime.program(program_id="circuit-runner").parameters() params.circuits = qc params.measurement_error_mitigation = True # Configure backend options options = {'backend_name': backend.name()} # Execute the circuit using the "circuit-runner" program. job = provider.runtime.run(program_id="circuit-runner", options=options, inputs=params) # Get runtime job result. result = job.result(decoder=RunnerResult) If the program has any interim results, you can use the ``callback`` parameter of the :meth:`run` method to stream the interim results. Alternatively, you can use the :meth:`RuntimeJob.stream_results` method to stream the results at a later time, but before the job finishes. The :meth:`run` method returns a :class:`~qiskit.providers.ibmq.runtime.RuntimeJob` object. You can use its methods to perform tasks like checking job status, getting job result, and canceling job. """ def __init__(self, provider: 'accountprovider.AccountProvider') -> None: """IBMRuntimeService constructor. Args: provider: IBM Quantum account provider. """ self._provider = provider self._api_client = RuntimeClient(provider.credentials) self._access_token = provider.credentials.access_token self._ws_url = provider.credentials.runtime_url.replace('https', 'wss') self._programs = {} # type: Dict def pprint_programs(self, refresh: bool = False, detailed: bool = False, limit: int = 20, skip: int = 0) -> None: """Pretty print information about available runtime programs. Args: refresh: If ``True``, re-query the server for the programs. Otherwise return the cached value. detailed: If ``True`` print all details about available runtime programs. limit: The number of programs returned at a time. Default and maximum value of 20. skip: The number of programs to skip. """ programs = self.programs(refresh, limit, skip) for prog in programs: print("="*50) if detailed: print(str(prog)) else: print(f"{prog.program_id}:",) print(f" Name: {prog.name}") print(f" Description: {prog.description}") def programs(self, refresh: bool = False, limit: int = 20, skip: int = 0) -> List[RuntimeProgram]: """Return available runtime programs. Currently only program metadata is returned. Args: refresh: If ``True``, re-query the server for the programs. Otherwise return the cached value. limit: The number of programs returned at a time. ``None`` means no limit. skip: The number of programs to skip. Returns: A list of runtime programs. """ if skip is None: skip = 0 if not self._programs or refresh: self._programs = {} current_page_limit = 20 offset = 0 while True: response = self._api_client.list_programs(limit=current_page_limit, skip=offset) program_page = response.get("programs", []) # count is the total number of programs that would be returned if # there was no limit or skip count = response.get("count", 0) for prog_dict in program_page: program = self._to_program(prog_dict) self._programs[program.program_id] = program if len(self._programs) == count: # Stop if there are no more programs returned by the server. break offset += len(program_page) if limit is None: limit = len(self._programs) return list(self._programs.values())[skip:limit+skip] def program(self, program_id: str, refresh: bool = False) -> RuntimeProgram: """Retrieve a runtime program. Currently only program metadata is returned. Args: program_id: Program ID. refresh: If ``True``, re-query the server for the program. Otherwise return the cached value. Returns: Runtime program. Raises: RuntimeProgramNotFound: If the program does not exist. QiskitRuntimeError: If the request failed. """ if program_id not in self._programs or refresh: try: response = self._api_client.program_get(program_id) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeProgramNotFound(f"Program not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to get program: {ex}") from None self._programs[program_id] = self._to_program(response) return self._programs[program_id] def _to_program(self, response: Dict) -> RuntimeProgram: """Convert server response to ``RuntimeProgram`` instances. Args: response: Server response. Returns: A ``RuntimeProgram`` instance. """ backend_requirements = {} parameters = {} return_values = {} interim_results = {} if "spec" in response: backend_requirements = response["spec"].get('backend_requirements', {}) parameters = response["spec"].get('parameters', {}) return_values = response["spec"].get('return_values', {}) interim_results = response["spec"].get('interim_results', {}) return RuntimeProgram(program_name=response['name'], program_id=response['id'], description=response.get('description', ""), parameters=parameters, return_values=return_values, interim_results=interim_results, max_execution_time=response.get('cost', 0), creation_date=response.get('creation_date', ""), update_date=response.get('update_date', ""), backend_requirements=backend_requirements, is_public=response.get('is_public', False), data=response.get('data', ""), api_client=self._api_client) def run( self, program_id: str, options: Union[RuntimeOptions, Dict], inputs: Union[Dict, ParameterNamespace], callback: Optional[Callable] = None, result_decoder: Optional[Type[ResultDecoder]] = None, image: Optional[str] = "" ) -> RuntimeJob: """Execute the runtime program. Args: program_id: Program ID. options: Runtime options that control the execution environment. See :class:`RuntimeOptions` for all available options. Currently the only required option is ``backend_name``. inputs: Program input parameters. These input values are passed to the runtime program. callback: Callback function to be invoked for any interim results. The callback function will receive 2 positional parameters: 1. Job ID 2. Job interim result. result_decoder: A :class:`ResultDecoder` subclass used to decode job results. ``ResultDecoder`` is used if not specified. image: (DEPRECATED) The runtime image used to execute the program, specified in the form of image_name:tag. Not all accounts are authorized to select a different image. Returns: A ``RuntimeJob`` instance representing the execution. Raises: IBMQInputValueError: If input is invalid. """ if isinstance(options, dict): options = RuntimeOptions(**options) if image: warnings.warn("Passing the 'image' keyword to IBMRuntimeService.run is " "deprecated and will be removed in a future release. " "Please pass it in as part of 'options'.", DeprecationWarning, stacklevel=2) options.image = image options.validate() # If using params object, extract as dictionary if isinstance(inputs, ParameterNamespace): inputs.validate() inputs = vars(inputs) backend_name = options.backend_name result_decoder = result_decoder or ResultDecoder response = self._api_client.program_run(program_id=program_id, credentials=self._provider.credentials, backend_name=backend_name, params=inputs, image=options.image, log_level=options.log_level) backend = self._provider.get_backend(backend_name) job = RuntimeJob(backend=backend, api_client=self._api_client, credentials=self._provider.credentials, job_id=response['id'], program_id=program_id, params=inputs, user_callback=callback, result_decoder=result_decoder, image=options.image) return job def upload_program( self, data: str, metadata: Optional[Union[Dict, str]] = None ) -> str: """Upload a runtime program. In addition to program data, the following program metadata is also required: - name - max_execution_time - description Program metadata can be specified using the `metadata` parameter or individual parameter (for example, `name` and `description`). If the same metadata field is specified in both places, the individual parameter takes precedence. For example, if you specify:: upload_program(metadata={"name": "name1"}, name="name2") ``name2`` will be used as the program name. Args: data: Program data or path of the file containing program data to upload. metadata: Name of the program metadata file or metadata dictionary. A metadata file needs to be in the JSON format. The ``parameters``, ``return_values``, and ``interim_results`` should be defined as JSON Schema. See :file:`program/program_metadata_sample.json` for an example. The fields in metadata are explained below. * name: Name of the program. Required. * max_execution_time: Maximum execution time in seconds. Required. * description: Program description. Required. * is_public: Whether the runtime program should be visible to the public. The default is ``False``. * spec: Specifications for backend characteristics and input parameters required to run the program, interim results and final result. * backend_requirements: Backend requirements. * parameters: Program input parameters in JSON schema format. * return_values: Program return values in JSON schema format. * interim_results: Program interim results in JSON schema format. Returns: Program ID. Raises: IBMQInputValueError: If required metadata is missing. RuntimeDuplicateProgramError: If a program with the same name already exists. IBMQNotAuthorizedError: If you are not authorized to upload programs. QiskitRuntimeError: If the upload failed. """ program_metadata = self._read_metadata(metadata=metadata) for req in ['name', 'description', 'max_execution_time']: if req not in program_metadata or not program_metadata[req]: raise IBMQInputValueError(f"{req} is a required metadata field.") if "def main(" not in data: # This is the program file with open(data, "r") as file: data = file.read() try: program_data = to_base64_string(data) response = self._api_client.program_create(program_data=program_data, **program_metadata) except RequestsApiError as ex: if ex.status_code == 409: raise RuntimeDuplicateProgramError( "Program with the same name already exists.") from None if ex.status_code == 403: raise IBMQNotAuthorizedError( "You are not authorized to upload programs.") from None raise QiskitRuntimeError(f"Failed to create program: {ex}") from None return response['id'] def _read_metadata( self, metadata: Optional[Union[Dict, str]] = None ) -> Dict: """Read metadata. Args: metadata: Name of the program metadata file or metadata dictionary. Returns: Return metadata. """ upd_metadata: dict = {} if metadata is not None: if isinstance(metadata, str): with open(metadata, 'r') as file: upd_metadata = json.load(file) else: upd_metadata = metadata # TODO validate metadata format metadata_keys = ['name', 'max_execution_time', 'description', 'spec', 'is_public'] return {key: val for key, val in upd_metadata.items() if key in metadata_keys} def update_program( self, program_id: str, data: str = None, metadata: Optional[Union[Dict, str]] = None, name: str = None, description: str = None, max_execution_time: int = None, spec: Optional[Dict] = None ) -> None: """Update a runtime program. Program metadata can be specified using the `metadata` parameter or individual parameters, such as `name` and `description`. If the same metadata field is specified in both places, the individual parameter takes precedence. Args: program_id: Program ID. data: Program data or path of the file containing program data to upload. metadata: Name of the program metadata file or metadata dictionary. name: New program name. description: New program description. max_execution_time: New maximum execution time. spec: New specifications for backend characteristics, input parameters, interim results and final result. Raises: RuntimeProgramNotFound: If the program doesn't exist. QiskitRuntimeError: If the request failed. """ if not any([data, metadata, name, description, max_execution_time, spec]): warnings.warn("None of the 'data', 'metadata', 'name', 'description', " "'max_execution_time', or 'spec' parameters is specified. " "No update is made.") return if data: if "def main(" not in data: # This is the program file with open(data, "r") as file: data = file.read() data = to_base64_string(data) if metadata: metadata = self._read_metadata(metadata=metadata) combined_metadata = self._merge_metadata( metadata=metadata, name=name, description=description, max_execution_time=max_execution_time, spec=spec) try: self._api_client.program_update( program_id, program_data=data, **combined_metadata) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeProgramNotFound(f"Program not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to update program: {ex}") from None if program_id in self._programs: program = self._programs[program_id] program._refresh() def _merge_metadata( self, metadata: Optional[Dict] = None, **kwargs: Any ) -> Dict: """Merge multiple copies of metadata. Args: metadata: Program metadata. **kwargs: Additional metadata fields to overwrite. Returns: Merged metadata. """ merged = {} metadata = metadata or {} metadata_keys = ['name', 'max_execution_time', 'description', 'spec'] for key in metadata_keys: if kwargs.get(key, None) is not None: merged[key] = kwargs[key] elif key in metadata.keys(): merged[key] = metadata[key] return merged def delete_program(self, program_id: str) -> None: """Delete a runtime program. Args: program_id: Program ID. Raises: RuntimeProgramNotFound: If the program doesn't exist. QiskitRuntimeError: If the request failed. """ try: self._api_client.program_delete(program_id=program_id) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeProgramNotFound(f"Program not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to delete program: {ex}") from None if program_id in self._programs: del self._programs[program_id] def set_program_visibility(self, program_id: str, public: bool) -> None: """Sets a program's visibility. Args: program_id: Program ID. public: If ``True``, make the program visible to all. If ``False``, make the program visible to just your account. Raises: RuntimeJobNotFound: if program not found (404) QiskitRuntimeError: if update failed (401, 403) """ try: self._api_client.set_program_visibility(program_id, public) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeJobNotFound(f"Program not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to set program visibility: {ex}") from None if program_id in self._programs: program = self._programs[program_id] program._is_public = public def job(self, job_id: str) -> RuntimeJob: """Retrieve a runtime job. Args: job_id: Job ID. Returns: Runtime job retrieved. Raises: RuntimeJobNotFound: If the job doesn't exist. QiskitRuntimeError: If the request failed. """ try: response = self._api_client.job_get(job_id) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeJobNotFound(f"Job not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to delete job: {ex}") from None return self._decode_job(response) def jobs( self, limit: Optional[int] = 10, skip: int = 0, pending: bool = None, program_id: str = None ) -> List[RuntimeJob]: """Retrieve all runtime jobs, subject to optional filtering. Args: limit: Number of jobs to retrieve. ``None`` means no limit. skip: Starting index for the job retrieval. pending: Filter by job pending state. If ``True``, 'QUEUED' and 'RUNNING' jobs are included. If ``False``, 'DONE', 'CANCELLED' and 'ERROR' jobs are included. program_id: Filter by Program ID. Returns: A list of runtime jobs. """ job_responses = [] # type: List[Dict[str, Any]] current_page_limit = limit or 20 offset = skip while True: jobs_response = self._api_client.jobs_get( limit=current_page_limit, skip=offset, pending=pending, program_id=program_id) job_page = jobs_response["jobs"] # count is the total number of jobs that would be returned if # there was no limit or skip count = jobs_response["count"] job_responses += job_page if len(job_responses) == count - skip: # Stop if there are no more jobs returned by the server. break if limit: if len(job_responses) >= limit: # Stop if we have reached the limit. break current_page_limit = limit - len(job_responses) else: current_page_limit = 20 offset += len(job_page) return [self._decode_job(job) for job in job_responses] def delete_job(self, job_id: str) -> None: """Delete a runtime job. Note that this operation cannot be reversed. Args: job_id: ID of the job to delete. Raises: RuntimeJobNotFound: If the job doesn't exist. QiskitRuntimeError: If the request failed. """ try: self._api_client.job_delete(job_id) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeJobNotFound(f"Job not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to delete job: {ex}") from None def _decode_job(self, raw_data: Dict) -> RuntimeJob: """Decode job data received from the server. Args: raw_data: Raw job data received from the server. Returns: Decoded job data. """ hub = raw_data['hub'] group = raw_data['group'] project = raw_data['project'] if self._provider.credentials.unique_id().to_tuple() != (hub, group, project): # Try to find the right backend try: original_provider = self._provider._factory.get_provider(hub, group, project) backend = original_provider.get_backend(raw_data['backend']) except (IBMQProviderError, QiskitBackendNotFoundError): backend = IBMQRetiredBackend.from_name( backend_name=raw_data['backend'], provider=None, credentials=Credentials(token="", url="", hub=hub, group=group, project=project), api=None ) else: backend = self._provider.get_backend(raw_data['backend']) params = raw_data.get('params', {}) if isinstance(params, list): if len(params) > 0: params = params[0] else: params = {} if not isinstance(params, str): params = json.dumps(params) decoded = json.loads(params, cls=RuntimeDecoder) return RuntimeJob(backend=backend, api_client=self._api_client, credentials=self._provider.credentials, job_id=raw_data['id'], program_id=raw_data.get('program', {}).get('id', ""), params=decoded, creation_date=raw_data.get('created', None)) def logout(self) -> None: """Clears authorization cache on the server. For better performance, the runtime server caches each user's authorization information. This method is used to force the server to clear its cache. Note: Invoke this method ONLY when your access level to the runtime service has changed - for example, the first time your account is given the authority to upload a program. """ self._api_client.logout()
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 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. """Qiskit runtime program.""" import logging import re from typing import Optional, List, Dict from types import SimpleNamespace from qiskit.providers.ibmq.exceptions import IBMQInputValueError, IBMQNotAuthorizedError from .exceptions import QiskitRuntimeError, RuntimeProgramNotFound from ..api.clients.runtime import RuntimeClient from ..api.exceptions import RequestsApiError logger = logging.getLogger(__name__) class RuntimeProgram: """Class representing program metadata. This class contains the metadata describing a program, such as its name, ID, description, etc. You can use the :class:`~qiskit.providers.ibmq.runtime.IBMRuntimeService` to retrieve the metadata of a specific program or all programs. For example:: from qiskit import IBMQ provider = IBMQ.load_account() # To retrieve metadata of all programs. programs = provider.runtime.programs() # To retrieve metadata of a single program. program = provider.runtime.program(program_id='circuit-runner') print(f"Program {program.name} takes parameters {program.parameters().metadata}") """ def __init__( self, program_name: str, program_id: str, description: str, parameters: Optional[Dict] = None, return_values: Optional[Dict] = None, interim_results: Optional[Dict] = None, max_execution_time: int = 0, backend_requirements: Optional[Dict] = None, creation_date: str = "", update_date: str = "", is_public: Optional[bool] = False, data: str = "", api_client: Optional[RuntimeClient] = None ) -> None: """RuntimeProgram constructor. Args: program_name: Program name. program_id: Program ID. description: Program description. parameters: Documentation on program parameters. return_values: Documentation on program return values. interim_results: Documentation on program interim results. max_execution_time: Maximum execution time. backend_requirements: Backend requirements. creation_date: Program creation date. update_date: Program last updated date. is_public: ``True`` if program is visible to all. ``False`` if it's only visible to you. data: Program data. api_client: Runtime api client. """ self._name = program_name self._id = program_id self._description = description self._max_execution_time = max_execution_time self._backend_requirements = backend_requirements or {} self._parameters = parameters or {} self._return_values = return_values or {} self._interim_results = interim_results or {} self._creation_date = creation_date self._update_date = update_date self._is_public = is_public self._data = data self._api_client = api_client def __str__(self) -> str: def _format_common(schema: Dict) -> None: """Add title, description and property details to `formatted`.""" if "description" in schema: formatted.append(" "*4 + "Description: {}".format(schema["description"])) if "type" in schema: formatted.append(" "*4 + "Type: {}".format(str(schema["type"]))) if "properties" in schema: formatted.append(" "*4 + "Properties:") for property_name, property_value in schema["properties"].items(): formatted.append(" "*8 + "- " + property_name + ":") for key, value in property_value.items(): formatted.append(" "*12 + "{}: {}".format(sentence_case(key), str(value))) formatted.append(" "*12 + "Required: " + str(property_name in schema.get("required", []))) def sentence_case(camel_case_text: str) -> str: """Converts camelCase to Sentence case""" if camel_case_text == '': return camel_case_text sentence_case_text = re.sub('([A-Z])', r' \1', camel_case_text) return sentence_case_text[:1].upper() + sentence_case_text[1:].lower() formatted = [f'{self.program_id}:', f" Name: {self.name}", f" Description: {self.description}", f" Creation date: {self.creation_date}", f" Update date: {self.update_date}", f" Max execution time: {self.max_execution_time}"] formatted.append(" Input parameters:") if self._parameters: _format_common(self._parameters) else: formatted.append(" "*4 + "none") formatted.append(" Interim results:") if self._interim_results: _format_common(self._interim_results) else: formatted.append(" "*4 + "none") formatted.append(" Returns:") if self._return_values: _format_common(self._return_values) else: formatted.append(" "*4 + "none") return '\n'.join(formatted) def to_dict(self) -> Dict: """Convert program metadata to dictionary format. Returns: Program metadata in dictionary format. """ return { "program_id": self.program_id, "name": self.name, "description": self.description, "max_execution_time": self.max_execution_time, "backend_requirements": self.backend_requirements, "parameters": self.parameters(), "return_values": self.return_values, "interim_results": self.interim_results, "is_public": self._is_public } def parameters(self) -> 'ParameterNamespace': """Program parameter namespace. You can use the returned namespace to assign parameter values and pass the namespace to :meth:`qiskit.providers.ibmq.runtime.IBMRuntimeService.run`. The namespace allows you to use auto-completion to find program parameters. Note that each call to this method returns a new namespace instance and does not include any modification to the previous instance. Returns: Program parameter namespace. """ return ParameterNamespace(self._parameters) @property def program_id(self) -> str: """Program ID. Returns: Program ID. """ return self._id @property def name(self) -> str: """Program name. Returns: Program name. """ return self._name @property def description(self) -> str: """Program description. Returns: Program description. """ return self._description @property def return_values(self) -> Dict: """Program return value definitions. Returns: Return value definitions for this program. """ return self._return_values @property def interim_results(self) -> Dict: """Program interim result definitions. Returns: Interim result definitions for this program. """ return self._interim_results @property def max_execution_time(self) -> int: """Maximum execution time in seconds. A program execution exceeding this time will be forcibly terminated. Returns: Maximum execution time. """ return self._max_execution_time @property def backend_requirements(self) -> Dict: """Backend requirements. Returns: Backend requirements for this program. """ return self._backend_requirements @property def creation_date(self) -> str: """Program creation date. Returns: Program creation date. """ return self._creation_date @property def update_date(self) -> str: """Program last updated date. Returns: Program last updated date. """ return self._update_date @property def is_public(self) -> bool: """Whether the program is visible to all. Returns: Whether the program is public. """ return self._is_public @property def data(self) -> str: """Program data. Returns: Program data. Raises: IBMQNotAuthorizedError: if user is not the program author. """ if not self._data: self._refresh() if not self._data: raise IBMQNotAuthorizedError( 'Only program authors are authorized to retrieve program data') return self._data def _refresh(self) -> None: """Refresh program data and metadata Raises: RuntimeProgramNotFound: If the program does not exist. QiskitRuntimeError: If the request failed. """ try: response = self._api_client.program_get(self._id) except RequestsApiError as ex: if ex.status_code == 404: raise RuntimeProgramNotFound(f"Program not found: {ex.message}") from None raise QiskitRuntimeError(f"Failed to get program: {ex}") from None self._backend_requirements = {} self._parameters = {} self._return_values = {} self._interim_results = {} if "spec" in response: self._backend_requirements = response["spec"].get('backend_requirements', {}) self._parameters = response["spec"].get('parameters', {}) self._return_values = response["spec"].get('return_values', {}) self._interim_results = response["spec"].get('interim_results', {}) self._name = response['name'] self._id = response['id'] self._description = response.get('description', "") self._max_execution_time = response.get('cost', 0) self._creation_date = response.get('creation_date', "") self._update_date = response.get('update_date', "") self._is_public = response.get('is_public', False) self._data = response.get('data', "") class ParameterNamespace(SimpleNamespace): """ A namespace for program parameters with validation. This class provides a namespace for program parameters with auto-completion and validation support. """ def __init__(self, parameters: Dict): """ParameterNamespace constructor. Args: parameters: The program's input parameters. """ super().__init__() # Allow access to the raw program parameters dict self.__metadata = parameters # For localized logic, create store of parameters in dictionary self.__program_params: dict = {} for parameter_name, parameter_value in parameters.get("properties", {}).items(): # (1) Add parameters to a dict by name setattr(self, parameter_name, None) # (2) Store the program params for validation self.__program_params[parameter_name] = parameter_value @property def metadata(self) -> Dict: """Returns the parameter metadata""" return self.__metadata def validate(self) -> None: """Validate program input values. Note: This method only verifies that required parameters have values. It does not fail the validation if the namespace has extraneous parameters. Raises: IBMQInputValueError: if validation fails """ # Iterate through the user's stored inputs for parameter_name, parameter_value in self.__program_params.items(): # Set invariants: User-specified parameter value (value) and if it's required (req) value = getattr(self, parameter_name, None) # Check there exists a program parameter of that name. if value is None and parameter_name in self.metadata.get("required", []): raise IBMQInputValueError('Param (%s) missing required value!' % parameter_name) def __str__(self) -> str: """Creates string representation of object""" # Header header = '| {:10.10} | {:12.12} | {:12.12} ' \ '| {:8.8} | {:>15} |'.format( 'Name', 'Value', 'Type', 'Required', 'Description' ) params_str = '\n'.join([ '| {:10.10} | {:12.12} | {:12.12}| {:8.8} | {:>15} |'.format( parameter_name, str(getattr(self, parameter_name, "None")), str(parameter_value.get("type", "None")), str(parameter_name in self.metadata.get("required", [])), str(parameter_value.get("description", "None")) ) for parameter_name, parameter_value in self.__program_params.items()]) return "ParameterNamespace (Values):\n%s\n%s\n%s" \ % (header, '-' * len(header), params_str)
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # 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=invalid-name """Interactive error map for IBM Quantum Experience devices.""" import math from typing import Tuple, Union import numpy as np from plotly.subplots import make_subplots import plotly.graph_objects as go import matplotlib as mpl from qiskit.providers.ibmq.ibmqbackend import IBMQBackend from .plotly_wrapper import PlotlyWidget, PlotlyFigure from ..device_layouts import DEVICE_LAYOUTS from ..colormaps import (HELIX_LIGHT, HELIX_LIGHT_CMAP, HELIX_DARK, HELIX_DARK_CMAP) from ..exceptions import VisualizationValueError, VisualizationTypeError def iplot_error_map( backend: IBMQBackend, figsize: Tuple[int] = (800, 500), show_title: bool = True, remove_badcal_edges: bool = True, background_color: str = 'white', as_widget: bool = False ) -> Union[PlotlyFigure, PlotlyWidget]: """Plot the error map of a device. Args: backend: Plot the error map for this backend. figsize: Figure size in pixels. show_title: Whether to show figure title. remove_badcal_edges: Whether to remove bad CX gate calibration data. background_color: Background color, either 'white' or 'black'. as_widget: ``True`` if the figure is to be returned as a ``PlotlyWidget``. Otherwise the figure is to be returned as a ``PlotlyFigure``. Returns: The error map figure. Raises: VisualizationValueError: If an invalid input is received. VisualizationTypeError: If the specified `backend` is a simulator. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import IBMQ from qiskit.providers.ibmq.visualization import iplot_error_map IBMQ.load_account() provider = IBMQ.get_provider(group='open', project='main') backend = provider.get_backend('ibmq_vigo') iplot_error_map(backend, as_widget=True) """ meas_text_color = '#000000' if background_color == 'white': color_map = HELIX_LIGHT_CMAP text_color = '#000000' plotly_cmap = HELIX_LIGHT elif background_color == 'black': color_map = HELIX_DARK_CMAP text_color = '#FFFFFF' plotly_cmap = HELIX_DARK else: raise VisualizationValueError( '"{}" is not a valid background_color selection.'.format(background_color)) if backend.configuration().simulator: raise VisualizationTypeError('Requires a device backend, not a simulator.') config = backend.configuration() n_qubits = config.n_qubits cmap = config.coupling_map if n_qubits in DEVICE_LAYOUTS.keys(): grid_data = DEVICE_LAYOUTS[n_qubits] else: fig = go.Figure() fig.update_layout(showlegend=False, plot_bgcolor=background_color, paper_bgcolor=background_color, width=figsize[0], height=figsize[1], margin=dict(t=60, l=0, r=0, b=0) ) out = PlotlyWidget(fig) return out props = backend.properties().to_dict() t1s = [] t2s = [] for qubit_props in props['qubits']: count = 0 for item in qubit_props: if item['name'] == 'T1': t1s.append(item['value']) count += 1 elif item['name'] == 'T2': t2s.append(item['value']) count += 1 if count == 2: break # U2 error rates single_gate_errors = [0]*n_qubits for gate in props['gates']: if gate['gate'] == 'u2': _qubit = gate['qubits'][0] single_gate_errors[_qubit] = gate['parameters'][0]['value'] # Convert to percent single_gate_errors = 100 * np.asarray(single_gate_errors) avg_1q_err = np.mean(single_gate_errors) max_1q_err = max(single_gate_errors) single_norm = mpl.colors.Normalize( vmin=min(single_gate_errors), vmax=max_1q_err) q_colors = [mpl.colors.rgb2hex(color_map(single_norm(err))) for err in single_gate_errors] line_colors = [] cx_idx = [] if n_qubits > 1 and cmap: cx_errors = [] for cmap_qubits in cmap: for gate in props['gates']: if gate['qubits'] == cmap_qubits: cx_errors.append(gate['parameters'][0]['value']) break else: continue # Convert to percent cx_errors = 100 * np.asarray(cx_errors) # remove bad cx edges if remove_badcal_edges: cx_idx = np.where(cx_errors != 100.0)[0] else: cx_idx = np.arange(len(cx_errors)) avg_cx_err = np.mean(cx_errors[cx_idx]) for err in cx_errors: if err != 100.0 or not remove_badcal_edges: cx_norm = mpl.colors.Normalize( vmin=min(cx_errors[cx_idx]), vmax=max(cx_errors[cx_idx])) line_colors.append(mpl.colors.rgb2hex(color_map(cx_norm(err)))) else: line_colors.append("#ff0000") # Measurement errors read_err = [] for qubit in range(n_qubits): for item in props['qubits'][qubit]: if item['name'] == 'readout_error': read_err.append(item['value']) read_err = 100 * np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) if n_qubits < 10: num_left = n_qubits num_right = 0 else: num_left = math.ceil(n_qubits / 2) num_right = n_qubits - num_left x_max = max([d[1] for d in grid_data]) y_max = max([d[0] for d in grid_data]) max_dim = max(x_max, y_max) qubit_size = 32 font_size = 14 offset = 0 if cmap: if y_max / max_dim < 0.33: qubit_size = 24 font_size = 10 offset = 1 if n_qubits > 5: right_meas_title = "Readout Error (%)" else: right_meas_title = None if cmap and cx_idx.size > 0: cx_title = "CNOT Error Rate [Avg. {}%]".format(np.round(avg_cx_err, 3)) else: cx_title = None fig = make_subplots(rows=2, cols=11, row_heights=[0.95, 0.05], vertical_spacing=0.15, specs=[[{"colspan": 2}, None, {"colspan": 6}, None, None, None, None, None, {"colspan": 2}, None, None], [{"colspan": 4}, None, None, None, None, None, {"colspan": 4}, None, None, None, None]], subplot_titles=("Readout Error (%)", None, right_meas_title, "Hadamard Error Rate [Avg. {}%]".format( np.round(avg_1q_err, 3)), cx_title) ) # Add lines for couplings if cmap and n_qubits > 1 and cx_idx.size > 0: for ind, edge in enumerate(cmap): is_symmetric = False if edge[::-1] in cmap: is_symmetric = True y_start = grid_data[edge[0]][0] + offset x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] + offset x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start x_mid = x_end y_mid = y_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start x_mid = x_start y_mid = y_end else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start x_mid = x_end y_mid = y_end else: if y_start == y_end: x_mid = (x_end - x_start) / 2 + x_start y_mid = y_end elif x_start == x_end: x_mid = x_end y_mid = (y_end - y_start) / 2 + y_start else: x_mid = (x_end - x_start) / 2 + x_start y_mid = (y_end - y_start) / 2 + y_start fig.add_trace( go.Scatter(x=[x_start, x_mid, x_end], y=[-y_start, -y_mid, -y_end], mode="lines", line=dict(width=6, color=line_colors[ind]), hoverinfo='text', hovertext='CX<sub>err</sub>{B}_{A} = {err} %'.format( A=edge[0], B=edge[1], err=np.round(cx_errors[ind], 3)) ), row=1, col=3) # Add the qubits themselves qubit_text = [] qubit_str = "<b>Qubit {}</b><br>H<sub>err</sub> = {} %" qubit_str += "<br>T1 = {} \u03BCs<br>T2 = {} \u03BCs" for kk in range(n_qubits): qubit_text.append(qubit_str.format(kk, np.round(single_gate_errors[kk], 3), np.round(t1s[kk], 2), np.round(t2s[kk], 2))) if n_qubits > 20: qubit_size = 23 font_size = 11 if n_qubits > 50: qubit_size = 20 font_size = 9 qtext_color = [] for ii in range(n_qubits): if background_color == 'black': if single_gate_errors[ii] > 0.8*max_1q_err: qtext_color.append('black') else: qtext_color.append('white') else: qtext_color.append('white') fig.add_trace(go.Scatter( x=[d[1] for d in grid_data], y=[-d[0]-offset for d in grid_data], mode="markers+text", marker=go.scatter.Marker(size=qubit_size, color=q_colors, opacity=1), text=[str(ii) for ii in range(n_qubits)], textposition="middle center", textfont=dict(size=font_size, color=qtext_color), hoverinfo="text", hovertext=qubit_text), row=1, col=3) fig.update_xaxes(row=1, col=3, visible=False) _range = None if offset: _range = [-3.5, 0.5] fig.update_yaxes(row=1, col=3, visible=False, range=_range) # H error rate colorbar min_1q_err = min(single_gate_errors) max_1q_err = max(single_gate_errors) if n_qubits > 1: fig.add_trace(go.Heatmap(z=[np.linspace(min_1q_err, max_1q_err, 100), np.linspace(min_1q_err, max_1q_err, 100)], colorscale=plotly_cmap, showscale=False, hoverinfo='none'), row=2, col=1) fig.update_yaxes(row=2, col=1, visible=False) fig.update_xaxes(row=2, col=1, tickvals=[0, 49, 99], ticktext=[np.round(min_1q_err, 3), np.round((max_1q_err-min_1q_err)/2+min_1q_err, 3), np.round(max_1q_err, 3)]) # CX error rate colorbar if cmap and n_qubits > 1 and cx_idx.size > 0: min_cx_err = min(cx_errors) max_cx_err = max(cx_errors) if min_cx_err == max_cx_err: min_cx_err = 0 # Force more than 1 color. fig.add_trace(go.Heatmap(z=[np.linspace(min_cx_err, max_cx_err, 100), np.linspace(min_cx_err, max_cx_err, 100)], colorscale=plotly_cmap, showscale=False, hoverinfo='none'), row=2, col=7) fig.update_yaxes(row=2, col=7, visible=False) min_cx_idx_err = min(cx_errors[cx_idx]) max_cx_idx_err = max(cx_errors[cx_idx]) fig.update_xaxes(row=2, col=7, tickvals=[0, 49, 99], ticktext=[np.round(min_cx_idx_err, 3), np.round((max_cx_idx_err-min_cx_idx_err)/2+min_cx_idx_err, 3), np.round(max_cx_idx_err, 3)]) hover_text = "<b>Qubit {}</b><br>M<sub>err</sub> = {} %" # Add the left side meas errors for kk in range(num_left-1, -1, -1): fig.add_trace(go.Bar(x=[read_err[kk]], y=[kk], orientation='h', marker=dict(color='#eedccb'), hoverinfo="text", hoverlabel=dict(font=dict(color=meas_text_color)), hovertext=[hover_text.format(kk, np.round(read_err[kk], 3) )] ), row=1, col=1) fig.add_trace(go.Scatter(x=[avg_read_err, avg_read_err], y=[-0.25, num_left-1+0.25], mode='lines', hoverinfo='none', line=dict(color=text_color, width=2, dash='dot')), row=1, col=1) fig.update_yaxes(row=1, col=1, tickvals=list(range(num_left)), autorange="reversed") fig.update_xaxes(row=1, col=1, range=[0, 1.1*max_read_err], tickvals=[0, np.round(avg_read_err, 2), np.round(max_read_err, 2)], showline=True, linewidth=1, linecolor=text_color, tickcolor=text_color, ticks="outside", showgrid=False, zeroline=False) # Add the right side meas errors, if any if num_right: for kk in range(n_qubits-1, num_left-1, -1): fig.add_trace(go.Bar(x=[-read_err[kk]], y=[kk], orientation='h', marker=dict(color='#eedccb'), hoverinfo="text", hoverlabel=dict(font=dict(color=meas_text_color)), hovertext=[hover_text.format(kk, np.round(read_err[kk], 3))] ), row=1, col=9) fig.add_trace(go.Scatter(x=[-avg_read_err, -avg_read_err], y=[num_left-0.25, n_qubits-1+0.25], mode='lines', hoverinfo='none', line=dict(color=text_color, width=2, dash='dot') ), row=1, col=9) fig.update_yaxes(row=1, col=9, tickvals=list(range(n_qubits-1, num_left-1, -1)), side='right', autorange="reversed", ) fig.update_xaxes(row=1, col=9, range=[-1.1*max_read_err, 0], tickvals=[0, -np.round(avg_read_err, 2), -np.round(max_read_err, 2)], ticktext=[0, np.round(avg_read_err, 2), np.round(max_read_err, 2)], showline=True, linewidth=1, linecolor=text_color, tickcolor=text_color, ticks="outside", showgrid=False, zeroline=False) # Makes the subplot titles smaller than the 16pt default for ann in fig['layout']['annotations']: ann['font'] = dict(size=13) title_text = "{} Error Map".format(backend.name()) if show_title else '' fig.update_layout(showlegend=False, plot_bgcolor=background_color, paper_bgcolor=background_color, width=figsize[0], height=figsize[1], title=dict(text=title_text, x=0.452), title_font_size=20, font=dict(color=text_color), margin=dict(t=60, l=0, r=40, b=0) ) if as_widget: return PlotlyWidget(fig) return PlotlyFigure(fig)
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # 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. """A module for visualizing device coupling maps.""" import math from typing import List import numpy as np from qiskit.exceptions import MissingOptionalLibraryError, QiskitError from qiskit.providers.backend import BackendV2 from qiskit.tools.visualization import HAS_MATPLOTLIB, VisualizationError from qiskit.visualization.utils import matplotlib_close_if_inline def plot_gate_map( backend, figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, qubit_coordinates=None, ): """Plots the gate map of a device. Args: backend (BaseBackend): The backend instance that will be used to plot the device gate map. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: QiskitError: if tried to pass a simulator, or if the backend is None, but one of num_qubits, mpl_data, or cmap is None. MissingOptionalLibraryError: if matplotlib not installed. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_gate_map %matplotlib inline provider = IBMQ.load_account() accountProvider = IBMQ.get_provider(hub='ibm-q') backend = accountProvider.get_backend('ibmq_vigo') plot_gate_map(backend) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_gate_map", pip_install="pip install matplotlib", ) if isinstance(backend, BackendV2): pass elif backend.configuration().simulator: raise QiskitError("Requires a device backend, not simulator.") qubit_coordinates_map = {} qubit_coordinates_map[1] = [[0, 0]] qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] qubit_coordinates_map[7] = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 1], [2, 2]] qubit_coordinates_map[20] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], ] qubit_coordinates_map[15] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], ] qubit_coordinates_map[16] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], ] qubit_coordinates_map[27] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], [3, 6], [0, 7], [1, 7], [3, 7], [4, 7], [1, 8], [3, 8], [1, 9], [2, 9], [3, 9], [3, 10], ] qubit_coordinates_map[28] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], ] qubit_coordinates_map[53] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [5, 2], [5, 6], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [7, 0], [7, 4], [7, 8], [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [9, 2], [9, 6], ] qubit_coordinates_map[65] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [1, 0], [1, 4], [1, 8], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 10], [3, 2], [3, 6], [3, 10], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10], [5, 0], [5, 4], [5, 8], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [6, 10], [7, 2], [7, 6], [7, 10], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10], ] if isinstance(backend, BackendV2): num_qubits = backend.num_qubits coupling_map = backend.plot_coupling_map else: config = backend.configuration() num_qubits = config.n_qubits coupling_map = config.coupling_map # don't reference dictionary if provided as a parameter if qubit_coordinates is None: qubit_coordinates = qubit_coordinates_map.get(num_qubits) # try to adjust num_qubits to match the next highest hardcoded grid size if qubit_coordinates is None: if any([num_qubits < key for key in qubit_coordinates_map.keys()]): num_qubits_roundup = max(qubit_coordinates_map.keys()) for key in qubit_coordinates_map.keys(): if key < num_qubits_roundup and key > num_qubits: num_qubits_roundup = key qubit_coordinates = qubit_coordinates_map.get(num_qubits_roundup) return plot_coupling_map( num_qubits, qubit_coordinates, coupling_map, figsize, plot_directed, label_qubits, qubit_size, line_width, font_size, qubit_color, qubit_labels, line_color, font_color, ax, filename, ) def plot_coupling_map( num_qubits: int, qubit_coordinates: List[List[int]], coupling_map: List[List[int]], figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, ): """Plots an arbitrary coupling map of qubits (embedded in a plane). Args: num_qubits (int): The number of qubits defined and plotted. qubit_coordinates (List[List[int]]): A list of two-element lists, with entries of each nested list being the planar coordinates in a 0-based square grid where each qubit is located. coupling_map (List[List[int]]): A list of two-element lists, with entries of each nested list being the qubit numbers of the bonds to be plotted. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: MissingOptionalLibraryError: if matplotlib not installed. QiskitError: If length of qubit labels does not match number of qubits. Example: .. jupyter-execute:: from qiskit.visualization import plot_coupling_map %matplotlib inline num_qubits = 8 coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] plot_coupling_map(num_qubits, coupling_map, qubit_coordinates) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_coupling_map", pip_install="pip install matplotlib", ) import matplotlib.patches as mpatches import matplotlib.pyplot as plt input_axes = False if ax: input_axes = True if font_size is None: font_size = 12 if qubit_size is None: qubit_size = 24 if num_qubits > 20: qubit_size = 28 font_size = 10 if qubit_labels is None: qubit_labels = list(range(num_qubits)) else: if len(qubit_labels) != num_qubits: raise QiskitError("Length of qubit labels does not equal number of qubits.") if qubit_coordinates is not None: grid_data = qubit_coordinates else: if not input_axes: fig, ax = plt.subplots(figsize=(5, 5)) ax.axis("off") if filename: fig.savefig(filename) return fig x_max = max(d[1] for d in grid_data) y_max = max(d[0] for d in grid_data) max_dim = max(x_max, y_max) if figsize is None: if num_qubits == 1 or (x_max / max_dim > 0.33 and y_max / max_dim > 0.33): figsize = (5, 5) else: figsize = (9, 3) if ax is None: fig, ax = plt.subplots(figsize=figsize) ax.axis("off") # set coloring if qubit_color is None: qubit_color = ["#648fff"] * num_qubits if line_color is None: line_color = ["#648fff"] * len(coupling_map) if coupling_map else [] # Add lines for couplings if num_qubits != 1: for ind, edge in enumerate(coupling_map): is_symmetric = False if edge[::-1] in coupling_map: is_symmetric = True y_start = grid_data[edge[0]][0] x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start ax.add_artist( plt.Line2D( [x_start, x_end], [-y_start, -y_end], color=line_color[ind], linewidth=line_width, zorder=0, ) ) if plot_directed: dx = x_end - x_start dy = y_end - y_start if is_symmetric: x_arrow = x_start + dx * 0.95 y_arrow = -y_start - dy * 0.95 dx_arrow = dx * 0.01 dy_arrow = -dy * 0.01 head_width = 0.15 else: x_arrow = x_start + dx * 0.5 y_arrow = -y_start - dy * 0.5 dx_arrow = dx * 0.2 dy_arrow = -dy * 0.2 head_width = 0.2 ax.add_patch( mpatches.FancyArrow( x_arrow, y_arrow, dx_arrow, dy_arrow, head_width=head_width, length_includes_head=True, edgecolor=None, linewidth=0, facecolor=line_color[ind], zorder=1, ) ) # Add circles for qubits for var, idx in enumerate(grid_data): # add check if num_qubits had been rounded up if var >= num_qubits: break _idx = [idx[1], -idx[0]] ax.add_artist( mpatches.Ellipse( _idx, qubit_size / 48, qubit_size / 48, # This is here so that the changes color=qubit_color[var], zorder=1, ) ) # to how qubits are plotted does if label_qubits: # not affect qubit size kwarg. ax.text( *_idx, s=qubit_labels[var], horizontalalignment="center", verticalalignment="center", color=font_color, size=font_size, weight="bold", ) ax.set_xlim([-1, x_max + 1]) ax.set_ylim([-(y_max + 1), 1]) ax.set_aspect("equal") if not input_axes: matplotlib_close_if_inline(fig) if filename: fig.savefig(filename) return fig return None def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None): """Plot the layout of a circuit transpiled for a given target backend. Args: circuit (QuantumCircuit): Input quantum circuit. backend (BaseBackend): Target backend. view (str): Layout view: either 'virtual' or 'physical'. Returns: Figure: A matplotlib figure showing layout. Raises: QiskitError: Invalid view type given. VisualizationError: Circuit has no layout attribute. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: import numpy as np from qiskit import QuantumCircuit, IBMQ, transpile from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt %matplotlib inline IBMQ.load_account() ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend) """ if circuit._layout is None: raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.") if isinstance(backend, BackendV2): num_qubits = backend.num_qubits else: num_qubits = backend.configuration().n_qubits qubits = [] qubit_labels = [None] * num_qubits bit_locations = { bit: {"register": register, "index": index} for register in circuit._layout.get_registers() for index, bit in enumerate(register) } for index, qubit in enumerate(circuit._layout.get_virtual_bits()): if qubit not in bit_locations: bit_locations[qubit] = {"register": None, "index": index} if view == "virtual": for key, val in circuit._layout.get_virtual_bits().items(): bit_register = bit_locations[key]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(val) qubit_labels[val] = bit_locations[key]["index"] elif view == "physical": for key, val in circuit._layout.get_physical_bits().items(): bit_register = bit_locations[val]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(key) qubit_labels[key] = key else: raise VisualizationError("Layout view must be 'virtual' or 'physical'.") qcolors = ["#648fff"] * num_qubits for k in qubits: qcolors[k] = "k" if isinstance(backend, BackendV2): cmap = backend.plot_coupling_map else: cmap = backend.configuration().coupling_map lcolors = ["#648fff"] * len(cmap) for idx, edge in enumerate(cmap): if edge[0] in qubits and edge[1] in qubits: lcolors[idx] = "k" fig = plot_gate_map( backend, qubit_color=qcolors, qubit_labels=qubit_labels, line_color=lcolors, qubit_coordinates=qubit_coordinates, ) return fig def plot_error_map(backend, figsize=(12, 9), show_title=True): """Plots the error map of a given backend. Args: backend (IBMQBackend): Given backend. figsize (tuple): Figure size in inches. show_title (bool): Show the title or not. Returns: Figure: A matplotlib figure showing error map. Raises: VisualizationError: Input is not IBMQ backend. VisualizationError: The backend does not provide gate errors for the 'sx' gate. MissingOptionalLibraryError: If seaborn is not installed Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_error_map %matplotlib inline IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') plot_error_map(backend) """ try: import seaborn as sns except ImportError as ex: raise MissingOptionalLibraryError( libname="seaborn", name="plot_error_map", pip_install="pip install seaborn", ) from ex if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_error_map", pip_install="pip install matplotlib", ) import matplotlib import matplotlib.pyplot as plt from matplotlib import gridspec, ticker color_map = sns.cubehelix_palette(reverse=True, as_cmap=True) props = backend.properties().to_dict() config = backend.configuration().to_dict() num_qubits = config["n_qubits"] # sx error rates single_gate_errors = [0] * num_qubits for gate in props["gates"]: if gate["gate"] == "sx": _qubit = gate["qubits"][0] for param in gate["parameters"]: if param["name"] == "gate_error": single_gate_errors[_qubit] = param["value"] break else: raise VisualizationError( f"Backend '{backend}' did not supply an error for the 'sx' gate." ) # Convert to percent single_gate_errors = 100 * np.asarray(single_gate_errors) avg_1q_err = np.mean(single_gate_errors) single_norm = matplotlib.colors.Normalize( vmin=min(single_gate_errors), vmax=max(single_gate_errors) ) q_colors = [color_map(single_norm(err)) for err in single_gate_errors] cmap = config["coupling_map"] directed = False line_colors = [] if cmap: directed = False if num_qubits < 20: for edge in cmap: if [edge[1], edge[0]] not in cmap: directed = True break cx_errors = [] for line in cmap: for item in props["gates"]: if item["qubits"] == line: cx_errors.append(item["parameters"][0]["value"]) break else: continue # Convert to percent cx_errors = 100 * np.asarray(cx_errors) avg_cx_err = np.mean(cx_errors) cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors), vmax=max(cx_errors)) line_colors = [color_map(cx_norm(err)) for err in cx_errors] # Measurement errors read_err = [] for qubit in range(num_qubits): for item in props["qubits"][qubit]: if item["name"] == "readout_error": read_err.append(item["value"]) read_err = 100 * np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) fig = plt.figure(figsize=figsize) gridspec.GridSpec(nrows=2, ncols=3) grid_spec = gridspec.GridSpec( 12, 12, height_ratios=[1] * 11 + [0.5], width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2], ) left_ax = plt.subplot(grid_spec[2:10, :1]) main_ax = plt.subplot(grid_spec[:11, 1:11]) right_ax = plt.subplot(grid_spec[2:10, 11:]) bleft_ax = plt.subplot(grid_spec[-1, :5]) if cmap: bright_ax = plt.subplot(grid_spec[-1, 7:]) qubit_size = 28 if num_qubits <= 5: qubit_size = 20 plot_gate_map( backend, qubit_color=q_colors, line_color=line_colors, qubit_size=qubit_size, line_width=5, plot_directed=directed, ax=main_ax, ) main_ax.axis("off") main_ax.set_aspect(1) if cmap: single_cb = matplotlib.colorbar.ColorbarBase( bleft_ax, cmap=color_map, norm=single_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) single_cb.locator = tick_locator single_cb.update_ticks() single_cb.update_ticks() bleft_ax.set_title(f"H error rate (%) [Avg. = {round(avg_1q_err, 3)}]") if cmap is None: bleft_ax.axis("off") bleft_ax.set_title(f"H error rate (%) = {round(avg_1q_err, 3)}") if cmap: cx_cb = matplotlib.colorbar.ColorbarBase( bright_ax, cmap=color_map, norm=cx_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) cx_cb.locator = tick_locator cx_cb.update_ticks() bright_ax.set_title(f"CNOT error rate (%) [Avg. = {round(avg_cx_err, 3)}]") if num_qubits < 10: num_left = num_qubits num_right = 0 else: num_left = math.ceil(num_qubits / 2) num_right = num_qubits - num_left left_ax.barh(range(num_left), read_err[:num_left], align="center", color="#DDBBBA") left_ax.axvline(avg_read_err, linestyle="--", color="#212121") left_ax.set_yticks(range(num_left)) left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12) left_ax.invert_yaxis() left_ax.set_title("Readout Error (%)", fontsize=12) for spine in left_ax.spines.values(): spine.set_visible(False) if num_right: right_ax.barh( range(num_left, num_qubits), read_err[num_left:], align="center", color="#DDBBBA", ) right_ax.axvline(avg_read_err, linestyle="--", color="#212121") right_ax.set_yticks(range(num_left, num_qubits)) right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) right_ax.set_yticklabels( [str(kk) for kk in range(num_left, num_qubits)], fontsize=12 ) right_ax.invert_yaxis() right_ax.invert_xaxis() right_ax.yaxis.set_label_position("right") right_ax.yaxis.tick_right() right_ax.set_title("Readout Error (%)", fontsize=12) else: right_ax.axis("off") for spine in right_ax.spines.values(): spine.set_visible(False) if show_title: fig.suptitle(f"{backend.name()} Error Map", fontsize=24, y=0.9) matplotlib_close_if_inline(fig) return fig
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# -*- 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/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 2022. # # 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. """A swap strategy pass for blocks of commuting gates.""" from __future__ import annotations from collections import defaultdict from qiskit.circuit import Gate, QuantumCircuit, Qubit from qiskit.converters import circuit_to_dag from qiskit.dagcircuit import DAGCircuit, DAGOpNode from qiskit.transpiler import TransformationPass, Layout, TranspilerError from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.swap_strategy import SwapStrategy from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.commuting_2q_block import ( Commuting2qBlock, ) class Commuting2qGateRouter(TransformationPass): """A class to swap route one or more commuting gates to the coupling map. This pass routes blocks of commuting two-qubit gates encapsulated as :class:`.Commuting2qBlock` instructions. This pass will not apply to other instructions. The mapping to the coupling map is done using swap strategies, see :class:`.SwapStrategy`. The swap strategy should suit the problem and the coupling map. This transpiler pass should ideally be executed before the quantum circuit is enlarged with any idle ancilla qubits. Otherwise we may swap qubits outside of the portion of the chip we want to use. Therefore, the swap strategy and its associated coupling map do not represent physical qubits. Instead, they represent an intermediate mapping that corresponds to the physical qubits once the initial layout is applied. The example below shows how to map a four qubit :class:`.PauliEvolutionGate` to qubits 0, 1, 3, and 4 of the five qubit device with the coupling map .. parsed-literal:: 0 -- 1 -- 2 | 3 | 4 To do this we use a line swap strategy for qubits 0, 1, 3, and 4 defined it in terms of virtual qubits 0, 1, 2, and 3. .. code-block:: python from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.transpiler import Layout, CouplingMap, PassManager from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import ApplyLayout from qiskit.transpiler.passes import SetLayout from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import ( SwapStrategy, FindCommutingPauliEvolutions, Commuting2qGateRouter, ) # Define the circuit on virtual qubits op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) # Define the swap strategy on qubits before the initial_layout is applied. swap_strat = SwapStrategy.from_line([0, 1, 2, 3]) # Chose qubits 0, 1, 3, and 4 from the backend coupling map shown above. backend_cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (1, 3), (3, 4)]) initial_layout = Layout.from_intlist([0, 1, 3, 4], *circ.qregs) pm_pre = PassManager( [ FindCommutingPauliEvolutions(), Commuting2qGateRouter(swap_strat), SetLayout(initial_layout), FullAncillaAllocation(backend_cmap), EnlargeWithAncilla(), ApplyLayout(), ] ) # Insert swap gates, map to initial_layout and finally enlarge with ancilla. pm_pre.run(circ).draw("mpl") This pass manager relies on the ``current_layout`` which corresponds to the qubit layout as swap gates are applied. The pass will traverse all nodes in the dag. If a node should be routed using a swap strategy then it will be decomposed into sub-instructions with swap layers in between and the ``current_layout`` will be modified. Nodes that should not be routed using swap strategies will be added back to the dag taking the ``current_layout`` into account. """ def __init__( self, swap_strategy: SwapStrategy | None = None, edge_coloring: dict[tuple[int, int], int] | None = None, ) -> None: r""" Args: swap_strategy: An instance of a :class:`.SwapStrategy` that holds the swap layers that are used, and the order in which to apply them, to map the instruction to the hardware. If this field is not given if should be contained in the property set of the pass. This allows other passes to determine the most appropriate swap strategy at run-time. edge_coloring: An optional edge coloring of the coupling map (I.e. no two edges that share a node have the same color). If the edge coloring is given then the commuting gates that can be simultaneously applied given the current qubit permutation are grouped according to the edge coloring and applied according to this edge coloring. Here, a color is an int which is used as the index to define and access the groups of commuting gates that can be applied simultaneously. If the edge coloring is not given then the sets will be built-up using a greedy algorithm. The edge coloring is useful to position gates such as ``RZZGate``\s next to swap gates to exploit CX cancellations. """ super().__init__() self._swap_strategy = swap_strategy self._bit_indices: dict[Qubit, int] | None = None self._edge_coloring = edge_coloring def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the pass by decomposing the nodes it applies on. Args: dag: The dag to which we will add swaps. Returns: A dag where swaps have been added for the intended gate type. Raises: TranspilerError: If the swap strategy was not given at init time and there is no swap strategy in the property set. TranspilerError: If the quantum circuit contains more than one qubit register. TranspilerError: If there are qubits that are not contained in the quantum register. """ if self._swap_strategy is None: swap_strategy = self.property_set["swap_strategy"] if swap_strategy is None: raise TranspilerError("No swap strategy given at init or in the property set.") else: swap_strategy = self._swap_strategy if len(dag.qregs) != 1: raise TranspilerError( f"{self.__class__.__name__} runs on circuits with one quantum register." ) if len(dag.qubits) != next(iter(dag.qregs.values())).size: raise TranspilerError("Circuit has qubits not contained in the qubit register.") new_dag = dag.copy_empty_like() current_layout = Layout.generate_trivial_layout(*dag.qregs.values()) # Used to keep track of nodes that do not decompose using swap strategies. accumulator = new_dag.copy_empty_like() for node in dag.topological_op_nodes(): if isinstance(node.op, Commuting2qBlock): # Check that the swap strategy creates enough connectivity for the node. self._check_edges(dag, node, swap_strategy) # Compose any accumulated non-swap strategy gates to the dag accumulator = self._compose_non_swap_nodes(accumulator, current_layout, new_dag) # Decompose the swap-strategy node and add to the dag. new_dag.compose(self.swap_decompose(dag, node, current_layout, swap_strategy)) else: accumulator.apply_operation_back(node.op, node.qargs, node.cargs) self._compose_non_swap_nodes(accumulator, current_layout, new_dag) return new_dag def _compose_non_swap_nodes( self, accumulator: DAGCircuit, layout: Layout, new_dag: DAGCircuit ) -> DAGCircuit: """Add all the non-swap strategy nodes that we have accumulated up to now. This method also resets the node accumulator to an empty dag. Args: layout: The current layout that keeps track of the swaps. new_dag: The new dag that we are building up. accumulator: A DAG to keep track of nodes that do not decompose using swap strategies. Returns: A new accumulator with the same registers as ``new_dag``. """ # Add all the non-swap strategy nodes that we have accumulated up to now. order = layout.reorder_bits(new_dag.qubits) order_bits: list[int | None] = [None] * len(layout) for idx, val in enumerate(order): order_bits[val] = idx new_dag.compose(accumulator, qubits=order_bits) # Re-initialize the node accumulator return new_dag.copy_empty_like() def _position_in_cmap(self, dag: DAGCircuit, j: int, k: int, layout: Layout) -> tuple[int, ...]: """A helper function to track the movement of virtual qubits through the swaps. Args: j: The index of decision variable j (i.e. virtual qubit). k: The index of decision variable k (i.e. virtual qubit). layout: The current layout that takes into account previous swap gates. Returns: The position in the coupling map of the virtual qubits j and k as a tuple. """ bit0 = dag.find_bit(layout.get_physical_bits()[j]).index bit1 = dag.find_bit(layout.get_physical_bits()[k]).index return bit0, bit1 def _build_sub_layers( self, current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """A helper method to build-up sets of gates to simultaneously apply. This is done with an edge coloring if the ``edge_coloring`` init argument was given or with a greedy algorithm if not. With an edge coloring all gates on edges with the same color will be applied simultaneously. These sublayers are applied in the order of their color, which is an int, in increasing color order. Args: current_layer: All gates in the current layer can be applied given the qubit ordering of the current layout. However, not all gates in the current layer can be applied simultaneously. This function creates sub-layers by building up sub-layers of gates. All gates in a sub-layer can simultaneously be applied given the coupling map and current qubit configuration. Returns: A list of gate dicts that can be applied. The gates a position 0 are applied first. A gate dict has the qubit tuple as key and the gate to apply as value. """ if self._edge_coloring is not None: return self._edge_coloring_build_sub_layers(current_layer) else: return self._greedy_build_sub_layers(current_layer) def _edge_coloring_build_sub_layers( self, current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """The edge coloring method of building sub-layers of commuting gates.""" sub_layers: list[dict[tuple[int, int], Gate]] = [ {} for _ in set(self._edge_coloring.values()) ] for edge, gate in current_layer.items(): color = self._edge_coloring[edge] sub_layers[color][edge] = gate return sub_layers @staticmethod def _greedy_build_sub_layers( current_layer: dict[tuple[int, int], Gate] ) -> list[dict[tuple[int, int], Gate]]: """The greedy method of building sub-layers of commuting gates.""" sub_layers = [] while len(current_layer) > 0: current_sub_layer, remaining_gates = {}, {} blocked_vertices: set[tuple] = set() for edge, evo_gate in current_layer.items(): if blocked_vertices.isdisjoint(edge): current_sub_layer[edge] = evo_gate # A vertex becomes blocked once a gate is applied to it. blocked_vertices = blocked_vertices.union(edge) else: remaining_gates[edge] = evo_gate current_layer = remaining_gates sub_layers.append(current_sub_layer) return sub_layers def swap_decompose( self, dag: DAGCircuit, node: DAGOpNode, current_layout: Layout, swap_strategy: SwapStrategy ) -> DAGCircuit: """Take an instance of :class:`.Commuting2qBlock` and map it to the coupling map. The mapping is done with the swap strategy. Args: dag: The dag which contains the :class:`.Commuting2qBlock` we route. node: A node whose operation is a :class:`.Commuting2qBlock`. current_layout: The layout before the swaps are applied. This function will modify the layout so that subsequent gates can be properly composed on the dag. swap_strategy: The swap strategy used to decompose the node. Returns: A dag that is compatible with the coupling map where swap gates have been added to map the gates in the :class:`.Commuting2qBlock` to the hardware. """ trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) gate_layers = self._make_op_layers(dag, node.op, current_layout, swap_strategy) # Iterate over and apply gate layers max_distance = max(gate_layers.keys()) circuit_with_swap = QuantumCircuit(len(dag.qubits)) for i in range(max_distance + 1): # Get current layer and replace the problem indices j,k by the corresponding # positions in the coupling map. The current layer corresponds # to all the gates that can be applied at the ith swap layer. current_layer = {} for (j, k), local_gate in gate_layers.get(i, {}).items(): current_layer[self._position_in_cmap(dag, j, k, current_layout)] = local_gate # Not all gates that are applied at the ith swap layer can be applied at the same # time. We therefore greedily build sub-layers. sub_layers = self._build_sub_layers(current_layer) # Apply sub-layers for sublayer in sub_layers: for edge, local_gate in sublayer.items(): circuit_with_swap.append(local_gate, edge) # Apply SWAP gates if i < max_distance: for swap in swap_strategy.swap_layer(i): (j, k) = [trivial_layout.get_physical_bits()[vertex] for vertex in swap] circuit_with_swap.swap(j, k) current_layout.swap(j, k) return circuit_to_dag(circuit_with_swap) def _make_op_layers( self, dag: DAGCircuit, op: Commuting2qBlock, layout: Layout, swap_strategy: SwapStrategy ) -> dict[int, dict[tuple, Gate]]: """Creates layers of two-qubit gates based on the distance in the swap strategy.""" gate_layers: dict[int, dict[tuple, Gate]] = defaultdict(dict) for node in op.node_block: edge = (dag.find_bit(node.qargs[0]).index, dag.find_bit(node.qargs[1]).index) bit0 = layout.get_virtual_bits()[dag.qubits[edge[0]]] bit1 = layout.get_virtual_bits()[dag.qubits[edge[1]]] distance = swap_strategy.distance_matrix[bit0, bit1] gate_layers[distance][edge] = node.op return gate_layers def _check_edges(self, dag: DAGCircuit, node: DAGOpNode, swap_strategy: SwapStrategy): """Check if the swap strategy can create the required connectivity. Args: node: The dag node for which to check if the swap strategy provides enough connectivity. swap_strategy: The swap strategy that is being used. Raises: TranspilerError: If there is an edge that the swap strategy cannot accommodate and if the pass has been configured to raise on such issues. """ required_edges = set() for sub_node in node.op: edge = (dag.find_bit(sub_node.qargs[0]).index, dag.find_bit(sub_node.qargs[1]).index) required_edges.add(edge) # Check that the swap strategy supports all required edges if not required_edges.issubset(swap_strategy.possible_edges): raise TranspilerError( f"{swap_strategy} cannot implement all edges in {required_edges}." )
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# 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. """Remove all barriers in a circuit""" from qiskit.dagcircuit import DAGCircuit from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler.passes.utils import control_flow class RemoveBarriers(TransformationPass): """Return a circuit with any barrier removed. This transformation is not semantics preserving. Example: .. plot:: :include-source: from qiskit import QuantumCircuit from qiskit.transpiler.passes import RemoveBarriers circuit = QuantumCircuit(1) circuit.x(0) circuit.barrier() circuit.h(0) circuit = RemoveBarriers()(circuit) circuit.draw('mpl') """ @control_flow.trivial_recurse def run(self, dag: DAGCircuit) -> DAGCircuit: """Run the RemoveBarriers pass on `dag`.""" dag.remove_all_ops_named("barrier") return dag
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# This code is part of Qiskit. # # (C) Copyright IBM 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. """Base classes for an approximate circuit definition.""" from __future__ import annotations from abc import ABC, abstractmethod from typing import Optional, SupportsFloat import numpy as np from qiskit import QuantumCircuit class ApproximateCircuit(QuantumCircuit, ABC): """A base class that represents an approximate circuit.""" def __init__(self, num_qubits: int, name: Optional[str] = None) -> None: """ Args: num_qubits: number of qubit this circuit will span. name: a name of the circuit. """ super().__init__(num_qubits, name=name) @property @abstractmethod def thetas(self) -> np.ndarray: """ The property is not implemented and raises a ``NotImplementedException`` exception. Returns: a vector of parameters of this circuit. """ raise NotImplementedError @abstractmethod def build(self, thetas: np.ndarray) -> None: """ Constructs this circuit out of the parameters(thetas). Parameter values must be set before constructing the circuit. Args: thetas: a vector of parameters to be set in this circuit. """ raise NotImplementedError class ApproximatingObjective(ABC): """ A base class for an optimization problem definition. An implementing class must provide at least an implementation of the ``objective`` method. In such case only gradient free optimizers can be used. Both method, ``objective`` and ``gradient``, preferable to have in an implementation. """ def __init__(self) -> None: # must be set before optimization self._target_matrix: np.ndarray | None = None @abstractmethod def objective(self, param_values: np.ndarray) -> SupportsFloat: """ Computes a value of the objective function given a vector of parameter values. Args: param_values: a vector of parameter values for the optimization problem. Returns: a float value of the objective function. """ raise NotImplementedError @abstractmethod def gradient(self, param_values: np.ndarray) -> np.ndarray: """ Computes a gradient with respect to parameters given a vector of parameter values. Args: param_values: a vector of parameter values for the optimization problem. Returns: an array of gradient values. """ raise NotImplementedError @property def target_matrix(self) -> np.ndarray: """ Returns: a matrix being approximated """ return self._target_matrix @target_matrix.setter def target_matrix(self, target_matrix: np.ndarray) -> None: """ Args: target_matrix: a matrix to approximate in the optimization procedure. """ self._target_matrix = target_matrix @property @abstractmethod def num_thetas(self) -> int: """ Returns: the number of parameters in this optimization problem. """ raise NotImplementedError
https://github.com/jeevesh2002/QuantumKatasQiskit
jeevesh2002
# Run this cell using Ctrl+Enter (⌘+Enter on Mac). from testing import exercise from typing import Tuple import math Complex = Tuple[float, float] Polar = Tuple[float, float] @exercise def imaginary_power(n : int) -> int: # If n is divisible by 4 if n % 4 == 0: return ... else: return ... @exercise def complex_add(x : Complex, y : Complex) -> Complex: # You can extract elements from a tuple like this a = x[0] b = x[1] c = y[0] d = y[1] # This creates a new variable and stores the real component into it real = a + c # Replace the ... with code to calculate the imaginary component imaginary = ... # You can create a tuple like this ans = (real, imaginary) return ans @exercise def complex_mult(x : Complex, y : Complex) -> Complex: # Fill in your own code return ... @exercise def conjugate(x : Complex) -> Complex: return ... @exercise def complex_div(x : Complex, y : Complex) -> Complex: return ... @exercise def modulus(x : Complex) -> float: return ... @exercise def complex_exp(x : Complex) -> Complex: return ... @exercise def complex_exp_real(r : float, x : Complex) -> Complex: return ... @exercise def polar_convert(x : Complex) -> Polar: r = ... theta = ... return (r, theta) @exercise def cartesian_convert(x : Polar) -> Complex: return ... @exercise def polar_mult(x : Polar, y : Polar) -> Polar: return ... @exercise def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex: return ...
https://github.com/jeevesh2002/QuantumKatasQiskit
jeevesh2002
# Run this cell using Ctrl+Enter (⌘+Enter on Mac). from testing import exercise from typing import Tuple import math Complex = Tuple[float, float] Polar = Tuple[float, float] @exercise def imaginary_power(n : int) -> int: # If n is divisible by 4 if n % 4 == 0: return 1 else: return -1 @exercise def complex_add(x : Complex, y : Complex) -> Complex: # You can extract elements from a tuple like this a = x[0] b = x[1] c = y[0] d = y[1] # This creates a new variable and stores the real component into it real = a + c # Replace the ... with code to calculate the imaginary component imaginary = b + d # You can create a tuple like this, with the real and imaginary part of the number ans = (real, imaginary) return ans @exercise def complex_mult(x : Complex, y : Complex) -> Complex: # Here is another, more compact way of extracting the parts of the complex number: (a, b) = x (c, d) = y real = (a * c) - (b * d) imaginary = (a * d) + (c * b) # Instead of creating a separate tuple with the result, we return the tuple directly return (real, imaginary) @exercise def conjugate(x : Complex) -> Complex: real = x[0] # The sign can be easily flipped with the unary minus operator imaginary = - x[1] return (real, imaginary) @exercise def complex_div(x : Complex, y : Complex) -> Complex: (a, b) = x (c, d) = y # We will use the denominator multiple times, so we'll store the value in a separate variable, # to make the code easier to use and less error prone. # Here we use ** to raise c and d to the second power. denominator = (c ** 2) + (d ** 2) real = ((a * c) + (b * d)) / denominator imaginary = ((a * (-d) ) + (c * b)) / denominator return (real, imaginary) @exercise def modulus(x : Complex) -> float: return math.sqrt(x[0] ** 2 + x[1] ** 2) @exercise def complex_exp(x : Complex) -> Complex: (a, b) = x expa = math.e ** a real = expa * math.cos(b) imaginary = expa * math.sin(b) return (real, imaginary) @exercise def complex_exp_real(r : float, x : Complex) -> Complex: # Since ln(r) is only defined for positive numbers, we check for this special case. # If r = 0, raising it to any power will give 0. # Calling return before the end of the function will not execute the rest of the function. if (r == 0): return (0,0) (a, b) = x # Raise r to the power of a ra = r ** a # Natural logarithm of r lnr = math.log(r) real = ra * math.cos(b * lnr) imaginary = ra * math.sin(b * lnr) return (real, imaginary) @exercise def polar_convert(x : Complex) -> Polar: (a, b) = x r = math.sqrt(a**2 + b **2) theta = math.atan2(b, a) return (r, theta) @exercise def cartesian_convert(x : Polar) -> Complex: (r, theta) = x real = r * math.cos(theta) imaginary = r * math.sin(theta) return (real, imaginary) @exercise def polar_mult(x : Polar, y : Polar) -> Polar: (r1, theta1) = x (r2, theta2) = y radius = r1 * r2 angle = theta1 + theta2 # If the calculated angle is larger then pi, we will subtract 2pi if (angle > math.pi): # Reassign the value for angle angle = angle - 2.0 * math.pi # If the calculated angle is smaller then -pi, we will add 2 pi elif (angle <= -math.pi): angle = angle + 2.0 * math.pi return (radius, angle) @exercise def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex: (a, b) = x (c, d) = y # Convert x to polar form r = math.sqrt(a ** 2 + b ** 2) theta = math.atan2(b, a) # Special case for r = 0 if (r == 0): return (0, 0) lnr = math.log(r) exponent = math.exp(lnr * c - d * theta) real = exponent * (math.cos(lnr * d + theta * c )) imaginary = exponent * (math.sin(lnr * d + theta * c)) return (real, imaginary)
https://github.com/jeevesh2002/QuantumKatasQiskit
jeevesh2002
# Run this cell using Ctrl+Enter (⌘+Enter on Mac). from testing import exercise, create_empty_matrix from typing import List import math, cmath Matrix = List[List[complex]] @exercise def matrix_add(a : Matrix, b : Matrix) -> Matrix: # You can get the size of a matrix like this: rows = len(a) columns = len(a[0]) # You can use the following function to initialize a rows×columns matrix filled with 0s to store your answer c = create_empty_matrix(rows, columns) # You can use a for loop to execute its body several times; # in this loop variable i will take on each value from 0 to n-1, inclusive for i in range(rows): # Loops can be nested for j in range(columns): # You can access elements of a matrix like this: x = a[i][j] y = b[i][j] # You can modify the elements of a matrix like this: c[i][j] = ... return c @exercise def scalar_mult(x : complex, a : Matrix) -> Matrix: # Fill in the missing code and run the cell to check your work. return ... @exercise def matrix_mult(a : Matrix, b : Matrix) -> Matrix: return ... @exercise def matrix_inverse(a : Matrix) -> Matrix: return ... @exercise def transpose(a : Matrix) -> Matrix: return ... @exercise def conjugate(a : Matrix) -> Matrix: return ... @exercise def adjoint(a : Matrix) -> Matrix: return ... from pytest import approx @exercise def is_matrix_unitary(a : Matrix) -> bool: return ... @exercise def inner_prod(v : Matrix, w : Matrix) -> complex: return ... @exercise def normalize(v : Matrix) -> Matrix: return ... @exercise def outer_prod(v : Matrix, w : Matrix) -> Matrix: return ... @exercise def tensor_product(a : Matrix, b : Matrix) -> Matrix: return ... @exercise def find_eigenvalue(a : Matrix, v : Matrix) -> float: return ... @exercise def find_eigenvector(a : Matrix, x : float) -> Matrix: return ...
https://github.com/jeevesh2002/QuantumKatasQiskit
jeevesh2002
# Run this cell using Ctrl+Enter (⌘+Enter on Mac). from testing import exercise, create_empty_matrix from typing import List import math, cmath Matrix = List[List[complex]] @exercise def matrix_add(a : Matrix, b : Matrix) -> Matrix: # You can get the size of a matrix like this: rows = len(a) columns = len(a[0]) # You can use the following function to initialize a rows×columns matrix filled with 0s to store your answer c = create_empty_matrix(rows, columns) for i in range(rows): for j in range(columns): # You can access elements of a matrix like this: x = a[i][j] y = b[i][j] # You can modify the elements of a matrix like this: c[i][j] = a[i][j] + b[i][j] return c @exercise def scalar_mult(x : complex, a : Matrix) -> Matrix: rows = len(a) columns = len(a[0]) c = create_empty_matrix(rows, columns) for i in range(rows): for j in range(columns): c[i][j] = a[i][j] * x return c @exercise def matrix_mult(a : Matrix, b : Matrix) -> Matrix: rows = len(a) # the number of rows of the left matrix common = len(a[0]) # = len(b) - the common dimension of the matrices columns = len(b[0]) # the number of columns of the right matrix ans = create_empty_matrix(rows, columns) for currentRow in range(rows): for currentColumn in range(columns): for k in range(common): ans[currentRow][currentColumn] += a[currentRow][k] * b[k][currentColumn] return ans @exercise def matrix_inverse(m : Matrix) -> Matrix: # Extract each element of the array into a named variable a = m[0][0] b = m[0][1] c = m[1][0] d = m[1][1] # Calculate the determinant determinant = (a * d) - (b * c) # Create the inverse of the matrix following the formula above ans = [[d / determinant, -b / determinant], [-c / determinant, a / determinant]] return ans @exercise def transpose(a : Matrix) -> Matrix: rows = len(a) columns = len(a[0]) # Note that the resulting matrix dimensions are swapped compared to the original ones ans = create_empty_matrix(columns, rows) for i in range(rows): for j in range(columns): ans[j][i] = a[i][j] return ans @exercise def conjugate(a : Matrix) -> Matrix: rows = len(a) columns = len(a[0]) ans = create_empty_matrix(rows, columns) for i in range(rows): for j in range(columns): ans[i][j] = complex(a[i][j].real, -a[i][j].imag) return ans @exercise def adjoint(a : Matrix) -> Matrix: # Call the transpose function with the input matrix a transp = transpose(a) # Call the conjugate function with the transposed matrix as input ans = conjugate(transp) return ans from pytest import approx @exercise def is_matrix_unitary(a : Matrix) -> bool: n = len(a) # Calculate the adjoint matrix adjointA = adjoint(a) # Multiply the adjoint matrix by the input matrix multipliedMatrix = matrix_mult(a, adjointA) # Check whether the multiplication result is (approximately) identity matrix for i in range(n): for j in range(n): # An identity matrix has 1's in all the places where the row index and column index are equal... if i == j: if multipliedMatrix[i][j] != approx(1): return False # ... and 0's in all the places where the row index and column index are different else: if multipliedMatrix[i][j] != approx(0): return False return True @exercise def inner_prod(v : Matrix, w : Matrix) -> complex: # Calculate the adjoint of the v vector adjointV = adjoint(v) # Multiply the adjoint v and w. The result will be a matrix with only one element. resultMatrix = matrix_mult(adjointV, w) # To get the actual complex number, we have to take one element from the multiplication result. return resultMatrix[0][0] @exercise def normalize(v : Matrix) -> Matrix: norm = math.sqrt(inner_prod(v, v).real) n = len(v) ans = create_empty_matrix(n, 1) # Divide each element of the vector by the norm for i in range(n): ans[i][0] = v[i][0] / norm return ans @exercise def outer_prod(v : Matrix, w : Matrix) -> Matrix: # Calculate adjoint of the W adjointW = adjoint(w) # Multiply V by W adjoint return matrix_mult(v, adjointW) @exercise def tensor_product(a : Matrix, b : Matrix) -> Matrix: aRows = len(a) # the number of rows for matrix a aColumns = len(a[0]) # the number of columns for matrix a bRows = len(b) # the number of rows for matrix b bColumns = len(b[0]) # the number of columns for matrix b ans = create_empty_matrix(aRows * bRows, aColumns * bColumns) # Outer pair of loops, iterating trough the elements of the left matrix for i in range(aRows): for j in range(aColumns): # Inner pair of loops, iterating through the elements of the right matrix for k in range(bRows): for l in range(bColumns): ans[i * bRows + k][j * bColumns + l] = a[i][j] * b[k][l] return ans from pytest import approx @exercise def find_eigenvalue(a : Matrix, v : Matrix) -> float: n = len(v) multiplied = matrix_mult(a, v) for i in range(n): if (v[i][0] != approx(0)): return multiplied[i][0] / v[i][0] @exercise def find_eigenvector(a : Matrix, x : float) -> Matrix: # Check for possible edge cases if (a[0][1] == 0): if (a[0][0] - x == 0): if (a[1][0] == 0): return [[1], [0]] else: return [[(a[1][1] - x) / (-a[1][0])], [1]] else: return [[0], [1]] v0 = 1 v1 = (a[0][0] - x) / (-a[0][1]) return [[v0], [v1]]
https://github.com/jeevesh2002/QuantumKatasQiskit
jeevesh2002
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(1) # print the statevector print(f"Initial Statevector: {Statevector.from_instruction(circuit).data}\n\n") # Add an X gate followed by a H gate to put the qubit in |-> state circuit.x(0) circuit.h(0) print("After putting the qubit in |-> state\n\n") # print the statevector print("Final Statevector: ", Statevector.from_instruction(circuit).data) import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.quantum_info import Statevector # Create a Quantum Register with 3 qubits q = QuantumRegister(3) # Create a Quantum Circuit acting on the q register to demonstrate the GHZ state circuit = QuantumCircuit(q) # Add a H gate on qubit 0, putting this qubit in superposition. circuit.h(q[0]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(q[0], q[1]) # Add a CX (CNOT) gate on control qubit 0 and target qubit 2 circuit.cx(q[0], q[2]) from qiskit.quantum_info import Statevector # Set the intial state of the simulator to the ground state using from_int state = Statevector.from_int(0, 2**3) # Evolve the state by the quantum circuit state = state.evolve(circuit) #draw using latex state.draw('latex') from qiskit.visualization import array_to_latex #Alternative way of representing in latex array_to_latex(state) state.draw('qsphere')
https://github.com/jeevesh2002/QuantumKatasQiskit
jeevesh2002
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector # Create a quantum circuit with one qubit qc = QuantumCircuit(1) # Put the qubit into an uneven superposition # ry(theta) is a rotation around the y-axis by angle theta qc.ry(1.0, 0) # Print the statevector |𝜓❭ print(f"The Qubit is in State |𝜓❭ = {Statevector.from_instruction(qc).data}") # Let's apply the X gate; notice how it swaps the amplitudes of the |0❭ and |1❭ basis states qc.x(0) # Print the statevector X|𝜓❭ print(f"The Qubit is in State X|𝜓❭ = {Statevector.from_instruction(qc).data}") # Applying the Z gate adds -1 relative phase to the |1❭ basis states qc.z(0) # Print the statevector ZX|𝜓❭ print(f"The Qubit is in State ZX|𝜓❭ = {Statevector.from_instruction(qc).data}") # Finally, applying the Y gate returns the qubit to its original state |𝜓❭, with an extra global phase of i qc.y(0) # Print the statevector YZX|𝜓❭ print(f"The Qubit is in State YZX|𝜓❭ = {Statevector.from_instruction(qc).data}")
https://github.com/jeevesh2002/QuantumKatasQiskit
jeevesh2002
%kata T1_ApplyY operation ApplyY (q : Qubit) : Unit is Adj+Ctl { Y(q); // As simple as that } %kata T2_GlobalPhaseI operation GlobalPhaseI (q : Qubit) : Unit is Adj+Ctl { Z(q); Y(q); X(q); } %kata T3_SignFlipOnZero operation SignFlipOnZero (q : Qubit) : Unit is Adj+Ctl { X(q); // Flip the qubit Z(q); // Apply negative phase on the |1> state X(q); // Flip the qubit back } %kata T4_PrepareMinus operation PrepareMinus (q : Qubit) : Unit is Adj+Ctl { X(q); // Turn |0> into |1> H(q); // Turn |1> into |-> } %kata T5_ThreeQuatersPiPhase operation ThreeQuatersPiPhase (q : Qubit) : Unit is Adj+Ctl { S(q); T(q); } %kata T6_PrepareRotatedState open Microsoft.Quantum.Math; operation PrepareRotatedState (alpha : Double, beta : Double, q : Qubit) : Unit is Adj+Ctl { Rx(2.0 * ArcTan2(beta, alpha), q); } %kata T7_PrepareArbitraryState open Microsoft.Quantum.Math; operation PrepareArbitraryState (alpha : Double, beta : Double, theta : Double, q : Qubit) : Unit is Adj+Ctl { Ry(2.0 * ArcTan2(beta, alpha), q); // Step 1 R1(theta, q); // Step 2 }
https://github.com/Slope86/QiskitExtension
Slope86
from qiskit_extension.quantum_circuit2 import QuantumCircuit2 as qc2 from qiskit_extension.state_vector2 import StateVector2 as sv2 circuit_EPR = qc2(2) # 1. 在qubit 0 的位置放入一個Hadamard gate circuit_EPR.h(0) # 2. 放入一個CNOT gate, 控制qubit為0, 目標qubit為1 circuit_EPR.cx(0, 1) # 3. 繪製電路圖 circuit_EPR.show_circ() circuit_EPR.to_matrix() circuit_EPR.show_matrix() # 建立一個|00>的state vector state00 = sv2.from_label('00') # 顯示出此sv2物件的狀態 state00.show_state() # 建立state vector: 2( √2|0> + |+> - |-> ) state_x0 = sv2.from_label((2**0.5,"0"),"+",(-1,"-")) # 顯示出此sv2物件的狀態 state_x0.show_state() state00.to_matrix() state_x0.to_matrix() state00.show_matrix() state_x0.show_matrix() # 將|00>經過EPR電路後的狀態 state_EPR = state00.evolve(circuit_EPR) # 顯示出此sv2物件的狀態 state_EPR.show_state() # 建立一個GHZ state state_GHZ = sv2.from_label("000","111") # 量測GHZ state的第一個qubit, 並顯示出結果 state_GHZ.show_measure(0) # 量測EPR pair的第一,二顆qubit後,將各種量測結果對應到的state vector存入一個list中 list_after_measure_bit01 = state_GHZ.measure([0,1]) # 顯示出量測到00的後state vector list_after_measure_bit01[0b00].show_state() # 此為None, 因為GHZ量測第0,1顆qubit,不可能出現01的結果 list_after_measure_bit01[0b01] is None # show_state() 預設以Z基底顯示狀態 state_x0.show_state() # 1/√2(|0>+|1>) # 以X基底顯示狀態 state_x0.show_state(basis='x') # |+> # 自動判斷基底(以最小entropy的基底顯示) state_x0.show_state(basis="") # |+> # measure() / show_measure() 預設以Z基底量測 state_GHZ.show_measure(0) # |0>: |00>, |1>: |11> # 以X基底量測 state_GHZ.show_measure(0, basis='x') # |+>: 1/√2(|00>+|11>), |->: 1/√2(|00>-|11>)
https://github.com/Slope86/QiskitExtension
Slope86
import math import random from qiskit_extension.quantum_circuit2 import QuantumCircuit2 as qc2 from qiskit_extension.state_vector2 import StateVector2 as sv2 state_unknown = sv2.from_label((random.random(), "0"), (random.random(), "1")) state_unknown.show_state() # Create a 2bits quantum circuit circ_init = qc2(2) # Entangle two ground state qubits to an EPR pair circ_init.h(0) circ_init.cx(0,1) # Put the ground state into the circuit to get the EPR pair state_EPR = sv2(circ_init) # Show state_EPR, confirm it is EPR pair state_EPR.show_state() # Combined state_unknown and state_EPR into a 3-qubit sv2 object state_before_teleport = state_unknown.expand(state_EPR) state_before_teleport.show_state() # Create the circuit for Bell measurement circ_bell = qc2(3) circ_bell.cx(0,1) circ_bell.h(0) # Bell measurement on qubits(0,1), and store the four possible states as a list after measurement # list[0b00]=state after measurement result is 00, # list[0b01]=state after measurement result is 01, # ... list_state_after_measure = state_before_teleport.evolve(circ_bell).measure([0,1]) # Show the four possible states after the Bell measurement # Display format: (|00> indicates the measured state, followed by a colon indicating [the remaining state after measurement result is 00]) # |00>: 1/2|0> + 1/2|1> ... state_before_teleport.evolve(circ_bell).show_measure([0,1]) state_after_teleport = list_state_after_measure[0b00] state_after_teleport.show_state(hide=[0,1]) # Correction circuit circ_correction = qc2(3) circ_correction.x(2) # Applying the correction circuit state_after_teleport = list_state_after_measure[0b01].evolve(circ_correction) state_after_teleport.show_state(hide=[0,1]) # Correction circuit circ_correction = qc2(3) circ_correction.z(2) # Applying the correction circuit state_after_teleport = list_state_after_measure[0b10].evolve(circ_correction) state_after_teleport.show_state(hide=[0,1]) # Correction circuit circ_correction = qc2(3) circ_correction.x(2) circ_correction.z(2) # Applying the correction circuit state_after_teleport = list_state_after_measure[0b11].evolve(circ_correction) state_after_teleport.show_state(hide=[0,1])
https://github.com/Slope86/QiskitExtension
Slope86
import math from qiskit_extension.quantum_circuit2 import QuantumCircuit2 as qc2 from qiskit_extension.state_vector2 import StateVector2 as sv2 # Create a 4bits quantum circuit circ_init = qc2(4) # Make ground state qubit(0,1) and qubit(2,3) entangled into two EPR pairs circ_init.h([0,2]) circ_init.cx([0,2],[1,3]) # Display the circuit circ_init.show_circ() # Put the ground state into the circuit we build in previous step, and get two EPR pairs state_EPR = sv2(circ_init) # Show state state_EPR.show_state() circ_Bell_measure = qc2(4) circ_Bell_measure.cx(1,2) circ_Bell_measure.h(1) # Bell measurement on qubits(1,2), and store the four possible states as a list after measurement # list[0b00]=state after measurement result is 00, # list[0b01]=state after measurement result is 01, # ... list_state_EPR_after_Bell_measure = state_EPR.evolve(circ_Bell_measure).measure([1,2]) # Show the four possible states after the Bell measurement # Display format: (|00> indicates the measured state, followed by a colon indicating [the remaining state after measurement result is 00]) # |00>: 1/2|0> + 1/2|1> ... state_EPR.evolve(circ_Bell_measure).show_measure([1,2]) # Get the state after measuring, and the measurement result is 01 state_before_correction = list_state_EPR_after_Bell_measure[0b01] # Show the state before correction state_before_correction.show_state(hide=[1,2]) # Correction circuit (measurement result is 01, so perform Pauli-X on qubit 3) circ_correction = qc2(4) circ_correction.x(3) # Put state_before_correction into the correction circuit, get the state after correction state_after_correction = state_before_correction.evolve(circ_correction) # Show corrected state, make sure that entangled swap successful state_after_correction.show_state(hide=[1,2])
https://github.com/Slope86/QiskitExtension
Slope86
from qiskit_extension.quantum_circuit2 import QuantumCircuit2 as qc2 from qiskit_extension.state_vector2 import StateVector2 as sv2 circuit_EPR = qc2(2) # 1. put a Hadamard gate in the qubit 0 position circuit_EPR.h(0) # 2. put a CNOT gate, control qubit 0, target qubit 1 circuit_EPR.cx(0, 1) # 3. draw the circuit circuit_EPR.show_circ() circuit_EPR.to_matrix() circuit_EPR.show_matrix() # Create a state vector of |00> state00 = sv2.from_label('00') # Show the state of this sv2 object state00.show_state() # Create state vector: 2( √2|0> + |+> - |-> ) state_x0 = sv2.from_label((2**0.5, "0"), "+",(-1,"-")) # Show the state of this sv2 object state_x0.show_state() state00.to_matrix() state_x0.to_matrix() state00.show_matrix() state_x0.show_matrix() # The state of |00> after the EPR circuit state_EPR = state00.evolve(circuit_EPR) # Show the state of this sv2 object state_EPR.show_state() # Create a GHZ state state_GHZ = sv2.from_label("000", "111") # Measure the first qubit of the GHZ state, and display the result state_GHZ.show_measure(0) # After measuring the first and second qubits of the EPR pair, the state vector corresponding to each measurement result is stored in a list list_after_measure_bit01 = state_GHZ.measure([0,1]) # Show the state vector after measured and the measurement result = 00 list_after_measure_bit01[0b00].show_state() # This is None, because the GHZ measurement of the 0,1 qubit, the result of 00 is not possible list_after_measure_bit01[0b01] is None # show_state() preset to show state in z-basis state_x0.show_state() # 1/√2(|0>+|1>) # Show state with X basis state_x0.show_state(basis='x') # |+> # Automatically determine the basis (show the basis with the smallest entropy) state_x0.show_state(basis="") # |+> # measure() / show_measure() preset to measure in Z basis state_GHZ.show_measure(0) # |0>: |00>, |1>: |11> # Measure in X basis state_GHZ.show_measure(0, basis='x') # |+>: 1/√2(|00>+|11>), |->: 1/√2(|00>-|11>)
https://github.com/Slope86/QiskitExtension
Slope86
import math import random from qiskit_extension.quantum_circuit2 import QuantumCircuit2 as qc2 from qiskit_extension.state_vector2 import StateVector2 as sv2 state_unknown = sv2.from_label((random.random(), "0"), (random.random(), "1")) state_unknown.show_state() # Create a 2bits quantum circuit circ_init = qc2(2) # Entangle two ground state qubits to an EPR pair circ_init.h(0) circ_init.cx(0,1) # Put the ground state into the circuit to get the EPR pair state_EPR = sv2(circ_init) # Show state_EPR, confirm it is EPR pair state_EPR.show_state() # Combined state_unknown and state_EPR into a 3-qubit sv2 object state_before_teleport = state_unknown.expand(state_EPR) state_before_teleport.show_state() # Create the circuit for Bell measurement circ_bell = qc2(3) circ_bell.cx(0,1) circ_bell.h(0) # Bell measurement on qubits(0,1), and store the four possible states as a list after measurement # list[0b00]=state after measurement result is 00, # list[0b01]=state after measurement result is 01, # ... list_state_after_measure = state_before_teleport.evolve(circ_bell).measure([0,1]) # Show the four possible states after the Bell measurement # Display format: (|00> indicates the measured state, followed by a colon indicating [the remaining state after measurement result is 00]) # |00>: 1/2|0> + 1/2|1> ... state_before_teleport.evolve(circ_bell).show_measure([0,1]) state_after_teleport = list_state_after_measure[0b00] state_after_teleport.show_state(hide=[0,1]) # Correction circuit circ_correction = qc2(3) circ_correction.x(2) # Applying the correction circuit state_after_teleport = list_state_after_measure[0b01].evolve(circ_correction) state_after_teleport.show_state(hide=[0,1]) # Correction circuit circ_correction = qc2(3) circ_correction.z(2) # Applying the correction circuit state_after_teleport = list_state_after_measure[0b10].evolve(circ_correction) state_after_teleport.show_state(hide=[0,1]) # Correction circuit circ_correction = qc2(3) circ_correction.x(2) circ_correction.z(2) # Applying the correction circuit state_after_teleport = list_state_after_measure[0b11].evolve(circ_correction) state_after_teleport.show_state(hide=[0,1])
https://github.com/Slope86/QiskitExtension
Slope86
import math from qiskit_extension.quantum_circuit2 import QuantumCircuit2 as qc2 from qiskit_extension.state_vector2 import StateVector2 as sv2 # Create a 4bits quantum circuit circ_init = qc2(4) # Make ground state qubit(0,1) and qubit(2,3) entangled into two EPR pairs circ_init.h([0,2]) circ_init.cx([0,2],[1,3]) # Display the circuit circ_init.show_circ() # Put the ground state into the circuit we build in previous step, and get two EPR pairs state_EPR = sv2(circ_init) # Show state state_EPR.show_state() circ_Bell_measure = qc2(4) circ_Bell_measure.cx(1,2) circ_Bell_measure.h(1) # Bell measurement on qubits(1,2), and store the four possible states as a list after measurement # list[0b00]=state after measurement result is 00, # list[0b01]=state after measurement result is 01, # ... list_state_EPR_after_Bell_measure = state_EPR.evolve(circ_Bell_measure).measure([1,2]) # Show the four possible states after the Bell measurement # Display format: (|00> indicates the measured state, followed by a colon indicating [the remaining state after measurement result is 00]) # |00>: 1/2|0> + 1/2|1> ... state_EPR.evolve(circ_Bell_measure).show_measure([1,2]) # Get the state after measuring, and the measurement result is 01 state_before_correction = list_state_EPR_after_Bell_measure[0b01] # Show the state before correction state_before_correction.show_state(hide=[1,2]) # Correction circuit (measurement result is 01, so perform Pauli-X on qubit 3) circ_correction = qc2(4) circ_correction.x(3) # Put state_before_correction into the correction circuit, get the state after correction state_after_correction = state_before_correction.evolve(circ_correction) # Show corrected state, make sure that entangled swap successful state_after_correction.show_state(hide=[1,2])
https://github.com/Slope86/QiskitExtension
Slope86
"""Module to construct, simulate, and visualize quantum circuit""" from __future__ import annotations import itertools import typing from typing import List import numpy as np from IPython.display import Latex from numpy.typing import NDArray from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, quantum_info, transpile from qiskit.visualization import plot_histogram from qiskit_aer import AerSimulator from qiskit_extension import latex_drawer from qiskit_extension.state_vector2 import StateVector2 if typing.TYPE_CHECKING: import matplotlib.figure class QuantumCircuit2(QuantumCircuit): """An extended class of QuantumCircuit from Qiskit: https://qiskit.org/documentation/stubs/qiskit.circuit.QuantumCircuit.html Args: number_of_qubits (int, optional): Number of qubits. Defaults to 1. """ def __init__(self, number_of_qubits: int = 1): # Use Aer's qasm_simulator self.simulator = AerSimulator() self.n = number_of_qubits q = QuantumRegister(self.n, "q") c = ClassicalRegister(self.n, "c") super().__init__(q, c) def to_matrix(self) -> NDArray[np.complex128]: """Return matrix form of the quantum circuit""" reverse_qc = self.reverse_bits() # REVERSE the order of qubits to fit textbook notation return quantum_info.Operator(reverse_qc).data def show_matrix(self): """Show the matrix form of the quantum circuit in LaTeX""" return latex_drawer.matrix_to_latex(self.to_matrix()) def show_circ(self) -> Latex: """Show the circuit in LaTeX""" return self.draw(output="latex", idle_wires=False) # type: ignore def show_measure_all(self) -> matplotlib.figure.Figure: """Measure every qubit at the end of the circuit, then plot the result Returns: matplotlib.figure.Figure: A histogram of the measurement result """ for i in range(self.n): self.measure(i, i) # compile the circuit down to low-level QASM instructions # supported by the backend (not needed for simple circuits) compiled_circuit = transpile(self, self.simulator) # Execute the circuit on the qasm simulator job = self.simulator.run(compiled_circuit, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(self) print(f"\nTotal count : {counts}\n") # Plot a histogram return plot_histogram(counts) def get_state(self) -> StateVector2: """Initialize the state to ground state, then evolve the state by the quantum circuit. Returns: StateVector2: Final state of the quantum circuit """ # Set the initial state of the simulator to the ground state using from_int state = StateVector2.from_int(i=0, dims=2**self.n) # Evolve the state by the quantum circuit state = state.evolve(self) return state def phase_shift(self, theta, qubit) -> None: """Phase shift gate Args: theta (_type_): phase shift angle qubit (_type_): which qubit to apply the gate """ self.p(theta, qubit) self.x(qubit) self.p(theta, qubit) self.x(qubit) def h_all(self) -> None: """Perform H gate on every qubit""" for i in range(self.n): self.h(i) def cz_line_all(self) -> None: """Perform CZ gate on qubit(0,1), qubit(1,2), qubit(2,3) ... , qubit(n-1,n)""" for i in range(self.n - 1): self.cz(i, i + 1) def cz_star_all(self, center=0) -> None: """Perform CZ gate on (center qubit, every other qubit) Args: center (int, optional): Center qubit. Defaults to 0. """ for i in range(self.n): if i == center: continue self.cz(center, i) def cz_complete(self) -> None: """Perform CZ gate on every possible combination of qubits""" for qubit_c, qubit_t in itertools.combinations(range(self.n), 2): self.cz(qubit_c, qubit_t) def z2epr_pair(self, qubit_c: List[int] | int, qubit_t: List[int] | int) -> None: """Perform Z to EPR pair transformation Args: qubit_c (List[int] | int): control qubit qubit_t (List[int] | int): target qubit """ if isinstance(qubit_c, int) and isinstance(qubit_t, int): qubit_c, qubit_t = [qubit_c], [qubit_t] if isinstance(qubit_c, list) and isinstance(qubit_t, list): if len(qubit_c) != len(qubit_t): raise ValueError("qubit_c and qubit_t must have the same length") for c, t in zip(qubit_c, qubit_t): self.h(c) self.cx(c, t) else: raise TypeError("qubit_c and qubit_t must be List[int] or int") def epr2z_basis(self, qubit_c: List[int] | int, qubit_t: List[int] | int) -> None: """Perform EPR pair to Z basis transformation Args: qubit_c (List[int] | int): control qubit qubit_t (List[int] | int): target qubit """ if isinstance(qubit_c, int) and isinstance(qubit_t, int): qubit_c, qubit_t = [qubit_c], [qubit_t] if isinstance(qubit_c, list) and isinstance(qubit_t, list): if len(qubit_c) != len(qubit_t): raise ValueError("qubit_c and qubit_t must have the same length") for c, t in zip(qubit_c, qubit_t): self.cx(c, t) self.h(c) else: raise TypeError("qubit_c and qubit_t must both be List[int] or both be int")
https://github.com/Slope86/QiskitExtension
Slope86
"""Module to store, manipulate and visualize quantum state vector.""" from __future__ import annotations import copy import itertools import re from typing import Iterable, List, Tuple import numpy as np from IPython.display import Latex from numpy.typing import NDArray from qiskit import QuantumCircuit from qiskit.circuit import Instruction from qiskit.exceptions import QiskitError from qiskit.quantum_info import Statevector from scipy import stats from qiskit_extension import latex_drawer from qiskit_extension.ket import Ket class StateVector2(Statevector): """An extended class of Statevector from Qiskit: https://qiskit.org/documentation/stubs/qiskit.quantum_info.Statevector.html Args: data (np.ndarray | list | Statevector | QuantumCircuit | Instruction): Data from which the statevector can be constructed. This can be either a complex vector, another statevector, a ``QuantumCircuit`` or ``Instruction``. If the data is a circuit or instruction, the statevector is constructed by assuming that all qubits are initialized to the zero state. dims (int | tuple | list, optional): The subsystem dimension of the state. """ def __init__(self, data, dims: int | Iterable[int] | None = None) -> None: if not isinstance(data, np.ndarray | list | Statevector | QuantumCircuit | Instruction): raise QiskitError("Input only accepts np.ndarray | list | Statevector | QuantumCircuit | Instruction") # REVERSE the order of qubits to fit textbook notation if isinstance(data, QuantumCircuit): data = data.reverse_bits() elif isinstance(data, Instruction): data = Statevector(data).reverse_qargs() self._data: NDArray[np.complex128] super().__init__(data, dims) self._num_of_qubit = int(np.log2(len(self._data))) self._basis = ["z"] * self._num_of_qubit @classmethod def __init__with_basis( cls, data, dims: int | Iterable[int] | None = None, basis: List[str] | str = [] ) -> StateVector2: """Initialize statevector with basis.""" state_vector = cls(data, dims) state_vector.basis = list(basis) + ["z"] * (state_vector._num_of_qubit - len(basis)) return state_vector def __repr__(self) -> str: """Return the official string representation of a Statevector.""" vector_str = np.array2string(self.to_matrix(), separator=", ") return f"Statevector:\n{vector_str}" @property def data(self) -> NDArray[np.complex128]: return self._data.copy() @property def basis(self) -> List[str]: return self._basis.copy() @data.setter def data(self, data: NDArray[np.complex128]): self._data = data.copy() @basis.setter def basis(self, basis: List[str]): self._basis = basis.copy() def copy(self) -> StateVector2: """Return a copy of the current statevector.""" return copy.deepcopy(self) def to_matrix(self) -> NDArray[np.complex128]: """Return matrix form of statevector""" clone = self.copy() clone._basis_convert("z" * self._num_of_qubit) vector = clone._data matrix = vector[np.newaxis].T # type: ignore return matrix def entropy(self, state: StateVector2 | Statevector | None = None) -> float: """Return entropy of input statevector.""" if state is None: state = self return stats.entropy(state.probabilities(), base=2) # type: ignore def evolve(self, circ: QuantumCircuit | NDArray, qargs: List[int] | None = None) -> StateVector2: """Evolve self(statevector) by a quantum circuit or matrix. return the evolved state as a new statevector. (self's state will not be changed) Args: circ (QuantumCircuit): The circ to evolve by. qargs (List[int], optional): A list of subsystem positions to apply the operator on. Returns: StateVector2: The new evolved statevector. """ clone = self.copy() original_basis = clone.basis clone._basis_convert(["z"] * self._num_of_qubit) new_state = clone._evolve(circ, qargs) new_state._basis_convert(original_basis) return new_state def _evolve(self, circ: QuantumCircuit | NDArray, qargs: List[int] | None = None) -> StateVector2: """Evolve self(z-basis statevector) by a quantum circuit or matrix. return the evolved state as a new statevector. (self's state will not be changed) Args: circ (QuantumCircuit): The object to evolve by. qargs (List[int], optional): A list of subsystem positions to apply the operator on. Returns: StateVector2: The new evolved statevector. """ if not isinstance(circ, QuantumCircuit | np.ndarray): raise QiskitError("Input is not a QuantumCircuit.") if isinstance(circ, QuantumCircuit): circ = circ.reverse_bits() # REVERSE the order of qubits to fit textbook notation evolve_data = super().evolve(circ, qargs).data return StateVector2.__init__with_basis(data=evolve_data, basis=self.basis) def measure( self, measure: List[int] | int | str, basis: List[str] | str | None = None, shot=100 ) -> List[StateVector2]: """measure statevector Args: measure (List[int] | int | str): which qubits to measure basis (List[str] | str | None, optional): measure in what basis. Defaults to current stored basis. shot (int, optional): number of shots. Defaults to 100. Returns: List[StateVector2]: list of statevector after measurement """ states = self._measure(measure, basis, shot)[1] for state in states: if state is not None: state._basis_convert(self.basis) return states def _measure( self, measure: List[int] | int | str, basis: List[str] | str | None = None, shot=100 ) -> Tuple[List[StateVector2], List[StateVector2]]: """measure statevector Args: measure (List[int] | int | str): which qubits to measure basis (List[str] | str, optional): measure in what basis. Defaults to current stored basis. shot (int, optional): number of shots. Defaults to 100. Returns: Tuple[List[StateVector2], List[StateVector2]]: list of measured statevector, list of remained statevector after measurement """ clone = self.copy() if isinstance(measure, str): measure = [int(char) for char in measure] elif isinstance(measure, int): measure = [measure] if basis is not None: convert_basis = clone.basis for i in range(len(basis)): convert_basis[measure[i]] = basis[i] clone._basis_convert(convert_basis) measure_state_list = [None] * 2 ** len(measure) # crate empty list for saving measure state remain_state_list = [None] * 2 ** len(measure) # crate empty list for saving remain state for _ in range(shot): measure_ket: str remain_state: Statevector # REVERSE measure bit number to fit qiskit statevector measure notation reverse_measure = [clone._num_of_qubit - 1 - i for i in measure] measure_ket, remain_state = Statevector(clone.data).measure(qargs=reverse_measure) # type: ignore measure_ket = measure_ket[::-1] # REVERSE the order of qubits to fit textbook notation if measure_state_list[int(measure_ket, 2)] is None: basis = clone.basis measure_basis = "" for i in measure: measure_basis += basis[i] basis_convert_measure_ket = "" for b, k in zip(measure_basis, measure_ket): match b: case "z": basis_convert_measure_ket += Ket.z1 if int(k) else Ket.z0 case "x": basis_convert_measure_ket += Ket.x1 if int(k) else Ket.x0 case "y": basis_convert_measure_ket += Ket.y1 if int(k) else Ket.y0 measure_state_list[int(measure_ket, 2)] = clone._from_label(basis_convert_measure_ket, to_z_basis=False) remain_state_list[int(measure_ket, 2)] = StateVector2.__init__with_basis( data=remain_state.data, basis=clone.basis ) return (measure_state_list, remain_state_list) def show_matrix(self): """show the matrix form of statevector in LaTeX""" return latex_drawer.matrix_to_latex(self.to_matrix()) def show_state( self, basis: List[str] | str | None = None, hide: List[int] | str = [], output_length: int = 2, output: str = "latex", ): """visualize statevector Args: basis (List[str] | str, optional): convert statevector's basis to input basis. Defaults to skip basis convert. hide (List[int] | str, optional): hide qubits. Default to show all qubits. output_length (int, optional): 2^output_length = number of terms in each line. Defaults to 2(= 4 terms/line) output (str, optional): visualization method. Defaults to "latex". Returns: matplotlib.Figure or str or TextMatrix or IPython.display.Latex: visualization output """ clone = self.copy() if basis is not None: clone._basis_convert(basis) match output: case "text": return print(clone) case "latex": return latex_drawer.state_to_latex(clone, hide, output_length) case "latex_source": return latex_drawer.state_to_latex(clone, hide, output_length, source=True) case _: return clone.draw(output=output) def show_measure( self, measure: List[int] | int | str, basis: List[str] | str | None = None, hide: List[int] | str = [], output_length: int = 2, remaining_basis: List[str] | str | None = None, ) -> Latex: """visualize measure result Args: measure (List[int] | int | str): qubits to measure basis (List[int] | str, optional): measure in what basis. Defaults to z basis. hide (List[int] | str, optional): hide qubits. Default to show all qubits. output_length (int, optional): 2^output_length = number of terms in each line. Defaults to 2(= 4 terms/line) remaining_basis (List[str] | str, optional): change statevector's basis to input basis before measure. Returns: Latex: visualization output """ if isinstance(hide, str): hide = [int(char) for char in hide] elif isinstance(hide, int): hide = [hide] if isinstance(measure, str): measure = [int(char) for char in measure] elif isinstance(measure, int): measure = [measure] clone = self.copy() if remaining_basis is not None: remaining_basis = list(remaining_basis) + ["-"] * (self._num_of_qubit - len(remaining_basis)) if basis is None: basis = ["z"] * len(measure) for i, b in zip(measure, basis): remaining_basis[i] = b clone._basis_convert(remaining_basis) result = clone._measure(measure=measure, basis=basis, shot=4 * 2 ** len(measure)) return latex_drawer.measure_result_to_latex(result, measure + hide, output_length) # type: ignore @classmethod def from_int(cls, i: int, dims: int | Iterable[int]) -> StateVector2: """Return a computational basis statevector. Args: i (int): the basis state element. dims (int | Iterable[int]): The subsystem dimensions of the statevector Returns: StateVector2: The statevector object. """ state = super().from_int(i, dims) return cls(state.data, dims) @classmethod def from_instruction(cls, instruction): """Return the output statevector of an instruction. The statevector is initialized in the state :math:`|{0,\\ldots,0}\\rangle` of the same number of qubits as the input instruction or circuit, evolved by the input instruction, and the output statevector returned. Args: instruction (qiskit.circuit.Instruction or QuantumCircuit): instruction or circuit Returns: Statevector: The final statevector. Raises: QiskitError: if the instruction contains invalid instructions for the statevector simulation. """ if not isinstance(instruction, QuantumCircuit | Instruction): raise QiskitError("Input is not a valid instruction or circuit.") return cls(instruction) @classmethod def from_label(cls, *args: str | Tuple[complex, str]) -> StateVector2: """Create a state vector from input coefficient and label string. Example: from_label("0", "1") = (|0> + |1>)/√2, from_label("00", "01", "10", "11") = (|00> + |01> + |10> + |11>)/2 = |++>, from_label( (2**0.5,"0") , "+" , (-1,"-") ) = ( √2|0> + |+> - |-> )/2 = |+> Args: args (str | Tuple[complex, str]): The input label string or tuple of coefficient and label string. Returns: StateVector2: The statevector object. Raises: QiskitError: if labels contain invalid characters or labels have different number of qubits. """ coeffs: List[complex] = [] labels: List[str] = [] for i, arg in enumerate(args): if isinstance(arg, tuple): coeffs.append(arg[0]) labels.append(arg[1]) else: coeffs.append(1.0) labels.append(arg) if not Ket.check_valid(labels[i]): raise QiskitError("Invalid label string.") if len(labels[0]) != len(labels[i]): raise QiskitError("Each label's number of qubits must be the same.") state: StateVector2 = cls._from_label(labels[0]) * coeffs[0] for coeff, label in zip(coeffs[1:], labels[1:]): state += cls._from_label(label) * coeff if type(state) is not StateVector2: raise QiskitError("Unexpected error.") state /= super(type(state), state).trace() ** 0.5 return state @classmethod def _from_label(cls, label: str, to_z_basis: bool = True) -> StateVector2: if to_z_basis: label = label.replace(Ket.z0, "0") label = label.replace(Ket.x0, "+") label = label.replace(Ket.y0, "r") label = label.replace(Ket.z1, "1") label = label.replace(Ket.x1, "-") label = label.replace(Ket.y1, "l") state = super().from_label(label) return cls(state.data) basis = "" for ket in label: match ket: case Ket.z0 | Ket.z1: basis += "z" case Ket.x0 | Ket.x1: basis += "x" case Ket.y0 | Ket.y1: basis += "y" label = label.replace(Ket.z0, "0") label = label.replace(Ket.x0, "0") label = label.replace(Ket.y0, "0") label = label.replace(Ket.z1, "1") label = label.replace(Ket.x1, "1") label = label.replace(Ket.y1, "1") state = super().from_label(label) return cls.__init__with_basis(state.data, basis=basis) def expand(self, other): """Return the tensor product state other ⊗ self. Args: other (Statevector2): a quantum state object. Returns: Statevector: the tensor product state other ⊗ self. Raises: QiskitError: if other is not a quantum state. """ clone = self.copy() clone._basis_convert("z" * self._num_of_qubit) other_clone = other.copy() other_clone._basis_convert("z" * other._num_of_qubit) state_expand = super(type(other_clone), other_clone).expand(clone) return StateVector2(state_expand.data) def _basis_convert( self, basis: List[str] | str = [], algorithm: str = "global", ) -> None: """Convert basis of statevector Args: basis (List[str] | str, optional):new basis. Defaults to auto choose basis with minimum entropy. algorithm (str, optional): if don't specify which basis to convert, (basis = "-") convert basis to basis with "local" or "global" minimum entropy. Defaults to "global". """ # check if input is valid target_basis = list(basis) + ["-"] * (self._num_of_qubit - len(basis)) del basis if re.match(R"^[\-xyz]+$", "".join(target_basis)) is None: raise QiskitError("Invalid basis.") # convert basis using QuantumCircuit auto_basis_index = [] circ_convert = QuantumCircuit(self._num_of_qubit) for i in range(self._num_of_qubit): if target_basis[i] == self._basis[i]: continue if target_basis[i] != "-": self._xyz_convert_circ(self.basis[i], target_basis[i], circ_convert, i) self._basis[i] = target_basis[i] else: auto_basis_index.append(i) self._data = self._evolve(circ_convert)._data if not auto_basis_index: return # if user don't specify which basis to convert, convert basis to basis with minimum entropy match algorithm: case "global": if len(auto_basis_index) > 8: print( "Warning: global minimum entropy basis convert with more then 8 qubits might take a long time." ) new_basis = self._global_min_entropy_basis(auto_basis_index) case "local": new_basis = self._local_min_entropy_basis(auto_basis_index) case _: raise QiskitError("Invalid min_entropy_basis_find_method.") self._basis_convert(new_basis) def _global_min_entropy_basis(self, auto_basis_index: List[int]) -> List[str]: """find basis with global minimum entropy Args: auto_basis_index (List[int]): index of auto-choose-basis Returns: List[str]: basis with global minimum entropy """ num_of_auto_basis = len(auto_basis_index) min_entropy = float("inf") min_basis = self.basis try_basis = self.basis for basis in itertools.product(["z", "x", "y"], repeat=num_of_auto_basis): # type: ignore for i in range(num_of_auto_basis): try_basis[auto_basis_index[i]] = basis[i] try_state = self.copy() try_state._basis_convert(try_basis) if (entropy := try_state.entropy()) < min_entropy: min_entropy = entropy min_basis = try_basis.copy() return min_basis def _local_min_entropy_basis(self, auto_basis_index: List[int]) -> List[str]: """find basis with local minimum entropy Args: auto_basis_index (List[int]): index of auto-choose-basis Returns: List[str]: basis with local minimum entropy """ # Step 1: Change all auto-choose-basis to y, e.g. [-, -, -, -] -> [z, z, z, z], calculate entropy # Step 2,3: Same as Step 1, but with x-basis and y-basis # Step 4: from Step 1 to 3, choose the basis with minimum entropy. clone_state = self.copy() min_entropy = float("inf") min_basis = clone_state.basis for basis in ["z", "x", "y"]: try_state = clone_state.copy() try_basis = try_state.basis for i in auto_basis_index: try_basis[i] = basis try_state._basis_convert(try_basis) if (entropy := try_state.entropy()) < min_entropy: min_entropy = entropy min_basis = try_basis clone_state._basis_convert(min_basis) # Step 1: Change the first auto-choose-basis to y, e.g. [-, -, -, -] -> [y, -, -, -], calculate entropy, # Step 2,3: Same as Step 1, but with x-basis and z-basis # Step 4: from Step 1 to 3, choose the basis with minimum entropy. # Step 5: Repeat Step 1 to 4 for the second auto-choose-basis, and so on. (greedy) # e.g. [-, -, -, -] -> [x, -, -, -] -> [x, z, -, -] -> [x, z, y, -] -> [x, z, y, z] min_entropy = float("inf") min_basis = clone_state.basis for i in auto_basis_index: try_basis = clone_state.basis for basis in ["y", "x", "z"]: try_basis[i] = basis try_state = clone_state.copy() try_state._basis_convert(try_basis) if (entropy_tmp := try_state.entropy()) < min_entropy: min_entropy = entropy_tmp min_basis[i] = basis clone_state._basis_convert(min_basis) return min_basis @staticmethod def _xyz_convert_circ(basis: str, new_basis: str, circ: QuantumCircuit, qubit: int) -> None: """Add the corresponding gate that converts different basis Args: basis (str): original basis new_basis (str): new basis circ (QuantumCircuit): quantum circuit to convert basis Returns: QuantumCircuit: quantum circuit to convert basis """ if basis == new_basis: return basis += new_basis match basis: case "zx" | "xz": circ.h(qubit) case "zy": circ.sdg(qubit) circ.h(qubit) case "yz": circ.h(qubit) circ.s(qubit) case "xy": circ.h(qubit) circ.sdg(qubit) circ.h(qubit) case "yx": circ.h(qubit) circ.s(qubit) circ.h(qubit) return
https://github.com/Tojarieh97/VQE
Tojarieh97
import numpy as np from qiskit.opflow import X, Z, I from qiskit.algorithms.optimizers import L_BFGS_B from qiskit.circuit.library import EfficientSU2 bfgs_optimizer = L_BFGS_B(maxiter=60) a_1 = np.random.random_sample() a_2 = np.random.random_sample() J_21 = np.random.random_sample() H_transverse_ising = a_1*(I^X) + a_2*(X^I) + J_21*(Z^Z) print("========== Transverse Ising Model Hamiltonian for Two Qubits ==========\n") print(H_transverse_ising.to_matrix()) print() H2_molecule_Hamiltonian = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) print("========== H2 Molecule Hamiltonian for Two Qubits ==========\n") print(H2_molecule_Hamiltonian.to_matrix()) print() def vqe(hamiltonian, anzatz, optimazer, min_dist): # Create the initial parameters params = np.random.rand(3) ret = optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params) # Obtain the output distribution using the final parameters qc = get_var_form(ret[0]) t_qc = transpile(qc, backend) qobj = assemble(t_qc, shots=NUM_SHOTS) counts = backend.run(qobj).result().get_counts(qc) output_distr = get_probability_distribution(counts) #calculate the target function old_res = old_state.dagger * hamiltonian * old_state print(old_res) #minimaize the target function #iterate the process vqe((I^I).to_matrix(),) (I^I).to_matrix()
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.circuit.library.standard_gates import RXGate, RZGate, CXGate, CZGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister def anzats_circ(thetas, phis, D1, D2): qr = QuantumRegister(4, name="q") cr = ClassicalRegister(4, name='c') qc = QuantumCircuit(qr, cr) for d in range(D1): qc.append(RXGate(phis[0]), [qr[2]]) qc.append(RXGate(phis[1]), [qr[3]]) qc.append(RZGate(phis[2]), [qr[2]]) qc.append(RZGate(phis[3]), [qr[3]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) for d in range(D2): qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) qc.append(CZGate(), [qr[0], qr[1]]) qc.append(CZGate(), [qr[1], qr[2]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) return qc #Define in this box the parameters for the anzats import numpy as np #you may define here the requsted parameters as you'd like thetas = np.array([0,0,0,0,np.pi/2,np.pi/2,np.pi/2,np.pi/2]) phis = np.array([np.pi,np.pi,np.pi,np.pi]) #you may define here the requested number of iterations D1 and D2 as described in Fig.1 of Subspace-search variational quantum #eigensolver for excited states. D1 = 1 D2 = 1 #display the created circuit qc = anzats_circ(thetas,phis,D1,D2) qc.draw()
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.circuit.library.standard_gates import RXGate, RZGate, CXGate, CZGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister def anzats_circ1(thetas, D2, in_state): qr = QuantumRegister(4, name="q") qc = QuantumCircuit(qr) qc.initialize(in_state) for d in range(D2): qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) qc.append(CZGate(), [qr[0], qr[1]]) qc.append(CZGate(), [qr[1], qr[2]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) qc.measure_all() return qc def anzats_circ1_uninitialized(thetas, D2): qr = QuantumRegister(4, name="q") qc = QuantumCircuit(qr) for d in range(D2): qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) qc.append(CZGate(), [qr[0], qr[1]]) qc.append(CZGate(), [qr[1], qr[2]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) qc.measure_all() return qc import numpy as np def get_k_basis(k, n): full_basis = np.identity(n) return full_basis[:k] from qiskit.opflow import X, Z, I, H, Y # for convinience let all coefficients ai and Jij be 0.5 H_transverse_ising = 0.5*((I^I^I^X) + (I^I^X^I) + (I^X^I^I) + (X^I^I^I) + \ (Z^Z^I^I) + (Z^I^Z^I) + (Z^I^I^Z) + (I^Z^Z^I) + \ (I^Z^I^Z) + (I^I^Z^Z)) # TODO: change this to a 4 qubits Hamiltonian H2_molecule_Hamiltonian = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) import matplotlib from qiskit import assemble, Aer from qiskit import * from qiskit.visualization import plot_histogram import math sim = Aer.get_backend('aer_simulator') def convert_string_to_index(string): return int(string, 2) # TODO: this isn't the right way to calculate the result state, should be changed def convert_result_to_state(result): total_meas = 0 for k in result.keys(): total_meas += result[k] amount_of_qubits = len(k) state = np.zeros(2**amount_of_qubits) for k in result.keys(): index = convert_string_to_index(k) state[index] = result[k]/total_meas return state # TODO: finish these functions def calc_ising_avg(qc): avg = 0 for i in range(4): qc_tmp = qc.copy() qc_tmp.append(H, [i]) def calc_molecular_avg(qc): pass def calc_target_func1(thetas, basis, D2, Ham): target_func = 0 for j in basis: qc = anzats_circ1(thetas, D2, j) print(qc.draw()) qobj = assemble(qc) result = sim.run(qobj).result().get_counts() state = convert_result_to_state(result) dagger_state = np.matrix(state) state = dagger_state.getH() state = np.array(state) dagger_state = np.array(dagger_state) # TODO: calculate this with estimation with the Ham pauli strings # if Ham == "Ising Model": # product = calc_ising_avg(qc) # else product = calc_molecular_avg(qc) product = np.matmul(Ham, state) product = np.matmul(dagger_state, product) target_func += product return target_func # JUST TO RUN AND CHECK k = 4 basis = get_k_basis(k,16) D2 = 1 Ham = H_transverse_ising.to_matrix() thetas = np.zeros(8) calc_target_func1(thetas, basis, D2, Ham) def objective_func1(thetas): k = 4 basis = get_k_basis(k,16) D2 = 1 Ham = H_transverse_ising.to_matrix() # Ham = H_transverse_ising target_func = calc_target_func1(thetas, basis,D2, Ham) return target_func[0][0] from qiskit.algorithms.optimizers import L_BFGS_B bfgs_optimizer = L_BFGS_B(maxiter=60) point, value, nfev = bfgs_optimizer.optimize(8,objective_func1,initial_point=np.zeros(8)) print(point) print("---point---") print(value) print("---value---") thetas_opt = point def anzats_circ2(phis, D1, in_state): qr = QuantumRegister(4, name="q") cr = ClassicalRegister(4) qc = QuantumCircuit(qr, cr) qc.initialize(in_state) for d in range(D1): qc.append(RXGate(phis[0]), [qr[2]]) qc.append(RXGate(phis[1]), [qr[3]]) qc.append(RZGate(phis[2]), [qr[2]]) qc.append(RZGate(phis[3]), [qr[3]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) return qc def calc_target_func2(thetas_opt, phis, in_state, D1, D2, Ham): target_func = 0 qc2 = anzats_circ2(phis, D1, in_state) qc1 = anzats_circ1_uninitialized(thetas_opt, D2) qc = qc2.compose(qc1) print(qc.draw()) qobj = assemble(qc) result = sim.run(qobj).result().get_counts() state = convert_result_to_state(result) dagger_state = np.matrix(state) state = dagger_state.getH() state = np.array(state) dagger_state = np.array(dagger_state) # TODO: calculate this with estimation with the Ham pauli strings # if Ham == "Ising Model": # product = calc_ising_avg(qc) # else product = calc_molecular_avg(qc) product = np.matmul(Ham, state) product = np.matmul(dagger_state, product) target_func += product return target_func i = np.random.randint(0,k) def objective_func2(phis): in_state = basis[i] print("in state") print(in_state) D1 = 1 D2 = 1 Ham = H_transverse_ising.to_matrix() # Ham = H_transverse_ising target_func2 = calc_target_func2(thetas_opt, phis, in_state, D1, D2, Ham) print("target func:") print(target_func2[0][0]) return target_func2[0][0] def objective_func2_neg(phis): return -1*objective_func2(phis) #to see wraping function is working well phis = np.array([np.pi, np.pi, np.pi, np.pi]) exp =objective_func2(phis) print("exp:") print(exp) exp_neg =objective_func2_neg(phis) print("exp_neg:") print(exp_neg) point, value, nfev = bfgs_optimizer.optimize(4,objective_func2_neg,initial_point=np.array([2, 2, 2, 2])) print(point) print("---point---") print(value) print("---value---") value = -value print(value)
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.circuit.library.standard_gates import RXGate, RZGate, CXGate, CZGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister import numpy as np def anzats_circ(thetas, D1, D2, in_state): qr = QuantumRegister(4, name="q") qc = QuantumCircuit(qr) qc.initialize(in_state) for d in range(D1): qc.append(RXGate(thetas[8]), [qr[2]]) qc.append(RXGate(thetas[9]), [qr[3]]) qc.append(RZGate(thetas[10]), [qr[2]]) qc.append(RZGate(thetas[11]), [qr[3]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) for d in range(D2): qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) qc.append(CZGate(), [qr[0], qr[1]]) qc.append(CZGate(), [qr[1], qr[2]]) qc.append(CZGate(), [qr[2], qr[3]]) qc.barrier(qr) qc.append(RXGate(thetas[0]), [qr[0]]) qc.append(RXGate(thetas[1]), [qr[1]]) qc.append(RXGate(thetas[2]), [qr[2]]) qc.append(RXGate(thetas[3]), [qr[3]]) qc.append(RZGate(thetas[4]), [qr[0]]) qc.append(RZGate(thetas[5]), [qr[1]]) qc.append(RZGate(thetas[6]), [qr[2]]) qc.append(RZGate(thetas[7]), [qr[3]]) qc.measure_all() return qc def get_k_basis(k, n): full_basis = np.identity(n) return full_basis[:k]
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.opflow import X, Z, I H2_op = (-1.052373245772859 * I ^ I) + \ (0.39793742484318045 * I ^ Z) + \ (-0.39793742484318045 * Z ^ I) + \ (-0.01128010425623538 * Z ^ Z) + \ (0.18093119978423156 * X ^ X) import numpy as np from qiskit.opflow import X, Z, I N = 2 H = 0*X for i in range(1,N+1): a_i = np.random.random_sample() for j in range(1,i+1): J_ij = np.random.random_sample() H += J_ij*Z*Z H += a_i*X print(H) import numpy as np from qiskit.opflow import X, Z, I N = 2 a_1 = np.random.random_sample() a_2 = np.random.random_sample() J_21 = np.random.random_sample() H = a_1*(I^X) + a_2*(X^I) + J_21*(Z^Z) print(H.to_matrix())
https://github.com/Tojarieh97/VQE
Tojarieh97
import numpy as np np.random.seed(999999) target_distr = np.random.rand(2) # We now convert the random vector into a valid probability vector target_distr /= sum(target_distr) print(target_distr) from qiskit.circuit.library import EfficientSU2 ansatz = EfficientSU2(num_qubits=2, entanglement='linear') print(ansatz.parameters) from qiskit import QuantumCircuitc, ClassicalRegister, QuantumRegister qc = QuantumCircuit(qr, cr) qr = QuantumRegister(1, name="q") cr = ClassicalRegister(1, name='c') from qiskit import QuantumCircuitc, ClassicalRegister, QuantumRegister def get_var_form(params): qr = QuantumRegister(1, name="q") cr = ClassicalRegister(1, name='c') ansatz = EfficientSU2(num_qubits=2, entanglement='linear') ansatz.u3(params[0], params[1], params[2], qr[0]) ansatz.measure(qr, cr[0]) return qc from qiskit import Aer, transpile, assemble backend = Aer.get_backend("qasm_simulator") NUM_SHOTS = 10000 def get_probability_distribution(counts): output_distr = [v / NUM_SHOTS for v in counts.values()] if len(output_distr) == 1: output_distr.append(1 - output_distr[0]) return output_distr def objective_function(params): # Obtain a quantum circuit instance from the paramters qc = get_var_form(params) qc.draw() # Execute the quantum circuit to obtain the probability distribution associated with the current parameters t_qc = transpile(qc, backend) qobj = assemble(t_qc, shots=NUM_SHOTS) result = backend.run(qobj).result() # Obtain the counts for each measured state, and convert those counts into a probability vector output_distr = get_probability_distribution(result.get_counts(qc)) # Calculate the cost as the distance between the output distribution and the target distribution cost = sum([np.abs(output_distr[i] - target_distr[i]) for i in range(2)]) return cost from qiskit.algorithms.optimizers import L_BFGS_B import numpy as np bfgs_optimizer = L_BFGS_B(maxiter=60) # Create the initial parameters (noting that our single qubit variational form has 3 parameters) params = np.random.rand(3) ret = bfgs_optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params) # Obtain the output distribution using the final parameters qc = get_var_form(ret[0]) t_qc = transpile(qc, backend) qobj = assemble(t_qc, shots=NUM_SHOTS) counts = backend.run(qobj).result().get_counts(qc) output_distr = get_probability_distribution(counts) print("Target Distribution:", target_distr) print("Obtained Distribution:", output_distr) print("Output Error (Manhattan Distance):", ret[1]) print("Parameters Found:", ret[0])
https://github.com/Tojarieh97/VQE
Tojarieh97
import sys sys.path.append('../../') import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import I, X, Y, Z import matplotlib.pyplot as plt from volta.observables import sample_hamiltonian from volta.hamiltonians import BCS_hamiltonian EPSILONS = [3, 3, 3, 3] V = -2 hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) #BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix()) print(f"Eigenvalues: {eigenvalues}") def create_circuit(n: int) -> list: return [QuantumCircuit(n) for _ in range(2)] n = hamiltonian.num_qubits init_states = create_circuit(n) def copy_unitary(list_states: list) -> list: out_states = [] for state in list_states: out_states.append(state.copy()) return out_states import textwrap def apply_initialization(list_states: list) -> None: for ind, state in enumerate(list_states): b = bin(ind)[2:] if len(b) != n: b = '0'*(n - len(b)) + b spl = textwrap.wrap(b, 1) for qubit, val in enumerate(spl): if val == '1': state.x(qubit) apply_initialization(init_states) initialization = copy_unitary(init_states) from qiskit.circuit.library import TwoLocal ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2) def apply_ansatz(ansatz: QuantumCircuit, list_states: list) -> None: for states in list_states: states.append(ansatz, range(n)) apply_ansatz(ansatz, init_states) init_states[-1].draw('mpl') def _apply_varform_params(ansatz, params: list): """Get an hardware-efficient ansatz for n_qubits given parameters. """ # Define variational Form var_form = ansatz # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len(params), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function from qiskit import BasicAer from qiskit.utils import QuantumInstance def cost_function(params:list) -> float: backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend, shots=10000) cost = 0 w = np.arange(len(init_states), 0, -1) for i, state in enumerate(init_states): qc = _apply_varform_params(state, params) # Hamiltonian hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian, ansatz=qc, backend=backend) cost += w[i] * hamiltonian_eval return cost from qiskit.aqua.components.optimizers import COBYLA optimizer = COBYLA() n_parameters = len(init_states[0].parameters) params = np.random.rand(n_parameters) optimal_params, mean_energy, n_iters = optimizer.optimize(num_vars=n_parameters, objective_function=cost_function, initial_point=params) mean_energy, sum(eigenvalues[:2]) # Optimized first ansatz ansatz_1 = _apply_varform_params(ansatz, optimal_params) ansatz_1.name = 'U(θ)' def cost_function_ind(ind: int, params:list) -> float: backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend, shots=10000) cost = 0 # Define Ansatz qc = _apply_varform_params(init_states[ind], params) # Hamiltonian hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian, ansatz=qc, backend=backend) cost += hamiltonian_eval return cost energies = [] for i in range(len(init_states)): energies.append(cost_function_ind(ind=i, params=optimal_params)) energies = np.array(energies) for i in range(len(init_states)): print(f"Value for the {i} state: {energies[i]}\t expected energy {eigenvalues[i]}")
https://github.com/Tojarieh97/VQE
Tojarieh97
from openfermion.chem import MolecularData from openfermion.transforms import get_fermion_operator, jordan_wigner from openfermion.linalg import get_ground_state, get_sparse_operator import numpy import scipy import scipy.linalg # Load saved file for LiH. diatomic_bond_length = 1.2 geometry = [('H', (0., 0., 0.)), ('H', (0., 0., diatomic_bond_length))] basis = 'sto-3g' multiplicity = 1 # Set Hamiltonian parameters. active_space_start = 1 active_space_stop = 3 # Generate and populate instance of MolecularData. molecule = MolecularData(geometry, basis, multiplicity, description="1.2") molecule.load() # Get the Hamiltonian in an active space. molecular_hamiltonian = molecule.get_molecular_hamiltonian( occupied_indices=range(1), active_indices=range(1, 2)) # Map operator to fermions and qubits. fermion_hamiltonian = get_fermion_operator(molecular_hamiltonian) qubit_hamiltonian = jordan_wigner(fermion_hamiltonian) qubit_hamiltonian.compress() print('The Jordan-Wigner Hamiltonian in canonical basis follows:\n{}'.format(qubit_hamiltonian)) # Get sparse operator and ground state energy. sparse_hamiltonian = get_sparse_operator(qubit_hamiltonian) energy, state = get_ground_state(sparse_hamiltonian) print('Ground state energy before rotation is {} Hartree.\n'.format(energy)) # Randomly rotate. n_orbitals = molecular_hamiltonian.n_qubits // 2 n_variables = int(n_orbitals * (n_orbitals - 1) / 2) numpy.random.seed(1) random_angles = numpy.pi * (1. - 2. * numpy.random.rand(n_variables)) kappa = numpy.zeros((n_orbitals, n_orbitals)) index = 0 for p in range(n_orbitals): for q in range(p + 1, n_orbitals): kappa[p, q] = random_angles[index] kappa[q, p] = -numpy.conjugate(random_angles[index]) index += 1 # Build the unitary rotation matrix. difference_matrix = kappa + kappa.transpose() rotation_matrix = scipy.linalg.expm(kappa) # Apply the unitary. molecular_hamiltonian.rotate_basis(rotation_matrix) # Get qubit Hamiltonian in rotated basis. qubit_hamiltonian = jordan_wigner(molecular_hamiltonian) qubit_hamiltonian.compress() print('The Jordan-Wigner Hamiltonian in rotated basis follows:\n{}'.format(qubit_hamiltonian)) # Get sparse Hamiltonian and energy in rotated basis. sparse_hamiltonian = get_sparse_operator(qubit_hamiltonian) energy, state = get_ground_state(sparse_hamiltonian) print('Ground state energy after rotation is {} Hartree.'.format(energy))
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.algorithms import VQE from qiskit.algorithms.optimizers import SLSQP, L_BFGS_B from qiskit.circuit.library import TwoLocal num_qubits = 2 ansatz = TwoLocal(num_qubits, 'ry', 'cz') opt = SLSQP(maxiter=60) bfgs_optimizer = L_BFGS_B(maxiter=60) vqe = VQE(ansatz, optimizer=opt) ansatz.draw() from qiskit import Aer backend = Aer.get_backend('aer_simulator_statevector') from qiskit.utils import QuantumInstance backend = Aer.get_backend('aer_simulator') quantum_instance = QuantumInstance(backend=backend, shots=800, seed_simulator=99) from qiskit.opflow import X, Z, I print(I.to_matrix()) print((Z^I).to_matrix()) H2_op = (-1.052373245772859 * I ^ I) + \ (0.39793742484318045 * I ^ Z) + \ (-0.39793742484318045 * Z ^ I) + \ (-0.01128010425623538 * Z ^ Z) + \ (0.18093119978423156 * X ^ X) print(H2_op.to_matrix()) from qiskit.utils import algorithm_globals seed = 50 algorithm_globals.random_seed = seed qi = QuantumInstance(Aer.get_backend('statevector_simulator'), seed_transpiler=seed, seed_simulator=seed) ansatz = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz') slsqp = SLSQP(maxiter=1000) vqe = VQE(ansatz, optimizer=bfgs_optimizer, quantum_instance=qi) result = vqe.compute_minimum_eigenvalue(H2_op) print(result) from qiskit.circuit.library import EfficientSU2 entanglements = ["linear", "full"] for entanglement in entanglements: ansatz = EfficientSU2(num_qubits=4, entanglement=entanglement) if entanglement == "linear": print("=============Linear Entanglement:=============") vqe = VQE(ansatz, optimizer=bfgs_optimizer, quantum_instance=qi) result = vqe.compute_minimum_eigenvalue(H2_op) print(result) print() else: print("=============Full Entanglement:=============") vqe = VQE(ansatz, optimizer=bfgs_optimizer, quantum_instance=qi) result = vqe.compute_minimum_eigenvalue(H2_op) print(result) print()
https://github.com/Tojarieh97/VQE
Tojarieh97
import sys sys.path.append('../../') import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import I, X, Y, Z import matplotlib.pyplot as plt from volta.observables import sample_hamiltonian from volta.hamiltonians import BCS_hamiltonian EPSILONS = [3, 3] V = -2 hamiltonian = BCS_hamiltonian(EPSILONS, V) print(hamiltonian) eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix()) print(f"Eigenvalues: {eigenvalues}") def create_circuit(n: int) -> list: return [QuantumCircuit(n) for _ in range(2)] n = hamiltonian.num_qubits init_states = create_circuit(n) def copy_unitary(list_states: list) -> list: out_states = [] for state in list_states: out_states.append(state.copy()) return out_states import textwrap def apply_initialization(list_states: list) -> None: for ind, state in enumerate(list_states): b = bin(ind)[2:] if len(b) != n: b = '0'*(n - len(b)) + b spl = textwrap.wrap(b, 1) for qubit, val in enumerate(spl): if val == '1': state.x(qubit) apply_initialization(init_states) initialization = copy_unitary(init_states) from qiskit.circuit.library import TwoLocal ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2) def apply_ansatz(ansatz: QuantumCircuit, list_states: list) -> None: for states in list_states: states.append(ansatz, range(n)) apply_ansatz(ansatz, init_states) init_states[1].draw('mpl') w = np.arange(n, 0, -1) w def _apply_varform_params(ansatz, params: list): """Get an hardware-efficient ansatz for n_qubits given parameters. """ # Define variational Form var_form = ansatz # Get Parameters from the variational form var_form_params = sorted(var_form.parameters, key=lambda p: p.name) # Check if the number of parameters is compatible assert len(var_form_params) == len(params), "The number of parameters don't match" # Create a dictionary with the parameters and values param_dict = dict(zip(var_form_params, params)) # Assing those values for the ansatz wave_function = var_form.assign_parameters(param_dict) return wave_function from qiskit import BasicAer from qiskit.utils import QuantumInstance def cost_function(params:list) -> float: backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend, shots=10000) cost = 0 # Define Ansatz for i, state in enumerate(init_states): qc = _apply_varform_params(state, params) # Hamiltonian hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian, ansatz=qc, backend=backend) cost += w[i] * hamiltonian_eval return cost from qiskit.aqua.components.optimizers import COBYLA optimizer = COBYLA(maxiter=1000) n_parameters = len(init_states[0].parameters) params = np.random.rand(n_parameters) optimal_params, mean_energy, n_iters = optimizer.optimize(num_vars=n_parameters, objective_function=cost_function, initial_point=params) mean_energy # Optimized first ansatz ansatz_1 = _apply_varform_params(ansatz, optimal_params) ansatz_1.name = 'U(θ)' apply_ansatz(ansatz_1, init_states) init_states[2].draw() from qiskit.aqua import QuantumInstance def cost_function_ind(ind: int, params:list) -> float: backend = BasicAer.get_backend('qasm_simulator') backend = QuantumInstance(backend, shots=10000) cost = 0 # Define Ansatz qc = _apply_varform_params(init_states[ind], params) # Hamiltonian hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian, ansatz=qc, backend=backend) cost += hamiltonian_eval return - cost from functools import partial cost = partial(cost_function_ind, 2) n_parameters = len(init_states[0].parameters) params = np.random.rand(n_parameters) optimal_params, energy_gs, n_iters = optimizer.optimize(num_vars=n_parameters, objective_function=cost, initial_point=params) energy_gs eigenvalues # Optimized second ansatz ansatz_2 = _apply_varform_params(ansatz, optimal_params) ansatz_2.name = 'V(ϕ)'
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 from qiskit.circuit.library.standard_gates import RXGate, RZGate, RYGate, CXGate, CZGate, SGate, HGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister import numpy as np def get_linear_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3): quantum_register = QuantumRegister(num_of_qubits, name="qubit") quantum_circuit = QuantumCircuit(quantum_register) quantum_circuit.initialize(input_state) for iteration in range(circuit_depth): for qubit_index in range(num_of_qubits): RY_theta_index = iteration*2*num_of_qubits + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) for qubit_index in range(num_of_qubits - 1): quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[qubit_index + 1]]) for qubit_index in range(num_of_qubits): RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) return quantum_circuit def get_full_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3): quantum_register = QuantumRegister(num_of_qubits, name="qubit") quantum_circuit = QuantumCircuit(quantum_register) quantum_circuit.initialize(input_state) for iteration in range(circuit_depth): for qubit_index in range(num_of_qubits): RY_theta_index = iteration*2*num_of_qubits + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) for qubit_index in range(num_of_qubits - 1): for target_qubit_index in range(qubit_index + 1, num_of_qubits): quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[target_qubit_index]]) for qubit_index in range(num_of_qubits): RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) return quantum_circuit initial_thetas = np.random.uniform(low=0, high=360, size=32) initial_eigenvector = np.identity(16)[0] print(get_linear_entangelment_ansatz(4, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24) initial_eigenvector = np.identity(8)[0] print(get_linear_entangelment_ansatz(3, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16) initial_eigenvector = np.identity(4)[0] print(get_linear_entangelment_ansatz(2, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=32) initial_eigenvector = np.identity(16)[0] print(get_full_entangelment_ansatz(4, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24) initial_eigenvector = np.identity(8)[0] print(get_full_entangelment_ansatz(3, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16) initial_eigenvector = np.identity(4)[0] print(get_full_entangelment_ansatz(2, initial_thetas, 3))
https://github.com/Tojarieh97/VQE
Tojarieh97
from qiskit.algorithms import VQE from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend=backend, shots=800, seed_transpiler=seed, seed_simulator=seed) from qiskit.algorithms.optimizers import L_BFGS_B bfgs_optimizer = L_BFGS_B(maxiter=60) import numpy as np from qiskit.opflow import X, Z, I a_1 = np.random.random_sample() a_2 = np.random.random_sample() J_21 = np.random.random_sample() H_transverse_ising = a_1*(I^X) + a_2*(X^I) + J_21*(Z^Z) print("========== Transverse Ising Model Hamiltonian for Two Qubits ==========\n") print(H_transverse_ising.to_matrix()) print() H2_molecule_Hamiltonian = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) print("========== H2 Molecule Hamiltonian for Two Qubits ==========\n") print(H2_molecule_Hamiltonian.to_matrix()) print() from qiskit.circuit.library import EfficientSU2 def minimum_eigenvalue_by_vqe(num_qubits, ansatz_entanglement, optimizer, quantum_instance, hamiltonian): ansatz = EfficientSU2(num_qubits=num_qubits, entanglement=entanglement) vqe = VQE(ansatz, optimizer, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(hamiltonian) print(result) num_qubits = 2 entanglement = "linear" minimum_eigenvalue_by_vqe(num_qubits, entanglement, bfgs_optimizer, quantum_instance, H_transverse_ising) num_qubits = 2 entanglement = "full" minimum_eigenvalue_by_vqe(num_qubits, entanglement, bfgs_optimizer, quantum_instance, H_transverse_ising) num_qubits = 2 entanglement = "linear" minimum_eigenvalue_by_vqe(num_qubits, entanglement, bfgs_optimizer, quantum_instance, H2_molecule_Hamiltonian) num_qubits = 2 entanglement = "full" minimum_eigenvalue_by_vqe(num_qubits, entanglement, bfgs_optimizer, quantum_instance, H2_molecule_Hamiltonian)
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 50 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in zip(pauli_coeffs, pauli_strings): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=360, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="BFGS", options={"maxiter":NUM_ITERATIONS, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[0] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3) approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 50 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 50 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 50 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} print(sum(proba_distribution.values())) return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) print(counts) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile import random def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) print(approximated_energies) insert_approximated_energy_to_list_of_all_approximated_energies(L) print(approximated_energies) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="COBYLA", options={"maxiter":NUM_ITERATIONS, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[0] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(exact_eigenvalue, margin=3) approximated_energies = [] approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) def initialize_approximated_energy_to_list_of_all_approximated_energies(approximated_energies): approximated_energies = [] import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 from qiskit.circuit.library.standard_gates import RXGate, RZGate, RYGate, CXGate, CZGate, SGate, HGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister import numpy as np def get_linear_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3): quantum_register = QuantumRegister(num_of_qubits, name="qubit") quantum_circuit = QuantumCircuit(quantum_register) quantum_circuit.initialize(input_state) for iteration in range(circuit_depth): for qubit_index in range(num_of_qubits): RY_theta_index = iteration*2*num_of_qubits + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) for qubit_index in range(num_of_qubits - 1): quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[qubit_index + 1]]) for qubit_index in range(num_of_qubits): RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) return quantum_circuit def get_full_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3): quantum_register = QuantumRegister(num_of_qubits, name="qubit") quantum_circuit = QuantumCircuit(quantum_register) quantum_circuit.initialize(input_state) for iteration in range(circuit_depth): for qubit_index in range(num_of_qubits): RY_theta_index = iteration*2*num_of_qubits + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) for qubit_index in range(num_of_qubits - 1): for target_qubit_index in range(qubit_index + 1, num_of_qubits): quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[target_qubit_index]]) for qubit_index in range(num_of_qubits): RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) return quantum_circuit initial_thetas = np.random.uniform(low=0, high=360, size=32) initial_eigenvector = np.identity(16)[0] print(get_linear_entangelment_ansatz(4, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24) initial_eigenvector = np.identity(8)[0] print(get_linear_entangelment_ansatz(3, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16) initial_eigenvector = np.identity(4)[0] print(get_linear_entangelment_ansatz(2, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=32) initial_eigenvector = np.identity(16)[0] print(get_full_entangelment_ansatz(4, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24) initial_eigenvector = np.identity(8)[0] print(get_full_entangelment_ansatz(3, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16) initial_eigenvector = np.identity(4)[0] print(get_full_entangelment_ansatz(2, initial_thetas, 3))
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="COBYLA", options={"maxiter":NUM_ITERATIONS, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[0] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3) approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 100 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=360, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="COBYLA", options={"maxiter":NUM_ITERATIONS, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[0] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3) approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 100 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 100 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 50 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} print(sum(proba_distribution.values())) return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) print(counts) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile import random def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="COBYLA", options={"maxiter":NUM_ITERATIONS, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[0] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(exact_eigenvalue, margin=3) approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 from qiskit.circuit.library.standard_gates import RXGate, RZGate, RYGate, CXGate, CZGate, SGate, HGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister import numpy as np def get_linear_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3): quantum_register = QuantumRegister(num_of_qubits, name="qubit") quantum_circuit = QuantumCircuit(quantum_register) quantum_circuit.initialize(input_state) for iteration in range(circuit_depth): for qubit_index in range(num_of_qubits): RY_theta_index = iteration*2*num_of_qubits + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) for qubit_index in range(num_of_qubits - 1): quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[qubit_index + 1]]) for qubit_index in range(num_of_qubits): RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) return quantum_circuit def get_full_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3): quantum_register = QuantumRegister(num_of_qubits, name="qubit") quantum_circuit = QuantumCircuit(quantum_register) quantum_circuit.initialize(input_state) for iteration in range(circuit_depth): for qubit_index in range(num_of_qubits): RY_theta_index = iteration*2*num_of_qubits + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) for qubit_index in range(num_of_qubits - 1): for target_qubit_index in range(qubit_index + 1, num_of_qubits): quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[target_qubit_index]]) for qubit_index in range(num_of_qubits): RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index RZ_theta_index = RY_theta_index + num_of_qubits quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]]) quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]]) return quantum_circuit initial_thetas = np.random.uniform(low=0, high=360, size=32) initial_eigenvector = np.identity(16)[0] print(get_linear_entangelment_ansatz(4, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24) initial_eigenvector = np.identity(8)[0] print(get_linear_entangelment_ansatz(3, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16) initial_eigenvector = np.identity(4)[0] print(get_linear_entangelment_ansatz(2, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=32) initial_eigenvector = np.identity(16)[0] print(get_full_entangelment_ansatz(4, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24) initial_eigenvector = np.identity(8)[0] print(get_full_entangelment_ansatz(3, initial_thetas, 3)) initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16) initial_eigenvector = np.identity(4)[0] print(get_full_entangelment_ansatz(2, initial_thetas, 3))
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 100 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="CG", options={"maxiter":NUM_ITERATIONS, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[0] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3) approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 100 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="L-BFGS-B", options={"maxiter":NUM_ITERATIONS, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[0] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3) approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 1000 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 100 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in zip(pauli_coeffs, pauli_strings): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="Nelder-Mead", options={"maxiter":NUM_ITERATIONS, "return_all": True, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[3] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3) approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)