Example #1
0
def handle_request(req_type: str, client_soc: socket.socket,
                   cir: circuit.Circuit, data: bytes):
    """
    Main handler for client request after client data has been received
    :param req_type: http method
    :param client_soc: the client connection
    :param cir: given circuit object
    :param data: the client data
    :return: status code
    """
    # Create random stream ID and get the address port
    streamID = random.randint(100, 1000)
    addr_port = get_addrport(data, req_type)
    # If the client used connect, do http tunneling
    if req_type == 'CONNECT':
        status_code = cir.start_stream(streamID, addr_port)
        if status_code == 0:
            # client_soc.sendall(CONNECT_RESPONSE_SUCCESS)
            print("CONNECT Successful, Tunneling Encrypted Data...")
            client_soc.sendall(CONNECT_RESPONSE_SUCCESS)
            tunnel_mode(client_soc, cir, streamID)
    # Else send the client request as is because no encryption with tls is needed
    else:
        status_code = cir.start_stream(streamID, addr_port)
        if status_code == 0:
            send_data(cir, data, streamID)
            response, _ = cir.receive_data()
            print(response)
            client_soc.sendall(response)
            tunnel_mode(client_soc, cir, streamID)
            # client_soc.close()
        return status_code
    def __init__(self, parent, controller, show_settings, height, width):
        super().__init__(parent)

        self["style"] = "Background.TFrame"
        self["height"] = height
        self["width"] = width

        self.parent = parent

        self.func = None
        self.start, self.end = 0, 0

        self.controller = controller
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.circuit = Circuit(self, height=height, width=.8 * width)
        self.circuit.grid(row=0, column=0, sticky="NSEW")

        self.control_panel = Control_Panel(self,
                                           height=height,
                                           width=.2 * width)
        self.control_panel.grid(row=0, column=1, sticky="NSEW")

        self.handle_entries_change()
def clique_n2_th18n(n, k, edges):
    clauses = []

    for i in range(1, n + 1):
        for j in range(i + 1, n + 1):
            if (i, j) not in edges:
                clauses += [[-i, -j]]

    c = Circuit(input_labels=[f'x{i}' for i in range(1, n + 1)], gates={})
    c.outputs = add_thn(c, c.input_labels, k, is5n=False)

    def makesatvar(s):
        if s[0] == 'x':
            return int(s[1:])
        else:
            return int(s[1:]) + n + 1

    for gate in c.gates.keys():
        var = makesatvar(gate)
        pr1 = makesatvar(c.gates[gate][0])
        pr2 = makesatvar(c.gates[gate][1])
        op = c.gates[gate][2]
        clauses += [[pr1, pr2, var if op[0] == '1' else -var]]
        clauses += [[pr1, -pr2, var if op[1] == '1' else -var]]
        clauses += [[-pr1, pr2, var if op[2] == '1' else -var]]
        clauses += [[-pr1, -pr2, var if op[3] == '1' else -var]]

    clauses += [[makesatvar(c.outputs)]]

    save_cnf_formula_to_file('clique.cnf', clauses, n + len(c.gates))
    return clauses, '18n'
Example #4
0
    def add_constraint(self, dip, outputs):
        """
        Adds a new dip/output constraint to the SAT solver.

        dip: the DIP for the constraint
        outputs: the oracle outputs for the DIP passed in
        """
        constraint_ckt0 = Circuit.specify_inputs(dip,
                                                 self.nodes,
                                                 self.output_names,
                                                 key_suffix="__ckt0")
        constraint_ckt1 = Circuit.specify_inputs(dip,
                                                 self.nodes,
                                                 self.output_names,
                                                 key_suffix="__ckt1")

        output_constraints0 = []
        output_constraints1 = []

        for name in constraint_ckt0.outputs():
            output_constraints0.append(
                constraint_ckt0.outputs()[name] == outputs[name])
            output_constraints1.append(
                constraint_ckt1.outputs()[name] == outputs[name])

        self.solver.add(*output_constraints0)
        self.solver.add(*output_constraints1)
