def ask_for_device ():
    
    d = input("Do you want to play on the real device? (y/n)\n").upper()
    if (d=="Y"):
        device = IBMQ.get_backend('ibmq_5_tenerife') # if real, we use ibmqx4
    else:
        device = Aer.get_backend('qasm_simulator') # otherwise, we use a simulator
        
    return device
 def compute_winner(self):
     """Find overall game winner, by finding winners of each outcome"""
     self.c.size = self.q.size #Make them the same
     self.qc.measure(self.q, self.c) #Measure
     backend = Aer.get_backend('qasm_simulator')
     job_sim = execute(self.qc, backend=backend, shots=100)
     sim_result = job_sim.result()
     print("simulation: ", sim_result)
     print(sim_result.get_counts(self.qc))
     self.counts = sim_result.get_counts(self.qc)
     for count in self.counts: #Takes key names
         c = list(count)[:-1] #splits key '1011' => ['1','0','1','1']
         c = c[::-1] #invert it so it goes 0 up...
         #Ignore the last bit since I dont know how to get rid of it
         #It is zero always.
         #The reason it is included is that I create a quantum register and
         #then start adding operations, quantum registers need at least one bit.
         counter = 0
         weight = self.counts[count]
         empty = np.zeros((self.x,self.y),dtype=str)
         for m in self.moves:
             if m.player == 0:
                 char = 'x'
             elif m.player==1:
                 char = 'o'
             result = []
             if m.q1:
                 result.append(c[counter])
                 counter+=1
             if m.q2:
                 result.append(c[counter])
                 counter+=1
             #print(result)
             if len(result) == len(m.indices):
                 #print(m)
                 if result[0]=='1':
                     empty[m.indices[0][0],m.indices[0][1]] = char
                 if len(result)>1:
                     if result[1]=='1':
                         if result[0]=='1':
                             print('problem! a move appeard in two places.')
                             print(m)
                         empty[m.indices[1][0],m.indices[1][1]] = char
             elif not result: #Then it was a classcal move
                 empty[m.indices[0][0],m.indices[0][1]] = char
         xscore,oscore=self.winners(empty)
         print('X wins: '+str(xscore))
         print('O wins: '+str(oscore))
         print('Shots: '+str(weight))
         print(empty)
def evaluate_circuit(gamma_beta, qr, p):
    n = len(gamma_beta)//2
    circuit = create_circuit(qr, gamma_beta[:n], gamma_beta[n:], p)
    return np.real(Hc.eval("matrix", circuit, Aer.get_backend('statevector_simulator'))[0])
# -*- coding: utf-8 -*-
"""
Created on Mon May 20 21:07:00 2019

@author: hnorlen
"""

from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram

from IPython.core.display import display

print("Ch 5: Upside down quantum coin toss")
print("-----------------------------------")

qc = QuantumCircuit(1, 1)
initial_vector = [0. + 0.j, 1. + 0.j]
qc.initialize(initial_vector, 0)

#qc.x(0)
qc.h(0)
qc.measure(0, 0)

print(qc)
#display(qc.draw())

backend = Aer.get_backend('qasm_simulator')

counts = execute(qc, backend, shots=1).result().get_counts(qc)

display(plot_histogram(counts))
from qiskit.transpiler import passes
from qiskit.test.mock import FakeMelbourne
from qiskit.transpiler.passes import CrosstalkAdaptiveSchedule
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.transpiler import Layout
from z3 import Real, Bool, Sum, Implies, And, Or, Not, Optimize
import logging
from numpy import pi
# with open(sys.argv[1],'r') as f:
#     contents = f.read()
f= sys.argv[1]
print(f)
#quit()
backend = FakeMelbourne()
#print(Aer.backends())
backend2 = Aer.get_backend('statevector_simulator')
#quit()
qreg_q = QuantumRegister(14, 'q')
crosstalk_prop={}
crosstalk_prop[(0,1)]={(2,3):0.9}
crosstalk_prop[(2,3)]={(0,1):0.9}
#crosstalk_prop[(5,6)]={(8,9):0.2}
crosstalk_prop[(8,9)]={(10,11):0.9}
crosstalk_prop[(10,11)]={(8,9):0.9}
circuit = QuantumCircuit(14, 14)
#circuit = QuantumCircuit.from_qasm_file('')
circuit = QuantumCircuit.from_qasm_file(f'/Users/feihua/pythonfile/516projectcode/circuits/large/{f}') 
# circuit.x(qreg_q[0])
# circuit.x(qreg_q[2])
# circuit.h(qreg_q[0])
# circuit.cu1(pi/2, qreg_q[1], qreg_q[0])
Example #6
0
def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps):
    #Check for correct data types of input
    if not isinstance(nsites, int):
        raise TypeError("Number of sites should be int")
    if np.isscalar(excitations):
        raise TypeError("Initial state should be list or numpy array")
    if not np.isscalar(total_time):
        raise TypeError("Evolution time should be scalar")
    if not np.isscalar(dt):
        raise TypeError("Time step should be scalar")
    if not isinstance(trotter_steps, int):
        raise TypeError("Number of trotter slices should be int")

    numq = 2 * nsites
    num_steps = int(total_time / dt)
    print('Num Steps: ', num_steps)
    print('Total Time: ', total_time)
    data = np.zeros((2**numq, num_steps))

    for t_step in range(0, num_steps):
        #Create circuit with t_step number of steps
        q = QuantumRegister(numq)
        c = ClassicalRegister(numq)
        qcirc = QuantumCircuit(q, c)

        #=========USE THIS REGION TO SET YOUR INITIAL STATE==============
        #Loop over each excitation
        for flip in excitations:
            qcirc.x(flip)
#            qcirc.z(flip)
#===============================================================

        qcirc.barrier()
        #Append circuit with Trotter steps needed
        qc_evolve(qcirc, nsites, t_step * dt, dt, hop, U, trotter_steps)
        #Measure the circuit
        for i in range(numq):
            qcirc.measure(i, i)

    #Choose provider and backend
    #provider = IBMQ.get_provider()
    #backend = Aer.get_backend('statevector_simulator')
        backend = Aer.get_backend('qasm_simulator')
        #backend = provider.get_backend('ibmq_qasm_simulator')
        #backend = provider.get_backend('ibmqx4')
        #backend = provider.get_backend('ibmqx2')
        #backend = provider.get_backend('ibmq_16_melbourne')

        shots = 8192
        max_credits = 10  #Max number of credits to spend on execution
        job_exp = execute(qcirc,
                          backend=backend,
                          shots=shots,
                          max_credits=max_credits)
        job_monitor(job_exp)
        result = job_exp.result()
        counts = result.get_counts(qcirc)
        print(result.get_counts(qcirc))
        print("Job: ", t_step + 1, " of ", num_steps, " complete.")

        #Store results in data array and normalize them
        for i in range(2**numq):
            if counts.get(get_bin(i, numq)) is None:
                dat = 0
            else:
                dat = counts.get(get_bin(i, numq))
            data[i, t_step] = dat / shots
    return data
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, execute, Aer
import numpy as np
import math as m
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]

q = QuantumRegister(1)
test_qubit = QuantumCircuit(q)
# Got a minus/zero vector by default.
# q6_0: |0>
test_qubit.iden(q[0])
# Applying identity matrix on zero vector.
#          ┌────┐
# q6_0: |0>┤ Id ├
#          └────┘
# Passing the circuit that we want to execute that is Identy gate on zero vector.
# Parameter#1 The circuit that is identity vector applied on zero vector.
# Parameter#2 statevector_simulator

