Exemplo n.º 1
0
 def testSort(self):
     """
     Tests Wire.sort
     """
     wire = Wire("bacd")
     wire = wire.sort()
     self.assertEqual(wire, "abcd")
Exemplo n.º 2
0
def half_adder(a, b, s, c):
    d = Wire(0)
    e = Wire(0)
    or_gate(a, b, d)
    and_gate(a, b, c)
    interver(c, e)
    and_gate(d, e, s)
Exemplo n.º 3
0
 def testSwap(self):
     """
     Tests Wire.swap()
     """
     wire = Wire("Test")
     wire = wire.swap(0, 3)
     self.assertEqual(wire, "tesT")
Exemplo n.º 4
0
    def testGetDiff(self):
        """
        Tests Wire.getDiff() 
        """

        wire = Wire("Test")
        wire = wire.getDiff("TESTING")
        self.assertEqual(wire, 7)
Exemplo n.º 5
0
    def prettified(self):
        """
    Makes the protoboard slightly more appealing by collapsing long vertical
        wires (when possible) and shifting horizontal wires up or down to avoid
        corssing wires (when possible).
    I apologize for really ugly code :(
    This is targetted for the regular protoboard structure, and not any others.
        I.e. changing the constants will result in this code not being as
        useful.
    """
        new = Proto_Board().with_loc_disjoint_set_forest(self._loc_disjoint_set_forest)
        for piece in self._pieces:
            new = new.with_piece(piece)
        for i, wire in enumerate(self._wires):
            if wire.vertical():
                r1, c1 = wire.loc_1
                r2, c2 = wire.loc_2
                assert c1 == c2
                if r1 > r2:
                    r1, r2 = r2, r1
                    c1, c2 = c2, c1
                if r2 - r1 == 1:
                    new = new.with_wire(wire)
                    continue

                def safe(r):
                    return r == r1 or r == r2 or (self.free((r, c1)) and self.rep_for((r, c1)) is None)

                if r1 in RAIL_ROWS and r2 in BODY_BOTTOM_ROWS and all(safe(r) for r in [2, 6, 7]):
                    pairs = ((r1, 2), (6, 7))
                elif r1 in RAIL_ROWS and r2 in RAIL_ROWS and all(safe(r) for r in [2, 6, 7, 11]):
                    pairs = ((r1, 2), (6, 7), (11, r2))
                elif r1 in BODY_TOP_ROWS and r2 in RAIL_ROWS and all(safe(r) for r in [6, 7, 11]):
                    pairs = ((6, 7), (11, r2))
                else:
                    pairs = ((r1, r2),)
                for _r, r_ in pairs:
                    w = Wire((_r, c1), (r_, c1), wire.node)
                    new = new.with_wire(w)
            elif wire.horizontal():
                r1, c1 = wire.loc_1
                r2, c2 = wire.loc_2
                assert r1 == r2
                r = r1
                # try to get horizontal wires closer to the center
                rows = [2, 3, 4, 5, 6] if r1 <= 6 else [11, 10, 9, 8, 7]
                for _r in rows:
                    test_wire = Wire((_r, c1), (_r, c2), wire.node)
                    if (
                        not any(test_wire.crosses(w) for w in self._wires[i + 1 :])
                        and not any(test_wire.crosses(w) for w in new._wires)
                        and not any(piece.crossed_by(test_wire) for piece in new._pieces)
                    ):
                        r = _r
                new = new.with_wire(Wire((r, c1), (r, c2), wire.node))
            else:
                new = new.with_wire(wire)
        return new
Exemplo n.º 6
0
 def test_creat_face(self):
     # create a box
     b = get_test_box_shape()
     # take the first edge
     t = Topo(b)
     wire = next(t.wires())
     my_wire = Wire(wire)
     assert not my_wire.IsNull()
     assert my_wire.tolerance == 1e-06
Exemplo n.º 7
0
    def testForEach(self):
        """
        Tests Wire.forEach()
        """
        def mul2(thing):
            return thing * 2

        wire = Wire("test")
        wire = wire.forEach(mul2)
        self.assertEqual(wire, ["tt", "ee", "ss", "tt"])