Example #5
0
def test_cleartext_dist32():
    x = 4060000
    y = 7390000
    cx = 4063500
    cy = 7396000
    rsq = 64000000
    answer = 1 if ((x - cx)**2 + (y - cy)**2) < rsq else 0

    inputs = [0 for _ in range(32)]
    x_bits = [int(b) for b in bin(x)[2:]]
    if len(x_bits) < 32:
        x_bits = [0 for _ in range(32 - len(x_bits))] + x_bits
    y_bits = [int(b) for b in bin(y)[2:]]
    if len(y_bits) < 32:
        y_bits = [0 for _ in range(32 - len(y_bits))] + y_bits
    cx_bits = [int(b) for b in bin(cx)[2:]]
    if len(cx_bits) < 32:
        cx_bits = [0 for _ in range(32 - len(cx_bits))] + cx_bits
    cy_bits = [int(b) for b in bin(cy)[2:]]
    if len(cy_bits) < 32:
        cy_bits = [0 for _ in range(32 - len(cy_bits))] + cy_bits
    rsq_bits = [int(b) for b in bin(rsq)[2:]]
    if len(rsq_bits) < 32:
        rsq_bits = [0 for _ in range(32 - len(rsq_bits))] + rsq_bits
    inputs.extend(x_bits[::-1])
    inputs.extend(y_bits[::-1])
    inputs.extend(cx_bits[::-1])
    inputs.extend(cy_bits[::-1])
    inputs.extend(rsq_bits[::-1])
    c = Circuit("bristol_circuits/dist32.txt", ['V' for _ in range(192)])
    out_bit = asyncio.run(c.evaluate(inputs))
    assert out_bit[0] == answer, "computed wrong value"
Example #6
0
def to_networkx(circuit: Circuit, feed_dict: CircuitState) -> networkx.DiGraph:
    net = networkx.DiGraph()
    sources = set(circuit.sources).union(feed_dict.keys())
    for op in circuit.ops:
        net.add_node(id(op), op=op.as_json, source=False, source_value=False)
    for source in sources:
        net.add_node(id(source),
                     op={'op_type': 'source'},
                     source=True,
                     source_value=bool(
                         feed_dict.get(source, source.default_value)))
        for op in circuit.downstream_ops(source):
            net.add_edge(id(source),
                         id(op),
                         line=source.as_json,
                         id=id(source))
    for op in circuit.ops:
        for out_line in op.out_lines:
            for out_op in circuit.downstream_ops(out_line):
                net.add_edge(id(op),
                             id(out_op),
                             line=out_line.as_json,
                             id=id(out_line))
    js = networkx.readwrite.json_graph.node_link_data(net)
    with open('graph.json', 'w') as fn:
        json.dump(js, fn)
Example #7
0
def publish():

    rospy.init_node("node3", anonymous=False)
    pub = rospy.Publisher('/gazebo/set_model_state', ModelState, queue_size=10)
    rate = rospy.Rate(200)

    nodo = ModelState()
    nodo.model_name = "prius_hybrid_1"

    circuit = Circuit()
    circuit.run()

    for i in range(2 * (len(circuit.points)) / 3, len(circuit.points)):

        position = circuit.points[i]
        previous_position = circuit.points[i - 1]

        nodo = calculate_position_and_orientation(nodo, position,
                                                  previous_position)

        pub.publish(nodo)
        rate.sleep()

    while not rospy.is_shutdown():

        for i in range(len(circuit.points)):

            position = circuit.points[i]
            previous_position = circuit.points[i - 1]

            nodo = calculate_position_and_orientation(nodo, position,
                                                      previous_position)

            pub.publish(nodo)
            rate.sleep()
Example #8
0
def lol2():
    circuit = Circuit(input_labels=['i1', 'i2', 'i3', 'i4', 'i5'])
    x1, x2, x3, x4, x5 = circuit.input_labels
    a0, a1 = add_sum3(circuit, [x1, x2, x3])
    b0, b1 = add_sum3(circuit, [a0, x4, x5])
    w1, w2 = add_sum2(circuit, [a1, b1])
    circuit.outputs = [b0, w1, w2]
    check_sum_circuit(circuit)
    print(circuit)
Example #9
0
def run_test_circuit_2(name):
    R1 = Resistor('R1', [0, 1], 5)  # 5 Ohm
    V2 = VoltageSource('V2', [0, 1], 1)  # 1 Volt

    test_circuit = Circuit()
    test_circuit.add_components([R1, V2])

    test_circuit.solve_DC()  # DC

    test_circuit.print_matrix()
    test_circuit.print_results()
