示例#1
0
    def iterate(self,
                fullt,
                steps,
                autogen_fname=None,
                localdefs=None,
                autogen='autogen'):
        """
        Iterates over the system of equations 
        """
        if autogen_fname is not None:
            autogen = autogen_fname
            del autogen_fname
            util.warn(
                "parameter 'autogen_fname' is deprecated. Use 'autogen' instead."
            )

        # setting up the timesteps
        dt = fullt / float(steps)
        self.t = [dt * i for i in range(steps)]

        # generates the initializator and adds the timestep
        self.init_text = self.generate_init(localdefs=localdefs)
        self.init_text += '\ndt = %s' % dt

        #print init_text

        # generates the derivatives
        self.func_text = self.generate_function()
        #print func_text

        self.dynamic_code = self.init_text + '\n' + self.func_text

        try:
            fp = open('%s.py' % autogen, 'wt')
            fp.write('%s\n' % self.init_text)
            fp.write('%s\n' % self.func_text)
            fp.close()
            autogen_mod = __import__(autogen)
            try:
                os.remove('%s.pyc' % autogen)
            except OSError:
                pass  # must be a read only filesystem
            imp.reload(autogen_mod)
        except Exception as exc:
            msg = "'%s' in:\n%s\n*** dynamic code error ***\n%s" % (
                exc, self.dynamic_code, exc)
            util.error(msg)

        # x0 has been auto generated in the initialization
        self.alldata = rk4(autogen_mod.derivs, autogen_mod.x0, self.t)

        for index, node in enumerate(self.nodes):
            self.lazy_data[node] = [row[index] for row in self.alldata]
示例#2
0
    def iterate( self, fullt, steps, autogen_fname=None, localdefs=None, autogen='autogen'  ):
        """
        Iterates over the system of equations 
        """
        if autogen_fname is not None:
            autogen = autogen_fname
            del autogen_fname
            util.warn("parameter 'autogen_fname' is deprecated. Use 'autogen' instead." )
        
        # setting up the timesteps
        dt = fullt/float(steps)
        self.t  = [ dt * i for i in range(steps) ]

        # generates the initializator and adds the timestep
        self.init_text  = self.generate_init( localdefs=localdefs )
        self.init_text += '\ndt = %s' % dt

        #print init_text
        
        # generates the derivatives
        self.func_text = self.generate_function()
        #print func_text
       
        self.dynamic_code = self.init_text + '\n' + self.func_text             
        
        try:
            fp = open( '%s.py' % autogen, 'wt')
            fp.write( '%s\n' % self.init_text )
            fp.write( '%s\n' % self.func_text )
            fp.close()
            autogen_mod = __import__( autogen )
            try:
                os.remove( '%s.pyc' % autogen )
            except OSError:
                pass # must be a read only filesystem
            imp.reload( autogen_mod )
        except Exception as exc:
            msg = "'%s' in:\n%s\n*** dynamic code error ***\n%s" % ( exc, self.dynamic_code, exc )
            util.error(msg)

        # x0 has been auto generated in the initialization
        self.alldata = rk4(autogen_mod.derivs, autogen_mod.x0, self.t) 
        
        for index, node in enumerate( self.nodes ):
            self.lazy_data[node] = [ row[index] for row in self.alldata ]
示例#3
0

def df_dt(x, t):

    a = 0.1
    b = 0.02
    c = 0.3
    d = 0.01
    """Funcion del sistema en forma canonica"""
    dx = a * x[0] - b * x[0] * x[1]
    dy = -c * x[1] + d * x[0] * x[1]
    return np.array([dx, dy])


# initial conditions for the system
x0 = 40
y0 = 9

# vector of times
t = np.linspace(0, 200, 800)

result = py.rk4(df_dt, [x0, y0], t)
print result

plt.plot(t, result)

