Example #1
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")
Example #2
0
 def mate(self, dad, mom):
     size = dad.dnaLength
     offspring = DNA()
     for i in range(0, size):
         if random() > 0.5: # 50% chance to get dad's gene
             offspring.dna[i] = dad.dna[i]
         else: # 50% chance to get mom's gene
             offspring.dna[i] = mom.dna[i]
         if random() < self.mutation_chance:
             offspring.mutate_gene(i)
     return offspring
Example #3
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
Example #5
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
    def generate(self):
        for n in range(len(self.population)):
            try:
                member1, member2 = random.sample(self.mating_pool, 2)
            except:
                member1, member2 = [DNA(len(self.target)) for _ in range(2)]

            child = member1.crossover(member2)
            child.mutate(self.mutation_rate)
            self.population[n] = child

        self.generations += 1
Example #7
0
 def create_creature(self,
                     position=None,
                     creature_information=CreatureInformation(0, None)):
     """create a creature with default parameters"""
     if (position is None):
         position = (int(random.uniform(0,
                                        400)), int(random.uniform(0, 400)))
     information = creature_information
     dna = DNA(100, 100, 1, 5)
     #print(f"x:{position[0]} y:{position[1]}")
     creature = Creature(position, dna, information, self.world)
     self.register(creature, position)
     return creature
Example #8
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,)
Example #9
0
    def __init__(self, target):
        self.population = []
        self.selected_inds = []
        self.target = target
        self.length = len(target)
        self.pop_size = 200

        for i in range(self.pop_size):
            dna = DNA(self.target)
            for j in range(self.length):
                num = random.randint(32, 127)
                char = chr(num)
                dna.genes.append(char)
            self.population.append(dna)
Example #10
0
def get_a_dna_with_some_structure():
    cards = [
        ScoreCard(0, 10),
        ScoreCard(1, 20),
        ScoreCard(2, 30),
        ScoreCard(3, 40),
        ScoreCard(4, 50),
        ScoreCard(5, 60),
        ScoreCard(6, 70),
        ScoreCard(7, 80),
        ScoreCard(8, 90),
        ScoreCard(9, 100)
    ]
    return DNA(structure=cards)
    def __init__(self, target, mutation_rate, max_pop):
        self.target = target
        self.mutation_rate = mutation_rate

        self.population = [DNA(len(target)) for _ in range(max_pop)]
        self.mating_pool = []
        self.finished = False
        self.perfect_score = len(target)

        self.generations = 0
        self.best = ""
        self.max_fitness = 0

        self.calc_fitness()
Example #12
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)
Example #13
0
def read_file(data_list, filename):
    """ Reads a file with DNA promoter data
            and fills a list with that data.
            Args:
                data_list (list) : the empty list you want to put data into
                filename (str) : path to the file you want to open
    """
    with open(filename, newline='') as f:
        reader = csv.reader(f, delimiter=' ')
        for line in reader:
            # splits the line into the part with the promoter and the sequence for easy
            # processing
            # gene = [field.strip() for field in line.split(' ')]
            dna = DNA(line[0], line[1])
            # slow way of growing a list but it works for this purpose
            data_list.append(dna)
    def __init__(self, p, m, num):

        self.population = []
        self.matingPool = []
        self.generations = 0
        self.finished = False
        self.target = p
        self.mutationRate = m
        self.perfectScore = 1

        self.best = ""

        for x in range(num):
            self.population.append(DNA(len(self.target)))

        self.calcFitness()
Example #15
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)
Example #16
0
    def __init__(self, dna=None):
        self.position = pygame.math.Vector2(width / 2, height / 2)
        self.velocity = pygame.math.Vector2()
        self.acceleration = pygame.math.Vector2()

        if dna == None:
            self.dna = DNA()
        else:
            self.dna = dna

        self.n = 3
        self.r = 10
        self.fitness = 0
        self.count = 0

        self.calculate_angle()
        self.re_calculate_points()
