Ejemplo n.º 1
0
def run_example():

    def residual(t,y,yd):

        res_0 = yd[0]-y[2]
        res_1 = yd[1]-y[3]
        res_2 = yd[2]+y[4]*y[0]
        res_3 = yd[3]+y[4]*y[1]+9.82
        res_4 = y[2]**2+y[3]**2-y[4]*(y[0]**2+y[1]**2)-y[1]*9.82

        return np.array([res_0,res_1,res_2,res_3,res_4])
    
    #The initial conditons
    t0  = 0.0 #Initial time
    y0  = [1.0, 0.0, 0.0, 0.0, 0.0] #Initial conditions
    yd0 = [0.0, 0.0, 0.0, -9.82, 0.0] #Initial conditions
    print (residual(t0,y0,yd0))

    model = Implicit_Problem(residual, y0, yd0, t0)             #Create an Assimulo problem
    model.name = 'Pendulum'        #Specifies the name of problem (optional)

    sim = IDA(model) #Create the IDA solver
        
    tfinal = 10.0        #Specify the final time
    ncp = 500            #Number of communcation points (number of return points)

    t,y,yd = sim.simulate(tfinal, ncp) #Use the .simulate method to simulate and provide the final time and ncp (optional)
    
    sim.plot()
Ejemplo n.º 2
0
    def simulate(self, Tend, nIntervals, gridWidth):

        problem = Implicit_Problem(self.rhs, self.y0, self.yd0)
        problem.name = 'IDA'
        # solver.rhs = self.right_hand_side
        problem.handle_result = self.handle_result
        problem.state_events = self.state_events
        problem.handle_event = self.handle_event
        problem.time_events = self.time_events
        problem.finalize = self.finalize
        # Create IDA object and set additional parameters
        simulation = IDA(problem)
        simulation.atol = self.atol
        simulation.rtol = self.rtol
        simulation.verbosity = self.verbosity
        if hasattr(simulation, 'continuous_output'):
            simulation.continuous_output = False  # default 0, if one step approach should be used
        elif hasattr(simulation, 'report_continuously'):
            simulation.report_continuously = False  # default 0, if one step approach should be used
        simulation.tout1 = self.tout1
        simulation.lsoff = self.lsoff

        # Calculate nOutputIntervals:
        if gridWidth <> None:
            nOutputIntervals = int((Tend - self.t0) / gridWidth)
        else:
            nOutputIntervals = nIntervals
        # Check for feasible input parameters
        if nOutputIntervals == 0:
            print 'Error: gridWidth too high or nIntervals set to 0! Continue with nIntervals=1'
            nOutputIntervals = 1
        # Perform simulation
        simulation.simulate(Tend, nOutputIntervals)  # to get the values: t_new, y_new,  yd_new = simulation.simulate
Ejemplo n.º 3
0
    def simulate(self, Tend, nIntervals, gridWidth):

        problem = Implicit_Problem(self.rhs, self.y0, self.yd0)
        problem.name = 'IDA'
        # solver.rhs = self.right_hand_side
        problem.handle_result = self.handle_result
        problem.state_events = self.state_events
        problem.handle_event = self.handle_event
        problem.time_events = self.time_events
        problem.finalize = self.finalize
        # Create IDA object and set additional parameters
        simulation = IDA(problem)
        simulation.atol = self.atol
        simulation.rtol = self.rtol
        simulation.verbosity = self.verbosity
        if hasattr(simulation, 'continuous_output'):
            simulation.continuous_output = False  # default 0, if one step approach should be used
        elif hasattr(simulation, 'report_continuously'):
            simulation.report_continuously = False  # default 0, if one step approach should be used
        simulation.tout1 = self.tout1
        simulation.lsoff = self.lsoff

        # Calculate nOutputIntervals:
        if gridWidth <> None:
            nOutputIntervals = int((Tend - self.t0) / gridWidth)
        else:
            nOutputIntervals = nIntervals
        # Check for feasible input parameters
        if nOutputIntervals == 0:
            print 'Error: gridWidth too high or nIntervals set to 0! Continue with nIntervals=1'
            nOutputIntervals = 1
        # Perform simulation
        simulation.simulate(Tend, nOutputIntervals)  # to get the values: t_new, y_new,  yd_new = simulation.simulate
