Esempio n. 1
0
 def generate(self, P): # generate environment and populate with ecosystems #
     for i in range(0, P.grid_size): # x coords
         self.grid.append([]) # build the rows
         for j in range(0, P.grid_size): # y coords
             eco = Ecosystem(P, (i, j)) # create an ecosystem at the plot
             eco.connect(P.grid_size) # connect the ecosystem to its neighbors
             self.grid[i].append(eco) # put ecosystem into environment grid
             if( i == 0 and j == 0): # this is the initial founder square with the initial 500 inds
                 eco.populate(P)
Esempio n. 2
0
class Game(arcade.Window):
    """ Main application class. """
    def __init__(self, width, height):
        super().__init__(width, height, 'Ecosystem Simulation')

        self.sprite_list = None

        self.ecosystem = None

        arcade.set_background_color(arcade.color.BLACK)

    def setup(self):
        self.sprite_list = arcade.SpriteList()

        self.ecosystem = Ecosystem(int(SCREEN_WIDTH / CELL_WIDTH),
                                   int(SCREEN_HEIGHT / CELL_HEIGHT))

    def on_draw(self):
        """ Render the screen. """
        arcade.start_render()
        self.sprite_list.draw()

    def update(self, delta_time):
        """ All the logic to move, and the game logic goes here. """
        self.sprite_list = arcade.SpriteList()

        ecosystem_organisms = self.ecosystem.run()

        for organism in ecosystem_organisms:
            sprite = arcade.Sprite(organism.get_image(), 1)
            sprite.center_x = organism.x * CELL_WIDTH + CELL_WIDTH / 2
            sprite.center_y = organism.y * CELL_HEIGHT + CELL_HEIGHT / 2
            self.sprite_list.append(sprite)
Esempio n. 3
0
def simulate(i):
    genList = ['power', 'velocity', 'intelligence', 'fertility', 'hostility']
    numLives = 30

    print(f"init start. numlives: {numLives}")
    ecosystem = Ecosystem(numLives=numLives,
                          genList=genList,
                          MAP_WIDTH=c.MAP_WIDTH,
                          MAP_HEIGHT=c.MAP_HEIGHT)
    print(f"init finished: {i}-----------------------------------------")

    while ecosystem.time < 500:
        ecosystem.nextEpoch()
        # 선택(내부에 evaluation(싸우는거) 포함)
        selectedCreatures = ecosystem.selection(ecosystem.lives)
        # 교차
        crossOveredCreature = ecosystem.crossover(selectedCreatures[0],
                                                  selectedCreatures[1])
        # 변이
        crossOveredCreature = ecosystem.mutation(crossOveredCreature,
                                                 c.MUTATION_RATE)
        ecosystem.lives.append(crossOveredCreature)
        ecosystem.created.append(crossOveredCreature)
        ecosystem.time += 1
        ecosystem.numLives += 1
        # print(f'epoch {ecosystem.time}: numLives: {ecosystem.numLives}')
    print(f"simulation finished: {i}---------------------------------------")
    '''
    print(f"numlives: {ecosystem.numLives}")
    print(f"lenoflives: {len(ecosystem.lives)}")
    for cr in ecosystem.lives:
        print(cr)
    '''

    return ecosystem.numLives, ecosystem.lives
    def generate_data_structure(self, code_directory, output_file):
        files = self.get_class_files(code_directory)
        self.ecosystem = Ecosystem()
        self.parse_files(files)

        f = open(output_file, "w")
        f.write(self.ecosystem.serialize())
        f.close()

        return self.ecosystem
Esempio n. 5
0
def main(argv):
    for i in range(len(argv)):
        if argv[i] == "-g":
            if len(argv)-i == 1: # last argument
                graphic_output.graphics_init("f")
            else:
                graphic_output.graphics_init(argv[i+1])
    
    simMins, width, height = inputCreatures()
    ecosystem = Ecosystem(simMins, width, height)
    ecosystem.loadCreatures(num_and_what_creatures, creature_funcs, creatures)

    ecosystem.startSimulation()