# Applying x gate on zero vector.
#           ┌───┐
# q10_0: |0>┤ X ├
#           └───┘
Example #8
0
def test_random_circuit_generator_qiskit_comparison():
  gates_c = ["circuit.i({})", \
             "circuit.x({})", \
             "circuit.y({})", \
             "circuit.z({})", \
             "circuit.h({})", \
             "circuit.t({})", \
             "circuit.cx({}, {})", \
             "circuit.cy({}, {})", \
             "circuit.cz({}, {})", \
             "circuit.ch({}, {})", \
             "circuit.swap({}, {})", \
             #"circuit.rx({}, {})", \
             #"circuit.ry({}, {})", \
             #"circuit.rz({}, {})", \
             "circuit.rot({}, {})", \
             "circuit.crot({}, {}, {})"]
  gates_qkit = ["qubit.iden(q_reg[{}])", \
                "qubit.x(q_reg[{}])", \
                "qubit.y(q_reg[{}])", \
                "qubit.z(q_reg[{}])", \
                "qubit.h(q_reg[{}])", \
                "qubit.t(q_reg[{}])", \
                "qubit.cx(q_reg[{}], q_reg[{}])", \
                "qubit.cy(q_reg[{}], q_reg[{}])", \
                "qubit.cz(q_reg[{}], q_reg[{}])", \
                "qubit.ch(q_reg[{}], q_reg[{}])", \
                "qubit.swap(q_reg[{}], q_reg[{}])", \
                #"qubit.rx({}, q_reg[{}])", \
                #"qubit.ry({}, q_reg[{}])", \
                #"qubit.rz({}, q_reg[{}])", \
                "qubit.u1({}, q_reg[{}])", \
                "qubit.cu1({},q_reg[{}], q_reg[{}])"]
  gate_type = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 4]
  #gate_type = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4]
  func_len = len(gates_c)
  S_simulator = Aer.backends(name='statevector_simulator')[0]
  #errors = 0

  # number of circuits generated
  for _ in range(n_of_circuits_generated):
    n_qbit = random.randrange(2, 21)
    circuit = qcs.circuit_init(n_qbit)
    q_reg = QuantumRegister(n_qbit)
    qubit = QuantumCircuit(q_reg)

    # number of gates on circuit
    for _ in range(n_of_gates_per_circuit):
      q = random.randrange(0, n_qbit - 1)
      gate_choice = random.randrange(0, func_len)
      my_gate = gates_c[gate_choice]
      qiskit_gate = gates_qkit[gate_choice]
      gtype = gate_type[gate_choice]

      # single gate
      if (gtype == 1):
        exec(my_gate.format(q))
        exec(qiskit_gate.format(q))

      # controlled gate
      elif (gtype == 2):
        side = random.choice(["up", "down"])
        if (q == n_qbit - 1):
          q = q - 1
        if side == "up":
          exec(my_gate.format(q, q + 1))
          exec(qiskit_gate.format(q, q + 1))
        if side == "down":
          exec(my_gate.format(q + 1, q))
          exec(qiskit_gate.format(q + 1, q))

      # rotation gates
      if (gtype == 3):
        angle = random.uniform(-np.pi, np.pi)
        exec(my_gate.format(q, angle))
        exec(qiskit_gate.format(angle, q))

      # controlled rotation gate
      elif (gtype == 4):
        angle = random.uniform(-np.pi, np.pi)
        side = random.choice(["up", "down"])
        if (q == n_qbit - 1):
          q = q - 1
        if side == "up":
          exec(my_gate.format(q, q + 1, angle))
          exec(qiskit_gate.format(angle, q, q + 1))
        if side == "down":
          exec(my_gate.format(q + 1, q, angle))
          exec(qiskit_gate.format(angle, q + 1, q))

    # getting and comparing results
    result = circuit.execute(probs_autocalc=False)
    sv = result.get_state_vector()
    job = execute(qubit, S_simulator)
    result_qkit = job.result()
    sv_qkit = result_qkit.get_statevector()
    assert np.testing.assert_allclose(sv, sv_qkit, atol=1e-8, rtol=1e-8) \
                                                                      == None
class QCircuitMachine(RuleBasedStateMachine):
    """Build a Hypothesis rule based state machine for constructing, transpiling
    and simulating a series of random QuantumCircuits.

    Build circuits with up to QISKIT_RANDOM_QUBITS qubits, apply a random
    selection of gates from qiskit.circuit.library with randomly selected
    qargs, cargs, and parameters. At random intervals, transpile the circuit for
    a random backend with a random optimization level and simulate both the
    initial and the transpiled circuits to verify that their counts are the
    same.

    """

    qubits = Bundle("qubits")
    clbits = Bundle("clbits")

    backend = Aer.get_backend("qasm_simulator")
    max_qubits = int(backend.configuration().n_qubits / 2)

    def __init__(self):
        super().__init__()
        self.qc = QuantumCircuit()

    @precondition(lambda self: len(self.qc.qubits) < self.max_qubits)
    @rule(target=qubits, n=st.integers(min_value=1, max_value=max_qubits))
    def add_qreg(self, n):
        """Adds a new variable sized qreg to the circuit, up to max_qubits."""
        n = min(n, self.max_qubits - len(self.qc.qubits))
        qreg = QuantumRegister(n)
        self.qc.add_register(qreg)
        return multiple(*list(qreg))

    @rule(target=clbits, n=st.integers(1, 5))
    def add_creg(self, n):
        """Add a new variable sized creg to the circuit."""
        creg = ClassicalRegister(n)
        self.qc.add_register(creg)
        return multiple(*list(creg))

    # Gates of various shapes

    @rule(gate=st.sampled_from(oneQ_gates), qarg=qubits)
    def add_1q_gate(self, gate, qarg):
        """Append a random 1q gate on a random qubit."""
        self.qc.append(gate(), [qarg], [])

    @rule(
        gate=st.sampled_from(twoQ_gates),
        qargs=st.lists(qubits, max_size=2, min_size=2, unique=True),
    )
    def add_2q_gate(self, gate, qargs):
        """Append a random 2q gate across two random qubits."""
        self.qc.append(gate(), qargs)

    @rule(
        gate=st.sampled_from(threeQ_gates),
        qargs=st.lists(qubits, max_size=3, min_size=3, unique=True),
    )
    def add_3q_gate(self, gate, qargs):
        """Append a random 3q gate across three random qubits."""
        self.qc.append(gate(), qargs)

    @rule(
        gate=st.sampled_from(oneQ_oneP_gates),
        qarg=qubits,
        param=st.floats(
            allow_nan=False,
            allow_infinity=False,
            min_value=-10 * pi,
            max_value=10 * pi,
            allow_subnormal=False,
        ),
    )
    def add_1q1p_gate(self, gate, qarg, param):
        """Append a random 1q gate with 1 random float parameter."""
        self.qc.append(gate(param), [qarg])

    @rule(
        gate=st.sampled_from(oneQ_twoP_gates),
        qarg=qubits,
        params=st.lists(
            st.floats(
                allow_nan=False,
                allow_infinity=False,
                min_value=-10 * pi,
                max_value=10 * pi,
                allow_subnormal=False,
            ),
            min_size=2,
            max_size=2,
        ),
    )
    def add_1q2p_gate(self, gate, qarg, params):
        """Append a random 1q gate with 2 random float parameters."""
        self.qc.append(gate(*params), [qarg])

    @rule(
        gate=st.sampled_from(oneQ_threeP_gates),
        qarg=qubits,
        params=st.lists(
            st.floats(
                allow_nan=False,
                allow_infinity=False,
                min_value=-10 * pi,
                max_value=10 * pi,
                allow_subnormal=False,
            ),
            min_size=3,
            max_size=3,
        ),
    )
    def add_1q3p_gate(self, gate, qarg, params):
        """Append a random 1q gate with 3 random float parameters."""
        self.qc.append(gate(*params), [qarg])

    @rule(
        gate=st.sampled_from(twoQ_oneP_gates),
        qargs=st.lists(qubits, max_size=2, min_size=2, unique=True),
        param=st.floats(
            allow_nan=False,
            allow_infinity=False,
            min_value=-10 * pi,
            max_value=10 * pi,
            allow_subnormal=False,
        ),
    )
    def add_2q1p_gate(self, gate, qargs, param):
        """Append a random 2q gate with 1 random float parameter."""
        self.qc.append(gate(param), qargs)

    @rule(
        gate=st.sampled_from(twoQ_threeP_gates),
        qargs=st.lists(qubits, max_size=2, min_size=2, unique=True),
        params=st.lists(
            st.floats(
                allow_nan=False,
                allow_infinity=False,
                min_value=-10 * pi,
                max_value=10 * pi,
                allow_subnormal=False,
            ),
            min_size=3,
            max_size=3,
        ),
    )
    def add_2q3p_gate(self, gate, qargs, params):
        """Append a random 2q gate with 3 random float parameters."""
        self.qc.append(gate(*params), qargs)

    @rule(gate=st.sampled_from(oneQ_oneC_gates), qarg=qubits, carg=clbits)
    def add_1q1c_gate(self, gate, qarg, carg):
        """Append a random 1q, 1c gate."""
        self.qc.append(gate(), [qarg], [carg])

    @rule(gate=st.sampled_from(variadic_gates), qargs=st.lists(qubits, min_size=1, unique=True))
    def add_variQ_gate(self, gate, qargs):
        """Append a gate with a variable number of qargs."""
        self.qc.append(gate(len(qargs)), qargs)

    @precondition(lambda self: len(self.qc.data) > 0)
    @rule(carg=clbits, data=st.data())
    def add_c_if_last_gate(self, carg, data):
        """Modify the last gate to be conditional on a classical register."""
        creg = carg.register
        val = data.draw(st.integers(min_value=0, max_value=2 ** len(creg) - 1))

        last_gate = self.qc.data[-1]

        # Conditional instructions are not supported
        assume(isinstance(last_gate[0], Gate))

        last_gate[0].c_if(creg, val)

    # Properties to check

    @invariant()
    def qasm(self):
        """After each circuit operation, it should be possible to build QASM."""
        self.qc.qasm()

    @precondition(lambda self: any(isinstance(d[0], Measure) for d in self.qc.data))
    @rule(
        backend=st.one_of(st.none(), st.sampled_from(mock_backends)),
        opt_level=st.integers(min_value=0, max_value=3),
    )
    def equivalent_transpile(self, backend, opt_level):
        """Simulate, transpile and simulate the present circuit. Verify that the
        counts are not significantly different before and after transpilation.

        """

        print(f"Evaluating circuit at level {opt_level} on {backend}:\n{self.qc.qasm()}")

        assume(backend is None or backend.configuration().n_qubits >= len(self.qc.qubits))

        shots = 4096

        aer_counts = execute(self.qc, backend=self.backend, shots=shots).result().get_counts()

        try:
            xpiled_qc = transpile(self.qc, backend=backend, optimization_level=opt_level)
        except Exception as e:
            failed_qasm = "Exception caught during transpilation of circuit: \n{}".format(
                self.qc.qasm()
            )
            raise RuntimeError(failed_qasm) from e

        xpiled_aer_counts = (
            execute(xpiled_qc, backend=self.backend, shots=shots).result().get_counts()
        )

        count_differences = dicts_almost_equal(aer_counts, xpiled_aer_counts, 0.05 * shots)

        assert count_differences == "", "Counts not equivalent: {}\nFailing QASM: \n{}".format(
            count_differences, self.qc.qasm()
        )
