Exemplo n.º 1
0
    def __enter__(self):
        '''
        Enter context,

        Attributes:
            eng (MainEngine): main engine.
            backend ('graphical' or 'simulate'): backend used.
            qureg (Qureg): quantum register.
        '''
        if self.task == 'ibm':
            import projectq.setups.ibm
        else:
            import projectq.setups.default

        # create a main compiler engine with a specific backend:
        if self.task == 'draw':
            self.backend = CircuitDrawer()
            # locations = {0: 0, 1: 1, 2: 2, 3:3} # swap order of lines 0-1-2.
            # self.backend.set_qubit_locations(locations)
        elif self.task == 'simulate':
            print(
                'ProjecQ simulation in training can be slow, since in scipy context, we cached a lot gates.'
            )
            self.backend = Simulator(gate_fusion=True)
        elif self.task == 'ibm':
            # choose device
            device = self.ibm_config.get(
                'device', 'ibmqx2' if self.num_bit <= 5 else 'ibmqx5')
            # check data
            if self.ibm_config is None:
                raise
            if device == 'ibmqx5':
                device_num_bit = 16
            else:
                device_num_bit = 5
            if device_num_bit < self.num_bit:
                raise AttributeError(
                    'device %s has not enough qubits for %d bit simulation!' %
                    (device, self.num_bit))

            self.backend = IBMBackend(use_hardware=True,
                                      num_runs=self.ibm_config['num_runs'],
                                      user=self.ibm_config['user'],
                                      password=self.ibm_config['password'],
                                      device=device,
                                      verbose=True)
        else:
            raise ValueError('engine %s not defined' % self.task)
        self.eng = MainEngine(self.backend)
        # initialize register
        self.qureg = self.eng.allocate_qureg(self.num_bit)
        return self
    def is_available(self, cmd):
        """
        Check if the IBM backend can perform the Command cmd and return True if so.

        Args:
            cmd (Command): The command to check
        """
        return IBMBackend().is_available(cmd)
Exemplo n.º 3
0
 def initialize_quantum_engine(self):
     """
     Quantum Engine Initializer
     (pass credentials namedtuple to use IBM's Quantum Computer with your username and password, otherwise will simulate locally)
     """
     if self.credentials:
         quantum_engine = MainEngine(
             IBMBackend(user=self.credentials.username,
                        password=self.credentials.password,
                        use_hardware=self.remote_hardware),
             engine_list=projectq.setups.ibm.get_engine_list())
     else:
         quantum_engine = MainEngine()
     return quantum_engine
Exemplo n.º 4
0
    # allocate the quantum register to entangle
    qureg = eng.allocate_qureg(num_qubits)

    # entangle the qureg
    Entangle | qureg

    # measure; should be all-0 or all-1
    All(Measure) | qureg

    # run the circuit
    eng.flush()

    # access the probabilities via the back-end:
    results = eng.backend.get_probabilities(qureg)
    for state in results:
        print("Measured {} with p = {}.".format(state, results[state]))

    # return one (random) measurement outcome.
    return [int(q) for q in qureg]


if __name__ == "__main__":
    # create main compiler engine for the IBM back-end
    eng = MainEngine(IBMBackend(use_hardware=False,
                                num_runs=1024,
                                verbose=False,
                                device='ibmqx4'),
                     engine_list=projectq.setups.ibm.get_engine_list())
    # run the circuit and print the result
    print(run_entangle(eng))
Exemplo n.º 5
0
import projectq.setups.ibm
from projectq.ops import H, Measure
from projectq import MainEngine
from projectq.backends import IBMBackend

# create a main compiler engine
eng = MainEngine(IBMBackend(True))

# allocate one qubit
q1 = eng.allocate_qubit()

# put it in superposition
H | q1

# measure
Measure | q1

eng.flush()
# print the result:
print("Measured: {}".format(int(q1)))
# -*- coding: utf-8 -*-
# pylint: skip-file
"""Example of a simple quantum random number generator using IBM's API."""

import projectq.setups.ibm
from projectq import MainEngine
from projectq.backends import IBMBackend
from projectq.ops import H, Measure

# create a main compiler engine
eng = MainEngine(IBMBackend(),
                 engine_list=projectq.setups.ibm.get_engine_list())

# allocate one qubit
q1 = eng.allocate_qubit()

# put it in superposition
H | q1

# measure
Measure | q1

eng.flush()
# print the result:
print("Measured: {}".format(int(q1)))
Exemplo n.º 7
0
from projectq import MainEngine  # import the main compiler engine
from projectq.ops import H, Measure  # import the operations we want to perform (Hadamard and measurement)
from projectq.backends import IBMBackend
import os

# extract IBM Quantum Experience login details from environ
ibmqe_user = os.environ.get('IBMQE_USER')
ibmqe_password = os.environ.get('IBMQE_PASSWORD')

