def simulate_without_display(manifest, Simulator):
    '''
    Run to completion with a given Simulator class.
    '''
    manifest_options = read_manifest(manifest)
    opts = SurfaceCRNOptionParser(manifest_options)
    simulator = Simulator(surface=opts.grid,
                          transition_rules=opts.transition_rules,
                          seed=seed,
                          simulation_duration=opts.max_duration)
    while not simulator.done():
        simulator.process_next_reaction()

    return simulator.time
Exemple #2
0
def simulate_without_display(manifest_file, lattice):
    '''
    Run until completion or max time, storing an array of species counts at
    the times of each reaction, along with an array of times. At the end,
    display a graph of species concentrations as they change.
    '''
    from surface_crns.readers.manifest_readers import read_manifest
    from surface_crns.options.option_processor import SurfaceCRNOptionParser
    species_tracked = ["O", "OH_3F", "OH_top", "H2O"]

    manifest_options = read_manifest("water_adsorption.txt")
    opts = SurfaceCRNOptionParser(manifest_options)
    simulator = QueueSimulator(surface=lattice,
                               transition_rules=opts.transition_rules,
                               seed=opts.rng_seed,
                               simulation_duration=opts.max_duration)
    times = [0]
    concs = dict()
    for species in species_tracked:
        concs[species] = [0]
    for node in lattice:
        if node.state in concs:
            concs[node.state][0] += 1
    while not simulator.done():
        next_rxn = simulator.process_next_reaction()
        if next_rxn is None:
            break
        times.append(next_rxn.time)
        for species in species_tracked:
            concs[species].append(concs[species][-1])
        for reactant in next_rxn.rule.inputs:
            if reactant in concs:
                concs[reactant][-1] -= 1
        for product in next_rxn.rule.outputs:
            if product in concs:
                concs[product][-1] += 1

    for species in species_tracked:
        plt.plot(times, concs[species], label=species)
    plt.plot(times,
             np.array(concs["OH_top"]) + np.array(concs["OH_3F"]),
             label="OH")
    plt.legend()
    plt.xlabel("Time (s)")
    plt.ylabel("Molecule Count (#)")
    plt.title("Evolution of water adsorption and splitting on Ag crystal")
    plt.show()
def main():
    input_filename = sys.argv[1]
    manifest_options = manifest_readers.read_manifest(input_filename)
    init_state = manifest_options["init_state"].transpose()

    output_filename = input_filename[:input_filename.rfind(".")] \
                        + "_spinning_arrow_init.txt"
    with open(output_filename, 'w') as outfile:
        for j in range(init_state.shape[1] + 2):
            outfile.write("Edge_D ")
        for i in range(init_state.shape[0]):
            outfile.write("\nEdge_R ")
            for j in range(init_state.shape[1]):
                orig_state = init_state[i, j]
                position = str(j % 3 + 3 * (i % 3) + 1)
                orientation = "D" if (i + j) % 2 == 0 else "U"
                outfile.write(f"{orig_state}_{orientation}_{position}_None ")
            outfile.write("Edge_L")
        outfile.write("\n")
        for j in range(init_state.shape[1] + 2):
            outfile.write("Edge_U ")
Exemple #4
0
def main():
    '''
    Run several simulations, saving states in CSV format at a few times.
    # '''
    # # sCRNs maps manifest filenames to lists of times at which to save.
    # # Uncomment lines for sCRNs you'd like to save.
    sCRNs = dict()
    sCRNs["GH_big_spiral_manifest.txt"] = [50, 200, 350, 770, 1200]
    sCRNs["big_GoL_manifest.txt"] = [500 * i for i in range(10)]
    sCRNs["bitmap_butterfly_manifest.txt"] = [0, 50, 150, 250, 300, 350, 500]
    sCRNs["anthill_manifest.txt"] = [100, 2000, 5000, 14000, 20000]

    for name, times in sCRNs.items():
        base_name = name.split(".")[0].replace("_manifest", "")
        manifest_filename = os.path.join("Manifests", name)
        manifest_options = read_manifest(manifest_filename)
        opts = SurfaceCRNOptionParser(manifest_options)
        simulator = QueueSimulator(surface=opts.grid,
                                   transition_rules=opts.transition_rules,
                                   seed=opts.rng_seed,
                                   simulation_duration=max(times) * 1.1)
        time = 0
        t_idx = 0
        next_t = times[t_idx]
        while True:
            if time >= next_t:
                outfile = os.path.join("Outputs",
                                       f"{base_name}_T={next_t}.csv")
                write_snapshot(outfile, simulator.surface)
                t_idx += 1
                if t_idx >= len(times):
                    break
                next_t = times[t_idx]
            next_rxn = simulator.process_next_reaction()
            if next_rxn is None:
                break
            time = next_rxn.time
Exemple #5
0
    def __init__(self, manifest_filename=None, options=None):
        self.DEBUG = False

        if manifest_filename and options:
            raise Exception("GridSimTimeProfiler can be initialized with " +
                            "either a manifest file or a dictionary of " +
                            "options, but not both.")
        if manifest_filename:
            self.options = manifest_readers.read_manifest(manifest_filename)
        elif options:
            self.options = options
        else:
            raise Exception("GridSimTimeProfiler must be initialized with " +
                            "either a manifest file name or a dictionary " +
                            "of options read from a manifest file.")

        # Read out miscellaneous options from manifest
        if 'debug' in self.options:
            debug_flag = self.options['debug'].lower()
            if debug_flag in ['true', 'on', 'yes']:
                self.DEBUG = True
            elif debug_flag in ['false', 'off', 'no']:
                self.DEBUG = False
            else:
                self.DEBUG = bool(int(self.options['debug']))
        else:
            DEBUG = debug
        if 'rng_seed' in self.options:
            self.RAND_SEED = int(self.options['rng_seed'])
        else:
            self.RAND_SEED = 0
        if 'max_duration' in self.options:
            self.SIMULATION_DURATION = float(self.options['max_duration'])
        else:
            self.SIMULATION_DURATION = 100

        # Load transition rules
        if 'transition_rules' in self.options:
            self.transition_rules = self.options['transition_rules']
            # Check validity of rules and add colors if necessary.
            for rule in self.transition_rules:
                # Check that reactions are unimolecular or bimolecular
                if len(rule.inputs) != len(rule.outputs):
                    raise Exception(
                        "Invalid transition rule " + str(rule) +
                        "\nTransition rules for a surface CRN must" +
                        "have the same number of inputs and " + "outputs.")
                if len(rule.inputs) > 2:
                    raise Exception("Invalid transition rule " + str(rule) +
                                    "\nOnly transition rules between one or " +
                                    "two species are allowed in this " +
                                    "implementation.")
            if self.DEBUG:
                print("Transition rules:\n" + str(self.transition_rules))
        else:
            raise Exception("Transition rules required in manifest.")

        # Set up grid and define initial state
        if 'init_state' in self.options:
            self.initial_state = self.options['init_state']
            if self.DEBUG:
                print("Initial state:")
                print(str(self.initial_state))
        else:
            raise Exception("Initial state required in manifest")

        self.grid = grids.SquareGrid(self.initial_state.shape[0],
                                     self.initial_state.shape[1])
        self.grid.set_global_state(self.initial_state)

        # Set up simulation timer
        self.simulation = simulators.QueueSimulator(
            surface=self.grid,
            transition_rules=self.transition_rules,
            seed=self.RAND_SEED,
            simulation_duration=self.SIMULATION_DURATION)