repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
string qasmStr = "" qasmStr print(qasmStr)
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
ILUA_LOG_LEVEL=debug a =2 q_command -- our API object q_command = {} q_command.tools_placed = false q_command.game_running_time = 0 q_command.block_pos = {} q_command.circuit_specs = {} -- dir_str, pos, num_wires, num_columns, is_on_grid q_command.circuit_specs.pos = {} -- x, y, z function q_command:create_qasm_for_node(circuit_node_pos, wire_num, include_measurement_blocks, c_if_table, tomo_meas_basis) local qasm_str = "" local circuit_node_block = circuit_blocks:get_circuit_block(circuit_node_pos) local q_block = q_command:get_q_command_block(circuit_node_pos) if circuit_node_block then local node_type = circuit_node_block.get_node_type() if node_type == CircuitNodeTypes.EMPTY or node_type == CircuitNodeTypes.TRACE or node_type == CircuitNodeTypes.CTRL then -- Throw away a c_if if present c_if_table[wire_num] = "" -- Return immediately with zero length qasm_str return qasm_str else if c_if_table[wire_num] and c_if_table[wire_num] ~= "" then qasm_str = qasm_str .. c_if_table[wire_num] .. " " c_if_table[wire_num] = "" end end local ctrl_a = circuit_node_block.get_ctrl_a() local ctrl_b = circuit_node_block.get_ctrl_b() local swap = circuit_node_block.get_swap() local radians = circuit_node_block.get_radians() -- For convenience and brevity, create a zero-based, string, wire number --local wire_num_idx = tostring(wire_num - 1 + -- circuit_node_block.get_circuit_specs_wire_num_offset()) --local ctrl_a_idx = tostring(ctrl_a - 1 + -- circuit_node_block.get_circuit_specs_wire_num_offset()) --local ctrl_b_idx = tostring(ctrl_b - 1 + -- circuit_node_block.get_circuit_specs_wire_num_offset()) -- TODO: Replace above with below? local wire_num_idx = tostring(wire_num - 1) local ctrl_a_idx = tostring(ctrl_a - 1) local ctrl_b_idx = tostring(ctrl_b - 1) local swap_idx = tostring(swap - 1) if node_type == CircuitNodeTypes.IDEN then -- Identity gate qasm_str = qasm_str .. 'id q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.X then local threshold = 0.0001 if math.abs(radians - math.pi) <= threshold then if ctrl_a ~= -1 then if ctrl_b ~= -1 then -- Toffoli gate qasm_str = qasm_str .. 'ccx q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. ctrl_b_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' else -- Controlled X gate qasm_str = qasm_str .. 'cx q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' end else -- Pauli-X gate qasm_str = qasm_str .. 'x q[' .. wire_num_idx .. '];' end else -- Rotation around X axis qasm_str = qasm_str .. 'rx(' .. tostring(radians) .. ') ' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' end elseif node_type == CircuitNodeTypes.Y then local threshold = 0.0001 if math.abs(radians - math.pi) <= threshold then if ctrl_a ~= -1 then -- Controlled Y gate qasm_str = qasm_str .. 'cy q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' else -- Pauli-Y gate qasm_str = qasm_str .. 'y q[' .. wire_num_idx .. '];' end else -- Rotation around Y axis qasm_str = qasm_str .. 'ry(' .. tostring(radians) .. ') ' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' end elseif node_type == CircuitNodeTypes.Z then local threshold = 0.0001 if math.abs(radians - math.pi) <= threshold then if ctrl_a ~= -1 then -- Controlled Z gate qasm_str = qasm_str .. 'cz q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' else -- Pauli-Z gate qasm_str = qasm_str .. 'z q[' .. wire_num_idx .. '];' end else if circuit_node_block.get_ctrl_a() ~= -1 then -- Controlled rotation around the Z axis qasm_str = qasm_str .. 'crz(' .. tostring(radians) .. ') ' qasm_str = qasm_str .. 'q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' else -- Rotation around Z axis qasm_str = qasm_str .. 'rz(' .. tostring(radians) .. ') ' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' end end elseif node_type == CircuitNodeTypes.S then -- S gate qasm_str = qasm_str .. 's q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.SDG then -- S dagger gate qasm_str = qasm_str .. 'sdg q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.T then -- T gate qasm_str = qasm_str .. 't q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.TDG then -- T dagger gate qasm_str = qasm_str .. 'tdg q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.H then if ctrl_a ~= -1 then -- Controlled Hadamard qasm_str = qasm_str .. 'ch q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' else -- Hadamard gate qasm_str = qasm_str .. 'h q[' .. wire_num_idx .. '];' end elseif node_type == CircuitNodeTypes.BARRIER then -- barrier qasm_str = qasm_str .. 'barrier q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.MEASURE_Z then if include_measurement_blocks then -- Measurement block --qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c[' .. wire_num_idx .. '];' qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c' .. wire_num_idx .. '[0];' end elseif node_type == CircuitNodeTypes.QUBIT_BASIS then qasm_str = qasm_str .. 'reset q[' .. wire_num_idx .. '];' if circuit_node_block.get_node_name():sub(-2) == "_1" then qasm_str = qasm_str .. 'x q[' .. wire_num_idx .. '];' end elseif node_type == CircuitNodeTypes.CONNECTOR_M then -- Connector to wire extension, so traverse local wire_extension_block_pos = circuit_node_block.get_wire_extension_block_pos() if wire_extension_block_pos.x ~= 0 then local wire_extension_block = circuit_blocks:get_circuit_block(wire_extension_block_pos) local wire_extension_dir_str = wire_extension_block.get_circuit_dir_str() local wire_extension_circuit_pos = wire_extension_block.get_circuit_pos() if wire_extension_circuit_pos.x ~= 0 then local wire_extension_circuit = circuit_blocks:get_circuit_block(wire_extension_circuit_pos) local extension_wire_num = wire_extension_circuit.get_circuit_specs_wire_num_offset() + 1 local extension_num_columns = wire_extension_circuit.get_circuit_num_columns() for column_num = 1, extension_num_columns do -- Assume dir_str is "+Z" local circ_node_pos = {x = wire_extension_circuit_pos.x + column_num - 1, y = wire_extension_circuit_pos.y, z = wire_extension_circuit_pos.z} if wire_extension_dir_str == "+X" then circ_node_pos = {x = wire_extension_circuit_pos.x, y = wire_extension_circuit_pos.y, z = wire_extension_circuit_pos.z - column_num + 1} elseif wire_extension_dir_str == "-X" then circ_node_pos = {x = wire_extension_circuit_pos.x, y = wire_extension_circuit_pos.y, z = wire_extension_circuit_pos.z + column_num - 1} elseif wire_extension_dir_str == "-Z" then circ_node_pos = {x = wire_extension_circuit_pos.x - column_num + 1, y = wire_extension_circuit_pos.y, z = wire_extension_circuit_pos.z} end qasm_str = qasm_str .. q_command:create_qasm_for_node(circ_node_pos, extension_wire_num, include_measurement_blocks, c_if_table, tomo_meas_basis) end end end elseif node_type == CircuitNodeTypes.SWAP and swap ~= -1 then if ctrl_a ~= -1 then -- Controlled Swap qasm_str = qasm_str .. 'cswap q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '],' qasm_str = qasm_str .. 'q[' .. swap_idx .. '];' else -- Swap gate qasm_str = qasm_str .. 'swap q[' .. wire_num_idx .. '],' qasm_str = qasm_str .. 'q[' .. swap_idx .. '];' end elseif node_type == CircuitNodeTypes.C_IF then local node_name = circuit_node_block.get_node_name() local register_idx_str = node_name:sub(35, 35) local eq_val_str = node_name:sub(39, 39) c_if_table[wire_num] = "if(c" .. register_idx_str .. "==" .. eq_val_str .. ")" elseif node_type == CircuitNodeTypes.BLOCH_SPHERE or node_type == CircuitNodeTypes.COLOR_QUBIT then if include_measurement_blocks then if tomo_meas_basis == 1 then -- Measure in the X basis (by first rotating -pi/2 radians on Y axis) qasm_str = qasm_str .. 'ry(' .. tostring(-math.pi / 2) .. ') ' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' elseif tomo_meas_basis == 2 then -- Measure in the Y basis (by first rotating pi/2 radians on X axis) qasm_str = qasm_str .. 'rx(' .. tostring(math.pi / 2) .. ') ' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' elseif tomo_meas_basis == 3 then -- Measure in the Z basis (no rotation necessary) end qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c' .. wire_num_idx .. '[0];' end end else print("Unknown gate!") end if LOG_DEBUG then minetest.debug("End of create_qasm_for_node(), qasm_str:\n" .. qasm_str) end return qasm_str end
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
-- our API object q_command = {} q_command.tools_placed = false q_command.game_running_time = 0 q_command.block_pos = {} q_command.circuit_specs = {} -- dir_str, pos, num_wires, num_columns, is_on_grid q_command.circuit_specs.pos = {} -- x, y, z function q_command:create_qasm_for_node(circuit_node_pos, wire_num, include_measurement_blocks, c_if_table, tomo_meas_basis) local qasm_str = "" local circuit_node_block = circuit_blocks:get_circuit_block(circuit_node_pos) local q_block = q_command:get_q_command_block(circuit_node_pos) if circuit_node_block then local node_type = circuit_node_block.get_node_type() if node_type == CircuitNodeTypes.EMPTY or node_type == CircuitNodeTypes.TRACE or node_type == CircuitNodeTypes.CTRL then -- Throw away a c_if if present c_if_table[wire_num] = "" -- Return immediately with zero length qasm_str return qasm_str else if c_if_table[wire_num] and c_if_table[wire_num] ~= "" then qasm_str = qasm_str .. c_if_table[wire_num] .. " " c_if_table[wire_num] = "" end end local ctrl_a = circuit_node_block.get_ctrl_a() local ctrl_b = circuit_node_block.get_ctrl_b() local swap = circuit_node_block.get_swap() local radians = circuit_node_block.get_radians() -- For convenience and brevity, create a zero-based, string, wire number --local wire_num_idx = tostring(wire_num - 1 + -- circuit_node_block.get_circuit_specs_wire_num_offset()) --local ctrl_a_idx = tostring(ctrl_a - 1 + -- circuit_node_block.get_circuit_specs_wire_num_offset()) --local ctrl_b_idx = tostring(ctrl_b - 1 + -- circuit_node_block.get_circuit_specs_wire_num_offset()) -- TODO: Replace above with below? local wire_num_idx = tostring(wire_num - 1) local ctrl_a_idx = tostring(ctrl_a - 1) local ctrl_b_idx = tostring(ctrl_b - 1) local swap_idx = tostring(swap - 1) if node_type == CircuitNodeTypes.IDEN then -- Identity gate qasm_str = qasm_str .. 'id q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.X then local threshold = 0.0001 if math.abs(radians - math.pi) <= threshold then if ctrl_a ~= -1 then if ctrl_b ~= -1 then -- Toffoli gate qasm_str = qasm_str .. 'ccx q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. ctrl_b_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' else -- Controlled X gate qasm_str = qasm_str .. 'cx q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' end else -- Pauli-X gate qasm_str = qasm_str .. 'x q[' .. wire_num_idx .. '];' end else -- Rotation around X axis qasm_str = qasm_str .. 'rx(' .. tostring(radians) .. ') ' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' end elseif node_type == CircuitNodeTypes.Y then local threshold = 0.0001 if math.abs(radians - math.pi) <= threshold then if ctrl_a ~= -1 then -- Controlled Y gate qasm_str = qasm_str .. 'cy q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' else -- Pauli-Y gate qasm_str = qasm_str .. 'y q[' .. wire_num_idx .. '];' end else -- Rotation around Y axis qasm_str = qasm_str .. 'ry(' .. tostring(radians) .. ') ' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' end elseif node_type == CircuitNodeTypes.Z then local threshold = 0.0001 if math.abs(radians - math.pi) <= threshold then if ctrl_a ~= -1 then -- Controlled Z gate qasm_str = qasm_str .. 'cz q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' else -- Pauli-Z gate qasm_str = qasm_str .. 'z q[' .. wire_num_idx .. '];' end else if circuit_node_block.get_ctrl_a() ~= -1 then -- Controlled rotation around the Z axis qasm_str = qasm_str .. 'crz(' .. tostring(radians) .. ') ' qasm_str = qasm_str .. 'q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' else -- Rotation around Z axis qasm_str = qasm_str .. 'rz(' .. tostring(radians) .. ') ' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' end end elseif node_type == CircuitNodeTypes.S then -- S gate qasm_str = qasm_str .. 's q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.SDG then -- S dagger gate qasm_str = qasm_str .. 'sdg q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.T then -- T gate qasm_str = qasm_str .. 't q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.TDG then -- T dagger gate qasm_str = qasm_str .. 'tdg q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.H then if ctrl_a ~= -1 then -- Controlled Hadamard qasm_str = qasm_str .. 'ch q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' else -- Hadamard gate qasm_str = qasm_str .. 'h q[' .. wire_num_idx .. '];' end elseif node_type == CircuitNodeTypes.BARRIER then -- barrier qasm_str = qasm_str .. 'barrier q[' .. wire_num_idx .. '];' elseif node_type == CircuitNodeTypes.MEASURE_Z then if include_measurement_blocks then -- Measurement block --qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c[' .. wire_num_idx .. '];' qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c' .. wire_num_idx .. '[0];' end elseif node_type == CircuitNodeTypes.QUBIT_BASIS then qasm_str = qasm_str .. 'reset q[' .. wire_num_idx .. '];' if circuit_node_block.get_node_name():sub(-2) == "_1" then qasm_str = qasm_str .. 'x q[' .. wire_num_idx .. '];' end elseif node_type == CircuitNodeTypes.CONNECTOR_M then -- Connector to wire extension, so traverse local wire_extension_block_pos = circuit_node_block.get_wire_extension_block_pos() if wire_extension_block_pos.x ~= 0 then local wire_extension_block = circuit_blocks:get_circuit_block(wire_extension_block_pos) local wire_extension_dir_str = wire_extension_block.get_circuit_dir_str() local wire_extension_circuit_pos = wire_extension_block.get_circuit_pos() if wire_extension_circuit_pos.x ~= 0 then local wire_extension_circuit = circuit_blocks:get_circuit_block(wire_extension_circuit_pos) local extension_wire_num = wire_extension_circuit.get_circuit_specs_wire_num_offset() + 1 local extension_num_columns = wire_extension_circuit.get_circuit_num_columns() for column_num = 1, extension_num_columns do -- Assume dir_str is "+Z" local circ_node_pos = {x = wire_extension_circuit_pos.x + column_num - 1, y = wire_extension_circuit_pos.y, z = wire_extension_circuit_pos.z} if wire_extension_dir_str == "+X" then circ_node_pos = {x = wire_extension_circuit_pos.x, y = wire_extension_circuit_pos.y, z = wire_extension_circuit_pos.z - column_num + 1} elseif wire_extension_dir_str == "-X" then circ_node_pos = {x = wire_extension_circuit_pos.x, y = wire_extension_circuit_pos.y, z = wire_extension_circuit_pos.z + column_num - 1} elseif wire_extension_dir_str == "-Z" then circ_node_pos = {x = wire_extension_circuit_pos.x - column_num + 1, y = wire_extension_circuit_pos.y, z = wire_extension_circuit_pos.z} end qasm_str = qasm_str .. q_command:create_qasm_for_node(circ_node_pos, extension_wire_num, include_measurement_blocks, c_if_table, tomo_meas_basis) end end end elseif node_type == CircuitNodeTypes.SWAP and swap ~= -1 then if ctrl_a ~= -1 then -- Controlled Swap qasm_str = qasm_str .. 'cswap q[' .. ctrl_a_idx .. '],' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '],' qasm_str = qasm_str .. 'q[' .. swap_idx .. '];' else -- Swap gate qasm_str = qasm_str .. 'swap q[' .. wire_num_idx .. '],' qasm_str = qasm_str .. 'q[' .. swap_idx .. '];' end elseif node_type == CircuitNodeTypes.C_IF then local node_name = circuit_node_block.get_node_name() local register_idx_str = node_name:sub(35, 35) local eq_val_str = node_name:sub(39, 39) c_if_table[wire_num] = "if(c" .. register_idx_str .. "==" .. eq_val_str .. ")" elseif node_type == CircuitNodeTypes.BLOCH_SPHERE or node_type == CircuitNodeTypes.COLOR_QUBIT then if include_measurement_blocks then if tomo_meas_basis == 1 then -- Measure in the X basis (by first rotating -pi/2 radians on Y axis) qasm_str = qasm_str .. 'ry(' .. tostring(-math.pi / 2) .. ') ' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' elseif tomo_meas_basis == 2 then -- Measure in the Y basis (by first rotating pi/2 radians on X axis) qasm_str = qasm_str .. 'rx(' .. tostring(math.pi / 2) .. ') ' qasm_str = qasm_str .. 'q[' .. wire_num_idx .. '];' elseif tomo_meas_basis == 3 then -- Measure in the Z basis (no rotation necessary) end qasm_str = qasm_str .. 'measure q[' .. wire_num_idx .. '] -> c' .. wire_num_idx .. '[0];' end end else print("Unknown gate!") end if LOG_DEBUG then minetest.debug("End of create_qasm_for_node(), qasm_str:\n" .. qasm_str) end return qasm_str end
https://github.com/HuangJunye/Qiskit-for-GameDev
HuangJunye
from qiskit import QuantumCircuit from circuit_grid import CircuitGridModel, CircuitGridNode import circuit_node_types as node_types from sympy import pi import logging id_gate = CircuitGridNode(node_types.ID) x_gate = CircuitGridNode(node_types.X, 1) y_gate = CircuitGridNode(node_types.Y, 1) z_gate = CircuitGridNode(node_types.Z, 1) h_gate = CircuitGridNode(node_types.H, 1) s_gate = CircuitGridNode(node_types.S, 1) sdg_gate = CircuitGridNode(node_types.SDG, 1) t_gate = CircuitGridNode(node_types.T, 1) tdg_gate = CircuitGridNode(node_types.TDG, 1) u1_gate = CircuitGridNode(node_types.U1, 1, theta=pi) u2_gate = CircuitGridNode(node_types.U2, 1, theta=pi, phi=pi) u3_gate = CircuitGridNode(node_types.U3, 1, theta=pi, phi=pi, lam=pi) rx_gate = CircuitGridNode(node_types.RX, 1, theta=pi) ry_gate = CircuitGridNode(node_types.RY, 1, theta=pi) rz_gate = CircuitGridNode(node_types.RZ, 1, theta=pi) cx_gate = CircuitGridNode(node_types.CX, 1, ctrl_a=0) cy_gate = CircuitGridNode(node_types.CY, 2, ctrl_a=1) cz_gate = CircuitGridNode(node_types.CZ, 3, ctrl_a=2) ch_gate = CircuitGridNode(node_types.CH, 4, ctrl_a=3) crz_gate = CircuitGridNode(node_types.CRZ, 1, theta=pi, ctrl_a=0) cu1_gate = CircuitGridNode(node_types.CU1, 1, theta=pi, ctrl_a=0) cu3_gate = CircuitGridNode(node_types.CU3, 1, theta=pi, phi=pi, lam=pi, ctrl_a=0) ccx_gate = CircuitGridNode(node_types.CCX, 2, ctrl_a=0, ctrl_b=1) swap_gate = CircuitGridNode(node_types.SWAP, 1, swap=2) cswap_gate = CircuitGridNode(node_types.CSWAP, 1, ctrl_a=0, swap=2) barrier = CircuitGridNode(node_types.BARRIER, 1) measure_z = CircuitGridNode(node_types.MEASURE_Z, 1) reset = CircuitGridNode(node_types.RESET, 1) _if = CircuitGridNode(node_types.IF, 1) gates = [ id_gate, x_gate, y_gate, z_gate, h_gate, s_gate, sdg_gate, t_gate, tdg_gate, u1_gate, u2_gate, u3_gate, rx_gate, ry_gate, rz_gate, cx_gate, cy_gate, cz_gate, ch_gate, crz_gate, cu1_gate, cu3_gate, ccx_gate, swap_gate, cswap_gate, barrier, measure_z, reset, _if ] for gate in gates: print(gate) for gate in gates: print(gate.qasm()) circuit_grid = CircuitGridModel(4,5) print(circuit_grid) print(gates[0]) for j in range(circuit_grid.circuit_depth): for i in range(circuit_grid.qubit_count): circuit_grid.set_node(i,j,gates[i*circuit_grid.circuit_depth + j]) qasm_str = circuit_grid.create_qasm_for_circuit() print(qasm_str) qc = QuantumCircuit.from_qasm_str(qasm_str) qc.draw()
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
#Declaring variables a = 2 print(a) print(type(a)) #This is an integer #True and False are special keywords in python boolean = True print(boolean) print(type(boolean)) #Here 7e-2 is 7x10^-2 and the 1j actually is the square root of -1 b = 7e-2 + (8e-2)*1j print(b) print(type(b)) # This is a complex number #We will now try to re initiallize variable a and it will change its class a = 7.2 print(a) print(type(a)) #this is a float string = "a word" print(string) print(type(string)) #Type conversions can be done too a_s = str(a) bool3 = bool(a) print(a_s) print(type(a_s)) print(bool3) print(type(bool3)) #we also have lists, dictionaries and tuples list1 = [1,2,3,4,5,6,"word"] # A list. Same as an array and is dynamic in length dict1 = {1: 3, 'k':'f'} #A dictionary. This maps the first one as index to the second term as value tuple1 = (1,2,4,5,0,-1,dict1) #A tuple. This is a collection of objects which get reordered are cannot be changed once assigned (immutable) print(list1) print(type(list1)) print(dict1) print(type(dict1)) print(tuple1) print(type(tuple1)) print(list1[-1])#Prints last index print(dict1['k'])#Prints the mapped value to 'k' #Using is var1 = 78 tuple2 = (1,2,4,5,0,-1,dict1) print(var1 is 78)#This will be true print(tuple1 is tuple2)#This will be false since tuples,lists and dicts essentially are addresses #Hence even when they have same value, is requires also same addresses print(tuple1 == tuple2)#This shows true since == checks equality in values print(tuple1[-1] is tuple1[-1])#This is true since these both point to the same variable var2 = 1 print(var2 in list1)#Shows true since var2 is infact in this list bool1 = True bool2 = False print(bool1 and bool2) print(bool1 or bool2) print(not bool2) if bool1: print('bool1 is true')#This one is executed as per our declarations elif not bool2: print('bool2 is false and so is bool1')#This one isnt reached else: print('bool1 is false but bool2 is true')#This one isnt reached for i in list1: print(i) for i in range(10):#iterates over numbers 0 to 9 both included print(i) print(" ") for i in range(1,10):#iterates over numbers 1 to 9 both included print(i) for k,d in dict1.items(): print(k,d) g = 100 while(g > 0): g = g//2#This returns the integer division of g print(g) def myfunc(a):#takes an input of a return a*2 #returns the double of a print(myfunc(2))#Calls function giving 2 as input print(myfunc(3.4 + 4j)) print(myfunc(list1)) def myfunc2(*args):# we use *args when we do not know how many arguments will be sent s = 0 for i in args: s = s + i return s print(myfunc2(34)) print(myfunc2(34,35,36)) def myfunc3(**kwargs):#we use **kwargs when we are to receive unkown number of keyword arguments #A keyword argument is where you provide a name to the variable as you pass it into the function. for i,j in kwargs.items(): print(i,j) myfunc3(x1 = 1, x2 = "abcd", x3 = list1) add = lambda a,b: a+b #A lamda function takes arguments and returns only one value print(add(list1,list1)) #essentially adds the list to itself import numpy as np #imports the package numpy and we have renamed it to np so our code looks cleaner print(np.pi)#Good old pi arr = np.array([[1,3],[4,2]])#Essentially an array and the argument given print(arr) print(arr.shape)#this gives the shape of the arr arr2 = np.array([[0.3,8j],[9j,0]]) arr3 = np.matmul(arr2,arr)#this will give the matrix multiplication of arr2*arr print(arr3)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() # The '0' state plot_bloch_vector([0,0,1]) # The '1' state plot_bloch_vector([0,0,-1]) qc1 = QuantumCircuit(2,2) # Initializing a quantum ciruit (2 qubits, 2 classical bits) # All initialized to '0' by default. qc1.draw(output='mpl') # Draws the circuit diagram qc1.x(0) # Applying X gate to the first qubit qc1.draw(output='mpl') qc1.x(1) # Applying X gate to the second qubit qc1.draw(output='mpl') # The '+' state plot_bloch_vector([1,0,0]) # The '-' state plot_bloch_vector([-1,0,0]) qc2 = QuantumCircuit(2,2) # A new quantum circuit with 2 qubits and 2 classical bits qc2.h(0) # Applying the Hadamard gate on first qubit qc2.draw(output='mpl') qc2.cx(0,1) # Applying CX gate ('control','target') qc2.draw(output='mpl') qc2.measure(0,0) # Measure first qubit and store it in first classical bit qc2.measure(1,1) # Measure second qubit and store it in second classical bit # The code below plots a histogram of the measurement result. You can copy it for further use. def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc2) print(counts) plot_histogram(counts) qc1.h(0) qc1.cx(0, 1) qc1.draw(output='mpl') qc1.measure(0,0) qc1.measure(1,1) def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 2000).result() counts = result.get_counts() return counts counts = run_circuit(qc1) print(counts) plot_histogram(counts) qc3 = QuantumCircuit(3,3) qc3.x(range(3)) # Setting the all qubits to '1' qc3.toffoli(0,1,2) # (control,control,target) qc3.measure(0,0) qc3.measure(1,1) qc3.measure(2,2) def run_circuit(qc3): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc3, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc3) print(counts) plot_histogram(counts) # The output should be '011' as the highest (q2) is flipped because the other two qubits were set to '1' qc4 = QuantumCircuit(2,2) #Applying the Pauli-X gate to quantum bit 0, we turn it into 1 so that the swap outcome is observable. qc4.x(0) qc4.cx(0, 1) qc4.cx(1, 0) qc4.cx(0, 1) qc4.draw(output='mpl') qc4.measure(0,0) qc4.measure(1,1) def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 2000).result() counts = result.get_counts() return counts counts = run_circuit(qc4) print(counts) plot_histogram(counts) qc5 = QuantumCircuit(2,2) #We turn quantum bit 1 into 1 so that we can observe the results of HZH on both 0 (from q0) and 1 (from q1). qc5.x(1) qc5.h((0, 1)) qc5.z((0, 1)) qc5.h((0, 1)) qc5.draw(output='mpl') qc5.measure(0,0) qc5.measure(1,1) def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 2000).result() counts = result.get_counts() return counts counts = run_circuit(qc5) print(counts) plot_histogram(counts) qc6 = QuantumCircuit(3,3) #Initializing quantum bits using gates: #q0 is initialized to 0. #q1 is initialized to 1. qc6.x(1) #q2 is initialized to the state given above. qc6.x(2) qc6.h(2) qc6.t(2) #We change q2 for the controlled swap now; we'll bring it back to the same state afterwards. qc6.tdg(2) qc6.h(2) #Controlled swap. qc6.toffoli(0, 2, 1) qc6.toffoli(1, 2, 0) qc6.toffoli(0, 2, 1) #We convert q2 back to whatever it was. qc6.h(2) qc6.t(2) qc6.draw(output='mpl') qc6.measure(0, 0) qc6.measure(1, 1) qc6.measure(2, 2) def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 2000).result() counts = result.get_counts() return counts counts = run_circuit(qc6) print(counts) plot_histogram(counts)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() qc1 = QuantumCircuit(3,3) # All initialized to '0' by default. qc1.x(0) #This is for the purpose of setting the control qubit to '1' qc1.x(2) #As a result, the second target qubit becomes '1' while the first remains '0'. Now, lets's try swapping them. #Fredkin gate: def fredkin(qc): qc.toffoli(0,1,2) qc.toffoli(0,2,1) qc.toffoli(0,1,2) fredkin(qc1) qc1.draw('mpl') #First let's measure all three qubits. #We're using the classical bits to store the result obtained on measuring each corresponding qubit. qc1.measure(0,0) qc1.measure(1,1) qc1.measure(2,2) #Now we use the same function we defined yesterday to run a quantum circuit def run_circuit(qc2): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc2, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts1=run_circuit(qc1) print(counts1) plot_histogram(counts1) qc2 = QuantumCircuit(3,3) # All initialized to '0' by default. qc2.x(2) #The second target qubit is initialised to '1' fredkin(qc2) qc2.measure(0,0) qc2.measure(1,1) qc2.measure(2,2) qc2.draw(output='mpl') counts2=run_circuit(qc2) print(counts2) plot_histogram(counts2) qc = QuantumCircuit(1) #This is how we apply the rotation operators in Qiskit, mentioning the angle of rotation and qubit no. as parameters qc.rx(np.pi/2, 0) qc.draw('mpl') def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate print(final_vector(qc)) # This prints the vector obtained on applying the above gate to the qubit state '0' # The Pauli-X gate serves this purpose, as demonstrated below: qc3 = QuantumCircuit(1) theta = np.pi/7 qc3.x(0) qc3.ry(theta, 0) qc3.x(0) print(final_vector(qc3)) qc3 = QuantumCircuit(1) qc3.ry(-theta, 0) print(final_vector(qc3)) #Run this code for different values of theta and see if the two vectors printed are equal in each case qc4 = QuantumCircuit(1) alpha = np.pi/2 beta = 0 gamma = np.pi/2 delta = np.pi def A(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) C(qc4, 0, beta, delta) qc4.x(0) B(qc4, 0, beta, gamma, delta) qc4.x(0) A(qc4, 0, beta, gamma) qc4.unitary([[1.j, 0.], [0., 1.j]], [0]) print(final_vector(qc4)) qc4 = QuantumCircuit(1) qc4.h(0) print(final_vector(qc4)) qc5 = QuantumCircuit(3, 3) # Target qubit q1 is initially |1> and target qubit q2 is initially |0>. qc5.x(0) # Control qubit initialized to |1> to see effects of controlled Hadamard. qc5.x(1) # One target qubit initialized to |1>. alpha = np.pi/2 beta = 0 gamma = np.pi/2 delta = np.pi def A(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) C(qc5, [1, 2], beta, delta) qc5.cx(0, [1, 2]) B(qc5, [1, 2], beta, gamma, delta) qc5.cx(0, [1, 2]) A(qc5, [1, 2], beta, gamma) qc5.s(0) # Using S gate because alpha = pi/2 qc5.measure(0, 0) qc5.measure(1, 1) qc5.measure(2, 2) qc5.draw('mpl') def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 10000).result() counts = result.get_counts() return counts counts = run_circuit(qc5) print(counts) plot_histogram(counts) qc_u3=QuantumCircuit(1) qc_u3.u3(np.pi/6,-np.pi/2,np.pi/2,0) print(final_vector(qc_u3)) qc_rx=QuantumCircuit(1) qc_rx.rx(np.pi/6,0) print(final_vector(qc_rx)) #Getting the same results will verify our observation stated above ######### Defining some constants and functions ########## # Constants for the decomposition of Hadamard gate. H_alpha = np.pi/2 H_beta = 0 H_gamma = np.pi/2 H_delta = np.pi # V^2 = X V = [[0.5+0.5j, 0.5-0.5j], [0.5-0.5j, 0.5+0.5j]] # Constants for the decomposition of V (where V^2 = X). V_alpha = np.pi/4 V_beta = np.pi/2 V_gamma = -np.pi/2 V_delta = -np.pi/2 # Functions to implement A, B, C (generalized). def A_gate(qc, qbits, beta, gamma): qc.ry(gamma/2, qbits) qc.rz(beta, qbits) def B_gate(qc, qbits, beta, gamma, delta): qc.rz(-(beta+delta)/2, qbits) qc.ry(-gamma/2, qbits) def C_gate(qc, qbits, beta, delta): qc.rz((delta-beta)/2, qbits) # Higher abstraction functions. def controlled_V(qc, control, target): C_gate(qc, target, V_beta, V_delta) qc.cx(control, target) B_gate(qc, target, V_beta, V_gamma, V_delta) qc.cx(control, target) A_gate(qc, target, V_beta, V_gamma) qc.t(control) # Using T gate because V_alpha = pi/4. def controlled_Vdg(qc, control, target): C_gate(qc, target, V_beta, V_delta) qc.cx(control, target) B_gate(qc, target, V_beta, -V_gamma, V_delta) qc.cx(control, target) A_gate(qc, target, V_beta, -V_gamma) qc.tdg(control) # Using Tdg gate because V_alpha = pi/4, so Vdg_alpha would be -pi/4. def double_controlled_X(qc, control1, control2, target): controlled_V(qc, control2, target) qc.cx(control1, control2) controlled_Vdg(qc, control2, target) qc.cx(control1, control2) controlled_V(qc, control1, target) ############ Constructing the circuit ############## qc6 = QuantumCircuit(7, 5) # No need to measure ancillary qubits :P # q0, q1, q2, q3 are control qubits # q4, q5 are ancillary qubits # q6 is the target qubit # Change the following line to try different combinations of control qubits: qc6.x([0,1,2,3]) C_gate(qc6, 6, H_beta, H_delta) double_controlled_X(qc6, 0, 1, 4) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 4, 5, 6) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 0, 1, 4) B_gate(qc6, 6, H_beta, H_gamma, H_delta) double_controlled_X(qc6, 0, 1, 4) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 4, 5, 6) double_controlled_X(qc6, 2, 3, 5) double_controlled_X(qc6, 0, 1, 4) A_gate(qc6, 6, H_beta, H_gamma) qc6.s([0,1,2,3]) # Using S gate because H_alpha = pi/2. qc6.measure(0, 0) qc6.measure(1, 1) qc6.measure(2, 2) qc6.measure(3, 3) qc6.measure(6, 4) qc6.draw('mpl') def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') result = execute(qc, backend, shots = 2000).result() counts = result.get_counts() return counts counts = run_circuit(qc6) print(counts) plot_histogram(counts)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() qr = QuantumRegister(3) crz = ClassicalRegister(1) crx = ClassicalRegister(2) # we will need seperates registers for using 'c_if' later. qc = QuantumCircuit(qr,crz,crx) qc.x(0) qc.h(0) # 'psi' can't be unknown to us as we are creating it here. Let us take '-' state as our 'psi' # We will verify later if the '-' is been teleported. qc.h(1) qc.cx(1,2) # creating a bell state qc.barrier() # Use barrier to separate steps, everything till this barrier is just intialisation. qc.cx(0,1) # '0' and '1' are with Alice and '2' is with Bob. # psi_1 prepared. qc.h(0) # psi_2 prepared. qc.barrier() qc.measure(0,0) qc.measure(1,1) qc.draw (output = 'mpl') qc.x(2).c_if(crx,1) # 'c_if' compares a classical register with a value (either 0 or 1) and performs the qc.z(2).c_if(crz,1) # operation if they are equal. qc.draw('mpl') # be careful of the order of applying X and Z! qc.h(2) qc.measure(2,crx[1]) def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc) print(counts) plot_histogram(counts) # the output should be '1xx' if the teleportation is successful. # Refer to above cell for a detailed explanation of the strategy. qc1 = QuantumCircuit(2, 2) # Preparing Alice's Bell state: \beta_{00} qc1.h(0) qc1.cx(0, 1) # Skyler's mischief: # Suppose for this example that she applied Pauli-Y. # You can change 'y' to 'x' or 'z' in the following line for other cases. qc1.y(0) # Alice's strategy: qc1.cx(0, 1) qc1.h(0) qc1.measure(0, 0) qc1.measure(1, 1) qc1.draw('mpl') def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc1) print(counts) if '10' in counts: print('Skyler used Pauli-X!') if '11' in counts: print('Skyler used Pauli-Y!') if '01' in counts: print('Skyler used Pauli-Z!') plot_histogram(counts)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.compiler import * from qiskit.tools.jupyter import * from qiskit.visualization import * import numpy as np import qiskit.quantum_info as qi # Loading your IBM Q account(s) provider = IBMQ.load_account() #This cell is just for seeing what the U tilde matrix looks like a, b, c, d = np.cos(np.pi/8), np.sin(np.pi/8), -np.sin(np.pi/8), np.cos(np.pi/8) u_tilde = np.array([[a,c],[b,d]]).reshape(2,2) print(u_tilde) #This cell defines the controlled variant of the U tilde matrix qc_for_u = QuantumCircuit(1) qc_for_u.ry(np.pi/4, 0) qc_for_u.name = "U" controlled_u_tilde = qc_for_u.to_gate().control(2) qc1 = QuantumCircuit(3) qc1.x(0) qc1.x(1) qc1.toffoli(0,1,2)#Flipping the third bit if the first two are zero qc1.x(0) #Essentially 000 -> 001 qc1.x(1) qc1.x(0) qc1.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one qc1.x(0) #Essentially 001 -> 011 qc1.append(controlled_u_tilde, [1, 2, 0]) qc1.x(0) qc1.toffoli(0,2,1)#Undoing the flip from before qc1.x(0) qc1.x(0) qc1.x(1) qc1.toffoli(0,1,2)#Undoing the flip from before qc1.x(0) qc1.x(1) qc1.draw('mpl') U_circ = qi.Operator(qc1).data print(U_circ) qc2 = QuantumCircuit(3) # Code for U qc2.x(0) qc2.x(1) qc2.toffoli(0,1,2)#Flipping the third bit if the first two are zero qc2.x(0) #Essentially 000 -> 001 qc2.x(1) qc2.x(0) qc2.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one qc2.x(0) #Essentially 001 -> 011 qc2.append(controlled_u_tilde, [1, 2, 0]) qc2.x(0) qc2.toffoli(0,2,1)#Undoing the flip from before qc2.x(0) qc2.x(0) qc2.x(1) qc2.toffoli(0,1,2)#Undoing the flip from before qc2.x(0) qc2.x(1) # Code for V qc2.x(0) qc2.toffoli(0,1,2) # |010> -> |011> qc2.x(0) qc2.toffoli(1,2,0) # V-tilde is the same as Toffoli qc2.x(0) qc2.toffoli(0,1,2) # Reversing the flip qc2.x(0) qc2.draw('mpl') def without_global_phase(matrix: np.ndarray, atol: float = 1e-8) : phases1 = np.angle(matrix[abs(matrix) > atol].ravel(order='F')) if len(phases1) > 0: matrix = np.exp(-1j * phases1[0]) * matrix return matrix V_circ = without_global_phase(qi.Operator(qc2).data) print(V_circ) #Function just returns norm ignoring global phase between unitaries def norm(unitary_a: np.ndarray, unitary_b: np.ndarray) : return np.linalg.norm(without_global_phase(unitary_b)-without_global_phase(unitary_a), ord=2) #Make the Pauli Y gate qcy = QuantumCircuit(1) for i in range(6): qcy.t(0) qcy.h(0) for i in range(4): qcy.t(0) qcy.h(0) for i in range(2): qcy.t(0) Y_circ = qi.Operator(qcy).data Y = np.array([[0,-1j],[1j,0]]) print(norm(Y_circ,Y)) print("Final Circuit:") qcy.draw('mpl') uni_q = np.array([[-0.25+0.60355339j, 0.60355339+0.45710678j], [0.60355339-0.45710678j, 0.25+0.60355339j]]).reshape(2,2) while True: qc3 = QuantumCircuit(1) for i in range(5): for j in range(np.random.randint(8)): qc3.t(0) qc3.h(0) for j in range(np.random.randint(8)): qc3.t(0) uni_q_circ = qi.Operator(qc3).data if norm(uni_q_circ,uni_q) < 1e-8: break print("Final Error: ", norm(uni_q_circ,uni_q)) print("Final Circuit:") qc3.draw('mpl') #Defining the gate as controlled_irx from qiskit.extensions import * pi_alpha = np.arccos(0.6) qc_for_irx = QuantumCircuit(1) irx = np.array([[1j*np.cos(pi_alpha/2),np.sin(pi_alpha/2)],[np.sin(pi_alpha/2),1j*np.cos(pi_alpha/2)]]).reshape(2,2) g_irx = UnitaryGate(data=irx,label=None) controlled_irx = g_irx.control(2) def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate n = 4 qcb = QuantumCircuit(n,n) qcb.x(0)#Ancilla qcb.x(1)#Ancilla You can use these two as control to use the controlled_irx gate count1 = 0 while abs(0.5 - (count1*pi_alpha/np.pi)%2) >= 1e-2 or count1 % 4 != 0: count1 += 1 count2 = 0 while abs(1.5 - (count2*pi_alpha/np.pi)%2) >= 1e-2 or count2 % 4 != 0: count2 += 1 count3 = 0 while abs(4.0 - (count3*pi_alpha/np.pi)%4) >= 1e-2 or count3 % 4 != 2: count3 += 1 for i in range(count1): # Rotation about x by pi/2 (count1 % 4 == 0) qcb.append(controlled_irx, [0, 1, 2]) qcb.cx(2, 3) for i in range(count2): # Rotation about x by -pi/2 (count2 % 4 == 0) qcb.append(controlled_irx, [0, 1, 2]) qcb.x(0) qcb.cx(3, 0) for i in range(count3): # Rotation about x by 0 (count3 % 4 == 2) qcb.append(controlled_irx, [0, 2, 3]) qcb.cx(3, 0) qcb.x(0) print("Executing circuit...") #Get state of qubit which should have the |+> state using the backend simulator i = 3 #Index for the qubit at |+> state qcb.h(i)#Puts the |+> state to |0> for i in range(4): qcb.measure(i, i) def run_circuit(qcb): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qcb, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qcb) print(counts) plot_histogram(counts)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * import numpy as np from fractions import Fraction as frac import qiskit.quantum_info as qi # Loading your IBM Q account(s) provider = IBMQ.load_account() qc=QuantumCircuit(4) #In this particular oracle, the last qubit is storing the value of the function qc.cx(0,3) qc.cx(1,3) qc.cx(2,3) #The last qubit is 1 if there are odd no. of 1s in the other 3 qubits #and 0 otherwise #Hence it is a balanced function qc.draw('mpl') qc1=QuantumCircuit(3) qc1.x(2) qc1.h(0) qc1.h(1) qc1.h(2) qc1.barrier(range(3)) qc1.cx(0,2) qc1.cx(1,2) qc1.barrier(range(3)) qc1.h(0) qc1.h(1) meas = QuantumCircuit(3, 2) meas.measure(range(2),range(2)) # The Qiskit circuit object supports composition using # the addition operator. circ = qc1+meas circ.draw('mpl') backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(circ, backend_sim, shots=1000) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) plot_histogram(counts) qc2=QuantumCircuit(5) qc2.x(4) qc2.h(0) qc2.h(1) qc2.h(2) qc2.h(3) qc2.h(4) qc2.barrier(range(5)) #Your code for the oracle here #YOU ARE PERMITTED TO USE ONLY SINGLE QUBIT GATES AND CNOT(cx) GATES qc2.cx(0,4) qc2.cx(1,4) qc2.cx(2,4) qc2.cx(3,4) qc2.x(4) qc2.barrier(range(5)) qc2.h(0) qc2.h(1) qc2.h(2) qc2.h(3) meas2 = QuantumCircuit(5, 4) meas2.measure(range(4),range(4)) circ2 = qc2+meas2 circ2.draw('mpl') #verification cell, reinitialising the circuit so that it's easier for you to copy-paste the oracle qc2=QuantumCircuit(5) #Add X gates HERE as required to change the input state qc2.x([0,2]) qc2.barrier(range(5)) qc2.cx(0,4) qc2.cx(1,4) qc2.cx(2,4) qc2.cx(3,4) qc2.x(4) qc2.barrier(range(5)) measv = QuantumCircuit(5, 1) measv.measure(4,0) circv = qc2+measv circv.draw('mpl') #DO NOT RUN THIS CELL WITHOUT EDITING THE ABOVE ONE AS DESIRED #The following code will give you f(x) for the value of x you chose in the above cell backend_sim2 = Aer.get_backend('qasm_simulator') job_sim2 = execute(circv, backend_sim2, shots=1000) result_sim2 = job_sim2.result() counts2 = result_sim2.get_counts(circv) print(counts2) plot_histogram(counts2)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
%matplotlib inline # Importing standard Qiskit libraries import random from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * #Get the library to check the answers %pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git from mnp_qc_workshop_2020.bb84 import * # Configuring account provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') # with this simulator it wouldn't work \ # Initial setup random.seed(64) # do not change this seed, otherwise you will get a different key random.seed(64) # This is your 'random' bit string that determines your bases numqubits = 16 bob_bases = str('{0:016b}'.format(random.getrandbits(numqubits))) def bb84(): print('Bob\'s bases:', bob_bases) # Now Alice will send her bits one by one... all_qubit_circuits = [] for qubit_index in range(numqubits): # This is Alice creating the qubit thisqubit_circuit = alice_prepare_qubit(qubit_index) # This is Bob finishing the protocol below bob_measure_qubit(bob_bases, qubit_index, thisqubit_circuit) # We collect all these circuits and put them in an array all_qubit_circuits.append(thisqubit_circuit) # Now execute all the circuits for each qubit results = execute(all_qubit_circuits, backend=backend, shots=1).result() # And combine the results bits = '' for qubit_index in range(numqubits): bits += [measurement for measurement in results.get_counts(qubit_index)][0] return bits # Here is your task def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit): if bob_bases[qubit_index] == '1': qubit_circuit.h(0) qubit_circuit.measure(0, 0) bits = bb84() print('Bob\'s bits: ', bits) check_bits(bits) alice_bases = '0100000101011100' # Alice's bases bits key = '' for i in range(16): if bob_bases[i] == alice_bases[i]: key += bits[i] print(key) check_key(key) message = get_message()# encrypted message decrypted = '' for i in range(len(message)): x = key[-(i%len(key))-1] y = message[-i-1] if x == y: decrypted = '0' + decrypted else: decrypted = '1' + decrypted print(decrypted) check_decrypted(decrypted) decrypted_to_string_ASCII = '' i = 0 while i < 43: decrypted_to_string_ASCII += decrypted[] check_message(decrypted_to_string_ASCII)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.compiler import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() qc1=QuantumCircuit(2) qc1.h(0) qc1.h(1) qc1.barrier() #The part between the barriers is our oracle qc1.cz(0,1) #We are using a controlled-Z gate which flips the sign of the second qubit when both qubits are set to '1' qc1.barrier() qc1.draw('mpl') def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate print(final_vector(qc1)) #We can see that the desired state has been obtained qc2=QuantumCircuit(3) qc2.h(0) qc2.h(1) qc2.h(2) qc2.barrier() #The part between the barriers is our oracle qc2.x(0) qc2.h(1) qc2.x(2) qc2.ccx(0, 2, 1) qc2.x(0) qc2.h(1) qc2.x(2) qc2.barrier() qc2.draw('mpl') def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate print(final_vector(qc2)) def ccz_gate(qc,a,b,c): qc.h(c) qc.ccx(a,b,c) qc.h(c) #Let's create an oracle which will mark the states 101 and 110 #(This particular oracle won't be using ancilla qubits) def phase_oracle(circuit): circuit.cz(0, 2) circuit.cz(0, 1) n=3 qc2=QuantumCircuit(n,n) for i in range(0,n): qc2.h(i) qc2.barrier([0,1,2]) #This creates a superposition of all states #We will now perform the Grover iteration phase_oracle(qc2) qc2.barrier([0,1,2]) for i in range(0,n): qc2.h(i) #Performing a conditional phase shift qc2.x(0) qc2.x(1) qc2.x(2) ccz_gate(qc2,0,1,2) qc2.x(0) qc2.x(1) qc2.x(2) for i in range(0,n): qc2.h(i) #The Grover iteration is now complete qc2.barrier([0,1,2]) qc2.draw('mpl') qc2.measure(0,0) qc2.measure(1,1) qc2.measure(2,2) qc2.draw('mpl') def counts_circ(circ): backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(circ, backend_sim, shots=2000) result_sim = job_sim.result() counts = result_sim.get_counts(circ) return(counts) plot_histogram(counts_circ(qc2)) qc_mct=QuantumCircuit(5,5) for i in range(0,4): qc_mct.x(i) qc_mct.mct([0,1,2,3],4) qc_mct.draw('mpl') qc_mct.measure(0,0) qc_mct.measure(1,1) qc_mct.measure(2,2) qc_mct.measure(3,3) qc_mct.measure(4,4) plot_histogram(counts_circ(qc_mct)) def c3z_gate(qc, a, b, c, d): qc.h(d) qc.mct([a, b, c], d) qc.h(d) def phase_oracle(qc): qc.x(1) qc.x(3) c3z_gate(qc, 0, 1, 2, 3) # Handles 1010 qc.x(2) c3z_gate(qc, 0, 1, 2, 3) # Handles 1000 qc.x(3) c3z_gate(qc, 0, 1, 2, 3) # Handles 1001 qc.x(2) qc.x(0) qc.x(3) c3z_gate(qc, 0, 1, 2, 3) # Handles 0010 qc.x(0) qc.x(1) qc.x(3) n = 4 qc3 = QuantumCircuit(n, n) for i in range(0,n): qc3.h(i) qc3.barrier([0, 1, 2, 3]) phase_oracle(qc3) qc3.barrier([0, 1, 2, 3]) for i in range(0,n): qc3.h(i) qc3.x(0) qc3.x(1) qc3.x(2) qc3.x(3) c3z_gate(qc3, 0, 1, 2, 3) qc3.x(0) qc3.x(1) qc3.x(2) qc3.x(3) for i in range(0,n): qc3.h(i) qc3.barrier([0, 1, 2, 3]) qc3.measure(0, 0) qc3.measure(1, 1) qc3.measure(2, 2) qc3.measure(3, 3) qc3.draw('mpl') def counts_circ(circ): backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(circ, backend_sim, shots=2000) result_sim = job_sim.result() counts = result_sim.get_counts(circ) return(counts) plot_histogram(counts_circ(qc3))
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.compiler import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import scipy import numpy as np from IPython.display import display, Math, Latex import qiskit.quantum_info as qi %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cu1(np.pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # Let's see how it looks: qc = QuantumCircuit(4,4) qft(qc,4) qc.draw(output = 'mpl') def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) return circuit.decompose() # .decompose() allows us to see the individual gates qc = inverse_qft(qc,4) qc.measure(range(4),range(4)) def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc) print(counts) plot_histogram(counts) # we should get the intial state '0000' qc1 = QuantumCircuit(3,3) qc1.x(0) qc1.x(1) qc1.x(2) # try for different initial values for i in range(4):# choose the number of times you want to do qft) qft(qc1,3) qc1.measure(0,0) qc1.measure(1,1) qc1.measure(2,2) def run_circuit(qc1): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc1, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc1) print(counts) plot_histogram(counts) qc2 = QuantumCircuit(2) for i in range(2): qft(qc2, 2) matrix = qi.Operator(qc2).data print(matrix) def Modulo_increment(qc): qft(qc,4) for i in range(4): qc.u1(np.pi/(2**(3-i)), i) qft(qc, 4) return qc # checking for the case of '1000' qc2 = QuantumCircuit(4,4) qc2.x(3) qc2 = Modulo_increment(qc2) qc2.measure(range(4),range(4)) # qc2.draw('mpl') def run_circuit(qc2): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc2, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc2) print(counts) plot_histogram(counts) # checking for the case of '1101' qc3 = QuantumCircuit(4,4) qc3.x(3) qc3.x(2) qc3.x(0) qc3 = Modulo_increment(qc2) qc3.measure(range(4),range(4)) def run_circuit(qc3): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc3, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc3) print(counts) plot_histogram(counts) # checking for the case of '1111' qc4 = QuantumCircuit(4,4) qc4.x(range(4)) qc4 = Modulo_increment(qc4) qc4.measure(range(4),range(4)) def run_circuit(qc4): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc4, backend, shots = 10000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc4) print(counts) plot_histogram(counts)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
!pip install tabulate %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from tabulate import tabulate import numpy as np # Loading your IBM Q account(s) provider = IBMQ.load_account() def qft_dagger(n): """n-qubit QFTdagger the first n qubits in circ""" qc = QuantumCircuit(n) # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cu1(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc def __c_amod15(power): """Controlled multiplication by a mod 15""" U = QuantumCircuit(4) for iteration in range(power): U.swap(2,3) U.swap(1,2) U.swap(0,1) for q in range(4): U.x(q) U = U.to_gate() U.name = "a^%i mod 15" % (power) c_U = U.control() return c_U t=3 qc = QuantumCircuit(t+4,t) for i in range(t): qc.h(i) # The first t qubits are the first register (storing 'x') qc.x(6) #The second register is in state |1> # Oracle for the f(x) mentioned above def Oracle(qc): for q in range(3): qc.append(__c_amod15(2**q), [q] + [i+3 for i in range(4)]) Oracle(qc) qc.append(qft_dagger(t),range(t)) # inverse quantum fourier transform only of the register (first 4 qubits) qc.measure(range(t), range(t)) def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 100000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qc) print(counts) plot_histogram(counts) rows, eigenvalues = [], [] for output in counts: decimal = int(output, 2) eigenvalue = decimal/(2**t) eigenvalues.append(eigenvalue) rows.append(["%s(bin) = %i(dec)" % (output, decimal), "%i/%i = %.2f" % (decimal, 2**t, eigenvalue)]) print(tabulate(rows, headers=["Register Output", "Phase"])) 0.333333333.as_integer_ratio() rows = [] for eigenvalue in eigenvalues: numerator, denominator = eigenvalue.as_integer_ratio() rows.append([eigenvalue, "%i/%i" % (numerator, denominator), denominator]) print(tabulate(rows, headers=["Phase", "Fraction", "Guess for r"], colalign=('right','right','right')))
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
!pip install tabulate %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from tabulate import tabulate # Loading your IBM Q account(s) provider = IBMQ.load_account() #Get the library to check the answers %pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git from mnp_qc_workshop_2020.discrete_logarithm import qft_dagger, oracle, check_answer n_qubits = 3 #Number of qubits for the registers of |x1> and |x2> #For figuring out you would just need 2*n_qubits classical bits qc_disc_log = QuantumCircuit(4+n_qubits+n_qubits, n_qubits+n_qubits) for i in range(2*n_qubits): qc_disc_log.h(i) qc_disc_log.x(9) qc_disc_log.append(oracle(), range(10)) qc_disc_log.append(qft_dagger(3), range(3)) qc_disc_log.append(qft_dagger(3) ,[3,4,5]) qc_disc_log.measure(range(2*n_qubits), range(2*n_qubits)) qc_disc_log.draw('text') backend = Aer.get_backend('qasm_simulator') results = execute(qc_disc_log, backend, shots=8192).result() counts = results.get_counts() plot_histogram(counts) rows_x_1, eigenvalues_x_1 = [], [] for output in counts: decimal = int(output, 2)//8 eigenvalue = decimal/(2**3) eigenvalues_x_1.append(eigenvalue) rows_x_1.append(["%s(bin) = %i(dec)" % (output[0:3], decimal), "%i/%i = %.2f" % (decimal, 2**3, eigenvalue)]) print(tabulate(rows_x_1, headers=["Register Output", "Phase"])) rows_x_2, eigenvalues_x_2 = [], [] for output in counts: decimal = int(output, 2) - ((int(output, 2)//8)*8) eigenvalue = decimal/(2**3) eigenvalues_x_2.append(eigenvalue) rows_x_2.append(["%s(bin) = %i(dec)" % (output[3:6], decimal), "%i/%i = %.2f" % (decimal, 2**3, eigenvalue)]) print(tabulate(rows_x_2, headers=["Register Output", "Phase"])) #Store your value for s here s = 3 #Do analysis of oracle here qc = QuantumCircuit(10, 4) qc.x(0) qc.x(9) qc.append(oracle(), range(10)) qc.measure([6,7,8,9], range(4)) backend = Aer.get_backend('qasm_simulator') results = execute(qc, backend, shots=8192).result() counts = results.get_counts() plot_histogram(counts) # On x1=1, ans = 2 and on x2=1, ans = 8 #Store values of a and b here a, b = 2, 8 check_answer(s,a,b)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
# Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.compiler import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import scipy import numpy as np from IPython.display import display, Math, Latex import qiskit.quantum_info as qi %matplotlib inline %pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git from mnp_qc_workshop_2020.unitary_circuit import * U = get_unitary() print(U.shape) fig, (ax1, ax2) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6)) ax1.imshow(np.real(U)) #plot real parts of each element ax2.imshow(np.imag(U)) #plot imaginary parts of each element fig, (ax3, ax4) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6)) ax3.imshow(np.abs(U)) #plot the absolute values of each element ax4.imshow(np.angle(U)) #plot the phase angles of each element qc = QuantumCircuit(4) qc.unitary(U, range(4)) matrix = qi.Operator(qc).data print(matrix) # # #Your code here # # # qc = transpile(qc,basis_gates=['cx','u3'],optimization_level=3) # qc.draw('mpl') #Run this cell for getting your circuit checked check_circuit(qc)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 200000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts # qc1 was already initialised to |1>|1>. qc1.h(0) # qc1 => (|0>|1> + |1>|1>)/sqrt(2) qc1.cx(0,1) # qc1 => (|0>|1> + |1>|0>)/sqrt(2) #measure qc1.measure([0,1],[0,1]) counts = run_circuit(qc1) print(counts) plot_histogram(counts) qc_swap = QuantumCircuit(2,2) qc_swap.x(0) #initial state => |1>|0> # applying swap qc_swap.cx(0,1) qc_swap.cx(1,0) qc_swap.cx(0,1) #Following from the circuit diagram. # There is also qc_swap.swap(0,1) # measure qc_swap.measure([0,1],[0,1]) counts = run_circuit(qc_swap) print(counts) plot_histogram(counts) qc5 = QuantumCircuit(2,2) qc5.x(1) # initial state is |0>|1> SO THAT WE KNOW WHAT BOTH |0> AND |1> MAP TO. # A lot of people did a mistake here in not understanding why we are using |0> and |1> #apply HZH on both qubits. qc5.h([0,1]) qc5.z([0,1]) qc5.h([0,1]) # measure qc5.measure([0,1],[0,1]) counts = run_circuit(qc5) print(counts) plot_histogram(counts) # final state would be |1>|0> = X(|0>|1>) # Hence they are equal (Actually not. We can only conclude that they agree only upto a global phase. I think now you can appreciate this now.) qc6 = QuantumCircuit(3,3) qc6.x(0) # Set any one qubit of the 2 swapping qubits to '1' to see a noticable difference between input and output. qc6.initialize([1/np.sqrt(2), -complex(1,1)/2],2) # Optional. Initializing the 3rd qubit. # convert 3rd qubit into |1> qc6.tdg(2) qc6.h(2) # OR #qc6.t(2) #qc6.s(2) #qc6.h(2) #qc6.x(2) # You can check that they are equivalent. # As you know now, it's a Fredkin gate. qc6.toffoli(2,1,0) qc6.toffoli(2,0,1) qc6.toffoli(2,1,0) #reset the third qubit to its intial state qc6.h(2) qc6.t(2) # Measure qc6.measure([0,1,2],[0,1,2]) counts = run_circuit(qc6) print(counts) plot_histogram(counts)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() qc1 = QuantumCircuit(3,3) # All initialized to '0' by default. qc1.x(0) #This is for the purpose of setting the control qubit to '1' qc1.x(2) #As a result, the second target qubit becomes '1' while the first remains '0'. Now, lets's try swapping them. #Fredkin gate: def fredkin(qc): qc.toffoli(0,1,2) qc.toffoli(0,2,1) qc.toffoli(0,1,2) fredkin(qc1) qc1.draw('mpl') #First let's measure all three qubits. #We're using the classical bits to store the result obtained on measuring each corresponding qubit. qc1.measure(0,0) qc1.measure(1,1) qc1.measure(2,2) #Now we use the same function we defined yesterday to run a quantum circuit def run_circuit(qc2): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc2, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts1=run_circuit(qc1) print(counts1) plot_histogram(counts1) qc2 = QuantumCircuit(3,3) # All initialized to '0' by default. qc2.x(2) #The second target qubit is initialised to '1' fredkin(qc2) qc2.measure(0,0) qc2.measure(1,1) qc2.measure(2,2) qc2.draw('mpl') counts2=run_circuit(qc2) print(counts2) plot_histogram(counts2) qc = QuantumCircuit(1) #This is how we apply the rotation operators in Qiskit, mentioning the angle of rotation and qubit no. as parameters qc.rx(np.pi/2,0) qc.draw('mpl') def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate print(final_vector(qc)) # This prints the vector obtained on applying the above gate to the qubit state '0' #Verifying for the X gate qc3=QuantumCircuit(1) qc3.x(0) qc3.ry(np.pi/8,0) #Enter an angle of your choice qc3.x(0) print(final_vector(qc3)) qc3=QuantumCircuit(1) qc3.ry(-np.pi/8,0) print(final_vector(qc3)) #Run this code for different values of theta and see if the two vectors printed are equal in each case #Verifying for the H gate qc3=QuantumCircuit(1) qc3.h(0) qc3.ry(np.pi/8,0) #Enter an angle of your choice qc3.h(0) print(final_vector(qc3)) qc3=QuantumCircuit(1) qc3.ry(-np.pi/8,0) print(final_vector(qc3)) #Run this code for different values of theta and see if the two vectors printed are equal in each case gamma = np.pi/2 alpha = np.pi/2 beta= 0 delta = np.pi def A(qc,b,g,q): qc.ry(g/2,q) qc.rz(b,q) def B(qc,g,d,b,q): qc.rz((-d-b)/2,q) qc.ry(-g/2,q) def C(qc,d,b,q): qc.rz((d-b)/2,q) #Initialising the unitary matrix for the global phase #exp(i pi/2) = i U = np.array([[1j, 0],[0, 1j]]) #Let us now apply the transformation qc4 = QuantumCircuit(1) C(qc4,delta,beta,0) qc4.x(0) B(qc4,gamma,delta,beta,0) qc4.x(0) A(qc4,beta,gamma,0) qc4.unitary(U, [0], 0) print(final_vector(qc4)) #Reinitialise the Quantum Circuit qc4 = QuantumCircuit(1) qc4.h(0) print(final_vector(qc4)) #We get that exp(i alpha) AXBXC = H, thus the decomposition is correct #Note: We will be accepting solutions which differ in global phase qc5=QuantumCircuit(2,2) qc5.x(0) C(qc5,delta,beta,1) qc5.cx(0,1) B(qc5,gamma,delta,beta,1) qc5.cx(0,1) A(qc5,beta,gamma,1) qc5.u1(alpha,0) qc5.measure(0,0) qc5.measure(1,1) qc5.draw('mpl') #Note: You don't need to draw the circuit, we're just displaying it for clarity counts5=run_circuit(qc5) print(counts5) plot_histogram(counts5) #We have succesfully implemented the controlled Hadamard gate qc_u3=QuantumCircuit(1) qc_u3.u3(np.pi/6,-np.pi/2,np.pi/2,0) print(final_vector(qc_u3)) qc_rx=QuantumCircuit(1) qc_rx.rx(np.pi/6,0) print(final_vector(qc_rx)) #Getting the same results will verify our observation stated above #Let's first build controlled V and controlled V dagger gates def V(qc,q0,qt): C(qc,np.pi/2,3*np.pi/2,qt) qc.cx(q0,qt) B(qc,np.pi/2,np.pi/2,3*np.pi/2,qt) qc.cx(q0,qt) A(qc,3*np.pi/2,np.pi/2,qt) qc.u1(5*np.pi/4,q0) def Vdag(qc,q0,qt): C(qc,3*np.pi/2,np.pi/2,qt) qc.cx(q0,qt) B(qc,np.pi/2,3*np.pi/2,np.pi/2,qt) qc.cx(q0,qt) A(qc,np.pi/2,np.pi/2,qt) qc.u1(3*np.pi/4,q0) #Now we can build the Toffoli gate def toffoli(qc,q0,q1,q2): V(qc,q1,q2) qc.cx(q0,q1) Vdag(qc,q1,q2) qc.cx(q0,q1) V(qc,q0,q2) qch=QuantumCircuit(8,5) #The 3 qubits from fifth to seventh will be used as work qubits #To check the final vector, let's just set all qubits to |1> for i in range(4): qch.x(i) toffoli(qch,0,1,4) toffoli(qch,2,4,5) toffoli(qch,3,5,6) #The seventh qubit, ie, q6 will be used as the control qubit in the controlled Hadamard #Let's just copy paste the code of the controlled Hadamard gate gamma = np.pi/2 alpha = np.pi/2 beta= 0 delta = np.pi C(qch,delta,beta,7) qch.cx(6,7) B(qch,gamma,delta,beta,7) qch.cx(6,7) A(qch,beta,gamma,7) qch.u1(alpha,6) #Let's undo the Toffolis toffoli(qch,0,1,4) toffoli(qch,2,4,5) toffoli(qch,3,5,6) qch.measure(0,0) qch.measure(1,1) qch.measure(2,2) qch.measure(3,3) qch.measure(7,4) qch.draw('mpl') countsh=run_circuit(qch) print(countsh) plot_histogram(countsh) #Hence we have successfully applied the C^4(H) gate
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 200000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts THE ONLY TASK qc1 = QuantumCircuit(2,2) # preparing 'a' bell pair which is |beta_00> here qc1.h(0) qc1.cx(0,1) qc1.barrier([0,1]) # Apply any pauli gate here a = input("BE SKYLER. APPLY ANY OF THE FOUR PAULI GATES:") if a == 'X': qc1.x(1) if a == 'Y': qc1.y(1) if a == 'Z': qc1.z(1) # if it's not any of them, it's I. So we don't need to do anything. qc1.barrier([0,1]) # Change the state into standard states: |00>, |01>, |10>, |11> depending on the gate applied qc1.cx(0,1) qc1.h(0) #Measure qc1.measure([0,1],[0,1]) backend = Aer.get_backend('qasm_simulator') result = execute(qc1, backend, shots = 1024).result() counts = result.get_counts() plot_histogram(counts) # On observation we get this mapping print('Skyler applied this gate: ') if '00' in counts.keys(): print('I') # She bluffed. # Don't worry if you haven't considered this case. Happens. elif '10' in counts.keys(): print('X') elif '11' in counts.keys(): print('Y') else: print('Z') plot_histogram(counts)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.compiler import * from qiskit.tools.jupyter import * from qiskit.visualization import * import numpy as np import qiskit.quantum_info as qi # Loading your IBM Q account(s) provider = IBMQ.load_account() #This cell is just for seeing what the U tilde matrix looks like a, b, c, d = np.cos(np.pi/8), np.sin(np.pi/8), -np.sin(np.pi/8), np.cos(np.pi/8) u_tilde = np.array([[a,c],[b,d]]).reshape(2,2) print(u_tilde) #This cell defines the controlled variant of the U tilde matrix qc_for_u = QuantumCircuit(1) qc_for_u.ry(np.pi/4, 0) qc_for_u.name = "U" controlled_u_tilde = qc_for_u.to_gate().control(2) qc1 = QuantumCircuit(3) qc1.x(0) qc1.x(1) qc1.toffoli(0,1,2)#Flipping the third bit if the first two are zero qc1.x(0) #Essentially 000 -> 001 qc1.x(1) qc1.x(0) qc1.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one qc1.x(0) #Essentially 001 -> 011 qc1.append(controlled_u_tilde, [1, 2, 0]) qc1.x(0) qc1.toffoli(0,2,1)#Undoing the flip from before qc1.x(0) qc1.x(0) qc1.x(1) qc1.toffoli(0,1,2)#Undoing the flip from before qc1.x(0) qc1.x(1) qc1.draw('mpl') U_circ = qi.Operator(qc1).data print(U_circ) qc2 = QuantumCircuit(3) #Code for executing U qc2.x(0) qc2.x(1) qc2.toffoli(0,1,2)#Flipping the third bit if the first two are zero qc2.x(0) #Essentially 000 -> 001 qc2.x(1) qc2.x(0) qc2.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one qc2.x(0) #Essentially 001 -> 011 qc2.append(controlled_u_tilde, [1, 2, 0]) qc2.x(0) qc2.toffoli(0,2,1)#Undoing the flip from before qc2.x(0) qc2.x(0) qc2.x(1) qc2.toffoli(0,1,2)#Undoing the flip from before qc2.x(0) qc2.x(1) #Code for executing V qc2.x(0) qc2.toffoli(0,1,2)#Flipping the third bit if the first is zero and second is one qc2.x(0) #Essentially 010 -> 011 qc2.toffoli(1,2,0) qc2.x(0) qc2.toffoli(0,1,2)#Undoing the flip from before qc2.x(0) qc2.draw('mpl') def without_global_phase(matrix: np.ndarray, atol: float = 1e-8) : phases1 = np.angle(matrix[abs(matrix) > atol].ravel(order='F')) if len(phases1) > 0: matrix = np.exp(-1j * phases1[0]) * matrix return matrix V_circ = without_global_phase(qi.Operator(qc2).data) print(V_circ) #Function just returns norm ignoring global phase between unitaries def norm(unitary_a: np.ndarray, unitary_b: np.ndarray) : return np.linalg.norm(without_global_phase(unitary_b)-without_global_phase(unitary_a), ord=2) #Make the Pauli Y gate qcy = QuantumCircuit(1) qcy.t(0) qcy.t(0) qcy.t(0) qcy.t(0) qcy.h(0) qcy.t(0) qcy.t(0) qcy.t(0) qcy.t(0) qcy.h(0)# Essentially XZ is being applied since T^4 = X and HXH = Z and XZ = iY but global phase is ignored Y_circ = qi.Operator(qcy).data Y = np.array([[0,-1j],[1j,0]]) print(norm(Y_circ,Y)) uni_q = np.array([[-0.25+0.60355339j, 0.60355339+0.45710678j], [0.60355339-0.45710678j, 0.25+0.60355339j]]).reshape(2,2) qc3 = QuantumCircuit(1) qc_min = 1000 while(True): parameters = np.random.randint(8, size=6) #Samling integers from 0 to 7 and getting 6 of them for i in parameters[0:5]: for j in range(i): qc3.t(0) qc3.h(0) for j in range(parameters[-1]): qc3.t(0) if norm(qi.Operator(qc3).data,uni_q) <= 1e-8:#Break if we have reached the right combination print(parameters) break qc_min = np.sum(parameters) qc3 = QuantumCircuit(1)#Reinitiallize circuit uni_q_circ = qi.Operator(qc3).data print(norm(uni_q_circ,uni_q)) qc3.draw('mpl')#Drawing the actual solution #Note that there are multiple solutions so as long as your norm #was of order 1.65e-9 you are correct. The reason of these multiple #solutions is because there are commutativity relations that we #havent bothered calculating #There are better ways and many of you probably did use them. This is the best circuit we found #If you search amongst all the possibilities or iterate the right way this will be the solution you find #The difference between this cell and the one above is that the one above came from a random number generator qc3 = QuantumCircuit(1) qc3.t(0) qc3.h(0) qc3.t(0) qc3.t(0) qc3.t(0) qc3.h(0) qc3.t(0) qc3.h(0) qc3.t(0) qc3.h(0) qc3.t(0) qc3.t(0) qc3.h(0) qc3.draw('mpl') #Defining the gate as controlled_irx from qiskit.extensions import * pi_alpha = np.arccos(0.6) qc_for_irx = QuantumCircuit(1) irx = np.array([[1j*np.cos(pi_alpha/2),np.sin(pi_alpha/2)],[np.sin(pi_alpha/2),1j*np.cos(pi_alpha/2)]]).reshape(2,2) g_irx = UnitaryGate(data=irx,label=None) controlled_irx = g_irx.control(2) alpha = pi_alpha/np.pi i = 0 while(True): if abs((alpha*i)%2 - 0.5) <= 0.001: print(i) break i += 1 i = 1 while(True): if abs((alpha*i)%2) <= 0.013 and (i%4 == 2): print(i) break i += 1 n = 4 qcb = QuantumCircuit(n,n) qcb.x(0)#Ancilla qcb.x(1)#Ancilla You can use these two as control to use the controlled_irx gate #Doing the Rx(pi/2) for i in range(476): qcb.append(controlled_irx,[0,1,2]) #Controlled not off first qubit (here first qubit is actually the third one cause we have two ancillas) qcb.cx(2,3) #Doing the Rx(3pi/2) which is Rx(-pi/2) essentially qcb.x(2) for i in range(476): qcb.append(controlled_irx,[0,1,2]) # This makes the state |11> flip sign if third and fourth qubit is 1 #so that way we know that fourth qubit has |+> state always qcb.x(0)#reset ancillas qcb.x(1)#reset ancillas qcb.cx(2,0) qcb.cx(3,1) for i in range(122): qcb.append(controlled_irx,[0,1,3]) qcb.cx(3,1) qcb.cx(2,0) #Get state of qubit which should have the |+> state using the backend simulator i = 3#Index for the qubit at |+> state qcb.h(i)#Puts the |+> state to |0> qcb.measure(i, i) def run_circuit(qcb): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qcb, backend, shots = 2000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts counts = run_circuit(qcb) print(counts) plot_histogram(counts)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
%matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * import numpy as np from fractions import Fraction as frac import qiskit.quantum_info as qi # Loading your IBM Q account(s) provider = IBMQ.load_account() qc=QuantumCircuit(4) #In this particular oracle, the last qubit is storing the value of the function qc.cx(0,3) qc.cx(1,3) qc.cx(2,3) #The last qubit is 1 if there are odd no. of 1s in the other 3 qubits #and 0 otherwise #Hence it is a balanced function qc.draw('mpl') qc1=QuantumCircuit(3) qc1.x(2) qc1.h(0) qc1.h(1) qc1.h(2) qc1.barrier(range(3)) qc1.cx(0,2) qc1.cx(1,2) qc1.barrier(range(3)) qc1.h(0) qc1.h(1) meas = QuantumCircuit(3, 2) meas.measure(range(2),range(2)) # The Qiskit circuit object supports composition using # the addition operator. circ = qc1+meas circ.draw('mpl') backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(circ, backend_sim, shots=1000) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) plot_histogram(counts) qc2=QuantumCircuit(5) qc2.x(4) qc2.h(0) qc2.h(1) qc2.h(2) qc2.h(3) qc2.h(4) qc2.barrier(range(5)) #The oracle: qc2.x(0) qc2.x(1) qc2.x(3) qc2.cx(0,4) qc2.cx(1,4) qc2.cx(2,4) qc2.cx(3,4) qc2.x(0) qc2.x(1) qc2.x(3) #oracle ends here qc2.barrier(range(5)) qc2.h(0) qc2.h(1) qc2.h(2) qc2.h(3) meas2 = QuantumCircuit(5, 4) meas2.measure(range(4),range(4)) circ2 = qc2+meas2 circ2.draw('mpl') #verification cell, reinitialising the circuit so that it's easier for you to copy-paste the oracle qc2=QuantumCircuit(5) #Add X gates HERE as required to change the input state #Let's check for |1001> qc2.x(0) qc2.x(3) qc2.barrier(range(5)) #Copy and paste your code for the oracle from the above cell here qc2.x(0) qc2.x(1) qc2.x(3) qc2.cx(0,4) qc2.cx(1,4) qc2.cx(2,4) qc2.cx(3,4) qc2.x(0) qc2.x(1) qc2.x(3) qc2.barrier(range(5)) measv = QuantumCircuit(5, 1) measv.measure(4,0) circv = qc2+measv circv.draw('mpl') #DO NOT RUN THIS CELL WITHOUT EDITING THE ABOVE ONE AS DESIRED #The following code will give you f(x) for the value of x you chose in the above cell backend_sim2 = Aer.get_backend('qasm_simulator') job_sim2 = execute(circv, backend_sim2, shots=1000) result_sim2 = job_sim2.result() counts2 = result_sim2.get_counts(circv) print(counts2) plot_histogram(counts2) #Similarly you can check f(x) for different values of x
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
%matplotlib inline # Importing standard Qiskit libraries import random from qiskit import execute, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * #Get the library to check the answers %pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git from mnp_qc_workshop_2020.bb84 import * # Configuring account provider = IBMQ.load_account() backend = provider.get_backend('ibmq_qasm_simulator') # with this simulator it wouldn't work \ # Initial setup random.seed(64) # do not change this seed, otherwise you will get a different key # This is your 'random' bit string that determines your bases numqubits = 16 bob_bases = str('{0:016b}'.format(random.getrandbits(numqubits))) def bb84(): print('Bob\'s bases:', bob_bases) # Now Alice will send her bits one by one... all_qubit_circuits = [] for qubit_index in range(numqubits): # This is Alice creating the qubit thisqubit_circuit = alice_prepare_qubit(qubit_index) # This is Bob finishing the protocol below bob_measure_qubit(bob_bases, qubit_index, thisqubit_circuit) # We collect all these circuits and put them in an array all_qubit_circuits.append(thisqubit_circuit) # Now execute all the circuits for each qubit results = execute(all_qubit_circuits, backend=backend, shots=1).result() # And combine the results bits = '' for qubit_index in range(numqubits): bits += [measurement for measurement in results.get_counts(qubit_index)][0] return bits # Here is your task def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit): if(bob_bases[qubit_index] == '1'): qubit_circuit.h(0)#Just change basis to +,- and then measure qubit_circuit.measure(0,0) bits = bb84() print('Bob\'s bits: ', bits) check_bits(bits) alice_bases = '0100000101011100' # Alice's bases bits key = '' for i in range(16): if alice_bases[i]==bob_bases[i]: key = key + bits[i]#The key is only added to for the case where the bases are the same print(key) check_key(key) message = get_message()# encrypted message decrypted = '' for i in range(344): if key[i%8] == '1': if message[i] == '0': m = '1' else: m = '0' decrypted = decrypted + m else: decrypted = decrypted + message[i] #The key is sort of applied like a mask over each of the 43 8 bit sequences #of the 344 bitstring and its just a xor operation here print(decrypted) check_decrypted(decrypted) decrypted_to_string_ASCII = '' for i in range(43): decrypted_to_string_ASCII += str(chr(int(decrypted[(i*8):(i*8)+8],2)))#sequentially taking the 8 bit sequences print(decrypted_to_string_ASCII) check_message(decrypted_to_string_ASCII)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
from qiskit import * from qiskit.compiler import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() qc1=QuantumCircuit(2) qc1.h(0) qc1.h(1) qc1.barrier() #The part between the barriers is our oracle qc1.cz(0,1) #We are using a controlled-Z gate which flips the sign of the second qubit when both qubits are set to '1' qc1.barrier() qc1.draw('mpl') def final_vector(qc): backend = Aer.get_backend('statevector_simulator') job = execute(qc, backend) result = job.result() outputstate = result.get_statevector(qc, decimals=3) return outputstate print(final_vector(qc1)) #We can see that the desired state has been obtained qc2=QuantumCircuit(3) qc2.h(0) qc2.h(1) qc2.h(2) qc2.barrier() #The part between the barriers is our oracle qc2.x(0) qc2.x(2) #We are just using the ccz gate which we have defined later qc2.h(1) qc2.ccx(0,2,1) qc2.h(1) qc2.x(2) qc2.x(0) qc2.barrier() qc2.draw('mpl') #print the final vector print(final_vector(qc2)) #The negative sign has been applied only to |010> in the equal superposition of states def ccz_gate(qc,a,b,c): qc.h(c) qc.ccx(a,b,c) qc.h(c) #Let's create an oracle which will mark the states 101 and 110 #(This particular oracle won't be using ancilla qubits) def phase_oracle(circuit): circuit.cz(0, 2) circuit.cz(0, 1) n=3 qc2=QuantumCircuit(n,n) for i in range(0,n): qc2.h(i) qc2.barrier([0,1,2]) #This creates a superposition of all states #We will now perform the Grover iteration phase_oracle(qc2) qc2.barrier([0,1,2]) for i in range(0,n): qc2.h(i) #Performing a conditional phase shift qc2.x(0) qc2.x(1) qc2.x(2) ccz_gate(qc2,0,1,2) qc2.x(0) qc2.x(1) qc2.x(2) for i in range(0,n): qc2.h(i) #The Grover iteration is now complete qc2.barrier([0,1,2]) qc2.draw('mpl') qc2.measure(0,0) qc2.measure(1,1) qc2.measure(2,2) qc2.draw('mpl') def counts_circ(circ): backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(circ, backend_sim, shots=2000) result_sim = job_sim.result() counts = result_sim.get_counts(circ) return(counts) plot_histogram(counts_circ(qc2)) qc_mct=QuantumCircuit(5,5) for i in range(0,4): qc_mct.x(i) qc_mct.mct([0,1,2,3],4) qc_mct.draw('mpl') qc_mct.measure(0,0) qc_mct.measure(1,1) qc_mct.measure(2,2) qc_mct.measure(3,3) qc_mct.measure(4,4) plot_histogram(counts_circ(qc_mct)) def cccz_gate(qc,a,b,c,d): #Suppose qubit d is the target qubit qc.h(d) qc.mct([a,b,c],d) qc.h(d) #Let's now define the operation for the conditional phase shift (i.e., on |0000>) def zero_oracle(qc): qc.x([0,1,2,3]) cccz_gate(qc,0,1,2,3) qc.x([0,1,2,3]) n=4 qc3=QuantumCircuit(n,n) for i in range(0,n): qc3.h(i) qc3.barrier([0,1,2,3]) #Finally the oracle for marking the solution states qc3.x(1) ccz_gate(qc3,0,1,2) ccz_gate(qc3,0,1,3) qc3.x(1) #The above portion just marked states '1001' and '1010' qc3.x(1) qc3.x(3) ccz_gate(qc3,1,3,0) ccz_gate(qc3,1,3,2) qc3.x(3) qc3.x(1) #This portion marked states '1000' and '0010' #The oracle ends qc3.barrier([0,1,2,3]) for i in range(0,n): qc3.h(i) zero_oracle(qc3) for i in range(0,n): qc3.h(i) #The Grover iteration is now complete qc3.barrier([0,1,2,3]) qc3.draw('mpl') qc3.measure([0,1,2,3],[0,1,2,3]) plot_histogram(counts_circ(qc3))
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
!pip install qiskit from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import numpy as np from IPython.display import display, Math, Latex import qiskit.quantum_info as qi %matplotlib inline # Loading your IBM Q account(s) provider = IBMQ.load_account() def run_circuit(qc): backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend result = execute(qc, backend, shots = 200000).result() # we run the simulation counts = result.get_counts() # we get the counts return counts def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cu1(np.pi/2**(n-qubit), qubit, n) # At the end of our function, we call the same function again on # the next qubits (we reduced n by one earlier in the function) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) def inverse_qft(circuit, n): """Does the inverse QFT on the first n qubits in circuit""" # First we create a QFT circuit of the correct size: qft_circ = qft(QuantumCircuit(n), n) # Then we take the inverse of this circuit invqft_circ = qft_circ.inverse() # And add it to the first n qubits in our existing circuit circuit.append(invqft_circ, circuit.qubits[:n]) return circuit.decompose() # .decompose() allows us to see the individual gates swap_registers(circuit, n) return circuit # Basically change the values of n starting from 1,2(you know which aren't I),3,... We will start with 3 a = 0 n = 3 while a==0: c = ClassicalRegister(5) q = QuantumRegister(5) qc = QuantumCircuit(q,c) for i in range(n): qft(qc,5) qc.measure(range(5),range(5)) counts = run_circuit(qc) if len(counts.keys()) == 1: if '00000' in counts.keys(): a=1 print(n) n = n+1 # Actually due to qiskit using reverse order for bit strings sometimes produces weird results when it comes to such matrices repeatedly. # Nevertheless, you can search up on the internet for QFT matrix and you can calculate that QFT^4 indeed equals I. # The matrix can be easily solved theoretically and can be found on the internet, Here we will get the matrix according to the qiskit nomenclature. qc = QuantumCircuit(2) qft(qc, 2) qft(qc, 2) with np.printoptions(precision=3, suppress=True): print(qi.Operator(qc).data) # The required function. Also recall that T^2 = S, S^2 = Z. def Modulo_increment(qc): # 4 bit circuit where q3 is MSB qft(qc,4) qc.rz(np.pi/8,0) qc.t(1) qc.s(2) qc.z(3) inverse_qft(qc,4) return qc # Then you can check for different values.
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
!pip install tabulate %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from tabulate import tabulate # Loading your IBM Q account(s) provider = IBMQ.load_account() #Get the library to check the answers %pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git from mnp_qc_workshop_2020.discrete_logarithm import qft_dagger, oracle, check_answer n_qubits = 3 #Number of qubits for the registers of |x1> and |x2> #For figuring out you would just need 2*n_qubits classical bits qc_disc_log = QuantumCircuit(4+n_qubits+n_qubits, n_qubits+n_qubits) for i in range(6): qc_disc_log.h(i) qc_disc_log.x(9)#Flip the first bit in third register to bring in state |1> taking q6 as LSB qc_disc_log.append(oracle(),range(10))#Applying oracle qc_disc_log.append(qft_dagger(n_qubits), range(n_qubits))#Inverse QFT on register 1 qc_disc_log.append(qft_dagger(n_qubits), range(n_qubits,2*n_qubits))#Inverse QFT on register 2 qc_disc_log.measure(range(6),range(6)) qc_disc_log.draw('text') backend = Aer.get_backend('qasm_simulator') results = execute(qc_disc_log, backend, shots=8192).result() counts = results.get_counts() plot_histogram(counts) rows_x_1, eigenvalues_x_1 = [], [] for output in counts: decimal = int(output, 2)//8 eigenvalue = decimal/(2**3) eigenvalues_x_1.append(eigenvalue) rows_x_1.append(["%s(bin) = %i(dec)" % (output[0:3], decimal), "%i/%i = %.2f" % (decimal, 2**3, eigenvalue)]) print(tabulate(rows_x_1, headers=["Register Output", "Phase"])) rows_x_2, eigenvalues_x_2 = [], [] for output in counts: decimal = int(output, 2) - ((int(output, 2)//8)*8) eigenvalue = decimal/(2**3) eigenvalues_x_2.append(eigenvalue) rows_x_2.append(["%s(bin) = %i(dec)" % (output[3:6], decimal), "%i/%i = %.2f" % (decimal, 2**3, eigenvalue)]) print(tabulate(rows_x_2, headers=["Register Output", "Phase"])) def make_guess_for_s(e1,e2): if e1==0 or e2==0: return "NaN" for a in range(2,4): if ((e1*a) - int(e1*a)) == e2: #This is because there will be roll over of the values in the register return a return "Nan" rows = [] for i in range(len(eigenvalues_x_1)): eigenvalue_x_1 = eigenvalues_x_1[i] numerator1, denominator1 = eigenvalue_x_1.as_integer_ratio() eigenvalue_x_2 = eigenvalues_x_2[i] numerator2, denominator2 = eigenvalue_x_2.as_integer_ratio() s_val = make_guess_for_s(eigenvalue_x_1,eigenvalue_x_2) rows.append([eigenvalue_x_1, "%i/%i" % (numerator1, denominator1), eigenvalue_x_2, "%i/%i" % (numerator2, denominator2), s_val]) print(tabulate(rows, headers=["Phase in 1st register","Fraction", "Phase in 2nd register", "Fraction", "Guess for s"], colalign=('right','right','right','right','right'))) #Store your value for s here s = 3 from math import gcd for i in range(2,15): j = 1 if(gcd(i,15)!=1): continue while(True): if (i**j)%15 == 1: break j = j+1 if(j == 4): print(i) qc_an = QuantumCircuit(10,4) qc_an.x(0)#This way the oracle multiplies by a mod 15 qc_an.x(9)#Flip the first bit in third register to bring in state |1> qc_an.append(oracle(),range(10))#Applying oracle qc_an.measure(range(6,10),range(4)) qc_an.draw('text') backend = Aer.get_backend('qasm_simulator') results = execute(qc_an, backend, shots=1024).result() counts = results.get_counts() plot_histogram(counts) qc_bn = QuantumCircuit(10,4) qc_bn.x(3)#This way the oracle multiplies by b mod 15 qc_bn.x(9)#Flip the first bit in third register to bring in state |1> qc_bn.append(oracle(),range(10))#Applying oracle qc_bn.measure(range(6,10),range(4)) qc_bn.draw('text') backend = Aer.get_backend('qasm_simulator') results = execute(qc_bn, backend, shots=1024).result() counts = results.get_counts() plot_histogram(counts) #Store values of a and b here a, b = 2,8 check_answer(s,a,b)
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
mnp-club
# Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.compiler import * from qiskit.tools.jupyter import * from qiskit.visualization import * import matplotlib.pyplot as plotter import scipy import numpy as np from IPython.display import display, Math, Latex import qiskit.quantum_info as qi %matplotlib inline %pip install -I git+https://github.com/mnp-club/MnP_QC_Workshop.git from mnp_qc_workshop_2020.unitary_circuit import * U = get_unitary() print(U.shape) fig, (ax1, ax2) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6)) ax1.imshow(np.real(U)) #plot real parts of each element ax2.imshow(np.imag(U)) #plot imaginary parts of each element fig, (ax3, ax4) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6)) ax3.imshow(np.abs(U)) #plot the absolute values of each element ax4.imshow(np.angle(U)) #plot the phase angles of each element qc1 = QuantumCircuit(4) qc1.unitary(U,range(4)) qc1 = transpile(qc1,basis_gates=['cx','u3'],optimization_level=3) qc1.draw('mpl') #Run this cell for getting your circuit checked check_circuit(qc1) H = scipy.linalg.hadamard(16)/4 #Normalizing has to be done HU = np.matmul(H,U) fig, (ax1, ax2) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6)) ax1.imshow(np.real(HU)) #plot real parts of each element ax2.imshow(np.imag(HU)) #plot imaginary parts of each element fig, (ax3, ax4) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6)) ax3.imshow(np.abs(HU)) #plot the absolute values of each element ax4.imshow(np.angle(HU)) #plot the phase angles of each element qc2 = QuantumCircuit(4) #for i in range(4): # qc2.h(i) qc2.unitary(HU,range(4)) for i in range(4): qc2.h(i) qc2 = transpile(qc2,basis_gates=['cx','u3'],optimization_level=3) qc2.draw('mpl') #Run this cell for getting your circuit checked check_circuit(qc2) HUH = np.matmul(HU,H) fig, (ax1, ax2) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6)) ax1.imshow(np.real(HUH)) #plot real parts of each element ax2.imshow(np.imag(HUH)) #plot imaginary parts of each element fig, (ax3, ax4) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6)) ax3.imshow(np.abs(HUH)) #plot the absolute values of each element ax4.imshow(np.angle(HUH)) #plot the phase angles of each element qc3 = QuantumCircuit(4) for i in range(4): qc3.h(i) qc3.unitary(HUH,range(4)) for i in range(4): qc3.h(i) qc3 = transpile(qc3,basis_gates=['cx','u3'],optimization_level=3) qc3.draw('mpl') #Run this cell for getting your circuit checked check_circuit(qc3) diag = np.diag(HUH) print(diag) a = np.sqrt(0.5) clean_diag = [ 1, a+(a*1j), -a+(a*1j), -1, 1j, a-(a*1j), -a-(a*1j), 1j, -a-(a*1j), 1j, -1, a+(a*1j), a-(a*1j), 1, -1j, a-(a*1j)] print(clean_diag) qc31 = QuantumCircuit(4) for i in range(4): qc31.h(i) qc31.diagonal(clean_diag,qc31.qubits) for i in range(4): qc31.h(i) qc31 = transpile(qc31,basis_gates=['cx','u3'],optimization_level=3) qc31.draw('mpl') #Run this cell for getting your circuit checked check_circuit(qc31) func = lambda a: np.array([[1,0],[0,np.exp(1j*np.pi*a/4)]]) def checking_of_diag(diag_v): for i in range(16): if np.abs(diag_v[i]-clean_diag[i])>=0.001 and np.abs(diag_v[i]+clean_diag[i])>=0.001: return False return True while(True): par = np.random.randint(low=1,high=8, size=4)#We will assume that all atleast rotate by pi/4 V_test = np.kron(np.kron(func(par[0]),func(par[1])),np.kron(func(par[2]),func(par[3]))) if checking_of_diag(np.diag(V_test)): print(par) break differences = np.identity(16) for i in range(16): if np.abs(V_test[i,i]-clean_diag[i]) >= 0.0001: print(i) differences[i,i] = -1 def without_global_phase(matrix: np.ndarray, atol: float = 1e-8) : phases1 = np.angle(matrix[abs(matrix) > atol].ravel(order='F')) if len(phases1) > 0: matrix = np.exp(-1j * phases1[0]) * matrix return matrix #Function just returns norm ignoring global phase between unitaries def norm(unitary_a: np.ndarray, unitary_b: np.ndarray) : return np.linalg.norm(without_global_phase(unitary_b)-without_global_phase(unitary_a), ord=2) qc_d = QuantumCircuit(4) for i in range(64): if (i%2) == 1: qc_d.cz(0,1) if (i//2)%2 == 1: qc_d.cz(0,2) if (i//4)%2 == 1: qc_d.cz(0,3) if (i//8)%2 == 1: qc_d.cz(1,2) if (i//16)%2 == 1: qc_d.cz(1,3) if (i//32)%2 == 1: qc_d.cz(3,2) if norm(qi.Operator(qc_d).data,differences) <= 0.001: print(i) break qc_d = QuantumCircuit(4) qc = QuantumCircuit(4) theta1 = par[3]*np.pi/4 theta2 = par[2]*np.pi/4 theta3 = par[1]*np.pi/4 theta4 = par[0]*np.pi/4 qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc.rz(theta1,0) qc.rz(theta2,1) qc.rz(theta3,2) qc.rz(theta4,3) qc.cz(1,3) qc.cz(0,2) qc.cz(0,3) qc.h(0) qc.h(1) qc.h(2) qc.h(3) qc = transpile(qc,basis_gates=['cx','u3'],optimization_level=3) qc.draw('mpl') #Run this cell for getting your circuit checked check_circuit(qc)
https://github.com/IceKhan13/QiskitFlow
IceKhan13
''' This is a implementation of the quantum teleportation algorithm ''' from qiskit import * from qiskit.visualization import plot_histogram import os, shutil, numpy from matplotlib.pyplot import plot, draw, show LaTex_folder_Quantum_Teleportation = str(os.getcwd())+'/Latex_quantum_gates/Quantum_Teleportation/' if not os.path.exists(LaTex_folder_Quantum_Teleportation): os.makedirs(LaTex_folder_Quantum_Teleportation) else: shutil.rmtree(LaTex_folder_Quantum_Teleportation) os.makedirs(LaTex_folder_Quantum_Teleportation) qc = QuantumCircuit(3,3) ## prepare the state to be teleported phi = 0*numpy.pi theta= 0.5*numpy.pi lam = 0*numpy.pi qc.u(phi=phi, theta=theta,lam=lam,qubit=0) ## teleport the state qc.barrier() qc.h(1) qc.cx(1,2) qc.cz(0,1) qc.h(0) qc.h(1) qc.barrier() qc.measure([0,1],[0,1]) qc.barrier() qc.x(2).c_if(0,1) qc.z(2).c_if(1,1) qc.h(2) qc.measure(2,2) LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit f_name = 'quantum_teleportation.tex' with open(LaTex_folder_Quantum_Teleportation+f_name, 'w') as f: f.write(LaTex_code) # simulation simulator = Aer.get_backend('qasm_simulator') result = execute(qc, backend=simulator, shots=100000).result() counts = {'0':0, '1': 0} print(result.get_counts().keys()) for key, value in result.get_counts().items(): if(key[0] == '0'): counts['0'] += value else: counts['1'] += value print(counts) plt = plot_histogram(counts) draw() show(block=True)
https://github.com/IceKhan13/QiskitFlow
IceKhan13
import math import datetime import qiskitflow from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit def my_quantum_program(experiment_name: str = "Awesome experiment", seed: int = 42): """ Awesome docs here """ qf = qiskitflow.Experiment(experiment_name) start = datetime.datetime.now() # do some quantum coding here qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.u3(3.141592653589793, 1.5707963267948966, 4.71238898038469, qreg_q[0]) quantum_circuit_execution_result = circuit.measure(qreg_q[0], creg_c[0]) end = datetime.datetime.now() execution_time = end - start qf.write_metric("execution time", execution_time) qf.write_parameter("somehting important", "YEAH!") qf.write_parameter("t1", 42) qf.write_parameter("version of calbiration of almaden backend", 0.0.1) qf.write_measurement("intermediate measurement", quantum_circuit_execution_result) qf.write_result({ "something here to write as results": "great!" }) if __name__ == "__main__": my_quantum_program()
https://github.com/IceKhan13/QiskitFlow
IceKhan13
import qiskit import numpy as np from math import sqrt,pi from qiskit import * from qiskit.visualization import * from qiskit.extensions import Initialize from qiskit.quantum_info import * import time from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import * import math import datetime # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qc = QuantumCircuit(1) # Create a quantum circuit with one qubit psi = [1/sqrt(2),1/sqrt(2)] # Define initial_state in a superposition state initial_state =Initialize(psi) qc.append(initial_state, [0]) # Apply initialisation operation to the 0th qubit result = execute(qc,Aer.get_backend('statevector_simulator')).result() # Do the simulation, returning the result exp_state = result.get_statevector(qc) print(exp_state) # Display the output state vector qr = QuantumRegister(3) cr = ClassicalRegister(1) circuit = QuantumCircuit(qr,cr) circuit.append(initial_state,[0]) circuit.barrier() circuit.h(qr[1]) circuit.cx(qr[1],qr[2]) circuit.barrier() circuit.cx(qr[0],qr[1]) circuit.h(qr[0]) circuit.barrier() circuit.cz(qr[0],qr[2]) circuit.cx(qr[1],qr[2]) #inverse_init_gate = initial_state.gates_to_uncompute() #circuit.append(inverse_init_gate,[2]) circuit.measure(qr[2],cr) circuit.draw() t =time.time() backend = Aer.get_backend('qasm_simulator') job_circuit= execute(circuit,backend=backend,shots=1) device_counts = job_circuit.result().get_counts(circuit) job_monitor(job_circuit) print(job_circuit.job_id()) print('Time taken:', time.time()-t) qc = QuantumRegister(3) #cr = ClassicalRegister(1) circuit = QuantumCircuit(qc) circuit.append(initial_state,[0]) circuit.barrier() circuit.h(qc[1]) circuit.cx(qc[1],qc[2]) circuit.barrier() circuit.cx(qc[0],qc[1]) circuit.h(qc[0]) circuit.barrier() circuit.cz(qc[0],qc[2]) circuit.cx(qc[1],qc[2]) #inverse_init_gate = initial_state.gates_to_uncompute() #circuit.append(inverse_init_gate,[2]) #circuit.measure(qr[2],cr) circuit.draw() t = time.time() qst_circuit = state_tomography_circuits(circuit,qc[2]) job_circuit = execute(qst_circuit,backend=backend,shots=8192) job_monitor(job_circuit) print(job_circuit.job_id()) print('Time taken:', time.time()-t) tomo_circuit = StateTomographyFitter(job_circuit.result(),qst_circuit) tomo_circuit.data rho_circuit = tomo_circuit.fit() print(rho_circuit) F_state = state_fidelity(exp_state,rho_circuit) print('Fit_fidelity_state:',F_state) plot_state_city(rho_circuit) pur = purity(rho_circuit) print(pur)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(3) qc.ccx(0,1,2) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for ccx gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(3) qc.x(0) qc.x(1) qc.ccx(0,1,2) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(3) qc.cswap(0,1,2) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for cswap gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(3) qc.x(0) qc.x(1) qc.cswap(0,1,2) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex')
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,QuantumRegister,transpile from qiskit.test.mock import FakeVigo,FakeLondon qc=QuantumCircuit(1) qc.h(0) qc.barrier(0) qc.x(0) qc.barrier(0) qc.h(0) qc.draw(output="mpl") device_backend = FakeVigo() config_details = device_backend.configuration() config_details.backend_name config_details.n_qubits config_details.basis_gates qc_transpile=transpile(qc,device_backend) qc_transpile.draw(output="mpl") qc=QuantumCircuit(1) qc.h(0) qc.x(0) qc.h(0) qc.draw(output="mpl") qc_transpile=transpile(qc,device_backend) qc_transpile.draw(output="mpl") device_backend = FakeLondon() config_details = device_backend.configuration() config_details.backend_name config_details.n_qubits config_details.basis_gates qc=QuantumCircuit(1) qc.h(0) qc.x(0) qc.h(0) qc.draw(output="mpl") qc_transpile=transpile(qc,device_backend) qc_transpile.draw(output="mpl") qc=QuantumCircuit(1) qc.h(0) qc.barrier(0) qc.x(0) qc.barrier(0) qc.h(0) qc.draw(output="mpl") qc_transpile=transpile(qc,device_backend) qc_transpile.draw(output="mpl")
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi # No barrier gate present qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.draw(output="mpl") #Let's apply a barrier gate with no arguments qc=QuantumCircuit(1) qc.h(0) qc.h(0) qc.barrier() qc.y(0) qc.draw(output="mpl") #Let's apply a barrier gate with no arguments for a 3-qubit Quantum Circuit # If we don't specify any arguments, then the barrier is applied across all the qubits qc=QuantumCircuit(3) qc.h(range(2)) qc.barrier() qc.x(2) qc.draw(output="mpl") #Let's apply a barrier gate with 1 arguments for a 3-qubit Quantum Circuit # We want to apply a barrier only to the q0 qc=QuantumCircuit(3) qc.h(range(2)) qc.barrier(0) qc.x(2) qc.draw(output="mpl") qc=QuantumCircuit(3) qc.h(range(2)) qc.barrier(0,1) qc.x(2) qc.draw(output="mpl") # barrier is applied to q0 and q1 qc=QuantumCircuit(3) qc.h(range(2)) qc.barrier(0,1,2) qc.x(2) qc.draw(output="mpl") qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.draw(output="mpl") qc=QuantumCircuit(3) qc.h(range(2)) qc.barrier() qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.barrier() qc.cx(1,0) qc.draw(output="mpl") qr=QuantumRegister(3) qc=QuantumCircuit(qr) qc.x(0) qc.barrier(qr) qc.h(1) qc.barrier(qr) qc.s(1) qc.barrier(qr) qc.h(2) qc.draw(output="mpl")
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,BasicAer,transpile from qiskit.extensions import * from qiskit.quantum_info.operators import Operator, Pauli from qiskit.visualization import * from math import * import numpy as np backend=BasicAer.get_backend('unitary_simulator') qc=QuantumCircuit(1) qc.h(0) qc.x(0) qc.h(0) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) Operator(ZGate()).data qc=QuantumCircuit(1) qc.h(0) qc.z(0) qc.h(0) qc.draw() job = backend.run(transpile(qc, backend)) job.result().get_unitary(qc, decimals=3) Operator(XGate()).data qc=QuantumCircuit(1) qc.h(0) qc.z(0) qc.draw(output="mpl") #visualize_transition(qc) array_to_latex(Operator(XGate()).data) array_to_latex(Operator(YGate()).data) array_to_latex(Operator(ZGate()).data) array_to_latex(Operator(SGate()).data) array_to_latex(Operator(SdgGate()).data) array_to_latex(Operator(TGate()).data) array_to_latex(Operator(TdgGate()).data)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * qc1=QuantumCircuit(2,2) qc2=QuantumCircuit(3,3) #qc=qc1+qc2 #qc.draw() #Note: circuits are incompatible qc1=QuantumCircuit(2,2) qc1.h(0) qc1.s(1) qc2=QuantumCircuit(2,2) qc2.x(1) qc2.cx(0,1) qc1.draw(output='mpl') qc2.draw(output='mpl') qc=qc1+qc2 qc.draw(output='mpl') qc1=QuantumCircuit(2,2) qc1.h(0) qc1.s(1) qc1.draw(output='mpl') qc2=QuantumCircuit(3,3) qc2.x(1) qc2.cx(0,2) qc2.draw(output='mpl') # rhs added to lhs qc=qc2.compose(qc1) qc.draw(output='mpl') qc.num_qubits # If inplace attribute is not included , then it returns QuantumCircuit type(qc2.compose(qc1)) qc1=QuantumCircuit(2,2) qc1.h(0) qc1.s(1) qc2=QuantumCircuit(3,3) qc2.x(1) qc2.cx(0,2) qc2.compose(qc1,inplace=True) qc2.draw(output='mpl') type(qc2) qc2.num_qubits # If inplace attribute is true , then it returns None type(qc2.compose(qc1,inplace=True)) qc1=QuantumCircuit(2,2) qc1.h(0) qc1.s(1) qc2=QuantumCircuit(3,3) qc2.x(1) qc2.cx(0,2) qc2.compose(qc1,qubits=[2,1],inplace=True) qc2.draw(output='mpl') qc=QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.x(1) qc.draw(output='mpl') qc_meas=QuantumCircuit(2) qc_meas.measure_all() qc_meas.draw(output='mpl') qc.compose(qc_meas,inplace=True) qc.draw(output='mpl')
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(2) qc.crx(pi/2,0,1) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for CRx gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.crx(pi/2,0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.cry(pi/2,0,1) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for CRy gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.cry(pi/2,0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.crz(pi/2,0,1) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for CRz gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.crz(pi/2,0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex')
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister # If the name is not given, default name is taken q=QuantumRegister(2) q # We can also give the name to the quantum register q=QuantumRegister(2,'qr') q c=ClassicalRegister(2) c=ClassicalRegister(2,'cr') q=QuantumRegister(2,'qr') c=ClassicalRegister(2,'cr') qc=QuantumCircuit(q,c) qc=QuantumCircuit(QuantumRegister(2,'qr'),ClassicalRegister(2,'cr')) qc=QuantumCircuit(QuantumRegister(2,'qr')) qc=QuantumCircuit(QuantumRegister(2)) qc=QuantumCircuit(QuantumRegister(2),ClassicalRegister(2)) qc=QuantumCircuit(2) qc=QuantumCircuit(2,2) qc # In this example, we have given registers name qc=QuantumCircuit(QuantumRegister(2,'qr'),ClassicalRegister(2,'cr')) qc.draw(output="mpl") print(qc.qubits) print(qc.clbits) # In this example, we have NOT given registers name qc=QuantumCircuit(2,2) qc.draw(output="mpl") print(qc.qubits) print(qc.clbits) qc.qregs qc.cregs qc.num_qubits qc.num_clbits qc.clbits qc.qubits qc.width() #total number of qubits and classical bits
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit import numpy as np qc = QuantumCircuit(3) qc.ccx(0,1,2) qc.draw(output="mpl") qc.decompose().draw(output="mpl") qc = QuantumCircuit(2) qc.y(0) qc.z(1) qc.h(0) qc.swap(0,1) qc.draw(output="mpl") qc.decompose().draw(output="mpl") qc.decompose().decompose().draw(output="mpl") qc = QuantumCircuit(1) qc.initialize([1/np.sqrt(2), -1/np.sqrt(2)], 0) qc.draw(output="mpl") qc.decompose().draw(output="mpl") qc.decompose().decompose().draw(output="mpl") qc.decompose().decompose().decompose().draw(output="mpl") qc.decompose().decompose().decompose().decompose().draw(output="mpl")
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector def qasm_sim(qc): backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1024) result = job.result() counts = result.get_counts(qc) return counts qc=QuantumCircuit(2) qc.x(0) qc.h(1) qc.draw(output="mpl") qc.measure_all() qc.draw(output="mpl") qc.size() qc.clbits qc=QuantumCircuit(2) qc.x(0) qc.h(1) qc.draw(output="mpl") qc=QuantumCircuit(2,2) # 2 qubits and 2 bits qc.x(0) qc.h(1) qc.draw(output="mpl") qc.measure(0,0) qc.measure(1,1) qc.draw(output="mpl") qc=QuantumCircuit(2,2) # 2 qubits and 2 bits qc.x(0) qc.h(1) qc.draw(output="mpl") qc.measure([0,1],[0,1]) qc.draw(output="mpl") qc=QuantumCircuit(2) qc.measure_all() qc.draw(output="mpl") backend = Aer.get_backend('qasm_simulator') job=execute (qc, backend) result = job.result() counts = result.get_counts() print(counts) qc=QuantumCircuit(2,2) # 2 qubits and 2 bits qc.x(0) qc.h(1) qc.measure(range(2),range(2)) qc.draw(output="mpl") q=QuantumRegister(2,'qr') c=ClassicalRegister(2,'cr') qc=QuantumCircuit(q,c) qc.h(0) qc.x(1) qc.draw(output="mpl") qc=QuantumCircuit(2,2) # 2 qubits and 2 bits qc.x(0) qc.h(1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc.reset(1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(1) qc.x(0) qc.h(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(1) # 2 qubits and 2 bits qc.x(0) qc.reset(0) qc.h(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qr=QuantumRegister(2,'qr') cr=ClassicalRegister(2,'cr') qc=QuantumCircuit(qr,cr) # 2 qubits and 2 bits qc.x(0) qc.x(1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc.s(qr[1]).c_if(cr,0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qr=QuantumRegister(2,'qr') cr=ClassicalRegister(2,'cr') qc=QuantumCircuit(qr,cr) # 2 qubits and 2 bits qc.x(0) qc.measure([0,1],[0,1]) qc.draw(output="mpl") qasm_sim(qc) qc.s(qr[0]).c_if(cr,1) qc.draw(output="mpl") qasm_sim(qc) qc.x(qr[1]).c_if(cr,1) qc.measure([0,1],[0,1]) qc.draw(output="mpl") qasm_sim(qc)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,QuantumRegister,transpile import qiskit.test.mock as fake_backends from qiskit.test.mock import FakeProvider provider = FakeProvider() backends =provider.backends() backends backend=provider.get_backend(name ='fake_vigo') backend from qiskit.test.mock import FakeVigo device_backend = FakeVigo() device_backend device_backend.name() config_details = device_backend.configuration() config_details.backend_name config_details.n_qubits config_details.basis_gates for i in range(len(backends)): backend_details = backends[i] config_details = backend_details.configuration() if config_details.n_qubits <=5: print(backends[i],":",config_details.basis_gates) from qiskit.test.mock import FakeLondon device_backend = FakeLondon() config_details = device_backend.configuration() config_details.backend_name config_details.n_qubits config_details.basis_gates
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(2) qc.cx(0,1) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for cx gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(2) qc.cx(1,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for cx gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(2) qc.cx(0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) print(state) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.cx(0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.cx(0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.cy(0,1) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for cy gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.cy(0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.cz(0,1) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for cz gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.x(1) qc.cz(0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.ch(0,1) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for ch gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.ch(0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.cp(pi/2,0,1) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for cp gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.x(1) qc.cp(pi/2,0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.swap(0,1) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for swap gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(2) qc.x(0) qc.swap(0,1) qc.draw(output="mpl") state = Statevector.from_instruction(qc) state.draw(output='latex')
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,AncillaRegister q=QuantumRegister(2) q=QuantumRegister(2,'qr') c=ClassicalRegister(2) c=ClassicalRegister(2,'cr') qr1=QuantumRegister(2,'qr_1') qr2=QuantumRegister(3,'qr_2') c=ClassicalRegister(2,'cr') qc=QuantumCircuit(qr1,qr2,c) qc.draw(output="mpl") qc.width() qc.qubits qc.num_qubits qr1=QuantumRegister(2,'qr_1') anc=AncillaRegister(3,'an') c=ClassicalRegister(2,'cr') qc=QuantumCircuit(qr1,anc,c) qc.draw(output="mpl") qc.width() qc.num_qubits qc.num_clbits qc.qubits # provides the information of qubits added qr1 anc qc qc=QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.x(1) qc.draw(output='mpl') qc.qregs qc.num_qubits qc2=QuantumRegister(2) qc.add_register(qc2) qc.draw(output='mpl') qc.qregs qc.num_qubits qr=QuantumRegister(2,'q') cr=ClassicalRegister(2,'c') qc=QuantumCircuit(qr,cr) qc.h(0) qc.x(1) qc.draw(output="mpl") qr qc.qregs qr_add=QuantumRegister(2,'qr_add') qc.add_register(qr_add) qc.draw(output="mpl") qr_add qc.qregs cr_add=ClassicalRegister(2,'cr_add') qc.add_register(cr_add) qc.draw(output="mpl") cr_add qc.cregs qc.measure([0,1,2,3],[0,1,2,3]) qc.draw(output="mpl")
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit, Aer, assemble import numpy as np from qiskit.visualization import plot_histogram, plot_bloch_multivector from qiskit.visualization import array_to_latex qc = QuantumCircuit(3) # Apply H-gate to each qubit: for qubit in range(3): qc.h(qubit) # See the circuit: qc.draw() # Let's see the result svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() # In Jupyter Notebooks we can display this nicely using Latex. # If not using Jupyter Notebooks you may need to remove the # array_to_latex function and use print(final_state) instead. array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.x(0) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.x(0) qc.h(1) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.h(1) qc.draw() svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() array_to_latex(final_state, prefix="\\text{Statevector} = ") qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw() usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(1) qc.x(0) qc.z(0) qc.h(0) qc.draw() usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(3) qc.x(2) qc.z(1) qc.h(0) qc.draw() usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) # Apply a CNOT: qc.cx(0,1) qc.draw() # Let's get the result: qc.save_statevector() qobj = assemble(qc) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") plot_bloch_multivector(final_state) qc = QuantumCircuit(2) # Apply H-gate to the first: qc.h(0) qc.draw() # Let's get the result: qc.save_statevector() qobj = assemble(qc) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") plot_bloch_multivector(final_state) qc = QuantumCircuit(2) # Apply H-gate to the first: qc.x(0) qc.h(1) qc.cx(1,0) qc.draw() # Let's get the result: qc.save_statevector() qobj = assemble(qc) result = svsim.run(qobj).result() # Print the statevector neatly: final_state = result.get_statevector() array_to_latex(final_state, prefix="\\text{Statevector = }") qc = QuantumCircuit(2) # Apply H-gate to the first: qc.x(0) qc.h(1) qc.cx(1,0) usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n")
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.draw(output="mpl") print(qc.qasm()) qc_qasm=qc.qasm(filename='sample.qasm') print(qc_qasm) qc1=qc.from_qasm_file("./sample.qasm") qc1.draw(output="mpl") qc2=qc.from_qasm_str(qc.qasm()) qc2.draw(output="mpl")
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,Aer,execute,transpile,BasicAer from qiskit.visualization import * import numpy as np qc = QuantumCircuit(1) qc.initialize([1/np.sqrt(2), -1/np.sqrt(2)], 0) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") print(sv) plot_state_qsphere(sv,show_state_phases=True) qc = QuantumCircuit(1) qc.x(0) qc.h(0) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") qc = QuantumCircuit(2) qc.initialize('01', qc.qubits) qc.draw(output="mpl") backend = BasicAer.get_backend('statevector_simulator') job = backend.run(transpile(qc, backend)) qc_state = job.result().get_statevector(qc) qc_state array_to_latex(qc_state) qc = QuantumCircuit(2) qc.x(0) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") qc = QuantumCircuit(2) qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits) qc.draw() backend = BasicAer.get_backend('statevector_simulator') job = backend.run(transpile(qc, backend)) qc_state = job.result().get_statevector(qc) qc_state array_to_latex(qc_state) qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.cx(0,1) qc.sdg(1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex")
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.size() qc.width() qc.depth() qc.num_qubits qc.count_ops() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.size() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.width() qc.qregs qc.qubits qc.num_qubits qc.cregs qc.clbits qc.num_clbits qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(1) qc.h(0) qc.y(0) qc.draw(output="mpl") qc.depth() #Let's apply a barrier gate with no arguments qc=QuantumCircuit(1) qc.h(0) qc.h(0) qc.y(0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.barrier() qc.cx(1,0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.qubits qc.num_qubits qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.count_ops()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
# We import the necessary functions from Qiskit from qiskit.visualization import plot_bloch_multivector, visualize_transition from qiskit import QuantumCircuit, Aer, execute from math import pi # We create a quantum circuit with one qubit qc = QuantumCircuit(1) # We execute the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result() # We get the statevector of the quantum circuit statevector = result.get_statevector(qc) # We plot the statevector on the Bloch sphere plot_bloch_multivector(statevector) qc.ry(pi/2, 0) qc.draw(output='mpl') visualize_transition(qc) qc1 = QuantumCircuit(1) qc1.rx(pi/3, 0) qc1.draw(output='mpl') visualize_transition(qc1) qc2 = QuantumCircuit(1) qc2.rz(pi, 0) qc2.draw(output='mpl') visualize_transition(qc2)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister qc=QuantumCircuit(QuantumRegister(3,'qr')) qc.h(0) qc.h(1) qc.h(2) qc.draw(output="mpl") qc=QuantumCircuit(QuantumRegister(3,'qr')) qc.h(range(3)) qc.draw(output="mpl") q=QuantumRegister(3,'qr') qc=QuantumCircuit(q) qc.h(q[0:3]) qc.draw(output="mpl") q=QuantumRegister(3,'qr') qc=QuantumCircuit(q) qc.h(q[0]) qc.draw(output="mpl")
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi from qiskit.visualization import * qc=QuantumCircuit(1) qc.x(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-X gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.x(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-X gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.y(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-Y gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.y(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-Y gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(1) qc.z(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-Z gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(1) qc.z(0) qc.draw(output="mpl") qc=QuantumCircuit(1) qc.x(0) qc.z(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Pauli-Z gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Hadamard gate print(result.get_unitary(qc, decimals=3)) state = Statevector.from_instruction(qc) state.draw(output='latex') qc=QuantumCircuit(1) qc.x(0) qc.h(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Hadamard gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.s(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for S gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.s(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for S gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.s(0) qc.s(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for S dagger gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.sdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Sdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.sdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Sdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.sdg(0) qc.sdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Sdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.t(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for T gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.t(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for T gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.tdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Tdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.tdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Tdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.tdg(0) qc.tdg(0) qc.tdg(0) qc.tdg(0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Tdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.z(0) backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for Tdg gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.p(pi,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for P gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.p(pi/2,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for P gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.p(pi/4,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for P gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.p(pi,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for P gate print(result.get_unitary(qc, decimals=3)) qc=QuantumCircuit(1) qc.x(0) qc.p(pi/2,0) qc.draw(output="mpl") qc=QuantumCircuit(1) qc.x(0) qc.p(pi/4,0) qc.draw(output="mpl") qc=QuantumCircuit(1) qc.p(0,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for P gate print(result.get_unitary(qc, decimals=3)) I=result.get_unitary(qc, decimals=3) array_to_latex(I)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.extensions import * from qiskit.quantum_info import Statevector,Operator from math import pi from qiskit.visualization import * qc = QuantumCircuit(1) qc.u(pi/2,pi/2,pi/2,0) qc.draw(output="mpl") backend = Aer.get_backend('unitary_simulator') job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for U gate Ugate_unitary=result.get_unitary(qc, decimals=3) print(Ugate_unitary) Ugate_unitary.data array_to_latex(Ugate_unitary) array_to_latex(Operator(UGate(pi/2,pi/2,pi/2)).data) qc = QuantumCircuit(1) qc.u(pi/2,0,pi,0) qc.draw(output="mpl") job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for U gate Ugate_unitary=result.get_unitary(qc, decimals=3) print(Ugate_unitary) array_to_latex(Ugate_unitary) array_to_latex(Operator(UGate(pi/2,0,pi)).data) array_to_latex(Operator(HGate()).data) qc = QuantumCircuit(1) qc.u(0,0,pi/2,0) qc.draw(output="mpl") job = execute(qc, backend) result = job.result() #Obtain the unitary matrix for U gate Ugate_unitary=result.get_unitary(qc, decimals=3) print(Ugate_unitary) array_to_latex(Ugate_unitary) array_to_latex(Operator(UGate(0,0,pi/2)).data) array_to_latex(Operator(PhaseGate(pi/2)).data) array_to_latex(Operator(UGate(pi/2,0,0)).data) array_to_latex(Operator(RYGate(pi/2)).data) array_to_latex(Operator(UGate(0,pi/2,-pi/2)).data) array_to_latex(Operator(RXGate(0)).data)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit.providers.aer import AerProvider,Aer from qiskit import QuantumCircuit from qiskit.test.mock import FakeVigo provider=AerProvider() backend_list=provider.backends() backend_list backend_list[0].name() for name in backend_list: print(name) backend=provider.backends(name='qasm_simulator') backend backend=provider.get_backend(name='qasm_simulator') backend backend.name() type(provider.backends()[0]) provider.backends()[0].name() print(provider.backends()[0]) print(provider.backends()[-1]) provider.backends()[0:8] provider.backends()[8:-1] from qiskit.providers.aer import AerSimulator backend=AerSimulator() backend backend.name() qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.measure_all() qc.draw(output="mpl") backend=AerSimulator() result= backend.run(qc).result() counts=result.get_counts() print(counts) backend=AerSimulator.from_backend(FakeVigo()) result= backend.run(qc).result() counts=result.get_counts() print(counts) backend=provider.backends(name='aer_simulator') backend backend=provider.get_backend(name='aer_simulator') backend backend.name() backend=Aer.backends(name='aer_simulator') backend backend=Aer.get_backend(name='aer_simulator') backend backend.name() #from qiskit.providers.aer import AerSimulator backend=AerSimulator() # creates an object of class AerSimulator backend backend.name()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit, Aer,execute, IBMQ,transpile from qiskit.visualization import * from qiskit.test.mock import FakeVigo qc=QuantumCircuit(3) qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.measure_all() qc.draw(output="mpl") qc.depth() # on the ideal simulator backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) backend = FakeVigo() job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) transpile_circuit=transpile(qc,backend) job=backend.run(transpile_circuit) result=job.result() counts=result.get_counts() print(counts) transpile_circuit.draw(output="mpl") transpile_circuit.depth() plot_circuit_layout(transpile_circuit, backend) transpile_circuit_new=transpile(qc,backend,optimization_level=2,initial_layout=[0,1,2]) job=backend.run(transpile_circuit_new) result=job.result() counts=result.get_counts() print(counts) transpile_circuit_new.draw(output="mpl") transpile_circuit_new.depth() plot_circuit_layout(transpile_circuit_new,backend)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit, Aer,execute, IBMQ from qiskit.visualization import plot_histogram ## Sample Program: Bell Circuit qc=QuantumCircuit(2,2) # 2 qubits and 2 classical bits qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc.measure([0,1],[0,1]) qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) plot_histogram(counts,title="Bell State without noise") #Load the account provider=IBMQ.load_account() #List all the available backends for the account #provider.backends() #Get the backend backend=provider.get_backend('ibmq_bogota') #Execute the circuit on the backend job=execute(qc,backend,shots=1024) #job.cancel() job.status() from qiskit.tools import job_monitor job_monitor(job) job.status() result=job.result() counts=result.get_counts() print(counts) plot_histogram(counts,title="Bell State with noise") job.job_id() from qiskit.compiler import transpile backend=provider.get_backend('ibmq_qasm_simulator') transpile_circuit=transpile(qc,backend) transpile_circuit.draw(output="mpl") from qiskit.compiler import transpile,assemble backend=provider.get_backend('ibmq_bogota') transpile_circuit=transpile(qc,backend) transpile_circuit.draw(output="mpl") backend.configuration().basis_gates backend=provider.get_backend('ibmq_bogota') transpile_circuit=transpile(qc,backend) job=backend.run(transpile_circuit) job.status() job_monitor(job) result=job.result() counts=result.get_counts() print(counts) plot_histogram(counts)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,IBMQ,execute, transpile,Aer from qiskit.visualization import plot_circuit_layout qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") transpile_circuit=transpile(qc) transpile_circuit.draw(output="mpl") provider=IBMQ.load_account() #Get the backend backend=provider.get_backend('ibmq_bogota') transpile_circuit=transpile(qc,backend) transpile_circuit.draw(output="mpl") backend.configuration().basis_gates plot_circuit_layout(transpile_circuit, backend) qc=QuantumCircuit(3) qc.h(0) qc.x(1) qc.cx(0,2) qc.draw(output="mpl") qc.depth() transpile_circuit=transpile(qc,backend) transpile_circuit.draw(output="mpl") transpile_circuit.depth() plot_circuit_layout(transpile_circuit, backend) transpile_circuit_0=transpile(qc,backend,optimization_level=0) transpile_circuit_0.draw(output="mpl") plot_circuit_layout(transpile_circuit_0, backend) transpile_circuit_0.depth() transpile_circuit_1=transpile(qc,backend,optimization_level=1) transpile_circuit_1.draw(output="mpl") plot_circuit_layout(transpile_circuit_1, backend) transpile_circuit_1.depth() transpile_circuit_2=transpile(qc,backend,optimization_level=2) transpile_circuit_2.draw(output="mpl") plot_circuit_layout(transpile_circuit_2, backend) transpile_circuit_2.depth() transpile_circuit_3=transpile(qc,backend,optimization_level=3) transpile_circuit_3.draw(output="mpl") plot_circuit_layout(transpile_circuit_3, backend) transpile_circuit_3.depth() from qiskit.tools.jupyter import * backend transpile_circuit_new=transpile(qc,backend,optimization_level=3,initial_layout=[2,3,4]) transpile_circuit_new.draw(output="mpl") plot_circuit_layout(transpile_circuit_new, backend) transpile_circuit_new=transpile(qc,backend,optimization_level=3,initial_layout=[0,2,3]) transpile_circuit_new.draw(output="mpl") plot_circuit_layout(transpile_circuit_new, backend) transpile_circuit_new.depth()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit.providers.aer import AerProvider from qiskit import Aer from qiskit import QuantumCircuit from qiskit.test.mock import FakeVigo Aer.backends() type(Aer.backends()[0]) Aer.backends() for name in (Aer.backends()): print(name) Aer.backends()[0].name() print(Aer.backends()[0]) print(Aer.backends()[-1]) Aer.backends()[0:8] Aer.backends()[8:-1] from qiskit.providers.aer import AerSimulator backend=AerSimulator() backend backend.name() qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.measure_all() qc.draw(output="mpl") backend=AerSimulator() result= backend.run(qc).result() counts=result.get_counts() print(counts) backend=AerSimulator.from_backend(FakeVigo()) result= backend.run(qc).result() counts=result.get_counts() print(counts) provider=AerProvider() backend=provider.backends(name='aer_simulator') backend backend=provider.get_backend(name='aer_simulator') backend backend.name() backend=Aer.backends(name='aer_simulator') backend backend=Aer.get_backend(name='aer_simulator') backend backend.name() #from qiskit.providers.aer import AerSimulator backend=AerSimulator() # creates an object of class AerSimulator backend backend.name()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import BasicAer from qiskit.providers.basicaer import BasicAerProvider backend_list=BasicAer.backends() backend_list for name in backend_list: print(name) backend=BasicAer.get_backend('qasm_simulator') backend backend.name() backend=BasicAer.backends(name='qasm_simulator') backend provider=BasicAerProvider() backend_list=provider.backends() backend_list for name in backend_list: print(name) backend=provider.backends(name='qasm_simulator') backend backend=provider.get_backend('qasm_simulator') backend backend.name() backend=BasicAer.backends(name='qasm_simulator') backend backend=BasicAer.get_backend('qasm_simulator') backend backend.name() provider=BasicAerProvider() backend=provider.backends(name='qasm_simulator') backend backend=provider.get_backend('qasm_simulator') backend backend.name() from qiskit.providers.basicaer import QasmSimulatorPy backend=QasmSimulatorPy() backend backend.name()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.draw(output="mpl") print(qc.qasm()) qc_qasm=qc.qasm(filename='sample.qasm') print(qc_qasm) qc1=qc.from_qasm_file("./sample.qasm") qc1.draw(output="mpl") qc2=qc.from_qasm_str(qc.qasm()) qc2.draw(output="mpl")
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister # If the name is not given, default name is taken q=QuantumRegister(2) q # We can also give the name to the quantum register q=QuantumRegister(2,'qr') q c=ClassicalRegister(2) c=ClassicalRegister(2,'cr') q=QuantumRegister(2,'qr') c=ClassicalRegister(2,'cr') qc=QuantumCircuit(q,c) qc=QuantumCircuit(QuantumRegister(2,'qr'),ClassicalRegister(2,'cr')) qc=QuantumCircuit(QuantumRegister(2,'qr')) qc=QuantumCircuit(QuantumRegister(2)) qc=QuantumCircuit(QuantumRegister(2),ClassicalRegister(2)) qc=QuantumCircuit(2) qc=QuantumCircuit(2,2) qc # In this example, we have given registers name qc=QuantumCircuit(QuantumRegister(2,'qr'),ClassicalRegister(2,'cr')) qc.draw(output="mpl") print(qc.qubits) print(qc.clbits) # In this example, we have NOT given registers name qc=QuantumCircuit(2,2) qc.draw(output="mpl") print(qc.qubits) print(qc.clbits) qc.qregs qc.cregs qc.num_qubits qc.num_clbits qc.clbits qc.qubits qc.width() #total number of qubits and classical bits
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
import numpy as np from qiskit import QuantumCircuit, BasicAer, execute from qiskit.circuit.library import YGate from qiskit.quantum_info import Operator, average_gate_fidelity, process_fidelity, state_fidelity #we define a operator op_a = Ygate op_a = Operator(YGate()) # we define also op_b=np.exp(1j / 2) * op_a which is essentially op_a but with a global phase np.exp(1j / 2) op_b = np.exp(1j / 2) * op_a #we run the fidelity for those gates average_gate_fidelity(op_a,op_b) process_fidelity(op_a, op_b) # same here, but now with a general state n = 1/np.sqrt(3) desired_state = [n,np.sqrt(1-n**2)] qc = QuantumCircuit(1) qc.initialize(desired_state,0) qc.draw('mpl') # we run it with help of a simulator back_sv = BasicAer.get_backend('statevector_simulator') result = execute(qc, back_sv).result() qc_sv = result.get_statevector(qc) #Now, we run the fidelity for those states and we see they are the same state_fidelity(desired_state, qc_sv)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit.quantum_info.operators import Operator, Pauli from qiskit.visualization import * from qiskit.extensions import XGate,HGate from qiskit import QuantumCircuit,BasicAer,execute X=Operator([[0,1],[1,0]]) X X.data array_to_latex(X.data) pauli_Xgate = Pauli(label='X') Operator(pauli_Xgate) array_to_latex(Operator(pauli_Xgate).data) Operator(pauli_Xgate).is_unitary() Operator(XGate()) array_to_latex(Operator(XGate()).data) qc = QuantumCircuit(1) qc.x(0) # Convert circuit to an operator by implicit unitary simulation Operator(qc) array_to_latex(Operator(qc).data) #Create an operator XX = Operator(Pauli(label='XX')) # Add to a circuit qc = QuantumCircuit(2) qc.append(XX, [0,1]) qc.measure_all() qc.draw('mpl') #Get the backend backend=BasicAer.get_backend('qasm_simulator') job=backend.run(qc) result=job.result() counts=result.get_counts() print(counts) # Add to a circuit qc = QuantumCircuit(2) qc.append(Pauli(label='XX'), [0,1]) qc.measure_all() qc.draw('mpl') #Get the backend backend=BasicAer.get_backend('qasm_simulator') job=execute(qc,backend) result=job.result() counts=result.get_counts() print(counts) array_to_latex(Operator(HGate()).data)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import * from qiskit.quantum_info import Statevector from math import pi qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.size() qc.width() qc.depth() qc.num_qubits qc.count_ops() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.size() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.width() qc.qregs qc.qubits qc.num_qubits qc.cregs qc.clbits qc.num_clbits qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(1) qc.h(0) qc.y(0) qc.draw(output="mpl") qc.depth() #Let's apply a barrier gate with no arguments qc=QuantumCircuit(1) qc.h(0) qc.h(0) qc.y(0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.ccx(0,1,2) qc.ry(pi,0) qc.ch(1,2) qc.tdg(2) qc.cx(1,0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.barrier() qc.cx(1,0) qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.depth() qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.qubits qc.num_qubits qc=QuantumCircuit(3) qc.h(range(2)) qc.x(2) qc.barrier() qc.ccx(0,1,2) qc.barrier() qc.ry(pi,0) qc.ch(1,2) qc.barrier() qc.tdg(2) qc.cx(1,0) qc.measure_all() qc.draw(output="mpl") qc.count_ops()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit.quantum_info import * from qiskit import QuantumCircuit qc=QuantumCircuit(2) sv=Statevector.from_label('01') sv_evolve=sv.evolve(qc) sv_evolve sv_evolve.data sv_evolve.draw(output="latex") sv_evolve.draw('qsphere') qc=QuantumCircuit(2) sv=Statevector.from_int(2,2**2) sv_evolve=sv.evolve(qc) sv_evolve sv_evolve.data sv_evolve.draw(output="latex") qc=QuantumCircuit(2) density_M=DensityMatrix.from_label('01') density_M=density_M.evolve(qc) density_M density_M.data density_M.draw(output="latex") density_M.to_operator() density_M.to_statevector() density_M.draw('city')
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,BasicAer,Aer,transpile,execute from qiskit.visualization import * qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.measure_all() qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) # For the statevector ,no measurements qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) plot_state_city(sv) qc=QuantumCircuit(2) qc.x(0) qc.h(0) qc.cx(0,1) qc.measure_all() qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) # For the statevector ,no measurements qc=QuantumCircuit(2) qc.x(0) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) plot_state_city(sv) qc=QuantumCircuit(2) qc.h(0) qc.x(1) qc.cx(0,1) qc.measure_all() qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) # For the statevector ,no measurements qc=QuantumCircuit(2) qc.h(0) qc.x(1) qc.cx(0,1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) plot_state_city(sv) qc=QuantumCircuit(2) qc.x(0) qc.h(0) qc.x(1) qc.cx(0,1) qc.measure_all() qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) # For the statevector ,no measurements qc=QuantumCircuit(2) qc.x(0) qc.h(0) qc.x(1) qc.cx(0,1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) plot_state_city(sv) qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) qc=QuantumCircuit(1) qc.x(0) qc.h(0) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv,show_state_phases=True) qc=QuantumCircuit(1) qc.h(0) qc.sdg(0) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv, show_state_phases=True) qc=QuantumCircuit(3) qc.h(0) qc.cx(0,1) qc.cx(0,2) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend,shots=1024) result=job.result() sv=result.get_statevector() sv.draw(output="latex") plot_state_qsphere(sv, show_state_phases=True)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,Aer,transpile,execute from qiskit.quantum_info import * from qiskit.visualization import * qc=QuantumCircuit(2) qc.h(0) qc.h(1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') job=execute(qc,backend) result=job.result() sv=result.get_statevector() sv sv.data array_to_latex(sv.data) sv.draw("latex") sv.draw("qsphere") qc_transpile=transpile(qc,backend) job=backend.run(qc_transpile) result=job.result() sv=result.get_statevector() sv sv.data array_to_latex(sv.data) sv.draw("latex") sv_label=Statevector.from_label('++') sv_label.data qc=QuantumCircuit(2) sv=Statevector.from_label('++') sv_evolve=sv.evolve(qc) sv_evolve sv_evolve.data sv sv_evolve.draw(output="latex") qc.draw(output="mpl") qc.initialize(sv_evolve) qc.draw(output="mpl") qc=QuantumCircuit(2) qc.initialize([0.5,0.5,0.5,0.5],[0,1]) sv_evolve=sv.evolve(qc) sv_evolve sv_evolve.draw("latex") array_to_latex(sv_evolve.data) qc.draw(output="mpl") from qiskit import BasicAer qc=QuantumCircuit(2) qc.h(0) qc.h(1) qc.draw(output="mpl") backend=BasicAer.get_backend('statevector_simulator') qc_transpile=transpile(qc,backend) job=backend.run(qc_transpile) result=job.result() sv=result.get_statevector() sv array_to_latex(sv.data) # basis |0> and dim= 2^1=2 sv_label_0=Statevector.from_int(0,2**1) sv_label_0.data sv_label_0.draw("latex") # basis 1(|01>) and dim= 2^2=4 sv_label=Statevector.from_int(1,2**2) sv_label.data sv_label.draw("latex") # basis |0> and dim= 2^2=4 sv_label=Statevector.from_int(0,2**2) sv_label.data sv_label.draw("latex") qc=QuantumCircuit(2) qc.h(0) qc.h(1) sv_evolve=sv_label.evolve(qc) sv_evolve sv_evolve.draw("latex") array_to_latex(sv_evolve.data)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,BasicAer,Aer,transpile,execute, IBMQ from qiskit.visualization import plot_histogram qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc.measure_all() qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') backend.name() job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) plot_histogram(counts) provider=IBMQ.load_account() #Get the backend backend=provider.get_backend('ibmq_bogota') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) plot_histogram(counts) jobID=job.job_id() jobID qc=job.circuits() qc[0].draw(output="mpl")
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,BasicAer,Aer,transpile qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') backend.name() job=backend.run(qc) result=job.result() sv=result.get_statevector() sv sv.draw(output='latex') backend=Aer.get_backend('statevector_simulator') qc_transpile=transpile(qc,backend) job=backend.run(qc_transpile) result=job.result() sv=result.get_statevector() print(sv) sv.draw(output='latex') qc=QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw(output="mpl") backend=Aer.get_backend('statevector_simulator') qc_transpile=transpile(qc,backend) job=backend.run(qc_transpile) result=job.result() sv=result.get_statevector() print(sv) sv.draw(output='latex') # get the raw data of the experiment sv.data
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit import * # Loading your IBM Q account(s) #provider = IBMQ.load_account() q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.x(q[0]) sim = Aer.get_backend('unitary_simulator') job = execute(qc, sim) unitary = job.result().get_unitary() unitary unitary = array_to_latex(unitary) unitary
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import IBMQ from qiskit.providers.ibmq import least_busy #IBMQ.save_account('TOKEN ID needs to be provided') #Load the account IBMQ.load_account() # Providers available IBMQ.providers() ibmq_account = IBMQ.load_account() backends = ibmq_account.backends() backends backend = ibmq_account.get_backend('ibmq_qasm_simulator') backend backend.name() backend=ibmq_account.backend.ibmq_qasm_simulator backend backend.name() ibmq_provider = IBMQ.get_provider(hub='ibm-q') ibmq_provider.backends() ibmq_provider.backends(filters=lambda b: b.configuration().n_qubits > 5) ibmq_provider.backends(n_qubits=5, operational=True) ibmq_provider.backends(simulator=False, operational=True) ibmq_provider.backends(simulator=True) least_busy(ibmq_provider.backends()) backend=least_busy(ibmq_provider.backends()) backend.name() backend.provider() backend.configuration() backend.status() backend.properties() backend=ibmq_account.backend.ibmq_qasm_simulator backend.name() backend.provider() backend.configuration() backend.status() backend.properties() backend=ibmq_account.backend.ibmq_bogota backend.jobs() backend.jobs()[0]
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit,IBMQ, execute from qiskit.visualization import * from qiskit.tools import job_monitor # Bell Quantum Circuit qc=QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc.measure([0,1],[0,1]) qc.draw(output="mpl") #IBMQ.save_account('TOKEN ID needs to be provided') #Load the account provider=IBMQ.load_account() provider.backends() #Get the backend backend=provider.get_backend('ibmq_bogota') #Execute the circuit on the backend job=execute(qc,backend,shots=1024) job.status() backend.status() job_monitor(job) job.status() #Obtain the result result=job.result() #get and print the counts counts=result.get_counts() print(counts) plot_histogram(counts,title="Bell State Counts") job.job_id() job.backend() job.result() job.status() jobID=job.job_id() job_get=backend.retrieve_job(jobID) job_get job_get.result().get_counts(qc) counts backend.jobs() ## 3. List of unfinished jobs of the backend: active_jobs() backend.active_jobs() ## 4. No of jobs which can be submitted to the backend : remaining_jobs_count() backend.remaining_jobs_count() backend.status() backend.name() backend.provider()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import IBMQ, BasicAer, QuantumCircuit, execute import qiskit.tools.jupyter from qiskit.tools import job_monitor from qiskit.visualization import plot_gate_map, plot_error_map from qiskit.providers.ibmq import least_busy provider = IBMQ.load_account() %qiskit_version_table print(qiskit.__qiskit_version__) ## qiskit terra version print(qiskit.__version__) %qiskit_copyright BasicAer.backends() # It works also for other simulators such as: Aer.backends() %qiskit_backend_overview backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and not b.configuration().simulator and b.status().operational==True)) print(backend) # Plot gate map plot_gate_map(backend, plot_directed = True) # Plot error map plot_error_map(backend) qc_open = QuantumCircuit.from_qasm_file('myfile.qasm') qc_open.draw('mpl') temp = QuantumCircuit(2) temp.h(0) temp.h(1) temp.s(0) temp.s(1) qasm_str = temp.qasm() #returning a qasm string, THIS SIMPLE qasm_str qc_open1 = QuantumCircuit.from_qasm_str(qasm_str) qc_open1 == qc_open %qiskit_job_watcher backend_sim = BasicAer.get_backend('qasm_simulator') job = execute(qc_open1, backend_sim, shots = 1024) job_monitor(job) # or job.status()
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
# From IBMQ backends information we know import qiskit from qiskit import IBMQ from qiskit.providers.ibmq import least_busy from qiskit.tools.jupyter import * # IBMQ.save_account("Token needs to be provided") provider = IBMQ.load_account() %qiskit_backend_overview backend = provider.get_backend('ibmq_bogota') backend %qiskit_version_table import qiskit qiskit.__version__ qiskit.__qiskit_version__ %qiskit_job_watcher
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector from math import pi,sqrt qc = QuantumCircuit(2) qc.h(1) state = Statevector.from_instruction(qc) plot_bloch_multivector(state, title="New Bloch Multivector", reverse_bits=False) state plot_bloch_multivector(state, title="New Bloch Multivector") vector=[1/sqrt(2),0,0,1/sqrt(2)] plot_bloch_multivector(vector) vector=[1/sqrt(2),0,1/sqrt(2),0] plot_bloch_multivector(vector)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
import numpy as np from qiskit.visualization import plot_bloch_vector %matplotlib inline I = np.array([ [1., 0.], [0., 1.] ]) X = np.array([ [0., 1.], [1., 0.] ]) Y = np.array([ [0., -1.j], [1.j, 0.] ]) Z = np.array([ [1., 0.], [0., -1.] ]) def Rx(theta): return np.cos(theta/2) * I - 1.j * np.sin(theta/2) * X def Ry(theta): return np.cos(theta/2) * I - 1.j * np.sin(theta/2) * Y def Rz(theta): return np.cos(theta/2) * I - 1.j * np.sin(theta/2) * Z def density_matrix(state): if len(state.shape) == 1: state = state.reshape(-1, 1) return state * np.conjugate(state.T) def state2bloch(state): rho = density_matrix(state) x, y, z = np.trace(X @ rho), np.trace(Y @ rho), np.trace(Z @ rho) return np.real(np.array([x, y, z])) def bloch2state(vec, epsilon = 1e-10): x, y, z = np.real(vec) cos = np.sqrt((1 + z)/2) if z > 1 - epsilon: # theta = 0 return np.array([1., 0.]) elif z < -1 + epsilon: # theta = pi return np.array([0., 1.]) else: sin = np.sqrt(x**2 + y**2) / (2*cos) if x < 0: sin = -sin if abs(x) < epsilon: # phi = pi/2, 3pi/2 if y >= 0: phi = np.pi/2 else: phi = 3 * np.pi/2 else: phi = np.arctan(y/x) return np.array([cos, np.exp(1.j*phi)*sin]) #print(state2bloch(np.array([1., 0.]))) #print(bloch2state(np.array([0., 0., 1.]))) init_vec = np.array([0., 0., 1.]) print(init_vec) display(plot_bloch_vector(init_vec)) final_vec = state2bloch(Rx(np.pi/4) @ bloch2state(init_vec)) print(final_vec) display(plot_bloch_vector(final_vec)) init_state = np.array([1., 0.]) final_state = Rx(np.pi/4) @ Ry(np.pi/4) @ init_state final_vec = state2bloch(final_state) print(final_vec) display(plot_bloch_vector(final_vec)) def rot(theta): return np.array([ [np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)], ]) init_vec = np.array([0., 0., 1.]) vec = init_vec[:] vec[[2,0]] = rot(np.pi/4)@vec[[2,0]] # rotate only 2:z, 0:x around Y-axis vec[[1,2]] = rot(np.pi/4)@vec[[1,2]] # rotate only 1:y, 2:z around X-axis print(vec) display(plot_bloch_vector(vec)) from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(1) # First, rotate around Y-axis qc.ry(np.pi/4, 0) state = Statevector.from_instruction(qc) print('First, rotate around Y-axis...') display(plot_bloch_multivector(state)) # Then, rotate around X-axis qc.rx(np.pi/4, 0) print('Then, rotate around X-axis.') state = Statevector.from_instruction(qc) display(plot_bloch_multivector(state))
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit, Aer,execute, IBMQ from qiskit.visualization import plot_histogram ## Sample Program: Bell Circuit qc=QuantumCircuit(2,2) # 2 qubits and 2 classical bits qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc.measure([0,1],[0,1]) qc.draw(output="mpl") backend=Aer.get_backend('qasm_simulator') job=execute(qc,backend,shots=1024) result=job.result() counts=result.get_counts() print(counts) plot_histogram(counts,title="Bell State without noise") #Load the account provider=IBMQ.load_account() #List all the available backends for the account #provider.backends() #Get the backend backend=provider.get_backend('ibmq_bogota') #Execute the circuit on the backend job=execute(qc,backend,shots=1024) result=job.result() counts2=result.get_counts() print(counts2) plot_histogram(counts2,title="Bell State with noise") #Load the account provider=IBMQ.load_account() #List all the available backends for the account #provider.backends() #Get the backend backend=provider.get_backend('ibmq_belem') #Execute the circuit on the backend job=execute(qc,backend,shots=1024) result=job.result() counts3=result.get_counts() print(counts3) plot_histogram(counts3,title="Bell State with noise") plot_histogram([counts2,counts3],legend=['Bogota_device', 'Belem_device']) legend=['Bogota_device', 'Belem_device'] plot_histogram([counts2,counts3],legend=legend) counts_legend='Bogota_device' counts2_legend ='Belem_device' plot_histogram([counts2,counts3],legend=[counts_legend,counts2_legend]) plot_histogram([counts,counts2],legend=['qasm simulator','Bogota Real device']) counts hist_plot=plot_histogram([counts,counts2],legend=['qasm simulator','Bogota Real device']) type(hist_plot) hist_plot hist_plot.savefig('histPlot.png') %matplotlib inline hist_plot.show() from IPython.display import display display(hist_plot)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit.visualization import * from qiskit import QuantumCircuit,transpile from qiskit import IBMQ provider=IBMQ.load_account() provider provider.backends() backend=provider.get_backend("ibmq_lima") backend plot_gate_map(backend) plot_error_map(backend) qc=QuantumCircuit(3) qc.h(0) qc.cx(0,1) qc.z(1) qc.draw(output="mpl") qc_transpile=transpile(qc,backend) qc_transpile.draw(output="mpl") plot_circuit_layout(qc_transpile,backend)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit qc=QuantumCircuit(3,3) qc.h(0) qc.x(1) qc.cx(0,1) qc.h(1) qc.ccx(0,1,2) qc.draw() qc.draw(output='text') qc.draw(output='mpl') qc.draw(output='latex_source') qc=QuantumCircuit(3,3) qc.h(0) qc.barrier() qc.x(1) qc.cx(0,1) qc.h(1) qc.barrier() qc.ccx(0,1,2) qc.draw(output="mpl") qc=QuantumCircuit(3,3) qc.h(0) qc.barrier() qc.x(1) qc.cx(0,1) qc.h(1) qc.barrier() qc.ccx(0,1,2) qc.draw(output="mpl",plot_barriers=False) qc=QuantumCircuit(3,3) qc.h(0) qc.barrier() qc.x(1) qc.cx(0,1) qc.h(1) qc.barrier() qc.ccx(0,1,2) qc.draw(output="mpl") qc=QuantumCircuit(3,3) qc.h(0) qc.barrier() qc.x(1) qc.cx(0,1) qc.h(1) qc.barrier() qc.ccx(0,1,2) qc.draw(output="mpl",reverse_bits=True) print(qc) qc=QuantumCircuit(3,3) qc.h(0) qc.barrier() qc.x(1) qc.cx(0,1) qc.h(1) qc.barrier() qc.ccx(0,1,2) qc.draw(output="mpl",initial_state=True)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,BasicAer,execute from qiskit.visualization import * qc=QuantumCircuit(2,2) qc.h(0) qc.x(1) qc.draw(output="mpl") backend=BasicAer.get_backend('statevector_simulator') job=execute(qc,backend) result=job.result() sv=result.get_statevector() print(sv) plot_state_city(sv) plot_state_qsphere(sv) qc=QuantumCircuit(2,2) qc.x(0) qc.h(0) qc.h(1) qc.s(0) qc.draw(output="mpl") backend=BasicAer.get_backend('statevector_simulator') job=execute(qc,backend) result=job.result() sv=result.get_statevector() print(sv) plot_state_qsphere(sv) plot_state_paulivec(sv) plot_state_hinton(sv) plot_bloch_multivector(sv) qc=QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") backend=BasicAer.get_backend('statevector_simulator') job=execute(qc,backend) result=job.result() sv=result.get_statevector() print(sv) plot_bloch_multivector(sv) plot_state_qsphere(sv) plot_state_city(sv)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit from qiskit.visualization import visualize_transition,circuit_drawer from math import pi qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) circuit_drawer(qc,output="mpl") qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") visualize_transition(qc)
https://github.com/hkhetawat/QArithmetic
hkhetawat
from QArithmetic import mult from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit import BasicAer from qiskit.tools.visualization import iplot_histogram from qiskit.tools.visualization import circuit_drawer # number of qubits N = 2 a = QuantumRegister(N, 'a') b = QuantumRegister(N, 'b') m = QuantumRegister(2*N, 'res') anc = QuantumRegister(4, 'anc') c = QuantumRegister(N, 'anc2') cr = ClassicalRegister(2*N+1) #create quantum circuit qc = QuantumCircuit(a, b, m, anc, cr) qc.add_register(c) H = QuantumCircuit(a, b, m, anc, c, cr) H.h(a) H.h(b) mult(qc, a, b, m, N) qc.x(m[0]) qc.x(m[3]) qc.ccx(m[0], m[1], anc[0]) qc.ccx(m[2], anc[0], anc[1]) qc.ccx(m[3], anc[2], anc[1]) qc.cx(anc[1], anc[2]) qc.ccx(m[3], anc[2], anc[1]) qc.ccx(m[2], anc[0], anc[1]) qc.ccx(m[0], m[1], anc[0]) qc.x(m[0]) qc.x(m[3]) Grover = H + qc Grover.barrier(a) Grover.barrier(b) Grover.measure(a[0], cr[0]) Grover.measure(a[1], cr[1]) Grover.measure(b[0], cr[2]) Grover.measure(b[1], cr[3]) Grover.measure(anc[2], cr[4]) from qiskit import BasicAer backend_sim = BasicAer.get_backend('qasm_simulator') job_sim = execute(Grover, backend_sim) result_sim = job_sim.result() counts = result_sim.get_counts(Grover) print(counts) from qiskit.tools.visualization import plot_histogram, iplot_histogram plot_histogram(counts)
https://github.com/hkhetawat/QArithmetic
hkhetawat
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import add # Registers and circuit. a = QuantumRegister(4) b = QuantumRegister(5) ca = ClassicalRegister(4) cb = ClassicalRegister(5) qc = QuantumCircuit(a, b, ca, cb) # Numbers to add. qc.x(a[1]) # a = 01110 qc.x(a[2]) qc.x(a[3]) qc.x(b[0]) # b = 01011 qc.x(b[1]) qc.x(b[3]) # Add the numbers, so |a>|b> to |a>|a+b>. add(qc, a, b, 4) # Measure the results. qc.measure(a, ca) qc.measure(b, cb) # Simulate the circuit. backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc)) from QArithmetic import sub # Registers and circuit. a = QuantumRegister(5) b = QuantumRegister(5) ca = ClassicalRegister(5) cb = ClassicalRegister(5) qc = QuantumCircuit(a, b, ca, cb) # Numbers to subtract. qc.x(a[1]) # a = 01110 qc.x(a[2]) qc.x(a[3]) qc.x(b[0]) # b = 01011 qc.x(b[1]) qc.x(b[3]) # Add the numbers, so |a>|b> to |a>|a-b>. sub(qc, a, b, 5) # Measure the results. qc.measure(a, ca) qc.measure(b, cb) # Simulate the circuit. backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc)) from QArithmetic import mult # Registers and circuit. a = QuantumRegister(2) b = QuantumRegister(2) m = QuantumRegister(4) cm = ClassicalRegister(4) qc = QuantumCircuit(a, b, m, cm) # Numbers to multiply. qc.x(a[1]) # a = 10 = 2 qc.x(b[0]) # b = 11 = 3 qc.x(b[1]) # Multiply the numbers, so |a>|b>|m=0> to |a>|b>|a*b>. mult(qc, a, b, m, 2) # Measure the result. qc.measure(m, cm) # Simulate the circuit. backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc)) from QArithmetic import div # Registers and circuit. a = QuantumRegister(4) b = QuantumRegister(4) c = QuantumRegister(2) ca = ClassicalRegister(4) cb = ClassicalRegister(4) cc = ClassicalRegister(2) qc = QuantumCircuit(a,b,c,ca,cb,cc) # Inputs. qc.x(a[0]) # a = 0011 qc.x(a[1]) qc.x(b[3]) # b = 1000 # Divide a by b. div(qc, a, b, c, 2) # Measure. qc.measure(a, ca) qc.measure(b, cb) qc.measure(c, cc) # Simulate the circuit. backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc)) from QArithmetic import power from qiskit.providers.aer import QasmSimulator # Registers and circuit a = QuantumRegister(2) b = QuantumRegister(2) m = QuantumRegister(6) ca = ClassicalRegister(2) cb = ClassicalRegister(2) cm = ClassicalRegister(6) qc = QuantumCircuit(a, b, m, ca, cb, cm) # Inputs. qc.x(a[1]) # a = 10 qc.x(b[1]) # b = 10 # Raise a to the b power. power(qc, a, b, m) # Measure. qc.measure(a, ca) qc.measure(b, cb) qc.measure(m, cm) #Simulate the circuit. backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc)) from QArithmetic import bitwise_and # Registers and circuit. a = QuantumRegister(4) b = QuantumRegister(4) c = QuantumRegister(4) ca = ClassicalRegister(4) cb = ClassicalRegister(4) cc = ClassicalRegister(4) qc = QuantumCircuit(a, b, c, ca, cb, cc) # Inputs qc.x(a[1]) # a =1010 qc.x(a[3]) qc.x(b[0]) # b = 1011 qc.x(b[1]) qc.x(b[3]) # Take the bitwise AND. bitwise_and(qc, a, b, c, 4) # Measure. qc.measure(a, ca) qc.measure(b, cb) qc.measure(c, cc) # Simulate the circuit. backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc)) from QArithmetic import bitwise_or # Registers and circuit. a = QuantumRegister(4) b = QuantumRegister(4) c = QuantumRegister(4) ca = ClassicalRegister(4) cb = ClassicalRegister(4) cc = ClassicalRegister(4) qc = QuantumCircuit(a, b, c, ca, cb, cc) # Input. qc.x(a[1]) # a = 1010 qc.x(a[3]) qc.x(b[0]) # b = 1011 qc.x(b[1]) qc.x(b[3]) # Take the bitwise OR. bitwise_or(qc, a, b, c, 4) # Measure. qc.measure(a, ca) qc.measure(b, cb) qc.measure(c, cc) # Simulate the circuit. backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc)) from QArithmetic import bitwise_xor # Registers and circuit. a = QuantumRegister(4) b = QuantumRegister(4) c = QuantumRegister(4) ca = ClassicalRegister(4) cb = ClassicalRegister(4) cc = ClassicalRegister(4) qc = QuantumCircuit(a, b, c, ca, cb, cc) # Input. qc.x(a[1]) # a = 1010 qc.x(a[3]) qc.x(b[0]) # b = 1011 qc.x(b[1]) qc.x(b[3]) # Take the bitwise XOR. bitwise_xor(qc, a, b, c, 4) # Measure. qc.measure(a, ca) qc.measure(b, cb) qc.measure(c, cc) # Simulate the circuit. backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc)) from QArithmetic import bitwise_not # Registers and circuit. a = QuantumRegister(4) b = QuantumRegister(4) ca = ClassicalRegister(4) cb = ClassicalRegister(4) qc = QuantumCircuit(a, b, ca, cb) # Input. qc.x(a[1]) # a = 1010 qc.x(a[3]) # Take the bitwise NOT. bitwise_not(qc, a, b, 4) # Measure. qc.measure(a, ca) qc.measure(b, cb) # Simulate the circuit. backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
from math import pi from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister from qft import qft, iqft, cqft, ciqft, ccu1 from qiskit.circuit.library import SXdgGate ################################################################################ # Bitwise Operators ################################################################################ # bit-wise operations def bitwise_and(qc, a, b, c, N): for i in range(0, N): qc.ccx(a[i], b[i], c[i]) def bitwise_or(qc, a, b, c, N): for i in range(0, N): qc.ccx(a[i], b[i], c[i]) qc.cx(a[i], c[i]) qc.cx(b[i], c[i]) def bitwise_xor(qc, a, b, c, N): for i in range(0, N): qc.cx(a[i], c[i]) qc.cx(b[i], c[i]) def bitwise_not(qc, a, c, N): for i in range(0, N): qc.cx(a[i], c[i]) qc.x(c[i]) # Cyclically left-shifts a binary string "a" of length n. # If "a" is zero-padded, equivalent to multiplying "a" by 2. def lshift(circ, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n,1,-1): circ.swap(a[i-1],a[i-2]) # Cyclically left-shifts a binary string "a" of length n, controlled by c. # If "a" is zero-padded, equivalent to multiplying "a" by 2, if and only if c. def c_lshift(circ, c, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n,1,-1): circ.cswap(c, a[i-1],a[i-2]) # Cyclically right-shifts a binary string "a" of length n. # If "a" is zero-padded, equivalent to dividing "a" by 2. def rshift(circ, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n-1): circ.swap(a[i],a[i+1]) # Cyclically right-shifts a binary string "a" of length n, controlled by c. # If "a" is zero-padded, equivalent to dividing "a" by 2, if and only if c. def c_rshift(circ, c, a, n=-1): # Init n if it was not if n == -1: n = len(a) # Iterate through pairs and do swaps. for i in range(n,1,-1): circ.cswap(c, a[i-1],a[i-2]) ################################################################################ # Addition Circuits ################################################################################ # Define some functions for the ripple adder. def sum(circ, cin, a, b): circ.cx(a,b) circ.cx(cin,b) def carry(circ, cin, a, b, cout): circ.ccx(a, b, cout) circ.cx(a, b) circ.ccx(cin, b, cout) def carry_dg(circ, cin, a, b, cout): circ.ccx(cin, b, cout) circ.cx(a, b) circ.ccx(a, b, cout) # Draper adder that takes |a>|b> to |a>|a+b>. # |a> has length x and is less than or equal to n # |b> has length n+1 (left padded with a zero). # https://arxiv.org/pdf/quant-ph/0008033.pdf def add(circ, a, b, n): # move n forward by one to account for overflow n += 1 # Take the QFT. qft(circ, b, n) # Compute controlled-phases. # Iterate through the targets. for i in range(n,0,-1): # Iterate through the controls. for j in range(i,0,-1): # If the qubit a[j-1] exists run cu1, if not assume the qubit is 0 and never existed if len(a) - 1 >= j - 1: circ.cu1(2*pi/2**(i-j+1), a[j-1], b[i-1]) # Take the inverse QFT. iqft(circ, b, n) # Draper adder that takes |a>|b> to |a>|a+b>, controlled on |c>. # |a> has length x and is less than or equal to n # |b> has length n+1 (left padded with a zero). # |c> is a single qubit that's the control. def cadd(circ, c, a, b, n): # move n forward by one to account for overflow n += 1 # Take the QFT. cqft(circ, c, b, n) # Compute controlled-phases. # Iterate through the targets. for i in range(n,0,-1): # Iterate through the controls. for j in range(i,0,-1): # If the qubit a[j-1] exists run ccu, if not assume the qubit is 0 and never existed if len(a) - 1 >= j - 1: ccu1(circ, 2*pi/2**(i-j+1), c, a[j-1], b[i-1]) # Take the inverse QFT. ciqft(circ, c, b, n) # Adder that takes |a>|b> to |a>|a+b>. # |a> has length n. # |b> has length n+1. # Based on Vedral, Barenco, and Ekert (1996). def add_ripple(circ, a, b, n): # Create a carry register of length n. c = QuantumRegister(n) circ.add_register(c) # Calculate all the carries except the last one. for i in range(0, n-1): carry(circ, c[i], a[i], b[i], c[i+1]) # The last carry bit is the leftmost bit of the sum. carry(circ, c[n-1], a[n-1], b[n-1], b[n]) # Calculate the second-to-leftmost bit of the sum. circ.cx(c[n-1],b[n-1]) # Invert the carries and calculate the remaining sums. for i in range(n-2,-1,-1): carry_dg(circ, c[i], a[i], b[i], c[i+1]) sum(circ, c[i], a[i], b[i]) # Adder that takes |a>|b>|0> to |a>|b>|a+b>. # |a> has length n. # |b> has length n. # |s> = |0> has length n+1. def add_ripple_ex(circ, a, b, s, n): # Copy b to s. for i in range(0, n): circ.cx(b[i],s[i]) # Add a and s. add_ripple(circ, a, s, n) ################################################################################ # Subtraction Circuits ################################################################################ # Subtractor that takes |a>|b> to |a>|a-b>. # |a> has length n+1 (left padded with a zero). # |b> has length n+1 (left padded with a zero). def sub(circ, a, b, n): # Flip the bits of a. circ.x(a) # Add it to b. add(circ, a, b, n - 1) # Flip the bits of the result. This yields the sum. circ.x(b) # Flip back the bits of a. circ.x(a) # Subtractor that takes |a>|b> to |a-b>|b>. # |a> has length n+1 (left padded with a zero). # |b> has length n+1 (left padded with a zero). def sub_swap(circ, a, b, n): # Flip the bits of a. circ.x(a) # Add it to b. add(circ, b, a, n - 1) # Flip the bits of the result. This yields the sum. circ.x(a) # Subtractor that takes |a>|b> to |a>|a-b>. # |a> has length n. # |b> has length n+1. def sub_ripple(circ, a, b, n): # We add "a" to the 2's complement of "b." # First flip the bits of "b." circ.x(b) # Create a carry register of length n. c = QuantumRegister(n) circ.add_register(c) # Add 1 to the carry register, which adds 1 to b, negating it. circ.x(c[0]) # Calculate all the carries except the last one. for i in range(0, n-1): carry(circ, c[i], a[i], b[i], c[i+1]) # The last carry bit is the leftmost bit of the sum. carry(circ, c[n-1], a[n-1], b[n-1], b[n]) # Calculate the second-to-leftmost bit of the sum. circ.cx(c[n-1],b[n-1]) # Invert the carries and calculate the remaining sums. for i in range(n-2,-1,-1): carry_dg(circ, c[i], a[i], b[i], c[i+1]) sum(circ, c[i], a[i], b[i]) # Flip the carry to restore it to zero. circ.x(c[0]) # Subtractor that takes |a>|b>|0> to |a>|b>|a-b>. # |a> has length n. # |b> has length n. # |s> = |0> has length n+1. def sub_ripple_ex(circ, a, b, s, n): # Copy b to s. for i in range(0, n): circ.cx(b[i],s[i]) # Subtract a and s. sub_ripple(circ, a, s, n) ################################################################################ # Multiplication Circuit ################################################################################ # Controlled operations # Take a subset of a quantum register from index x to y, inclusive. def sub_qr(qr, x, y): # may also be able to use qbit_argument_conversion sub = [] for i in range (x, y+1): sub = sub + [(qr[i])] return sub def full_qr(qr): return sub_qr(qr, 0, len(qr) - 1) # Computes the product c=a*b. # a has length n. # b has length n. # c has length 2n. def mult(circ, a, b, c, n): for i in range (0, n): cadd(circ, a[i], b, sub_qr(c, i, n+i), n) # Computes the product c=a*b if and only if control. # a has length n. # b has length n. # control has length 1. # c has length 2n. def cmult(circ, control, a, b, c, n): qa = QuantumRegister(len(a)) qb = QuantumRegister(len(b)) qc = QuantumRegister(len(c)) tempCircuit = QuantumCircuit(qa, qb, qc) mult(tempCircuit, qa, qb, qc, n) tempCircuit = tempCircuit.control(1) #Add Decomposition after pull request inclusion #5446 on terra print("Remember To Decompose after release >0.16.1") circ.compose(tempCircuit, qubits=full_qr(control) + full_qr(a) + full_qr(b) + full_qr(c), inplace=True) ################################################################################ # Division Circuit ################################################################################ # Divider that takes |p>|d>|q>. # |p> is length 2n and has n zeros on the left: 0 ... 0 p_n ... p_1. # |d> has length 2n and has n zeros on the right: d_2n ... d_{n+1) 0 ... 0. # |q> has length n and is initially all zeros. # At the end of the algorithm, |q> will contain the quotient of p/d, and the # left n qubits of |p> will contain the remainder of p/d. def div(circ, p, d, q, n): # Calculate each bit of the quotient and remainder. for i in range(n,0,-1): # Left shift |p>, which multiplies it by 2. lshift(circ, p, 2*n) # Subtract |d> from |p>. sub_swap(circ, p, d, 2*n) # If |p> is positive, indicated by its most significant bit being 0, # the (i-1)th bit of the quotient is 1. circ.x(p[2*n-1]) circ.cx(p[2*n-1], q[i-1]) circ.x(p[2*n-1]) # If |p> is negative, indicated by the (i-1)th bit of |q> being 0, add D back # to P. circ.x(q[i-1]) cadd(circ, q[i-1], d, p, 2*n - 1) circ.x(q[i-1]) ################################################################################ # Expontential Circuit ################################################################################ # square that takes |a> |b> # |a> is length n and is a unsigned integer # |b> is length 2n and has 2n zeros, after execution b = a^2 def square(circ, a, b, n=-1): if n == -1: n = len(a) # First Addition circ.cx(a[0], b[0]) for i in range(1, n): circ.ccx(a[0], a[i], b[i]) # Custom Addition Circuit For Each Qubit of A for k in range(1, n): # modifying qubits d = b[k:n+k+1] qft(circ, d, n+1) #Technically the first few QFT could be refactored to use less gates due to guaranteed controls # Compute controlled-phases. # Iterate through the targets. for i in range(n+1,0,-1): # Iterate through the controls. for j in range(i,0,-1): if len(a) - 1 < j - 1: pass # skip over non existent qubits elif k == j - 1: # Cannot control twice circ.cu1(2*pi/2**(i-j+1), a[j-1], d[i-1]) else: ccu1(circ, 2*pi/2**(i-j+1), a[k], a[j-1], d[i-1]) iqft(circ, d, n+1) # a has length n # b has length v # finalOut has length n*((2^v)-1), for safety def power(circ, a, b, finalOut): #Because this is reversible/gate friendly memory blooms to say the least # Track Number of Qubits n = len(a) v = len(b) # Left 0 pad a, to satisfy multiplication function arguments aPad = AncillaRegister(n * (pow(2, v) - 3)) # Unsure of where to Anciallas these circ.add_register(aPad) padAList = full_qr(aPad) aList = full_qr(a) a = aList + padAList # Create a register d for mults and init with state 1 d = AncillaRegister(n) # Unsure of where to Anciallas these circ.add_register(d) # Create a register for tracking the output of cmult to the end ancOut = AncillaRegister(n*2) # Unsure of where to Anciallas these circ.add_register(ancOut) # Left 0 pad finalOut to provide safety to the final multiplication if (len(a) * 2) - len(finalOut) > 0: foPad = AncillaRegister((len(a) * 2) - len(finalOut)) circ.add_register(foPad) padFoList = full_qr(foPad) foList = full_qr(finalOut) finalOut = foList + padFoList # Create zero bits num_recycle = (2 * n * (pow(2, v) - 2)) - (n * pow(2, v)) # 24 permaZeros = [] if num_recycle > 0: permaZeros = AncillaRegister(num_recycle) #8 circ.add_register(permaZeros) permaZeros = full_qr(permaZeros) # Instead of MULT copy bits over if v >= 1: for i in range(n): circ.ccx(b[0], a[i], d[i]) circ.x(b[0]) circ.cx(b[0], d[0]) circ.x(b[0]) # iterate through every qubit of b for i in range(1,v): # for every bit of b for j in range(pow(2, i)): # run multiplication operation if and only if b is 1 bonus = permaZeros[:2*len(d) - len(ancOut)] cmult(circ, [b[i]], a[:len(d)], d, full_qr(ancOut) + bonus, len(d)) # if the multiplication was not run copy the qubits so they are not destroyed when creating new register circ.x(b[i]) for qub in range(0,len(d)): circ.ccx(b[i], d[qub], ancOut[qub]) circ.x(b[i]) # Move the output to the input for next function and double the qubit length d = ancOut if i == v - 1 and j == pow(2, i) - 2: # this is the second to last step send qubiits to output ancOut = finalOut elif not (i == v - 1 and j == pow(2, i) - 1): # if this is not the very last step # create a new output register of twice the length and register it ancOut = AncillaRegister(len(d) + n) # Should label permazero bits circ.add_register(ancOut)
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import add # Input N N = 4 a = QuantumRegister(N) b = QuantumRegister(N+1) ca = ClassicalRegister(N) cb = ClassicalRegister(N+1) qc = QuantumCircuit(a, b, ca, cb) # Input Superposition # a = 01110 qc.x(a[1]) qc.x(a[2]) qc.x(a[3]) # b = 01011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) add(qc, a, b, N) qc.measure(a, ca) qc.measure(b, cb) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import add_ripple # Input N N = 4 a = QuantumRegister(N) b = QuantumRegister(N+1) ca = ClassicalRegister(N) cb = ClassicalRegister(N+1) qc = QuantumCircuit(a, b, ca, cb) # Input Superposition # a = 1110 qc.x(a[1]) qc.x(a[2]) qc.x(a[3]) # b = 01011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) add_ripple(qc, a, b, N) qc.measure(a, ca) qc.measure(b, cb) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import add_ripple_ex # Input N N = 4 a = QuantumRegister(N) b = QuantumRegister(N) s = QuantumRegister(N+1) ca = ClassicalRegister(N) cb = ClassicalRegister(N) cs = ClassicalRegister(N+1) qc = QuantumCircuit(a, b, s, ca, cb, cs) # Input Superposition # a = 1110 qc.x(a[1]) qc.x(a[2]) qc.x(a[3]) # b = 1011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) add_ripple_ex(qc, a, b, s, N) qc.measure(a, ca) qc.measure(b, cb) qc.measure(s, cs) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import bitwise_and, bitwise_or, bitwise_xor, bitwise_not # Input N N = 4 a = QuantumRegister(N) b = QuantumRegister(N) c = QuantumRegister(N) ca = ClassicalRegister(N) cb = ClassicalRegister(N) cc = ClassicalRegister(N) qc = QuantumCircuit(a, b, c, ca, cb, cc) # Input Superposition # a = 1110 qc.x(a[1]) qc.x(a[3]) # b = 1011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) bitwise_not(qc, a, c, N) qc.measure(a, ca) qc.measure(b, cb) qc.measure(c, cc) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import cadd # Input N N = 4 a = QuantumRegister(N) b = QuantumRegister(N+1) c = QuantumRegister(1) ca = ClassicalRegister(N) cb = ClassicalRegister(N+1) cc = ClassicalRegister(1) qc = QuantumCircuit(a, b, c, ca, cb, cc) # Input Superposition # a = 01110 qc.x(a[1]) qc.x(a[2]) qc.x(a[3]) # b = 01011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) # c = 0 # qc.x(c) cadd(qc, c, a, b, N) qc.measure(a, ca) qc.measure(b, cb) qc.measure(c, cc) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import cmult # Input N N = 3 c = QuantumRegister(1) a = QuantumRegister(N) b = QuantumRegister(N) m = QuantumRegister(2*N) cm = ClassicalRegister(2*N) qc = QuantumCircuit(c, a, b, m, cm) # Input # a = 010 = 2 qc.x(a[1]) # b = 011 = 3 qc.x(b[0]) qc.x(b[1]) qc.x(c)# turns operation on cmult(qc, c, a, b, m, N) qc.measure(m, cm) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import div # Input n n = 2 p = QuantumRegister(2*n) d = QuantumRegister(2*n) q = QuantumRegister(n) cp = ClassicalRegister(2*n) cd = ClassicalRegister(2*n) cq = ClassicalRegister(n) qc = QuantumCircuit(p,d,q,cp,cd,cq) # Input Superposition # p = 0011 qc.x(p[0]) qc.x(p[1]) # d = 1000 qc.x(d[3]) div(qc, p, d, q, n) qc.measure(p, cp) qc.measure(d, cd) qc.measure(q, cq) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
""" This file allows to test the Multiplication blocks Ua. This blocks, when put together as explain in the report, do the exponentiation. The user can change N, n, a and the input state, to create the circuit: up_reg |+> ---------------------|----------------------- |+> | | | -------|--------- ------------ | | ------------ down_reg |x> ------------ | Mult | ------------ |(x*a) mod N> ------------ | | ------------ ----------------- Where |x> has n qubits and is the input state, the user can change it to whatever he wants This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import math import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT from qfunctions import cMULTmodN """ Function to properly get the final state, it prints it to user """ """ This is only possible in this way because the program uses the statevector_simulator """ def get_final(results, number_aux, number_up, number_down): i=0 """ Get total number of qubits to go through all possibilities """ total_number = number_aux + number_up + number_down max = pow(2,total_number) print('|aux>|top_register>|bottom_register>\n') while i<max: binary = bin(i)[2:].zfill(total_number) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ If the respective state is not zero, then print it and store the state of the register where the result we are looking for is. This works because that state is the same for every case where number !=0 """ if number!=0: print('|{0}>|{1}>|{2}>'.format(binary[0:number_aux],binary[number_aux:(number_aux+number_up)],binary[(number_aux+number_up):(total_number)]),number) if binary[number_aux:(number_aux+number_up)]=='1': store = binary[(number_aux+number_up):(total_number)] i=i+1 print(' ') return int(store, 2) """ Main program """ if __name__ == '__main__': """ Select number N to do modN""" N = int(input('Please insert integer number N: ')) print(' ') """ Get n value used in QFT, to know how many qubits are used """ n = math.ceil(math.log(N,2)) """ Select the value for 'a' """ a = int(input('Please insert integer number a: ')) print(' ') """ Please make sure the a and N are coprime""" if math.gcd(a,N)!=1: print('Please make sure the a and N are coprime. Exiting program.') exit() print('Total number of qubits used: {0}\n'.format(2*n+3)) print('Please check source file to change input quantum state. By default is |2>.\n') ts = time.time() """ Create quantum and classical registers """ aux = QuantumRegister(n+2) up_reg = QuantumRegister(1) down_reg = QuantumRegister(n) aux_classic = ClassicalRegister(n+2) up_classic = ClassicalRegister(1) down_classic = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(down_reg , up_reg , aux, down_classic, up_classic, aux_classic) """ Initialize with |+> to also check if the control is working""" circuit.h(up_reg[0]) """ Put the desired input state in the down quantum register. By default we put |2> """ circuit.x(down_reg[1]) """ Apply multiplication""" cMULTmodN(circuit, up_reg[0], down_reg, aux, int(a), N, n) """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ Show the final state after the multiplication """ after_exp = get_final(outputstate, n+2, 1, n) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('When control=1, value after exponentiation is in bottom quantum register: |{0}>'.format(after_exp))
https://github.com/hkhetawat/QArithmetic
hkhetawat
""" This file allows to test the various QFT implemented. The user must specify: 1) The number of qubits it wants the QFT to be implemented on 2) The kind of QFT want to implement, among the options: -> Normal QFT with SWAP gates at the end -> Normal QFT without SWAP gates at the end -> Inverse QFT with SWAP gates at the end -> Inverse QFT without SWAP gates at the end The user must can also specify, in the main function, the input quantum state. By default is a maximal superposition state This file uses as simulator the local simulator 'statevector_simulator' because this simulator saves the quantum state at the end of the circuit, which is exactly the goal of the test file. This simulator supports sufficient qubits to the size of the QFTs that are going to be used in Shor's Algorithm because the IBM simulator only supports up to 32 qubits """ """ Imports from qiskit""" from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, IBMQ, BasicAer """ Imports to Python functions """ import time """ Local Imports """ from qfunctions import create_QFT, create_inverse_QFT """ Function to properly print the final state of the simulation """ """ This is only possible in this way because the program uses the statevector_simulator """ def show_good_coef(results, n): i=0 max = pow(2,n) if max > 100: max = 100 """ Iterate to all possible states """ while i<max: binary = bin(i)[2:].zfill(n) number = results.item(i) number = round(number.real, 3) + round(number.imag, 3) * 1j """ Print the respective component of the state if it has a non-zero coefficient """ if number!=0: print('|{}>'.format(binary),number) i=i+1 """ Main program """ if __name__ == '__main__': """ Select how many qubits want to apply the QFT on """ n = int(input('\nPlease select how many qubits want to apply the QFT on: ')) """ Select the kind of QFT to apply using the variable what_to_test: what_to_test = 0: Apply normal QFT with the SWAP gates at the end what_to_test = 1: Apply normal QFT without the SWAP gates at the end what_to_test = 2: Apply inverse QFT with the SWAP gates at the end what_to_test = 3: Apply inverse QFT without the SWAP gates at the end """ print('\nSelect the kind of QFT to apply:') print('Select 0 to apply normal QFT with the SWAP gates at the end') print('Select 1 to apply normal QFT without the SWAP gates at the end') print('Select 2 to apply inverse QFT with the SWAP gates at the end') print('Select 3 to apply inverse QFT without the SWAP gates at the end\n') what_to_test = int(input('Select your option: ')) if what_to_test<0 or what_to_test>3: print('Please select one of the options') exit() print('\nTotal number of qubits used: {0}\n'.format(n)) print('Please check source file to change input quantum state. By default is a maximal superposition state with |+> in every qubit.\n') ts = time.time() """ Create quantum and classical registers """ quantum_reg = QuantumRegister(n) classic_reg = ClassicalRegister(n) """ Create Quantum Circuit """ circuit = QuantumCircuit(quantum_reg, classic_reg) """ Create the input state desired Please change this as you like, by default we put H gates in every qubit, initializing with a maximimal superposition state """ #circuit.h(quantum_reg) """ Test the right QFT according to the variable specified before""" if what_to_test == 0: create_QFT(circuit,quantum_reg,n,1) elif what_to_test == 1: create_QFT(circuit,quantum_reg,n,0) elif what_to_test == 2: create_inverse_QFT(circuit,quantum_reg,n,1) elif what_to_test == 3: create_inverse_QFT(circuit,quantum_reg,n,0) else: print('Noting to implement, exiting program') exit() """ show results of circuit creation """ create_time = round(time.time()-ts, 3) if n < 8: print(circuit) print(f"... circuit creation time = {create_time}") ts = time.time() """ Simulate the created Quantum Circuit """ simulation = execute(circuit, backend=BasicAer.get_backend('statevector_simulator'),shots=1) """ Get the results of the simulation in proper structure """ sim_result=simulation.result() """ Get the statevector of the final quantum state """ outputstate = sim_result.get_statevector(circuit, decimals=3) """ show execution time """ exec_time = round(time.time()-ts, 3) print(f"... circuit execute time = {exec_time}") """ Print final quantum state to user """ print('The final state after applying the QFT is:\n') show_good_coef(outputstate,n)
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from numpy.lib.function_base import copy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from qiskit.providers.aer import QasmSimulator from QArithmetic import full_qr, power from copy import copy from qiskit.tools.visualization import circuit_drawer # Input N N = 2 X = 2 # qc will take exponentially longer to compile with each increase a = QuantumRegister(N) b = QuantumRegister(X) m = QuantumRegister(N*(pow(2,X)-1)) ca = ClassicalRegister(N) cm = ClassicalRegister(N*(pow(2,X)-1)) qc = QuantumCircuit(a, b, m, cm, ca) # Input # a = 11 = 3 qc.x(a[0]) qc.x(a[1]) # b= 11 = 3 qc.x(b[0]) qc.x(b[1]) power(qc, a, b, m) qc.measure(m, cm) qc.measure(a, ca) backend_sim = Aer.get_backend('qasm_simulator') print("started job") job_sim = execute(qc, backend_sim, shots=1) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import lshift, rshift # Input N n = 5 a = QuantumRegister(n) b = QuantumRegister(n) ca = ClassicalRegister(n) cb = ClassicalRegister(n) qc = QuantumCircuit(a, b, ca, cb) # Input Superposition # a = 11010 qc.x(a[1]) qc.x(a[3]) qc.x(a[4]) # b = 00011 qc.x(b[0]) qc.x(b[1]) # Left-shift |a>. lshift(qc, a, n) lshift(qc, a, n) qc.measure(a, ca) # Right-shift |b>. rshift(qc, b, n) rshift(qc, b, n) qc.measure(b, cb) # Simulate the circuit. backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import square # Input N N = 3 a = QuantumRegister(N) b = QuantumRegister(2*N) cb = ClassicalRegister(2*N) qc = QuantumCircuit(a, b, cb) # Input # a = 111 = 7 qc.x(a[0]) qc.x(a[1]) qc.x(a[2]) square(qc, a, b) qc.measure(b, cb) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import sub # Input N N = 4 a = QuantumRegister(N+1) b = QuantumRegister(N+1) ca = ClassicalRegister(N+1) cb = ClassicalRegister(N+1) qc = QuantumCircuit(a, b, ca, cb) # Input Superposition # a = 01110 qc.x(a[1]) qc.x(a[2]) qc.x(a[3]) # b = 01011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) sub(qc, a, b, N+1) qc.measure(a, ca) qc.measure(b, cb) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import sub_ripple # Input N N = 4 a = QuantumRegister(N) b = QuantumRegister(N+1) ca = ClassicalRegister(N) cb = ClassicalRegister(N+1) qc = QuantumCircuit(a, b, ca, cb) # Input Superposition # a = 1110 qc.x(a[1]) qc.x(a[2]) qc.x(a[3]) # b = 01011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) sub_ripple(qc, a, b, N) qc.measure(a, ca) qc.measure(b, cb) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import sub_ripple_ex # Input N N = 4 a = QuantumRegister(N) b = QuantumRegister(N) s = QuantumRegister(N+1) ca = ClassicalRegister(N) cb = ClassicalRegister(N) cs = ClassicalRegister(N+1) qc = QuantumCircuit(a, b, s, ca, cb, cs) # Input Superposition # a = 1110 qc.x(a[1]) qc.x(a[2]) qc.x(a[3]) # b = 1011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) sub_ripple_ex(qc, a, b, s, N) qc.measure(a, ca) qc.measure(b, cb) qc.measure(s, cs) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import sub_swap # Input N N = 4 a = QuantumRegister(N+1) b = QuantumRegister(N+1) ca = ClassicalRegister(N+1) cb = ClassicalRegister(N+1) qc = QuantumCircuit(a, b, ca, cb) # Input Superposition # a = 01110 qc.x(a[1]) qc.x(a[2]) qc.x(a[3]) # b = 01011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) sub_swap(qc, a, b, N+1) qc.measure(a, ca) qc.measure(b, cb) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
Alice-Bob-SW
from qiskit import Aer, IBMQ, execute from qiskit import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram, plot_state_city """ Qiskit backends to execute the quantum circuit """ def simulator(qc): """ Run on local simulator :param qc: quantum circuit :return: """ backend = Aer.get_backend("qasm_simulator") shots = 2048 tqc = transpile(qc, backend) qobj = assemble(tqc, shots=shots) job_sim = backend.run(qobj) qc_results = job_sim.result() return qc_results, shots def simulator_state_vector(qc): """ Select the StatevectorSimulator from the Aer provider :param qc: quantum circuit :return: statevector """ simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qc, simulator).result() state_vector = result.get_statevector(qc) return state_vector def real_quantum_device(qc): """ Use the IBMQ essex device :param qc: quantum circuit :return: """ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_santiago') shots = 2048 TQC = transpile(qc, backend) qobj = assemble(TQC, shots=shots) job_exp = backend.run(qobj) job_monitor(job_exp) QC_results = job_exp.result() return QC_results, shots def counts(qc_results): """ Get counts representing the wave-function amplitudes :param qc_results: :return: dict keys are bit_strings and their counting values """ return qc_results.get_counts() def plot_results(qc_results): """ Visualizing wave-function amplitudes in a histogram :param qc_results: quantum circuit :return: """ plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False)) def plot_state_vector(state_vector): """Visualizing state vector in the density matrix representation""" plt.show(plot_state_city(state_vector))
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
Alice-Bob-SW
''' qiskitpool/job.py Contains the QJob class ''' from functools import partial from qiskit import execute class QJob(): ''' QJob Job manager for asynch qiskit backends ''' def __init__(self, *args, qjob_id=None, **kwargs): ''' QJob.__init__ Initialiser for a qiksit job :: *args :: Args for qiskit execute :: **kwargs :: Kwargs for qiskit execute ''' self.job_fn = partial(execute, *args, **kwargs) self.job = None self.done = False self.test_count = 10 self.qjob_id = qjob_id def __call__(self): ''' QJob.__call__ Wrapper for QJob.run ''' return self.run() def run(self): ''' QJob.run Send async job to qiskit backend ''' self.job = self.job_fn() return self def poll(self): ''' QJob.poll Poll qiskit backend for job completion status ''' if self.job is not None: return self.job.done() return False def cancel(self): ''' QJob.cancel Cancel job on backend ''' if self.job is None: return None return self.job.cancel() def position(self): pos = self.job.queue_position() if pos is None: return 0 return pos def status(self): if self.job is None: return 'LOCAL QUEUE' else: status = self.job.status().value if 'running' in status: return 'RUNNING' if 'run' in status: return 'COMPLETE' if 'validated' in status: return 'VALIDATING' if 'queued' in status: pos = self.position() return f'QISKIT QUEUE: {self.position()}' def status_short(self): if self.job is None: return ' ' else: status = self.job.status().value if 'running' in status: return 'R' if 'run' in status: return 'C' if 'validated' in status: return 'V' if 'queued' in status: return str(self.position()) def result(self): ''' QJob.result Get result from backend Non blocking - returns False if a job is not yet ready ''' if self.poll(): return self.job.result() return False
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
Alice-Bob-SW
from qiskit import Aer, IBMQ, execute from qiskit import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram, plot_state_city """ Qiskit backends to execute the quantum circuit """ def simulator(qc): """ Run on local simulator :param qc: quantum circuit :return: """ backend = Aer.get_backend("qasm_simulator") shots = 2048 tqc = transpile(qc, backend) qobj = assemble(tqc, shots=shots) job_sim = backend.run(qobj) qc_results = job_sim.result() return qc_results, shots def simulator_state_vector(qc): """ Select the StatevectorSimulator from the Aer provider :param qc: quantum circuit :return: statevector """ simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qc, simulator).result() state_vector = result.get_statevector(qc) return state_vector def real_quantum_device(qc): """ Use the IBMQ essex device :param qc: quantum circuit :return: """ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_santiago') shots = 2048 TQC = transpile(qc, backend) qobj = assemble(TQC, shots=shots) job_exp = backend.run(qobj) job_monitor(job_exp) QC_results = job_exp.result() return QC_results, shots def counts(qc_results): """ Get counts representing the wave-function amplitudes :param qc_results: :return: dict keys are bit_strings and their counting values """ return qc_results.get_counts() def plot_results(qc_results): """ Visualizing wave-function amplitudes in a histogram :param qc_results: quantum circuit :return: """ plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False)) def plot_state_vector(state_vector): """Visualizing state vector in the density matrix representation""" plt.show(plot_state_city(state_vector))