def run_example():

	#initial values
	t0 = 0
	y0 = np.array([0., -0.10344, -0.65, 0., 0. , 0., -0.628993, 0.047088]) #|phi_s| <= 0.1034 rad, |phi_b| <= 0.12 rad
	yd0 = np.array([0., 0., 0., 0., 0., 0., 0., 0.])
	sw = [False, True, False]
	
	#problem
	model = Implicit_Problem(pecker, y0, yd0, t0, sw0=sw)
	model.state_events = state_events #from woodpecker.py
	model.handle_event = handle_event #from woodpecker.py
	model.name = 'Woodpeckermodel'
	sim = IDA(model) #create IDA solver
	tfinal = 2.0 #final time
	ncp = 500 #number control points	
	sim.suppress_alg = True
	sim.rtol=1.e-6
	sim.atol[6:8] = 1e6
	sim.algvar[6:8] = 0
	t, y, yd = sim.simulate(tfinal, ncp) #simulate
	
	#plot
	fig, ax = P.subplots()
	ax.plot(t, y[:, 0], label='z')
	legend = ax.legend(loc='upper center', shadow=True)
	P.grid()
	
	P.figure(1)
	fig2, ax2 = P.subplots()
	ax2.plot(t, y[:, 1], label='phi_s')
	ax2.plot(t, y[:, 2], label='phi_b')
	legend = ax2.legend(loc='upper center', shadow=True)
	P.grid()
	
	P.figure(2)
	fig3, ax3 = P.subplots()
	ax3.plot(t, y[:, 4], label='phi_sp')
	ax3.plot(t, y[:, 5], label='phi_bp')
	legend = ax3.legend(loc='upper center', shadow=True)
	P.grid()
	
	P.figure(3)
	fig4, ax4 = P.subplots()
	ax4.plot(t, y[:, 6], label='lambda_1')
	ax4.plot(t, y[:, 7], label='lambda_2')
	legend = ax4.legend(loc='upper right', shadow=True)
	P.grid()
	
	#event data
	sim.print_event_data()
	
	#show plots
	P.show()
	print("...")
	P.show()
Ejemplo n.º 5
0
def run_example(with_plots=True):
    
    #Define the residual
    def f(t,y,yd):
        eps = 1.e-6
        my = 1./eps
        yd_0 = y[1]
        yd_1 = my*((1.-y[0]**2)*y[1]-y[0])
        
        res_0 = yd[0]-yd_0
        res_1 = yd[1]-yd_1
        
        return N.array([res_0,res_1])
    
    y0 = [2.0,-0.6] #Initial conditions
    yd0 = [-.6,-200000.]
    
    #Define an Assimulo problem
    imp_mod = Implicit_Problem(f,y0,yd0)
    imp_mod.name = 'Van der Pol (implicit)'
    
    #Define an explicit solver
    imp_sim = Radau5DAE(imp_mod) #Create a Radau5 solver
    
    #Sets the parameters
    imp_sim.atol = 1e-4 #Default 1e-6
    imp_sim.rtol = 1e-4 #Default 1e-6
    imp_sim.inith = 1.e-4 #Initial step-size

    #Simulate
    t, y, yd = imp_sim.simulate(2.) #Simulate 2 seconds
    
    #Plot
    if with_plots:
        P.plot(t,y[:,0], marker='o')
        P.show()
    
    #Basic test
    x1 = y[:,0]
    assert N.abs(x1[-1]-1.706168035) < 1e-3 #For test purpose
Ejemplo n.º 6
0
def run_example(with_plots=True):

    #Define the residual
    def f(t, y, yd):
        eps = 1.e-6
        my = 1. / eps
        yd_0 = y[1]
        yd_1 = my * ((1. - y[0]**2) * y[1] - y[0])

        res_0 = yd[0] - yd_0
        res_1 = yd[1] - yd_1

        return N.array([res_0, res_1])

    y0 = [2.0, -0.6]  #Initial conditions
    yd0 = [-.6, -200000.]

    #Define an Assimulo problem
    imp_mod = Implicit_Problem(f, y0, yd0)
    imp_mod.name = 'Van der Pol (implicit)'

    #Define an explicit solver
    imp_sim = Radau5DAE(imp_mod)  #Create a Radau5 solver

    #Sets the parameters
    imp_sim.atol = 1e-4  #Default 1e-6
    imp_sim.rtol = 1e-4  #Default 1e-6
    imp_sim.inith = 1.e-4  #Initial step-size

    #Simulate
    t, y, yd = imp_sim.simulate(2.)  #Simulate 2 seconds

    #Plot
    if with_plots:
        P.plot(t, y[:, 0], marker='o')
        P.show()

    #Basic test
    x1 = y[:, 0]
    assert N.abs(x1[-1] - 1.706168035) < 1e-3  #For test purpose
