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 __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)
예제 #3
0
    a_beta = np.arange(0, np.pi, step_size)
    a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)

    F1 = 3 - (np.sin(2 * a_beta)**2 * np.sin(2 * a_gamma)**2 - 0.5 * np.sin(
        4 * a_beta) * np.sin(4 * a_gamma)) * (1 + np.cos(4 * a_gamma)**2)

    result = np.where(F1 == np.amax(F1))
    a = list(zip(result[0], result[1]))[0]

    gamma = a[0] * step_size
    beta = a[1] * step_size

    prog = make_circuit(4)
    sample_shot = 3962
    writefile = open("../data/startQiskit99.csv", "w")
    # prog.draw('mpl', filename=(kernel + '.png'))
    backend = BasicAer.get_backend('qasm_simulator')

    circuit1 = transpile(prog, FakeYorktown())
    circuit1.measure_all()
    prog = circuit1

    info = execute(prog, backend=backend,
                   shots=sample_shot).result().get_counts()

    print(info, file=writefile)
    print("results end", file=writefile)
    print(circuit1.depth(), file=writefile)
    print(circuit1, file=writefile)
    writefile.close()
예제 #4
0
파일: qapprox.py 프로젝트: qMSUZ/QCS
#! /usr/bin/python3

import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import BasicAer
from qiskit import IBMQ

# access to IBM Account
#IBMQ.save_account('MY_TOKEN')
#IBMQ.load_accounts()

backend = BasicAer.get_backend('statevector_simulator')
#backend = BasicAer.get_backend('unitary_simulator')
#backend = BasicAer.get_backend('qasm_simulator')

def qc_approx_sim(x, t1, t2):
    theta1 = x - t1;
    theta2 = x - t2;

    q = QuantumRegister(2, 'q')
    c = ClassicalRegister(2, 'c')
    qc = QuantumCircuit(q, c)

    qc.h( q[0] )
    qc.h( q[1] )

    qc.u3(t1, 0.0, 0.0, q[0]);
    qc.u3(t2, 0.0, 0.0, q[1]);

    qc.barrier( q )
예제 #5
0
 def qasm(shots=100):
     return QuantumInstance(
         backend=BasicAer.get_backend('qasm_simulator'),
         shots=shots,
         seed_simulator=2,
         seed_transpiler=2)
예제 #6
0
    a_gamma = np.arange(0, np.pi, step_size)
    a_beta = np.arange(0, np.pi, step_size)
    a_gamma, a_beta = np.meshgrid(a_gamma, a_beta)

    F1 = 3 - (np.sin(2 * a_beta)**2 * np.sin(2 * a_gamma)**2 - 0.5 * np.sin(
        4 * a_beta) * np.sin(4 * a_gamma)) * (1 + np.cos(4 * a_gamma)**2)

    result = np.where(F1 == np.amax(F1))
    a = list(zip(result[0], result[1]))[0]

    gamma = a[0] * step_size
    beta = a[1] * step_size

    prog = make_circuit(4)
    sample_shot = 5600
    writefile = open("../data/startQiskit_Class96.csv", "w")
    # prog.draw('mpl', filename=(kernel + '.png'))
    backend = BasicAer.get_backend('statevector_simulator')

    circuit1 = transpile(prog, FakeYorktown())
    prog = circuit1

    info = execute(prog, backend=backend,
                   shots=sample_shot).result().get_counts()

    print(info, file=writefile)
    print("results end", file=writefile)
    print(circuit1.depth(), file=writefile)
    print(circuit1, file=writefile)
    writefile.close()
 def eval_op(op):
     from qiskit import execute
     backend = BasicAer.get_backend('qasm_simulator')
     evaluation_circuits = op.construct_evaluation_circuit(qc, False)
     job = execute(evaluation_circuits, backend, shots=1024)
     return op.evaluate_with_result(job.result(), False)
    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.")
예제 #9
0
c.u1(pi/4,qr[2])
c.cu3(0,pi/2,0,qr[2],qr[1])
c.h(qr[2])
c.swap(qr[1],qr[2])
c.cu3(2*pi,0,0,qr[1],qr[3])
c.cu3(pi,-pi,0,qr[2],qr[3])
c.h(qr[1])
c.h(qr[2])

#c.x(qr[0])
#c.measure(qr[0],cr[0])
#c.reset(qr[0])

c.draw(filename='./Resources/Circuit.pdf', output='mpl')

Usim = BAer.get_backend('statevector_simulator')
job = exe(c, Usim)
X = job.result().get_statevector(c)
print(X)

#|1><1| projective measurement only half down indices remains.
#(original order & index start from 1)

x = np.array([X[2-1],X[10-1]])
x = x / LA.norm(x)
print("simulation answer: ", x)
print("true answer: ",  [0.2425,-0.9701])

#backend = BAer.get_backend('qasm_simulator')
#job = exe(c, backend, shots=1024)
#job.result().get_counts(c)
예제 #10
0
if __name__ == '__main__':
    from jupyterthemes import jtplot

    jtplot.style(theme='monokai', context='notebook', ticks=True, grid=False)

    from qiskit.tools.jupyter import *
    from qiskit import IBMQ

    IBMQ.load_account()
    # provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
    provider = IBMQ.get_provider(hub='ibm-q-oxford',
                                 group='on-boarding',
                                 project='on-boarding-proj')
    from qiskit import BasicAer
    backend = BasicAer.get_backend('unitary_simulator')

    a0 = 0.2
    a1 = 0.8
    b0 = 0.3
    b1 = 0.7
    c000 = 0.15
    c001 = 0.3
    c010 = 0.4
    c011 = 0.1
    c100 = 0.85
    c101 = 0.7
    c110 = 0.6
    c111 = 0.9

    parents = np.array([a0, a1, b0, b1])
예제 #11
0
    '897bcc7b8ed8bb1ab9783d9e57d4d5551741efac0deb606de146c28afabec10853c751104509a8856afbd58a2052ac034ef72baddc8a3b127b71e2ac80b751f3',
    overwrite=True)

# Create a Quantum Circuit
qc = QuantumCircuit(2, 2)

# Add a H gate on qubit 0, putting this qubit in superposition.
qc.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
qc.cx(0, 1)
# Add a Measure gate to see the state.
qc.measure([0, 1], [0, 1])

# See a list of available local simulators
print("BasicAer backends: ", BasicAer.backends())
backend_sim = BasicAer.get_backend('qasm_simulator')

# Compile and run the Quantum circuit on a simulator backend
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()

# Show the results
print(result_sim.get_counts(qc))

# Authenticate for access to remote backends
try:
    provider = IBMQ.load_account()
except:
    print("""WARNING: No valid IBMQ credentials found on disk.
             You must store your credentials using IBMQ.save_account(token, url).