def testPowerSpetraSlow(self):
     xs = 0.4  # fraction of slow currents in microcircuit
     xs_mode = 0.5  # fraction of slow currents from 4I to 4I
     dsd = 1.0
     circ = circuit.Circuit('microcircuit', analysis_type=None)
     I_new = circ.I.copy()
     # reduce indegrees from 4I to 4E
     I_new[2][3] = np.round(circ.I[2][3] * (1.0 - 0.15))
     Next_new = circ.Next.copy()
     # adjust external input to 4E
     Next_new[2] -= 300
     Next_new[2] *= (1.0 - 0.011)
     new_params = {
         'de_sd': circ.de * dsd,
         'di_sd': circ.di * dsd,
         'I': I_new,
         'Next': Next_new,
         'delay_dist': 'truncated_gaussian'
     }
     params = circ.params
     params.update(new_params)
     params['xs'] = np.ones((8, 8)) * xs
     params['xs_ext'] = np.ones(8) * xs
     params['xs'][3][3] = xs_mode
     circ = circuit.Circuit('microcircuit', params, fmax=500.0)
     freqs, power = circ.create_power_spectra()
     power_test = h5.load_h5(self.test_data, 'power_slow')
     assert (np.allclose(power_test, power, rtol=self.rtol, atol=self.atol))
Exemplo n.º 2
0
def inverse_qft(n, prepared=True, init_state=[]):
    qft_circuit = circuit.Circuit(n, prepared=prepared, init_state=init_state)

    # Reflect the qubits (the QFT swaps their order by default)
    qft_circuit.append_layer(swap_all(n))

    if n == 1:
        qft_circuit.append_layer("H")
        return qft_circuit

    for i in range(n):
        i = n - i - 1
        # Layers with the rotations
        for j in range(1, n - i):
            qft_circuit.append_layer(
                gates.CU(j + i, i, gates.R((-1) * 2 * gates.PI / (2**(j + 1))),
                         n))

        # Layer with the H gate
        current_layer = []
        for j in range(i):
            current_layer.append("I")

        current_layer.append("H")

        for j in range(n - i - 1):
            current_layer.append("I")

        qft_circuit.append_layer(*current_layer)

    return qft_circuit
def pair_double_sel(ps, pm, pg, eta, a0, a1, theta):
    """
    Create a entangled pair using the double selection
    distillation protocol. The EPL protocol is used in the intermediate
    entangled pairs used.

    Parameters
    ----------
    ps : single qubit gate error rate.
    pm : measurement error rate.
    pg : two qubit gate error rate.
    eta : detection efficiency.
    a0 : extra environmental error when electron spin is being operated.
    a1 : default environmental error.
    theta : determines how the states are initialized when generating remote
            entanglement.
    """
    cb = circuit_block.Blocks(ps, pm, pg, eta, a0, a1, theta)
    epl = pair_EPL(ps, pm, pg, eta, a0, a1, theta)

    double_sel = circuit.Circuit(a0=a0, a1=a1,
                                 circuit_block=cb.double_selection_ops,
                                 targets=[0, 1], ancillas1=[2, 3],
                                 ancillas2=[4, 5], sigma="Z")
    double_sel.add_circuit(circuit_block=cb.swap_pair,
                           pair=[0, 1])
    double_sel.add_circuit(circuit_block=epl.append_circuit)
    double_sel.add_circuit(circuit_block=epl.append_circuit)
    double_sel.add_circuit(circuit_block=cb.start_epl)

    return double_sel
Exemplo n.º 4
0
def borneC(pi, matrice, v=False):
    s = 0
    c = circuit.Circuit(pi, matrice)
    tc = c.resolve()
    if len(pi) == len(matrice[0]):
        #cas particulier ou pi est un ordonancement final
        return tc
    #amelioration tC prime
    c = circuit.Circuit2M(pi, matrice)
    tB = c.resolve()
    if v:
        print('matrice : ', matrice)
    machineA = matrice[0]
    machineB = matrice[1]
    machineC = matrice[2]
    tA = 0
    miniB = float("inf")
    miniAB = float("inf")
    for i in range(len(machineC)):
        if i not in pi:
            s += machineC[i]
            miniB = min(miniB, machineB[i])
            miniAB = min(miniAB, machineA[i] + machineB[i])
        else:
            tA += machineA[i]
    s += max(tc, tB + miniB, tA + miniAB)
    return s
