コード例 #1
0
ファイル: particle.py プロジェクト: Stasiche/Space
 def __init__(self, r, name='noname', v=Vector2d(0, 0), mass=1):
     self.r = r
     self.v = v
     self.name = name
     self.mass = mass
     self.force = Vector2d(0, 0)
     self.color = (1, 1, 1)
コード例 #2
0
ファイル: test.py プロジェクト: Stasiche/Space
def make_univer(n_particles=int(10e6)):
    max_v = 1
    min_v = -1
    particles = [Particle(r=Vector2d(random.uniform(-box_size // 2, box_size // 2),
                                             random.uniform(-box_size // 2, box_size // 2)),
                                  v=Vector2d(random.uniform(min_v, max_v),
                                             random.uniform(min_v, max_v)))]
    # global box_size

    i = 1
    while True:
        # if i % (n_particles//100) == 0:
        #     print('box:', i // (n_particles//100) + 1)
        tmp_par = Particle(r=Vector2d(random.uniform(-box_size // 2, box_size // 2),
                                             random.uniform(-box_size // 2, box_size // 2)),
                                  v=Vector2d(random.uniform(min_v, max_v),
                                             random.uniform(min_v, max_v)))
        flag = 1
        # for particle1 in particles:
        #     tmp_e = particle1.r - tmp_par.r
        #     if abs(tmp_e) == 0:
        #         continue
        #     tmp_f = forces.base_force(particle1, tmp_par)
        #     if (tmp_f.x*tmp_e.x + tmp_f.y*tmp_e.y) < 0:
        #         flag = 0

        if flag == 1:
            particles.append(tmp_par)
            i += 1

        if i >= n_particles:
            break

        # print(i)
    return particles
コード例 #3
0
ファイル: solver.py プロジェクト: tkuestner/netwalk
 def _add_edges(self):
     for x, y in itertools.product(range(self.columns), range(self.rows)):
         node = Vector2d(x, y)
         right_neighbor = Vector2d((x + 1) % self.columns, y)
         top_neighbor = Vector2d(x, (y + 1) % self.rows)
         self._edges[node, right_neighbor] = Edges.State.unknown
         self._edges[right_neighbor, node] = Edges.State.unknown
         self._edges[node, top_neighbor] = Edges.State.unknown
         self._edges[top_neighbor, node] = Edges.State.unknown
コード例 #4
0
ファイル: bh_tree.py プロジェクト: Stasiche/Space
    def calculate_force(self, particle, node=None):
        if node is None:
            node = self.root

        force = Vector2d(0, 0)
        if len(node.particles) == 0:
            return force

        # if (node.type == 2) and (abs(node.particles[0].r - particle.r) != 0):
        if (node.type == 2) and (node.particles[0] != particle):
            tmp_f = forces.base_force(particle, node.particles[0])
            # print(particle.name, node.name, node.depth, len(node.particles))
            # if particle.name == constants.median:
            #     tmp_brute_f = Vector2d()
            #     for particle_brute in node.particles:
            #         tmp_brute_f += forces.base_force(particle, particle_brute)
            #
            #     len_error = (abs(tmp_f) - abs(tmp_brute_f)) / (abs(tmp_brute_f) + constants.epsilon)
            #     print(len_error, '|', tmp_f, '|', tmp_brute_f)
            force += tmp_f

        cm = node.get_cm()
        if (node.type == 1) and (mac.mac(particle, node)):
            # print(particle.name, node.name)
            # print(particle.name,  node.name, node.depth, len(node.particles))
            tmp_f = forces.base_force(
                particle,
                Particle(r=cm, v=node.get_mv(), mass=node.mass, name='aprox'))

            a = 0.1
            b = 0.8
            tmp_color = ((b - a) * np.random.random() + a,
                         (b - a) * np.random.random() + a,
                         (b - a) * np.random.random() + a)

            self.save_particles += len(node.particles) - 1
            for particle_color in node.particles:
                particle_color.color = tmp_color

            if particle.name == constants.median:
                tmp_brute_f = Vector2d()
                for particle_brute in node.particles:
                    tmp_brute_f += forces.base_force(particle, particle_brute)

                len_error = (abs(tmp_f) - abs(tmp_brute_f)) / (
                    abs(tmp_brute_f) + constants.epsilon)
                print(len_error, '|', tmp_f, '|', abs(tmp_f), '|', tmp_brute_f,
                      '|', abs(tmp_brute_f))
            force += tmp_f

        if (node.type == 1) and not (mac.mac(particle, node)):
            for child in node.children:
                force += self.calculate_force(particle, child)

        return force
コード例 #5
0
ファイル: dinamic_NTC.py プロジェクト: Stasiche/Space
def make_net(n_particles=int(10e6)):
    particles = []
    n_rows = int(math.sqrt(n_particles))
    h = constants.box_size // n_rows
    for i in range(n_particles):
        particles.append(
            Particle(r=Vector2d(i % n_rows * h, i // n_rows * h),
                     v=Vector2d()))
        # print(particles[-1].r)

    return particles, h
コード例 #6
0
ファイル: solver.py プロジェクト: tkuestner/netwalk
 def _handle_walls(self, walls):
     """Remove edges where there are walls."""
     for w in walls:
         tile1 = w.position
         tile2 = None
         if w.orientation == Wall.Orientation.horizontal:
             tile2 = w.position - Vector2d(0, 1)
         if w.orientation == Wall.Orientation.vertical:
             tile2 = w.position - Vector2d(1, 0)
         tile1 = self.grid.normalize(tile1)
         tile2 = self.grid.normalize(tile2)
         self.edges[tile1, tile2] = Edges.State.absent
コード例 #7
0
ファイル: atom.py プロジェクト: MikeHibbert/Osmos-Clone
 def __init__(self, x, y, width, hieght, image, isPlayer=False):
     self.position = Vector2d(x, y)
     self.sprite = image
     self.velocity = Vector2d(0, 0)
     self.isPlayer = isPlayer
     self.width = width
     self.height = hieght
     self.radius = width / 2
     self.mass = self.radius * ATOM_MASS_PER_PER_PIXEL
     self.isVisible = True
     self.font = pygame.font.Font('freesansbold.ttf', 10) 
     self.colliding = False
コード例 #8
0
ファイル: main.py プロジェクト: MikeHibbert/Osmos-Clone
    def apply_player_direction(self, delta):
        direction = Vector2d(0, 0)

        if self.moveDOWN:
            direction += Vector2d(0, PLAYER_ACCELERATION)
        if self.moveUP:
            direction += Vector2d(0, -PLAYER_ACCELERATION)
        if self.moveRIGHT:
            direction += Vector2d(PLAYER_ACCELERATION, 0)
        if self.moveLEFT:
            direction += Vector2d(-PLAYER_ACCELERATION, 0)

        self.playerAtom.velocity += direction
コード例 #9
0
def make_hex_2(r, center):
    particles = [Particle(r=center, v=Vector2d(), name=0)]

    for i in range(r):
        tmp_par = []
        for angle in [j * math.pi / 3 for j in range(6)]:
            tmp_par.append(
                Particle(r=center + Vector2d(
                    (i + 1) * constants.a * math.sin(angle),
                    (i + 1) * constants.a * math.cos(angle)),
                         v=Vector2d(),
                         name=len(particles)))

        for j, particle in enumerate(tmp_par[:-1]):
            particles.append(particle)

            # fig, ax1 = plt.subplots(figsize=(4, 4))
            # x = [particle.r.x for particle in particles]
            # y = [particle.r.y for particle in particles]
            # ax1.scatter(x=x, y=y, marker='o', c='r', edgecolor='b')
            # ax1.set_title('Scatter: $x$ versus $y$')
            # ax1.set_xlabel('$x$')
            # ax1.set_ylabel('$y$')
            # plt.show()

            e_tmp = particle.r - tmp_par[j + 1].r
            e_tmp = e_tmp * (1 / abs(e_tmp))
            for k in range(i):
                particles.append(
                    Particle(r=particle.r - e_tmp * constants.a,
                             v=Vector2d(),
                             name=len(particles)))

                # fig, ax1 = plt.subplots(figsize=(4, 4))
                # x = [particle.r.x for particle in particles]
                # y = [particle.r.y for particle in particles]
                # ax1.scatter(x=x, y=y, marker='o', c='r', edgecolor='b')
                # ax1.set_title('Scatter: $x$ versus $y$')
                # ax1.set_xlabel('$x$')
                # ax1.set_ylabel('$y$')
                # plt.show()

        particles.append(tmp_par[-1])
        e_tmp = tmp_par[-1].r - tmp_par[0].r
        e_tmp = e_tmp * (1 / abs(e_tmp))
        for k in range(i):
            particles.append(
                Particle(r=particle.r - e_tmp * constants.a,
                         v=Vector2d(),
                         name=len(particles)))
    return particles
コード例 #10
0
 def _setup_walls(self):
     for w in self.puzzle.walls:
         self.grid.add_widget(WallWidget(w))
         # Double the walls on the board's borders
         if w.position.x == 0 and w.orientation == Wall.Orientation.vertical:
             w2 = Wall(Vector2d(w.position.x + self.columns, w.position.y),
                       w.orientation)
             # noinspection PyTypeChecker
             self.grid.add_widget(WallWidget(w2))
         if w.position.y == 0 and w.orientation == Wall.Orientation.horizontal:
             w2 = Wall(Vector2d(w.position.x, w.position.y + self.rows),
                       w.orientation)
             # noinspection PyTypeChecker
             self.grid.add_widget(WallWidget(w2))
コード例 #11
0
ファイル: main2.py プロジェクト: Stasiche/Space
def make_univer(n_particles=int(10e6)):
    particles = []
    # global box_size
    max_v = 1
    min_v = -1
    for i in range(n_particles):
        if i % (n_particles // 100) == 0:
            print(i // (n_particles // 100) + 1)
        particles.append(
            Particle(r=Vector2d(random.randint(-box_size // 2, box_size // 2),
                                random.randint(-box_size // 2, box_size // 2)),
                     v=Vector2d(random.randint(min_v, max_v),
                                random.randint(min_v, max_v))))

    return particles
コード例 #12
0
ファイル: diplom2.py プロジェクト: Stasiche/Space
def create_sphere2(radii, lengths, num_sumples=2000, mass=1):
    attempts = 100
    # particles = [Particle(r=Vector3d(), mass=10)]
    particles = []
    num = 100
    for i in range(0, len(lengths) // num):
        cur_num_particles = 0
        while True:
            u = np.random.uniform(0, 2 * np.pi)
            tmp_z = np.random.uniform(0, 1)

            mul = tmp_z**(1 / 3)
            # mul = (mul * lengths[i*num + num-1]) + (lengths[i*num + num-1] - lengths[i*num])
            mul = lengths[i * num] + mul * (lengths[i * num + num - 1] -
                                            lengths[i * num])
            r1 = radii[0] * mul
            r2 = radii[1] * mul

            tmp = [r1 * np.cos(u), r2 * np.sin(u)]
            if criterion(tmp, particles):
                [x, y] = [tmp[0], tmp[1]]
                particles.append(Particle(r=Vector2d(x, y), mass=mass))

                cur_num_particles += 1
            # if cur_num_particles % 1 == 0:
            #     print(cur_num_particles)
            if cur_num_particles == num // 10:
                break
    return particles
コード例 #13
0
ファイル: solver.py プロジェクト: tkuestner/netwalk
    def _inspect_tile(self, node, state):
        """Inspect a single tile/node and try to reduce the number of possible orientations left by trying one after
        another.
        """
        tile = state.tiles[node]

        if len(tile.possible_orientations) <= 0:
            return len(tile.possible_orientations)

        tile.possible_orientations = [o for o in tile.possible_orientations if self._valid_orientation(node, o, state)]

        # noinspection PyTypeChecker
        for i, d in enumerate(Direction):
            collected_edges = []
            for o in tile.possible_orientations:
                connectors = tile_connectors[tile.link][o]
                collected_edges.append(connectors[i])
            # Reduce: check all edges are the same, either all True or all False
            if collected_edges and collected_edges.count(collected_edges[0]) == len(collected_edges):
                edge_state = collected_edges[0]
            else:
                continue
            child = node + d.vector
            child = Vector2d(child.x % self.columns, child.y % self.rows)
            # edge_state is either True or False
            if state.edges[node, child] is not Edges.State.unknown:
                assert ((edge_state is True and state.edges[node, child] is Edges.State.present) or
                        (edge_state is False and state.edges[node, child] is Edges.State.absent))
            state.edges[node, child] = Edges.State.present if edge_state is True else Edges.State.absent
コード例 #14
0
ファイル: solver.py プロジェクト: tkuestner/netwalk
 def run(self):
     """Run the solver. This might take some time."""
     all_tiles = deque(n for n in self.grid)
     initial_state = Solver.State(self.tiles, self.edges)
     self._handle_simple_tiles(initial_state)
     work_stack = [Solver.WorkItem(initial_state, all_tiles)]
     while work_stack:
         item = work_stack.pop()
         state = item.state
         work = item.work
         investigate = self._forward_inference(state, work)
         if not investigate:
             continue  # Pop next state from stack
         # Choose tile with least amount of possible orientations left
         minimum = None
         min_pos = Vector2d(0, 0)
         for node in self.grid:
             orientations = len(state.tiles[node].possible_orientations)
             if orientations >= 2 and (minimum is None or orientations < minimum):
                 minimum = orientations
                 min_pos = node
         assert minimum is not None
         for o in state.tiles[min_pos].possible_orientations:
             neighbors = deque(self.grid.neighbors(min_pos))
             child_state = state.clone()
             child_state.tiles[min_pos].possible_orientations = [o]
             self._inspect_tile(min_pos, child_state)  # apply this orientation to edges
             work_stack.append(Solver.WorkItem(child_state, neighbors))
     print("Found {} solution(s)".format(len(self.solutions)))
コード例 #15
0
ファイル: atom.py プロジェクト: MikeHibbert/Osmos-Clone
 def collides_with(self, entity):
     retVal = False
     if self.isVisible and entity.isVisible:
         myPosition = Vector2d( self.position.x - self.radius, 
                                self.position.y - self.radius)
         entityPosition = Vector2d( entity.position.x - entity.radius, 
                                        entity.position.y - entity.radius)   
         
         totalRadiuses = self.radius + entity.radius
         distance = myPosition - entityPosition
         
         if distance.length() < totalRadiuses:
             retVal = True
             self.colliding = True
         
     return retVal
コード例 #16
0
    def calculate_force(self, particle, node=None):
        if node is None:
            node = self.root

        force = Vector2d(0, 0)
        if len(node.particles) == 0:
            return force

        if (node.type == 2) and (node.particles[0] != particle):
            tmp_f = forces.base_force(particle, node.particles[0])
            # print(particle.name, node.name, node.depth, len(node.particles))
            force += tmp_f

        cm = node.get_cm()
        if (node.type == 1) and (mac.mac(particle, node)):
            # print(particle.name, node.name)
            # print(particle.name,  node.name, node.depth, len(node.particles))
            tmp_f = forces.base_force(particle, Particle(r=cm, v=node.get_mv(), mass=node.mass))

            force += tmp_f

        if (node.type == 1) and not(mac.mac(particle, node)):
            for child in node.children:
                force += self.calculate_force(particle, child)

        return force
コード例 #17
0
ファイル: diplom2.py プロジェクト: Stasiche/Space
def criterion(tmp, particles):
    tmp_particle = Particle(r=Vector2d(*tmp))
    for particle in particles:
        # print((tmp_particle.r - particle.r).dot(forces.base_force(tmp_particle, particle)))
        # if (tmp_particle.r - particle.r).dot(forces.base_force(tmp_particle, particle)) > -0.3:
        if abs(tmp_particle.r - particle.r) < 1 * constants.a:
            return False
    return True
コード例 #18
0
ファイル: l2z2b.py プロジェクト: piotrnarecki/lista2Python
def main():
    print("correct vector:")
    correct_vector = Vector2d(-6.9, 42)
    correct_vector.print_vector()
    print("length:", correct_vector.vector_length())
    print()

    print("multiplied vector:")
    multiplied_vector1 = correct_vector.multiply_vector(5)
    multiplied_vector1.print_vector()
    print()

    print("vector multiplied by wrong factor:")
    multiplied_vector2 = correct_vector.multiply_vector('f')
    multiplied_vector2.print_vector()
    print()

    print("vector multiplied by nothing:")
    multiplied_vector2 = correct_vector.multiply_vector()
    multiplied_vector2.print_vector()
    print()

    print("wrong argument vector:")
    wrong_argument_vector = Vector2d(-6.9, 'f')
    wrong_argument_vector.print_vector()
    print(wrong_argument_vector.vector_length())
    print

    print("not enough arguments vector:")
    not_enough_arguments_vector = Vector2d(65)
    not_enough_arguments_vector.print_vector()
    print(not_enough_arguments_vector.vector_length())
    print()

    print("no arguments vector:")
    no_arguments_vector = Vector2d()
    no_arguments_vector.print_vector()
    print no_arguments_vector.vector_length()
    print()

    print("to much arguments vector:")
    to_much_arguments_vector = Vector2d(2, 3, 4)
    to_much_arguments_vector.print_vector()
    print(to_much_arguments_vector.vector_length())
    print()
コード例 #19
0
ファイル: io_xyz.py プロジェクト: Stasiche/Barnes-Hut
def read(read_path):
    particles = []
    with open(read_path, 'r') as inputfile:
        s_tmp = inputfile.read()
        for el in s_tmp.split('\n')[2:]:
            if el != '':
                rx, ry, cr, cg, cb = el.split()
                particles.append(Particle(r=Vector2d(float(rx), float(ry)), name=len(particles)))
    return particles
コード例 #20
0
    def run(self):
        """Execute the builder

        :return: The created puzzle
        :rtype: Puzzle
        """
        self._source = Vector2d(self.columns // 2, self.rows // 2)
        grid = self._create_tree()
        walls = self._create_walls()
        rotated_tiles = self._rotate(grid)
        return Puzzle(grid, walls, self._source, rotated_tiles, self.wrap)
コード例 #21
0
ファイル: dinamic_NTC.py プロジェクト: Stasiche/Space
def make_hex(k=10, l=10):
    # k количество рядов до середины
    # l количество в крайнем ряду
    particles = []
    for i in range(k):
        for j in range(i + l):
            particles.append(
                Particle(r=Vector2d(constants.a * i * math.sqrt(3) / 2,
                                    constants.a * j - constants.a * 0.5 * i),
                         v=Vector2d(),
                         name=len(particles)))
    for i in range(k, 2 * k - 1):
        for j in range(l + k - 2 - (i - k)):
            particles.append(
                Particle(r=Vector2d(
                    constants.a * i * math.sqrt(3) / 2,
                    constants.a * j + constants.a * 0.5 * (i - 2 * k + 2)),
                         v=Vector2d(),
                         name=len(particles)))
    return particles
コード例 #22
0
    def _create_walls(self, percent=0.06, rsd=0.2):
        """Randomly place some walls

        The actual number of walls is drawn from a normal distribution.

        :param float percent: Mean percent of walls to be created
        :param float rsd: Relative standard deviation
        """
        walls = set()  # collect all possible walls
        for x, y in itertools.product(range(self.columns), range(self.rows)):
            if (self.wrap
                    or y != 0) and not self._nodes[x, y].edges[Direction.down]:
                walls.add(Wall(Vector2d(x, y), Wall.Orientation.horizontal))
            if (self.wrap
                    or x != 0) and not self._nodes[x, y].edges[Direction.left]:
                walls.add(Wall(Vector2d(x, y), Wall.Orientation.vertical))
        mean = len(walls) * percent
        count = clamp(int(random.gauss(mean, rsd * mean)), 0, len(walls))
        walls = random.sample(walls, count)
        return walls
コード例 #23
0
ファイル: diplom2.py プロジェクト: Stasiche/Space
def get_and_plot_density(particles, radii, rotation, center, num=100):
    cm = Vector2d()
    particles_ = copy.deepcopy(particles)

    derotation = np.linalg.inv(rotation)

    for particle in particles_:
        particle.r.x -= center[0]
        particle.r.y -= center[1]

        tmp = np.dot(np.array([particle.r.x, particle.r.y]), derotation)
        particle.r = Vector2d(tmp[0], tmp[1])

        cm += particle.r
    cm = cm * (1 / len(particles_))

    for i in range(len(particles)):
        particles_[i].r.x *= 1 / radii[0]
        particles_[i].r.y *= 1 / radii[1]

    lengths = sorted([abs(particle.r) for particle in particles_])
    density = []
    l = []
    # particles = sorted(particles, key=lambda particle: abs(particle.r - cm))

    for i in range(len(lengths) // num):
        density.append(num * particles_[0].mass /
                       (np.pi *
                        (lengths[i * num + num - 1]**2 - lengths[i * num]**2)))
        # l.append(lengths[i*num] + 0.5*(lengths[i*num + num-1] - lengths[i*num]))
        l.append(lengths[i * num])

    ig, ax1 = plt.subplots(figsize=(4, 4))

    ax1.scatter(x=l, y=density, marker='o', c='r', edgecolor='b')
    ax1.set_title('Scatter: $x$ versus $y$')
    ax1.set_xlabel('$x$')
    ax1.set_ylabel('$y$')
    plt.show()

    return density, lengths
コード例 #24
0
 def example(cls):
     """A simple example puzzle"""
     grid = GridContainer(Grid(3, 3))
     grid[0, 2] = Tile(LinkType.dead_end, Direction.down)
     grid[1, 2] = Tile(LinkType.t_intersection, Direction.right)
     grid[2, 2] = Tile(LinkType.corner, Direction.left)
     grid[0, 1] = Tile(LinkType.dead_end, Direction.down)
     grid[1, 1] = Tile(LinkType.t_intersection, Direction.down)
     grid[1, 1].entity = EntityType.source
     grid[2, 1] = Tile(LinkType.straight, Direction.right)
     grid[0, 0] = Tile(LinkType.dead_end, Direction.down)
     grid[1, 0] = Tile(LinkType.corner, Direction.up)
     grid[2, 0] = Tile(LinkType.dead_end, Direction.right)
     walls = {
         Wall(Vector2d(0, 2), Wall.Orientation.horizontal),
         Wall(Vector2d(2, 1), Wall.Orientation.vertical)
     }
     return Puzzle(grid,
                   walls,
                   source=Vector2d(1, 1),
                   expected_moves=7,
                   wrap=False)
コード例 #25
0
ファイル: solver.py プロジェクト: tkuestner/netwalk
 def _valid_orientation(self, node, orientation, state):
     """Check if for a given node/tile, the given orientation is possible, i.e. compatible with the surrounding
     tiles.
     """
     connectors = tile_connectors[state.tiles[node].link][orientation]
     for d in Direction:
         child = node + d.vector
         child = Vector2d(child.x % self.columns, child.y % self.rows)
         if state.edges[node, child] is Edges.State.unknown:
             continue
         elif ((connectors[d.index] is True and state.edges[node, child] is Edges.State.absent) or
               (connectors[d.index] is False and state.edges[node, child] is Edges.State.present)):
             return False
     return True
コード例 #26
0
ファイル: polygon.py プロジェクト: lynch829/brachyprint
    def get_vertex(self, x, y=None):
        """Get a vertex from the polygon, if extant.
        
        :param x: x coordinate of the vertex, or optionally a list of coordinates.
        :keyword y: y coordinate of the vertex.

        XXX: this is currently very slow!
        """
        if not isinstance(x, Vector2d):
            x = Vector2d(x, y)

        for v in self.vertices:
            if v == x:
                return v

        return None
コード例 #27
0
    def _create_tree(self):
        """Create the underlying tree.

        The algorithm starts with a source in the center and chooses an already visited tile at random to extend the
        tree to a random unvisited tile.
        """
        self._nodes = GridContainer(Grid(self.columns, self.rows))
        nodes = self._nodes  # alias
        for x, y in itertools.product(range(self.columns), range(self.rows)):
            nodes[x, y] = Builder.Node()
        visited = GridContainer(Grid(self.columns, self.rows), False)
        visited[self._source] = True
        boundary = {self._source}
        while True:
            new_boundary = set()
            moves = []  # [(parent, child, direction), ...]  FIXME namedtuple
            for parent in boundary:
                for direction in Direction:
                    child = parent + direction.vector
                    if self.wrap:
                        child = Vector2d(child.x % self.columns,
                                         child.y % self.rows)
                    if 0 <= child.x < self.columns and 0 <= child.y < self.rows and not visited[
                            child]:
                        moves.append((parent, child, direction))
                        new_boundary.add(parent)
            if not moves:
                break
            weights = []
            for p, _, d in moves:
                nodes[p].edges[d] = True
                link = nodes[p].to_tile().link
                nodes[p].edges[d] = False
                weights.append(self.difficulties[self.difficulty][link])
            parent, child, direction = weighted_choice(moves, weights)
            new_boundary.add(child)
            visited[child] = True
            nodes[parent].edges[direction] = True
            nodes[child].edges[-direction] = True
            boundary = new_boundary

        # Transform nodes/edges into tiles with link type and orientation
        tiles = GridContainer(Grid(self.columns, self.rows))
        for x, y in itertools.product(range(self.columns), range(self.rows)):
            tiles[x, y] = nodes[x, y].to_tile()
        tiles[self._source].entity = EntityType.source
        return tiles
コード例 #28
0
 def check_power(self):
     """Check which tile is connected to the power source"""
     power = GridContainer(Grid(self.columns, self.rows), False)
     work = {self.puzzle.source}
     while work:
         parent = work.pop()
         power[parent] = True
         for direction in Direction:
             proto_child = parent + direction.vector
             if not self.puzzle.wrap and not self.board.grid.valid(
                     proto_child):
                 continue
             child = Vector2d(proto_child.x % self.columns,
                              proto_child.y % self.rows)
             # noinspection PyTypeChecker
             if (not power[child]
                     and self._connected(parent, child, direction)
                     and not self._blocking_wall(parent, proto_child)):
                 work.add(child)
     for x, y in itertools.product(range(self.columns), range(self.rows)):
         self.board[x, y].powered = power[x, y]
コード例 #29
0
ファイル: integrator.py プロジェクト: slode/triton
def main():
    from vector2d import Vector2d

    def f(t, x):
        return Vector2d(-1.9 * x[0] - 1.7 * x[1], x[0])

    t = 0
    dt = 0.05
    x = Vector2d(20, 10)
    data1 = []
    data2 = []
    for i in range(300):
        t, x = Integrator.rk4(t, dt, x, f)
        # vel
        data1.append((t, x[0]))
        #pos
        data2.append((t, x[1]))

    from pylab import plot, show, legend
    p1, = plot([i for i, j in data1], [j for i, j in data1], 'k--')
    p2, = plot([i for i, j in data2], [j for i, j in data2], 'k-')
    legend([p1, p2], ["Velocity", "Position"])
    show()
コード例 #30
0
ファイル: solver.py プロジェクト: tkuestner/netwalk
 def _handle_boundary(self):
     """Initialize edges, depending on the 'wrapping' option of the game."""
     for x in range(self.columns):
         self.edges[Vector2d(x, 0), Vector2d(x, self.rows - 1)] = Edges.State.absent
     for y in range(self.rows):
         self.edges[Vector2d(0, y), Vector2d(self.columns - 1, y)] = Edges.State.absent