Dataset Viewer
Auto-converted to Parquet
repo
stringclasses
798 values
file
stringclasses
672 values
content
stringlengths
4
6.59k
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This module contains the definition of a base class for quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class QFT(Pluggable): """Base class for QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): qft_params = params.get(Pluggable.SECTION_KEY_QFT) kwargs = {k: v for k, v in qft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This module contains the definition of a base class for quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class QFT(Pluggable): """Base class for QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): qft_params = params.get(Pluggable.SECTION_KEY_QFT) kwargs = {k: v for k, v in qft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This module contains the definition of a base class for quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class QFT(Pluggable): """Base class for QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): qft_params = params.get(Pluggable.SECTION_KEY_QFT) kwargs = {k: v for k, v in qft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This module contains the definition of a base class for quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class QFT(Pluggable): """Base class for QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): qft_params = params.get(Pluggable.SECTION_KEY_QFT) kwargs = {k: v for k, v in qft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This module contains the definition of a base class for quantum fourier transforms. """ from abc import abstractmethod from qiskit import QuantumRegister, QuantumCircuit from qiskit.aqua import Pluggable, AquaError class QFT(Pluggable): """Base class for QFT. This method should initialize the module and its configuration, and use an exception if a component of the module is available. Args: configuration (dict): configuration dictionary """ @abstractmethod def __init__(self, *args, **kwargs): super().__init__() @classmethod def init_params(cls, params): qft_params = params.get(Pluggable.SECTION_KEY_QFT) kwargs = {k: v for k, v in qft_params.items() if k != 'name'} return cls(**kwargs) @abstractmethod def _build_matrix(self): raise NotImplementedError @abstractmethod def _build_circuit(self, qubits=None, circuit=None, do_swaps=True): raise NotImplementedError def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True): """Construct the circuit. Args: mode (str): 'matrix' or 'circuit' qubits (QuantumRegister or qubits): register or qubits to build the circuit on. circuit (QuantumCircuit): circuit for construction. do_swaps (bool): include the swaps. Returns: The matrix or circuit depending on the specified mode. """ if mode == 'circuit': return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps) elif mode == 'matrix': return self._build_matrix() else: raise AquaError('Unrecognized mode: {}.'.format(mode))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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. """ Quantum teleportation example. Note: if you have only cloned the Qiskit repository but not used `pip install`, the examples only work from the root directory. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]] backend = BasicAer.get_backend("qasm_simulator") ############################################################### # Make a quantum program for quantum teleportation. ############################################################### q = QuantumRegister(3, "q") c0 = ClassicalRegister(1, "c0") c1 = ClassicalRegister(1, "c1") c2 = ClassicalRegister(1, "c2") qc = QuantumCircuit(q, c0, c1, c2, name="teleport") # Prepare an initial state qc.u(0.3, 0.2, 0.1, q[0]) # Prepare a Bell pair qc.h(q[1]) qc.cx(q[1], q[2]) # Barrier following state preparation qc.barrier(q) # Measure in the Bell basis qc.cx(q[0], q[1]) qc.h(q[0]) qc.measure(q[0], c0[0]) qc.measure(q[1], c1[0]) # Apply a correction qc.barrier(q) qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Execute. # Experiment does not support feedback, so we use the simulator ############################################################### # First version: not mapped initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2} job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph job = execute( qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout ) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit import * import matplotlib qr = QuantumRegister(2) #measurements from quantum bits = use classical register cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() # adding quantum gates to create entanglement (Hadamart gate) circuit.h(qr[0]) %matplotlib inline circuit.draw(output='mpl') #two qubit operation control X (logical if) circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') #entanglement achieved #measurement, storing measurements into computational register circuit.measure(qr,cr) circuit.draw(output='mpl') #performance simulations simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend = simulator) result = execute(circuit, backend = simulator).result() #plotting results from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) #running circuit on quantum computer IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') job= execute(circuit, backend=qcomp) from qiskit.tools import job_monitor job_monitor(job) result = job.result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit import * import matplotlib qr = QuantumRegister(2) #measurements from quantum bits = use classical register cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() # adding quantum gates to create entanglement (Hadamart gate) circuit.h(qr[0]) %matplotlib inline circuit.draw(output='mpl') #two qubit operation control X (logical if) circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') #entanglement achieved #measurement, storing measurements into computational register circuit.measure(qr,cr) circuit.draw(output='mpl') #performance simulations simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend = simulator) result = execute(circuit, backend = simulator).result() #plotting results from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) #running circuit on quantum computer IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') job= execute(circuit, backend=qcomp) from qiskit.tools import job_monitor job_monitor(job) result = job.result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit import * import matplotlib qr = QuantumRegister(2) #measurements from quantum bits = use classical register cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() # adding quantum gates to create entanglement (Hadamart gate) circuit.h(qr[0]) %matplotlib inline circuit.draw(output='mpl') #two qubit operation control X (logical if) circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') #entanglement achieved #measurement, storing measurements into computational register circuit.measure(qr,cr) circuit.draw(output='mpl') #performance simulations simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend = simulator) result = execute(circuit, backend = simulator).result() #plotting results from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) #running circuit on quantum computer IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') job= execute(circuit, backend=qcomp) from qiskit.tools import job_monitor job_monitor(job) result = job.result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit import * import matplotlib qr = QuantumRegister(2) #measurements from quantum bits = use classical register cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() # adding quantum gates to create entanglement (Hadamart gate) circuit.h(qr[0]) %matplotlib inline circuit.draw(output='mpl') #two qubit operation control X (logical if) circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') #entanglement achieved #measurement, storing measurements into computational register circuit.measure(qr,cr) circuit.draw(output='mpl') #performance simulations simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend = simulator) result = execute(circuit, backend = simulator).result() #plotting results from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) #running circuit on quantum computer IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') job= execute(circuit, backend=qcomp) from qiskit.tools import job_monitor job_monitor(job) result = job.result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit import * import matplotlib qr = QuantumRegister(2) #measurements from quantum bits = use classical register cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() # adding quantum gates to create entanglement (Hadamart gate) circuit.h(qr[0]) %matplotlib inline circuit.draw(output='mpl') #two qubit operation control X (logical if) circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') #entanglement achieved #measurement, storing measurements into computational register circuit.measure(qr,cr) circuit.draw(output='mpl') #performance simulations simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend = simulator) result = execute(circuit, backend = simulator).result() #plotting results from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) #running circuit on quantum computer IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') job= execute(circuit, backend=qcomp) from qiskit.tools import job_monitor job_monitor(job) result = job.result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * backend = BasicAer.get_backend('dm_simulator') qc1 = QuantumCircuit(1) options1 = { 'custom_densitymatrix': 'max_mixed' } run1 = execute(qc1,backend,**options1) result1 = run1.result() print('Density Matrix: \n',result1['results'][0]['data']['densitymatrix']) qc2 = QuantumCircuit(2) options2 = { 'custom_densitymatrix': 'binary_string', 'initial_densitymatrix': '01' } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() print('Density Matrix: \n',result2['results'][0]['data']['densitymatrix'])
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * backend = BasicAer.get_backend('dm_simulator') qc1 = QuantumCircuit(1) options1 = { 'custom_densitymatrix': 'max_mixed' } run1 = execute(qc1,backend,**options1) result1 = run1.result() print('Density Matrix: \n',result1['results'][0]['data']['densitymatrix']) qc2 = QuantumCircuit(2) options2 = { 'custom_densitymatrix': 'binary_string', 'initial_densitymatrix': '01' } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() print('Density Matrix: \n',result2['results'][0]['data']['densitymatrix'])
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * backend = BasicAer.get_backend('dm_simulator') qc1 = QuantumCircuit(1) options1 = { 'custom_densitymatrix': 'max_mixed' } run1 = execute(qc1,backend,**options1) result1 = run1.result() print('Density Matrix: \n',result1['results'][0]['data']['densitymatrix']) qc2 = QuantumCircuit(2) options2 = { 'custom_densitymatrix': 'binary_string', 'initial_densitymatrix': '01' } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() print('Density Matrix: \n',result2['results'][0]['data']['densitymatrix'])
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * backend = BasicAer.get_backend('dm_simulator') qc1 = QuantumCircuit(1) options1 = { 'custom_densitymatrix': 'max_mixed' } run1 = execute(qc1,backend,**options1) result1 = run1.result() print('Density Matrix: \n',result1['results'][0]['data']['densitymatrix']) qc2 = QuantumCircuit(2) options2 = { 'custom_densitymatrix': 'binary_string', 'initial_densitymatrix': '01' } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() print('Density Matrix: \n',result2['results'][0]['data']['densitymatrix'])
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * backend = BasicAer.get_backend('dm_simulator') qc1 = QuantumCircuit(1) options1 = { 'custom_densitymatrix': 'max_mixed' } run1 = execute(qc1,backend,**options1) result1 = run1.result() print('Density Matrix: \n',result1['results'][0]['data']['densitymatrix']) qc2 = QuantumCircuit(2) options2 = { 'custom_densitymatrix': 'binary_string', 'initial_densitymatrix': '01' } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() print('Density Matrix: \n',result2['results'][0]['data']['densitymatrix'])
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * import numpy as np %matplotlib inline qc = QuantumCircuit(1,1) qc.s(0) qc.measure(0,0,basis='X') backend = BasicAer.get_backend('dm_simulator') run = execute(qc,backend) result = run.result() result['results'][0]['data']['densitymatrix'] qc1 = QuantumCircuit(1,1) qc1.s(0) qc1.measure(0,0, basis='N', add_param=np.array([1,2,3])) backend = BasicAer.get_backend('dm_simulator') run1 = execute(qc1,backend) result1 = run1.result() result1['results'][0]['data']['densitymatrix'] qc2 = QuantumCircuit(3,2) qc2.measure(0,0,basis='Bell',add_param='01') options2 = { 'plot': True } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() result2['results'][0]['data']['bell_probabilities01'] qc3 = QuantumCircuit(3,3) qc3.h(0) qc3.cx(0,1) qc3.cx(1,2) qc3.measure(0,0,basis='Ensemble',add_param='X') backend = BasicAer.get_backend('dm_simulator') options3 = { 'plot': True } run3 = execute(qc3,backend,**options3) result3 = run3.result() result3['results'][0]['data']['ensemble_probability'] qc4 = QuantumCircuit(3,3) qc4.h(0) qc4.cx(0,1) qc4.cx(1,2) qc4.measure(0,0,basis='Expect',add_param='ZIZ') backend = BasicAer.get_backend('dm_simulator') run4 = execute(qc4,backend) result4 = run4.result() result4['results'][0]['data']['Pauli_string_expectation']
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * import numpy as np %matplotlib inline qc = QuantumCircuit(1,1) qc.s(0) qc.measure(0,0,basis='X') backend = BasicAer.get_backend('dm_simulator') run = execute(qc,backend) result = run.result() result['results'][0]['data']['densitymatrix'] qc1 = QuantumCircuit(1,1) qc1.s(0) qc1.measure(0,0, basis='N', add_param=np.array([1,2,3])) backend = BasicAer.get_backend('dm_simulator') run1 = execute(qc1,backend) result1 = run1.result() result1['results'][0]['data']['densitymatrix'] qc2 = QuantumCircuit(3,2) qc2.measure(0,0,basis='Bell',add_param='01') options2 = { 'plot': True } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() result2['results'][0]['data']['bell_probabilities01'] qc3 = QuantumCircuit(3,3) qc3.h(0) qc3.cx(0,1) qc3.cx(1,2) qc3.measure(0,0,basis='Ensemble',add_param='X') backend = BasicAer.get_backend('dm_simulator') options3 = { 'plot': True } run3 = execute(qc3,backend,**options3) result3 = run3.result() result3['results'][0]['data']['ensemble_probability'] qc4 = QuantumCircuit(3,3) qc4.h(0) qc4.cx(0,1) qc4.cx(1,2) qc4.measure(0,0,basis='Expect',add_param='ZIZ') backend = BasicAer.get_backend('dm_simulator') run4 = execute(qc4,backend) result4 = run4.result() result4['results'][0]['data']['Pauli_string_expectation']
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * import numpy as np %matplotlib inline qc = QuantumCircuit(1,1) qc.s(0) qc.measure(0,0,basis='X') backend = BasicAer.get_backend('dm_simulator') run = execute(qc,backend) result = run.result() result['results'][0]['data']['densitymatrix'] qc1 = QuantumCircuit(1,1) qc1.s(0) qc1.measure(0,0, basis='N', add_param=np.array([1,2,3])) backend = BasicAer.get_backend('dm_simulator') run1 = execute(qc1,backend) result1 = run1.result() result1['results'][0]['data']['densitymatrix'] qc2 = QuantumCircuit(3,2) qc2.measure(0,0,basis='Bell',add_param='01') options2 = { 'plot': True } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() result2['results'][0]['data']['bell_probabilities01'] qc3 = QuantumCircuit(3,3) qc3.h(0) qc3.cx(0,1) qc3.cx(1,2) qc3.measure(0,0,basis='Ensemble',add_param='X') backend = BasicAer.get_backend('dm_simulator') options3 = { 'plot': True } run3 = execute(qc3,backend,**options3) result3 = run3.result() result3['results'][0]['data']['ensemble_probability'] qc4 = QuantumCircuit(3,3) qc4.h(0) qc4.cx(0,1) qc4.cx(1,2) qc4.measure(0,0,basis='Expect',add_param='ZIZ') backend = BasicAer.get_backend('dm_simulator') run4 = execute(qc4,backend) result4 = run4.result() result4['results'][0]['data']['Pauli_string_expectation']
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * import numpy as np %matplotlib inline qc = QuantumCircuit(1,1) qc.s(0) qc.measure(0,0,basis='X') backend = BasicAer.get_backend('dm_simulator') run = execute(qc,backend) result = run.result() result['results'][0]['data']['densitymatrix'] qc1 = QuantumCircuit(1,1) qc1.s(0) qc1.measure(0,0, basis='N', add_param=np.array([1,2,3])) backend = BasicAer.get_backend('dm_simulator') run1 = execute(qc1,backend) result1 = run1.result() result1['results'][0]['data']['densitymatrix'] qc2 = QuantumCircuit(3,2) qc2.measure(0,0,basis='Bell',add_param='01') options2 = { 'plot': True } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() result2['results'][0]['data']['bell_probabilities01'] qc3 = QuantumCircuit(3,3) qc3.h(0) qc3.cx(0,1) qc3.cx(1,2) qc3.measure(0,0,basis='Ensemble',add_param='X') backend = BasicAer.get_backend('dm_simulator') options3 = { 'plot': True } run3 = execute(qc3,backend,**options3) result3 = run3.result() result3['results'][0]['data']['ensemble_probability'] qc4 = QuantumCircuit(3,3) qc4.h(0) qc4.cx(0,1) qc4.cx(1,2) qc4.measure(0,0,basis='Expect',add_param='ZIZ') backend = BasicAer.get_backend('dm_simulator') run4 = execute(qc4,backend) result4 = run4.result() result4['results'][0]['data']['Pauli_string_expectation']
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * import numpy as np %matplotlib inline qc = QuantumCircuit(1,1) qc.s(0) qc.measure(0,0,basis='X') backend = BasicAer.get_backend('dm_simulator') run = execute(qc,backend) result = run.result() result['results'][0]['data']['densitymatrix'] qc1 = QuantumCircuit(1,1) qc1.s(0) qc1.measure(0,0, basis='N', add_param=np.array([1,2,3])) backend = BasicAer.get_backend('dm_simulator') run1 = execute(qc1,backend) result1 = run1.result() result1['results'][0]['data']['densitymatrix'] qc2 = QuantumCircuit(3,2) qc2.measure(0,0,basis='Bell',add_param='01') options2 = { 'plot': True } backend = BasicAer.get_backend('dm_simulator') run2 = execute(qc2,backend,**options2) result2 = run2.result() result2['results'][0]['data']['bell_probabilities01'] qc3 = QuantumCircuit(3,3) qc3.h(0) qc3.cx(0,1) qc3.cx(1,2) qc3.measure(0,0,basis='Ensemble',add_param='X') backend = BasicAer.get_backend('dm_simulator') options3 = { 'plot': True } run3 = execute(qc3,backend,**options3) result3 = run3.result() result3['results'][0]['data']['ensemble_probability'] qc4 = QuantumCircuit(3,3) qc4.h(0) qc4.cx(0,1) qc4.cx(1,2) qc4.measure(0,0,basis='Expect',add_param='ZIZ') backend = BasicAer.get_backend('dm_simulator') run4 = execute(qc4,backend) result4 = run4.result() result4['results'][0]['data']['Pauli_string_expectation']
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * %matplotlib inline import matplotlib.pyplot as plt # The Circuit q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q,c) qc.u1(3.6,0) qc.cx(0,1) qc.u1(2.6,2) qc.cx(1,0) qc.s(2) qc.y(2) qc.measure(q,c,basis='Ensemble',add_param='Z') backend = BasicAer.get_backend('dm_simulator') # Noise parameters options = {} options1 = { "thermal_factor": 0., "decoherence_factor": .9, "depolarization_factor": 0.99, "bell_depolarization_factor": 0.99, "decay_factor": 0.99, "rotation_error": {'rx':[1., 0.], 'ry':[1., 0.], 'rz': [1., 0.]}, "tsp_model_error": [1., 0.], "plot": False } # Execution with and without noise run = execute(qc,backend,**options) result = run.result() run_error = execute(qc,backend,**options1) result_error = run_error.result() # Final state (probabilities) prob = result['results'][0]['data']['ensemble_probability'] prob1 = result_error['results'][0]['data']['ensemble_probability'] import numpy as np labels = prob1.keys() without_noise = prob.values() with_noise = prob1.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * %matplotlib inline import matplotlib.pyplot as plt # The Circuit q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q,c) qc.u1(3.6,0) qc.cx(0,1) qc.u1(2.6,2) qc.cx(1,0) qc.s(2) qc.y(2) qc.measure(q,c,basis='Ensemble',add_param='Z') backend = BasicAer.get_backend('dm_simulator') # Noise parameters options = {} options1 = { "thermal_factor": 0., "decoherence_factor": .9, "depolarization_factor": 0.99, "bell_depolarization_factor": 0.99, "decay_factor": 0.99, "rotation_error": {'rx':[1., 0.], 'ry':[1., 0.], 'rz': [1., 0.]}, "tsp_model_error": [1., 0.], "plot": False } # Execution with and without noise run = execute(qc,backend,**options) result = run.result() run_error = execute(qc,backend,**options1) result_error = run_error.result() # Final state (probabilities) prob = result['results'][0]['data']['ensemble_probability'] prob1 = result_error['results'][0]['data']['ensemble_probability'] import numpy as np labels = prob1.keys() without_noise = prob.values() with_noise = prob1.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * %matplotlib inline import matplotlib.pyplot as plt # The Circuit q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q,c) qc.u1(3.6,0) qc.cx(0,1) qc.u1(2.6,2) qc.cx(1,0) qc.s(2) qc.y(2) qc.measure(q,c,basis='Ensemble',add_param='Z') backend = BasicAer.get_backend('dm_simulator') # Noise parameters options = {} options1 = { "thermal_factor": 0., "decoherence_factor": .9, "depolarization_factor": 0.99, "bell_depolarization_factor": 0.99, "decay_factor": 0.99, "rotation_error": {'rx':[1., 0.], 'ry':[1., 0.], 'rz': [1., 0.]}, "tsp_model_error": [1., 0.], "plot": False } # Execution with and without noise run = execute(qc,backend,**options) result = run.result() run_error = execute(qc,backend,**options1) result_error = run_error.result() # Final state (probabilities) prob = result['results'][0]['data']['ensemble_probability'] prob1 = result_error['results'][0]['data']['ensemble_probability'] import numpy as np labels = prob1.keys() without_noise = prob.values() with_noise = prob1.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * %matplotlib inline import matplotlib.pyplot as plt # The Circuit q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q,c) qc.u1(3.6,0) qc.cx(0,1) qc.u1(2.6,2) qc.cx(1,0) qc.s(2) qc.y(2) qc.measure(q,c,basis='Ensemble',add_param='Z') backend = BasicAer.get_backend('dm_simulator') # Noise parameters options = {} options1 = { "thermal_factor": 0., "decoherence_factor": .9, "depolarization_factor": 0.99, "bell_depolarization_factor": 0.99, "decay_factor": 0.99, "rotation_error": {'rx':[1., 0.], 'ry':[1., 0.], 'rz': [1., 0.]}, "tsp_model_error": [1., 0.], "plot": False } # Execution with and without noise run = execute(qc,backend,**options) result = run.result() run_error = execute(qc,backend,**options1) result_error = run_error.result() # Final state (probabilities) prob = result['results'][0]['data']['ensemble_probability'] prob1 = result_error['results'][0]['data']['ensemble_probability'] import numpy as np labels = prob1.keys() without_noise = prob.values() with_noise = prob1.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import * %matplotlib inline import matplotlib.pyplot as plt # The Circuit q = QuantumRegister(3) c = ClassicalRegister(3) qc = QuantumCircuit(q,c) qc.u1(3.6,0) qc.cx(0,1) qc.u1(2.6,2) qc.cx(1,0) qc.s(2) qc.y(2) qc.measure(q,c,basis='Ensemble',add_param='Z') backend = BasicAer.get_backend('dm_simulator') # Noise parameters options = {} options1 = { "thermal_factor": 0., "decoherence_factor": .9, "depolarization_factor": 0.99, "bell_depolarization_factor": 0.99, "decay_factor": 0.99, "rotation_error": {'rx':[1., 0.], 'ry':[1., 0.], 'rz': [1., 0.]}, "tsp_model_error": [1., 0.], "plot": False } # Execution with and without noise run = execute(qc,backend,**options) result = run.result() run_error = execute(qc,backend,**options1) result_error = run_error.result() # Final state (probabilities) prob = result['results'][0]['data']['ensemble_probability'] prob1 = result_error['results'][0]['data']['ensemble_probability'] import numpy as np labels = prob1.keys() without_noise = prob.values() with_noise = prob1.values() x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x - width/2, without_noise, width, label='Without Noise') rects2 = ax.bar(x + width/2, with_noise, width, label='With Noise') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Probability') ax.set_title('Ensemble Probabilities with Noise') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.show()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit_aqua import Operator, run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import partition from qiskit import Aer from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising number_list = partition.read_numbers_from_file('sample.partition') qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input = EnergyInput(qubitOp) print(number_list) if True: np.random.seed(8123179) number_list = partition.random_number_list(5, weight_range=25) qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input.qubit_op = qubitOp print(number_list) to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE'] print(to_be_tested_algos) algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) cplex_installed = True try: CPLEX_Ising.check_pluggable_valid() except Exception as e: cplex_installed = False if cplex_installed: algorithm_cfg = { 'name': 'CPLEX.Ising', 'display': 0 } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params, algo_input) x_dict = result['x_sol'] print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'L_BFGS_B', 'maxfun': 6000 } var_form_cfg = { 'name': 'RYRZ', 'depth': 3, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit_aqua import Operator, run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import partition from qiskit import Aer from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising number_list = partition.read_numbers_from_file('sample.partition') qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input = EnergyInput(qubitOp) print(number_list) if True: np.random.seed(8123179) number_list = partition.random_number_list(5, weight_range=25) qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input.qubit_op = qubitOp print(number_list) to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE'] print(to_be_tested_algos) algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) cplex_installed = True try: CPLEX_Ising.check_pluggable_valid() except Exception as e: cplex_installed = False if cplex_installed: algorithm_cfg = { 'name': 'CPLEX.Ising', 'display': 0 } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params, algo_input) x_dict = result['x_sol'] print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'L_BFGS_B', 'maxfun': 6000 } var_form_cfg = { 'name': 'RYRZ', 'depth': 3, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit_aqua import Operator, run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import partition from qiskit import Aer from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising number_list = partition.read_numbers_from_file('sample.partition') qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input = EnergyInput(qubitOp) print(number_list) if True: np.random.seed(8123179) number_list = partition.random_number_list(5, weight_range=25) qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input.qubit_op = qubitOp print(number_list) to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE'] print(to_be_tested_algos) algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) cplex_installed = True try: CPLEX_Ising.check_pluggable_valid() except Exception as e: cplex_installed = False if cplex_installed: algorithm_cfg = { 'name': 'CPLEX.Ising', 'display': 0 } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params, algo_input) x_dict = result['x_sol'] print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'L_BFGS_B', 'maxfun': 6000 } var_form_cfg = { 'name': 'RYRZ', 'depth': 3, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit_aqua import Operator, run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import partition from qiskit import Aer from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising number_list = partition.read_numbers_from_file('sample.partition') qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input = EnergyInput(qubitOp) print(number_list) if True: np.random.seed(8123179) number_list = partition.random_number_list(5, weight_range=25) qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input.qubit_op = qubitOp print(number_list) to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE'] print(to_be_tested_algos) algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) cplex_installed = True try: CPLEX_Ising.check_pluggable_valid() except Exception as e: cplex_installed = False if cplex_installed: algorithm_cfg = { 'name': 'CPLEX.Ising', 'display': 0 } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params, algo_input) x_dict = result['x_sol'] print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'L_BFGS_B', 'maxfun': 6000 } var_form_cfg = { 'name': 'RYRZ', 'depth': 3, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit_aqua import Operator, run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import partition from qiskit import Aer from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising number_list = partition.read_numbers_from_file('sample.partition') qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input = EnergyInput(qubitOp) print(number_list) if True: np.random.seed(8123179) number_list = partition.random_number_list(5, weight_range=25) qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input.qubit_op = qubitOp print(number_list) to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE'] print(to_be_tested_algos) algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) cplex_installed = True try: CPLEX_Ising.check_pluggable_valid() except Exception as e: cplex_installed = False if cplex_installed: algorithm_cfg = { 'name': 'CPLEX.Ising', 'display': 0 } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params, algo_input) x_dict = result['x_sol'] print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'L_BFGS_B', 'maxfun': 6000 } var_form_cfg = { 'name': 'RYRZ', 'depth': 3, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumCircuit from qiskit.visualization import visualize_transition,circuit_drawer from math import pi qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) circuit_drawer(qc,output="mpl") qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") visualize_transition(qc)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumCircuit from qiskit.visualization import visualize_transition,circuit_drawer from math import pi qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) circuit_drawer(qc,output="mpl") qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") visualize_transition(qc)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumCircuit from qiskit.visualization import visualize_transition,circuit_drawer from math import pi qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) circuit_drawer(qc,output="mpl") qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") visualize_transition(qc)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumCircuit from qiskit.visualization import visualize_transition,circuit_drawer from math import pi qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) circuit_drawer(qc,output="mpl") qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") visualize_transition(qc)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumCircuit from qiskit.visualization import visualize_transition,circuit_drawer from math import pi qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw(output="mpl") qc=QuantumCircuit(2) qc.h(0) qc.cx(0,1) circuit_drawer(qc,output="mpl") qc=QuantumCircuit(1) qc.h(0) qc.draw(output="mpl") visualize_transition(qc)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example showing how to draw a quantum circuit using Qiskit. """ from qiskit import QuantumCircuit def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit bell_circuit = build_bell_circuit() # Use the internal .draw() to print the circuit print(bell_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example showing how to draw a quantum circuit using Qiskit. """ from qiskit import QuantumCircuit def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit bell_circuit = build_bell_circuit() # Use the internal .draw() to print the circuit print(bell_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example showing how to draw a quantum circuit using Qiskit. """ from qiskit import QuantumCircuit def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit bell_circuit = build_bell_circuit() # Use the internal .draw() to print the circuit print(bell_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example showing how to draw a quantum circuit using Qiskit. """ from qiskit import QuantumCircuit def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit bell_circuit = build_bell_circuit() # Use the internal .draw() to print the circuit print(bell_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example showing how to draw a quantum circuit using Qiskit. """ from qiskit import QuantumCircuit def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) return qc # Create the circuit bell_circuit = build_bell_circuit() # Use the internal .draw() to print the circuit print(bell_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation circuit = QuantumCircuit(5) # Quantum Instantaneous Polynomial Time example circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.z(0) circuit.z(4) circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.cx(3, 2) print(circuit) pm = PassManager() pm.append([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = pm.run(circuit) print(new_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation circuit = QuantumCircuit(5) # Quantum Instantaneous Polynomial Time example circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.z(0) circuit.z(4) circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.cx(3, 2) print(circuit) pm = PassManager() pm.append([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = pm.run(circuit) print(new_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation circuit = QuantumCircuit(5) # Quantum Instantaneous Polynomial Time example circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.z(0) circuit.z(4) circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.cx(3, 2) print(circuit) pm = PassManager() pm.append([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = pm.run(circuit) print(new_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation circuit = QuantumCircuit(5) # Quantum Instantaneous Polynomial Time example circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.z(0) circuit.z(4) circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.cx(3, 2) print(circuit) pm = PassManager() pm.append([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = pm.run(circuit) print(new_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. from qiskit import QuantumCircuit from qiskit.transpiler import PassManager from qiskit.transpiler.passes import CommutationAnalysis, CommutativeCancellation circuit = QuantumCircuit(5) # Quantum Instantaneous Polynomial Time example circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.z(0) circuit.z(4) circuit.cx(0, 1) circuit.cx(2, 1) circuit.cx(4, 3) circuit.cx(2, 3) circuit.cx(3, 2) print(circuit) pm = PassManager() pm.append([CommutationAnalysis(), CommutativeCancellation()]) new_circuit = pm.run(circuit) print(new_circuit)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import IBMQ from qiskit import BasicAer as Aer from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle, Rectangle import copy from ipywidgets import widgets from IPython.display import display, clear_output try: IBMQ.load_accounts() except: pass class run_game(): # Implements a puzzle, which is defined by the given inputs. def __init__(self,initialize, success_condition, allowed_gates, vi, qubit_names, eps=0.1, backend=Aer.get_backend('qasm_simulator'), shots=1024,mode='circle',verbose=False): """ initialize List of gates applied to the initial 00 state to get the starting state of the puzzle. Supported single qubit gates (applied to qubit '0' or '1') are 'x', 'y', 'z', 'h', 'ry(pi/4)'. Supported two qubit gates are 'cz' and 'cx'. Specify only the target qubit. success_condition Values for pauli observables that must be obtained for the puzzle to declare success. allowed_gates For each qubit, specify which operations are allowed in this puzzle. 'both' should be used only for operations that don't need a qubit to be specified ('cz' and 'unbloch'). Gates are expressed as a dict with an int as value. If this is non-zero, it specifies the number of times the gate is must be used (no more or less) for the puzzle to be successfully solved. If the value is zero, the player can use the gate any number of times. vi Some visualization information as a three element list. These specify: * which qubits are hidden (empty list if both shown). * whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles). * whether the correlation circles (the four in the middle) are shown. qubit_names The two qubits are always called '0' and '1' from the programming side. But for the player, we can display different names. eps=0.1 How close the expectation values need to be to the targets for success to be declared. backend=Aer.get_backend('qasm_simulator') Backend to be used by Qiskit to calculate expectation values (defaults to local simulator). shots=1024 Number of shots used to to calculate expectation values. mode='circle' Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line'). verbose=False """ def get_total_gate_list(): # Get a text block describing allowed gates. total_gate_list = "" for qubit in allowed_gates: gate_list = "" for gate in allowed_gates[qubit]: if required_gates[qubit][gate] > 0 : gate_list +=''+ gate+" (use "+str(required_gates[qubit][gate])+" time"+"s"*(required_gates[qubit][gate]>1)+")" elif allowed_gates[qubit][gate]==0: gate_list +=' '+gate +'' if gate_list!="": if qubit=="both" : gate_list = "\nAllowed symmetric operations:" + gate_list else : gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list total_gate_list += gate_list +"\n" return total_gate_list def get_success(required_gates): # Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used. success = True grid.get_rho() if verbose: print(grid.rho) for pauli in success_condition: success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps) for qubit in required_gates: for gate in required_gates[qubit]: success = success and (required_gates[qubit][gate]==0) return success def get_command(gate,qubit
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
ates[qubit][gate]==0: gate_list +=' '+gate +'' if gate_list!="": if qubit=="both" : gate_list = "\nAllowed symmetric operations:" + gate_list else : gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list total_gate_list += gate_list +"\n" return total_gate_list def get_success(required_gates): # Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used. success = True grid.get_rho() if verbose: print(grid.rho) for pauli in success_condition: success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps) for qubit in required_gates: for gate in required_gates[qubit]: success = success and (required_gates[qubit][gate]==0) return success def get_command(gate,qubit): # For a given gate and qubit, return the string describing the corresoinding Qiskit string. if qubit=='both': qubit = '1' qubit_name = qubit_names[qubit] for name in qubit_names.values(): if name!=qubit_name: other_name = name # then make the command (both for the grid, and for printing to screen) if gate in ['x','y','z','h']: real_command = 'grid.qc.'+gate+'(grid.qr['+qubit+'])' clean_command = 'qc.'+gate+'('+qubit_name+')' elif gate in ['ry(pi/4)','ry(-pi/4)']: real_command = 'grid.qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,grid.qr['+qubit+'])' clean_command = 'qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,'+qubit_name+')' elif gate in ['cz','cx','swap']: real_command = 'grid.qc.'+gate+'(grid.qr['+'0'*(qubit=='1')+'1'*(qubit=='0')+'],grid.qr['+qubit+'])' clean_command = 'qc.'+gate+'('+other_name+','+qubit_name+')' return [real_command,clean_command] clear_output() bloch = [None] # set up initial state and figure grid = pauli_grid(backend=backend,shots=shots,mode=mode) for gate in initialize: eval( get_command(gate[0],gate[1])[0] ) required_gates = copy.deepcopy(allowed_gates) # determine which qubits to show in figure if allowed_gates['0']=={} : # if no gates are allowed for qubit 0, we know to only show qubit 1 shown_qubit = 1 elif allowed_gates['1']=={} : # and vice versa shown_qubit = 0 else : shown_qubit = 2 # show figure grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']} all_allowed_gates_raw = [] for q in ['0','1','both']: all_allowed_gates_raw += list(allowed_gates[q]) all_allowed_gates_raw = list(set(all_allowed_gates_raw)) all_allowed_gates = [] for g in ['bloch','unbloch']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in ['x','y','z','h','cz','cx']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in all_allowed_gates_raw: if g not in all_allowed_gates:
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
figure grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']} all_allowed_gates_raw = [] for q in ['0','1','both']: all_allowed_gates_raw += list(allowed_gates[q]) all_allowed_gates_raw = list(set(all_allowed_gates_raw)) all_allowed_gates = [] for g in ['bloch','unbloch']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in ['x','y','z','h','cz','cx']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in all_allowed_gates_raw: if g not in all_allowed_gates: all_allowed_gates.append( g ) gate = widgets.ToggleButtons(options=description['gate']+all_allowed_gates) qubit = widgets.ToggleButtons(options=['']) action = widgets.ToggleButtons(options=['']) boxes = widgets.VBox([gate,qubit,action]) display(boxes) if vi[1]: print('\nYour quantum program so far\n') self.program = [] def given_gate(a): # Action to be taken when gate is chosen. This sets up the system to choose a qubit. if gate.value: if gate.value in allowed_gates['both']: qubit.options = description['qubit'] + ["not required"] qubit.value = "not required" else: allowed_qubits = [] for q in ['0','1']: if (gate.value in allowed_gates[q]) or (gate.value in allowed_gates['both']): allowed_qubits.append(q) allowed_qubit_names = [] for q in allowed_qubits: allowed_qubit_names += [qubit_names[q]] qubit.options = description['qubit'] + allowed_qubit_names def given_qubit(b): # Action to be taken when qubit is chosen. This sets up the system to choose an action. if qubit.value not in ['',description['qubit'][0],'Success!']: action.options = description['action']+['Apply operation'] def given_action(c): # Action to be taken when user confirms their choice of gate and qubit. # This applied the command, updates the visualization and checks whether the puzzle is solved. if action.value not in ['',description['action'][0]]: # apply operation if action.value=='Apply operation': if qubit.value not in ['',description['qubit'][0],'Success!']: # translate bit gates to qubit gates if gate.value=='NOT': q_gate = 'x' elif gate.value=='CNOT': q_gate = 'cx' else: q_gate = gate.value if qubit.value=="not required": q = qubit_names['1'] else: q = qubit.value q01 = '0'*(qubit.value==qubit_names['0']) + '1'*(qubit.value==qubit_names['1']) + 'both'*(qubit.value=="not required") if q_gate in ['bloch','unbloch']: if q_gate=='bloch': bloch[0] = q01 else: bloch[0] = None else: command = get_command(q_gate,q01) eval(command[0]) if vi[1]: print(command[1]) self.program.append( command[1] ) if required_gates[q01][gate.value]>0: required_gates[q01][gate.value] -= 1 grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) success = get_success(required_gates) if success
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
qubit_names['1'] else: q = qubit.value q01 = '0'*(qubit.value==qubit_names['0']) + '1'*(qubit.value==qubit_names['1']) + 'both'*(qubit.value=="not required") if q_gate in ['bloch','unbloch']: if q_gate=='bloch': bloch[0] = q01 else: bloch[0] = None else: command = get_command(q_gate,q01) eval(command[0]) if vi[1]: print(command[1]) self.program.append( command[1] ) if required_gates[q01][gate.value]>0: required_gates[q01][gate.value] -= 1 grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) success = get_success(required_gates) if success: gate.options = ['Success!'] qubit.options = ['Success!'] action.options = ['Success!'] plt.close(grid.fig) else: gate.value = description['gate'][0] qubit.options = [''] action.options = [''] gate.observe(given_gate) qubit.observe(given_qubit) action.observe(given_action) class pauli_grid(): # Allows a quantum circuit to be created, modified and implemented, and visualizes the output in the style of 'Hello Quantum'. def __init__(self,backend=Aer.get_backend('qasm_simulator'),shots=1024,mode='circle'): """ backend=Aer.get_backend('qasm_simulator') Backend to be used by Qiskit to calculate expectation values (defaults to local simulator). shots=1024 Number of shots used to to calculate expectation values. mode='circle' Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line'). """ self.backend = backend self.shots = shots self.box = {'ZI':(-1, 2),'XI':(-2, 3),'IZ':( 1, 2),'IX':( 2, 3),'ZZ':( 0, 3),'ZX':( 1, 4),'XZ':(-1, 4),'XX':( 0, 5)} self.rho = {} for pauli in self.box: self.rho[pauli] = 0.0 for pauli in ['ZI','IZ','ZZ']: self.rho[pauli] = 1.0 self.qr = QuantumRegister(2) self.cr = ClassicalRegister(2) self.qc = QuantumCircuit(self.qr, self.cr) self.mode = mode # colors are background, qubit circles and correlation circles, respectively if self.mode=='line': self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] else: self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0]) self.ax = self.fig.add_subplot(111) plt.axis('off') self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w') self.lines = {} for pauli in self.box: w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
/255,236/255),(33/255,114/255,216/255)] else: self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0]) self.ax = self.fig.add_subplot(111) plt.axis('off') self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w') self.lines = {} for pauli in self.box: w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0,1.0,1.0), lw=0 ) b = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(0.0,0.0,0.0), lw=0 ) c = {} c['w'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(0,0,0), zorder=10) ) c['b'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(1,1,1), zorder=10) ) self.lines[pauli] = {'w':w,'b':b,'c':c} def get_rho(self): # Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. bases = ['ZZ','ZX','XZ','XX'] results = {} for basis in bases: temp_qc = copy.deepcopy(self.qc) for j in range(2): if basis[j]=='X': temp_qc.h(self.qr[j]) temp_qc.barrier(self.qr) temp_qc.measure(self.qr,self.cr) job = execute(temp_qc, backend=self.backend, shots=self.shots) results[basis] = job.result().get_counts() for string in results[basis]: results[basis][string] = results[basis][string]/self.shots prob = {} # prob of expectation value -1 for single qubit observables for j in range(2): for p in ['X','Z']: pauli = {} for pp in 'IXZ': pauli[pp] = (j==1)*pp + p + (j==0)*pp prob[pauli['I']] = 0 for basis in [pauli['X'],pauli['Z']]: for string in results[basis]: if string[(j+1)%2]=='1': prob[pauli['I']] += results[basis][string]/2 # prob of expectation value -1 for two qubit observables for basis in ['ZZ','ZX','XZ','XX']: prob[basis] = 0 for string in results[basis]: if string[0]!=string[1]: prob[basis] += results[basis][string] for pauli in prob: self.rho[pauli] = 1-2*prob[pauli] def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""): """ rho = None Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc. labels = None Dictionary of strings for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' that are printed in the corresponding boxes. bloch = None If a qubit name is supplied, and if mode='line',
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
['I']] += results[basis][string]/2 # prob of expectation value -1 for two qubit observables for basis in ['ZZ','ZX','XZ','XX']: prob[basis] = 0 for string in results[basis]: if string[0]!=string[1]: prob[basis] += results[basis][string] for pauli in prob: self.rho[pauli] = 1-2*prob[pauli] def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""): """ rho = None Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc. labels = None Dictionary of strings for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' that are printed in the corresponding boxes. bloch = None If a qubit name is supplied, and if mode='line', Bloch circles are displayed for this qubit hidden = [] Which qubits have their circles hidden (empty list if both shown). qubit = True Whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles). corr = True Whether the correlation circles (the four in the middle) are shown. message A string of text that is displayed below the grid. """ def see_if_unhidden(pauli): # For a given Pauli, see whether its circle should be shown. unhidden = True # first: does it act non-trivially on a qubit in `hidden` for j in hidden: unhidden = unhidden and (pauli[j]=='I') # second: does it contain something other than 'I' or 'Z' when only bits are shown if qubit==False: for j in range(2): unhidden = unhidden and (pauli[j] in ['I','Z']) # third: is it a correlation pauli when these are not allowed if corr==False: unhidden = unhidden and ((pauli[0]=='I') or (pauli[1]=='I')) return unhidden def add_line(line,pauli_pos,pauli): """ For mode='line', add in the line. line = the type of line to be drawn (X, Z or the other one) pauli = the box where the line is to be drawn expect = the expectation value that determines its length """ unhidden = see_if_unhidden(pauli) coord = None p = (1-self.rho[pauli])/2 # prob of 1 output # in the following, white lines goes from a to b, and black from b to c if unhidden: if line=='Z': a = ( self.box[pauli_pos][0], self.box[pauli_pos][1]+l/2 ) c = ( self.box[pauli_pos][0], self.box[pauli_pos][1]-l/2 ) b = ( (1-p)*a[0] + p*c[0], (1-p)*a[1] + p*c[1] ) lw = 8 coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2 elif line=='X': a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] ) c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] ) b = ( (1-p)*a[0] + p*c[0], (1-p)*a[1] + p*c[1] ) lw = 9 coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2 else: a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) ) c = ( self.box[pauli_pos][0]-l/(2*np
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
] ) lw = 8 coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2 elif line=='X': a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] ) c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] ) b = ( (1-p)*a[0] + p*c[0], (1-p)*a[1] + p*c[1] ) lw = 9 coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2 else: a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) ) c = ( self.box[pauli_pos][0]-l/(2*np.sqrt(2)), self.box[pauli_pos][1]-l/(2*np.sqrt(2)) ) b = ( (1-p)*a[0] + p*c[0], (1-p)*a[1] + p*c[1] ) lw = 9 self.lines[pauli]['w'].pop(0).remove() self.lines[pauli]['b'].pop(0).remove() self.lines[pauli]['w'] = plt.plot( [a[0],b[0]], [a[1],b[1]], color=(1.0,1.0,1.0), lw=lw ) self.lines[pauli]['b'] = plt.plot( [b[0],c[0]], [b[1],c[1]], color=(0.0,0.0,0.0), lw=lw ) return coord l = 0.9 # line length r = 0.6 # circle radius L = 0.98*np.sqrt(2) # box height and width if rho==None: self.get_rho() # draw boxes for pauli in self.box: if 'I' in pauli: color = self.colors[1] else: color = self.colors[2] self.ax.add_patch( Rectangle( (self.box[pauli][0],self.box[pauli][1]-1), L, L, angle=45, color=color) ) # draw circles for pauli in self.box: unhidden = see_if_unhidden(pauli) if unhidden: if self.mode=='line': self.ax.add_patch( Circle(self.box[pauli], r, color=(0.5,0.5,0.5)) ) else: prob = (1-self.rho[pauli])/2 self.ax.add_patch( Circle(self.box[pauli], r, color=(prob,prob,prob)) ) # update bars if required if self.mode=='line': if bloch in ['0','1']: for other in 'IXZ': px = other*(bloch=='1') + 'X' + other*(bloch=='0') pz = other*(bloch=='1') + 'Z' + other*(bloch=='0') z_coord = add_line('Z',pz,pz) x_coord = add_line('X',pz,px) for j in self.lines[pz]['c']: self.lines[pz]['c'][j].center = (x_coord,z_coord) self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04 px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1') pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1') add_line('Z',pz,pz) add_line('X',px,px) else: for pauli in self.box: for j in self.lines[pauli]['c']: self.lines[pauli]['c'][j].radius = 0.0 if pauli in
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
1') + 'X' + other*(bloch=='0') pz = other*(bloch=='1') + 'Z' + other*(bloch=='0') z_coord = add_line('Z',pz,pz) x_coord = add_line('X',pz,px) for j in self.lines[pz]['c']: self.lines[pz]['c'][j].center = (x_coord,z_coord) self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04 px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1') pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1') add_line('Z',pz,pz) add_line('X',px,px) else: for pauli in self.box: for j in self.lines[pauli]['c']: self.lines[pauli]['c'][j].radius = 0.0 if pauli in ['ZI','IZ','ZZ']: add_line('Z',pauli,pauli) if pauli in ['XI','IX','XX']: add_line('X',pauli,pauli) if pauli in ['XZ','ZX']: add_line('ZX',pauli,pauli) self.bottom.set_text(message) if labels: for pauli in box: plt.text(self.box[pauli][0]-0.05,self.box[pauli][1]-0.85, pauli) self.ax.set_xlim([-3,3]) self.ax.set_ylim([0,6]) self.fig.canvas.draw()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import IBMQ from qiskit import BasicAer as Aer from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle, Rectangle import copy from ipywidgets import widgets from IPython.display import display, clear_output try: IBMQ.load_accounts() except: pass class run_game(): # Implements a puzzle, which is defined by the given inputs. def __init__(self,initialize, success_condition, allowed_gates, vi, qubit_names, eps=0.1, backend=Aer.get_backend('qasm_simulator'), shots=1024,mode='circle',verbose=False): """ initialize List of gates applied to the initial 00 state to get the starting state of the puzzle. Supported single qubit gates (applied to qubit '0' or '1') are 'x', 'y', 'z', 'h', 'ry(pi/4)'. Supported two qubit gates are 'cz' and 'cx'. Specify only the target qubit. success_condition Values for pauli observables that must be obtained for the puzzle to declare success. allowed_gates For each qubit, specify which operations are allowed in this puzzle. 'both' should be used only for operations that don't need a qubit to be specified ('cz' and 'unbloch'). Gates are expressed as a dict with an int as value. If this is non-zero, it specifies the number of times the gate is must be used (no more or less) for the puzzle to be successfully solved. If the value is zero, the player can use the gate any number of times. vi Some visualization information as a three element list. These specify: * which qubits are hidden (empty list if both shown). * whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles). * whether the correlation circles (the four in the middle) are shown. qubit_names The two qubits are always called '0' and '1' from the programming side. But for the player, we can display different names. eps=0.1 How close the expectation values need to be to the targets for success to be declared. backend=Aer.get_backend('qasm_simulator') Backend to be used by Qiskit to calculate expectation values (defaults to local simulator). shots=1024 Number of shots used to to calculate expectation values. mode='circle' Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line'). verbose=False """ def get_total_gate_list(): # Get a text block describing allowed gates. total_gate_list = "" for qubit in allowed_gates: gate_list = "" for gate in allowed_gates[qubit]: if required_gates[qubit][gate] > 0 : gate_list +=''+ gate+" (use "+str(required_gates[qubit][gate])+" time"+"s"*(required_gates[qubit][gate]>1)+")" elif allowed_gates[qubit][gate]==0: gate_list +=' '+gate +'' if gate_list!="": if qubit=="both" : gate_list = "\nAllowed symmetric operations:" + gate_list else : gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list total_gate_list += gate_list +"\n" return total_gate_list def get_success(required_gates): # Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used. success = True grid.get_rho() if verbose: print(grid.rho) for pauli in success_condition: success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps) for qubit in required_gates: for gate in required_gates[qubit]: success = success and (required_gates[qubit][gate]==0) return success def get_command(gate,qubit
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
ates[qubit][gate]==0: gate_list +=' '+gate +'' if gate_list!="": if qubit=="both" : gate_list = "\nAllowed symmetric operations:" + gate_list else : gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list total_gate_list += gate_list +"\n" return total_gate_list def get_success(required_gates): # Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used. success = True grid.get_rho() if verbose: print(grid.rho) for pauli in success_condition: success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps) for qubit in required_gates: for gate in required_gates[qubit]: success = success and (required_gates[qubit][gate]==0) return success def get_command(gate,qubit): # For a given gate and qubit, return the string describing the corresoinding Qiskit string. if qubit=='both': qubit = '1' qubit_name = qubit_names[qubit] for name in qubit_names.values(): if name!=qubit_name: other_name = name # then make the command (both for the grid, and for printing to screen) if gate in ['x','y','z','h']: real_command = 'grid.qc.'+gate+'(grid.qr['+qubit+'])' clean_command = 'qc.'+gate+'('+qubit_name+')' elif gate in ['ry(pi/4)','ry(-pi/4)']: real_command = 'grid.qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,grid.qr['+qubit+'])' clean_command = 'qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,'+qubit_name+')' elif gate in ['cz','cx','swap']: real_command = 'grid.qc.'+gate+'(grid.qr['+'0'*(qubit=='1')+'1'*(qubit=='0')+'],grid.qr['+qubit+'])' clean_command = 'qc.'+gate+'('+other_name+','+qubit_name+')' return [real_command,clean_command] clear_output() bloch = [None] # set up initial state and figure grid = pauli_grid(backend=backend,shots=shots,mode=mode) for gate in initialize: eval( get_command(gate[0],gate[1])[0] ) required_gates = copy.deepcopy(allowed_gates) # determine which qubits to show in figure if allowed_gates['0']=={} : # if no gates are allowed for qubit 0, we know to only show qubit 1 shown_qubit = 1 elif allowed_gates['1']=={} : # and vice versa shown_qubit = 0 else : shown_qubit = 2 # show figure grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']} all_allowed_gates_raw = [] for q in ['0','1','both']: all_allowed_gates_raw += list(allowed_gates[q]) all_allowed_gates_raw = list(set(all_allowed_gates_raw)) all_allowed_gates = [] for g in ['bloch','unbloch']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in ['x','y','z','h','cz','cx']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in all_allowed_gates_raw: if g not in all_allowed_gates:
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
figure grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']} all_allowed_gates_raw = [] for q in ['0','1','both']: all_allowed_gates_raw += list(allowed_gates[q]) all_allowed_gates_raw = list(set(all_allowed_gates_raw)) all_allowed_gates = [] for g in ['bloch','unbloch']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in ['x','y','z','h','cz','cx']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in all_allowed_gates_raw: if g not in all_allowed_gates: all_allowed_gates.append( g ) gate = widgets.ToggleButtons(options=description['gate']+all_allowed_gates) qubit = widgets.ToggleButtons(options=['']) action = widgets.ToggleButtons(options=['']) boxes = widgets.VBox([gate,qubit,action]) display(boxes) if vi[1]: print('\nYour quantum program so far\n') self.program = [] def given_gate(a): # Action to be taken when gate is chosen. This sets up the system to choose a qubit. if gate.value: if gate.value in allowed_gates['both']: qubit.options = description['qubit'] + ["not required"] qubit.value = "not required" else: allowed_qubits = [] for q in ['0','1']: if (gate.value in allowed_gates[q]) or (gate.value in allowed_gates['both']): allowed_qubits.append(q) allowed_qubit_names = [] for q in allowed_qubits: allowed_qubit_names += [qubit_names[q]] qubit.options = description['qubit'] + allowed_qubit_names def given_qubit(b): # Action to be taken when qubit is chosen. This sets up the system to choose an action. if qubit.value not in ['',description['qubit'][0],'Success!']: action.options = description['action']+['Apply operation'] def given_action(c): # Action to be taken when user confirms their choice of gate and qubit. # This applied the command, updates the visualization and checks whether the puzzle is solved. if action.value not in ['',description['action'][0]]: # apply operation if action.value=='Apply operation': if qubit.value not in ['',description['qubit'][0],'Success!']: # translate bit gates to qubit gates if gate.value=='NOT': q_gate = 'x' elif gate.value=='CNOT': q_gate = 'cx' else: q_gate = gate.value if qubit.value=="not required": q = qubit_names['1'] else: q = qubit.value q01 = '0'*(qubit.value==qubit_names['0']) + '1'*(qubit.value==qubit_names['1']) + 'both'*(qubit.value=="not required") if q_gate in ['bloch','unbloch']: if q_gate=='bloch': bloch[0] = q01 else: bloch[0] = None else: command = get_command(q_gate,q01) eval(command[0]) if vi[1]: print(command[1]) self.program.append( command[1] ) if required_gates[q01][gate.value]>0: required_gates[q01][gate.value] -= 1 grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) success = get_success(required_gates) if success
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
qubit_names['1'] else: q = qubit.value q01 = '0'*(qubit.value==qubit_names['0']) + '1'*(qubit.value==qubit_names['1']) + 'both'*(qubit.value=="not required") if q_gate in ['bloch','unbloch']: if q_gate=='bloch': bloch[0] = q01 else: bloch[0] = None else: command = get_command(q_gate,q01) eval(command[0]) if vi[1]: print(command[1]) self.program.append( command[1] ) if required_gates[q01][gate.value]>0: required_gates[q01][gate.value] -= 1 grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) success = get_success(required_gates) if success: gate.options = ['Success!'] qubit.options = ['Success!'] action.options = ['Success!'] plt.close(grid.fig) else: gate.value = description['gate'][0] qubit.options = [''] action.options = [''] gate.observe(given_gate) qubit.observe(given_qubit) action.observe(given_action) class pauli_grid(): # Allows a quantum circuit to be created, modified and implemented, and visualizes the output in the style of 'Hello Quantum'. def __init__(self,backend=Aer.get_backend('qasm_simulator'),shots=1024,mode='circle'): """ backend=Aer.get_backend('qasm_simulator') Backend to be used by Qiskit to calculate expectation values (defaults to local simulator). shots=1024 Number of shots used to to calculate expectation values. mode='circle' Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line'). """ self.backend = backend self.shots = shots self.box = {'ZI':(-1, 2),'XI':(-2, 3),'IZ':( 1, 2),'IX':( 2, 3),'ZZ':( 0, 3),'ZX':( 1, 4),'XZ':(-1, 4),'XX':( 0, 5)} self.rho = {} for pauli in self.box: self.rho[pauli] = 0.0 for pauli in ['ZI','IZ','ZZ']: self.rho[pauli] = 1.0 self.qr = QuantumRegister(2) self.cr = ClassicalRegister(2) self.qc = QuantumCircuit(self.qr, self.cr) self.mode = mode # colors are background, qubit circles and correlation circles, respectively if self.mode=='line': self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] else: self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0]) self.ax = self.fig.add_subplot(111) plt.axis('off') self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w') self.lines = {} for pauli in self.box: w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
/255,236/255),(33/255,114/255,216/255)] else: self.colors = [(1.6/255,72/255,138/255),(132/255,177/255,236/255),(33/255,114/255,216/255)] self.fig = plt.figure(figsize=(5,5),facecolor=self.colors[0]) self.ax = self.fig.add_subplot(111) plt.axis('off') self.bottom = self.ax.text(-3,1,"",size=9,va='top',color='w') self.lines = {} for pauli in self.box: w = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(1.0,1.0,1.0), lw=0 ) b = plt.plot( [self.box[pauli][0],self.box[pauli][0]], [self.box[pauli][1],self.box[pauli][1]], color=(0.0,0.0,0.0), lw=0 ) c = {} c['w'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(0,0,0), zorder=10) ) c['b'] = self.ax.add_patch( Circle(self.box[pauli], 0.0, color=(1,1,1), zorder=10) ) self.lines[pauli] = {'w':w,'b':b,'c':c} def get_rho(self): # Runs the circuit specified by self.qc and determines the expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. bases = ['ZZ','ZX','XZ','XX'] results = {} for basis in bases: temp_qc = copy.deepcopy(self.qc) for j in range(2): if basis[j]=='X': temp_qc.h(self.qr[j]) temp_qc.barrier(self.qr) temp_qc.measure(self.qr,self.cr) job = execute(temp_qc, backend=self.backend, shots=self.shots) results[basis] = job.result().get_counts() for string in results[basis]: results[basis][string] = results[basis][string]/self.shots prob = {} # prob of expectation value -1 for single qubit observables for j in range(2): for p in ['X','Z']: pauli = {} for pp in 'IXZ': pauli[pp] = (j==1)*pp + p + (j==0)*pp prob[pauli['I']] = 0 for basis in [pauli['X'],pauli['Z']]: for string in results[basis]: if string[(j+1)%2]=='1': prob[pauli['I']] += results[basis][string]/2 # prob of expectation value -1 for two qubit observables for basis in ['ZZ','ZX','XZ','XX']: prob[basis] = 0 for string in results[basis]: if string[0]!=string[1]: prob[basis] += results[basis][string] for pauli in prob: self.rho[pauli] = 1-2*prob[pauli] def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""): """ rho = None Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc. labels = None Dictionary of strings for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' that are printed in the corresponding boxes. bloch = None If a qubit name is supplied, and if mode='line',
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
['I']] += results[basis][string]/2 # prob of expectation value -1 for two qubit observables for basis in ['ZZ','ZX','XZ','XX']: prob[basis] = 0 for string in results[basis]: if string[0]!=string[1]: prob[basis] += results[basis][string] for pauli in prob: self.rho[pauli] = 1-2*prob[pauli] def update_grid(self,rho=None,labels=False,bloch=None,hidden=[],qubit=True,corr=True,message=""): """ rho = None Dictionary of expectation values for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ'. If supplied, this will be visualized instead of the results of running self.qc. labels = None Dictionary of strings for 'ZI', 'IZ', 'ZZ', 'XI', 'IX', 'XX', 'ZX' and 'XZ' that are printed in the corresponding boxes. bloch = None If a qubit name is supplied, and if mode='line', Bloch circles are displayed for this qubit hidden = [] Which qubits have their circles hidden (empty list if both shown). qubit = True Whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles). corr = True Whether the correlation circles (the four in the middle) are shown. message A string of text that is displayed below the grid. """ def see_if_unhidden(pauli): # For a given Pauli, see whether its circle should be shown. unhidden = True # first: does it act non-trivially on a qubit in `hidden` for j in hidden: unhidden = unhidden and (pauli[j]=='I') # second: does it contain something other than 'I' or 'Z' when only bits are shown if qubit==False: for j in range(2): unhidden = unhidden and (pauli[j] in ['I','Z']) # third: is it a correlation pauli when these are not allowed if corr==False: unhidden = unhidden and ((pauli[0]=='I') or (pauli[1]=='I')) return unhidden def add_line(line,pauli_pos,pauli): """ For mode='line', add in the line. line = the type of line to be drawn (X, Z or the other one) pauli = the box where the line is to be drawn expect = the expectation value that determines its length """ unhidden = see_if_unhidden(pauli) coord = None p = (1-self.rho[pauli])/2 # prob of 1 output # in the following, white lines goes from a to b, and black from b to c if unhidden: if line=='Z': a = ( self.box[pauli_pos][0], self.box[pauli_pos][1]+l/2 ) c = ( self.box[pauli_pos][0], self.box[pauli_pos][1]-l/2 ) b = ( (1-p)*a[0] + p*c[0], (1-p)*a[1] + p*c[1] ) lw = 8 coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2 elif line=='X': a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] ) c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] ) b = ( (1-p)*a[0] + p*c[0], (1-p)*a[1] + p*c[1] ) lw = 9 coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2 else: a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) ) c = ( self.box[pauli_pos][0]-l/(2*np
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
] ) lw = 8 coord = (b[1] - (a[1]+c[1])/2)*1.2 + (a[1]+c[1])/2 elif line=='X': a = ( self.box[pauli_pos][0]+l/2, self.box[pauli_pos][1] ) c = ( self.box[pauli_pos][0]-l/2, self.box[pauli_pos][1] ) b = ( (1-p)*a[0] + p*c[0], (1-p)*a[1] + p*c[1] ) lw = 9 coord = (b[0] - (a[0]+c[0])/2)*1.1 + (a[0]+c[0])/2 else: a = ( self.box[pauli_pos][0]+l/(2*np.sqrt(2)), self.box[pauli_pos][1]+l/(2*np.sqrt(2)) ) c = ( self.box[pauli_pos][0]-l/(2*np.sqrt(2)), self.box[pauli_pos][1]-l/(2*np.sqrt(2)) ) b = ( (1-p)*a[0] + p*c[0], (1-p)*a[1] + p*c[1] ) lw = 9 self.lines[pauli]['w'].pop(0).remove() self.lines[pauli]['b'].pop(0).remove() self.lines[pauli]['w'] = plt.plot( [a[0],b[0]], [a[1],b[1]], color=(1.0,1.0,1.0), lw=lw ) self.lines[pauli]['b'] = plt.plot( [b[0],c[0]], [b[1],c[1]], color=(0.0,0.0,0.0), lw=lw ) return coord l = 0.9 # line length r = 0.6 # circle radius L = 0.98*np.sqrt(2) # box height and width if rho==None: self.get_rho() # draw boxes for pauli in self.box: if 'I' in pauli: color = self.colors[1] else: color = self.colors[2] self.ax.add_patch( Rectangle( (self.box[pauli][0],self.box[pauli][1]-1), L, L, angle=45, color=color) ) # draw circles for pauli in self.box: unhidden = see_if_unhidden(pauli) if unhidden: if self.mode=='line': self.ax.add_patch( Circle(self.box[pauli], r, color=(0.5,0.5,0.5)) ) else: prob = (1-self.rho[pauli])/2 self.ax.add_patch( Circle(self.box[pauli], r, color=(prob,prob,prob)) ) # update bars if required if self.mode=='line': if bloch in ['0','1']: for other in 'IXZ': px = other*(bloch=='1') + 'X' + other*(bloch=='0') pz = other*(bloch=='1') + 'Z' + other*(bloch=='0') z_coord = add_line('Z',pz,pz) x_coord = add_line('X',pz,px) for j in self.lines[pz]['c']: self.lines[pz]['c'][j].center = (x_coord,z_coord) self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04 px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1') pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1') add_line('Z',pz,pz) add_line('X',px,px) else: for pauli in self.box: for j in self.lines[pauli]['c']: self.lines[pauli]['c'][j].radius = 0.0 if pauli in
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
1') + 'X' + other*(bloch=='0') pz = other*(bloch=='1') + 'Z' + other*(bloch=='0') z_coord = add_line('Z',pz,pz) x_coord = add_line('X',pz,px) for j in self.lines[pz]['c']: self.lines[pz]['c'][j].center = (x_coord,z_coord) self.lines[pz]['c'][j].radius = (j=='w')*0.05 + (j=='b')*0.04 px = 'I'*(bloch=='0') + 'X' + 'I'*(bloch=='1') pz = 'I'*(bloch=='0') + 'Z' + 'I'*(bloch=='1') add_line('Z',pz,pz) add_line('X',px,px) else: for pauli in self.box: for j in self.lines[pauli]['c']: self.lines[pauli]['c'][j].radius = 0.0 if pauli in ['ZI','IZ','ZZ']: add_line('Z',pauli,pauli) if pauli in ['XI','IX','XX']: add_line('X',pauli,pauli) if pauli in ['XZ','ZX']: add_line('ZX',pauli,pauli) self.bottom.set_text(message) if labels: for pauli in box: plt.text(self.box[pauli][0]-0.05,self.box[pauli][1]-0.85, pauli) self.ax.set_xlim([-3,3]) self.ax.set_ylim([0,6]) self.fig.canvas.draw()
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import IBMQ from qiskit import BasicAer as Aer from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle, Rectangle import copy from ipywidgets import widgets from IPython.display import display, clear_output try: IBMQ.load_accounts() except: pass class run_game(): # Implements a puzzle, which is defined by the given inputs. def __init__(self,initialize, success_condition, allowed_gates, vi, qubit_names, eps=0.1, backend=Aer.get_backend('qasm_simulator'), shots=1024,mode='circle',verbose=False): """ initialize List of gates applied to the initial 00 state to get the starting state of the puzzle. Supported single qubit gates (applied to qubit '0' or '1') are 'x', 'y', 'z', 'h', 'ry(pi/4)'. Supported two qubit gates are 'cz' and 'cx'. Specify only the target qubit. success_condition Values for pauli observables that must be obtained for the puzzle to declare success. allowed_gates For each qubit, specify which operations are allowed in this puzzle. 'both' should be used only for operations that don't need a qubit to be specified ('cz' and 'unbloch'). Gates are expressed as a dict with an int as value. If this is non-zero, it specifies the number of times the gate is must be used (no more or less) for the puzzle to be successfully solved. If the value is zero, the player can use the gate any number of times. vi Some visualization information as a three element list. These specify: * which qubits are hidden (empty list if both shown). * whether both circles shown for each qubit (use True for qubit puzzles and False for bit puzzles). * whether the correlation circles (the four in the middle) are shown. qubit_names The two qubits are always called '0' and '1' from the programming side. But for the player, we can display different names. eps=0.1 How close the expectation values need to be to the targets for success to be declared. backend=Aer.get_backend('qasm_simulator') Backend to be used by Qiskit to calculate expectation values (defaults to local simulator). shots=1024 Number of shots used to to calculate expectation values. mode='circle' Either the standard 'Hello Quantum' visualization can be used (with mode='circle') or the alternative line based one (mode='line'). verbose=False """ def get_total_gate_list(): # Get a text block describing allowed gates. total_gate_list = "" for qubit in allowed_gates: gate_list = "" for gate in allowed_gates[qubit]: if required_gates[qubit][gate] > 0 : gate_list +=''+ gate+" (use "+str(required_gates[qubit][gate])+" time"+"s"*(required_gates[qubit][gate]>1)+")" elif allowed_gates[qubit][gate]==0: gate_list +=' '+gate +'' if gate_list!="": if qubit=="both" : gate_list = "\nAllowed symmetric operations:" + gate_list else : gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list total_gate_list += gate_list +"\n" return total_gate_list def get_success(required_gates): # Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used. success = True grid.get_rho() if verbose: print(grid.rho) for pauli in success_condition: success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps) for qubit in required_gates: for gate in required_gates[qubit]: success = success and (required_gates[qubit][gate]==0) return success def get_command(gate,qubit
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
ates[qubit][gate]==0: gate_list +=' '+gate +'' if gate_list!="": if qubit=="both" : gate_list = "\nAllowed symmetric operations:" + gate_list else : gate_list = "\nAllowed operations for " + qubit_names[qubit] + ":\n" + " "*10 + gate_list total_gate_list += gate_list +"\n" return total_gate_list def get_success(required_gates): # Determine whether the success conditions are satisfied, both for expectation values, and the number of gates to be used. success = True grid.get_rho() if verbose: print(grid.rho) for pauli in success_condition: success = success and (abs(success_condition[pauli] - grid.rho[pauli])<eps) for qubit in required_gates: for gate in required_gates[qubit]: success = success and (required_gates[qubit][gate]==0) return success def get_command(gate,qubit): # For a given gate and qubit, return the string describing the corresoinding Qiskit string. if qubit=='both': qubit = '1' qubit_name = qubit_names[qubit] for name in qubit_names.values(): if name!=qubit_name: other_name = name # then make the command (both for the grid, and for printing to screen) if gate in ['x','y','z','h']: real_command = 'grid.qc.'+gate+'(grid.qr['+qubit+'])' clean_command = 'qc.'+gate+'('+qubit_name+')' elif gate in ['ry(pi/4)','ry(-pi/4)']: real_command = 'grid.qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,grid.qr['+qubit+'])' clean_command = 'qc.ry('+'-'*(gate=='ry(-pi/4)')+'np.pi/4,'+qubit_name+')' elif gate in ['cz','cx','swap']: real_command = 'grid.qc.'+gate+'(grid.qr['+'0'*(qubit=='1')+'1'*(qubit=='0')+'],grid.qr['+qubit+'])' clean_command = 'qc.'+gate+'('+other_name+','+qubit_name+')' return [real_command,clean_command] clear_output() bloch = [None] # set up initial state and figure grid = pauli_grid(backend=backend,shots=shots,mode=mode) for gate in initialize: eval( get_command(gate[0],gate[1])[0] ) required_gates = copy.deepcopy(allowed_gates) # determine which qubits to show in figure if allowed_gates['0']=={} : # if no gates are allowed for qubit 0, we know to only show qubit 1 shown_qubit = 1 elif allowed_gates['1']=={} : # and vice versa shown_qubit = 0 else : shown_qubit = 2 # show figure grid.update_grid(bloch=bloch[0],hidden=vi[0],qubit=vi[1],corr=vi[2],message=get_total_gate_list()) description = {'gate':['Choose gate'],'qubit':['Choose '+'qu'*vi[1]+'bit'],'action':['Make it happen!']} all_allowed_gates_raw = [] for q in ['0','1','both']: all_allowed_gates_raw += list(allowed_gates[q]) all_allowed_gates_raw = list(set(all_allowed_gates_raw)) all_allowed_gates = [] for g in ['bloch','unbloch']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in ['x','y','z','h','cz','cx']: if g in all_allowed_gates_raw: all_allowed_gates.append( g ) for g in all_allowed_gates_raw: if g not in all_allowed_gates:
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
-