示例#1
0
def test_simulator_run():
    """Test if the run() method returns the computed statistics"""
    board = sg.Board(size=(10, 10))
    board.add(lf.Blinker(length=3), loc=(0, 1))
    sim = sg.Simulator(board)
    stats = sim.run(sg.rules.conway_classic, iters=10)
    assert isinstance(stats, dict)
示例#2
0
def test_simulator_animate_without_run():
    """Test if animate() method throws an error when called before run()"""
    board = sg.Board(size=(10, 10))
    board.add(lf.Blinker(length=3), loc=(0, 1))
    sim = sg.Simulator(board)
    with pytest.raises(ValueError):
        sim.animate()
示例#3
0
def test_compute_statistics():
    """Test if compute_statistics() returns a dictionary"""
    board = sg.Board(size=(10, 10))
    board.add(lf.Blinker(length=3), loc=(0, 1))
    sim = sg.Simulator(board)
    sim.run(sg.rules.conway_classic, iters=10)
    stats = sim.compute_statistics(sim.get_history())
    assert isinstance(stats, dict)
示例#4
0
def test_simulator_animate():
    """Test if animate() method returns a FuncAnimation"""
    board = sg.Board(size=(10, 10))
    board.add(lf.Blinker(length=3), loc=(0, 1))
    sim = sg.Simulator(board)
    sim.run(sg.rules.conway_classic, iters=10)
    anim = sim.animate()
    assert isinstance(anim, animation.FuncAnimation)
示例#5
0
def test_simulator_get_history_shape():
    """Test if get_history() will return the expected shape"""
    board = sg.Board(size=(10, 10))
    board.add(lf.Blinker(length=3), loc=(0, 1))
    sim = sg.Simulator(board)
    sim.run(sg.rules.conway_classic, iters=10)
    hist = sim.get_history()
    assert hist.shape == (10, 10, 10)
示例#6
0
def test_simulator_inplace():
    """Test if board state didn't change after a simulation run"""
    board = sg.Board(size=(10, 10))
    board.add(lf.Glider(), loc=(0, 0))

    # Initial board state, must be the same always
    init_board = board.state.copy()

    # Run simulator
    sim = sg.Simulator(board)
    sim.run(sg.rules.conway_classic, iters=10)
    assert np.array_equal(board.state, init_board)
示例#7
0
from lib import imageToBinary as i2b

MULTICAST_GROUP = ('239.1.2.3', 8080)

WIDTH = 64
HEIGHT = 32
ITERS = 900

board = sg.Board(size=(HEIGHT, WIDTH))

np.random.seed(42)
noise = np.random.choice([0, 1], size=(HEIGHT, WIDTH))
custom_lf = lf.Custom(noise)
board.add(custom_lf, loc=(0, 0))

sim = sg.Simulator(board)

sock = socket.socket(
    socket.AF_INET,  # Internet
    socket.SOCK_DGRAM)  # UDP
ttl = struct.pack('b', 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)

sim.run(sg.rules.conway_classic, iters=ITERS)

for i in range(ITERS):

    final = np.asarray(sim.get_history()[i] * 255, dtype=np.uint8)
    final = cv2.cvtColor(final, cv2.COLOR_GRAY2BGR)
    sock.sendto(i2b.imageToBinary(final, WIDTH, HEIGHT), MULTICAST_GROUP)
