def test_get_backend_configuration(self):
        """Test get_backend_configuration.

        If all correct should return configuration for the
        local_qasm_simulator.
        """
        qp = QuantumProgram(specs=QPS_SPECS)
        test = len(qp.get_backend_configuration("local_qasm_simulator"))
        self.assertEqual(test, 6)
    def test_get_backend_configuration(self):
        """Test get_backend_configuration.

        If all correct should return configuration for the
        local_qasm_simulator.
        """
        qp = QuantumProgram(specs=QPS_SPECS)
        test = len(qp.get_backend_configuration("local_qasm_simulator"))
        self.assertEqual(test, 6)
Beispiel #3
0
 def get_available_qubit_number(self):
     if self._backend is None:
         raise RuntimeError(
             "You should select a backend before asking for its qubit number."
         )
     if "local" in self._backend:
         return 16
     return QuantumProgram.get_backend_configuration(
         self, self._backend)['n_qubits']
Beispiel #4
0
def vqe(molecule='H2', depth=6, max_trials=200, shots=1):
    if molecule == 'H2':
        n_qubits = 2
        Z1 = 1
        Z2 = 1
        min_distance = 0.2
        max_distance = 4

    elif molecule == 'LiH':
        n_qubits = 4
        Z1 = 1
        Z2 = 3
        min_distance = 0.5
        max_distance = 5

    else:
        raise QISKitError("Unknown molecule for VQE.")

    # Read Hamiltonian
    ham_name = os.path.join(os.path.dirname(__file__),
                            molecule + '/' + molecule + 'Equilibrium.txt')
    pauli_list = Hamiltonian_from_file(ham_name)
    H = make_Hamiltonian(pauli_list)

    # Exact Energy
    exact = np.amin(la.eig(H)[0]).real
    print('The exact ground state energy is: {}'.format(exact))

    # Optimization
    device = 'local_qasm_simulator'
    qp = QuantumProgram()

    if shots != 1:
        H = group_paulis(pauli_list)

    entangler_map = qp.get_backend_configuration(device)['coupling_map']

    if entangler_map == 'all-to-all':
        entangler_map = {i: [j for j in range(n_qubits) if j != i] for i in range(n_qubits)}
    else:
        entangler_map = mapper.coupling_list2dict(entangler_map)

    initial_theta = np.random.randn(2 * n_qubits * depth)   # initial angles
    initial_c = 0.01                                        # first theta perturbations
    target_update = 2 * np.pi * 0.1                         # aimed update on first trial
    save_step = 20                                          # print optimization trajectory

    cost = partial(cost_function, qp, H, n_qubits, depth, entangler_map, shots, device)

    SPSA_params = SPSA_calibration(cost, initial_theta, initial_c, target_update, stat=25)
    output = SPSA_optimization(cost, initial_theta, SPSA_params, max_trials, save_step, last_avg=1)

    return qp
Beispiel #5
0
def vqe(molecule='H2', depth=6, max_trials=200, shots=1):
    if molecule == 'H2':
        n_qubits = 2
        Z1 = 1
        Z2 = 1
        min_distance = 0.2
        max_distance = 4

    elif molecule == 'LiH':
        n_qubits = 4
        Z1 = 1
        Z2 = 3
        min_distance = 0.5
        max_distance = 5

    else:
        raise QISKitError("Unknown molecule for VQE.")

    # Read Hamiltonian
    ham_name = os.path.join(os.path.dirname(__file__),
                            molecule + '/' + molecule + 'Equilibrium.txt')
    pauli_list = Hamiltonian_from_file(ham_name)
    H = make_Hamiltonian(pauli_list)

    # Exact Energy
    exact = np.amin(la.eig(H)[0]).real
    print('The exact ground state energy is: {}'.format(exact))

    # Optimization
    device = 'local_qasm_simulator'
    qp = QuantumProgram()

    if shots != 1:
        H = group_paulis(pauli_list)

    entangler_map = qp.get_backend_configuration(device)['coupling_map']

    if entangler_map == 'all-to-all':
        entangler_map = {
            i: [j for j in range(n_qubits) if j != i]
            for i in range(n_qubits)
        }
    else:
        entangler_map = mapper.coupling_list2dict(entangler_map)

    initial_theta = np.random.randn(2 * n_qubits * depth)  # initial angles
    initial_c = 0.01  # first theta perturbations
    target_update = 2 * np.pi * 0.1  # aimed update on first trial
    save_step = 20  # print optimization trajectory

    cost = partial(cost_function, qp, H, n_qubits, depth, entangler_map, shots,
                   device)

    SPSA_params = SPSA_calibration(cost,
                                   initial_theta,
                                   initial_c,
                                   target_update,
                                   stat=25)
    output = SPSA_optimization(cost,
                               initial_theta,
                               SPSA_params,
                               max_trials,
                               save_step,
                               last_avg=1)

    return qp