Exemplo n.º 8
0
def ListPackages(Where=''):
    out = []
    DbConnection = sqlite3.connect('main.db')
    DbCursor = DbConnection.cursor()
    for row in DbCursor.execute("SELECT * FROM PACKAGES " + Where).fetchall():
        Obj = Wire()
        Obj.Id = row[0]
        Obj.Position = row[1]
        Obj.Destination = row[14]
        out.append(Obj)
    DbConnection.close()
    return out
Exemplo n.º 9
0
def ListWires(Where=''):
    out = []
    DbConnection = sqlite3.connect('main.db')
    DbCursor = DbConnection.cursor()
    for row in DbCursor.execute("SELECT * FROM WIRES " + Where).fetchall():
        Obj = Wire()
        Obj.Id = row[0]
        Obj.Port1Id = row[1]
        Obj.Port2Id = row[2]
        out.append(Obj)
    DbConnection.close()
    return out
Exemplo n.º 10
0
def test_construction_with_instructions():
    target = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
    instructions = "U2,R2"

    wire = Wire(instructions)
    assert wire.instructions == instructions
    assert wire.points == target

    wire = Wire()
    wire.instructions = instructions
    assert wire.instructions == instructions
    assert wire.points == target
def test_closest_combined_step_distance(wire_one, wire_two):
    wires = [wire_one, wire_two]
    grid = Grid(wires)
    assert grid.closest_combined_step_distance == 30

    wire_one = Wire("R75,D30,R83,U83,L12,D49,R71,U7,L72")
    wire_two = Wire("U62,R66,U55,R34,D71,R55,D58,R83")
    grid = Grid([wire_one, wire_two])
    assert grid.closest_combined_step_distance == 610

    wire_one = Wire("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51")
    wire_two = Wire("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7")
    grid = Grid([wire_one, wire_two])
    assert grid.closest_combined_step_distance == 410