Esempio n. 6
0
 def generate(self,
              P):  # generate environment and populate with ecosystems #
     for i in range(0, P.grid_size):  # x coords
         self.grid.append([])  # build the rows
         for j in range(0, P.grid_size):  # y coords
             eco = Ecosystem(P, (i, j))  # create an ecosystem at the plot
             eco.connect(
                 P.grid_size)  # connect the ecosystem to its neighbors
             self.grid[i].append(eco)  # put ecosystem into environment grid
             if (
                     i == 0 and j == 0
             ):  # this is the initial founder square with the initial 500 inds
                 eco.populate(P)
class CodeParser:
    def get_directory_files(self, path):
        entries = os.listdir(path)
        files = []
        for entry in entries:
            if isfile(join(path, entry)):
                files.append(join(path, entry))
            elif isdir(join(path, entry)):
                files.extend(self.get_directory_files(join(path, entry)))

        return files

    def get_class_files(self, code_directory):
        files = self.get_directory_files(code_directory)
        return filter(lambda path: path.endswith(".h"), files)

    def parse_class_file(self, input_lines, include_path):
        current_class = None
        current_type = ''
        for line in input_lines:
            matches = {
                'component': re.match(ENGINE_COMPONENT_REGEX, line),
                'object': re.match(ENGINE_OBJECT_REGEX, line),
                'field': re.match(ENGINE_FIELD_REGEX, line)
            }        

            if matches['component']:
                self.ecosystem.add_class_description(copy.copy(current_class))
                component_name = matches['component'].group('componentName')
                current_class = EngineComponentDescription(component_name, include_path)
            elif matches['object']:
                self.ecosystem.add_class_description(copy.copy(current_class))
                component_name = matches['object'].group('objectName')
                current_class = EngineObjectDescription(component_name, include_path)
            elif matches['field']:
                field_type = matches['field'].group('fieldType')
                field_name = matches['field'].group('fieldName')
                isArray = False

                arrayMatch = re.match(ARRAY_TYPE_REGEX, field_type)
                if arrayMatch:
                    isArray = True
                    field_type = arrayMatch.group("type")

                current_class.add_field(FieldDescription(field_name, field_type, isArray))

        self.ecosystem.add_class_description(copy.copy(current_class))

    def parse_files(self, files):
        for path in files:
            f = open(path, "r")
            lines = []
            for line in f:
                lines.append(line)

            self.parse_class_file(lines, path)
            f.close()

    def generate_data_structure(self, code_directory, output_file):
        files = self.get_class_files(code_directory)
        self.ecosystem = Ecosystem()
        self.parse_files(files)

        f = open(output_file, "w")
        f.write(self.ecosystem.serialize())
        f.close()

        return self.ecosystem
Esempio n. 8
0
        tls = net.get_trophic_levels()

        top, top_preds = net.top_predators()
        basal, basal_sps = net.basal()
        for u, v in net.edges():
            if u in basal_sps and v in top_preds and tls[v] == 3:
                net.remove_edge(u, v)

        print 'new connectance = ', net.connectance()
    else:
        net = obtain_interactions_network()
        net_to_save = net.copy()
        nx.write_graphml(net_to_save, network_file)

    ecosystem = Ecosystem(net, drawing=False)
    ecosystem.initialise_world(True)
    #ecosystem.draw_species_distribution()

    out_row = get_out_row(0, net, '', 0, '', '')
    out.writerow(out_row)

    #    iteration_to_reset = (int) (math.ceil(ITERATIONS*NETWORK_RESET))

    out_row_eco = get_eco_state_row(0, ecosystem)
    out_eco.writerow(out_row_eco)

    #    print ecosystem.get_groups_counts()
    #    plot_series = []
    #    plot_prods = []
    #    plot_mut_prods = []