Exemplo n.º 5
0
def generate_rep_bare_meas_ion(n_data,
                               stabilizer_list,
                               n_rounds,
                               even_spaced=True):
    '''
    '''

    n_stab = len(stabilizer_list) / 2

    rep_meas_circ = cir.Circuit()
    circ_I = generate_wait_circ(n_data)
    circ_I = cir.Encoded_Gate('WAIT', [circ_I]).circuit_wrap()
    rep_meas_circ.join_circuit(circ_I, False)

    for i in range(n_rounds):
        gate_nameX = 'SX_%i' % i
        stab_circX = generate_bare_meas_ion(n_data, stabilizer_list[:n_stab])
        stab_circX = cir.Encoded_Gate(gate_nameX, [stab_circX]).circuit_wrap()
        gate_nameZ = 'SZ_%i' % i
        stab_circZ = generate_bare_meas_ion(n_data, stabilizer_list[n_stab:])
        stab_circZ = cir.Encoded_Gate(gate_nameZ, [stab_circZ]).circuit_wrap()
        rep_meas_circ.join_circuit(stab_circX, False)
        rep_meas_circ.join_circuit(stab_circZ, False)

        if even_spaced:
            circ_I = generate_wait_circ(n_data)
            circ_I = cir.Encoded_Gate('WAIT', [circ_I]).circuit_wrap()
            rep_meas_circ.join_circuit(circ_I, False)

    if not even_spaced:
        circ_I = generate_wait_circ(n_data)
        circ_I = cir.Encoded_Gate('WAIT', [circ_I]).circuit_wrap()
        rep_meas_circ.join_circuit(circ_I, False)

    return rep_meas_circ
def ghz2_double(ps, pm, pg, eta, a0, a1, theta):
    """
    GHZ state of weigth 2 created using 2 Bell pairs
    generated using the double selection protocol.

    Parameters
    ----------
    ps : (scalar) single qubit gate error rate.
    pm : (scalar) measurement error rate.
    pg : (scalar) two qubit gate error rate.
    eta : (scalar) detection efficiency.
    a0 : (scalar) extra environmental error when electron spin is being operated.
    a1 : (scalar) default environmental error.
    theta : (scalar) determines how the states are initialized when generating remote
            entanglement.
    """
    cb = circuit_block.Blocks(ps, pm, pg, eta, a0, a1, theta)
    pair = pair_double_sel(ps, pm, pg, eta, a0, a1, theta)

    ghz = circuit.Circuit(a0=a0, a1=a1,
                          circuit_block=cb.single_selection_ops,
                          targets=[0, 1], ancillas=[2, 3], sigma="Z")
    ghz.add_circuit(circuit_block=cb.swap_pair,
                    pair=[0, 1])
    ghz.add_circuit(circuit_block=pair.run_parallel)

    return ghz
Exemplo n.º 7
0
def main():
    t1 = []
    t2 = []
    t3 = []
    t4 = []
    t5 = []
    for counter in range(10):
        print(counter)
        c1 = circuit.Circuit.rand_circuit(sparse_tensor_gate.TensorGate,
                                          sparse_tools.clifford_set, 8, 64)
        c2 = circuit.Circuit.rand_circuit(sparse_tensor_gate.TensorGate,
                                          sparse_tools.clifford_set, 8, 64)
        c3 = circuit.Circuit(c1 + c2)

        t1.append(time.time())
        p1 = collapse(c1)
        t2.append(time.time())
        p2 = collapse(c2)
        t3.append(time.time())
        p3a = p1 * p2
        t4.append(time.time())
        p3b = collapse(c3)
        t5.append(time.time())

    d1 = np.mean([t2[i] - t1[i] for i in range(len(t1))])
    d2 = np.mean([t3[i] - t2[i] for i in range(len(t1))])
    d3 = np.mean([t4[i] - t3[i] for i in range(len(t1))])
    d4 = np.mean([t5[i] - t4[i] for i in range(len(t1))])
    print(f'p1: {d1}\np2: {d2}\np3: {d3}\np4: {d4}')
