Exemplo n.º 1
0
def printCircuit(packed_amplitudes):
   compiler_engine = uccsd_trotter_engine(CommandPrinter())
   wavefunction = compiler_engine.allocate_qureg(4)
   for i in range(2):
      X | wavefunction[i]
   evolution_op = uccsd_singlet_evolution(packed_amplitudes, 4, 2)
   evolution_op | wavefunction
   compiler_engine.flush()
   return
Exemplo n.º 2
0
def test_or():
    a = Debugger()
    engine_list = [a]
    eng = projectq.MainEngine(engine_list=engine_list,
                              backend=CommandPrinter())
    q1 = eng.allocate_qubit()
    q2 = eng.allocate_qubit()

    ParityMeasurementGate("Z0 X1") | q1 + q2

    assert (a.commands[-1].gate._bases[0][0] == 0)
    assert (a.commands[-1].gate._bases[0][1] == "Z")
Exemplo n.º 3
0
def _eng_emulation():
    # Only decomposing native ProjectQ gates
    # -> using emulation for gates in projectq.libs.math
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    eng = MainEngine(
        engine_list=[
            TagRemover(),
            AutoReplacer(rule_set),
            TagRemover(),
            CommandPrinter(),
        ],
        verbose=True,
    )
    return eng
Exemplo n.º 4
0
def test_decomposition():
    a = Debugger()
    decomp = DecompositionRuleSet(
        modules=[projectq.setups.decompositions.parity_measurement])
    engine_list = [AutoReplacer(decomp), InstructionFilter(is_supported), a]
    eng = projectq.MainEngine(engine_list=engine_list,
                              backend=CommandPrinter(accept_input=False))
    q1 = eng.allocate_qubit()
    q2 = eng.allocate_qubit()

    ParityMeasurementGate("Z0 X1") | q1 + q2

    print(a.commands)
    #TODO
    #assert(a.commands[-1].gate._bases[0][0] == 0)
    #assert(a.commands[-1].gate._bases[0][1] == "Z")
    assert (False)
Exemplo n.º 5
0
def _eng_decomp():
    def no_math_emulation(eng, cmd):
        if isinstance(cmd.gate, BasicMathGate):
            return False
        if isinstance(cmd.gate, ClassicalInstructionGate):
            return True
        try:
            return len(cmd.gate.matrix) > 0
        except AttributeError:
            return False

    rule_set = DecompositionRuleSet(modules=[projectq.libs.math, projectq.setups.decompositions.qft2crandhadamard])
    eng = MainEngine(
        engine_list=[
            TagRemover(),
            AutoReplacer(rule_set),
            InstructionFilter(no_math_emulation),
            TagRemover(),
            CommandPrinter(),
        ]
    )
    return eng
Exemplo n.º 6
0
from projectq.ops import X, Y, Z, T, H, CNOT, SqrtX, All, Measure
from hiq.projectq.backends import SimulatorMPI
from hiq.projectq.cengines import GreedyScheduler, HiQMainEngine
from projectq.backends import CommandPrinter
from projectq.setups.default import get_engine_list

import numpy as np
import random
import copy
from mpi4py import MPI

# Create main engine to compile the code to machine instructions(required)
#eng = HiQMainEngine(SimulatorMPI(gate_fusion=True, num_local_qubits=20))
eng = HiQMainEngine(engine_list=get_engine_list() + [CommandPrinter()])

# Qubit number N
num_of_qubit = 5

#Circuit Depth
depth = 30

# Gate
gate_set = [X, Y, Z, T, H, SqrtX, CNOT]

# Use the method provided by the main engine to create qubit registers
qureg = eng.allocate_qureg(num_of_qubit)

for i in range(depth):

    #Pick random gate from gate_set
    chosen_gate = random.sample(gate_set, 1)
Exemplo n.º 7
0
    # print(sum(wave_func.conj() * target_state))
    circuit = "; ".join(output)
    return circuit.replace("Qureg", "qubit")


if __name__ == "__main__":
    backend = SimulatorMPI(gate_fusion=True)
    cache_depth = 10
    rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
    engines = [
        TagRemover(),
        LocalOptimizer(cache_depth),
        AutoReplacer(rule_set),
        TagRemover(),
        LocalOptimizer(cache_depth),
        GreedyScheduler(),
        CommandPrinter()
    ]
    eng = HiQMainEngine(backend, engines)
    qureg = eng.allocate_qureg(5)

    target_state = np.random.rand(2**5) + np.random.rand(2**5) * 1.j
    target_state = target_state / np.linalg.norm(target_state)

    mapper = "5\n0,1\n1,2\n1,3\n2,3\n2,4\n3,4"
    circuit = circuit_generator(eng, target_state, mapper)

    All(Measure) | qureg

    print(circuit)
Exemplo n.º 8
0
    return output


if __name__ == '__main__':

    N = 15
    n = int(np.ceil(np.log2(N)))

    a = shor.find_co_prime_stochastic(N)
    if a < 0:
        print("Factor is", -a)
        exit(0)
    print("a =", a)
    nx = n + 1

    circuit_backend = CommandPrinter()
    qi_engine = MainEngine(circuit_backend)

    circuit = Circuit()
    circuit.create_bus(qi_engine, n + 2)
    circuit.add_all_logicals(qi_engine)

    output = None
    if cache_file is None:
        output = capture_output_mod(circuit, qi_engine, a, nx, N, n)
        f = open("../../cached/" + str(uuid.uuid4()) + ".cache", "w+")
        f.write(output)
        f.close()
        print("Amount of gate operations:", circuit.gates_applied)
        print("Amount of single gate operations:", circuit.single_applied)
        print("Amount of two qubit operations:", circuit.two_applied)
