コード例 #1
0
    def __init__(self, vals, weights, max_weight, ans, shots=8192):

        self.provider = IonQProvider(token='API-token')

        # Get an IonQ simulator backend to run circuits on:
        self.backend = self.provider.get_backend("ionq_simulator")

        # get the weighted Pauli Operators
        self.ham = ks.get_operator(vals, weights, max_weight)[0]
        # get the shift for Maximum values
        self.shift = ks.get_operator(vals, weights, max_weight)[1]

        self.shots = shots

        # number of qubits used
        self.n_qubits = self.ham.num_qubits

        # build the ansatz from this module
        self.ansatz = RealAmplitudes(self.n_qubits, reps=1)

        # number of parameters for this ansatz
        self.num_params = self.ansatz.num_parameters

        # default an initial energy to be large value
        self.prev_energy = 100000000000

        # real answer from the DWave Side
        self.ans = ans
コード例 #2
0
    def compile_and_run(self, t, vertex_coins, mode="ionq_simulator"):

        from qiskit_ionq_provider import IonQProvider 
        from qiskit.tools.visualization import circuit_drawer 
        from qiskit.providers.jobstatus import JobStatus

        provider = IonQProvider(token='UXA0mTBVroG62waNXpn6yCXDyx2iDNH0')
        backend = provider.get_backend(mode)

        self.build_evolution_operator(vertex_coins)
        circuit = self.evolve(t)

        transpiled = transpile(circuit, backend=backend)
        print(circuit_drawer(circuit))

        job = backend.run(transpiled)


        #save job_id
        job_id = job.job_id()

        if mode == "ionq_simulator":
            #Fetch the result:
            result = job.result()

        elif mode == "ionq_qpu":
            job=backend.retrieve_job(job_id)
            while job.status() is not JobStatus.DONE:
                time.sleep(5)


        from qiskit.visualization import plot_histogram
        fig = plot_histogram(result.get_counts())
        fig.savefig("hist.png")
コード例 #3
0
    def run(self):
        provider = IonQProvider(token=self.__API_KEY)
        backend = provider.get_backend("ionq_qpu")
        job = backend.run(self.get_circuit(), shots=1)
        return job.result()


#%%
# h = gt.HadamardGate(0)
# x = gt.XGate(1)
# cnot = gt.CNOTGate(1, 2)
# tof = gt.ToffoliGate([0, 2], 1)
# measure = gt.MeasureGate()
# swap = gt.SWAPGate([1, 2])
# #%%
# c = ct.Circuit(API_KEY=API_KEY)
# fig = c.draw()
# fig.savefig("figures/initial_circuit.png")
# #%%
# c.apply_gate(h)
# c.apply_gate(cnot)
# c.apply_gate(x)
# c.apply_gate(tof)
# c.apply_gate(swap)
# c.apply_gate(measure)
# c.draw()
# #%%
# result = c.simulate()
# plot_histogram(result.get_counts())
# #%%
# result = c.run()
# #%%
# img = c.draw()
# type(img)
# #%%

# #%%
コード例 #4
0
def test_provider_getbackend():
    """Verifies that provider.get_backend works."""
    pro = IonQProvider("123456")

    for backend in pro.backends():
        assert backend == pro.get_backend(backend.name())
コード例 #5
0
def test_provider_autocomplete():
    """Verifies that provider.backends autocomplete works."""
    pro = IonQProvider("123456")

    for backend in pro.backends():
        assert hasattr(pro.backends, backend.name())
コード例 #6
0
#!/usr/bin/env python
# coding: utf-8

from qiskit import *
from qiskit_ionq_provider import IonQProvider
from qiskit.providers.jobstatus import JobStatus
#Call provider and set token value
provider = IonQProvider(token='BFmvdArkiCbsS12r4LZf5VgYDo4HngsS')
from random import randrange
import numpy as np

from swap_test import swap_test
from hash import crypto_hash, bitstring


# given a message, produces a Quantum Digital Signature
class Signed_Transaction():
    def __init__(self, message):
        self.message = message
        self.bitstring = self.string_to_bitstring(message)
        self.signed_transaction = self.sign_transaction()

    def string_to_bitstring(self, m):
        bs = ""
        for i in bytes(m, encoding='utf-8'):
            bs += bin(i)[2:]
        return bs

    # make M pairs of private keys
    def generate_priv_keys(self):
        n = 4