Example #17
0
 def __init__(self, target, dna, id):
     self.pos = PVector(width / 2, height)
     self.vel = PVector()
     self.acc = PVector()
     self.reached = False
     self.isCollided = False
     self.rotMod = 0
     self.fitMod = 0
     if dna:
         self.dna = dna
     else:
         self.dna = DNA(None)
     self.count = 0
     self.target = target
     self.fitness = 0
     self.id = id
     self.col = color(0)
Example #18
0
 def __init__(self, canvas, dna=None):
     self.pos = np.array([50, 200]).astype(np.float)
     self.vel = np.array([0, 0]).astype(np.float)
     self.acc = np.array([0, 0]).astype(np.float)
     self.completed = False
     self.crashed = False
     if (dna is None):
         self.dna = DNA()
     else:
         self.dna = dna
     self.fitness = 0
     self.size = 5
     self.canv = canvas
     self.idLine = self.canv.create_line(self.pointsLine, fill="white")
     self.id = self.canv.create_oval(self.points,
                                     fill="white",
                                     outline="white")
Example #19
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))
Example #20
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)
Example #21
0
def main(_):
    flags_obj = tf.flags.FLAGS
    euler_graph = tf_euler.dataset.get_dataset(flags_obj.dataset)
    euler_graph.load_graph()

    dims = [flags_obj.hidden_dim] * (flags_obj.layers + 1)
    if flags_obj.run_mode == 'train':
        metapath = [euler_graph.train_edge_type] * flags_obj.layers
    else:
        metapath = [euler_graph.all_edge_type] * flags_obj.layers
    num_steps = int((euler_graph.total_size + 1) // flags_obj.batch_size *
                    flags_obj.num_epochs)

    model = DNA(dims,
                metapath,
                euler_graph.feature_idx,
                euler_graph.feature_dim,
                euler_graph.label_idx,
                euler_graph.label_dim,
                group_num=flags_obj.group_num,
                head_num=flags_obj.head_num)

    params = {
        'train_node_type': euler_graph.train_node_type[0],
        'batch_size': flags_obj.batch_size,
        'optimizer': flags_obj.optimizer,
        'learning_rate': flags_obj.learning_rate,
        'log_steps': flags_obj.log_steps,
        'model_dir': flags_obj.model_dir,
        'id_file': euler_graph.id_file,
        'infer_dir': flags_obj.model_dir,
        'total_step': num_steps
    }
    config = tf.estimator.RunConfig(log_step_count_steps=None)
    model_estimator = NodeEstimator(model, params, config)

    if flags_obj.run_mode == 'train':
        model_estimator.train()
    elif flags_obj.run_mode == 'evaluate':
        model_estimator.evaluate()
    elif flags_obj.run_mode == 'infer':
        model_estimator.infer()
    else:
        raise ValueError('Run mode not exist!')
Example #22
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))
Example #23
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))
Example #24
0
    def evaluate(self):
        max_fitness_gene = heapq.nlargest(1, self.gene_pool)[0]
        max_fitness = float(max_fitness_gene.fitness())

        mating_pool = []
        for gene in self.gene_pool:
            num_occurrences = int(gene.fitness() / max_fitness * 100)
            for _ in repeat(None, num_occurrences):
                mating_pool.append(gene)

        for _ in repeat(None, self.POPULATION_SIZE):
            parent_0 = mating_pool[random.randint(0, len(mating_pool)-1)]
            parent_1 = mating_pool[random.randint(0, len(mating_pool)-1)]

            new_gene = DNA(parent_0.crossover(parent_1))
            heapq.heappush(self.gene_pool, new_gene)

        self.gene_pool = heapq.nlargest(self.POPULATION_SIZE, self.gene_pool)

        return self.gene_pool[0]
