예제 #1
0
파일: mcsolve.py 프로젝트: partus/qutip
def _no_collapse_expect_out(num_times,expect_out):
    ##Calculates xpect.values at times tlist if no collapse ops. given
    #  
    #------------------------------------
    opt=odeconfig.options
    if odeconfig.tflag in array([1,10,11]):
        ODE=ode(odeconfig.tdfunc)
        code = compile('ODE.set_f_params('+odeconfig.string+')', '<string>', 'exec')
        exec(code)
    elif odeconfig.tflag==2:
        ODE=ode(_cRHStd)
    elif odeconfig.tflag in array([20,22]):
        ODE=ode(_tdRHStd)
    elif odeconfig.tflag==3:
        ODE=ode(_pyRHSc)
    else:
        ODE = ode(cyq_ode_rhs)
        ODE.set_f_params(odeconfig.h_data, odeconfig.h_ind, odeconfig.h_ptr)
    
    ODE.set_integrator('zvode',method=opt.method,order=opt.order,atol=opt.atol,rtol=opt.rtol,nsteps=opt.nsteps,first_step=opt.first_step,min_step=opt.min_step,max_step=opt.max_step) #initialize ODE solver for RHS
    ODE.set_initial_value(odeconfig.psi0,odeconfig.tlist[0]) #set initial conditions
    for jj in range(odeconfig.e_num):
        expect_out[jj][0]=mc_expect(odeconfig.e_ops_data[jj],odeconfig.e_ops_ind[jj],odeconfig.e_ops_ptr[jj],odeconfig.e_ops_isherm[jj],odeconfig.psi0)
    for k in range(1,num_times):
        ODE.integrate(odeconfig.tlist[k],step=0) #integrate up to tlist[k]
        if ODE.successful():
            state=ODE.y/norm(ODE.y)
            for jj in range(odeconfig.e_num):
                expect_out[jj][k]=mc_expect(odeconfig.e_ops_data[jj],odeconfig.e_ops_ind[jj],odeconfig.e_ops_ptr[jj],odeconfig.e_ops_isherm[jj],state)
        else:
            raise ValueError('Error in ODE solver')
    return expect_out #return times and expectiation values
예제 #2
0
파일: systems.py 프로젝트: AlexS12/PyFME
    def __init__(self, lat, lon, h, psi=0, x_earth=0, y_earth=0,
                 integrator='dopri5', use_jac=False, **integrator_params):
        """
        Initialize the equations of the chosen model and selects the
        integrator. Check `scipy.integrate.ode` to see available integrators.

        If use_jac = True the jacobian of the equations is used for the
        integration.
        """
        super().__init__(lat, lon, h, psi, x_earth, y_earth)
        # State vector must be initialized with set_initial_state_vector() method
        self.state_vector = None

        from pyfme.models.euler_flat_earth import lamceq, kaeq, kleq
        self.lamceq = lamceq

        if use_jac:
            from pyfme.models.euler_flat_earth import lamceq_jac, kaeq_jac
            jac_LM_and_AM = lamceq_jac
            jac_att = kaeq_jac
            jac_nav = None  # not implemented
        else:
            jac_LM_and_AM = None
            jac_att = None
            jac_nav = None

        self._ode_lamceq = ode(lamceq, jac=jac_LM_and_AM)
        self._ode_kaqeq = ode(kaeq, jac=jac_att)
        self._ode_kleq = ode(kleq, jac=jac_nav)

        self._ode_lamceq.set_integrator(integrator, **integrator_params)
        self._ode_kaqeq.set_integrator(integrator, **integrator_params)
        self._ode_kleq.set_integrator(integrator, **integrator_params)
예제 #3
0
    def shooting_function_full(self, r0):
        r"""
        The function used in the shooting algorithm.

        This is the full algorithm from integrating over
        :math:`0 \le \theta \le \pi`. The difference between the
        solution and its derivative at the matching point is the
        error to be minimized.

        Parameters
        ----------

        r0 : list of float
            Initial guess for the horizon radius, as outlined above.

        Returns
        -------

        list of float
            The error at the matching point.
        """
        # First half of the horizon
        H0 = np.array([r0[0], 0.0])
        solver1 = ode(self.expansion)
        solver1.set_integrator("dopri5", atol=1.e-8, rtol=1.e-6)
        solver1.set_initial_value(H0, 0.0)
        solver1.integrate(np.pi / 2.0)
        # Second half of the horizon
        H0 = np.array([r0[1], 0.0])
        solver2 = ode(self.expansion)
        solver2.set_integrator("dopri5", atol=1.e-8, rtol=1.e-6)
        solver2.set_initial_value(H0, np.pi)
        solver2.integrate(np.pi / 2.0)

        return solver1.y - solver2.y
예제 #4
0
파일: system.py 프로젝트: olrosales/PyFME
    def __init__(self, integrator="dopri5", model="euler_flat_earth", jac=False, **integrator_params):
        """
        Initialize the equations of the chosen model and selects the
        integrator. Check `scipy.integrate.ode` to see available integrators.

        If jac = True the jacobian of the equations is used for the
        integration.
        """

        if model not in models:
            raise ValueError(
                "The specified model is not available, please \
                             check available models in ..."
            )

        if jac:
            jac_LM_and_AM = euler_flat_earth.jac_linear_and_angular_momentum_eqs
            jac_att = euler_flat_earth.jac_linear_and_angular_momentum_eqs
            jac_nav = None  # not implemented
        else:
            jac_LM_and_AM = None
            jac_att = None
            jac_nav = None

        self._LM_and_AM_eqs = ode(euler_flat_earth.linear_and_angular_momentum_eqs, jac=jac_LM_and_AM)
        self._attitude_eqs = ode(euler_flat_earth.kinematic_angular_eqs, jac=jac_att)
        self._navigation_eqs = ode(euler_flat_earth.navigation_eqs, jac=jac_nav)

        self._LM_and_AM_eqs.set_integrator(integrator, **integrator_params)
        self._attitude_eqs.set_integrator(integrator, **integrator_params)
        self._navigation_eqs.set_integrator(integrator, **integrator_params)

        # State vector must be initialized with set_initial_values() method
        self.state_vector = None
예제 #5
0
파일: test_integrate.py 프로젝트: 87/scipy
    def test_concurrent_ok(self):
        f = lambda t, y: 1.0

        for k in xrange(3):
            for sol in ('vode', 'zvode', 'dopri5', 'dop853'):
                r = ode(f).set_integrator(sol)
                r.set_initial_value(0, 0)

                r2 = ode(f).set_integrator(sol)
                r2.set_initial_value(0, 0)

                r.integrate(r.t + 0.1)
                r2.integrate(r2.t + 0.1)
                r2.integrate(r2.t + 0.1)

                assert_allclose(r.y, 0.1)
                assert_allclose(r2.y, 0.2)

            for sol in ('dopri5', 'dop853'):
                r = ode(f).set_integrator(sol)
                r.set_initial_value(0, 0)

                r2 = ode(f).set_integrator(sol)
                r2.set_initial_value(0, 0)

                r.integrate(r.t + 0.1)
                r.integrate(r.t + 0.1)
                r2.integrate(r2.t + 0.1)
                r.integrate(r.t + 0.1)
                r2.integrate(r2.t + 0.1)

                assert_allclose(r.y, 0.3)
                assert_allclose(r2.y, 0.2)
예제 #6
0
    def s_ode(self,params):
        x0 = np.ones(3)
        s0 = np.zeros(18)
        solver_x = ode(self.dx).set_integrator('dopri5')
        solver_x.set_initial_value(x0,0).set_f_params(params,)

        solver_s = ode(self.ds).set_integrator('dopri5')
        solver_s.set_initial_value(s0,0).set_f_params(params,x0)

        dt = 1
        t1 = 250
        sensitivities = []
        for column in self.cols:
            for param in self.params:
                sensitivities.append('{0},{1}'.format(column,param))
        sol = pandas.DataFrame(np.empty((t1/dt,22)),columns=self.cols+sensitivities)
        i = 0
        #return solver_x,solver_s
        while solver_x.successful() and solver_s.successful() and solver_x.t < t1:
            solver_x.integrate(solver_x.t+dt)
            sol.iloc[i][self.cols] = solver_x.y
            solver_s.set_f_params(params,solver_x.y)
            solver_s.integrate(solver_s.t+dt)
            sol.iloc[i][sensitivities] = solver_s.y
            i += 1
        return sol
예제 #7
0
def run_trials(z, integrators, times, M):
    # Set up ODE solver
    for integrator in integrators:
        if integrator == 'dop853' or integrator == 'dopri5':
            solver = ode(system)
            solver.set_integrator(integrator, atol=1E-1, rtol=1E-3)
        elif integrator == 'bdf':
            solver = ode(system)
            solver.set_integrator('vode', method=integrator, atol=1E-1, rtol=1E-3, nsteps=2000)

        name = integrator + ' ' + str(times[-1]) + ' ' + str(M)
        try:
            z, c1, c2, t, c1_40km, c2_40km = load_variables(name)
            print "Loaded data for: " + name
        except:
            print "Starting solver: ", integrator, "with times", times
            c1, c2, c1_40km, c2_40km, t = solve(solver, c, times, integrator)
            save_variables(name, z, c1, c2, t, c1_40km, c2_40km)

        # And plot some things
        if times[-1] == 86400.0:
            labels = [str(int(time / 3600.)) + " hours" for time in times[1:]]
            plot_c1(z, c, c1, labels, name)
            plot_c2(z, c, c2, labels, name)
        elif times[-1] == 864000.0:
            plot_40km(t, c1_40km, c2_40km, name)
예제 #8
0
파일: driver.py 프로젝트: katyhuff/pyrk
def solve(si, y, infile):
    """Conducts the solution step, based on the dopri5 integrator in scipy

    :param si: the simulation info object
    :type si: SimInfo
    :param y: the solution vector
    :type y: np.ndarray
    :param infile: the imported infile module
    :type infile: imported module
    """
    n = ode(f_n).set_integrator('dopri5')
    n.set_initial_value(y0_n(si), si.timer.
                        t0.magnitude)
    n.set_f_params(si)
    th = ode(f_th).set_integrator('dopri5', nsteps=infile.nsteps)
    th.set_initial_value(y0_th(si), si.timer.t0.magnitude)
    th.set_f_params(si)
    while (n.successful()
           and n.t < si.timer.tf.magnitude
           and th.t < si.timer.tf.magnitude):
        si.timer.advance_one_timestep()
        si.db.record_all()
        n.integrate(si.timer.current_time().magnitude)
        update_n(n.t, n.y, si)
        th.integrate(si.timer.current_time().magnitude)
        update_th(th.t, n.y, th.y, si)
    return si.y
예제 #9
0
파일: mcsolve.py 프로젝트: partus/qutip
def _no_collapse_psi_out(num_times,psi_out):
    ##Calculates state vectors at times tlist if no collapse AND no expectation values are given.
    #
    opt=odeconfig.options
    if odeconfig.tflag in array([1,10,11]):
        ODE=ode(odeconfig.tdfunc)
        code = compile('ODE.set_f_params('+odeconfig.string+')', '<string>', 'exec')
        exec(code)
    elif odeconfig.tflag==2:
        ODE=ode(_cRHStd)
    elif odeconfig.tflag in array([20,22]):
        ODE=ode(_tdRHStd)
    elif odeconfig.tflag==3:
        ODE=ode(_pyRHSc)
    else:
        ODE = ode(cyq_ode_rhs)
        ODE.set_f_params(odeconfig.h_data, odeconfig.h_ind, odeconfig.h_ptr)
        
    ODE.set_integrator('zvode',method=opt.method,order=opt.order,atol=opt.atol,rtol=opt.rtol,nsteps=opt.nsteps,first_step=opt.first_step,min_step=opt.min_step,max_step=opt.max_step) #initialize ODE solver for RHS
    ODE.set_initial_value(odeconfig.psi0,odeconfig.tlist[0]) #set initial conditions
    psi_out[0]=Qobj(odeconfig.psi0,odeconfig.psi0_dims,odeconfig.psi0_shape,'ket')
    for k in range(1,num_times):
        ODE.integrate(odeconfig.tlist[k],step=0) #integrate up to tlist[k]
        if ODE.successful():
            psi_out[k]=Qobj(ODE.y/norm(ODE.y,2),odeconfig.psi0_dims,odeconfig.psi0_shape,'ket')
        else:
            raise ValueError('Error in ODE solver')
    return psi_out
def Weightloss_Shooting():
	age, sex =  38. , 'female'
	H, BW    =  1.73, 72.7
	T		 =  12*7.   # Time frame = 3 months    
	
	PALf, EIf = 1.7, 2025
	def EI(t): return EIf
	
	def PAL(t): return PALf
	
	from solution import fat_mass, compute_weight_curve, weight_odes
	F = fat_mass(BW,age,H,sex)
	L = BW-F
	# Fix activity level and determine Energy Intake to achieve Target weight of 145 lbs = 65.90909 kg
	
	init_FL = np.array([F,L])
	EI0, EI1 = 2000, 1950					# Variable Energy Intake
	beta = 65.90909*2.2
	reltol, abstol = 1e-9,1e-8
	dim, iterate = 2, 15
	print '\nj = 1', '\nt = ', EI0
	for j in range(2,iterate):
		print '\nj = ', j, '\nt = ', EI1
		ode_f = lambda t,y: weight_odes(t,y,EI1,PAL(t))
		example1 = ode(ode_f).set_integrator('dopri5',atol=abstol,rtol=reltol) 
		example1.set_initial_value(init_FL, 0.) 
		y1 = 2.2*sum(example1.integrate(T) )
		
		if abs(y1-beta)<1e-8: 
			print '\n--Solution computed successfully--'
			break
		# Update
		ode_f = lambda t,y: weight_odes(t,y,EI0,PAL(t))
		example0 = ode(ode_f).set_integrator('dopri5',atol=abstol,rtol=reltol) 
		example0.set_initial_value(init_FL, 0.) 
		y0 = 2.2*sum(example0.integrate(T))
		
		EI2 = EI1 - (y1 - beta)*(EI1-EI0)/(y1- y0)
		EI0 = EI1
		EI1 = EI2
		
	# Here we plot the solution 
	ode_f = lambda t,y: weight_odes(t,y,EI1,PAL(t))
	example = ode(ode_f).set_integrator('dopri5',atol=abstol,rtol=reltol)
	example.set_initial_value(init_FL, 0.) 
	
	X = np.linspace(0.,T,801)
	Y = np.zeros((len(X),dim))
	Y[0,:] = init_FL
	
	for j in range(1,len(X)): Y[j,:] = example.integrate(X[j]) 
	
	print '\n|y(T) - Target Weight| = ', np.abs(beta-2.2*sum(Y[-1,:]) ),'\n'
	plt.plot(X,2.2*(Y[:,0]+Y[:,1]),'-k',linewidth=2.0)
	plt.axis([-1,T+1,0,170])
	plt.show(); plt.clf()
	return 
예제 #11
0
 def addMethods(self):
     # override to add _solver function
     ODEsystem.addMethods(self, usePsyco=False)
     if self.haveJacobian():
         self._solver = ode(getattr(self,self.funcspec.spec[1]),
                         getattr(self,self.funcspec.auxfns["Jacobian"][1]))
         self._funcreg['_solver'] = ('self',
              'ode(getattr(self,self.funcspec.spec[1]),' \
                + 'getattr(self,self.funcspec.auxfns["Jacobian"][1]))')
     else:
         self._solver = ode(getattr(self,self.funcspec.spec[1]))
         self._funcreg['_solver'] = ('self', 'ode(getattr(self,' \
                                               + 'self.funcspec.spec[1]))')