コード例 #7
0
class PlayGround:
    def __init__(self, vals, weights, max_weight, ans, shots=8192):

        self.provider = IonQProvider(token='API-token')

        # Get an IonQ simulator backend to run circuits on:
        self.backend = self.provider.get_backend("ionq_simulator")

        # get the weighted Pauli Operators
        self.ham = ks.get_operator(vals, weights, max_weight)[0]
        # get the shift for Maximum values
        self.shift = ks.get_operator(vals, weights, max_weight)[1]

        self.shots = shots

        # number of qubits used
        self.n_qubits = self.ham.num_qubits

        # build the ansatz from this module
        self.ansatz = RealAmplitudes(self.n_qubits, reps=1)

        # number of parameters for this ansatz
        self.num_params = self.ansatz.num_parameters

        # default an initial energy to be large value
        self.prev_energy = 100000000000

        # real answer from the DWave Side
        self.ans = ans

    def get_result(self, qcs, shots=1000):

        full_rd = None  # full result dictionary
        for aqc in qcs:

            # had to transpile otherwise will have illegal gates
            t_aqc = transpile(aqc, self.backend)
            job = self.backend.run(t_aqc, shots=shots)

            # save job_id
            # job_id_bell = job.job_id()

            # Fetch the result:
            result = job.result()
            rd = result.to_dict()
            if full_rd is None:
                full_rd = rd
            else:
                full_rd['results'].append(rd['results'])

        fin_result = Result.from_dict(full_rd)
        return fin_result

    def compute_energy(self, cur_param, demo=True, which_params=None):

        # compute the energy correspond to our WeightedPauliOperators
        # with ansatz having parameters: cur_param

        qc_binded = update_params(self.ansatz, cur_param)

        # had to do this for provider's limitation
        qc_cur = QuantumCircuit(self.n_qubits)
        qc_cur.compose(qc_binded, inplace=True)

        # append to evaluation circuit for state initialized by the ansatz,
        # this is in qc_cur
        # append the appropriate rotation to compute
        # expectation value for WeightedPaulioperators
        wpauli_circuits = self.ham.construct_evaluation_circuit(qc_cur, False)

        if not demo:
            result = self.get_result(wpauli_circuits, shots=self.shots)

            e = self.ham.evaluate_with_result(result, False)
        else:
            # generate some pseudo random energy landscape for demo purposes
            e = abs(np.sin(cur_param[which_params[0]]))**abs(cur_param[0])
            e *= abs(np.cos(cur_param[which_params[1]]))**abs(cur_param[1])
            e *= abs(self.ans)
            e *= np.random.random()
            if np.isnan(e):
                pdb.set_trace()
        return e

    def plot_energy_landscape(self,
                              ax,
                              prev_param,
                              which_params,
                              p_rng0,
                              p_rng1,
                              step=10,
                              demo=True):

        # plot the energies landscapes around the prev_param
        # due to limitations we only vary two parameters at a time

        energies = np.ones((step, step))

        theta0i = prev_param[which_params[0]]
        theta1i = prev_param[which_params[1]]

        theta0r = np.linspace(theta0i + p_rng0[0], theta0i + p_rng0[1], step)
        theta1r = np.linspace(theta1i + p_rng1[0], theta1i + p_rng1[1], step)

        for i, theta0 in enumerate(theta0r):
            for j, theta1 in enumerate(theta1r):
                cur_param = prev_param
                cur_param[which_params[0]] = theta0
                cur_param[which_params[1]] = theta1

                e = self.compute_energy(cur_param, demo, which_params)

                energies[i][j] = e

        X, Y = np.meshgrid(theta0r, theta1r)

        # plot current location
        ax.plot([theta0i] * 10, [theta1i] * 10,
                np.linspace(np.min(energies), np.max(energies), 10),
                'or-',
                alpha=0.8,
                linewidth=1.5)

        ax.plot_surface(X,
                        Y,
                        energies,
                        cmap=cm.coolwarm,
                        linewidth=0,
                        antialiased=False)

        ax.set_ylabel('theta{}'.format(which_params[0]))
        ax.set_xlabel('theta{}'.format(which_params[1]))

        return ax

    def ask_move(self):

        # asks which direction and magnitude you want to move
        print("Anon bid me how thee wanteth to moveth in the parameter space.")
        print("Chooseth thy grise wisely!")
        print("Lacking valor moves shall beest did punish")

        changes = np.zeros((self.num_params, ))

        print("Tell me which two parameters you want to move in")

        var1 = int(
            input("Enter a number between 0 and {0} separated by a space: ".
                  format(self.num_params)) or randrange(self.num_params))
        var2 = int(
            input("Enter a number between 0 and {0} separated by a space: ".
                  format(self.num_params)) or randrange(self.num_params))

        delta = np.pi / 100

        for i in [int(var1), int(var2)]:
            j = int(
                input('How many steps for parameter {}?'.format(i))
                or randrange(5))
            changes[i] = j * delta

        return changes, [int(var1), int(var2)]

    def ask_show_param(self):

        # asks which parameter to show the plot
        print(
            "Which two parameters would you like to see for the next energy landscape plot"
        )

        var1 = int(
            input("Enter a number between 0 and {0} separated by a space: ".
                  format(self.num_params)) or randrange(self.num_params))
        var2 = int(
            input("Enter a number between 0 and {0} separated by a space: ".
                  format(self.num_params)) or randrange(self.num_params))

        return int(var1), int(var2)

    def punish_player(self, cur_energy):

        # if you get to a higher energy, give random kick to parameters

        if self.prev_energy < cur_energy:
            print("You moved from energy {0} to {1}".format(
                self.prev_energy, cur_energy))
            print(
                "Bad move, a strong wind blows you to somewhere else in parameter space"
            )
            punish = np.random.random((self.num_params, )) * np.pi / 100
            return punish
        else:
            print("Well done, your current energy is {}".format(cur_energy))
            print("You maybe one step closer to the ground state energy {}".
                  format(self.ans))
            self.prev_energy = cur_energy
            return np.zeros((self.num_params, ))

    def do_move(self, new_params, demo, which_params):

        # actually change the update parameters
        e = self.compute_energy(new_params, demo, which_params)

        punish_step = self.punish_player(e)
        return punish_step + new_params  # update the prev_param

    def play(self):
        prev_param = np.pi * np.random.random((self.num_params, )) - np.pi / 2
        next_param = None
        counter = 0
        while not isclose(self.prev_energy, self.ans, rel_tol=0.05):

            # fig, axs = plt.subplots(2, 2)
            fig = plt.figure()
            # loop over this to show multiple views
            for i in range(4):
                print("Now pick some parameter pairs")
                vary_param = self.ask_show_param()

                cur_ax = fig.add_subplot(2, 2, i + 1, projection='3d')
                cur_ax = self.plot_energy_landscape(cur_ax, prev_param,
                                                    vary_param,
                                                    [-np.pi / 10, np.pi / 10],
                                                    [-np.pi / 10, np.pi / 10],
                                                    10)

            plt.title("Optimal answer: {}".format(self.ans))
            plt.show()
            # change this retarded funciton I wrote
            # put the optimal answer on the title of the plot
            moves, which_params = self.ask_move()
            next_param = prev_param + moves
            prev_param = self.do_move(next_param, True, which_params)
            if counter >= 2:
                print("You mad yet bro?")

            counter += 1

        print("Brave Soul, congratulations!")
        print("Now you know the hard works a VQE has to do right?")
