Ejemplo n.º 1
0
 def create_genius(self):
     genius = DNA()
     genius.dna = [  3,0.06,0.0001,10,5, # PID Ramp Up
                     7,0.05,0,2,5,       # PID Overshoot Over 
                     1,0.04,0.01,5,10,   # PID Hold Over
                     10,0.03,0,2,5,      # PID Land Over
                     0.9,0.04,0.01,5,10, # PID Hold
                     3,0.06,0.0001,10,5, # PID Ramp Down
                     7,0.05,0,2,5,       # PID Overshoot Under
                     1,0.04,0.01,5,10,   # PID Hold Under
                     10,0.03,0,2,5,      # PID Land Under
                     2.8, # Max Heat Overshoot
                     3.4, # Max Cool Overshoot
                     2, # Heat Sample Window
                     2, # Cool Sample Window
                     40, # Max Hold Power
                     150, # Max Ramp Power
                     4, # Heat Block Window
                     3, # Cool Block Window
                     1.2, # Heat Overshoot Attenuation
                     0.2, # Heat Overshoot Activation RR
                     0.1, # Heat Overshoot Activation SP
                     1.5, # Cool Overshoot Attenuation
                     0.3, # Cool Overshoot Activation RR
                    -0.1, # Cool Overshoot Activation SP
                     1.6, # Temp Ctrl Over RR Limit
                     1.5, # Temp Ctrl Under RR Limit
                     1.5, # Temp Ctrl Over Block Window
                     1.75, # Temp Ctrl Under Block Window
                 ]
     return genius
Ejemplo n.º 2
0
class TestGetPair(unittest.TestCase):
    def setUp(self):
        self.dna = DNA()
    
    def test_lowercase(self):
        self.dna.to_pair = "a"
        self.dna.get_pair()
        self.assertEqual(self.dna.to_pair, "A")

    def test_a_t(self):
        self.dna.to_pair = "A"
        self.dna.get_pair()
        self.assertEqual(self.dna.pair, "T")

    def test_t_a(self):
        self.dna.to_pair = "T"
        self.dna.get_pair()
        self.assertEqual(self.dna.pair, "A")

    def test_g_c(self):
        self.dna.to_pair = "G"
        self.dna.get_pair()
        self.assertEqual(self.dna.pair, "C")

    def test_c_g(self):
        self.dna.to_pair = "C"
        self.dna.get_pair()xb
        self.assertEqual(self.dna.pair, "G")
Ejemplo n.º 3
0
def main():
    
    # Open master image in RGB mode
    master_image = Image.open("obama.png").convert(mode="RGB")   
    width, height = master_image.size

    # Create initial polygons
    polygons = []
    for i in range(200):
        x_points = np.random.random_integers(low=0,high=width,size=3).tolist()
        y_points = np.random.random_integers(low=0,high=height,size=3).tolist()
        points = zip(x_points, y_points)
        color = tuple(np.random.random_integers(low=0, high=255, size=4).tolist())
        polygon = Polygon(points, color)
        polygons.append(polygon)

    # Create initial DNA
    parent = DNA(polygons, master_image)

    # Evolve DNA and breed fittest
    for i in range(1000):
        child = parent.breed()
        if child.fitness < parent.fitness:
            parent = child

    # Save image and polygon information
    parent.save()
Ejemplo n.º 4
0
 def __init__(self,
              gameDisplay,
              w=40,
              h=40,
              snake_len=3,
              life=10000,
              food_energy=10,
              dna=None,
              color=None):
     self.w = w
     self.h = h
     self.body = []
     self.xdir = 1
     self.ydir = 0
     self.dir = 1
     self.grow = False
     self.snake_len = snake_len
     self.gameDisplay = gameDisplay
     self.create_snake()
     self.died = False
     if color is None:
         self.color = (randint(0, 255), randint(0, 255), randint(0, 200))
     else:
         self.color = (randint(0, 255), randint(0, 255), randint(0, 200))
     self.score = 0
     self.life = life
     self.life_orig = life
     self.food_energy = food_energy
     if dna is None:
         self.dna = DNA(6, 4, [0, 10])
     else:
         self.dna = dna
     self.food = []
     self.cur_state = None
     self.reward = 0
Ejemplo n.º 5
0
 def test_container_inequality(self):
     dna1 = DNA([ScoreCard(1, 10), ScoreCard(2, 20)])
     dna2 = DNA([ScoreCard(3, 30), ScoreCard(4, 40)])
     self.assertNotEqual(dna1, dna2)
     container1 = Container(dna1, 1)
     container2 = Container(dna2, 1)
     self.assertNotEqual(container1, container2)
     self.assertNotEqual(container1.__hash__(), container2.__hash__())
Ejemplo n.º 6
0
def test():
    test_input = "A A T G C C T A T G G C"
    expected_output = "A A T G C C T A T G G C\nT T A C G G A T A C C G"
    dna = DNA()
    strand = dna.get_strand(test_input)
    print "Output:\n%s" % (strand)
    print "Expected:\n%s" % (expected_output)
    if strand == expected_output: print "PASS"
    else: print "FAIL"
Ejemplo n.º 7
0
    def random_dna(self):
        population_dna = []

        for _ in range(self.population):
            dna = DNA(self.goal_len)
            dna.random_dna()
            population_dna.append(dna)

        return population_dna
 def crossover(self, first, second):
     point = random.randint(0, len(self.aim) - 1)
     new_dna = DNA(self.aim, self.mutation_rate)
     for i in range(len(self.aim)):
         if i <= point:
             new_dna.dna.append(first.dna[i])
         else:
             new_dna.dna.append(second.dna[i])
     new_dna.calc_fitness()
     return new_dna