예제 #12
0
def DimensionalForms(BoundConditions, NDParameters, X0=param.X0, d=param.d, rICp=param.rICp, \
                     rhoH=param.rhoH, alpha=param.alpha, rhoD=param.rhoD, g=param.g, hminus=param.hmin, \
                     hmaxi=param.hmax, dh=param.dt, geom="cart", AbsTole=param.AbsTol, RelTole=param.AbsTol):
    """ Integration RK (de type Dormand Prince 4-5) of the equations system for an horizontal F-layer.
    resolutionSystem(y0, t0, tmax, dt, *arg)
    Default parameters for the others arguments are :
    PeT=1.e6,
    MX=0.17,
    MP=0.016,
    Veff=1.e7,
    gamma=7.2,
    Atol=1.e-10,
    Rtol=1.e-12
    The result is given in fully dimensional form. 
    """

    if geom == "cart":
        sol = ode(systemdiff.cart).set_integrator(
            'dopri5', atol=param.AbsTol, rtol=param.AbsTol, nsteps=1e7)
    elif geom == "spher":
        sol = ode(systemdiff.spher).set_integrator(
            'dopri5', atol=param.AbsTol, rtol=param.AbsTol, nsteps=1e7)

    sol.set_initial_value(BoundConditions, param.hmin)
    sol.set_f_params(NDParameters)  # (PeT, Mx, Mp, Veff, gamma)
    X, dXdh, phiVs,  h = BoundConditions[0] * np.ones(1), BoundConditions[1] * np.ones(1), \
      BoundConditions[2] * np.ones(1), param.hmin * np.ones(1)

    if param.dt > 0:
        while sol.successful() and sol.t < param.hmax:
            sol.integrate(sol.t + param.dt)
        # print("%g %g" % (r.t, r.y))
            X = np.append(X, sol.y[0])
            dXdh = np.append(dXdh, sol.y[1])
            phiVs = np.append(phiVs, sol.y[2])
            h = np.append(h, sol.t)
    else:
        while sol.successful() and sol.t > param.hmax:
            sol.integrate(sol.t + param.dt)
        # print("%g %g" % (r.t, r.y))
            X = np.append(X, sol.y[0])
            dXdh = np.append(dXdh, sol.y[1])
            phiVs = np.append(phiVs, sol.y[2])
            h = np.append(h, sol.t)

    # back to fully dimensional:
    x = X0 * X
    z = h * d
    T = param.Tliq0 * (1 - NDParameters['Mp'] * h - X * NDParameters['Mx'])

    return z, x, phiVs, T
예제 #13
0
def run():
    data_x = []
    data_y = []

    dt = 0.1
    tmax = 10
    state = None

    m = model.model_push()
    ir = sciint.ode(m.step).set_integrator('vode', atol=0.01)
    ir.set_initial_value(m.init, 0)

    while state is None or state[2] < m.x_h and ir.t < tmax:
        state = ir.integrate(ir.t + dt/1000)
        data_x.append(ir.t)
        data_y.append(m.M)

    if ir.t >= tmax:
        print('front failed')
        plt.ylim(0, m.Mmax + 10)
        plt.plot(data_x, data_y)
        plt.xlabel('Время t [с]')
        plt.ylabel('Момент М(t) [Н м]')
        plt.show()
        return None

    t1 = ir.t
    m = model.model_torque()
    ir = sciint.ode(m.step).set_integrator('vode', atol=0.01)
    m.init = [
        state[0], 0,
        state[2] - m.L * cos(asin(((state[3] - m.y_f)/m.L))), m.r_k + m.y_f
    ]
    state2 = state[:]
    ir.set_initial_value(m.init, 0)
    state = None
    while state is None or state[2] < m.x_h and ir.t + t1 < tmax:
        state = ir.integrate(ir.t + dt/1000)
        data_x.append(ir.t + t1)
        data_y.append(m.M)

    if ir.t + t1 >= tmax:
        print('rear failed')
        return None
    print('all pass')
    plt.ylim(0, m.Mmax + 10)
    plt.plot(data_x, data_y)
    plt.xlabel('Время t [с]')
    plt.ylabel('Момент М(t) [Н м]')
    plt.show()
    return (m.init, state2)
예제 #14
0
파일: test_integrate.py 프로젝트: 87/scipy
    def test_concurrent_fail(self):
        for sol in ('vode', 'zvode'):
            f = lambda t, y: 1.0

            r = ode(f).set_integrator(sol)
            r.set_initial_value(0, 0)

            r2 = ode(f).set_integrator(sol)
            r2.set_initial_value(0, 0)

            r.integrate(r.t + 0.1)
            r2.integrate(r2.t + 0.1)

            assert_raises(RuntimeError, r.integrate, r.t + 0.1)
def Cannon_Shooting(t0,t1,za=0.,va=45,nu=.0003): 
	a, b = 0., 195
	beta =  0.
	
	# t0,t1 = np.pi/6., np.pi/7
	dim, iterate = 3,40
	reltol, abstol = 1e-9,1e-8
	
	# Initial_Conditions = np.array([z=za,v=va,phi=t])
	g = 9.8067
	def ode_f(x,y): 
		# y = [z,v,phi]
		return np.array([np.tan(y[2]), -(g*np.sin(y[2]) + nu*y[1]**2.)/(y[1]*np.cos(y[2])), 
		-g/y[1]**2.])
	
	
	print '\nj = 1'
	print 't = ', t0
	for j in range(2,iterate):
		print '\nj = ', j
		print 't = ', t1
		example1 = ode(ode_f).set_integrator('dopri5',atol=abstol,rtol=reltol) 
		example1.set_initial_value(np.array([za,va,t1]),a) 
		y1 = example1.integrate(b)[0]
		
		if abs(y1-beta)<1e-8: 
			print '\n--Solution y computed successfully--'
			break
		# Update
		example0 = ode(ode_f).set_integrator('dopri5',atol=abstol,rtol=reltol) 
		example0.set_initial_value(np.array([za,va,t0]),a) 
		y0 = example0.integrate(b)[0]
		
		t2 = t1 - (y1 - beta)*(t1-t0)/(y1- y0)
		t0 = t1
		t1 = t2
		
	# Here we plot the solution 
	example = ode(ode_f).set_integrator('dopri5',atol=abstol,rtol=reltol)
	example.set_initial_value(np.array([za,va,t1]),a) 
	X = np.linspace(a,b,801)
	Y = np.zeros((len(X),dim))
	Y[0,:] = np.array([0.,0.5,t1])
	
	for j in range(1,len(X)): Y[j,:] = example.integrate(X[j]) 
	
	print '\n|y(b) - beta| = ', np.abs(beta-Y[-1,0]),'\n'
	# plt.plot(X,Y[:,0],'-k')
	return X,Y
def Exercise1(): 
# y'' +4y = -9sin(x), y(0) = 1., y(3*pi/4.) = -(1.+3*sqrt(2))/2., y'(0) = -2
# Exact Solution: y(x) = cos(2x) + (1/2)sin(2x) - 3sin(x)
	
	a, b = 0., 3*np.pi/4.
	alpha, beta =  1., -(1.+3*np.sqrt(2))/2.
	t0,t1 = 3., 1.
	dim, iterate = 2,10
	reltol, abstol = 1e-9,1e-8
	def ode_f(x,y): return np.array([y[1] , -4.*y[0] - 9.*np.sin(x)])
	
	
	print '\nj = 1','\nt = ', t0
	
	for j in range(2,iterate):
		print '\nj = ', j,'\nt = ', t1
		
		if j >2: 
			y0 = y1			# Update
		else:
			example = ode(ode_f).set_integrator('dopri5',atol=abstol,rtol=reltol) 
			example.set_initial_value(np.array([alpha,t0]),a) 
			y0 = example.integrate(b)[0]
			
		example = ode(ode_f).set_integrator('dopri5',atol=abstol,rtol=reltol) 
		example.set_initial_value(np.array([alpha,t1]),a) 
		y1 = example.integrate(b)[0]
		if abs(y1-beta)<1e-8: 
			print '\n--Solution y computed successfully--',\
			'\n|y(b) - beta| = ',np.abs(beta-y1),'\n'
			break
		
		t2 = t1 - (y1 - beta)*(t1-t0)/(y1- y0)
		t0 = t1
		t1 = t2
	
	# Plots the solution
	example = ode(ode_f).set_integrator('dopri5',atol=abstol,rtol=reltol)
	example.set_initial_value(np.array([alpha,t1]),a) 
	X = np.linspace(a,b,401)
	Y = np.zeros((len(X),dim))
	Y[0,:] = np.array([alpha, t1])
	
	for j in range(1,len(X)): 
		Y[j,:] = example.integrate(X[j]) 
	plt.plot(X,Y[:,0],'-k')
	plt.show()
	return 
예제 #17
0
def implicit_black_box(propensities, V, X, w, h, deter_vector, stoc_positions, positions, valid, deriv):

    # Adjustment for systems reaching steady state

    temp = derivative_G(propensities, V, X, w, deter_vector, stoc_positions, positions, valid)
    # pdb.set_trace()
    valid_adjust_pos = np.where(np.sum(np.abs(temp), axis=0) < 1e-10, True, False)

    valid_adjust = valid[:, :]
    valid_adjust[valid_adjust_pos, :] = False

    # print(" Reached Steady State %d"%(np.sum(valid_adjust_pos)))

    from scipy.integrate import ode

    # pdb.set_trace()
    deter_ode = ode(f).set_integrator("lsoda", method="adams", with_jacobian=False)
    deter_ode.set_initial_value(X[deter_vector, :].flatten(), 0).set_f_params(
        [propensities, V, X, deter_vector, stoc_positions, positions, valid_adjust, w]
    )

    # pdb.set_trace()
    while deter_ode.successful() and deter_ode.t < h:
        deter_ode.integrate(h)

        # print("Black Box: \n"+ str(deter_ode.y))

        # print("iterator : \n:"+str(next_X[deter_vector,:]))
    X[deter_vector, :] = deter_ode.y.reshape((np.sum(deter_vector), X.shape[1]))

    # Another adjust to compensate for non negative
    X = np.where(X < 0.0, 0.0, X)

    return X
예제 #18
0
def solve_opt(n,k):
    nsteps = 1000-1
    t = np.zeros((nsteps))
    y = np.zeros((nsteps))
    w0 = 1.98
    y0 = [w0]
    t0 = 1.99
    t1 = .001
    dt = (t1-w0)/nsteps
    r = ode(multi_winner_ode)
    r.set_f_params(n, k)
    r.set_initial_value(y0, t0)
    r.set_integrator("dropri853", nsteps=5000)
    i = 0
    while r.successful() and r.t > t1:
        r.integrate(r.t+dt)
        print("%g %g" % (r.t, r.y))

        t[i] = r.t
        y[i] = r.y
        i+=1
    w = np.where(y<0, 0, y)
    # plt.plot(t, w)

    # plt.show()
    bid_func = interp1d(t[::-1], w[::-1])
    print(min(t), max(t))
    return bid_func
def run_ODE(f, a_in, C, D, num_of_variables, T = 10, dt = 0.01, y0 = None):
    '''Run the ODE for the given set of equations and record the outputs.

    Args:
        f (function): Evolution of the system.

        a_in (function): inputs as a function of time.

        C,D (matrices): matrices to use to obtain output from system state and
            input.

        num_of_variables (int): number of variables the system has.

        T (optional[positive float]): length of simulation.

        dt (optional[float]): time step used by the simulation.

    Returns:
        (array): 
        An array Y of outputs.

    '''
    if y0 is None:
        y0 = np.asmatrix([0.]*num_of_variables).T

    r = ode(f).set_integrator('zvode', method='bdf')
    r.set_initial_value(y0, 0.)
    Y = []
    while r.successful() and r.t < T:
        Y.append(C*r.y+D*a_in(r.t))
        r.integrate(r.t+dt)
    return Y
예제 #20
0
파일: flight.py 프로젝트: treygreer/treb
    def run(self, start, velocity):
        # state data structures
        self.t=zeros(self.num_steps)
        self.Y=zeros([self.num_steps, 4])
        self.Y[0] = array([start[0],start[1],velocity[0],velocity[1]])

        r = ode(self.deriv)
        r.set_integrator('vode', rtol=1e-9, atol=1e-6)
        r.set_initial_value(self.Y[0],t=0.0)

        time_idx=1
        while r.successful() and r.t < self.max_time:
            r.integrate(time_idx*self.time_step)
            self.t[time_idx] = r.t
            self.Y[time_idx] = r.y
            time_idx = time_idx + 1

            if self.debug:
                print ("time=%10.3f: x=%g y=%g vx=%g vy=%g" % \
                      (r.t, r.y[0], r.y[1], r.y[2], r.y[3]))

            if r.y[1]<0:
                break
            
        # simulation done: truncate arrays 
        self.Y.resize([time_idx, self.Y.shape[1]])
        self.t.resize([time_idx])
예제 #21
0
 def __init__(self, params, capital, consumption, jacobian, utility):
     """Initializes a RamseyModel object with the following attributes:
     
         params:   (dict) Dictionary of model parameters.
         
         capital:  (callable) Equation of motion for capital (per 
                   person/effective person).
                             
         euler:    (callable) Equation describing consumption (per 
                   person/effective person).
                             
         jacobian: (callable) Function returning the model's jacobian matrix 
                   of partial derivatives.
                             
         utility:  (callable) Utility function representing household 
                   preferences over consumption.
         
     """
     self.params      = params
     self.capital     = capital
     self.consumption = consumption
     self.jacobian    = jacobian
     self.utility     = utility
                
     # initialize model steady state
     self.steady_state = SteadyState(self)
     
     # create an instance of the scipy.integrate.ode class
     f = lambda t, y, params: [self.capital(y, params), 
                               self.consumption(y, params)]
     jac = lambda t, y, params: self.jacobian(y, params)        
     self.simulator = integrate.ode(f, jac)
예제 #22
0
파일: simulator.py 프로젝트: Pyomo/pyomo
    def _simulate_with_scipy(self, initcon, tsim, switchpts,
                             varying_inputs, integrator,
                             integrator_options):

        scipyint = \
            scipy.ode(self._rhsfun).set_integrator(integrator,
                                                   **integrator_options)
        scipyint.set_initial_value(initcon, tsim[0])

        profile = np.array(initcon)
        i = 1
        while scipyint.successful() and scipyint.t < tsim[-1]:

            # check if tsim[i-1] is a switching time and update value
            if tsim[i - 1] in switchpts:
                for v in self._siminputvars.keys():
                    if tsim[i - 1] in varying_inputs[v]:
                        p = self._templatemap[self._siminputvars[v]]
                        p.set_value(varying_inputs[v][tsim[i - 1]])

            profilestep = scipyint.integrate(tsim[i])
            profile = np.vstack([profile, profilestep])
            i += 1

        if not scipyint.successful():
            raise DAE_Error("The Scipy integrator %s did not terminate "
                            "successfully." % integrator)
        return [tsim, profile]
예제 #23
0
파일: Journey.py 프로젝트: kartikkumar/emtg
    def PlotJourneyBoundaryOrbits(self, JourneyAxes):

        for boundarystate in self.boundary_states:
            BoundaryStateScaled = np.array(boundarystate) / self.LU
            BoundaryStateScaled[3:6] *= self.TU
            r = np.linalg.norm(BoundaryStateScaled[0:3])
            v = np.linalg.norm(BoundaryStateScaled[3:6])
            a = r / (2.0 - r*v*v)
            T = 2*math.pi*math.sqrt(a**3)

            StateIntegrateObject = ode(EOM.EOM_inertial_2body, jac=EOM.EOM_jacobian_intertial_2body).set_integrator('dop853', atol=1.0e-8, rtol=1.0e-8)
            StateIntegrateObject.set_initial_value(BoundaryStateScaled).set_f_params(1.0).set_jac_params(1.0)

            dt = T / 100
            StateHistory = []
            while StateIntegrateObject.successful() and StateIntegrateObject.t <= T * 1.01:
                StateIntegrateObject.integrate(StateIntegrateObject.t + dt)
                StateHistory.append(StateIntegrateObject.y * self.LU)

            X = []
            Y = []
            Z = []
            for StateLine in StateHistory:
                X.append(StateLine[0])
                Y.append(StateLine[1])
                Z.append(StateLine[2])

            JourneyAxes.plot(X, Y, Z, lw=2, c='0.75')