plt.xlabel('Tiempo')
plt.ylabel('Tamano de la poblecion')
plt.legend(('presa', 'depredador'))
plt.title('Modelo Lotka-Volterra')
plt.show()
示例#4
0
class PldeModel( BoolModel ):
    """
    This class generates python code that will be executed inside 
    the Runge-Kutta integrator.
    """
    def __init__(self, text, mode='plde'):
        
        # run the regular boolen engine for one step to detect syntax errors
        model = BoolModel(text=text, mode='sync')
        model.initialize( missing=util.randbool )
        model.iterate( steps=1 )

        # onto the main initialization
        self.INIT_LINE  = helper.init_line
        self.OVERRIDE   = default_override
        self.DEFAULT_EQUATION = default_equation
        self.EXTRA_INIT = ''

        # setting up this engine
        BoolModel.__init__(self, text=text, mode=mode)
        self.dynamic_code = '*** not yet generated ***'
        self.lazy_data = {}
    
    @property
    def data(self):
        "For compatibility with the async engine"
        return self.lazy_data

    def initialize(self, missing=None, defaults={} ):
        "Custom initializer"
        BoolModel.initialize( self, missing=missing, defaults=defaults )
        
        # will also maintain the order of insertion
        self.mapper  = odict.odict() 
        self.indexer = {}
        
        # this will maintain the order of nodes
        self.nodes = list(self.nodes)
        self.nodes.sort()
        for index, node in enumerate(self.nodes):
            triplet = self.first[node]
            self.mapper [node] = ( index, node, triplet )
            self.indexer[node] = index
        
        # a sanity check
        assert self.nodes == self.mapper.keys()

    def generate_init( self, localdefs ):
        """
        Generates the initialization lines
        """
        init = [ ]
        
        init.extend( self.EXTRA_INIT.splitlines() )
        init.append( '# dynamically generated code' )
        init.append( '# abbreviations: c=concentration, d=decay, t=threshold, n=newvalue' )
        init.append( '# %s' % self.mapper.values() )

        for index, node, triplet in self.mapper.values():
            conc, decay, tresh = boolmapper(triplet)
            #assert decay > 0, 'Decay for node %s must be larger than 0 -> %s' % (node, str(triplet))   
            store = dict( index=index, conc=conc, decay=decay, tresh=tresh, node=node)
            line = self.INIT_LINE( store )
            init.append( line )
        
        if localdefs:
            init.extend( [ '# custom imports', 'import %s' % localdefs, 'reload(%s)' % localdefs, 'from %s import *' % localdefs ]   )

        init_text = '\n'.join( init )
        return init_text
    
    def create_equation( self, tokens ):
        """
        Creates a python equation from a list of tokens.
        """
        original = '#' + tokenizer.tok2line(tokens)
        node  = tokens[1].value
        lines = [ '', original ]
        
        line  = self.OVERRIDE(node, indexer=self.indexer, tokens=tokens)
        if line is None:
            line = self.DEFAULT_EQUATION( tokens=tokens, indexer=self.indexer )
        
        if isinstance(line, str):
            line = [ line ]

        lines.extend( [ x.strip() for x in line ] )
        return lines  

    def generate_function(self ):
        """
        Generates the function that will be used to integrate
        """
        sep = ' ' * 4

        indices = [ x[0] for x in self.mapper.values() ]
        assign  = [ 'c%d' % i for i in indices ]
        retvals = [ 'n%d' % i for i in indices ]
        zeros   = map(lambda x: '0.0', indices ) 
        assign  = ', '.join(assign)
        retvals = ', '.join(retvals)
        zeros   = ', '.join( zeros )

        body = []
        body.append( 'x0 = %s' % assign )
        body.append( 'def derivs( x, t):' )
         
        body.append( '    %s = x' % assign )
        body.append( '    %s = %s' % (retvals, zeros) )
        for tokens in self.update_tokens:
            equation = self.create_equation( tokens )
            equation = [ sep + e for e in equation ]
            body.append( '\n'.join( equation)  )
        body.append( '' )
        body.append( "    return ( %s ) " % retvals )
        text = '\n'.join( body )
        
        return text

    def iterate( self, fullt, steps, autogen_fname=None, localdefs=None, autogen='autogen'  ):
        """
        Iterates over the system of equations 
        """
        if autogen_fname is not None:
            autogen = autogen_fname
            del autogen_fname
            util.warn("parameter 'autogen_fname' is deprecated. Use 'autogen' instead." )
        
        # setting up the timesteps
        dt = fullt/float(steps)
        self.t  = [ dt * i for i in range(steps) ]

        # generates the initializator and adds the timestep
        self.init_text  = self.generate_init( localdefs=localdefs )
        self.init_text += '\ndt = %s' % dt

        #print init_text
        
        # generates the derivatives
        self.func_text = self.generate_function()
        #print func_text
       
        self.dynamic_code = self.init_text + '\n' + self.func_text             
        
        try:
            fp = open( '%s.py' % autogen, 'wt')
            fp.write( '%s\n' % self.init_text )
            fp.write( '%s\n' % self.func_text )
            fp.close()
            autogen_mod = __import__( autogen )
            try:
                os.remove( '%s.pyc' % autogen )
            except OSError:
                pass # must be a read only filesystem
            reload( autogen_mod )
        except Exception, exc:
            msg = "'%s' in:\n%s\n*** dynamic code error ***\n%s" % ( exc, self.dynamic_code, exc )
            util.error(msg)

        # x0 has been auto generated in the initialization
        self.alldata = rk4(autogen_mod.derivs, autogen_mod.x0, self.t) 
        
        for index, node in enumerate( self.nodes ):
            self.lazy_data[node] = [ row[index] for row in self.alldata ]
