示例#1
0
    def __init__(self, pop_size, mutation_prob, num_cooperators, num_partials,
                 num_defectors):

        self._REPRO_THRESHOLD = 10
        self.population = []
        self.pop_size = pop_size
        self.mutation_prob = mutation_prob

        self.num_cooperators = num_cooperators
        self.num_partials = num_partials
        self.num_defectors = num_defectors

        # create population of the specified size of randomly generated organisms
        # for i in range(0, pop_size):
        #    org = organism.Organism( self.mutation_prob , self.num_cooperators, self.num_partials, self.num_defectors)
        #   self.population.append(org)

        for _ in range(0, self.num_cooperators):
            org = organism.Organism(self.mutation_prob, 10)
            self.population.append(org)
        for _ in range(0, self.num_partials):
            org = organism.Organism(self.mutation_prob, 5)
            self.population.append(org)
        for _ in range(0, self.num_defectors):
            org = organism.Organism(self.mutation_prob, 0)
            self.population.append(org)
示例#2
0
def parse_organism(org,
                   in_path=cs.STRING_PATH,
                   out_path=cs.JSON_PATH,
                   check=True):
    ppi_name = '{}.protein.links.v10.5.txt'.format(org)
    node_name = '{}_parsed_nodes.json'.format(org)
    edge_name = '{}_parsed_edges.json'.format(org)

    ppi_path = utils.join_path(in_path, ppi_name)
    node_path = utils.join_path(out_path, node_name)
    edge_path = utils.join_path(out_path, edge_name)

    if (check and utils.files_exist([node_name, edge_name], out_path)):
        message = 'using existing parsed jsons for {}'.format(org)
        utils.print_log(message)

    else:
        message = ('parsing ppi information of {}').format(org)
        utils.print_log(message)

        parse_organism_ppi(org, ppi_path, node_path, edge_path)

        message = ('ppi parsing finished for {}').format(org)
        utils.print_log(message)

    return organism.Organism(nodes_file=node_path,
                             edges_file=edge_path,
                             org_id=org)
示例#3
0
def main():
    maxx = maxy = 10

    board = arena.Arena(maxx, maxy)

    board.update( ((3, 5), 20) )

    dna = [("MOV", 1),          # 0 Move one ahead
           ("TUR", 1),          # 1 Turn right
           ("SEN", 1),          # 2 Sense ahead
           ("JGZ", 6),          # 3 Found food!
           ("MOV", 1),          # 4 Move one ahead
           ("JMP", 0),          # 5 Repeat
           ("EAT", 1)           # 6 Eat the food found
           ]

    bacterium = organism.Organism((5, 5), organism.SOUTH, dna)

    orglist = [bacterium]

    retval = None

    quit = False
    tick = 0

    while not quit:
        for current_org in orglist:
            retval = current_org.run(board.arena)
            if retval:
                board.update( (retval[0], retval[1]) )
        prompt = "(tick: %d)> " % tick
        quit = raw_input(prompt)
        tick += 1
示例#4
0
  def setUp(self):
    test_attributes = {"Visualization": {"Color": "#00FF00"}}

    self.__grid = C_Grid(100, 100)
    self.__grid_object = organism.Organism(self.__grid, (5, 5))
    self.__grid_object.set_attributes(test_attributes)

    self.__grid_vis = visualization.GridVisualization(100, 100)
    self.__grid_object_vis = visualization.GridObjectVisualization(
        self.__grid_vis, self.__grid_object)
示例#5
0
  def setUp(self):
    # Reset the list of saved grid objects so that we end up with the right
    # indices.
    grid_object.GridObject.clear_objects()

    test_attributes1 = {"CommonName": "Test Species",
        "Taxonomy": {"Domain": "TestDomain"}}
    test_attributes2 = copy.deepcopy(test_attributes1)
    test_attributes2["Taxonomy"]["Domain"] = "TestDomain2"
    test_attributes3 = copy.deepcopy(test_attributes1)
    test_attributes3["Taxonomy"]["Domain"] = "TestDomain3"

    grid = C_Grid(10, 10)

    # Simply instantiating our handler should register it.
    self.__test_handler = TestUpdateHandler.TestingHandler()

    self.__organism1 = organism.Organism(grid, (0, 0))
    self.__organism2 = organism.Organism(grid, (1, 1))
    self.__organism3 = organism.Organism(grid, (2, 2))
    self.__organism1.set_attributes(test_attributes1)
    self.__organism2.set_attributes(test_attributes2)
    self.__organism3.set_attributes(test_attributes3)
