def iterate(field, local_field, local_field0, timesteps, image_interval): for m in range(1, timesteps+1): exchange(local_field0) evolve(local_field, local_field0, a, dt, dx2, dy2) if m % image_interval == 0: comm.Gather(local_field[1:-1,:], field, root=0) if rank == 0: write_field(field, m)
def iterate(field, local_field, local_field0, timesteps, image_interval): for m in range(1, timesteps + 1): exchange(local_field0) evolve(local_field, local_field0, a, dt, dx2, dy2) if m % image_interval == 0: # TODO: gather partial fields to reconstruct the full field comm.Gather(local_field[1:-1], field, root=0) if rank == 0: write_field(field, m)
def evolve_words_reverse(words, available_rules, generations, metric, optimisation_function): '''Evolves the given list of words in reverse, according to the given list of rules, for a number of generations. If no more applicable rules are available, the evolution will stop early. Returns the evolved list of words and a list of rule which were applied. ''' # Transform each rule to its reversed equivalent reverse_rules = list(map(reverse_rule, available_rules)) # Invert the optimisation algorithm if optimisation_function == min: optimisation_function = max else: optimisation_function = min applied_rules = [] try: for _ in range(generations): rule, words = evolve.evolve(words, reverse_rules, metric, optimisation_function) applied_rules.append(rule) reverse_rules.remove(rule) # StopIteration is raised when there are no more applicable rules except StopIteration: return words, list(reversed(applied_rules)) # When returning, the applied rules list is reversed due to the reverse # chronological order. return words, list(reversed(applied_rules))
def evolve_words(words, rules, generations, metric, optimisation_function): '''Evolves the given list of words according to the given list of rules, for a number of generations. If no more applicable rules are available, the evolution will stop early. Returns the evolved list of words and a list of rule which were applied. ''' applied_rules = [] # Create a mutable copy of the global rules list, from which rules # are deleted to ensure they run only once. available_rules = copy.deepcopy(rules) try: for _ in range(generations): rule, words = evolve.evolve(words, available_rules, metric, optimisation_function) applied_rules.append(rule) available_rules.remove(rule) # StopIteration is raised when there are no more applicable rules except StopIteration: return words, applied_rules return words, applied_rules
def test_evolve_returns_different_evolved_sequences(self): new_sequences0 = evolve.evolve(self.old_sequence, taxa=10, t=0.1, omega=1.1, kappa=1.5, lmbda=0.01, ti_td=0.1) new_sequences1 = evolve.evolve(self.old_sequence, taxa=10, t=0.1, omega=1.1, kappa=1.5, lmbda=0.01, ti_td=0.1) for i, j in zip(new_sequences0, new_sequences1): self.assertNotEqual(i, j)
def benchmark_evolve_big_set(): with open('../../data/split/Seq2_Sus', 'r') as f: old_sequence = f.read()[10:].replace('\n', '').lower() taxa = 100 start_time = time.time() new_sequences, mutations = evolve.evolve(old_sequence, taxa=taxa, log=True, omega=0.1) print("taxa:{}, sec:{}".format(taxa, time.time() - start_time)) return old_sequence, new_sequences, mutations
def main(prng=None, display=False): if prng is None: prng = Random() prng.seed(time()) models = os.listdir('models') nltr = '\n ' print( f"Available models:{nltr}{nltr.join([f'{i}) {x}' for i, x in enumerate(models)])}" ) with open('summaries/summary.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow([ 'model', 'algorithm', 'best_human', 'best_evolved', 'decrease', 'genome' ]) for model in models: problem = Slicing(stl_file=f'models/{model}') best_human = 9999 best_cc = [] for c in hardcoded: temp = problem.slice_and_get_fit(c) if temp < best_human: best_human = temp best_cc = c problem.slice_and_get_fit(best_cc, f'best_{model}_human') with open('summaries/summary.csv', 'a', newline='') as file: writer = csv.writer(file) writer.writerow( [model, 'human', best_human, best_human, 0, best_cc]) algorithms = ['ga', 'eda', 'es'] for algorithm in algorithms: for i in range(5): final_pop = evolve(algorithm, problem, hardcoded, prng, model=model, appendix=f"_{i}") print(f'{algorithm} run {i} completed') stats = inspyred.ec.analysis.fitness_statistics(final_pop) final_pop.sort(reverse=True) best = final_pop[0] problem.slice_and_get_fit(best.candidate, f'best_{model}_{algorithm}_{i}') with open('summaries/summary.csv', 'a', newline='') as file: writer = csv.writer(file) writer.writerow([ model, algorithm, best_human, best.fitness, 1 - best.fitness / best_human, best.candidate ]) generation_plot(open( f"summaries/stats_{model}_{algorithm}_{i}.csv", "r"), algorithm=f"{model}_{algorithm}_{i}")
def test_evolve_with_log(self): new_sequences, mutations = evolve.evolve(self.old_sequence, taxa=10, t=0.1, omega=1.1, kappa=1.5, lmbda=0.01, ti_td=0.1, log=True) self.assertIsInstance(mutations, list)
def test_evolve_no_insertion(self): new_sequences = evolve.evolve(self.old_sequence, taxa=10, t=0.1, omega=1.1, kappa=1.5, lmbda=0.01, ti_td=0.0) self.assertEqual(len(new_sequences), 10) for i in new_sequences: self.assertEqual(len(self.old_sequence), len(i))
def test_evolve_with_high_insertion(self): new_sequences = evolve.evolve(self.old_sequence, taxa=10, t=0.1, omega=1.1, kappa=1.5, lmbda=0.1, ti_td=10.0) self.assertEqual(len(new_sequences), 10) len_new_sequences = sum([len(i) for i in new_sequences]) self.assertTrue(len_new_sequences != 10 * len(self.old_sequence))
def main(prng=None, display=False): if prng is None: prng = Random() prng.seed(time()) models = os.listdir('models') print('optimizing material usage') with open('summaries/summary_material.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow([ 'model', 'algorithm', 'best_human', 'best_evolved', 'decrease', 'genome' ]) for model in models: problem = Slicing(stl_file=f'models/{model}', kw_cost=0, block_duplicates=True) best_human = 9999 best_cc = [] for c in hardcoded: temp = problem.slice_and_get_fit(c) if temp < best_human: best_human = temp best_cc = c problem.slice_and_get_fit(best_cc, f'best_human_{model}_material') with open('summaries/summary_material.csv', 'a', newline='') as file: writer = csv.writer(file) writer.writerow( [model, 'human', best_human, best_human, 0, best_cc]) algorithms = ['ga', 'eda', 'es'] for algorithm in algorithms: final_pop = evolve(algorithm, problem, hardcoded, prng, model=model, appendix="_material") print(f'{algorithm} completed') stats = inspyred.ec.analysis.fitness_statistics(final_pop) final_pop.sort(reverse=True) best = final_pop[0] problem.slice_and_get_fit(best.candidate, f'best_{model}_{algorithm}_material') with open('summaries/summary_material.csv', 'a', newline='') as file: writer = csv.writer(file) writer.writerow([ model, algorithm, best_human, best.fitness, 1 - best.fitness / best_human, best.candidate ]) generation_plot(open( f"summaries/stats_{model}_{algorithm}_material.csv", "r"), algorithm=f"{model}_{algorithm}_material")
def evolve_pokemon(cursor, args): pokemon_name = args[0] try: evolved_pokemon = evolve(pokemon_name) except Exception as e: return { 'error': 400, 'details': 'This pokemon can not be evolved ' + str(e) } evolved_details = get_pokemon_details(evolved_pokemon) update_pokemon_details(cursor, pokemon_name, evolved_details) update_types(cursor, (evolved_pokemon, ))
def test_evolve(self): new_sequences = evolve.evolve(self.old_sequence, taxa=10, t=0.1, omega=1.1, kappa=1.5, lmbda=0.01, ti_td=0.1) self.assertEqual(len(new_sequences), 10) self.assertTrue(any( i != self.old_sequence for i in new_sequences)) #vanishing probability of failure
# velocities = constantP["velocities"] # # with open("test.csv", "wb") as csvfile: # f=csv.writer(csvfile) # f.writerow(x) # f.writerow(y) # f.writerow([velocity.real for velocity in velocities]) #print "Initial population of {} gives {}".format(len(population), evolve.simulation.get_time(population[0])) hugepop = [] for popnumber in range(5): population = GA.create_population(5) for i in range(5): newpop = evolve.evolve(population) population = newpop #print "Population of {} members gives latest value of = {} ".format(len(newpop), evolve.simulation.get_time(newpop[0])) hugepop.append(population[0]) print "Population of {} members gives latest value of = {} ".format(len(newpop), evolve.simulation.get_time(newpop[0])) for i in range(5): finalpop = evolve.evolve(hugepop) hugepop = finalpop # bestpower = evolve.simulation.get_time(hugepop[0]) # velocities = bestpower["velocities"] print "Hugepop generated best time of {}".format(evolve.simulation.get_time(hugepop[0])) # with open("test2.csv", "wb") as csvfile: # f=csv.writer(csvfile) # f.writerow(x) # f.writerow(y)
#with individuals evolving in each generation for gen in range(1,generations+1) : fitnesses = [0]*pop for i in range(pop) : for j in range(i+1,pop) : player1 = players[i] player2 = players[j] #first match curr_fitness = match(player1,player2,n,win1,\ win2,loss1,loss2,draw1,draw2) fitnesses[i] += curr_fitness[0] fitnesses[j] += curr_fitness[1] #interchanging first and second player player1 = players[j] player2 = players[i] #second match curr_fitness = match(player1,player2,n,win1,\ win2,loss1,loss2,draw1,draw2) fitnesses[j] += curr_fitness[0] fitnesses[i] += curr_fitness[1] players = evolve(players,fitnesses) #saving the best individual as the trained model np.save(file_location+str(n),players[0])
def pycola_evolve(input_file, output_file, box_length, level, gridscale=3) : # Set up the parameters from the MUSIC ic snapshot: # music_file="/home/yren/EXA/code/cosmoflow-sims/MUSIC/peter_ics_bl_128.hdf5" #music_file="/home/yren/EXA/code/cosmoflow-sims/MUSIC/peter_ics_bl128_level3.hdf5" # Set up according to instructions for # aux.boundaries() ## boxsize=256.0 # in Mpc/h ## level=8 ## level_zoom=8 ## gridscale=3 boxsize=float(box_length) # boxsize=128.0 # in Mpc/h level=level level_zoom=level #gridscale=3 # Set up according to instructions for # ic.import_music_snapshot() # level0='08' # should match level above # level1='08' # should match level_zoom above # level0='09' # should match level above # level1='09' # should match level_zoom above level0="%02d"%(level) level1="%02d"%(level_zoom) # Set how much to cut from the sides of the full box. # This makes the COLA box to be of the following size in Mpc/h: # (2.**level-(cut_from_sides[0]+cut_from_sides[1]))/2.**level*boxsize # This is the full box. Set FULL=True in evolve() below cut_from_sides=[0,0]# 100Mpc/h. # # These are the interesting cases: #cut_from_sides=[64,64]# 75Mpc/h #cut_from_sides=[128,128] # 50Mpc/h #cut_from_sides=[192,192] # 25Mpc/h sx_full1, sy_full1, sz_full1, sx_full_zoom1, sy_full_zoom1, \ sz_full_zoom1, offset_from_code \ = import_music_snapshot(input_file, \ boxsize,level0=level0,level1=level1) # sx_full1 = sx_full1.astype('float32') # sy_full1 = sy_full1.astype('float32') # sz_full1 = sz_full1.astype('float32') # sx_full_zoom1 = sx_full_zoom1.astype('float32') # sy_full_zoom1 = sy_full_zoom1.astype('float32') # sz_full_zoom1 = sz_full_zoom1.astype('float32') NPART_zoom=list(sx_full_zoom1.shape) # print "Starting 2LPT on full box." #Get bounding boxes for full box with 1 refinement level for MUSIC. BBox_in, offset_zoom, cellsize, cellsize_zoom, \ offset_index, BBox_out, BBox_out_zoom, \ ngrid_x, ngrid_y, ngrid_z, gridcellsize \ = boundaries(boxsize, level, level_zoom, \ NPART_zoom, offset_from_code, [0,0], gridscale) sx2_full1, sy2_full1, sz2_full1, sx2_full_zoom1, \ sy2_full_zoom1, sz2_full_zoom1 \ = ic_2lpt( cellsize, sx_full1 , sy_full1 , sz_full1 , cellsize_zoom=cellsize_zoom, sx_zoom = sx_full_zoom1, sy_zoom = sy_full_zoom1, sz_zoom = sz_full_zoom1, boxsize=boxsize, ngrid_x_lpt=ngrid_x,ngrid_y_lpt=ngrid_y,ngrid_z_lpt=ngrid_z, offset_zoom=offset_zoom,BBox_in=BBox_in) #Get bounding boxes for the COLA box with 1 refinement level for MUSIC. BBox_in, offset_zoom, cellsize, cellsize_zoom, \ offset_index, BBox_out, BBox_out_zoom, \ ngrid_x, ngrid_y, ngrid_z, gridcellsize \ = boundaries( boxsize, level, level_zoom, \ NPART_zoom, offset_from_code, cut_from_sides, gridscale) # Trim full-box displacement fields down to COLA volume. sx_full = sx_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sy_full = sy_full1[BBox_out[0,0]:BBox_out[0,1], BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sz_full = sz_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sx_full_zoom = sx_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sy_full_zoom = sy_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sz_full_zoom = sz_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] del sx_full1, sy_full1, sz_full1, sx_full_zoom1, sy_full_zoom1, sz_full_zoom1 sx2_full = sx2_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sy2_full = sy2_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sz2_full = sz2_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sx2_full_zoom = sx2_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sy2_full_zoom = sy2_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sz2_full_zoom = sz2_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] del sx2_full1, sy2_full1, sz2_full1, sx2_full_zoom1, sy2_full_zoom1, sz2_full_zoom1 #print "2LPT on full box is done." #print "Starting COLA!" px, py, pz, vx, vy, vz, \ px_zoom, py_zoom, pz_zoom, vx_zoom, vy_zoom, vz_zoom \ = evolve( cellsize, sx_full, sy_full, sz_full, sx2_full, sy2_full, sz2_full, FULL=True, cellsize_zoom=cellsize_zoom, sx_full_zoom = sx_full_zoom , sy_full_zoom = sy_full_zoom , sz_full_zoom = sz_full_zoom , sx2_full_zoom = sx2_full_zoom, sy2_full_zoom = sy2_full_zoom, sz2_full_zoom = sz2_full_zoom, offset_zoom=offset_zoom, BBox_in=BBox_in, ngrid_x=ngrid_x, ngrid_y=ngrid_y, ngrid_z=ngrid_z, gridcellsize=gridcellsize, ngrid_x_lpt=ngrid_x, ngrid_y_lpt=ngrid_y, ngrid_z_lpt=ngrid_z, gridcellsize_lpt=gridcellsize, a_final=1., a_initial=1./10., n_steps=10, save_to_file=True, # set this to True to output the snapshot to a file file_npz_out=output_file, ) del vx_zoom,vy_zoom,vz_zoom del vx,vy,vz
def test_evolve_with_high_insertion(self): new_sequences = evolve.evolve(self.old_sequence, taxa=10, t=0.1, omega=1.1, kappa=1.5, lmbda=0.1, ti_td=10.0) self.assertEqual(len(new_sequences), 10) len_new_sequences = sum([len(i) for i in new_sequences]) self.assertTrue(len_new_sequences != 10*len(self.old_sequence))
params = [ x for (y, x) in sorted(zip(scores, params), key=lambda pair: pair[0]) ] fas = [x for (y, x) in sorted(zip(scores, fas), key=lambda pair: pair[0])] scores.sort() print '--- evolving ---' for ev in range(7): print ev print params print devs print fas print scores params = evolve(params, devs, frac=0.5) print params for ev_pos in range(len(params) - int(0.5 * len(params)), len(params)): print ev_pos print params[ev_pos] p = params[ev_pos] deltas = [] for key in train: print key (sample_frequency, wav), onset = wavs[key] computed_onset = compute_onset(sample_frequency, wav, p[0], durations=[(0, p[1]), (0.001, p[2]), (0.02, p[3])],
import evolve pop = [[0 for x in xrange(2)] for y in xrange(2)] pop[1][0] = 1 pop[0][1] = 1 pop[1][1] = 1 popAccept = [[1 for x in xrange(2)] for y in xrange(2)] popEvolved = evolve.evolve(pop, 2, 2, 1, 0) if (popEvolved == popAccept): print 'SUCCESS' else: print 'FAILURE'
mul = 1 grid = 20 n = grid * mul psi = np.zeros((n, n), dtype=np.float32) ome = np.zeros((n, n), dtype=np.float32) dt = float(0.01 / mul) nu = float(0.061) ps = psi om = ome ps_list = [] #om_list = [] for t in range(int(1 / dt)): # omega を時間発展する omout = evolve.evolve(ps, om, dt, nu) # psi を poisson 方程式から求める psout = poisson.solve(ps, omout) ps_list.append(psout) # om_list.append(omout) ps = psout om = omout kx = np.array([ [-1, 1] ]) ky = np.array([ [-1], [1] ]) xx, yy = np.meshgrid(np.linspace(0.0, 1.0, n), np.linspace(0.0, 1.0, n)) xs = xx[0::mul, 0::mul] ys = yy[0::mul, 0::mul] fig = plt.figure(figsize=(10,10)) ims = []
init_population(exp_name, generation, population) else: # init directory structure for next generation init_generation(exp_name, generation+1, population) # run models submit_it(exp_name, generation, population) # evaluate cost function and run genetic algorithm # calc_vrms for current generation # rank current generation rank_population(exp_name, generation, population) # cross over and mutate to create next generation evolve(exp_name, generation, populatoin) # resubmit this script to run next generation script = [] ##initial script settings script.append("#!/bin/bash\n") script.append("#PBS -S /bin/bash\n") script.append("#PBS -q express\n") script.append("#PBS -l ncpus=1\n") script.append("#PBS -l wd\n") script.append("#PBS -l walltime=04:00:00\n") script.append("#PBS -l mem=60gb\n") script.append("#PBS -N reef%d\n" % (generation+1)) script.append("#PBS -P ep4\n") script.append("cd ${PBS_O_WORKDIR}\n")
def run(music_file): import numpy as np import matplotlib.pyplot as plt from aux import boundaries from ic import ic_2lpt, import_music_snapshot from evolve import evolve from cic import CICDeposit_3 from potential import initialize_density # Set up the parameters from the MUSIC ic snapshot: # Set up according to instructions for # aux.boundaries() boxsize = 100.0 # in Mpc/h level = 7 level_zoom = 8 gridscale = 1 # Set up according to instructions for # ic.import_music_snapshot() level0 = '07' # should match level above level1 = '08' # should match level_zoom above # Set how much to cut from the sides of the full box. # This makes the COLA box to be of the following size in Mpc/h: # (2.**level-(cut_from_sides[0]+cut_from_sides[1]))/2.**level*boxsize # This is the full box. Set FULL=True in evolve() below #cut_from_sides=[0,0]# 100Mpc/h. # # These are the interesting cases: #cut_from_sides=[64,64]# 75Mpc/h #cut_from_sides=[128,128] # 50Mpc/h # cut_from_sides=[192,192] # 25Mpc/h cut_from_sides = [192 / 4, 192 / 4] # 25Mpc/h with level/zoom = 7/8 sx_full1, sy_full1, sz_full1, sx_full_zoom1, sy_full_zoom1, \ sz_full_zoom1, offset_from_code \ = import_music_snapshot(music_file, \ boxsize,level0=level0,level1=level1) sx_full1 = sx_full1.astype('float32') sy_full1 = sy_full1.astype('float32') sz_full1 = sz_full1.astype('float32') sx_full_zoom1 = sx_full_zoom1.astype('float32') sy_full_zoom1 = sy_full_zoom1.astype('float32') sz_full_zoom1 = sz_full_zoom1.astype('float32') NPART_zoom = list(sx_full_zoom1.shape) print "Starting 2LPT on full box." #Get bounding boxes for full box with 1 refinement level for MUSIC. BBox_in, offset_zoom, cellsize, cellsize_zoom, \ offset_index, BBox_out, BBox_out_zoom, \ ngrid_x, ngrid_y, ngrid_z, gridcellsize \ = boundaries(boxsize, level, level_zoom, \ NPART_zoom, offset_from_code, [0,0], gridscale) sx2_full1, sy2_full1, sz2_full1, sx2_full_zoom1, \ sy2_full_zoom1, sz2_full_zoom1 \ = ic_2lpt( cellsize, sx_full1 , sy_full1 , sz_full1 , cellsize_zoom=cellsize_zoom, sx_zoom = sx_full_zoom1, sy_zoom = sy_full_zoom1, sz_zoom = sz_full_zoom1, boxsize=100.00, ngrid_x_lpt=ngrid_x,ngrid_y_lpt=ngrid_y,ngrid_z_lpt=ngrid_z, offset_zoom=offset_zoom,BBox_in=BBox_in) #Get bounding boxes for the COLA box with 1 refinement level for MUSIC. BBox_in, offset_zoom, cellsize, cellsize_zoom, \ offset_index, BBox_out, BBox_out_zoom, \ ngrid_x, ngrid_y, ngrid_z, gridcellsize \ = boundaries( boxsize, level, level_zoom, \ NPART_zoom, offset_from_code, cut_from_sides, gridscale) # Trim full-box displacement fields down to COLA volume. sx_full = sx_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sy_full = sy_full1[BBox_out[0,0]:BBox_out[0,1], BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sz_full = sz_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sx_full_zoom = sx_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sy_full_zoom = sy_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sz_full_zoom = sz_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] del sx_full1, sy_full1, sz_full1, sx_full_zoom1, sy_full_zoom1, sz_full_zoom1 sx2_full = sx2_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sy2_full = sy2_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sz2_full = sz2_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sx2_full_zoom = sx2_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sy2_full_zoom = sy2_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sz2_full_zoom = sz2_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] del sx2_full1, sy2_full1, sz2_full1, sx2_full_zoom1, sy2_full_zoom1, sz2_full_zoom1 print "2LPT on full box is done." print "Starting COLA!" px, py, pz, vx, vy, vz, \ px_zoom, py_zoom, pz_zoom, vx_zoom, vy_zoom, vz_zoom \ = evolve( cellsize, sx_full, sy_full, sz_full, sx2_full, sy2_full, sz2_full, FULL=False, cellsize_zoom=cellsize_zoom, sx_full_zoom = sx_full_zoom , sy_full_zoom = sy_full_zoom , sz_full_zoom = sz_full_zoom , sx2_full_zoom = sx2_full_zoom, sy2_full_zoom = sy2_full_zoom, sz2_full_zoom = sz2_full_zoom, offset_zoom=offset_zoom, BBox_in=BBox_in, ngrid_x=ngrid_x, ngrid_y=ngrid_y, ngrid_z=ngrid_z, gridcellsize=gridcellsize, ngrid_x_lpt=ngrid_x, ngrid_y_lpt=ngrid_y, ngrid_z_lpt=ngrid_z, gridcellsize_lpt=gridcellsize, a_final=1., a_initial=1./10., n_steps=10, save_to_file=False, # set this to True to output the snapshot to a file file_npz_out='tmp.npz', ) del vx_zoom, vy_zoom, vz_zoom del vx, vy, vz print "Making a figure ..." # grid size for figure array ngrid = 2 * 128 # physical size of figure array cutsize = 12.0 #Mpc/h # offset vector [Mpc/h]: com = [1.30208333, 1.10677083, 0.944] com[0] += offset_zoom[0]+cellsize_zoom * \ (BBox_out_zoom[0,1]-BBox_out_zoom[0,0])/2.0-cutsize/2.0 com[1] += offset_zoom[1]+cellsize_zoom * \ (BBox_out_zoom[1,1]-BBox_out_zoom[1,0])/2.0-cutsize/2.0 com[2] += offset_zoom[2]+cellsize_zoom * \ (BBox_out_zoom[2,1]-BBox_out_zoom[2,0])/2.0-cutsize/2.0 density, den_k, den_fft, _ = initialize_density(ngrid, ngrid, ngrid) density.fill(0.0) # Lay down fine particles on density array with CiC: CICDeposit_3( px_zoom - com[0], py_zoom - com[1], pz_zoom - com[2], px_zoom, py_zoom, pz_zoom, #dummies density, cellsize_zoom, cutsize / float(ngrid), 0, 0, # dummy 0, # dummy np.array([[0, 0], [0, 0], [0, 0]], dtype='int32'), np.array([0.0, 0.0, 0.0], dtype='float32'), 0) # Lay down any present crude particles on density array with CiC: CICDeposit_3( px - com[0], py - com[1], pz - com[2], px, py, pz, #dummies density, cellsize, cutsize / float(ngrid), 0, 0, # dummy 0, # dummy BBox_in, np.array([0.0, 0.0, 0.0], dtype='float32'), 0) # make the figure: plt.imshow(np.arcsinh( (density.mean(axis=2)) * np.sinh(1.0) / 10.0)**(1. / 3.), vmin=0.0, vmax=1.75, interpolation='bicubic', cmap='CMRmap_r') plt.axis('off') plt.show()
def preevolve(my_data): """ preevolve is called before we being the timestepping loop. For the incompressible solver, this does an initial projection on the velocity field and then goes through the full evolution to get the value of phi. The fluid state (u, v) is then reset to values before this evolve. """ myg = my_data.grid u = my_data.get_var("x-velocity") v = my_data.get_var("y-velocity") my_data.fill_BC("x-velocity") my_data.fill_BC("y-velocity") # 1. do the initial projection. This makes sure that our original # velocity field satisties div U = 0 # next create the multigrid object. We want Neumann BCs on phi # at solid walls and periodic on phi for periodic BCs MG = multigrid.CellCenterMG2d(myg.nx, myg.ny, xl_BC_type="periodic", xr_BC_type="periodic", yl_BC_type="periodic", yr_BC_type="periodic", xmin=myg.xmin, xmax=myg.xmax, ymin=myg.ymin, ymax=myg.ymax, verbose=0) # first compute divU divU = MG.soln_grid.scratch_array() divU[MG.ilo:MG.ihi+1,MG.jlo:MG.jhi+1] = \ 0.5*(u[myg.ilo+1:myg.ihi+2,myg.jlo:myg.jhi+1] - u[myg.ilo-1:myg.ihi ,myg.jlo:myg.jhi+1])/myg.dx + \ 0.5*(v[myg.ilo:myg.ihi+1,myg.jlo+1:myg.jhi+2] - v[myg.ilo:myg.ihi+1,myg.jlo-1:myg.jhi ])/myg.dy # solve L phi = DU # initialize our guess to the solution MG.init_zeros() # setup the RHS of our Poisson equation MG.init_RHS(divU) # solve MG.solve(rtol=1.e-10) # store the solution in our my_data object -- include a single # ghostcell phi = my_data.get_var("phi") solution = MG.get_solution() phi[myg.ilo-1:myg.ihi+2,myg.jlo-1:myg.jhi+2] = \ solution[MG.ilo-1:MG.ihi+2,MG.jlo-1:MG.jhi+2] # compute the cell-centered gradient of phi and update the # velocities gradp_x = myg.scratch_array() gradp_y = myg.scratch_array() gradp_x[myg.ilo:myg.ihi+1,myg.jlo:myg.jhi+1] = \ 0.5*(phi[myg.ilo+1:myg.ihi+2,myg.jlo:myg.jhi+1] - phi[myg.ilo-1:myg.ihi ,myg.jlo:myg.jhi+1])/myg.dx gradp_y[myg.ilo:myg.ihi+1,myg.jlo:myg.jhi+1] = \ 0.5*(phi[myg.ilo:myg.ihi+1,myg.jlo+1:myg.jhi+2] - phi[myg.ilo:myg.ihi+1,myg.jlo-1:myg.jhi ])/myg.dy u[:,:] -= gradp_x v[:,:] -= gradp_y # fill the ghostcells my_data.fill_BC("x-velocity") my_data.fill_BC("y-velocity") # 2. now get an approximation to gradp at n-1/2 by going through the # evolution. # store the current solution copyData = patch.cell_center_data_clone(my_data) # get the timestep dt = timestep.timestep(copyData) # evolve evolve.evolve(copyData, dt) # update gradp_x and gradp_y in our main data object gp_x = my_data.get_var("gradp_x") gp_y = my_data.get_var("gradp_y") new_gp_x = copyData.get_var("gradp_x") new_gp_y = copyData.get_var("gradp_y") gp_x[:,:] = new_gp_x[:,:] gp_y[:,:] = new_gp_y[:,:] print "done with the pre-evolution"
def test_evolve(self): new_sequences = evolve.evolve(self.old_sequence, taxa=10, t=0.1, omega=1.1, kappa=1.5, lmbda=0.01, ti_td=0.1) self.assertEqual(len(new_sequences), 10) self.assertTrue(any(i != self.old_sequence for i in new_sequences)) #vanishing probability of failure
def test_evolve_returns_different_evolved_sequences(self): new_sequences0 = evolve.evolve(self.old_sequence, taxa=10, t=0.1, omega=1.1, kappa=1.5, lmbda=0.01, ti_td=0.1) new_sequences1 = evolve.evolve(self.old_sequence, taxa=10, t=0.1, omega=1.1, kappa=1.5, lmbda=0.01, ti_td=0.1) for i,j in zip(new_sequences0, new_sequences1): self.assertNotEqual(i, j)
"USAGE: embla.py <originalfile> <maximumgenerations> <reproductionrate> <.fileextension>" ) exit() #sets up imput seed = sys.argv[1] max = sys.argv[2] rep = sys.argv[3] ext = sys.argv[4] max = int(max) rep = int(rep) wdir = os.getcwd() #gets working directory gen = 1 #sets generation number wdirgen = wdir + "/G" + str(gen) ev = evolve.evolve() wdirseed = wdir + "/" + seed if not os.path.exists(wdirgen): os.makedirs(wdirgen) wdirgenseed = wdirgen + "/" + seed shutil.copy(wdirseed, wdirgenseed) while (gen <= max): copy = 0 next = gen + 1 wdirnext = wdir + "/G" + str(next) nextspecies = wdirnext + "/" + seed numspecies = len([ name for name in os.listdir(wdirgen) if os.path.isfile(os.path.join(wdirgen, name)) ])
def runit(infile, outfile, omM): import numpy as np import matplotlib.pyplot as plt from aux import boundaries from ic import ic_2lpt,import_music_snapshot from evolve import evolve from cic import CICDeposit_3 from potential import initialize_density # Set up the parameters from the MUSIC ic snapshot: music_file=infile # Set up according to instructions for # aux.boundaries() boxsize=512.0 # in Mpc/h level=9 level_zoom=9 gridscale=3 # Set up according to instructions for # ic.import_music_snapshot() level0='09' # should match level above level1='09' # should match level_zoom above # Set how much to cut from the sides of the full box. # This makes the COLA box to be of the following size in Mpc/h: # (2.**level-(cut_from_sides[0]+cut_from_sides[1]))/2.**level*boxsize # This is the full box. Set FULL=True in evolve() below cut_from_sides=[0,0]# 100Mpc/h. # # These are the interesting cases: #cut_from_sides=[64,64]# 75Mpc/h #cut_from_sides=[128,128] # 50Mpc/h #cut_from_sides=[192,192] # 25Mpc/h ### some nonsens eto convert types from float64 to float32 - I think this is the cause of an error later? sx_full1, sy_full1, sz_full1, sx_full_zoom1, sy_full_zoom1, \ sz_full_zoom1, offset_from_code \ = import_music_snapshot(music_file, \ boxsize,level0=level0,level1=level1) NPART_zoom=list(sx_full_zoom1.shape) print "Starting 2LPT on full box." #Get bounding boxes for full box with 1 refinement level for MUSIC. BBox_in, offset_zoom, cellsize, cellsize_zoom, \ offset_index, BBox_out, BBox_out_zoom, \ ngrid_x, ngrid_y, ngrid_z, gridcellsize \ = boundaries(boxsize, level, level_zoom, \ NPART_zoom, offset_from_code, [0,0], gridscale) sx2_full1, sy2_full1, sz2_full1, sx2_full_zoom1, \ sy2_full_zoom1, sz2_full_zoom1 \ = ic_2lpt( cellsize, sx_full1 , sy_full1 , sz_full1 , cellsize_zoom=cellsize_zoom, sx_zoom = sx_full_zoom1, sy_zoom = sy_full_zoom1, sz_zoom = sz_full_zoom1, boxsize=boxsize, ngrid_x_lpt=ngrid_x,ngrid_y_lpt=ngrid_y,ngrid_z_lpt=ngrid_z, offset_zoom=offset_zoom,BBox_in=BBox_in) #Get bounding boxes for the COLA box with 1 refinement level for MUSIC. BBox_in, offset_zoom, cellsize, cellsize_zoom, \ offset_index, BBox_out, BBox_out_zoom, \ ngrid_x, ngrid_y, ngrid_z, gridcellsize \ = boundaries( boxsize, level, level_zoom, \ NPART_zoom, offset_from_code, cut_from_sides, gridscale) # Trim full-box displacement fields down to COLA volume. sx_full = sx_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sy_full = sy_full1[BBox_out[0,0]:BBox_out[0,1], BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sz_full = sz_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sx_full_zoom = sx_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sy_full_zoom = sy_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sz_full_zoom = sz_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] del sx_full1, sy_full1, sz_full1, sx_full_zoom1, sy_full_zoom1, sz_full_zoom1 sx2_full = sx2_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sy2_full = sy2_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sz2_full = sz2_full1[BBox_out[0,0]:BBox_out[0,1], \ BBox_out[1,0]:BBox_out[1,1], \ BBox_out[2,0]:BBox_out[2,1]] sx2_full_zoom = sx2_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sy2_full_zoom = sy2_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] sz2_full_zoom = sz2_full_zoom1[BBox_out_zoom[0,0]:BBox_out_zoom[0,1], \ BBox_out_zoom[1,0]:BBox_out_zoom[1,1], \ BBox_out_zoom[2,0]:BBox_out_zoom[2,1]] del sx2_full1, sy2_full1, sz2_full1, sx2_full_zoom1, sy2_full_zoom1, sz2_full_zoom1 print "2LPT on full box is done." print "Starting COLA!" print "cellsize:", cellsize px, py, pz, vx, vy, vz, \ px_zoom, py_zoom, pz_zoom, vx_zoom, vy_zoom, vz_zoom \ = evolve( cellsize, sx_full, sy_full, sz_full, sx2_full, sy2_full, sz2_full, FULL=True, cellsize_zoom=cellsize_zoom, sx_full_zoom = sx_full_zoom , sy_full_zoom = sy_full_zoom , sz_full_zoom = sz_full_zoom , sx2_full_zoom = sx2_full_zoom, sy2_full_zoom = sy2_full_zoom, sz2_full_zoom = sz2_full_zoom, offset_zoom=offset_zoom, BBox_in=BBox_in, ngrid_x=ngrid_x, ngrid_y=ngrid_y, ngrid_z=ngrid_z, gridcellsize=gridcellsize, ngrid_x_lpt=ngrid_x, ngrid_y_lpt=ngrid_y, ngrid_z_lpt=ngrid_z, gridcellsize_lpt=gridcellsize, Om = float(omM), Ol = 1.0-float(omM), a_final=1., a_initial=1./10., n_steps=10, save_to_file=True, # set this to True to output the snapshot to a file file_npz_out=outfile, ) del vx_zoom,vy_zoom,vz_zoom del vx,vy,vz
if gc_debug: from collections import defaultdict from gc import get_objects before = defaultdict(int) after = defaultdict(int) for i in get_objects(): before[type(i)] += 1 import cherrypy import dowser """cherrypy.tree.mount(dowser.Root()) cherrypy.config.update({ 'environment': 'embedded', 'server.socket_port': 8081 }) cherrypy.engine.start()""" evolve.evolve(ea, evolve_args) if gc_debug: objs = get_objects() for i in objs: after[type(i)] += 1 items = [(k, after[k] - before[k]) for k in after if after[k] - before[k]] for j, (k, v) in enumerate( sorted(items, key=lambda (k, v): v, reverse=True)): print ' ', k, v, [ str(i) for i in evolve.random.sample(objs, 1000) if type(i) == k ][:10] if j > 5: break del objs del items
= evolve( cellsize, sx_full, sy_full, sz_full, sx2_full, sy2_full, sz2_full, FULL=True, cellsize_zoom=cellsize_zoom, sx_full_zoom = sx_full_zoom , sy_full_zoom = sy_full_zoom , sz_full_zoom = sz_full_zoom , sx2_full_zoom = sx2_full_zoom, sy2_full_zoom = sy2_full_zoom, sz2_full_zoom = sz2_full_zoom, offset_zoom=offset_zoom, BBox_in=BBox_in, ngrid_x=ngrid_x, ngrid_y=ngrid_y, ngrid_z=ngrid_z, gridcellsize=gridcellsize, ngrid_x_lpt=ngrid_x, ngrid_y_lpt=ngrid_y, ngrid_z_lpt=ngrid_z, gridcellsize_lpt=gridcellsize, a_final=1., a_initial=1./10., n_steps=10, save_to_file=True, # set this to True to output the snapshot to a file file_npz_out='tmp.npz' )
def preevolve(my_data): """ preevolve is called before we being the timestepping loop. For the incompressible solver, this does an initial projection on the velocity field and then goes through the full evolution to get the value of phi. The fluid state (u, v) is then reset to values before this evolve. """ myg = my_data.grid u = my_data.get_var("x-velocity") v = my_data.get_var("y-velocity") my_data.fill_BC("x-velocity") my_data.fill_BC("y-velocity") # 1. do the initial projection. This makes sure that our original # velocity field satisties div U = 0 # next create the multigrid object. We want Neumann BCs on phi # at solid walls and periodic on phi for periodic BCs MG = multigrid.CellCenterMG2d(myg.nx, myg.ny, xl_BC_type="periodic", xr_BC_type="periodic", yl_BC_type="periodic", yr_BC_type="periodic", xmin=myg.xmin, xmax=myg.xmax, ymin=myg.ymin, ymax=myg.ymax, verbose=0) # first compute divU divU = MG.soln_grid.scratch_array() divU[MG.ilo:MG.ihi+1,MG.jlo:MG.jhi+1] = \ 0.5*(u[myg.ilo+1:myg.ihi+2,myg.jlo:myg.jhi+1] - u[myg.ilo-1:myg.ihi ,myg.jlo:myg.jhi+1])/myg.dx + \ 0.5*(v[myg.ilo:myg.ihi+1,myg.jlo+1:myg.jhi+2] - v[myg.ilo:myg.ihi+1,myg.jlo-1:myg.jhi ])/myg.dy # solve L phi = DU # initialize our guess to the solution MG.init_zeros() # setup the RHS of our Poisson equation MG.init_RHS(divU) # solve MG.solve(rtol=1.e-10) # store the solution in our my_data object -- include a single # ghostcell phi = my_data.get_var("phi") solution = MG.get_solution() phi[myg.ilo-1:myg.ihi+2,myg.jlo-1:myg.jhi+2] = \ solution[MG.ilo-1:MG.ihi+2,MG.jlo-1:MG.jhi+2] # compute the cell-centered gradient of phi and update the # velocities gradp_x = myg.scratch_array() gradp_y = myg.scratch_array() gradp_x[myg.ilo:myg.ihi+1,myg.jlo:myg.jhi+1] = \ 0.5*(phi[myg.ilo+1:myg.ihi+2,myg.jlo:myg.jhi+1] - phi[myg.ilo-1:myg.ihi ,myg.jlo:myg.jhi+1])/myg.dx gradp_y[myg.ilo:myg.ihi+1,myg.jlo:myg.jhi+1] = \ 0.5*(phi[myg.ilo:myg.ihi+1,myg.jlo+1:myg.jhi+2] - phi[myg.ilo:myg.ihi+1,myg.jlo-1:myg.jhi ])/myg.dy u[:, :] -= gradp_x v[:, :] -= gradp_y # fill the ghostcells my_data.fill_BC("x-velocity") my_data.fill_BC("y-velocity") # 2. now get an approximation to gradp at n-1/2 by going through the # evolution. # store the current solution copyData = patch.cell_center_data_clone(my_data) # get the timestep dt = timestep.timestep(copyData) # evolve evolve.evolve(copyData, dt) # update gradp_x and gradp_y in our main data object gp_x = my_data.get_var("gradp_x") gp_y = my_data.get_var("gradp_y") new_gp_x = copyData.get_var("gradp_x") new_gp_y = copyData.get_var("gradp_y") gp_x[:, :] = new_gp_x[:, :] gp_y[:, :] = new_gp_y[:, :] print "done with the pre-evolution"
l = Controller() genome = np.random.rand(Controller.N_GENES) l.set_genome(genome) xs = linspace(0, 1, 101) highbat_outs, lowbat_outs, unscaled_outs = [], [], [] for x in xs: highbat_out, unscaled_out = l.output(x, [1.0, 1.0]) lowbat_out, unscaled_out = l.output(x, [0.0, 0.0]) highbat_outs.append(highbat_out) lowbat_outs.append(lowbat_out) unscaled_outs.append(unscaled_out) plot(xs, highbat_outs, label='high battery') plot(xs, lowbat_outs, label='low battery') plot(xs, unscaled_outs, label='no battery influence') xlabel('ipsilateral sensor') ylabel('ipsilateral motor output') xlim(0, 1) ylim(-1.05, 1.05) legend() show() if __name__ == '__main__': # test_directional_sensors() # test_animat_no_controller() # test_link_piecewise() evolve()
from collections import defaultdict from gc import get_objects before = defaultdict(int) after = defaultdict(int) for i in get_objects(): before[type(i)] += 1 import cherrypy import dowser """cherrypy.tree.mount(dowser.Root()) cherrypy.config.update({ 'environment': 'embedded', 'server.socket_port': 8081 }) cherrypy.engine.start()""" evolve.evolve(ea, evolve_args) if gc_debug: objs = get_objects() for i in objs: after[type(i)]+=1 items = [(k,after[k]-before[k]) for k in after if after[k]-before[k]] for j, (k,v) in enumerate(sorted(items, key = lambda (k,v):v, reverse=True)): print ' ', k, v, [str(i) for i in evolve.random.sample(objs, 1000) if type(i) == k][:10] if j > 5: break del objs del items from guppy import hpy h = hpy() print h.heap() del h
def iterate(field, field0, timesteps, image_interval): for m in range(1, timesteps + 1): evolve(field, field0, a, dt, dx2, dy2) if m % image_interval == 0: write_field(field, m)