예제 #24
0
 def integrateODE(self,state,thetavec,u0):
     '''
     Integrates ODE over the gridpoints theta
     '''
     if not self.Vf ==None:
         Fs = self.Vf,self.wf,self.w2f
     else:
         Fs = None
     def dy_dtheta(theta,y):
         dy = self.Para.differentialEquation(y,theta,state,Fs)
         return dy
     
     lambda_1,lambda_2,theta_ = state
     mu_tilde = -lambda_2/theta_
     if thetavec[0] > self.theta_min:
         thetavec = hstack((self.theta_min,thetavec))
     y0 = self.getInitial_y(u0,mu_tilde,thetavec[0],state)
     
     r = ode(dy_dtheta).set_integrator('vode',rtol=1e-10,atol = 1e-10,nsteps=1000)
     r.set_initial_value(y0,thetavec[0])
     y = ones((len(thetavec),2))
     y[0] = y0
     for i,theta in enumerate(thetavec[1:]):
         y[i+1] = r.integrate(theta)
         if y[i+1,1] >0:
             break
         if not r.successful():
             print "ode failed"
             break
         
     if thetavec[0] == self.theta_min:
         return y[1:]
     else:
         return y
예제 #25
0
파일: base.py 프로젝트: willigott/framed
    def numerical_integrator(self, t0, tf, dt, initial_conditions, solver, verbose):
        """
        the numerical_integrator() method integrates the ODE of the dynamic system using a numerical solver
        """
        f = self._ode_RHS
        if initial_conditions:
            y0 = initial_conditions
        else:
            y0 = self.initial_conditions

        MdFBA_ode = ode(f).set_integrator(solver)
        MdFBA_ode.set_initial_value(y0, t0)

        t = [t0]
        y = [y0]

        while MdFBA_ode.successful() and MdFBA_ode.t < tf:
            MdFBA_ode.integrate(MdFBA_ode.t + dt)

            t.append(MdFBA_ode.t)
            y.append(MdFBA_ode.y)

            if verbose:
                print MdFBA_ode.t

        t = numpy.array(t)
        y = numpy.array(y)
        return t, y
예제 #26
0
def CalculateAllDistancesFor(startPosition, minTime, maxTime, display=True, numSteps = 100):
    """ Calculate all distances for every t and tau between min and maxtime, 
        with # of steps """
    minT, minTau = minTime
    maxT, maxTau = maxTime
    allTs = np.linspace(minT, maxT, numSteps)
    allTaus = np.linspace(minTau, maxTau, numSteps)
    distDataType = np.dtype([('Distance', np.float64), ('DistanceTau', np.float64)])
    allDistances = np.empty((numSteps,numSteps), dtype=distDataType)
    doprIntegrator = ode(currentField.GetDataAt).set_integrator("dopri5")

    distIterator = np.nditer(allDistances, flags=['multi_index'], op_flags=['readwrite'])
    while not distIterator.finished:
        t = allTs[distIterator.multi_index[0]]
        tau = allTaus[distIterator.multi_index[1]]
        doprIntegrator.set_initial_value(startPosition, t)
        distance = linalg.norm(startPosition - doprIntegrator.integrate(t+tau))
        print(" distance calculated (t: {}, tau: {}): {}".format(t, tau, distance))
        distIterator[0] = (distance, distance / tau)
        distIterator.iternext()

    if display:
        import mpl_toolkits.mplot3d.axes3d as axes3d
        fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
        ax.plot_surface(allTs, allTaus, allDistances['DistanceTau'], cmap=plt.get_cmap('jet'), rstride=1, cstride=1, vmin=-150, vmax=150, shade=True)
        plt.show()
        
    return allDistances
def solve_dydt(tSpan,y0,options,M):
    
    # unpack option values
    opt_rtol = options[0]
    opt_atol = options[1]
    dt = options[2]
    # use initial and final time range
    t0 = tSpan[0]
    tmax = tSpan[1]
    # set equation to solve
    solver = ode(Fct_sys)
    # initialize time and solution vectors
    t   = []
    sol = []
    sol.append(y0)
    t.append(t0)
    # solver initial value
    solver.set_initial_value(y0, t0).set_f_params(M)
    # solver options
    solver.set_integrator('dopri5',atol=opt_atol,rtol=opt_rtol)

    # Start solver 
    while solver.successful() and solver.t < tmax:
        solver.integrate(solver.t + dt)
        t.append(solver.t)
        sol.append(solver.y)             
    
    # Array conversion and processing for sensitivity and plotting
    t   = array(t)
    sol = array(sol)

    return t, sol
예제 #28
0
    def run(self, number_of_trajectories=1, seed=None):
        """ Run one simulation of the model.

        number_of_trajectories: How many trajectories should be run.
        seed: the random number seed (incremented by one for multiple runs).
        input_file: the filename of the solver input data file .
        loaddata: boolean, should the result object load the data into memory on creation.

        Returns:
            URDMEResult object.
                or, if number_of_trajectories > 1
            a list of URDMEResult objects
        """
        if not self.is_compiled:
            self.compile()
                
        solver = ode(self.derivative_fn).set_integrator('vode', method='bdf', order=15, atol=self.error_tolarance)
        solver.set_initial_value(self.solver_initial_value, 0)
        
        result = PDEResult(self.model)
        ndofs = result.U.shape[1]
        for tndx, t in enumerate(self.model.tspan):
            while solver.successful() and solver.t < t:
                solver.integrate(t)
            result.U[tndx:tndx+1,:] = solver.y.reshape(1,ndofs)

        if number_of_trajectories > 1:
            return [result]*number_of_trajectories
        else:
            return result
예제 #29
0
파일: lqr.py 프로젝트: alexansari101/nlsymb
    def solve(self, **kwargs):
        n, m = self.dims
        sa, sb = (-self.ta, -self.tb)

        Pdot = lambda s, P: self._Pdot(s, P)
        solver = ode(Pdot)

        solver.set_integrator('vode', max_step=1e-2, **kwargs)
        solver.set_initial_value(self.Pb.ravel(), sb)

        self._Ptj = Trajectory('P')
        results = [(-sb, self.Pb)]

        while solver.successful() and solver.t < sa + 1e-2:
            solver.integrate(sa, step=True)
            P = solver.y.reshape((n, n))
        
            # find which jumps lie between this time step and the previous one
            # add the corresponding term to b = solver.y + jumpterm
            if self.jumps:
                prevtime = results[-1][0]  # replace with call to _bt.tmin
                for (tj, fj) in self.jumps:
                    if prevtime > tj and tj > -solver.t:
                        #  positive sign because backwards integration
                        P = P + matmult(fj.T, P) + matmult(P, fj)
                        solver.set_initial_value(P.ravel(), solver.t) 
            
            results.append((-solver.t, P))

        for (t, P) in reversed(results):
            self._Ptj.addpoint(t, P=P)

        self._Ptj.interpolate()
        self.P = lambda t: self._Ptj.P(t)
예제 #30
0
    def _run_solout_break_test(self, integrator):
        # Check correct usage of stopping via solout
        ts = []
        ys = []
        t0 = 0.0
        tend = 10.0
        y0 = [1.0, 2.0]

        def solout(t, y):
            ts.append(t)
            ys.append(y.copy())
            if t > tend/2.0:
                return -1

        def rhs(t, y):
            return [y[0] + y[1], -y[1]**2]

        ig = ode(rhs).set_integrator(integrator)
        ig.set_solout(solout)
        ig.set_initial_value(y0, t0)
        ret = ig.integrate(tend)
        assert_array_equal(ys[0], y0)
        assert_array_equal(ys[-1], ret)
        assert_equal(ts[0], t0)
        assert_(ts[-1] > tend/2.0)
        assert_(ts[-1] < tend)
예제 #31
0
print('R=', str(R))

# target point
xT = np.array([-1, -1])
# target region around xT
Starget = np.array([[9.5616, 2.2650], [2.2650, 3.6483]])
t1 = 2
dt = 0.05


# Compute the xs
def ff(t, y):
    return -f(y)


r = ode(ff).set_integrator('vode', method='bdf', with_jacobian=False)
r.set_initial_value(xT, 0)
ts = [r.t]
xs = [r.y]
while r.successful() and r.t < t1:
    r.integrate(r.t + dt)
    ts.append(r.t)
    xs.append(r.y)
xs.reverse()

# Compute the As
N = len(ts)
As = []
Bs = []
Ks = []
for t in range(N):
예제 #32
0
#m = 10.0e19
m1 = 10.0e13
lna_step = 0.0001
A0 = 1.
A1 = 0.001
A_real, n_iter = Secante_1D(A0, A1, fs, m1, a_i, lna_step, tol=0.00001, N=200)

IC = ic_lsfdm(A_real, m1, a_i)

print "Trying with our best initial conditions:", IC
#Y = odeint(background_system_real,IC,lna,mxstep=1000000)
#o = ode(background_system_real).set_integrator('vode', method='bdf', order=15, nsteps=5000)
#o = ode(background_system_real).set_integrator('vode', method='adams', order=12, nsteps=3000)
#o = ode(background_system_real).set_integrator('lsoda',nsteps = 5000)
o = ode(background_system_real).set_integrator('dopri5', nsteps=4000)
#o = ode(background_system_real).set_integrator('dop853',nsteps = 3000)

o.set_initial_value(IC, math.log(a_i))
rs = []
ys = []
while o.successful() and o.t < 0:
    o.integrate(o.t + lna_step)
    rs.append(o.t)
    ys.append(o.y)
lna = np.vstack(rs)
Y = np.vstack(ys).T
om_phi = lna * 0.
for i in range(len(lna)):
    om_phi[i] = -math.cos(Y[1, i])
예제 #33
0
    def __init__(self, patient_number=0):
        """
        Initializing the simulation environment.
        """
        np.random.seed(1) ### Fixing seed


        self.previous_action = 0

        ## Loading variable parameters
        reward_flag, bg_init_flag = self._update_parameters()


        # Initialize bolus history
        self.bolusHistoryIndex = 0
        self.bolusHistoryValue = []
        self.bolusHistoryTime = []
        self.insulinOnBoard = np.zeros(1)

        # Initialize sensor model
        self.CGMlambda = 15.96    # Johnson parameter of recalibrated and synchronized sensor error.
        self.CGMepsilon = -5.471  # Johnson parameter of recalibrated and synchronized sensor error.
        self.CGMdelta = 1.6898    # Johnson parameter of recalibrated and synchronized sensor error.
        self.CGMgamma = -0.5444   # Johnson parameter of recalibrated and synchronized sensor error.
        self.CGMerror = 0
        self.sensor_noise = np.random.randn(1)
        # self.CGMaux = []
        self.sensorNoiseValue = 0.07 # Set a value

        # =======================
        # Anas patient parameters
        # =======================
        P, init_basal, carb_factor, _ = matlab_to_python(patient_number)
        init_basal_optimal = init_basal
        self.P = P
        self.init_basal_optimal = init_basal_optimal
        self.bolus = carb_factor

        self.action_space = spaces.Box(0, 2*self.init_basal_optimal[0], (1,), dtype=np.float32)


        if bg_init_flag == 'random':
            self.init_basal = np.random.choice(np.linspace(init_basal_optimal-2, init_basal_optimal, 10))
        elif bg_init_flag == 'fixed':
            self.init_basal = init_basal_optimal

        # Flag for manually resetting the init
        self.reset_basal_manually = None

        self._seed()
        self.viewer = None

        # ==========================================
        # Setting up the Hovorka simulator
        # ==========================================

        # Initial values for parameters
        initial_pars = (self.init_basal, 0, P)

        # Initial value
        X0 = fsolve(hovorka_model_tuple, np.zeros(11), args=initial_pars)
        self.X0 = X0

        # Simulation setup
        self.integrator = ode(hovorka_model)
        self.integrator.set_integrator('vode', method='bdf', order=5)

        self.integrator.set_initial_value(X0, 0)

        # Simulation time in minutes
        self.simulation_time = 30
        self.n_solver_steps = 1
        self.stepsize = int(self.simulation_time/self.n_solver_steps)
        self.observation_space = spaces.Box(0, 500, (int(self.stepsize + 4 + 2),), dtype=np.float32)

        # State is BG, simulation_state is parameters of hovorka model
        initial_bg = X0[-1] * 18
        initial_insulin = np.ones(4) * self.init_basal_optimal
        initial_iob = np.zeros(1)
        self.state = np.concatenate([np.repeat(initial_bg, self.simulation_time), initial_insulin, initial_iob, np.zeros(1)])

        self.simulation_state = X0

        # Keeping track of entire blood glucose level for each episode
        self.bg_history = []
        self.insulin_history = initial_insulin

        # ====================
        # Meal setup
        # ====================

        eating_time = 1
        meals, meal_indicator = meal_generator(eating_time=eating_time, premeal_bolus_time=0)

        self.meals = meals
        self.meal_indicator = meal_indicator
        self.eating_time = eating_time

        # Counter for number of iterations
        self.num_iters = 0

        # If blood glucose is less than zero, the simulator is out of bounds.
        self.bg_threshold_low = 0
        self.bg_threshold_high = 500

        # TODO: This number is arbitrary
        self.max_iter = 2160

        # Reward flag
        self.reward_flag = reward_flag

        self.steps_beyond_done = None
예제 #34
0
tend = 2e5 * year

tarr = (tcurrent, tend)

tstep = 1e5 * year

for r in rr:
    afstand = r/AU
    
    mi, mc, nc, ac = input_mass_distribution(a_min,a_max, a_maxp, n_a, r)
    nc = np.asarray(nc)
    sig_d0 = nc * mc

    K,C = coagulation_kernel(ac, mc, r,'bm_pp_set_az')

    ode = spi.ode(ndot_coagulation2,jacobian)

    # BDF method suitable to stiff systems of ODE's
    atol = 1e0 # absolute error
    rtol = 1e-6 # relative error
    with_jacobian = True
    ode.set_integrator('vode', method='bdf', with_jacobian=with_jacobian, nsteps=5000, atol=atol, rtol=rtol)
    ode.set_initial_value(nc, t)
    
    while ode.successful() and ode.t < tend:
        nf = ode.integrate(ode.t + tstep)

    plt.figure(1)
    plt.loglog()
    plt.plot(ac*1e2,nf*mc,label="Radial distance: %s AU" %afstand)
    plt.ylim(1e-19, 1e0)
예제 #35
0
def calculate_path(profile, particle, p, y0, delta_t):
    """
    Calculate the trajectory of a particle

    Calculate the trajectory of a particle by integrating its path using
    the `scipy.integrate.ode` object and associated methods.

    Parameters
    ----------
    profile : `ambient.Profile` object
        Ambient CTD data for the model simulation
    particle : `LagrangianParticle` object
        Object describing the properties and behavior of the particle.
    p : `ModelParams` object
        Collection of model parameters passed to `derivs`.
    y0 : ndarray
        Initial values of the state space (depth in m, masses in kg, and heat
        content in J of the particle) at the release point
    delta_t : float
        Maximum step size (s) to take in the integration

    Notes
    -----
    The differential equation in `derivs` is written with respect to time, so
    the independent variable in this simulation is time.  The vertical
    coordinate; therefore, becomes a dependent variable, along with the masses
    of each component in the particle and the particle temperature.  Thus,
    the state space is::

        y = np.hstack((z0, m0, H0))

    where `H0` is the initial heat content, `m_p * cp * T0`.  The variables
    in the state space can be returned by::

        >>> import seawater
        >>> z = y[2]
        >>> m = y[3:-1]
        >>> T = y[-1] / (np.sum(y[1:-1]) * particle.cp)

    """
    # Create the integrator object:  use "vode" with "backward
    # differentiation formula" for stiff ODEs
    r = integrate.ode(derivs).set_integrator('vode',
                                             method='bdf',
                                             atol=1.e-6,
                                             rtol=1e-3,
                                             order=5,
                                             max_step=delta_t)

    # Initialize the state space
    t0 = 0.
    r.set_initial_value(y0, t0)

    # Set passing variables for derivs method
    r.set_f_params(profile, particle, p)

    # Create vectors (using the list data type) to store the solution
    t = [t0]
    y = [y0]

    # Integrate to the free surface (profile.z_min)
    k = 0
    psteps = 10.
    stop = False
    while r.successful() and not stop:

        # Print progress to the screen
        m0 = np.sum(y[0][3:-1])
        mt = np.sum(y[-1][3:-1])
        f = mt / m0
        if np.remainder(np.float(k), psteps) == 0.:
            print('    Depth:  %g (m), t:  %g (s), k: %d, f: %g (--)' %
                  (r.y[2], t[-1], k, f))

        # Perform one step of the integration
        r.integrate(t[-1] + delta_t, step=True)

        # Store the results
        if particle.K_T == 0:
            # Make the state-space heat correct
            Ta = profile.get_values(r.y[2], 'temperature')
            r.y[-1] = np.sum(r.y[3:-1]) * particle.cp * Ta
        for i in range(len(r.y[3:-1])):
            if r.y[i + 3] < 0.:
                # Concentration should not overshoot zero
                r.y[i + 3] = 0.
        t.append(r.t)
        y.append(r.y)
        k += 1

        # Evaluate stop criteria
        if r.successful():
            # Check if bubble dissolved (us = 0 or based on fdis) or reached
            # the free surface
            us = -(y[-2][2] - y[-1][2]) / (t[-2] - t[-1])
            if r.y[2] <= profile.z_min or us <= 0. or f < particle.fdis:
                stop = True
            if k > 5000:
                stop = True

    # Remove any negative depths due to overshooting the free surface
    t = np.array(t)
    y = np.array(y)
    rows = y[:, 2] >= 0
    t = t[rows]
    y = y[rows, :]

    # Return the solution
    print('    Depth:  %g (m), t:  %g (s), k: %d' % (y[-1, 2], t[-1], k))
    return (t, y)
