Example #1
0
def testDnaSize():
	dna = Dna(1, 3)
	assert len(dna.genes) == 12
	assert len(dna.genes) == dna.length
	dna2 = Dna(2, 3)
	assert dna2.length == 22
	dna3 = Dna(2, 4)
	assert dna3.length == 26
Example #2
0
def testShapeExtraction():
	dna = Dna(2, 3)
	dna.genes = [2, 3, 
					255, 0, 0, 255,
					1, 2, 3, 4, 5, 6, 
					255, 0, 0, 255,
					7, 8, 9, 10, 11, 12]
	assert sorted(dna.polyAtIndex(1)) == sorted([(255, 0, 0, 255), [(7, 8), (9, 10), (11, 12)]])
Example #3
0
def testImageCreation():
	dna = Dna(2, 3)
	dna.genes = [2, 3, 
					255, 0, 0, 100,
					10, 10, 250, 250, 10, 250,
					0, 255, 0, 50,
					10, 10, 250, 10, 10, 250]	
	image = ImageTools.imageFromDna(dna)	
	image.show()
Example #4
0
 def initialize_population(self):
     """Initializes the population.
     """
     for _ in range(self.params.get('pop_size')):
         tmp_dna = Dna(self.initialize_bits(),
                       self.params.get('item_weights'),
                       self.params.get('item_values'),
                       Bag(self.params.get('bag_size')))
         tmp_dna.eval_vals()
         self.pop.append(tmp_dna)
Example #5
0
def testMutationRanges():
	dna = Dna(1, 3)
	for i in xrange(100):
		dna.mutate(1)
	for i in xrange(dna.headerSize, dna.length):
		gene = dna.genes[i]
		if dna.indexIsColour(i):
			assert gene > 0 and gene <= 255
		else:
			assert gene > 0 and gene <= Dna.imgSize
 def __init__(self, size, polyCount, vertexCount, targetImage):
     self.size = size
     self.targetImage = targetImage
     self.artists = [Dna(polyCount, vertexCount) for i in xrange(size)]
     [a.randomisePolys() for a in self.artists]
     self.cycles = 0
     self.improvements = 0
     self.mutationLevel = 0
Example #7
0
    def __init__(self):
        self.dna = Dna()
        self.acc = [0, 0]
        self.pos = [0, 0]
        self.vel = [0, 0]

        self.timer = 20
        pass
    def __init__(self, dna=None):
        if dna:
            self.dna = dna
        else:
            self.dna = Dna()
        self.keys = [Keys.UP, Keys.DOWN, Keys.LEFT, Keys.RIGHT]

        self.fitness = 0
        self.count = -1
Example #9
0
    def crossover(self, parent_a: Creature, parent_b: Creature) -> Dna:
        """
        Generates a new child with crossover.
        """

        # Compare both parent's genes.
        matching, disjoint, excess, max_number, a_connections, b_connections = self.compare_genomes(parent_a, parent_b)
        fit_parent = parent_a if parent_a.fitness > parent_b.fitness else parent_b \
            if parent_a.fitness < parent_b.fitness else None
        non_matching = disjoint + excess

        # Decide which genes the child will inherit.
        # For each gene, add the parent it will be inherited from. After everything is decided add the genes.
        child_gene_sources = dict()
        for number in matching:

            # Inherit weight from a random parent.
            if random() < 0.5:
                child_gene_sources[number] = parent_a
            else:
                child_gene_sources[number] = parent_b

        # If there is a fit parent, inherit disjoint and matching genes from it.
        if fit_parent:
            for number in non_matching:
                if number in fit_parent.dna.connections:
                    child_gene_sources[number] = fit_parent

        # If both parents are equally fit, inherit disjoint and excess genes randomly.
        else:
            for number in non_matching:
                if random() < 0.5 and number in a_connections:
                    child_gene_sources[number] = parent_a
                elif number in b_connections:
                    child_gene_sources[number] = parent_b

        # Add all genes the child should inherit.
        child_connections = dict()
        child_nodes = dict()
        for number, parent in child_gene_sources.items():
            connection = parent.dna.connections[number]
            child_connections[number] = connection
            src_number, dst_number = connection.src_number, connection.dst_number
            child_nodes[src_number] = parent.dna.nodes[src_number]
            child_nodes[dst_number] = parent.dna.nodes[dst_number]

        # Generate child.
        child_dna = Dna(nodes=child_nodes, connections=child_connections)
        return child_dna
Example #10
0
 def crossover(self, parent1, parent2, crossover_point):
     """Applies one point crossover operation to between two Dna objects. 
     Returns the results of the crossover by two Dna object.
     
     Keyword Arguments:
     parent1 -- Dna object that represents firs parent of crossover. 
     parent2 -- Dna object that represents second parent of crossover. 
     crossover_point -- Integer index of the crossover point.  
     """
     crossover_point += 1
     print('Applying Crossover:\t at', crossover_point)
     print('Parents: ', (parent1, parent2))
     child1_bits = parent1.bits[:crossover_point] + parent2.bits[
         crossover_point:]
     child2_bits = parent2.bits[:crossover_point] + parent1.bits[
         crossover_point:]
     child1 = Dna(child1_bits, self.params.get('item_weights'),
                  self.params.get('item_values'),
                  Bag(self.params.get('bag_size')))
     child2 = Dna(child2_bits, self.params.get('item_weights'),
                  self.params.get('item_values'),
                  Bag(self.params.get('bag_size')))
     print('Children: ', (child1_bits, child2_bits))
     return (child1, child2)