Beispiel #6
0
class QC():
    '''
    class QC
    '''
    # pylint: disable=too-many-instance-attributes
    def __init__(self, backend='local_qasm_simulator', remote=False, qubits=3):
        # private member
        # __qp
        self.__qp = None

        # calc phase
        self.phase = [
            ['0', 'initialized.']
            ]
        # config
        self.backend = backend
        self.remote = remote
        self.qubits = qubits
        # circuits variable
        self.shots = 2
        # async
        self.wait = False
        self.last = ['init', 'None']

        self.load()

    def load(self, api_info=True):
        '''
        load
        '''
        self.__qp = QuantumProgram()
        if self.remote:
            try:
                import Qconfig
                self.__qp.set_api(Qconfig.APItoken, Qconfig.config["url"],
                                  hub=Qconfig.config["hub"],
                                  group=Qconfig.config["group"],
                                  project=Qconfig.config["project"])

            except ImportError as ex:
                msg = 'Error in loading Qconfig.py!. Error = {}\n'.format(ex)
                sys.stdout.write(msg)
                sys.stdout.flush()
                return False

            if api_info is True:
                api = self.__qp.get_api()
                sys.stdout.write('<IBM Quantum Experience API information>\n')
                sys.stdout.flush()
                sys.stdout.write('Version: {0}\n'.format(api.api_version()))
                sys.stdout.write('User jobs (last 5):\n')
                jobs = api.get_jobs(limit=500)

                def format_date(job_item):
                    '''
                    format
                    '''
                    return datetime.strptime(job_item['creationDate'],
                                             '%Y-%m-%dT%H:%M:%S.%fZ')
                sortedjobs = sorted(jobs,
                                    key=format_date)
                sys.stdout.write('  {0:<32} {1:<24} {2:<9} {3}\n'
                                 .format('id',
                                         'creationDate',
                                         'status',
                                         'backend'))
                sys.stdout.write('{:-^94}\n'.format(""))
                for job in sortedjobs[-5:]:
                    sys.stdout.write('  {0:<32} {1:<24} {2:<9} {3}\n'
                                     .format(job['id'],
                                             job['creationDate'],
                                             job['status'],
                                             job['backend']['name']))
                sys.stdout.write('There are {0} jobs on the server\n'
                                 .format(len(jobs)))
                sys.stdout.write('Credits: {0}\n'
                                 .format(api.get_my_credits()))
                sys.stdout.flush()

        self.backends = self.__qp.available_backends()
        status = self.__qp.get_backend_status(self.backend)

        if 'available' in status:
            if status['available'] is False:
                return False
        return True

    def set_config(self, config=None):
        '''
        set config
        '''
        if config is None:
            config = {}

        if 'backend' in config:
            self.backend = str(config['backend'])
            if 'local_' in self.backend:
                self.remote = False
            else:
                self.remote = True

        if 'remote' in config:
            self.remote = config['remote']

        if 'qubits' in config:
            self.qubits = int(config['qubits'])

        return True

    def _progress(self, phasename, text):
        self.phase.append([str(phasename), str(text)])
        text = "Phase {0}: {1}".format(phasename, text)
        sys.stdout.write("{}\n".format(text))
        sys.stdout.flush()

    def _init_circuit(self):
        self._progress('1', 'Initialize quantum registers and circuit')
        qubits = self.qubits

        quantum_registers = [
            {"name": "cin", "size": 1},
            {"name": "qa", "size": qubits},
            {"name": "qb", "size": qubits},
            {"name": "cout", "size": 1}
            ]

        classical_registers = [
            {"name": "ans", "size": qubits + 1}
            ]

        if 'cin' in self.__qp.get_quantum_register_names():
            self.__qp.destroy_quantum_registers(quantum_registers)
            self.__qp.destroy_classical_registers(classical_registers)

        q_r = self.__qp.create_quantum_registers(quantum_registers)
        c_r = self.__qp.create_classical_registers(classical_registers)

        self.__qp.create_circuit("qcirc", q_r, c_r)

    def _create_circuit_qadd(self):
        # quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184
        def majority(circuit, q_a, q_b, q_c):
            '''
            majority
            '''
            circuit.cx(q_c, q_b)
            circuit.cx(q_c, q_a)
            circuit.ccx(q_a, q_b, q_c)

        def unmaj(circuit, q_a, q_b, q_c):
            '''
            unmajority
            '''
            circuit.ccx(q_a, q_b, q_c)
            circuit.cx(q_c, q_a)
            circuit.cx(q_a, q_b)

        def adder(circuit, c_in, q_a, q_b, c_out, qubits):
            '''
            adder
            '''
            # pylint: disable=too-many-arguments
            majority(circuit, c_in[0], q_b[0], q_a[0])
            for i in range(qubits - 1):
                majority(circuit, q_a[i], q_b[i + 1], q_a[i + 1])

            circuit.cx(q_a[qubits - 1], c_out[0])

            for i in range(qubits - 1)[::-1]:
                unmaj(circuit, q_a[i], q_b[i + 1], q_a[i + 1])
            unmaj(circuit, c_in[0], q_b[0], q_a[0])

        if 'add' not in self.__qp.get_circuit_names():
            [c_in, q_a, q_b, c_out] = map(self.__qp.get_quantum_register,
                                          ["cin", "qa", "qb", "cout"])
            ans = self.__qp.get_classical_register('ans')
            qadder = self.__qp.create_circuit("qadd",
                                              [c_in, q_a, q_b, c_out],
                                              [ans])
            adder(qadder, c_in, q_a, q_b, c_out, self.qubits)

        return 'add' in self.__qp.get_circuit_names()

    def _create_circuit_qsub(self):
        circuit_names = self.__qp.get_circuit_names()
        if 'qsub' not in circuit_names:
            if 'qadd' not in circuit_names:
                self._create_circuit_qadd()

            # subtractor circuit
            self.__qp.add_circuit('qsub', self.__qp.get_circuit('qadd'))
            qsubtractor = self.__qp.get_circuit('qsub')
            qsubtractor.reverse()
        return 'qsub' in self.__qp.get_circuit_names()

    def _qadd(self, input_a, input_b=None, subtract=False, observe=False):
        # pylint: disable=too-many-locals

        def measure(circuit, q_b, c_out, ans):
            '''
            measure
            '''
            circuit.barrier()
            for i in range(self.qubits):
                circuit.measure(q_b[i], ans[i])
            circuit.measure(c_out[0], ans[self.qubits])

        def char2q(circuit, cbit, qbit):
            '''
            char2q
            '''
            if cbit == '1':
                circuit.x(qbit)
            elif cbit == 'H':
                circuit.h(qbit)
                self.shots = 5 * (2**self.qubits)

        def input_state(circuit, input_a, input_b=None):
            '''
            input state
            '''
            input_a = input_a[::-1]
            for i in range(self.qubits):
                char2q(circuit, input_a[i], q_a[i])

            if input_b is not None:
                input_b = input_b[::-1]
                for i in range(self.qubits):
                    char2q(circuit, input_b[i], q_b[i])

        def reset_input(circuit, c_in, q_a, c_out):
            '''
            reset input
            '''
            circuit.reset(c_in)
            circuit.reset(c_out)
            for i in range(self.qubits):
                circuit.reset(q_a[i])

        # get registers
        [c_in, q_a, q_b, c_out] = map(self.__qp.get_quantum_register,
                                      ["cin", "qa", "qb", "cout"])
        ans = self.__qp.get_classical_register('ans')
        qcirc = self.__qp.get_circuit('qcirc')

        self._progress('2',
                       'Define input state ({})'
                       .format('QADD' if subtract is False else 'QSUB'))
        if input_b is not None:
            if subtract is True:
                # subtract
                input_state(qcirc, input_b, input_a)
            else:
                # add
                input_state(qcirc, input_a, input_b)
        else:
            reset_input(qcirc, c_in, q_a, c_out)
            input_state(qcirc, input_a)

        self._progress('3',
                       'Define quantum circuit ({})'
                       .format('QADD' if subtract is False else 'QSUB'))
        if subtract is True:
            self._create_circuit_qsub()
            qcirc.extend(self.__qp.get_circuit('qsub'))
        else:
            self._create_circuit_qadd()
            qcirc.extend(self.__qp.get_circuit('qadd'))

        if observe is True:
            measure(qcirc, q_b, c_out, ans)

    def _qsub(self, input_a, input_b=None, observe=False):
        self._qadd(input_a, input_b, subtract=True, observe=observe)

    def _qope(self, input_a, operator, input_b=None, observe=False):
        if operator == '+':
            return self._qadd(input_a, input_b, observe=observe)
        elif operator == '-':
            return self._qsub(input_a, input_b, observe=observe)
        return None

    def _compile(self, name, cross_backend=None, print_qasm=False):
        self._progress('4', 'Compile quantum circuit')

        coupling_map = None
        if cross_backend is not None:
            backend_conf = self.__qp.get_backend_configuration(cross_backend)
            coupling_map = backend_conf.get('coupling_map', None)
            if coupling_map is None:
                sys.stdout.write('backend: {} coupling_map not found'
                                 .format(cross_backend))

        qobj = self.__qp.compile([name],
                                 backend=self.backend,
                                 shots=self.shots,
                                 seed=1,
                                 coupling_map=coupling_map)

        if print_qasm is True:
            sys.stdout.write(self.__qp.get_compiled_qasm(qobj, 'qcirc'))
            sys.stdout.flush()
        return qobj

    def _run(self, qobj):
        self._progress('5', 'Run quantum circuit (wait for answer)')
        result = self.__qp.run(qobj, wait=5, timeout=100000)
        return result

    def _run_async(self, qobj):
        '''
        _run_async
        '''
        self._progress('5', 'Run quantum circuit')
        self.wait = True

        def async_result(result):
            '''
            async call back
            '''
            self.wait = False
            self.last = self.result_parse(result)

        self.__qp.run_async(qobj,
                            wait=5, timeout=100000, callback=async_result)

    def _is_regular_number(self, numstring, base):
        '''
        returns input binary format string or None.
        '''
        if base == 'bin':
            binstring = numstring
        elif base == 'dec':
            if numstring == 'H':
                binstring = 'H'*self.qubits
            else:
                binstring = format(int(numstring), "0{}b".format(self.qubits))

        if len(binstring) != self.qubits:
            return None

        return binstring

    def get_seq(self, text, base='dec'):
        '''
        convert seq and check it
        if text is invalid, return the list of length 0.
        '''
        operators = u'(\\+|\\-)'
        seq = re.split(operators, text)

        # length check
        if len(seq) % 2 == 0 or len(seq) == 1:
            return []

        # regex
        if base == 'bin':
            regex = re.compile(r'[01H]+')
        else:
            regex = re.compile(r'(^(?!.H)[0-9]+|H)')

        for i in range(0, len(seq), 2):
            match = regex.match(seq[i])
            if match is None:
                return []
            num = match.group(0)
            seq[i] = self._is_regular_number(num, base)

            if seq[i] is None:
                return []

        return seq

    def result_parse(self, result):
        '''
        result_parse
        '''
        data = result.get_data("qcirc")
        sys.stdout.write("job id: {0}\n".format(result.get_job_id()))
        sys.stdout.write("raw result: {0}\n".format(data))
        sys.stdout.write("{:=^40}\n".format("answer"))

        counts = data['counts']
        sortedcounts = sorted(counts.items(),
                              key=lambda x: -x[1])

        sortedans = []
        for count in sortedcounts:
            if count[0][0] == '1':
                ans = 'OR'
            else:
                ans = str(int(count[0][-self.qubits:], 2))
            sortedans.append(ans)
            sys.stdout.write('Dec: {0:>2} Bin: {1} Count: {2} \n'
                             .format(ans, str(count[0]), str(count[1])))

        sys.stdout.write('{0:d} answer{1}\n'
                         .format(len(sortedans),
                                 '' if len(sortedans) == 1 else 's'))
        sys.stdout.write("{:=^40}\n".format(""))
        if 'time' in data:
            sys.stdout.write("time: {0:<3} sec\n".format(data['time']))
        sys.stdout.write("All process done.\n")
        sys.stdout.flush()

        uniqanswer = sorted(set(sortedans), key=sortedans.index)

        ans = ",".join(uniqanswer)

        return [str(result), ans]

    def exec_calc(self, text, base='dec', wait_result=False):
        '''
        exec_calc
        '''
        seq = self.get_seq(text, base)
        print('QC seq:', seq)
        if seq == []:
            return ["Syntax error", None]

        # fail message
        fail_msg = None

        try:
            self._init_circuit()
            numbers = seq[0::2]     # slice even index
            i = 1
            observe = False
            for oper in seq[1::2]:  # slice odd index
                if i == len(numbers) - 1:
                    observe = True
                if i == 1:
                    self._qope(numbers[0], oper, numbers[1], observe=observe)
                else:
                    self._qope(numbers[i], oper, observe=observe)
                i = i + 1

            qobj = self._compile('qcirc')

            if wait_result is True:
                [status, ans] = self.result_parse(self._run(qobj))
            else:
                self._run_async(qobj)
                [status, ans] = [
                    'Wait. Calculating on {0}'.format(self.backend),
                    '...'
                    ]

        except QISKitError as ex:
            fail_msg = ('There was an error in the circuit!. Error = {}\n'
                        .format(ex))
        except RegisterSizeError as ex:
            fail_msg = ('Error in the number of registers!. Error = {}\n'
                        .format(ex))

        if fail_msg is not None:
            sys.stdout.write(fail_msg)
            sys.stdout.flush()
            return ["FAIL", None]

        return [status, ans]