Example #10
0
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Car tutorial")
        width = 1280
        height = 720

        self.screen = pygame.display.set_mode((width, height))
        self.clock = pygame.time.Clock()
        self.ticks = 60
        self.exit = False
        self.circuit = Circuit(self.screen)
Example #11
0
class AStarHandler:
    def __init__(self, heuristic):
        self.circuit = Circuit()
        self.circuit.start()
        self.bestPerformer = copy.deepcopy(self.circuit)
        self.matrix = [[0 for x in range(self.circuit.ROWS)]
                       for y in range(self.circuit.COLS)]
        self.updateMatrix()
        for wiresPermut in itertools.permutations(
                self.circuit.getWires(), len(self.circuit.getWires())):
            #print(wiresPermut)
            for wireKey in wiresPermut:
                #print(wireKey)
                wire = self.circuit.wires[wireKey]
                start = self.matrix[wire.startR][wire.startC]
                dest = self.matrix[wire.goalR][wire.goalC]
                path = astar(start, dest, self.matrix, heuristic)
                if len(path) < 1:
                    continue
                current = path[0]
                for item in path:
                    move = item.row - current.row, item.col - current.col
                    #print(move)
                    #print(item.row, item.col)
                    self.circuit.move(wireKey, move[0], move[1])
                    current = item
                self.updateMatrix()
                #self.circuit.printPathMatrix()
            #print("circuit fitness: ",self.circuit.getFitness()," Best performer fitness " ,self.bestPerformer.getFitness())

            if (int(self.circuit.getFitness()) > int(
                    self.bestPerformer.getFitness())):
                #print("Updated best")
                self.bestPerformer = copy.deepcopy(self.circuit)
            self.circuit.restart()
            self.updateMatrix()
        #print("Best performer has fitness: ", self.bestPerformer.getFitness())
        print("Turns: " + str(self.bestPerformer.getTotalTurns()))
        print("WireLength: " + str(self.bestPerformer.getWireLength()))
        print("Completed Wires: " +
              str(self.bestPerformer.getCompletedWires()))
        print("Fitness: " + str(self.bestPerformer.getFitness()))
        self.bestPerformer.drawResult()

    def updateMatrix(self):
        for row in range(self.circuit.ROWS):
            for col in range(self.circuit.COLS):
                self.matrix[row][col] = Node(self.circuit.pathM[row][col], row,
                                             col)
                #print(self.matrix[row][col].value)
        for wireKey in self.circuit.getWires():
            wire = self.circuit.wires[wireKey]
            #print(wire.goalR, wire.goalC)
            self.matrix[wire.goalR][wire.goalC].value = 2
Example #12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-ckt",
                        type=str,
                        required=True,
                        help="name of the ircuit, e.g. c17, no extension")
    parser.add_argument("-tp",
                        type=int,
                        required=True,
                        help="name of the ircuit, e.g. c17, no extension")
    parser.add_argument("-cpu",
                        type=int,
                        required=True,
                        help="name of the ircuit, e.g. c17, no extension")
    args = parser.parse_args()

    print("\n======================================================")
    print("Run | circuit: {} | Test Count: {} | CPUs: {}".format(
        args.ckt, args.tp, args.cpu))
    start_time = time.time()
    circuit = Circuit(args.ckt)
    circuit.read_circuit()
    circuit.lev()

    # inputnum = len(circuit.input_num_list)
    # limit = [0, pow(2, inputnum)-1]
    # for i in range(100):
    #     b = ('{:0%db}'%inputnum).format(randint(limit[0], limit[1]))
    #     list_to_logicsim = []
    #     for j in range(inputnum):
    #         list_to_logicsim.append(int(b[j]))
    #     circuit.logic_sim(list_to_logicsim)
    #     print(b)
    #     # print_nodes(circuit)

    # observability() need to follow controllability()
    circuit.SCOAP_CC()
    circuit.SCOAP_CO()
    # circuit.STAFAN_CS(100)
    # circuit.STAFAN_B()

    circuit.STAFAN(args.tp, num_proc=args.cpu)
    # circuit.co_ob_info()
    graph = circuit.gen_graph()
    suffix = round(math.log10(args.tp))
    fname = ("10e" + str(suffix)) if (suffix % 1 == 0) else str(args.tp)
    fname = "./../data/graph/" + args.ckt + "_" + fname + ".graphml"
    print("Saving graph in ", fname)
    nx.write_graphml(graph, fname)
    print("Saved!")
    print("Total simulation ime: {:.2f} seconds".format(time.time() -
                                                        start_time))
    print()
