Example #1
0
def revive_simulation(rev_parameters, sim_functions):
    print('\n[' + rev_parameters["simulation_name"].upper() + ' REVIVAL SIMULATION]')
    Populations = {}
    if "sim_folder" in rev_parameters:
        print('Accessing simulation files directory...') 
        print('Excavating World entity: ' + rev_parameters['eco_file'] + '...')
        World = excavate_world(rev_parameters['sim_folder'] + \
                               rev_parameters['eco_file'])
        print('Updating parameters with World dimensions...')
        rev_parameters["world_z"] = len(World.ecosystem[0][0][0])
        rev_parameters["world_y"] = len(World.ecosystem[0][0])
        rev_parameters["world_x"] = len(World.ecosystem[0])
        for i in range(len(rev_parameters["pop_files"])):
            print('\nReviving population file: ' + \
                rev_parameters["pop_files"][i] + '...')
            pop_file = rev_parameters["sim_folder"] + \
                rev_parameters["pop_files"][i]
            Populations[rev_parameters["population_names"][i]] = \
                revive_population(pop_file)
        print('\nUpdating revival generation start in simulation parameters...')
        rev_parameters["rev_start"] = [Populations[pop_name].generation 
                                       for pop_name in Populations]
    elif "database_source" in rev_parameters:
        print('Constructing database directory...')
        dbpath = os.sep.join([os.getcwd(), 
                              'Simulations', 
                              rev_parameters["database_source"]])
        print('Connecting to database file: ' + \
            rev_parameters["database_source"] + '...')
        (con, cur) = connect_database(dbpath, None)
        if rev_parameters["simulation_time"] == 'default':
            print('Acquiring simulation starting time...')
            rev_parameters["simulation_time"] = db_list_simulations(cur)[0][0]
        print('Reconstructing old simulation parameters...')
        temp_parameters = db_reconstruct_simulation_parameters(cur, 
                                    rev_parameters["simulation_time"])
        print('Assimilating old simulation parameters with new simulation parameters...')
        for key in temp_parameters:
            if key not in rev_parameters:
                rev_parameters[key] = temp_parameters[key]
        print('Reconstructing World entity...')
        World = db_reconstruct_world(cur, rev_parameters["simulation_time"], 
                                     rev_parameters["rev_start"][0])
        print('\nUpdating population names parameter...')
        for pop_name in rev_parameters["population_names"]:
            print('Reconstructing population: ' + pop_name + '...')
            Populations[pop_name] = db_reconstruct_population(cur, 
                              rev_parameters["simulation_time"], pop_name, 
            rev_parameters["rev_start"][rev_parameters["population_names"].index(pop_name)])
        print('Terminating database connection...')
        con.close()
    print('Updating last generation revival and population size simulation parameters...')
    rev_parameters["rev_finish"] = [(Populations[pop_name].generation + \
                                     rev_parameters["extend_gen"]) 
                                    for pop_name in Populations]
    rev_parameters["rev_pop_size"] = [len(Populations[pop_name].agents) 
                                      for pop_name in Populations]
    print('\nStarting simulation core...')
    simulation_core(sim_functions, rev_parameters, Populations, World)