예제 #36
0

f = lambda x: relu(x - threshold)


def dXdt(X, t=0):
	return (- X + gain * input_signal(t) - np.dot(f(X), feedback_gain))/tau


def dXdt_ode(t, X):
	print X
	return (- X + gain * input_signal(t) - np.dot(f(X), feedback_gain))/tau


X0 = np.zeros((layer_size,))

# X, infodict = integrate.odeint(dXdt, X0, Tvec, full_output=True)
# X_euler = integrate_euler(dXdt, X0, Tvec, dt)


Xseq = list()

r = integrate.ode(dXdt_ode).set_integrator("dopri5", method="bdf")
r.set_initial_value(X0)

while r.successful() and r.t < Tmax:
	
	Xseq.append(r.integrate(r.t + dt))

Xseq = np.asarray(Xseq)
예제 #37
0
파일: bz.py 프로젝트: princeixr/Echo
                point = point + 1
                tn = peak_pos[point]
                tn_1 = peak_pos[point - 1]
                # print(point, i)
            theta.append((i - tn) / (tn - tn_1))
        else:
            theta.append(0)
    return theta


# print(U_ss(x,z))
t = np.linspace(0, 3000, 10000)
delta_t = t[1] - t[0]
print(delta_t)
arr = []
r = ode(model).set_integrator(name="lsoda", method="BDF", nsteps=100000)
r.set_initial_value(y0, 0).set_f_params(n)
for i in range(len(t)):
    print(i)
    r.integrate(r.t + delta_t)
    arr.append(r.y)
arr = np.array(arr)

thetaArr = []
for k in range(n, 2 * n):
    print(k)
    thetaArr.append(theta_func(t, arr[:, k]))
    print(k)
thetaArr = np.array(thetaArr)
R_theta = (1 / n) * abs(np.sum(np.exp(2 * np.pi * 1j * thetaArr), axis=0))
plt.plot(t, R_theta)
예제 #38
0
파일: spes.py 프로젝트: rieder/limepy
    def _poisson(self, potonly):
        """ Solves Poisson equation """
        # y = [phi, u_j, U, K_j], where u = -M(<r)/G

        # Initialize
        self.r = numpy.array([0])
        self._y = numpy.r_[self.phi0, numpy.zeros(2 * self.nmbin + 1)]

        if (not potonly): self._y = numpy.r_[self._y, numpy.zeros(self.nmbin)]

        # Ode solving using Runge-Kutta integator of order 4(5) 'dopri5'
        # (Hairor, Norsett& Wanner 1993)
        max_step = self.maxr if (potonly) else self.max_step
        sol = ode(self._odes)
        sol.set_integrator('dopri5',
                           nsteps=1e6,
                           max_step=max_step,
                           atol=self.ode_atol,
                           rtol=self.ode_rtol)
        sol.set_solout(self._logcheck)
        sol.set_f_params(potonly)
        sol.set_initial_value(self._y, 0)
        sol.integrate(self.maxr)

        # Extrapolate to rt
        derivs = self._odes(self.r[-1], self._y[:, -1], self.potonly)
        self.rt = self.r[-1] - self._y[0][-1] / derivs[0]
        dr = self.rt - self.r[-1]
        ylast = [0]

        for i in range(len(derivs) - 1):
            ylast.append(self._y[1 + i, -1] + derivs[i + 1] * dr)
        self._y = numpy.c_[self._y, ylast]

        # Set the converged flag to True if successful
        if (self.rt < self.maxr) & (sol.successful()):
            self.converged = True
        else:
            self.converged = False

        # Fill arrays needed if potonly=True
        self.r = numpy.r_[self.r, self.rt]
        self.rhat = self.r * 1.0

        self.phihat = numpy.r_[self._y[0, :]]
        self.phi = self.phihat * 1.0
        self.nbound = len(self.phihat)

        self._Mjtot = -sol.y[1:1 + self.nmbin] / self.G

        self.M = sum(self._Mjtot)
        self.Mpe = -sol.y[1 + self.nmbin] / self.G
        self.fpe = self.Mpe / self.M

        # Save the derivative of the potential for the potential interpolater
        dphidr = numpy.sum(self._y[1:1 + self.nmbin, 1:],
                           axis=0) / self.r[1:]**2
        self.dphidrhat1 = numpy.r_[0, dphidr]

        self.A = 1 / (2 * pi * self.s2j)**1.5 / self.rhoint0

        self.mc = -self._y[1, :] / self.G

        # Compute radii to be able to scale in case potonly=True
        self.U = self._y[2 + self.nmbin,
                         -1] - 0.5 * self.G * self.M**2 / self.rt

        # Get half-mass radius from cubic interpolation, because the half-mass
        # radius can be used as a scale length, this needs to be done
        # accurately, a linear interpolation does not suffice. Because the
        # density array is not known yet at this point, we need a temporary
        # evaluation of density in the vicinity of r_h
        ih = numpy.searchsorted(self.mc, 0.5 * self.mc[-1]) - 1
        rhotmp = numpy.zeros(2)
        for j in range(self.nmbin):
            phi = self.phihat[ih:ih + 2] / self.s2j[j]
            rhotmp += self.alpha[j] * self._rhohat(phi, self.r[ih:ih + 2], j)
        drdm = 1. / (4 * pi * self.r[ih:ih + 2]**2 * rhotmp)
        rmc_and_derivs = numpy.vstack([[self.r[ih:ih + 2]], [drdm]]).T

        self.rh = BPoly.from_derivatives(self.mc[ih:ih + 2],
                                         rmc_and_derivs)(0.5 * self.mc[-1])
        self.rv = -0.5 * self.G * self.M**2 / self.U

        # Solve (mass-less) part outside rt
        if (self.nrt > 1):
            # Continue to solve until rlast
            sol.set_solout(self._logcheck2)
            sol.set_f_params(potonly)
            sol.set_initial_value(self._y[:, -1], self.rt)
            sol.integrate(self.nrt * self.rt)

        self.rhat = self.r * 1.0
        self.phihat = numpy.r_[self.phihat, self._y[0, self.nbound:]]
        self.mc = numpy.r_[self.mc,
                           numpy.zeros(len(self._y[0, self.nbound:])) +
                           self.mc[-1]]
        self.phi = self.phihat * 1.0

        dphidr = numpy.sum(self._y[1:1 + self.nmbin, self.nbound:],
                           axis=0) / self.r[self.nbound:]**2
        self.dphidrhat1 = numpy.r_[self.dphidrhat1, dphidr]

        # Additional stuff
        if (not potonly):
            # Calculate kinetic energy
            self.K = numpy.sum(sol.y[4:5])

            # Calculate density and velocity dispersion components
            if (not self.multi):
                self.rhohat = self._rhohat(self.phihat, self.r, 0)
                self.rhohatpe = self._rhohatpe(self.phihat, self.r, 0)
                self.rho = self.rhohat * 1.0
                self.rhope = self.rhohatpe * 1.0

                self.v2 = self._get_v2(self.phihat, self.rhohat, 0)
예제 #39
0
    def PlotEvent(self, GraphicsObject, LU, TU, mu, PlotOptions):
        #switch between different event types
        if self.EventType == "launch" or self.EventType == "departure":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='g',
                                   marker='^')
        elif self.EventType == "begin_spiral" or self.EventType == "end_spiral":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='orange',
                                   marker='^')
        elif self.EventType == "upwr_flyby":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='b',
                                   marker=r'$\circlearrowleft$')
        elif self.EventType == "pwr_flyby":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='r',
                                   marker=r'$\circlearrowleft$')
        elif self.EventType == "chem_burn":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='r',
                                   marker='o')
        elif self.EventType == "SFthrust" or self.EventType == "PSBIthrust" or self.EventType == "coast" or self.EventType == "force-coast":
            color = ''
            if self.EventType == "coast":
                linestyle = '--'
                color = 'k'
                weight = 1
            elif self.EventType == "SFthrust" or self.EventType == "PSBIthrust":
                linestyle = '-'
                color = 'k'
                weight = 2
                if PlotOptions.ShowThrustVectors:
                    ControlVector = np.array(
                        self.Thrust) / self.AvailableThrust * LU * 0.1
                    GraphicsObject.plot(self.SpacecraftState[0] +
                                        np.array([0.0, ControlVector[0]]),
                                        self.SpacecraftState[1] +
                                        np.array([0.0, ControlVector[1]]),
                                        self.SpacecraftState[2] +
                                        np.array([0.0, ControlVector[2]]),
                                        c='r',
                                        lw=2)

            else:
                linestyle = '--'
                color = 'b'
                weight = 1

            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=1,
                                   c=color,
                                   marker='o')

            if PlotOptions.ShowPropagatedTrajectory:
                CenterPointState = np.zeros(6)
                CenterPointState[0:6] = np.array(self.SpacecraftState) / LU
                CenterPointState[3:6] *= TU
                CenterPointStateAfterManeuver = copy.deepcopy(CenterPointState)
                CenterPointStateAfterManeuver[3:6] += np.array(
                    self.DeltaVorThrustVectorControl) * TU / LU

                ForwardIntegrateObject = ode(
                    EOM.EOM_inertial_2body).set_integrator('dop853',
                                                           atol=1.0e-6,
                                                           rtol=1.0e-6)
                ForwardIntegrateObject.set_initial_value(
                    CenterPointStateAfterManeuver).set_f_params(
                        1.0).set_jac_params(1.0)

                dt = self.TimestepLength * 86400.0 / TU / 10
                StateHistoryForward = []
                while ForwardIntegrateObject.successful(
                ) and ForwardIntegrateObject.t < self.TimestepLength * 86400.0 / TU / 2.0:
                    ForwardIntegrateObject.integrate(ForwardIntegrateObject.t +
                                                     dt)
                    StateHistoryForward.append(ForwardIntegrateObject.y * LU)

                BackwardIntegrateObject = ode(
                    EOM.EOM_inertial_2body).set_integrator('dop853',
                                                           atol=1.0e-6,
                                                           rtol=1.0e-6)
                BackwardIntegrateObject.set_initial_value(
                    CenterPointState).set_f_params(1.0).set_jac_params(1.0)

                dt = self.TimestepLength * 86400.0 / TU / 10
                StateHistoryBackward = []
                while BackwardIntegrateObject.successful(
                ) and BackwardIntegrateObject.t > -self.TimestepLength * 86400.0 / TU / 2.0:
                    BackwardIntegrateObject.integrate(
                        BackwardIntegrateObject.t - dt)
                    StateHistoryBackward.append(BackwardIntegrateObject.y * LU)

                StateHistoryBackward.reverse()

                X = []
                Y = []
                Z = []
                for StateLine in StateHistoryBackward:
                    X.append(StateLine[0])
                    Y.append(StateLine[1])
                    Z.append(StateLine[2])
                for StateLine in StateHistoryForward:
                    X.append(StateLine[0])
                    Y.append(StateLine[1])
                    Z.append(StateLine[2])

                GraphicsObject.plot(X, Y, Z, lw=weight, c=color, ls=linestyle)

        elif self.EventType == "FBLTthrust" or self.EventType == "FBLTSthrust":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=2,
                                   c='k',
                                   marker='o')

            if PlotOptions.ShowThrustVectors:
                ControlVector = np.array(
                    self.Thrust) / self.AvailableThrust * LU * 0.1
                GraphicsObject.plot(self.SpacecraftState[0] +
                                    np.array([0.0, ControlVector[0]]),
                                    self.SpacecraftState[1] +
                                    np.array([0.0, ControlVector[1]]),
                                    self.SpacecraftState[2] +
                                    np.array([0.0, ControlVector[2]]),
                                    c='r',
                                    lw=2)

            if PlotOptions.ShowPropagatedTrajectory:
                CenterPointState = np.zeros(7)
                CenterPointState[0:6] = np.array(self.SpacecraftState) / LU
                CenterPointState[3:6] *= TU
                CenterPointState[6] = 1.0
                ScaledThrust = np.array(
                    self.Thrust) * TU * TU / 1000.0 / self.Mass / LU
                ScaledMdot = self.MassFlowRate / self.Mass * TU

                ForwardIntegrateObject = ode(
                    EOM.EOM_inertial_2bodyconstant_thrust).set_integrator(
                        'dop853', atol=1.0e-6, rtol=1.0e-6)
                ForwardIntegrateObject.set_initial_value(
                    CenterPointState).set_f_params(ScaledThrust, ScaledMdot,
                                                   1.0).set_jac_params(
                                                       ScaledThrust,
                                                       ScaledMdot, 1.0)

                dt = self.TimestepLength * 86400.0 / TU / 10
                StateHistoryForward = []
                while ForwardIntegrateObject.successful(
                ) and ForwardIntegrateObject.t < self.TimestepLength * 86400.0 / TU / 2.0:
                    ForwardIntegrateObject.integrate(ForwardIntegrateObject.t +
                                                     dt)
                    StateHistoryForward.append(ForwardIntegrateObject.y * LU)

                BackwardIntegrateObject = ode(
                    EOM.EOM_inertial_2bodyconstant_thrust).set_integrator(
                        'dop853', atol=1.0e-6, rtol=1.0e-6)
                BackwardIntegrateObject.set_initial_value(
                    CenterPointState).set_f_params(ScaledThrust, ScaledMdot,
                                                   1.0).set_jac_params(
                                                       ScaledThrust,
                                                       ScaledMdot, 1.0)

                dt = self.TimestepLength * 86400.0 / TU / 10
                StateHistoryBackward = []
                while BackwardIntegrateObject.successful(
                ) and BackwardIntegrateObject.t > -self.TimestepLength * 86400.0 / TU / 2.0:
                    BackwardIntegrateObject.integrate(
                        BackwardIntegrateObject.t - dt)
                    StateHistoryBackward.append(BackwardIntegrateObject.y * LU)

                StateHistoryBackward.reverse()

                X = []
                Y = []
                Z = []
                for StateLine in StateHistoryBackward:
                    X.append(StateLine[0])
                    Y.append(StateLine[1])
                    Z.append(StateLine[2])
                for StateLine in StateHistoryForward:
                    X.append(StateLine[0])
                    Y.append(StateLine[1])
                    Z.append(StateLine[2])

                GraphicsObject.plot(X, Y, Z, lw=2, c='k')

        elif self.EventType == "insertion":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='r',
                                   marker='v')
        elif self.EventType == "LT_rndzvs":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='m',
                                   marker='o')
        elif self.EventType == "intercept":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='m',
                                   marker='d')
        elif self.EventType == "rendezvous":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='r',
                                   marker='d')
        elif self.EventType == "match-vinf":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='c',
                                   marker='s')
        elif self.EventType == "match_point":
            GraphicsObject.scatter(self.SpacecraftState[0],
                                   self.SpacecraftState[1],
                                   self.SpacecraftState[2],
                                   s=4,
                                   c='k',
                                   marker='s')

        if PlotOptions.ShowTextDescriptions and not (
                self.EventType == 'zeroflyby' or self.EventType == 'coast' or
                self.EventType == 'force-coast' or self.EventType == "SFthrust"
                or self.EventType == "FBLTthrust" or self.EventType
                == "PSBIthrust" or self.EventType == "match_point"
                or self.EventType == "waiting"):
            self.LabelEvent(GraphicsObject, PlotOptions)