def msquare():
    ans = []

    Q_program = QuantumProgram()
    Q_program.set_api(Qconfig.APItoken,
                      Qconfig.config["url"])  # set the APIToken and API url

    N = 4
    # Creating registers
    qr = Q_program.create_quantum_register("qr", N)

    # for recording the measurement on qr
    cr = Q_program.create_classical_register("cr", N)

    circuitName = "sharedEntangled"
    sharedEntangled = Q_program.create_circuit(circuitName, [qr], [cr])

    #Create uniform superposition of all strings of length 2
    for i in range(2):
        sharedEntangled.h(qr[i])

    #The amplitude is minus if there are odd number of 1s
    for i in range(2):
        sharedEntangled.z(qr[i])

    #Copy the content of the fist two qubits to the last two qubits
    for i in range(2):
        sharedEntangled.cx(qr[i], qr[i + 2])

    #Flip the last two qubits
    for i in range(2, 4):
        sharedEntangled.x(qr[i])
    #we first define controlled-u gates required to assign phases
    from math import pi

    def ch(qProg, a, b):
        """ Controlled-Hadamard gate """
        qProg.h(b)
        qProg.sdg(b)
        qProg.cx(a, b)
        qProg.h(b)
        qProg.t(b)
        qProg.cx(a, b)
        qProg.t(b)
        qProg.h(b)
        qProg.s(b)
        qProg.x(b)
        qProg.s(a)
        return qProg

    def cu1pi2(qProg, c, t):
        """ Controlled-u1(phi/2) gate """
        qProg.u1(pi / 4.0, c)
        qProg.cx(c, t)
        qProg.u1(-pi / 4.0, t)
        qProg.cx(c, t)
        qProg.u1(pi / 4.0, t)
        return qProg

    def cu3pi2(qProg, c, t):
        """ Controlled-u3(pi/2, -pi/2, pi/2) gate """
        qProg.u1(pi / 2.0, t)
        qProg.cx(c, t)
        qProg.u3(-pi / 4.0, 0, 0, t)
        qProg.cx(c, t)
        qProg.u3(pi / 4.0, -pi / 2.0, 0, t)
        return qProg

    # dictionary for Alice's operations/circuits
    aliceCircuits = {}
    # Quantum circuits for Alice when receiving idx in 1, 2, 3
    for idx in range(1, 4):
        circuitName = "Alice" + str(idx)
        aliceCircuits[circuitName] = Q_program.create_circuit(
            circuitName, [qr], [cr])
        theCircuit = aliceCircuits[circuitName]

        if idx == 1:
            #the circuit of A_1
            theCircuit.x(qr[1])
            theCircuit.cx(qr[1], qr[0])
            theCircuit = cu1pi2(theCircuit, qr[1], qr[0])
            theCircuit.x(qr[0])
            theCircuit.x(qr[1])
            theCircuit = cu1pi2(theCircuit, qr[0], qr[1])
            theCircuit.x(qr[0])
            theCircuit = cu1pi2(theCircuit, qr[0], qr[1])
            theCircuit = cu3pi2(theCircuit, qr[0], qr[1])
            theCircuit.x(qr[0])
            theCircuit = ch(theCircuit, qr[0], qr[1])
            theCircuit.x(qr[0])
            theCircuit.x(qr[1])
            theCircuit.cx(qr[1], qr[0])
            theCircuit.x(qr[1])

        elif idx == 2:
            theCircuit.x(qr[0])
            theCircuit.x(qr[1])
            theCircuit = cu1pi2(theCircuit, qr[0], qr[1])
            theCircuit.x(qr[0])
            theCircuit.x(qr[1])
            theCircuit = cu1pi2(theCircuit, qr[0], qr[1])
            theCircuit.x(qr[0])
            theCircuit.h(qr[0])
            theCircuit.h(qr[1])

        elif idx == 3:
            theCircuit.cz(qr[0], qr[1])
            theCircuit.swap(qr[0], qr[1])
            theCircuit.h(qr[0])
            theCircuit.h(qr[1])
            theCircuit.x(qr[0])
            theCircuit.x(qr[1])
            theCircuit.cz(qr[0], qr[1])
            theCircuit.x(qr[0])
            theCircuit.x(qr[1])

        #measure the first two qubits in the computational basis
        theCircuit.measure(qr[0], cr[0])
        theCircuit.measure(qr[1], cr[1])

    # dictionary for Bob's operations/circuits
    bobCircuits = {}
    # Quantum circuits for Bob when receiving idx in 1, 2, 3
    for idx in range(1, 4):
        circuitName = "Bob" + str(idx)
        bobCircuits[circuitName] = Q_program.create_circuit(
            circuitName, [qr], [cr])
        theCircuit = bobCircuits[circuitName]
        if idx == 1:
            theCircuit.x(qr[2])
            theCircuit.x(qr[3])
            theCircuit.cz(qr[2], qr[3])
            theCircuit.x(qr[3])
            theCircuit.u1(pi / 2.0, qr[2])
            theCircuit.x(qr[2])
            theCircuit.z(qr[2])
            theCircuit.cx(qr[2], qr[3])
            theCircuit.cx(qr[3], qr[2])
            theCircuit.h(qr[2])
            theCircuit.h(qr[3])
            theCircuit.x(qr[3])
            theCircuit = cu1pi2(theCircuit, qr[2], qr[3])
            theCircuit.x(qr[2])
            theCircuit.cz(qr[2], qr[3])
            theCircuit.x(qr[2])
            theCircuit.x(qr[3])

        elif idx == 2:
            theCircuit.x(qr[2])
            theCircuit.x(qr[3])
            theCircuit.cz(qr[2], qr[3])
            theCircuit.x(qr[3])
            theCircuit.u1(pi / 2.0, qr[3])
            theCircuit.cx(qr[2], qr[3])
            theCircuit.h(qr[2])
            theCircuit.h(qr[3])

        elif idx == 3:
            theCircuit.cx(qr[3], qr[2])
            theCircuit.x(qr[3])
            theCircuit.h(qr[3])

        #measure the third and fourth qubits in the computational basis
        theCircuit.measure(qr[2], cr[2])
        theCircuit.measure(qr[3], cr[3])

    a, b = random.randint(1, 3), random.randint(1,
                                                3)  #generate random integers

    for i in range(3):
        for j in range(3):
            a = i + 1
            b = j + 1
            # print("The values of a and b are, resp.,", a,b)
            aliceCircuit = aliceCircuits["Alice" + str(a)]
            bobCircuit = bobCircuits["Bob" + str(b)]

            circuitName = "Alice" + str(a) + "Bob" + str(b)
            Q_program.add_circuit(circuitName,
                                  sharedEntangled + aliceCircuit + bobCircuit)

            backend = "local_qasm_simulator"
            ##backend = "ibmqx2"

            shots = 1  # We perform a one-shot experiment
            results = Q_program.execute([circuitName],
                                        backend=backend,
                                        shots=shots)
            answer = results.get_counts(circuitName)
            # print(answer)
            for key in answer.keys():
                aliceAnswer = [int(key[-1]), int(key[-2])]
                bobAnswer = [int(key[-3]), int(key[-4])]
                if sum(aliceAnswer
                       ) % 2 == 0:  #the sume of Alice answer must be even
                    aliceAnswer.append(0)
                else:
                    aliceAnswer.append(1)
                if sum(bobAnswer) % 2 == 1:  #the sum of Bob answer must be odd
                    bobAnswer.append(0)
                else:
                    bobAnswer.append(1)
                break

            # print("Alice answer for a = ", a, "is", aliceAnswer)
            # print("Bob answer for b = ", b, "is", bobAnswer)

            print(a, b)
            ans.append(aliceAnswer)
            ans.append(bobAnswer)

            # if(aliceAnswer[b-1] != bobAnswer[a-1]): #check if the intersection of their answers is the same
            #     print("Alice and Bob lost")
            # else:
            #     print("Alice and Bob won")

            backend = "local_qasm_simulator"
            #backend = "ibmqx2"
            shots = 10  # We perform 10 shots of experiments for each round
            nWins = 0
            nLost = 0
            for a in range(1, 4):
                for b in range(1, 4):
                    # print("Asking Alice and Bob with a and b are, resp.,", a,b)
                    rWins = 0
                    rLost = 0

                    aliceCircuit = aliceCircuits["Alice" + str(a)]
                    bobCircuit = bobCircuits["Bob" + str(b)]
                    circuitName = "Alice" + str(a) + "Bob" + str(b)
                    Q_program.add_circuit(
                        circuitName,
                        sharedEntangled + aliceCircuit + bobCircuit)

                    if backend == "ibmqx2":
                        ibmqx2_backend = Q_program.get_backend_configuration(
                            'ibmqx2')
                        ibmqx2_coupling = ibmqx2_backend['coupling_map']
                        results = Q_program.execute(
                            [circuitName],
                            backend=backend,
                            shots=shots,
                            coupling_map=ibmqx2_coupling,
                            max_credits=3,
                            wait=10,
                            timeout=240)
                    else:
                        results = Q_program.execute([circuitName],
                                                    backend=backend,
                                                    shots=shots)
                    answer = results.get_counts(circuitName)

                    for key in answer.keys():
                        kfreq = answer[
                            key]  #frequencies of keys obtained from measurements
                        aliceAnswer = [int(key[-1]), int(key[-2])]
                        bobAnswer = [int(key[-3]), int(key[-4])]
                        if sum(aliceAnswer) % 2 == 0:
                            aliceAnswer.append(0)
                        else:
                            aliceAnswer.append(1)
                        if sum(bobAnswer) % 2 == 1:
                            bobAnswer.append(0)
                        else:
                            bobAnswer.append(1)

                        #print("Alice answer for a = ", a, "is", aliceAnswer)
                        #print("Bob answer for b = ", b, "is", bobAnswer)

                        if (aliceAnswer[b - 1] != bobAnswer[a - 1]):
                            #print(a, b, "Alice and Bob lost")
                            nLost += kfreq
                            rLost += kfreq
                        else:
                            #print(a, b, "Alice and Bob won")
                            nWins += kfreq
                            rWins += kfreq
            #         print("\t#wins = ", rWins, "out of ", shots, "shots")
            #
            # print("Number of Games = ", nWins+nLost)
            # print("Number of Wins = ", nWins)
            # print("Winning probabilities = ", (nWins*100.0)/(nWins+nLost))
    return ans