Example #25
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)
Example #26
0
    def __init__(self,
                 x: float,
                 y: float,
                 dna=DNA(),
                 direction: float = 0.0,
                 name: str = 'object',
                 health: int = None):
        color = pygame.Color(int(dna.genes[0] * 255), int(dna.genes[1] * 255),
                             int(dna.genes[2] * 255))
        speed = auxiliary.map(dna.genes[3], 0, 1, self.min_speed,
                              self.max_speed)
        size = auxiliary.map(dna.genes[4], 0, 1, self.min_size, self.max_size)
        multiply_chance = (auxiliary.map(dna.genes[5], 0, 1,
                                         self.min_s_multiply,
                                         self.max_s_multiply),
                           auxiliary.map(dna.genes[5], 0, 1,
                                         self.max_a_multiply,
                                         self.min_a_multiply))
        vision_radius = auxiliary.map(dna.genes[6], 0, 1, size,
                                      self.max_vision_radius)
        super().__init__(x,
                         y,
                         size,
                         speed,
                         color,
                         direction,
                         vision_radius,
                         name=name,
                         multiply_chance=multiply_chance,
                         health=health)
        self.dna = dna

        # counter for food consumed

        self.log("creature created")
        self.log(f"health dna creature: {self.health}")
@author: WRShipway
"""
import pandas as pd
from dna import DNA

if __name__ == "__main__":
    database_list = ["small" if i < 4 else "large" for i in range(20)]

    assert_list = [
        "Bob", "No match", "No match", "Alice", "Lavender", "Luna", "Ron",
        "Ginny", "Draco", "Albus", "HermioneTest", "Lily", "No match",
        "Severus", "Sirius", "No match", "Harry", "No match", "Fred",
        "No match"
    ]

    for i in range(len(database_list)):
        database = 'databases/{}.csv'.format(database_list[i])
        sequence = 'sequences/{}.txt'.format(i + 1)
        df_STR = pd.read_csv(database)
        df_sequence = pd.read_csv(sequence)
        result = DNA(database, sequence)

        assert result == assert_list[i],  \
        "--error in test {}--\nYour program should output '{}'" \
        .format((i+1), assert_list[i])

        if DNA(database, sequence) != assert_list[i]:
            pass
            #print("--error in test {}--". format(i+1))
Example #28
0
    is_staff,
    login,
    get_user,
)
from common.rpc.auth import is_admin
from common.rpc.slack import post_message

CERTBOT_ARGS = [
    "--dns-google",
    "--dns-google-propagation-seconds",
    "180",
]

app = Flask(__name__)
dna = DNA(
    "hosted",
    cb_args=CERTBOT_ARGS,
)

if not os.path.exists("data"):
    os.makedirs("data")

if not os.path.exists("data/saves"):
    os.makedirs("data/saves")

sh("chmod", "666", f"{os.getcwd()}/dna.sock")


@list_apps.bind(app)
@only("buildserver")
def list_apps():
    return {
Example #29
0

def fitness(agent):
    correct = 0
    for i in range(LENGTH_TARGET):
        if TARGET[i] == agent.dna[i]:
            correct += 1
    return correct / LENGTH_TARGET


last_population = []
current_population = [[], []]  # current_population[0] = agent
# current_population[1] = fitness

for _ in range(POPULATION_SIZE):
    agent = DNA(size=LENGTH_TARGET,
                random_generator=random_generator.RandomLetterGenerator())
    fitness_score = fitness(agent)
    current_population[AGENTS].append(agent)
    current_population[FITNESS_SCORES].append(fitness_score)

best_dna = ''
while best_dna != TARGET:
    last_population = current_population
    current_population = [[], []]
    for i in range(POPULATION_SIZE):
        random_agent, another_random_agent = random.choices(
            population=last_population[AGENTS],
            weights=last_population[FITNESS_SCORES],
            k=2)
        child_agent = random_agent.crossover(another_random_agent).mutated(
            mutation_rate=0.01)
Example #30
0
        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")