예제 #40
0
def move_rob(adj_Mat, num_Nodes, num_Edges, a, b, c, fileName, test=0):

    global adjMat
    global numNodes
    global numEdges
    global alpha
    global beta
    global gamma
    global init
    global score
    global edgeList
    global xdiff
    global np_pos
    global t1

    adjMat = adj_Mat
    numNodes = num_Nodes
    numEdges = num_Edges
    alpha = a
    beta = b
    gamma = c

    count = 0
    score = []

    while count < 10:

        init = []
        edgeList = []
        t_rob = []
        nodes = []
        near_axis = random.choice(range(numNodes))
        for i in range(numNodes):
            if (i == near_axis):
                init.append(random.uniform(0.89, 0.99))
            else:
                init.append(random.uniform(0.01, 0.11))

        for i in range(numNodes):
            for j in range(numNodes):
                if (adjMat[i][j] == 1):
                    edgeList.append((i, j))
                    init.append(random.uniform(0.01, 0.11))
        init.append(random.random())

        xdiff = random.uniform(-0.3, 0.3)
        t1 = int(random.random() * 200 + 200)
        st_pos = (8.0 / 9) + xdiff

        x_target = 0.5

        x_rob = []
        x_cur = 0
        r = ode(model).set_integrator('vode', rtol=10e-3, atol=10e-6)
        r.set_initial_value(init)
        dt = 0.05
        while r.successful() and r.t < t1:
            x_cur = r.y[-1]
            x_rob.append(x_cur % 1)
            nodes.append(r.y[0:-1])
            t_rob.append(r.t)
            r.integrate(t1, step=True)

        if (test == 1):
            plt.figure()
            plt.subplot(311)
            for i in range(numNodes):
                plt.plot(t_rob, [node[i] for node in nodes],
                         label="p" + str(i + 1))
            plt.legend(loc="upper right")

            plt.subplot(312)
            for i in range(numEdges):
                plt.plot(t_rob, [node[numNodes + i] for node in nodes],
                         label="t" + str(i + 1))
            plt.legend(loc="upper right")

            plt.subplot(313)
            plt.scatter(t_rob, [x for x in x_rob],
                        s=0.1,
                        label="Robot position")
            plt.xlabel("Alpha:" + str(alpha))
            plt.legend(loc="upper right")
            plt.show()
            return

        rob_dist = [
            abs(pos - x_target) for pos in x_rob[int(0.8 * len(x_rob)):]
        ]

        score_val = np.max(rob_dist)

        score.append(score_val)
        count += 1

    mean_score = np.mean(score)
    print "Mean of max distance:" + str(mean_score)
    if (mean_score < 0.1):
        file = open("value" + fileName + ".txt", 'a+')
        file.write("Score=" + str(mean_score) + '\n')
        file.write("alpha=" + str(alpha) + '\n')
        file.write("beta=" + str(beta) + '\n')
        file.write("gamma=" + str(gamma) + '\n')
        file.write('\n')
        file.close()
    return mean_score
예제 #41
0
def find_rotational_ic(body_dict, print_time=False):
    """
    """

    now = time.time()

    from scipy.integrate import ode

    # turn off aerodynamic forces
    body_dict = body_dict.copy()  # just to be safe
    body_dict['aero_interp'] = None

    ang0 = np.r_[0, 0, 0]  # horizontal flight
    omg0 = np.r_[0, 0, 0]  # no angular velocity

    # v0_non = 1.7 / np.sqrt(2 * 29 / rho)  # .2409, Ws=29
    soln0 = np.r_[omg0, ang0]

    # pick a velocity in the VPD (ignored in rotation function)
    dRo0 = np.r_[0, 0, 0]

    # arguments to the rotation dynamics function
    vel_body_dict = (dRo0, body_dict)

    # phases in cycle to simulate rotational dynamics
    ntime_rot = 200  # 200
    tend = 1 / body_dict['theta_dict']['f_theta']
    ts_rot = np.linspace(0, tend, ntime_rot + 1)[:-1]

    solver = ode(rotational_dynamics_eom)
    solver.set_integrator('dopri5')
    solver.set_initial_value(soln0, ts_rot[0])  # x0, t0
    solver.set_f_params(vel_body_dict)

    # integrate over one undulation cycle
    i = 1
    soln_rot = [soln0]
    while i < ntime_rot:
        t1 = time.time()
        if print_time and i % 10 == 0:
            print('Phase {} of {} in find_rotational_ic'.format(i, ntime_rot))
        solver.integrate(ts_rot[i])
        out = solver.y

        soln_rot.append(out)
        i = i + 1
        t2 = time.time()
        if print_time and i % 10 == 0:
            print('\t{0:.3f} sec'.format(t2 - t1))

    if print_time:
        print('Find rotational IC: {0:.3f} sec'.format(time.time() - now))

    # unpack the solution
    soln_rot = np.array(soln_rot)
    wx, wy, wz, yaw, pitch, roll = soln_rot.T
    ang = np.c_[yaw, pitch, roll]
    # omg = np.c_[wx, wy, wz]

    # initial yaw, pitch, and roll angles in radians
    return -ang.mean(axis=0)
예제 #42
0
파일: hamiltonian.py 프로젝트: ndavila/FRIB
	i = -1
	k = 0
	file = open('hamil.txt','r')
	for j,line in enumerate(file):
		if j % n == 0:
			i += 1
			k = 0
		elem = float(line)
		Ax[i] += elem*x[k]
		k+=1
	file.close()
	return(-(x.T@x)*Ax + (x.T@Ax)*x)



r = ode(f)
r.set_initial_value(x,0) #langsos algorithm

t1=10
dt=0.1
start = time.time()
while r.successful() and r.t < t1:
	r.integrate(r.t+dt)
end = time.time()



print("RNN eig: ",r.y.T@[email protected]/([email protected]))
print("calculation time with RNN: ", end - start)

예제 #43
0
      
      return At
                  
 
  #integrate the preallocated FSP
  def FSPCalc_ODE_prealloc(self,parameters,TimeVar,case,N,x0,t,error):
      errorcheck = 0
      
      
      while errorcheck == 0:
          FSP = lambda g,x: np.ravel(np.dot(At[0][g],np.array([x]).T))
          
          #ode15s.set_integrator('vode', method='bdf', order=15, nsteps=3000)
          At = self.Test_A(parameters,N,TimeVar,case,t)
          Jac = lambda x,t: At[t]
          ode15s = ode(FSP,jac=Jac)
          ode15s.set_integrator('dopri5',nsteps=3000)
          ode15s.set_initial_value(x0, t[0]) 
          solution = np.empty((len(t),3*N))
          solution[0,:] = x0[:,0]
      
          for g in range(1,len(t)):
              ode15s.set_initial_value(solution[g-1,:],t[g-1])
                              
              solution[g,:] = ode15s.integrate(g)            
          errorcheck = 1
          for i in range(0,len(t)):
              if 1-sum(solution[i]) > error:
                  errorcheck = 0
                  
          if errorcheck == 0:
    
    dx[2] = x[2]*(mupr*x[0]/(kpr/mr+x[0]) + \
    mupc*x[1]/(kpc/mc+x[1])-dp) - D*x[2]
    
    dx[3] = D*N0 - x[0]*munr*mr/ynr*x[3]/(knr+x[3]) - \
    x[1]*munc*mc/ync*x[3]/(knc+x[3]) - D*x[3]
    
    return dx
    
##### Solve procedure goes here #####
Rsol = []; Csol = []; Psol = []; Nsol = []
Rsol.append(x0[0])
Csol.append(x0[1])
Psol.append(x0[2])
Nsol.append(x0[3])
r = ode(becks4Eq).set_integrator('dopri5',nsteps=100000,verbosity=1)
r.set_initial_value(x0,0).set_f_params(N0,D)
for t in tpts[1:]:
    if STOC_D:
        D_t = sp.random.gamma(D**2/var_D,var_D/D)
    else:
        D_t = D
    r.set_f_params(N0,D_t)
    r.integrate(t)
    assert(r.successful())
    Rsol.append(r.y[0])
    Csol.append(r.y[1])
    Psol.append(r.y[2])
    Nsol.append(r.y[3])
    
##### Plot solution #####
예제 #45
0
def main():
  # grab delta and g from the command line
  delta      = float(argv[1])
  g          = float(argv[2])

  particles  = 4

  # setup shared data
  dim1B     = 8

  # this defines the reference state
  # 1st state
  holes     = [0,1,2,3]
  particles = [4,5,6,7]

  # 2nd state
  # holes     = [0,1,4,5]
  # particles = [2,3,6,7]

  # 3rd state
  # holes     = [0,1,6,7]
  # particles = [2,3,4,5]

  # basis definitions
  bas1B     = range(dim1B)
  bas2B     = construct_basis_2B(holes, particles)
  basph2B   = construct_basis_ph2B(holes, particles)

  idx2B     = construct_index_2B(bas2B)
  idxph2B   = construct_index_2B(basph2B)

  # occupation number matrices
  occ1B     = construct_occupation_1B(bas1B, holes, particles)
  occA_2B   = construct_occupationA_2B(bas2B, occ1B)
  occB_2B   = construct_occupationB_2B(bas2B, occ1B)
  occC_2B   = construct_occupationC_2B(bas2B, occ1B)

  occphA_2B = construct_occupationA_2B(basph2B, occ1B)

  # store shared data in a dictionary, so we can avoid passing the basis
  # lookups etc. as separate parameters all the time
  user_data  = {
    "dim1B":      dim1B, 
    "holes":      holes,
    "particles":  particles,
    "bas1B":      bas1B,
    "bas2B":      bas2B,
    "basph2B":    basph2B,
    "idx2B":      idx2B,
    "idxph2B":    idxph2B,
    "occ1B":      occ1B,
    "occA_2B":    occA_2B,
    "occB_2B":    occB_2B,
    "occC_2B":    occC_2B,
    "occphA_2B":  occphA_2B,

    "eta_norm":   0.0,                # variables for sharing data between ODE solver
    "dE":         0.0,                # and main routine


    "calc_eta":   eta_white,          # specify the generator (function object)
    "calc_rhs":   flow_imsrg2         # specify the right-hand side and truncation
  }

  # set up initial Hamiltonian
  H1B, H2B = pairing_hamiltonian(delta, g, user_data)

  E, f, Gamma = normal_order(H1B, H2B, user_data) 

  # reshape Hamiltonian into a linear array (initial ODE vector)
  y0   = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1)))

  # integrate flow equations 
  solver = ode(derivative_wrapper,jac=None)
  solver.set_integrator('vode', method='bdf', order=5, nsteps=1000)
  solver.set_f_params(user_data)
  solver.set_initial_value(y0, 0.)

  sfinal = 50
  ds = 0.1

  print "%-8s   %-14s   %-14s   %-14s   %-14s   %-14s   %-14s   %-14s   %-14s"%(
    "s", "E" , "DE(2)", "DE(3)", "E+DE", "dE/ds", 
    "||eta||", "||fod||", "||Gammaod||")
  # print "-----------------------------------------------------------------------------------------------------------------"
  print "-" * 148
  while solver.successful() and solver.t < sfinal:
    ys = solver.integrate(sfinal, step=True)
    
    dim2B = dim1B*dim1B
    E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B)

    DE2 = calc_mbpt2(f, Gamma, user_data)
    DE3 = calc_mbpt3(f, Gamma, user_data)

    norm_fod     = calc_fod_norm(f, user_data)
    norm_Gammaod = calc_Gammaod_norm(Gamma, user_data)

    print "%8.5f %14.8f   %14.8f   %14.8f   %14.8f   %14.8f   %14.8f   %14.8f   %14.8f"%(
      solver.t, E , DE2, DE3, E+DE2+DE3, user_data["dE"], user_data["eta_norm"], norm_fod, norm_Gammaod)
    if abs(DE2/E) < 10e-8: break
예제 #46
0
    def integrate(self, dt, planets):
        """Update the planet masses and radii:

        args:
            dt      : Time to integrate for
            planets : Planets container
        """
        if planets.N == 0: return
        self.update()

        chem = False
        if planets.chem:
            chem = True

        f = self._f_gas

        def dMdt(R_p, M_core, M_env):
            Mdot_s = self._peb_acc.computeMdot(R_p, M_core + M_env)
            Mdot_g = self._gas_acc.computeMdot(R_p, M_core, M_env)

            return Mdot_s * (1 - f), Mdot_g + Mdot_s * f

        def dRdt(R_p, M_core, M_env):
            if self._migrate:
                return self._migrate.migration_rate(R_p, M_core + M_env)
            else:
                return np.zeros_like(R_p)

        N = planets.N
        Rmin = self._disc.R[0]

        def f_integ(_, y):
            R_p = y[:N]
            M_core = y[N:2 * N]
            M_env = y[2 * N:3 * N]

            Rdot = dRdt(R_p, M_core, M_env)
            Mcdot, Medot = dMdt(R_p, M_core, M_env)

            accreted = R_p <= Rmin
            Rdot[accreted] = Mcdot[accreted] = Medot[accreted] = 0

            dydt = np.empty_like(y)
            dydt[:N] = Rdot
            dydt[N:2 * N] = Mcdot
            dydt[2 * N:3 * N] = Medot

            if chem:
                Xs, Xg = self._compute_chem(R_p)

                #Ms = Mcdot * f / (1-f)
                Ms = 0
                Mg = np.maximum(Medot - Mcdot, 0)
                Nspec = Xs.shape[0]
                dydt[3 * N:(3 + Nspec) * N] = (Mcdot * Xs).ravel()
                dydt[(3 + Nspec) * N:(3 + 2 * Nspec) * N] = (Ms * Xs +
                                                             Mg * Xg).ravel()

            return dydt

        integ = ode(f_integ).set_integrator('dopri5', rtol=1e-5, atol=1e-5)

        if chem:
            Chem_core = (planets.M_core * planets.X_core).flat
            Chem_env = (planets.M_env * planets.X_env).flat
            X0 = np.concatenate([
                planets.R, planets.M_core, planets.M_env, Chem_core, Chem_env
            ])
        else:
            X0 = np.concatenate([planets.R, planets.M_core, planets.M_env])
        integ.set_initial_value(X0, 0)

        integ.integrate(dt)

        # Compute the fraction of the core / envelope that was accreted in
        # solids

        planets.R = integ.y[:N]
        planets.M_core = integ.y[N:2 * N]
        planets.M_env = integ.y[2 * N:3 * N]

        if chem:
            Ns = np.prod(planets.X_core.shape)
            Xc = integ.y[3 * N:3 * N + Ns].reshape(-1, N)
            Xe = integ.y[3 * N + Ns:3 * N + 2 * Ns].reshape(-1, N)
            planets.X_core = Xc / np.maximum(planets.M_core, 1e-300)
            planets.X_env = Xe / np.maximum(planets.M_env, 1e-300)