Ejemplo n.º 7
0
    resid12 = -lambda_2 - g * m - lambda_3(z1 - z2)

    resid13 = (x1 * du[6] + x1_dot**2) + (y1 * du[7] + y1_dot**2) - du[8]
    resid14 = (x1 * du[9] + x1_dot**2) + (y1 * du[10] + y1_dot**2) - du[11]
    resid15 = (x1 - x2) * (du[6] - du[9]) + (x1_dot - x2_dot) * (x1_dot -
                                                                 x2_dot)
    resid16 = (y1 - y2) * (du[7] - du[10]) + (y1_dot - y2_dot) * (y1_dot -
                                                                  y2_dot)
    resid17 = (z1 - z2) * (du[8] - du[11]) + (z1_dot - z2_dot) * (z1_dot -
                                                                  z2_dot)

    return np.array([
        resid1, resid2, resid3, resid4, resid5, resid6, resid7, resid8, resid9,
        resid10, resid11, resid12, resid13, resid14, resid15, resid16, resid17
    ])


#initial conditions
t0 = 0.0
u0 = [1.0, 1.0, 1.0, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0, 0, 0]
du0 = [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0, 0, 0]

model = Implicit_Problem(residual, u0, du0, t0)
model.name = 'masses linked on surface'

sim = IDA(model)
tfinal = 10.0  #Specify the final time
ncp = 500  #Number of communication points (number of return points)

t, y, yd = sim.simulate(tfinal, ncp)
sim.plot()
Ejemplo n.º 8
0
      np.real(ux_x_min), \
      np.imag(ux_x_min), \
      np.real(b_par_x_min), \
      np.imag(b_par_x_min), \
      np.real(u_perp_x_min), \
      np.imag(u_perp_x_min) ))
dU_x_min = np.concatenate(( \
      np.real(dux_x_min), \
      np.imag(dux_x_min), \
      np.real(db_par_x_min), \
      np.imag(db_par_x_min), \
      np.real(du_perp_x_min), \
      np.imag(du_perp_x_min) ))

model = Implicit_Problem(residual, U_x_min, dU_x_min, x_min)
model.name = 'Pendulum'

sim = IDA(model)

# x,U,dU = sim.simulate(x_max, nx)

# sim.plot()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, vA(x, 0))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, np.real(ux_ana(x, 0)))
ax.plot(x, np.imag(ux_ana(x, 0)))
Ejemplo n.º 9
0
def run_example(with_plots=True):
    
    #Defines the residual
    def f(t,y,yd):
        
        res_0 = yd[0]-y[2]
        res_1 = yd[1]-y[3]
        res_2 = yd[2]+y[4]*y[0]
        res_3 = yd[3]+y[4]*y[1]+9.82
        #res_4 = y[0]**2+y[1]**2-1
        res_4 = y[2]**2+y[3]**2-y[4]*(y[0]**2+y[1]**2)-y[1]*9.82

        return N.array([res_0,res_1,res_2,res_3,res_4])
    
    #Defines the jacobian
    def jac(c,t,y,yd):
        jacobian = N.zeros([len(y),len(y)])
        
        #Derivative
        jacobian[0,0] = 1*c
        jacobian[1,1] = 1*c
        jacobian[2,2] = 1*c
        jacobian[3,3] = 1*c
        
        #Differentiated
        jacobian[0,2] = -1
        jacobian[1,3] = -1
        jacobian[2,0] = y[4]
        jacobian[3,1] = y[4]
        jacobian[4,0] = y[0]*2*y[4]*-1
        jacobian[4,1] = y[1]*2*y[4]*-1-9.82
        jacobian[4,2] = y[2]*2
        jacobian[4,3] = y[3]*2
        
        #Algebraic
        jacobian[2,4] = y[0]
        jacobian[3,4] = y[1]
        jacobian[4,4] = -(y[0]**2+y[1]**2)
        
        return jacobian
        
    #The initial conditons
    y0 = [1.0,0.0,0.0,0.0,5] #Initial conditions
    yd0 = [0.0,0.0,0.0,-9.82,0.0] #Initial conditions
    
    #Create an Assimulo implicit problem
    imp_mod = Implicit_Problem(f,y0,yd0)
    
    #Sets the options to the problem
    imp_mod.jac = jac #Sets the jacobian
    imp_mod.algvar = [1.0,1.0,1.0,1.0,0.0] #Set the algebraic components
    imp_mod.name = 'Test Jacobian'
    
    #Create an Assimulo implicit solver (IDA)
    imp_sim = IDA(imp_mod) #Create a IDA solver
    
    #Sets the paramters
    imp_sim.atol = 1e-6 #Default 1e-6
    imp_sim.rtol = 1e-6 #Default 1e-6
    imp_sim.suppress_alg = True #Suppres the algebraic variables on the error test
    
    #Let Sundials find consistent initial conditions by use of 'IDA_YA_YDP_INIT'
    imp_sim.make_consistent('IDA_YA_YDP_INIT')
    
    #Simulate
    t, y, yd = imp_sim.simulate(5,1000) #Simulate 5 seconds with 1000 communication points
    
    #Basic tests
    nose.tools.assert_almost_equal(y[-1][0],0.9401995, places=4)
    nose.tools.assert_almost_equal(y[-1][1],-0.34095124, places=4)
    nose.tools.assert_almost_equal(yd[-1][0], -0.88198927, places=4)
    nose.tools.assert_almost_equal(yd[-1][1], -2.43227069, places=4)
    
    #Plot
    if with_plots:
        P.plot(t,y)
        P.show()