示例#6
0
    def __init__(self, target, mutationRate, size):
        # this is the list of all the organisms in a generation
        self.population = []
        # matingPool of the population
        self.matingPool = []
        # the size of a population
        self.size = size
        # this is the generation of the population
        self.generations = 0
        # this takes care of the termination
        self.finished = False
        # this is the target that needs to match
        self.target = target
        self.mutationRate = mutationRate

        # creating the first population GENERATION 1
        # can be thought of as the setup function
        for idx in range(self.size):
            self.population.append(organism.Organism(len(self.target)))
        # calculates the fitness of all the organisms
        self.calcFitness()
示例#7
0
  def test_predation(self):
    predator = organism.Organism(self.__grid, (1, 1))
    self.assertTrue(self.__grid.Update())

    # These attributes will cause the predator organism to prey on the other
    # one.
    prey_attributes = {"Taxonomy": {"Genus": "Prey", "Species": "Species"},
        "Metabolism": {"Animal": {"PredatorFactorStrength": -1,
        "PredatorFactorVisibility": -1}}}
    predator_attributes = {"Prey": "Prey Species",
        "Taxonomy": {"Genus": "Predator", "Species": "Species"}, "Metabolism":
        {"Animal": {"PreyFactorStrength": 1,
        "PreyFactorVisibility": -1}}}
    self.__organism.set_attributes(prey_attributes)
    predator.set_attributes(predator_attributes)

    # Initialize some default metabolisms for the organisms.
    predator.metabolism = AnimalMetabolism(0.5, 0.1, 310.15, 0.5, 0.37)
    self.__organism.metabolism = AnimalMetabolism(0.5, 0.1, 310.15,
                                                  0.5, 0.37)
    original_energy = predator.metabolism.energy()

    # Move the two organisms into a position where they conflict.
    self.__organism.set_position((0, 0))
    with self.assertRaises(grid_object.GridObjectError):
      predator.set_position((0, 0))

    # Handle the conflict.
    predator.handle_conflict()

    # Check that the prey is dead.
    self.assertFalse(self.__organism.is_alive())
    # Check that the predator has all the prey's energy.
    self.assertEqual(original_energy * 2, predator.metabolism.energy())

    # The conflict should now be resolved, and we should be able to update the
    # grid.
    self.assertTrue(self.__grid.Update())
示例#8
0
  def setUp(self):
    grid_object.GridObject.clear_objects()

    self.__grid = C_Grid(10, 10)
    self.__organism = organism.Organism(self.__grid, (0, 0))
示例#9
0
import organism
phrase = input('Input a phrase as the target: ')
target = [ch for ch in phrase]
num_of_genes = len(target)
mutationRate = 0.1

print('*' * 40)

word1 = organism.Organism(num_of_genes)
print('GENES OF WORD1=', word1.genes)

word1.fitnessFunction(target)
print('FITNESS OF WORD1=', word1.fitness)

print('*' * 40)

word2 = organism.Organism(num_of_genes)
print('GENES OF WORD2=', word2.genes)

word2.fitnessFunction(target)
print('FITNESS OF WORD2=', word2.fitness)

print('*' * 40)

childWord = word1.crossover(word2)
print('GENES OF CHILDWORD=', childWord.genes)

childWord.fitnessFunction(target)
print('FITNESS OF CHILDWORD=', childWord.fitness)

