def approximate_via_cnots(unitary):
    dim = unitary.shape[0]
    n_qubits = int(math.log(dim, 2))
    converter.n_qubits = n_qubits
    r = RewriteTket(Circuit(n_qubits), [], [])
    r.set_target_unitary(unitary)
    # cnot_circuit = approximate_with_cnots(unitary)
    cnot_circuit = qft3
    # print(dag_to_circuit(tk_to_dagcircuit(cnot_circuit)))
    n_params = (cnot_circuit.n_gates * 2 + n_qubits) * 3

    def distance(params):
        f = r.fidelity(add_params_to_template(cnot_circuit, params))
        return (1 - max(0, f)**0.5)**0.5

    best_distance = 1
    best_circ = None
    for _ in range(10):
        initial = np.random.random((n_params, ))
        res = scipy.optimize.minimize(distance,
                                      initial,
                                      method='SLSQP',
                                      options={'ftol': 0.01},
                                      callback=lambda x: print(distance(x)))
        if res.success and res.fun < best_distance:
            best_distance = res.fun
            best_circ = add_params_to_template(cnot_circuit, res.x)
            if res.fun < 0.01:
                return best_circ, best_distance
    return best_circ, best_distance
Exemplo n.º 2
0
def run_multiple_angles(n_qubits,
                        n_angles,
                        s,
                        noise1=[],
                        noise2=[],
                        rewriter=None):
    # Return average fidelity
    total = 0
    if rewriter is None:
        c = Circuit(n_qubits)
        rewriter = RewriteTket(c, noise1, noise2, verbose=False)
    for i in range(n_angles):
        circuit = pauli_gadget(i * 2 / n_angles, s, n_qubits)
        Transform.OptimisePauliGadgets().apply(circuit)
        rewriter.set_circuit_and_target(circuit)
        f = rewriter.fidelity(rewriter.instructions)
        total = total + f
    return total / n_angles
Exemplo n.º 3
0
def plot_angles(s):
    fid = ProcessFidelityFinder(len(s))
    rewriter = RewriteTket(Circuit(len(s)),
                           single_noise,
                           cnot_noise,
                           verbose=False)
    # backend = AerBackend(amplified_qiskit_model("ibmqx4", amplification=amplification))
    # backend = IBMQBackend("ibmq_5_tenerife")
    angles = [2 * i / 200 for i in range(101)]
    fidelities = []
    opt_fidelities = []
    for a in angles:
        print(a)
        #filename1 = "../metrics/data/sim_10/c" + str(a) + ".txt"
        #filename2 = "../metrics/data/sim_10/rounded" + str(a) + ".txt"
        # create files if they don't exist:
        #with open(filename1, "a+") as file:
        #    pass
        #with open(filename2, "a+") as file:
        #    pass
        #rewriter.set_circuit_and_target(pauli_gadget(a, s, len(s)))
        #f = rewriter.reduce()
        circ = pauli_gadget(a, s, len(s))
        rewriter.set_circuit_and_target(circ.copy())
        cleanup.apply(circ)
        f = rewriter.reduce()
        fidelities.append(f[0])
        opt_fidelities.append(f[1])
        #fidelities.append(fid.f_pro_simulated(circ.copy(), rewriter.target, backend, filename1))
        #print(fidelities[-1])
        #rewriter.reduce()
        #opt_fidelities.append(fid.f_pro_simulated(rewriter.circuit.copy(), rewriter.target, backend, filename2))
        #print(opt_fidelities[-1])
    plt.figure()
    line_orig, = plt.plot(angles, fidelities)
    line_reduced, = plt.plot(angles, opt_fidelities, r'--')
    plt.xlabel(r"$\alpha$ (multiples of $\pi$)")
    plt.ylabel("Fidelity of " + s + " gadget")
    plt.legend((line_orig, line_reduced), ("Original", "Rounded"),
               loc="upper left",
               bbox_to_anchor=(0.14, 0.95))
    plt.savefig("../graphs/gadget_" + s + "_ibm_sim_10.png")
    plt.close()
