# X[time][ring][cell] X = np.zeros((tau, rings, ringsize), float) Y = np.zeros((tau, rings, ringsize), float) for ring in range(rings): for cell in range(ringsize): X[0][ring][cell] = X0[cell][ring] Y[0][ring][cell] = Y0[cell][ring] time = np.arange(0, h * N + h, h) # Loop over all cells and time points startTime = mytime.time() for t in range(0, N): index = t % tau for ring in range(0, rings): timestep.timestep(X, Y, cylinderConcPerCell, index, ring, t, tau, omega, Am) # Generate progress output to standard out if t % 5 == 0 and t != 0: elapsed = mytime.time() - startTime ratio = 1.0 * t / N print ('%d/%d, \t %.1f%%, \t elapsed: %.1f \t ETA: %.1f'\ % (t, N, ratio*100, elapsed, elapsed/ratio-elapsed)) # Write data output to files if t % sampleFreq == 0: # Write raw data to files # writeCylinder('outputX_F_Dxr_' + str(Dxr) + '_k_' + ':', X, t) # writeCylinder('outputY_F_Dxr_' + str(Dxr) + '_k_' + ':', Y, t) # Write X matrix to image file
# Not standard modules: ensure these files are in the current directory import timestep as ts import simple_plot as sp import simple_animate as sa from matplotlib import pyplot # Sample initial condition and code for testing #dx = 0.025 xmax = 2.0 nx = 41 dx = xmax/(nx-1) nt = 50 test_ic = numpy.zeros((1, nx)) # put at assert to accept 1-by-nx ICs test_ic[0, 0.5/dx: 1/dx + 1] = 2 test_solution = ts.timestep(test_ic, 'fd') sp.plot_at(0, test_solution) sp.plot_at(30, test_solution) sa.animate_it(test_solution) # try a different IC - Double hat test_ic_2 = test_ic.copy() test_ic_2[0, 0.7/dx: 0.9/dx] = 0 test_solution_2 = ts.timestep(test_ic_2, 'fd') sp.plot_at(0, test_solution_2) # see initial condition sp.plot_at(24, test_solution_2) # see intermediate step sp.plot_at(49, test_solution_2) # see final state #BUG: clipped sa.animate_it(test_solution_2) pyplot.show() # to make it show after all the previous non-blocking figures
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"
# correct C_to = C_tot(num_point, p, p0, C_atm0, f_ocean, freeze, T) #correct tau = tau_ir(p, p0, T, freeze) #tau! BTW correct infrared = OLR(sigma_SB, T, tau) # correct qq = Q(insol, albedo, infrared) # ha = hab(num_point, T, freeze, boil) deltat = timestep(diff, latt, delta_latt, num_point, C_to) """ phi += phidot*deltat diff, deltax, x, insol[i], f_ice[i], C_tot[i], albedo[i], tau_ir[i],infrared[i],Q[i],hab[i] = value_update(T,phi,deltat) deltat = timestep(diff, x, deltax, nx, C_tot) phi += phidot*deltat diff, deltax, x, insol[i], f_ice[i], C_tot[i], albedo[i], tau_ir[i],infrared[i],Q[i],hab[i] = value_update(T,phi,deltat) T_max = freeze + 0.9*(boil - freeze) timeyr = time/yr T_mean_old = np.mean(T)
def simulate(parameters, landscape, burnInT, tf, initial_ecosystem=None, idxRun=None, suffix=None): ''' parameters: dictionary, see script.py for example landscape: string, defines the landscape as a string of H and L for high and low-quality habitats burnInT: integer, some number of timesteps (generations) to not store in the pickle file tf: integer, number of timesteps idxRun: integer, when multiple runs on the same parameter-set/suffix are run, may want to separate pickled results file by additional suffix, like *_run0.pkl, *_run1.pkl, etc. suffix: string, the string to identify the pickled results file i.e. ecosystems_suffix_run0.pkl ''' # initialise ecosystem if initial_ecosystem == None: # random start for individuals geneRandFnc = lambda geneType: random.randint( 0, 2**parameters['genetics'][geneType]['noLoci'] - 1) #sexRandFnc = lambda: random.choice( parameters['sexes'] ) natalHabRandFnc = lambda: random.choice(landscape) initial_ecosystem = [{ 'adults': [{ 'sex': 'h', 'natalHabType': natalHabRandFnc(), 'genotype': { geneType: geneRandFnc(geneType) for geneType in parameters['genetics'].keys() } }, { 'sex': 'h', 'natalHabType': natalHabRandFnc(), 'genotype': { geneType: geneRandFnc(geneType) for geneType in parameters['genetics'].keys() } }], 'juveniles': list(), } for habType in landscape] ecosystem = copy.deepcopy( initial_ecosystem ) # make a deep copy so we can store the initial conditions in pickle file # simulate ecosystem for burn-in timesteps, but don't record results t = 1 while t <= burnInT and not ecosystemIsEmpty(ecosystem): ecosystem, _ = timestep(parameters, ecosystem, landscape) t += 1 # simulate ecosystem for remaining timesteps and record results ecosystems = list() # a place to store the ecosystem at each timestep while t <= tf and not ecosystemIsEmpty(ecosystem): # one timestep of simulation ecosystem, _ = timestep(parameters, ecosystem, landscape) # store info ecosystems.append(copy.deepcopy(ecosystem)) t += 1 # pickle the info # build the pickled results file's name fName = 'ecosystems' if suffix == None: suffix = parameters2filesuffix(tf, landscape, parameters) fName += suffix if idxRun != None: fName += '_run' + str(idxRun) fName += '.pkl' # open the file with the name fName f = open(fName, 'wb') # a string explaining the pickle file path = os.path.dirname(os.path.realpath('simulate.py')) ss = 'Created by simulate.py in ' + path + '.\n' ss += 'Contains the following:\n' ss += '0. ss, string: this string you are reading now.\n' ss += '1. burnInT, integer: the number of unrecorded timesteps of burn-in.\n' ss += '2. t, integer: the total number up to which timesteps run (so range(burnInT+1,t)).\n' ss += '3. tf, integer: the total maximum number up to which timesteps were attempted (if pop did not go extinct, t = tf+1).\n' ss += '4. landscape, string: a string defining the landscape habitat type composition (e.g. LLLLHHHLLLL).\n' ss += '5. ecosystems, list of lists of dictionaries: the ecosystem at the end of each recorded timestep.\n' ss += '6. path, string: the path in which the run was performed.\n' ss += '7. parameters, dictionary: the parameter values with which the run was performed.\n' ss += '8. initial_ecosystem, list of dictionaries: the initial ecosystem.\n' pickle.dump(ss, f) # 0. pickle.dump(burnInT, f) pickle.dump(t, f) pickle.dump(tf, f) # 3. pickle.dump(landscape, f) pickle.dump(ecosystems, f) pickle.dump(path, f) # 6. pickle.dump(parameters, f) pickle.dump(initial_ecosystem, f) f.close()
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"
import numpy # Not standard modules: ensure these files are in the current directory import timestep as ts import simple_plot as sp import simple_animate as sa from matplotlib import pyplot # Sample initial condition and code for testing #dx = 0.025 xmax = 2.0 nx = 41 dx = xmax / (nx - 1) nt = 50 test_ic = numpy.zeros((1, nx)) # put at assert to accept 1-by-nx ICs test_ic[0, 0.5 / dx:1 / dx + 1] = 2 test_solution = ts.timestep(test_ic, 'fd') sp.plot_at(0, test_solution) sp.plot_at(30, test_solution) sa.animate_it(test_solution) # try a different IC - Double hat test_ic_2 = test_ic.copy() test_ic_2[0, 0.7 / dx:0.9 / dx] = 0 test_solution_2 = ts.timestep(test_ic_2, 'fd') sp.plot_at(0, test_solution_2) # see initial condition sp.plot_at(24, test_solution_2) # see intermediate step sp.plot_at(49, test_solution_2) # see final state #BUG: clipped sa.animate_it(test_solution_2) pyplot.show() # to make it show after all the previous non-blocking figures
def _csv_line_extract_datetime(_line): line = timestep(_line) return datetime(year=int(line.year), month=int(line.month), day=int(line.day), hour=int(line.hour), \ minute=int(line.minute))