Exemplo n.º 8
0
    def __init__(self, modelType, modelParam, numInverters):
        s0 = 3.0
        if modelType == "lcMosfet":
            model = circuit.LcMosfet
            self.Vtp = modelParam[0]
            self.Vtn = modelParam[1]
            self.Vdd = modelParam[2]
            self.Kn = modelParam[3]
            self.Kp = modelParam[4]
            nfet = circuit.MosfetModel('nfet', self.Vtn, self.Kn)
            pfet = circuit.MosfetModel('pfet', self.Vtp, self.Kp)

        elif modelType == "scMosfet":
            model = circuit.ScMosfet
            self.Vdd = modelParam[0]
            nfet = circuit.MosfetModel('nfet')
            pfet = circuit.MosfetModel('pfet')

        self.numInverters = numInverters

        # V = [V0, V1, V2, ... grnd, Vdd]
        transistorList = []
        for i in range(numInverters):
            transistorList.append(
                model(numInverters, i, (i + 1) % numInverters, nfet, s0))
            transistorList.append(
                model(numInverters + 1, i, (i + 1) % numInverters, pfet,
                      s0 * 2))

        self.c = circuit.Circuit(transistorList)

        self.bounds = []
        for i in range(numInverters):
            self.bounds.append([0.0, self.Vdd])
Exemplo n.º 9
0
    def __init__(self, modelType, modelParam, inputVoltage):
        self.inputVoltage = inputVoltage
        s0 = 3.0
        if modelType == "lcMosfet":
            model = circuit.LcMosfet
            self.Vtp = modelParam[0]
            self.Vtn = modelParam[1]
            self.Vdd = modelParam[2]
            self.Kn = modelParam[3]
            self.Kp = modelParam[4]
            nfet = circuit.MosfetModel('nfet', self.Vtn, self.Kn)
            pfet = circuit.MosfetModel('pfet', self.Vtp, self.Kp)

        elif modelType == "scMosfet":
            model = circuit.ScMosfet
            self.Vdd = modelParam[0]
            nfet = circuit.MosfetModel('nfet')
            pfet = circuit.MosfetModel('pfet')

        # V = [outputVoltage, inputVoltage, grnd, Vdd]
        transistorList = []
        transistorList.append(model(2, 1, 0, nfet, s0))
        transistorList.append(model(3, 1, 0, pfet, s0 * 2))

        self.c = circuit.Circuit(transistorList)

        self.bounds = []
        # output voltage
        self.bounds.append([0.0, self.Vdd])
Exemplo n.º 10
0
    def __init__(self):
        self.circuit = circuit.Circuit()  # the circuit which Alice will garble
        # a mapping of each wire to its two labels (secret!)
        self.wire_labels = dict()

        # the wires which Alice will supply input to, mapped to their corresponding inputs.
        # Values of this dictionary are secret!
        self.input_wires = dict()

        # a mapping of encrypted values to entry pairs. We cache this so that, if point-and-permute is enabled we can
        # sort encrypted values according to their select bits without having to decrypt. We intentionally garble
        # gates separately from permuting gates, and do it after encryption, to match the accompanying written
        # tutorial.
        self.encrypted_entries = dict()

        # the random R value for free-XOR. Only used if free-XOR is enabled

        if config.USE_FREE_XOR:
            if config.USE_POINT_PERMUTE:
                self.R = bitstring.Bits(bytes=os.urandom(16))
            else:
                # if we are using free-xor and NOT using point-and-permute, we need to to make sure R has the proper
                # zero bits just like the labels, otherwise things get messed up!
                self.R = bitstring.Bits(bytes=bytes(
                    config.CLASSIC_SECURITY_PARAMETER)) + bitstring.Bits(
                        bytes=os.urandom(16 -
                                         config.CLASSIC_SECURITY_PARAMETER))
            config.R = self.R
            print("ALICE: Generating random R = {}".format(self.R.hex))