Esempio n. 9
0
def plot(steps):
    populations = {
        'rabbit': [],
        'bee': [],
        'fox': [],
        'flower': [],
        'grass': []
    }

    genetics_factors = {'rabbit': [], 'fox': []}

    ecosystem = Ecosystem(int(SCREEN_WIDTH / CELL_WIDTH),
                          int(SCREEN_HEIGHT / CELL_HEIGHT))

    # Iterate over time
    actual_steps = steps
    for i in range(steps):
        ecosystem_organisms = ecosystem.run()

        rabbits = 0
        foxes = 0
        bees = 0
        flowers = 0
        grass = 0

        rabbit_genetics_factor = 0
        fox_genetics_factor = 0

        for organism in ecosystem_organisms:
            # Observe animal populations
            if organism.type == Type.RABBIT:
                rabbits += 1
                rabbit_genetics_factor += organism.genetics_factor
            elif organism.type == Type.FOX:
                foxes += 1
                fox_genetics_factor += organism.genetics_factor
            elif organism.type == Type.BEE:
                bees += 1
            elif organism.type == Type.FLOWER:
                flowers += 1
            elif organism.type == Type.GRASS:
                grass += 1

        populations['rabbit'].append(rabbits)
        populations['fox'].append(foxes)
        populations['bee'].append(bees)
        populations['flower'].append(flowers)
        populations['grass'].append(grass)

        if not i % 100:
            print('Iteration ' + str(i) + ':')
            print('  ' + str(foxes) + ' foxes')
            print('  ' + str(rabbits) + ' rabbits')
            print('  ' + str(bees) + ' bees')
            print('  ' + str(flowers) + ' flowers')

        if rabbits != 0:
            genetics_factors['rabbit'].append(rabbit_genetics_factor / rabbits)
        else:
            actual_steps = i
            break
        if foxes != 0:
            genetics_factors['fox'].append(fox_genetics_factor / foxes)
        else:
            actual_steps = i
            break

    if actual_steps >= 25000:
        # Plot the results
        plt.plot(populations['rabbit'], label='Rabbits')
        plt.plot(populations['fox'], label='Foxes')
        plt.plot(populations['bee'], label='Bees')
        plt.plot(populations['flower'], label='Flowers')
        plt.plot(populations['grass'], label='Grass')
        plt.xlabel('Time')
        plt.legend(loc='upper right')
        plt.ylabel('Population amount')
        plt.show()

        plt.plot(genetics_factors['rabbit'], label='Rabbits')
        plt.plot(genetics_factors['fox'], label='Foxes')
        plt.xlabel('Time')
        plt.legend(loc='upper right')
        plt.ylabel('Genetics factor')
        plt.show()
        return True, actual_steps
    else:
        return False, actual_steps
Esempio n. 10
0
    def setup(self):
        self.sprite_list = arcade.SpriteList()

        self.ecosystem = Ecosystem(int(SCREEN_WIDTH / CELL_WIDTH),
                                   int(SCREEN_HEIGHT / CELL_HEIGHT))
def main():
    args= parse_args()
    file = args.file
    target_string = args.target
    charset = args.charset
    random_crossover = args.random_crossover
    tournament_size = args.tournament_size
    population_size = args.population_size

    if not file and not target_string:
        print 'ERROR: Must pass either a file containing a target string or a target string'
        sys.exit(1)

    if file:
        with open(file) as f:
            target_string = f.readline()

    for char in target_string:
        if char not in charset:
            print 'ERROR: Characters does not contain all characters in target string'
            sys.exit(1)
    

    # set ideal target
    target_individual = Individual(list(target_string))
    
    # set ecosystem
    ecosystem = Ecosystem(charset, target_individual, tournament_size)
    ecosystem.set_random_current_population(population_size)
    
    # evolve ecosystem until the fittest individual matches the target
    while ecosystem.get_current_fittest() != target_individual:
        ecosystem.print_results()
        ecosystem.evolve()
    ecosystem.print_results()

    # print success message
    ecosystem.print_success()
