def plot_solution(population, ds): # ds = generate_dataset(dx_dt, theta) ti = [t / 10 for t in times] theta1 = np.array([1, 1]) theta = [] # rint "================================" # rint population plt.figure(1) for p in population: m = math.fsum(p) / float(len(p)) print str(m) + " median " + str(p[len(population) / 2]) theta.append(m) plt.hist(p) plt.figure(2) X0 = np.array([1, 0.5]) t = np.arange(0, 15, 0.1) X = integrate.odeint(dx_dt, X0, t, args=(theta,)) Y = integrate.odeint(dx_dt, X0, t, args=(theta1,)) x, y = X.T x1, y1 = Y.T plt.figure(3) plt.subplot(211) plt.plot(t, x, "r-", label="x(t)") plt.plot(t, x1, "g-", label="x(t))") plt.subplot(212) plt.plot(ti, ds[:, 0], marker="s", linestyle="", color="g") plt.plot(t, y, "b-", label="y(t)") plt.plot(t, y1, "g-", label="y(t)") plt.plot(ti, ds[:, 1], marker="^", linestyle="", color="g") plt.xlabel("time") plt.show()
def Rhalf(Rp,Rn,a,b): Rn /= Rp c = (a*a + b*b)**0.5 / Rp r = linspace(0.001,1,100) def numer(f,r): lo,hi = theta_lohi(Rn,c,0,r) return r*r * (sin(lo)-sin(hi)) def denom(f,r): lo,hi = theta_lohi(Rn,c,0,r) return r * (hi - lo) def arc(f,r): lo,hi = theta_lohi(Rn,c,d,r) return r * (hi - lo) up = odeint(numer,[0],r) dn = odeint(denom,[0],r) d = up[-1,0]/dn[-1,0] area = odeint(arc,[0],r) for i in range(1,len(r)): if area[i-1] < 0.5*area[-1] and area[i] > 0.5*area[-1]: return Rp * r[i]
def compute_jacobian(star, differences, surface_guesses, core_guesses, core_masses, surface_masses, mass_step): jacobian =(np.zeros((4,4))) for i in range(0,4): guess_star = copy(star) if i == 0: step_size = core_guesses[0]*0.01 guess_star.core_pressure = core_guesses[0] + step_size elif i == 1: step_size = core_guesses[1]*0.01 guess_star.core_temp = core_guesses[1] + step_size elif i == 2: step_size = surface_guesses[2]*0.01 guess_star.total_radius = surface_guesses[2] + step_size elif i == 3: step_size = surface_guesses[3]*0.01 guess_star.total_lum = surface_guesses[3] + step_size new_surface = inward_start(guess_star) new_core = outward_start(guess_star, mass_step) new_differences = difference_is(odeint(derivatives, new_core, core_masses, args=(guess_star,)), odeint(derivatives, new_surface, surface_masses, args=(guess_star,))) jacobian[:,i] = np.asarray((new_differences - differences)/step_size) return np.linalg.inv(jacobian)
def __init__(self, f, u0, s, t, dfdu=None): self.f = f self.t = np.array(t, float).copy() self.s = np.array(s, float).copy() if self.s.ndim == 0: self.s = self.s[np.newaxis] if dfdu is None: dfdu = ddu(f) self.dfdu = dfdu u0 = np.array(u0, float) if u0.ndim == 1: # run up to t[0] f = lambda u, t : self.f(u, s) assert t[0] >= 0 and t.size > 1 N0 = int(t[0] / (t[-1] - t[0]) * t.size) u0 = odeint(f, u0, np.linspace(0, t[0], N0+1))[-1] # compute a trajectory self.u = odeint(f, u0, t - t[0]) else: assert (u0.shape[0],) == t.shape self.u = u0.copy() self.dt = t[1:] - t[:-1] self.uMid = 0.5 * (self.u[1:] + self.u[:-1]) self.dudt = (self.u[1:] - self.u[:-1]) / self.dt[:,np.newaxis]
def Advect(self, flow_type = None, t0 = 0, dt = 0, extra_args = None): if flow_type is not None: # Number of particles num_particles = len(self.Particles); # Get the positions of all of the particles x0, y0, z0 = self.GetCoordinates(); # Time vector tf = t0 + dt; # Time vector t = np.array([t0, tf]); # Initial positions as a numpy vector # in the form compatible with the # velocity functions xy0 = np.array(x0 + y0); # xy0 = np.array([x0, y0]); # Choose between fields if "hama" in flow_type.lower(): xy = (odeint(HamaVelocity, y0 = xy0, t = t, args = (extra_args,)))[-1, :]; elif "cpipe" in flow_type.lower(): xy = (odeint(cpipe, y0 = xy0, t = t, args = (extra_args,)))[-1, :]; # Extract the new positions x_new, y_new = Parse_Vector_2d(xy); # Set the new coordinates self.SetCoordinates(x = x_new, y = y_new);
def exercise3part1(T=200, Deltat=0.1, epsilon=0.5): "In this exercise we want to perturb the parameters of the Lorenz system to see how the shape of the Lorenz attractor change" y0=np.random.randn(3) t = np.arange(0.,T, Deltat) data = integrate.odeint(vectorfield, y0, t=t,args=(10,28,8/3)) data_sigma=integrate.odeint(vectorfield, y0, t=t,args=(10+epsilon,28,8/3)) data_rho=integrate.odeint(vectorfield, y0, t=t,args=(10,28+epsilon,8/3)) data_beta=integrate.odeint(vectorfield, y0, t=t,args=(10,28,8/3+epsilon)) fig = plt.figure() ax0 = fig.add_subplot(2, 2, 1, projection='3d') ax1 = fig.add_subplot(2, 2, 2, projection='3d') ax2 = fig.add_subplot(2, 2, 3, projection='3d') ax3 = fig.add_subplot(2, 2, 4, projection='3d') ax0.plot(data[:,0],data[:,1],data[:,2]) ax1.plot(data_sigma[:,0],data_sigma[:,1],data_sigma[:,2]) ax2.plot(data_rho[:,0],data_rho[:,1],data_rho[:,2]) ax3.plot(data_beta[:,0],data_beta[:,1],data_beta[:,2]) ax0.set_title('Standard parameters') ax1.set_title('Sigma perturbed') ax2.set_title('Rho perturbed') ax3.set_title('Beta perturbed') pylab.show() print 'From the plot, the system seems to be more sensibile in beta perturbations'
def test_repeated_t_values(): """Regression test for gh-8217.""" def func(x, t): return -0.25*x t = np.zeros(10) sol = odeint(func, [1.], t) assert_array_equal(sol, np.ones((len(t), 1))) tau = 4*np.log(2) t = [0]*9 + [tau, 2*tau, 2*tau, 3*tau] sol = odeint(func, [1, 2], t, rtol=1e-12, atol=1e-12) expected_sol = np.array([[1.0, 2.0]]*9 + [[0.5, 1.0], [0.25, 0.5], [0.25, 0.5], [0.125, 0.25]]) assert_allclose(sol, expected_sol) # Edge case: empty t sequence. sol = odeint(func, [1.], []) assert_array_equal(sol, np.array([], dtype=np.float64).reshape((0, 1))) # t values are not monotonic. assert_raises(ValueError, odeint, func, [1.], [0, 1, 0.5, 0]) assert_raises(ValueError, odeint, func, [1, 2, 3], [0, -1, -2, 3])
def get_pressure(Planet,layers): radii = Planet.get('radius') density = Planet.get('density') gravity = Planet.get('gravity') num_mantle_layers, num_core_layers, number_h2o_layers = layers # convert radii to depths depths = radii[-1] - radii depths_core = depths[:num_core_layers] gravity_core = gravity[:num_core_layers] density_core = density[:num_core_layers] depths_mant = depths[num_core_layers:(num_core_layers+num_mantle_layers)] gravity_mant = gravity[num_core_layers:(num_core_layers+num_mantle_layers)] density_mant = density[num_core_layers:(num_core_layers+num_mantle_layers)] # Make a spline fit of density as a function of depth rhofunc_mant = interpolate.UnivariateSpline(depths_mant[::-1], density_mant[::-1]) # Make a spline fit of gravity as a function of depth gfunc_mant = interpolate.UnivariateSpline(depths_mant[::-1], gravity_mant[::-1]) rhofunc_core = interpolate.UnivariateSpline(depths_core[::-1], density_core[::-1]) gfunc_core = interpolate.UnivariateSpline(depths_core[::-1], gravity_core[::-1]) if number_h2o_layers > 0: depths_water = depths[(num_core_layers + num_mantle_layers):] gravity_water = gravity[(num_core_layers + num_mantle_layers):] density_water = density[(num_core_layers + num_mantle_layers):] rhofunc_water = interpolate.UnivariateSpline(depths_water[::-1], density_water[::-1]) gfunc_water = interpolate.UnivariateSpline(depths_water[::-1], gravity_water[::-1]) #integrate from 1 bar pressure_water = np.ravel(odeint((lambda p, x: gfunc_water(x) * rhofunc_water(x)),(1./10000.)*1.e9, depths_water[::-1])) WMB_pres = pressure_water[-1] #does not account for very small water layers and ends up breaking code WMB_pres = 5.e8 else: WMB_pres = 5.e8 # integrate the hydrostatic equation pressure_mant = np.ravel(odeint((lambda p, x: gfunc_mant(x) * rhofunc_mant(x)),WMB_pres, depths_mant[::-1])) CMB_pres = pressure_mant[-1] pressure_core = np.ravel(odeint((lambda p, x: gfunc_core(x) * rhofunc_core(x)),CMB_pres, depths_core[::-1])) if number_h2o_layers > 0: pressure = np.concatenate((pressure_water,pressure_mant,pressure_core),axis=0) pressure = [((i/1.e9)*10000.) for i in pressure] return np.asarray(pressure[::-1]) else: pressure = np.concatenate((pressure_mant,pressure_core),axis=0) pressure = [((i/1.e9)*10000.) for i in pressure] return np.asarray(pressure[::-1])
def delta_r(self): """ returns the coeficient delta indicating the RADIAL stability of the movement """ time = np.linspace(0, 5, 1000) def sm1(x, t): if x[0] < 0: return np.array([x[1], 0]) else: return np.array([x[1], self.eta*self.Ez0(x[0])]) traj = odeint(sm1,[0,1.],time) if traj[-1,0] < 0: ind = np.where(traj[:,0] > 0)[0][-1] tm = [time[ind+1],time[ind]] zm = [traj[ind+1,0],traj[ind,0]] period = np.interp(0,zm,tm) def sm2(x, t): t = t - np.floor(t/period)*period pos = np.interp(t, time, traj[:,0]) psi = self.alpha + self.b**2/4. + (self.eta/2.)*self.d2V(pos) return np.array([x[1], psi*x[0], x[3], psi*x[2]]) x0 = [1, 0, 0, 1] sol = odeint(sm2, x0, np.linspace(0, period, 1000)) delta = np.abs((sol[-1,0] + sol[-1,3])/2) beta = np.arccos((sol[-1,0] + sol[-1,3])/2)/np.pi if self.b == 0.: return delta else: out = np.log(delta + np.sqrt(np.abs(delta**2-1)))/period - self.b return out else: return 1.0
def getEta(data,t,xi): global samp, ETA, time, agent, XI if t < len(data): return data[t] else: XI = xi # update input function from paramteter if len(data) == 0: ETA0 = getInitialEta(agent.beta,agent.gamma,XI) data.append(ETA0[:]) for T in range(len(data),t+1): # TODO: should this be samp*t so that accuracy is not lost far from 0??? logging.info('solving ode @ t='+str(T)+', using '+str(samp)+' sub-samples') time = linspace(0,T,samp) #(start,end,nSamples) etadot_0 = [0,0,0,0,0] #assumption of 1st order model #get arrays of data len=samp*t ETA[0] = integrate.odeint(eta1Func,[data[0][0],etadot_0[0]],time) ETA[1] = integrate.odeint(eta2Func,[data[0][1],etadot_0[1]],time) ETA[2] = integrate.odeint(eta3Func,[data[0][2],etadot_0[2]],time) ETA[3] = integrate.odeint(eta4Func,[data[0][3],etadot_0[3]],time) ETA[4] = integrate.odeint(eta5Func,[data[0][4],etadot_0[4]],time) logging.debug('len(result)='+str(len(ETA[0][:,0]))) # restructure ETA using [eta#][time , eta_or_dEta] ) E = [ETA[0][-1,0],\ ETA[1][-1,0],\ ETA[2][-1,0],\ ETA[3][-1,0],\ ETA[4][-1,0]] data.append(E) return data[t]
def integrate(state, N_t=20, T=1., pts=None): """ flow forward integration Points pts are carried along the flow without affecting it """ assert(N) assert(DIM) assert(SIGMA) gaussian.N = N gaussian.DIM = DIM gaussian.SIGMA = SIGMA t_span = np.linspace(0. ,T , N_t ) #print 'forward integration: SIGMA = ' + str(SIGMA) + ', N = ' + str(N) + ', DIM = ' + str(DIM) + ', N_t = ' + str(N_t) + ', T = ' + str(T) if parallel: odef = ode_function else: odef = ode_function_single if pts == None: y_span = odeint( odef , state , t_span) return (t_span, y_span) else: y_span = odeint( odef , np.hstack((state,pts.flatten())) , t_span) return (t_span, y_span[:,0:get_dim_state()], y_span[:,get_dim_state():])
def crystal_embed(e,eta): """ Evaluates crystal embedding potential by solving the one-dimensional Schroedinger equation through one unit cell in both directions. """ y0=[1.0,0.0,0.0,0.0] z1=np.linspace(-z_left,-z_left+alat,101) sol1=odeint(schroed,y0,z1,args=(e,eta)) z2=np.linspace(-z_left+alat,-z_left,101) sol2=odeint(schroed,y0,z2,args=(e,eta)) psi1=complex(sol1[50,0],sol1[50,1]) psi1_prime=complex(sol1[50,2],sol1[50,3]) psi2=complex(sol2[50,0],sol2[50,1]) psi2_prime=complex(sol2[50,2],sol2[50,3]) wronskian=psi1*psi2_prime-psi2*psi1_prime psi1=complex(sol1[100,0],sol1[100,1]) psi2=complex(sol2[100,0],sol2[100,1]) cos_ka=0.5*(psi1+psi2) ka=arccos(cos_ka) if ka.imag<0: ka=np.conj(ka) exp_ka=cos_ka+1.0j*sqrt(1.0-cos_ka**2) emb_cryst=0.5*wronskian/(exp_ka-psi2) if emb_cryst.imag>0.0: exp_ka=cos_ka-1.0j*sqrt(1.0-cos_ka**2) emb_cryst=0.5*wronskian/(exp_ka-psi2) return emb_cryst
def ode_wrapper(fun,x0,tsp): # array of times at which dynamic uncertainty happens tdisc = np.arange(tsp[0],tsp[-1]+DT,DT) # determine (ad hoc) whether the called function takes 2 or 3 args flag_stoch = False try: dy = fun(x0,tsp[0],0.0) flag_stoch = True except TypeError: dy = fun(x0,tsp[0]) flag_stoch = False yt = np.zeros((len(tdisc),len(x0))) y0 = x0.copy() for k in range(len(tdisc)-1): if flag_stoch: # compute the noise v = np.random.normal(scale=q_w) yp = sp.odeint(fun,y0,tdisc[k:k+2],args=(v,)) else: yp = sp.odeint(fun,y0,tdisc[k:k+2]) yt[k,:] = y0.copy() y0 = yp[-1,:].copy() yt[-1,:] = y0.copy() # interpolate in the new history to match the passed-in history tsp ysp = np.zeros((len(tsp),len(x0))) for k in range(len(x0)): ysp[:,k] = np.interp(tsp,tdisc,yt[:,k]) return ysp
def main(): # Load the data data = json.loads(open("problem_2.json").read()) # Make the time array t = np.linspace(0, data["t_f"], 10000) grid_number = data["grid_number"] initial_conditions = [] for i in np.linspace(data["x_ic"][0], data["x_ic"][1], grid_number): for j in np.linspace(data["y_ic"][0], data["y_ic"][1], grid_number): initial_conditions.append([i, j]) solns = [] for i in xrange(0, grid_number**2): solns.append(odeint(SYSTEM, initial_conditions[i], t)) for ic in data["other_ic"]: solns.append(odeint(SYSTEM, ic, t)) x = np.linspace(data["x_ic"][0], data["x_ic"][1], 10000) plt.figure() plt.plot(x, f_1(x), "k") plt.plot(x, f_2(x), "k") for soln in solns: plt.plot(soln[:,0], soln[:,1]) plt.xlabel(r"$x$") plt.ylabel(r"$y$") plt.xlim(data["x_ic"][0], data["x_ic"][1]) plt.ylim(data["y_ic"][0], data["y_ic"][1]) plt.title(r"$\dot{x} = 1 + y - e^{-x}$; $\dot{y} = x^3 - y$") plt.savefig("2_simulation.png", format="png", dpi=300) plt.close() gc.collect()
def computeTrajectories(func, E0=np.zeros(3), **keywords): """Movement of electron and ion under a constant magnetic field. Positional arguments: func -- the name of the function computing dy/dt at time t0 Keyword arguments: E0 -- Constant component of the electric field All other keyword arguments are collected in a 'keywords' dictionary and are specific to each func.""" from scipy.integrate import odeint # Processes the func specific arguments re0, rp0 = "ri" in keywords.keys() and keywords["ri"] or [np.zeros(3),np.zeros(3)] if "vi" in keywords.keys(): # Initial velocity v0 = keywords["vi"] else: v0 = np.array([0,1,0]) wce, wcp = "wc" in keywords.keys() and keywords["wc"] or [0,0] tf = 350; NPts = 10*tf; t = np.linspace(0,tf,NPts) # Time points # Integration of the equations of movement Q0 = np.concatenate((re0,v0)) # Initial values if "wc" in keywords.keys(): keywords["wc"] = wce Qe = odeint(func, Q0, t, args=(-q/me,E0,B0,keywords)) # Trajectory for the "electron" Q0 = np.concatenate((rp0,v0)) # Initial values if "wc" in keywords.keys(): keywords["wc"] = wcp Qp = odeint(func, Q0, t, args=(q/Mp,E0,B0,keywords)) # Trajectory for the "ion" return Qe, Qp
def newton_ang_func(L_val,c2,m): L = L_val slope = (m*(m+1)+c2-L)/(m+1)/2. z0 = [1+step*slope,slope] z = odeint(f,z0,x_ang,args=(c2,L,m)) temp=1-pow(x_ang,2.0) temp=pow(temp,m/2.) zz=temp*z[:,0] first_zz = np.array([1]) zz=np.append(first_zz, zz) sloper = -(m*(m+1)+c2-L)/(m+1)/2. z0r = [1-step*sloper,sloper] zr = odeint(f,z0r,x_angr,args=(c2,L,m)) zzr=temp*zr[:,0] zzr=np.append(first_zz, zzr) return z[:,1][-1]
def draw(self,file=None): """ Trace l'ensemble des lignes de champ passant par les points de départ stockés dans Startpoints. Si un nom de fichier est donné, enregistre la figure dans le fichier mais n'affiche rien à l'écran """ def fun(P,t): B = self.B(P) Bx = B[0] By = B[1] B = np.sqrt(Bx*Bx+By*By) return [Bx/pow(B,4./3.),By/pow(B,4./3.)] t = np.linspace(0,self.k*self.maxint,self.numpoints/2) t2 = - t for P0 in self.startpoints: sol = odeint(fun,P0,t) x = sol[:,0] y = sol[:,1] pl.plot(x,y,'-',color='k') sol = odeint(fun,P0,t2) x = sol[1:,0] y = sol[1:,1] pl.plot(x,y,'-',color='k') pl.arrow(x[1],y[1],x[0]-x[1],y[0]-y[1],color='k') pl.title(self.title) pl.xlim([-self.size,self.size]) pl.ylim([-self.size,self.size]) if file: pl.savefig(file) pl.close() else: pl.show()
def Gate(x,t): global pars xinf = ActivationCurve(V[:,1], pars[0], pars[1]) tau = Kinetic(V[:,1], pars[2], pars[3], pars[4], pars[5]) return (xinf-x)/tau # the following function is the optimisation part of the algorithm. The two chanels are modeled with initial conditions # and the result is compared to the data, taking account the parameter physiological ranges for identificationdef FullTrace(p,time,y): pars = p[0:6] rinit1 = ActivationCurve(V[:,0], pars[0], pars[1]) # initial values r1 = odeint(Gate,rinit1,time) pars = p[7:13] rinit2 = ActivationCurve(V[:,0], pars[0], pars[1]) # initial values r2 = odeint(Gate,rinit2,time) I = p[6]*r1*(V[:,1]-E)+p[13]*r2*(V[:,1]-E) # this plot is to see in real time the reconstructed curves trying to fit the data (very fun) plot(time,y,'b'); hold(True) plot(time,I,'--r');hold(False) draw() # this part is added to constrain the algorithm with physiological search ranges A = 0 for a in arange(len(p)): if p[a] > HB[a] : A = A + (p[a] - HB[a])*1e8 if p[a] < LB[a] : A = A + (LB[a]-p[a])*1e8 return sum(array(y - I)*array(y - I))+A
def modelrun(self): """ Method to integrate a specific size-based model variant. The integration it is done with the module "integrate.odeint", from the library scipy. """ try: if self.Model == "Imm": outarray = odeint(self.sizemodel_imm, self.initcond, self.timedays) return outarray elif self.Model == "TraitDif": outarray = odeint(self.sizemodel_traitdif, self.initcond, self.timedays) return outarray elif self.Model == "FixVar": outarray = odeint(self.sizemodel_fixvar, self.initcond, self.timedays) return outarray elif self.Model == "UnsustVar": outarray = odeint(self.sizemodel_unvar, self.initcond, self.timedays) return outarray elif self.Model == "FullModel": outarray = odeint(self.fullmodel, self.initcond, self.timedays, rtol=1e-12, atol=1e-12) return outarray raise Exception("InputError:", "it is not a valid size model variant. Please specify one model variant " "from: Imm, TraitDif, Fixvar, UnsustVar or FullModel.\n") except Exception as expt: print expt.args[0], self.Model, expt.args[1] raise
def solve_leg_transient(self): """Solves leg based on array of transient BC's.""" self.delta_x = self.x[1] - self.x[0] self.y0 = self.T_x try: self.T_xt except AttributeError: self.odeint_output = odeint( self.get_dTx_dt, y0=self.y0, t=self.t_array, full_output=1 ) self.T_xt = self.odeint_output[0] else: self.y0 = self.T_xt[-1,:] self.odeint_output = odeint( self.get_dTx_dt, y0=self.y0, t=self.t_array, full_output=1 ) self.T_xt = np.concatenate((self.T_xt, self.odeint_output[0]))
def optimalControl(D, A, b, c, x_zv, H, g, t0, t_zv): N = 30 y = np.zeros(len(A)) h = (t_zv - t0) / N tj = [] for i in xrange(1, int(N) + 1): tj.append(t0 + i * h) tt = [t0, t_zv] B0 = odeint(func, x_zv, tt, args=(A, b))[1] tt1 = [t0, tj[0]] y1 = odeint(func1, y, tt1, args=(A, b))[1] temp = odeint(func1, y1, tj, args=(A, b)) B = np.random.random((len(A), int(N))) for i in xrange(int(N)): B[:, i] = temp[int(N) - i - 1] A_new, D_new, G, b_new, c_new, h = prepareQuad(B, B0, D, H, N, c, g) u = cvx.solvers.qp(D_new, c_new, G, h, A_new, b_new)['x'] for i in xrange(0, int(N)): tj[i] -= (t_zv - t0) / N pylab.plot(tj, u) pylab.show()
def runClock(dut, t_start, init_cond): global ts, dt, sig_jit global p0, z0 global t_ab, t_ba alpha = random.normal(0, sig_jit) beta = random.normal(0, sig_jit) print (alpha, beta) t1 = arange(0, t_ab + alpha, dt) t2 = arange(0, t_ba + beta, dt) concatenate((t1, [t_ab + alpha])) # 0 ~ t_ab + jitter concatenate((t2, [t_ba + beta ])) # 0 ~ t_ba + jitter t2 = map(lambda x: x + t1[-1], t2) # 0 ~ t_ab+jitter, t_ab+jitter ~ (t_ab+t_ba+2*jitter) state_half = odeint(dut, init_cond, t1, args=(t_start, p0, z0)) eventAtA(state_half[-1,:]) # comparator / DAC if(t_ba > dt): # when t_ba = 0 sec (NRZ DAC) state_full = odeint(dut, state_half[-1], t2, args=(t_start, p0, z0)) eventAtB(state_full[-1,:]) # DAC (RZ) t = concatenate((t1, t2 )) state = concatenate((state_half, state_full)) else: t = t1 state = state_half return (t, state)
def poly(n,zi,dz,filename): ''' Integrates the L-E equation and returns and writes to a file the important values. n is the index, zi is the interval to use the polynomial solution, dz is the step size, filename is the prefix for the output file (filename+.fits) ''' #set up equation and variables LEeq = LEeqn(n) zs = np.arange(0.,zi,dz) nz = np.size(zs) #integrate over initial interval using polynomial y = intg.odeint(thPN,np.array([1.,0.]),zs) #integrate until th<0 while y[-1,0]>0.: zs2 = np.arange(zs[-1],zs[-1]+200.*dz,dz) zs = np.append(zs,zs2) y = np.append(y,intg.odeint(LEeq,y[-1],zs2),axis=0) #write progress sys.stdout.write("\rz={0},th={1}".format(zs[-1],y[-1,0])) sys.stdout.flush() sys.stdout.write("\n") #only keep values where th>0 ngood= np.size(np.where(y[:,0]>0.)) zs = zs[:ngood] y = y[:ngood] #prepare output array data = np.array([zs,y[:,0],-(zs**2)*y[:,1],(-3./zs)*y[:,1]]) #write and return data fits.writeto(filename+'.fits',data) return data
def test_nonlinear_store(): """ Test the behaviour of the NonLinearStore NonLinearStore should emulate a storage volume with the outflow proportional to the square of the current volume, \frac{dV(t)}{dt} = I(t) = \frac{V(t)^2}{C_q} This test compares the performance of the analytical soltuions in NonLinearStore (from Wilby 1994) with a numerical integration of the above equation. """ from scipy.integrate import odeint def dVdt(V, t, I, Cq): """ RHS of NonLinearStore ODE """ Q = I - V**2/Cq if V <= 0.0: # Volume should not be allowed to go negative. Therefore no net outflow when V <= 0.0 return max(Q, 0.0) return Q C = 0.5 store = NonLinearStore(np.zeros(1), nonlinear_storage_constant=C) I = np.array([10.0]) O = np.empty_like(I) store.step(I, O) # Solve system numerical for the first time-step. Unlike the LinearStore there is no analytical solution given # for the mean outflow. Therefore we can use a single time-step in the numerical integration and average the result # to test against the analytical mean value for the timestep. t = np.linspace(0, 1.0, 2.0) V = odeint(dVdt, 0.0, t, args=(I, C)) # Test mean outflow np.testing.assert_allclose(np.mean(V**2/C), O, rtol=1e-3) # and end of time-step outflow. np.testing.assert_allclose(V[-1]**2/C, np.array(store.previous_outflow), rtol=1e-3) # And repeat for a second step ... store.step(I, O) V = odeint(dVdt, V[-1], t+1.0, args=(I, C)) # Test mean outflow np.testing.assert_allclose(np.mean(V**2/C), O, rtol=1e-3) # and end of time-step outflow. np.testing.assert_allclose(V[-1]**2/C, np.array(store.previous_outflow), rtol=1e-3) # And repeat for a third step with zero inflow I = np.array([0.0]) store.step(I, O) V = odeint(dVdt, V[-1], t+1.0, args=(I, C)) # Test mean outflow np.testing.assert_allclose(np.mean(V**2/C), O, rtol=1e-3) # and end of time-step outflow. np.testing.assert_allclose(V[-1]**2/C, np.array(store.previous_outflow), rtol=1e-3) # And repeat for a fourth step with -ve inflow I = np.array([-1.0]) store.step(I, O) V = odeint(dVdt, V[-1], t+1.0, args=(I, C)) # Test mean outflow np.testing.assert_allclose(np.mean(V**2/C), O, rtol=1e-3) # and end of time-step outflow. np.testing.assert_allclose(V[-1]**2/C, np.array(store.previous_outflow), rtol=1e-3, atol=1e-10)
def numerical_equilibrium(self): res = self.deterministic() f = lambdify(res.keys(), res.values()) g = lambda y, t: f(*y) r = odeint(g, y0=np.ones(len(res.keys())), t=[0.0, 1e6])[-1] r = odeint(g, y0=r, t=[0.0, 1e6])[-1] return dict(zip(res.keys(), r))
def integrate(self): atol=1.49012e-8 rtol=1.49012e-8 if len(self.dvar)==0: raise sodeError, "No equations defined." if 't' not in self.parval.keys(): raise sodeError, "Integration time limit 't' is undefined." #TODO: implement adaptive grid t = np.linspace(0,self.parval['t'], 10) # initial t.sort() # sort in case t value was negative dx = self.getdx() parvals = map(lambda v: eval(self.rhs[v], dict(math.__dict__.items() + self.parval.items())), self.dvar) x = odeint(dx, parvals, t,atol=atol,rtol=rtol) # integrate ODEs if np.isnan(x).sum(): raise NameError, "Integration failed" # check for NANs in output D0 = 0 # curve length from previous iteration refine = True # flag to refine grid npadd = 2 print "\n\nStart grid refinement" iref=0 # iteration counter while t.shape[0]<10000 and refine: # limit number of grid points iref += 1 ds = map(lambda i: np.linalg.norm(x[i+1,:] - x[i,:]), range(x.shape[0]-1)) # curve segments lengths D = sum(ds) # curve length if (D == 0): break # stationary point? dmax = max(ds) # max segment length # C = x.mean(0) # curve center # rs = map(lambda i: np.linalg.norm(x[i,:] - C), range(x.shape[0])) # curve points distance from center # S = max(rs) # curve radius print "\nGrid points count: %d"%t.shape[0] print "Track length: %f"%D print "Track length change: %.1f%%"%((1-D0/D)*100) print "Max segment length: %f"%max(ds) # print "Track size: %f"%S refine = False for i in xrange(0,t.shape[0]-1): a=x[i+1,:]-x[i,:] b=dx(x[i,:], t[i])*(t[i+1]-t[i]) d = np.linalg.norm(a-b)/np.linalg.norm(a) if d > 1e-1 and np.abs((a / (atol + rtol*x[i]))).max() > 1: t.resize((t.shape[0]+npadd)) t[-npadd:] = np.linspace(t[i],t[i+1],npadd+2)[1:-1] # t.resize((t.shape[0]+1)) # t[-1] = (t[i]+t[i+1])/2 # print "refine at %f (%e,%f)"%(t[-1], np.linalg.norm(b-a), d) refine = True if not refine and abs((D-D0)/D) > 5e-2: l=t.shape[0] t.resize((2*l-1)) t[-l+1:] = (t[1:l] +t[:l-1])/2 refine = True D0 = D t.sort() x = odeint(dx, parvals, t, atol=atol,rtol=rtol) print "New grid points count: %d"%t.shape[0] if not refine: print "Grid is fine", else: print "Grid points limit reached", print " after %d iterations"%iref self.t = t self.tracks = x self.tracks2dict()
def solveequation(params,times,Cai): timepoints = np.where(times == 0) yinitial = initialConditions(params,Cai) yinitial.append(0) yinitial.append(0) Ca = 5e-6 k_1 = params[1] k2 = params[2] k_2 = params[3] ksr = params[4] krr=params[5] Kd=params[6] rmax=params[7] k1=(rmax*Ca)/(Ca+Kd) Caa=params[8] CaS=params[9] CaF=params[0] CaFa = params[10] CaFS = params[11] CaFF = params[12] def f(yinitial,times): A = yinitial[0] B = yinitial[1] C = yinitial[2] D = yinitial[3] E = yinitial[4] dA = -k1*CaFa*Ca**Caa*A + k_1*B dB = -(k_1+CaFS*Ca**CaS*ksr+k2)*B+A*k1*CaFa*Ca**Caa+C*k_2 dC = -(krr*CaFa*Ca**CaF+k_2)*C + B*k2 dD = B*ksr*CaFS*Ca**CaS dE = C*krr*CaFF*Ca**CaF return [dA,dB,dC,dD,dE] out = np.array(odeint(f,yinitial,times[timepoints[0][0]:timepoints[0][1]])) output = out[:,3]+out[:,4] Ca = 10e-6; k1 =(rmax*Ca)/(Ca+Kd) out = np.array(odeint(f,yinitial,times[timepoints[0][1]:timepoints[0][2]])) output = np.append(output,(out[:,3]+out[:,4])) Ca = 30e-6; k1 =(rmax*Ca)/(Ca+Kd) out = np.array(odeint(f,yinitial,times[timepoints[0][2]:timepoints[0][3]])) output = np.append(output,(out[:,3]+out[:,4])) Ca = 100e-6; k1 =(rmax*Ca)/(Ca+Kd) out = np.array(odeint(f,yinitial,times[timepoints[0][3]:])) output = np.append(output,(out[:,3]+out[:,4])) return output
def test(): theta = [2., 4.] theta1 = [2., 20.] t = np.arange(0, 5, 0.1) X0 = 1. X = integrate.odeint(gene_reg, X0, t, args=(theta,)) X1 = integrate.odeint(gene_reg_simple, X0, t, args=(theta1,)) plt.plot(t, X, 'r-') plt.show()
def trajectories(Q0, QbyM, tf): """Computes the electron and proton trajectories""" NPts = 5*tf; t = np.linspace(0,tf,NPts) # Integration of the equations of movement Qe = odeint(EqMovement, Q0, t, args=(QbyM[0],)) Qp = odeint(EqMovement, Q0, t, args=(QbyM[1],)) return Qe, Qp
def devFromInput(x, mh, vev, model): """ Given x=[mu12,lam1] at input scale, compute next iteration of these parameters using the Coleman-Weinberg potential. """ #mu12, mu22, l1, l2, l3, l4, l5 = x mu12, l1 = x v = vev # Modify RGE initial conditions y0 = model.y0 y0[6] = l1 y0[8] = mu12 # update the input values stored in the model object! model.y0 = y0 inputScale = np.sqrt(model.inputRgScaleSq) # Integrate RGEs to mu=v tmin = 0; tmax = np.log(v/inputScale) tvev = np.log(v/inputScale) ti = np.array([0., tvev]) model.rgsys.twoLoop = True y_at_t = integrate.odeint(model.rgsys.f,y0,ti) # y_at_t: [0] initial, [1] at vev y_at_v = y_at_t[1] # Update the potential parameters, compute v and mh model.renormScaleSq = v**2. g1,g2,g3,yt,yb,ytau,l1,Zh,mu12 = y_at_v model.setPara(l1,mu12) model.setGauge(g1,g2,g3) model.setYukawa(yt,yb,ytau) model.setFieldRenorm(Zh) Vlp = model.gradV([v],T=0.)[0] - mu12*v - l1*v**3 Vl2p = model.d2V([v],T=0)[0,0] - mu12 - 3.*l1*v**2 l1New = (mh**2 + Vlp/v - Vl2p)/(2.*v**2) mu12New = - l1New*v**2 - Vlp/v # RG evolve back to input scale y_at_v[6] = l1New y_at_v[8] = mu12New ti_reverse = ti[::-1] y_at_t = integrate.odeint(model.rgsys.f,y_at_v,ti_reverse) l1New = y_at_t[1][6] mu12New = y_at_t[1][8] return [mu12New,l1New]
def lsim2(system, U=None, T=None, X0=None, **kwargs): """ Simulate output of a continuous-time linear system, by using the ODE solver `scipy.integrate.odeint`. Parameters ---------- system : an instance of the LTI class or a tuple describing the system. The following gives the number of elements in the tuple and the interpretation: * 2: (num, den) * 3: (zeros, poles, gain) * 4: (A, B, C, D) U : array_like (1D or 2D), optional An input array describing the input at each time T. Linear interpolation is used between given times. If there are multiple inputs, then each column of the rank-2 array represents an input. If U is not given, the input is assumed to be zero. T : array_like (1D or 2D), optional The time steps at which the input is defined and at which the output is desired. The default is 101 evenly spaced points on the interval [0,10.0]. X0 : array_like (1D), optional The initial condition of the state vector. If `X0` is not given, the initial conditions are assumed to be 0. kwargs : dict Additional keyword arguments are passed on to the function odeint. See the notes below for more details. Returns ------- T : 1D ndarray The time values for the output. yout : ndarray The response of the system. xout : ndarray The time-evolution of the state-vector. Notes ----- This function uses :func:`scipy.integrate.odeint` to solve the system's differential equations. Additional keyword arguments given to `lsim2` are passed on to `odeint`. See the documentation for :func:`scipy.integrate.odeint` for the full list of arguments. """ if isinstance(system, lti): sys = system else: sys = lti(*system) if X0 is None: X0 = zeros(sys.B.shape[0], sys.A.dtype) if T is None: # XXX T should really be a required argument, but U was # changed from a required positional argument to a keyword, # and T is after U in the argument list. So we either: change # the API and move T in front of U; check here for T being # None and raise an excpetion; or assign a default value to T # here. This code implements the latter. T = linspace(0, 10.0, 101) T = atleast_1d(T) if len(T.shape) != 1: raise ValueError("T must be a rank-1 array.") if U is not None: U = atleast_1d(U) if len(U.shape) == 1: U = U.reshape(-1, 1) sU = U.shape if sU[0] != len(T): raise ValueError("U must have the same number of rows " "as elements in T.") if sU[1] != sys.inputs: raise ValueError("The number of inputs in U (%d) is not " "compatible with the number of system " "inputs (%d)" % (sU[1], sys.inputs)) # Create a callable that uses linear interpolation to # calculate the input at any time. ufunc = interpolate.interp1d(T, U, kind='linear', axis=0, bounds_error=False) def fprime(x, t, sys, ufunc): """The vector field of the linear system.""" return dot(sys.A, x) + squeeze(dot(sys.B, nan_to_num(ufunc([t])))) xout = integrate.odeint(fprime, X0, T, args=(sys, ufunc), **kwargs) yout = dot(sys.C, transpose(xout)) + dot(sys.D, transpose(U)) else: def fprime(x, t, sys): """The vector field of the linear system.""" return dot(sys.A, x) xout = integrate.odeint(fprime, X0, T, args=(sys, ), **kwargs) yout = dot(sys.C, transpose(xout)) return T, squeeze(transpose(yout)), xout
def calcul(Yinit, t1, t2, TabConst): """Calcule l'evolution des variables entre t1 et t2 à partir de la config Yinit""" T = linspace(t1, t2, floor((t2 - t1) * ptsperh)) return T, odeint(eqs, Yinit, T, args=(TabConst, 0))
# ODE solver parameters abserr = 1.0e-8 relerr = 1.0e-6 stoptime = 10.0 numpoints = 1001 # Create the time samples for the output of the ODE solver. t = np.linspace(0, stoptime, numpoints) # Pack up the parameters and initial conditions: p = [m, kp, kd, L, StartTime, Umax] x0 = [x_init, x_dot_init] # Call the ODE solver. resp = odeint(eq_of_motion, x0, t, args=(p, ), atol=abserr, rtol=relerr) #----- Plot the response # Many of these setting could also be made default by the .matplotlibrc file fig = figure(figsize=(6, 4)) ax = gca() subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96) setp(ax.get_ymajorticklabels(), fontsize=18) setp(ax.get_xmajorticklabels(), fontsize=18) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.grid(True, linestyle=':', color='0.75') ax.set_axisbelow(True)
R_0 = 0 # R_0为治愈者的初始人数 S_0 = N - I_0 - R_0 # S_0为易感者的初始人数 T = 150 # T为传播时间 # INI为初始状态下的数组 INI = (S_0, I_0, R_0) def funcSIR(inivalue, _): Y = np.zeros(3) X = inivalue # 易感个体变化 Y[0] = - (beta * X[0] * X[1]) / N # 感染个体变化 Y[1] = (beta * X[0] * X[1]) / N - gamma * X[1] # 治愈个体变化 Y[2] = gamma * X[1] return Y T_range = np.arange(0, T + 1) RES = spi.odeint(funcSIR, INI, T_range) plt.plot(RES[:, 0], color='darkblue', label='Susceptible', marker='.') plt.plot(RES[:, 1], color='red', label='Infection', marker='.') plt.plot(RES[:, 2], color='green', label='Recovery', marker='.') plt.title('SIR Model') plt.legend() plt.xlabel('Day') plt.ylabel('Number') plt.show()
plt.legend() plt.xlim(left=0.0, right=0.02) plt.ylim(top=1.6, bottom=0.6) plt.xlabel('k1_inv') plt.ylabel('k2') plt.savefig('two_parameter.png') # plt.show() # numerical solution k1_inv_val = 0.01 k2_val_numerical = 1.0 initial = [0.2, 0.3] dt = 0.1 t_max = 4000 t = np.linspace(0, t_max, int(t_max / dt)) sol = odeint(equation, initial, t) fig = plt.figure(figsize=(20, 10)) plt.plot(t, sol[:, 0], color='black', label='x') plt.plot(t, sol[:, 1], color='black', linestyle='--', label='y') plt.legend() plt.xlabel('t') plt.savefig('numerical.png') additional_solutions = [] additional_initial = [(0.5, 0.15), (0.5, 0.4)] for init in additional_initial: sol_add = odeint(equation, init, t) additional_solutions.append(sol_add) sol_end = odeint(equation, [sol[len(t) - 1, 0], sol[len(t) - 1, 1]], t)
def mwg_ode(self, n_samples, Y_t, start_ind, tmin, tmax, n_eval, w_mat, x0, theta0, theta_true, theta_sd, gamma, rwsd, accept=False): # Get problem dimensions and initialization n_theta = len(theta0) theta_curr = theta0.copy() theta_prop = theta0.copy() paccept = np.zeros(n_theta, dtype=int) Theta = np.zeros((n_samples, n_theta)) n_obs = len(Y_t) n_skip = n_eval // n_obs # MCMC process old_state1 = self._n_state1 old_state2 = self._n_state2 self._n_state1 = 1 self._n_state2 = 1 tseq = np.linspace(tmin, tmax, n_eval + 1) X_curr = odeint(self._fitz, x0, tseq, args=(theta_curr, ))[start_ind::n_skip] lp_curr = self._logprior(Y_t, X_curr, gamma, theta_curr, theta_true, theta_sd) for i in range(n_samples): for j in range(n_theta): theta_prop[j] += rwsd[j] * np.random.randn() if theta_prop[j] > 0: X_prop = odeint(self._fitz, x0, tseq, args=(theta_prop, ))[start_ind::n_skip] lp_prop = self._logprior(Y_t, X_prop, gamma, theta_prop, theta_true, theta_sd) lacc = lp_prop - lp_curr if lacc > 0 or np.random.uniform() < np.exp(lacc): theta_curr[j] = theta_prop[j] lp_curr = lp_prop paccept[j] = paccept[j] + 1 else: theta_prop[j] = theta_curr[j] else: theta_prop[j] = theta_curr[j] # storage Theta[i] = theta_curr self._n_state1 = old_state1 self._n_state2 = old_state2 # output if not accept: return Theta else: paccept = paccept / n_samples return Theta, paccept
ter_1 = np.sqrt((A * a**(3 * n + 3.) + B)**(1. / (1 + n)) - 3 * K * a) dadt = ter_1 / np.sqrt(3. * a) return dadt ######### parameters n = 0.05 ### the alpha A = 1 / 3. K = 0. a0 = 1. ####### constant of integration B = np.array([0., 0.6, 1.8, 2.5, 5.0]) labels = ["B=0.0", "B=0.6", "B=1.8", "B=2.5", "B=5.0"] ####### time t = np.linspace(0., 21, 201) for i in range(len(B)): sol1 = odeint(GCG, a0, t, args=(A, B[i], 0.)) plt.plot(t, sol1, label=labels[i]) plt.legend(loc="upper left") plt.xlabel('time ($t$)') plt.ylabel('scale factor ($a$)') plt.grid() plt.title(r'Varying $B$') axes = plt.gca() plt.show()
def solve_mean_field_first_order( Model, DYN_SYSTEM={ 'RecExc': { 'aff_pops': ['AffExc'], 'x0': 1. }, 'RecInh': { 'aff_pops': ['AffExc'], 'x0': 1. } }, dt=0.1, tstop=100., INPUTS={ 'AffExc_RecExc': np.ones(1000), 'AffExc_RecInh': np.ones(1000) }, T=5e-3, replace_x0=False, verbose=False): """ if replace_x0 -> then you can directly use get_stat_props """ DYN_KEYS = [key for key in DYN_SYSTEM.keys() ] # for a quick access to the dynamical system variables # initialize neuronal and synaptic params for key in DYN_KEYS: DYN_SYSTEM[key]['nrn_params'] = built_up_neuron_params(Model, key) DYN_SYSTEM[key]['syn_input'] = build_up_afferent_synaptic_input(Model,\ DYN_KEYS+DYN_SYSTEM[key]['aff_pops'], key, verbose=verbose) # --- CONSTRUCT THE DIFFERENTIAL OPERATOR --- # def dX_dt(X, t, dt, DYN_KEYS, DYN_SYSTEM, INPUTS): dX_dt, RATES = [], {} # we fill the X-defined recurent act: for x, key in zip(X, DYN_KEYS): RATES['F_' + key] = x # then we compute it, key by key for i, key in enumerate(DYN_KEYS): for aff_key in DYN_SYSTEM[key]['aff_pops']: RATES['F_'+aff_key] = INPUTS[aff_key+'_'+key][\ min([int(t/dt), len(INPUTS[aff_key+'_'+key])-1]) ] Fout = input_output(DYN_SYSTEM[key]['nrn_params'], DYN_SYSTEM[key]['syn_input'], RATES, Model['COEFFS_' + key]) dX_dt.append((Fout - X[i]) / T) # Simple one-dimensional framework return dX_dt # ------------------------------------------- # # starting point X0 = [] for key in DYN_KEYS: X0.append(DYN_SYSTEM[key]['x0']) X = odeint(dX_dt, X0, np.arange(int(tstop / dt)) * dt, args=(dt, DYN_KEYS, DYN_SYSTEM, INPUTS)) output = {} for key, x in zip(DYN_KEYS, X.T): output[key] = x if replace_x0: DYN_SYSTEM[key]['x0'] = x[-1] return output
y_0 = np.array([t0, r0, theta0, phi0, p_r0, p_theta0]) # these are functions of _0: # angular momentum (= r * p^phi) b = p_phi # energy at infinity #E = 0.973101 E = energy(y_0, a, b) # Carter's constant _q = q(theta0, p_theta0, a, E, b) zeta = np.linspace(0, T, nt + 1) orbit = np.zeros((nt + 1, 6)) orbit = spi.odeint(deriv, y_0, zeta, (a, E, b, _q), atol=1e-10) t = orbit[:, 0] r = orbit[:, 1] theta = orbit[:, 2] phi = orbit[:, 3] pr = orbit[:, 4] ptheta = orbit[:, 5] orbit_x = np.sqrt(r**2 + a * a) * \ np.sin(theta) * np.cos(phi) orbit_y = np.sqrt(r**2 + a * a) * \ np.sin(theta) * np.sin(phi) orbit_z = r * np.cos(theta) imaxs = maxima(pr)
def run_oscil(x0,T,p): t = np.linspace(0, T, 1000) dxdt = lambda x,t : f(x, t, p) x_t = integrate.odeint(dxdt, x0, t) return(t,x_t)
plt.xlabel('Vrijeme (s)') plt.ylabel('Kut (Radijani)') plt.legend(['Nelinearno', 'Linearno'], loc='top right') plt.show() Egp = m * g * l T = 2 * np.pi * (np.sqrt(l / g)) print(T) #Graf time = np.arange(0, 10, 0.025) x0 = np.radians(0.0) theta1 = odeint(formule, [theta0, x0], time) w = np.sqrt(g / l) theta2 = [theta0 * np.cos(w * t) for t in time] running = True t = 0 dt = 0.025 n = int(input("Koliko kuglica želiš pomaknuti? ")) pygame.init() screen = pygame.display.set_mode((Xsize, Ysize)) dx = 80 for i in range(n):
) #set joint torques to zero for first simulation numerical_specified = zeros(3) # numerical_specified[0] = 0.1 #changing this value will add constant torque to joint args = {'constants': numerical_constants, 'specified': numerical_specified} frames_per_sec = 60 final_time = 3 t = linspace(0.0, final_time, final_time * frames_per_sec) #integrate equations of motion right_hand_side(x0, 0.0, numerical_specified, numerical_constants) #create variable to store trajectories of states as func of time y = odeint(right_hand_side, x0, t, args=(numerical_specified, numerical_constants)) #plot trajectory of each joint # fig = plt.figure(1) # ax = fig.add_subplot() # plt.plot(t, rad2deg(y[:, :3])) #generalized positions-first 3 states # plt.draw() # plt.pause(30) #visualization ---------------------------------------------------------------- #print(pydy.shapes.__all__) #draw spheres at each joint j0_shape = Sphere(color='black', radius=0.025) j1_shape = Sphere(color='black', radius=0.025)
E = sig(JEE * sEE - JEI * sEI + iE) # stim here makes E less like integrator under long stim I = sig(JIE * sIE - JII * sII) dEE = (-sEE + E) / tEE dIE = (-sIE + E) / tIE dEI = (-sEI + I) / tEI dII = (-sII + I) / tII diE = (-iE + JO * stim(t)) / tO return [dEE, dEI, dIE, dII, diE] #%% stim by external y0 = [.5, .5, .5, .5, 0] t = numpy.arange(1000) for JO in [-200, 200, 2e3, 2e4, 2e5, 2e9, 2e12]: y = odeint(NDF, y0, t, tfirst=True) sEE, sEI, sIE, sII, iE = y[:, 0], y[:, 1], y[:, 2], y[:, 3], y[:, 4] E = sig(JEE * sEE - JEI * sEI + iE) pyplot.plot(E) #%% stim by initial value JO = 0 t = numpy.arange(1000) for E0 in [-0.005, 0.005, 0.01, 0.02, 0.04]: y0 = [E0 + 0.5, E0 + 0.5, .5, .5, 0] y = odeint(NDF, y0, t, tfirst=True) sEE, sEI, sIE, sII, iE = y[:, 0], y[:, 1], y[:, 2], y[:, 3], y[:, 4] E = sig(JEE * sEE - JEI * sEI + iE) pyplot.plot(E) #%% iE = y[:, 4]
x30 = 0 v_x30 = 5000 y30 = 5*149 * 10**9 v_y30 = 0 s0 = (x10, v_x10, y10, v_y10, x20, v_x20, y20, v_y20, x30, v_x30, y30, v_y30) m1 = 2.10777 * 10**30 m2 = 1.193 * 10**30 m3 = 0.596 *10**30 G = 6.67 * 10**(-11) sol = odeint(move_func, s0, t) fig = plt.figure() bodys = [] for i in range (0, len(t), 1): body1, = plt.plot(sol[:i,0], sol[:i,2], '-', color='r') body1_line, = plt.plot(sol[i, 0], sol[i,2], 'o', color='r') body2, = plt.plot(sol[:i,4], sol[:i,6], '-', color='g') body2_line, = plt.plot(sol[i, 4], sol[i,6], 'o', color='g') body3, = plt.plot(sol[:i,8], sol[:i,10], '-', color='b') body3_line, = plt.plot(sol[i, 8], sol[i,10], 'o', color='b') bodys.append([body1, body1_line, body2, body2_line, body3, body3_line])
def CancerSim(y, t, rN, rT, Kn, Kt, aNT, aTN): Nn = y[0] Nt = y[1] dNndt = rN * (1 - ((Nn + aNT * Nt) / Kn)) * Nn dNtdt = rT * (1 - ((Nt + aTN * Nn) / Kt)) * Nt return [dNndt, dNtdt] params2 = (0.5, 0.5, 10, 10, 0.5, 2) params3 = (0.5, 0.5, 10, 10, 0.5, 0.5) params4 = (0.5, 0.5, 10, 10, 2, 0.5) N0 = [0.01, 0.01] times = range(0, 500) modelSim2 = spint.odeint(func=CancerSim, y0=N0, t=times, args=params2) modelOutput2 = pandas.DataFrame({ "t": times, "Nn": modelSim2[:, 0], "Nt": modelSim2[:, 1] }) g2 = ggplot(modelOutput2, aes(x="t")) g2 = g + geom_line(aes(y="Nn")) g2 = g + geom_line(aes(y="Nt")) g2
numberOfAngles = 10 fangle = p.figure() p.title("Forcing angle") for angleIndex in range(numberOfAngles): leaderLocation = array([2*cos(angleIndex*2*pi/numberOfAngles),2*sin(angleIndex*2*pi/numberOfAngles)]) print "leaderLocation", leaderLocation X0 = array([0,0,0,leaderLocation[0],leaderLocation[1],0]) f = f1(X0) print "control input", f[2] p.plot(array([angleIndex*2*pi/numberOfAngles*180/pi]), array([f[2]]),"bo") # p.show() # Integrate the system. X0 = array([0,0,0,5,10,0]) t = linspace(0,runTime,200) X, infodict = integrate.odeint(f1, X0, t, full_output=True) print infodict['message'] print "leader locations", X[:,0:1] # Plot the trajectories. f1 = p.figure() for ind in range(0,N): p.plot(X[:,3*ind],X[:,3*ind+1],'-rx', label=str(ind)) p.grid() p.legend(loc="best") p.xlabel('x') p.ylabel('y') # p.xlim([0,.5]) # p.ylim([0,.5]) p.title('Trajectory of agents.')
t = np.linspace(0, 60, 60) # The SIR model differential equations. def deriv(y, t, N, beta, gamma): S, I, R = y dSdt = -beta * S * I / N dIdt = beta * S * I / N - gamma * I dRdt = gamma * I return dSdt, dIdt, dRdt # Initial conditions vector y0 = S0, I0, R0 # Integrate the SIR equations over the time grid, t. ret = odeint(deriv, y0, t, args=(N, beta, gamma)) S, I, R = ret.T # Plot the data on three separate curves for S(t), I(t) and R(t) fig = plt.figure(facecolor='w') ax = fig.add_subplot(111, axisbelow=True) ax.plot(t, S / 1000, 'b', alpha=0.5, lw=2, label='Susceptible') ax.plot(t, I / 1000, 'r', alpha=0.5, lw=2, label='Infected') ax.plot(t, R / 1000, 'g', alpha=0.5, lw=2, label='Recovered with immunity') ax.set_xlabel('Time /days') ax.set_ylabel('Number (1000s)') ax.set_ylim(0, 1.2) ax.yaxis.set_tick_params(length=0) ax.xaxis.set_tick_params(length=0) ax.grid(b=True, which='major', c='w', lw=2, ls='-') legend = ax.legend()
sigma = 5.67e-8 Ta = 23 Cp = 500 m = 0.004 TaK = Ta + 273.15 def labsim(TC, t): TK = TC + 273.15 dTCdt = (U * A * (Ta - TC) + sigma * eps * A * (TaK**4 - TK**4) + alpha * 50) / (m * Cp) return dTCdt tm = np.linspace(0, n, n + 1) # Time values Tsim = odeint(labsim, 23, tm) # calculate losses from conv and rad conv = U * A * (Ta - Tsim) rad = sigma * eps * A * (TaK**4 - (Tsim + 273.15)**4) loss = conv + rad gain = alpha * 50 # Plot results plt.figure() plt.subplot(2, 1, 1) plt.plot(tm, Tsim, 'b-', label='Simulated') if connected: plt.plot(tm, T1, 'r.', label='Measured') plt.ylabel(r'Temperature ($^oC$)') plt.legend()
def model(y, t): w = 2 * math.pi * 60 Vrms = 120 L = 0.006 dydt = (heaviside(t) * (2**0.5) * Vrms * math.cos(w * t)) * (1/L) - y*(0.05/L) return dydt # initial condition y0 = 5 # time points t = np.linspace(0,20) # solve ODE y = odeint(model,y0,t) # plot results plt.plot(t,y) plt.xlabel('t') plt.ylabel('y(t)') plt.show() ## --------------------- # Multiple graphs # def f(s,t): # a = 4 # b = 7
def value(c_var, dspan, vreme, vreme_c, Lambda, mu_val, broj_mesta, g_function, Cc): Out = odeint(model, var_init, dspan, args = (vreme_c, vreme, c_var, Lambda, mu_val, broj_mesta)) function = [function_evaluate(g_function, Out[i,:], Cc, c_var, vreme_c, self.time_control[i]) for i in range(len(self.time_control))] return function, Out
# Function that evaluates the RHS of the ODE. It has two components, # representing the changes in prey and predator populations. def f(y, t): return np.array([alpha1*y[0]-beta1*y[0]*y[1], \ -alpha2*y[1]+beta2*y[0]*y[1]]) # Specify the range of time values where the ODE should be solved at time = np.linspace(0, 70, 500) # Initial conditions, set to the initial populations of prey and predators yinit = np.array([10, 5]) # Solve ODE using the "odeint" library in SciPy y = odeint(f, yinit, time) # Print the solutions #for i in range(0,500): # print(time[i],x[i,0],x[i,1]) # Plot the solutions plt.figure() p0, = plt.plot(time, y[:, 0]) p1, = plt.plot(time, y[:, 1]) plt.legend([p0, p1], ["Prey", "Predators"]) plt.xlabel('t') plt.ylabel('Population') plt.show()
def fit_odeint(x, beta, gamma): return integrate.odeint(SIR_model_t, SIR0, t, args=(beta, gamma))[:, 1]
llg.alpha=0.1 llg.H_app=(0,0,0) llg.A = 1.3e-11 llg.D = 4e-3 #llg.set_m(( # 'MS * (2*x[0]/L - 1)', # 'sqrt(MS*MS - MS*MS*(2*x[0]/L - 1)*(2*x[0]/L - 1))', # '0'), L=length, MS=llg.Ms) llg.set_m(( 'MS', '0', '0'), MS=llg.Ms) llg.setup(use_dmi=True,use_exchange=True) llg.pins = [] print "point 0:",mesh.coordinates()[0] print "Solving problem..." y = llg.m[:] y.shape=(3,len(llg.m)/3) ts = numpy.linspace(0, 7e-10, 1000) tol = 1e-4 for i in range(len(ts)-1): print i ys,infodict = odeint(llg.solve_for, llg.m, [ts[i],ts[i+1]], full_output=True,printmessg=True,rtol=tol,atol=tol) df.plot(llg._m) df.interactive() print "Done"
import numpy as np def CG(a, t, A, B): dadt = np.sqrt(np.sqrt(A * a**6 + B)) / np.sqrt(3. * a) return dadt A = 1. / 3 B = 0.3 a0 = 0.1 t = np.linspace(0, 16, 101) from scipy.integrate import odeint sol1 = odeint(CG, a0, t, args=(A, B)) import matplotlib.pyplot as plt def d1(a): den = np.sqrt(B / a**6. + A) return den plt.plot(t, d1(sol1[:])) plt.xlabel(r'time ($t$)') plt.ylabel(r'density ($\rho$)') plt.legend() #plt.grid()
def simulate_wt_experiment(inits, total_protein, sig, learned_params, time): odes = odeint(model, inits, time, args=(total_protein, sig, learned_params)) return odes
def pooled_plotter_data_model(k=[],save = False): if k == []: k = np.loadtxt('data/pooled_param_drug_cpt11.txt') # print(k) tot_dose = pk.CPT11_tot_dose pat_cp_data = pk.CPT11 pat_sn_data = pk.SN38 vol = pk.vol data_time = pk.CPT11_time pat_range = pk.pat_nums_cpt Title_str = 'CPT11' tmax = 36 x0 = [0]*9 a = int(np.ceil(len(pat_range)/2)) fig0, ax0 = plt.subplots(2,int(np.ceil(len(pat_range)/2)),sharex = True, sharey = True) # fig0.suptitle('CPT11 model vs data') fig1, ax1 = plt.subplots(2,int(np.ceil(len(pat_range)/2)),sharex = True, sharey = True) # fig1.suptitle('SN38 model vs data') plt.setp(ax0, xticks=np.arange(0,tmax+1,12),xticklabels = [24,12,24,12]) plt.setp(ax1, xticks=np.arange(0,tmax+1,12),xticklabels = [24,12,24,12]) cmax_cp = [None]*len(pat_range) cmax_sn = [None]*len(pat_range) cmax_cp_time = [None]*len(pat_range) cmax_sn_time = [None]*len(pat_range) cost = [None]*len(pat_range) SS_tot = [None]*len(pat_range) SS_res = [None]*len(pat_range) for i in pat_range: tspan = data_time[i] t = np.sort(list(np.linspace(0.1,36,1000))+list(tspan)) t = np.sort(list(set(t))) pos = np.where(np.in1d(t,tspan))[0] x = odeint(non_phys_ode_CPT,x0,t,(k,tot_dose[i],vol[i]),hmax=1) x = np.multiply(1000,x) ax0[int(np.floor(i/a)),i%a].plot(t,x[:,2],'k--') ax0[int(np.floor(i/a)),i%a].plot(tspan,np.multiply(1000,pat_cp_data[i]),'.',color='0.4',mew=2) ax0[int(np.floor(i/a)),i%a].spines['right'].set_visible(False) ax0[int(np.floor(i/a)),i%a].spines['top'].set_visible(False) ax0[int(np.floor(i/a)),i%a].text(24,1.2,'('+str(pat_range[i]+1)+')') ax1[int(np.floor(i/a)),i%a].plot(t,x[:,3],'k--') ax1[int(np.floor(i/a)),i%a].plot(tspan,np.multiply(1000,pat_sn_data[i]),'.',color='0.4',mew=2) ax1[int(np.floor(i/a)),i%a].spines['right'].set_visible(False) ax1[int(np.floor(i/a)),i%a].spines['top'].set_visible(False) ax1[int(np.floor(i/a)),i%a].text(24,0.03,'('+str(pat_range[i]+1)+')') plt.setp( ax0[int(np.floor(i/a)),i%a].xaxis.get_majorticklabels(), rotation=90 ) plt.setp( ax1[int(np.floor(i/a)),i%a].xaxis.get_majorticklabels(), rotation=90 ) D_cp = np.multiply(1000,pat_cp_data[i]) D_sn = np.multiply(1000,pat_sn_data[i]) cmax_cp[i] = np.max(x[:,2]) cmax_sn[i] = np.max(x[:,3]) cmax_cp_time[i] = t[np.argmax(x[:,2])] cmax_sn_time[i] = t[np.argmax(x[:,3])] M_cp = x[pos,2] M_sn = x[pos,3] cost[i] = np.nansum(np.square((M_cp - D_cp)/(2.19317759e-02)) + np.square((M_sn - D_sn)/(6.81021571e-04))) SS_tot = np.nansum((D_cp - np.nanmean(D_cp))**2) + np.nansum((D_sn - np.nanmean(D_sn))**2) SS_res = np.nansum(np.square((M_cp - D_cp))) + np.nansum(np.square((M_sn - D_sn))) Cost = np.sum(cost) r2 = 1 - np.sum(SS_res)/np.sum(SS_tot) if int(np.floor(len(pat_range)/2))%2 != 0: fig0.delaxes(ax0[-1,-1]) fig1.delaxes(ax1[-1,-1]) ax0[int(np.floor(i/a)),i%a].legend(labels=['model','data'],bbox_to_anchor=(1.3,1)) fig0.text(0.5,-0.05,'Time (h)',ha='right') fig0.text(0.05,0.65,'Concentration (ng/ml)',ha='right',rotation='vertical') ax1[int(np.floor(i/a)),i%a].legend(labels=['model','data'],bbox_to_anchor=(2.9,1)) fig1.text(0.5,-0.05,'Time (h)',ha='right') fig1.text(0.05,0.65,'Concentration (ng/ml)',ha='right',rotation='vertical') plt.setp(ax0,ylim=[0,np.max(cmax_cp)*1.1]) plt.setp(ax1,ylim=[0,np.max(cmax_sn)*1.15]) plt.show() if save: np.savetxt('cmax_cpt_patients.txt',cmax_cp) np.savetxt('cmax_sn_patients.txt',cmax_sn) np.savetxt('cmax_cp_time.txt',cmax_cp_time) np.savetxt('cmax_sn_time.txt',cmax_sn_time) folder_path = uf.new_folder('Model_fitting') with PdfPages(folder_path+'model_fit_for_'+Title_str+'.pdf') as pdf: pdf.savefig(fig0, bbox_inches='tight') with PdfPages(folder_path+'model_fit_for_SN38.pdf') as pdf: pdf.savefig(fig1, bbox_inches='tight') return x,Cost, r2
((kd + Y[2])**2 / ((kd + Y[2])**2 + kd * bt))) ]) # to generate the x-axes t = np.linspace(0, 10, 1000) #initial values func0 = [0, 0, 0] # [N,V,CA] pars = (-0.0275, 0.025, 0.0145, 0.008, -0.015, 4.0e-7, 1.5e-7, 2.664, -0.07, -0.09, 0.08, 3.1416e-13, 7.854e-14, 1.57e-13, 1.9635e-14, 1.0e-6, 1.0e-4, 7.9976e7, 1.3567537e2) Y = integrate.odeint(func, func0, t, pars) n, v, ca = Y.T # the plots plt.subplot(4, 1, 1) plt.plot(t, n, 'r', linewidth=2, label='n') plt.xlabel('t') plt.ylabel('n(t)') plt.legend(loc='best') plt.subplot(4, 1, 2) plt.plot(t, v, 'b', linewidth=2, label='v') plt.xlabel('t') plt.ylabel('v(t)')
def non_phys_plotter_data_model_colour(k=[],save = False): if k == []: k = np.loadtxt('data/pat_param_drug_cpt11.txt') tot_dose = pk.CPT11_tot_dose pat_cp_data = pk.CPT11 pat_sn_data = pk.SN38 data_time = pk.CPT11_time pat_range = pk.pat_nums_cpt Title_str = 'CPT11' tmax = 36 x0 = [0]*9 a = int(np.ceil(len(pat_range)/2)) fig0, ax0 = plt.subplots(2,int(np.ceil(len(pat_range)/2)),sharex = True, sharey = True) fig0.suptitle('CPT11 model fit to data') fig1, ax1 = plt.subplots(2,int(np.ceil(len(pat_range)/2)),sharex = True, sharey = True) fig1.suptitle('SN38 model fit to data') plt.setp(ax0, xticks=np.arange(0,tmax+1,12)) plt.setp(ax1, xticks=np.arange(0,tmax+1,12)) cmax_cp = [None]*len(pat_range) cmax_sn = [None]*len(pat_range) cmax_cp_time = [None]*len(pat_range) cmax_sn_time = [None]*len(pat_range) cost = [None]*len(pat_range) for i in pat_range: tspan = data_time[i] t = np.sort(list(np.linspace(0.1,36,1000))+list(tspan)) t = np.sort(list(set(t))) pos = np.where(np.in1d(t,tspan))[0] x = odeint(non_phys_ode_CPT,x0,t,(k[i],tot_dose[i]),hmax=1) ax0[int(np.floor(i/a)),i%a].plot(t,x[:,2],'--',color=(0,0,0.5)) ax0[int(np.floor(i/a)),i%a].plot(tspan,pat_cp_data[i],'.',color=(0.7,0,0),mew=2) ax0[int(np.floor(i/a)),i%a].spines['right'].set_visible(False) ax0[int(np.floor(i/a)),i%a].spines['top'].set_visible(False) ax0[int(np.floor(i/a)),i%a].text(24,0.0012,'('+str(pat_range[i]+1)+')') ax1[int(np.floor(i/a)),i%a].plot(t,x[:,3] + x[:,7],'--',color=(0,0,0.5)) ax1[int(np.floor(i/a)),i%a].plot(tspan,pat_sn_data[i],'.',color=(0.7,0,0),mew=2) ax1[int(np.floor(i/a)),i%a].spines['right'].set_visible(False) ax1[int(np.floor(i/a)),i%a].spines['top'].set_visible(False) ax1[int(np.floor(i/a)),i%a].text(24,0.00003,'('+str(pat_range[i]+1)+')') plt.setp( ax0[int(np.floor(i/a)),i%a].xaxis.get_majorticklabels(), rotation=90 ) plt.setp( ax1[int(np.floor(i/a)),i%a].xaxis.get_majorticklabels(), rotation=90 ) cmax_cp[i] = np.max(x[:,2]) cmax_sn[i] = np.max(x[:,3] + x[:,7]) cmax_cp_time[i] = t[np.argmax(x[:,2])] cmax_sn_time[i] = t[np.argmax(x[:,3])] M_cp = x[pos,2] M_sn = x[pos,3] + x[pos,7] D_cp = pat_cp_data[i] D_sn = pat_sn_data[i] cost[i] = np.nansum(np.square(M_cp - D_cp)/M_cp + np.square(M_sn - D_sn)/M_sn) if int(np.floor(len(pat_range)/2))%2 != 0: fig0.delaxes(ax0[-1,-1]) fig1.delaxes(ax1[-1,-1]) ax0[int(np.floor(i/a)),i%a].legend(labels=['model','data'],bbox_to_anchor=(1.3,1)) fig0.text(0.5,-0.05,'Time (h)',ha='right') fig0.text(-0.05,0.65,'Concentration (mg/ml)',ha='right',rotation='vertical') ax1[int(np.floor(i/a)),i%a].legend(labels=['model','data'],bbox_to_anchor=(2.9,1)) fig1.text(0.5,-0.05,'Time (h)',ha='right') fig1.text(-0.05,0.65,'Concentration (mg/ml)',ha='right',rotation='vertical') plt.setp(ax0,ylim=[0,np.max(cmax_cp)*1.1]) plt.setp(ax1,ylim=[0,np.max(cmax_sn)*1.1]) if save: np.savetxt('cmax_cpt_patients.txt',cmax_cp) np.savetxt('cmax_sn_patients.txt',cmax_sn) np.savetxt('cmax_cp_time.txt',cmax_cp_time) np.savetxt('cmax_sn_time.txt',cmax_sn_time) folder_path = uf.new_folder('Model_fitting') with PdfPages(folder_path+'model_fit_for_'+Title_str+'_colour.pdf') as pdf: pdf.savefig(fig0, bbox_inches='tight') with PdfPages(folder_path+'model_fit_for_SN38_colour.pdf') as pdf: pdf.savefig(fig1, bbox_inches='tight') return x,cost
g_l = 0.1 v_k = -100.0 v_na = 50.0 v_l = -67.0 i_ext = 1.5 t_final = 100.0 dt = 0.01 v = -70.0 if __name__ == "__main__": tau_d = 2.0 tau_r = 0.2 x0 = initial_condition(v) t = np.arange(0, t_final, dt) sol = odeint(derivative, x0, t) V = sol[:, 0] S1 = sol[:, -1] # --------------------------------------------------------------# tau_r = 1.0 sol = odeint(derivative, x0, t) S2 = sol[:, -1] fig, ax = pl.subplots(3, figsize=(7, 5), sharex=True) ax[0].plot(t, V, lw=2, c="k") ax[1].plot(t, S1, lw=2, c="k") ax[2].plot(t, S2, lw=2, c="k") ax[0].set_xlim(min(t), max(t)) ax[0].set_ylim(-100, 100)
zp = np.zeros(6) zp[0:3] = z[3:6] z2 = ((-g * m_t) / (r**3)) * z[0:3] - R.T @ (dR_dt2 @ z[0:3] + 2 * dR_dt @ z[3:6]) + J_2[0:3] + J_3[0:3] zp[3:6] = z2 return zp t, x, y, z, vx, vy, vz = leer_eof( "S1B_OPER_AUX_POEORB_OPOD_20200827T111142_V20200806T225942_20200808T005942.EOF" ) z0 = np.array([x[0], y[0], z[0], vx[0], vy[0], vz[0]]) sol = odeint(satelite, z0, t) x_s = sol[:, 0] y_s = sol[:, 1] z_s = sol[:, 2] y_1 = [-5e6, 0, 5e6] eje_y = ["-5000", "0", "5000"] x_1 = [0, 18000, 36000, 54000, 72000, 90000] eje_x = ["0", "5", "10", "15", "20", "25"] plt.figure() plt.subplot(3, 1, 1) plt.title("Posición") plt.ylabel("X (KM)")