Example #13
0
def exp_check_c432_behavioral(
    mode="ckt",
    tp=100,
):
    if mode not in ["ckt", "v"]:
        raise NameError("mode {} is not accepted".format(mode))
    print(
        "Checking c432 behavioral golden with c432 in {} format".format(mode))
    circuit = Circuit("c432")
    LoadCircuit(circuit, mode)
    circuit.lev()
    check_c432_logicsim(circuit, tp, mode)
Example #14
0
def test_circuit_resistance():
    circuit = Circuit()
    battery = VoltageSource(circuit, 9)  # 9 volts
    resistor = Resistor(circuit, 10)  # 1 ohm
    battery.negative = resistor.positive
    battery.positive = resistor.negative = circuit._ground
    print circuit.graph.edges()
    mna = circuit.assemble_mna_equation()
    stuff = mna.simulate(10.0, 0.1)

    circuit.draw()
    plt.savefig('crkt1.png')
Example #15
0
def test_cleartext_unnormalized_subregion_example():
    answer = 300

    inputs = [0 for _ in range(64)] + [1 for _ in range(1200)]

    c = Circuit("bristol_circuits/unnormalized_subregion_100_10.txt",
                ['V' for _ in range(1264)])
    out_bits = asyncio.run(c.evaluate(inputs))
    out_string = ''.join([str(i) for i in list(reversed(out_bits))])
    for i in range(10):
        assert eval('0b' + out_string[i * 64:(i + 1) *
                                      64]) == answer, "computed wrong value"
Example #16
0
def run_circuit_process(t, n, c_path, index, queues, main_queue, inputs,
                        triples):
    print(f"starting node {index}")
    shamir = Shamir(t, n)
    messenger = MockMessenger(t, n, index, queues)
    c = Circuit(c_path)
    outputs = c.evaluate(inputs,
                         shamir=shamir,
                         messenger=messenger,
                         triples=triples)
    main_queue.put(outputs)
    print(f"closing node {index}")
 def test_eval_order(self):
     c = Circuit(2)
     f = AdditionGate("F")
     g = AdditionGate("G")
     h = ScalarMultGate(2, "H")
     c.add_gate(h, ["INPUT1"])
     c.add_gate(f, ["H","INPUT0"])
     c.add_gate(g, ["F", "H"], True)
     self.assertEqual(c.eval_order(), ['H', 'F', 'G', 'OUTPUT'])
Example #18
0
def run_test_circuit_4(name):
    G2 = Conductor('G2', [1, 0], 0.25)  # 0.5 1/Ohm
    R1 = Resistor('R1', [1, 2], 1)  # 2 Ohm
    R3 = Resistor('R3', [2, 0], 5)  # 4 Ohm
    I4 = CurrentSource('I4', [0, 1], 2)  # 0.5 Ampere

    test_circuit = Circuit()
    test_circuit.add_components([R1, G2, R3, I4])

    test_circuit.solve_DC()  # DC

    test_circuit.print_matrix()
    test_circuit.print_results()
Example #19
0
def run_test_circuit_3(name):
    R1 = Resistor('R1', [1, 0], 2)  # 2 Ohm
    R2 = Resistor('R2', [1, 2], 1)  # 1 Ohm
    R3 = Resistor('R3', [2, 0], 5)  # 1 Ohm
    V4 = VoltageSource('V4', [1, 0], 4)  # 1 Volt

    test_circuit = Circuit()
    test_circuit.add_components([R1, R2, R3, V4])

    test_circuit.solve_DC('HM10')  # DC

    test_circuit.print_matrix()
    test_circuit.print_results()
Example #20
0
 def __init__(self):
     local_dir = os.path.dirname(__file__)
     config_path = os.path.join(local_dir, 'config')
     self.circuit = Circuit()
     self.circuit.start()
     self.wireNames = self.circuit.getWires()
     self.numInputs = self.circuit.getPathMatrixSize() + len(
         self.wireNames) * 4
     self.numOutputs = len(self.wireNames) * 4
     self.editConfig(config_path)
     self.bestFitness = -999999
     self.stats = None
     self.run(config_path)