# login to IBM and instantiate the quantumEngine object
compiler_engines = ibm_setup.get_engine_list()
eng = MainEngine(IBMBackend(use_hardware=True,
                            num_runs=1024,
                            verbose=False,
                            user=ibmqe_user,
                            password=ibmqe_password,
                            device='ibmqx5',
                            num_retries=3000,
                            interval=1,
                            retrieve_execution=None),
                 engine_list=compiler_engines)

# allocate a quantum register with 1 qubit
qubit = eng.allocate_qubit()

# apply a Hadamard gate to put in super position
H | qubit

# measure the qubit
Measure | qubit
Exemplo n.º 8
0
            All(H) | [qureg[e[0]], qureg[e[1]]]
            CNOT | (qureg[e[0]], qureg[e[1]])
            All(H) | [qureg[e[0]], qureg[e[1]]]
        else:
            CNOT | (qureg[e[0]], qureg[e[1]])

    # measure; should be all-0 or all-1
    Measure | qureg

    # run the circuit
    eng.flush()

    # access the probabilities via the back-end:
    results = eng.backend.get_probabilities(qureg)
    for state, probability in sorted(list(results.items())):
        print("Measured {} with p = {}.".format(state, probability))

    # return one (random) measurement outcome.
    return [int(q) for q in qureg]


if __name__ == "__main__":
    # create main compiler engine for the 16-qubit IBM back-end
    eng = MainEngine(
        IBMBackend(use_hardware=True,
                   num_runs=1024,
                   verbose=False,
                   device='ibmqx5'))
    # run the circuit and print the result
    print(run_test(eng))
Exemplo n.º 9
0
    histogram(eng.backend, qureg)
    plt.show()

    # return one (random) measurement outcome.
    return [int(q) for q in qureg]


if __name__ == "__main__":
    #devices commonly available :
    # ibmq_16_melbourne (15 qubit)
    # ibmq_essex (5 qubit)
    # ibmq_qasm_simulator (32 qubits)
    # and plenty of other 5 qubits devices!
    #
    # To get a token, create a profile at:
    # https://quantum-computing.ibm.com/
    #
    device = None # replace by the IBM device name you want to use
    token = None  # replace by the token given by IBMQ
    if token is None:
        token = getpass.getpass(prompt='IBM Q token > ')
    if device is None:
        device = getpass.getpass(prompt='IBM device > ')
    # create main compiler engine for the IBM back-end
    eng = MainEngine(IBMBackend(use_hardware=True, token=token, num_runs=1024,
                                verbose=False, device=device),
                     engine_list=projectq.setups.ibm.get_engine_list(
                         token=token, device=device))
    # run the circuit and print the result
    print(run_entangle(eng))