Exemplo n.º 11
0
 def testFiringRatesSlow(self):
     circ = circuit.Circuit('microcircuit', analysis_type='stationary')
     params = circ.params
     xs_array = [0.1 * i for i in range(10)]
     rates = []
     for xs in xs_array:
         params['xs'] = np.ones((8, 8)) * xs
         params['xs_ext'] = np.ones(8) * xs
         circ = circuit.Circuit('microcircuit',
                                params,
                                analysis_type='stationary',
                                from_file=False)
         rates.append(circ.th_rates)
     rates = np.transpose(np.asarray(rates))
     rates_test = h5.load_h5(self.test_data, 'rates_slow')
     assert (np.allclose(rates_test, rates, rtol=self.rtol, atol=self.atol))
Exemplo n.º 12
0
    def syndrome_meas_circuit(self):
        """Returns a circuit which measures all stabilizer generators
        onto ancillae, using ``measure_gen_onto_ancilla``."""

        return sum((self.measure_gen_onto_ancilla(idx_gen).relabel_qubits(
            {self.nq: self.nq + idx_gen})
                    for idx_gen in range(len(self.group_generators))),
                   circuit.Circuit())
def ghz4_epl(ps, pm, pg, eta, a0, a1, theta):
    """
    GHZ state of weigth 4 created using 4 Bell pairs
    generated using the EPL protocol.

    Parameters
    ----------
    ps : (scalar) single qubit gate error rate.
    pm : (scalar) measurement error rate.
    pg : (scalar) two qubit gate error rate.
    eta : (scalar) detection efficiency.
    a0 : (scalar) extra environmental error when electron spin is being operated.
    a1 : (scalar) default environmental error.
    theta : (scalar) determines how the states are initialized when generating remote
            entanglement.
    """
    # Circuits are assemebled in reversed order
    cb = circuit_block.Blocks(ps, pm, pg, eta, a0, a1, theta)
    epl = pair_EPL(ps, pm, pg, eta, a0, a1, theta)


    # Phase 3 - Create GHZ
    # Perform the measurements
    ghz = circuit.Circuit(a0=a0, a1=a1,
                          circuit_block=cb.collapse_ancillas_GHZ,
                          ghz_size=4,
                          measure_pos=[4, 5, 6, 7])
    # Apply two qubit gates in the nodes
    ghz.add_circuit(circuit_block=cb.two_qubit_gates, controls=[1, 3, 0, 2],
                    targets=[4, 5, 6, 7], sigma="X")

    # Phase 2 Create last two pairs
    pair = circuit.Circuit(a0=a0, a1=a1, circuit_block=cb.swap_pair,
                           pair=[0, 1])
    pair.add_circuit(circuit_block=cb.start_epl)
    wrap_EPL_parallel = circuit.Circuit(a0=a0, a1=a1,
                                        circuit_block=pair.run_parallel)

    ghz.add_circuit(circuit_block=wrap_EPL_parallel.append_circuit)

    # Phase 1 Create initial two pairs

    ghz.add_circuit(circuit_block=epl.run_parallel)

    return ghz
Exemplo n.º 14
0
def generate_wait_circ(n_data):
    '''
    '''

    circ_I = cir.Circuit()
    for i in range(n_data):
        circ_I.add_gate_at([i], 'I_idle')

    return circ_I