Exemplo n.º 9
0
                         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
    molecular_hamiltonian = molecule.get_molecular_hamiltonian(
        occupied_indices=range(active_space_start),
        active_indices=range(active_space_start, active_space_stop))

    fermion_hamiltonian = get_fermion_operator(molecular_hamiltonian)
    print(fermion_hamiltonian)
    qubit_hamiltonian = jordan_wigner(fermion_hamiltonian)

    qubit_hamiltonian.compress()
    compiler_engine = uccsd_trotter_engine(CommandPrinter())
    initial_energy = energy_objective(opt_amplitudes)

    # Run VQE Optimization to find new CCSD parameters
    opt_result = minimize(energy_objective, opt_amplitudes,
                          method="a", options={'disp':True})

    opt_energy, opt_amplitudes = opt_result.fun, opt_result.x

    fci_energies += [float(molecule.fci_energy)]
    UCCSD_energies += [float(opt_energy)]

    # Print Results
    print("\nResults for {}:".format(molecule.name))
    print("Optimal UCCSD Singlet Energy: {}".format(opt_energy))
    print("Exact FCI Energy: {} Hartrees".format(molecule.fci_energy))
Exemplo n.º 10
0
temp = LocalOptimizer(cache_depth)
engines = [
    TagRemover(), temp,
    AutoReplacer(rule_set),
    TagRemover(),
    LocalOptimizer(cache_depth),
    GreedyScheduler()
]

# create a list of restriction engines
restric_engine = restrictedgateset.get_engine_list(one_qubit_gates=(X, Y, Z, H,
                                                                    S, T, Rx,
                                                                    Ry, Rz),
                                                   two_qubit_gates=(CZ, CX))

eng = HiQMainEngine(backend, engine_list=engines + [CommandPrinter()])


class SqrtYGate(BasicGate):
    """ Square-root X gate class """
    @property
    def matrix(self):
        return (0.5 + 0.5j) * np.matrix([[1, -1], [1, 1]])

    def tex_str(self):
        return r'$\sqrt{Y}$'

    def __str__(self):
        return "SqrtY"

    def get_merged(self, other):
Exemplo n.º 11
0
#!/usr/bin/env python3
from projectq import MainEngine
from projectq.backends import CommandPrinter, Simulator
from projectq.setups import restrictedgateset
from projectq.ops import X, Z, H, Ry, Rz, CNOT, All, Measure

# set restricted gate-set
restricted_list = restrictedgateset.get_engine_list(one_qubit_gates=(Rz, Ry),
                                                    two_qubit_gates=(CNOT, ),
                                                    other_gates=())
# set engine
restricted_compiler = MainEngine(backend=CommandPrinter(accept_input=False),
                                 engine_list=restricted_list)

#  print qasm
printqasm = MainEngine(backend=CommandPrinter(accept_input=False))
# specify simulate locally
simulate = MainEngine(backend=Simulator())


def qprogram(eng):
    q = eng.allocate_qureg(8)

    # Q in binary: '01010001'
    # recall H Z H is X
    H | q[1]
    Z | q[1]
    H | q[1]

    X | q[3]
    X | q[7]
Exemplo n.º 12
0
rule_set = DecompositionRuleSet(modules=[projectq.setups.decompositions])
engines = [
    TagRemover(),
    LocalOptimizer(cache_depth),
    AutoReplacer(rule_set),
    TagRemover(),
    LocalOptimizer(cache_depth),
    GreedyScheduler()
]

# create a list of restriction engines
restric_engine = restrictedgateset.get_engine_list(one_qubit_gates=(X, Y, Z, H,
                                                                    S, T, Rx,
                                                                    Ry, Rz),
                                                   two_qubit_gates=(CZ, CX))

eng = HiQMainEngine(backend,
                    engine_list=restric_engine + engines + [CommandPrinter()])
qureg = eng.allocate_qureg(2)

H | qureg[0]
with Control(eng, qureg[0]):
    Rx(np.pi / 2) | qureg[1]
eng.flush(
)  # In order to have all the above gates sent to the simulator and executed
mapping, wavefunc = copy.deepcopy(eng.backend.cheat())

All(Measure) | qureg

print(wavefunc)
print(mapping)
Exemplo n.º 13
0
from openfermionprojectq import uccsd_trotter_engine, uccsd_singlet_evolution
from projectq.backends import CommandPrinter
from projectq.ops import X

from example2 import molecule

compiler_engine = uccsd_trotter_engine(compiler_backend=CommandPrinter())
wavefunction = compiler_engine.allocate_qureg(molecule.n_qubits)
test_amplitudes = [-1.03662149e-08, 5.65340580e-02]
evolution_operator = uccsd_singlet_evolution(test_amplitudes,
                                             molecule.n_qubits,
                                             molecule.n_electrons)
print('Sample output')
for i in range(molecule.n_electrons):
    X | wavefunction[i]
evolution_operator | wavefunction
compiler_engine.flush()
Exemplo n.º 14
0
#!/usr/bin/env python3

from projectq import MainEngine
from projectq.ops import X, Z, H, All, Measure
from projectq.backends import CommandPrinter
from projectq.backends import Simulator

# specify compiler
compiler = MainEngine(backend=CommandPrinter(accept_input=False))
# specify simulate locally
simulate = MainEngine(backend=Simulator())


def qprogram(eng):
    q = eng.allocate_qureg(8)

    # Q in binary
    # bitstring = '01010001'

    # recall H Z H is X
    H | q[1]
    Z | q[1]
    H | q[1]

    X | q[3]
    X | q[7]

    # measure all the qubits
    All(Measure) | q

    # execute the quantum program
Exemplo n.º 15
0
 def __init__(self, outStrIO, accept_input=True, default_measure=False,
              in_place=False):
     CommandPrinter.__init__(self)
     self.outStrIO = outStrIO