예제 #47
0
def integrate_triple_system(ics,
                            timemin,
                            timemax,
                            Nevals,
                            body0,
                            body1,
                            body2,
                            octupole_potential=True,
                            short_range_forces_conservative=False,
                            short_range_forces_dissipative=False,
                            solve_for_spin_vector=False,
                            version='tides',
                            tol=1.0e-10,
                            integrator='scipy',
                            add_derivatives=False):

    atol = tol
    rtol = tol / 10.0
    rtol = 1.0e-8

    m0, m1, m2 = body0.mass, body1.mass, body2.mass
    radius0, radius1 = body0.radius, body1.radius
    dradius0_dt, dradius1_dt = body0.dradius_dt, body1.dradius_dt
    gyroradius0, gyroradius1 = body0.gyroradius, body1.gyroradius
    dgyroradius0_dt, dgyroradius1_dt = body0.dgyroradius_dt, body1.dgyroradius_dt
    k2_0, k2_1 = body0.apsidal_constant, body1.apsidal_constant
    tv0, tv1 = body0.viscous_time, body1.viscous_time
    tauconv0, tauconv1 = body0.convective_time, body1.convective_time
    tlag0, tlag1 = body0.tidal_lag_time, body1.tidal_lag_time

    rtol, atol = np.zeros(len(ics)), np.zeros(len(ics))
    for key, val in triples.triple_keys.items():
        if val is not None:
            rtol[val] = 10 * triple_precision[key]
            atol[val] = triple_precision[key]

    #rtol,atol = 1.e-9,1.e-08

    #integrator='other'
    #integrator = 'bsint'

    time = np.linspace(timemin, timemax, Nevals)
    params = m0,m1,m2,radius0,radius1,gyroradius0,gyroradius1,k2_0,k2_1,\
             tv0,tv1,tauconv0,tauconv1,\
             tlag0,tlag1,\
             dradius0_dt, dradius1_dt,\
             dgyroradius0_dt, dgyroradius1_dt,\
             octupole_potential,\
             short_range_forces_conservative,short_range_forces_dissipative,solve_for_spin_vector

    if (integrator == 'scipy'):
        if (version == 'tides'):
            params = m0,m1,m2,radius0,radius1,gyroradius0,gyroradius1,k2_0,k2_1,tv0,tv1,\
                     octupole_potential,\
                     short_range_forces_conservative,short_range_forces_dissipative,solve_for_spin_vector

            sol =integ.odeint(threebody_ode_vf_tides_modified,ics,time,\
                              args=params,\
                              atol=atol,rtol=rtol,mxstep=1000000,hmin=0.0000001,mxords=16,mxordn=12)
        elif (version == 'full'):
            sol =integ.odeint(threebody_ode_vf_full_modified,ics,time,\
                              args=params,\
                              atol=atol,rtol=rtol,mxstep=1000000,hmin=0.000000001,mxords=12,mxordn=10)
            if (add_derivatives):
                for kk, y in enumerate(sol):
                    if (kk == 0):
                        dsol_dt = threebody_ode_vf_full_modified(
                            y, time[kk],
                            *params)[:len(triples.triple_derivative_keys)]
                    else:
                        dsol_dt = np.vstack(
                            (dsol_dt,
                             threebody_ode_vf_full_modified(
                                 y, time[kk],
                                 *params)[:len(triples.triple_derivative_keys)]
                             ))

    else:
        if (version == 'tides'):
            params = [p for p in params if p is not None]
            solver = integ.ode(threebody_ode_vf_tides).set_integrator(
                'dopri', nsteps=3000000, atol=atol, rtol=rtol, method='bdf')
        elif (version == 'full'):
            #solver = integ.ode(threebody_ode_vf_full).set_integrator('lsoda',nsteps=3000000,atol=atol,rtol=rtol, method='bdf',min_step=0.00001,max_order_ns=10)
            solver = integ.ode(threebody_ode_vf_full).set_integrator(
                'dopri', nsteps=3000000, atol=atol, rtol=rtol, method='bdf')

        solver.set_initial_value(ics, time[0]).set_f_params(*params)
        kk = 1
        sol = []
        sol.append(ics)
        while solver.successful() and solver.t < time[-1]:
            solver.integrate(time[kk])
            sol.append(solver.y)
            kk += 1
        sol = np.asarray(sol)

    retval = np.column_stack((time, sol))

    if add_derivatives: retval = retval, dsol_dt

    return retval
예제 #48
0
               2 * i] = -delta * X[3 + i * 2] - a * X[2 + i * 2] - 3 * b * X[
                   2 + i *
                   2] * X[0]**2  #xprime acceleration for orthagnormal vectors
        xprime[2 + 2 * i] = X[3 +
                              i * 2]  #xprime velocity for orthagnormal vectors
    return xprime  #returns matrix of velocitys and accelerations


orbits = 100  #number of orbits
dt = 0.5  #time step
"""Setting initial conditions for normalised linear system (remember python starts counting at 0)"""
x[2] = 1
x[5] = 1

backend = 'dopri5'  #Integration method
r = ode(duffing).set_integrator(backend)
t = 0
r.set_initial_value(x, t)
counter = 0
t1 = orbits * 2 * np.pi * w
while r.successful(
) and tlist[-1] < t1:  #will integrate up until t1 time is reached
    r.integrate(
        r.t + dt
    )  #step=True means that variable steps are used, with more steps where gradient is close to zero.
    tlist.append(r.t)  #adds results to already created lists
    x = r.y
    #Normalise first vector
    for j in range(0, n):
        zvector[0] = zvector[0] + (x[n * (j + 1)])**2
    zvector[0] = np.sqrt(zvector[0])
예제 #49
0
def dyn(R0, ModVar, UseOp, tobsEnd, tol):
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.integrate import ode
    from scipy import optimize
    from gammamin_fzero import minimize_gammamin
    from nextstep_ode import nextstep_func
    if UseOp.save_params:
        import os
    if tol < 1e-5:
        print_error = True
    else:
        print_error = False

    c, pi, mp, me, kB = 2.9979e10, np.pi, 1.6726e-24, 9.1094e-28, 1.38065e-16
    qe = 4.803204e-10
    sigma_B = 5.6704e-5  ### Stephan Boltzann constant in cgs
    rad_const = 4 * sigma_B / c  #### Radiation constant
    #Initial conditions
    #ModVar.M0 = ModVar.E0*c**-2
    if UseOp.reverseShock: grandNan = [float('nan')] * 19
    else: grandNan = [float('nan')] * 12

    useSpread = True  #If you want to turn spread off, turn it off on this line!

    UseOp.remix_radloss = True
    UseOp.continuous_radloss = True

    #################
    ### Constants ###
    #################

    mup, mue = 1., me / mp
    sigmaT = 6.6524e-25
    numeric_Eint = True  ### numeric or analytical approach to solve Eint?

    ##############################
    ### Runge-Kutta 853 method ###
    ##############################
    """
    0 - tburst
    1 - tcomoving
    2 - Gamma
    3 - Eint2
    4 - Eint3
    5 - theta
    6 - Erad2
    7 - Erad3
    8 - Esh2
    9 - Esh3
    10 - Ead2
    11 - Ead3
    12 - M2
    13 - M3
    14 - deltaR4
    """

    ### Allocating space and setting initial values
    Rstop = 1e23
    nsteps = int(np.ceil(100 * np.log10(Rstop / R0)))

    beta0 = 1 - 0.5 / ModVar.Gamma0**2 - 1 / 8. / ModVar.Gamma0**4
    beta0c = beta0 * c

    M20 = 2 * pi * R0**3 * (1 - np.cos(ModVar.theta0)) * ModVar.A0 * (
        mp + me) * R0**-ModVar.s / 3
    tburst0, tcomoving0 = R0 / beta0c, R0 / beta0c / ModVar.Gamma0
    tobs, rho, B = np.zeros(nsteps), np.zeros(nsteps), np.zeros(nsteps)
    Eint20 = M20 * (ModVar.Gamma0 - 1) * c**2
    gamma_c_w = np.zeros(nsteps)
    gamma_c_w[0] = 6 * me * c / (
        ModVar.A0 * R0**(-ModVar.s) * (mp + me)
    ) / sigmaT / 8 / tcomoving0 / ModVar.eB / Eint20 * M20  ### Mass weighted cooling Lorentz factor

    if UseOp.reverseShock:
        gamma_c_w_RS = np.ones(nsteps)
        gamma_c_w_RS *= float('inf')

        rho4, BRS, gamma43_minus_one = np.zeros(nsteps), np.zeros(
            nsteps), np.zeros(nsteps)

        alpha_of = ModVar.tprompt * beta0c
        shutOff = False
    if ModVar.theta0 < 1e-3:
        one_minus_costheta0 = ModVar.theta0**2 / 2 - ModVar.theta0**4 / 24 + ModVar.theta0**6 / 120
    else:
        one_minus_costheta0 = 1 - np.cos(ModVar.theta0)

    initial_values = [
        tburst0, tcomoving0, ModVar.Gamma0,
        (ModVar.Gamma0 - 1) * M20 / ModVar.M0, 0., ModVar.theta0, 0., 0., 0.,
        0., 0., 0., M20 / ModVar.M0, 0., 0.
    ]
    #initial_values = [tburst0,tcomoving0,ModVar.Gamma0,(ModVar.Gamma0-1)*M20/ModVar.M0,0.,ModVar.theta0,0.,0.,0.,0.,0.,0.,M20/ModVar.M0,0.,0.] ### Logarithmic
    """
    ### An initial very small step, to initialize reverse shock quantities
    infmal_R0 = R0*1e-9

    initial_values += nextstep_func(R0 , initial_values , s , ModVar.Gamma0  , z , ModVar.theta0 , ModVar.tprompt , ModVar.M0 , ModVar.A0/ModVar.M0 , ModVar.R_ISM , [UseOp.radiativeLosses,remix_radloss,continuous_radloss,fixed_epsilon,UseOp.reverseShock,UseOp.exponential_outflow] , [ModVar.epsilone,ModVar.eB,p,ModVar.epsilone3,ModVar.eB3,pRS],float('inf'),float('inf')) * infmal_R0
    

    R0 = R0 + infmal_R0
    """
    odeinstance = ode(nextstep_func)
    #firststep = R0/10000
    odeinstance.set_integrator("dop853",
                               rtol=1e-5,
                               nsteps=100000,
                               first_step=R0 * 1e-9)
    if UseOp.reverseShock:
        odeinstance.set_f_params(ModVar, UseOp, float('inf'), float('inf'),
                                 False)
    else:
        odeinstance.set_f_params(ModVar, UseOp, float('inf'))

    odeinstance.set_initial_value(initial_values, R0)

    R = np.zeros(nsteps)
    out = np.zeros([nsteps, len(initial_values)])
    for i in range(nsteps):

        ###################
        ### Integrating ###
        ###################

        nextR = R0 * (Rstop / R0)**(float(i + 1) / float(nsteps))

        #try:
        out[i] = odeinstance.integrate(nextR)
        """
        except:
            while firststep > 1:
                if i == 0:
                    firststep /= 10
                    print 'reducing first step to %s'%(firststep)
                    try:
                        odeinstance.set_integrator("dop853", rtol=1e-3, nsteps=100000, first_step=firststep)
                        out[i] = odeinstance.integrate(nextR)
                        break
                    except:
                         firststep /= 10
                   
                else:
                    print '\n\n\n!!!\n\n\n'
                    raise NameError('i is not 0 and nextstep_ode.py still crashed')
        """
        R[i] = np.copy(odeinstance.t)
        tobs[i] = (1 + ModVar.z) * (out[i, 0] - R[i] / c)
        beta = np.sqrt(1 - out[i, 2]**-2)

        ######################################
        ### Magnetic fields and densities  ###
        ######################################

        rho1_fac = ModVar.A0 * (mp + me)
        if ModVar.s == 0:  ### CM
            rho[i] = ModVar.A0 * (mp + me)
        else:
            if R[i] < ModVar.R_ISM:
                rho[i] = ModVar.A0 * R[i]**(-ModVar.s) * (mp + me)
            else:
                rho[i] = ModVar.A0 * R[i]**(-ModVar.s) * (mp + me)

        rho2 = 4 * rho1_fac * out[i, 2] * R[i]**(-ModVar.s)
        B_fac = np.sqrt(8 * pi * ModVar.eB)
        B[i] = B_fac * np.sqrt(out[i, 3]) / np.sqrt(out[i, 12]) * np.sqrt(
            rho2
        ) * c  ### Factor c is because Eint is on the form E/ModVar.M0/c**2 and M on the form M/ModVar.M0
        gamma_max = (6 * pi * qe / sigmaT / B[i])**.5
        if UseOp.reverseShock:
            if out[i, 4] < 0:  ### Negative energy in the RS
                out[i, 4] = 0.
            if beta < 0.99:
                gamma43_minus_one[i] = out[i, 2] * ModVar.Gamma0 * (
                    1 - beta * beta0)
            else:
                gamma43_minus_one[i] = out[i, 2] * ModVar.Gamma0 * (
                    1 / ModVar.Gamma0**2 + 1 / out[i, 2]**2 - 1 /
                    out[i, 2]**2 / ModVar.Gamma0**2) / (1 + beta * beta0) - 1
            if out[i, 13] > 0:
                rho4_fac_1 = ModVar.M0 / 2 / alpha_of / np.pi / one_minus_costheta0
                rho4_fac = rho4_fac_1 / R[i]**2
                rho4[i] = rho4_fac * np.exp(-out[i, 14] / alpha_of)
                if rho4[i] < 1e-60:
                    rho4[i] = 0.  ### Avoiding numerical overflows
                    BRS[i] = 0.
                    shutOff = True
                    odeinstance.set_f_params(ModVar, UseOp, gamma_c_w[i],
                                             gamma_c_w_RS[i], shutOff)

                else:
                    rho3 = 4 * out[i, 2] * rho4[i]
                    BRS_fac = np.sqrt(8 * pi * ModVar.eB3)
                    BRS[i] = BRS_fac * np.sqrt(out[i, 4]) / np.sqrt(
                        out[i, 13]
                    ) * np.sqrt(
                        rho3
                    ) * c  ### Factor c is because Eint is on the form E/ModVar.M0/c**2 and M on the form M/ModVar.M0
                    if np.isnan(BRS[i]):
                        print 'E3 =', out[i, 4]
                        print 'M3 =', out[i, 13]
                        print 'rho3 =', rho3
                    if BRS[i] == 0:
                        BRS[i] = 1e-70
                    gamma_max_RS = np.sqrt(6 * pi * qe / sigmaT / BRS[i])

        #############################
        ### Calculating gamma_c_w ###
        #############################
        if i > 0:
            dM2 = (out[1:i + 1, 12] - out[:i, 12])
            gamma_c_w_fac = 6 * pi * me * c / sigmaT
            rho2_array = 4 * rho1_fac * out[:i, 2] * R[:i]**(-ModVar.s)
            B_array = B_fac * np.sqrt(out[:i, 3]) / np.sqrt(
                out[:i, 12]) * np.sqrt(rho2_array) * c
            gamma_c_w_array = gamma_c_w_fac / B_array**2 / out[:i, 1]
            gamma_c_w[i] = np.sum(
                dM2 * gamma_c_w_array) / (out[i - 1, 12] - M20 / ModVar.M0)
            if gamma_c_w[i] > gamma_max:
                gamma_c_w[i] = np.copy(gamma_max)
            if UseOp.reverseShock and BRS[i] > 0:
                dM3 = (out[1:i + 1, 13] - out[:i, 13])
                rho3_array = 4 * out[:i, 2] * rho4_fac_1 * np.exp(
                    -out[:i, 14] / alpha_of) * R[:i]**-2
                BRS_array = BRS[:
                                i]  #BRS_fac * np.sqrt(out[:i,4]) / np.sqrt(out[:i,13]) * np.sqrt(rho3_array) * c

                gamma_c_w_RS_array = gamma_c_w_fac / BRS_array**2 / out[:i, 1]
                gamma_c_w_RS[i] = np.sum(dM3 * gamma_c_w_RS_array) / out[i - 1,
                                                                         13]
                """
                if gamma_c_w_RS[i] > gamma_max_RS:
                    gamma_c_w_RS[i] = np.copy(gamma_max_RS)
                """

        ############################
        ### Calulating gamma_min ###
        ############################
        """
            
        #gamma_min[i] = (p-2)/(p-1)*(ModVar.epsilone/mue*(out[i,2]-1)+1)
        

        gamma_min[i] = minimize_gammamin(gamma_c_w[i] , gamma_max , p , ModVar.epsilone , out[i,2] - 1,mue)
        gamma_min_inj = minimize_gammamin(gamma_max , gamma_max , p ,ModVar.epsilone , out[i,2] - 1,mue)
        
        
        if UseOp.reverseShock:
            
            if (out[i,13]>0) and (BRS[i]>0) and (gamma_c_w_RS[i] > 1) and (i > 0): 
                gamma_min_RS[i] = minimize_gammamin(gamma_c_w_RS[i] , gamma_max_RS , pRS , ModVar.epsilone3 , gamma43_minus_one[i] , mue)
                gamma_min_RS_inj = minimize_gammamin(gamma_max_RS , gamma_max_RS , pRS , ModVar.epsilone3 , gamma43_minus_one[i] , mue)
            else:
                gamma_min_RS[i] = (pRS-2)/(pRS-1)*(ModVar.epsilone3/mue*gamma43_minus_one[i]+1)
                gamma_min_RS_inj = np.copy(gamma_min_RS[i])
            odeinstance.set_f_params(s , ModVar.Gamma0  , z , ModVar.theta0 , ModVar.tprompt , ModVar.M0 , ModVar.A0/ModVar.M0 , ModVar.R_ISM , [UseOp.radiativeLosses,remix_radloss,continuous_radloss,fixed_epsilon,UseOp.reverseShock,UseOp.exponential_outflow] , [ModVar.epsilone,ModVar.eB,p,ModVar.epsilone3,ModVar.eB3,pRS] , gamma_c_w[i] , gamma_min_inj , gamma_min[i] , gamma_c_w_RS[i], gamma_min_RS_inj , gamma_min_RS[i] , shutOff)
        else:
            odeinstance.set_f_params(s , ModVar.Gamma0  , z , ModVar.theta0 , ModVar.tprompt , ModVar.M0 , ModVar.A0/ModVar.M0 , ModVar.R_ISM , [UseOp.radiativeLosses,remix_radloss,continuous_radloss,fixed_epsilon,UseOp.reverseShock,UseOp.exponential_outflow] , [ModVar.epsilone,ModVar.eB,p,ModVar.epsilone3,ModVar.eB3,pRS] , gamma_c_w[i] , gamma_min_inj , gamma_min[i])
        if ( not odeinstance.successful()):
            raise NameError('stepsize')
        if ( tobs[i-3] > tobsEnd):#*365.35*10 ):
            break #Stop at 10 years
        """

    out[:, 3] *= ModVar.M0 * c**2
    out[:, 4] *= ModVar.M0 * c**2
    out[:, 6] *= ModVar.M0 * c**2
    out[:, 7] *= ModVar.M0 * c**2
    out[:, 8] *= ModVar.M0 * c**2
    out[:, 9] *= ModVar.M0 * c**2
    out[:, 10] *= ModVar.M0 * c**2
    out[:, 11] *= ModVar.M0 * c**2
    out[:, 12] *= ModVar.M0
    out[:, 13] *= ModVar.M0
    """
    plt.plot(R[:i+1] , out[:i+1,2])
    plt.ylabel(r'$\Gamma$')
    plt.loglog()
    plt.show()

    plt.plot(R[:i] , (out[1:i+1,13]-out[:i,13]) / (R[1:i+1]-R[:i]))
    plt.loglog()
    plt.ylabel(r'$\frac{dM_3}{dR}$')
    plt.show()

    plt.plot(R[:i+1] , out[:i+1,12])
    plt.ylabel(r'$M_2$')
    plt.loglog()
    plt.show()

    plt.plot(R[:i+1] , out[:i+1,13])
    plt.ylabel(r'$M_3$')
    plt.loglog()
    plt.show()
    plt.plot(R[:i+1] , out[:i+1,3])
    plt.ylabel(r'$E_{\rm int,2}$')
    plt.loglog()
    plt.show()
    plt.plot(R[:i+1] , out[:i+1,4])
    plt.ylabel(r'$E_{\rm int,3}$')
    plt.loglog()
    plt.show()
    plt.plot(R[:i+1] , out[:i+1,14])
    plt.ylabel(r'$\Delta R_4$')
    plt.loglog()
    plt.show()
    """
    ### Calculating gamma_min ###
    gamma_min = (ModVar.p - 2) / (ModVar.p -
                                  1) * (1 + mp / me * ModVar.epsilone *
                                        (out[:i + 1, 2] - 1))
    gamma_min[np.where(gamma_min < 1)] = 1.
    if UseOp.reverseShock:
        ### Calculating gamma_min_RS ###
        gamma_min_RS = (ModVar.pRS - 2) / (ModVar.pRS - 1) * (
            1 + mp / me * ModVar.epsilone3 * gamma43_minus_one[:i + 1])

    if UseOp.save_params:

        os.system('rm Parameters/*')
        np.savetxt('Parameters/tobs.txt', tobs[:i + 1])
        np.savetxt('Parameters/tburst.txt', out[:i + 1, 0])
        np.savetxt('Parameters/tcomoving.txt', out[:i + 1, 1])
        np.savetxt('Parameters/Gamma.txt', out[:i + 1, 2])
        np.savetxt('Parameters/R.txt', R[:i + 1])
        #np.savetxt('Parameters/ModVar.epsilon_rad.txt',ModVar.epsilon_rad[:i+1])
        np.savetxt('Parameters/dM2dR.txt',
                   (out[1:i + 1, 12] - out[:i, 12]) / (R[1:i + 1] - R[:i]))
        np.savetxt('Parameters/M2.txt', out[:i + 1, 12])
        np.savetxt('Parameters/Eint2.txt', out[:i + 1, 3])
        np.savetxt('Parameters/Esh2.txt', out[:i + 1, 8])
        np.savetxt('Parameters/Ead2.txt', out[:i + 1, 10])
        np.savetxt('Parameters/Erad2.txt', out[:i + 1, 6])
        np.savetxt('Parameters/gamma_c_w.txt', gamma_c_w[:i + 1])
        np.savetxt('Parameters/gamma_min.txt', gamma_min)
        np.savetxt('Parameters/B.txt', B[:i + 1])
        np.savetxt('Parameters/theta.txt', out[:i + 1, 5])
        np.savetxt('Parameters/rho.txt', rho[:i + 1])
        if UseOp.reverseShock:

            np.savetxt('Parameters/dM3dR.txt',
                       (out[1:i + 1, 13] - out[:i, 13]) / (R[1:i + 1] - R[:i]))
            np.savetxt('Parameters/M3.txt', out[:i + 1, 13])
            #np.savetxt('Parameters/epsilon_rad_RS.txt',ModVar.epsilon_rad_RS[:i+1])
            np.savetxt('Parameters/Eint3.txt', out[:i + 1, 4])
            np.savetxt('Parameters/Esh3.txt', out[:i + 1, 9])
            np.savetxt('Parameters/Ead3.txt', out[:i + 1, 11])
            np.savetxt('Parameters/Erad3.txt', out[:i + 1, 7])
            np.savetxt('Parameters/Gamma43_minus_one.txt',
                       gamma43_minus_one[:i + 1])
            np.savetxt('Parameters/gamma_c_w_RS.txt', gamma_c_w_RS[:i + 1])
            np.savetxt('Parameters/gamma_min_RS.txt', gamma_min_RS)
            np.savetxt('Parameters/BRS.txt', BRS[:i + 1])
            np.savetxt('Parameters/rho4.txt', rho4[:i + 1])

    if UseOp.reverseShock:
        ### RS_elements_upper reduces RS arrays to where there is an RS component
        RS_elements_upper = np.count_nonzero(rho4)

        return out[:i + 1,
                   2], out[:i + 1,
                           0], tobs[:i +
                                    1], out[:i + 1,
                                            1], out[:i + 1,
                                                    5], out[:i + 1,
                                                            12], out[:
                                                                     RS_elements_upper,
                                                                     13], out[:
                                                                              i
                                                                              +
                                                                              1,
                                                                              3], out[:
                                                                                      RS_elements_upper,
                                                                                      4], B[:
                                                                                            i
                                                                                            +
                                                                                            1], BRS[:
                                                                                                    RS_elements_upper], rho[:
                                                                                                                            i
                                                                                                                            +
                                                                                                                            1], rho4[:
                                                                                                                                     RS_elements_upper], R[:
                                                                                                                                                           i
                                                                                                                                                           +
                                                                                                                                                           1], gamma43_minus_one[:
                                                                                                                                                                                 RS_elements_upper], gamma_min, gamma_min_RS, gamma_c_w[:
                                                                                                                                                                                                                                        i
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        1], gamma_c_w_RS[:
                                                                                                                                                                                                                                                         RS_elements_upper], RS_elements_upper
    else:
        return out[:i + 1,
                   2], out[:i + 1,
                           0], tobs[:i +
                                    1], out[:i + 1,
                                            1], out[:i + 1,
                                                    5], out[:i + 1,
                                                            12], None, out[:i +
                                                                           1,
                                                                           3], None, B[:
                                                                                       i
                                                                                       +
                                                                                       1], None, rho[:
                                                                                                     i
                                                                                                     +
                                                                                                     1], None, R[:
                                                                                                                 i
                                                                                                                 +
                                                                                                                 1], None, gamma_min, None, gamma_c_w[:
                                                                                                                                                      i
                                                                                                                                                      +
                                                                                                                                                      1], None, None