Esempio n. 12
0
def build_ecosystem(ecosystem_type, directional):
    if ecosystem_type == '2_competitive':
        scenarios = [
            CompetitiveScenario(agent_colors=['red', 'yellow'],
                                directional=directional)
        ]
        populations = create_populations(2)
        assigned_pops = [populations]
    elif ecosystem_type == '2_cooperative':
        scenarios = [
            CooperativeScenario(agent_colors=['green', 'blue'],
                                directional=directional)
        ]
        populations = create_populations(2)
        assigned_pops = [populations]
    elif ecosystem_type == '3_mixed':
        scenarios = [
            CompetitiveScenario(agent_colors=['red', 'yellow'],
                                directional=directional),
            CooperativeScenario(agent_colors=['yellow', 'blue'],
                                directional=directional)
        ]
        populations = create_populations(3)
        assigned_pops = [populations[0:2], populations[1:3]]
    elif ecosystem_type == '3_competitive':
        scenarios = [
            CompetitiveScenario(agent_colors=['red', 'orange'],
                                directional=directional),
            CompetitiveScenario(agent_colors=['orange', 'yellow'],
                                directional=directional)
        ]
        populations = create_populations(3)
        assigned_pops = [populations[0:2], populations[1:3]]
    elif ecosystem_type == '4_mixed':
        scenarios = [
            CooperativeScenario(agent_colors=['green', 'yellow'],
                                directional=directional),
            CompetitiveScenario(agent_colors=['yellow', 'orange'],
                                directional=directional),
            CooperativeScenario(agent_colors=['orange', 'blue'],
                                directional=directional)
        ]
        populations = create_populations(4)
        assigned_pops = [populations[0:2], populations[1:3], populations[2:4]]
    elif ecosystem_type == '2_spread':
        scenarios = [SimpleSpreadScenario(num_agents=2)]
        populations = create_populations(2)
        assigned_pops = [populations]

    else:
        raise RuntimeError("Invalid ecosystem type {}".format(ecosystem_type))
    environments = []
    for scenario in scenarios:
        world = scenario.make_world()
        if directional:
            env = DirectionalMultiAgentEnv(world,
                                           scenario.reset_world,
                                           scenario.reward,
                                           scenario.observation_organism,
                                           done_callback=scenario.done)
        else:
            env = MultiAgentEnv(world,
                                scenario.reset_world,
                                scenario.reward,
                                scenario.observation,
                                done_callback=scenario.done)
        environments.append(env)
    ecosystem = Ecosystem(environments, populations, assigned_pops)
    return ecosystem
Esempio n. 13
0
       
    tls = net.get_trophic_levels()
        
    top, top_preds = net.top_predators()
    basal, basal_sps = net.basal()
    for u,v in net.edges():
        if u in basal_sps and v in top_preds and tls[v] == 3:
            net.remove_edge(u,v)
                
    print 'new connectance = ', net.connectance()
    if not READ_FILE_NETWORK:
	net_to_save = net.copy()
        nx.write_graphml(net_to_save, network_file)
    
    ##################################################################################################################
    ecosystem = Ecosystem(net, drawing=False)
    ecosystem.initialise_world(True)
    
    out_row = get_out_row(0, net, '', 0, '', '')
    out.writerow(out_row)
    
    out_row_eco = get_eco_state_row(0, ecosystem)
    out_eco.writerow(out_row_eco)
    
    
    series_counts = dict()
    if SPATIAL_VARIATION:
        centroids_counts = dict()
        areas_counts = dict()
    ##this structure holds the numbers of immigration, birth and dead of individuals
    ##for each species during the last ITERATIONS_TO_RECORD iterations