Example #10
0
from qiskit import Aer
from qiskit import IBMQ

for backend in Aer.backends():
    print(backend.name())

for backend in IBMQ.providers():
    print(backend.name())
def minicomposer(nqubits=5, bloch=False, dirac=False, qsphere=False):
    out = widgets.Output
    single_gates = ['I', 'X', 'Y', 'Z', 'H', 'T', 'Tdg', 'S', 'Sdg']
    multi_gates = ['CX', 'CZ', 'SWAP']
    qc = QuantumCircuit(nqubits)
    if bloch or dirac or qsphere:
        backend = Aer.get_backend('statevector_simulator')

    class CircuitWidget:
        def __init__(self):
            self.waiting_for = 'gate'
            self.current_gate = ''
            self.qubits = ['']
            self.code = ""
            self.statevec = []

    widget_state = CircuitWidget()
    cell_pretext = """def create_circuit():\n    qc = QuantumCircuit({})\n""".format(
        nqubits)
    cell_ending = "    return qc"

    def on_sqg_click(btn):
        """On single-qubit-gate button click"""
        if widget_state.waiting_for == 'gate':
            widget_state.waiting_for = 'sqg_qubit'
            update_output()
            widget_state.current_gate = btn.description

    def on_mqg_click(btn):
        """On multi-qubit-gate button click"""
        if widget_state.waiting_for == 'gate':
            widget_state.waiting_for = 'mqg_qubit_0'
            update_output()
            widget_state.current_gate = btn.description

    def on_qubit_click(btn):
        """On qubit button click"""
        if widget_state.waiting_for == 'sqg_qubit':
            widget_state.qubits[0] = int(btn.description)
            apply_gate()
            widget_state.waiting_for = 'gate'
            update_output()
        elif widget_state.waiting_for == 'mqg_qubit_0':
            widget_state.qubits[0] = int(btn.description)
            widget_state.waiting_for = 'mqg_qubit_1'
            update_output()
        elif widget_state.waiting_for == 'mqg_qubit_1':
            widget_state.qubits.append(int(btn.description))
            widget_state.waiting_for = 'gate'
            apply_gate()
            update_output()

    def on_clear_click(btn):
        """On Clear button click"""
        widget_state.current_gate = 'Clear'
        widget_state.waiting_for = 'gate'
        apply_gate()
        update_output()

    def apply_gate():
        """Uses widget_state to apply the last selected gate, update
        the code cell and prepare widget_state for the next selection"""
        functionmap = {
            'I': 'qc.iden',
            'X': 'qc.x',
            'Y': 'qc.y',
            'Z': 'qc.z',
            'H': 'qc.h',
            'S': 'qc.s',
            'T': 'qc.t',
            'Sdg': 'qc.sdg',
            'Tdg': 'qc.tdg',
            'CX': 'qc.cx',
            'CZ': 'qc.cz',
            'SWAP': 'qc.swap'
        }
        gate = widget_state.current_gate
        qubits = widget_state.qubits
        widget_state.code += "    "
        if len(qubits) == 2:
            widget_state.code += functionmap[gate]
            widget_state.code += "({0}, {1})\n".format(qubits[0], qubits[1])
            widget_state.qubits.pop()
        elif widget_state.current_gate == 'Clear':
            widget_state.code = ""
        else:
            widget_state.code += functionmap[gate] + "({})\n".format(qubits[0])
        qc = QuantumCircuit(nqubits)
        # This is especially awful I know, please don't judge me
        exec(widget_state.code.replace("    ", ""))
        qc.draw('mpl').savefig('circuit_widget_temp.svg', format='svg')
        if bloch or dirac or qsphere:
            ket = execute(qc, backend).result().get_statevector()
            if bloch:
                plot_bloch_multivector(ket, show_state_labels=True).savefig(
                    'circuit_widget_temp_bs.svg', format='svg')
            if qsphere:
                plot_state_qsphere(ket, show_state_labels=True).savefig(
                    'circuit_widget_temp_qs.svg', format='svg')
            if dirac:
                widget_state.statevec = ket

    # Create buttons for single qubit gates
    sqg_btns = [widgets.Button(description=gate) for gate in single_gates]
    # Link these to the on_sqg_click function
    for button in sqg_btns:
        button.on_click(on_sqg_click)
    # Create buttons for qubits
    qubit_btns = [
        widgets.Button(description=str(qubit)) for qubit in range(nqubits)
    ]
    # Register these too
    for button in qubit_btns:
        button.on_click(on_qubit_click)
    # Create & register buttons for multi-qubit gates, clear
    mqg_btns = [widgets.Button(description=gate) for gate in multi_gates]
    for button in mqg_btns:
        button.on_click(on_mqg_click)
    clear_btn = widgets.Button(description="Clear")
    clear_btn.on_click(on_clear_click)

    instruction = widgets.Label(value="Select a gate to add to the circuit:")
    qc.draw('mpl').savefig('circuit_widget_temp.svg', format='svg')
    if bloch or dirac or qsphere:
        ket = execute(qc, backend).result().get_statevector()
        if bloch:
            plot_bloch_multivector(ket).savefig('circuit_widget_temp_bs.svg',
                                                format='svg')
            with open('circuit_widget_temp_bs.svg', 'r') as img:
                bloch_sphere = widgets.HTML(value=img.read())
        if qsphere:
            plot_state_qsphere(ket).savefig('circuit_widget_temp_qs.svg',
                                            format='svg')
            with open('circuit_widget_temp_qs.svg', 'r') as img:
                qsphere = widgets.HTML(value=img.read())
        if dirac:
            widget_state.statevec = ket
            latex_statevec = widgets.HTMLMath(vec_in_text_braket(ket))

    qiskit_code = widgets.HTML(value='')

    with open('circuit_widget_temp.svg', 'r') as img:
        drawing = widgets.HTML(value=img.read())

    def display_widget():
        sqg_box = widgets.HBox(sqg_btns)
        mqg_box = widgets.HBox(mqg_btns + [clear_btn])
        qubit_box = widgets.HBox(qubit_btns)
        main_box = widgets.VBox([sqg_box, mqg_box, qubit_box])
        visuals = [drawing]
        if bloch:
            visuals.append(bloch_sphere)
        if qsphere:
            visuals.append(qsphere)
        if dirac:
            visuals.append(latex_statevec)
        vis_box = widgets.VBox(visuals)
        display(instruction, main_box, vis_box)
        display(qiskit_code)

    def update_output():
        """Changes the availability of buttons depending on the state
        of widget_state.waiting_for, updates displayed image"""
        if widget_state.waiting_for == 'gate':
            for button in sqg_btns:
                button.disabled = False
            for button in mqg_btns:
                if nqubits > 1:
                    button.disabled = False
                else:
                    button.disabled = True
            for button in qubit_btns:
                button.disabled = True
            instruction.value = "Select a gate to add to the circuit:"
        else:
            for button in sqg_btns:
                button.disabled = True
            for button in mqg_btns:
                button.disabled = True
            for button in qubit_btns:
                button.disabled = False
            if widget_state.waiting_for == 'sqg_qubit':
                instruction.value = "Select a qubit to perform the gate on:"
            elif widget_state.waiting_for == 'mqg_qubit_0':
                instruction.value = "Select the control qubit:"
            elif widget_state.waiting_for == 'mqg_qubit_1':
                instruction.value = "Select the target qubit:"
                qubit_btns[widget_state.qubits[0]].disabled = True
        with open('circuit_widget_temp.svg', 'r') as img:
            drawing.value = img.read()
        if bloch:
            with open('circuit_widget_temp_bs.svg', 'r') as img:
                bloch_sphere.value = img.read()
        if qsphere:
            with open('circuit_widget_temp_qs.svg', 'r') as img:
                qsphere.value = img.read()
        if dirac:
            latex_statevec.value = vec_in_text_braket(widget_state.statevec)

        complete_code = cell_pretext + widget_state.code + cell_ending
        qiskit_code.value = f"""
            <div class="output_html" style="line-height: 1.21429em; font-size: 14px">
                {Code(complete_code, language='python')._repr_html_()}
            </div>
        """

    display_widget()
    update_output()