nWins = 0
nLost = 0
for a in range(1, 4):
    for b in range(1, 4):
        print("Asking Alice and Bob with a and b are, resp.,", a, b)
        rWins = 0
        rLost = 0

        aliceCircuit = aliceCircuits["Alice" + str(a)]
        bobCircuit = bobCircuits["Bob" + str(b)]
        circuitName = "Alice" + str(a) + "Bob" + str(b)
        Q_program.add_circuit(circuitName,
                              sharedEntangled + aliceCircuit + bobCircuit)

        if backend == "ibmqx2":
            ibmqx2_backend = Q_program.get_backend_configuration('ibmqx2')
            ibmqx2_coupling = ibmqx2_backend['coupling_map']
            results = Q_program.execute([circuitName],
                                        backend=backend,
                                        shots=shots,
                                        coupling_map=ibmqx2_coupling,
                                        max_credits=3,
                                        wait=10,
                                        timeout=240)
        else:
            results = Q_program.execute([circuitName],
                                        backend=backend,
                                        shots=shots)
        answer = results.get_counts(circuitName)

        for key in answer.keys():
Beispiel #9
0
circuits = ['Bell']

qobj = qp.compile(circuits, backend)

result = qp.run(qobj, wait=2, timeout=240)


#print(result.get_counts('Bell'))