示例#5
0
timeSeries = np.arange(0, 20, timeStep)
X = (10.0, 1.0)

#Ranges of a and b to test over
a_range = np.arange(0.001, 0.05, 0.001).tolist()
b_range = np.arange(0.01, 1.0, 0.01).tolist()

#Default values of a and b
a = 0.0025
b = 0.1

#Record the values of X1 and X2 at t=20 for each value in a_range
a_sens = []
for i in a_range:
    a = i
    Xout = pylab.rk4(simulate, X, timeSeries)
    t20_values = Xout[19].tolist()
    #third column will be a value. b remains default throughout
    t20_values.append(i)

    a_sens.append(t20_values)

a_sens = np.array(a_sens)

#Reset a to default to test sensitivity to b
a = 0.0025

b_sens = []
for i in b_range:
    b = i
    Xout = pylab.rk4(simulate, X, timeSeries)
    #dx=px
    dx=v[2]
    #dx=py
    dy=v[3]

    return(dx, dy, dpx, dpy)


#Values to go into the rk4 function
dt=0.01
fintime=500.0
tim=np.arange(0.0, fintime, dt)

# (x,y,px,py) <- intial values
Xout1=pylab.rk4(system1, (0.02, 0.2, 0.001, 0.2), tim)
Xout2=pylab.rk4(system1, (0.01, 0.3, 0.002, 0.1), tim)

fig=plt.figure()
ax = fig.gca(projection='3d')

#Graphs taken from http://matplotlib.org/examples/mplot3d/lorenz_attractor.html
#This system has 4 dimmensions but just looking at 3 still shows different patterns between the two starting conditions.
#Oringal initial values in red, slight change in them in blue.
ax.plot(Xout1[:,0], Xout1[:,1], Xout1[:,2], '-r')
ax.plot(Xout2[:,0], Xout2[:,1], Xout2[:,2], '-b')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('System 1')
ax.legend()
示例#7
0
    #dx=px
    dx = v[2]
    #dx=py
    dy = v[3]

    return (dx, dy, dpx, dpy)


#Values to go into the rk4 function
dt = 0.01
fintime = 500.0
tim = np.arange(0.0, fintime, dt)

# (x,y,px,py) <- intial values
Xout1 = pylab.rk4(system1, (0.02, 0.2, 0.001, 0.2), tim)
Xout2 = pylab.rk4(system1, (0.01, 0.3, 0.002, 0.1), tim)

fig = plt.figure()
ax = fig.gca(projection='3d')

#Graphs taken from http://matplotlib.org/examples/mplot3d/lorenz_attractor.html
#This system has 4 dimmensions but just looking at 3 still shows different patterns between the two starting conditions.
#Oringal initial values in red, slight change in them in blue.
ax.plot(Xout1[:, 0], Xout1[:, 1], Xout1[:, 2], '-r')
ax.plot(Xout2[:, 0], Xout2[:, 1], Xout2[:, 2], '-b')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('System 1')
ax.legend()
timeSeries=np.arange(0,20, timeStep)
X = (10.0, 1.0)

#Ranges of a and b to test over
a_range=np.arange(0.001, 0.05, 0.001).tolist()
b_range=np.arange(0.01, 1.0, 0.01).tolist()

#Default values of a and b
a=0.0025
b=0.1

#Record the values of X1 and X2 at t=20 for each value in a_range
a_sens=[]
for i in a_range:
    a=i
    Xout=pylab.rk4(simulate, X, timeSeries)
    t20_values=Xout[19].tolist()
    #third column will be a value. b remains default throughout
    t20_values.append(i)

    a_sens.append(t20_values)

a_sens=np.array(a_sens)


#Reset a to default to test sensitivity to b
a=0.0025

b_sens=[]
for i in b_range:
    b=i