Example #12
0
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.rx(w[0], q[0])
qc.rx(w[1], q[1])
qc.rx(w[2], q[2])

qc.ry(w[3], q[0])
qc.ry(w[4], q[1])
qc.ry(w[5], q[2])

qc.rz(w[6], q[0])
qc.rz(w[7], q[1])
qc.rz(w[8], q[2])

qc.cx(q[0], q[1])
qc.cx(q[1], q[2])

qc.rx(w[9], q[0])
qc.ry(w[10], q[0])
qc.rz(w[11], q[0])

qc.rx(w[12], q[1])
qc.ry(w[13], q[1])
qc.rz(w[14], q[1])
# -

job = execute(qc, backend=Aer.get_backend("statevector_simulator"))
vec = job.result().get_statevector()
for i in vec:
    print(i)
Example #13
0
# Gets IBMQ providers
IBMQ.providers()
provider = IBMQ.get_provider("ibm-q")

# Tells us the queue length and qubit availability of all the backends
for backend in provider.backends():
    try:
        qubit_count = len(backend.properties().qubits)
    except:
        qubit_count = "simulated"
    print(
        f"{backend.name()} has {backend.status().pending_jobs} queued and {qubit_count} qubits"
    )

# Simulator backend
for backend in Aer.backends():
    print(backend)

# Choose a specific backend
simulator_backend = Aer.get_backend('qasm_simulator')

backend = provider.get_backend("ibmq_athens")
backend_online_sim = provider.get_backend("ibmq_qasm_simulator")
'''
Run Simulation Through Backend
'''
job = q.execute(circuit, backend=backend_online_sim, shots=500)
job_monitor(job)

# Plot Results
result = job.result()
Example #14
0
# \end{pmatrix}$

# In[2]:

# Let's do an X-gate on a |0> qubit
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.x(q[0])
qc.draw(output='mpl')

# Note: There is a new syntax that omits `Quantum Register` , but in this challenge, we will use the above syntax because it is easier to understand the algorithms of complex quantum circuits. (You can see the new notation [here](https://qiskit.org/documentation/stubs/qiskit.circuit.QuantumCircuit.html?highlight=quantumcircuit#qiskit.circuit.QuantumCircuit).)

# In[3]:

# Let's see the result
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result().get_statevector(qc, decimals=3)
plot_bloch_multivector(result)

# ### H Gate
# A Hadamard gate represents a rotation of $\pi$ about the axis that is in the middle of the $X$-axis and $Z$-axis.
# It maps the basis state $|0\rangle$ to $\frac{|0\rangle + |1\rangle}{\sqrt{2}}$, which means that a measurement will have equal probabilities of being `1` or `0`, creating a 'superposition' of states. This state is also written as $|+\rangle$.
#
# $H = \frac{1}{\sqrt{2}}\begin{pmatrix}
# 1 & 1 \\
# 1 & -1 \\
# \end{pmatrix}$

# In[4]:

# Let's do an H-gate on a |0> qubit
Example #15
0
def run_simulation (system, indx, commandprinter = False, noise = False):

    def vqe_create_solver(num_particles, num_orbitals, qubit_mapping,
                          two_qubit_reduction, z2_symmetries,
                          initial_point = system.opt_amplitudes,
                          noise = noise):

        initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping,
                                    two_qubit_reduction, z2_symmetries.sq_list)

        var_form = UCCSD(num_orbitals=num_orbitals,
                         num_particles=num_particles,
                         initial_state=initial_state,
                         qubit_mapping=qubit_mapping,
                         two_qubit_reduction=two_qubit_reduction,
                         z2_symmetries=z2_symmetries)

        if noise:
            var_form = EfficientSU2(num_qubits = no_qubits, entanglement="linear")
        else:
            var_form = UCCSD(num_orbitals=num_orbitals,
                             num_particles=num_particles,
                             initial_state=initial_state,
                             qubit_mapping=qubit_mapping,
                             two_qubit_reduction=two_qubit_reduction,
                             z2_symmetries=z2_symmetries)

        vqe = VQE(var_form=var_form, optimizer=SLSQP(maxiter=500),
                  include_custom=True, initial_point = initial_point)
        vqe.quantum_instance = backend
        return vqe

    basis_string = 'sto-3g'
    charge = 0
    spin = 1

    no_qubits = 6


    if noise:
        optimizer = SPSA(maxiter=100)
        IBMQ.load_account()
        provider = IBMQ.get_provider(hub='ibm-q')
        qasm = Aer.get_backend("qasm_simulator")
        device = provider.get_backend("ibmq_16_melbourne")
        coupling_map = device.configuration().coupling_map
        noise_model = NoiseModel.from_backend(device.properties())
        backend = QuantumInstance(backend=qasm,
                                  shots=10000,
                                  noise_model=noise_model,
                                  coupling_map=coupling_map,
                                  measurement_error_mitigation_cls=CompleteMeasFitter,
                                  cals_matrix_refresh_period=30)
    else:
        optimizer = SLSQP(maxiter=500)
        backend = Aer.get_backend('qasm_simulator')

    ########################################################################

    # Begin Running Simulation, Convert distance_counter to angstroms
    geometry = ['H 0. 0. ' + str(system.atoms[0].position[-1] * 0.529177249),
                'H 0. 0. ' + str(system.atoms[1].position[-1] * 0.529177249),
                'H 0. 0. ' + str(system.atoms[2].position[-1] * 0.529177249)]

    if indx is not None:
        geometry[indx] = 'H 0. 0. ' + str(system.atoms[indx].stand_by_position * 0.529177249)

    print(geometry)

    driver = PySCFDriver(atom=geometry,
                         unit=UnitsType.ANGSTROM, charge=charge, spin=spin, basis=basis_string)


    # # # # # # # # # # # # # # # # # # # # # #
    # VQE Result
    # # # # # # # # # # # # # # # # # # # # # #
    mgse = MolecularGroundStateEnergy(driver,
                                      qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                                      two_qubit_reduction=False, freeze_core=False,
                                      z2symmetry_reduction=None)

    vqe_result = mgse.compute_energy(vqe_create_solver).energy
    system.opt_amplitudes = mgse.solver.optimal_params

    # # # # # # # # # # # # # # # # # # # # # #
    # Exact Result
    # # # # # # # # # # # # # # # # # # # # # #
    mgse = MolecularGroundStateEnergy(driver, NumPyMinimumEigensolver(),
                                      qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                                      two_qubit_reduction=False, freeze_core=False,
                                      z2symmetry_reduction=None)
    exact_result = mgse.compute_energy().energy

    print("VQE Result:", vqe_result,
          "Exact Energy:", exact_result)

    return ({"Exact Energy" : exact_result, "VQE Energy" : vqe_result})
Example #16
0
 def get_simulator(self):
     return Aer.get_backend('qasm_simulator')
def Mont_Mul(x, y, m):

    n = len(x)

    x_reg = QuantumRegister(n + 1)
    y_reg = QuantumRegister(n + 2)
    y_reg_0 = QuantumRegister(1)
    m_reg = QuantumRegister(n + 2)
    a_reg = QuantumRegister(n + 2)
    u_reg = QuantumRegister(n + 1)
    onecubit = QuantumRegister(1)

    a_cl_reg = ClassicalRegister(n + 2)
    u_cl_reg = ClassicalRegister(n + 1)
    cl_reg = ClassicalRegister(n + 1)
    one_cl_reg = ClassicalRegister(1)

    circ_u = QuantumCircuit(u_reg, y_reg_0, u_cl_reg)
    circ_a = QuantumCircuit(a_reg, y_reg, m_reg, a_cl_reg, onecubit,
                            one_cl_reg)

    if y[n - 1] == '1':
        circ_u.x(y_reg_0)

    for i in range(n):
        if y[i] == '1':
            circ_a.x(y_reg[n - i - 1])
    for i in range(n):
        if m[i] == '1':
            circ_a.x(m_reg[n - i - 1])

    for i in range(n):
        if x[n - i - 1] == '1':
            add(u_reg, y_reg_0, circ_u)
        circ_u.measure(u_reg[0], u_cl_reg[0])
        result = execute(circ_u,
                         backend=Aer.get_backend('qasm_simulator'),
                         shots=2).result().get_counts(circ_u)
        measure_u = int((list(result.keys())[0]))

        if x[n - i - 1] == '1':
            add(a_reg, y_reg, circ_a)
        if measure_u == 1:
            add(a_reg, m_reg, circ_a)
        rshift(circ_a, a_reg, n + 2, onecubit)
        circ_a.measure(a_reg, a_cl_reg)
        circ_a.measure(onecubit, one_cl_reg)
        result = execute(circ_a,
                         backend=Aer.get_backend('qasm_simulator'),
                         shots=2).result().get_counts(circ_a)
        total = list(result.keys())[0]
        measure_a = total[2:]

        measure_onecubit = int(total[0])
        if measure_onecubit == 1:
            circ_a.x(onecubit)

        # loading a0 to u0
        if measure_a[n + 1] == '1':
            if measure_u == 0:
                circ_u.x(u_reg[0])
        else:
            if measure_u == 1:
                circ_u.x(u_reg[0])

    if (int(measure_a) >= int(m)):
        sub(a_reg, m_reg, circ_a)

    circ_a.measure(a_reg, a_cl_reg)
    result = execute(circ_a,
                     backend=Aer.get_backend('qasm_simulator'),
                     shots=2).result().get_counts(circ_a)
    total = list(result.keys())[0]
    final_a = total[2:]
    return final_a
Example #18
0
def phase_estimation(U: Callable[[QuantumCircuit, int, int], QuantumCircuit],
                     bits: int,
                     show: bool = True,
                     shots: int = 2048) -> Tuple[float, QuantumCircuit]:
    """
    Estimates θ, given a unitary operator U, such that U|ψ} = e^(2πiθ)|ψ}
    
    U: A function that adds controlled unitary gates to a given circuit, and returns the circuit
    bits: bit-size of phase estimation circuit (excluding ψ)
    
    show: if True, displays circuit and histogram of results (Jupyter notebook only)
    shots: number of shots (runs) to be executed
    
    Returns the tuple: (estimated theta, quantum estimation circuit)
    """
    backend = Aer.get_backend('qasm_simulator')
    #     q = QuantumCircuit(bits+1, bits)
    qr = QuantumRegister(bits, 'q')
    psi = QuantumRegister(1, 'psi')
    cr = ClassicalRegister(bits, 'c')
    q = QuantumCircuit(qr, psi, cr)

    # Apply Unitaries
    q.x(bits)  # Initialize |ψ}
    for i in range(bits):
        q.h(i)
        for _ in range(2**i):
            q = U(q, bits, i)  # apply controlled unitary
    q.barrier()

    # Inverse QFT
    swapped = []
    for a, b in enumerate(range(bits)[::-1]):
        if (a == b) or (a in swapped) or (b in swapped):
            break
        q.swap(a, b)  # swap bits
        swapped += [a, b]

    for i in range(bits):
        # apply inverse QFT controlled unitaries
        [
            q.cu1(-np.pi / 2**k, i, qubit)
            for qubit, k in enumerate(range(1, i + 1)[::-1])
            if (i > 0) and (qubit < i)
        ]
        q.h(i)
        q.barrier()

    # Measure
    [q.measure(i, i) for i in range(bits)]

    if show:
        try:
            display(q.draw(output='mpl'))
        except:
            pass

    counts = execute(q, backend=backend, shots=shots).result().get_counts()
    ans = [int(c, 2) for c, v in counts.items()
           if v == max(counts.values())][0]  # result with max counts
    estimated_theta = ans / (2**bits)
    if show:
        try:
            display(plot_histogram(counts))
            print("Highest Count Value: ", bin(ans), " = ", ans)
            print(f"Estimated theta: {ans}/2^{bits} = ", estimated_theta)
        except:
            pass
    return estimated_theta, q
Example #19
0
# # Executing it!

# In[2]:

# Compile the Scaffold to OpenQASM
from scaffcc_interface import ScaffCC
openqasmBell = ScaffCC(scaffold_codeBell).get_openqasm()
print(openqasmBell)

# ### Execute on a Simulator

# In[3]:

from qiskit import Aer, QuantumCircuit, execute
Aer.backends()

# In[4]:

simulator = Aer.get_backend('qasm_simulator')
vqe_circBell = QuantumCircuit.from_qasm_str(openqasmBell)
num_shots = 100000
sim_resultBell = execute(vqe_circBell, simulator, shots=num_shots).result()

countsBell = sim_resultBell.get_counts()

expected_valueBellXX = (+countsBell.get('00', 0) - countsBell.get(
    '01', 0) + countsBell.get('10', 0) - countsBell.get('11', 0)) / num_shots
expected_valueBellYY = (-countsBell.get('00', 0) + countsBell.get(
    '01', 0) + countsBell.get('10', 0) - countsBell.get('11', 0)) / num_shots
expected_valueBellZZ = (+countsBell.get('00', 0) + countsBell.get(
Example #20
0
inv_cnot.h(0)
inv_cnot.h(1)

inv_cnot.barrier()

inv_cnot.measure(q, c)

# In[51]:

# Draw the circuit
inv_cnot.draw(output='mpl')

# In[52]:

# Execute the circuit
job = execute(inv_cnot, backend=Aer.get_backend('qasm_simulator'), shots=1024)

result = job.result()

# In[53]:

# Print the result
print(result.get_counts(inv_cnot))

# In[54]:

# Plot the result
from qiskit.visualization import plot_histogram

plot_histogram(result.get_counts(inv_cnot))
def ChooseBackEnd(quantumCircuit, backendType="statevector_simulator", qubitsToBeMeasured=range(4), numberShots=4096, noisePresent=False, RealDeviceName="ibmq_ourense",number=12):

    if backendType == "statevector_simulator":
        backend = Aer.get_backend('statevector_simulator')
        result = execute(quantumCircuit, backend).result()
        probabilityVectors = np.square(np.absolute(result.get_statevector()))
        listForMusic = []
        for k in range(2**len(qubitsToBeMeasured)):
            listForMusic.append("%.3f" % (probabilityVectors[k]))

    elif backendType == "qasm_simulator":
        if noisePresent == False:
            # no noise
            quantumCircuit.measure(qubitsToBeMeasured, qubitsToBeMeasured)
            print(qubitsToBeMeasured)

            backend = Aer.get_backend('qasm_simulator')
            result = execute(quantumCircuit, backend, shots=numberShots).result()
            counts = result.get_counts()
            listForMusic = []
            for i in range(2**len(qubitsToBeMeasured)):
                bitstring = str(bin(i)[2:])
                bitstring = "0"*(4-len(bitstring))+bitstring
                if bitstring in counts.keys():
                    listForMusic.append("%.3f" % (counts[bitstring]/float(numberShots)))
                else:
                    listForMusic.append("0.000")
        else:
            print(qubitsToBeMeasured)
            quantumCircuit.measure(qubitsToBeMeasured,qubitsToBeMeasured)
            provider=IBMQ.save_account('XXX-YOUR-TOKEN')
            # simulate noise of a real device
            IBMQ.load_account()
            IBMQ.providers()


            device = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend(RealDeviceName)
            properties = device.properties()
            coupling_map = device.configuration().coupling_map

            # Generate an Aer noise model for device
            noise_model = noise.device.basic_device_noise_model(properties)
            basis_gates = noise_model.basis_gates


            # Perform noisy simulation
            backend = Aer.get_backend('qasm_simulator')
            job_sim = execute(quantumCircuit, backend,
                              coupling_map=coupling_map,
                              noise_model=noise_model,
                              basis_gates=basis_gates)
            result = job_sim.result()

            counts = result.get_counts()
            listForMusic = []
            for i in range(2**len(qubitsToBeMeasured)):
                bitstring = str(bin(i)[2:])
                bitstring = "0"*(4-len(bitstring))+bitstring
                if bitstring in counts.keys():
                    listForMusic.append("%.3f" % (counts[bitstring]/float(numberShots)))
                else:
                    listForMusic.append("0.000")
    elif backendType == "real_device":
        # real device
        quantumCircuit.measure(qubitsToBeMeasured,qubitsToBeMeasured)
        provider=IBMQ.save_account('XXX-YOUR-TOKEN')
        # simulate noise of a real device
        IBMQ.load_account()
        IBMQ.providers()


        device = IBMQ.get_provider(hub='ibm-q', group='open', project='main').get_backend(RealDeviceName)
        job_exp = execute(quantumCircuit, backend=device)

        job_monitor(job_exp)

        result = job_exp.result()

        counts = result.get_counts()
        listForMusic = []
        for i in range(2**len(qubitsToBeMeasured)):
            bitstring = str(bin(i)[2:])
            bitstring = "0"*(4-len(bitstring))+bitstring
            if bitstring in counts.keys():
                listForMusic.append(" %.3f" % (counts[bitstring]/float(numberShots)))
            else:
                listForMusic.append("0.000")


    return listForMusic
half_adder1.cx(0,3)
half_adder1.cx(1,3)
half_adder1.ccx(0,1,4)
half_adder1.barrier()

half_adder1.ccx(3,2,5)
#4 and 5 Or in 6
half_adder1.barrier()

half_adder1.x(4)
half_adder1.x(5)
half_adder1.ccx(4,5,6)
half_adder1.x(6)


half_adder1.cx(2,3)
half_adder1.barrier()
half_adder1.measure(6,1)



half_adder1.measure(3,0)

counts = execute(half_adder1, Aer.get_backend("qasm_simulator")).result().get_counts()
plot_histogram(counts)

half_adder1.draw()

"""Above was a full-adder"""

Example #23
0
# the LICENSE.txt file in the root directory of this source tree.
"""
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 compile, Aer

###############################################################
# Set the backend name and coupling map.
###############################################################
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
backend = Aer.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.u3(0.3, 0.2, 0.1, q[0])

# Prepare a Bell pair
qc.h(q[1])
Example #24
0
 # specify the angles
 rotation_angle1 = random_angle/360*2*pi
 rotation_angle2 = rotation_angle1 + pi/2
 
 #
 # first qubit
 #
 q1 =  QuantumRegister(1) 
 c1 = ClassicalRegister(1) 
 qc1 = QuantumCircuit(q1,c1)
 
 # rotate the qubit
 qc1.ry(2 * rotation_angle1,q1[0])
 
 # read the quantum state
 job = execute(qc1,Aer.get_backend('statevector_simulator'),optimization_level=0)
 current_quantum_state1=job.result().get_statevector(qc1) 
 [x1,y1]=[current_quantum_state1[0].real,current_quantum_state1[1].real]
 
 #
 # second qubit 
 #
 q2 =  QuantumRegister(1) 
 c2 = ClassicalRegister(1) 
 qc2 = QuantumCircuit(q2,c2)
 
 # rotate the qubit    
 qc2.ry(2 * rotation_angle2,q2[0])
     
 # read the quantum state
 job = execute(qc2,Aer.get_backend('statevector_simulator'),optimization_level=0)
Example #25
0
def sys_evolve_eng(nsites, excitations, total_time, dt, hop, U, trotter_steps):
    #Check for correct data types of input
    if not isinstance(nsites, int):
        raise TypeError("Number of sites should be int")
    if np.isscalar(excitations):
        raise TypeError("Initial state should be list or numpy array")
    if not np.isscalar(total_time):
        raise TypeError("Evolution time should be scalar")
    if not np.isscalar(dt):
        raise TypeError("Time step should be scalar")
    if not isinstance(trotter_steps, int):
        raise TypeError("Number of trotter slices should be int")

    numq = 2 * nsites
    num_steps = int(total_time / dt)
    print('Num Steps: ', num_steps)
    print('Total Time: ', total_time)
    data = np.zeros((2**numq, num_steps))
    energies = np.zeros(num_steps)

    for t_step in range(0, num_steps):
        #Create circuit with t_step number of steps
        q = QuantumRegister(numq)
        c = ClassicalRegister(numq)
        qcirc = QuantumCircuit(q, c)

        #=========SET YOUR INITIAL STATE==============
        #Loop over each excitation
        for flip in excitations:
            qcirc.x(flip)
        # qcirc.h(flip)
        # qcirc.t(flip)
        #===============================================================

        qcirc.barrier()
        #Append circuit with Trotter steps needed
        qc_evolve(qcirc, nsites, t_step * dt, dt, hop, U, trotter_steps)
        #Measure the circuit
        for i in range(numq):
            qcirc.measure(i, i)

    #Choose provider and backend
    #provider = IBMQ.get_provider()
    #backend = Aer.get_backend('statevector_simulator')
        backend = Aer.get_backend('qasm_simulator')
        #backend = provider.get_backend('ibmq_qasm_simulator')
        #backend = provider.get_backend('ibmqx4')
        #backend = provider.get_backend('ibmqx2')
        #backend = provider.get_backend('ibmq_16_melbourne')
        shots = 8192
        max_credits = 10  #Max number of credits to spend on execution
        job_exp = execute(qcirc,
                          backend=backend,
                          shots=shots,
                          max_credits=max_credits)
        #job_monitor(job_exp)
        result = job_exp.result()
        counts = result.get_counts(qcirc)
        #print(result.get_counts(qcirc))
        print("Job: ", t_step + 1, " of ", num_steps, " computing energy...")

        #Store results in data array and normalize them
        for i in range(2**numq):
            if counts.get(get_bin(i, numq)) is None:
                dat = 0
            else:
                dat = counts.get(get_bin(i, numq))
            data[i, t_step] = dat / shots

    #=======================================================
    #Compute energy of system
    #Compute repulsion energies
        repulsion_energy = measure_repulsion(U, nsites, counts, shots)

        #Compute hopping energies
        #Get list of hopping pairs
        even_pairs = []
        for i in range(0, nsites - 1, 2):
            #up_pair = [i, i+1]
            #dwn_pair = [i+nsites, i+nsites+1]
            even_pairs.append([i, i + 1])
            even_pairs.append([i + nsites, i + nsites + 1])
        odd_pairs = []
        for i in range(1, nsites - 1, 2):
            odd_pairs.append([i, i + 1])
            odd_pairs.append([i + nsites, i + nsites + 1])

        #Start with even hoppings, initialize circuit and find hopping pairs
        q = QuantumRegister(numq)
        c = ClassicalRegister(numq)
        qcirc = QuantumCircuit(q, c)
        #Loop over each excitation
        for flip in excitations:
            qcirc.x(flip)
        qcirc.barrier()
        #Append circuit with Trotter steps needed
        qc_evolve(qcirc, nsites, t_step * dt, dt, hop, U, trotter_steps)
        even_hopping = measure_hopping(hop, even_pairs, qcirc, numq)
        #===============================================================
        #Now do the same for the odd hoppings
        #Start with even hoppings, initialize circuit and find hopping pairs
        q = QuantumRegister(numq)
        c = ClassicalRegister(numq)
        qcirc = QuantumCircuit(q, c)
        #Loop over each excitation
        for flip in excitations:
            qcirc.x(flip)
        qcirc.barrier()
        #Append circuit with Trotter steps needed
        qc_evolve(qcirc, nsites, t_step * dt, dt, hop, U, trotter_steps)
        odd_hopping = measure_hopping(hop, odd_pairs, qcirc, numq)

        total_energy = repulsion_energy + even_hopping + odd_hopping
        energies[t_step] = total_energy
        print("Total Energy is: ", total_energy)
        print("Job: ", t_step + 1, " of ", num_steps, " complete")
    return data, energies
Example #26
0
 def test_aliases_return_empty_list(self):
     """Test backends() return an empty list if name is unknown."""
     self.assertEqual(Aer.backends("bad_name"), [])
    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 Aer.backends():
        print(backend.status())
    my_backend = Aer.get_backend('local_qasm_simulator')
    print("(QASM Simulator configuration) ")
    pprint.pprint(my_backend.configuration())
    print("(QASM Simulator properties) ")
    pprint.pprint(my_backend.properties())


    print("\n(IMQ Backends)")
    for backend in IBMQ.backends():
        print(backend.status())

    # select least busy available device and execute.
    least_busy_device = least_busy(IBMQ.backends(simulator=False))
    print("Running on current least busy device: ", least_busy_device)
Example #28
0
 def test_aer_deprecated(self):
     """test deprecated aer backends are resolved correctly"""
     old_name = 'local_qiskit_simulator'
     new_backend = Aer.get_backend(old_name)
     self.assertIsInstance(new_backend, QasmSimulator)
init_state = Custom(N_QUBITS, state_vector=init_state_vect)

# Prepare the actual initial state with a quantum register
qr = QuantumRegister(N_QUBITS)
circuit_init = init_state.construct_circuit('circuit', qr)

# Create as a partial so that when minimizing we don't change the values of the qr or of p.
evaluate = partial(evaluate_circuit, qr=qr, p=p)

# Minimize evaluate_circuit over gamma and beta only.
# We are minimizing so that we can have the minimum cost Hamiltonian
# This is the "variational" part of the algorithm. We are running the quantum circuit multiple times to find the minimum
result = minimize(evaluate, np.concatenate([gamma, beta]), method='L-BFGS-B')
print(result)

# The above found the minimum beta and gamma. So we run the quantum circuit with these angles

circuit = create_circuit(qr, result['x'][:p], result['x'][p:], p)

backend = BasicAer.get_backend('statevector_simulator')
job = execute(circuit, backend)
state = np.asarray(job.result().get_statevector(circuit))
print(np.absolute(state))
print(np.angle(state))

Z0 = pauli_z(0, 1)
Z1 = pauli_z(1, 1)

print(Z0.eval("matrix", circuit, Aer.get_backend('statevector_simulator'))[0])
print(Z1.eval("matrix", circuit, Aer.get_backend('statevector_simulator'))[0])
Example #30
0
def w_state_3q():
    "Choice of the backend"
    # using local qasm simulator
    backend = Aer.get_backend('qasm_simulator')

    # using IBMQ qasm simulator
    # backend = IBMQ.get_backend('ibmq_qasm_simulator')
    # using real device
    # backend = least_busy(IBMQ.backends(simulator=False))

    flag_qx2 = True
    if backend.name() == 'ibmqx4':
        flag_qx2 = False

    print("Your choice for the backend is: ", backend, "flag_qx2 is: ",
          flag_qx2)

    # 3-qubit W state
    n = 3
    q = QuantumRegister(n)
    c = ClassicalRegister(n)

    W_states = QuantumCircuit(q, c)

    W_states.x(q[2])  # start is |100>
    F_gate(W_states, q, 2, 1, 3, 1)  # Applying F12
    F_gate(W_states, q, 1, 0, 3, 2)  # Applying F23

    if flag_qx2:  # option ibmqx2
        W_states.cx(q[1], q[2])  # cNOT 21
        W_states.cx(q[0], q[1])  # cNOT 32

    else:  # option ibmqx4
        cxrv(W_states, q, 1, 2)
        cxrv(W_states, q, 0, 1)

    for i in range(3):
        W_states.measure(q[i], c[i])

    shots = 1000
    time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
    print('start W state 3-qubit on', backend, "N=", shots, time_exp)
    result = execute(W_states, backend=backend, shots=shots)
    time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
    print('end   W state 3-qubit on', backend, "N=", shots, time_exp)

    # In[39]:

    frequencies = result.result().get_counts(W_states)
    freq1 = frequencies['001']
    freq2 = frequencies['010']
    freq3 = frequencies['100']

    line1 = [1]
    line2 = [2]
    line3 = [4]

    real_data = np.zeros(
        shape=1000)  # real_data is actually an ndarray, not an array

    i = 0
    linespassed = 0
    for i in range(freq1):
        real_data[i] += line1

    linespassed += freq1
    for i in range(freq2):
        real_data[linespassed + i] += line2

    linespassed += freq2
    for i in range(freq3):
        real_data[linespassed + i] += line3

    return real_data
noise_model.add_all_qubit_quantum_error(error_2, ["cx"])

# Get basis gates from noise model
basis_gates = noise_model.basis_gates

# Make a circuit
circ = QuantumCircuit(3, 3)
circ.h(0)
circ.cx(0, 1)
circ.cx(1, 2)
circ.measure([0, 1, 2], [0, 1, 2])

# execute the quantum circuit
result = execute(
    circ,
    Aer.get_backend("statevector_simulator"),
    basis_gates=basis_gates,
    noise_model=noise_model,
).result()
psi = result.get_statevector(circ)
counts = result.get_counts(0)

circ.draw(output="mpl")
plt.show()

plot_state_city(psi)
plot_state_hinton(psi)
plot_state_qsphere(psi)
plot_state_paulivec(psi)
plot_bloch_multivector(psi)
def experiment(p, t, sigma_1, sigma_2, U, noise_model):
    #Note: p=1 is PEA + Scrambling gate (This is p=0 in other codes)
    n_register_qubits = p * t
    n_state_qubits = 2
    n_or_qubits = p * (t - 1)

    register_qubits = QuantumRegister(n_register_qubits)
    state_qubits = QuantumRegister(n_state_qubits)
    or_qubits = QuantumRegister(n_or_qubits)
    c = ClassicalRegister(2)

    circ = QuantumCircuit(register_qubits, or_qubits, state_qubits, c)

    circ.h(state_qubits)  #initial input state

    #Initial Round
    circ.h(register_qubits)

    #Controlled U(2)
    for i, q in enumerate(register_qubits[:t][::-1]):
        for k in range(0, 2**i):
            circ.unitary(Single_Controlled_Unitary(U),
                         [state_qubits[1], state_qubits[0], q],
                         label='cu')

    #QFT-dagger
    for qubit in range(int(t / 2)):
        circ.swap(qubit, t - qubit - 1)
    for j in range(t, 0, -1):
        k = t - j
        for m in range(k):
            circ.cu1(-np.pi / float(2**(k - m)), t - m - 1, t - k - 1)
        circ.h(t - k - 1)

    #Reset (OR + Scrambling gates)
    #OR-Gate
    circ.x(register_qubits[:t])
    circ.x(or_qubits[0])
    circ.ccx(register_qubits[0], register_qubits[1], or_qubits[0])
    #Scrambling gate
    circ.ch(or_qubits[0], state_qubits)

    #Subsequent Rounds
    for j in range(1, p):

        #CCU
        for i, q in enumerate(register_qubits[t * j:t * (j + 1)][::-1]):
            for k in range(0, 2**i):
                circ.unitary(
                    Two_Controlled_Unitary(U),
                    [state_qubits[1], state_qubits[0], or_qubits[j - 1], q],
                    label='ccu')

        #QFT-dagger
        for qubit in range(int(t / 2)):
            circ.swap(qubit + t * j, t - qubit - 1 + t * j)
        for f in range(t, 0, -1):
            k = t - f
            for m in range(k):
                circ.cu1(-np.pi / float(2**(k - m)), t - m - 1 + t * j,
                         t - k - 1 + t * j)
            circ.h(t - k - 1 + t * j)

        #OR-Gate
        circ.x(register_qubits[t * j:t * (j + 1)])
        circ.x(or_qubits[j])
        circ.ccx(register_qubits[t * j], register_qubits[t * j + 1],
                 or_qubits[j])
        #Scrambling gate
        circ.ch(or_qubits[j], state_qubits)

    #Pauli Measurements (There's a neater way to do this!)
    if sigma_1 == 'z' and sigma_2 == 'I':
        circ.iden(state_qubits[0])
        circ.iden(state_qubits[1])

    if sigma_1 == 'x' and sigma_2 == 'I':
        circ.h(state_qubits[0])
        circ.iden(state_qubits[1])

    if sigma_1 == 'y' and sigma_2 == 'I':
        circ.sdg(state_qubits[0])
        circ.h(state_qubits[0])
        circ.iden(state_qubits[1])

    if sigma_1 == 'I' and sigma_2 == 'z':
        circ.swap(state_qubits[0], state_qubits[1])

    if sigma_1 == 'I' and sigma_2 == 'x':
        circ.swap(state_qubits[0], state_qubits[1])
        circ.h(state_qubits[0])
        circ.iden(state_qubits[1])

    if sigma_1 == 'I' and sigma_2 == 'y':
        circ.swap(state_qubits[0], state_qubits[1])
        circ.iden(state_qubits[1])
        circ.sdg(state_qubits[0])
        circ.h(state_qubits[0])

    if sigma_1 == 'z' and sigma_2 == 'z':
        circ.cx(state_qubits[1], state_qubits[0])

    if sigma_1 == 'z' and sigma_2 == 'x':
        circ.h(state_qubits[1])
        circ.iden(state_qubits[0])
        circ.cx(state_qubits[1], state_qubits[0])

    if sigma_1 == 'z' and sigma_2 == 'y':
        circ.sdg(state_qubits[1])
        circ.h(state_qubits[1])
        circ.iden(state_qubits[0])
        circ.cx(state_qubits[1], state_qubits[0])

    if sigma_1 == 'x' and sigma_2 == 'z':
        circ.iden(state_qubits[1])
        circ.h(state_qubits[0])
        circ.cx(state_qubits[1], state_qubits[0])

    if sigma_1 == 'x' and sigma_2 == 'x':
        circ.h(state_qubits[1])
        circ.h(state_qubits[0])
        circ.cx(state_qubits[1], state_qubits[0])

    if sigma_1 == 'x' and sigma_2 == 'y':
        circ.sdg(state_qubits[1])
        circ.h(state_qubits[1])
        circ.h(state_qubits[0])
        circ.cx(state_qubits[1], state_qubits[0])

    if sigma_1 == 'y' and sigma_2 == 'z':
        circ.iden(state_qubits[1])
        circ.sdg(state_qubits[0])
        circ.h(state_qubits[0])
        circ.cx(state_qubits[1], state_qubits[0])

    if sigma_1 == 'y' and sigma_2 == 'x':
        circ.h(state_qubits[1])
        circ.sdg(state_qubits[0])
        circ.h(state_qubits[0])
        circ.cx(state_qubits[1], state_qubits[0])

    if sigma_1 == 'y' and sigma_2 == 'y':
        circ.sdg(state_qubits[1])
        circ.h(state_qubits[1])
        circ.sdg(state_qubits[0])
        circ.h(state_qubits[0])
        circ.cx(state_qubits[1], state_qubits[0])

    circ.measure(state_qubits, c)

    shots = 8192
    #IBMQ.load_account()
    #provider = IBMQ.get_provider('ibm-q')
    #qcomp = provider.get_backend('ibmq_qasm_simulator')
    qcomp = Aer.get_backend('qasm_simulator')
    job = execute(circ,
                  backend=qcomp,
                  shots=shots,
                  noise_model=noise_model,
                  basis_gates=noise_model.basis_gates)
    #print(job_monitor(job))
    result = job.result()
    result_dictionary = result.get_counts(circ)
    probs = {}
    for output in ['00', '01', '10', '11']:
        if output in result_dictionary:
            probs[output] = result_dictionary[output]
        else:
            probs[output] = 0

    return (probs['00'] + probs['11'] - probs['01'] - probs['10']) / shots