Exemplo n.º 15
0
def arborescence_mix(nbTaches, matrice, b=bornes.b1, debug=False):
    P1 = projet.Johnson(nbTaches, matrice)
    c = circuit.Circuit(P1, matrice)
    v = c.resolve()
    taches = [i for i in range((int)(nbTaches))]
    tree = Arbre(taches, matrice, b)
    tree.borneSup = [v]
    P, res = tree.resolve()
    tree.accuracy(debug)
    return P, res
Exemplo n.º 16
0
    def measure_node_to_circuit(self, measurement_node: qiskit.qasm.node.Measure)\
            -> circuit.Circuit:
        c = circuit.Circuit(self.num_qubits())

        op_list = [rotation.PauliOperator.I] * self.num_qubits()
        measure_idx: int = _SegmentedQASMParser.extract_measurement_idx(
            measurement_node)
        op_list[measure_idx] = _SegmentedQASMParser.measurement_operator
        c.add_pauli_block(rotation.Measurement.from_list(op_list))

        return c
 def mixed_maker_helper(N, circuit_scale):
     num_T = int(circuit_scale * (N**2) * T_percent)
     num_gates = int(circuit_scale * (N**2) * (1 - T_percent))
     circ = circuit.Circuit.rand_circuit(gate_constructor,
                                         tools.clifford_set, N, num_gates)
     circT = circuit.Circuit.rand_circuit(gate_constructor,
                                          {'T': tools.universal_set["T"]},
                                          N, num_gates)
     circ2 = circ + circT
     random.shuffle(circ2)
     return circuit.Circuit(circ2)
Exemplo n.º 18
0
    def parse_new_circ_line(self, new_circ_line_list):
        """new-circ: global-id purpose is_predicted_circuit"""
        assert (len(new_circ_line_list) == 4)
        assert (new_circ_line_list[0] == "new-circ:")

        global_id, purpose = new_circ_line_list[1], new_circ_line_list[2]
        is_predicted = new_circ_line_list[3]

        new_circ = circuit.Circuit(global_id, purpose, is_predicted,
                                   self.timestamp)
        self.hs_log.register_circuit(new_circ)
Exemplo n.º 19
0
def GetAnalyzer(name=None, plot=False):
    if name is None:
        name = circuit._DEFAULT_CIRCUIT_NAME
    with analyzer_instances_lock(util.READ_LOCKED):
        if name in analyzer_instances:
            analyzer = analyzer_instances[name]
        else:
            analyzer_instances_lock.promote()  # Write locked.
            analyzer = CircuitAnalyzer(circuit.Circuit(name), plot=plot)
            analyzer_instances[name] = analyzer
    return analyzer
Exemplo n.º 20
0
def build_circuit(bitlength, n_parties, output_max=True):
    num_inputs = [bitlength] * n_parties
    c = circuit.Circuit(n_parties, num_inputs)
    x0 = [0]
    for i in range(1, n_parties):
        x0.append(x0[i - 1] + num_inputs[i - 1])
    bitmap, maximum = max_block(c, n_parties, bitlength, x0, output_max, None)
    if output_max == True:
        c.add_to_output_wires(maximum)
    c.add_to_output_wires(bitmap)
    c.wire_outputs()
    return str(c)