def simulated_annealing(unitary, n_layers):
    dim = unitary.shape[0]
    n_qubits = int(math.log(dim, 2))
    converter.n_qubits = n_qubits
    n_cnots = (n_layers // 2) * (n_qubits // 2) + ((n_qubits - 1) // 2) * (
        (n_layers + 1) // 2)
    r = RewriteTket(Circuit(n_qubits), [], [])
    r.set_target_unitary(unitary)
    skips = []
    circuit, distance = approximate_scipy(unitary, n_layers, r, [])
    for k in range(10):
        new_skip = random.choice([i for i in range(n_cnots) if i not in skips])
        print("maybe I will skip", new_skip)
        new_circ, new_d = approximate_scipy(unitary, n_layers, r,
                                            skips + [new_skip])
        if new_d <= distance:  # or random.random() < (1 - new_d + distance) / (5 * k + 1):
            print("skipping", new_skip)
            circuit, distance, skips = new_circ, new_d, skips + [new_skip]
        else:
            print("not skipping", new_skip)
        print(circuit.n_gates, circuit.n_gates_of_type(OpType.CX))
        if distance < 0.01:
            print("returning early", distance)
            return circuit, r.fidelity(circuit)
    print(distance)
    return circuit, r.fidelity(circuit)
Exemplo n.º 5
0
def run_multiple(n_qubits, n_iter):
    c = Circuit(n_qubits)
    rewriter = RewriteTket(c, single_noise, cnot_noise, verbose=False)
    rewriter.verbose = True
    for _ in range(n_iter):
        circuit = random_pauli_gadget(n_qubits)
        Transform.OptimisePauliGadgets().apply(circuit)
        rewriter.set_circuit_and_target(circuit)
        rewriter.reduce()
        print(rewriter.instructions)
        print("\n\n")
from tket_pauli_gadgets.tket_circuit_rewriter import RewriteTket
from tket_pauli_gadgets.process_matrix import ProcessMatrixFinder
from common_gates import random_unitary, U3_params, U3_derivative
import random
import cmath

random.seed(42)

n_qubits = 3
n_layers = 6 * 4**(n_qubits - 1) // n_qubits
converter.n_qubits = n_qubits
proc_finder = ProcessMatrixFinder(n_qubits, [], [])
unitary = random_unitary(n_qubits)
#qft
#unitary = np.array([[cmath.exp(complex(0, i * j * 2 * math.pi / (2 ** n_qubits))) for j in range(2 ** n_qubits)] for i in range(2 ** n_qubits)]) / 2 ** (n_qubits / 2)
r = RewriteTket(Circuit(n_qubits), [], [])
r.set_target_unitary(unitary)


def build_alternating_cnots_circuit(n_qubits, n_layers, params, skips=None):
    if skips is None:
        skips = []
    c = Circuit(n_qubits)
    cnot_count = 0
    cnots_full = 0
    for i in range(n_layers):
        if i % 2:
            for q in range(n_qubits // 2):
                if cnots_full not in skips:
                    c.add_operation(OpType.U3, params[2 * cnot_count], [2 * q])
                    c.add_operation(OpType.U3, params[2 * cnot_count + 1],
Exemplo n.º 7
0
def get_fid(s: str, angle: float, rewriter: RewriteTket):
    circuit = pauli_gadget(angle, s, len(s))
    cleanup.apply(circuit)
    rewriter.set_circuit_and_target(circuit)
    return rewriter.fidelity(rewriter.instructions)
Exemplo n.º 8
0
def run(n_qubits):
    circuit = random_gadget_circuit(n_qubits, 3)
    rewriter = RewriteTket(circuit, single_noise, cnot_noise, verbose=True)
    rewriter.reduce()
    print(rewriter.circuit.get_commands())
Exemplo n.º 9
0
def get_opt_fid(s: str, angle: float, rewriter: RewriteTket):
    rewriter.set_circuit_and_target(pauli_gadget(angle, s, len(s)))
    return rewriter.reduce()[1]
Exemplo n.º 10
0
from tket_pauli_gadgets.tket_circuit_rewriter import RewriteTket, cleanup
from tket_pauli_gadgets.noise_models import channels
from tket_pauli_gadgets.chem import get_circuit
import numpy as np
from pytket.qiskit import tk_to_dagcircuit
from qiskit.converters.dag_to_circuit import dag_to_circuit
import matplotlib.pyplot as plt

np.set_printoptions(edgeitems=10, linewidth=1000)

amplification = 10
single_noise, cnot_noise = channels(amplification=amplification)
params = [0, 0.05]

circ = get_circuit(params, 13)
rewriter = RewriteTket(circ, single_noise, cnot_noise, verbose=False)

fid_none = []
fid_tket = []
fid_opt = []

for i in range(13):
    print(i)
    short_circ = get_circuit(params, i)
    rewriter.set_circuit(short_circ.copy())
    rewriter.original_fidelity = rewriter.fidelity(rewriter.instructions)
    fid_none.append(rewriter.original_fidelity)
    rewriter.set_circuit(short_circ)
    f = rewriter.reduce()
    fid_tket.append(f[0])
    fid_opt.append(f[1])