Example #2
0
def simulate(sim_parameters, sim_functions, eb = event_broker()):
    '''
    Function called by simulation to run the actual simulation based on a 
    set of parameters and functions.
    
    Simulation parameters dictionary contains the following keys:
        - simulation_name: Short name of the simulation.
        - population_names: Population name(s) in a list.
        - population_locations: A list of lists containing (x, y, z) 
        coordinates in the world to deploy the populations. There must be
        equal numbers of items in this list as population_names. However,
        one population can be deployed into one or more ecological cell(s).
        - deployment_code: Defines the type of deployment. Allowable values 
        are 0 (custom deployment scheme which users can implement by over-
        riding dose.dose_functions.deployment_scheme() function), 1 (all 
        organisms are in one location), 2 (organisms are randomly deployed 
        across a list of population locations given for the population), 3 
        (oganisms are randomly deployed across a list of population locations 
        given for the population), 4 (organisms are dispersed from a specific 
        location where the defined location will have the maximum allocation 
        before dispersal happens). (see simulation_calls.deployment for more 
        details)
        - chromosome_bases: List containing allowable bases in the 
        chromosome.
        - background_mutation: Defines background mutation rate where 0.01 
        represents 1% mutation and 0.5 represents 50% mutation.
        - additional_mutation: Defines mutation rate on top of background 
        mutation rate where 0.01 represents 1% mutation and 0.5 represents 
        50% mutation.
        - mutation_type: Type of mutation for background mutation rate. 
        Allowable values are 'point' (point mutation), 'insert' (insert a 
        base), 'delete' (delete a base), 'invert' (invert a stretch of the 
        chromosome), 'duplicate' (duplicate a stretch of the chromosome), 
        'translocate' (translocate  a stretch of chromosome to another 
        random position). 
        - chromosome_size: Number of bases for a chromosome.
        - genome_size: Number of chromosome(s) in a genome.
        - max_tape_length: Maximum number of cells for array used in 
        Ragaraja interpreter, which will be stored as 
        Organism.status['blood'].
        - clean_cell: Toggle to define if a new tape will be used for 
        Ragaraja interpreter. If True, at every Ragaraja interpretation of 
        the source (genome), a new tape ([0] * max_tape_length) will be 
        provided. If False, the tape stored as Organism.status['blood'] 
        (results from previous interpretation of genome) will be used.
        - interpret_chromosome: Toggle to define whether genomes will be 
        interpreted by Ragaraja. If True, chromosomes of each organism will 
        be interpreted by Ragaraja. 
        - max_codon: Maximum number of Ragaraja instructions to execute per 
        organism, which can be used as force-break from endless loop.
        - population_size: Number of organisms per population for initial 
        deployment.
        - eco_cell_capacity: Maximum number of organisms per ecological 
        cell at the time of deployment prior to the start of simulation.
        - world_x: Number of ecological cells in the x-axis of the 
        World.ecosystem.
        - world_y: Number of ecological cells in the y-axis of the 
        World.ecosystem.
        - world_z: Number of ecological cells in the z-axis of the 
        World.ecosystem.
        - goal: Goal for population to reach. This provides a goal for use 
        in fitness functions.
        - maximum_generations: Number of generations to simulate.
        - fossilized_ratio: Proportion (less than 1) of the population to 
        fossilize or freeze.
        - fossilized_frequency: Number of generations (intervals) for each 
        population fossilization or freezing event.
        - print_frequency: Number of generations (intervals) for each 
        reporting event into files.
        - ragaraja_version: Ragaraga instruction version to activate. (see 
        ragaraja.activate_version() for more details)
        - ragaraja_instructions: A list defining a set of Ragaraga 
        instructions to activate. This is only useful when ragaraja_version 
        is 0.
        - eco_buried_frequency: Number of generations (intervals) for each 
        ecological freezing or burial event.
        - database_file: Logging database file name. This file will be 
        located in <current working directory>/Simulations folder
        - database_logging_frequency: Number of generations (intervals) for 
        each database logging event. 
    
    Methods / Functions from dose.dose_functions class to be over-ridden 
    as simulation_functions (for more details, please look at 
    dose.dose_functions class):
        - organism_movement: organism_movement and organism_location are 
        both methods / functions to execute movement of organisms within 
        the world. The semantic difference between organism_movement and 
        organism_location is that organism_movement is generally used for 
        short travels while organism_location is used for long travel.
        - organism_location: organism_movement and organism_location are 
        both methods / functions to execute movement of organisms within 
        the world. The semantic difference between organism_movement and 
        organism_location is that organism_movement is generally used for 
        short travels while organism_location is used for long travel.
        - ecoregulate: Broad spectrum management of the entire 
        ecosystem.
        - update_ecology: Process the input and output from the activities 
        of the organisms in the current ecological cell into a local 
        ecological cell condition, and update the ecosystem.
        - update_local: Update local ecological cell condition from the 
        ecosystem.
        - report: Generate a text report of ecosystem (World.ecosystem) at 
        regular intervals, within the simulation, as determined by 
        "print_frequency" in the simulation parameters.
        - fitness: Calculate the fitness score of each organism within the 
        population(s).
        - mutation_scheme: Trigger mutational events in each chromosome 
        of the genome within an organism.
        - prepopulation_control: Trigger population control events before 
        mating event in each generation.
        - mating: Trigger mating events in each generation.
        - postpopulation_control: Trigger population control events after 
        mating event in each generation.
        - generation_events: Trigger other defined events in each 
        generation.
        - population_report: Generate a text report of the population(s) 
        and/or each organisms within the population at regular intervals, 
        within the simulation, as determined by "print_frequency" in the 
        simulation parameters
        - database_report: Implement database logging of each organism 
        in each population, and the ecosystem status. The frequency of 
        logging is determined by "database_logging_frequency" in the 
        simulation_parameters.
        - deployment_scheme: Implement a user-specific / simulation-
        specific deployment scheme used to deploy organisms into the 
        World. This function will only be used when "deployment_code" in 
        simulation parameters dictionary equals to 0.
    
    @param sim_parameters: Dictionary of simulation parameters
    @param sim_functions: A class inherited from dose.dose_functions
    class to implement all the needed simulation functions.
    @param eb: An instance of dose.event_broker
    '''

    eb.log("[" + sim_parameters["simulation_name"].upper() + " SIMULATION]")

    if "initial_chromosome" not in sim_parameters:
        eb.log('Adding initial chromosome to simulation parameters')
        sim_parameters["initial_chromosome"] = ['0'] * sim_parameters["chromosome_size"]

    eb.log('Adding deployment scheme to simulation parameters')
    sim_parameters["deployment_scheme"] = sim_functions.deployment_scheme

    eb.log('Constructing World entity')
    world = dose_world.World(sim_parameters["world_x"], sim_parameters["world_y"], sim_parameters["world_z"])
    eb.log('Spawning populations')
    populations = spawn_populations(sim_parameters)
    eb.log('Starting simulation core')
    simulation_core(sim_functions, sim_parameters, eb, populations, world)