Exemplo n.º 21
0
    def __init__(self, modelType, modelParam, inputVoltage):
        s0 = 3.0
        self.inputVoltage = inputVoltage

        if modelType == "lcMosfet":
            model = circuit.LcMosfet
            self.Vtp = modelParam[0]
            self.Vtn = modelParam[1]
            self.Vdd = modelParam[2]
            self.Kn = modelParam[3]
            self.Kp = modelParam[4]
            nfet = circuit.MosfetModel('nfet',
                                       self.Vtn,
                                       self.Kn,
                                       gds="default")
            pfet = circuit.MosfetModel('pfet',
                                       self.Vtp,
                                       self.Kp,
                                       gds="default")

        elif modelType == "scMosfet":
            model = circuit.ScMosfet
            self.Vdd = modelParam[0]
            nfet = circuit.MosfetModel('nfet')
            pfet = circuit.MosfetModel('pfet')

        # with the voltage array containing [grnd, Vdd, input, X[0], X[1], X[2]]
        # where X[0] is the output voltage and X[1] is the voltage at node with
        # nfets and X[2] is the voltage at node with pfets

        # src, gate, drain = grnd, input, X[1]
        m0 = model(0, 2, 4, nfet, s0)

        # src, gate, drain = X[1], input, X[0]
        m1 = model(4, 2, 3, nfet, s0)

        # src, gate, drain = X[1], X[0], Vdd
        m2 = model(4, 3, 1, nfet, s0)

        # src, gate, drain = Vdd, input, X[2]
        m3 = model(1, 2, 5, pfet, s0 * 2.0)

        # src, gate, drain = X[2], in, X[0]
        m4 = model(5, 2, 3, pfet, s0 * 2.0)

        # src, gate, drain = X[2], X[0], grnd
        m5 = model(5, 3, 0, pfet, s0 * 2.0)

        self.c = circuit.Circuit([m0, m1, m2, m3, m4, m5])

        self.bounds = []
        for i in range(3):
            self.bounds.append([0.0, self.Vdd])
Exemplo n.º 22
0
 def testEmpiricalTransferFunction(self):
     params = {}
     params['tf_mode'] = 'empirical'
     params['tau_impulse'] = np.array(
         [8.555, 5.611, 4.167, 4.381, 4.131, 3.715, 4.538, 3.003])
     params['delta_f'] = np.array([
         0.0880, 0.458, 0.749, 0.884, 1.183, 1.671, 0.140, 1.710
     ]) / self.net.params['w']
     net = circuit.Circuit('microcircuit', params)
     freqs, power = net.create_power_spectra()
     power_test = h5.load_h5(self.test_data, 'empirical/power')
     assert (np.allclose(power_test, power, rtol=self.rtol, atol=self.atol))
def ghz3_bk_simple(ps, pm, pg, eta, a0, a1, theta):
    """
    GHZ state of weigth 3 created using 2 Bell pairs
    generated using the Barret-Kok protocol.

    Parameters
    ----------
    ps : (scalar) single qubit gate error rate.
    pm : (scalar) measurement error rate.
    pg : (scalar) two qubit gate error rate.
    eta : (scalar) detection efficiency.
    a0 : (scalar) extra environmental error when electron spin is being operated.
    a1 : (scalar) default environmental error.
    theta : (scalar) determines how the states are initialized when generating remote
            entanglement.
    """
    # Circuits are assemebled in reversed order
    cb = circuit_block.Blocks(ps, pm, pg, eta, a0, a1, theta)


    # Phase 3 - Create GHZ
    # Perform the measurements
    ghz = circuit.Circuit(a0=a0, a1=a1,
                          circuit_block=cb.collapse_ancillas_GHZ,
                          ghz_size=3,
                          measure_pos=[2])
    # Apply two qubit gates in the nodes
    ghz.add_circuit(circuit_block=cb.two_qubit_gates, controls=[1],
                    targets=[2], sigma="X")

    # Phase 2 Create second pair
    ghz.add_circuit(circuit_block=cb.swap_pair,
                    pair=[0, 1])
    bk = circuit.Circuit(a0=a0, a1=a1, circuit_block=cb.start_BK)
    ghz.add_circuit(circuit_block=bk.append_circuit)

    # Phase 1 Create initial pair
    ghz.add_circuit(circuit_block=cb.start_BK)

    return ghz
