Dataset Viewer
Auto-converted to Parquet Duplicate
repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
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
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/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
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 * %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
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. 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 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): # 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: 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: 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,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', 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.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 ['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
# 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. """ Example use of the initialize gate to prepare arbitrary pure states. """ import math from qiskit import QuantumCircuit, execute, BasicAer ############################################################### # Make a quantum circuit for state initialization. ############################################################### circuit = QuantumCircuit(4, 4, name="initializer_circ") desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] circuit.initialize(desired_vector, [0, 1, 2, 3]) circuit.measure([0, 1, 2, 3], [0, 1, 2, 3]) print(circuit) ############################################################### # Execute on a simulator backend. ############################################################### shots = 10000 # Desired vector print("Desired probabilities: ") print([format(abs(x * x), ".3f") for x in desired_vector]) # Initialize on local simulator sim_backend = BasicAer.get_backend("qasm_simulator") job = execute(circuit, sim_backend, shots=shots) result = job.result() counts = result.get_counts(circuit) qubit_strings = [format(i, "04b") for i in range(2**4)] print("Probabilities from simulator: ") print([format(counts.get(s, 0) / shots, ".3f") for s in qubit_strings])
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 on how to load a file into a QuantumCircuit.""" from qiskit import QuantumCircuit from qiskit import execute, BasicAer circ = QuantumCircuit.from_qasm_file("examples/qasm/entangled_registers.qasm") print(circ) # See the backend sim_backend = BasicAer.get_backend("qasm_simulator") # Compile and run the Quantum circuit on a local simulator backend job_sim = execute(circ, sim_backend) sim_result = job_sim.result() # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(circ))
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
# 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. """ Ripple adder example based on Cuccaro et al., quant-ph/0410184. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import BasicAer from qiskit import execute ############################################################### # Set the backend name and coupling map. ############################################################### backend = BasicAer.get_backend("qasm_simulator") coupling_map = [ [0, 1], [0, 8], [1, 2], [1, 9], [2, 3], [2, 10], [3, 4], [3, 11], [4, 5], [4, 12], [5, 6], [5, 13], [6, 7], [6, 14], [7, 15], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], ] ############################################################### # Make a quantum program for the n-bit ripple adder. ############################################################### n = 2 a = QuantumRegister(n, "a") b = QuantumRegister(n, "b") cin = QuantumRegister(1, "cin") cout = QuantumRegister(1, "cout") ans = ClassicalRegister(n + 1, "ans") qc = QuantumCircuit(a, b, cin, cout, ans, name="rippleadd") def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c) def unmajority(p, a, b, c): """Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b) # Build a temporary subcircuit that adds a to b, # storing the result in b adder_subcircuit = QuantumCircuit(cin, a, b, cout) majority(adder_subcircuit, cin[0], b[0], a[0]) for j in range(n - 1): majority(adder_subcircuit, a[j], b[j + 1], a[j + 1]) adder_subcircuit.cx(a[n - 1], cout[0]) for j in reversed(range(n - 1)): unmajority(adder_subcircuit, a[j], b[j + 1], a[j + 1]) unmajority(adder_subcircuit, cin[0], b[0], a[0]) # Set the inputs to the adder qc.x(a[0]) # Set input a = 0...0001 qc.x(b) # Set input b = 1...1111 # Apply the adder qc &= adder_subcircuit # Measure the output register in the computational basis for j in range(n): qc.measure(b[j], ans[j]) qc.measure(cout[0], ans[n]) ############################################################### # execute the program. ############################################################### # First version: not mapped job = execute(qc, backend=backend, coupling_map=None, shots=1024) 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) 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, 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. """Example of using the StochasticSwap pass.""" from qiskit.transpiler.passes import StochasticSwap from qiskit.transpiler import CouplingMap from qiskit.converters import circuit_to_dag from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circ = QuantumCircuit(qr, cr) circ.cx(qr[1], qr[2]) circ.cx(qr[0], qr[3]) circ.measure(qr[0], cr[0]) circ.h(qr) circ.cx(qr[0], qr[1]) circ.cx(qr[2], qr[3]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) dag = circuit_to_dag(circ) # ┌─┐┌───┐ ┌─┐ # q_0: |0>─────────────────■──────────────────┤M├┤ H ├──■─────┤M├ # ┌───┐ │ └╥┘└───┘┌─┴─┐┌─┐└╥┘ # q_1: |0>──■───────┤ H ├──┼───────────────────╫──────┤ X ├┤M├─╫─ # ┌─┴─┐┌───┐└───┘ │ ┌─┐ ║ └───┘└╥┘ ║ # q_2: |0>┤ X ├┤ H ├───────┼─────────■─────┤M├─╫────────────╫──╫─ # └───┘└───┘ ┌─┴─┐┌───┐┌─┴─┐┌─┐└╥┘ ║ ║ ║ # q_3: |0>───────────────┤ X ├┤ H ├┤ X ├┤M├─╫──╫────────────╫──╫─ # └───┘└───┘└───┘└╥┘ ║ ║ ║ ║ # c_0: 0 ═══════════════════════════════╬══╬══╩════════════╬══╩═ # ║ ║ ║ # c_1: 0 ═══════════════════════════════╬══╬═══════════════╩════ # ║ ║ # c_2: 0 ═══════════════════════════════╬══╩════════════════════ # ║ # c_3: 0 ═══════════════════════════════╩═══════════════════════ # # ┌─┐┌───┐ ┌─┐ # q_0: |0>────────────────────■──┤M├┤ H ├──────────────────■──┤M├────── # ┌─┴─┐└╥┘└───┘┌───┐┌───┐ ┌─┴─┐└╥┘┌─┐ # q_1: |0>──■───X───────────┤ X ├─╫──────┤ H ├┤ X ├─X────┤ X ├─╫─┤M├─── # ┌─┴─┐ │ ┌───┐└───┘ ║ └───┘└─┬─┘ │ └───┘ ║ └╥┘┌─┐ # q_2: |0>┤ X ├─┼──────┤ H ├──────╫─────────────■───┼──────────╫──╫─┤M├ # └───┘ │ ┌───┐└───┘ ║ │ ┌─┐ ║ ║ └╥┘ # q_3: |0>──────X─┤ H ├───────────╫─────────────────X─┤M├──────╫──╫──╫─ # └───┘ ║ └╥┘ ║ ║ ║ # c_0: 0 ════════════════════════╩════════════════════╬═══════╩══╬══╬═ # ║ ║ ║ # c_1: 0 ═════════════════════════════════════════════╬══════════╩══╬═ # ║ ║ # c_2: 0 ═════════════════════════════════════════════╬═════════════╩═ # ║ # c_3: 0 ═════════════════════════════════════════════╩═══════════════ # # # 2 # | # 0 - 1 - 3 # Build the expected output to verify the pass worked expected = QuantumCircuit(qr, cr) expected.cx(qr[1], qr[2]) expected.h(qr[2]) expected.swap(qr[0], qr[1]) expected.h(qr[0]) expected.cx(qr[1], qr[3]) expected.h(qr[3]) expected.measure(qr[1], cr[0]) expected.swap(qr[1], qr[3]) expected.cx(qr[2], qr[1]) expected.h(qr[3]) expected.swap(qr[0], qr[1]) expected.measure(qr[2], cr[2]) expected.cx(qr[3], qr[1]) expected.measure(qr[0], cr[3]) expected.measure(qr[3], cr[0]) expected.measure(qr[1], cr[1]) expected_dag = circuit_to_dag(expected) # Run the pass on the dag from the input circuit pass_ = StochasticSwap(coupling, 20, 999) after = pass_.run(dag) # Verify the output of the pass matches our expectation assert expected_dag == after
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, 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 use Qiskit-Terra at level 0 (novice). This example shows the most basic way to user Terra. It builds some circuits and runs them on both the BasicAer (local Qiskit provider) or IBMQ (remote IBMQ provider). To control the compile parameters we have provided a transpile function which can be used as a level 1 user. """ # Import the Qiskit modules from qiskit import QuantumCircuit from qiskit import execute, BasicAer # making first circuit: bell state qc1 = QuantumCircuit(2, 2) qc1.h(0) qc1.cx(0, 1) qc1.measure([0, 1], [0, 1]) # making another circuit: superpositions qc2 = QuantumCircuit(2, 2) qc2.h([0, 1]) qc2.measure([0, 1], [0, 1]) # setting up the backend print("(BasicAER Backends)") print(BasicAer.backends()) # running the job job_sim = execute([qc1, qc2], BasicAer.get_backend("qasm_simulator")) sim_result = job_sim.result() # Show the results print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2))
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 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 use Qiskit at level 1 (intermediate). This example shows how an intermediate user interacts with Terra. It builds some circuits and transpiles them with transpile options. It then makes a qobj object which is just a container to be run on a backend. The same qobj can be submitted to many backends (as shown). It is the user's responsibility to make sure it can be run (i.e. it conforms to the restrictions of the backend, if any). This is useful when you want to compare the same circuit on different backends without recompiling the whole circuit, or just want to change some runtime parameters. To control the passes that transform the circuit, we have a pass manager for the level 2 user. """ import pprint, time # Import the Qiskit modules from qiskit import IBMQ, BasicAer from qiskit import QiskitError from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.compiler import transpile, assemble from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor try: IBMQ.load_accounts() except: print("""WARNING: There's no connection with the API for remote backends. Have you initialized a file with your personal token? For now, there's only access to local simulator backends...""") try: # Create a Quantum and Classical Register and give them names. qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') # Making first circuit: bell state qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) qc1.measure(qubit_reg, clbit_reg) # Making another circuit: superpositions qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition") qc2.h(qubit_reg) qc2.measure(qubit_reg, clbit_reg) # Setting up the backend print("(Aer Backends)") for backend in BasicAer.backends(): print(backend.status()) qasm_simulator = BasicAer.get_backend('qasm_simulator') # Compile and run the circuit on a real device backend # See a list of available remote backends print("\n(IBMQ Backends)") for backend in IBMQ.backends(): print(backend.status()) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) except: print("All devices are currently unavailable.") print("Running on current least busy device: ", least_busy_device) # Transpile the circuits to make them compatible with the experimental backend [qc1_new, qc2_new] = transpile(circuits=[qc1, qc2], backend=least_busy_device) print("Bell circuit before transpile:") print(qc1.draw()) print("Bell circuit after transpile:") print(qc1_new.draw()) print("Superposition circuit before transpile:") print(qc2.draw()) print("Superposition circuit after transpile:") print(qc2_new.draw()) # Assemble the two circuits into a runnable qobj qobj = assemble([qc1_new, qc2_new], shots=1000) # Running qobj on the simulator sim_job = qasm_simulator.run(qobj) # Getting the result sim_result=sim_job.result() # Show the results print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2)) # Running the job. exp_job = least_busy_device.run(qobj) job_monitor(exp_job) exp_result = exp_job.result() # Show the results print(exp_result.get_counts(qc1)) print(exp_result.get_counts(qc2)) except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex))
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 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 use Qiskit at level 2 (advanced). This example shows how an advanced user interacts with Terra. It builds some circuits and transpiles them with the pass_manager. """ import pprint, time # Import the Qiskit modules from qiskit import IBMQ, BasicAer from qiskit import QiskitError from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.extensions import SwapGate from qiskit.compiler import assemble from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor from qiskit.transpiler import PassManager from qiskit.transpiler import CouplingMap from qiskit.transpiler.passes import Unroller from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import TrivialLayout from qiskit.transpiler.passes import Decompose from qiskit.transpiler.passes import CXDirection from qiskit.transpiler.passes import LookaheadSwap try: IBMQ.load_accounts() except: print("""WARNING: There's no connection with the API for remote backends. Have you initialized a file with your personal token? For now, there's only access to local simulator backends...""") try: qubit_reg = QuantumRegister(4, name='q') clbit_reg = ClassicalRegister(4, name='c') # Making first circuit: superpositions qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell") qc1.h(qubit_reg[0]) qc1.cx(qubit_reg[0], qubit_reg[1]) qc1.measure(qubit_reg, clbit_reg) # Making another circuit: GHZ State qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition") qc2.h(qubit_reg) qc2.cx(qubit_reg[0], qubit_reg[1]) qc2.cx(qubit_reg[0], qubit_reg[2]) qc2.cx(qubit_reg[0], qubit_reg[3]) qc2.measure(qubit_reg, clbit_reg) # Setting up the backend print("(Aer Backends)") for backend in BasicAer.backends(): print(backend.status()) qasm_simulator = BasicAer.get_backend('qasm_simulator') # Compile and run the circuit on a real device backend # See a list of available remote backends print("\n(IBMQ Backends)") for backend in IBMQ.backends(): print(backend.status()) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) except: print("All devices are currently unavailable.") print("Running on current least busy device: ", least_busy_device) # making a pass manager to compile the circuits coupling_map = CouplingMap(least_busy_device.configuration().coupling_map) print("coupling map: ", coupling_map) pm = PassManager() pm.append(TrivialLayout(coupling_map)) pm.append(FullAncillaAllocation(coupling_map)) pm.append(EnlargeWithAncilla()) pm.append(LookaheadSwap(coupling_map)) pm.append(Decompose(SwapGate)) pm.append(CXDirection(coupling_map)) pm.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx'])) qc1_new = pm.run(qc1) qc2_new = pm.run(qc2) print("Bell circuit before passes:") print(qc1.draw()) print("Bell circuit after passes:") print(qc1_new.draw()) print("Superposition circuit before passes:") print(qc2.draw()) print("Superposition circuit after passes:") print(qc2_new.draw()) # Assemble the two circuits into a runnable qobj qobj = assemble([qc1_new, qc2_new], shots=1000) # Running qobj on the simulator print("Running on simulator:") sim_job = qasm_simulator.run(qobj) # Getting the result sim_result=sim_job.result() # Show the results print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2)) # Running the job. print("Running on device:") exp_job = least_busy_device.run(qobj) job_monitor(exp_job) exp_result = exp_job.result() # Show the results print(exp_result.get_counts(qc1)) print(exp_result.get_counts(qc2)) except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex))
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 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Utils for reading a user preference config files.""" import configparser import os from qiskit import exceptions DEFAULT_FILENAME = os.path.join(os.path.expanduser("~"), '.qiskit', 'settings.conf') class UserConfig: """Class representing a user config file The config file format should look like: [default] circuit_drawer = mpl """ def __init__(self, filename=None): """Create a UserConfig Args: filename (str): The path to the user config file. If one isn't specified ~/.qiskit/settings.conf is used. """ if filename is None: self.filename = DEFAULT_FILENAME else: self.filename = filename self.settings = {} self.config_parser = configparser.ConfigParser() def read_config_file(self): """Read config file and parse the contents into the settings attr.""" if not os.path.isfile(self.filename): return self.config_parser.read(self.filename) if 'default' in self.config_parser.sections(): circuit_drawer = self.config_parser.get('default', 'circuit_drawer') if circuit_drawer: if circuit_drawer not in ['text', 'mpl', 'latex', 'latex_source']: raise exceptions.QiskitUserConfigError( "%s is not a valid circuit drawer backend. Must be " "either 'text', 'mpl', 'latex', or 'latex_source'" % circuit_drawer) self.settings['circuit_drawer'] = circuit_drawer def get_config(): """Read the config file from the default location or env var It will read a config file at either the default location ~/.qiskit/settings.conf or if set the value of the QISKIT_SETTINGS env var. It will return the parsed settings dict from the parsed config file. Returns: dict: The settings dict from the parsed config file. """ filename = os.getenv('QISKIT_SETTINGS', DEFAULT_FILENAME) if not os.path.isfile(filename): return {} user_config = UserConfig(filename) user_config.read_config_file() return user_config.settings
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 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Simulator command to snapshot internal simulator representation. """ import warnings from qiskit import QuantumCircuit from qiskit.circuit import CompositeGate from qiskit import QuantumRegister from qiskit.circuit import Instruction from qiskit.extensions.exceptions import ExtensionError class Snapshot(Instruction): """Simulator snapshot instruction.""" def __init__(self, label, snapshot_type='statevector', num_qubits=0, num_clbits=0, params=None): """Create new snapshot instruction. Args: label (str): the snapshot label for result data. snapshot_type (str): the type of the snapshot. num_qubits (int): the number of qubits for the snapshot type [Default: 0]. num_clbits (int): the number of classical bits for the snapshot type [Default: 0]. params (list or None): the parameters for snapshot_type [Default: None]. Raises: ExtensionError: if snapshot label is invalid. """ if not isinstance(label, str): raise ExtensionError('Snapshot label must be a string.') self._label = label self._snapshot_type = snapshot_type if params is None: params = [] super().__init__('snapshot', num_qubits, num_clbits, params) def assemble(self): """Assemble a QasmQobjInstruction""" instruction = super().assemble() instruction.label = self._label instruction.snapshot_type = self._snapshot_type return instruction def inverse(self): """Special case. Return self.""" return Snapshot(self.num_qubits, self.num_clbits, self.params[0], self.params[1]) @property def snapshot_type(self): """Return snapshot type""" return self._snapshot_type @property def label(self): """Return snapshot label""" return self._label @label.setter def label(self, name): """Set snapshot label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None. """ if isinstance(name, str): self._label = name else: raise TypeError('label expects a string') def snapshot(self, label, snapshot_type='statevector', qubits=None, params=None): """Take a statevector snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). For other types of snapshots use the Snapshot extension directly. Args: label (str): a snapshot label to report the result snapshot_type (str): the type of the snapshot. qubits (list or None): the qubits to apply snapshot to [Default: None]. params (list or None): the parameters for snapshot_type [Default: None]. Returns: QuantumCircuit: with attached command Raises: ExtensionError: malformed command """ # Convert label to string for backwards compatibility if not isinstance(label, str): warnings.warn( "Snapshot label should be a string, " "implicit conversion is depreciated.", DeprecationWarning) label = str(label) # If no qubits are specified we add all qubits so it acts as a barrier # This is needed for full register snapshots like statevector if isinstance(qubits, QuantumRegister): qubits = qubits[:] if not qubits: tuples = [] if isinstance(self, QuantumCircuit): for register in self.qregs: tuples.append(register) if not tuples: raise ExtensionError('no qubits for snapshot') qubits = [] for tuple_element in tuples: if isinstance(tuple_element, QuantumRegister): for j in range(tuple_element.size): qubits.append((tuple_element, j)) else: qubits.append(tuple_element) return self.append( Snapshot( label, snapshot_type=snapshot_type, num_qubits=len(qubits), params=params), qubits) # Add to QuantumCircuit and CompositeGate classes QuantumCircuit.snapshot = snapshot CompositeGate.snapshot = snapshot
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # 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. """Decorator for using with Qiskit unit tests.""" import functools import os import sys import unittest from .utils import Path from .http_recorder import http_recorder from .testing_options import get_test_options def is_aer_provider_available(): """Check if the C++ simulator can be instantiated. Returns: bool: True if simulator executable is available """ # TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC if sys.platform == 'darwin': return False try: import qiskit.providers.aer # pylint: disable=unused-import except ImportError: return False return True def requires_aer_provider(test_item): """Decorator that skips test if qiskit aer provider is not available Args: test_item (callable): function or class to be decorated. Returns: callable: the decorated function. """ reason = 'Aer provider not found, skipping test' return unittest.skipIf(not is_aer_provider_available(), reason)(test_item) def slow_test(func): """Decorator that signals that the test takes minutes to run. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(*args, **kwargs): skip_slow = not TEST_OPTIONS['run_slow'] if skip_slow: raise unittest.SkipTest('Skipping slow tests') return func(*args, **kwargs) return _wrapper def _get_credentials(test_object, test_options): """Finds the credentials for a specific test and options. Args: test_object (QiskitTestCase): The test object asking for credentials test_options (dict): Options after QISKIT_TESTS was parsed by get_test_options. Returns: Credentials: set of credentials Raises: ImportError: if the Exception: when the credential could not be set and they are needed for that set of options """ try: from qiskit.providers.ibmq.credentials import (Credentials, discover_credentials) except ImportError: raise ImportError('qiskit-ibmq-provider could not be found, and is ' 'required for mocking or executing online tests.') dummy_credentials = Credentials( 'dummyapiusersloginWithTokenid01', 'https://quantumexperience.ng.bluemix.net/api') if test_options['mock_online']: return dummy_credentials if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''): # Special case: instead of using the standard credentials mechanism, # load them from different environment variables. This assumes they # will always be in place, as is used by the Travis setup. return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL')) else: # Attempt to read the standard credentials. discovered_credentials = discover_credentials() if discovered_credentials: # Decide which credentials to use for testing. if len(discovered_credentials) > 1: try: # Attempt to use QE credentials. return discovered_credentials[dummy_credentials.unique_id()] except KeyError: pass # Use the first available credentials. return list(discovered_credentials.values())[0] # No user credentials were found. if test_options['rec']: raise Exception('Could not locate valid credentials. You need them for ' 'recording tests against the remote API.') test_object.log.warning('No user credentials were detected. ' 'Running with mocked data.') test_options['mock_online'] = True return dummy_credentials def requires_qe_access(func): """Decorator that signals that the test uses the online API: It involves: * determines if the test should be skipped by checking environment variables. * if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is set, it reads the credentials from an alternative set of environment variables. * if the test is not skipped, it reads `qe_token` and `qe_url` from `Qconfig.py`, environment variables or qiskitrc. * if the test is not skipped, it appends `qe_token` and `qe_url` as arguments to the test function. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs): if TEST_OPTIONS['skip_online']: raise unittest.SkipTest('Skipping online tests') credentials = _get_credentials(self, TEST_OPTIONS) self.using_ibmq_credentials = credentials.is_ibmq() kwargs.update({'qe_token': credentials.token, 'qe_url': credentials.url}) decorated_func = func if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']: # For recording or for replaying existing cassettes, the test # should be decorated with @use_cassette. vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none' decorated_func = http_recorder( vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func) return decorated_func(self, *args, **kwargs) return _wrapper TEST_OPTIONS = get_test_options()
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 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. """Decorator for using with Qiskit unit tests.""" import functools import os import sys import unittest from .utils import Path from .http_recorder import http_recorder from .testing_options import get_test_options def is_aer_provider_available(): """Check if the C++ simulator can be instantiated. Returns: bool: True if simulator executable is available """ # TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC if sys.platform == 'darwin': return False try: import qiskit.providers.aer # pylint: disable=unused-import except ImportError: return False return True def requires_aer_provider(test_item): """Decorator that skips test if qiskit aer provider is not available Args: test_item (callable): function or class to be decorated. Returns: callable: the decorated function. """ reason = 'Aer provider not found, skipping test' return unittest.skipIf(not is_aer_provider_available(), reason)(test_item) def slow_test(func): """Decorator that signals that the test takes minutes to run. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(*args, **kwargs): skip_slow = not TEST_OPTIONS['run_slow'] if skip_slow: raise unittest.SkipTest('Skipping slow tests') return func(*args, **kwargs) return _wrapper def _get_credentials(test_object, test_options): """Finds the credentials for a specific test and options. Args: test_object (QiskitTestCase): The test object asking for credentials test_options (dict): Options after QISKIT_TESTS was parsed by get_test_options. Returns: Credentials: set of credentials Raises: ImportError: if the Exception: when the credential could not be set and they are needed for that set of options """ try: from qiskit.providers.ibmq.credentials import (Credentials, discover_credentials) except ImportError: raise ImportError('qiskit-ibmq-provider could not be found, and is ' 'required for mocking or executing online tests.') dummy_credentials = Credentials( 'dummyapiusersloginWithTokenid01', 'https://quantumexperience.ng.bluemix.net/api') if test_options['mock_online']: return dummy_credentials if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''): # Special case: instead of using the standard credentials mechanism, # load them from different environment variables. This assumes they # will always be in place, as is used by the Travis setup. return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL')) else: # Attempt to read the standard credentials. discovered_credentials = discover_credentials() if discovered_credentials: # Decide which credentials to use for testing. if len(discovered_credentials) > 1: try: # Attempt to use QE credentials. return discovered_credentials[dummy_credentials.unique_id()] except KeyError: pass # Use the first available credentials. return list(discovered_credentials.values())[0] # No user credentials were found. if test_options['rec']: raise Exception('Could not locate valid credentials. You need them for ' 'recording tests against the remote API.') test_object.log.warning('No user credentials were detected. ' 'Running with mocked data.') test_options['mock_online'] = True return dummy_credentials def requires_qe_access(func): """Decorator that signals that the test uses the online API: It involves: * determines if the test should be skipped by checking environment variables. * if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is set, it reads the credentials from an alternative set of environment variables. * if the test is not skipped, it reads `qe_token` and `qe_url` from `Qconfig.py`, environment variables or qiskitrc. * if the test is not skipped, it appends `qe_token` and `qe_url` as arguments to the test function. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs): if TEST_OPTIONS['skip_online']: raise unittest.SkipTest('Skipping online tests') credentials = _get_credentials(self, TEST_OPTIONS) self.using_ibmq_credentials = credentials.is_ibmq() kwargs.update({'qe_token': credentials.token, 'qe_url': credentials.url}) decorated_func = func if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']: # For recording or for replaying existing cassettes, the test # should be decorated with @use_cassette. vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none' decorated_func = http_recorder( vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func) return decorated_func(self, *args, **kwargs) return _wrapper TEST_OPTIONS = get_test_options()
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 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. """Utils for using with Qiskit unit tests.""" import logging import os import unittest from enum import Enum from qiskit import __path__ as qiskit_path class Path(Enum): """Helper with paths commonly used during the tests.""" # Main SDK path: qiskit/ SDK = qiskit_path[0] # test.python path: qiskit/test/python/ TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python')) # Examples path: examples/ EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples')) # Schemas path: qiskit/schemas SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas')) # VCR cassettes path: qiskit/test/cassettes/ CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes')) # Sample QASMs path: qiskit/test/python/qasm QASMS = os.path.normpath(os.path.join(TEST, 'qasm')) def setup_test_logging(logger, log_level, filename): """Set logging to file and stdout for a logger. Args: logger (Logger): logger object to be updated. log_level (str): logging level. filename (str): name of the output file. """ # Set up formatter. log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:' ' %(message)s'.format(logger.name)) formatter = logging.Formatter(log_fmt) # Set up the file handler. file_handler = logging.FileHandler(filename) file_handler.setFormatter(formatter) logger.addHandler(file_handler) # Set the logging level from the environment variable, defaulting # to INFO if it is not a valid level. level = logging._nameToLevel.get(log_level, logging.INFO) logger.setLevel(level) class _AssertNoLogsContext(unittest.case._AssertLogsContext): """A context manager used to implement TestCase.assertNoLogs().""" # pylint: disable=inconsistent-return-statements def __exit__(self, exc_type, exc_value, tb): """ This is a modified version of TestCase._AssertLogsContext.__exit__(...) """ self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if exc_type is not None: # let unexpected exceptions pass through return False if self.watcher.records: msg = 'logs of level {} or higher triggered on {}:\n'.format( logging.getLevelName(self.level), self.logger.name) for record in self.watcher.records: msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname, record.lineno, record.getMessage()) self._raiseFailure(msg)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
from qiskit import Aer, IBMQ, execute from qiskit import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram, plot_state_city """ Qiskit backends to execute the quantum circuit """ def simulator(qc): """ Run on local simulator :param qc: quantum circuit :return: """ backend = Aer.get_backend("qasm_simulator") shots = 2048 tqc = transpile(qc, backend) qobj = assemble(tqc, shots=shots) job_sim = backend.run(qobj) qc_results = job_sim.result() return qc_results, shots def simulator_state_vector(qc): """ Select the StatevectorSimulator from the Aer provider :param qc: quantum circuit :return: statevector """ simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qc, simulator).result() state_vector = result.get_statevector(qc) return state_vector def real_quantum_device(qc): """ Use the IBMQ essex device :param qc: quantum circuit :return: """ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_santiago') shots = 2048 TQC = transpile(qc, backend) qobj = assemble(TQC, shots=shots) job_exp = backend.run(qobj) job_monitor(job_exp) QC_results = job_exp.result() return QC_results, shots def counts(qc_results): """ Get counts representing the wave-function amplitudes :param qc_results: :return: dict keys are bit_strings and their counting values """ return qc_results.get_counts() def plot_results(qc_results): """ Visualizing wave-function amplitudes in a histogram :param qc_results: quantum circuit :return: """ plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False)) def plot_state_vector(state_vector): """Visualizing state vector in the density matrix representation""" plt.show(plot_state_city(state_vector))
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A module of magic functions""" import time import threading from IPython.display import display # pylint: disable=import-error from IPython.core import magic_arguments # pylint: disable=import-error from IPython.core.magic import cell_magic, Magics, magics_class # pylint: disable=import-error try: import ipywidgets as widgets # pylint: disable=import-error except ImportError: raise ImportError('These functions need ipywidgets. ' 'Run "pip install ipywidgets" before.') import qiskit from qiskit.tools.events.progressbar import TextProgressBar from .progressbar import HTMLProgressBar def _html_checker(job_var, interval, status, header, _interval_set=False): """Internal function that updates the status of a HTML job monitor. Args: job_var (BaseJob): The job to keep track of. interval (int): The status check interval status (widget): HTML ipywidget for output ot screen header (str): String representing HTML code for status. _interval_set (bool): Was interval set by user? """ job_status = job_var.status() job_status_name = job_status.name job_status_msg = job_status.value status.value = header % (job_status_msg) while job_status_name not in ['DONE', 'CANCELLED']: time.sleep(interval) job_status = job_var.status() job_status_name = job_status.name job_status_msg = job_status.value if job_status_name == 'ERROR': break else: if job_status_name == 'QUEUED': job_status_msg += ' (%s)' % job_var.queue_position() if not _interval_set: interval = max(job_var.queue_position(), 2) else: if not _interval_set: interval = 2 status.value = header % (job_status_msg) status.value = header % (job_status_msg) @magics_class class StatusMagic(Magics): """A class of status magic functions. """ @cell_magic @magic_arguments.magic_arguments() @magic_arguments.argument( '-i', '--interval', type=float, default=None, help='Interval for status check.' ) def qiskit_job_status(self, line='', cell=None): """A Jupyter magic function to check the status of a Qiskit job instance. """ args = magic_arguments.parse_argstring(self.qiskit_job_status, line) if args.interval is None: args.interval = 2 _interval_set = False else: _interval_set = True # Split cell lines to get LHS variables cell_lines = cell.split('\n') line_vars = [] for cline in cell_lines: if '=' in cline and '==' not in cline: line_vars.append(cline.replace(' ', '').split('=')[0]) elif '.append(' in cline: line_vars.append(cline.replace(' ', '').split('(')[0]) # Execute the cell self.shell.ex(cell) # Look for all vars that are BaseJob instances jobs = [] for var in line_vars: iter_var = False if '#' not in var: # The line var is a list or array, but we cannot parse the index # so just iterate over the whole array for jobs. if '[' in var: var = var.split('[')[0] iter_var = True elif '.append' in var: var = var.split('.append')[0] iter_var = True if iter_var: for item in self.shell.user_ns[var]: if isinstance(item, qiskit.providers.basejob.BaseJob): jobs.append(item) else: if isinstance(self.shell.user_ns[var], qiskit.providers.basejob.BaseJob): jobs.append(self.shell.user_ns[var]) # Must have one job class if not any(jobs): raise Exception( "Cell must contain at least one variable of BaseJob type.") # List index of job if checking status of multiple jobs. multi_job = False if len(jobs) > 1: multi_job = True job_checkers = [] # Loop over every BaseJob that was found. for idx, job_var in enumerate(jobs): style = "font-size:16px;" if multi_job: idx_str = '[%s]' % idx else: idx_str = '' header = "<p style='{style}'>Job Status {id}: %s </p>".format(id=idx_str, style=style) status = widgets.HTML( value=header % job_var.status().value) thread = threading.Thread(target=_html_checker, args=(job_var, args.interval, status, header, _interval_set)) thread.start() job_checkers.append(status) # Group all HTML widgets into single vertical layout box = widgets.VBox(job_checkers) display(box) @magics_class class ProgressBarMagic(Magics): """A class of progress bar magic functions. """ @cell_magic @magic_arguments.magic_arguments() @magic_arguments.argument( '-t', '--type', type=str, default='html', help="Type of progress bar, 'html' or 'text'." ) def qiskit_progress_bar(self, line='', cell=None): # pylint: disable=W0613 """A Jupyter magic function to generate progressbar. """ args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line) if args.type == 'html': HTMLProgressBar() elif args.type == 'text': TextProgressBar() else: raise qiskit.QiskitError('Invalid progress bar type.') self.shell.ex(cell)
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 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. # TODO: Remove after 0.7 and the deprecated methods are removed # pylint: disable=unused-argument """ Two quantum circuit drawers based on: 0. Ascii art 1. LaTeX 2. Matplotlib """ import errno import logging import os import subprocess import tempfile from PIL import Image from qiskit import user_config from qiskit.visualization import exceptions from qiskit.visualization import latex as _latex from qiskit.visualization import text as _text from qiskit.visualization import utils from qiskit.visualization import matplotlib as _matplotlib logger = logging.getLogger(__name__) def circuit_drawer(circuit, scale=0.7, filename=None, style=None, output=None, interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit to different formats (set by output parameter): 0. text: ASCII art TextDrawing that can be printed in the console. 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Args: circuit (QuantumCircuit): the quantum circuit to draw scale (float): scale of image to draw (shrink if < 1) filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file. This option is only used by the `mpl`, `latex`, and `latex_source` output types. If a str is passed in that is the path to a json file which contains that will be open, parsed, and then used just as the input dict. output (str): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. By default the 'text' drawer is used unless a user config file has an alternative backend set as the default. If the output is passed in that backend will always be used. interactive (bool): when set true show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. line_length (int): Sets the length of the lines generated by `text` output type. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). However, if you're running in jupyter the default line length is set to 80 characters. If you don't want pagination at all, set `line_length=-1`. reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): Options are `left`, `right` or `none`, if anything else is supplied it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. `none` results in each gate being placed in its own column. Currently only supported by text drawer. Returns: PIL.Image: (output `latex`) an in-memory representation of the image of the circuit diagram. matplotlib.figure: (output `mpl`) a matplotlib figure object for the circuit diagram. String: (output `latex_source`). The LaTeX source code. TextDrawing: (output `text`). A drawing that can be printed as ascii art Raises: VisualizationError: when an invalid output method is selected ImportError: when the output methods requieres non-installed libraries. .. _style-dict-doc: The style dict kwarg contains numerous options that define the style of the output circuit visualization. While the style dict is used by the `mpl`, `latex`, and `latex_source` outputs some options in that are only used by the `mpl` output. These options are defined below, if it is only used by the `mpl` output it is marked as such: textcolor (str): The color code to use for text. Defaults to `'#000000'` (`mpl` only) subtextcolor (str): The color code to use for subtext. Defaults to `'#000000'` (`mpl` only) linecolor (str): The color code to use for lines. Defaults to `'#000000'` (`mpl` only) creglinecolor (str): The color code to use for classical register lines `'#778899'`(`mpl` only) gatetextcolor (str): The color code to use for gate text `'#000000'` (`mpl` only) gatefacecolor (str): The color code to use for gates. Defaults to `'#ffffff'` (`mpl` only) barrierfacecolor (str): The color code to use for barriers. Defaults to `'#bdbdbd'` (`mpl` only) backgroundcolor (str): The color code to use for the background. Defaults to `'#ffffff'` (`mpl` only) fontsize (int): The font size to use for text. Defaults to 13 (`mpl` only) subfontsize (int): The font size to use for subtext. Defaults to 8 (`mpl` only) displaytext (dict): A dictionary of the text to use for each element type in the output visualization. The default values are: { 'id': 'id', 'u0': 'U_0', 'u1': 'U_1', 'u2': 'U_2', 'u3': 'U_3', 'x': 'X', 'y': 'Y', 'z': 'Z', 'h': 'H', 's': 'S', 'sdg': 'S^\\dagger', 't': 'T', 'tdg': 'T^\\dagger', 'rx': 'R_x', 'ry': 'R_y', 'rz': 'R_z', 'reset': '\\left|0\\right\\rangle' } You must specify all the necessary values if using this. There is no provision for passing an incomplete dict in. (`mpl` only) displaycolor (dict): The color codes to use for each circuit element. By default all values default to the value of `gatefacecolor` and the keys are the same as `displaytext`. Also, just like `displaytext` there is no provision for an incomplete dict passed in. (`mpl` only) latexdrawerstyle (bool): When set to True enable latex mode which will draw gates like the `latex` output modes. (`mpl` only) usepiformat (bool): When set to True use radians for output (`mpl` only) fold (int): The number of circuit elements to fold the circuit at. Defaults to 20 (`mpl` only) cregbundle (bool): If set True bundle classical registers (`mpl` only) showindex (bool): If set True draw an index. (`mpl` only) compress (bool): If set True draw a compressed circuit (`mpl` only) figwidth (int): The maximum width (in inches) for the output figure. (`mpl` only) dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl` only) margin (list): `mpl` only creglinestyle (str): The style of line to use for classical registers. Choices are `'solid'`, `'doublet'`, or any valid matplotlib `linestyle` kwarg value. Defaults to `doublet`(`mpl` only) """ image = None config = user_config.get_config() # Get default from config file else use text default_output = 'text' if config: default_output = config.get('circuit_drawer', 'text') if output is None: output = default_output if output == 'text': return _text_circuit_drawer(circuit, filename=filename, line_length=line_length, reverse_bits=reverse_bits, plotbarriers=plot_barriers, justify=justify) elif output == 'latex': image = _latex_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'latex_source': return _generate_latex_source(circuit, filename=filename, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'mpl': image = _matplotlib_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) else: raise exceptions.VisualizationError( 'Invalid output type %s selected. The only valid choices ' 'are latex, latex_source, text, and mpl' % output) if image and interactive: image.show() return image # ----------------------------------------------------------------------------- # Plot style sheet option # ----------------------------------------------------------------------------- def qx_color_scheme(): """Return default style for matplotlib_circuit_drawer (IBM QX style).""" return { "comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)", "textcolor": "#000000", "gatetextcolor": "#000000", "subtextcolor": "#000000", "linecolor": "#000000", "creglinecolor": "#b9b9b9", "gatefacecolor": "#ffffff", "barrierfacecolor": "#bdbdbd", "backgroundcolor": "#ffffff", "fold": 20, "fontsize": 13, "subfontsize": 8, "figwidth": -1, "dpi": 150, "displaytext": { "id": "id", "u0": "U_0", "u1": "U_1", "u2": "U_2", "u3": "U_3", "x": "X", "y": "Y", "z": "Z", "h": "H", "s": "S", "sdg": "S^\\dagger", "t": "T", "tdg": "T^\\dagger", "rx": "R_x", "ry": "R_y", "rz": "R_z", "reset": "\\left|0\\right\\rangle" }, "displaycolor": { "id": "#ffca64", "u0": "#f69458", "u1": "#f69458", "u2": "#f69458", "u3": "#f69458", "x": "#a6ce38", "y": "#a6ce38", "z": "#a6ce38", "h": "#00bff2", "s": "#00bff2", "sdg": "#00bff2", "t": "#ff6666", "tdg": "#ff6666", "rx": "#ffca64", "ry": "#ffca64", "rz": "#ffca64", "reset": "#d7ddda", "target": "#00bff2", "meas": "#f070aa" }, "latexdrawerstyle": True, "usepiformat": False, "cregbundle": False, "plotbarrier": False, "showindex": False, "compress": True, "margin": [2.0, 0.0, 0.0, 0.3], "creglinestyle": "solid", "reversebits": False } # ----------------------------------------------------------------------------- # _text_circuit_drawer # ----------------------------------------------------------------------------- def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False, plotbarriers=True, justify=None, vertically_compressed=True): """ Draws a circuit using ascii art. Args: circuit (QuantumCircuit): Input circuit filename (str): optional filename to write the result line_length (int): Optional. Breaks the circuit drawing to this length. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). If you don't want pagination at all, set line_length=-1. reverse_bits (bool): Rearrange the bits in reverse order. plotbarriers (bool): Draws the barriers when they are there. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. vertically_compressed (bool): Default is `True`. It merges the lines so the drawing will take less vertical room. Returns: TextDrawing: An instances that, when printed, draws the circuit in ascii art. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) text_drawing = _text.TextDrawing(qregs, cregs, ops) text_drawing.plotbarriers = plotbarriers text_drawing.line_length = line_length text_drawing.vertically_compressed = vertically_compressed if filename: text_drawing.dump(filename) return text_drawing # ----------------------------------------------------------------------------- # latex_circuit_drawer # ----------------------------------------------------------------------------- def _latex_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on latex (Qcircuit package) Requires version >=2.6.0 of the qcircuit LaTeX package. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: PIL.Image: an in-memory representation of the circuit diagram Raises: OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is missing. CalledProcessError: usually points errors during diagram creation. """ tmpfilename = 'circuit' with tempfile.TemporaryDirectory() as tmpdirname: tmppath = os.path.join(tmpdirname, tmpfilename + '.tex') _generate_latex_source(circuit, filename=tmppath, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) image = None try: subprocess.run(["pdflatex", "-halt-on-error", "-output-directory={}".format(tmpdirname), "{}".format(tmpfilename + '.tex')], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True) except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to compile latex. ' 'Is `pdflatex` installed? ' 'Skipping latex circuit drawing...') raise except subprocess.CalledProcessError as ex: with open('latex_error.log', 'wb') as error_file: error_file.write(ex.stdout) logger.warning('WARNING Unable to compile latex. ' 'The output from the pdflatex command can ' 'be found in latex_error.log') raise else: try: base = os.path.join(tmpdirname, tmpfilename) subprocess.run(["pdftocairo", "-singlefile", "-png", "-q", base + '.pdf', base]) image = Image.open(base + '.png') image = utils._trim(image) os.remove(base + '.png') if filename: image.save(filename, 'PNG') except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to convert pdf to image. ' 'Is `poppler` installed? ' 'Skipping circuit drawing...') raise return image def _generate_latex_source(circuit, filename=None, scale=0.7, style=None, reverse_bits=False, plot_barriers=True, justify=None): """Convert QuantumCircuit to LaTeX string. Args: circuit (QuantumCircuit): input circuit scale (float): image scaling filename (str): optional filename to write latex style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: str: Latex string appropriate for writing to file. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) latex = qcimg.latex() if filename: with open(filename, 'w') as latex_file: latex_file.write(latex) return latex # ----------------------------------------------------------------------------- # matplotlib_circuit_drawer # ----------------------------------------------------------------------------- def _matplotlib_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on matplotlib. If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline. We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: matplotlib.figure: a matplotlib figure object for the circuit diagram """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) return qcd.draw(filename)
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
3