Example #21
0
def load_neurohdf(filename, hdf5path, memmapped=False):
    """ Loads the circuit from a NeuroHDF file as exported from CATMAID

    Parameters
    ----------
    filename : str
        Path to the NeuroHDF file
    hdfpath : str
        HDF5 path to the irregular dataset containing the circuit
        e.g. /Microcircuit
    """
    if memmapped:
        raise NotImplementedError('Memmapped HDF5 reading not yet implemented')

    circuit = Circuit()

    f = h5py.File(filename, 'r')
    circuitdata_group=f[hdf5path]
    vertices_group = circuitdata_group.get('vertices')
    connectivity_group = circuitdata_group.get('connectivity')
    metadata_group = circuitdata_group.get('metadata')

    def helpdict(v):
        helpdict = dict.fromkeys( v.attrs.keys() )
        for k in helpdict:
            helpdict[k] = v.attrs.get(k)
        return helpdict

    for k,v in vertices_group.items():
        if k == 'id':
            circuit.vertices = vertices_group[k].value
        else:
            circuit.vertices_properties[k] = dict.fromkeys( [const.DATA, const.METADATA] )
            circuit.vertices_properties[k][const.DATA] = v.value
            circuit.vertices_properties[k][const.METADATA] = helpdict(v)
        print('Added vertices {0}'.format(k))

    for k,v in connectivity_group.items():
        if k == 'id':
            circuit.connectivity = connectivity_group[k].value
        else:
            circuit.connectivity_properties[k] = dict.fromkeys( [const.DATA, const.METADATA] )
            circuit.connectivity_properties[k][const.DATA] = v.value
            circuit.connectivity_properties[k][const.METADATA] = helpdict(v)

        print('Added connectivity {0}'.format(k))
    if metadata_group:
        for k,v in metadata_group.items():
            circuit.metadata[k] = dict.fromkeys( [const.DATA, const.METADATA] )
            circuit.metadata[k][const.DATA] = v.value
            circuit.metadata[k][const.METADATA] = helpdict(v)
        print('Added metadata {0}'.format(k))
    circuit._remap_vertices_id2indices()
    f.close()

    return circuit
def test_simple_calc():
    x1, x2 = Input(), Input()
    coef1, coef2 = Parameter(1), Parameter(3)
    func = Circuit([x1, x2], [x1 * coef1 + x2 * coef2])
    assert func([1, 1]) == [4]
    assert func([10, -1]) == [7]

    func_clone = func.clone()
    coef1.val = -1
    assert func([1, 1]) == [2]
    assert func([10, -1]) == [-13]

    assert func_clone([1, 1]) == [4]
    assert func_clone([10, -1]) == [7]
Example #23
0
    def __init__(self, nodes, output_names):
        self.nodes = nodes
        self.output_names = output_names

        self.locked_ckt0 = Circuit.from_nodes(nodes,
                                              output_names,
                                              key_suffix="__ckt0")
        self.locked_ckt1 = Circuit.from_nodes(nodes,
                                              output_names,
                                              key_suffix="__ckt1")
        self.miter_ckt = Circuit.miter(self.locked_ckt0, self.locked_ckt1)

        self.solver = Solver()
        self.solver.add(self.miter_ckt.outputs()["diff"] == True)
Example #24
0
def build_circuit(cir: circuit.Circuit):
    """
    Main function to build a circuit
    :param cir: given initialized circuit object
    :return: status code
    """
    # Incrementally build the circuit hops and if something wrong happens at some point return error
    status_code = cir.build_hop_1()
    if status_code == 0:
        status_code = cir.build_hop_2()
        if status_code == 0:
            status_code = cir.build_hop_3()
            return status_code
    return 1
Example #25
0
File: main.py Project: prtx/DFT
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-ckt", type=str, required=True, help="circuit name, c17, no extension")
    parser.add_argument("-tp", type=int, required=False, help="number of tp for random sim")
    parser.add_argument("-cpu", type=int, required=False, help="number of parallel CPUs")
    args = parser.parse_args()

    print("\n======================================================")
    print("Run | circuit: {} | Test Count: {} | CPUs: {}".format(args.ckt, args.tp, args.cpu))
    print("======================================================\n")

    circuit = Circuit(args.ckt)
    LoadCircuit(circuit, "ckt")
    circuit.lev()