Exemplo n.º 24
0
    def measure_gen_onto_ancilla(self, gen_idx):
        """
        Produces a circuit that measures the stabilizer code generator 
        ``self.group_generators[gen_idx]`` onto the qubit labelled by 
        ``stab.nq`` (that is, the next qubit not in the physical register
        used by the code).
        
        :param int gen_idx: Index of a generator of the stabilizer group, as
            specified by the ``group_generators`` property of this instance.
        :returns qecc.Circuit: A circuit that maps a measurement of
            ``group_generators[gen_idx]`` onto a measurement of :math:`Z` on the
            ancilla qubit alone.
        """

        circ = circuit.Circuit()
        for qubit_idx, operator in enumerate(
                self.group_generators[gen_idx].op):
            # operator = (self.group_generators[gen_idx].op)[qubit_idx]
            if operator == 'I':
                pass
            elif operator == 'Z':
                circ += circuit.Circuit(('CNOT', qubit_idx, self.nq))
            elif operator == 'Y':
                circ += circuit.Circuit(
                    circuit.Location('P', qubit_idx),
                    circuit.Location('Z', qubit_idx),
                    circuit.Location('H', qubit_idx),
                    circuit.Location('CNOT', qubit_idx, self.nq),
                    circuit.Location('H', qubit_idx),
                    circuit.Location('P', qubit_idx))
            elif operator == 'X':
                circ += circuit.Circuit(
                    circuit.Location('H', qubit_idx),
                    circuit.Location('CNOT', qubit_idx, self.nq),
                    circuit.Location('H', qubit_idx))
            else:
                raise ValueError("Pauli operator not I, X, Y, or Z")
        return circ
Exemplo n.º 25
0
def init_func():
    house = 0
    end_sw = 0

    curr_player = 0
    hands = init_shuffle()
    p1 = player(hands[0], 0)
    p2 = player(hands[1], 0)
    p3 = player(hands[2], 0)

    player_arr = [p1, p2, p3]

    c = ct.Circuit()
    return c, house, end_sw, curr_player, player_arr
Exemplo n.º 26
0
def random_evaluation(pi, nbTaches, matrice, nbEvalutation=10):
    taille = nbTaches - len(pi)
    mini = float('inf')
    for i in range(nbEvalutation):
        genome = pi[::]
        while len(genome) != nbTaches:
            r = random.randint(0, nbTaches - 1)
            if r not in genome:
                genome.append(r)
        #print('genome : ', genome)
        c = circuit.Circuit(genome, matrice)
        res = c.resolve()
        mini = min(mini, res)
    return mini
def ghz3_double(ps, pm, pg, eta, a0, a1, theta):
    """
    GHZ state of weigth 3 created using 3 Bell pairs
    generated using the EPL protocol.

    Parameters
    ----------
    ps : (scalar) single qubit gate error rate.
    pm : (scalar) measurement error rate.
    pg : (scalar) two qubit gate error rate.
    eta : (scalar) detection efficiency.
    a0 : (scalar) extra environmental error when electron spin is being operated.
    a1 : (scalar) default environmental error.
    theta : (scalar) determines how the states are initialized when generating remote
            entanglement.
    """
    # Circuits are assemebled in reversed order
    cb = circuit_block.Blocks(ps, pm, pg, eta, a0, a1, theta)
    pair = pair_double_sel(ps, pm, pg, eta, a0, a1, theta)

    # Phase 3 - Create GHZ
    # Perform the measurements
    ghz = circuit.Circuit(a0=a0, a1=a1,
                          circuit_block=cb.collapse_ancillas_GHZ,
                          ghz_size=3,
                          measure_pos=[3, 4, 5])
    # Apply two qubit gates in the nodes
    ghz.add_circuit(circuit_block=cb.two_qubit_gates, controls=[1, 2, 0],
                    targets=[3, 4, 5], sigma="X")

    # Phase 1 Create initial pair
    swaped_pair = circuit.Circuit(a0=a0, a1=a1, circuit_block=cb.swap_pair,
                                  pair=[0, 1])
    swaped_pair.add_circuit(circuit_block=pair.run_as_block)
    ghz.add_circuit(circuit_block=swaped_pair.run_parallel, parallel=3)

    return ghz
