Beispiel #1
0
def simulation(size, steps):
    np.random.seed(None)

    grow = ChangeStateRule(from_state=0, to_state=1, p_change=0.0025)
    lightning = ChangeStateRule(
        from_state=1,
        to_state=2,
        p_change=1e-5,
    )
    burn = SlowBurnRule()

    forest = CellularAutomaton(
        shape=size,
        rules=[grow, lightning, burn],
    )
    recorder = AutomataRecorder(automaton=forest)

    forest.start()
    for i in range(steps):
        forest.step()

    palette = np.zeros((256, 3), dtype='uint8')
    palette[1] = [0, 255, 0]
    palette[2] = [255, 0, 0]
    palette[3] = [255, 255, 255]

    save_image_sequence(recorder, 'test.gif', palette, 100)
Beispiel #2
0
def simulation(p_mold, size, steps, transform=None):
    np.random.seed(None)

    grow = ChangeStateRule(from_state=0, to_state=1, p_change=0.0025)
    # lightning = ChangeStateRule(
    #     from_state=1,
    #     to_state=2,
    #     p_change=1e-5,
    # )
    # burn = SlowBurnRule()
    burn_groves = BurnGrovesRule()
    mold = MoldRule(dead_state=3, p_mold=p_mold)
    mold_die = ChangeStateRule(from_state=3, to_state=0, p_change=1.0)
    fire_out = ChangeStateRule(from_state=2, to_state=0, p_change=1.0)

    forest = CellularAutomaton(
        shape=size,
        rules=[mold_die, fire_out, grow, burn_groves, mold],
    )
    recorder = AutomataRecorder(automaton=forest, transform=transform)

    forest.start()
    for i in range(steps):
        forest.step()

    return recorder.as_array()[:, 1:4].T
Beispiel #3
0
def run_single_simulation(initial_state_path, n_steps, movie_path,
                          interactive_plot_path):
    logging.info("Loading initial state from %s" % initial_state_path)
    try:
        initial_state = np.load(initial_state_path)
    except ValueError:
        try:
            initial_state = numpy.loadtxt(initial_state_path)
        except ValueError:
            try:
                initial_state = numpy.loadtxt(initial_state_path,
                                              delimiter=",")
            except ValueError:
                logging.error(
                    "Invalid input file %s provided. Only binary files in Numpy format and"
                    "space or comma-separated text files are supported." %
                    initial_state_path)
                raise

    automaton = CellularAutomaton(initial_state=initial_state)
    automaton.run_until_attractor_found(n_steps)
    if automaton.attractor is not None:
        prop_cells_alive = numpy.sum(numpy.mean(
            automaton.attractor, axis=0)) / (automaton.attractor.shape[1] *
                                             automaton.attractor.shape[2])
        logging.info(
            "Attractor found after {} steps, with periodicity {} and {} live cells on average"
            .format(automaton.attractor_found_after,
                    automaton.attractor_period, prop_cells_alive))

    if movie_path:
        logging.info("Creating %s and saving it to %s" % (MOVIE, movie_path))
        automaton.reset_state(initial_state)
        create_movie(automaton, n_steps, movie_path)

    if interactive_plot_path:
        logging.info("Creating %s and saving it to %s" %
                     (INTERACTIVE_PLOT, interactive_plot_path))
        automaton.reset_state(initial_state)
        create_interactive_plot(automaton, n_steps, interactive_plot_path)