Ejemplo n.º 9
0
class TestGetOutput(unittest.TestCase):
    def setUp(self):
        self.dna = DNA()

    def test_output(self):
        self.dna.in_sequence = "1234"
        self.dna.out_sequence = "5678"
        self.dna.get_output()
        expected = "1234\n5678"
        self.assertEqual(self.dna.strand, expected)
Ejemplo n.º 10
0
class DNAVis(Widget):
    def __init__(self, **kw):
        super(DNAVis, self).__init__(**kw)
        self.dna = DNA()
        self.crawler = self.dna.spawn_crawler()

        self.bind(size=self.redraw, pos=self.redraw)

    def redraw(self, *ar):
        for w in self.children[:]:
            if isinstance(w, NodeVis):
                self.remove_widget(w)

        node_lookup = {}

        y = self.top - 100
        crawler = self.dna.spawn_crawler()
        crawler.reset()
        indent = 100

        for n, indent_no in crawler.crawl_indents():
            indent += 100 * indent_no

            nv = NodeVis(size=(100, 100), text=n.name)
            node_lookup[n] = nv
            nv.x = self.x + indent
            nv.y = y

            self.add_widget(nv)
            y -= 100

        crawler = self.crawler
        cv = NodeVis(size=(100, 100), text="CRAWLER", color=[0.7, 0.05, 0])
        if crawler.current_node is not None:
            cv.x = node_lookup[crawler.current_node].x - 100
            cv.y = node_lookup[crawler.current_node].y
        else:
            cv.y = self.top - 100
            cv.x = self.width - cv.width
        self.add_widget(cv)

    def eval_input(self, text):
        dna = self.dna
        crawler = self.crawler

        if not hasattr(self, "exec_locals"):
            self.exec_locals = locals()

        try:
            to_run = compile(text, "", "exec")
            exec(to_run, globals(), self.exec_locals)
        except (NameError, SyntaxError, AttributeError, TypeError) as err:
            print(err)

        self.redraw()
Ejemplo n.º 11
0
 def test_does_not_actually_shorten_original_strand(self):
     self.assertEqual(
         1,
         DNA('AGACAACAGCCAGCCGCCGGATT').hamming_distance('AGGCAA'))
     self.assertEqual(
         4,
         DNA('AGACAACAGCCAGCCGCCGGATT').hamming_distance(
             'AGACATCTTTCAGCCGCCGGATTAGGCAA'))
     self.assertEqual(
         1,
         DNA('AGACAACAGCCAGCCGCCGGATT').hamming_distance('AGG'))
Ejemplo n.º 12
0
    def create_population(self, pop_size, genius=None):
        population = []
        
        for i in range(0, pop_size):
            creature = DNA()
            creature.generate_DNA()
            population.append(creature)

        if genius != None:
            population = population[:-1] + [genius]            

        return population
Ejemplo n.º 13
0
def _get_query_seqs(count_start, ref, ref_complement, sRNA_length):
    """

    :param count_start:
    :param ref:
    :param ref_complement:
    :param sRNA_length:
    :return:
    """
    query_seq_fwd = DNA(ref[count_start:(count_start + sRNA_length)])
    query_seq_rvs = DNA(ref_complement[count_start:(count_start +
                                                    sRNA_length)])
    return query_seq_fwd, query_seq_rvs