Ejemplo n.º 10
0
y0 = numpy.array([0.5, 0,0, -0, 0, 0.5,-1e-4,0])
yd0 =  numpy.array([-0, 0, 0.5,-g, 1e-12, 0, 0, 0])

w0 = -0.91
y0 = numpy.array([0.5, 0,0, -0, w0, w0,-1e-4,0])
yd0 =  numpy.array([-0, w0, w0,-g, 1e-12, 0, 0, 0])

#y0 = numpy.array([4.83617428e-01, -3.00000000e-02, -2.16050178e-01, 1.67315232e-16, -5.39725367e-14, -1.31300925e+01, -7.20313572e-02, -6.20545138e-02])
#yd0 = numpy.array([1.55140566e-17, -5.00453439e-15, -1.31302838e+01, 6.62087352e-13, -2.13577297e-10, 2.21484026e+02, -4.67637454e+00, -2.89824658e+00])
#startsw = [0,1, 0, 0]

problem = Implicit_Problem(res, y0, yd0, t0, sw0=startsw)

problem.state_events = state_events
problem.handle_event = handle_event
problem.name = 'Woodpecker'

phipIndex = [4, 5]
lambdaIndex = [6, 7]
sim = IDA(problem)
sim.rtol = 1e-6

sim.atol[phipIndex] = 1e8
sim.algvar[phipIndex] = 1
sim.atol[lambdaIndex] = 1e8
sim.algvar[lambdaIndex] = 1 

sim.suppress_alg = True
ncp = 500

tfinal = 2
Ejemplo n.º 11
0
import numpay as np
import pylab as P
from assimulo.problem import Implicit_Problem
from assimulo.solvers import IDA

y0 = np.array([0 0 0 0 0 0 0])
yp0 = np.array([0 0 0 0 0 0 0])
t0 = 0.0



model = Implicit_Problem(squeezer, y0, yp0, t0)
model.name = 'Squeezer'

solver = IDA(model)


Ejemplo n.º 12
0
from scipy import *
from assimulo.problem import Implicit_Problem
from assimulo.solvers import IDA
from Project_2 import squeezer as sq
from Project_2 import squeezer2 as sq2
import matplotlib.pyplot as plt

t0 = 0
tfinal = 0.03

# Model 1, squeezer with index 3 constraints
y0_1,yp0_1 = sq.init_squeezer()
ncp_1 = 100
model_1 = Implicit_Problem(sq.squeezer, y0_1, yp0_1, t0)
model_1.name = 'Squeezer index 3 constraints'
sim_1 = IDA(model_1)
sim_1.suppress_alg = True
sim_1.algvar = array([1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0])
sim_1.atol = ones(20,)
for i in range(size(sim_1.atol)):
    if 0 <= i <= 6:
        sim_1.atol[i] = pow(10,-6)
    else:
        sim_1.atol[i] = pow(10,5)