childWord.mutation(mutationRate)
示例#10
0
def mainGraphicsLoop():
    global frames, totalOrgs

    # Initialize the game engine
    pygame.init()

    orgsani = chaosapi.setup()
    organ = orgsani[0]
    for org in organ['organisms']:
        organismList.append(organism.Organism(org))
    totalOrgs = organ['stats']['orgsSpawnedSoFar']

    #set window peramiters and open the window
    size = (screenWidth, screenWidth)
    screen = pygame.display.set_mode(size)

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    font = pygame.font.SysFont('Comic Sans MS', 15)

    # -------- Main Program Loop -----------
    while not done:

        frames += 1

        # --- Main event loop
        for event in pygame.event.get():  # User did something
            if event.type == pygame.QUIT:  # If user clicked close
                done = True  # Flag that we are done so we exit this loop
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    for org in organismList:
                        scoredOrgs.append(org)
                    organismList.clear()

        profiler.start('everything')

        screen.fill((255, 255, 255))

        for region in wall_regions:
            pygame.draw.rect(screen, region[5],
                             (region[0], region[1], region[2], region[3]))

        for scoreOrbs in scoreOrb.scoreOrbList:
            pygame.draw.circle(screen, scoreOrbs.color,
                               (scoreOrbs.x, scoreOrbs.y), scoreOrbs.radius)
            textsurface = font.render(str(scoreOrbs.score), False, (0, 0, 0))
            screen.blit(textsurface, (scoreOrbs.x, scoreOrbs.y))

        encoded = []
        if len(organismList) <= 0:
            for score in scoredOrgs:
                encoded.append(score.to_json())

            scoredOrgs.clear()
            organismList.clear()
            jsonMes = json.dumps({"report": encoded})
            newOrgs = chaosapi.reportOrgs('mechanist', 'finalRoom', orgsani[1],
                                          orgsani[2], jsonMes)
            totalOrgs = newOrgs['stats']['orgsSpawnedSoFar']
            for orgsi in newOrgs['organisms']:
                organismList.append(organism.Organism(orgsi))

        profiler.start('organisms')
        for org in organismList[:]:
            org.neuralNetwork.evaluate()

            color = (255, 0, 0)
            textsurface = font.render(str(org.trainingRoomNamespace), False,
                                      (255, 255, 255))
            orgAmount = font.render(
                str(totalOrgs) + " / 2000", False, (255, 255, 255))
            screen.blit(textsurface, (0, 0))
            screen.blit(orgAmount, (70, 0))

            if (frames - org.timeSinceLastScore) >= org.maxFrames:
                scoredOrgs.append(org)
                organismList.remove(org)
                continue

            for scoreOrbs in scoreOrb.scoreOrbList:
                scoreOrbs.intersects(org)

            # Read & handle outputs
            for output in org.neuralNetwork.outputs:

                if output.type == 'TurnOutput':
                    org.turnOutput(output._lastValue)
                if output.type == 'MoveOutput':
                    org.moveOutput(output._lastValue)
                if output.type == 'MoveSidewaysOutput':
                    org.sidwaysMoveOutput(output._lastValue)

            # Show the player's location before drawing eyes
            pygame.draw.circle(screen, org.color, (int(org.x), int(org.y)),
                               org.radius)

            view_x = org.x + math.cos(
                org.rotation * math.pi / 180) * org.radius * 2
            view_y = org.y - math.sin(
                org.rotation * math.pi / 180) * org.radius * 2
            pygame.draw.line(screen, (0, 0, 0), (org.x, org.y),
                             (view_x, view_y), 2)

            for color in org.neuralNetwork.colors:
                org.color = color.color
            # Render eyes
            for i in org.neuralNetwork.inputs:
                eyeValue = i.attributeValue
                eye = org.neuralNetwork.eyesDict[i.eyeId]

                eyeDirection = eye.direction + -org.rotation
                distance = 100 + org.radius
                distance_x = math.cos(eyeDirection * math.pi / 180) * distance
                distance_y = math.sin(eyeDirection * math.pi / 180) * distance
                x = org.x + distance_x
                y = org.y + distance_y

                trace_x = org.x + math.cos(
                    eyeDirection * math.pi / 180) * org.radius
                trace_y = org.y + math.sin(
                    eyeDirection * math.pi / 180) * org.radius
                trace_distance = distance - org.radius
                eye_to_wall = distance_to_wall(trace_x, trace_y, eyeDirection,
                                               trace_distance)
                eye_to_orb = distance_to_orb(trace_x, trace_y, eyeDirection,
                                             trace_distance)
                #While looking at nothing turn a weird purplish color
                if eye_to_wall[0] == -1 and eye_to_orb[0] == -1:
                    value = 0
                    color = (123, 57, 199)

                #While looking at a wall that is the same as the eyeValue turn green and change the value
                elif eyeValue == eye_to_wall[1]:
                    value = (trace_distance - eye_to_wall[0]) / trace_distance
                    color = (0, 255, 0)

                #While looking at an orb that is the same as the eyeValue turn cyan and change the value
                elif eyeValue == eye_to_orb[1]:
                    value = (trace_distance - eye_to_orb[0]) / trace_distance
                    color = (0, 255, 255)

                #While looking at something else turn yellow
                else:
                    value = 0
                    color = (123, 57, 199)
                eye.value = value

                pygame.draw.line(screen, color, (trace_x, trace_y), (x, y), 2)

                score = font.render(str(org.score), False, (0, 0, 0))
                screen.blit(score, (org.x, org.y))
        profiler.end()
        profiler.end()
        #update the screen
        pygame.display.flip()