Esempio n. 14
0
def simulate2(i):
    genList = ['power', 'velocity', 'intelligence', 'fertility', 'hostility']
    numLives = 30

    print(f"init start. numlives: {numLives}")
    ecosystem = Ecosystem(numLives=numLives,
                          genList=genList,
                          MAP_WIDTH=c.MAP_WIDTH,
                          MAP_HEIGHT=c.MAP_HEIGHT)
    print(f"init finished: {i}-----------------------------------------")

    data = list()
    powerData = list()
    veloData = list()
    intelData = list()
    fertilData = list()
    hostilData = list()
    numLivesData = list()

    epochtime = 500

    while ecosystem.time < epochtime:
        ecosystem.nextEpoch()
        # 선택(내부에 evaluation(싸우는거) 포함)
        selectedCreatures = ecosystem.selection(ecosystem.lives)
        # 교차
        crossOveredCreature = ecosystem.crossover(selectedCreatures[0],
                                                  selectedCreatures[1])
        # 변이
        crossOveredCreature = ecosystem.mutation(crossOveredCreature,
                                                 c.MUTATION_RATE)
        ecosystem.lives.append(crossOveredCreature)
        ecosystem.created.append(crossOveredCreature)
        ecosystem.time += 1
        ecosystem.numLives += 1
        # print(f'epoch {ecosystem.time}: numLives: {ecosystem.numLives}')

        avgDict = {
            'power': 0,
            'velocity': 0,
            'intelligence': 0,
            'fertility': 0,
            'hostility': 0,
        }
        if not ecosystem.numLives:
            data.append((0, avgDict))
            print("numLives is 0")
            continue
        if ecosystem.numLives < 0:
            # data.append((0, avgDict))
            print("numLives < 0")
            continue

        for creature in ecosystem.lives:
            infos = creature.getInfo()
            for geneName in avgDict.keys():
                avgDict[geneName] += infos[geneName]
        for geneName in avgDict.keys():
            avgDict[geneName] /= ecosystem.numLives
        data.append((ecosystem.numLives, avgDict))
    print(f"simulation finished: {i}---------------------------------------")

    for numLives, d in data:
        powerData.append(d['power'])
        veloData.append(d['velocity'])
        intelData.append(d['intelligence'])
        fertilData.append(d['fertility'])
        hostilData.append(d['hostility'])
        numLivesData.append(numLives)

    f, axes = plt.subplots(2, 3)
    xrange = np.arange(epochtime)
    axes[0][0].set_title("power")
    axes[0][0].plot(xrange, powerData)

    axes[0][1].set_title("velocity")
    axes[0][1].plot(xrange, veloData)

    axes[0][2].set_title("intelligence")
    axes[0][2].plot(xrange, intelData)

    axes[1][0].set_title("fertility")
    axes[1][0].plot(xrange, fertilData)

    axes[1][1].set_title("hostility")
    axes[1][1].plot(xrange, hostilData)

    axes[1][2].set_title("numLives")
    axes[1][2].plot(xrange, numLivesData)

    plt.show()

    return ecosystem.numLives, ecosystem.lives