t, y, yd = sim_1.simulate(tfinal, ncp_1)
plt.plot(t,y[:,14:shape(y)[1]]) # Plots the Lagrange multipliers
plt.show()
plt.plot(t,(y[:,0:7]+pi)%(2*pi)-pi) # Plots the position variables i.e beta,gamma etc, modulo 2pi.
plt.show()

# Model 2, squeezer with index 2 constraints
Ejemplo n.º 13
0
    sim.atol[lambdaIndex] = 1e-1
    sim.atol[velocityIndex] = 1e-5
elif indexNumber == 2:
    problem = Implicit_Problem(squeezer2, y0, yd0, t0)
    algvar[lambdaIndex] = 0
    algvar[velocityIndex] = 1
    sim = IDA(problem)
    sim.atol = numpy.ones(numpy.size(y0))*1e-7
    sim.atol[lambdaIndex] = 1e-5
    sim.atol[velocityIndex] = 1e-5
elif indexNumber == 1:
    problem = Explicit_Problem(squeezer1, y0[0:14], t0)
    sim = RungeKutta34(problem)
    sim.atol = numpy.ones(14)*1e-7

problem.name = 'Squeezer'

sim.rtol = 1e-8 

tfinal = 0.03
ncp = 5000

if indexNumber == 2 or indexNumber == 3:
    sim.algvar = algvar
    sim.suppress_alg = True
    t, y, yd = sim.simulate(tfinal, ncp)
elif indexNumber == 1:
    t, y, = sim.simulate(tfinal, ncp)


Ejemplo n.º 14
0
y0 = numpy.array([0.5, 0,0, -0, 0, 0.5,-1e-4,0])
yd0 =  numpy.array([-0, 0, 0.5,-g, 1e-12, 0, 0, 0])

w0 = -0.91
y0 = numpy.array([0.5, 0,0, -0, w0, w0,-1e-4,0])
yd0 =  numpy.array([-0, w0, w0,-g, 1e-12, 0, 0, 0])

#y0 = numpy.array([4.83617428e-01, -3.00000000e-02, -2.16050178e-01, 1.67315232e-16, -5.39725367e-14, -1.31300925e+01, -7.20313572e-02, -6.20545138e-02])
#yd0 = numpy.array([1.55140566e-17, -5.00453439e-15, -1.31302838e+01, 6.62087352e-13, -2.13577297e-10, 2.21484026e+02, -4.67637454e+00, -2.89824658e+00])
#startsw = [0,1, 0, 0]

problem = Implicit_Problem(res, y0, yd0, t0, sw0=startsw)

problem.state_events = state_events
problem.handle_event = handle_event
problem.name = 'Woodpecker'

phipIndex = [4, 5]
lambdaIndex = [6, 7]
sim = IDA(problem)
sim.rtol = 1e-6

sim.atol[phipIndex] = 1e8
sim.algvar[phipIndex] = 1
sim.atol[lambdaIndex] = 1e8
sim.algvar[lambdaIndex] = 1 

sim.suppress_alg = True
ncp = 500

tfinal = 2
Ejemplo n.º 15
0
     np.real(ux_x_min), \
     np.imag(ux_x_min), \
     np.real(b_par_x_min), \
     np.imag(b_par_x_min), \
     np.real(u_perp_x_min), \
     np.imag(u_perp_x_min) ])
dU_x_min = np.array([ \
     np.real(dux_x_min), \
     np.imag(dux_x_min), \
     np.real(db_par_x_min), \
     np.imag(db_par_x_min), \
     np.real(du_perp_x_min), \
     np.imag(du_perp_x_min) ])

model = Implicit_Problem(residual, U_x_min, dU_x_min, x_min)
model.name = 'Resonant absorption'

sim = IDA(model)

x, U, dU = sim.simulate(x_max, nx)

x = np.array(x)

ux_r = U[:, 0]
ux_i = U[:, 1]
b_par_r = U[:, 2]
b_par_i = U[:, 3]
u_perp_r = U[:, 4]
u_perp_i = U[:, 5]