pprint(qp.available_backends())

#pprint(qp.get_backend_status('ibmqx2'))


pprint(qp.get_backend_configuration('ibmqx5'))




# quantum register for the first circuit
q1 = qp.create_quantum_register('q1', 4)
c1 = qp.create_classical_register('c1', 4)
# quantum register for the second circuit
q2 = qp.create_quantum_register('q2', 2)
c2 = qp.create_classical_register('c2', 2)
# making the first circuits
qc1 = qp.create_circuit('GHZ', [q1], [c1])
qc2 = qp.create_circuit('superpostion', [q2], [c2])
qc1.h(q1[0])
qc1.cx(q1[0], q1[1])
Beispiel #10
0
    def create_experiment(self, qp: QuantumProgram,
                          input) -> Tuple[str, dict, str]:
        a, b = input
        qm = self.qubit_mapping
        name = self.name
        algorithm = self.algorithm
        backend = self.backend

        # qubit mapping
        if qm is None:
            index_a1 = 2
            index_a2 = 1
            index_b1 = 3
            index_b2 = 0
        else:
            index_a1 = qm["a1"]
            index_a2 = qm["a2"]
            index_b1 = qm["b1"]
            index_b2 = qm["b2"]

        # input build
        q: QuantumRegister = qp.create_quantum_register("q", 5)
        ans = qp.create_classical_register("ans", 5)
        qc: QuantumCircuit = qp.create_circuit(name, [q], [ans])

        a1: Tuple[QuantumRegister, int] = q[index_a1]
        a2: Tuple[QuantumRegister, int] = q[index_a2]
        b1: Tuple[QuantumRegister, int] = q[index_b1]
        b2: Tuple[QuantumRegister, int] = q[index_b2]
        expected = list("00000")
        expected_result = (int(a, 2) + int(b, 2)) % 4
        expected[index_a1] = str(int(expected_result / 2) % 2)
        expected[index_a2] = str(int(expected_result / 1) % 2)
        expected[index_b1] = b[2]
        expected[index_b2] = b[3]
        expected = "".join(reversed(expected))

        # circuit setup
        if a[2] == "1":
            qc.x(a1)
        if a[3] == "1":
            qc.x(a2)
        if b[2] == "1":
            qc.x(b1)
        if b[3] == "1":
            qc.x(b2)

        processor = self.backend
        conf = qp.get_backend_configuration(processor, list_format=False)
        coupling_map = conf["coupling_map"]

        algorithm(qc, a1, a2, b1, b2, coupling_map)

        qc.measure(q, ans)

        # compilation
        qobj = qp.compile(name_of_circuits=[name],
                          backend=backend,
                          config=conf,
                          max_credits=3)
        qasm = qp.get_compiled_qasm(qobj, name)
        qasm_lines = self.qasm((a, b), expected) + qasm.split("\n")

        qasm = "\n".join(filter(lambda x: len(x) > 0, qasm_lines))

        return qasm, qobj, expected