Exemplo n.º 28
0
    def expend(self, debug=False):
        node = self.LNode[-1]
        if debug:
            print('on examine le noeud ', node)
        res = node.expend(debug)
        if debug:
            print('res : ', res)
        if res == None:
            del self.LNode[-1]
        else:
            if type(res) == bool and res == True:
                #on est arriver à une feuille
                v = node.borneInf
                if len(node.P) < self.nbTaches:
                    #noeud intermedaire
                    del self.LNode[-1]
                else:
                    if debug:
                        print('--------------------------------')
                        print('on examine une feuille ')
                        print('borne inf : {}, borne sup : {}'.format(
                            v, self.borneSup))
                        print('--------------------------------')

                    #pas nessessaire pour la borne1
                    c = circuit.Circuit(node.P, self.matrice)
                    trueValue = c.resolve()

                    if trueValue < self.borneSup[0]:
                        #probleme il faut prendre la vrai valeur de la solution ?
                        self.borneSup = [trueValue]
                        if debug:
                            print('la nouvelle borne sup est :', v)
                        self.bestP = node.P[::]
                        if debug:
                            print('bestP : {}'.format(self.bestP))
                    del self.LNode[-1]
            else:
                P = (node.P)[::]
                P.append(res)
                Lrestantes = (node.Lrestantes)[::]
                Lrestantes.remove(res)
                self.cpt += 1
                new = Noeud(P, self.matrice, Lrestantes, self.f_borneInf,
                            self.borneSup)
                if debug:
                    print("creation du noeud :", new)
                self.LNode.append(new)
Exemplo n.º 29
0
def local_test(filename):
    with open(filename) as json_file:
        json_circuits = json.load(json_file)

    for json_circuit in json_circuits['circuits']:
        circuit = c.Circuit(json_circuit)
        # generate title
        generateTitle(json_circuit['name'])

        for aliceInput in circuit.perms(len(json_circuit['alice'])):
            # check whether this circuit involves bob.
            if circuit.bob:
                # build relevant files needed to send to bob
                toBob = circuit.sendToBob(aliceInput)
                # iterate through bob's potential inputs.
                for bobInput in circuit.perms(len(json_circuit['bob'])):
                    # get the reference output to verify the results.
                    test = circuit.compute(aliceInput + bobInput)
                    # do oblivious transfer on this.
                    bobPInput = []
                    for i in range(len(bobInput)):
                        bobValue = bobInput[i]
                        bobIndex = toBob['bobIndex'][i]
                        otB = ot.Bob(bobValue)
                        inp1, inp2 = circuit.setupBobOT(bobIndex)
                        otA = ot.Alice(inp1, inp2)
                        # garbled circuit stuff.
                        ot_c = otA.send_c()
                        h0 = otB.send_h0(ot_c)
                        c_1, E, length = otA.sendMessage(h0)
                        payload = otB.getMessage(c_1, E, length)
                        bobPInput.append(payload)
                    # bob evaluates the output.
                    output = bh.evaluate(toBob, pinputs=bobPInput)
                    # create checksum to determine whether
                    # our output is the same as the input.
                    check = True if test == output else False
                    if check:
                        # the computation is equivalent;
                        # Alice will compute the truth table.
                        circuit.printRow(aliceInput, bobInput)
                    else:
                        print("ERROR: The garbled circuit does not compute.")
            else:
                # bob is not involved in this circuit so theres no point
                # computing our encrypted transfer.
                circuit.printRow(aliceInput, None)
Exemplo n.º 30
0
    def oracle_circuit(o):
        o = "{0:b}".format(o).zfill(n)
        oracle_circuit = circuit.Circuit(n + 1, prepared=True)
        first_third_layer = []
        for i in range(n):
            if o[i] == 0:
                first_third_layer.append("X")
            else:
                first_third_layer.append("I")
        first_third_layer.append("I")
        oracle_circuit.append_layer(*first_third_layer)

        second_layer = [CNOT_All()]
        oracle_circuit.append_layer(*second_layer)

        oracle_circuit.append_layer(*first_third_layer)
        return oracle_circuit