Example #3
0
def revive_simulation(rev_parameters, sim_functions, eb = event_broker()):

    eb.log("[" + rev_parameters["simulation_name"].upper() + " REVIVAL SIMULATION]")

    populations = {}
    world = None
    eb.log("Accessing simulation files directory")
    if "sim_folder" in rev_parameters:

        eb.log('Excavating World entity: ' + rev_parameters['eco_file'])
        world = excavate_world(rev_parameters['sim_folder'] + rev_parameters['eco_file'])

        eb.log('Updating parameters with World dimensions')
        rev_parameters["world_z"] = len(world.ecosystem[0][0][0])
        rev_parameters["world_y"] = len(world.ecosystem[0][0])
        rev_parameters["world_x"] = len(world.ecosystem[0])

        for i in range(len(rev_parameters["pop_files"])):
            eb.log('Reviving population file: ' + rev_parameters["pop_files"][i])
            pop_file = rev_parameters["sim_folder"] + rev_parameters["pop_files"][i]
            populations[rev_parameters["population_names"][i]] = revive_population(pop_file)

        eb.log('Updating revival generation start in simulation parameters')
        rev_parameters["rev_start"] = [populations[pop_name].generation for pop_name in populations]

    elif "database_source" in rev_parameters:

        eb.log('Constructing database directory')
        dbpath = os.sep.join([os.getcwd(), 'Simulations', rev_parameters["database_source"]])

        eb.log('Connecting to database file: ' + rev_parameters["database_source"])
        (con, cur) = connect_database(dbpath, None)

        if rev_parameters["simulation_time"] == 'default':
            eb.log('Acquiring simulation starting time')
            rev_parameters["simulation_time"] = db_list_simulations(cur)[0][0]

        eb.log('Reconstructing old simulation parameters')
        temp_parameters = db_reconstruct_simulation_parameters(cur, rev_parameters["simulation_time"])

        eb.log('Assimilating old simulation parameters with new simulation parameters')
        for key in temp_parameters:
            if key not in rev_parameters:
                rev_parameters[key] = temp_parameters[key]

        eb.log('Reconstructing World entity')
        world = db_reconstruct_world(cur, rev_parameters["simulation_time"], rev_parameters["rev_start"][0])

        eb.log('Updating population names parameter')
        for pop_name in rev_parameters["population_names"]:
            eb.log('Reconstructing population: ' + pop_name)
            populations[pop_name] = db_reconstruct_population(cur, rev_parameters["simulation_time"], pop_name,
                                                              rev_parameters["rev_start"][rev_parameters
                                                              ["population_names"].index(pop_name)])
        eb.log('Terminating database connection')
        con.close()

    eb.log('Updating last generation revival and population size simulation parameters')
    rev_parameters["rev_finish"] = [(populations[pop_name].generation + rev_parameters["extend_gen"])
                                    for pop_name in populations]
    rev_parameters["rev_pop_size"] = [len(populations[pop_name].agents) for pop_name in populations]

    eb.log('Starting simulation core')
    simulation_core(sim_functions, rev_parameters, populations, world)