Esempio n. 15
0
def main():
    setup_logger()
    logger.debug('DEBUG')
    print " *"*30, "\nWe start NOW!"  # ***
    # all_gene_names = extract_all_gene_names(my_example_of_ecosystem_settings)
    # all_strings = extract_all_strings(
    #    my_example_of_ecosystem_settings,
    #    exceptions = No_effect_directives + All_action_names)
    # print 'ALL GENES:', all_gene_names
    # print 'ALL STRINGS:', all_strings
    # print 'DIFFERENCE:', [
    #    item
    #    for item in all_strings
    #    if not item in all_gene_names and \
    #        not item in All_allowed_directives_in_expression]
    enable_graphics = True
    make_sleeps = False
    time_lapse = 4
    Total_time = 5000

    ecosystem = Ecosystem(my_example_of_ecosystem_settings,
                          elements_to_store)

    ecosystem.minimum_population_allowed = 200

    """ ***********************  TRIAL ZONE ****************************

    ecosystem.evolve()

    org = ecosystem.get_random_organisms(1)[0]

    print_dictionary(
        evaluate_functions_of_a_dictionary(
            org['offers to sell'], org
            )
        )

    f_set = {'-': ('nutrient A reserve',
                   'minimum nutrient A reserve for procreating')}
    f = ecosystem.function_maker.read_function_settings(
        '#organism',
        f_set)


    print_organism(org, 'nutrient A reserve',
                   'minimum nutrient A reserve for procreating')
    print_organism(org, 'nutrient A surplus')

    print f(org)

    print org['value in next cycle']['nutrient A surplus'](org)

    exit()

    f_set = {'curve from 0 to 1': 'photosynthesis capacity'}

    f = ecosystem.function_maker.read_function_settings(
        'output function #organism #input',
        f_set)

    for org in ecosystem.organisms_list:
        print f(org, 5)

    exit()

    f_set = {'extract #biotope sunlight (percentage)': (
                            'normalized location x',
                            'normalized location y',
                            0.8
                        )}

    f_2_set = {
        '#biotope sunlight': (
            'normalized location x',
            'normalized location y'
            )
        }

    org = choice(ecosystem.organisms_list)
    print_dictionary(org)

    f = ecosystem.function_maker.read_function_settings('#organism', f_set)
    f_2 = ecosystem.function_maker.read_function_settings('#organism', f_2_set)

    print f(org), f_2(org)

    for i in range(10):
        org.act()

    print_dictionary(org)

    # f_set = ecosystem.settings['constraints']['can procreate']
    # f_set = {'cost': 'procreate'}
    f_set = 'time'
    f = ecosystem.function_maker.read_function_settings('#organism', f_set)

    # print f(ecosystem)

    for org in ecosystem.organisms_list:
        print f(org)

    exit()

    *********************** (TRIAL ZONE) ************************** """

    if enable_graphics:
        gui = GUI(ecosystem)
    # Loop
    print "LOOPING:"
    while ((len(ecosystem.organisms_list) > 0) and
           (ecosystem.time < Total_time)):
        # Print ecosystem status:
        if ecosystem.time % time_lapse == 0:
            print_ecosystem_status(ecosystem)
            # organism1, organism2 = ecosystem.get_random_organisms(
            #    number_of_random_organisms = 2)
        if flag_store_data:
            ecosystem.data_storer.store_data()
        # Evolve:
        ecosystem.evolve()
        if enable_graphics:
            gui.handle_events()
            gui.draw_ecosystem()
        if make_sleeps:
            sleep(1.0)  # To remove
        if ecosystem.population() < ecosystem.minimum_population_allowed:
            n = ecosystem.minimum_population_allowed - ecosystem.population()
            ecosystem.create_new_organisms(n)
            print n, "organisms created",

    print "Time:", ecosystem.time, "Number of organisms:", \
        len(ecosystem.organisms_list)  # ***

    if enable_graphics:
        gui.delete()
    tls = net.get_trophic_levels()
        
    top, top_preds = net.top_predators()
    basal, basal_sps = net.basal()
    for u,v in net.edges():
        if u in basal_sps and v in top_preds and tls[v] == 3:
            net.remove_edge(u,v)
                
    print 'new connectance = ', net.connectance()

    if not READ_FILE_NETWORK:
        net_to_save = net.copy()
        nx.write_graphml(net_to_save, network_file)
    
    ##############################################
    ecosystem = Ecosystem(net, drawing=False)
    ecosystem.initialise_world(True)

    # here it works out the inital populations
    series_counts = dict()
    dict_stats = get_eco_state_row(0, ecosystem)
    series_counts[0] = ecosystem.populations

    # we don't this to store data, just for its keys
    cumulative_sps_stats = dict.fromkeys(net.nodes(), None)

       
    ##############################################
    for i in range(1, ITERATIONS+1):
        print i
        ecosystem.update_world()
        tls = net.get_trophic_levels()

        top, top_preds = net.top_predators()
        basal, basal_sps = net.basal()
        for u, v in net.edges():
            if u in basal_sps and v in top_preds and tls[v] == 3:
                net.remove_edge(u, v)

        print "new connectance = ", net.connectance()
    else:
        net = obtain_interactions_network()
        net_to_save = net.copy()
        nx.write_graphml(net_to_save, network_file)

    ecosystem = Ecosystem(net, drawing=False)
    ecosystem.initialise_world(True)

    # here it works out the inital populations
    series_counts = dict()
    dict_stats = get_eco_state_row(0, ecosystem)
    series_counts[0] = ecosystem.populations

    # we don't this to store data, just for its keys!
    cumulative_sps_stats = dict.fromkeys(net.nodes(), None)

    for i in range(1, ITERATIONS + 1):
        print i
        ecosystem.update_world()

        # dict_stats = get_eco_state_row(ITERATIONS, ecosystem)