fig = plt.figure()
Ejemplo n.º 16
0
def dae_solver(residual,
               y0,
               yd0,
               t0,
               p0=None,
               jac=None,
               name='DAE',
               solver='IDA',
               algvar=None,
               atol=1e-6,
               backward=False,
               display_progress=True,
               pbar=None,
               report_continuously=False,
               rtol=1e-6,
               sensmethod='STAGGERED',
               suppress_alg=False,
               suppress_sens=False,
               usejac=False,
               usesens=False,
               verbosity=30,
               tfinal=10.,
               ncp=500):
    '''
    DAE solver.

    Parameters
    ----------
    residual: function
        Implicit DAE model.
    y0: List[float]
        Initial model state.
    yd0: List[float]
        Initial model state derivatives.
    t0: float
        Initial simulation time.
    p0: List[float]
        Parameters for which sensitivites are to be calculated.
    jac: function
        Model jacobian.
    name: string
        Model name.
    solver: string
        DAE solver.
    algvar: List[bool]
        A list for defining which variables are differential and which are algebraic.
        The value True(1.0) indicates a differential variable and the value False(0.0) indicates an algebraic variable.
    atol: float
        Absolute tolerance.
    backward: bool
        Specifies if the simulation is done in reverse time.
    display_progress: bool
        Actives output during the integration in terms of that the current integration is periodically printed to the stdout.
        Report_continuously needs to be activated.
    pbar: List[float]
        An array of positive floats equal to the number of parameters. Default absolute values of the parameters.
        Specifies the order of magnitude for the parameters. Useful if IDAS is to estimate tolerances for the sensitivity solution vectors.
    report_continuously: bool
        Specifies if the solver should report the solution continuously after steps.
    rtol: float
        Relative tolerance.
    sensmethod: string
        Specifies the sensitivity solution method.
        Can be either ‘SIMULTANEOUS’ or ‘STAGGERED’. Default is 'STAGGERED'.
    suppress_alg: bool
        Indicates that the error-tests are suppressed on algebraic variables.
    suppress_sens: bool
        Indicates that the error-tests are suppressed on the sensitivity variables.
    usejac: bool
        Sets the option to use the user defined jacobian.
    usesens: bool
        Aactivates or deactivates the sensitivity calculations.
    verbosity: int
        Determines the level of the output.
        QUIET = 50 WHISPER = 40 NORMAL = 30 LOUD = 20 SCREAM = 10
    tfinal: float
        Simulation final time.
    ncp: int
        Number of communication points (number of return points).

    Returns
    -------
    sol: solution [time, model states], List[float]
    '''
    if usesens is True:  # parameter sensitivity
        model = Implicit_Problem(residual, y0, yd0, t0, p0=p0)
    else:
        model = Implicit_Problem(residual, y0, yd0, t0)

    model.name = name

    if usejac is True:  # jacobian
        model.jac = jac

    if algvar is not None:  # differential or algebraic variables
        model.algvar = algvar

    if solver == 'IDA':  # solver
        from assimulo.solvers import IDA
        sim = IDA(model)

    sim.atol = atol
    sim.rtol = rtol
    sim.backward = backward  # backward in time
    sim.report_continuously = report_continuously
    sim.display_progress = display_progress
    sim.suppress_alg = suppress_alg
    sim.verbosity = verbosity

    if usesens is True:  # sensitivity
        sim.sensmethod = sensmethod
        sim.pbar = np.abs(p0)
        sim.suppress_sens = suppress_sens

    # Simulation
    # t, y, yd = sim.simulate(tfinal, ncp=(ncp - 1))
    ncp_list = np.linspace(t0, tfinal, num=ncp, endpoint=True)
    t, y, yd = sim.simulate(tfinal, ncp=0, ncp_list=ncp_list)

    # Plot
    # sim.plot()

    # plt.figure()
    # plt.subplot(221)
    # plt.plot(t, y[:, 0], 'b.-')
    # plt.legend([r'$\lambda$'])
    # plt.subplot(222)
    # plt.plot(t, y[:, 1], 'r.-')
    # plt.legend([r'$\dot{\lambda}$'])
    # plt.subplot(223)
    # plt.plot(t, y[:, 2], 'k.-')
    # plt.legend([r'$\eta$'])
    # plt.subplot(224)
    # plt.plot(t, y[:, 3], 'm.-')
    # plt.legend([r'$\dot{\eta}$'])

    # plt.figure()
    # plt.subplot(221)
    # plt.plot(t, yd[:, 0], 'b.-')
    # plt.legend([r'$\dot{\lambda}$'])
    # plt.subplot(222)
    # plt.plot(t, yd[:, 1], 'r.-')
    # plt.legend([r'$\ddot{\lambda}$'])
    # plt.subplot(223)
    # plt.plot(t, yd[:, 2], 'k.-')
    # plt.legend([r'$\dot{\eta}$'])
    # plt.subplot(224)
    # plt.plot(t, yd[:, 3], 'm.-')
    # plt.legend([r'$\ddot{\eta}$'])

    # plt.figure()
    # plt.subplot(121)
    # plt.plot(y[:, 0], y[:, 1])
    # plt.xlabel(r'$\lambda$')
    # plt.ylabel(r'$\dot{\lambda}$')
    # plt.subplot(122)
    # plt.plot(y[:, 2], y[:, 3])
    # plt.xlabel(r'$\eta$')
    # plt.ylabel(r'$\dot{\eta}$')

    # plt.figure()
    # plt.subplot(121)
    # plt.plot(yd[:, 0], yd[:, 1])
    # plt.xlabel(r'$\dot{\lambda}$')
    # plt.ylabel(r'$\ddot{\lambda}$')
    # plt.subplot(122)
    # plt.plot(yd[:, 2], yd[:, 3])
    # plt.xlabel(r'$\dot{\eta}$')
    # plt.ylabel(r'$\ddot{\eta}$')

    # plt.figure()
    # plt.subplot(121)
    # plt.plot(y[:, 0], y[:, 2])
    # plt.xlabel(r'$\lambda$')
    # plt.ylabel(r'$\eta$')
    # plt.subplot(122)
    # plt.plot(y[:, 1], y[:, 3])
    # plt.xlabel(r'$\dot{\lambda}$')
    # plt.ylabel(r'$\dot{\eta}$')

    # plt.figure()
    # plt.subplot(121)
    # plt.plot(yd[:, 0], yd[:, 2])
    # plt.xlabel(r'$\dot{\lambda}$')
    # plt.ylabel(r'$\dot{\eta}$')
    # plt.subplot(122)
    # plt.plot(yd[:, 1], yd[:, 3])
    # plt.xlabel(r'$\ddot{\lambda}$')
    # plt.ylabel(r'$\ddot{\eta}$')

    # plt.show()

    sol = [t, y, yd]
    return sol