예제 #50
0
파일: 3.py 프로젝트: ggb367/Fall-2019
jdos = 0.00108248


def derivFcn(t, y):
    return JTwo(t, y, MU, jdos, RE)


r_0 = [-5282.628, -4217.988, 296.511]
v_0 = [-4.541972, 5.885228, 2.043106]

T0 = 0.0
times = np.arange(0, 86400, 100)
tF = 86400
dT = 100
Y_0 = np.concatenate([r_0, v_0], axis=0)
rv = ode(derivFcn)

#  The integrator type 'dopri5' is the same as MATLAB's ode45()!
#  rtol and atol are the relative and absolute tolerances, respectively
rv.set_integrator('dopri5', rtol=1e-10, atol=1e-20)
rv.set_initial_value(Y_0, T0)
output = []
output.append(np.insert(Y_0, 0, T0))

# Run the integrator and populate output array with positions and velocities
while rv.successful() and rv.t < tF:  # rv.successful() and
    rv.integrate(rv.t + dT)
    output.append(np.insert(rv.y, 0, rv.t))

#  Convert the output a numpy array for later use
output = np.array(output)
예제 #51
0
V0= 8 #o volume inicial não se altera
Fe= 0.7 #L/h || caudal de entrada || 350 g/L glucose
Se= 350 #concentração do substrato de entrada g/L

#lista com os valores iniciais fornecida a func
y0= [X0, S0, A0, P0, V]

#lista com os parametros fornecida a func
params= [k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, V0, Fe, Se]

t0= 0 #tempo inicial
t= 20 #tempo final
dt= 0.001 #intervalo de tempo entre reads

# Call the ODE solver
r = ode(bl21_FB).set_integrator('lsoda', method='bdf', lband=0) #lband é o limite inferior -- para nao haver valores negativos
r.set_initial_value(y0, t0).set_f_params(params)

#storing variables
T, x, s, a, p, v= [], [], [], [], [], []

while r.successful() and r.t < t:
    time= r.t + dt
    T.append(r.t)
    x.append(r.integrate(time)[0])
    s.append(r.integrate(time)[1])
    a.append(r.integrate(time)[2])
    p.append(r.integrate(time)[3])
    v.append(r.integrate(time)[4])
    #print(time, r.integrate(time))
예제 #52
0
def target_orbit(target_crossing,x0,t0,tf,mu,backend_bigprop,backend_littleprop,tol_integrate,tol_step,tol_converge):
    '''
    target_crossing = nth crossing to target a perpendicular crossing
    x0 = 42 element initial state; the first 6 elements contain the 
        non-dimensionalized, rotating position and velocity; the remaining 
        elements are the state transition matrix.
    t0 = initial time
    tf = final time (this is typically going to be larger than the actual 
        desired propagation time)
    mu = mass ratio of the two primaries
    backend_bigprop = integrator to use when taking large steps
    backend_littleprop = integrator to use when bisecting the crossing (if 
        bigprop uses vode, this must use a different integrator)
    tol_integrate = integration tolerance
    tol_step = smallest step size that the integrator will use
    tol_converge = tolerance to determine whether crossing is perpendicular
    '''
    bigprop = ode(cr3bp_eom).set_integrator(backend_bigprop,atol=tol_integrate,rtol=tol_integrate)
    littleprop = ode(cr3bp_eom).set_integrator(backend_littleprop,atol=tol_integrate,rtol=tol_integrate)
    error = 1
    iteration = 0
    while np.abs(error) > tol_converge:
        #integrate
        bigprop.set_initial_value(x0,t0).set_f_params(mu)
        t = [t0]
        x = [x0]
        current_crossing = 0
        last_y = np.sign(x0[4])
        while bigprop.successful() and current_crossing < target_crossing:
            #step
            current_state = bigprop.integrate(tf,step=True)
            #check for crossing
            if np.sign(current_state[1]) != np.sign(last_y):
                current_crossing += 1
                #littleprop to find actual crossing
                if current_crossing == target_crossing:
                    dt = (t[-1]-t[-2])
                    while np.abs(current_state[1]) > tol_converge and abs(dt) > tol_step:
                        dt = -dt/2
                        last_y = current_state[1]
                        littleprop.set_initial_value(current_state,bigprop.t).set_f_params(mu)
                        current_state = littleprop.integrate(littleprop.t+dt)
                        #take another step if we didn't cross on the first one
                        if np.sign(current_state[1]) == np.sign(last_y):
                            current_state = littleprop.integrate(littleprop.t+dt)
                #save correct time
                t.append(littleprop.t)
            else:
                #save correct time
                t.append(bigprop.t)
            #save data to arrays
            x.append(current_state)
            last_y = current_state[1]
        #targeting algorithm to update initial conditions
        error = current_state[3]
        r1 = np.sqrt( (current_state[0]+mu)**2 + current_state[1]**2 + current_state[2]**2 )
        r2 = np.sqrt( (current_state[0]-1+mu)**2 + current_state[1]**2 + current_state[2]**2 )
        ax = 2*current_state[4] + current_state[0] - (1-mu)*(current_state[0]+mu)/r1**3 - mu*(current_state[0]-1+mu)/r2**3
        X = np.array([[x0[4]],[t[len(t)-1]]])
        FX = np.array([[current_state[1]],[current_state[3]]])
        DF = np.array([[current_state[16],current_state[4]],[current_state[28],ax]])
        update = np.zeros((2,1))
        update = np.mat(X) - np.mat(np.transpose(DF))*np.linalg.inv(np.mat(DF)*np.mat(np.transpose(DF)))*np.mat(FX)
        x0[4] = update[0]
        #increase perpendicular crossing tolerance if stuck
        if iteration > 10:
            tol_converge = 10*tol_converge
            iteration = -1
        iteration += 1
        
    return t,x
예제 #53
0
import warnings

def logistic(t, y, r):
    return r * y * (1.0 - y)

r = .01
t0 = 0
y0 = 1e-5
t1 = 5000.0

#backend = 'vode'
backend = 'dopri5'
#backend = 'dop853'

solver = sp.ode(logistic).set_integrator(backend, nsteps=1)
solver.set_initial_value(y0, t0).set_f_params(r)
# suppress Fortran-printed warning
solver._integrator.iwork[2] = -1

sol = []
warnings.filterwarnings("ignore", category=UserWarning)
while solver.t < t1:
    solver.integrate(t1, step=True)
    sol.append([solver.t, solver.y])
warnings.resetwarnings()
sol = np.array(sol)

# plot

py.figure(4)
예제 #54
0
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 17 15:04:39 2018