Beispiel #11
0
def create_experiment(Q_program: QuantumProgram,
                      a: str,
                      b: str,
                      experiment: Experiment,
                      silent=True) -> Tuple[str, dict, str]:

    qm = experiment.qubit_mapping
    name = experiment.name
    algorithm = experiment.algorithm
    backend = experiment.backend

    # qubit mapping
    if qm is None:
        index_a1 = 2
        index_a2 = 1
        index_b1 = 3
        index_b2 = 0
    else:
        index_a1 = qm["a1"]
        index_a2 = qm["a2"]
        index_b1 = qm["b1"]
        index_b2 = qm["b2"]

    # input build
    q: QuantumRegister = Q_program.create_quantum_register("q", 5)
    ans = Q_program.create_classical_register("ans", 5)
    qc: QuantumCircuit = Q_program.create_circuit(name, [q], [ans])

    a1: Tuple[QuantumRegister, int] = q[index_a1]
    a2: Tuple[QuantumRegister, int] = q[index_a2]
    b1: Tuple[QuantumRegister, int] = q[index_b1]
    b2: Tuple[QuantumRegister, int] = q[index_b2]
    expected = list("00000")
    expected_result = (int(a, 2) + int(b, 2)) % 4
    expected[index_a1] = str(int(expected_result / 2) % 2)
    expected[index_a2] = str(int(expected_result / 1) % 2)
    expected[index_b1] = b[2]
    expected[index_b2] = b[3]
    expected = "".join(reversed(expected))
    if not silent:
        print("Job: %s + %s = %s. Expecting answer: %s" %
              (a, b, bin(expected_result), expected))

    # circuit setup
    if a[2] == "1":
        if not silent: print("a1 setting to 1")
        qc.x(a1)
    if a[3] == "1":
        if not silent: print("a2 setting to 1")
        qc.x(a2)
    if b[2] == "1":
        if not silent: print("b1 setting to 1")
        qc.x(b1)
    if b[3] == "1":
        if not silent: print("b2 setting to 1")
        qc.x(b2)

    processor = "ibmqx4"
    conf = Q_program.get_backend_configuration(processor, list_format=False)
    coupling_map = conf["coupling_map"]

    algorithm(qc, a1, a2, b1, b2, coupling_map)

    qc.measure(q, ans)

    # compilation
    qobj = Q_program.compile(name_of_circuits=[name],
                             backend=backend,
                             config=conf,
                             max_credits=3)
    qasm = Q_program.get_compiled_qasm(qobj, name)
    qasm_lines = experiment.qasm((a, b), expected) + qasm.split("\n")

    qasm = "\n".join(filter(lambda x: len(x) > 0, qasm_lines))

    return qasm, qobj, expected