示例#11
0
def main():

    with open('config.json') as config_file:
        settings = json.load(config_file)

    #Starting module:
    pygame.init()
    display = pygame.display.set_mode([
        settings['pygame_settings']['window_height'],
        settings['pygame_settings']['window_width']
    ])
    clock = pygame.time.Clock()

    orgs = []
    predators = []
    food = []
    poison = []

    for i in range(50):
        food.append(
            numpy.array([
                random.uniform(0, settings['pygame_settings']['window_width']),
                random.uniform(0, settings['pygame_settings']['window_height'])
            ],
                        dtype='float64'))
    for i in range(10):
        orgs.append(
            organism.Organism(
                settings, display,
                random.randrange(0,
                                 settings['pygame_settings']['window_height']),
                random.randrange(0,
                                 settings['pygame_settings']['window_width'])))
        predators.append(
            predator.Predator(
                settings, display,
                random.randrange(0,
                                 settings['pygame_settings']['window_height']),
                random.randrange(0,
                                 settings['pygame_settings']['window_width'])))
        food.append(
            numpy.array([
                random.uniform(0, settings['pygame_settings']['window_width']),
                random.uniform(0, settings['pygame_settings']['window_height'])
            ],
                        dtype='float64'))
        poison.append((numpy.array([
            random.uniform(0, settings['pygame_settings']['window_width']),
            random.uniform(0, settings['pygame_settings']['window_height'])
        ],
                                   dtype='float64')))
    running = True
    while (running):
        display.fill(settings['colors']['black'])

        if random.random() < 0.01:
            poison.append(
                numpy.array([
                    random.uniform(
                        0, settings['pygame_settings']['window_width']),
                    random.uniform(
                        0, settings['pygame_settings']['window_height'])
                ],
                            dtype='float64'))

        if len(orgs) < 5 or random.random() < 0.0001:
            orgs.append(
                organism.Organism(
                    settings, display,
                    random.randrange(
                        0, settings['pygame_settings']['window_height']),
                    random.randrange(
                        0, settings['pygame_settings']['window_width'])))

        if len(predators) < 10:
            predators.append(
                predator.Predator(
                    settings, display,
                    random.randrange(
                        0, settings['pygame_settings']['window_height']),
                    random.randrange(
                        0, settings['pygame_settings']['window_width'])))

        if len(food) < 100:
            food.append(
                numpy.array([
                    random.uniform(
                        0, settings['pygame_settings']['window_width']),
                    random.uniform(
                        0, settings['pygame_settings']['window_height'])
                ],
                            dtype='float64'))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        for org in orgs[::-1]:
            # print(org.health)
            org.eat(food, 0)
            org.eat(poison, 1)
            org.boundaries()

            org.update()
            org.draw()

            if org.dead(food):
                orgs.remove(org)
                print("Organism died")
            else:
                org.reproduce(orgs)

        for pred in predators[::-1]:
            pred.fight(orgs)
            pred.boundaries()

            pred.update()
            pred.draw()

        for i in food:
            pygame.draw.circle(display, (0, 0, 225), [int(i[0]), int(i[1])], 3)

        for i in poison:
            pygame.draw.circle(display, (122, 4, 233),
                               [int(i[0]), int(i[1])], 3)
        pygame.display.update()
        clock.tick(60)

    pygame.quit()