Exemplo n.º 10
0
    Returns:
        measurement (list<int>): List of measurement outcomes.
    """
    # allocate the quantum register to entangle
    qureg = eng.allocate_qureg(num_qubits)

    # entangle the qureg
    Entangle | qureg

    # measure; should be all-0 or all-1
    Measure | qureg

    # run the circuit
    eng.flush()

    # access the probabilities via the back-end:
    results = eng.backend.get_probabilities(qureg)
    for state in results:
        print("Measured {} with p = {}.".format(state, results[state]))

    # return one (random) measurement outcome.
    return [int(q) for q in qureg]


if __name__ == "__main__":
    # create main compiler engine for the IBM back-end
    eng = MainEngine(
        IBMBackend(use_hardware=True, num_runs=1024, verbose=False))
    # run the circuit and print the result
    print(run_entangle(eng))
Exemplo n.º 11
0
class ProjectQContext(object):
    '''
    Context for running circuits.

    Args:
        num_bit (int): number of bits in register.
        task ('ibm'|'draw'|'simulate'): task that decide the environment type.
        ibm_config (dict): extra arguments for IBM backend.
    '''

    def __init__(self, num_bit, task, ibm_config=None):
        self.task = task
        self.num_bit = num_bit
        self.ibm_config = ibm_config

    def __enter__(self):
        '''
        Enter context,

        Attributes:
            eng (MainEngine): main engine.
            backend ('graphical' or 'simulate'): backend used.
            qureg (Qureg): quantum register.
        '''
        if self.task=='ibm':
            import projectq.setups.ibm
        else:
            import projectq.setups.default

        # create a main compiler engine with a specific backend:
        if self.task == 'draw':
            self.backend = CircuitDrawer()
            # locations = {0: 0, 1: 1, 2: 2, 3:3} # swap order of lines 0-1-2.
            # self.backend.set_qubit_locations(locations)
        elif self.task == 'simulate':
            print('ProjecQ simulation in training can be slow, since in scipy context, we cached a lot gates.')
            self.backend = Simulator()
        elif self.task == 'ibm':
            # choose device
            device = self.ibm_config.get('device', 'ibmqx2' if self.num_bit<=5 else 'ibmqx5')
            # check data
            if self.ibm_config is None:
                raise
            if device == 'ibmqx5':
                device_num_bit = 16
            else:
                device_num_bit = 5
            if device_num_bit < self.num_bit:
                raise AttributeError('device %s has not enough qubits for %d bit simulation!'%(device, self.num_bit))

            self.backend = IBMBackend(use_hardware=True, num_runs=self.ibm_config['num_runs'],
                    user=self.ibm_config['user'],
                    password=self.ibm_config['password'],
                    device=device, verbose=True)
        else:
            raise ValueError('engine %s not defined' % self.task)
        self.eng = MainEngine(self.backend)
        # initialize register
        self.qureg = self.eng.allocate_qureg(self.num_bit)
        return self

    def __exit__(self, exc_type, exc_val, traceback):
        '''
        exit, meanwhile cheat and get wave function.

        Attributes:
            wf (1darray): for 'simulate' task, the wave function vector.
            res (1darray): for 'ibm' task, the measurements output.
        '''
        if traceback is not None:
            return False
        if self.task == 'draw':
            self._viz_circuit()
        elif self.task == 'simulate':
            self.eng.flush()
            order, qvec = self.backend.cheat()
            self.wf = np.array(qvec)
            order = [order[i] for i in range(len(self.qureg))]
            self.wf = np.transpose(self.wf.reshape([2]*len(self.qureg), order='F'), axes=order).ravel(order='F')
            Measure | self.qureg
            self.eng.flush()
        elif self.task == 'ibm':
            Measure | self.qureg
            self.eng.flush()
            self.res = self.backend.get_probabilities(self.qureg)
        else:
            raise
        return self

    def _viz_circuit(self):
        Measure | self.qureg
        self.eng.flush()
        # print latex code to draw the circuit:
        s = self.backend.get_latex()

        # save graph to latex file
        os.chdir(TEX_FOLDER)
        with open(TEX_FILENAME, 'w') as f:
            f.write(s)

        # texfile = os.path.join(folder, 'circuit-%d.tex'%bench_id)
        pdffile = TEX_FILENAME[:-3]+'pdf'
        os.system('pdflatex %s'%TEX_FILENAME)
        openfile(pdffile)
Exemplo n.º 12
0
def main():

    args = _define_args()

    args = args.parse_args()

    _check(args)

    fin = args.infile
    fout = args.outfile

    engines = ibm.get_engine_list()

    # remove the CNot flipper
    if not args.ibm:
        engines = engines[:-2] + engines[-1:]
        print('Converting...')
    else:
        print('Converting for IBM Q Experience...')

    if args.on_hardware:
        print('We will run the converted code on the IBM device {}\n.'.format(
            args.ibm))
        backend = IBMBackend(use_hardware=True,
                             device=args.ibm,
                             num_runs=args.n)
    elif args.s:
        print('We will run the converted code on the IBM simulator\n.')
        backend = IBMBackend(use_hardware=False,
                             device=args.ibm,
                             num_runs=args.n)
    else:
        # backend similar to IBMBackend creating qasm code but without running it
        backend = GetQASMBackend()

    eng = MainEngine(backend=backend, engine_list=engines)

    s = fin.read()
    fin.close()

    # parse input
    root = grammar.parse(s)
    # create visitor that transforms tree into gate list
    visitor = ToGateListVisitor()
    # pass root of parsed tree to visitor
    gate_list = visitor.visit(root)
    #gate_list=flatten_touples(gate_list)

    # create circuit from gate_list
    nb_qubits = build_circuit(gate_list, eng)
    # create qasm code
    qasm = get_qasm(eng, nb_qubits)

    if fout == sys.stdout:
        print(5 * '=' + ' OpenQASM code ' + 5 * '=')

    fout.write(qasm)

    if fout != sys.stdout:
        print('OpenQASM output saved to {}'.format(fout.name))
    print()

    if hasattr(backend, 'get_probabilities'):
        print(5 * '=' + ' Results from {} run on hardware '.format(args.n) +
              5 * '=')
        for k, v in sorted(backend.get_probabilities(qureg).items()):
            print('Probability for state |{}>: {}'.format(k, v))
Exemplo n.º 13
0
molecule = run_pyscf(molecule,
                     run_scf=run_scf,
                     run_mp2=run_mp2,
                     run_cisd=run_cisd,
                     run_ccsd=run_ccsd,
                     run_fci=run_fci)

# Use a Jordan-Wigner encoding, and compress to remove 0 imaginary components
qubit_hamiltonian = jordan_wigner(molecule.get_molecular_hamiltonian())
qubit_hamiltonian.compress()
# compiler_engine = uccsd_trotter_engine(CommandPrinter())
compiler_engine = uccsd_trotter_engine(
    compiler_backend=IBMBackend(user="******",
                                password="******",
                                use_hardware=False,
                                num_runs=1024,
                                verbose=False))

n_amplitudes = uccsd_singlet_paramsize(molecule.n_qubits, molecule.n_electrons)
initial_amplitudes = [0.01] * n_amplitudes
energy_objective(initial_amplitudes)

# # Run VQE Optimization to find new CCSD parameters
# opt_result = minimize(energy_objective, initial_amplitudes,
#                       method="CG", options={'disp':True})
#
# opt_energy, opt_amplitudes = opt_result.fun, opt_result.x
#
# print("\n Results for {}:".format(molecule.name))
# print("Optimal UCCSD Singlet Energy: {}".format(opt_energy))
Exemplo n.º 14
0
    parser.add_argument("--number",
                        action="store",
                        default=10,
                        dest="input_number",
                        help="select the number to factor")
    myarg = parser.parse_args()

    # GET VARIABLES FROM CK_ENV
    verbose = os.getenv('CK_VERBOSE', False)
    ibm_device = os.getenv('CK_PROJECTQ_IBM_DEVICE', "IBM_OFF")
    print(ibm_device)

    if ibm_device in ["ibmqx2", "ibmqx4", "ibmqx5"]:
        print("IBM Backend")
        eng = MainEngine(IBMBackend(use_hardware=False,
                                    num_runs=1,
                                    device=ibm_device),
                         setup=projectq.setups.ibm)
    else:
        # make the compiler and run the circuit on the simulator backend
        eng = MainEngine(Simulator(gate_fusion=False), compilerengines)

    # print welcome message and ask the user for the number to factor
    print(
        "\n\t\033[37mprojectq\033[0m\n\t--------\n\tImplementation of Shor"
        "\'s algorithm.",
        end="")

    #    N = int(input('\n\tNumber to factor: '))
    N = int(myarg.input_number)
    print("\n\tFactoring N = {}: \033[0m".format(N), end="")
Exemplo n.º 15
0
from projectq.ops import H, Measure, StatePreparation
from projectq import MainEngine
import projectq.setups.ibm
from projectq.backends import IBMBackend

#Intialization
ME = MainEngine(IBMBackend(), projectq.setups.ibm.get_engine_list())
rand_list = []


#random integer generation using 1 qubit and Hadamard gate
def getrandomquantum(mainengine):
    qubit = mainengine.allocate_qubit()
    H | qubit
    Measure | qubit
    rand_int = int(qubit)
    rand_list.append(rand_int)


for i in range(10):
    getrandomquantum(ME)

#Flush gates
ME.flush()
print(rand_list)
Exemplo n.º 16
0
import math, numpy, random, time, getpass  # normal python stuff

from projectq import MainEngine  # import the main compiler engine
from projectq.ops import H, S, T, X, CNOT, Entangle, get_inverse, Measure  # import the operations we want to perform

import projectq.setups.ibm
from projectq.backends import IBMBackend

eng = MainEngine(
    IBMBackend(use_hardware=True,
               num_runs=1024,
               verbose=False,
               user=None,
               password=None))

print("\n\n\n\n===== Welcome to Quantum Battleships! =====\n\n")
print("  ~~ A game by the Decodoku project ~~ ")
print("\n\n")
print("When in doubt, press any key to continue!")
raw_input()
print("This is a game for two players.")
raw_input()
print("Player 1 will choose the position of a Battleship.")
raw_input()
print("Player 2 will try to bomb it.")
raw_input()

# get player 1 to position boat
print("We start with Player 1.")
print("Look away Player 2!")
raw_input()
Exemplo n.º 17
0
import os
from pathlib import Path

import projectq.setups.ibm  # Imports the default compiler to map to IBM QE
from dotenv import load_dotenv
from projectq.backends import IBMBackend
from projectq.ops import All, Entangle, Measure
from projectq import MainEngine

try:
    current_path = Path('.') / '.env'
    load_dotenv(current_path)
    token = os.environ['IBM_QUANTUM_API_KEY']
    device = device = 'ibmq_rome'
    compiler_engines = projectq.setups.ibm.get_engine_list(token=token,
                                                           device=device)
    engine = MainEngine(IBMBackend(token=token,
                                   use_hardware=True,
                                   num_runs=1024,
                                   verbose=True,
                                   device=device),
                        engine_list=compiler_engines)
    qureg = engine.allocate_qureg(3)
    Entangle | qureg
    All(Measure) | qureg
    engine.flush()
    print([int(q) for q in qureg])
except KeyError:
    print("Please define the environment variables: IBM_QUANTUM_API_KEY")