repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/Qiskit/qiskit-transpiler-service
Qiskit
# -*- coding: utf-8 -*- # (C) Copyright 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Unit-testing linear_function_collection""" from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit_transpiler_service.ai.collection import CollectPermutations def test_permutation_collection_pass(random_circuit_transpiled): collect = PassManager( [ CollectPermutations(), ] ) collected_circuit = collect.run(random_circuit_transpiled) assert isinstance(collected_circuit, QuantumCircuit) def test_permutation_collection_pass_collect(swap_circ): collect = PassManager( [ CollectPermutations(min_block_size=1, max_block_size=5), ] ) collected_circuit = collect.run(swap_circ) assert isinstance(collected_circuit, QuantumCircuit) assert any(g.operation.name.lower() == "permutation" for g in collected_circuit) def test_permutation_collection_pass_no_collect(rzz_circ): collect = PassManager( [ CollectPermutations(min_block_size=7, max_block_size=12), ] ) collected_circuit = collect.run(rzz_circ) assert all(g.operation.name.lower() != "permutation" for g in collected_circuit) def test_permutation_collection_max_block_size(swap_circ): collect = PassManager( [ CollectPermutations(max_block_size=7), ] ) collected_circuit = collect.run(swap_circ) assert all(len(g.qubits) <= 7 for g in collected_circuit) def test_permutation_collection_min_block_size(swap_circ): collect = PassManager( [ CollectPermutations(min_block_size=7, max_block_size=12), ] ) collected_circuit = collect.run(swap_circ) assert all( len(g.qubits) >= 7 or g.operation.name.lower() != "permutation" for g in collected_circuit )
https://github.com/Qiskit/qiskit-transpiler-service
Qiskit
# -*- coding: utf-8 -*- # (C) Copyright 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Unit-testing routing_ai""" import pytest from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.exceptions import TranspilerError from qiskit_transpiler_service.ai.routing import AIRouting @pytest.mark.parametrize("layout_mode", ["KEEP", "OPTIMIZE", "IMPROVE"]) @pytest.mark.parametrize("optimization_level", [1, 2, 3]) def test_qv_routing(optimization_level, layout_mode, backend, qv_circ): pm = PassManager( [ AIRouting( optimization_level=optimization_level, layout_mode=layout_mode, backend_name=backend, ) ] ) circuit = pm.run(qv_circ) assert isinstance(circuit, QuantumCircuit) @pytest.mark.parametrize("optimization_level", [0, 4, 5]) def test_qv_routing_wrong_opt_level(optimization_level, backend, qv_circ): pm = PassManager( [AIRouting(optimization_level=optimization_level, backend_name=backend)] ) with pytest.raises(TranspilerError): pm.run(qv_circ) @pytest.mark.parametrize("layout_mode", ["RECREATE", "BOOST"]) def test_qv_routing_wrong_layout_mode(layout_mode, backend, qv_circ): with pytest.raises(ValueError): PassManager([AIRouting(layout_mode=layout_mode, backend_name=backend)])
https://github.com/QPong/qpong-livestream
QPong
import numpy as np import pygame import qiskit from . import globals, resources, node_types GRID_WIDTH = 66 GRID_HEIGHT = 66 GATE_TILE_WIDTH = 43 GATE_TILE_HEIGHT = 45 LINE_WIDTH = 1 # navigation MOVE_LEFT = 1 MOVE_RIGHT = 2 MOVE_UP = 3 MOVE_DOWN = 4 class CircuitGrid(pygame.sprite.RenderPlain): """Enables interaction with circuit""" def __init__(self, xpos, ypos): self.xpos = xpos self.ypos = ypos self.selected_wire = 0 self.selected_column = 0 self.model = CircuitGridModel(globals.NUM_QUBITS,16) self.circuit_grid_background = CircuitGridBackground(self.model) self.circuit_grid_cursor = CircuitGridCursor() self.gate_tiles = np.empty((self.model.max_wires, self.model.max_columns), dtype = CircuitGridGate) for row_idx in range(self.model.max_wires): for col_idx in range(self.model.max_columns): self.gate_tiles[row_idx][col_idx] = \ CircuitGridGate(self.model, row_idx, col_idx) pygame.sprite.RenderPlain.__init__(self, self.circuit_grid_background, self.gate_tiles, self.circuit_grid_cursor) self.update() def update(self, *args): sprite_list = self.sprites() for sprite in sprite_list: sprite.update() self.circuit_grid_background.rect.left = self.xpos self.circuit_grid_background.rect.top = self.ypos for row_idx in range(self.model.max_wires): for col_idx in range(self.model.max_columns): self.gate_tiles[row_idx][col_idx].rect.centerx = \ self.xpos + GRID_WIDTH * (col_idx + 1.5) self.gate_tiles[row_idx][col_idx].rect.centery = \ self.ypos + GRID_HEIGHT * (row_idx + 1.0) self.highlight_selected_node(self.selected_wire, self.selected_column) def highlight_selected_node(self, wire_num, column_num): self.selected_wire = wire_num self.selected_column = column_num self.circuit_grid_cursor.rect.left = self.xpos + GRID_WIDTH * (self.selected_column + 1) self.circuit_grid_cursor.rect.top = self.ypos + GRID_HEIGHT * (self.selected_wire + 0.5) def move_to_adjacent_node(self, direction): if direction == MOVE_LEFT and self.selected_column > 0: self.selected_column -= 1 elif direction == MOVE_RIGHT and self.selected_column < self.model.max_columns - 1: self.selected_column += 1 elif direction == MOVE_UP and self.selected_wire > 0: self.selected_wire -= 1 elif direction == MOVE_DOWN and self.selected_wire < self.model.max_wires - 1: self.selected_wire += 1 self.highlight_selected_node(self.selected_wire, self.selected_column) def get_selected_node_gate_part(self): return self.model.get_node_gate_part(self.selected_wire, self.selected_column) def handle_input(self, key): match (key): case pygame.K_a: self.move_to_adjacent_node(MOVE_LEFT), case pygame.K_d: self.move_to_adjacent_node(MOVE_RIGHT), case pygame.K_w: self.move_to_adjacent_node(MOVE_UP), case pygame.K_s: self.move_to_adjacent_node(MOVE_DOWN), case pygame.K_x: self.handle_input_x(), case pygame.K_y: self.handle_input_y(), case pygame.K_z: self.handle_input_z(), case pygame.K_h: self.handle_input_h(), case pygame.K_SPACE: self.handle_input_delete(), case pygame.K_c: self.handle_input_ctrl(), case pygame.K_UP: self.handle_input_move_ctrl(MOVE_UP), case pygame.K_DOWN: self.handle_input_move_ctrl(MOVE_DOWN), case pygame.K_LEFT: self.handle_input_rotate(-np.pi / 8), case pygame.K_RIGHT: self.handle_input_rotate(np.pi / 8) def handle_input_x(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.EMPTY: circuit_grid_node = CircuitGridNode(node_types.X) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def handle_input_y(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.EMPTY: circuit_grid_node = CircuitGridNode(node_types.Y) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def handle_input_z(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.EMPTY: circuit_grid_node = CircuitGridNode(node_types.Z) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def handle_input_h(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.EMPTY: circuit_grid_node = CircuitGridNode(node_types.H) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def handle_input_delete(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.X or \ selected_node_gate_part == node_types.Y or \ selected_node_gate_part == node_types.Z or \ selected_node_gate_part == node_types.H: self.delete_controls_for_gate(self.selected_wire, self.selected_column) if selected_node_gate_part == node_types.CTRL: gate_wire_num = \ self.model.get_gate_wire_for_control_node(self.selected_wire, self.selected_column) if gate_wire_num >= 0: self.delete_controls_for_gate(gate_wire_num, self.selected_column) elif selected_node_gate_part != node_types.SWAP and \ selected_node_gate_part != node_types.CTRL and \ selected_node_gate_part != node_types.TRACE: circuit_grid_node = CircuitGridNode(node_types.EMPTY) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def handle_input_ctrl(self): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.X or \ selected_node_gate_part == node_types.Y or \ selected_node_gate_part == node_types.Z or \ selected_node_gate_part == node_types.H: circuit_grid_node = self.model.get_node(self.selected_wire, self.selected_column) if circuit_grid_node.ctrl_a >= 0: # Gate already has a control qubit so remove it orig_ctrl_a = circuit_grid_node.ctrl_a circuit_grid_node.ctrl_a = -1 self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) # Remove TRACE nodes for wire_num in range(min(self.selected_wire, orig_ctrl_a) + 1, max(self.selected_wire, orig_ctrl_a)): if self.model.get_node_gate_part(wire_num, self.selected_column) == node_types.TRACE: self.model.set_node(wire_num, self.selected_column, CircuitGridNode(node_types.EMPTY)) self.update() else: # Attempt to place a control qubit beginning with the wire above if self.selected_wire >= 0: if self.place_ctrl_qubit(self.selected_wire, self.selected_wire - 1) == -1: if self.selected_wire < self.model.max_wires: if self.place_ctrl_qubit(self.selected_wire, self.selected_wire + 1) == -1: print("Can't place control qubit") self.display_exceptional_condition() def handle_input_move_ctrl(self, direction): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.X or \ selected_node_gate_part == node_types.Y or \ selected_node_gate_part == node_types.Z or \ selected_node_gate_part == node_types.H: circuit_grid_node = self.model.get_node(self.selected_wire, self.selected_column) if 0 <= circuit_grid_node.ctrl_a < self.model.max_wires: # Gate already has a control qubit so try to move it if direction == MOVE_UP: candidate_wire_num = circuit_grid_node.ctrl_a - 1 if candidate_wire_num == self.selected_wire: candidate_wire_num -= 1 else: candidate_wire_num = circuit_grid_node.ctrl_a + 1 if candidate_wire_num == self.selected_wire: candidate_wire_num += 1 if 0 <= candidate_wire_num < self.model.max_wires: if self.place_ctrl_qubit(self.selected_wire, candidate_wire_num) == candidate_wire_num: print("control qubit successfully placed on wire ", candidate_wire_num) if direction == MOVE_UP and candidate_wire_num < self.selected_wire: if self.model.get_node_gate_part(candidate_wire_num + 1, self.selected_column) == node_types.EMPTY: self.model.set_node(candidate_wire_num + 1, self.selected_column, CircuitGridNode(node_types.TRACE)) elif direction == MOVE_DOWN and candidate_wire_num > self.selected_wire: if self.model.get_node_gate_part(candidate_wire_num - 1, self.selected_column) == node_types.EMPTY: self.model.set_node(candidate_wire_num - 1, self.selected_column, CircuitGridNode(node_types.TRACE)) self.update() else: print("control qubit could not be placed on wire ", candidate_wire_num) def handle_input_rotate(self, radians): selected_node_gate_part = self.get_selected_node_gate_part() if selected_node_gate_part == node_types.X or \ selected_node_gate_part == node_types.Y or \ selected_node_gate_part == node_types.Z: circuit_grid_node = self.model.get_node(self.selected_wire, self.selected_column) circuit_grid_node.radians = (circuit_grid_node.radians + radians) % (2 * np.pi) self.model.set_node(self.selected_wire, self.selected_column, circuit_grid_node) self.update() def place_ctrl_qubit(self, gate_wire_num, candidate_ctrl_wire_num): """Attempt to place a control qubit on a wire. If successful, return the wire number. If not, return -1 """ if candidate_ctrl_wire_num < 0 or candidate_ctrl_wire_num >= self.model.max_wires: return -1 candidate_wire_gate_part = \ self.model.get_node_gate_part(candidate_ctrl_wire_num, self.selected_column) if candidate_wire_gate_part == node_types.EMPTY or \ candidate_wire_gate_part == node_types.TRACE: circuit_grid_node = self.model.get_node(gate_wire_num, self.selected_column) circuit_grid_node.ctrl_a = candidate_ctrl_wire_num self.model.set_node(gate_wire_num, self.selected_column, circuit_grid_node) self.model.set_node(candidate_ctrl_wire_num, self.selected_column, CircuitGridNode(node_types.EMPTY)) self.update() return candidate_ctrl_wire_num else: print("Can't place control qubit on wire: ", candidate_ctrl_wire_num) return -1 def delete_controls_for_gate(self, gate_wire_num, column_num): control_a_wire_num = self.model.get_node(gate_wire_num, column_num).ctrl_a control_b_wire_num = self.model.get_node(gate_wire_num, column_num).ctrl_b # Choose the control wire (if any exist) furthest away from the gate wire control_a_wire_distance = 0 control_b_wire_distance = 0 if control_a_wire_num >= 0: control_a_wire_distance = abs(control_a_wire_num - gate_wire_num) if control_b_wire_num >= 0: control_b_wire_distance = abs(control_b_wire_num - gate_wire_num) control_wire_num = -1 if control_a_wire_distance > control_b_wire_distance: control_wire_num = control_a_wire_num elif control_a_wire_distance < control_b_wire_distance: control_wire_num = control_b_wire_num if control_wire_num >= 0: for wire_idx in range(min(gate_wire_num, control_wire_num), max(gate_wire_num, control_wire_num) + 1): print("Replacing wire ", wire_idx, " in column ", column_num) circuit_grid_node = CircuitGridNode(node_types.EMPTY) self.model.set_node(wire_idx, column_num, circuit_grid_node) class CircuitGridBackground(pygame.sprite.Sprite): """Background for circuit grid""" def __init__(self, circuit_grid_model): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([GRID_WIDTH * (circuit_grid_model.max_columns + 2), GRID_HEIGHT * (circuit_grid_model.max_wires + 1)]) self.image.convert() self.image.fill(globals.WHITE) self.rect = self.image.get_rect() pygame.draw.rect(self.image, globals.BLACK, self.rect, LINE_WIDTH) for wire_num in range(circuit_grid_model.max_wires): pygame.draw.line(self.image, globals.BLACK, (GRID_WIDTH * 0.5, (wire_num + 1) * GRID_HEIGHT), (self.rect.width - (GRID_WIDTH * 0.5), (wire_num + 1) * GRID_HEIGHT), LINE_WIDTH) class CircuitGridGate(pygame.sprite.Sprite): """Images for nodes""" def __init__(self, circuit_grid_model, wire_num, column_num): pygame.sprite.Sprite.__init__(self) self.circuit_grid_model = circuit_grid_model self.wire_num = wire_num self.column_num = column_num self.update() def update(self): node_type = self.circuit_grid_model.get_node_gate_part(self.wire_num, self.column_num) if node_type == node_types.H: self.image, self.rect = resources.load_image('gates/h_gate.png', -1) elif node_type == node_types.X: node = self.circuit_grid_model.get_node(self.wire_num, self.column_num) if node.ctrl_a >= 0 or node.ctrl_b >= 0: if self.wire_num > max(node.ctrl_a, node.ctrl_b): self.image, self.rect = resources.load_image('gates/not_gate_below_ctrl.png', -1) else: self.image, self.rect = resources.load_image('gates/not_gate_above_ctrl.png', -1) elif node.radians != 0: self.image, self.rect = resources.load_image('gates/rx_gate.png', -1) self.rect = self.image.get_rect() pygame.draw.arc(self.image, globals.MAGENTA, self.rect, 0, node.radians % (2 * np.pi), 6) pygame.draw.arc(self.image, globals.MAGENTA, self.rect, node.radians % (2 * np.pi), 2 * np.pi, 1) else: self.image, self.rect = resources.load_image('gates/x_gate.png', -1) elif node_type == node_types.Y: node = self.circuit_grid_model.get_node(self.wire_num, self.column_num) if node.radians != 0: self.image, self.rect = resources.load_image('gates/ry_gate.png', -1) self.rect = self.image.get_rect() pygame.draw.arc(self.image, globals.MAGENTA, self.rect, 0, node.radians % (2 * np.pi), 6) pygame.draw.arc(self.image, globals.MAGENTA, self.rect, node.radians % (2 * np.pi), 2 * np.pi, 1) else: self.image, self.rect = resources.load_image('gates/y_gate.png', -1) elif node_type == node_types.Z: node = self.circuit_grid_model.get_node(self.wire_num, self.column_num) if node.radians != 0: self.image, self.rect = resources.load_image('gates/rz_gate.png', -1) self.rect = self.image.get_rect() pygame.draw.arc(self.image, globals.MAGENTA, self.rect, 0, node.radians % (2 * np.pi), 6) pygame.draw.arc(self.image, globals.MAGENTA, self.rect, node.radians % (2 * np.pi), 2 * np.pi, 1) else: self.image, self.rect = resources.load_image('gates/z_gate.png', -1) elif node_type == node_types.S: self.image, self.rect = resources.load_image('gates/s_gate.png', -1) elif node_type == node_types.SDG: self.image, self.rect = resources.load_image('gates/sdg_gate.png', -1) elif node_type == node_types.T: self.image, self.rect = resources.load_image('gates/t_gate.png', -1) elif node_type == node_types.TDG: self.image, self.rect = resources.load_image('gates/tdg_gate.png', -1) elif node_type == node_types.IDEN: self.image, self.rect = resources.load_image('gates/iden_gate.png', -1) elif node_type == node_types.CTRL: if self.wire_num > \ self.circuit_grid_model.get_gate_wire_for_control_node(self.wire_num, self.column_num): self.image, self.rect = resources.load_image('gates/ctrl_gate_bottom_wire.png', -1) else: self.image, self.rect = resources.load_image('gates/ctrl_gate_top_wire.png', -1) elif node_type == node_types.TRACE: self.image, self.rect = resources.load_image('gates/trace_gate.png', -1) elif node_type == node_types.SWAP: self.image, self.rect = resources.load_image('gates/swap_gate.png', -1) else: self.image = pygame.Surface([GATE_TILE_WIDTH, GATE_TILE_HEIGHT]) self.image.set_alpha(0) self.rect = self.image.get_rect() self.image.convert() class CircuitGridCursor(pygame.sprite.Sprite): """Cursor to highlight current grid node""" def __init__(self): pygame.sprite.Sprite.__init__(self) self.image, self.rect = resources.load_image('circuit-grid-cursor.png') self.image.convert_alpha() class CircuitGridModel(): """Grid-based model that is built when user interacts with circuit""" def __init__(self, max_wires, max_columns): self.max_wires = max_wires self.max_columns = max_columns self.nodes = np.empty((max_wires, max_columns), dtype = CircuitGridNode) def __str__(self): retval = '' for wire_num in range(self.max_wires): retval += '\n' for column_num in range(self.max_columns): retval += str(self.get_node_gate_part(wire_num, column_num)) + ', ' return 'CircuitGridModel: ' + retval def set_node(self, wire_num, column_num, circuit_grid_node): self.nodes[wire_num][column_num] = \ CircuitGridNode(circuit_grid_node.node_type, circuit_grid_node.radians, circuit_grid_node.ctrl_a, circuit_grid_node.ctrl_b, circuit_grid_node.swap) def get_node(self, wire_num, column_num): return self.nodes[wire_num][column_num] def get_node_gate_part(self, wire_num, column_num): requested_node = self.nodes[wire_num][column_num] if requested_node and requested_node.node_type != node_types.EMPTY: # Node is occupied so return its gate return requested_node.node_type else: # Check for control nodes from gates in other nodes in this column nodes_in_column = self.nodes[:, column_num] for idx in range(self.max_wires): if idx != wire_num: other_node = nodes_in_column[idx] if other_node: if other_node.ctrl_a == wire_num or other_node.ctrl_b == wire_num: return node_types.CTRL elif other_node.swap == wire_num: return node_types.SWAP return node_types.EMPTY def get_gate_wire_for_control_node(self, control_wire_num, column_num): """Get wire for gate that belongs to a control node on the given wire""" gate_wire_num = -1 nodes_in_column = self.nodes[:, column_num] for wire_idx in range(self.max_wires): if wire_idx != control_wire_num: other_node = nodes_in_column[wire_idx] if other_node: if other_node.ctrl_a == control_wire_num or \ other_node.ctrl_b == control_wire_num: gate_wire_num = wire_idx print("Found gate: ", self.get_node_gate_part(gate_wire_num, column_num), " on wire: " , gate_wire_num) return gate_wire_num def compute_circuit(self): qr = qiskit.QuantumRegister(self.max_wires, 'q') qc = qiskit.QuantumCircuit(qr) for column_num in range(self.max_columns): for wire_num in range(self.max_wires): node = self.nodes[wire_num][column_num] if node: if node.node_type == node_types.IDEN: # Identity gate qc.i(qr[wire_num]) elif node.node_type == node_types.X: if node.radians == 0: if node.ctrl_a != -1: if node.ctrl_b != -1: # Toffoli gate qc.ccx(qr[node.ctrl_a], qr[node.ctrl_b], qr[wire_num]) else: # Controlled X gate qc.cx(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-X gate qc.x(qr[wire_num]) else: # Rotation around X axis qc.rx(node.radians, qr[wire_num]) elif node.node_type == node_types.Y: if node.radians == 0: if node.ctrl_a != -1: # Controlled Y gate qc.cy(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Y gate qc.y(qr[wire_num]) else: # Rotation around Y axis qc.ry(node.radians, qr[wire_num]) elif node.node_type == node_types.Z: if node.radians == 0: if node.ctrl_a != -1: # Controlled Z gate qc.cz(qr[node.ctrl_a], qr[wire_num]) else: # Pauli-Z gate qc.z(qr[wire_num]) else: if node.ctrl_a != -1: # Controlled rotation around the Z axis qc.crz(node.radians, qr[node.ctrl_a], qr[wire_num]) else: # Rotation around Z axis qc.rz(node.radians, qr[wire_num]) elif node.node_type == node_types.S: # S gate qc.s(qr[wire_num]) elif node.node_type == node_types.SDG: # S dagger gate qc.sdg(qr[wire_num]) elif node.node_type == node_types.T: # T gate qc.t(qr[wire_num]) elif node.node_type == node_types.TDG: # T dagger gate qc.tdg(qr[wire_num]) elif node.node_type == node_types.H: if node.ctrl_a != -1: # Controlled Hadamard qc.ch(qr[node.ctrl_a], qr[wire_num]) else: # Hadamard gate qc.h(qr[wire_num]) elif node.node_type == node_types.SWAP: if node.ctrl_a != -1: # Controlled Swap qc.cswap(qr[node.ctrl_a], qr[wire_num], qr[node.swap]) else: # Swap gate qc.swap(qr[wire_num], qr[node.swap]) return qc class CircuitGridNode(): """Represents a node in the circuit grid""" def __init__(self, node_type, radians=0.0, ctrl_a=-1, ctrl_b=-1, swap=-1): self.node_type = node_type self.radians = radians self.ctrl_a = ctrl_a self.ctrl_b = ctrl_b self.swap = swap def __str__(self): string = 'type: ' + str(self.node_type) string += ', radians: ' + str(self.radians) if self.radians != 0 else '' string += ', ctrl_a: ' + str(self.ctrl_a) if self.ctrl_a != -1 else '' string += ', ctrl_b: ' + str(self.ctrl_b) if self.ctrl_b != -1 else '' return string
https://github.com/QPong/qpong-livestream
QPong
import pygame import qiskit from . import globals class Computer: def __init__(self): pass def update(self): pass class ClassicalComputer(Computer): def __init__(self, paddle): self.paddle = paddle self.score = 0 self.speed = 3 def update(self, ball): if self.paddle.rect.centery - ball.rect.centery > 0: self.paddle.rect.y -= self.speed else: self.paddle.rect.y += self.speed if pygame.sprite.collide_mask(ball, self.paddle): ball.bounce() class QuantumComputer(Computer): def __init__(self, quantum_paddles, circuit_grid) -> None: self.paddles = quantum_paddles.paddles self.score = 0 self.circuit_grid = circuit_grid self.measured_state = 0 self.last_measurement_time = pygame.time.get_ticks() - globals.MEASUREMENT_COOLDOWN_TIME def update(self, ball): current_time = pygame.time.get_ticks() # trigger measurement when the ball is close to quantum paddles if 88 < ball.rect.x / globals.WIDTH_UNIT < 92: if current_time - self.last_measurement_time > globals.MEASUREMENT_COOLDOWN_TIME: self.update_after_measurement() self.last_measurement_time = pygame.time.get_ticks() else: self.update_before_measurement() if pygame.sprite.collide_mask(ball, self.paddles[self.measured_state]): ball.bounce() def update_before_measurement(self): simulator = qiskit.BasicAer.get_backend("statevector_simulator") circuit = self.circuit_grid.model.compute_circuit() transpiled_circuit = qiskit.transpile(circuit, simulator) statevector = simulator.run(transpiled_circuit, shots=100).result().get_statevector() for basis_state, amplitude in enumerate(statevector): self.paddles[basis_state].image.set_alpha(abs(amplitude)**2*255) def update_after_measurement(self): simulator = qiskit.BasicAer.get_backend("qasm_simulator") circuit = self.circuit_grid.model.compute_circuit() circuit.measure_all() transpiled_circuit = qiskit.transpile(circuit, simulator) counts = simulator.run(transpiled_circuit, shots=1).result().get_counts() self.measured_state = int(list(counts.keys())[0], 2) for paddle in self.paddles: paddle.image.set_alpha(0) self.paddles[self.measured_state].image.set_alpha(255)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
%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 * # Loading your IBM Q account(s) provider = IBMQ.load_account() import scipy from scipy.stats import unitary_group u = unitary_group.rvs(2) print(u) qc = QuantumCircuit(2) qc.iso(u, [0], []) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy import linalg h = scipy.linalg.hadamard(2) import numpy as np u1 = np.dot(h, u) u2 = np.dot(u1, h) c2 = [] for i in range (2): c2.append(u2[i,i]) print(c2) qc = QuantumCircuit(2) qc.diagonal(c2, [0]) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy.stats import unitary_group u = unitary_group.rvs(4) print(u) qc = QuantumCircuit(4) qc.iso(u, [0,1], []) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy import linalg h = scipy.linalg.hadamard(4)/2 import numpy as np u1 = np.dot(h, u) u2 = np.dot(u1, h) c2 = [] for i in range (4): c2.append(u2[i,i]) print(c2) qc = QuantumCircuit(4) qc.diagonal(c2, [0, 1]) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy.stats import unitary_group u = unitary_group.rvs(8) print(u) qc = QuantumCircuit(4) qc.iso(u, [0, 1, 2], []) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy import linalg h = scipy.linalg.hadamard(8)/3 import numpy as np u1 = np.dot(h, u) u2 = np.dot(u1, h) c2 = [] for i in range (8): c2.append(u2[i,i]) print(c2) qc = QuantumCircuit(4) qc.diagonal(c2, [0, 1, 2]) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy.stats import unitary_group u = unitary_group.rvs(16) print(u) qc = QuantumCircuit(4) qc.iso(u, [0, 1, 2, 3], []) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy import linalg h = scipy.linalg.hadamard(16)/4 import numpy as np u1 = np.dot(h, u) u2 = np.dot(u1, h) c2 = [] for i in range (16): c2.append(u2[i,i]) print(c2) qc = QuantumCircuit(4) qc.diagonal(c2, [0, 1, 2, 3]) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy.stats import unitary_group u = unitary_group.rvs(32) print(u) qc = QuantumCircuit(8) qc.iso(u, [0, 1, 2, 3, 4], []) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy import linalg h = scipy.linalg.hadamard(32)/5 import numpy as np u1 = np.dot(h, u) u2 = np.dot(u1, h) c2 = [] for i in range (32): c2.append(u2[i,i]) print(c2) qc = QuantumCircuit(8) qc.diagonal(c2, [0, 1, 2, 3, 4]) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy.stats import unitary_group u = unitary_group.rvs(64) print(u) qc = QuantumCircuit(8) qc.iso(u, [0, 1, 2, 3, 4, 5], []) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy import linalg h = scipy.linalg.hadamard(64)/6 import numpy as np u1 = np.dot(h, u) u2 = np.dot(u1, h) c2 = [] for i in range (64): c2.append(u2[i,i]) print(c2) qc = QuantumCircuit(8) qc.diagonal(c2, [0, 1, 2, 3, 4, 5]) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy.stats import unitary_group u = unitary_group.rvs(128) print(u) qc = QuantumCircuit(8) qc.iso(u, [0, 1, 2, 3, 4, 5, 6], []) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy import linalg h = scipy.linalg.hadamard(128)/7 import numpy as np u1 = np.dot(h, u) u2 = np.dot(u1, h) c2 = [] for i in range (128): c2.append(u2[i,i]) print(c2) qc = QuantumCircuit(8) qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6]) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy.stats import unitary_group u = unitary_group.rvs(256) print(u) qc = QuantumCircuit(8) qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7], []) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy import linalg h = scipy.linalg.hadamard(256)/8 import numpy as np u1 = np.dot(h, u) u2 = np.dot(u1, h) c2 = [] for i in range (256): c2.append(u2[i,i]) print(c2) qc = QuantumCircuit(8) qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7]) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy.stats import unitary_group u = unitary_group.rvs(512) print(u) qc = QuantumCircuit(16) qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7, 8], []) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy import linalg h = scipy.linalg.hadamard(512)/9 import numpy as np u1 = np.dot(h, u) u2 = np.dot(u1, h) c2 = [] for i in range (512): c2.append(u2[i,i]) print(c2) qc = QuantumCircuit(16) qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7, 8]) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy.stats import unitary_group u = unitary_group.rvs(1024) print(u) qc = QuantumCircuit(16) qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], []) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc) import scipy from scipy import linalg h = scipy.linalg.hadamard(1024)/10 import numpy as np u1 = np.dot(h, u) u2 = np.dot(u1, h) c2 = [] for i in range (1024): c2.append(u2[i,i]) print(c2) qc = QuantumCircuit(16) qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3) circuit_drawer(qc)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
from qiskit import QuantumCircuit, assemble, Aer, execute from math import pi, sqrt from qiskit.visualization import plot_bloch_multivector, plot_histogram import numpy as np qc = QuantumCircuit(2) qc.h(0) qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) res = sim.run(qobj).result().get_statevector() plot_bloch_multivector(res) qc = QuantumCircuit(2) qc.h(0) qc.cp(pi/4, 0, 1) qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) res = sim.run(qobj).result().get_statevector() plot_bloch_multivector(res) qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) res = sim.run(qobj).result().get_statevector() plot_bloch_multivector(res) qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.cp(-pi/2, 0, 1) qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) res = sim.run(qobj).result().get_statevector() plot_bloch_multivector(res) qc = QuantumCircuit(2) for i in range(2): qc.x(i) qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) res = sim.run(qobj).result().get_statevector() plot_bloch_multivector(res) qc = QuantumCircuit(2) for i in range(2): qc.x(i) qc.cp(pi/4, 0, 1) qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) res = sim.run(qobj).result().get_statevector() plot_bloch_multivector(res)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
import numpy as np from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, assemble, transpile from qiskit.visualization import plot_histogram from qiskit_textbook.problems import dj_problem_oracle def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First generate a random number that tells us which CNOTs to # wrap in X-gates: b = np.random.randint(1,2**n) # Next, format 'b' as a binary string of length 'n', padded with zeros: b_str = format(b, '0'+str(n)+'b') # Next, we place the first X-gates. Each digit in our binary string # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1 # we apply an X-gate to that qubit: for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Do the controlled-NOT gates for each qubit, using the output qubit # as the target: for qubit in range(n): oracle_qc.cx(qubit, n) # Next, place the final X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': oracle_qc.x(qubit) # Case in which oracle is constant if case == "constant": # First decide what the fixed output of the oracle will be # (either always 0 or always 1) output = np.random.randint(2) if output == 1: oracle_qc.x(n) oracle_gate = oracle_qc.to_gate() oracle_gate.name = "Oracle" # To show when we display the circuit return oracle_gate def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n+1)) # Finally, perform the H-gates again and measure: for qubit in range(n): dj_circuit.h(qubit) for i in range(n): dj_circuit.measure(i, i) return dj_circuit n = 4 oracle = dj_problem_oracle(1) dj_circuit = dj_algorithm(oracle, n) dj_circuit.draw() sim = Aer.get_backend('aer_simulator') transpiled_dj_circuit = transpile(dj_circuit, sim) qobj = assemble(transpiled_dj_circuit) results = sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) oracle = dj_problem_oracle(2) dj_circuit = dj_algorithm(oracle, n) dj_circuit.draw() sim = Aer.get_backend('aer_simulator') transpiled_dj_circuit = transpile(dj_circuit, sim) qobj = assemble(transpiled_dj_circuit) results = sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) oracle = dj_problem_oracle(3) dj_circuit = dj_algorithm(oracle, n) dj_circuit.draw() sim = Aer.get_backend('aer_simulator') transpiled_dj_circuit = transpile(dj_circuit, sim) qobj = assemble(transpiled_dj_circuit) results = sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) oracle = dj_problem_oracle(4) dj_circuit = dj_algorithm(oracle, n) dj_circuit.draw() sim = Aer.get_backend('aer_simulator') transpiled_dj_circuit = transpile(dj_circuit, sim) qobj = assemble(transpiled_dj_circuit) results = sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) oracle = dj_problem_oracle(5) dj_circuit = dj_algorithm(oracle, n) dj_circuit.draw() sim = Aer.get_backend('aer_simulator') transpiled_dj_circuit = transpile(dj_circuit, sim) qobj = assemble(transpiled_dj_circuit) results = sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
from qiskit_textbook.widgets import bv_widget bv_widget(4, "1011", hide_oracle=False) from qiskit_textbook.widgets import bv_widget bv_widget(8, "11101101", hide_oracle=False)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle # The function simon_oracle (imported above) creates a Simon oracle for the bitstring b # Simon_Oracle def simon_gen_oracle(b): # to create copies of first register to second register for i in range(n): circ.cx(i, n+i) #change the name of variable 'circ' depending on what you name your circuit # appying cx based on b k=0 for i in range(n-1, -1, -1): #reading the character of b in reverse order if b[i] == '1': #if there is a '1' in b, because if there is a '0' we leave it unchanged m = n #we assign the value of n to some variable m for j in range(n-1, -1, -1): if b[j] == '1': #if we encounter '1' then we implement cx with respect to those b which are '1' circ.cx(k, m) m+=1 break k+=1 # when the bitstring is not '1', we increment k by 1 and go to next bit n = 4 b = '1001' circ = QuantumCircuit(n*2, n) circ.h(range(n)) circ.barrier() simon_gen_oracle(b) circ.barrier() circ.h(range(n)) circ.measure(range(n), range(n)) circ.draw() # use local simulator aer_sim = Aer.get_backend('aer_simulator') shots = 1024 qobj = assemble(circ, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) # Calculate the dot product of the results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) for z in counts: print( '{}.{} = {} (mod 2)'.format(b, z, bdotz(b,z), ) ) b_1 = '1001' n = len(b_1) simon_circuit = QuantumCircuit(n*2, n) # Apply Hadamard gates before querying the oracle simon_circuit.h(range(n)) # Apply barrier for visual separation simon_circuit.barrier() simon_circuit += simon_oracle(b_1) # Apply barrier for visual separation simon_circuit.barrier() # Apply Hadamard gates to the input register simon_circuit.h(range(n)) # Measure qubits simon_circuit.measure(range(n), range(n)) simon_circuit.draw() # use local simulator aer_sim = Aer.get_backend('aer_simulator') shots = 1024 qobj = assemble(simon_circuit, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) # Calculate the dot product of the results def bdotz(b_1, z): accum = 0 for i in range(len(b_1)): accum += int(b_1[i]) * int(z[i]) return (accum % 2) for z in counts: print( '{}.{} = {} (mod 2)'.format(b_1, z, bdotz(b_1,z), ) )
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
import numpy as np from numpy import pi from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram, plot_bloch_multivector def qft(circuit, n): """QFT on the first n qubits in circuit""" qft_rotations(circuit, n) swap_registers(circuit, n) return circuit def qft_rotations(circuit, n): if n == 0: # Exit function if circuit is empty return circuit n -= 1 # Indexes start from 0 circuit.h(n) # Apply the H-gate to the most significant qubit for qubit in range(n): # For each less significant qubit, we need to do a # smaller-angled controlled rotation: circuit.cp(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 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 # Putting the qubit in the state |4> nqubits = 3 number = 4 qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) qc.p(number*pi/4,0) qc.p(number*pi/2,1) qc.p(number*pi,2) qc.draw() qc_init = qc.copy() qc_init.save_statevector() sim = Aer.get_backend("aer_simulator") statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qc = inverse_qft(qc, nqubits) qc.measure_all() qc.draw() # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= nqubits and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) shots = 1024 transpiled_qc = transpile(qc, backend, optimization_level=3) job = backend.run(transpiled_qc, shots=shots) job_monitor(job) counts = job.result().get_counts() plot_histogram(counts) # Putting the qubit in the state |4> nqubits = 3 number = 3 qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) qc.p(number*pi/4,0) qc.p(number*pi/2,1) qc.p(number*pi,2) qc.draw() qc_init = qc.copy() qc_init.save_statevector() sim = Aer.get_backend("aer_simulator") statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qc = inverse_qft(qc, nqubits) qc.measure_all() qc.draw() # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= nqubits and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) shots = 1024 transpiled_qc = transpile(qc, backend, optimization_level=3) job = backend.run(transpiled_qc, shots=shots) job_monitor(job) counts = job.result().get_counts() plot_histogram(counts)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import IBMQ, Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools from qiskit.visualization import plot_histogram def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! for qubit in range(n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-math.pi/float(2**(j-m)), m, j) qc.h(j) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/2 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/4 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 7*2*math.pi/8 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/2 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
import matplotlib.pyplot as plt import numpy as np from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram from math import gcd from numpy.random import randint import pandas as pd from fractions import Fraction def c_amod15(a, power): """Controlled multiplication by a mod 15""" if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") U = QuantumCircuit(4) for iteration in range(power): if a in [2,13]: U.swap(0,1) U.swap(1,2) U.swap(2,3) if a in [7,8]: U.swap(2,3) U.swap(1,2) U.swap(0,1) if a == 11: U.swap(1,3) U.swap(0,2) if a in [7,11,13]: for q in range(4): U.x(q) U = U.to_gate() U.name = "%i^%i mod 15" % (a, power) c_U = U.control() return c_U 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.cp(-np.pi/float(2**(j-m)), m, j) qc.h(j) qc.name = "QFT†" return qc # Specify variables n_count = 8 # number of counting qubits a = 2 # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), # second one is power of 2 [q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8 # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df) # Specify variables n_count = 8 # number of counting qubits a = 8 # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), # second one is power of 2 [q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8 # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df) # Specify variables n_count = 8 # number of counting qubits a = 11 # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), # second one is power of 2 [q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8 # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df) # Specify variables n_count = 8 # number of counting qubits a = 13 # Create QuantumCircuit with n_count counting qubits # plus 4 qubits for U to act on qc = QuantumCircuit(n_count + 4, n_count) # Initialize counting qubits # in state |+> for q in range(n_count): qc.h(q) # And auxiliary register in state |1> qc.x(3+n_count) # Do controlled-U operations for q in range(n_count): qc.append(c_amod15(a, 2**q), # second one is power of 2 [q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8 # Do inverse-QFT qc.append(qft_dagger(n_count), range(n_count)) # Measure circuit qc.measure(range(n_count), range(n_count)) qc.draw(fold=-1) # -1 means 'do not fold' aer_sim = Aer.get_backend('aer_simulator') t_qc = transpile(qc, aer_sim) qobj = assemble(t_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append([f"{output}(bin) = {decimal:>3}(dec)", f"{decimal}/{2**n_count} = {phase:.2f}"]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
#initialization import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, assemble, transpile from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.providers.ibmq import least_busy # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.problems import grover_problem_oracle def initialize_s(qc, qubits): """Apply a H-gate to 'qubits' in qc""" for q in qubits: qc.h(q) return qc def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s n = 4 qc = QuantumCircuit(n) oracle1 = grover_problem_oracle(4, variant=2, print_solutions=True) qc = initialize_s(qc, [0,1,2,3]) # we run two iterations here qc.append(oracle1, [0,1,2,3]) qc.append(diffuser(n), [0,1,2,3]) qc.append(oracle1, [0,1,2,3]) qc.append(diffuser(n), [0,1,2,3]) qc.measure_all() qc.draw() aer_sim = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, aer_sim) qobj = assemble(transpiled_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) # Verification of Solution n = 4 oracle = grover_problem_oracle(n, variant=2, print_solutions = True) # 0th variant of oracle, with n qubits qc = QuantumCircuit(n) qc.append(oracle, [0,1,2,3]) n = 4 qc = QuantumCircuit(n) oracle = grover_problem_oracle(4, variant=1, print_solutions=True) qc = initialize_s(qc, [0,1,2,3]) # we run two iterations here qc.append(oracle, [0,1,2,3]) qc.append(diffuser(n), [0,1,2,3]) qc.measure_all() qc.draw() aer_sim = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, aer_sim) qobj = assemble(transpiled_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) n = 4 qc = QuantumCircuit(n) oracle = grover_problem_oracle(4, variant=1, print_solutions=True) qc = initialize_s(qc, [0,1,2,3]) # we run two iterations here qc.append(oracle, [0,1,2,3]) qc.append(diffuser(n), [0,1,2,3]) qc.append(oracle, [0,1,2,3]) qc.append(diffuser(n), [0,1,2,3]) qc.measure_all() qc.draw() aer_sim = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, aer_sim) qobj = assemble(transpiled_qc) results = aer_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) # define the number of qubits needed n # define your own oracle and the nummber of iterations you need # this code makes use of just the diffuser function def grover_oracle(oracle, iterations): # applying h gates for i in range(n): qc.h(i) #applying the oracle specified a = [] for i in range(n): a.append(i) for i in range(iterations): qc.append(oracle, a) qc.append(diffuser(n), a) qc.measure_all() return qc n = 4 iterations = 2 oracle = grover_problem_oracle(n, variant=1, print_solutions=True) qc = QuantumCircuit(n, n) qc = grover_oracle(oracle, iterations) qc.draw()
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit import qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.problems import grover_problem_oracle def diffuser(nqubits): qc = QuantumCircuit(nqubits) # Apply transformation |s> -> |00..0> (H-gates) for qubit in range(nqubits): qc.h(qubit) # Apply transformation |00..0> -> |11..1> (X-gates) for qubit in range(nqubits): qc.x(qubit) # Do multi-controlled-Z gate qc.h(nqubits-1) qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc.h(nqubits-1) # Apply transformation |11..1> -> |00..0> for qubit in range(nqubits): qc.x(qubit) # Apply transformation |00..0> -> |s> for qubit in range(nqubits): qc.h(qubit) # We will return the diffuser as a gate U_s = qc.to_gate() U_s.name = "U$_s$" return U_s def grover_unsolved(): n=3 qc = QuantumCircuit(n) for i in range(n): qc.h(i) #oracle qc.cz(0, 2) qc.cz(1, 2) #diffuser #use the model of general diffuser qc.h(range(3)) qc.x(range(3)) qc.h(2) qc.mct([0,1],2) qc.h(2) qc.x(range(3)) qc.h(range(3)) return qc grit = grover_unsolved().to_gate() grit.label = "Grover" cgrit = grit.control() #This code implements the QFT on n qubits: def qft(n): """Creates an n-qubit QFT circuit""" circuit = QuantumCircuit(3) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(np.pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # inversing the circuit qft_dagger = qft(3).to_gate().inverse() qft_dagger.label = "QFT†" # Create QuantumCircuit t = 3 # no. of counting qubits n = 3 # no. of searching qubits qc = QuantumCircuit(n+t, t) # Circuit with n+t qubits and t classical bits # Initialize all qubits to |+> for qubit in range(t+n): qc.h(qubit) # Begin controlled Grover iterations iterations = 1 for qubit in range(t): # qubits in range of counting quibts for i in range(iterations): qc.append(cgrit, [qubit] + [*range(t, n+t)]) #controlled grover oracle iterations *= 2 # iteration in power of 2 # Do inverse QFT on counting qubits qc.append(qft_dagger, range(t)) # Measure counting qubits qc.measure(range(t), range(t)) # Display the circuit qc.draw() # Execute and see results aer_sim = Aer.get_backend('aer_simulator') transpiled_qc = transpile(qc, aer_sim) qobj = assemble(transpiled_qc) job = aer_sim.run(qobj) hist = job.result().get_counts() plot_histogram(hist) measured_str = max(hist, key=hist.get) measured_int = int(measured_str,2) print("Register Output = %i" % measured_int) theta = (measured_int/(2**t))*math.pi*2 print("Theta = %.5f" % theta) N = 2**n M = N * (math.sin(theta/2)**2) print("No. of Solutions = %.1f" % (N-M)) m = t - 1 # Upper bound: Will be less than this err = (math.sqrt(2*M*N) + N/(2**(m+1)))*(2**(-m)) print("Error < %.2f" % err)
https://github.com/hritiksauw199/Qiskit-textbook-solutions
hritiksauw199
from qiskit import QuantumCircuit import qiskit.quantum_info as qi qc_AB = QuantumCircuit(1) qc_AB.h(0) qc_AB.s(0) qc_AB.z(0) qc_AB.draw() psi_AB = qi.Statevector.from_instruction(qc_AB) psi_AB.draw('latex', prefix='|\\psi_{AB}\\rangle = ') rho_AB = qi.DensityMatrix.from_instruction(qc_AB) rho_AB.draw('latex', prefix='\\rho_{AB} = ') from qiskit.visualization import plot_state_city plot_state_city(rho_AB.data, title='Density Matrix') qc_AB = QuantumCircuit(2) qc_AB.h(0) qc_AB.h(1) qc_AB.draw() psi_AB = qi.Statevector.from_instruction(qc_AB) psi_AB.draw('latex', prefix='|\\psi_{AB}\\rangle = ') rho_AB = qi.DensityMatrix.from_instruction(qc_AB) rho_AB.draw('latex', prefix='\\rho_{AB} = ') from qiskit.visualization import plot_state_city plot_state_city(rho_AB.data, title='Density Matrix') qc_AB = QuantumCircuit(2) qc_AB.h(0) qc_AB.h(1) qc_AB.draw() psi_AB = qi.Statevector.from_instruction(qc_AB) psi_AB.draw('latex', prefix='|\\psi_{AB}\\rangle = ') rho_AB = qi.DensityMatrix.from_instruction(qc_AB) rho_AB.draw('latex', prefix='\\rho_{AB} = ') rho_B = qi.partial_trace(rho_AB,[0]) rho_A = qi.partial_trace(rho_AB,[1]) display(rho_B.draw('latex', prefix=" \\rho_{B} = "), rho_A.draw('latex', prefix=" \\rho_{A} = "))
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector excited = Statevector.from_int(1, 2) plot_bloch_multivector(excited.data) from qiskit.tools.jupyter import * from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') backend = provider.get_backend('ibmq_armonk') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support Pulse" dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() import numpy as np # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The Rabi sweep will be at the given qubit frequency. center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") from qiskit import pulse, assemble # This is where we access all of our Pulse features! from qiskit.pulse import Play from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[0]) # Rabi experiment parameters # Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75 num_rabi_points = 50 drive_amp_min = 0 drive_amp_max = 0.75 drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points) # drive waveforms mush be in units of 16 drive_sigma = 80 # in dt drive_samples = 8*drive_sigma # in dt # Build the Rabi experiments: # A drive pulse at the qubit frequency, followed by a measurement, # where we vary the drive amplitude each time. rabi_schedules = [] for drive_amp in drive_amps: rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}") this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}") this_schedule += Play(rabi_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration this_schedule += measure << this_schedule.duration rabi_schedules.append(this_schedule) rabi_schedules[-1].draw(label=True, scaling=1.0) # assemble the schedules into a Qobj num_shots_per_point = 1024 rabi_experiment_program = assemble(rabi_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_point, schedule_los=[{drive_chan: center_frequency_Hz}] * num_rabi_points) # RUN the job on a real device #job = backend.run(rabi_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive result from previous run job = backend.retrieve_job("5ef3bf17dc3044001186c011") rabi_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') scale_factor = 1e-14 # center data around 0 def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = [] for i in range(num_rabi_points): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) rabi_values = np.real(baseline_remove(rabi_values)) plt.xlabel("Drive amp [a.u.]") plt.ylabel("Measured signal [a.u.]") plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values plt.show() from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit fit_params, y_fit = fit_function(drive_amps, rabi_values, lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B), [10, 0.1, 0.6, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() pi_amp = abs(drive_period / 2) print(f"Pi Amplitude = {pi_amp}") # Drive parameters # The drive amplitude for pi/2 is simply half the amplitude of the pi pulse drive_amp = pi_amp / 2 # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 1.8 time_step_us = 0.025 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us") this_schedule += Play(x90_pulse, drive_chan) this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay) this_schedule += measure << this_schedule.duration ramsey_schedules.append(this_schedule) ramsey_schedules[-1].draw(label=True, scaling=1.0) # Execution settings num_shots = 256 detuning_MHz = 2 ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz ramsey_program = assemble(ramsey_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots, schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules) ) # RUN the job on a real device #job = backend.run(ramsey_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive job from previous run job = backend.retrieve_job('5ef3ed3a84b1b70012374317') ramsey_results = job.result() ramsey_values = [] for i in range(len(times_us)): ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor) fit_params, y_fit = fit_function(times_us, np.real(ramsey_values), lambda x, A, del_f_MHz, C, B: ( A * np.cos(2*np.pi*del_f_MHz*x - C) + B ), [5, 1./0.4, 0, 0.25] ) # Off-resonance component _, del_f_MHz, _, _, = fit_params # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz") plt.xlim(0, np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend() plt.show()
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector excited = Statevector.from_int(1, 2) plot_bloch_multivector(excited.data) from qiskit.tools.jupyter import * from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') backend = provider.get_backend('ibmq_armonk') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support Pulse" dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() import numpy as np # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The Rabi sweep will be at the given qubit frequency. center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") from qiskit import pulse, assemble # This is where we access all of our Pulse features! from qiskit.pulse import Play from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[0]) # Rabi experiment parameters # Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75 num_rabi_points = 50 drive_amp_min = 0 drive_amp_max = 0.75 drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points) # drive waveforms mush be in units of 16 drive_sigma = 80 # in dt drive_samples = 8*drive_sigma # in dt # Build the Rabi experiments: # A drive pulse at the qubit frequency, followed by a measurement, # where we vary the drive amplitude each time. rabi_schedules = [] for drive_amp in drive_amps: rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}") this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}") this_schedule += Play(rabi_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration this_schedule += measure << this_schedule.duration rabi_schedules.append(this_schedule) rabi_schedules[-1].draw(label=True, scaling=1.0) # assemble the schedules into a Qobj num_shots_per_point = 1024 rabi_experiment_program = assemble(rabi_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_point, schedule_los=[{drive_chan: center_frequency_Hz}] * num_rabi_points) # RUN the job on a real device #job = backend.run(rabi_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive result from previous run job = backend.retrieve_job("5ef3bf17dc3044001186c011") rabi_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') scale_factor = 1e-14 # center data around 0 def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = [] for i in range(num_rabi_points): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) rabi_values = np.real(baseline_remove(rabi_values)) plt.xlabel("Drive amp [a.u.]") plt.ylabel("Measured signal [a.u.]") plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values plt.show() from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit fit_params, y_fit = fit_function(drive_amps, rabi_values, lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B), [10, 0.1, 0.6, 0]) plt.scatter(drive_amps, rabi_values, color='white') plt.plot(drive_amps, y_fit, color='red') drive_period = fit_params[2] # get period of rabi oscillation plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() pi_amp = abs(drive_period / 2) print(f"Pi Amplitude = {pi_amp}") # Drive parameters # The drive amplitude for pi/2 is simply half the amplitude of the pi pulse drive_amp = pi_amp / 2 # x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees x90_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp, sigma=drive_sigma, name='x90_pulse') # Ramsey experiment parameters time_max_us = 1.8 time_step_us = 0.025 times_us = np.arange(0.1, time_max_us, time_step_us) # Convert to units of dt delay_times_dt = times_us * us / dt # create schedules for Ramsey experiment ramsey_schedules = [] for delay in delay_times_dt: this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us") this_schedule += Play(x90_pulse, drive_chan) this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay) this_schedule += measure << this_schedule.duration ramsey_schedules.append(this_schedule) ramsey_schedules[-1].draw(label=True, scaling=1.0) # Execution settings num_shots = 256 detuning_MHz = 2 ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz ramsey_program = assemble(ramsey_schedules, backend=backend, meas_level=1, meas_return='avg', shots=num_shots, schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules) ) # RUN the job on a real device #job = backend.run(ramsey_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive job from previous run job = backend.retrieve_job('5ef3ed3a84b1b70012374317') ramsey_results = job.result() ramsey_values = [] for i in range(len(times_us)): ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor) fit_params, y_fit = fit_function(times_us, np.real(ramsey_values), lambda x, A, del_f_MHz, C, B: ( A * np.cos(2*np.pi*del_f_MHz*x - C) + B ), [5, 1./0.4, 0, 0.25] ) # Off-resonance component _, del_f_MHz, _, _, = fit_params # freq is MHz since times in us plt.scatter(times_us, np.real(ramsey_values), color='white') plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz") plt.xlim(0, np.max(times_us)) plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15) plt.ylabel('Measured Signal [a.u.]', fontsize=15) plt.title('Ramsey Experiment', fontsize=15) plt.legend() plt.show()
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib # the same spect pulse used in every schedule drive_amp = 0.9 drive_sigma = 16 drive_duration = 128 spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}") # Construct an np array of the frequencies for our experiment spec_freqs_GHz = np.arange(5.0, 5.2, 0.005) # Create the base schedule # Start with drive pulse acting on the drive channel spec_schedules = [] for freq in spec_freqs_GHz: sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt) spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq)) spec_schedule += Play(sb_spec_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration spec_schedule += measure << spec_schedule.duration spec_schedules.append(spec_schedule) spec_schedules[0].draw() from qiskit import assemble # assemble the schedules into a Qobj spec01_qobj = assemble(**helper.get_params('spec01', globals())) # run the simulation spec01_result = backend_sim.run(spec01_qobj, duffing_model).result() # retrieve the data from the experiment spec01_values = helper.get_values_from_result(spec01_result, qubit) fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0]) f01 = fit_params[1] plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values plt.plot(spec_freqs_GHz, y_fit, color='red') plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("01 Spectroscopy yields %f GHz"%f01) x180_amp = 0.629070 #from lab 6 Rabi experiment x_pulse = pulse_lib.gaussian(duration=drive_duration, amp=x180_amp, sigma=drive_sigma, name='x_pulse') anharmonicity_guess_GHz = -0.3 def build_spec12_pulse_schedule(freq): sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt) ### create a 12 spectroscopy pulse schedule spec12_schedule (already done) ### play an x pulse on the drive channel ### play sidebanded spec pulse on the drive channel ### add measurement pulse to schedule spec12_schedule = pulse.Schedule() ### WRITE YOUR CODE BETWEEN THESE LINES - START spec12_schedule += Play(x_pulse, drive_chan) spec12_schedule += Play(sb12_spec_pulse, drive_chan) spec12_schedule += measure << spec12_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - STOP return spec12_schedule sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess # now vary the sideband frequency for each spec pulse spec_schedules = [] for freq in sb_freqs_GHz: spec_schedules.append(build_spec12_pulse_schedule(freq)) spec_schedules[0].draw() # assemble the schedules into a Qobj spec12_qobj = assemble(**helper.get_params('spec12', globals())) answer1 = spec12_qobj # run the simulation spec12_result = backend_sim.run(spec12_qobj, duffing_model).result() # retrieve the data from the experiment spec12_values = helper.get_values_from_result(spec12_result, qubit) anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3]) f12 = fit_params[1] plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red') plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("12 Spectroscopy yields %f GHz"%f12) print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz)) from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
# import SymPy and define symbols import sympy as sp sp.init_printing(use_unicode=True) wr = sp.Symbol('\omega_r') # resonator frequency wq = sp.Symbol('\omega_q') # qubit frequency g = sp.Symbol('g', real=True) # vacuum Rabi coupling Delta = sp.Symbol('Delta', real=True) # wr - wq; defined later # import operator relations and define them from sympy.physics.quantum.boson import BosonOp a = BosonOp('a') # resonator photon annihilation operator from sympy.physics.quantum import pauli, Dagger, Commutator from sympy.physics.quantum.operatorordering import normal_ordered_form # Pauli matrices sx = pauli.SigmaX() sy = pauli.SigmaY() sz = pauli.SigmaZ() # qubit raising and lowering operators splus = pauli.SigmaPlus() sminus = pauli.SigmaMinus() # define J-C Hamiltonian in terms of diagonal and non-block diagonal terms H0 = wr*Dagger(a)*a - (1/2)*wq*sz; H1 = 0 H2 = g*(Dagger(a)*sminus + a*splus); HJC = H0 + H1 + H2; HJC # print # using the above method for finding the ansatz eta = Commutator(H0, H2); eta pauli.qsimplify_pauli(normal_ordered_form(eta.doit().expand())) A = sp.Symbol('A') B = sp.Symbol('B') eta = A * Dagger(a) * sminus - B * a * splus; pauli.qsimplify_pauli(normal_ordered_form(Commutator(H0, eta).doit().expand())) H2 S1 = eta.subs(A, g/Delta) S1 = S1.subs(B, g/Delta); S1.factor() Heff = H0 + H1 + 0.5*pauli.qsimplify_pauli(normal_ordered_form(Commutator(H2, S1).doit().expand())).simplify(); Heff from qiskit.tools.jupyter import * from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') backend = provider.get_backend('ibmq_armonk') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support Pulse" dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() import numpy as np # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The sweep will be centered around the estimated qubit frequency. center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") # scale factor to remove factors of 10 from the data scale_factor = 1e-14 # We will sweep 40 MHz around the estimated frequency frequency_span_Hz = 40 * MHz # in steps of 1 MHz. frequency_step_Hz = 1 * MHz # We will sweep 20 MHz above and 20 MHz below the estimated frequency frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 # Construct an np array of the frequencies for our experiment frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \ in steps of {frequency_step_Hz / MHz} MHz.") from qiskit import pulse # This is where we access all of our Pulse features! inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[qubit]) x_pulse = inst_sched_map.get('x', qubits=[qubit]) ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Create the base schedule # Start with drive pulse acting on the drive channel schedule = pulse.Schedule(name='Frequency sweep') schedule += x_pulse # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration schedule += measure << schedule.duration # Create the frequency settings for the sweep (MUST BE IN HZ) frequencies_Hz = frequencies_GHz*GHz schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz] schedule.draw(label=True, scaling=0.8) from qiskit import assemble frequency_sweep_program = assemble(schedule, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=schedule_frequencies) # RUN the job on a real device #job = backend.run(rabi_experiment_program) #print(job.job_id()) #from qiskit.tools.monitor import job_monitor #job_monitor(job) # OR retreive result from previous run job = backend.retrieve_job('5ef3b081fbc24b001275b03b') frequency_sweep_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') sweep_values = [] for i in range(len(frequency_sweep_results.results)): # Get the results from the ith experiment res = frequency_sweep_results.get_memory(i)*scale_factor # Get the results for `qubit` from this experiment sweep_values.append(res[qubit]) plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') # plot real part of sweep values plt.xlim([min(frequencies_GHz), max(frequencies_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured signal [a.u.]") plt.show() from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit fit_params, y_fit = fit_function(frequencies_GHz, np.real(sweep_values), lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, [5, 4.975, 1, 3] # initial parameters for curve_fit ) plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') plt.plot(frequencies_GHz, y_fit, color='red') plt.xlim([min(frequencies_GHz), max(frequencies_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() # Create the schedules for 0 and 1 schedule_0 = pulse.Schedule(name='0') schedule_0 += measure schedule_1 = pulse.Schedule(name='1') schedule_1 += x_pulse schedule_1 += measure << schedule_1.duration schedule_0.draw() schedule_1.draw() frequency_span_Hz = 320 * kHz frequency_step_Hz = 8 * kHz center_frequency_Hz = backend_defaults.meas_freq_est[qubit] print(f"Qubit {qubit} has an estimated readout frequency of {center_frequency_Hz / GHz} GHz.") frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz\ in steps of {frequency_step_Hz / MHz} MHz.") num_shots_per_frequency = 2048 frequencies_Hz = frequencies_GHz*GHz schedule_los = [{meas_chan: freq} for freq in frequencies_Hz] cavity_sweep_0 = assemble(schedule_0, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_los) cavity_sweep_1 = assemble(schedule_1, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_los) # RUN the job on a real device #job_0 = backend.run(cavity_sweep_0) #job_monitor(job_0) #job_0.error_message() #job_1 = backend.run(cavity_sweep_1) #job_monitor(job_1) #job_1.error_message() # OR retreive result from previous run job_0 = backend.retrieve_job('5efa5b447c0d6800137fff1c') job_1 = backend.retrieve_job('5efa6b2720eee10013be46b4') cavity_sweep_0_results = job_0.result() cavity_sweep_1_results = job_1.result() scale_factor = 1e-14 sweep_values_0 = [] for i in range(len(cavity_sweep_0_results.results)): res_0 = cavity_sweep_0_results.get_memory(i)*scale_factor sweep_values_0.append(res_0[qubit]) sweep_values_1 = [] for i in range(len(cavity_sweep_1_results.results)): res_1 = cavity_sweep_1_results.get_memory(i)*scale_factor sweep_values_1.append(res_1[qubit]) plotx = frequencies_Hz/kHz ploty_0 = np.abs(sweep_values_0) ploty_1 = np.abs(sweep_values_1) plt.plot(plotx, ploty_0, color='blue', marker='.') # plot real part of sweep values plt.plot(plotx, ploty_1, color='red', marker='.') # plot real part of sweep values plt.legend([r'$\vert0\rangle$', r'$\vert1\rangle$']) plt.grid() plt.xlabel("Frequency [kHz]") plt.ylabel("Measured signal [a.u.]") plt.yscale('log') plt.show()
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() # our backend is the Pulse Simulator from resources import helper from qiskit.providers.aer import PulseSimulator backend_sim = PulseSimulator() # sample duration for pulse instructions dt = 1e-9 # create the model duffing_model = helper.get_transmon(dt) # get qubit frequency from Duffing model qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift() import numpy as np # visualization tools import matplotlib.pyplot as plt plt.style.use('dark_background') # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 # kilohertz us = 1.0e-6 # microseconds ns = 1.0e-9 # nanoseconds from qiskit import pulse from qiskit.pulse import Play, Acquire from qiskit.pulse.pulse_lib import GaussianSquare # qubit to be used throughout the notebook qubit = 0 ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Construct a measurement schedule and add it to an InstructionScheduleMap meas_samples = 1200 meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150) measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit)) inst_map = pulse.InstructionScheduleMap() inst_map.add('measure', [qubit], measure_sched) # save the measurement/acquire pulse for later measure = inst_map.get('measure', qubits=[qubit]) from qiskit.pulse import pulse_lib # the same spect pulse used in every schedule drive_amp = 0.9 drive_sigma = 16 drive_duration = 128 spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp, sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}") # Construct an np array of the frequencies for our experiment spec_freqs_GHz = np.arange(5.0, 5.2, 0.005) # Create the base schedule # Start with drive pulse acting on the drive channel spec_schedules = [] for freq in spec_freqs_GHz: sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt) spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq)) spec_schedule += Play(sb_spec_pulse, drive_chan) # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration spec_schedule += measure << spec_schedule.duration spec_schedules.append(spec_schedule) spec_schedules[0].draw() from qiskit import assemble # assemble the schedules into a Qobj spec01_qobj = assemble(**helper.get_params('spec01', globals())) # run the simulation spec01_result = backend_sim.run(spec01_qobj, duffing_model).result() # retrieve the data from the experiment spec01_values = helper.get_values_from_result(spec01_result, qubit) fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0]) f01 = fit_params[1] plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values plt.plot(spec_freqs_GHz, y_fit, color='red') plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("01 Spectroscopy yields %f GHz"%f01) x180_amp = 0.629070 #from lab 6 Rabi experiment x_pulse = pulse_lib.gaussian(duration=drive_duration, amp=x180_amp, sigma=drive_sigma, name='x_pulse') anharmonicity_guess_GHz = -0.3 def build_spec12_pulse_schedule(freq): sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt) ### create a 12 spectroscopy pulse schedule spec12_schedule (already done) ### play an x pulse on the drive channel ### play sidebanded spec pulse on the drive channel ### add measurement pulse to schedule spec12_schedule = pulse.Schedule() ### WRITE YOUR CODE BETWEEN THESE LINES - START spec12_schedule += Play(x_pulse, drive_chan) spec12_schedule += Play(sb12_spec_pulse, drive_chan) spec12_schedule += measure << spec12_schedule.duration ### WRITE YOUR CODE BETWEEN THESE LINES - STOP return spec12_schedule sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess # now vary the sideband frequency for each spec pulse spec_schedules = [] for freq in sb_freqs_GHz: spec_schedules.append(build_spec12_pulse_schedule(freq)) spec_schedules[0].draw() # assemble the schedules into a Qobj spec12_qobj = assemble(**helper.get_params('spec12', globals())) answer1 = spec12_qobj # run the simulation spec12_result = backend_sim.run(spec12_qobj, duffing_model).result() # retrieve the data from the experiment spec12_values = helper.get_values_from_result(spec12_result, qubit) anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3]) f12 = fit_params[1] plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red') plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() print("12 Spectroscopy yields %f GHz"%f12) print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz)) from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();')); from grading_tools import send_code;send_code('ex1.ipynb')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
# import SymPy and define symbols import sympy as sp sp.init_printing(use_unicode=True) wr = sp.Symbol('\omega_r') # resonator frequency wq = sp.Symbol('\omega_q') # qubit frequency g = sp.Symbol('g', real=True) # vacuum Rabi coupling Delta = sp.Symbol('Delta', real=True) # wr - wq; defined later # import operator relations and define them from sympy.physics.quantum.boson import BosonOp a = BosonOp('a') # resonator photon annihilation operator from sympy.physics.quantum import pauli, Dagger, Commutator from sympy.physics.quantum.operatorordering import normal_ordered_form # Pauli matrices sx = pauli.SigmaX() sy = pauli.SigmaY() sz = pauli.SigmaZ() # qubit raising and lowering operators splus = pauli.SigmaPlus() sminus = pauli.SigmaMinus() # define J-C Hamiltonian in terms of diagonal and non-block diagonal terms H0 = wr*Dagger(a)*a - (1/2)*wq*sz; H1 = 0 H2 = g*(Dagger(a)*sminus + a*splus); HJC = H0 + H1 + H2; HJC # print # using the above method for finding the ansatz eta = Commutator(H0, H2); eta pauli.qsimplify_pauli(normal_ordered_form(eta.doit().expand())) A = sp.Symbol('A') B = sp.Symbol('B') eta = A * Dagger(a) * sminus - B * a * splus; pauli.qsimplify_pauli(normal_ordered_form(Commutator(H0, eta).doit().expand())) H2 S1 = eta.subs(A, g/Delta) S1 = S1.subs(B, g/Delta); S1.factor() Heff = H0 + H1 + 0.5*pauli.qsimplify_pauli(normal_ordered_form(Commutator(H2, S1).doit().expand())).simplify(); Heff from qiskit.tools.jupyter import * from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') backend = provider.get_backend('ibmq_armonk') backend_config = backend.configuration() assert backend_config.open_pulse, "Backend doesn't support Pulse" dt = backend_config.dt print(f"Sampling time: {dt*1e9} ns") backend_defaults = backend.defaults() import numpy as np # unit conversion factors -> all backend properties returned in SI (Hz, sec, etc) GHz = 1.0e9 # Gigahertz MHz = 1.0e6 # Megahertz kHz = 1.0e3 us = 1.0e-6 # Microseconds ns = 1.0e-9 # Nanoseconds # We will find the qubit frequency for the following qubit. qubit = 0 # The sweep will be centered around the estimated qubit frequency. center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz # warning: this will change in a future release print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.") # scale factor to remove factors of 10 from the data scale_factor = 1e-14 # We will sweep 40 MHz around the estimated frequency frequency_span_Hz = 40 * MHz # in steps of 1 MHz. frequency_step_Hz = 1 * MHz # We will sweep 20 MHz above and 20 MHz below the estimated frequency frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 # Construct an np array of the frequencies for our experiment frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \ in steps of {frequency_step_Hz / MHz} MHz.") from qiskit import pulse # This is where we access all of our Pulse features! inst_sched_map = backend_defaults.instruction_schedule_map measure = inst_sched_map.get('measure', qubits=[qubit]) x_pulse = inst_sched_map.get('x', qubits=[qubit]) ### Collect the necessary channels drive_chan = pulse.DriveChannel(qubit) meas_chan = pulse.MeasureChannel(qubit) acq_chan = pulse.AcquireChannel(qubit) # Create the base schedule # Start with drive pulse acting on the drive channel schedule = pulse.Schedule(name='Frequency sweep') schedule += x_pulse # The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration schedule += measure << schedule.duration # Create the frequency settings for the sweep (MUST BE IN HZ) frequencies_Hz = frequencies_GHz*GHz schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz] schedule.draw(label=True, scaling=0.8) from qiskit import assemble frequency_sweep_program = assemble(schedule, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=schedule_frequencies) # RUN the job on a real device job = backend.run(frequency_sweep_program) print(job.job_id()) from qiskit.tools.monitor import job_monitor job_monitor(job) # OR retreive result from previous run # job = backend.retrieve_job('5ef3b081fbc24b001275b03b') frequency_sweep_results = job.result() import matplotlib.pyplot as plt plt.style.use('dark_background') sweep_values = [] for i in range(len(frequency_sweep_results.results)): # Get the results from the ith experiment res = frequency_sweep_results.get_memory(i)*scale_factor # Get the results for `qubit` from this experiment sweep_values.append(res[qubit]) plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') # plot real part of sweep values plt.xlim([min(frequencies_GHz), max(frequencies_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured signal [a.u.]") plt.show() from scipy.optimize import curve_fit def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit fit_params, y_fit = fit_function(frequencies_GHz, np.real(sweep_values), lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, [5, 4.975, 1, 3] # initial parameters for curve_fit ) plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') plt.plot(frequencies_GHz, y_fit, color='red') plt.xlim([min(frequencies_GHz), max(frequencies_GHz)]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() # Create the schedules for 0 and 1 schedule_0 = pulse.Schedule(name='0') schedule_0 += measure schedule_1 = pulse.Schedule(name='1') schedule_1 += x_pulse schedule_1 += measure << schedule_1.duration schedule_0.draw() schedule_1.draw() frequency_span_Hz = 320 * kHz frequency_step_Hz = 8 * kHz center_frequency_Hz = backend_defaults.meas_freq_est[qubit] print(f"Qubit {qubit} has an estimated readout frequency of {center_frequency_Hz / GHz} GHz.") frequency_min = center_frequency_Hz - frequency_span_Hz / 2 frequency_max = center_frequency_Hz + frequency_span_Hz / 2 frequencies_GHz = np.arange(frequency_min / GHz, frequency_max / GHz, frequency_step_Hz / GHz) print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz\ in steps of {frequency_step_Hz / MHz} MHz.") num_shots_per_frequency = 2048 frequencies_Hz = frequencies_GHz*GHz schedule_los = [{meas_chan: freq} for freq in frequencies_Hz] cavity_sweep_0 = assemble(schedule_0, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_los) cavity_sweep_1 = assemble(schedule_1, backend=backend, meas_level=1, meas_return='avg', shots=num_shots_per_frequency, schedule_los=schedule_los) # RUN the job on a real device #job_0 = backend.run(cavity_sweep_0) #job_monitor(job_0) #job_0.error_message() #job_1 = backend.run(cavity_sweep_1) #job_monitor(job_1) #job_1.error_message() # OR retreive result from previous run job_0 = backend.retrieve_job('5efa5b447c0d6800137fff1c') job_1 = backend.retrieve_job('5efa6b2720eee10013be46b4') cavity_sweep_0_results = job_0.result() cavity_sweep_1_results = job_1.result() scale_factor = 1e-14 sweep_values_0 = [] for i in range(len(cavity_sweep_0_results.results)): res_0 = cavity_sweep_0_results.get_memory(i)*scale_factor sweep_values_0.append(res_0[qubit]) sweep_values_1 = [] for i in range(len(cavity_sweep_1_results.results)): res_1 = cavity_sweep_1_results.get_memory(i)*scale_factor sweep_values_1.append(res_1[qubit]) plotx = frequencies_Hz/kHz ploty_0 = np.abs(sweep_values_0) ploty_1 = np.abs(sweep_values_1) plt.plot(plotx, ploty_0, color='blue', marker='.') # plot real part of sweep values plt.plot(plotx, ploty_1, color='red', marker='.') # plot real part of sweep values plt.legend([r'$\vert0\rangle$', r'$\vert1\rangle$']) plt.grid() plt.xlabel("Frequency [kHz]") plt.ylabel("Measured signal [a.u.]") plt.yscale('log') plt.show()
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import json from typing import Any, Callable, Optional, Tuple, Union from urllib.parse import urljoin from qiskit import QuantumCircuit, execute from qiskit.providers import JobStatus from qiskit.providers.ibmq.job import IBMQJob from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint from .exercises import get_question_id from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate def _circuit_criteria( circuit: QuantumCircuit, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[int], Optional[int]]: if max_qubits is not None and circuit.num_qubits > max_qubits: print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.') print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.') return None, None try: if check_gates and not uses_multiqubit_gate(circuit): print('Your circuit appears to not use any multi-quibit gates.') print('Please review your circuit and try again.') return None, None cost = compute_cost(circuit) if min_cost is not None and cost < min_cost: print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n' 'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.') return None, None return circuit.num_qubits, cost except Exception as err: print(f'Unable to compute cost: {err}') return None, None def _circuit_grading( circuit: QuantumCircuit, lab_id: str, ex_id: str, is_submit: Optional[bool] = False, max_qubits: Optional[int] = None, min_cost: Optional[int] = None, check_gates: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: payload = None server = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or ' 'the grading servers are down right now.') return None, None else: server = None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: payload = { 'answer': circuit_to_json(circuit) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _job_grading( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str): print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}') print(f'Please submit a job as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading ' 'servers are down right now.') return None, None else: server = None job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id if not job: print('An invalid or non-existent job was specified.') return None, None job_status = job.status() if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]: print(f'Job did not successfully complete: {job_status.value}.') return None, None elif job_status is not JobStatus.DONE: print(f'Job has not yet completed: {job_status.value}.') print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.') return None, None header = job.result().header.to_dict() if 'qc_cost' not in header: if is_submit: print('An unprepared answer was specified. ' 'Please prepare() and grade() answer before submitting.') else: print('An unprepared answer was specified. Please prepare() answer before grading.') return None, None download_url, result_url = get_job_urls(job) if not download_url or not result_url: print('Unable to obtain job URLs') return None, None payload = { 'answer': json.dumps({ 'download_url': download_url, 'result_url': result_url }) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def _number_grading( answer: int, lab_id: str, ex_id: str, is_submit: Optional[bool] = False ) -> Tuple[Optional[dict], Optional[str]]: if not isinstance(answer, int): print(f'Expected a integer, but was given {type(answer)}') print(f'Please provide a number as your answer.') return None, None if not is_submit: server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server ' 'or the grading servers are down right now.') return None, None else: server = None payload = { 'answer': str(answer) } if is_submit: payload['questionNumber'] = get_question_id(lab_id, ex_id) else: payload['question_id'] = get_question_id(lab_id, ex_id) return payload, server def prepare_circuit( circuit: QuantumCircuit, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not isinstance(circuit, QuantumCircuit): print(f'Expected a QuantumCircuit, but was given {type(circuit)}') print(f'Please provide a circuit.') return None _, cost = _circuit_criteria( circuit, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if cost is not None: if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiment. Please wait...') job = execute( circuit, qobj_header={ 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def prepare_solver( solver_func: Callable, lab_id: str, ex_id: str, problem_set: Optional[Any] = None, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None, check_gates: Optional[bool] = False, **kwargs ) -> Optional[IBMQJob]: job = None if not callable(solver_func): print(f'Expected a function, but was given {type(solver_func)}') print(f'Please provide a function that returns a QuantumCircuit.') return None server = get_server_endpoint(lab_id, ex_id) if not server: print('Could not find a valid grading server or the grading servers are down right now.') return endpoint = server + 'problem-set' index, value = get_problem_set(lab_id, ex_id, endpoint) print(f'Running {solver_func.__name__}...') qc_1 = solver_func(problem_set) _, cost = _circuit_criteria( qc_1, max_qubits=max_qubits, min_cost=min_cost, check_gates=check_gates ) if value and index is not None and index >= 0 and cost is not None: qc_2 = solver_func(value) if 'backend' not in kwargs: kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator') # execute experiments print('Starting experiments. Please wait...') job = execute( [qc_1, qc_2], qobj_header={ 'qc_index': [None, index], 'qc_cost': cost }, **kwargs ) print(f'You may monitor the job (id: {job.job_id()}) status ' 'and proceed to grading when it successfully completes.') return job def grade_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, server = _circuit_grading( circuit, lab_id, ex_id, is_submit=False, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_job( job_or_id: Union[IBMQJob, str], lab_id: str, ex_id: str ) -> bool: payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def grade_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False) if payload: print('Grading your answer. Please wait...') return grade_answer( payload, server + 'validate-answer' ) return False def submit_circuit( circuit: QuantumCircuit, lab_id: str, ex_id: str, max_qubits: Optional[int] = 28, min_cost: Optional[int] = None ) -> bool: payload, _ = _circuit_grading( circuit, lab_id, ex_id, is_submit=True, max_qubits=max_qubits, min_cost=min_cost ) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_job( job_or_id: IBMQJob, lab_id: str, ex_id: str, ) -> bool: payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def submit_number( answer: int, lab_id: str, ex_id: str ) -> bool: payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True) if payload: print('Submitting your answer. Please wait...') return submit_answer(payload) return False def get_problem_set( lab_id: str, ex_id: str, endpoint: str ) -> Tuple[Optional[int], Optional[Any]]: problem_set_response = None try: payload = {'question_id': get_question_id(lab_id, ex_id)} problem_set_response = send_request(endpoint, query=payload, method='GET') except Exception as err: print('Unable to obtain the problem set') if problem_set_response: status = problem_set_response.get('status') if status == 'valid': try: index = problem_set_response.get('index') value = json.loads(problem_set_response.get('value')) return index, value except Exception as err: print(f'Problem set could not be processed: {err}') else: cause = problem_set_response.get('cause') print(f'Problem set failed: {cause}') return None, None def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool: try: answer_response = send_request(endpoint, body=payload) status = answer_response.get('status', None) cause = answer_response.get('cause', None) score = cost if cost else answer_response.get('score', None) handle_grade_response(status, score=score, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def submit_answer(payload: dict) -> bool: try: access_token = get_access_token() baseurl = get_submission_endpoint() endpoint = urljoin(baseurl, './challenges/answers') submit_response = send_request( endpoint, body=payload, query={'access_token': access_token} ) status = submit_response.get('status', None) if status is None: status = submit_response.get('valid', None) cause = submit_response.get('cause', None) handle_submit_response(status, cause=cause) return status == 'valid' or status is True except Exception as err: print(f'Failed: {err}') return False def handle_grade_response( status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None ) -> None: if status == 'valid': print('\nCongratulations 🎉! Your answer is correct.') if score is not None: print(f'Your score is {score}.') elif status == 'invalid': print(f'\nOops 😕! {cause}') print('Please review your answer and try again.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete then try again.') else: print(f'Failed: {cause}') print('Unable to grade your answer.') def handle_submit_response( status: Union[str, bool], cause: Optional[str] = None ) -> None: if status == 'valid' or status is True: print('\nSuccess 🎉! Your answer has been submitted.') elif status == 'invalid' or status is False: print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}') print('Make sure your answer is correct and successfully graded before submitting.') elif status == 'notFinished': print(f'Job has not finished: {cause}') print(f'Please wait for the job to complete, grade it, and then try to submit again.') else: print(f'Failed: {cause}') print('Unable to submit your answer at this time.')
https://github.com/abhik-99/Qiskit-Summer-School
abhik-99
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """In this example, two-qubit Bell states are generated using the plugin. Additionally, a Quac noise model is applied. """ import math import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, execute from qiskit.visualization import plot_histogram from quac_qiskit import Quac from quac_qiskit.models import QuacNoiseModel def main(): circuit = QuantumCircuit(2, 2) circuit.u2(0, math.pi, 0) circuit.cx(0, 1) circuit.measure_all() circuit2 = QuantumCircuit(2, 2) circuit2.h(0) circuit2.cx(0, 1) circuit2.measure_all() print("Available QuaC backends:") print(Quac.backends()) simulator = Quac.get_backend('generic_counts_simulator', n_qubits=2, max_shots=10000, max_exp=75, basis_gates=['u1', 'u2', 'u3', 'cx']) # generic backends require extra parameters # Noise model with T1, T2, and measurement error terms noise_model = QuacNoiseModel( [1000, 1000], [50000, 50000], [np.eye(2), np.array([[0.95, 0.1], [0.05, 0.9]])], None ) # Execute the circuit on the QuaC simulator job = execute([circuit, circuit2], simulator, shots=1000, quac_noise_model=noise_model) print(job.result()) print(job.result().get_counts()) plot_histogram(job.result().get_counts(), title="Bell States Example") plt.show() if __name__ == '__main__': main()
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """This example demonstrates the applying measurement error to a GHZ circuit in the plugin. Additionally, the use of multiple classical registers is demonstrated. """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute from qiskit.visualization import plot_histogram from quac_qiskit import Quac from quac_qiskit.format import quac_time_qasm_transpiler import matplotlib.pyplot as plt if __name__ == '__main__': # Note: measurement errors are included by setting the "meas" option to True # Qubit P(0 | 1) P(1 | 0) # 0 0.10799999999999998 0.024 # 1 0.039000000000000035 0.004 # 2 0.026 0.009000000000000008 # 3 0.03400000000000003 0.005 # 4 0.135 0.019 print(Quac.backends()) simulator = Quac.get_backend('fake_bogota_counts_simulator', t1=False, t2=False, meas=True, zz=True) # Build the GhZ circuit over five qubits quantum_register = QuantumRegister(4, "qreg") classical_register1 = ClassicalRegister(2, "creg1") classical_register2 = ClassicalRegister(2, "creg2") ghz_circ = QuantumCircuit() ghz_circ.add_register(quantum_register) ghz_circ.add_register(classical_register1) ghz_circ.add_register(classical_register2) ghz_circ.h(0) for qubit in range(1, 4): ghz_circ.cx(qubit - 1, qubit) ghz_circ.measure(quantum_register[0], classical_register1[0]) ghz_circ.measure(quantum_register[1], classical_register1[1]) ghz_circ.measure(quantum_register[2], classical_register2[0]) ghz_circ.measure(quantum_register[3], classical_register2[1]) quac_job = execute(ghz_circ, simulator, shots=1000) # print(quac_job.status()) print(f"Frequency results: {quac_job.result().get_counts()}") plot_histogram(quac_job.result().get_counts()) plt.title("GHZ States") plt.show() print("TIMEQASM of GHZ Circuit:") print(quac_time_qasm_transpiler(ghz_circ, simulator))
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """A brief example showing the workflow of simulation with the plugin. """ import math import matplotlib.pyplot as plt from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram from quac_qiskit import Quac def main(): circuit1 = QuantumCircuit(5, 5) circuit2 = QuantumCircuit(5, 5) circuit3 = QuantumCircuit(1, 1) circuit1.h(0) circuit2.u2(0, math.pi, 0) circuit3.u3(math.pi/2, math.pi, 0, 0) circuit1.measure(0, 0) circuit2.measure(0, 0) circuit3.measure(0, 0) print("Available QuaC backends:") print(Quac.backends()) simulator = Quac.get_backend('fake_vigo_density_simulator', meas=True) # Execute the circuit on the QuaC simulator job1 = execute(circuit1, simulator) job2 = execute(circuit2, simulator) job3 = execute(circuit3, simulator) print(f"Hadamard counts: {job1.result().get_counts()}") print(f"U2 counts: {job2.result().get_counts()}") print(f"U3 counts: {job3.result().get_counts()}") plot_histogram(job1.result().get_counts()) plot_histogram((job2.result().get_counts())) plot_histogram(job3.result().get_counts()) plt.show() if __name__ == '__main__': main()
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """Demonstrates plugin noise model optimization abilities by recovering T1 noise from an ideal user-defined noise model. """ from qiskit import IBMQ from quac_qiskit import Quac from qiskit.test.mock import FakeBurlington from qiskit.ignis.characterization.coherence import t1_circuits, t2_circuits from quac_qiskit.optimization import * from quac_qiskit.models import QuacNoiseModel def main(): # Get backends IBMQ.load_account() provider = IBMQ.get_provider(hub="ibm-q-ornl", group="anl", project="chm168") backend = provider.get_backend("ibmq_burlington") plugin_backend = Quac.get_backend("fake_burlington_density_simulator", t1=True, t2=True, meas=False, zz=False) # Get calibration circuits hardware_properties = FakeBurlington().properties() num_gates = np.linspace(10, 500, 30, dtype='int') qubits = list(range(len(backend.properties().qubits))) t1_circs, t1_delay = t1_circuits(num_gates, hardware_properties.gate_length('id', [0]) * 1e9, qubits) t2_circs, t2_delay = t2_circuits((num_gates / 2).astype('int'), hardware_properties.gate_length('id', [0]) * 1e9, qubits) # Formulate real noise model real_noise_model = QuacNoiseModel( t1_times=[1234, 2431, 2323, 2222, 3454], t2_times=[12000, 14000, 14353, 20323, 30232] ) # Formulate initial guess noise model (only same order of magnitude) guess_noise_model = QuacNoiseModel( t1_times=[1000, 1000, 1000, 1000, 1000], t2_times=[10000, 10000, 10000, 10000, 10000] ) # Calculate calibration circuit reference results reference_job = execute(t1_circs + t2_circs, plugin_backend, quac_noise_model=real_noise_model, optimization_level=0) reference_result = reference_job.result() # Calculate optimized noise model new_noise_model = optimize_noise_model_ng( guess_noise_model=guess_noise_model, circuits=t1_circs + t2_circs, backend=plugin_backend, reference_result=reference_result, loss_function=angle_objective_function ) # Show original noise model and optimized noise model print(f"Original noise model: {real_noise_model}") print(f"New noise model: {new_noise_model}") if __name__ == '__main__': main()
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """This module contains functions for generating QASM with QuaC """ import re from qiskit import QuantumCircuit, assemble, transpile from qiskit.providers import BaseBackend from quac_qiskit.simulators import list_schedule_experiment def quac_time_qasm_transpiler(circuit: QuantumCircuit, backend: BaseBackend) -> str: """Converts a circuit of type QuantumCircuit to a string of TIMEQASM specification :param circuit: a QuantumCircuit (need not be transpiled) :param backend: a specific backend to generate the QASM for (for tranpsilation) :return: a string containing necessary QASM with times for each gate """ # Get original QASM transpiled_circuit = transpile(circuit, backend) original_qasm = transpiled_circuit.qasm() # Get body of original QASM start = 2 + len(circuit.qregs) + len(circuit.cregs) original_qasm_body = original_qasm.splitlines()[start:] # Formulate header qasm_modified = "TIMEQASM 1.0;\n" qasm_modified += "\n".join(original_qasm.splitlines()[1:start]) qasm_modified += "\n" # Schedule circuit qobj = assemble(transpiled_circuit, backend) qexp = qobj.experiments[0] qschedule = list_schedule_experiment(qexp, backend.properties()) # Formulate body for instruction, time in qschedule: # Note: ID was custom injected by the scheduler in this plugin qasm_modified += f"{original_qasm_body[instruction.id][:-1]} @{time};\n" return qasm_modified def quac_qasm_transpiler(qiskit_qasm: str) -> str: """Converts Qiskit-generated QASM instructions into QuaC-supported instructions :param qiskit_qasm: a string with a QASM program :return: a string with a modified QuaC-supported QASM program """ quac_qasm = "" for line in qiskit_qasm.splitlines(): # Remove certain types of unsupported operations if any(instruction in line for instruction in ["measure", "creg", "barrier", "id"]): continue # Reformat implicit multiplication by pi for pi_mult in re.findall("[0-9]pi", line): line = line.replace(pi_mult, pi_mult[0] + '*pi') # Evaluate and inject new parameters instruction_params = re.findall("\(.+\)", line) # only one parameter set per line if len(instruction_params) == 1: instruction_params = instruction_params[0] else: quac_qasm += line + "\n" continue # Evaluate pi-based parameter expressions evaluated_instruction_params = "(" for parameter in instruction_params[1:-1].split(","): parameter = parameter.replace("pi", "np.pi") evaluated_instruction_params += str(eval(parameter)) + "," evaluated_instruction_params = evaluated_instruction_params[:-1] + ")" line = line.replace(instruction_params, evaluated_instruction_params) # Add formatted QASM line to final result quac_qasm += line + "\n" return quac_qasm
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """This module contains objective functions for optimizing noise models. """ from typing import List import numpy as np from qiskit import QuantumCircuit, execute from qiskit.result import Result from quac_qiskit.stat import kl_dist_smoothing, discrete_one_samp_ks, get_vec_angle from quac_qiskit.format import counts_to_list from quac_qiskit.models import QuacNoiseModel def kl_div_sum(circuits: List[QuantumCircuit], simulation_result: Result, reference_result: Result) -> float: """Given a set of test circuits and a Qiskit Result object for a simulation and hardware, the sum of K-L divergence between circuit result distributions for each circuit is computed :param circuits: a list of QuantumCircuit objects :param simulation_result: a Qiskit Result object :param reference_result: a Qiskit Result object :return: a float representing the total K-L divergence between distributions of all circuits """ total_kl_div = 0 for circuit in circuits: simulation_counts = np.array(counts_to_list(simulation_result.get_counts(circuit))) simulation_dist = simulation_counts / simulation_counts.sum() # normalize if using counts simulator reference_counts = np.array(counts_to_list(reference_result.get_counts(circuit))) reference_dist = reference_counts / reference_counts.sum() # normalize if using counts simulator total_kl_div += kl_dist_smoothing(reference_dist, simulation_dist, 1e-5) return total_kl_div def ks_div_sum(circuits: List[QuantumCircuit], simulation_result: Result, reference_result: Result) -> float: """Given a set of test circuits and a Qiskit Result object for a simulation and hardware, the sum of K-S distance between circuit result distributions for each circuit is computed :param circuits: a list of QuantumCircuit objects :param simulation_result: a Qiskit Result object :param reference_result: a Qiskit Result object :return: a float representing the total K-S distance between distributions of all circuits """ total_ks_div = 0 for circuit in circuits: simulation_counts = np.array(counts_to_list(simulation_result.get_counts(circuit))) simulation_dist = simulation_counts / simulation_counts.sum() # normalize if using counts simulator reference_counts = np.array(counts_to_list(reference_result.get_counts(circuit))) reference_dist = reference_counts / reference_counts.sum() # normalize if using counts simulator total_ks_div += discrete_one_samp_ks(reference_dist, simulation_dist, 8000)[0] return total_ks_div def angle_div_sum(circuits: List[QuantumCircuit], simulation_result: Result, reference_result: Result) -> float: """Given a set of test circuits and a Qiskit Result object for a simulation and hardware, the sum of angle distance between circuit result distributions for each circuit is computed :param circuits: a list of QuantumCircuit objects :param simulation_result: a Qiskit Result object :param reference_result: a Qiskit Result object :return: a float representing the total angle distance between distributions of all circuits """ total_angle_div = 0 for ind, circuit in enumerate(circuits): simulation_counts = np.array(counts_to_list(simulation_result.get_counts(circuit))) simulation_dist = simulation_counts / simulation_counts.sum() # normalize if using counts simulator reference_counts = np.array(counts_to_list(reference_result.get_counts(circuit))) reference_dist = reference_counts / reference_counts.sum() # normalize if using counts simulator total_angle_div += get_vec_angle(reference_dist, simulation_dist) return total_angle_div def kl_objective_function(noise_model_array: np.array, *args): """An objective function to be minimized based on K-L divergence :param noise_model_array: a Numpy array generated via QuacNoiseModel.to_array() :param args: QuantumCircuit objects run, the simulator to run on, and the hardware results :return: a float representing the "loss" over the set of circuits """ circuits, backend, reference_result = args noise_model = QuacNoiseModel.from_array(noise_model_array, backend.configuration().n_qubits) simulation_result = execute(circuits, backend, shots=1, quac_noise_model=noise_model).result() return kl_div_sum(circuits, simulation_result, reference_result) def ks_objective_function(noise_model_array: np.array, *args): """An objective function to be minimized based on K-S distance :param noise_model_array: a Numpy array generated via QuacNoiseModel.to_array() :param args: QuantumCircuit objects run, the simulator to run on, and the hardware results :return: a float representing the "loss" over the set of circuits """ circuits, backend, reference_result = args noise_model = QuacNoiseModel.from_array(noise_model_array, backend.configuration().n_qubits) simulation_result = execute(circuits, backend, shots=1, quac_noise_model=noise_model).result() return ks_div_sum(circuits, simulation_result, reference_result) def angle_objective_function(noise_model_array: np.array, *args): """An objective function to be minimized based on angle divergence :param noise_model_array: a Numpy array generated via QuacNoiseModel.to_array() :param args: QuantumCircuit objects run, the simulator to run on, and the hardware results :return: a float representing the "loss" over the set of circuits """ circuits, backend, reference_result = args noise_model = QuacNoiseModel.from_array(noise_model_array, backend.configuration().n_qubits) simulation_result = execute(circuits, backend, shots=1, quac_noise_model=noise_model).result() return angle_div_sum(circuits, simulation_result, reference_result)
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """This module contains objective functions for optimizing noise models. """ from concurrent import futures from typing import List import numpy as np from typing import Callable from scipy import optimize import nevergrad as ng from qiskit import QuantumCircuit from qiskit.providers import BaseBackend from qiskit.result import Result from quac_qiskit.models import QuacNoiseModel def optimize_noise_model_ng(guess_noise_model: QuacNoiseModel, circuits: List[QuantumCircuit], backend: BaseBackend, reference_result: Result, loss_function: Callable[[np.array], float]) -> QuacNoiseModel: """Refines T1 and T2 noise parameters until the divergence between the probability distributions of a provided list of circuits simulated with the plugin and run with the hardware is minimized using the Nevergrad TwoPointsDE optimizer :param guess_noise_model: a QuacNoiseModel object as an initial ideal guess :param circuits: a list of QuantumCircuit objects for loss computation :param backend: the backend simulator on which circuits should be run :param reference_result: the Qiskit Result object from running circuits on real hardware :param loss_function: the loss function that should be used for optimization (i.e., kl_objective_function) :return: an optimized QuacNoiseModel object """ arr = ng.p.Array(init=guess_noise_model.to_array()) arr.set_bounds(0, float('inf')) param = ng.p.Instrumentation(arr, circuits, backend, reference_result) optimizer = ng.optimizers.TwoPointsDE(parametrization=param, budget=100, num_workers=5) print(optimizer.num_workers) with futures.ThreadPoolExecutor(max_workers=optimizer.num_workers) as executor: result = optimizer.minimize(loss_function, executor=executor, batch_mode=True, verbosity=2) print(result[0][0].value) return QuacNoiseModel.from_array(result[0][0].value, backend.configuration().n_qubits) def optimize_noise_model(guess_noise_model: QuacNoiseModel, circuits: List[QuantumCircuit], backend: BaseBackend, reference_result: Result, loss_function: Callable[[np.array], float]) -> QuacNoiseModel: """Refines T1 and T2 noise parameters until the divergence between the probability distributions of a provided list of circuits simulated with the plugin and run with the hardware is minimized :param guess_noise_model: a QuacNoiseModel object as an initial ideal guess :param circuits: a list of QuantumCircuit objects for loss computation :param backend: the backend simulator on which circuits should be run :param reference_result: the Qiskit Result object from running circuits on real hardware :param loss_function: the loss function that should be used for optimization (i.e., kl_objective_function) :return: an optimized QuacNoiseModel object """ result = optimize.minimize(loss_function, guess_noise_model.to_array(), args=(circuits, backend, reference_result), method="Nelder-Mead", options={"disp": True, "adaptive": True}) return result.x
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """This module contains test cases for ensuring formatting functionality is working properly in the library. """ import unittest from qiskit import execute, Aer from quac_qiskit import Quac from quac_qiskit.format import * class FormattingTestCase(unittest.TestCase): """Tests gate functionality """ def setUp(self): # Set up QuaC simulator and QASM simulator self.quac_simulator = Quac.get_backend("fake_yorktown_density_simulator") self.sv_simulator = Aer.get_backend("statevector_simulator") def test_counts_to_list(self): counts = { "00": 3, "01": 5, "10": 12, "11": 18 } self.assertEqual(counts_to_list(counts), [3, 5, 12, 18]) counts = { "01": 5, "10": 12, "11": 18 } self.assertEqual(counts_to_list(counts), [0, 5, 12, 18]) counts = { "00 00": 3, "10 01": 5, "01 10": 12, "11 11": 18 } self.assertEqual(counts_to_list(counts), [3, 0, 0, 0, 0, 0, 12, 0, 0, 5, 0, 0, 0, 0, 0, 18]) def test_counts_to_dist(self): counts = { "00": 3, "01": 5, "10": 12, "11": 18 } self.assertEqual(counts_to_dist(counts), [3 / 38, 5 / 38, 12 / 38, 18 / 38]) counts = { "01": 5, "10": 12, "11": 18 } self.assertEqual(counts_to_dist(counts), [0, 5 / 35, 12 / 35, 18 / 35]) def test_statevector_to_prob(self): for index in range(32): x_setup = list(bin(index)[2:].zfill(5)) x_setup.reverse() x_qubits = [q_ind for q_ind in range(5) if x_setup[q_ind] == '1'] qc = QuantumCircuit(5) for q_ind in x_qubits: qc.x(q_ind) qc.measure_all() qc_statevector = execute(qc, self.sv_simulator).result().get_statevector(qc) prob_list = statevector_to_probabilities(qc_statevector) self.assertEqual(prob_list, [int(element == index) for element in range(32)]) def test_aggregate_counts(self): counts1 = {"00": 10, "10": 33} counts2 = {"01": 87, "00": 20} counts3 = {"00": 1, "11": 43} all_counts = [counts1, counts2, counts3] keys = ["00", "01", "10", "11"] agg_counts = aggregate_counts_results(all_counts, keys) self.assertEqual(agg_counts, {"00": 31, "01": 87, "10": 33, "11": 43}) if __name__ == '__main__': unittest.main()
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """This module contains test cases for ensuring gate addition and functionality is working properly in the library. """ import unittest from qiskit import execute, Aer from qiskit.circuit.random import random_circuit from quac_qiskit import Quac from quac_qiskit.format import * from quac_qiskit.models import QuacNoiseModel from quac_qiskit.stat import * class GateAdditionTestCase(unittest.TestCase): """Tests gate functionality """ def setUp(self): # Set up QuaC simulator and QASM simulator self.quac_simulator = Quac.get_backend("fake_yorktown_density_simulator") self.qasm_simulator = Aer.get_backend("statevector_simulator") def test_hadamard_gate(self): test_circuit = QuantumCircuit(1) test_circuit.h(0) test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [0.5, 0.5]), 5) def test_id_gate(self): test_circuit = QuantumCircuit(1) test_circuit.id(0) test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [1, 0]), 5) def test_x_gate(self): test_circuit = QuantumCircuit(1) test_circuit.x(0) test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [0, 1]), 5) def test_y_gate(self): test_circuit = QuantumCircuit(1) test_circuit.y(0) test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [0, 1]), 5) test_circuit = QuantumCircuit(1) test_circuit.x(0) test_circuit.y(0) test_circuit.y(0) test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [0, 1]), 5) def test_z_gate(self): test_circuit = QuantumCircuit(1) test_circuit.z(0) test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [1, 0]), 5) def test_rx_gate(self): test_circuit = QuantumCircuit(1) test_circuit.rx(np.pi, 0) test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [0, 1]), 5) test_circuit = QuantumCircuit(1) test_circuit.rx(np.pi / 2, 0) # Hadamard gate equivalent test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [0.5, 0.5]), 5) def test_ry_gate(self): test_circuit = QuantumCircuit(1) test_circuit.ry(np.pi, 0) test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [0, 1]), 5) test_circuit = QuantumCircuit(1) test_circuit.ry(np.pi / 2, 0) # Hadamard gate equivalent test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [0.5, 0.5]), 5) def test_rz_gate(self): test_circuit = QuantumCircuit(1) test_circuit.rz(np.pi, 0) test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLess(get_vec_angle(outcome_list, [1, 0]), 5) # should leave state alone test_circuit = QuantumCircuit(1) test_circuit.h(0) test_circuit.rz(np.pi, 0) # should not affect probabilities test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLess(get_vec_angle(outcome_list, [0.5, 0.5]), 5) def test_u1_gate(self): test_circuit = QuantumCircuit(1) test_circuit.u1(math.pi, 0) # same as Z gate test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLessEqual(get_vec_angle(outcome_list, [1, 0]), 5) def test_u2_gate(self): test_circuit = QuantumCircuit(1) test_circuit.u2(0, np.pi, 0) # behaves like a Hadamard gate test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLess(get_vec_angle(outcome_list, [0.5, 0.5]), 5) def test_u3_gate(self): test_circuit = QuantumCircuit(1) test_circuit.u3(np.pi / 2, 0, np.pi, 0) # behaves like a Hadamard gate test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLess(get_vec_angle(outcome_list, [0.5, 0.5]), 5) def test_cnot_gate(self): test_circuit = QuantumCircuit(2) test_circuit.h(0) test_circuit.cx(0, 1) test_circuit.measure_all() outcome_dist = execute(test_circuit, self.quac_simulator, shots=1000) outcome_list = counts_to_list(outcome_dist.result().get_counts()) self.assertLess(get_vec_angle(outcome_list, [0.5, 0, 0, 0.5]), 5) def test_random_circuits(self): for circuit_index in range(1000): num_qubits = random.randrange(1, 6) # Generate random circuit and transpile it to run on specific hardware random_circ = transpile(random_circuit(num_qubits, 5, measure=False), self.quac_simulator) random_circ.measure_all() # Get QuaC-calculated probabilities in a list plugin_probs = counts_to_dist( execute(random_circ, self.quac_simulator, shots=1, optimization_level=0, quac_noise_model=QuacNoiseModel.get_noiseless_model(5)).result().get_counts() ) # Get Qiskit-calculated probabilities in a list random_circ.remove_final_measurements() # avoid collapsing state vector qiskit_sv = execute(random_circ, self.qasm_simulator, shots=8000, optimization_level=0, ).result().get_statevector(random_circ) # qiskit_probs = qiskit_statevector_to_probabilities(qiskit_sv, 5) qiskit_probs = statevector_to_probabilities(qiskit_sv) # Calculate divergence of Qiskit and QuaC predictions difference_angle = get_vec_angle(qiskit_probs, plugin_probs) self.assertLess(difference_angle, 1e-5) if __name__ == '__main__': unittest.main()
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """This module contains test cases for ensuring gate addition and functionality is working properly in the library. """ import random import unittest import numpy as np from qiskit import execute, QuantumCircuit, Aer, transpile from qiskit.circuit.random import random_circuit from qiskit.ignis.characterization import t1_circuits, T1Fitter, t2_circuits, T2Fitter, zz_circuits, ZZFitter from qiskit.ignis.mitigation import TensoredMeasFitter from qiskit.test.mock import FakeYorktown from quac_qiskit import Quac from quac_qiskit.models import QuacNoiseModel class NoiseModelTestCase(unittest.TestCase): """Tests QuaC noise model functionality by recovering model parameters with Qiskit fitters """ def setUp(self): # Set up QuaC simulators self.quac_sim = Quac.get_backend("fake_yorktown_density_simulator", t1=True, t2=False, meas=False, zz=False) self.qasm_sim = Aer.get_backend("qasm_simulator") def test_t1_recovery(self): cal_circs, t1_delay = t1_circuits(np.linspace(10, 900, 10, dtype='int'), FakeYorktown().properties().gate_length('id', [0]) * 1e9, [0, 1, 2, 3, 4]) true_t1 = [1000 * (1 + random.random()) for _ in range(5)] t1_noise_model = QuacNoiseModel( true_t1, [float('inf') for _ in range(5)] ) t1_result = execute(cal_circs, self.quac_sim, quac_noise_model=t1_noise_model).result() t1_fit = T1Fitter(t1_result, t1_delay, [0, 1, 2, 3, 4], fit_p0=[1, 1000, 0], fit_bounds=([0, 0, -1], [2, 1e10, 1]), time_unit="nano-seconds") derived_t1 = t1_fit.time() max_diff = abs(np.array(derived_t1) - np.array(true_t1)).max() self.assertLess(max_diff, 1e-3) def test_t2_recovery(self): cal_circs, t2_delay = t2_circuits(np.floor(np.linspace(10, 900, 10, dtype='int') / 2).astype('int'), FakeYorktown().properties().gate_length('id', [0]) * 1e9, [0, 1, 2, 3, 4]) true_t2 = [10000 * (1 + random.random()) for _ in range(5)] t2_noise_model = QuacNoiseModel( [float('inf') for _ in range(5)], true_t2 ) t2_result = execute(cal_circs, self.quac_sim, quac_noise_model=t2_noise_model).result() t2_fit = T2Fitter(t2_result, t2_delay, [0, 1, 2, 3, 4], fit_p0=[1, 10000, 0], fit_bounds=([0, 0, -1], [2, 1e10, 1]), time_unit="nano-seconds") derived_t2 = t2_fit.time() max_diff = abs(np.array(derived_t2) - np.array(true_t2)).max() self.assertLess(max_diff, 1e-3) def test_meas_recovery(self): qubits = list(range(5)) # we are working with a 5-qubit machine # Develop random measurement matrices for each qubit of the form # [ P(0|0) P(0|1) ] # [ P(1|0) P(1|1) ] meas_mats = [] for _ in qubits: stay_zero = random.random() stay_one = random.random() meas_mats.append( np.array([ [stay_zero, 1 - stay_one], [1 - stay_zero, stay_one] ]) ) # Encode measurement matrices in QuacNoiseModel object meas_noise_model = QuacNoiseModel( [float('inf') for _ in qubits], [float('inf') for _ in qubits], meas_mats ) # Develop Quac-specfic measurement matrix calibration circuits # (cannot run circuits with 0 gates in Quac backends) empty_circ = QuantumCircuit(len(qubits)) for i in qubits: empty_circ.id(i) empty_circ.measure_all() empty_circ.name = f"cal_{''.join(['0' for _ in qubits])}" full_circ = QuantumCircuit(len(qubits)) for i in qubits: full_circ.x(i) full_circ.measure_all() full_circ.name = f"cal_{''.join(['1' for _ in qubits])}" meas_cal_circs = [empty_circ, full_circ] # Recover measurement matrices with Qiskit fitter meas_result = execute(meas_cal_circs, self.quac_sim, quac_noise_model=meas_noise_model).result() meas_fit = TensoredMeasFitter(meas_result, [[i] for i in qubits]) meas_matrices = meas_fit.cal_matrices max_diff = max([(meas_matrices[ind] - meas_mats[ind]).max() for ind in qubits]) self.assertLess(max_diff, 1e-10) def test_zz_recovery(self): qubits = list(range(5)) num_of_gates = np.arange(0, 600, 30) gate_time = FakeYorktown().properties().gate_length('id', [0]) * 1e9 # Develop zz-only noise model zz_dict = {} for qubit1 in qubits: for qubit2 in qubits: if qubit1 < qubit2: zz_dict[(qubit1, qubit2)] = (1 + random.random() * 2) * 1e-5 zz_noise_model = QuacNoiseModel( [float('inf') for _ in qubits], [float('inf') for _ in qubits], [np.eye(2) for _ in qubits], zz_dict ) for qubit1 in qubits: for qubit2 in qubits: if qubit1 < qubit2: print(qubit1) print(qubit2) zz_circs, xdata, osc_freq = zz_circuits(num_of_gates, gate_time, [qubit1], [qubit2], nosc=2) zz_result = execute(zz_circs, self.quac_sim, quac_noise_model=zz_noise_model, shots=1).result() fit = ZZFitter(zz_result, xdata, [qubit1], [qubit2], fit_p0=[1, osc_freq, -np.pi / 20, 0], fit_bounds=([-0.5, 0, -np.pi, -0.5], [1.5, 1e10, np.pi, 1.5]), time_unit="nano-seconds" ) self.assertLess(abs(abs(fit.ZZ_rate()[0]) - zz_dict[(qubit1, qubit2)]), 1e-10) def test_noise_model_from_backend(self): yorktown_quac_noise_model_t1t2 = QuacNoiseModel.from_backend(FakeYorktown(), t1=True, t2=True, meas=False, zz=False) yorktown_quac_noise_model_meas = QuacNoiseModel.from_backend(FakeYorktown(), t1=False, t2=False, meas=True, zz=False) qubits = list(range(5)) cal_circs, t1_delay = t1_circuits(np.linspace(10, 900, 10, dtype='int'), FakeYorktown().properties().gate_length('id', [0]) * 1e9, qubits) true_t1 = [FakeYorktown().properties().t1(q) * 1e9 for q in qubits] t1_result = execute(cal_circs, self.quac_sim, quac_noise_model=yorktown_quac_noise_model_t1t2, optimization_level=0).result() t1_fit = T1Fitter(t1_result, t1_delay, qubits, fit_p0=[1, 10000, 0], fit_bounds=([0, 0, -1], [2, 1e10, 1]), time_unit="nano-seconds") derived_t1 = t1_fit.time() max_diff = abs(np.array(derived_t1) - np.array(true_t1)).max() self.assertLess(max_diff, 1e-2) # Test T2 recovery cal_circs, t2_delay = t2_circuits(np.floor(np.linspace(10, 900, 10, dtype='int') / 2).astype('int'), FakeYorktown().properties().gate_length('id', [0]) * 1e9, qubits) true_t2 = [FakeYorktown().properties().t2(q) * 1e9 for q in qubits] t2_result = execute(cal_circs, self.quac_sim, quac_noise_model=yorktown_quac_noise_model_t1t2).result() t2_fit = T2Fitter(t2_result, t2_delay, qubits, fit_p0=[1, 10000, 0], fit_bounds=([0, 0, -1], [2, 1e10, 1]), time_unit="nano-seconds") derived_t2 = t2_fit.time() max_diff = abs(np.array(derived_t2) - np.array(true_t2)).max() self.assertLess(max_diff, 1e-2) # Recover measurement error meas_mats = [] for q in qubits: flip_1_to_0 = FakeYorktown().properties().qubit_property(q, "prob_meas0_prep1")[0] flip_0_to_1 = FakeYorktown().properties().qubit_property(q, "prob_meas1_prep0")[0] meas_mats.append( np.array([ [1 - flip_0_to_1, flip_1_to_0], [flip_0_to_1, 1 - flip_1_to_0] ]) ) # Develop Quac-specfic measurement matrix calibration circuits # (cannot run circuits with 0 gates in Quac backends) empty_circ = QuantumCircuit(len(qubits)) for i in qubits: empty_circ.id(i) empty_circ.measure_all() empty_circ.name = f"cal_{''.join(['0' for _ in qubits])}" full_circ = QuantumCircuit(len(qubits)) for i in qubits: full_circ.x(i) full_circ.measure_all() full_circ.name = f"cal_{''.join(['1' for _ in qubits])}" meas_cal_circs = [empty_circ, full_circ] # Recover measurement matrices with Qiskit fitter meas_result = execute(meas_cal_circs, self.quac_sim, quac_noise_model=yorktown_quac_noise_model_meas).result() meas_fit = TensoredMeasFitter(meas_result, [[i] for i in qubits]) meas_matrices = meas_fit.cal_matrices max_diff = max([(meas_matrices[ind] - meas_mats[ind]).max() for ind in qubits]) self.assertLess(max_diff, 1e-10) def test_noise_model_to_and_from_array(self): random_circs = [random_circuit(5, 5, measure=True) for _ in range(100)] true_t1 = [1000 * (1 + random.random()) for _ in range(5)] true_t2 = [10000 * (1 + random.random()) for _ in range(5)] # Develop random measurement matrices for each qubit of the form # [ P(0|0) P(0|1) ] # [ P(1|0) P(1|1) ] meas_mats = [] for _ in range(5): stay_zero = random.random() stay_one = random.random() meas_mats.append( np.array([ [stay_zero, 1 - stay_one], [1 - stay_zero, stay_one] ]) ) zz = {} for qubit1 in range(5): for qubit2 in range(5): if qubit1 != qubit2: zz[(qubit1, qubit2)] = random.randrange(1, 10) * 1e-5 random_quac_noise_model = QuacNoiseModel( true_t1, true_t2, [meas_mats[0] for _ in range(5)], None ) recovered_quac_noise_model = QuacNoiseModel.from_array(random_quac_noise_model.to_array(), 5) for circ in random_circs: transpiled_circ = transpile(circ, self.quac_sim, optimization_level=0) dist_original = execute(transpiled_circ, self.quac_sim, quac_noise_model=random_quac_noise_model, optimization_level=0).result().get_counts() dist_recovered = execute(transpiled_circ, self.quac_sim, quac_noise_model=recovered_quac_noise_model, optimization_level=0).result().get_counts() self.assertEqual(dist_original, dist_recovered) if __name__ == '__main__': unittest.main()
https://github.com/0tt3r/QuaC-qiskit
0tt3r
# -*- coding: utf-8 -*- """This module contains test cases for ensuring gate scheduling is working properly in the library. """ import unittest from qiskit import QuantumCircuit, assemble, transpile from qiskit.test.mock import FakeBogota from quac_qiskit import Quac from quac_qiskit.simulators import list_schedule_experiment class ScheduleTestCase(unittest.TestCase): """Tests QuaC noise model functionality by recovering model parameters with Qiskit fitters """ def setUp(self): # Set up QuaC simulators self.quac_sim = Quac.get_backend("fake_yorktown_density_simulator", t1=True, t2=False, meas=False, zz=False) def test_list_schedule(self): example_circ = QuantumCircuit(5) example_circ.h(0) example_circ.x(2) example_circ.x(0) example_circ.cx(0, 2) example_circ.y(3) example_circ.y(2) example_circ.measure_all() qobj = assemble(transpile(example_circ, FakeBogota()), backend=FakeBogota()) list_scheduled_circ = list_schedule_experiment(qobj.experiments[0], FakeBogota().properties()) expected_gates = ['u3', 'u3', 'u2', 'cx', 'cx', 'cx', 'cx', 'u3', 'barrier', 'measure', 'measure', 'measure', 'measure', 'measure'] expected_times = [1, 1, 1, 72.11111111111111, 513.0, 918.3333333333333, 1359.2222222222222, 1693.4444444444443, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554, 1764.5555555555554] index = 0 for gate, time in list_scheduled_circ: self.assertEqual(gate.name, expected_gates[index]) self.assertEqual(time, expected_times[index]) index += 1 if __name__ == '__main__': unittest.main()
https://github.com/kyungzzu/Qiskit-Hackathon2022
kyungzzu
# %grover search # %matplotlib inline from qiskit import * from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.circuit.library import ZGate from qiskit.circuit.library import Permutation from qiskit.circuit import * # provider = IBMQ.load_account() from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector def p_sbox_light_r(cir, b): cir.cx(b[2], b[1]) cir.ccx(b[1], b[2], b[3]) cir.ccx(b[3], b[1], b[2]) cir.ccx(b[0], b[2], b[1]) cir.cx(b[3], b[2]) cir.x(b[3]) cir.cx(b[1], b[2]) cir.cx(b[3], b[0]) cir.cx(b[0], b[1]) cir.x(b[0]) cir.ccx(b[1], b[2], b[3]) cir.swap(b[1], b[2]) cir.swap(b[2], b[3]) cir.cx(b[6], b[5]) cir.ccx(b[5], b[6], b[7]) cir.ccx(b[7], b[5], b[6]) cir.ccx(b[4], b[6], b[5]) cir.cx(b[7], b[6]) cir.x(b[7]) cir.cx(b[5], b[6]) cir.cx(b[7], b[4]) cir.cx(b[4], b[5]) cir.x(b[4]) cir.ccx(b[5], b[6], b[7]) # cir += Permutation(num_qubits = 8,pattern = [0, 2, 3, 1, 4, 6, 7, 5]) cir.swap(b[5], b[6]) cir.swap(b[6], b[7]) def p_sbox_inverse(cir, b): # cir += Permutation(num_qubits = 8, pattern = [0, 1, 2, 3, 4, 5, 6, 7]) cir.swap(b[6], b[7]) cir.swap(b[5], b[6]) cir.ccx(b[5], b[6], b[7]) cir.x(b[4]) cir.cx(b[4], b[5]) cir.cx(b[7], b[4]) cir.cx(b[5], b[6]) cir.x(b[7]) cir.cx(b[7], b[6]) cir.ccx(b[4], b[6], b[5]) cir.ccx(b[7], b[5], b[6]) cir.ccx(b[5], b[6], b[7]) cir.cx(b[6], b[5]) cir.swap(b[2], b[3]) cir.swap(b[1], b[2]) cir.ccx(b[1], b[2], b[3]) cir.x(b[0]) cir.cx(b[0], b[1]) cir.cx(b[3], b[0]) cir.cx(b[1], b[2]) cir.x(b[3]) cir.cx(b[3], b[2]) cir.ccx(b[0], b[2], b[1]) cir.ccx(b[3], b[1], b[2]) cir.ccx(b[1], b[2], b[3]) cir.cx(b[2], b[1]) def permutation(cir, m): # cir += Permutation(num_qubits = 8, pattern = [0, 4, 1, 5, 2, 6, 3, 7]) cir.swap(m[1], m[4]) cir.swap(m[2], m[4]) cir.swap(m[3], m[5]) cir.swap(m[5], m[6]) def permutation_inverse(cir, m): # cir += Permutation(num_qubits = 8, pattern = [0, 1, 2, 3, 4, 5, 6, 7]) cir.swap(m[5], m[6]) cir.swap(m[3], m[5]) cir.swap(m[2], m[4]) cir.swap(m[1], m[4]) def Encrypt(cir, m): p_sbox_light_r(cir, m) permutation(cir, m) p_sbox_light_r(cir, m) permutation(cir, m) p_sbox_light_r(cir, m) permutation(cir, m) p_sbox_light_r(cir, m) permutation(cir, m) def Decrypt(cir, m): permutation_inverse p_sbox_inverse(cir, m) permutation_inverse p_sbox_inverse(cir, m) permutation_inverse p_sbox_inverse(cir, m) permutation_inverse p_sbox_inverse(cir, m) # def DC_check(): # p = QuantumRegister(8) # p_prime = QuantumRegister(8) # res = ClassicalRegister(8) # res_prime = ClassicalRegister(8) # circuit = QuantumCircuit(p,p_prime, res_prime) # # n = 4 # # 01100001 # circuit.x(p[1]) # circuit.x(p[2]) # # circuit.x(p[4]) # # circuit.x(p[5]) # circuit.x(p[7]) # circuit.cx(p[0], p_prime[0]) # circuit.cx(p[1], p_prime[1]) # circuit.cx(p[2], p_prime[2]) # circuit.cx(p[3], p_prime[3]) # circuit.cx(p[4], p_prime[4]) # circuit.cx(p[5], p_prime[5]) # circuit.cx(p[6], p_prime[6]) # circuit.cx(p[7], p_prime[7]) # #delta = (01100101) # circuit.x(p_prime[1]) # circuit.x(p_prime[2]) # circuit.x(p_prime[5]) # circuit.x(p_prime[7]) # Encrypt(circuit, p) # Encrypt(circuit, p_prime) # circuit.cx(p[0], p_prime[0]) # circuit.cx(p[1], p_prime[1]) # circuit.cx(p[2], p_prime[2]) # circuit.cx(p[3], p_prime[3]) # circuit.cx(p[4], p_prime[4]) # circuit.cx(p[5], p_prime[5]) # circuit.cx(p[6], p_prime[6]) # circuit.cx(p[7], p_prime[7]) # circuit.measure([p_prime[0],p_prime[1],p_prime[2],p_prime[3],p_prime[4],p_prime[5],p_prime[6],p_prime[7]],[res_prime[0], res_prime[1], res_prime[2], res_prime[3], res_prime[4], res_prime[5], res_prime[6], res_prime[7]]) # backend = BasicAer.get_backend('qasm_simulator') # the device to run on # result = execute(circuit, backend, shots=1).result() # counts = result.get_counts(circuit) # print(counts) # DC_check() # #(01110011) def DC(): p = QuantumRegister(8) p_prime = QuantumRegister(8) res = ClassicalRegister(8) circuit = QuantumCircuit(p,p_prime,res) n = 4 #iteration number circuit.h(p[0:8]) for k in range(n): #oracle circuit.cx(p[0],p_prime[0]) circuit.cx(p[1],p_prime[1]) circuit.cx(p[2],p_prime[2]) circuit.cx(p[3],p_prime[3]) circuit.cx(p[4],p_prime[4]) circuit.cx(p[5],p_prime[5]) circuit.cx(p[6],p_prime[6]) circuit.cx(p[7],p_prime[7]) #delta = (01100101) circuit.x(p_prime[1]) circuit.x(p_prime[2]) circuit.x(p_prime[5]) circuit.x(p_prime[7]) Encrypt(circuit, p) Encrypt(circuit, p_prime) #Compute after s-box Delta circuit.cx(p[0],p_prime[0]) circuit.cx(p[1],p_prime[1]) circuit.cx(p[2],p_prime[2]) circuit.cx(p[3],p_prime[3]) circuit.cx(p[4],p_prime[4]) circuit.cx(p[5],p_prime[5]) circuit.cx(p[6],p_prime[6]) circuit.cx(p[7],p_prime[7]) #Check Delta = (01110011) circuit.x(p_prime[0]) circuit.x(p_prime[4]) circuit.x(p_prime[5]) circuit.append(ZGate().control(7), [p_prime[0],p_prime[1], p_prime[2],p_prime[3], p_prime[4],p_prime[5], p_prime[6],p_prime[7]]) #inverse circuit.x(p_prime[5]) circuit.x(p_prime[4]) circuit.x(p_prime[0]) circuit.cx(p[7],p_prime[7]) circuit.cx(p[6],p_prime[6]) circuit.cx(p[5],p_prime[5]) circuit.cx(p[4],p_prime[4]) circuit.cx(p[3],p_prime[3]) circuit.cx(p[2],p_prime[2]) circuit.cx(p[1],p_prime[1]) circuit.cx(p[0],p_prime[0]) Decrypt(circuit, p_prime) Decrypt(circuit, p) circuit.x(p_prime[7]) circuit.x(p_prime[5]) circuit.x(p_prime[2]) circuit.x(p_prime[1]) circuit.cx(p[7],p_prime[7]) circuit.cx(p[6],p_prime[6]) circuit.cx(p[5],p_prime[5]) circuit.cx(p[4],p_prime[4]) circuit.cx(p[3],p_prime[3]) circuit.cx(p[2],p_prime[2]) circuit.cx(p[1],p_prime[1]) circuit.cx(p[0],p_prime[0]) #diffusion circuit.h(p[0:8]) circuit.x(p[0:8]) circuit.append(ZGate().control(7), [p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]]) circuit.x(p[0:8]) circuit.h(p[0:8]) circuit.measure([p[0],p[1], p[2],p[3], p[4],p[5], p[6],p[7]], [res[0], res[1], res[2], res[3], res[4], res[5], res[6], res[7]]) backend = BasicAer.get_backend('qasm_simulator') # the device to run on result = execute(circuit, backend, shots=1).result() counts = result.get_counts(circuit) print(counts) DC()
https://github.com/askolik/quantum_gym_qiskit
askolik
import copy import random from collections import deque, namedtuple import numpy as np import matplotlib.pyplot as plt import gym import torch from qiskit import Aer from qiskit import QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.circuit import Parameter from qiskit.opflow import StateFn, PauliSumOp, ListOp from qiskit_machine_learning.neural_networks import OpflowQNN from qiskit_machine_learning.connectors import TorchConnector from torch import Tensor from torch.nn import Parameter as TorchParameter from torch.optim import Adam def build_quantum_model(n_qubits, n_layers): circuit = QuantumCircuit(n_qubits) data_params = [Parameter(f'x_{i}') for i in range(n_qubits)] data_weight_params = [Parameter(f'd_{i}') for i in range(n_qubits)] trainable_params = data_weight_params for layer in range(n_layers): for qubit in range(n_qubits): circuit.rx(data_params[qubit] * data_weight_params[qubit], qubit) var_param_y = Parameter(f't_y_{layer}_{qubit}') var_param_z = Parameter(f't_z_{layer}_{qubit}') trainable_params += [var_param_y, var_param_z] circuit.ry(var_param_y, qubit) circuit.rz(var_param_z, qubit) for qubit in range(n_qubits): circuit.cz(qubit, (qubit+1) % n_qubits) circuit.barrier() for qubit in range(n_qubits): var_param_y = Parameter(f't_y_{n_layers}_{qubit}') var_param_z = Parameter(f't_z_{n_layers}_{qubit}') trainable_params += [var_param_y, var_param_z] circuit.ry(var_param_y, qubit) circuit.rz(var_param_z, qubit) # circuit.draw(output='mpl', filename='my_circuit.png') print(circuit) return circuit, trainable_params, data_params def build_readout_ops(agent): action_left = PauliSumOp.from_list([('ZZII', 1.0)]) action_right = PauliSumOp.from_list([('IIZZ', 1.0)]) readout_op = ListOp([ ~StateFn(action_left) @ StateFn(agent), ~StateFn(action_right) @ StateFn(agent) ]) return readout_op def compute_q_vals(states, model, observable_weights, grad=True): scaled_states = [] for state in states: scaled_states.append([np.arctan(s) for s in state]) states_tensor = Tensor(states) if grad: print('batch size:', len(states_tensor)) res = model(states_tensor) else: with torch.no_grad(): res = model(states_tensor) q_vals = (res + 1) / 2 q_vals[:, 0] *= observable_weights[0] q_vals[:, 1] *= observable_weights[1] # print("Q0", q_vals[:, 0], observable_weights[0]) # print("Q1", q_vals[:, 1], observable_weights[1]) return q_vals def train_step( memory, model, target_model, batch_size, observable_weights, target_observable_weights, model_optimizer, observables_optimizer, loss, gamma): model_optimizer.zero_grad() observables_optimizer.zero_grad() transitions = random.sample(memory, batch_size) batch_memories = Transition(*zip(*transitions)) batch_states = batch_memories.state batch_actions = batch_memories.action batch_next_states = batch_memories.next_state batch_done = batch_memories.done batch_rewards = np.ones(batch_size) action_masks = [] one_hot_actions = {0: [1, 0], 1: [0, 1]} for action in batch_actions: action_masks.append(one_hot_actions[action]) q_vals = compute_q_vals( batch_states, model, observable_weights) q_vals_next = compute_q_vals( batch_next_states, target_model, target_observable_weights, grad=False) target_q_vals = torch.Tensor(batch_rewards) + torch.Tensor( np.ones(batch_size) * gamma) * torch.max(q_vals_next, 1).values * (1 - torch.Tensor(batch_done)) reduced_q_vals = torch.sum(q_vals * torch.Tensor(action_masks), dim=1) error = loss(reduced_q_vals, target_q_vals) error.backward() model_optimizer.step() observables_optimizer.step() # set up Qiskit backend and Gym backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) env = gym.make("CartPole-v0") # set hyperparameters for deep Q-learning n_qubits = 4 n_layers = 5 batch_size = 16 gamma = 0.99 # Q-learning discount factor epsilon = 1.0 # epsilon greedy policy initial value epsilon_min = 0.01 # minimum value of epsilon epsilon_decay = 0.99 # decay rate of epsilon n_episodes = 3000 batch_size = 16 update_qnet_after = 1 # agent update interval update_target_after = 1 # target network update interval # set up replay memory Transition = namedtuple('Transition', ( 'state', 'action', 'next_state', 'done')) max_memory_len = 10000 replay_memory = deque(maxlen=max_memory_len) grad_method ='param_shift' # grad_method ='fin_diff' # set up model agent, params, data_params = build_quantum_model(n_qubits, n_layers) observable_weights = TorchParameter(Tensor([1, 1])) readout_op = build_readout_ops(agent) qnn = OpflowQNN( readout_op, data_params, params, quantum_instance=quantum_instance) model = TorchConnector(qnn) # set up target model that is used to compute target Q-values # (not trained, only updated with Q-model's parameters at fixed intervals) target_agent, target_params, target_data_params = build_quantum_model(n_qubits, n_layers) target_observable_weights = Tensor([1, 1]) target_readout_op = build_readout_ops(target_agent) target_qnn = OpflowQNN( target_readout_op, target_data_params, target_params, quantum_instance=quantum_instance) target_model = TorchConnector(target_qnn) target_model.load_state_dict(model.state_dict()) # set up optimizers model_optimizer = Adam(model.parameters(), lr=0.001) observables_optimizer = Adam([observable_weights], lr=0.1) loss = torch.nn.SmoothL1Loss() episode_rewards = [0] for episode in range(n_episodes): episode_reward = 0 state = env.reset() for time_step in range(200): # choose action based on epsilon greedy policy if random.random() > epsilon: with torch.no_grad(): q_vals = compute_q_vals([state], model, observable_weights) action = int(torch.argmax(q_vals).numpy()) print("\tagent chose action") else: action = np.random.choice(2) # take step in environment and collect reward next_state, reward, done, _ = env.step(action) episode_reward += 1 # store transition in memory (without reward as it is always 1) replay_memory.append(Transition(state, action, next_state, int(done))) # perform one step of parameter updates if len(replay_memory) > batch_size and time_step % update_qnet_after == 0: train_step( replay_memory, model, target_model, batch_size, observable_weights, target_observable_weights, model_optimizer, observables_optimizer, loss, gamma) # update target model parameters if time_step % update_target_after == 0: with torch.no_grad(): target_model.load_state_dict(model.state_dict()) target_observable_weights = copy.deepcopy(observable_weights.data) if done: break episode_rewards.append(episode_reward) epsilon = max(epsilon_min, epsilon * epsilon_decay) print(f'Episode {episode}, episode reward: {episode_reward}, average reward: {np.mean(episode_rewards[-100:])}') plt.plot(episode_rewards) plt.ylabel("Score") plt.xlabel("Episode") plt.show()
https://github.com/askolik/quantum_gym_qiskit
askolik
import copy import random from collections import deque, namedtuple import numpy as np import matplotlib.pyplot as plt import gym import torch from qiskit import Aer from qiskit import QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.circuit import Parameter from qiskit.opflow import StateFn, PauliSumOp, ListOp, AerPauliExpectation, Gradient from qiskit_machine_learning.neural_networks import OpflowQNN from qiskit_machine_learning.connectors import TorchConnector from torch import Tensor from torch.nn import Parameter as TorchParameter from torch.optim import Adam from time import time def build_quantum_model(n_qubits, n_layers, is_target_model=False): name_prefix = '' if is_target_model: name_prefix = 'target_' circuit = QuantumCircuit(n_qubits) data_params = [ Parameter(f'{name_prefix}x_{i}_{j}') for i in range(n_qubits) for j in range(n_layers)] data_params_copy = copy.deepcopy(data_params)[::-1] data_weight_params = [ Parameter(f'{name_prefix}d_{i}_{j}') for i in range(n_qubits) for j in range(n_layers)] trainable_params = [] for layer in range(n_layers): for qubit in range(n_qubits): circuit.rx(data_params.pop(), qubit) var_param_y = Parameter(f't_y_{layer}_{qubit}') var_param_z = Parameter(f't_z_{layer}_{qubit}') trainable_params += [var_param_y, var_param_z] circuit.ry(var_param_y, qubit) circuit.rz(var_param_z, qubit) for qubit in range(n_qubits): circuit.cz(qubit, (qubit+1) % n_qubits) circuit.barrier() # print(circuit) # exit() return circuit, trainable_params, data_params_copy, data_weight_params def build_readout_ops(agent): action_left = PauliSumOp.from_list([('ZZII', 1.0)]) action_right = PauliSumOp.from_list([('IIZZ', 1.0)]) readout_op = ListOp([ ~StateFn(action_left) @ StateFn(agent), ~StateFn(action_right) @ StateFn(agent) ]) return readout_op, action_left, action_right def compute_q_vals(states, model, observable_weights, data_weights, n_layers, grad=True): input_states = [] for state in states: extended_state = torch.arctan(Tensor(state).repeat(1, n_layers) * data_weights) input_states.append(extended_state) states_tensor = torch.reshape(torch.stack(input_states), (len(input_states), n_layers*4)) if grad: res = model(states_tensor) else: with torch.no_grad(): res = model(states_tensor) q_vals = (res + 1) / 2 q_vals[:, 0] *= observable_weights[0] q_vals[:, 1] *= observable_weights[1] return q_vals def train_step( memory, model, target_model, batch_size, observable_weights, data_weights, target_observable_weights, target_data_weights, model_optimizer, observables_optimizer, data_weights_optimizer, loss, gamma, n_layers): transitions = random.sample(memory, batch_size) batch_memories = Transition(*zip(*transitions)) batch_states = batch_memories.state batch_actions = batch_memories.action batch_next_states = batch_memories.next_state batch_done = batch_memories.done batch_rewards = np.ones(batch_size) action_masks = [] one_hot_actions = {0: [1, 0], 1: [0, 1]} for action in batch_actions: action_masks.append(one_hot_actions[action]) model_optimizer.zero_grad() observables_optimizer.zero_grad() data_weights_optimizer.zero_grad() q_vals = compute_q_vals( batch_states, model, observable_weights, data_weights, n_layers) q_vals_next = compute_q_vals( batch_next_states, target_model, target_observable_weights, target_data_weights, n_layers, grad=False) target_q_vals = torch.Tensor(batch_rewards) + torch.Tensor( np.ones(batch_size) * gamma) * torch.max(q_vals_next, 1).values * (1 - torch.Tensor(batch_done)) reduced_q_vals = torch.sum(q_vals * torch.Tensor(action_masks), dim=1) error = loss(reduced_q_vals, target_q_vals) print('start backward()') error.backward() print('end backward()') model_optimizer.step() observables_optimizer.step() data_weights_optimizer.step() # set up Qiskit backend and Gym backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) env = gym.make("CartPole-v0") # set hyperparameters for deep Q-learning n_qubits = 4 n_layers = 5 gamma = 0.99 # Q-learning discount factor epsilon = 1.0 # epsilon greedy policy initial value epsilon_min = 0.01 # minimum value of epsilon epsilon_decay = 0.99 # decay rate of epsilon n_episodes = 3000 batch_size = 16 update_qnet_after = 1 # agent update interval update_target_after = 1 # target network update interval # set up replay memory Transition = namedtuple('Transition', ( 'state', 'action', 'next_state', 'done')) max_memory_len = 10000 replay_memory = deque(maxlen=max_memory_len) grad_method='param_shift' # grad_method='fin_diff' # set up model agent, params, data_params, data_weight_params = build_quantum_model( n_qubits, n_layers) observable_weights = TorchParameter(Tensor([1, 1])) data_weights = TorchParameter(Tensor(np.ones(shape=n_qubits*n_layers))) readout_op, action_left, action_right = build_readout_ops(agent) qnn_opflow = OpflowQNN( readout_op, data_params, params, exp_val=AerPauliExpectation(), gradient=Gradient(grad_method), quantum_instance=quantum_instance, input_gradients=False) model = TorchConnector(qnn_opflow) # set up target model that is used to compute target Q-values # (not trained, only updated with Q-model's parameters at fixed intervals) target_agent, target_params, target_data_params, target_data_weight_params = build_quantum_model( n_qubits, n_layers, is_target_model=True) target_observable_weights = Tensor([1, 1]) target_data_weights = TorchParameter(Tensor(np.ones(shape=n_qubits*n_layers))) target_readout_op, _, _ = build_readout_ops(target_agent) target_qnn = OpflowQNN( target_readout_op, target_data_params, target_params, exp_val=AerPauliExpectation(), gradient=Gradient(grad_method), quantum_instance=quantum_instance) target_qnn.input_gradients = False target_model = TorchConnector(target_qnn) target_model.load_state_dict(model.state_dict()) # set up optimizers model_optimizer = Adam(model.parameters(), lr=0.001) observables_optimizer = Adam([observable_weights], lr=0.1) data_weights_optimizer = Adam([data_weights], lr=0.1) loss = torch.nn.MSELoss() episode_rewards = [] print('start training') t_start_training = time() for episode in range(n_episodes): t_start_episode = time() episode_reward = 0 state = env.reset() for time_step in range(200): # env.render() print(f'episode {episode}, time_step {time_step}') # choose action based on epsilon greedy policy if random.random() > epsilon: with torch.no_grad(): q_vals = compute_q_vals([state], model, observable_weights, data_weights, n_layers) action = int(torch.argmax(q_vals).numpy()) else: action = np.random.choice(2) # take step in environment and collect reward next_state, reward, done, _ = env.step(action) episode_reward += 1 # store transition in memory (without reward as it is always 1) replay_memory.append(Transition(state, action, next_state, int(done))) state = next_state # perform one step of parameter updates if len(replay_memory) > batch_size and time_step % update_qnet_after == 0: train_step( replay_memory, model, target_model, batch_size, observable_weights, data_weights, target_observable_weights, target_data_weights, model_optimizer, observables_optimizer, data_weights_optimizer, loss, gamma, n_layers) # update target model parameters if time_step % update_target_after == 0: with torch.no_grad(): target_model.load_state_dict(model.state_dict()) target_observable_weights = copy.deepcopy(observable_weights.data) target_data_weights = copy.deepcopy(data_weights.data) if done: break episode_rewards.append(episode_reward) epsilon = max(epsilon_min, epsilon * epsilon_decay) t_end_episode = time() print('episode time:', (t_end_episode - t_start_episode)) if episode > 0: print(f'Episode {episode}, episode reward: {episode_reward}, average reward: {np.mean(episode_rewards[-100:])}') else: print(f'Episode {episode}, episode reward: {episode_reward}') t_end_training = time() print('training time:', (t_end_training - t_start_training)) plt.plot(episode_rewards) plt.ylabel("Score") plt.xlabel("Episode") plt.show()
https://github.com/henrik-dreyer/TASP-for-Qiskit
henrik-dreyer
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 2 17:07:01 2019 @author: henrikdreyer """ """TASP Ansatz described in https://journals.aps.org/pra/pdf/10.1103/PhysRevA.92.042303""" import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua.components.variational_forms import VariationalForm class TASP(VariationalForm): """Trotterized Adiabatic State Preparation. https://journals.aps.org/pra/pdf/10.1103/PhysRevA.92.042303""" CONFIGURATION = { 'name': 'TASP', 'description': 'TASP Variational Form', 'input_schema': { '$schema': 'http://json-schema.org/draft-07/schema#', 'id': 'tasp_schema', 'type': 'object', 'properties': { 'depth': { 'type': 'integer', 'default': 1, 'minimum': 1 }, }, 'additionalProperties': False }, 'depends': [ { 'pluggable_type': 'initial_state', 'default': { 'name': 'ZERO', } }, ], } def __init__(self, num_qubits, h_list, depth=1, initial_state=None): """Constructor. Args: num_qubits (int) : number of qubits depth (int) : number of TASP steps layers (corresponds to the variable S in equation 8 of the paper above) h_list (WeightedPauliOperator) : list of Hamiltonians with which to evolve, e.g. H_ex, H_hop, H_diag in the paper above. initial_state (InitialState): an initial state object """ self.validate(locals()) super().__init__() self._num_qubits = num_qubits self._h_list = h_list self._depth = depth self._initial_state = initial_state self._num_parameters=len(self._h_list)*depth self._bounds = [(-np.pi, np.pi)] * self._num_parameters def construct_circuit(self, parameters, q=None): """ Construct the variational form, given its parameters. Args: parameters (numpy.ndarray): circuit parameters q (QuantumRegister): Quantum Register for the circuit. Returns: QuantumCircuit: a quantum circuit with given `parameters` Raises: ValueError: the number of parameters is incorrect. """ if len(parameters) != self._num_parameters: raise ValueError('The number of parameters has to be {}'.format(self._num_parameters)) if q is None: q = QuantumRegister(self._num_qubits, name='q') if self._initial_state is not None: circuit = self._initial_state.construct_circuit('circuit', q) else: circuit = QuantumCircuit(q) for b in range(self._depth): for i in range(len(self._h_list)): if not self._h_list[i].is_empty(): circuit+=self._h_list[i].evolve(evo_time=parameters[i], quantum_registers=q) for i in range(len(self._h_list)-1,-1,-1): if not self._h_list[i].is_empty(): circuit+=self._h_list[i].evolve(evo_time=parameters[i], quantum_registers=q) return circuit
https://github.com/henrik-dreyer/TASP-for-Qiskit
henrik-dreyer
import numpy as np from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD from qiskit.aqua.components.variational_forms import TASP from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit.aqua.components.optimizers import COBYLA from qiskit import BasicAer from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.chemistry import FermionicOperator from qiskit.aqua import QuantumInstance #Classical part: set up molecular data, map to WeightedPauliOperator and find exact solution dist=0.735 driver = PySCFDriver(atom="H .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() repulsion_energy = molecule.nuclear_repulsion_energy num_spin_orbitals=molecule.num_orbitals*2 map_type='jordan_wigner' ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001) exact_solution = ExactEigensolver(qubitOp).run()['energy'] exact_solution=exact_solution+repulsion_energy #Set up initial state and UCCSD variational form with standard parameters HF_state=HartreeFock(qubitOp.num_qubits, num_spin_orbitals, num_particles, map_type) varform_UCCSD = UCCSD(qubitOp.num_qubits, depth=1, num_orbitals=num_spin_orbitals, num_particles=num_particles, active_occupied=None, active_unoccupied=None, initial_state=HF_state, qubit_mapping='jordan_wigner', two_qubit_reduction=False, num_time_slices=1, shallow_circuit_concat=True, z2_symmetries=None) #Run VQE using UCCSD variational form and compare with exact solution print('Molecule H2 at bond length ' + str(dist)) print('Running VQE with UCCSD. This may take a few minutes. Some intermediary energies while you wait:') opt_iter=15 optimizer = COBYLA(maxiter=opt_iter) n_shots=1000 instance=QuantumInstance(backend=BasicAer.get_backend("qasm_simulator"), shots=n_shots) vqe_instance = VQE(qubitOp, varform_UCCSD, optimizer=optimizer) result=vqe_instance.run(instance) energy=result['energy']+repulsion_energy print('Optimal energy is ' + str(energy) +'. Exact result is ' + str(exact_solution)) #Split the Hamiltonian into the abovementioned pieces diag_one_body=np.diag(np.diagonal(molecule.one_body_integrals)) offdiag_one_body=molecule.one_body_integrals-diag_one_body diag_two_body=np.zeros((num_spin_orbitals,num_spin_orbitals,num_spin_orbitals,num_spin_orbitals)) hop_two_body=np.zeros((num_spin_orbitals,num_spin_orbitals,num_spin_orbitals,num_spin_orbitals)) ex_two_body=np.zeros((num_spin_orbitals,num_spin_orbitals,num_spin_orbitals,num_spin_orbitals)) for i1 in range(num_spin_orbitals): for i2 in range(num_spin_orbitals): for i3 in range(num_spin_orbitals): for i4 in range(num_spin_orbitals): if i2==i3: if i1==i4: diag_two_body[i1,i2,i3,i4]=molecule.two_body_integrals[i1,i2,i3,i4] else: hop_two_body[i1,i2,i3,i4]=molecule.two_body_integrals[i1,i2,i3,i4] else: ex_two_body[i1,i2,i3,i4]=molecule.two_body_integrals[i1,i2,i3,i4] H_diag=FermionicOperator(h1=diag_one_body,h2=diag_two_body) H_hop=FermionicOperator(h1=offdiag_one_body,h2=hop_two_body) H_ex=FermionicOperator(h1=np.zeros((num_spin_orbitals,num_spin_orbitals)),h2=ex_two_body) H_diag=H_diag.mapping(map_type=map_type, threshold=0.00000001) H_hop=H_hop.mapping(map_type=map_type, threshold=0.00000001) H_ex=H_ex.mapping(map_type=map_type, threshold=0.00000001) h_list=[H_ex, H_hop, H_diag] #Define TASP variational form (the TASP class file is attached to original comment) S=1 varform_TASP=TASP(num_spin_orbitals, depth=S, h_list=h_list, initial_state=HF_state) print('Running VQE with TASP. This may take a few minutes. Some intermediary energies while you wait:') vqe_instance = VQE(qubitOp, varform_TASP, optimizer=optimizer) result=vqe_instance.run(instance) energy=result['energy']+repulsion_energy print('Optimal energy is ' + str(energy) +'. Exact result is ' + str(exact_solution)) n_param_UCCSD=varform_UCCSD.num_parameters qc_UCCSD=varform_UCCSD.construct_circuit(np.random.rand(n_param_UCCSD)) print('Number of parameters for UCCSD:', n_param_UCCSD) print('Depth for UCCSD:', qc_UCCSD.depth()) print('Gate counts:', qc_UCCSD.count_ops()) n_param_TASP=varform_TASP.num_parameters qc_TASP=varform_TASP.construct_circuit(np.random.rand(n_param_TASP)) print('Number of parameters for TASP:', n_param_TASP) print('Depth for TASP:', qc_TASP.depth()) print('Gate counts:', qc_TASP.count_ops())
https://github.com/hotstaff/qc
hotstaff
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Quantum Calculator - libqc Author: Hideto Manjo Licence: Apache License 2.0 ''' import sys import re from datetime import datetime from qiskit import QuantumProgram, QISKitError, RegisterSizeError class QC(): ''' class QC ''' # pylint: disable=too-many-instance-attributes def __init__(self, backend='local_qasm_simulator', remote=False, qubits=3): # private member # __qp self.__qp = None # calc phase self.phase = [ ['0', 'initialized.'] ] # config self.backend = backend self.remote = remote self.qubits = qubits # circuits variable self.shots = 2 # async self.wait = False self.last = ['init', 'None'] self.load() def load(self, api_info=True): ''' load ''' self.__qp = QuantumProgram() if self.remote: try: import Qconfig self.__qp.set_api(Qconfig.APItoken, Qconfig.config["url"], hub=Qconfig.config["hub"], group=Qconfig.config["group"], project=Qconfig.config["project"]) except ImportError as ex: msg = 'Error in loading Qconfig.py!. Error = {}\n'.format(ex) sys.stdout.write(msg) sys.stdout.flush() return False if api_info is True: api = self.__qp.get_api() sys.stdout.write('<IBM Quantum Experience API information>\n') sys.stdout.flush() sys.stdout.write('Version: {0}\n'.format(api.api_version())) sys.stdout.write('User jobs (last 5):\n') jobs = api.get_jobs(limit=500) def format_date(job_item): ''' format ''' return datetime.strptime(job_item['creationDate'], '%Y-%m-%dT%H:%M:%S.%fZ') sortedjobs = sorted(jobs, key=format_date) sys.stdout.write(' {0:<32} {1:<24} {2:<9} {3}\n' .format('id', 'creationDate', 'status', 'backend')) sys.stdout.write('{:-^94}\n'.format("")) for job in sortedjobs[-5:]: sys.stdout.write(' {0:<32} {1:<24} {2:<9} {3}\n' .format(job['id'], job['creationDate'], job['status'], job['backend']['name'])) sys.stdout.write('There are {0} jobs on the server\n' .format(len(jobs))) sys.stdout.write('Credits: {0}\n' .format(api.get_my_credits())) sys.stdout.flush() self.backends = self.__qp.available_backends() status = self.__qp.get_backend_status(self.backend) if 'available' in status: if status['available'] is False: return False return True def set_config(self, config=None): ''' set config ''' if config is None: config = {} if 'backend' in config: self.backend = str(config['backend']) if 'local_' in self.backend: self.remote = False else: self.remote = True if 'remote' in config: self.remote = config['remote'] if 'qubits' in config: self.qubits = int(config['qubits']) return True def _progress(self, phasename, text): self.phase.append([str(phasename), str(text)]) text = "Phase {0}: {1}".format(phasename, text) sys.stdout.write("{}\n".format(text)) sys.stdout.flush() def _init_circuit(self): self._progress('1', 'Initialize quantum registers and circuit') qubits = self.qubits quantum_registers = [ {"name": "cin", "size": 1}, {"name": "qa", "size": qubits}, {"name": "qb", "size": qubits}, {"name": "cout", "size": 1} ] classical_registers = [ {"name": "ans", "size": qubits + 1} ] if 'cin' in self.__qp.get_quantum_register_names(): self.__qp.destroy_quantum_registers(quantum_registers) self.__qp.destroy_classical_registers(classical_registers) q_r = self.__qp.create_quantum_registers(quantum_registers) c_r = self.__qp.create_classical_registers(classical_registers) self.__qp.create_circuit("qcirc", q_r, c_r) def _create_circuit_qadd(self): # quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184 def majority(circuit, q_a, q_b, q_c): ''' majority ''' circuit.cx(q_c, q_b) circuit.cx(q_c, q_a) circuit.ccx(q_a, q_b, q_c) def unmaj(circuit, q_a, q_b, q_c): ''' unmajority ''' circuit.ccx(q_a, q_b, q_c) circuit.cx(q_c, q_a) circuit.cx(q_a, q_b) def adder(circuit, c_in, q_a, q_b, c_out, qubits): ''' adder ''' # pylint: disable=too-many-arguments majority(circuit, c_in[0], q_b[0], q_a[0]) for i in range(qubits - 1): majority(circuit, q_a[i], q_b[i + 1], q_a[i + 1]) circuit.cx(q_a[qubits - 1], c_out[0]) for i in range(qubits - 1)[::-1]: unmaj(circuit, q_a[i], q_b[i + 1], q_a[i + 1]) unmaj(circuit, c_in[0], q_b[0], q_a[0]) if 'add' not in self.__qp.get_circuit_names(): [c_in, q_a, q_b, c_out] = map(self.__qp.get_quantum_register, ["cin", "qa", "qb", "cout"]) ans = self.__qp.get_classical_register('ans') qadder = self.__qp.create_circuit("qadd", [c_in, q_a, q_b, c_out], [ans]) adder(qadder, c_in, q_a, q_b, c_out, self.qubits) return 'add' in self.__qp.get_circuit_names() def _create_circuit_qsub(self): circuit_names = self.__qp.get_circuit_names() if 'qsub' not in circuit_names: if 'qadd' not in circuit_names: self._create_circuit_qadd() # subtractor circuit self.__qp.add_circuit('qsub', self.__qp.get_circuit('qadd')) qsubtractor = self.__qp.get_circuit('qsub') qsubtractor.reverse() return 'qsub' in self.__qp.get_circuit_names() def _qadd(self, input_a, input_b=None, subtract=False, observe=False): # pylint: disable=too-many-locals def measure(circuit, q_b, c_out, ans): ''' measure ''' circuit.barrier() for i in range(self.qubits): circuit.measure(q_b[i], ans[i]) circuit.measure(c_out[0], ans[self.qubits]) def char2q(circuit, cbit, qbit): ''' char2q ''' if cbit == '1': circuit.x(qbit) elif cbit == 'H': circuit.h(qbit) self.shots = 5 * (2**self.qubits) def input_state(circuit, input_a, input_b=None): ''' input state ''' input_a = input_a[::-1] for i in range(self.qubits): char2q(circuit, input_a[i], q_a[i]) if input_b is not None: input_b = input_b[::-1] for i in range(self.qubits): char2q(circuit, input_b[i], q_b[i]) def reset_input(circuit, c_in, q_a, c_out): ''' reset input ''' circuit.reset(c_in) circuit.reset(c_out) for i in range(self.qubits): circuit.reset(q_a[i]) # get registers [c_in, q_a, q_b, c_out] = map(self.__qp.get_quantum_register, ["cin", "qa", "qb", "cout"]) ans = self.__qp.get_classical_register('ans') qcirc = self.__qp.get_circuit('qcirc') self._progress('2', 'Define input state ({})' .format('QADD' if subtract is False else 'QSUB')) if input_b is not None: if subtract is True: # subtract input_state(qcirc, input_b, input_a) else: # add input_state(qcirc, input_a, input_b) else: reset_input(qcirc, c_in, q_a, c_out) input_state(qcirc, input_a) self._progress('3', 'Define quantum circuit ({})' .format('QADD' if subtract is False else 'QSUB')) if subtract is True: self._create_circuit_qsub() qcirc.extend(self.__qp.get_circuit('qsub')) else: self._create_circuit_qadd() qcirc.extend(self.__qp.get_circuit('qadd')) if observe is True: measure(qcirc, q_b, c_out, ans) def _qsub(self, input_a, input_b=None, observe=False): self._qadd(input_a, input_b, subtract=True, observe=observe) def _qope(self, input_a, operator, input_b=None, observe=False): if operator == '+': return self._qadd(input_a, input_b, observe=observe) elif operator == '-': return self._qsub(input_a, input_b, observe=observe) return None def _compile(self, name, cross_backend=None, print_qasm=False): self._progress('4', 'Compile quantum circuit') coupling_map = None if cross_backend is not None: backend_conf = self.__qp.get_backend_configuration(cross_backend) coupling_map = backend_conf.get('coupling_map', None) if coupling_map is None: sys.stdout.write('backend: {} coupling_map not found' .format(cross_backend)) qobj = self.__qp.compile([name], backend=self.backend, shots=self.shots, seed=1, coupling_map=coupling_map) if print_qasm is True: sys.stdout.write(self.__qp.get_compiled_qasm(qobj, 'qcirc')) sys.stdout.flush() return qobj def _run(self, qobj): self._progress('5', 'Run quantum circuit (wait for answer)') result = self.__qp.run(qobj, wait=5, timeout=100000) return result def _run_async(self, qobj): ''' _run_async ''' self._progress('5', 'Run quantum circuit') self.wait = True def async_result(result): ''' async call back ''' self.wait = False self.last = self.result_parse(result) self.__qp.run_async(qobj, wait=5, timeout=100000, callback=async_result) def _is_regular_number(self, numstring, base): ''' returns input binary format string or None. ''' if base == 'bin': binstring = numstring elif base == 'dec': if numstring == 'H': binstring = 'H'*self.qubits else: binstring = format(int(numstring), "0{}b".format(self.qubits)) if len(binstring) != self.qubits: return None return binstring def get_seq(self, text, base='dec'): ''' convert seq and check it if text is invalid, return the list of length 0. ''' operators = u'(\\+|\\-)' seq = re.split(operators, text) # length check if len(seq) % 2 == 0 or len(seq) == 1: return [] # regex if base == 'bin': regex = re.compile(r'[01H]+') else: regex = re.compile(r'(^(?!.H)[0-9]+|H)') for i in range(0, len(seq), 2): match = regex.match(seq[i]) if match is None: return [] num = match.group(0) seq[i] = self._is_regular_number(num, base) if seq[i] is None: return [] return seq def result_parse(self, result): ''' result_parse ''' data = result.get_data("qcirc") sys.stdout.write("job id: {0}\n".format(result.get_job_id())) sys.stdout.write("raw result: {0}\n".format(data)) sys.stdout.write("{:=^40}\n".format("answer")) counts = data['counts'] sortedcounts = sorted(counts.items(), key=lambda x: -x[1]) sortedans = [] for count in sortedcounts: if count[0][0] == '1': ans = 'OR' else: ans = str(int(count[0][-self.qubits:], 2)) sortedans.append(ans) sys.stdout.write('Dec: {0:>2} Bin: {1} Count: {2} \n' .format(ans, str(count[0]), str(count[1]))) sys.stdout.write('{0:d} answer{1}\n' .format(len(sortedans), '' if len(sortedans) == 1 else 's')) sys.stdout.write("{:=^40}\n".format("")) if 'time' in data: sys.stdout.write("time: {0:<3} sec\n".format(data['time'])) sys.stdout.write("All process done.\n") sys.stdout.flush() uniqanswer = sorted(set(sortedans), key=sortedans.index) ans = ",".join(uniqanswer) return [str(result), ans] def exec_calc(self, text, base='dec', wait_result=False): ''' exec_calc ''' seq = self.get_seq(text, base) print('QC seq:', seq) if seq == []: return ["Syntax error", None] # fail message fail_msg = None try: self._init_circuit() numbers = seq[0::2] # slice even index i = 1 observe = False for oper in seq[1::2]: # slice odd index if i == len(numbers) - 1: observe = True if i == 1: self._qope(numbers[0], oper, numbers[1], observe=observe) else: self._qope(numbers[i], oper, observe=observe) i = i + 1 qobj = self._compile('qcirc') if wait_result is True: [status, ans] = self.result_parse(self._run(qobj)) else: self._run_async(qobj) [status, ans] = [ 'Wait. Calculating on {0}'.format(self.backend), '...' ] except QISKitError as ex: fail_msg = ('There was an error in the circuit!. Error = {}\n' .format(ex)) except RegisterSizeError as ex: fail_msg = ('Error in the number of registers!. Error = {}\n' .format(ex)) if fail_msg is not None: sys.stdout.write(fail_msg) sys.stdout.flush() return ["FAIL", None] return [status, ans]
https://github.com/ionq-samples/getting-started
ionq-samples
import json, os, requests, time from getpass import getpass # Before you begin, get your API key from https://cloud.ionq.com/settings/keys # If your API key is stored as "IONQ_API_KEY" in your local environment, this # should find it. Otherwise you'll be prompted to enter your API key manually. api_key = os.getenv('IONQ_API_KEY') or getpass('Enter your IonQ API key: ') def submit_job(headers, data): url = "https://api.ionq.co/v0.3/jobs" response = requests.post(url, headers=headers, data=data) response_json = response.json() assert response.status_code == 200, f"Error: {response_json.get('message', 'Unknown error')}" return response_json["id"] def query_job(job_id, headers): url = f"https://api.ionq.co/v0.3/jobs/{job_id}" response = requests.get(url, headers=headers) response_json = response.json() assert response.status_code == 200, f"Error: {response_json.get('message', 'Unknown error')}" return response_json["status"] def get_job_results(job_id, headers): url = f"https://api.ionq.co/v0.3/jobs/{job_id}/results" response = requests.get(url, headers=headers) response_json = response.json() assert response.status_code == 200, f"Error: {response_json.get('message', 'Unknown error')}" return response_json headers = { "Authorization": f"apiKey {api_key}", "Content-Type": "application/json", } data = { "name": "API Example Circuit", "shots": 100, "target": "simulator", "input": { "format": "ionq.circuit.v0", "gateset": "qis", "qubits": 2, "circuit": [ { "gate": "h", "target": 0 }, { "gate": "cnot", "control": 0, "target": 1 } ] } } # Now we'll send the job to our backend for processing. job_id = submit_job(headers, json.dumps(data)) # And wait for the job to be run. status = "ready" while status != "completed": time.sleep(1) # wait for 1 second before querying again status = query_job(job_id, headers) # And once the job has run, we can plot the results. results = get_job_results(job_id, headers) print(results)
https://github.com/ionq-samples/getting-started
ionq-samples
%%capture # First, we install the essential libraries to our current Python runtime. # "%%capture" (above) captures and in this case, hides the output of this # cell, so you can comment it out if you need help debugging this step. %pip install cirq cirq_ionq matplotlib import cirq, cirq_ionq, matplotlib.pyplot as plt, os from getpass import getpass # Before you begin, get your API key from https://cloud.ionq.com/settings/keys # If your API key is stored as "IONQ_API_KEY" in your local environment, this # should find it. Otherwise you'll be prompted to enter your API key manually. api_key = os.getenv('IONQ_API_KEY') or getpass('Enter your IonQ API key: ') service = cirq_ionq.Service(api_key=api_key, default_target='simulator') # Now we set up our circuit. In this case, we're creating a circuit with two # qubits, applying an H gate to qubit-0, a CXGate to both, then measuring. q0, q1 = cirq.LineQubit.range(2) circuit = cirq.Circuit( cirq.H(q0), # H cirq.CX(q0, q1), # CNOT cirq.measure(q0, q1) # Measure both qubits ) # Before submitting the job, we can visualize the circuit using print(). print(circuit) result = service.run(circuit, name="Cirq example", repetitions=100) _ = cirq.plot_state_histogram(result, plt.subplot()) plt.show()
https://github.com/ionq-samples/getting-started
ionq-samples
%%capture # First, we install the essential libraries to our current Python runtime. # "%%capture" (above) captures and in this case, hides the output of this # cell, so you can comment it out if you need help debugging this step. %pip install pennylane pennylane-ionq import pennylane as qml import os from getpass import getpass # Before you begin, get your API key from https://cloud.ionq.com/settings/keys # If your API key is stored as "IONQ_API_KEY" in your local environment, this # should find it. Otherwise you'll be prompted to enter your API key manually. api_key = os.getenv('IONQ_API_KEY') or getpass('Enter your IonQ API key: ') # We need to specify the device where the circuit will be executed. In # this case we're using the `ionq.simulator`, but if you have QPU access you # can specify it here to run the job on a QPU directly. dev = qml.device( 'ionq.simulator', api_key=api_key, wires=2, ) @qml.qnode(dev) def circuit(): qml.Hadamard(wires=0) qml.CNOT(wires=[0, 1]) return qml.counts() fig, ax = qml.draw_mpl(circuit, style='sketch')() results = circuit() print({k: v.item() for k, v in results.items()})
https://github.com/ionq-samples/getting-started
ionq-samples
%%capture # First, we install the essential libraries to our current Python runtime. # "%%capture" (above) captures and in this case, hides the output of this # cell, so you can comment it out if you need help debugging this step. %pip install projectq import os from getpass import getpass import projectq.setups.ionq from projectq import MainEngine from projectq.backends import IonQBackend from projectq.libs.hist import histogram from projectq.ops import H, CNOT, Measure import matplotlib.pyplot as plt # Before you begin, get your API key from https://cloud.ionq.com/settings/keys # If your API key is stored as "IONQ_API_KEY" in your local environment, this # should find it. Otherwise you'll be prompted to enter your API key manually. token = os.getenv('IONQ_API_KEY') or getpass('Enter your IonQ API key: ') # We need to specify the device where the circuit will be executed. In this # case we're using the `ionq_simulator`, but if you have QPU access you can # specify it here to run the job on a QPU directly. device = 'ionq_simulator' backend = IonQBackend(token=token, device=device) compiler_engines = projectq.setups.ionq.get_engine_list(token=token, device=device) eng = MainEngine(backend, engine_list=compiler_engines) qubit1 = eng.allocate_qubit() # Allocate a quantum register with 1 qubit qubit2 = eng.allocate_qubit() H | qubit1 # Apply a Hadamard gate CNOT | (qubit1, qubit2) # Entangle the qubits Measure | qubit1 # Measure the qubit Measure | qubit2 eng.flush() # Flush all gates (and execute measurements) histogram(eng.backend, qubit1 + qubit2) plt.show()
https://github.com/ionq-samples/getting-started
ionq-samples
%%capture # First, we install the essential libraries to our current Python runtime. # "%%capture" (above) captures and in this case, hides the output of this # cell, so you can comment it out if you need help debugging this step. %pip install 'qbraid[runtime]' matplotlib import os from getpass import getpass from qbraid.runtime.ionq import IonQProvider # Before you begin, get your API key from https://cloud.ionq.com/settings/keys # If your API key is stored as "IONQ_API_KEY" in your local environment, this # should find it. Otherwise you'll be prompted to enter your API key manually. api_key = os.getenv("IONQ_API_KEY") or getpass("Enter your IonQ API key: ") provider = IonQProvider(api_key=api_key) # Now we set up our circuit. In this case, we're creating a circuit with two # qubits, applying an H gate to qubit-0, a CXGate to both,. program = """ OPENQASM 3; include "stdgates.inc"; qubit[2] q; h q[0]; cx q[0], q[1]; """ # Before submitting the job, we can visualize the circuit using qasm3_drawer(). from qbraid.visualization import qasm3_drawer qasm3_drawer(program) device = provider.get_device("simulator") job = device.run(program, name="qBraid example", shots=100) results = job.result() counts = results.measurement_counts() print(counts) from qbraid.visualization import plot_histogram plot_histogram(counts)
https://github.com/ionq-samples/getting-started
ionq-samples
import numpy as np from qiskit import QuantumCircuit # Building the circuit # Create a Quantum Circuit acting on a quantum register of three qubits circ = QuantumCircuit(3) # Add a H gate on qubit 0, putting this qubit in superposition. circ.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting # the qubits in a Bell state. circ.cx(0, 1) # Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting # the qubits in a GHZ state. circ.cx(0, 2) # We can visualise the circuit using QuantumCircuit.draw() circ.draw('mpl') from qiskit.quantum_info import Statevector # Set the initial state of the simulator to the ground state using from_int state = Statevector.from_int(0, 2**3) # Evolve the state by the quantum circuit state = state.evolve(circ) #draw using latex state.draw('latex') from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Build #------ # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0,1], [0,1]) # END # Execute #-------- # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator job = execute(circuit, simulator, shots=1000) # Grab results from the job result = job.result() # Return counts counts = result.get_counts(circuit) print("\nTotal count for 00 and 11 are:",counts) # END # Visualize #---------- # Using QuantumCircuit.draw(), as in previous example circuit.draw('mpl') # Analyze #-------- # Plot a histogram plot_histogram(counts) # END <h3 style="color: rgb(0, 125, 65)"><i>References</i></h3> https://qiskit.org/documentation/tutorials.html https://www.youtube.com/watch?v=P5cGeDKOIP0 https://qiskit.org/documentation/tutorials/circuits/01_circuit_basics.html https://docs.quantum-computing.ibm.com/lab/first-circuit
https://github.com/ionq-samples/getting-started
ionq-samples
%%capture %pip install qiskit %pip install qiskit_ibm_provider %pip install qiskit-aer # Importing standard Qiskit libraries from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer from qiskit_ibm_provider import IBMProvider from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.circuit.library import C3XGate # Importing matplotlib import matplotlib.pyplot as plt # Importing Numpy, Cmath and math import numpy as np import os, math, cmath from numpy import pi # Other imports from IPython.display import display, Math, Latex # Specify the path to your env file env_file_path = 'config.env' # Load environment variables from the file os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#')) # Load IBM Provider API KEY IBMP_API_KEY = os.environ.get('IBMP_API_KEY') # Loading your IBM Quantum account(s) IBMProvider.save_account(IBMP_API_KEY, overwrite=True) # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') qc_b1 = QuantumCircuit(2, 2) qc_b1.h(0) qc_b1.cx(0, 1) qc_b1.draw(output='mpl', style="iqp") sv = backend.run(qc_b1).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.x(0) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.z(0) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.x(1) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.x(0) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.x(0) qc_b4.h(0) qc_b4.x(1) qc_b4.cx(0, 1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.h(0) qc_b4.cx(0, 1) qc_b4.x(0) qc_b4.z(1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") def sv_latex_from_qc(qc, backend): sv = backend.run(qc).result().get_statevector() return sv.draw(output='latex') qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(3) sv_latex_from_qc(qc_ej2, backend) def circuit_adder (num): if num<1 or num>8: raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo. # Definición del circuito base que vamos a construir qreg_q = QuantumRegister(4, 'q') creg_c = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qreg_q, creg_c) qbit_position = 0 for element in reversed(np.binary_repr(num)): if (element=='1'): circuit.barrier() match qbit_position: case 0: # +1 circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]]) circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) circuit.x(qreg_q[0]) case 1: # +2 circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3]) circuit.cx(qreg_q[1], qreg_q[2]) circuit.x(qreg_q[1]) case 2: # +4 circuit.cx(qreg_q[2], qreg_q[3]) circuit.x(qreg_q[2]) case 3: # +8 circuit.x(qreg_q[3]) qbit_position+=1 return circuit add_3 = circuit_adder(3) add_3.draw(output='mpl', style="iqp") qc_test_2 = QuantumCircuit(4, 4) qc_test_2.x(1) qc_test_2_plus_3 = qc_test_2.compose(add_3) qc_test_2_plus_3.draw(output='mpl', style="iqp") sv_latex_from_qc(qc_test_2_plus_3, backend) qc_test_7 = QuantumCircuit(4, 4) qc_test_7.x(0) qc_test_7.x(1) qc_test_7.x(2) qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8)) sv_latex_from_qc(qc_test_7_plus_8, backend) #qc_test_7_plus_8.draw() theta = 6.544985 phi = 2.338741 lmbda = 0 alice_1 = 0 alice_2 = 1 bob_1 = 2 qr_alice = QuantumRegister(2, 'Alice') qr_bob = QuantumRegister(1, 'Bob') cr = ClassicalRegister(3, 'c') qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr) qc_ej3.barrier(label='1') qc_ej3.u(theta, phi, lmbda, alice_1); qc_ej3.barrier(label='2') qc_ej3.h(alice_2) qc_ej3.cx(alice_2, bob_1); qc_ej3.barrier(label='3') qc_ej3.cx(alice_1, alice_2) qc_ej3.h(alice_1); qc_ej3.barrier(label='4') qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]); qc_ej3.barrier(label='5') qc_ej3.x(bob_1).c_if(alice_2, 1) qc_ej3.z(bob_1).c_if(alice_1, 1) qc_ej3.measure(bob_1, bob_1); qc_ej3.draw(output='mpl', style="iqp") result = backend.run(qc_ej3, shots=1024).result() counts = result.get_counts() plot_histogram(counts) sv_0 = np.array([1, 0]) sv_1 = np.array([0, 1]) def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10): """ Check if the given numerical value corresponds to a symbolic constant within a specified tolerance. Parameters: - value (float): The numerical value to check. - symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations. Defaults to {1/np.sqrt(2): '1/√2'}. - tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10. Returns: str or float: If a match is found, returns the symbolic representation as a string (prefixed with '-' if the value is negative); otherwise, returns the original value. """ for constant, symbol in symbolic_constants.items(): if np.isclose(abs(value), constant, atol=tolerance): return symbol if value >= 0 else '-' + symbol return value def array_to_dirac_notation(array, tolerance=1e-10): """ Convert a complex-valued array representing a quantum state in superposition to Dirac notation. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state in superposition. - tolerance (float): Tolerance for considering amplitudes as negligible. Returns: str: The Dirac notation representation of the quantum state. """ # Ensure the statevector is normalized array = array / np.linalg.norm(array) # Get the number of qubits num_qubits = int(np.log2(len(array))) # Find indices where amplitude is not negligible non_zero_indices = np.where(np.abs(array) > tolerance)[0] # Generate Dirac notation terms terms = [ (find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b")) for i in non_zero_indices ] # Format Dirac notation dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms]) return dirac_notation def array_to_matrix_representation(array): """ Convert a one-dimensional array to a column matrix representation. Parameters: - array (numpy.ndarray): The one-dimensional array to be converted. Returns: numpy.ndarray: The column matrix representation of the input array. """ # Replace symbolic constants with their representations matrix_representation = np.array([find_symbolic_representation(value) or value for value in array]) # Return the column matrix representation return matrix_representation.reshape((len(matrix_representation), 1)) def array_to_dirac_and_matrix_latex(array): """ Generate LaTeX code for displaying both the matrix representation and Dirac notation of a quantum state. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state. Returns: Latex: A Latex object containing LaTeX code for displaying both representations. """ matrix_representation = array_to_matrix_representation(array) latex = "Matrix representation\n\\begin{bmatrix}\n" + \ "\\\\\n".join(map(str, matrix_representation.flatten())) + \ "\n\\end{bmatrix}\n" latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}' return Latex(latex) sv_b1 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b2 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b3 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b4 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4)
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import hashlib import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute from qiskit.circuit import Parameter from qiskit.providers.aer import QasmSimulator, StatevectorSimulator from qiskit.visualization import * from qiskit.quantum_info import * from qiskit.circuit.library import HGate success_msg = 'Your answer is correct and has been saved. Please continue to the next section.' fail_msg = 'Your answer is not correct. Please try again.' qc1 = QuantumCircuit(1) # Insert gates below to create the state # Insert the necessary gates to change to the Hadamard basis below and measure # Do not change below this line qc1.draw('mpl') basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'barrier', 'measure'] assert list(qc1.count_ops()) != [], "Circuit cannot be empty" assert set(qc1.count_ops().keys()).intersection(basis_gates) != set(), "Only basic gates are allowed" job = execute(qc1, backend=QasmSimulator(), shots=1024, seed_simulator=0) counts = job.result().get_counts() sv_check = Statevector.from_instruction(qc1.remove_final_measurements(inplace=False)).evolve(HGate()).equiv(Statevector.from_label('r')) op_check_dict = qc1.count_ops() _ = op_check_dict.pop('measure', None) _ = op_check_dict.pop('barrier', None) op_check = len(op_check_dict) > 1 print(success_msg if (sv_check and op_check) else fail_msg) answer1 = hashlib.sha256((str(counts)+str(sv_check and op_check)).encode()).hexdigest() plot_histogram(counts) from IPython.display import YouTubeVideo, display polariser_exp = YouTubeVideo('6N3bJ7Uxpp0', end=93, height=405, width=720, modestbranding=1) display(polariser_exp) beta = Parameter('β') qc2 = QuantumCircuit(1) # Enter your code below this line # Do not change below this line qc2.draw(output='mpl') def theoretical_prob(beta): ''' Definition of theoretical transmission probability. The expression for transmitted probability between two polarisers with a relative angle `beta` given in radians ''' # Fill in the correct expression for this probability and assign it to the variable tp below # You may use numpy function like so: np.func_name() tp = return tp beta_range = np.linspace(0, np.pi, 50) num_shots = 1024 basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'barrier', 'measure'] assert set(qc2.count_ops().keys()).intersection(basis_gates) != set(), "Only basic gates are allowed" job = execute(qc2, backend=QasmSimulator(), shots = num_shots, parameter_binds=[{beta: beta_val} for beta_val in beta_range], seed_simulator=0) # For consistent results counts = job.result().get_counts() # Calculating the probability of photons passing through probabilities = list(map(lambda c: c.get('0', 0)/num_shots, counts)) pol_checks = [Statevector.from_instruction(qc2.bind_parameters({beta: beta_val}) .remove_final_measurements(inplace=False)) .equiv(Statevector([np.cos(-beta_val), np.sin(-beta_val)])) for beta_val in beta_range] print(success_msg if all(pol_checks) else fail_msg) answer2 = hashlib.sha256((str(probabilities)+str(pol_checks)).encode()).hexdigest() fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111) t_prob = np.vectorize(theoretical_prob) ax.plot(beta_range, probabilities, 'o', label='Experimental') ax.plot(beta_range, t_prob(beta_range), '-', label='Theoretical') ax.set_xticks([i * np.pi / 4 for i in range(5)]) ax.set_xticklabels(['β', r'$\frac{\pi}{4}$', r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$'], fontsize=14) ax.set_xlabel('β', fontsize=14) ax.set_ylabel('Probability of Transmission', fontsize=14) ax.legend(fontsize=14) print(f'Answer 1: {answer1}') print(f'Answer 2: {answer2}')
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import hashlib import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute from qiskit.circuit import Parameter from qiskit.providers.aer import QasmSimulator, StatevectorSimulator from qiskit.visualization import * from qiskit.quantum_info import * from qiskit.circuit.library import HGate success_msg = 'Your answer is correct and has been saved. Please continue to the next section.' fail_msg = 'Your answer is not correct. Please try again.' qc1 = QuantumCircuit(1) # Insert gates below to create the state qc1.rx(-np.pi/2,0) # Insert the necessary gates to change to the Hadamard basis below qc1.h(0) # Do not change below this line qc1.measure_all() qc1.draw('mpl') basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'barrier', 'measure'] assert list(qc1.count_ops()) != [], "Circuit cannot be empty" assert set(qc1.count_ops().keys()).difference(basis_gates) == set(), "Only basic gates are allowed" job = execute(qc1, backend=QasmSimulator(), shots=1024, seed_simulator=0) counts = job.result().get_counts() sv_check = Statevector.from_instruction(qc1.remove_final_measurements(inplace=False)).evolve(HGate()).equiv(Statevector.from_label('r')) op_check_dict = qc1.count_ops() _ = op_check_dict.pop('measure', None) _ = op_check_dict.pop('barrier', None) op_check = len(op_check_dict) > 1 print(success_msg if (sv_check and op_check) else fail_msg) answer1 = hashlib.sha256((str(counts)+str(sv_check and op_check)).encode()).hexdigest() plot_histogram(counts) from IPython.display import YouTubeVideo, display polariser_exp = YouTubeVideo('6N3bJ7Uxpp0', end=93, height=405, width=720, modestbranding=1) display(polariser_exp) beta = Parameter('β') qc2 = QuantumCircuit(1) # Enter your code below this line qc2.ry(-2*beta, 0) qc2.measure_all() # Do not change below this line qc2.draw(output='mpl') def theoretical_prob(beta): ''' Definition of theoretical transmission probability. The expression for transmitted probability between two polarisers with a relative angle `beta` given in radians ''' # Fill in the correct expression for this probability and assign it to the variable tp below # You may use numpy function like so: np.func_name() tp = np.cos(-beta)**2 return tp beta_range = np.linspace(0, np.pi, 50) num_shots = 1024 basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'barrier', 'measure'] assert set(qc1.count_ops().keys()).difference(basis_gates) == set(), "Only basic gates are allowed" job = execute(qc2, backend=QasmSimulator(), shots = num_shots, parameter_binds=[{beta: beta_val} for beta_val in beta_range], seed_simulator=0) # For consistent results counts = job.result().get_counts() # Calculating the probability of photons passing through probabilities = list(map(lambda c: c.get('0', 0)/num_shots, counts)) pol_checks = [Statevector.from_instruction(qc2.bind_parameters({beta: beta_val}) .remove_final_measurements(inplace=False)) .equiv(Statevector([np.cos(-beta_val), np.sin(-beta_val)])) for beta_val in beta_range] print(success_msg if all(pol_checks) else fail_msg) answer2 = hashlib.sha256((str(probabilities)+str(pol_checks)).encode()).hexdigest() fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111) ax.plot(beta_range, probabilities, 'o', label='Experimental') ax.plot(beta_range, theoretical_prob(beta_range), '-', label='Theoretical') ax.set_xticks([i * np.pi / 4 for i in range(5)]) ax.set_xticklabels(['β', r'$\frac{\pi}{4}$', r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$'], fontsize=14) ax.set_xlabel('β', fontsize=14) ax.set_ylabel('Probability of Transmission', fontsize=14) ax.legend(fontsize=14)
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries and configuring account import qiskit from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator, StatevectorSimulator from qiskit.visualization import * from qiskit.quantum_info import * success_msg = 'Your answer is correct.' fail_msg = 'Your answer is not correct. Please try again.' basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'barrier', 'measure', 'snapshot'] qc1 = QuantumCircuit(3) # Insert gates below to create the state # Do not change below this line. You do not need to add an additional measurement. qc1.measure_all() qc1.draw('mpl') try: assert list(qc1.count_ops()) != [], "Circuit cannot be empty" assert set(qc1.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in qc1.data[-3:len(qc1.data)]]), "Measurement must be the last operation in a circuit." sv_check = Statevector.from_instruction(qc1.remove_final_measurements(inplace=False)).equiv((Statevector.from_label('000')+Statevector.from_label('111'))/np.sqrt(2)) assert sv_check, "You did not prepare the correct state." job = execute(qc1, backend=QasmSimulator(), shots=1024, seed_simulator=0) counts = job.result().get_counts() print(success_msg if (sv_check) else fail_msg) except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') plot_histogram(counts) def superdense_coding_circ(bitstr): ''' bitstr is a 2-character string with possible values '00', '01', '10', '11' ''' qc2 = QuantumCircuit(2) # Enter your code below this line # Prepare a Bell state B_00 below # Do not remove the following line qc2.snapshot('1') # Apply single-qubit gates only on q_0 to encode the bitstring # Do not remove the following line qc2.snapshot('2') # Apply gates to change to the Bell basis # Do not remove the following line qc2.snapshot('3') # Do not change below this line. You do not need to add an additional measurement. qc2.measure_all() return qc2 b00_sv = (Statevector.from_label('00')+Statevector.from_label('11'))/np.sqrt(2) b01_sv = (Statevector.from_label('01')+Statevector.from_label('10'))/np.sqrt(2) b10_sv = (Statevector.from_label('00')-Statevector.from_label('11'))/np.sqrt(2) b11_sv = (Statevector.from_label('01')-Statevector.from_label('10'))/np.sqrt(2) bell_states_sv = [b00_sv, b01_sv, b10_sv, b11_sv] basis_states = ['00', '01', '10', '11'] bell_dict = dict(zip(basis_states, bell_states_sv)) enc_dec_mat = np.zeros((len(basis_states),len(basis_states))) try: for state in basis_states: sv_checks = [] qc = superdense_coding_circ(state) assert list(qc.count_ops()) != [], f" Bitstring {state}: Circuit cannot be empty" assert qc.count_ops()['measure'] <= 2, f" Bitstring {state}: Please remove extra measurements" assert qc.count_ops()['snapshot'] == 3, f" Bitstring {state}: Please do not add or remove snapshots" assert set(qc.count_ops().keys()).difference(basis_gates) == set(), f" Bitstring {state}: Only the following basic gates are allowed: {basis_gates}" assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in qc.data[-2:len(qc.data)]]), f" Bitstring {state}: Measurement must be the last operation in a circuit." result = execute(qc.reverse_bits(),backend=QasmSimulator(), shots=1).result().get_counts().most_frequent() assert state == result, f" Bitstring {state}: Your encoding is not correct" enc_dec_mat[int(state,2), int(result,2)] = 1 sv = execute(qc.reverse_bits(), backend=StatevectorSimulator()).result().data()['snapshots']['statevector'] sv_checks.append(b00_sv.equiv(sv['1'][0])) sv_checks.append(bell_dict[state].equiv(sv['2'][0])) sv_checks.append(Statevector.from_label(state).equiv(sv['3'][0])) assert all(np.diag(enc_dec_mat) == np.ones(4)), "Your encoding is not correct" plt.matshow(enc_dec_mat, cmap='binary') plt.title('Superdense Coding Matrix') plt.xlabel("Alice's encoded bits", fontsize=14) plt.ylabel("Bob's decoded bits", fontsize=14) plt.xticks(ticks=range(4), labels=basis_states, fontsize=12) plt.yticks(ticks=range(4), labels=basis_states, fontsize=12) circ_check = all(sv_checks) assert circ_check, "Your circuit does not work for all bitstrings" print(success_msg if circ_check else fail_msg) except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}')
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries and configuring account import qiskit from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator, StatevectorSimulator from qiskit.visualization import * from qiskit.quantum_info import * success_msg = 'Your answer is correct.' fail_msg = 'Your answer is not correct. Please try again.' basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'barrier', 'measure', 'snapshot'] qc1 = QuantumCircuit(3) # Insert gates below to create the state qc1.h(0) qc1.cx(0,1) qc1.cx(1,2) # Do not change below this line. You do not need to add an additional measurement. qc1.measure_all() qc1.draw('mpl') try: assert list(qc1.count_ops()) != [], "Circuit cannot be empty" assert set(qc1.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in qc1.data[-3:len(qc1.data)]]), "Measurement must be the last operation in a circuit." sv_check = Statevector.from_instruction(qc1.remove_final_measurements(inplace=False)).equiv((Statevector.from_label('000')+Statevector.from_label('111'))/np.sqrt(2)) assert sv_check, "You did not prepare the correct state." job = execute(qc1, backend=QasmSimulator(), shots=1024, seed_simulator=0) counts = job.result().get_counts() print(success_msg if (sv_check) else fail_msg) except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') plot_histogram(counts) bell_prep_circ = QuantumCircuit(2) bell_prep_circ.h(0) bell_prep_circ.cx(0,1) def superdense_coding_circ(bitstr): ''' bitstr is a 2-character string with possible values '00', '01', '10', '11' ''' qc2 = QuantumCircuit(2) # Enter your code below this line # Prepare a Bell state B_00 below qc2.extend(bell_prep_circ) # Do not remove the following line qc2.snapshot('1') # Apply single-qubit gates only on q_0 to encode the bitstring if (bitstr[0] == '1'): qc2.z(0) if (bitstr[1] == '1'): qc2.x(0) # Do not remove the following line qc2.snapshot('2') # Apply gates to change to the Bell basis qc2.extend(bell_prep_circ.inverse()) # Do not remove the following line qc2.snapshot('3') # Do not change below this line. You do not need to add an additional measurement. qc2.measure_all() return qc2 b00_sv = (Statevector.from_label('00')+Statevector.from_label('11'))/np.sqrt(2) b01_sv = (Statevector.from_label('01')+Statevector.from_label('10'))/np.sqrt(2) b10_sv = (Statevector.from_label('00')-Statevector.from_label('11'))/np.sqrt(2) b11_sv = (Statevector.from_label('01')-Statevector.from_label('10'))/np.sqrt(2) bell_states_sv = [b00_sv, b01_sv, b10_sv, b11_sv] basis_states = ['00', '01', '10', '11'] bell_dict = dict(zip(basis_states, bell_states_sv)) enc_dec_mat = np.zeros((len(basis_states),len(basis_states))) try: for state in basis_states: sv_checks = [] qc = superdense_coding_circ(state) assert list(qc.count_ops()) != [], f" Bitstring {state}: Circuit cannot be empty" assert qc.count_ops()['measure'] <= 2, f" Bitstring {state}: Please remove extra measurements" assert qc.count_ops()['snapshot'] == 3, f" Bitstring {state}: Please do not add or remove snapshots" assert set(qc.count_ops().keys()).difference(basis_gates) == set(), f" Bitstring {state}: Only the following basic gates are allowed: {basis_gates}" assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in qc.data[-2:len(qc.data)]]), f" Bitstring {state}: Measurement must be the last operation in a circuit." result = execute(qc.reverse_bits(),backend=QasmSimulator(), shots=1).result().get_counts().most_frequent() assert state == result, f" Bitstring {state}: Your encoding is not correct" enc_dec_mat[int(state,2), int(result,2)] = 1 sv = execute(qc.reverse_bits(), backend=StatevectorSimulator()).result().data()['snapshots']['statevector'] sv_checks.append(b00_sv.equiv(sv['1'][0])) sv_checks.append(bell_dict[state].equiv(sv['2'][0])) sv_checks.append(Statevector.from_label(state).equiv(sv['3'][0])) assert all(np.diag(enc_dec_mat) == np.ones(4)), "Your encoding is not correct" plt.matshow(enc_dec_mat, cmap='binary') plt.title('Superdense Coding Matrix') plt.xlabel("Alice's encoded bits", fontsize=14) plt.ylabel("Bob's decoded bits", fontsize=14) plt.xticks(ticks=range(4), labels=basis_states, fontsize=12) plt.yticks(ticks=range(4), labels=basis_states, fontsize=12) circ_check = all(sv_checks) assert circ_check, "Your circuit does not work for all bitstrings" print(success_msg if circ_check else fail_msg) except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}')
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator from qiskit.visualization import * from qiskit.quantum_info import * basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'ccx', 'barrier', 'measure', 'snapshot'] or_oracle = QuantumCircuit(3) # Do not change below this line or_oracle.draw(output='mpl') or_tt = ['000', '011', '101', '111'] def check_or_oracle(tt_row): check_qc = QuantumCircuit(3) for i in range(2): if (tt_row[i] == '1'): check_qc.x(i) check_qc.extend(or_oracle) check_qc.measure_all() return (execute(check_qc.reverse_bits(),backend=QasmSimulator(), shots=1).result().get_counts().most_frequent() == tt_row) try: assert list(or_oracle.count_ops()) != [], f"Circuit cannot be empty" assert 'measure' not in or_oracle.count_ops(), f"Please remove measurements" assert set(or_oracle.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" for tt_row in or_tt: assert check_or_oracle(tt_row), f" Input {tt_row[0:2]}: Your encoding is not correct" print("Your oracle construction passed all checks") except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') bv_oracle = QuantumCircuit(3) bv_oracle.cx(0,2) bv_oracle.cx(1,2) bv_oracle.draw('mpl') bv_circ = QuantumCircuit(3,2) # Do not remove this line bv_circ.draw(output='mpl') try: assert list(bv_circ.count_ops()) != [], f"Circuit cannot be empty" assert set(bv_circ.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" counts = execute(bv_circ.reverse_bits(), backend=QasmSimulator(), shots=8192).result().get_counts() assert list(counts.keys()) == ['11'], "Your circuit did not produce the right answer" print(" Your circuit produced the correct output. Please submit for evaluation.") except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') plot_histogram(counts)
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator from qiskit.visualization import * from qiskit.quantum_info import * basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'ccx', 'barrier', 'measure', 'snapshot'] or_oracle = QuantumCircuit(3) or_oracle.x(range(2)) or_oracle.ccx(0,1,2) or_oracle.x(range(3)) # Do not change below this line or_oracle.draw(output='mpl') or_tt = ['000', '011', '101', '111'] def check_or_oracle(tt_row): check_qc = QuantumCircuit(3) for i in range(2): if (tt_row[i] == '1'): check_qc.x(i) check_qc.extend(or_oracle) check_qc.measure_all() return (execute(check_qc.reverse_bits(),backend=QasmSimulator(), shots=1).result().get_counts().most_frequent() == tt_row) try: assert list(or_oracle.count_ops()) != [], f"Circuit cannot be empty" assert 'measure' not in or_oracle.count_ops(), f"Please remove measurements" assert set(or_oracle.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" for tt_row in or_tt: assert check_or_oracle(tt_row), f" Input {tt_row[0:2]}: Your encoding is not correct" print("Your oracle construction passed all checks") except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') bv_oracle = QuantumCircuit(3) bv_oracle.cx(0,2) bv_oracle.cx(1,2) bv_oracle.draw('mpl') bv_circ = QuantumCircuit(3,2) bv_circ.x(2) bv_circ.h(range(3)) bv_circ.barrier() # Extend the circuit using bv_oracle bv_circ.extend(bv_oracle) bv_circ.barrier() # Apply the Hadamard transformation on all qubits and then measure q_0 and q_1 bv_circ.h(range(3)) bv_circ.measure([0,1], [0,1]) # Do not remove this line bv_circ.draw(output='mpl') try: assert list(bv_circ.count_ops()) != [], f"Circuit cannot be empty" assert set(bv_circ.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" counts = execute(bv_circ.reverse_bits(), backend=QasmSimulator(), shots=8192).result().get_counts() assert list(counts.keys()) == ['11'], "Your circuit did not produce the right answer" print(" Your circuit produced the correct output. Please submit for evaluation.") except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') plot_histogram(counts)
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
# %pip install numpy==1.19 qiskit==0.20 pylatexenc # Please uncomment this line if you are running on Google Colab or uncomment and run once if you are running locally. %matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator from qiskit.visualization import * import qiskit from packaging.version import parse as parse_version assert parse_version(np.__version__) >= parse_version('1.19'), "Please install the correct version of numpy using the command 'pip install --upgrade numpy==1.19'" assert parse_version(qiskit.__qiskit_version__['qiskit-terra']) >= parse_version('0.15'), "Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience" assert parse_version(qiskit.__qiskit_version__['qiskit-aer']) >= parse_version('0.6'), "Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience" assert parse_version(qiskit.__qiskit_version__['qiskit']) >= parse_version('0.20'),"Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience" from cryptography.fernet import Fernet import base64 basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'barrier', 'measure'] secret_message = b'gAAAAABfevgMDRKfpM75bCBMUfAvaUW_Fjs2PxFYkYOSCldJTUnl8oLKVZRaiPitXqwQwbMTx4YwSCf_n0HQ-RIBvLa58AN4Pi7Fp9hFxGtjwzIpWUXIUr-BGE_9SLvjUGgsQCyrhK9ZJ5Yy9R5F6w4Me0Csr19UU3IqQQIP3ffhInE5o68_CI_URCjHXpBUnztJoDmlBnZz3Ka5NykfUN22iulaFvXOyw==' print(f"The secret message is {secret_message.decode()}") num_qubits = 64 rng = np.random.default_rng(seed=10) alice_state = rng.integers(0, 2, size=num_qubits) bob_basis = rng.integers(0, 2, size=num_qubits) print(f"Alice's State:\t {np.array2string(alice_state, separator='')}") print(f"Bob's Bases:\t {np.array2string(bob_basis, separator='')}") def make_b92_circ(enc_state, meas_basis): ''' A function that makes a B92 QKD protocol simulation circuit enc_state: array of 0s and 1s denoting the state to be encoded using the following scheme: 0 -> |0> 1 -> |+> meas_basis: array of 0s and 1s denoting the basis to be used for measurement 0 -> Hadamard Basis 1 -> Computational Basis Note that both enc_state and meas_basis are arrays of integers, so if you are using them in if statements, compare them to integer values like 0 and 1 (without quotes). Since this is a function, you only have access to the variables enc_state and meas_basis. You may define other local variables. One such variable, num_qubits has been defined for you. This is the number of qubits in the B92 simulation QuantumCircuit() ''' num_qubits = len(enc_state) b92 = QuantumCircuit(num_qubits) # Sender prepares qubits # Add code below to encode the state in qubits b92.barrier() # Receiver measures the received qubits # Add code below to change basis for measurements. DO NOT add a measure() or measure_all() # Do not change below this line b92.measure_all() return b92 try: b92_circ = make_b92_circ(alice_state, bob_basis) assert list(b92_circ.count_ops()) != [], "Circuit cannot be empty" assert set(b92_circ.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in b92_circ.data[-b92_circ.num_qubits:len(b92_circ.data)]]), "Measurement must be the last operation in a circuit." assert b92_circ.count_ops()['measure'] == b92_circ.num_qubits, "Please do not add or remove measurements." temp_key = execute( b92_circ.reverse_bits(), backend=QasmSimulator(), shots=1, seed_simulator=10 ).result().get_counts().most_frequent() assert temp_key == bin(16228741048440553634)[2:], "Your circuit did not perform as expected. Please check the gates again." print(f"Bob's results:\t{temp_key}\nYour answer is correct.") except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') def b92_sifting(enc_state, meas_basis, meas_result): ''' The function that implements key sifting for the B92 QKD protocol. enc_state: array of 0s and 1s denoting the state to be encoded. (Array of integers) meas_basis: array of 0s and 1s denoting the basis to be used for measurement. (Array of integers) meas_result: A string of characters representing the results of measurement after the B92 QKD protocol. Note that this is a string and its elements are characters, so while using any if statements, compare the elements to '0' and '1' (with quotes) Since this is a function, you only have access to the variables enc_state, meas_basis and meas_result. You may define other local variables. num_qubits has been defined for you. This is the number of qubits in the B92 simulation QuantumCircuit. sender_key and receiver_key are initialised as two empty strings. You may append bits using the += operation as shown in the BB84 notebook. Note that you can only add characters. To change from other data types to characters, you may use str(). Check the BB84 notebook for examples. ''' num_qubits = len(enc_state) sender_key = '' receiver_key = '' # Loop over all bits in the meas_result string and add the necessary bits to both sender_key and receiver_key # Add your code below # Do not change bolow this line. return (sender_key, receiver_key) try: alice_key, bob_key = b92_sifting(alice_state, bob_basis, temp_key) assert ''.join([str(x ^ y) for x, y in zip(alice_key.encode(), bob_key.encode())]) != '1'*len(alice_key), "Please check your measurement convention" assert alice_key == bob_key, "They keys are different for Alice and Bob." assert alice_key == bob_key == bin(49522)[2:], "They keys is incorrect. Please check your solutions." print(f"Alice's Key: \t{alice_key}\nBob's Key: \t{bob_key}\nYour answer is correct.") g = Fernet(base64.b64encode(bob_key.encode()*2)) print(f"The secret message is: {g.decrypt(secret_message).decode()}") except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}')
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
# %pip install numpy==1.19 qiskit==0.20 pylatexenc # Please uncomment this line if you are running on Google Colab %matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator from qiskit.visualization import * import qiskit from packaging.version import parse as parse_version assert parse_version(np.__version__) >= parse_version('1.19'), "Please install the correct version of numpy using the command 'pip install --upgrade numpy==1.19'" assert parse_version(qiskit.__qiskit_version__['qiskit-terra']) >= parse_version('0.15'), "Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience" assert parse_version(qiskit.__qiskit_version__['qiskit-aer']) >= parse_version('0.6'), "Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience" assert parse_version(qiskit.__qiskit_version__['qiskit']) >= parse_version('0.20'),"Please make sure you have the correct version of Qiskit installed or run this on IBM Quantum Experience" from cryptography.fernet import Fernet import base64 basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'barrier', 'measure'] secret_message = b'gAAAAABfevgMDRKfpM75bCBMUfAvaUW_Fjs2PxFYkYOSCldJTUnl8oLKVZRaiPitXqwQwbMTx4YwSCf_n0HQ-RIBvLa58AN4Pi7Fp9hFxGtjwzIpWUXIUr-BGE_9SLvjUGgsQCyrhK9ZJ5Yy9R5F6w4Me0Csr19UU3IqQQIP3ffhInE5o68_CI_URCjHXpBUnztJoDmlBnZz3Ka5NykfUN22iulaFvXOyw==' print(f"The secret message is {secret_message.decode()}") num_qubits = 64 rng = np.random.default_rng(seed=10) alice_state = rng.integers(0, 2, size=num_qubits) bob_basis = rng.integers(0, 2, size=num_qubits) print(f"Alice's State:\t {np.array2string(alice_state, separator='')}") print(f"Bob's Bases:\t {np.array2string(bob_basis, separator='')}") def make_b92_circ(enc_state, meas_basis): ''' A function that makes a B92 QKD protocol simulation circuit enc_state: array of 0s and 1s denoting the state to be encoded using the following scheme: 0 -> |0> 1 -> |+> meas_basis: array of 0s and 1s denoting the basis to be used for measurement 0 -> Hadamard Basis 1 -> Computational Basis Note that both enc_state and meas_basis are arrays of integers, so if you are using them in if statements, compare them to integer values like 0 and 1 (without quotes). Since this is a function, you only have access to the variables enc_state and meas_basis. You may define other local variables. One such variable, num_qubits has been defined for you. This is the number of qubits in the B92 simulation QuantumCircuit() ''' num_qubits = len(enc_state) b92 = QuantumCircuit(num_qubits) # Sender prepares qubits # Add code below to encode the state in qubits for index in range(len(enc_state)): if enc_state[index] == 1: b92.h(index) b92.barrier() # Receiver measures the received qubits # Add code below to change basis for measurements. DO NOT add a measure() or measure_all() for index in range(len(meas_basis)): if meas_basis[index] == 0: b92.h(index) # Do not change below this line b92.measure_all() return b92 try: b92_circ = make_b92_circ(alice_state, bob_basis) assert list(b92_circ.count_ops()) != [], "Circuit cannot be empty" assert set(b92_circ.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}" assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in b92_circ.data[-b92_circ.num_qubits:len(b92_circ.data)]]), "Measurement must be the last operation in a circuit." assert b92_circ.count_ops()['measure'] == b92_circ.num_qubits, "Please do not add or remove measurements." temp_key = execute( b92_circ.reverse_bits(), backend=QasmSimulator(), shots=1, seed_simulator=10 ).result().get_counts().most_frequent() assert temp_key == bin(16228741048440553634)[2:], "Your circuit did not perform as expected. Please check the gates again." print(f"Bob's results:\t{temp_key}\nYour answer is correct.") except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}') def b92_sifting(enc_state, meas_basis, meas_result): ''' The function that implements key sifting for the B92 QKD protocol. enc_state: array of 0s and 1s denoting the state to be encoded. (Array of integers) meas_basis: array of 0s and 1s denoting the basis to be used for measurement. (Array of integers) meas_result: A string of characters representing the results of measurement after the B92 QKD protocol. Note that this is a string and its elements are characters, so while using any if statements, compare the elements to '0' and '1' (with quotes) Since this is a function, you only have access to the variables enc_state, meas_basis and meas_result. You may define other local variables. num_qubits has been defined for you. This is the number of qubits in the B92 simulation QuantumCircuit. sender_key and receiver_key are initialised as two empty strings. You may append bits using the += operation as shown in the BB84 notebook. Note that you can only add characters. To change from other data types to characters, you may use str(). Check the BB84 notebook for examples. ''' num_qubits = len(enc_state) sender_key = '' receiver_key = '' # Loop over all bits in the meas_result string and add the necessary bits to both sender_key and receiver_key # Add your code below for i in range(len(meas_result)): if meas_result[i] == '1': # Only choose bits where Bob measured a 1 sender_key += str(enc_state[i]) receiver_key += str(meas_basis[i]) # Do not change bolow this line. return (sender_key, receiver_key) try: alice_key, bob_key = b92_sifting(alice_state, bob_basis, temp_key) assert ''.join([str(x ^ y) for x, y in zip(alice_key.encode(), bob_key.encode())]) != '1'*len(alice_key), "Please check your measurement convention" assert alice_key == bob_key, "They keys are different for Alice and Bob." assert alice_key == bob_key == bin(49522)[2:], "They keys is incorrect. Please check your solutions." print(f"Alice's Key: \t{alice_key}\nBob's Key: \t{bob_key}\nYour answer is correct.") g = Fernet(base64.b64encode(bob_key.encode()*2)) print(f"The secret message is: {g.decrypt(secret_message).decode()}") except AssertionError as e: print(f'Your code has an error: {e.args[0]}') except Exception as e: print(f'This error occured: {e.args[0]}')
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
import math import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.visualization import plot_bloch_multivector from qiskit.visualization import plot_bloch_vector from qiskit.visualization import plot_histogram qbackend = Aer.get_backend('qasm_simulator') sbackend = Aer.get_backend('statevector_simulator') ubackend = Aer.get_backend('unitary_simulator') qiskit.__version__ import torch torch.__version__ import strawberryfields as sf sf.__version__ help(sf) import cirq cirq.__version__
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram import numpy as np #prepares the initial quantum states for the BB84 protocol by generating a list of quantum states and their associated bases. def prepare_bb84_states(num_qubits): states = [] bases = [] for _ in range(num_qubits): state, basis = generate_bb84_state() states.append(state) bases.append(basis) return states, bases #generates a single BB84 quantum state and its associated measurement basis. def generate_bb84_state(): basis = np.random.randint(2) # 0 for rectilinear basis, 1 for diagonal basis if np.random.rand() < 0.5: state = QuantumCircuit(1, 1) if basis == 0: state.h(0) else: state.s(0) state.h(0) else: state = QuantumCircuit(1, 1) if basis == 0: state.x(0) state.h(0) else: state.x(0) state.s(0) state.h(0) return state, basis #measures the quantum states with the appropriate basis and returns the measurement results def measure_bb84_states(states, bases): measurements = [] for state, basis in zip(states, bases): if basis == 0: state.measure(0, 0) else: state.h(0) state.measure(0, 0) measurements.append(state) return measurements #sifts the keys by comparing Alice and Bob's measurement bases and bits. It checks if the measurement bases match (the same basis) and appends the corresponding bits to the sifted keys def sift_keys(alice_bases, bob_bases, alice_bits, bob_bits): sifted_alice_bits = [] sifted_bob_bits = [] for a_basis, b_basis, a_bit, b_bit in zip(alice_bases, bob_bases, alice_bits, bob_bits): if a_basis == b_basis: sifted_alice_bits.append(a_bit) sifted_bob_bits.append(b_bit) return sifted_alice_bits, sifted_bob_bits #calculates the error rate between Alice's and Bob's sifted bits def error_rate(alice_bits, bob_bits): errors = sum([1 for a, b in zip(alice_bits, bob_bits) if a != b]) return errors / len(alice_bits) # simulates the BB84 protocol num_qubits = 100 num_qubits = 100 alice_states, alice_bases = prepare_bb84_states(num_qubits) bob_bases = np.random.randint(2, size=num_qubits) bob_measurements = measure_bb84_states(alice_states, bob_bases) alice_bits = [] for state in alice_states: result = execute(state, Aer.get_backend('qasm_simulator')).result() counts = result.get_counts(state) max_count = max(counts, key=counts.get) alice_bits.append(int(max_count)) bob_bits = [] for state in bob_measurements: result = execute(state, Aer.get_backend('qasm_simulator')).result() counts = result.get_counts(state) max_count = max(counts, key=counts.get) bob_bits.append(int(max_count)) sifted_alice_bits, sifted_bob_bits = sift_keys(alice_bases, bob_bases, alice_bits, bob_bits) error = error_rate(sifted_alice_bits, sifted_bob_bits) final_key = privacy_amplification(sifted_alice_bits) print("Sifted key length:", len(sifted_alice_bits)) print("Error rate:", error) print("Final secret key:", final_key)
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator from qiskit.visualization import * num_qubits = 32 alice_basis = np.random.randint(2, size=num_qubits) alice_state = np.random.randint(2, size=num_qubits) bob_basis = np.random.randint(2, size=num_qubits) oscar_basis = np.random.randint(2, size=num_qubits) print(f"Alice's State:\t {np.array2string(alice_state, separator='')}") print(f"Alice's Bases:\t {np.array2string(alice_basis, separator='')}") print(f"Oscar's Bases:\t {np.array2string(oscar_basis, separator='')}") print(f"Bob's Bases:\t {np.array2string(bob_basis, separator='')}") def make_bb84_circ(enc_state, enc_basis, meas_basis): ''' enc_state: array of 0s and 1s denoting the state to be encoded enc_basis: array of 0s and 1s denoting the basis to be used for encoding 0 -> Computational Basis 1 -> Hadamard Basis meas_basis: array of 0s and 1s denoting the basis to be used for measurement 0 -> Computational Basis 1 -> Hadamard Basis ''' num_qubits = len(enc_state) bb84_circ = QuantumCircuit(num_qubits) # Sender prepares qubits for index in range(len(enc_basis)): if enc_state[index] == 1: bb84_circ.x(index) if enc_basis[index] == 1: bb84_circ.h(index) bb84_circ.barrier() # Receiver measures the received qubits for index in range(len(meas_basis)): if meas_basis[index] == 1: bb84_circ.h(index) bb84_circ.measure_all() return bb84_circ bb84_AO = make_bb84_circ(alice_state, alice_basis, oscar_basis) oscar_result = execute(bb84_AO.reverse_bits(), backend=QasmSimulator(), shots=1).result().get_counts().most_frequent() print(f"Oscar's results:\t {oscar_result}") # Converting string to array oscar_state = np.array(list(oscar_result), dtype=int) print(f"Oscar's State:\t\t{np.array2string(oscar_state, separator='')}") bb84_OB = make_bb84_circ(oscar_state, oscar_basis, bob_basis) temp_key = execute(bb84_OB.reverse_bits(), backend=QasmSimulator(), shots=1).result().get_counts().most_frequent() print(f"Bob's results:\t\t {temp_key}") alice_key = '' bob_key = '' oscar_key = '' for i in range(num_qubits): if alice_basis[i] == bob_basis[i]: # Only choose bits where Alice and Bob chose the same basis alice_key += str(alice_state[i]) bob_key += str(temp_key[i]) oscar_key += str(oscar_result[i]) print(f"The length of the key is {len(bob_key)}") print(f"Alice's key contains\t {(alice_key).count('0')} zeroes and {(alice_key).count('1')} ones") print(f"Bob's key contains\t {(bob_key).count('0')} zeroes and {(bob_key).count('1')} ones") print(f"Oscar's key contains\t {(oscar_key).count('0')} zeroes and {(oscar_key).count('1')} ones") print(f"Alice's Key:\t {alice_key}") print(f"Bob's Key:\t {bob_key}") print(f"Oscar's Key:\t {oscar_key}")
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%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 * # Loading your IBM Q account(s) provider = IBMQ.load_account() a = 5 print(a) import numpy as np print(np.pi) print(np.random.randint(10)) from numpy.random import randint randint(10) a = -5 # Integers print(a) b = 16.001 # Floating point numbers print(b) c = 1+3j # Complex numbers print(c) list1 = [1,2,3,4] # A list of integers print(list1) print(len(list1)) # The number of elements list2 = [] # Square brackets initialises an empty list list2.append(10) # Append an element to the end of a list print(list2) print(list1[3]) # Accessing an element using square brackets. Indices start from 0 list1.remove(3) # Remove the element 3 print(list1) string1 = "Hello, World!" # Single or double quotes print(string1) print(string1[6:]) # Strings behave like a list of characters counts = { # Dictionaries are key-value pairs '00': 200, '10': 150, '01': 200, '11': 250 } counts.keys() # Get all the keys counts.values() # Get all the values counts.items() val = 10 if (val < 10): print("less than 10") else: print('10 or more') for i in range(0,11,2): # Range creates a list print(i) for num in [10,5,2,4]: print(num) for key, value in counts.items(): print(key, value) def foo(x): print(x) foo('hello') foo(10) def square(x): return x**2 square(4)
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator from qiskit.visualization import * from qiskit.quantum_info import * q1_sv = Statevector.from_label('0') q2_sv = Statevector.from_label('1') prod_sv = q1_sv.tensor(q2_sv) print(prod_sv.data) prod_sv2 = Statevector.from_label('01') print(prod_sv2.data) op1 = Operator.from_label('X') op2 = Operator.from_label('I') prod_op = op1.tensor(op2) print(prod_op.data) prod_op2 = Operator.from_label('XI') print(prod_op2.data) q1_sv_1 = q1_sv.evolve(op1) q2_sv_1 = q2_sv.evolve(op2) prod_sv_1 = q1_sv_1.tensor(q2_sv_1) prod_sv2_1 = prod_sv2.evolve(prod_op2) prod_sv_1.equiv(prod_sv2_1) qc = QuantumCircuit(2) # All qubits start in the |0> state qc.x(0) qc.draw(output='mpl') # qc.measure(0,0) # First argument is the qubit to be measured print(Operator(qc).data) Operator(qc).equiv(prod_op2) qc_rev = qc.reverse_bits() qc_rev.draw(output='mpl') print(Operator(qc_rev).data) Operator(qc_rev).equiv(prod_op2) qc2 = QuantumCircuit(2) qc2.h([0,1]) qc2.measure_all() qc2.draw(output='mpl') job = execute(qc2, backend=QasmSimulator(), shots=8192) result = job.result() result.get_counts() qc2_rev = qc2.reverse_bits() qc2_rev.draw(output='mpl') job = execute(qc2_rev, backend=QasmSimulator(), shots=8192) result = job.result() result.get_counts() qc = QuantumCircuit(2) qc.cx(0,1) qc.draw(output='mpl') cnot_op = Operator(qc) sv = Statevector.from_label('0+') # Little Endian sv2 = sv.evolve(cnot_op) plot_bloch_multivector(sv) plot_bloch_multivector(sv2) sv2.data
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, IBMQ from qiskit.compiler import transpile from qiskit.providers.aer import QasmSimulator, StatevectorSimulator from qiskit.visualization import * from qiskit.quantum_info import * qc1 = QuantumCircuit(1) qc1.x(0) qc1.measure_all() qc1.draw(output='mpl') job1 = execute(qc1, backend=QasmSimulator(), shots=1024) plot_histogram(job1.result().get_counts()) qc2 = QuantumCircuit(2) # State Preparation qc2.x(0) qc2.barrier() # Perform q_0 XOR 0 qc2.cx(0,1) qc2.measure_all() qc2.draw(output='mpl') job2 = execute(qc2.reverse_bits(), backend=QasmSimulator(), shots=1024) plot_histogram(job2.result().get_counts()) qc3 = QuantumCircuit(3) # State Preparation qc3.x(0) qc3.x(1) qc3.barrier() # Perform q_0 XOR 0 qc3.ccx(0,1,2) qc3.measure_all() qc3.draw(output='mpl') job3 = execute(qc3.reverse_bits(), backend=QasmSimulator(), shots=1024) plot_histogram(job3.result().get_counts()) qc4 = QuantumCircuit(3) # State Preparation qc4.h(range(3)) qc4.measure_all() qc4.draw(output='mpl') job4 = execute(qc4.reverse_bits(), backend=QasmSimulator(), shots=8192) plot_histogram(job4.result().get_counts()) from qiskit.providers.aer.noise import NoiseModel from qiskit.test.mock import FakeMelbourne device_backend = FakeMelbourne() coupling_map = device_backend.configuration().coupling_map noise_model = NoiseModel.from_backend(device_backend) basis_gates = noise_model.basis_gates result_noise = execute(qc4, QasmSimulator(), shots=8192, noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates).result() plot_histogram(result_noise.get_counts()) qc3_t = transpile(qc3, basis_gates=basis_gates) qc3_t.draw(output='mpl') # Loading your IBM Q account(s) provider = IBMQ.load_account() provider.backends() ibmq_backend = provider.get_backend('ibmq_16_melbourne') result_device = execute(qc4, backend=ibmq_backend, shots=8192).result() plot_histogram(result_device.get_counts())
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute from qiskit.providers.aer import QasmSimulator from qiskit.visualization import * from qiskit.quantum_info import * q1_sv = Statevector.from_label('+') # Available basis states are 0, 1, +, -, l, r print(q1_sv.data) q1_sv.is_valid() print(q1_sv.probabilities_dict()) print(sum(q1_sv.probabilities())) outcome, new_sv = q1_sv.measure() # This returns two values print(f'The outcome of measurement was {outcome}') print(f'The collapsed statevector after measurement is {new_sv.data}') outcome2, new2_sv = new_sv.measure() # This returns two values print('Measured collapsed statevector') print(f'The outcome of measurement was {outcome2}') print(f'The collapsed statevector after measurement is {new2_sv.data}') q1_sv = Statevector.from_label('+') measured_values = [int(q1_sv.measure()[0]) for _ in range(1000)] print(f'Number of 0 measured: {measured_values.count(0)}, Number of 1 measured: {measured_values.count(1)}') q1_sv = Statevector.from_label('+') # Available basis states are 0, 1, +, -, l, r plot_bloch_multivector(q1_sv) op1 = Operator.from_label('X') # I, X, Y, Z, S, T, H print(op1.data) op1.is_unitary() op1_adj = op1.adjoint() print(op1_adj.data) res = op1*op1_adj print(res.data) q2_sv_0 = Statevector.from_label('+') plot_bloch_multivector(q2_sv_0) op1 = Operator.from_label('Z') q2_sv_1 = q2_sv_0.evolve(op1) plot_bloch_multivector(q2_sv_1) op2 = Operator.from_label('Z') q2_sv_2 = q2_sv_1.evolve(op2.adjoint()) plot_bloch_multivector(q2_sv_2) print(q2_sv_0 == q2_sv_2) qc = QuantumCircuit(1) qc.h(0) qc.z(0) qc.draw(output='mpl') visualize_transition(qc, trace=True) qc = QuantumCircuit(1) qc.h(0) qc.z(0) qc.measure_all() qc.draw(output='mpl') job = execute(qc, backend=QasmSimulator(), shots=1024) plot_histogram(job.result().get_counts()) job.result().get_counts()
https://github.com/abhishekchak52/quantum-computing-course
abhishekchak52
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex from qiskit.extensions import Initialize from qiskit.ignis.verification import marginal_counts from qiskit.quantum_info import random_statevector # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ## SETUP # Protocol uses 3 qubits and 2 classical bits in 2 different registers qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical bits crx = ClassicalRegister(1, name="crx") # in 2 different registers teleportation_circuit = QuantumCircuit(qr, crz, crx) def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a,b) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, psi, a): qc.cx(psi, a) qc.h(psi) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): """Measures qubits a & b and 'sends' the results to Bob""" qc.barrier() qc.measure(a,0) qc.measure(b,1) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) measure_and_send(teleportation_circuit, 0 ,1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) # Apply gates if the registers qc.z(qubit).c_if(crz, 1) # are in the state '1' qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) ## STEP 3 measure_and_send(teleportation_circuit, 0, 1) ## STEP 4 teleportation_circuit.barrier() # Use barrier to separate steps bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() # Create random 1-qubit state psi = random_statevector(2) # Display it nicely display(array_to_latex(psi, prefix="|\\psi\\rangle =")) # Show it on a Bloch sphere plot_bloch_multivector(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) ## STEP 0 # First, let's initialize Alice's q0 qc.append(init_gate, [0]) qc.barrier() ## STEP 1 # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() ## STEP 2 # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) ## STEP 3 # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) ## STEP 4 # Bob decodes qubits bob_gates(qc, 2, crz, crx) # Display the circuit qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() plot_bloch_multivector(out_vector)
https://github.com/farhad-abdi/InSilicoQ
farhad-abdi
""" Quantum Data Encoding Functions: Basis Encoding, Amplitude Encoding, Angle Encoding """ from qiskit import QuantumCircuit from sklearn.preprocessing import normalize #import normalization function from qiskit.circuit.library import ZFeatureMap import numpy as np import math def angle_encoding(num_qubit, data): ''' Args: num_qubit : number of feature space dimesnion data : 1D array real data to be encoded Return: Quantum Data Circuit Object ''' data = normalize(data) feature_map = ZFeatureMap(feature_dimension= num_qubit, reps = 1 ) data_circ = feature_map.assign_parameters(data[0]/2) return data_circ def amplitude_encoding(data): ''' Args: data: 1D numpy array Return: Quantum Circ ''' cof = np.sum(np.power(data,2)) state = (1/np.sqrt(cof)) * data num_qubit = int(math.log2(len(data))) #how many time decopose trail and error!? decompose_time = len(data) circ = QuantumCircuit(num_qubit) circ.prepare_state(state, list(np.arange(num_qubit))) circ = circ.decompose(reps = decompose_time) return circ
https://github.com/farhad-abdi/InSilicoQ
farhad-abdi
import numpy as np from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram # Importing qiskit machine learning parameters from qiskit.circuit import Parameter, ParameterVector from qiskit.circuit.library import TwoLocal #first net imports from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.primitives import Sampler from qiskit_machine_learning.connectors import TorchConnector from qiskit_machine_learning.neural_networks import SamplerQNN # created quantum neural network in TorchConnector to make use of PyTorch-based training. def QGenerator(num_qubits) -> TorchConnector: qc = QuantumCircuit(num_qubits) qc.h(qc.qubits) ansatz = EfficientSU2(num_qubits, reps=6) qc.compose(ansatz, inplace=True) print(qc.num_parameters) shots = 10000 sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed}) qnn = SamplerQNN( circuit=qc, sampler=sampler, input_params=[], weight_params=qc.parameters, sparse=False, ) initial_weights = algorithm_globals.random.random(qc.num_parameters) return TorchConnector(qnn, initial_weights) #alternative qgan class QGAN: def __init__(self, num_qubit): self.num_q = num_qubit def qgenerator(self): generator = TwoLocal(self.num_q, # Parameterized single qubit rotations ['ry', 'rz'], 'cz', # Entangling gate 'full', # Entanglement structure: all to all reps=2, # Number of layers parameter_prefix='θ_g', name='Generator') generator = generator.decompose() # decompose into standard gates return generator def qdiscriminator(self): disc_weights = ParameterVector('θ_d', 12) discriminator = QuantumCircuit(3, name="Discriminator") discriminator.barrier() discriminator.h(0) discriminator.rx(disc_weights[0], 0) discriminator.ry(disc_weights[1], 0) discriminator.rz(disc_weights[2], 0) discriminator.rx(disc_weights[3], 1) discriminator.ry(disc_weights[4], 1) discriminator.rz(disc_weights[5], 1) discriminator.rx(disc_weights[6], 2) discriminator.ry(disc_weights[7], 2) discriminator.rz(disc_weights[8], 2) discriminator.cx(0, 2) discriminator.cx(1, 2) discriminator.rx(disc_weights[9], 2) discriminator.ry(disc_weights[10], 2) discriminator.rz(disc_weights[11], 2) #discriminator.draw() return discriminator def qgan_model(self): qgan = QuantumCircuit(self.num_q +1 ) qgan.compose(self.qgenerator(), inplace = True) qgan.compose(self.qdiscriminator(), inplace = True) return qgan
https://github.com/farhad-abdi/InSilicoQ
farhad-abdi
""" A collection of quantum graph based algorithms, the algorthms are mostly based on Grover Serach algorithm""" from qiskit import QuantumCircuit class MST: """ Mininum Spanning Tree Implementation """ def __init__(self, num_qubit): self.num_q = num_qubit def oracle_mst(self): oracle = QuantumCircuit(self.num_q) return oracle def diffuser_mst(self): diffuser = QuantumCircuit(self.num_q) return diffuser
https://github.com/farhad-abdi/InSilicoQ
farhad-abdi
# Quantum Kernel Machine Learning Functions import numpy as np ## Utilities import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from typing import Optional, Callable, List, Union from functools import reduce # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.visualization import * # Qiskit imports from qiskit import BasicAer from qiskit.circuit.library import ZZFeatureMap, PauliFeatureMap from qiskit.utils import QuantumInstance, algorithm_globals #Qiskit Machine Learning imports from qiskit_machine_learning.algorithms import QSVC from qiskit_machine_learning.kernels import QuantumKernel from qiskit_machine_learning.datasets import ad_hoc_data # seed for ramdomization, to keep outputs consistent seed = 123456 #Quantum Computing Backend used in Quantum Kernels qcomp_backend = QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024, seed_simulator=seed, seed_transpiler=seed) """ The following functions are implementations of ref[2] and the corresponding equations are numberd according to the paper. """ def data_map_eq8(x: np.ndarray) -> float: """ Define a function map from R^n to R. Args: x: data Returns: float: the mapped value """ coeff = x[0] if len(x) == 1 else reduce(lambda m, n: np.pi*(m * n), x) return coeff def data_map_eq9(x: np.ndarray) -> float: coeff = x[0] if len(x) == 1 else reduce(lambda m, n: (np.pi/2)*(m * n), 1 - x) return coeff def data_map_eq10(x: np.ndarray) -> float: coeff = x[0] if len(x) == 1 else reduce(lambda m, n: np.pi*np.exp(((m - n)*(m - n))/8), x) return coeff def data_map_eq11(x: np.ndarray) -> float: coeff = x[0] if len(x) == 1 else reduce(lambda m, n: (np.pi/3)*(m * n), 1/(np.cos(x))) return coeff def data_map_eq12(x: np.ndarray) -> float: coeff = x[0] if len(x) == 1 else reduce(lambda m, n: np.pi*(m * n), np.cos(x)) return coeff #Define Quantum Kernels Functions def qkern_default(): qfm_default = PauliFeatureMap(feature_dimension=2, paulis = ['ZI','IZ','ZZ'], reps=2, entanglement='full') return QuantumKernel(feature_map=qfm_default, quantum_instance=qcomp_backend) def qkern_eq8(): qfm_eq8 = PauliFeatureMap(feature_dimension=2, paulis = ['ZI','IZ','ZZ'], reps=2, entanglement='full', data_map_func=data_map_eq8) return QuantumKernel(feature_map=qfm_eq8, quantum_instance=qcomp_backend) def qkern_eq9(): qfm_eq9 = PauliFeatureMap(feature_dimension=2, paulis = ['ZI','IZ','ZZ'], reps=2, entanglement='full', data_map_func=data_map_eq9) return QuantumKernel(feature_map=qfm_eq9, quantum_instance=qcomp_backend) def qkern_eq10(): qfm_eq10 = PauliFeatureMap(feature_dimension=2, paulis = ['ZI','IZ','ZZ'], reps=2, entanglement='full', data_map_func=data_map_eq10) return QuantumKernel(feature_map=qfm_eq10, quantum_instance=qcomp_backend) def qkern_eq11(): qfm_eq11 = PauliFeatureMap(feature_dimension=2, paulis = ['ZI','IZ','ZZ'], reps=2, entanglement='full', data_map_func=data_map_eq11) return QuantumKernel(feature_map=qfm_eq11, quantum_instance=qcomp_backend) def qkern_eq12(): qfm_eq12 = PauliFeatureMap(feature_dimension=2, paulis = ['ZI','IZ','ZZ'], reps=2, entanglement='full', data_map_func=data_map_eq12) return QuantumKernel(feature_map=qfm_eq12, quantum_instance=qcomp_backend)
https://github.com/farhad-abdi/InSilicoQ
farhad-abdi
#importing packages import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble from qiskit.visualization import * ####################### #IMPLEMENTING QUANTUM CLASS: 1 trainable parameter #Hadamard gate (superposition) + Rotation_Y (trainable parameter) + Measure_Z. Returning the expectation value over n_shots class QuantumCircuit: """ This class provides an interface to interact with our Quantum Circuit """ def __init__(self, n_qubits, backend, shots): #-----Circuit definition self._circuit = qiskit.QuantumCircuit(n_qubits) self.theta = qiskit.circuit.Parameter('theta') all_qubits = [i for i in range (n_qubits)]#qubits vector self._circuit.h(all_qubits)#over all the qubits self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() #----- self.backend = backend self.shots = shots def run(self, thetas): #acting on a simulator t_qc = transpile(self._circuit, self.backend)#matching the features of a quantum device qobj = assemble(t_qc, shots = self.shots, parameter_binds = [{self.theta: theta} for theta in thetas])#assembling features (circuit, sampling, parameter list) job = self.backend.run(qobj)#running on the simulator result = job.result().get_counts() #counts for each values: |0> or |1>. DIVERSO DA LINK counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probability for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) #testing the implementation simulator = qiskit.Aer.get_backend('qasm_simulator') n_qubits = 1 circuit = QuantumCircuit(n_qubits, simulator, 100) print(circuit._circuit) #circuit._circuit.draw(output='mpl')#to print as a pyplot figure (new library needed) exp = circuit.run([np.pi]) print('Expected value for rotation pi: {}'.format(exp[0])) ####################### #CREATING A QUANTUM CLASSICAL CLASS #extending autograd functions for a quantum layer(forward and backward) class HybridFunction(Function): """Hybrid quantum-classical function definition""" @staticmethod def forward(ctx, input, quantum_circuit, shift): """Forward pass computation""" ctx.shift = shift ctx.quantum_circuit = quantum_circuit # context variable (it may take multiple values and return them related to the context). Used to keep track for backpropagation expectation_z = ctx.quantum_circuit.run(input[0].tolist()) #evaluating model with trainable parameter result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) #saves a given tensor for a future call to backward (trainable parameter and the result obtained) return result @staticmethod def backward(ctx, grad_output): #grad_output os previous gradient """Backward computation""" input, expectation =ctx.saved_tensors #evaluated in forward input_list = np.array(input.tolist()) #shifting parameters shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients=[] for i in range(len(input_list)): #evaluating model after shift expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) #evaluating gradient with finite difference formula gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None #returns the chain of previous gradient and evaluated gradient class Hybrid(nn.Module): """Hybrid quantum-cassical layer definition""" def __init__(self, n_qubits ,backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(n_qubits, backend, shots) self.shift = shift #parameter shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) #calling forward and backward ##################3 #DATA LOADING #training data n_samples=100 X_train=datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])) #keeping only labels 0 and 1 idx=np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]) X_train.data = X_train.data[idx] #tensor values X_train.targets = X_train.targets[idx]#tensor labels #making batches (dim = 1). Ir returns an iterable(pytorch tensor) train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True) data_iter = iter(train_loader)#making the iterable an iterator, an object with the next method that can be used in a for cycle #showing samples n_samples_show = 6 fig, axes = plt.subplots(nrows=1, ncols=int(n_samples_show), figsize=(10, 3)) #subolot returns the figure and axis that are indipendent as default while n_samples_show > 0: images, targets = data_iter.__next__() axes[int(n_samples_show) - 1].imshow(images[0].numpy().squeeze(), cmap='gray')#squeeze removes unuseful dim(1). Converting into a numpy vector axes[int(n_samples_show) - 1].set_xticks([]) axes[int(n_samples_show) - 1].set_yticks([]) axes[int(n_samples_show) - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 #validation data n_samples = 50 X_test = datasets.MNIST(root='./data', train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])) idx = np.append(np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]) X_test.data = X_test.data[idx] X_test.targets = X_test.targets[idx] test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True) ######################### #CREATING THE NN class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=5) #input = gray scale self.conv2 = nn.Conv2d(6, 16, kernel_size=5) self.dropout = nn.Dropout2d() #deactivating randomly some neurons to avoid overfitting self.fc1 = nn.Linear(256, 64) #input dimension: CH(16) x Matrix_dim (4x4) self.fc2 = nn.Linear(64,1) self.hybrid = Hybrid(n_qubits, qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi/2 ) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)),2) x = F.max_pool2d(F.relu(self.conv2(x)),2) x = self.dropout(x) x = x.view(1,-1) #reshaping tensor x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) #calling the forward method return torch.cat((x, 1-x),-1)#returning probabilities ####################### #TRAINING AND TESTING #function to train the nn def training_loop (n_epochs, optimizer, model, loss_fn, train_loader): loss_values = [] for epoch in range(0, n_epochs, +1): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad()#getting rid of previous gradients output = model(data)#forward pass loss = loss_fn(output, target) loss.backward() optimizer.step()#updating parameters total_loss.append(loss.item())#item transforms into a number loss_values.append(sum(total_loss)/len(total_loss))#obtainign the average loss print('Training [{:.0f}%] Loss: {:.4f}'.format(100*(epoch+1)/n_epochs, loss_values[-1])) return loss_values #defining a function to test our net def validate(model, test_loader, loss_function, n_test, axes): correct = 0 total_loss = [] count = 0 with torch.no_grad(): # disabling the gradient as we don't want to update parameters for batch_idx, (data, target) in enumerate(test_loader): output = model(data) #evaluating the model on test data # evaluating the accuracy of our model pred = output.argmax(dim=1, keepdim=True) # we are interested in the max value of probability correct += pred.eq(target.view_as(pred)).sum().item() # checking if it matches with label #evluating loss function loss = loss_function(output, target) total_loss.append(loss.item()) #printing the resut as images if count >= n_test: continue else: axes[count].imshow(data[0].numpy().squeeze(), cmap='gray') axes[count].set_xticks([]) axes[count].set_yticks([]) axes[count].set_title('Predicted {}'.format(pred.item())) count += 1 print('Performance on test data: \n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%' .format(sum(total_loss)/len(total_loss),(correct / len(test_loader))*100)) #Training the NN #we can use any optimiser, learning rate and cost/loss function to train over multiple epochs model = Net() params = list(model.parameters()) learning_rate = 0.001 optimizer = optim.Adam(params, learning_rate) loss_func = nn.NLLLoss() epochs = 20 loss_list = [] model.train() #training the module in training mode(specifying the intention to the layers). Used for dropout or batchnorm loss_list = (training_loop(epochs, optimizer, model, loss_func, train_loader)) #plotting the training graph plt.figure(num=2) plt.plot(loss_list) plt.title('Hybrid NN Training convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') ########################### #TESTING THE NN n_test_show = 6 fig, axes = plt.subplots(nrows=1, ncols=n_test_show, figsize=(10, 3)) model.eval() validate(model, test_loader, loss_func, n_test_show, axes) plt.show()
https://github.com/scaleway/qiskit-scaleway
scaleway
# Copyright 2024 Scaleway # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cirq import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit_scaleway import ScalewayProvider provider = ScalewayProvider( project_id="<your-scaleway-project-id>", secret_key="<your-scaleway-secret-key>", ) # Scaleway provides Qsim backend, whichs is compatible with Cirq SDK backend = provider.get_backend("qsim_simulation_l40s") # Define a quantum circuit that produces a 4-qubit GHZ state. qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.measure_all() # Create a QPU's session with Qsim installed for a limited duration session_id = backend.start_session( deduplication_id="my-qsim-session-workshop", max_duration="2h" ) # Create and send a job to the target session qsim_job = backend.run(qc, shots=1000, session_id=session_id) # Wait and get the result # To retrieve the result as Cirq result, you need to have Cirq package installed cirq_result = qsim_job.result(format="cirq") # Display the Cirq Result cirq.plot_state_histogram(cirq_result, plt.subplot()) plt.show() # Revoke manually the QPU's session if needed # If not done, will be revoked automatically after 2 hours backend.stop_session(session_id)
https://github.com/scaleway/qiskit-scaleway
scaleway
# Copyright 2024 Scaleway # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from qiskit.visualization import plot_histogram from qiskit import QuantumCircuit from qiskit_scaleway import ScalewayProvider provider = ScalewayProvider( project_id="<your-scaleway-project-id>", secret_key="<your-scaleway-secret-key>", ) # Scaleway provides Qsim backend, whichs is compatible with Cirq SDK backend = provider.get_backend("qsim_simulation_l40s") # Define a quantum circuit that produces a 4-qubit GHZ state. qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.measure_all() # Create a QPU's session with Qsim installed for a limited duration session_id = backend.start_session( deduplication_id="my-qsim-session-workshop", max_duration="2h" ) # Create and send a job to the target session qsim_job = backend.run(qc, shots=1000, session_id=session_id) # Wait and get the Qiskit result qiskit_result = qsim_job.result() # Display the result plot_histogram(qiskit_result.get_counts()) # Revoke manually the QPU's session if needed # If not done, will be revoked automatically after 2 hours backend.stop_session(session_id)
https://github.com/scaleway/qiskit-scaleway
scaleway
# Copyright 2024 Scaleway # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from qiskit import QuantumCircuit from qiskit_scaleway import ScalewayProvider provider = ScalewayProvider( project_id="<your-scaleway-project-id>", secret_key="<your-scaleway-secret-key>", ) # Retrieve a backend by providing search criteria. The search must have a single match backend = provider.get_backend("aer_simulation_2l4") # Define a quantum circuit that produces a 4-qubit GHZ state. qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.measure_all() # Create a QPU's session for a limited duration, a max_idle_duration can also be specified session_id = backend.start_session( deduplication_id="my-aer-session-workshop", max_duration="2h" ) # Create and send a job to the target session result = backend.run(qc, shots=1000, session_id=session_id).result() if result.success: print(result.get_counts()) else: print(result.to_dict()["error"]) # Revoke manually the QPU's session if needed # If not done, will be revoked automatically after 2 hours backend.stop_session(session_id)
https://github.com/scaleway/qiskit-scaleway
scaleway
# Copyright 2024 Scaleway # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from qiskit import QuantumCircuit from qiskit_scaleway import ScalewayProvider provider = ScalewayProvider( project_id="<your-scaleway-project-id>", secret_key="<your-scaleway-secret-key>", ) # Retrieve a backend by providing search criteria. The search must have a single match backend = provider.get_backend("aer_simulation_2l4") # Define a quantum circuit that produces a 4-qubit GHZ state. qc = QuantumCircuit(4) qc.h(0) qc.cx(0, 1) qc.cx(0, 2) qc.cx(0, 3) qc.measure_all() # Create and send a job to the new QPU's session (or on an existing one) result = backend.run(qc, shots=1000).result() if result.success: print(result.get_counts()) else: print(result.to_dict()["error"])
https://github.com/scaleway/qiskit-scaleway
scaleway
# Practical Implementation of a Quantum String Matching Algorithm # S. Faro, F.P. Marino, and A. Scardace # QUASAR 2024 %%capture !pip install ibm-cloud-sdk-core==3.18.2 !pip install qiskit==0.45.1 !pip install qiskit-aer==0.13.1 !pip install pylatexenc==2.10 from numpy import log2, sqrt from numpy import pi from qiskit.tools.visualization import plot_histogram from qiskit.circuit.gate import Gate from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit import transpile def run(circuit: QuantumCircuit, shots: int) -> dict: simulator = Aer.get_backend('aer_simulator') compiled_circuit = transpile(circuit, simulator) job = simulator.run(compiled_circuit, shots=shots) result = job.result() return result.get_counts(compiled_circuit) def init_register(bin_str: str) -> QuantumCircuit: data_qr = QuantumRegister(len(bin_str), 'data') qc = QuantumCircuit(data_qr) for i, bit in enumerate(bin_str): if bit == '1': qc.x(data_qr[i]) return qc classical_value = '1001' init_register(classical_value).draw(fold=255) def rot(n: int, s: int) -> QuantumCircuit: y_qr = QuantumRegister(n, 'y') qc = QuantumCircuit(y_qr, name='ROT_' + str(s)) for i in range(1, (int(log2(n)) - int(log2(s)) + 2)): for j in range(int(n / (s * (2**i)))): for q in range(j * s * (2**i), s * (j*2 ** i+1)): qc.swap(n - 1 - (q+s), n - 1 - (q+2 ** (i-1) * s + s)) return qc num_qubits = 8 shift_value = 2 rot(num_qubits, shift_value).draw(fold=255) def rot_gate(n: int, s: int) -> Gate: rot_circuit = rot(n, s) return rot_circuit.to_gate(label='ROT_' + str(s)) def parameterized_rot(n: int) -> QuantumCircuit: j_qr = QuantumRegister(int(log2(n)), 'j') y_qr = QuantumRegister(n, 'y') qc = QuantumCircuit(j_qr, y_qr) for i in range(int(log2(n))): crot = rot_gate(n, 2**i).control(1) qc = qc.compose(crot, [j_qr[i]] + y_qr[:]) return qc num_qubits = 8 parameterized_rot(num_qubits).draw(fold=255) text = '10110001' text_length = len(text) shift_qr = QuantumRegister(int(log2(text_length)), 'shift') text_qr = QuantumRegister(text_length, 'text') output_cr = ClassicalRegister(text_length, 'output_classic') circ = QuantumCircuit(shift_qr, text_qr, output_cr) circ.h(shift_qr) circ.append(init_register(text), text_qr[:]) circ.append(parameterized_rot(text_length), shift_qr[:] + text_qr[:]) circ.measure(text_qr, output_cr) counts = run(circ, 100) plot_histogram(counts, title='Rotate ' + text + ' Leftward in Superposition') def match(m: int) -> QuantumCircuit: x_qr = QuantumRegister(m, 'x') y_qr = QuantumRegister(m, 'y') out_qr = QuantumRegister(1, 'out') qc = QuantumCircuit(x_qr, y_qr, out_qr) for i in range(m): qc.cx(x_qr[i], y_qr[i]) qc.x(y_qr[i]) qc.mcx(y_qr[:], out_qr) for i in reversed(range(m)): qc.x(y_qr[i]) qc.cx(x_qr[i], y_qr[i]) return qc pattern_length = 4 match(pattern_length).draw(fold=255) text = '1011' text_length = len(text) pattern_qr = QuantumRegister(text_length, 'pattern') text_qr = QuantumRegister(text_length, 'text') output_qr = QuantumRegister(1, 'output') output_cr = ClassicalRegister(text_length + 1, 'output_classic') circ = QuantumCircuit(pattern_qr, text_qr, output_qr, output_cr) circ.h(pattern_qr) circ.append(init_register(text), text_qr[:]) circ.append(match(text_length), pattern_qr[:] + text_qr[:] + output_qr[:]) circ.measure(pattern_qr, output_cr[:-1]) circ.measure(output_qr, output_cr[-1]) counts = run(circ, 100) plot_histogram(counts, title='Matching ' + text) def match_gate(m: int) -> Gate: match_circuit = match(m) return match_circuit.to_gate(label='MATCH') def esm(m: int, n: int) -> QuantumCircuit: j_qr = QuantumRegister(int(log2(n)), 'j') x_qr = QuantumRegister(m, 'x') y_qr = QuantumRegister(n, 'y') out = QuantumRegister(1, 'out') qc = QuantumCircuit( j_qr, x_qr, y_qr, out ) qc = qc.compose(parameterized_rot(n), j_qr[:] + y_qr[:]) qc = qc.compose(match_gate(m), x_qr[:] + y_qr[:m] + out[:]) qc = qc.compose(parameterized_rot(n).inverse(), j_qr[:] + y_qr[:]) return qc pattern_length = 2 text_length = 4 esm(pattern_length, text_length).draw(fold=255) def esm_oracle(m: int, n: int): esm_circuit = esm(m, n) return esm_circuit.to_gate(label='ESMO') def diffuser(n: int) -> Gate: qc = QuantumCircuit(n) qc.h(range(n)) qc.x(range(n)) qc.h(n-1) qc.mcx(list(range(n-1)), n-1) qc.h(n-1) qc.x(range(n)) qc.h(range(n)) return qc.to_gate(label='DIFF') def grover(esmo: Gate, t: int, x: str, y: str) -> QuantumCircuit: n = len(y) m = len(x) logn = int(log2(n)) num_iterations = int(pi/4 * sqrt(n/t)) j_qr = QuantumRegister(logn, 'j') x_qr = QuantumRegister(m, 'x') y_qr = QuantumRegister(n, 'y') out_qr = QuantumRegister(2, 'out') out_cr = ClassicalRegister(logn+1, 'c') qc = QuantumCircuit(j_qr, x_qr, y_qr, out_qr, out_cr) qc.h(j_qr) qc.x(out_qr[0]) qc.h(out_qr[0]) qc = qc.compose(init_register(x), x_qr[:]) qc = qc.compose(init_register(y), y_qr[:]) for _ in range(num_iterations): qc = qc.compose(esmo) qc = qc.compose(diffuser(logn)) qc.measure(j_qr, out_cr[:-1]) qc = qc.compose(esmo, j_qr[:] + x_qr[:] + y_qr[:] + [out_qr[1]]) qc.measure(out_qr[1], out_cr[-1]) return qc x = '11' y = '10101100' esmo = esm_oracle(len(x), len(y)) grover(esmo, 1, x, y).draw(fold=255) x = '00' y = '01010101' esmo = esm_oracle(len(x), len(y)) counts = run(grover(esmo, 1, x, y), 100) plot_histogram(counts, title=f'Search for {x} in {y} - 0 occurrence(s)') x = '00' y = '11010011' esmo = esm_oracle(len(x), len(y)) counts = run(grover(esmo, 1, x, y), 100) plot_histogram(counts, title=f'Search for {x} in {y} - 1 occurrence(s)') x = '00' y = '00111001' esmo = esm_oracle(len(x), len(y)) counts = run(grover(esmo, 2, x, y), 100) plot_histogram(counts, title=f'Search for {x} in {y} - 2 occurrence(s)') def search(x: str, y: str) -> int: m = len(x) n = len(y) esmo = esm_oracle(m, n) for t in range(1, int(n/2) + 1): print('Trying with t =', t) results = run(grover(esmo, t, x, y), 1) results = list(results.keys())[0] outcome = int(results[0]) position = int(results[1:], 2) if outcome: return position else: print('Pattern not found in position', position) return -1 x = input('Enter the value of x: ') y = input('Enter the value of y: ') if len(x) > len(y): raise Exception('The length of x must be shorter than the length of y.') if x.count('0') + x.count('1') < len(x): raise Exception('The pattern must be a binary string.') if y.count('0') + y.count('1') < len(y): raise Exception('The text must be a binary string.') print('') position = search(x, y) if position >= 0: print('Pattern occurrence found in position', str(position)) else: print('Pattern occurrence not found.')
https://github.com/scaleway/qiskit-scaleway
scaleway
# Copyright 2024 Scaleway # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json from typing import Union, List from qiskit.providers import JobError from qiskit.result import Result from qiskit import qasm3 from ..utils import QaaSClient from ..versions import USER_AGENT from .scaleway_job import ScalewayJob from .scaleway_models import ( JobPayload, ClientPayload, BackendPayload, RunPayload, SerializationType, CircuitPayload, ) class AerJob(ScalewayJob): def __init__( self, name: str, backend, client: QaaSClient, circuits, config, ) -> None: super().__init__(name, backend, client) self._circuits = circuits self._config = config def submit(self, session_id: str) -> None: if self._job_id: raise RuntimeError(f"Job already submitted (ID: {self._job_id})") options = self._config.copy() run_opts = RunPayload( options={ "shots": options.pop("shots"), "memory": options.pop("memory"), "seed_simulator": options.pop("seed_simulator"), }, circuits=list( map( lambda c: CircuitPayload( serialization_type=SerializationType.QASM_V3, circuit_serialization=qasm3.dumps(c), ), self._circuits, ) ), ) backend_opts = BackendPayload( name=self.backend().name, version=self.backend().version, options=options, ) client_opts = ClientPayload( user_agent=USER_AGENT, ) job_payload = JobPayload.schema().dumps( JobPayload( backend=backend_opts, run=run_opts, client=client_opts, ) ) self._job_id = self._client.create_job( name=self._name, session_id=session_id, circuits=job_payload, ) def result( self, timeout=None, fetch_interval: int = 3 ) -> Union[Result, List[Result]]: if self._job_id == None: raise JobError("Job ID error") job_results = self._wait_for_result(timeout, fetch_interval) def __make_result_from_payload(payload: str) -> Result: payload_dict = json.loads(payload) return Result.from_dict( { "results": payload_dict["results"], "backend_name": payload_dict["backend_name"], "backend_version": payload_dict["backend_version"], "job_id": self._job_id, "qobj_id": ", ".join(x.name for x in self._circuits), "success": payload_dict["success"], "header": payload_dict.get("header"), "metadata": payload_dict.get("metadata"), } ) qiskit_results = list( map( lambda r: __make_result_from_payload( self._extract_payload_from_response(r) ), job_results, ) ) if len(qiskit_results) == 1: return qiskit_results[0] return qiskit_results
https://github.com/scaleway/qiskit-scaleway
scaleway
# Copyright 2024 Scaleway # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import io import collections import numpy as np from typing import ( Any, List, Callable, Iterable, Mapping, Optional, Sequence, Tuple, Union, cast, ) from qiskit import qasm2, QuantumCircuit from qiskit.providers import JobError from qiskit.result import Result from qiskit.transpiler.passes import RemoveBarriers from qiskit.result.models import ExperimentResult, ExperimentResultData from ..utils import QaaSClient from ..versions import USER_AGENT from .scaleway_job import ScalewayJob from .scaleway_models import ( JobPayload, ClientPayload, BackendPayload, RunPayload, SerializationType, CircuitPayload, ) def _tuple_of_big_endian_int(bit_groups: Iterable[Any]) -> Tuple[int, ...]: return tuple(_big_endian_bits_to_int(bits) for bits in bit_groups) def _big_endian_bits_to_int(bits: Iterable[Any]) -> int: result = 0 for e in bits: result <<= 1 if e: result |= 1 return result def _unpack_digits( packed_digits: str, binary: bool, dtype: Optional[str], shape: Optional[Sequence[int]], ) -> np.ndarray: if binary: dtype = cast(str, dtype) shape = cast(Sequence[int], shape) return _unpack_bits(packed_digits, dtype, shape) buffer = io.BytesIO() buffer.write(bytes.fromhex(packed_digits)) buffer.seek(0) digits = np.load(buffer, allow_pickle=False) buffer.close() return digits def _unpack_bits(packed_bits: str, dtype: str, shape: Sequence[int]) -> np.ndarray: bits_bytes = bytes.fromhex(packed_bits) bits = np.unpackbits(np.frombuffer(bits_bytes, dtype=np.uint8)) return bits[: np.prod(shape).item()].reshape(shape).astype(dtype) class QsimJob(ScalewayJob): def __init__( self, name: str, backend, client: QaaSClient, circuits, config, ) -> None: super().__init__(name, backend, client) assert circuits is QuantumCircuit or list self._circuits = circuits self._config = config def submit(self, session_id: str) -> None: if self._job_id: raise RuntimeError(f"Job already submitted (ID: {self._job_id})") options = self._config.copy() # Note 1: Barriers are only visual elements # Barriers are not managed by Cirq deserialization # Note 2: Qsim can only handle one circuit at a time circuit = RemoveBarriers()(self._circuits[0]) run_opts = RunPayload( options={"shots": options.pop("shots")}, circuits=[ CircuitPayload( serialization_type=SerializationType.QASM_V2, circuit_serialization=qasm2.dumps(circuit), ) ], ) options.pop("circuit_memoization_size") backend_opts = BackendPayload( name=self.backend().name, version=self.backend().version, options=options, ) client_opts = ClientPayload( user_agent=USER_AGENT, ) job_payload = JobPayload.schema().dumps( JobPayload( backend=backend_opts, run=run_opts, client=client_opts, ) ) self._job_id = self._client.create_job( name=self._name, session_id=session_id, circuits=job_payload, ) def __to_cirq_result(self, job_results) -> "cirq.Result": try: import cirq except: raise Exception("Cannot get Cirq result: Cirq not installed") from cirq.study import ResultDict if len(job_results) == 0: raise Exception("Empty result list") payload = self._extract_payload_from_response(job_results[0]) payload_dict = json.loads(payload) cirq_result = ResultDict._from_json_dict_(**payload_dict) return cirq_result def __to_qiskit_result(self, job_results): def __make_hex_from_result_array(result: Tuple): str_value = "".join(map(str, result)) integer_value = int(str_value, 2) return hex(integer_value) def __make_expresult_from_cirq_result( cirq_result: CirqResult, ) -> ExperimentResult: hist = dict( cirq_result.multi_measurement_histogram( keys=cirq_result.measurements.keys() ) ) return ExperimentResult( shots=cirq_result.repetitions, success=True, data=ExperimentResultData( counts={ __make_hex_from_result_array(key): value for key, value in hist.items() }, ), ) def __make_result_from_payload(payload: str) -> Result: payload_dict = json.loads(payload) cirq_result = CirqResult._from_json_dict_(**payload_dict) return Result( backend_name=self.backend().name, backend_version=self.backend().version, job_id=self._job_id, qobj_id=", ".join(x.name for x in self._circuits), success=True, results=[__make_expresult_from_cirq_result(cirq_result)], status=None, # TODO header=None, # TODO date=None, # TODO cirq_result=payload, ) qiskit_results = list( map( lambda r: __make_result_from_payload( self._extract_payload_from_response(r) ), job_results, ) ) if len(qiskit_results) == 1: return qiskit_results[0] return qiskit_results def result( self, timeout=None, fetch_interval: int = 3, format: str = "qiskit", ) -> Union[Result, List[Result], "cirq.Result"]: if self._job_id == None: raise JobError("Job ID error") match = { "qiskit": self.__to_qiskit_result, "cirq": self.__to_cirq_result, } job_results = self._wait_for_result(timeout, fetch_interval) return match.get(format, self.__to_qiskit_result)(job_results) class CirqResult: def __init__( self, *, measurements: Optional[Mapping[str, np.ndarray]] = None, records: Optional[Mapping[str, np.ndarray]] = None, ) -> None: if measurements is None and records is None: measurements = {} records = {} self._params = None self._measurements = measurements self._records = records @property def measurements(self) -> Mapping[str, np.ndarray]: if self._measurements is None: assert self._records is not None self._measurements = {} for key, data in self._records.items(): reps, instances, qubits = data.shape if instances != 1: raise ValueError("Cannot extract 2D measurements for repeated keys") self._measurements[key] = data.reshape((reps, qubits)) return self._measurements @property def records(self) -> Mapping[str, np.ndarray]: if self._records is None: assert self._measurements is not None self._records = { key: data[:, np.newaxis, :] for key, data in self._measurements.items() } return self._records @property def repetitions(self) -> int: if self._records is not None: if not self._records: return 0 return len(next(iter(self._records.values()))) else: if not self._measurements: return 0 return len(next(iter(self._measurements.values()))) def multi_measurement_histogram( self, *, keys: Iterable, fold_func: Callable = cast(Callable, _tuple_of_big_endian_int), ) -> collections.Counter: fixed_keys = tuple(key for key in keys) samples: Iterable[Any] = zip( *(self.measurements[sub_key] for sub_key in fixed_keys) ) if len(fixed_keys) == 0: samples = [()] * self.repetitions c: collections.Counter = collections.Counter() for sample in samples: c[fold_func(sample)] += 1 return c @classmethod def _from_packed_records(cls, records, **kwargs): return cls( records={key: _unpack_digits(**val) for key, val in records.items()}, **kwargs, ) @classmethod def _from_json_dict_(cls, **kwargs): if "measurements" in kwargs: measurements = kwargs["measurements"] return cls( params=None, measurements={ key: _unpack_digits(**val) for key, val in measurements.items() }, ) return cls._from_packed_records(records=kwargs["records"]) @property def repetitions(self) -> int: if not self.records: return 0 # Get the length quickly from one of the keyed results. return len(next(iter(self.records.values())))
https://github.com/scaleway/qiskit-scaleway
scaleway
import os import numpy as np import random from qiskit import QuantumCircuit from qiskit_scaleway import ScalewayProvider def _random_qiskit_circuit(size: int) -> QuantumCircuit: num_qubits = size num_gate = size qc = QuantumCircuit(num_qubits) for _ in range(num_gate): random_gate = np.random.choice(["unitary", "cx", "cy", "cz"]) if random_gate == "cx" or random_gate == "cy" or random_gate == "cz": control_qubit = np.random.randint(0, num_qubits) target_qubit = np.random.randint(0, num_qubits) while target_qubit == control_qubit: target_qubit = np.random.randint(0, num_qubits) getattr(qc, random_gate)(control_qubit, target_qubit) else: for q in range(num_qubits): random_gate = np.random.choice(["h", "x", "y", "z"]) getattr(qc, random_gate)(q) qc.measure_all() return qc def test_aer_multiple_circuits(): provider = ScalewayProvider( project_id=os.environ["QISKIT_SCALEWAY_PROJECT_ID"], secret_key=os.environ["QISKIT_SCALEWAY_API_TOKEN"], url=os.environ["QISKIT_SCALEWAY_API_URL"], ) backend = provider.get_backend("aer_simulation_pop_c16m128") assert backend is not None session_id = backend.start_session( name="my-aer-session-autotest", deduplication_id=f"my-aer-session-autotest-{random.randint(1, 1000)}", max_duration="5m", ) assert session_id is not None try: qc1 = _random_qiskit_circuit(20) qc2 = _random_qiskit_circuit(15) qc3 = _random_qiskit_circuit(21) qc4 = _random_qiskit_circuit(17) run_result = backend.run( [qc1, qc2, qc3, qc4], shots=1000, max_parallel_experiments=0, session_id=session_id, ).result() results = run_result.results assert len(results) == 4 for result in results: assert result.success finally: backend.stop_session(session_id)