コード例 #8
0
ファイル: circuit.py プロジェクト: xkykai/Imperial-go-brrr
 def run(self):
     provider = IonQProvider(token=self.__API_KEY)
     backend = provider.get_backend("ionq_qpu")
     job = backend.run(self.get_circuit(), shots=1)
     return job.result()
コード例 #9
0
ファイル: circuit.py プロジェクト: xkykai/Imperial-go-brrr
 def simulate(self):
     provider = IonQProvider(token=self.__API_KEY)
     backend = provider.get_backend("ionq_simulator")
     job = backend.run(self.get_circuit(), shots=100)
     return job.result()
コード例 #10
0
def loop():
    global alice_hp
    global bob_hp
    global GAMMA
    global friendliness

    qc = QuantumCircuit(3,3)
    j_hat = np.matrix(scipy.linalg.expm(
        np.kron(-1j * GAMMA * d_hat, d_hat / 2)))
#    qc.unitary(Operator(j_hat), [0, 1], label="Friendship")
    qc.rx(-np.pi/2,2)
    qc.cx(2,0)
    qc.cx(2,1)

    def defect(q):
        qc.x(q)     #Defecting is just a \sigma_x now
#        qc.z(q)

    def quantum(q):
        qc.y(q)
        qc.x(q)

    def exec_gate(q, gate):
        for g in gate:
            if g == 'Z':
                qc.z(q)
            elif g == 'Y':
                qc.y(q)
            elif g == 'X':
                qc.x(q)
            elif g == 'H':
                qc.h(q)
            elif g == 'T':
                qc.t(q)
            elif g == 'S':
                qc.s(q)

    def prompt(q):
        clear_screen()
        print_header(should_crawl=False)
        options = tuple(random.sample(OPTION_NAMES, 3))

        while True:
            print("\nWhat will {} do?".format(
                alice_name if q == 0 else bob_name))

            print("[1] Fight\t[2] Heal\t[3] Befriend")
            print("[4] {}\t[5] {}\t[6] {}".format(*options))

            result = input(bcolors.WARNING + ">>> " + bcolors.ENDC)
            try:
                i = int(result) - 1
                if i == 0:
                    defect(q)
                    return "Fight"
                elif i == 1:
                    return "Heal"
                elif i == 2:
                    quantum(q)
                    return "Befriend"
                else:
                    exec_gate(q, rand_gates[options[i - 3]])
                    return options[i - 3]
            except (ValueError, IndexError):
                print("Please enter an option number.")
                continue

    if random.choice([True, False]):
        alice_move = prompt(0)
        bob_move = prompt(1)
    else:
        bob_move = prompt(1)
        alice_move = prompt(0)
    clear_screen()