@author: mtkes
"""

from scipy.integrate import ode

y0, t0 = [1.0j, 2.0], 0


def f(t, y, arg1):
    return [1j * arg1 * y[0] + y[1], -arg1 * y[1]**2]


def jac(t, y, arg1):
    return [[1j * arg1, 1], [0, -arg1 * 2 * y[1]]]


r = ode(f, jac).set_integrator('zvode', method='bdf', with_jacobian=True)
r.set_initial_value(y0, t0).set_f_params(2.0).set_jac_params(2.0)
t1 = 10
dt = 1
while r.successful() and r.t < t1:
    r.integrate(r.t + dt)
    print("%g %g %g" % (r.t, abs(r.y[0]), abs(r.y[1])))
예제 #55
0
    _K = [[0.0, 0.3, 0.1, 0.1, 0.5, 0.0], [0.3, 0.0, 0.9, 0.0, 0.1, 1.0],
          [0.1, 0.9, 0.0, 0.4, 0.0, 0.2], [0.1, 0.0, 0.4, 0.0, 1.0, 0.4],
          [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
    _K = np.array(_K)
    _K = (_K + _K.T) / 2

    # Preparing oscillators with Kuramoto model
    oscN = 3  # num of oscillators

    Y0 = _Y0[:oscN]
    W = _W[:oscN]
    K = _K[:oscN, :oscN]

    ####################################################
    # Setting up ODE integrator
    kODE = ode(kuramoto_ODE)
    kODE.set_integrator("vode")

    # Set parameters into model
    kODE.set_initial_value(Y0, t0)
    kODE.set_f_params((W, K))

    # Run ODE integrator
    odeT, odePhi = [], []
    while kODE.successful() and kODE.t < t1:
        kODE.integrate(kODE.t + dt)

        odeT.append(kODE.t)
        odePhi.append(kODE.y)

    # Convert to numpy array
예제 #56
0
 def __init__(self, f, **kwargs):
     self.f = f
     self.h = kwargs.pop('h', 0.01)
     self.r = ode(f).set_integrator('dopri5')
     self.fig, self.ax = plt.subplots(1, 1)
예제 #57
0
            current_pass['Date1'] = date
            current_pass['Pass Length'] = (
                date - current_pass['Date0']).total_seconds()
            if max_el > 20:
                pass_list.append(current_pass)
                date += datetime.timedelta(days=30)

for _pass in pass_list:
    pass_directory = Directory + '/' + str(_pass['Date0']).replace(':', '-')
    if not os.path.exists(pass_directory):
        os.makedirs(pass_directory)

    r0, v0 = Satellite.propagate(*_pass['Date0'].timetuple()[0:6])
    state0 = hstack([r0, v0])

    solver = ode(propagate_orbit)
    solver.set_integrator('lsoda')
    solver.set_initial_value(state0, 0)
    #times = asarray(arange(0, _pass['Pass Length'], DT))

    positions = []
    times = []
    while solver.t < _pass['Pass Length']:
        positions.append(solver.integrate(solver.t + DT))
        times.append(solver.t)
    times = hstack(times)
    positions = vstack(positions)

    obs_vecs = []
    sun_vecs = []
    sat_poss = []
예제 #58
0
    def OutputEphemerisData(self, LU, TU, mu, timehistory, statehistory,
                            accelhistory):
        if self.EventType == 'coast' or self.EventType == 'force-coast' or self.EventType == "SFthrust" or self.EventType == "FBLTthrust" or self.EventType == "PSBIthrust" or self.EventType == "match_point":

            #propagate the state forward and back
            CenterPointState = []
            CenterPointState = np.zeros(7)
            CenterPointState[0:6] = np.array(self.SpacecraftState) / LU
            CenterPointState[3:6] *= TU
            CenterPointState[6] = 1.0

            if self.EventType == 'coast' or self.EventType == 'force-coast' or self.EventType == "SFthrust" or self.EventType == "PSBIthrust":
                CenterPointState = np.array(copy.deepcopy(
                    self.SpacecraftState))
                if self.EventType == "SFthrust" or event.EventType == "PSBIthrust":
                    CenterPointState[3:6] += np.array(
                        self.DeltaVorThrustVectorControl)
                CenterPointState /= LU
                CenterPointState[3:6] *= TU

                ForwardIntegrateObject = ode(
                    EOM.EOM_inertial_2body).set_integrator('dop853',
                                                           atol=1.0e-8,
                                                           rtol=1.0e-8)
                ForwardIntegrateObject.set_initial_value(
                    CenterPointState).set_f_params(1.0)

                StateHistoryForward = []
                TimeHistoryForward = []
                while ForwardIntegrateObject.successful(
                ) and ForwardIntegrateObject.t < (self.TimestepLength / 2.0 -
                                                  1) * 86400 / TU:
                    ForwardIntegrateObject.integrate(ForwardIntegrateObject.t +
                                                     86400 / TU)
                    StateHistoryForward.append(ForwardIntegrateObject.y * LU)
                    TimeHistoryForward.append(ForwardIntegrateObject.t * TU)

                #backward integration
                CenterPointState = np.array(copy.deepcopy(
                    self.SpacecraftState))
                CenterPointState /= LU
                CenterPointState[3:6] *= TU

                BackwardIntegrateObject = ode(
                    EOM.EOM_inertial_2body).set_integrator('dop853',
                                                           atol=1.0e-8,
                                                           rtol=1.0e-8)
                BackwardIntegrateObject.set_initial_value(
                    CenterPointState).set_f_params(1.0)

                StateHistoryBackward = []
                TimeHistoryBackward = []
                while BackwardIntegrateObject.successful(
                ) and BackwardIntegrateObject.t > -(self.TimestepLength / 2.0 -
                                                    1) * 86400 / TU:
                    BackwardIntegrateObject.integrate(
                        BackwardIntegrateObject.t - 86400 / TU)
                    StateHistoryBackward.append(BackwardIntegrateObject.y * LU)
                    TimeHistoryBackward.append(BackwardIntegrateObject.t * TU)

                StateHistoryBackward.reverse()
                TimeHistoryBackward.reverse()

                for StateLine in StateHistoryBackward:
                    statehistory.append(
                        np.array([
                            StateLine[0], StateLine[1], StateLine[2],
                            StateLine[3] / TU, StateLine[4] / TU,
                            StateLine[5] / TU
                        ]) * 1000)
                    accelhistory.append(np.array([0.0, 0.0, 0.0]))
                for TimeLine in TimeHistoryBackward:
                    timehistory.append(TimeLine + self.JulianDate * 86400)

                statehistory.append(
                    np.array([
                        self.SpacecraftState[0], self.SpacecraftState[1],
                        self.SpacecraftState[2], self.SpacecraftState[3],
                        self.SpacecraftState[4], self.SpacecraftState[5]
                    ]) * 1000)
                accelhistory.append(np.array([0.0, 0.0, 0.0]))
                timehistory.append(self.JulianDate * 86400)

                for StateLine in StateHistoryForward:
                    statehistory.append(
                        np.array([
                            StateLine[0], StateLine[1], StateLine[2],
                            StateLine[3] / TU, StateLine[4] / TU,
                            StateLine[5] / TU
                        ]) * 1000)
                    accelhistory.append(np.array([0.0, 0.0, 0.0]))
                for TimeLine in TimeHistoryForward:
                    timehistory.append(TimeLine + self.JulianDate * 86400)
            elif self.EventType == 'FBLTthrust':
                CenterPointState = np.zeros(7)
                CenterPointState[0:6] = np.array(self.SpacecraftState) / LU
                CenterPointState[3:6] *= TU
                CenterPointState[6] = 1.0

                ScaledThrust = np.array(
                    self.Thrust) / self.Mass / LU / 1000 * TU * TU
                ScaledMdot = self.MassFlowRate / self.Mass * TU

                ForwardIntegrateObject = ode(
                    EOM.EOM_inertial_2bodyconstant_thrust).set_integrator(
                        'dop853', atol=1.0e-8, rtol=1.0e-8)
                ForwardIntegrateObject.set_initial_value(
                    CenterPointState).set_f_params(ScaledThrust, ScaledMdot,
                                                   1.0)

                StateHistoryForward = []
                TimeHistoryForward = []
                while ForwardIntegrateObject.successful(
                ) and ForwardIntegrateObject.t < (self.TimestepLength / 2.0 -
                                                  1) * 86400 / TU:
                    ForwardIntegrateObject.integrate(ForwardIntegrateObject.t +
                                                     86400 / TU)
                    UnscaledState = copy.deepcopy(ForwardIntegrateObject.y)
                    UnscaledState[0:3] *= LU
                    UnscaledState[4:6] *= LU / TU
                    UnscaledState[6] *= self.Mass
                    StateHistoryForward.append(UnscaledState)
                    TimeHistoryForward.append(ForwardIntegrateObject.t * TU)

                BackwardIntegrateObject = ode(
                    EOM.EOM_inertial_2bodyconstant_thrust).set_integrator(
                        'dop853', atol=1.0e-8, rtol=1.0e-8)
                BackwardIntegrateObject.set_initial_value(
                    CenterPointState).set_f_params(ScaledThrust, ScaledMdot,
                                                   1.0)

                StateHistoryBackward = []
                TimeHistoryBackward = []
                while BackwardIntegrateObject.successful(
                ) and BackwardIntegrateObject.t > -(self.TimestepLength / 2.0 -
                                                    1) * 86400 / TU:
                    BackwardIntegrateObject.integrate(
                        BackwardIntegrateObject.t - 86400 / TU)
                    UnscaledState = copy.deepcopy(BackwardIntegrateObject.y)
                    UnscaledState[0:3] *= LU
                    UnscaledState[4:6] *= LU / TU
                    UnscaledState[6] *= self.Mass
                    StateHistoryBackward.append(UnscaledState)
                    TimeHistoryBackward.append(BackwardIntegrateObject.t * TU)

                StateHistoryBackward.reverse()
                TimeHistoryBackward.reverse()

                for StateLine in StateHistoryBackward:
                    statehistory.append(
                        np.array([
                            StateLine[0], StateLine[1], StateLine[2],
                            StateLine[3], StateLine[4], StateLine[5]
                        ]) * 1000)
                    accelhistory.append(
                        np.array([
                            self.Thrust[0] / StateLine[6],
                            self.Thrust[1] / StateLine[6],
                            self.Thrust[2] / StateLine[6]
                        ]))
                for TimeLine in TimeHistoryBackward:
                    timehistory.append(TimeLine + self.JulianDate * 86400)

                statehistory.append(
                    np.array([
                        self.SpacecraftState[0], self.SpacecraftState[1],
                        self.SpacecraftState[2], self.SpacecraftState[3],
                        self.SpacecraftState[4], self.SpacecraftState[5]
                    ]) * 1000)
                accelhistory.append(
                    np.array([
                        self.Thrust[0] / self.Mass, self.Thrust[1] / self.Mass,
                        self.Thrust[2] / self.Mass
                    ]))
                timehistory.append(self.JulianDate * 86400)

                for StateLine in StateHistoryForward:
                    statehistory.append(
                        np.array([
                            StateLine[0], StateLine[1], StateLine[2],
                            StateLine[3], StateLine[4], StateLine[5]
                        ]) * 1000)
                    accelhistory.append(
                        np.array([
                            self.Thrust[0] / StateLine[6],
                            self.Thrust[1] / StateLine[6],
                            self.Thrust[2] / StateLine[6]
                        ]))
                for TimeLine in TimeHistoryForward:
                    timehistory.append(TimeLine + self.JulianDate * 86400)

        else:
            statehistory.append(np.array(self.SpacecraftState[0:6]) * 1000.0)
            accelhistory.append(np.array([0.0, 0.0, 0.0]))
            timehistory.append(self.JulianDate * 86400)

        return timehistory, statehistory, accelhistory
    
    return dy

k = 9
_m = 1
T = 2*m.pi*m.sqrt(_m/k)
omega = 2*m.pi/T
N = 1e4
R0 = [0.5, 1.]

t0, t1 = 0, 5*T                

t = np.linspace(t0, t1, 10000)
R = np.zeros((len(t), len(R0)), dtype=np.float64)   
R[0, :] = R0
r = integrate.ode(oscillator).set_integrator("dopri5")  
r.set_initial_value(R0, t0)   
for i in range(1, t.size):
    R[i, :] = r.integrate(t[i]) 
    if not r.successful():
        raise RuntimeError("Could not integrate")

E = np.zeros((len(t), len(R0)), dtype = np.float64)
delta = np.zeros(len(t), dtype = np.float64)

for i in range (len(t)):
    E[i,:] = (0.5*(k*R[i,0]**2 + _m*R[i,1]**2), 0.5*k*R[i,0]**2 )
    delta[i]  = (E[i,1] - E[i,0])/E[i,0]

fig = plt.figure()
ax = fig.add_subplot(111)
예제 #60
0
def propagate_orbit(spacecraftConfig,
                    forcesCoeff,
                    surfaces,
                    eop_alldata,
                    ndays,
                    dt,
                    ode_flag=True):

    # Integrator
    int_tol = 1e-12
    intfcn = spacecraftConfig['intfcn']
    integrator = spacecraftConfig['integrator']

    # If flag is set use ode
    if ode_flag:

        start = time.time()

        y0 = spacecraftConfig['X'].flatten()
        tvec = np.arange(0., 86400. * ndays + (0.1 * dt), dt)

        solver = ode(intfcn)
        solver.set_integrator(integrator, atol=int_tol, rtol=int_tol)
        solver.set_f_params(
            [spacecraftConfig, forcesCoeff, surfaces, eop_alldata])

        solver.set_initial_value(y0, tvec[0])
        state = np.zeros((len(tvec), len(y0)))
        state[0] = y0

        k = 1
        while solver.successful() and solver.t < tvec[-1]:
            solver.integrate(tvec[k])
            state[k] = solver.y
            k += 1

#        print(k)
#        print(len(tvec))

#        solver = ode(self.FuncDyn)
#        solver.set_integrator(self.integrator)
#        self.t0 = 0.0
#        if (self.state.type=='3DoF'):
#            solver.set_f_params(self.forces)
#            self.lenForces = len(self.forces)
#            y0 =  [self.state.scStateOrekit.getPVCoordinates().getPosition().getX(),
#                   self.state.scStateOrekit.getPVCoordinates().getPosition().getY(),
#                   self.state.scStateOrekit.getPVCoordinates().getPosition().getZ(),
#                   self.state.scStateOrekit.getPVCoordinates().getVelocity().getX(),
#                   self.state.scStateOrekit.getPVCoordinates().getVelocity().getY(),
#                   self.state.scStateOrekit.getPVCoordinates().getVelocity().getZ()]
#            lenY0 = 6
#        elif (self.state.type=='6DoF'):
#            solver.set_f_params([self.forces,self.torques])
#            self.lenForces = len(self.forces)
#            self.lenTorques = len(self.torques)
#            # Below states should be defined in some inertial frame - e.g. J2000
#            y0 =  [self.state.scStateOrekit.getPVCoordinates().getPosition().getX(),
#                   self.state.scStateOrekit.getPVCoordinates().getPosition().getY(),
#                   self.state.scStateOrekit.getPVCoordinates().getPosition().getZ(),
#                   self.state.scStateOrekit.getPVCoordinates().getVelocity().getX(),
#                   self.state.scStateOrekit.getPVCoordinates().getVelocity().getY(),
#                   self.state.scStateOrekit.getPVCoordinates().getVelocity().getZ(),
#                   self.state.scStateOrientationIne2Body[0],
#                   self.state.scStateOrientationIne2Body[1],
#                   self.state.scStateOrientationIne2Body[2],
#                   self.state.scStateOrientationIne2Body[3],
#                   self.state.scStateOrientationRateBodywrtIne[0],
#                   self.state.scStateOrientationRateBodywrtIne[1],
#                   self.state.scStateOrientationRateBodywrtIne[2]]
#            lenY0 = 13
#        else:
#            print('Please select a 3DoF or 6DoF dynamics for the type')
#        solver.set_initial_value(y0, self.t0)
#        N = int(self.tShift/self.tStep)
#        t = np.linspace(self.t0, self.tShift, N)
#        self.sol = {}
#        self.sol['time'] = []
#        self.sol['time'].append(str(self.state.scStateOrekit.getDate()))
#        self.sol['state'] = np.empty((N, lenY0))
#        self.sol['state'][0] = y0
#        if (self.visibility!=None):
#            self.sol['visibility'] = np.zeros((N, 6))
#            visibilityState = self.visibility.ComputeVisibilityState()
#            if visibilityState[0]!=0.0:
#                appMagnitude = self.visibility.ComputeAppMagnitude()
#                self.sol['visibility'][0] = [appMagnitude,self.visibility.sumFobs\
#                        ,visibilityState[0],visibilityState[1],visibilityState[2]\
#                        ,visibilityState[3]]
#        k = 1
#        while solver.successful() and solver.t < self.tShift:
#            solver.integrate(t[k])
#            self.sol['state'][k] = solver.y
#            self.sol['time'].append(str(self.state.scStateOrekit.getDate()))
#            if (self.visibility!=None):
#                visibilityState = self.visibility.ComputeVisibilityState()
#                if visibilityState[0]!=0.0:
#                    appMagnitude = self.visibility.ComputeAppMagnitude()
#                    self.sol['visibility'][k] = [appMagnitude,self.visibility.sumFobs\
#                            ,visibilityState[0],visibilityState[1],visibilityState[2]\
#                            ,visibilityState[3]]
#            k += 1

# Otherwise use odeint
    else:

        start = time.time()

        # Setup propagator
        tvec = np.arange(0., 86400. * ndays + (0.1 * dt), dt)
        args = (spacecraftConfig, forcesCoeff, surfaces)
        int0 = spacecraftConfig['X'].flatten()

        print(int0)

        state = odeint(intfcn, int0, tvec, args, rtol=int_tol, atol=int_tol)

    # Print time
    print('Propagation Time:', time.time() - start)

    # Output time
    UTC0 = spacecraftConfig['time']
    UTC_times = [UTC0 + timedelta(seconds=ti) for ti in tvec]

    return UTC_times, state