Example #26
0
    def run(self, qc):
        circ = Circuit(qc.num_qubits)

        global_phase = 0.0

        for gate in qc.gates:
            rules, phase = gate.unroll()
            global_phase += phase

            for basis_gate in rules:
                circ.append(basis_gate)

        global_phase = sign(global_phase) * (abs(global_phase) % (2 * pi))

        return circ, global_phase
def compile_unitary(U):
    """
    Takes a unitary and returns a circuit - i.e. a list of CNOTs and single qubit gates.
    """

    # perform two level decomposition
    two_level_unitaries = two_level_decomp(U)

    assert(np.allclose(mat_mul(two_level_unitaries), U))

    controlled_ops = []

    # decompose each two-level unitary into fully controlled operations
    for t in two_level_unitaries:
        controlled_ops += two_level_to_fully_controlled(t)

    assert(np.allclose(mat_mul(controlled_ops),U))

    gates = []

    # decompose each fully controlled operations into single qubit and CNOT gates
    for c in controlled_ops:
        gates += fully_controlled_to_single_cnot(c)

    circ = Circuit(n)

    circ.add_gates(gates)

    prod = circ.evaluate()

    assert(np.allclose(prod, U))

    print('number of two-level: ' + str(len(two_level_unitaries)))
    print('number of fully controlled ops: ' + str(len(controlled_ops)))
    print('number of CNOT and single qubit gates: ' + str(len(gates)))
    s = [g for g in gates if type(g) is SingleQubitGate]
    c = [g for g in gates if type(g) is CNOTGate]

    print('Single gates: ' + str(len(s)))
    print('CNOT gates: ' + str(len(c)))

    print('approximation error: ' + str(np.linalg.norm(prod-U)))

    for g in gates:
        if np.allclose(g.total_matrix(), np.eye(2**g.num_qubits)):
            print('redundant gate')

    return circ
Example #28
0
 def getCircuits(self):
     focus_goal = (math.floor(self.focus_ratio * self.num_of_circuits * self.num_of_exerecises)) if (self.focus != '') else 0
     while (self.num_of_circuits > 0):
         circuit = Circuit(self.filtered_exercise_list, self.num_of_exerecises, self.focus, focus_goal, self.no_weights, self.no_stability_ball, self.no_machines)
         self.circuits.append(circuit)
         self.num_of_circuits -= 1
         focus_goal -= circuit.focused_count
Example #29
0
def search_till_found(x, y, n, c, shuffle_val, iterations):

	# Fresh start
    C = Circuit(x, y, c)
    n = circuits_priority(n, c)
    total_links = len(n)
    heap = []
    # Else the if statement crases later
    heappush(heap, (100, 0))

    # shuffle the deck, assign values to variables
    n = shuffle_n(n, shuffle_val)
    temp, spec, temp2, temp3 = -1, False, 0, 0

    # Either use a while loop till you find all or a forloop for any path
    # while heap[0][0] != 0:
    for i in range(iterations):
        shortest = shortest_path(C, x, y, c, n, total_links, spec)

        if not shortest: 
        	n = shuffle_n(n, shuffle_val)
        # If it found the same path, shuffle it
        elif temp == shortest[0]:
            n = shuffle_n(n, shuffle_val)
        # Else push the new path to the heap
        else:
            temp0 = heap[0][0]
            if temp0 == heap[0][0]:
                temp3 += 1
            if temp3 >= 5:
                spec = True
            temp = shortest[0]
            heappush(heap, shortest)
            n = heap[0][1]
    return heap[0]