Ejemplo n.º 17
0
def run_example(with_plots=True):
    r"""
    Example for the use of Radau5DAE to solve
    Van der Pol's equation
    
    .. math::
       
        \dot y_1 &= y_2 \\
        \dot y_2 &= \mu ((1.-y_1^2) y_2-y_1)

    with :math:`\mu= 10^6`.

    on return:
    
       - :dfn:`imp_mod`    problem instance
    
       - :dfn:`imp_sim`    solver instance

    """

    #Define the residual
    def f(t, y, yd):
        eps = 1.e-6
        my = 1. / eps
        yd_0 = y[1]
        yd_1 = my * ((1. - y[0]**2) * y[1] - y[0])

        res_0 = yd[0] - yd_0
        res_1 = yd[1] - yd_1

        return N.array([res_0, res_1])

    y0 = [2.0, -0.6]  #Initial conditions
    yd0 = [-.6, -200000.]

    #Define an Assimulo problem
    imp_mod = Implicit_Problem(f, y0, yd0)
    imp_mod.name = 'Van der Pol (implicit)'

    #Define an explicit solver
    imp_sim = Radau5DAE(imp_mod)  #Create a Radau5 solver

    #Sets the parameters
    imp_sim.atol = 1e-4  #Default 1e-6
    imp_sim.rtol = 1e-4  #Default 1e-6
    imp_sim.inith = 1.e-4  #Initial step-size

    #Simulate
    t, y, yd = imp_sim.simulate(2.)  #Simulate 2 seconds

    #Plot
    if with_plots:
        P.subplot(211)
        P.plot(t, y[:, 0])  #, marker='o')
        P.xlabel('Time')
        P.ylabel('State')
        P.subplot(212)
        P.plot(t, yd[:, 0] * 1.e-5)  #, marker='o')
        P.xlabel('Time')
        P.ylabel('State derivatives scaled with $10^{-5}$')
        P.suptitle(imp_mod.name)
        P.show()

    #Basic test
    x1 = y[:, 0]
    assert N.abs(x1[-1] - 1.706168035) < 1e-3  #For test purpose
    return imp_mod, imp_sim