def simulation(p_mold, size, steps):
    """ Perform a simulation of a moldy forest, returning statistics.

    Parameters
    ----------
    p_mold : probability
        The probability that a crowded tree dies of mold.
    size : size tuple
        The number of cells in each direction for the simulation.
    steps : int
        The number of ticks to run the simulation for.

    Returns
    -------
    counts : array
        Array with shape (4, steps) of counts of each state at
        each tick.
    """
    np.random.seed(None)

    # trees grow
    grow = ChangeStateRule(from_state=EMPTY, to_state=TREE, p_change=0.0025)

    # fires are started, and all connected trees burn
    burn_groves = BurnGrovesRule()

    # crowded trees have a chance to be infected with mold
    mold = MoldRule(dead_state=MOLD, p_mold=p_mold)

    # trees which are infected with mold die
    mold_die = ChangeStateRule(from_state=MOLD, to_state=EMPTY, p_change=1.0)

    # fires are extinguished
    fire_out = ChangeStateRule(from_state=FIRE, to_state=EMPTY, p_change=1.0)

    forest = CellularAutomaton(
        shape=size,
        rules=[mold_die, fire_out, grow, burn_groves, mold],
    )

    # record the number of each state
    recorder = AutomataRecorder(automaton=forest, transform=count_states)

    forest.start()
    for i in range(steps):
        forest.step()

    return recorder.as_array()
def main(rule, size, pattern, boundary, ticks):
    """ Run an elementary 1D cellular automaton. """
    pattern = [(0 if char == ' ' else 1) for char in pattern]

    # setup simulation
    rule = Elementary1DRule(rule_number=rule, boundary=boundary)
    pattern_overlay = PatternOverlay(pattern=pattern)
    world = CellularAutomaton(shape=(size, ),
                              initializers=[pattern_overlay],
                              rules=[rule])

    # initialize and display initial state
    world.start()
    print(automaton_to_text(world))

    # run
    for i in range(ticks):
        world.step()
        print(automaton_to_text(world))
def run_simulations(automata_size, n_simulations, data_dir):
    ensure_data_dir_and_subdirs(data_dir)

    logging.info("Running {n} simulations on a {a}x{a} grid.".format(n=args.n_simulations, a=args.automata_size))
    logging.info("Results will be saved under {data_folder}.".format(data_folder=data_dir))

    automata = CellularAutomaton(shape=(automata_size, automata_size))
    periods = []
    steps_to_reachs = []
    n_cells_alive = []
    n_not_reached_attractor = 0

    for i in tqdm(range(n_simulations)):
        automata.reset_state()

        initial_state = automata.state
        initial_state_file_name = data_dir.joinpath(INITIAL_STATES).joinpath("initial_state_{}".format(i))
        numpy.save(initial_state_file_name, initial_state)

        try:
            automata.run_until_attractor_found(n_max_steps=200)
        except AttractorNotFoundError as err:
            warnings.warn(str(err))
            n_not_reached_attractor += 1
            continue

        periods.append(automata.attractor_period)
        steps_to_reachs.append(automata.attractor_found_after)
        mean_cells_alive = numpy.sum(numpy.mean(automata.attractor, axis=0))
        n_cells_alive.append(mean_cells_alive)

    results = pandas.DataFrame({"period": periods,
                                "steps_to_reach": steps_to_reachs,
                                "n_cells_alive": n_cells_alive})
    results.to_csv(os.path.join(data_dir, "summary.csv"))

    logging.info("Simulations finished.")
    if n_not_reached_attractor == 0:
        logging.info("All simulations reached an attractor \U0001F973")
    else:
        logging.warning("{} simulations did not reach an attractor.".format(n_not_reached_attractor))
Beispiel #7
0
def simulation(size, steps):
    """ Perform a simulation of a forest fire, outputting a GIF.

    Parameters
    ----------
    size : size tuple
        The number of cells in each direction for the simulation.
    steps : int
        The number of ticks to run the simulation for.
    """
    np.random.seed(None)

    grow = ChangeStateRule(
        from_state=EMPTY,
        to_state=TREE,
        p_change=0.0025
    )
    lightning = ChangeStateRule(
        from_state=TREE,
        to_state=FIRE,
        p_change=1e-5,
    )
    burn = SlowBurnRule()

    forest = CellularAutomaton(
        shape=size,
        rules=[grow, lightning, burn],
    )
    recorder = AutomataRecorder(automaton=forest)

    forest.start()
    for i in range(steps):
        forest.step()

    palette = np.zeros((256, 3), dtype='uint8')
    palette[1] = GREEN
    palette[2] = RED

    save_image_sequence(recorder, 'test.gif', palette, 100)