Ejemplo n.º 14
0
    def run(self, pcr_model_path="hybrid_pcr_model.ml", record_path=None, warm_up=True, stagnant_period=None):
        population = []
        if warm_up:
            best_creature = self.create_genius()
        else:
            best_creature = DNA()
            best_creature.generate_DNA()
        best_creature.score = -1000000
        cgeneration = 0

        if stagnant_period == None:
            stagnant_period = self.max_generation
        # Increase mutation chance if the fitness score not improved over generations
        # Reach the mutation limit in half of the stagnant period
        mutation_initial_value = self.mutation_chance
        mutation_step = (self.mutation_limit - mutation_initial_value) / stagnant_period * 2
        
        for noGeneration in range(0, self.max_generation):
            population = self.breed_population(population=population, genius=best_creature)
            print(f"-------- Generation={noGeneration} / {self.max_generation} Population={len(population)} --------")
                
            for loc, creature in enumerate(population):
                self.eval_fitness_score(creature=creature, pcr_model=self.load_model(pcr_model_path))
                print(f"Creature {loc} scores {creature.score:.2f} fitness points")

            # Rank the creature fitness scores
            population.sort(key=self.getScore, reverse=True)

            # Kill the bottom half of the population
            population = population[:self.pop_size // 2]

            if population[0].score > best_creature.score:
                best_creature = population[0].copy()
                self.mutation_chance = mutation_initial_value
                cgeneration = 0
                print(f"*** Generation {noGeneration} new genius scores {best_creature.score} fitness points\n\n")
            else:
                cgeneration += 1
                if self.mutation_chance < self.mutation_limit:
                    self.mutation_chance += mutation_step     
                print(f"-------- Stagnant Period = {cgeneration} / {stagnant_period}")           

            if cgeneration >= stagnant_period:
                print(f"WARNING: Population quality has reach its peak. Algorithm ends.\n")
                break

        print("==============================================================")
        print(f"The best creature score is {best_creature.score:.2f} fitness points")
        self.export_creature(creature=best_creature,
                             filepath=record_path[:-4] + f"score{int(best_creature.score)}" + record_path[-4:],
                             pcr_model_path=pcr_model_path,)
Ejemplo n.º 15
0
    def __init__(self, dna = -1):
        # Genetic
        if dna == -1:
            self.dna = DNA()
        else:
            self.dna = deepcopy(dna)
            self.dna.mutate()

        # Copying evaluation function
        m, b = self.dna.eval_data
        self.evaluate = lambda x: m * x + b > 0

        # Cultural
        self.meme = np.random.choice([0, 1], size = str_len)
Ejemplo n.º 16
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem6')
    solution_dir = os.path.join("Problems", "Problem6Solution")

    data_reader = DataReader(problem_dataset_dir)
    test_cases, output = data_reader.get_data()

    for train_i in range(0, len(output)):
        case = test_cases[train_i]
        case_output = output[train_i]
        genome = case[0]
        k = case[1][0]
        l = case[1][1][0]
        t = case[1][1][1]
        dna = DNA(genome)
        clumps_patterns = dna.get_clumps_patterns(int(k), int(t), int(l))

        if clumps_patterns.sort() != case_output.sort():
            raise Exception("Output not matched!\nExpecting: " + str(case_output) + "\nFound: " + clumps_patterns)

    print("Passed training data..")

    writer = DataWriter(solution_dir)
    usage = Usage()

    for test_i in range(len(test_cases) - len(output), len(test_cases)):
        usage.start()
        case = test_cases[test_i]
        genome = case[0]
        k = case[1][0]
        l = case[1][1][0]
        t = case[1][1][1]
        dna = DNA(genome)
        clumps_patterns = dna.get_clumps_patterns(int(k), int(t), int(l))
        usage.end()

        writer.write_data(test_i, clumps_patterns, usage.get_execution_time(), usage.get_memory_usage())
        print("\n\nInput:\n" + genome + "\n" + str(k) + " " + str(l) + " " + str(t))

        print("\n\nOutput")
        print("=====")

        for clump in clumps_patterns:
            print(clump)

        print("\n")
        print("======")
        print("Execution Time: " + str(usage.get_execution_time()) + " s")
        print("Memory Used: " + str(usage.get_memory_usage()) + " MB")
Ejemplo n.º 17
0
    def generate_dna_from(alpha, beta):
        # handler = JSONHandler()
        # handler.load_file("./data/pudgies/" + alpha + ".json")
        # alpha_json = handler.get_data()
        # handler.load_file("./data/pudgies/" + beta + ".json")
        # beta_json = handler.get_data()
        #
        # alpha_dna = DNA(alpha_json["dna"])
        # beta_dna = DNA(beta_json["dna"])

        alpha_dna = DNA(alpha["dna"])
        beta_dna = DNA(beta["dna"])

        strand = DNA.combine_dna(alpha_dna, beta_dna)
        return DNA(strand)
Ejemplo n.º 18
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem2')
    solution_dir = os.path.join("Problems", "Problem2Solution")

    data_reader = DataReader(problem_dataset_dir)
    training_data, testing_data = data_reader.get_data()
    codons_table = data_reader.get_rna_codon_table()

    for sample in training_data:
        dna_string = sample[0][0]
        amino_acid = sample[0][1]
        output = sample[1]
        dna = DNA(dna_string)
        dna.set_codon_table(codons_table)
        candidates = dna.get_dna_to_amino_acid_candidates(amino_acid)

        if set(candidates) != set(output):
            raise Exception("Output not matched!\nExpecting: " + str(output) +
                            "\nFound: " + str(candidates))

    print("Passed training data..\n\n")

    writer = DataWriter(solution_dir)
    usage = Usage()

    for sample in testing_data:
        usage.start()
        dna_string = sample[0][0]
        amino_acid = sample[0][1]
        dna = DNA(dna_string)
        dna.set_codon_table(codons_table)
        candidates = dna.get_dna_to_amino_acid_candidates(amino_acid)
        usage.end()

        writer.write_data((dna_string, amino_acid), candidates,
                          usage.get_execution_time(), usage.get_memory_usage())
        print("DNA:\n" + dna_string)
        print("Protein\n" + amino_acid)

        print("\n\nOutput")
        print("=====")

        print(str(len(candidates)))
        for substring in candidates:
            print(substring)

        print("\n\nExecution Time: " + str(usage.get_execution_time()) + " s")
        print("Memory Usage: " + str(usage.get_memory_usage()) + " MB")
    def selection1(self):

        m = DNA.get_total_fitness()
        num1 = random.randint(1, m + 10)
        num2 = random.randint(1, m + 10)
        num_1 = num1
        num_2 = num2
        first_population = None
        second_population = None
        i = 0

        while first_population == None or second_population == None:
            if first_population == None:
                num1 -= self.population[4].fitness
                if num1 <= 0:
                    first_population = self.population[i]
            if second_population == None:
                num2 -= self.population[2].fitness
                if num2 <= 0:
                    second_population = self.population[i]
            i += 1
            if i >= self.strength:
                if num2 == num_2 or num1 == num_1:
                    first_population = self.population[random.randint(
                        0, self.strength - 1)]
                    second_population = self.population[random.randint(
                        0, self.strength - 1)]
                else:
                    i = 0
        return {'first': first_population, 'second': second_population}
Ejemplo n.º 20
0
 def generate_random_creature(self):
     return BrainCreature(x=random.uniform(0, self.width),
                          y=random.uniform(0, self.height),
                          dna=DNA(),
                          brain_dna=BrainDNA(),
                          name='Creature ' +
                          str(creature_id_generator.get_next_id()))
Ejemplo n.º 21
0
 def _CreatesPop(self):
     self.members = [
         DNA(func=self.func,
             upper_bound_vector=self.upper_bound,
             lower_bound_vector=self.lower_bound,
             size=len(self.upper_bound)) for _ in range(self.pop_size)
     ]
Ejemplo n.º 22
0
 def snakes_init(self):
     self.snakes = []
     for i in range(0, self.population):
         if self.dna is None:
             snake_dna = DNA()
             snake_dna.Q_table = self.load_dna()
             self.dna = snake_dna
         else:
             snake_dna = self.dna
         snake = Snake(self.gameDisplay,
                       self.w,
                       self.h,
                       snake_len=SNAKE_LEN,
                       life=LIFE,
                       food_energy=FOOD_ENERGY,
                       dna=snake_dna)
         self.snakes.append(snake)
Ejemplo n.º 23
0
    def __init__(self):
        self.gene_pool = []

        for index in range(self.POPULATION_SIZE):
            new_dna = DNA()
            self.gene_pool.append(new_dna)

        heapq.heapify(self.gene_pool)
Ejemplo n.º 24
0
 def __init__(self, num):
     self.num = num
     self.food = Food(num)
     self.bloops = []
     for i in range(num):
         loc = PVector(random(width), random(height))
         dna = DNA()
         self.bloops.append(Bloop(dna, loc))
Ejemplo n.º 25
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem9')
    solution_dir = os.path.join("Problems", "Problem9Solution")

    data_reader = DataReader(problem_dataset_dir)
    test_cases, output = data_reader.get_data()

    for train_i in range(0, len(output)):
        case = test_cases[train_i]
        case_output = output[train_i]
        genome = case[0]
        k = case[1][0]
        d = case[1][1]
        dna = DNA(genome)
        k_mers = dna.most_frequent_missmatched_k_mer(int(k), int(d))

        if set(case_output) != set(k_mers):
            raise Exception("Output not matched!\nExpecting: " + str(case_output) + "\nFound: " + str(k_mers))

    print("Passed training data..")

    writer = DataWriter(solution_dir)
    usage = Usage()

    for test_i in range(len(test_cases) - len(output) + 1, len(test_cases)):
        usage.start()
        case = test_cases[test_i]
        genome = case[0]
        k = case[1][0]
        d = case[1][1]
        dna = DNA(genome)
        k_mers = dna.most_frequent_missmatched_k_mer(int(k), int(d))
        usage.end()

        writer.write_data(test_i, k_mers, usage.get_execution_time(), usage.get_memory_usage())
        print("\n\nInput:\n" + genome + "\n" + str(k) + "\n" + str(d))

        print("\n\nOutput")
        print("=====")

        print('\n'.join(map(lambda v: str(v), k_mers)))

        print("\n")
        print("======")
        print("Execution Time: " + str(usage.get_execution_time()) + " s")
        print("Memory Used: " + str(usage.get_memory_usage()) + " MB")
Ejemplo n.º 26
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem5')
    solution_dir = os.path.join("Problems", "Problem5Solution")

    data_reader = DataReader(problem_dataset_dir)
    test_cases, output = data_reader.get_data()

    for train_i in range(0, len(output)):
        case = test_cases[train_i]
        case_output = output[train_i]
        pattern = case[0]
        genome = case[1]
        dna = DNA(genome)
        pattern_indices = dna.get_pattern_indices(pattern)

        if pattern_indices != case_output:
            raise Exception("Output not matched!\nExpecting: " +
                            str(case_output) + "\nFound: " + pattern_indices)
Ejemplo n.º 27
0
 def __init__(self):
     self.win = tk.Tk()
     self.configWin()
     self.spawnTarget()
     self.spawnObst()
     self.pop = Population(100, self.canv, self.targetPos, self.obstPos)
     self.LIFESPAN = DNA().LIFESPAN
     self.cnt = 0
     self.win.mainloop()
Ejemplo n.º 28
0
    def create_initial_population(self):

        """
        Create an initial population consisting of *population_size*
        primitive neural networks with an input-output structure
        """

        for individual_i in range(self.population_size):
            
            individual_dna = DNA(Settings.INPUT_SHAPE, Settings.OUTPUT_SHAPE)
            individual_dna.create_primitive_structure()

            individual_fitness = self.build_and_train_network(individual_dna)

            self.population.append(individual_dna)
            self.fitness.append(individual_fitness)

        self.best_generations_fitness.append(min(self.fitness))
Ejemplo n.º 29
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem5')
    solution_dir = os.path.join("Problems", "Problem5Solution")

    data_reader = DataReader(problem_dataset_dir)
    test_cases, output = data_reader.get_data()

    for train_i in range(0, len(output)):
        case = test_cases[train_i]
        case_output = output[train_i]
        pattern = case[0]
        genome = case[1]
        dna = DNA(genome)
        pattern_indices = dna.get_pattern_indices(pattern)

        if pattern_indices != case_output:
            raise Exception("Output not matched!\nExpecting: " + str(case_output) + "\nFound: " + pattern_indices)

    print("Passed training data..")

    writer = DataWriter(solution_dir)
    usage = Usage()

    for test_i in range(len(test_cases) - len(output), len(test_cases)):
        usage.start()
        case = test_cases[test_i]
        pattern = case[0]
        genome = case[1]
        dna = DNA(genome)
        pattern_indices = dna.get_pattern_indices(pattern)
        usage.end()

        writer.write_data(test_i + 1, pattern_indices, usage.get_execution_time(), usage.get_memory_usage())
        print("\n\nInput:\n" + pattern + "\n" + genome)

        print("\n\nOutput")
        print("=====")

        print(pattern_indices)

        print("\n")
        print("======")
        print("Execution Time: " + str(usage.get_execution_time()) + " s")
        print("Memory Used: " + str(usage.get_memory_usage()) + " MB")
Ejemplo n.º 30
0
    def generate_population(self):
        self.population = []

        for i in range(self.population_size):
            # generating DNA of an individual
            self.population.append(DNA(len(self.target)))
            # generating random genes of an individual
            self.population[i].generate_random_genes()

        self.generation += 1
Ejemplo n.º 31
0
    def import_from_json(self, load):
        self.handler.load_file(load)
        self.json_object = self.handler.get_data()
        self.name = self.json_object["name"]
        self.uid = self.json_object["uid"]
        self.parents = self.json_object["parents"]
        self.personality = self.json_object["personality"]
        self.color = self.json_object["color"]
        self.happiness = self.json_object["happiness"]
        strand = self.json_object["dna"]
        self.dna = DNA(strand)
        self.handler.close()

        logger.logging.info("---Importing Pudgi---")
        logger.logging.info("UID: " + str(self.uid))
        logger.logging.info("Name: " + self.name)
        logger.logging.info("Color: " + self.color)
        logger.logging.info("Personality: " + self.personality)
        logger.logging.info("Parents: " + str(self.parents))
Ejemplo n.º 32
0
    def reproduction(self):
        new_population = []

        for i in range(self.population_size):
            individual = DNA.cross_over(self.parents, len(self.target))
            individual.mutate(self.mutation_rate)
            new_population.append(individual)

        self.population = new_population
        self.generation += 1
Ejemplo n.º 33
0
 def generatePopulation(self):
     for i in range(self.populationSize):
         #Creates a new dna object
         dna = deepcopy(DNA())
         gene = GenePolygon(_canvasSize=self.canvasSize)
         dna.createGenes(gene=gene, n=self.geneCount)
         #Creates a new member with the dna
         member = Member(_dna=dna)
         #Adds the member to the population
         self.population.addMember(member)
Ejemplo n.º 34
0
    def initialize_genes(self, dna):
        if dna is not None:
            self.dna = dna
        else:
            self.dna = DNA(4)

        self.probability_of_turn = self.dna.get_gene(0) * 0.1 / 100
        self.angle_of_rotation = self.dna.get_gene(1) / 255 * self.TWO_PI
        self.speed = self.dna.get_gene(2) / 255.0 * 10
        self.probability_turn_direction = self.dna.get_gene(3) / 255.0 * 10
Ejemplo n.º 35
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem9')
    solution_dir = os.path.join("Problems", "Problem9Solution")

    data_reader = DataReader(problem_dataset_dir)
    test_cases, output = data_reader.get_data()

    for train_i in range(0, len(output)):
        case = test_cases[train_i]
        case_output = output[train_i]
        genome = case[0]
        k = case[1][0]
        d = case[1][1]
        dna = DNA(genome)
        k_mers = dna.most_frequent_missmatched_k_mer(int(k), int(d))

        if set(case_output) != set(k_mers):
            raise Exception("Output not matched!\nExpecting: " +
                            str(case_output) + "\nFound: " + str(k_mers))
Ejemplo n.º 36
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem17')
    solution_dir = os.path.join("Problems", "Problem17Solution")

    data_reader = DataReader(problem_dataset_dir)
    test_cases, output = data_reader.get_data()

    for train_i in range(0, len(output)):
        dna = test_cases[train_i][0]
        k = test_cases[train_i][1][0]
        score_matrix = test_cases[train_i][1][1]
        case_output = output[train_i]
        most_probable_k_mer = DNA(dna).get_most_probable_k_mer(int(k), score_matrix)

        if most_probable_k_mer != case_output:
            raise Exception("Output not matched!\nExpecting: " + str(case_output) + "\nFound: " + str(most_probable_k_mer))

    print("Passed training data..")

    writer = DataWriter(solution_dir)
    usage = Usage()

    for test_i in range(len(test_cases) - len(output) - 1, len(test_cases)):
        usage.start()
        dna = test_cases[test_i][0]
        k = test_cases[test_i][1][0]
        score_matrix = test_cases[test_i][1][1]
        most_probable_k_mer = DNA(dna).get_most_probable_k_mer(int(k), score_matrix)
        usage.end()

        writer.write_data(test_i + 1, most_probable_k_mer, usage.get_execution_time(), usage.get_memory_usage())
        print("\n\nInput:\n" + str(dna) + "\n" + str(k) + "\n" + str(score_matrix))

        print("\n\nOutput")
        print("=====")

        print(most_probable_k_mer)

        print("\n")
        print("======")
        print("Execution Time: " + str(usage.get_execution_time()) + " s")
        print("Memory Used: " + str(usage.get_memory_usage()) + " MB")
Ejemplo n.º 37
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem6')
    solution_dir = os.path.join("Problems", "Problem6Solution")

    data_reader = DataReader(problem_dataset_dir)
    test_cases, output = data_reader.get_data()

    for train_i in range(0, len(output)):
        case = test_cases[train_i]
        case_output = output[train_i]
        genome = case[0]
        k = case[1][0]
        l = case[1][1][0]
        t = case[1][1][1]
        dna = DNA(genome)
        clumps_patterns = dna.get_clumps_patterns(int(k), int(t), int(l))

        if clumps_patterns.sort() != case_output.sort():
            raise Exception("Output not matched!\nExpecting: " +
                            str(case_output) + "\nFound: " + clumps_patterns)
Ejemplo n.º 38
0
    def setUp(self):
        self.dna = DNA()

        self.n1 = TestNode('node1')
        self.n2 = TestNode('node2')
        self.n3 = TestNode('node3')
        self.n4 = TestNode('node4')

        self.dna.head = self.n1
        self.crawler = self.dna.spawn_crawler()
        self.crawler.attach_to(self.n1)
Ejemplo n.º 39
0
 def __init__(self,
              x: float,
              y: float,
              dna: DNA = DNA(),
              brain_dna: DNA = BrainDNA(),
              direction: float = 0.0,
              name: str = 'object',
              health: int = None):
     super().__init__(x, y, dna, direction, name, health=health)
     # objective function
     self.brain = Brain(brain_dna)
 def run(self, target_string):
     self.target = DNA(target_string)
     self.generations = self._initialise(target_string)
     result = []
     while True:
         next_generation = self.generations[-1].next_generation(self.target)
         result.append(self.generations[-1].best_fit())
         if result[-1][0] == target_string or len(result) > 1000:
             break
         self.generations.append(next_generation)
     return result
Ejemplo n.º 41
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem7')
    solution_dir = os.path.join("Problems", "Problem7Solution")

    data_reader = DataReader(problem_dataset_dir)
    test_cases, output = data_reader.get_data()

    for train_i in range(0, len(output)):
        case = test_cases[train_i]
        case_output = np.array(output[train_i])
        dna = DNA(case.strip())
        min_skew_indices = dna.get_min_skew()

        if not np.array_equal(case_output, min_skew_indices):
            raise Exception("Output not matched!\nExpecting: " + str(case_output) + "\nFound: " + str(min_skew_indices))

    print("Passed training data..")

    writer = DataWriter(solution_dir)
    usage = Usage()

    for test_i in range(len(test_cases) - len(output), len(test_cases)):
        usage.start()
        case = test_cases[test_i]
        dna = DNA(case.strip())
        min_skew_indices = dna.get_min_skew()
        usage.end()

        writer.write_data(test_i + 1, min_skew_indices, usage.get_execution_time(), usage.get_memory_usage())
        print("\n\nInput:\n" + case + "\n")

        print("\n\nOutput")
        print("=====")

        print(list(min_skew_indices))

        print("\n")
        print("======")
        print("Execution Time: " + str(usage.get_execution_time()) + " s")
        print("Memory Used: " + str(usage.get_memory_usage()) + " MB")
Ejemplo n.º 42
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem13')
    solution_dir = os.path.join("Problems", "Problem13Solution")

    data_reader = DataReader(problem_dataset_dir)
    test_cases, output = data_reader.get_data()

    for train_i in range(0, len(output)):
        (k, genome) = test_cases[train_i]
        case_output = output[train_i]
        dna = DNA(genome)
        k_mers = dna.get_k_mers(int(k))

        if sorted(case_output) != sorted(k_mers):
            raise Exception("Output not matched!\nExpecting: " + str(case_output) + "\nFound: " + str(k_mers))

    print("Passed training data..")

    writer = DataWriter(solution_dir)
    usage = Usage()

    for test_i in range(len(test_cases) - len(output), len(test_cases)):
        usage.start()
        (k, genome) = test_cases[test_i]
        dna = DNA(genome)
        k_mers = dna.get_k_mers(int(k))
        usage.end()

        writer.write_data(test_i + 1, k_mers, usage.get_execution_time(), usage.get_memory_usage())
        print("\n\nInput:\n" + k + "\n" + genome + "\n")

        print("\n\nOutput")
        print("=====")

        print(k_mers)

        print("\n")
        print("======")
        print("Execution Time: " + str(usage.get_execution_time()) + " s")
        print("Memory Used: " + str(usage.get_memory_usage()) + " MB")
Ejemplo n.º 43
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem4')
    solution_dir = os.path.join("Problems", "Problem4Solution")

    data_reader = DataReader(problem_dataset_dir)
    test_cases, output = data_reader.get_data()

    for train_i in range(0, len(output)):
        case = test_cases[train_i]
        case_output = output[train_i]
        dna = DNA(case)
        reverse_complement = dna.reverse_complement()

        if reverse_complement != case_output:
            raise Exception("Output not matched!\nExpecting: " + str(case_output) + "\nFound: " + reverse_complement)

    print("Passed training data..")

    writer = DataWriter(solution_dir)
    usage = Usage()

    for test_i in range(len(test_cases) - len(output), len(test_cases)):
        usage.start()
        case = test_cases[test_i]
        dna = DNA(case)
        reverse_complement = dna.reverse_complement()
        usage.end()

        writer.write_data(test_i + 1, reverse_complement, usage.get_execution_time(), usage.get_memory_usage())
        print("\n\nInput:\n" + case)

        print("\n\nOutput")
        print("=====")

        print(reverse_complement)

        print("\n")
        print("======")
        print("Execution Time: " + str(usage.get_execution_time()) + " s")
        print("Memory Used: " + str(usage.get_memory_usage()) + " MB")
Ejemplo n.º 44
0
def main():
    problem_dataset_dir = os.path.join('Problems', 'Problem2')
    solution_dir = os.path.join("Problems", "Problem2Solution")

    data_reader = DataReader(problem_dataset_dir)
    training_data, testing_data = data_reader.get_data()
    codons_table = data_reader.get_rna_codon_table()

    for sample in training_data:
        dna_string = sample[0][0]
        amino_acid = sample[0][1]
        output = sample[1]
        dna = DNA(dna_string)
        dna.set_codon_table(codons_table)
        candidates = dna.get_dna_to_amino_acid_candidates(amino_acid)

        if set(candidates) != set(output):
            raise Exception("Output not matched!\nExpecting: " + str(output) + "\nFound: " + str(candidates))

    print("Passed training data..\n\n")

    writer = DataWriter(solution_dir)
    usage = Usage()

    for sample in testing_data:
        usage.start()
        dna_string = sample[0][0]
        amino_acid = sample[0][1]
        dna = DNA(dna_string)
        dna.set_codon_table(codons_table)
        candidates = dna.get_dna_to_amino_acid_candidates(amino_acid)
        usage.end()

        writer.write_data((dna_string, amino_acid), candidates, usage.get_execution_time(), usage.get_memory_usage())
        print("DNA:\n" + dna_string)
        print("Protein\n" + amino_acid)

        print("\n\nOutput")
        print("=====")

        print(str(len(candidates)))
        for substring in candidates:
            print(substring)

        print("\n\nExecution Time: " + str(usage.get_execution_time()) + " s")
        print("Memory Usage: " + str(usage.get_memory_usage()) + " MB")
Ejemplo n.º 45
0
class TestGetSequence(unittest.TestCase):
    def setUp(self):
        self.dna = DNA()

    def test_integration_normal(self):
        self.dna.in_sequence = "AATGACCT"
        expected = "TTACTGGA"
        self.dna.get_sequence()
        self.assertEqual(self.dna.out_sequence, expected)
                        
    def test_integration_mixed_case(self):
        self.dna.in_sequence = "aAtgAcCt"
        expected = "TTACTGGA"
        self.dna.get_sequence()
        self.assertEqual(self.dna.out_sequence, expected)

    def test_integation_bad_input(self):
        self.dna.in_sequence = "1234567"
        with self.assertRaises(Exception) as e:
            self.dna.get_sequence()
        self.assertEqual(e.exception.message, "Not a DNA base")
Ejemplo n.º 46
0
class tests(test_utils):

    def setUp(self):
        self.dna = DNA()

        self.n1 = TestNode('node1')
        self.n2 = TestNode('node2')
        self.n3 = TestNode('node3')
        self.n4 = TestNode('node4')

        self.dna.head = self.n1
        self.crawler = self.dna.spawn_crawler()
        self.crawler.attach_to(self.n1)

    # test inserting (before, after, child)

    def test_1_insert_before(self):
        self.crawler.add_before(self.n2)
        self.check_seq(self.n2, self.n1)

        self.assertIsNone(self.n2.dna_node_prev_sib)
        self.assertIsNone(self.n1.dna_node_next_sib)

    def test_2_insert_after(self):
        self.crawler.add_after(self.n2)
        self.check_seq(self.n1, self.n2)

        self.assertIsNone(self.n1.dna_node_prev_sib)
        self.assertIsNone(self.n2.dna_node_next_sib)

    def test_3_insert_child(self):
        self.crawler.add_child(self.n3)
        self.check_child(self.n1, self.n3)

    # test removing

    def test_4_remove_head(self):
        c = self.crawler
        c.add_after(self.n2, self.n1)
        c.add_after(self.n3, self.n2)
        c.remove(self.n1)

        self.assertRaises(AssertionError, self.check_seq, self.n1, self.n2)
        self.assertIsNone(self.n1.dna_node_next_sib)

    def test_5_remove_tail(self):
        c = self.crawler
        c.add_after(self.n2, self.n1)
        c.add_after(self.n3, self.n2)
        c.remove(self.n3)

        self.assertRaises(AssertionError, self.check_seq, self.n2, self.n3)
        self.assertIsNone(self.n3.dna_node_prev_sib)

    def test_6_remove_middle(self):
        c = self.crawler
        c.add_after(self.n2, self.n1)
        c.add_after(self.n3, self.n2)
        c.remove(self.n2)

        self.check_seq(self.n1, self.n3)
        self.assertIsNone(self.n2.dna_node_next_sib)
        self.assertIsNone(self.n2.dna_node_prev_sib)

    def test_7_remove_child(self):
        c = self.crawler
        c.add_child(self.n2, self.n1)
        c.add_after(self.n3, self.n2)
        c.remove(self.n2)

        self.check_child(self.n1, self.n3)
        self.assertIsNone(self.n2.dna_node_parent)
        self.assertIsNone(self.n2.dna_node_next_sib)
        self.assertIsNone(self.n2.dna_node_prev_sib)

    # test low-level traversing

    def test_8_traverse_sibs(self):
        c = self.crawler
        c.add_child(self.n2, self.n1)
        c.add_after(self.n3, self.n1)

        self.assertIs(self.n1, c.current_node)
        self.assertIs(self.n3, c.next_sib())
        self.assertIsNone(c.next_sib())

    def test_9_traverse_node_flat(self):
        c = self.crawler
        c.add_after(self.n2, self.n1)
        c.add_after(self.n3, self.n2)

        self.assertIs(self.n1, c.current_node)
        self.assertIs(self.n2, c.next_node())
        self.assertIs(self.n3, c.next_node())
        self.assertIsNone(c.next_node())

    def test_10_traverse_node_wchild(self):
        c = self.crawler
        c.add_child(self.n2, self.n1)
        c.add_after(self.n3, self.n1)

        c = self.crawler
        self.assertIs(self.n1, c.current_node)
        self.assertIs(self.n2, c.next_node())
        self.assertIs(self.n3, c.next_node())
        self.assertIsNone(c.next_node())

    # test crawling

    def test_11_crawl_sibs(self):
        c = self.crawler
        c.add_child(self.n2, self.n1)
        c.add_after(self.n3, self.n1)

        gen = c.crawl_sibs()
        self.assertIs(self.n1, gen.next())
        self.assertIs(self.n3, gen.next())
        self.assertRaises(StopIteration, gen.next)

    def test_12_crawl_flat(self):
        c = self.crawler
        c.add_after(self.n2, self.n1)
        c.add_after(self.n3, self.n2)

        gen = c.crawl()
        self.assertIs(self.n1, gen.next())
        self.assertIs(self.n2, gen.next())
        self.assertIs(self.n3, gen.next())
        self.assertRaises(StopIteration, gen.next)

    def test_13_crawl_wchild(self):
        c = self.crawler
        c.add_child(self.n2, self.n1)
        c.add_after(self.n3, self.n1)

        gen = c.crawl()
        self.assertIs(self.n1, gen.next())
        self.assertIs(self.n2, gen.next())
        self.assertIs(self.n3, gen.next())
        self.assertRaises(StopIteration, gen.next)

    def test_14_crawl_w_mul_children(self):
        """
        Tests that when traversing this stucture we correctly jump from n3 to
        n4.

            n1 -- n2 -- n3
            |
            n4
        """
        c = self.crawler
        c.add_child(self.n2, self.n1)
        c.add_child(self.n3, self.n2)
        c.add_after(self.n4, self.n1)

        gen = c.crawl()
        self.assertIs(self.n1, gen.next())
        self.assertIs(self.n2, gen.next())
        self.assertIs(self.n3, gen.next())
        self.assertIs(self.n4, gen.next())
        self.assertRaises(StopIteration, gen.next)
Ejemplo n.º 47
0
 def setUp(self):
     self.dna = DNA()
Ejemplo n.º 48
0
class Creature:
    TWO_PI = 6.283185

    #location (x, y) and window_size (width, height)
    def __init__(self, location, window_size, image, batch, dna = None):
        self.window_width, self.window_height = window_size
        self.initialize_image(image, batch)
        self.initialize_genes(dna)
        self.initialize_attributes(location)

    def initialize_image(self, image, batch):
        self.sprite = pyglet.sprite.Sprite(image, batch=batch)
        self.sprite.image.anchor_x = self.sprite.width / 2
        self.sprite.image.anchor_y = self.sprite.height / 2
        self.sprite_boundary_width = self.sprite.width / 2
        self.sprite_boundary_height = self.sprite.height / 2

    def initialize_genes(self, dna):
        if dna is not None:
            self.dna = dna
        else:
            self.dna = DNA(4)

        self.probability_of_turn = self.dna.get_gene(0) * 0.1 / 100
        self.angle_of_rotation = self.dna.get_gene(1) / 255 * self.TWO_PI
        self.speed = self.dna.get_gene(2) / 255.0 * 10
        self.probability_turn_direction = self.dna.get_gene(3) / 255.0 * 10

    def initialize_attributes(self, location):
        self.sprite.x, self.sprite.y = location
        self.x_delta = (random() - 0.5) * self.speed
        self.y_delta = (random() - 0.5) * self.speed
        self.metabolic_rate = self.speed
        self.rotation = self.angle_of_rotation
        self.life = 200
        self.cycles = 0
        self.sprite.rotation = -(atan2(self.y_delta, self.x_delta) / self.TWO_PI) * 360

    def update(self):
        if not self.is_alive():
            self.remove_sprite()
            return

        if self.is_turning():
            dir_r = 1
            if random() < 0.5:
                dir_r = -1
            self.rotation = (self.rotation + dir_r * self.angle_of_rotation) % self.TWO_PI
            self.x_delta = -sin(self.rotation)
            self.y_delta = cos(self.rotation)
            self.sprite.rotation = -(atan2(self.y_delta, self.x_delta) / self.TWO_PI) * 360

        self.sprite.x = self.sprite.x + self.x_delta
        self.sprite.y = self.sprite.y + self.y_delta

        if self.is_x_off_map(): 
            self.sprite.x = self.sprite.x - self.x_delta

        if self.is_y_off_map():
            self.sprite.y = self.sprite.y - self.y_delta

        self.life -= self.metabolic_rate
        self.cycles += 1

    def is_turning(self):
        if random() < self.probability_of_turn:
            return True
        return False

    def is_y_off_map(self):
        if self.sprite.y < self.sprite_boundary_height or \
           self.sprite.y > self.window_height - self.sprite_boundary_height:
            return True
        return False

    def is_x_off_map(self):
        if self.sprite.x < self.sprite_boundary_width or \
           self.sprite.x > self.window_height - self.sprite_boundary_width:
            return True
        return False

    def get_location(self):
        return (self.sprite.x, self.sprite.y)

    def add_life(self):
        self.life += 100

    def is_alive(self):
        if self.life <= 0:
            return False
        return True

    def remove_sprite(self):
        self.sprite.batch = None
 def test_counts_a_nucleotide_only_once(self):
     dna = DNA('CGATTGGG')
     dna.count('T')
     self.assertEqual(2, dna.count('T'))
Ejemplo n.º 50
0
 def initializeChildPopulation(self, numOfChildren):
     for i in range(numOfChildren):
         self.genotypePopulation.append(DNA.randomGenotype(self.bitsInGenotypes))
Ejemplo n.º 51
0
    def __init__(self, **kw):
        super(DNAVis, self).__init__(**kw)
        self.dna = DNA()
        self.crawler = self.dna.spawn_crawler()

        self.bind(size=self.redraw, pos=self.redraw)
 def test_dna_counts_do_not_change_after_counting_uracil(self):
     dna = DNA('GATTACA')
     dna.count('U')
     expected = {"A": 3, "T": 2, "C": 1, "G": 1}
     self.assertEqual(expected, dna.nucleotide_counts())
 def test_counts_all_nucleotides(self):
     s = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"
     dna = DNA(s)
     expected = {'A': 20, 'T': 21, 'G': 17, 'C': 12}
     self.assertEqual(expected, dna.nucleotide_counts())