#    qc.unitary(Operator(j_hat.H), [0, 1], label="Battle")
    qc.cx(2,1)
    qc.cx(2,0)
    qc.rx(np.pi/2,2)
    
    qc.measure(range(3),range(3))

    msg = ""
    msg += "{} used {}{}!\n".format(alice_name, alice_move,
                                    " to heal 5 HP" if alice_move == "Heal" else "")
    msg += "{} used {}{}!\n".format(bob_name, bob_move,
                                    " to heal 5 HP" if bob_move == "Heal" else "")

    if alice_move == "Heal":
        alice_hp += 5
    if bob_move == "Heal":
        bob_hp += 5
    bob_hp = min(bob_hp, 100)
    alice_hp = min(alice_hp, 100)
    
    shots=1000
    provider = IonQProvider(token='token')
    backend = provider.get_backend("ionq_simulator")
    job = backend.run(qc, shots=1000)
#    backend = Aer.get_backend('qasm_simulator')
#    job = execute(qc, backend,shots=shots)
    result = job.result().get_counts()

    alice_exp = 0
    bob_exp = 0

    for outcome, prob in result.items():
        prob=prob/shots
        alice, bob = int(outcome[2]), int(outcome[1])  #These numbers have been changed to incorporate the extra qubit added
        alice, bob = payoff(alice, bob)
        alice_exp += prob * alice
        bob_exp += prob * bob

    if alice_move == "Befriend" and bob_move not in ("Befriend", "Heal") \
            and alice_exp > bob_exp or bob_move == "Befriend" \
            and alice_move not in ("Befriend", "Heal") and bob_exp > alice_exp:
        msg += bcolors.OKCYAN + bcolors.BOLD + \
            "It's the power of friendship!\n" + bcolors.ENDC

    if alice_exp == bob_exp:
        if alice_exp > 0:
            msg += bcolors.OKGREEN + \
                "It's a draw! Both sides heal {:.2f} HP!{}\n".format(
                    alice_exp, bcolors.ENDC)
        else:
            msg += bcolors.FAIL + \
                "It's a draw! Both sides take {:.2f} HP damage!{}\n".format(
                    abs(alice_exp), bcolors.ENDC)
        bob_hp += bob_exp
        alice_hp += alice_exp

    elif alice_exp > bob_exp:
        msg += bcolors.FAIL + "{} hits {} for {:.2f} HP damage!{}\n".format(
            alice_name, bob_name, alice_exp - bob_exp, bcolors.ENDC)
        bob_hp -= alice_exp - bob_exp
    else:
        msg += bcolors.FAIL + "{} hits {} for {:.2f} HP damage!{}\n".format(
            bob_name, alice_name, bob_exp - alice_exp, bcolors.ENDC)
        alice_hp -= bob_exp - alice_exp

    bob_hp = max(0, min(bob_hp, 100))
    alice_hp = max(0, min(alice_hp, 100))

    print_hp()
    print(qc)
    print("")
    crawl(msg)

    if alice_hp <= 0 or bob_hp <= 0:
        game_over()
        sys.exit(0)

    friendliness = min(max(abs(alice_hp - bob_hp) / 50,
                           1 - max(alice_hp, bob_hp) / 50), 1)
    GAMMA = friendliness * np.pi / 2

    time.sleep(2)
    clear_screen()
    print_header()
コード例 #11
0
import asyncio
from pathlib import Path

from qiskit import Aer
from qiskit_ionq_provider import IonQProvider 

import random

from qmc.utils import to_thread

with open(Path(__file__).parent / "API_KEY") as key_file:
    key = key_file.read().strip()

provider = IonQProvider(token=key)

class Backend:
    """The base Backend class"""

def _run_ionq_simulator(qc):
    backend = provider.get_backend("ionq_simulator")
    job = backend.run(qc, shots=2)
    result = job.result().get_counts().keys()
    if len(result) == 1:
        return list(result)[0]
    else:
        return random.choice(list(result))

class SimulatorBackend(Backend):
    async def schedule_execution(self, qc):
        result = await to_thread(_run_ionq_simulator, qc)
        return result