Example #11
0
    def base_dna() -> Tuple[Dna, List[ConnectionMutation]]:
        """
        Generate base Dna to start creatures from, connect nodes with connection mutations.
        """

        # Generate base Dna to start creatures from.
        base_nodes = {}
        for num in range(1, CREATURE_INPUTS + CREATURE_OUTPUTS + 1):
            base_nodes[num] = InputNode(num) if num < CREATURE_INPUTS + 1 else OutputNode(num, BIAS_RANGE)

        # Connect nodes with connection mutations.
        base_dna = Dna(CREATURE_INPUTS, CREATURE_OUTPUTS, nodes=base_nodes)
        mutations = []

        # Connect nodes by NEAT PARAMETER settings.
        if BASE_DNA == 'CONNECTED':
            for src_number in range(CREATURE_INPUTS):
                for dst_number in range(CREATURE_INPUTS, CREATURE_INPUTS + CREATURE_OUTPUTS):

                    # Generate connection mutation between each Input node to every Output node.
                    mutation = ConnectionMutation(len(mutations) + 1, src_number + 1, dst_number + 1)
                    mutations.append(mutation)
            base_dna.update(mutations)
        return base_dna, mutations
Example #12
0
from dna import Dna
import numpy as np
from numpy import random

gene = Dna(population=3000, mutation=0.4)

pop = gene.randomic_population()

generation = 1


def epoch(population):
    global generation
    print("=======================================")
    print("""------- Generation -------""" + str(generation))

    generation = generation + 1

    s = 0

    for i in range(len(population)):
        # Fit
        population[i].fitness()
        s = s + population[i].fit
        # mating Pool

    mean = s / gene.population
    print("-   mean error = {}".format(mean))
    print("========================================")
    matingPool = [gene]
    new_population = []
Example #13
0
from dna import Dna
from motif_search import MotifSearch

if __name__ == '__main__':
    file_name = 'dna'
    dna = Dna(file_name, generate=False)
    dna_lines = dna.lines
    print('10-Mer: ', dna.ten_mer)
    print('Mutated 10-Mers: ', dna.mutated_list)

    for k in range(9, 12):
        MotifSearch('random', dna_lines, k, check_period=500).print_results()
        MotifSearch('gibbs', dna_lines, k, check_period=500).print_results()
 def random(cls):
     """
     Generate a Candidate with 50 totally random Triangles.
     """
     dna = Dna.random()
     return cls(dna)
Example #15
0
        self.name = generate_name()
        self.fitness = 0
        self.health = CREATURE_HEALTH
        self.reach = CREATURE_REACH
        self.line_of_sight = CREATURE_LINE_OF_SIGHT

    def __str__(self):
        return CREATURE_STRING.format(self.name, self.dna.hidden)

    def __repr__(self):
        return str(self)

    def think(self, inputs: CreatureNetworkInput) -> CreatureNetworkOutput:
        """
        Gets the creature decision based on the inputs it was given.
        :param inputs: Sensory input.
        :return: Creature decision.
        """
        return CreatureNetworkOutput(*self.network.get_output(list(inputs)))

    def update(self, mutations: List[Union[MutationObject]]):
        self.dna.update(mutations)
        self.network = Network(self.dna.nodes, self.dna.node_connections)


if __name__ == '__main__':
    main_dna = Dna(inputs=2, outputs=6)
    c = Creature(dna=main_dna)
    print(c.think(CreatureNetworkInput(0, 0, 0)))
    print(c.think(CreatureNetworkInput(100, 100, 100)))
Example #16
0
def testDnaPolySwap():
	dna = Dna(2, 3)
	dna.genes =      [2, 3, 255, 0, 0, 100, 1, 2, 3, 4, 5, 6, 0, 255, 0, 50, 7, 8, 9, 10, 11, 12]	
	expectedResult = [2, 3, 0, 255, 0, 50, 7, 8, 9, 10, 11, 12, 255, 0, 0, 100, 1, 2, 3, 4, 5, 6]
	dna.swapPolys(0, 1)
	assert not cmp(dna.genes, expectedResult)
Example #17
0
def testDnaSpliceValidLength():
	mother = Dna(3, 3)
	father = Dna(3, 3)
	child = mother.splice(father)
	assert len(child.genes) == len(mother.genes)
Example #18
0
#!flask/bin/python
from flask import Flask
from flask import request, url_for
from flask import jsonify, abort
from dna import Dna
from werkzeug.utils import secure_filename
from alphabot_exceptions import *
import os 

d = Dna()
app = Flask(__name__)

@app.route('/', methods = ['GET', 'POST'])
def post_image():
    if request.method == 'GET':
        return "GET \n"
    if request.method == 'POST':
        
        
        file = request.files['file']
        filename = secure_filename(file.filename)
        file.save(filename)
        dirr = os.getcwd()
        osname = os.path.join(dirr, '')
        dest_img = osname + filename
        try: 
            results = d.find_distance_and_angle(dest_img)  ### pairnei path
            os.remove(dest_img)
            return jsonify(results)
        except BeaconNotFoundError:
            os.remove(dest_img)
Example #19
0
def testDnaInit():
	dna = Dna(3, 4)
	assert dna.genes[0] == 3
	assert dna.genes[1] == 4
	for i in range(2, dna.length-1):
		assert dna.genes[i] == 0
Example #20
0
def testIndexCategorisation():
	dna = Dna(1, 3)
	for i in xrange(2, 5):
		assert dna.indexIsColour(i) == True 
	for i in xrange(6, 12):
		assert dna.indexIsColour(i) == False