Ejemplo n.º 18
0
    res = np.zeros(6 * ct.nz)
    res[0:ct.nz] = np.real(dux + 1j * ct.omega * b_par + nabla_perp_u_perp)
    res[ct.nz:2 * ct.nz] = np.imag(dux + 1j * ct.omega * b_par +
                                   nabla_perp_u_perp)
    res[2 * ct.nz:3 * ct.nz] = np.real(db_par + 1j / ct.omega * L_ux)
    res[3 * ct.nz:4 * ct.nz] = np.imag(db_par + 1j / ct.omega * L_ux)
    res[4 * ct.nz:5 * ct.nz] = np.real(L_u_perp -
                                       1j * ct.omega * nabla_perp_b_par)
    res[5 * ct.nz:] = np.imag(L_u_perp - 1j * ct.omega * nabla_perp_b_par)

    return res


model = Implicit_Problem(residual, ct.U_x_min, ct.dU_x_min, ct.x_min)
model.name = 'Resonant abosprotion'

sim = IDA(model)

x, U, dU = sim.simulate(ct.x_max, ct.nx)

# sim.plot()

# fig = plt.figure()
# ax = fig.add_subplot(111)
# ax.plot(ct.z, ct.dU_perp_x_min[0:ct.nz])
# ax.plot(ct.z, np.real(ct.du_perp_ana(ct.x_min,ct.z)))

# fig = plt.figure()
# ax = fig.add_subplot(111)
# ax.plot(ct.z, ct.dU_perp_x_min[ct.nz:])
Ejemplo n.º 19
0
def run_example(with_plots=True):

    #Defines the residual
    def f(t, y, yd):

        res_0 = yd[0] - y[2]
        res_1 = yd[1] - y[3]
        res_2 = yd[2] + y[4] * y[0]
        res_3 = yd[3] + y[4] * y[1] + 9.82
        #res_4 = y[0]**2+y[1]**2-1
        res_4 = y[2]**2 + y[3]**2 - y[4] * (y[0]**2 + y[1]**2) - y[1] * 9.82

        return N.array([res_0, res_1, res_2, res_3, res_4])

    #Defines the jacobian
    def jac(c, t, y, yd):
        jacobian = N.zeros([len(y), len(y)])

        #Derivative
        jacobian[0, 0] = 1 * c
        jacobian[1, 1] = 1 * c
        jacobian[2, 2] = 1 * c
        jacobian[3, 3] = 1 * c

        #Differentiated
        jacobian[0, 2] = -1
        jacobian[1, 3] = -1
        jacobian[2, 0] = y[4]
        jacobian[3, 1] = y[4]
        jacobian[4, 0] = y[0] * 2 * y[4] * -1
        jacobian[4, 1] = y[1] * 2 * y[4] * -1 - 9.82
        jacobian[4, 2] = y[2] * 2
        jacobian[4, 3] = y[3] * 2

        #Algebraic
        jacobian[2, 4] = y[0]
        jacobian[3, 4] = y[1]
        jacobian[4, 4] = -(y[0]**2 + y[1]**2)

        return jacobian

    #The initial conditons
    y0 = [1.0, 0.0, 0.0, 0.0, 5]  #Initial conditions
    yd0 = [0.0, 0.0, 0.0, -9.82, 0.0]  #Initial conditions

    #Create an Assimulo implicit problem
    imp_mod = Implicit_Problem(f, y0, yd0)

    #Sets the options to the problem
    imp_mod.jac = jac  #Sets the jacobian
    imp_mod.algvar = [1.0, 1.0, 1.0, 1.0, 0.0]  #Set the algebraic components
    imp_mod.name = 'Test Jacobian'

    #Create an Assimulo implicit solver (IDA)
    imp_sim = IDA(imp_mod)  #Create a IDA solver

    #Sets the paramters
    imp_sim.atol = 1e-6  #Default 1e-6
    imp_sim.rtol = 1e-6  #Default 1e-6
    imp_sim.suppress_alg = True  #Suppres the algebraic variables on the error test

    #Let Sundials find consistent initial conditions by use of 'IDA_YA_YDP_INIT'
    imp_sim.make_consistent('IDA_YA_YDP_INIT')

    #Simulate
    t, y, yd = imp_sim.simulate(
        5, 1000)  #Simulate 5 seconds with 1000 communication points

    #Basic tests
    nose.tools.assert_almost_equal(y[-1][0], 0.9401995, places=4)
    nose.tools.assert_almost_equal(y[-1][1], -0.34095124, places=4)
    nose.tools.assert_almost_equal(yd[-1][0], -0.88198927, places=4)
    nose.tools.assert_almost_equal(yd[-1][1], -2.43227069, places=4)

    #Plot
    if with_plots:
        P.plot(t, y)
        P.show()