Beispiel #12
0
print(ran_qasm)

# You can use
# `qp.execute(circuits)
# to combine the compile and run in a single step.

out = qp.execute(circuits, backend, wait=2, timeout=240)
print(out)

## Execute on a Real Device
qp.set_api(Qconfig.APItoken,
           Qconfig.config['url'])  # set the APIToken and API url
real_device_backend = [
    backend for backend in qp.online_devices()
    if qp.get_backend_configuration(backend)['n_qubits'] == 5
    and qp.get_backend_status(backend)['available'] == True
]

print(qp.online_devices())

for backend in qp.online_devices():
    print(qp.get_backend_configuration(backend))
    print(qp.get_backend_status(backend))
# find and appropriate real device backend that your APIToken has access to run that has 5 qubits and is available
print(real_device_backend)
backend = real_device_backend[
    0]  # Backend where you execute your programl in this case, on the real Quatum Chip online
circuits = ['Circuit']  # Group of circuits to execute
shots = 1024  # Number of shots to run the program (experiment); maximum is 8192 shots.
max_credits = 3  # Maximu number of credits to spend on executions.
Beispiel #13
0
def create_experiment(Q_program: QuantumProgram, inputA: str, inputB: str,
                      name: str, backend: str) -> Tuple[str, str]:
    # qubit mapping
    index_a1 = 2
    index_a2 = 4
    index_b1 = 0
    index_b2 = 3

    # input build
    q = Q_program.create_quantum_register("q", 5)
    ans = Q_program.create_classical_register("ans", 5)
    qc: QuantumCircuit = Q_program.create_circuit(name, [q], [ans])

    a1 = q[index_a1]
    a2 = q[index_a2]
    b1 = q[index_b1]
    b2 = q[index_b2]
    expected = list("00000")
    expected_result = (int(a, 2) + int(b, 2)) % 4
    expected[index_a1] = str(int(expected_result / 2) % 2)
    expected[index_a2] = str(int(expected_result / 1) % 2)
    expected[index_b1] = b[2]
    expected[index_b2] = b[3]
    expected = "".join(reversed(expected))
    print("Job: %s + %s = %s. Expecting answer: %s" %
          (a, b, bin(expected_result), expected))

    # circuit setup
    if a[2] == "1":
        print("a1 setting to 1")
        qc.x(a1)
    if a[3] == "1":
        print("a2 setting to 1")
        qc.x(a2)
    if b[2] == "1":
        print("b1 setting to 1")
        qc.x(b1)
    if b[3] == "1":
        print("b2 setting to 1")
        qc.x(b2)

    # circuit algorithm
    qc.h(a1)
    qc.crk(2, a1, a2, cnot_back=True)
    qc.h(a2)

    qc.crk(1, a2, b2)
    qc.crk(2, a1, b2)
    qc.crk(1, a1, b1, cnot_back=True)

    qc.h(a2)
    qc.crk(-2, a1, a2, cnot_back=True)
    qc.h(a1)

    qc.measure(q, ans)

    # job parameters
    processor = "ibmqx4"
    print("Compile & Run manually for '%s' using backend '%s':" %
          (processor, backend))

    qobj_id = "@%s: %s(%s,%s) -> %s" % (
        datetime.now().strftime('%Y-%m-%d %H:%M:%S'), name, a, b, expected)

    conf = Q_program.get_backend_configuration(processor, list_format=False)
    qobj = Q_program.compile(name_of_circuits=[name],
                             backend=backend,
                             shots=shots,
                             config=conf,
                             max_credits=3,
                             qobj_id=qobj_id)
    qasm = Q_program.get_compiled_qasm(qobj, name)
    measurements = list(filter(lambda r: "measure" in r, qasm.split('\n')))
    instructions = list(filter(lambda r: "measure" not in r, qasm.split('\n')))

    qasm = "\n".join(["// draper(%s,%s)->%s" % (a, b, expected)] +
                     instructions + measurements)
    return qasm, expected