Exemplo n.º 12
0
def test_points_from_instructions():
    wire = Wire()
    wire.extend_points_from_instructions("U2")
    assert wire.points == [(0, 0), (0, 1), (0, 2)]

    wire = Wire()
    wire.extend_points_from_instructions("U2,R2")
    assert wire.points == [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
Exemplo n.º 13
0
    def Connect( self, dstPlug ):
        print 'Connecting:', self, '->', dstPlug
        pt1 = self.GetNode().GetRect().GetPosition() + self.GetPosition()
        pt2 = dstPlug.GetNode().GetRect().GetPosition() + dstPlug.GetPosition()
        wire = Wire( pt1, pt2, self.GetType() )
        wire.srcNode = self.GetNode()
        wire.dstNode = dstPlug.GetNode()
        wire.srcPlug = self
        wire.dstPlug = dstPlug
        self._wires.append( wire )
        dstPlug.GetWires().append( wire )

        dc = self.GetNode().GetParent().pdc
        wire.Draw( dc )
        self.GetNode().GetParent().RefreshRect( wire.GetRect(), False )
Exemplo n.º 14
0
 def testFormat(self):
     """
     Tests Wire.format()
     """
     var = "Test"
     wire = Wire("This is a {}").format(var)
     self.assertEqual(wire, "This is a Test")
Exemplo n.º 15
0
	def create(self):

		angle = next(self.angle_generator)
		position = next(self.position_generator)
		length = next(self.length_generator)
		
		return Wire(angle, *position, length = length)
 def cost((l1, l2)):
     wire = Wire(l1, l2, node)
     num_wires_crossed = sum(
         _wire.crosses(wire) for _wire in proto_board.get_wires())
     num_pieces_crossed = sum(
         piece.crossed_by(wire) for piece in proto_board.get_pieces())
     return 100 * (num_wires_crossed + num_pieces_crossed) + dist(
         l1, l2)
Exemplo n.º 17
0
    def addWire(self, portFullName1, portFullName2):
        port1 = self.portByFullName(portFullName1)
        port2 = self.portByFullName(portFullName2)

        wire = Wire(port1, port2)
        self.addItem(wire)
        self.view.notifyView('add', wire)

        return wire
Exemplo n.º 18
0
    def testLoop(self):
        wire = Wire("Test")

        def mul(i):
            return i * 2

        for i in wire:
            mul(i)
        self.assertEqual(1, 1)  # Pass
Exemplo n.º 19
0
def test_construction():
    wire = Wire()
    assert wire.RIGHT == 'R'
    assert wire.LEFT == 'L'
    assert wire.UP == 'U'
    assert wire.DOWN == 'D'
    assert wire.SHIFT_RIGHT == (1, 0)
    assert wire.SHIFT_LEFT == (-1, 0)
    assert wire.SHIFT_UP == (0, 1)
    assert wire.SHIFT_DOWN == (0, -1)
    assert not wire.instructions
    assert wire.points == [(0, 0)]
Exemplo n.º 20
0
def assemble_input(circuit, value):
    try:
        input_signal = int(value)
    except ValueError:
        input_part = circuit.get_wire(value)
        if not input_part:
            input_part = Wire()
            wire_name = value
            circuit.add_wire(input_part, wire_name)
    else:
        input_part = Signal(input_signal)

    return input_part
Exemplo n.º 21
0
 def connect_wires(self, selected_signal, mpos):
     for signal in self.signal_outputs:  # Connect to board outputs
         if signal.check_collision(mpos[0], mpos[1]) and selected_signal is not None and signal != selected_signal:
             for wire in self.wires:
                 if wire.end_signal == signal:
                     self.wires.remove(wire)
             self.wires.append(Wire(selected_signal, signal))
     for chip in self.chips:
         for signal in chip.inputs:  # Connect to gate inputs
             if signal.check_collision(mpos[0],
                                       mpos[1]) and selected_signal is not None and signal != selected_signal:
                 for wire in self.wires:
                     if wire.end_signal == signal:
                         self.wires.remove(wire)
                 self.wires.append(Wire(selected_signal, signal))
         for signal in chip.outputs:  # Connect to gate outputs
             if signal.check_collision(mpos[0],
                                       mpos[1]) and selected_signal is not None and signal != selected_signal:
                 for wire in self.wires:
                     if wire.end_signal == signal:
                         self.wires.remove(wire)
                 self.wires.append(Wire(selected_signal, signal))
Exemplo n.º 22
0
 def prettified(self):
   """
   Makes the protoboard slightly more appealing by collapsing long vertical
       wires (when possible) and shifting horizontal wires up or down to avoid
       corssing wires (when possible).
   I apologize for really ugly code :(
   This is targetted for the regular protoboard structure, and not any others.
       I.e. changing the constants will result in this code not being as
       useful.
   """
   new = Proto_Board().with_loc_disjoint_set_forest(
       self._loc_disjoint_set_forest)
   for piece in self._pieces:
     new = new.with_piece(piece)
   for i, wire in enumerate(self._wires):
     if wire.vertical():
       r1, c1 = wire.loc_1
       r2, c2 = wire.loc_2
       assert c1 == c2
       if r1 > r2:
         r1, r2 = r2, r1
         c1, c2 = c2, c1
       if r2 - r1 == 1:
         new = new.with_wire(wire)
         continue
       def safe(r):
         return r == r1 or r == r2 or (self.free((r, c1)) and self.rep_for(
             (r, c1)) is None)
       if r1 in RAIL_ROWS and r2 in BODY_BOTTOM_ROWS and all(safe(r) for r in
           [2, 6, 7]):
         pairs = ((r1, 2), (6, 7))
       elif r1 in RAIL_ROWS and r2 in RAIL_ROWS and all(safe(r) for r in
           [2, 6, 7, 11]):
         pairs = ((r1, 2), (6, 7), (11, r2))
       elif r1 in BODY_TOP_ROWS and r2 in RAIL_ROWS and all(safe(r) for r in
           [6, 7, 11]):
         pairs = ((6, 7), (11, r2))
       else:
         pairs = ((r1, r2),)
       for _r, r_ in pairs:
         w = Wire((_r, c1), (r_, c1), wire.node)
         new = new.with_wire(w)
     elif wire.horizontal():
       r1, c1 = wire.loc_1
       r2, c2 = wire.loc_2
       assert r1 == r2
       r = r1
       # try to get horizontal wires closer to the center
       rows = [2, 3, 4, 5, 6] if r1 <= 6 else [11, 10, 9, 8, 7]
       for _r in rows:
         test_wire = Wire((_r, c1), (_r, c2), wire.node)
         if (not any(test_wire.crosses(w) for w in self._wires[i + 1:]) and not
             any(test_wire.crosses(w) for w in new._wires) and not any(
             piece.crossed_by(test_wire) for piece in new._pieces)):
           r = _r
       new = new.with_wire(Wire((r, c1), (r, c2), wire.node))
     else:
       new = new.with_wire(wire)
   return new
Exemplo n.º 23
0
    def testReplace(self):
        """
        Tests Wire.replace()
        Tests with:
        - Wire.replace(old, new, count=1)
        - Wire.replace(old, new, count=2)
        - Wire.replace(old, new, count=None)
        """
        wire = Wire("Testing 1 2 3 Testing 1 2 3")
        wire = wire.replace("Testing", "Success", count=1)
        self.assertEqual(wire, "Success 1 2 3 Testing 1 2 3")

        wire = Wire("Testing 1 2 3 Testing 1 2 3 Testing")
        wire = wire.replace("Testing", "Success", count=2)
        self.assertEqual(wire, "Success 1 2 3 Success 1 2 3 Testing")

        wire = Wire("Testing Testing Testing 1 2 3 Testing")
        wire = wire.replace("Testing", "Success", count=None)
        self.assertEqual(wire, "Success Success Success 1 2 3 Success")
Exemplo n.º 24
0
def test():
    w1 = Wire([val for val in "R8,U5,L5,D3".split(",")])
    w2 = Wire([val for val in "U7,R6,D4,L4".split(",")])
    assert(part1([w1, w2]) == 6), "Failed 1 - 1"
    assert(part2([w1, w2]) == 30), "Failed 1 - 2"

    w3 = Wire([val for val in "R75,D30,R83,U83,L12,D49,R71,U7,L72".split(",")])
    w4 = Wire([val for val in "U62,R66,U55,R34,D71,R55,D58,R83".split(",")])
    assert(part1([w3, w4]) == 159), "Failed 2 - 1"
    assert(part2([w3, w4]) == 610), "Failed 2 - 2"

    w5 = Wire([val for val in "R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51".split(",")])
    w6 = Wire([val for val in "U98,R91,D20,R16,D67,R40,U7,R15,U6,R7".split(",")])
    assert(part1([w5, w6]) == 135), "Failed 3 - 1"
    assert(part2([w5, w6]) == 410), "Failed 3 - 2"
 def get_children(self):
   children = []
   proto_board, loc_pairs = self.state
   for i, (loc_1, loc_2, resistor, node) in enumerate(loc_pairs):
     # can extend a wire from |loc_1| towards |loc_2| from any of the
     #     the locations |loc_1| is internally connected to
     for neighbor_loc in filter(proto_board.free,
         proto_board.locs_connected_to(loc_1)):
       # get candidate end locations for the new wire to draw
       wire_ends = (self._wire_ends_from_rail_loc(neighbor_loc,
           proto_board) if is_rail_loc(neighbor_loc) else
           self._wire_ends_from_body_loc(neighbor_loc, proto_board,
           span=dist(loc_1, loc_2)))
       for wire_end in wire_ends:
         # make sure that there is a wire to draw
         if wire_end == neighbor_loc:
           continue
         new_wire = Wire(neighbor_loc, wire_end, node)
         # track number of pieces this wire crosses
         num_piece_crossings = sum(piece.crossed_by(new_wire) for piece in
             proto_board.get_pieces())
         if not ALLOW_PIECE_CROSSINGS and num_piece_crossings:
           continue
         # track number of other wires this new wire crosses
         any_same_orientation_crossings = False
         num_wire_crossings = 0
         for wire in proto_board.get_wires():
           if wire.crosses(new_wire):
             if wire.vertical() == new_wire.vertical():
               any_same_orientation_crossings = True
               break
             else:
               num_wire_crossings += 1
         # don't allow any wire crossings where the two wires have the same
         #     orientation
         if any_same_orientation_crossings:
           continue
         # continue if we do not want to allow any crossing wires at all, even
         #     ones of different orientation
         if not ALLOW_WIRE_CROSSINGS and num_wire_crossings:
           continue
         # construct a proto board with this new wire
         wire_proto_board = proto_board.with_wire(new_wire)
         # check that adding the wire is reasonable
         wire_proto_board_valid = (wire_proto_board and wire_proto_board is
             not proto_board)
         # potentially create another proto board with a resistor in place of
         #     the new wire
         add_resistor = (resistor is not None and not num_piece_crossings and
             not num_wire_crossings and new_wire.length() == 3)
         if add_resistor:
           n1, n2, r, label = (resistor.n1, resistor.n2, resistor.r,
               resistor.label)
           # find representatives for the two nodes, they better be there
           n1_group = proto_board.rep_for(n1)
           assert n1_group
           n2_group = proto_board.rep_for(n2)
           assert n2_group
           # check that wire loc 1 is in the same group as node n1
           assert proto_board.rep_for(new_wire.loc_1) == n1_group
           # find representative for wire loc 2, might not be there
           wire_loc_2_group = proto_board.rep_for(new_wire.loc_2)
           # if it is there, it better be the same as n2_group, or we can't put
           #     a resistor here
           if (not wire_loc_2_group) or wire_loc_2_group == n2_group:
             # figure out correct orientation of Resistor_Piece n1 and n2
             vertical = new_wire.vertical()
             if new_wire.c_1 < new_wire.c_2 or new_wire.r_1 < new_wire.r_2:
               resistor_piece = Resistor_Piece(n1, n2, r, vertical, label)
               resistor_piece.top_left_loc = new_wire.loc_1
             else:
               resistor_piece = Resistor_Piece(n2, n1, r, vertical, label)
               resistor_piece.top_left_loc = new_wire.loc_2
             # create proto board with resistor
             new_proto_board = proto_board.with_piece(resistor_piece)
             if not wire_loc_2_group:
               # ensure to mark the oposite location with its apporpriate node
               new_proto_board = new_proto_board.with_loc_repped(n2_group,
                   new_wire.loc_2)
             # would no longer need a resistor for this pair of locations
             new_resistor = None
             # and the node for the rest of the wires will be the node for the
             #     other end of the resistor
             new_node = n2
           else:
             # placing the resistor would create a violating connection
             add_resistor = False
         if not add_resistor:
           if wire_proto_board_valid:
             # can still put a wire down if allowed
             new_proto_board = wire_proto_board
             new_resistor = resistor
             new_node = node
           else:
             continue
         # we have a candidate proto board, compute state and cost
         new_loc_pairs = list(loc_pairs)
         new_cost = self.cost + new_wire.length()
         if proto_board.connected(wire_end, loc_2):
           new_loc_pairs.pop(i)
           # favor connectedness a lot
           new_cost -= 100
         else:
           new_loc_pairs[i] = (wire_end, loc_2, new_resistor, new_node)
         # penalize long wires
         new_cost += new_wire.length()
         # penalize many wires
         new_cost += 10
         # penalize wires crossing pieces (if allowed at all)
         new_cost += 1000 * num_piece_crossings
         # penalize crossing wires of opposite orientation (if allowed at all)
         new_cost += 1000 * num_wire_crossings
         # favor wires that get us close to the goal, and penalize wires
         #     that get us farther away
         new_cost += dist(wire_end, loc_2) - dist(loc_1, loc_2)
         children.append(Proto_Board_Search_Node(new_proto_board,
             frozenset(new_loc_pairs), self, new_cost,
             self.filter_wire_lengths))
         # if added a resistor, also create a proto board where we use a wire
         #     instead of the resistor
         if add_resistor and wire_proto_board_valid:
           wire_loc_pairs = list(loc_pairs)
           wire_loc_pairs[i] = (wire_end, loc_2, resistor, node)
           children.append(Proto_Board_Search_Node(wire_proto_board,
               frozenset(wire_loc_pairs), self, new_cost,
               self.filter_wire_lengths))
   return children
Exemplo n.º 26
0
 def set_wires(self, instructions: list):
     for instruction in instructions:
         wire = Wire(instruction)
         self._set_wire_points(wire)
def find_terrible_wiring(loc_pairs, start_proto_board):
    """
  Finds a terrible wiring without penalizing anything at all.
  To be used as a fall-back option.
  """
    proto_board = start_proto_board
    connect_loc_pairs = []
    resistor_r1 = PROTO_BOARD_HEIGHT / 2 - 1
    resistor_r2 = resistor_r1 + 1

    def find_free_c():
        c = PROTO_BOARD_WIDTH / 2
        for dc in xrange(PROTO_BOARD_WIDTH / 2):
            for sign in (-1, 1):
                _c = c + sign * dc
                locs = ((resistor_r1, _c), (resistor_r2, _c))
                if all(
                        proto_board.rep_for(loc) is None
                        and proto_board.free(loc) for loc in locs):
                    return _c
        return None

    for loc_1, loc_2, resistor, node in loc_pairs:
        if resistor:
            c = find_free_c()
            if c is None:
                print 'Terrible wiring failed: no space for resistor'
                return None
            resistor_piece = Resistor_Piece(resistor.n1, resistor.n2,
                                            resistor.r, True, resistor.label)
            resistor_piece.top_left_loc = (resistor_r1, c)
            proto_board = proto_board.with_piece(resistor_piece)
            proto_board = proto_board.with_loc_repped(
                proto_board.rep_for(resistor.n1), (resistor_r1, c))
            proto_board = proto_board.with_loc_repped(
                proto_board.rep_for(resistor.n2), (resistor_r2, c))
            connect_loc_pairs.append((loc_1, (resistor_r1, c), resistor.n1))
            connect_loc_pairs.append((loc_2, (resistor_r2, c), resistor.n2))
        else:
            connect_loc_pairs.append((loc_1, loc_2, node))
    for loc_1, loc_2, node in connect_loc_pairs:
        candidates = list(
            product(
                filter(proto_board.free, proto_board.locs_connected_to(loc_1)),
                filter(proto_board.free,
                       proto_board.locs_connected_to(loc_2))))
        if not candidates:
            print 'Terrible wiring failed: could not connect %s and %s' % (
                loc_1, loc_2)
            return None

        def cost((l1, l2)):
            wire = Wire(l1, l2, node)
            num_wires_crossed = sum(
                _wire.crosses(wire) for _wire in proto_board.get_wires())
            num_pieces_crossed = sum(
                piece.crossed_by(wire) for piece in proto_board.get_pieces())
            return 100 * (num_wires_crossed + num_pieces_crossed) + dist(
                l1, l2)

        l1, l2 = min(candidates, key=cost)
        proto_board = proto_board.with_wire(Wire(l1, l2, node))
    return proto_board
 def get_children(self):
     children = []
     proto_board, loc_pairs = self.state
     for i, (loc_1, loc_2, resistor, node) in enumerate(loc_pairs):
         # can extend a wire from |loc_1| towards |loc_2| from any of the
         #     the locations |loc_1| is internally connected to
         for neighbor_loc in filter(proto_board.free,
                                    proto_board.locs_connected_to(loc_1)):
             # get candidate end locations for the new wire to draw
             wire_ends = (
                 self._wire_ends_from_rail_loc(neighbor_loc, proto_board)
                 if is_rail_loc(neighbor_loc) else
                 self._wire_ends_from_body_loc(
                     neighbor_loc, proto_board, span=dist(loc_1, loc_2)))
             for wire_end in wire_ends:
                 # make sure that there is a wire to draw
                 if wire_end == neighbor_loc:
                     continue
                 new_wire = Wire(neighbor_loc, wire_end, node)
                 # track number of pieces this wire crosses
                 num_piece_crossings = sum(
                     piece.crossed_by(new_wire)
                     for piece in proto_board.get_pieces())
                 if not ALLOW_PIECE_CROSSINGS and num_piece_crossings:
                     continue
                 # track number of other wires this new wire crosses
                 any_same_orientation_crossings = False
                 num_wire_crossings = 0
                 for wire in proto_board.get_wires():
                     if wire.crosses(new_wire):
                         if wire.vertical() == new_wire.vertical():
                             any_same_orientation_crossings = True
                             break
                         else:
                             num_wire_crossings += 1
                 # don't allow any wire crossings where the two wires have the same
                 #     orientation
                 if any_same_orientation_crossings:
                     continue
                 # continue if we do not want to allow any crossing wires at all, even
                 #     ones of different orientation
                 if not ALLOW_WIRE_CROSSINGS and num_wire_crossings:
                     continue
                 # construct a proto board with this new wire
                 wire_proto_board = proto_board.with_wire(new_wire)
                 # check that adding the wire is reasonable
                 wire_proto_board_valid = (wire_proto_board
                                           and wire_proto_board
                                           is not proto_board)
                 # potentially create another proto board with a resistor in place of
                 #     the new wire
                 add_resistor = (resistor is not None
                                 and not num_piece_crossings
                                 and not num_wire_crossings
                                 and new_wire.length() == 3)
                 if add_resistor:
                     n1, n2, r, label = (resistor.n1, resistor.n2,
                                         resistor.r, resistor.label)
                     # find representatives for the two nodes, they better be there
                     n1_group = proto_board.rep_for(n1)
                     assert n1_group
                     n2_group = proto_board.rep_for(n2)
                     assert n2_group
                     # check that wire loc 1 is in the same group as node n1
                     assert proto_board.rep_for(new_wire.loc_1) == n1_group
                     # find representative for wire loc 2, might not be there
                     wire_loc_2_group = proto_board.rep_for(new_wire.loc_2)
                     # if it is there, it better be the same as n2_group, or we can't put
                     #     a resistor here
                     if (not wire_loc_2_group
                         ) or wire_loc_2_group == n2_group:
                         # figure out correct orientation of Resistor_Piece n1 and n2
                         vertical = new_wire.vertical()
                         if new_wire.c_1 < new_wire.c_2 or new_wire.r_1 < new_wire.r_2:
                             resistor_piece = Resistor_Piece(
                                 n1, n2, r, vertical, label)
                             resistor_piece.top_left_loc = new_wire.loc_1
                         else:
                             resistor_piece = Resistor_Piece(
                                 n2, n1, r, vertical, label)
                             resistor_piece.top_left_loc = new_wire.loc_2
                         # create proto board with resistor
                         new_proto_board = proto_board.with_piece(
                             resistor_piece)
                         if not wire_loc_2_group:
                             # ensure to mark the oposite location with its apporpriate node
                             new_proto_board = new_proto_board.with_loc_repped(
                                 n2_group, new_wire.loc_2)
                         # would no longer need a resistor for this pair of locations
                         new_resistor = None
                         # and the node for the rest of the wires will be the node for the
                         #     other end of the resistor
                         new_node = n2
                     else:
                         # placing the resistor would create a violating connection
                         add_resistor = False
                 if not add_resistor:
                     if wire_proto_board_valid:
                         # can still put a wire down if allowed
                         new_proto_board = wire_proto_board
                         new_resistor = resistor
                         new_node = node
                     else:
                         continue
                 # we have a candidate proto board, compute state and cost
                 new_loc_pairs = list(loc_pairs)
                 new_cost = self.cost + new_wire.length()
                 if proto_board.connected(wire_end, loc_2):
                     new_loc_pairs.pop(i)
                     # favor connectedness a lot
                     new_cost -= 100
                 else:
                     new_loc_pairs[i] = (wire_end, loc_2, new_resistor,
                                         new_node)
                 # penalize long wires
                 new_cost += new_wire.length()
                 # penalize many wires
                 new_cost += 10
                 # penalize wires crossing pieces (if allowed at all)
                 new_cost += 1000 * num_piece_crossings
                 # penalize crossing wires of opposite orientation (if allowed at all)
                 new_cost += 1000 * num_wire_crossings
                 # favor wires that get us close to the goal, and penalize wires
                 #     that get us farther away
                 new_cost += dist(wire_end, loc_2) - dist(loc_1, loc_2)
                 children.append(
                     Proto_Board_Search_Node(new_proto_board,
                                             frozenset(new_loc_pairs), self,
                                             new_cost,
                                             self.filter_wire_lengths))
                 # if added a resistor, also create a proto board where we use a wire
                 #     instead of the resistor
                 if add_resistor and wire_proto_board_valid:
                     wire_loc_pairs = list(loc_pairs)
                     wire_loc_pairs[i] = (wire_end, loc_2, resistor, node)
                     children.append(
                         Proto_Board_Search_Node(wire_proto_board,
                                                 frozenset(wire_loc_pairs),
                                                 self, new_cost,
                                                 self.filter_wire_lengths))
     return children
Exemplo n.º 29
0
from wire import Wire
from agenda import Agenda, THE_AGENDA

def monitor(name, wire):

    def show():
        nonlocal wire
        global THE_AGENDA
        print("{[name: %s]" % name, end="")
        print("[current_time: %s]" % THE_AGENDA.current_time, end="")
        print("[new_value: : %s]}" % wire.get_signal(), end="\n\n")

    wire.add_action(show)


i = Wire(0)
monitor("input", i)
o = Wire(0)
monitor("output", o)

print("-------------------inverter(i,o)----------------------")
inverter(i, o)
THE_AGENDA.run_all_actions()

print("------------------------------------------------------")
i.set_signal(1)
THE_AGENDA.run_all_actions()

print("------------------------------------------------------")
i.set_signal(0)
THE_AGENDA.run_all_actions()
Exemplo n.º 30
0
    parser = argparse.ArgumentParser()
    parser.add_argument("input_file", type=str, help="Input file with wires.")
    parser.add_argument("--part",
                        type=int,
                        default=1,
                        choices=[1, 2],
                        help="Either sovling part 1 or part 2 of problem")
    args = parser.parse_args()

    # Read in input file with list of masses and parse
    with open(args.input_file, 'r') as f:
        contents = f.readlines()

    wires = []
    for instructions in contents:
        wires.append(Wire(instructions))

    assert len(wires) == 2

    grid = Grid(wires)
    if args.part == 1:
        msg = "Closest intersection: {} Distance: {}"
        msg = msg.format(grid.closest_intersection,
                         grid.closest_intersection_distance)
        print(msg)

    elif args.part == 2:
        msg = "Closest combined step distance: {}"
        msg = msg.format(grid.closest_combined_step_distance)
        print(msg)
Exemplo n.º 31
0
def readFile() -> list:
    with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
        return [Wire(val for val in line[:-1].split(",")) for line in f.readlines()]
Exemplo n.º 32
0
 def testGetItem(self):
     wire = Wire("Test")
     self.assertEqual(wire[0], "T")
     self.assertEqual(wire["T"], 0)
Exemplo n.º 33
0
 def testSetItem(self):
     wire = Wire("Test")
     wire["T"] = 3
     self.assertEqual(str(wire), "tesT")
     wire[0] = "J"
     self.assertEqual(str(wire), "JesT")
Exemplo n.º 34
0
    def testRemoveDuplicate(self):
        """
        Tests Wire.removeDuplicate() 
        Tests with:
        - inOrder=True, caseSensitive=True
        - inOrder=False, caseSensitive=True
        - inOrder=True, caseSensitive=False
        - inOrder=False, caseSensitive=False
        """

        wire = Wire("Tester")
        wire = wire.removeDuplicate(inOrder=True)
        self.assertEqual(wire, "Testr")

        wire = Wire("Tester")
        wire = wire.removeDuplicate(inOrder=False)
        singles = ""
        for letter in list(wire):
            # This is a tricky bit of code here (don't let it confuse you)
            # What it does is it asserts that the letter is not in singles
            # which is defined before the for loop, if things go well
            # and an AssertionError is not made, then that letter is then added to singles
            # If there is a duplicate letter, then AssertionError would be made.
            self.assertNotIn(letter, singles)
            singles += letter

        wire = Wire("Tester")
        wire = wire.removeDuplicate(caseSensitive=False)
        singles = ""
        for letter in list(wire):
            # Same as above
            self.assertNotIn(letter.lower(), singles)
            singles += letter

        wire = Wire("Tester")
        wire = wire.removeDuplicate(inOrder=False, caseSensitive=False)