示例#8
0
def make_sprite(
    n_sprites: int,
    n_iters: int,
    repro_rate: int,
    stasis_rate: int,
):
    """Main function for creating sprites

    Parameters
    ----------
    n_sprites : int
        Number of sprites to generate
    n_iters : int
        Number of iterations to run the simulator
    repro_rate : int
        Inverse reproduction rate
    stasis_rate : int
        Stasis rate
    """
    logger.info("Initializing board")
    board = sg.Board(size=(8, 4))

    logger.info("Running simulation")
    sprator_list = []

    for sprite in range(n_sprites):
        noise = np.random.choice([0, 1], size=(8, 4))
        custom_lf = lf.Custom(noise)
        board.add(custom_lf, loc=(0, 0))
        sim = sg.Simulator(board)
        sim.run(
            custom_rule,
            iters=n_iters,
            repro_rate=repro_rate,
            stasis_rate=stasis_rate,
        )
        fstate = sim.get_history()[-1]

        logger.info(f"Generating sprite/s: {sprite}")
        sprator = np.hstack([fstate, np.fliplr(fstate)])
        sprator = np.pad(sprator,
                         mode="constant",
                         pad_width=1,
                         constant_values=1)
        sprator_with_outline = add_outline(sprator)
        sprator_gradient = get_gradient(sprator_with_outline)
        sprator_final = combine(sprator_with_outline, sprator_gradient)
        sprator_list.append(sprator_final)

    # Generate plot based on the grid size
    n_grid = int(sqrt(n_sprites))

    # Generate random colors as cmap
    r = lambda: "#%02X%02X%02X" % (
        random.randint(0, 255),
        random.randint(0, 255),
        random.randint(0, 255),
    )
    colors = ["black", "#f2f2f2", r(), r(), r()]
    cm.register_cmap(cmap=mpl.colors.LinearSegmentedColormap.from_list(
        "custom", colors).reversed())

    if n_grid == 1:
        fig, axs = plt.subplots(n_grid, n_grid, figsize=(5, 5))
        axs = fig.add_axes([0, 0, 1, 1], xticks=[], yticks=[], frameon=False)
        axs.imshow(sprator_list[0], cmap="custom_r", interpolation="nearest")
        fig.text(0, -0.05, "bit.ly/CellularSprites", ha="left", color="black")
    else:
        fig, axs = plt.subplots(n_grid, n_grid, figsize=(5, 5))
        for ax, sprator in zip(axs.flat, sprator_list):
            # TODO: Remove duplicates
            # Generate random colors as cmap
            r = lambda: "#%02X%02X%02X" % (
                random.randint(0, 255),
                random.randint(0, 255),
                random.randint(0, 255),
            )
            colors = ["black", "#f2f2f2", r(), r(), r()]
            cm.register_cmap(cmap=mpl.colors.LinearSegmentedColormap.from_list(
                "custom", colors).reversed())
            ax.imshow(sprator, cmap="custom_r", interpolation="nearest")
            ax.set_axis_off()
        fig.text(0.125, 0.05, "bit.ly/CellularSprites", ha="left")

    return fig
def generate_sprite(
    n_iters: int = 1,
    extinction: float = 0.125,
    survival: float = 0.375,
    size: int = 180,
    sprite_seed: int = None,
    color_seeds: List[int] = None,
):
    """Generate a sprite given various parameters

    Parameters
    ----------
    n_iters : int
        Number of iterations to run Conway's Game of Life.
    extinction : float (0.0 to 1.0)
        Controls how many dead cells will stay dead on the next iteration
        Default is 0.125 (around 1 cell)
    survival: float (0.0 to 1.0)
        Controls how many live cells will stay alive on the next iteration.
        Default is 0.375 (around 3 cells)
    size : int
        Size of the generated sprite in pixels. Default is 180 for 180 x 180px.
    sprite_seed : int (optional)
        Random seed for the Sprite. Default is None
    color_seeds : list (optional)
        Random seed for the colors. Default is None

    Returns
    -------
    matplotlib.Figure
    """
    logger.debug("Initializing board")
    board = sg.Board(size=(8, 4))

    logger.debug("Seeding the lifeform")
    if sprite_seed:
        np.random.seed(sprite_seed)
    noise = np.random.choice([0, 1], size=(8, 4))
    custom_lf = lf.Custom(noise)
    board.add(custom_lf, loc=(0, 0))

    logger.debug("Running the simulation")
    sim = sg.Simulator(board)
    sim.run(
        _custom_rule,
        iters=n_iters,
        n_extinct=int(extinction * 8),
        n_survive=int(survival * 8),
    )
    fstate = sim.get_history()[-1]

    logger.debug("Adding outline, gradient, and colors")
    sprite = np.hstack([fstate, np.fliplr(fstate)])
    sprite = np.pad(sprite, mode="constant", pad_width=1, constant_values=1)
    sprite_with_outline = _add_outline(sprite)
    sprite_gradient = _get_gradient(sprite_with_outline)
    sprite_final = _combine(sprite_with_outline, sprite_gradient)

    logger.trace("Registering a colormap")
    iterator = list(_group(3, color_seeds))[:3] if color_seeds else [None] * 3
    random_colors = [_color(seeds) for seeds in iterator]
    base_colors = ["black", "#f2f2f2"]
    colors = base_colors + random_colors
    logger.trace(f"Colors to use: {colors}")
    cm.register_cmap(
        cmap=mpl.colors.LinearSegmentedColormap.from_list(
            "custom", colors
        ).reversed()
    )

    logger.debug("Preparing final image")
    fig, axs = plt.subplots(1, 1, figsize=(1, 1), dpi=size)
    axs = fig.add_axes([0, 0, 1, 1], xticks=[], yticks=[], frameon=False)
    axs.imshow(sprite_final, cmap="custom_r", interpolation="nearest")
    logger.debug("Successfully generated sprite!")
    return fig