示例#1
0
def main():

    nucleotides = ["A", "U", "G", "C"]
    pop_size = 100
    target = '..((((((.........))))))..((((.....))))'
    rate = None
    length = len(target)
    ldscape = Landscape.Landscape(target)
    time = 50

    print("Starting RNA evolution with target {} of length {}".format(
        target, len(target)))
    db, init_pop = init(pop_size, length, ['A'], ldscape)
    params = {
        'c': rate,
        "pop_size": pop_size,
        'init_pop': init_pop,
        'landscape': ldscape,
        'nucleotides': nucleotides,
        'time': time,
        'db': db,
        "pos": get_bp_position(target)
    }
    print(init_pop)
    data_min = []
    data_mean = []

    for c in np.arange(1, 2, 0.5):
        params['c'] = c
        print("Start evolution with c = {}......".format(params['c']))
        pool = mp.Pool(mp.cpu_count())
        results = pool.map(evolution, [params] * 3)
        print(results)
    """
示例#2
0
def main():

    nucleotides = ["A", "U", "G", "C"]
    pop_size = 1000
    target = '((((((...((((........)))).(((((.......))))).....(((((.......))))).))))))....'
    #target = ".((((....((((((((....)))).((((........)))).....((((((....)))))).))))))))...."
    rate = 0.001
    length = len(target)
    ldscape = Landscape.Landscape(target)
    time = 300

    print("Starting RNA evolution with target of length {}".format(
        len(target)))
    db, init_pop = init(pop_size, length, nucleotides, ldscape)
    params = {
        'rate': rate,
        'init_pop': init_pop,
        'landscape': ldscape,
        'nucleotides': nucleotides,
        'time': time,
        'db': db
    }
    print(init_pop)
    print("Begin mutation......")
    best_pop, mf = evolution(params)
    print(mf)
    plt.plot(mf)
    plt.xlabel(r'Time($t$)')
    plt.ylabel('Mean Fitness')
    plt.savefig('../images/mean_fitness.pdf')
    print("the mean fitness plot is saved in images/mean_fitness.pdf")
    plt.show()
示例#3
0
def main():

    population_size = 100
    number_of_generation = 200
    mut_rate = 0.4
    mut_bp = 0.5
    lamda = -1
    k = 15
    type_ = "ham"
    method = "MDE"

    data = pandas.read_csv("defect-data.csv", sep=";")
    print len(data.values), len(list(set(data.values[:, 0]))), data.values[:,
                                                                           0]
    for line in (data.values):
        print "================================================================================"
        print line[0], line[1]
        print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"

        target_structure = line[1]
        init_deph = len(target_structure)
        print "Length ==", init_deph
        mut_prob = 1. / (init_deph)
        #mut_prob = 0.001
        if init_deph > 300:
            number_of_generation = 150
        mut_probs = np.array(rna.ptable(target_structure)[1:])
        mut_probs = mut_probs + mut_prob
        mut_probs[mut_probs > mut_prob] = 0

        landscape = Landscape.Landscape(lamda, k, type_, target_structure)
        rna_evolution = RNAEvolution.RNAEvolution(population_size, 0, None,
                                                  landscape, method)

        result = rna_evolution.run(number_of_generation, mut_probs, mut_bp, 4,
                                   str(line[0]) + "/")

        list_fitness = []
        good_result = []
        for ind in result:
            #print ind.RNA_structure, ind.fitness
            if ind.fitness != 0:
                list_fitness.append(ind.fitness)
                good_result.append(ind)
        list_fitness = sorted(list_fitness, reverse=True)
        #print list_fitness
        sorted_pop = []
        for fitness in list_fitness:
            for ind in good_result:
                if ind.fitness == fitness:
                    sorted_pop.append(ind)
        for i in range(10):
            print sorted_pop[i].RNA_seq, sorted_pop[i].mfe, sorted_pop[
                i].fitness

        print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
示例#4
0
def main():

    args = parse_arguments()

    nucleotides = ["A", "U", "G", "C"]
    pop_size = int(args.pop_size)
    #target= '((((((...((((........)))).(((((.......))))).....(((((.......))))).))))))....'
    target = str(args.target)
    rate = float(args.mutation_rate)
    length = len(target)
    ldscape = Landscape.Landscape(target)
    time = int(args.time)
    root_dir = "../data/ken_rafft/"
    if not path.exists(root_dir):
        mkdir(root_dir)
        mkdir(root_dir + str(args.log_folder))
    elif not path.exists(root_dir + str(args.log_folder)):
        mkdir(root_dir + str(args.log_folder))

    print("Starting RNA evolution with target of length {}".format(
        len(target)))
    files = listdir(root_dir + str(args.log_folder + "/"))
    print(len(files), files)
    nb_sel = len(list(filter(lambda elt: 'genselected' in elt, files)))

    db, init_pop = init(pop_size, length, nucleotides, ldscape)
    params = {
        'rate': rate,
        'init_pop': init_pop,
        'landscape': ldscape,
        'nucleotides': nucleotides,
        'time': time,
        'db': db,
        'lf': args.log_folder,
        'pop_size': pop_size,
        'init_gen': 0,
        'ft': args.folding_tool
    }
    params['init_pop'] = init_pop

    if nb_sel > 0:
        init_pop2 = read_csv("../data/ken_rafft/" +
                             str(args.log_folder + "/genselected" +
                                 str(nb_sel - 1) + ".csv"))
        params['init_gen'] = nb_sel - 1
        params['init_pop'] = init_pop2
        print(init_pop2)

    print(init_pop)
    print("Begin Evolution......")
    best_pop, mf = evolution(params)
示例#5
0
def main () : 

    population_size = 100

    N = 10
    k = 6
    p = 0.99

    lamda = [0,1,1]

    number_of_neighbors = 25

    number_of_generation = 100
    mut_prob = 1./N
 
    seed = 1000   
    

    landscape = Landscape.Landscape(N,k,seed,p) 
    evolution = Evolution.Evolution(landscape,population_size, 1, number_of_neighbors,Archive.Archive(10,""), N) 
    mth = ["None","N","R"]
    for i in range(3): 
        print " ====================================================================="
        archive =  Archive.Archive(10,mth[i]) 
        evolution.archiving = archive
        #evolution.lamda = lamda[i]
        
        history  = evolution.run(number_of_generation,mut_prob)
        maxs = [ ]
        for gen in history : 
            values = [genotype.fitness for genotype in gen]
            maxs.append(numpy.max(values))
        plt.plot(maxs, label=r"$method = $" +str(mth[i]))
        
    
    plt.xlabel("Generation")
    plt.ylabel("Max Fitness")

    plt.title("Novelty Vs Fitness")
    plt.legend(loc="lower right", shadow=True, fontsize='12')
    plt.show()
def main():

    population_size = 1000
    number_of_generation = 500
    mut_rate = 0.4
    mut_bp = 0.5
    lamda = 0.3
    k = 15
    type_ = "ham"
    #target_structure = ".....((...((....))...((....))...((....))...((....))...((....))...((....))...))...................."
    init_depth = len(target_structure)
    print "Length ==", init_depth
    mut_prob = 1. / (init_depth)
    #mut_prob = 0.001

    mut_probs = numpy.array(RNA.ptable(target_structure)[1:])
    mut_probs = mut_probs + mut_prob
    mut_probs[mut_probs > mut_prob] = 0

    landscape = Landscape.Landscape(lamda, k, type_, target_structure)

    data = [[
        "NA",
        ".....((...((....))...((....))...((....))...((....))...((....))...((....))...))....................",
        0, 1
    ]]

    initializer = Initializer(landscape, population_size)

    init_pop = initializer.initialize()

    for ind in init_pop:
        data.append([ind.RNA_seq, ind.RNA_structure, ind.mfe, ind.fitness])

    dataFrame = pandas.DataFrame(data)

    print(dataFrame)

    dataFrame.to_csv("../Logs/init_data/data1000_" + str(type_) + "_ " +
                     str(init_depth) + ".csv")
示例#7
0
 def __init__(self, height = 50, width = 50, initial_population =200, \
              Moore = False, torus = True, regrow = 1, seed = 42):
     
     '''
     Args:
         height - y axis of grid_size
         width - x axis of grid size
         initial_population - number of agents starting
         moore - type of neighborhood
         torus - whether or no world wraps
         regrow - amout each resource grows bas each step
         process - Number of additonal proces by agents
         0 = Movement/Survive; 1 = +trade, 2 = +
         
     Initial Parameters: 
         Multigrid
         ActivationbyBreed (see schedule)
         Num_Agents counter to account for each agent number
         timekeeper - dictionary to keep track of time for each section
         start_time - create initial time
         datacollector to collect agent data of model
     '''
     
     self.step_num = 0
     self.height = height
     self.width = width
     self.initial_population = initial_population
     self.num_agents = 0
     #Mesa Agent Scheduler
     #self.schedule = schedule.RandomActivationByBreed(self)
     self.ml = mlm.MultiLevel_Mesa(self, group_to_net = True)
     self.grid = MultiGrid(self.height, self.width, torus=True)
     self.regrow = regrow
     self.running = True
     self.price_record = defaultdict(list)
     self.meta_type = {}
     warnings.filterwarnings("ignore")
                   
     
     '''
     Recorders
       Start datacollector
       Start time recorder
     '''
     self.start_time = time.time()
     
     self.datacollector = DataCollector(\
                          model_reporters = {"MetaAgent": recorder.survivors}, \
                          tables ={"Health":["Agent", "Step", "Sugar_Level", \
                                             "Spice_Level"], \
                          "Time":["Time Per Step"]})
     
     
     '''
     
     Creates the landscape:
         Fours mounds 2 sugar, 2 spice located- 1 in each quadrant
         imports landscape module to account for various landscape sizes
     '''
     self.resource_dict = {}
     
     landscape = Landscape.create_landscape(height, width)
     #places resources from landscape on grid
     for k,v in landscape.items(): 
         resource =  R.resource(k, self, v, self.regrow)
         self.grid.place_agent(resource, (resource.pos[0], resource.pos[1]))
         #POINT
         self.ml.add(resource)
         
     
            
     #fills in empty grids with null value resource agent        
     #Deviation from GrAS -- in empty cells has random resource from 0 to 4
     for a,x,y in self.grid.coord_iter():
         if a == set():
             resource = R.resource((x,y), self, \
                                   (self.random.randrange(0,2), \
                                    self.random.randrange(0,2)),self.regrow)
             self.grid.place_agent(resource, (resource.pos[0], resource.pos[1]))
             #POINT
             self.ml.add(resource)
                     
        
     '''
     Creates the agents:
         
     '''
     pos_array = list(self.ml.agents_by_type[R.resource].keys())
     self.random.shuffle(pos_array)
     vision_array = np.random.randint(1,6,self.initial_population)
     spice_array = np.random.randint(1,6,self.initial_population)
     sugar_array = np.random.randint(1,6,self.initial_population)
     for n in range(self.initial_population):
         #x = 0
         #y = 0
         #print ("position: ", (n, x,y))
         #GrAS p. 108
         sugar = self.random.randrange(25,50)
         spice = self.random.randrange(25,50)
         #GrAS p.108
         sug_bolism = sugar_array[n]
         spice_bolism = spice_array[n]
         #GrAS p. 108
         vision = vision_array[n]
         neighbors = Moore
         a = N.NetAgent(n, pos_array[n], self, \
                              {"sug_bolism": sug_bolism, \
                              "spice_bolism": spice_bolism}, \
                              {1 : sugar, 2: spice}, {"vision": vision}, \
                              neighbors)
         #POINT
         self.ml.add(a)
         self.grid.place_agent(a,pos_array[n])
示例#8
0
                        if i == x and j == y:
                            pass  # update (x, y) at last
                        else:
                            self.landscape.env[i][j].update_belief(
                                1 / (1 - cell.belief[-1] * (1 - cell.fn)))
                cell.update_belief(
                    cell.fn /
                    (cell.belief[-1] * cell.fn + 1 - cell.belief[-1]))
                self.landscape.target_move()


if __name__ == '__main__':
    total_rule1_count = total_rule2_count = 0
    total_rule1_count_base = total_rule2_count_base = 0
    for i in range(100):
        landscape = Landscape()
        bs = BayesianSearch(landscape)

        # (x, y), rule1_count = bs.search(1)
        (
            x, y
        ), rule1_action_count, rule1_motion_count, rule1_search_count = bs.search_moving_target_onestep(
            1)
        print("rule1:", rule1_action_count)
        total_rule1_count += rule1_action_count

        for i in range(landscape.dim):
            for j in range(landscape.dim):
                landscape.env[i][j].reset_belief()

        # (x, y), rule2_count = bs.search(2)
    def run(self):

        # start music player
        pygame.mixer.music.load(self.music_file1)
        pygame.mixer.music.play(loops=-1)

        while not self.stop:

            # run the parts
            self.prepareScreen()
            self.showPicture(self.pic_file1, self.target_size, 1)
            self.wait(2500)
            if self.stop:
                break
            self.showPicture(self.pic_file1, self.target_size, 2)

            self.prepareScreen(False)
            self.stop = TitleText.TitleText(self.screen, self.target_fps).run()
            if self.stop:
                break

            # change tune
            pygame.mixer.music.fadeout(1500)
            self.prepareScreen(True)
            self.wait(1000)
            if self.stop:
                break
            pygame.mixer.music.load(self.music_file2)
            pygame.mixer.music.play(loops=-1)
            self.stop = TheStars.TheStars(self.screen, self.target_fps).run()
            if self.stop:
                break

            self.prepareScreen(False)
            self.stop = SideEffectCube.SideEffectCube(screen, self.target_fps,
                                                      25).run()
            if self.stop:
                break

            self.prepareScreen(True)
            self.stop = ShadowBobs.ShadowBobs(
                self.screen,
                30).run()  # not target pfs = 30, optimised for max this
            if self.stop:
                break

            # re-start the tune, as looping does not work very well
            pygame.mixer.music.fadeout(1500)
            self.prepareScreen(True)
            self.wait(1000)
            if self.stop:
                break
            pygame.mixer.music.play(loops=-1)

            self.prepareScreen(True)
            self.stop = TheGlobe.TheGlobe(self.screen, self.target_fps,
                                          25).run()
            if self.stop:
                break

            self.prepareScreen(True)
            self.stop = TheWorld.TheWorld(self.screen, self.target_fps).run()
            if self.stop:
                break

            self.prepareScreen(True)
            # change tune
            pygame.mixer.music.fadeout(1500)
            self.showPicture(self.pic_file2, self.target_size, 0)
            self.wait(1000)
            if self.stop:
                break
            pygame.mixer.music.load(self.music_file3)
            pygame.mixer.music.play(loops=-1)
            self.wait(2500)
            if self.stop:
                break

            self.prepareScreen(True)
            self.stop = Raytracing.Raytracing(self.screen,
                                              self.target_fps).run()
            if self.stop:
                break

            self.prepareScreen(True)
            self.stop = MilkyWay.MilkyWay(self.screen, self.target_fps,
                                          25).run()
            if self.stop:
                break

            self.prepareScreen(True)
            self.stop = BoxInABox.BoxInABox(self.screen, self.target_fps,
                                            25).run()
            if self.stop:
                break

            self.prepareScreen(True)
            self.stop = Landscape.Landscape(self.screen).run()
            if self.stop:
                break

            self.prepareScreen(True)
            self.stop = EndCredits.EndCredits(self.screen,
                                              self.target_fps).run()
            if self.stop:
                break

            self.prepareScreen(True)
            self.showPicture(self.pic_file3, (self.width, self.height), 0)
            self.wait(16000)

            self.stop = True  # do not loop from the start

        # exit; fade out, close display, stop music
        pygame.mixer.music.fadeout(2500)
        self.wait(2000)
        self.prepareScreen(True)

        pygame.quit()
        exit()