def one_step_change_circuit(circuit, subcircuit_size=5, connected=True):
    circuit_graph = circuit.construct_graph()
    while True:
        selected_nodes = random_combination(circuit.gates, subcircuit_size)
        graph = circuit_graph.subgraph(selected_nodes)

        if connected and not nx.is_weakly_connected(graph):
            continue
        subcircuit = tuple(graph.nodes)
        subcircuit_inputs, subcircuit_outputs = get_inputs_and_outputs(
            circuit, circuit_graph, subcircuit)
        if len(subcircuit_outputs) == subcircuit_size:
            continue

        random.shuffle(subcircuit_inputs)
        sub_in_tt, sub_out_tt = make_truth_tables(circuit, subcircuit_inputs,
                                                  subcircuit_outputs)
        improved_circuit = find_circuit(subcircuit_inputs, subcircuit_size,
                                        sub_in_tt, sub_out_tt)

        if isinstance(improved_circuit, Circuit):
            replaced_graph = circuit.replace_subgraph(improved_circuit,
                                                      subcircuit,
                                                      subcircuit_outputs)
            if nx.is_directed_acyclic_graph(replaced_graph):
                improved_full_circuit = Circuit.make_circuit(
                    replaced_graph, circuit.input_labels,
                    make_improved_circuit_outputs(circuit.outputs,
                                                  subcircuit_outputs,
                                                  improved_circuit.outputs))
                return fix_labels(improved_full_circuit)

        continue
def main():
    # Parse the command-line arguments.
    args = get_args()
    circuit_file = args.circuit_file[0]
    output_file = args.output_file
    if output_file:
        output_file = output_file[0]
    format_csv = args.format_csv

    # If the file exists, then check if it is a supported input file.
    if os.path.isfile(circuit_file):
        # If it is a supported input file, then parse it.
        if circuit_file.endswith(".in"):
            # Create a new Circuit object consisting of the gates from the input file.
            circuit = Circuit(circuit_file, output_file, format_csv)
            print("INFO::  Printing gates in circuit...")
            print()

            # Print the list of gates sorted by ID.
            circuit.print_gates()
            print()

            # Prompt the user for desired outputs.
            print("INFO::  Use spaces to select multiples (e.g., 1 4 6).")
            print("INFO::  To calculate all gates, just press 'Enter' without inputting anything.")
            selected_output = input("INPUT:: Select gates: ")

            # Validate the selected outputs to ensure they are in range.
            print("INFO::  Validating selected outputs...")
            selected_outputs = validate_selected_outputs(selected_output.split(), len(circuit.get_gates()))

            # Generate the truth table for the selected outputs.
            if output_file:
                print("INFO::  Outputting truth table to \"" + output_file + "\"...")
            else:
                print("INFO::  Printing truth table for selected outputs...")
            print("        This may take awhile for large numbers of inputs because of 2^n combinations...")
            print("        Total Combinations: " + str(pow(2, circuit.get_num_of_general_input_values())))
            if output_file is None:
                print()
            circuit.print_truth_table(selected_outputs)
            
        # Otherwise, display an error.
        else:
            print("ERROR:: Invalid file: \"" + circuit_file + "\"")
            print("        File must be of extension .in (e.g. circuit1.in).")
            
    # Otherwise, display an error.
    else:
        print("ERROR:: Cannot find file at path \"" + circuit_file + "\"")
 def __init__(self,pin_no):
     Circuit.__init__(self)
Example #33
0
 def __init__(self,pin_no):
     Circuit.__init__(self)
     self._pin_no = pin_no
     GPIO.setmode(GPIO.BCM)
     GPIO.setup(self._pin_no, GPIO.IN)
Example #34
0
from circuit import Circuit
from grover import iterator
from measurement import measure

if __name__ == "__main__":
    N = input("Enter the number of items in the search space: ")
    n = int(np.ceil(np.log2(N)) + 1)
    M = input("Enter the number of search targets: ")
    targets = []
    for i in range(M):
        target = raw_input("Target %d in binary: " % (i + 1))
        targets.append(target)
    num_iter = input("Number of iterations: ")

    initial_state = tensor(plus, n)
    circuit = Circuit(n, initial_state)
    # Apply the Z gate to the ancilla bit to make it |-> for phase kickback
    # Multiply by root 2 to renormalize without considering the ancilla qubit
    state = np.sqrt(2) * circuit.add_gate(Z, [n])

    # Switch to interactive mode
    plt.ion()
    # Plot the initial probability amplitudes and angle
    amps_fig = plt.figure(0)
    amps = amps_fig.add_subplot(111)
    amps.bar(np.arange(state.size / 2) + 0.1, abs(state[::2]) ** 2)
    amps_fig.show()
    angles_fig = plt.figure(1)
    angles = angles_fig.add_subplot(111, polar=True)
    theta = np.arccos(np.sqrt((2.0 ** (n - 1) - M) / (2 ** (n - 1))))
    angles.plot([theta, theta], [0, 1], "g-", linewidth=2)