Example #1
0
 def runSecSim(self, tMainSim):
     params = self.params
     
     # Define the parameters
     eqns_params = {'k1':params.k1, 
         'k2':params.k2, 
         'k3':params.k3, 
         's1_in':params.s1_in, 
         's2_in':params.s2_in, 
         'a':params.a, 
         'm1':params.m1, 
         'm2':params.m2, 
         'k_s1':params.k_s1, 
         'k_s2':params.k_s2, 
         'k_I':params.k_I, 
         'D':params.D, 
         'tau1':params.tau1, 
         'tau2':params.tau2}
     
     # Initialize the solver
     self.dde = dde23(eqns=self.eqns, params=eqns_params, supportcode=self.support_c_code)
     
     # Initialize history of the state variables
     self.initHist(tMainSim)
     
     # Set the simulation parameters
     tFinalSecSim = self.solverParams.mainSimStep
     self.dde.set_sim_params(tfinal=tFinalSecSim, AbsTol=self.solverParams.absTol, RelTol=self.solverParams.relTol, dtmax=None)
     
     # Run the secondary simulation
     self.dde.run()
Example #2
0
def enso_dde_model(kappa, tau, b, nyears = 120, subsample_to_monthly = False):
    from pydelay import dde23

    eqn = {'h' : '-tanh(kappa * h(t-tau)) + b*cos(2*pi*t)'}
    params = {
        'kappa' : kappa,
        'tau' : tau,
        'b' : b,
        'pi' : np.pi
    }
    histfunc = {'h' : lambda t: 1.}
    
    dde = dde23(eqns = eqn, params = params)
    dde.set_sim_params(tfinal = 10000, dtmax = 0.01)
    dde.hist_from_funcs(histfunc, 100)
    dde.run()

    dt = 0.001

    sol = dde.sample(1000, 10000, dt) # 1 is year, int step is month
    t = sol['t']
    h = sol['h']

    t = t[:nyears/dt]
    h = h[:nyears/dt]

    if subsample_to_monthly:
        step = int((1/12.)/dt)
        t = t[::step]
        h = h[::step]

    return t, h
Example #3
0
    def calcmsf(self, alpha, beta, transients=5, final=4000):
        """MSF ausrechnen.
        """
        le = 0
        self.params['alpha'] = alpha
        self.params['beta'] = beta

        system = neteqns(self.groups, self.H, self.T, self.eqns, params=self.params, coupling=self.coupling)
        system.update(neteqns(self.groups, self.H, self.T, self.vareqns, params=self.params, coupling=self.coupling, var=True))

#        print system # debug

        for i in range(final):
            sdde = dde23(eqns=system, params=self.params, debug=False)
            sdde.set_sim_params(tfinal=self.params['tau'])
            if i==0:
                sdde.hist_from_arrays(self.__fillinitdict(self.transient, sdde.hist))
            else:
                norm = self.__calcnorm(linsol)
                if i > transients:
                    le += log(norm)
                sdde.hist_from_arrays(self.__renormalized(linsol, norm))
            sdde.run()
            sol = sdde.sol
            linsol = sdde.sol_spl(self.resarray)
        exponent = le/((i-transients)*self.params['tau'])
        return exponent.real
Example #4
0
    def transient(self, initial_conditions, tmax):
        """Zunaechst die History mit der Zeitserie eines Systems fuellen.
           Aber nur, wenn noch nichts gepickled und nichts an sys.argv[0]
           (das File mit den Gleichungen) geändert wurde.
        """
        import cPickle as pickle
        import hashlib

        file1 = hashlib.md5(open(sys.argv[0]).read()).hexdigest()+'.pickle'

        try:
            sol1 = pickle.load(open(file1,'r'))
            print >> sys.stderr, 'Transiente wird aus {0} genommen'.format(file1)
        except:
            eqns1 = neteqns([[rowsum(self.G,0)]], self.H, self.T, self.eqns, params=self.params, coupling=self.coupling)

            print >> sys.stderr, 'rechne Transiente für 1 System mit Gleichungen:'
            print >> sys.stderr, eqns1 #Debug

            dde1 = dde23(eqns=eqns1, params=self.params)
            dde1.set_sim_params(tfinal=tmax)

            for v in initial_conditions:
                for w in dde1.hist:
                    if re.match(v,w):
                        dde1.hist[w] += initial_conditions[v]

            dde1.run()

            sol1 = dde1.sol
            del(dde1)

            pickle.dump(sol1,open(file1,'w'))

        return sol1
def dde_solver(t_i,Ac_i,Am_i,Bc_i,Bm_i,Rm_i,AB_i,AR_i,tf):
    # the model equations 
    eqns = { 
        'Ac' : '-k1*Rm*Ac',
        'Am' : 'k1*Rm(t-tau1)*Ac(t-tau1)*Heavi(t-tau1) - k2*Am*Rm + k2*AR - k2*Am*Bm + k3*AB',
        'Bc' : '-k4*Am*Bc',
        'Bm' : 'k4*Am(t-tau2)*Bc(t-tau2)*Heavi(t-tau2) - k2*Am*Bm + k3*AB',
        'Rm' : 'qR - k2*Am*Rm + k2*AR',
        'AB' : 'k2*Am*Bm - k3*AB',
        'AR' : 'k2*Am*Rm - k2*AR',
        }

    # define parameters
    params = {
        'k1' : const.k1,           
        'k2' : const.k2,
        'k3' : const.k3,
        'k4' : const.k4,
        'qR' : const.qR,
        'tau1' : const.tau1,
        'tau2' : const.tau2,
        }

    # initial conditions
    histdict = {
        't'  : t_i,
        'Ac' : Ac_i,
        'Am' : Am_i,
        'Bc' : Bc_i,
        'Bm' : Bm_i,
        'Rm' : Rm_i,
        'AB' : AB_i,
        'AR' : AR_i,
        }
    
    # intialize the solver
    dde = dde23(eqns=eqns, params=params)

    dde.hist_from_arrays(histdict,useend=False)
    # set the simulation parameters
    
    # (solve from t=0 to t=tf and limit the maximum step size to 1.0) 
    dde.set_sim_params(tfinal=tf, dtmax=1)

    # run the simulator
    dde.run()

    # get the solutions from the history dict
    t = dde.sol['t']
    Ac= dde.sol['Ac']
    Am= dde.sol['Am']
    Bc = dde.sol['Bc']
    Bm = dde.sol['Bm']
    Rm = dde.sol['Rm']
    AB = dde.sol['AB']
    AR = dde.sol['AR']

    return(t,Ac,Am,Bc,Bm,Rm,AB,AR)
Example #6
0
def simulateInPieces(eqns, params, histfuncs, tfinal, num_pieces, sample_dt): 
    """
    Simulate until `tfinal` in `num_pieces` steps to avoid memory
    overflow. Return the final solution sampled with a resolution of
    `sample_dt`.
    """

    piece_length = tfinal * 1.0 / num_pieces
    n = 0

    # simulatie first piece with the given `histfuncs`
    dde = dde23(eqns=eqns, params=params)
    dde.set_sim_params(tfinal=piece_length)
    dde.hist_from_funcs(histfuncs)
    dde.run()

    maxinterval = 4
    resolution = 1E-4

    # set the history array for the next runs
    hist = HistoryCache(dde, maxinterval, resolution)

    # Sample the final result.
    # You may choose to write something to disc isntead
    result = dde.sample(0, piece_length, sample_dt)

    n += 1
    while n < num_pieces:
        dde = dde23(eqns=eqns, params=params)
        dde.set_sim_params(tfinal=piece_length)
        hist.initializeHistory(dde)
        dde.run()

        # extend the previous result with the new piece
        tmp = dde.sample(0, piece_length, sample_dt)
        for key, value in tmp.iteritems():
            # By definition the simulation always starts at t=0.
            # So we have to shift the time array for the new piece 
            if key == 't':  
                result[key] = np.append(result[key], value + n * piece_length)
            else:
                result[key] = np.append(result[key], value)
        n += 1
        hist = HistoryCache(dde, maxinterval, resolution)
    return result
Example #7
0
 def run_transient(self, inits, ttransients=20):
     ttime = ttransients * self.params['tau']
     tsystem = neteqns(self.groups, self.H, self.T, self.eqns, params=self.params, coupling=self.coupling)
     tdde = dde23(eqns=tsystem, params=self.params)
     tdde.set_sim_params(tfinal=ttime)
     for v in inits:
         for w in tdde.hist:
             if re.match(v,w):
                 tdde.hist[w][-1] = inits[v]
     tdde.run()
     self.transient = tdde.sol_spl(self.resarray)
Example #8
0
    def __init__(self, eqns, G, H, T, params, coupling, noise):
        self.G = G
        self.H = H
        self.T = T
        self.params = params
        self.coupling = coupling
        self.eqns = eqns
        self.noise = noise
        self.sol = dict()

        self.eqnsN = neteqns(self.G, self.H, self.T, self.eqns, params=self.params, coupling=self.coupling)
        self.noiseN = netnoise(self.eqnsN, self.noise)

        print >> sys.stderr, 'Gleichungen fuers ganze Netz:'
        print >> sys.stderr, self.eqnsN  #Debug
        print >> sys.stderr, 'Noise fuers ganze Netz:'
        print >> sys.stderr, self.noiseN #Debug

        self.ddeN = dde23(eqns=self.eqnsN, params=self.params, noise=self.noiseN)
Example #9
0
# import the solver
from pydelay import dde23

eqns = {'x': '-x + k*x(t-10) + A* f(w,t)'}

params = {'k': 0.1, 'w': 2.0, 'A': 0.5}

# We can define a c function to be used in the equations
mycode = """
    double f(double w, double t) {
        return sin(w*t);
    }
    """

# initalise the solver
dde = dde23(eqns=eqns, params=params, supportcode=mycode)

# set the simulation parameters
dde.set_sim_params(tfinal=40)


# we can define the history as a python function
def myhist(t):
    return 0.01 * t**2


dde.hist_from_funcs({'x': myhist})

# run the simulation
dde.run()
Example #10
0
    'n': '(p - n - (1.0 +n) * pow(abs(E),2))/T'
}

params = {
    'a': 4.0,
    'p': 1.0,
    'T': 200.0,
    'K': 0.1,
    'tau': tau,
    'nu': 10**-5,
    'n0': 10.0
}

noise = {'E': 'sqrt(0.5*nu*(n+n0)) * (gwn() + ii*gwn())'}

dde = dde23(eqns=laser_equations, params=params, noise=noise)
dde.set_sim_params(tfinal=tfinal)

# use a dictionary to set the history
thist = np.linspace(0, tau, tfinal)
Ehist = np.zeros(len(thist)) + 1.0
nhist = np.zeros(len(thist)) - 0.2
dic = {'t': thist, 'E': Ehist, 'n': nhist}

# 'useend' is True by default in hist_from_dict and thus the
# time array is shifted correctly
dde.hist_from_arrays(dic)

dde.run()

t = dde.sol['t']
Example #11
0
params = { 
        'k': 0.1,
        'w': 2.0,
        'A': 0.5
        }

# We can define a c function to be used in the equations
mycode = """
    double f(double w, double t) {
        return sin(w*t);
    }
    """

# initalise the solver
dde = dde23(eqns=eqns, params=params, supportcode=mycode)

# set the simulation parameters
dde.set_sim_params(tfinal=40)

# we can define the history as a python function
def myhist(t):
    return 0.01*t**2

dde.hist_from_funcs({'x': myhist})

# run the simulation
dde.run()

sol = dde.sample(0.01)
t = sol['t']
Example #12
0
    def __init__(self, params = None, **kwargs):   
        if params == None:
            params = AttributeDict(kwargs)
        self.params = params
        
        #Calculate the equilibrium point
        def mu1(s, m, k):
            return (m*s)/(k + s)
        
        def mu2(s, m, k, k_I):
            return (m*s)/(k + s + (s/k_I)*(s/k_I))
        
        def eq_s1(s1, *args):
            (_k1, _k2, _k3, _s1_in, _s2_in, a, m1, _m2, k_s1, _k_s2, _k_I, D, _tau1, _tau2) = args
            return a*D - mu1(s1, m1, k_s1)
        
        def eq_s2(s2, *args):
            (_k1, _k2, _k3, _s1_in, _s2_in, a, _m1, m2, _k_s1, k_s2, k_I, D, _tau1, _tau2) = args
            return a*D - mu2(s2, m2, k_s2, k_I)
        
        eqs_args = (
            params.k1, params.k2, params.k3, 
            params.s1_in, params.s2_in, params.a, 
            params.m1, params.m2, 
            params.k_s1, params.k_s2, params.k_I, 
            params.D, params.tau1, params.tau2)
        
        s1_eqpnt = fsolve(eq_s1, 1.0, args = eqs_args)[0]
        x1_eqpnt = (params.s1_in - s1_eqpnt)/(params.a*params.k1)
        if x1_eqpnt < 0:
            s1_eqpnt = params.s1_in
            x1_eqpnt = 0.0
        
        s2_eqpnt_sol, _info, ier, _msg  = fsolve(eq_s2, 1.0, args = eqs_args, full_output = True)
        if ier != 1 or s2_eqpnt_sol[0] < 0:
            x2_eqpnt = 0.0
            s2_eqpnt = params.s2_in + params.k2*mu1(s1_eqpnt, params.m1, params.k_s1) * x1_eqpnt / params.D
        else:
            s2_eqpnt = s2_eqpnt_sol[0]
            x2_eqpnt = ((params.s2_in - s2_eqpnt)*params.D + params.k2*mu1(s1_eqpnt, params.m1, params.k_s1)*x1_eqpnt) \
                / (params.k3 * mu2(s2_eqpnt, params.m2, params.k_s2, params.k_I))
            
        self.equilibriumPoint = [s1_eqpnt, x1_eqpnt, s2_eqpnt, x2_eqpnt]
        if plotEqulibriumValuesAtTheEnd:
            print "equilibrium point (s1, x1, s2, x2) = ", self.equilibriumPoint
        
        # Define the specific growth rates (in 'C' source code)
        support_c_code = """
        double mu1(double s, double m, double k) {
            return (m*s)/(k + s);
        }
        
        double mu2(double s, double m, double k, double k_I) {
            return (m*s)/(k + s + (s/k_I)*(s/k_I));
        }
        """
        
        # Define the equations
        eqns = {
            's1': 'D*(s1_in - s1) - k1*mu1(s1, m1, k_s1)*x1',
            'x1': 'mu1(s1(t-tau1), m1, k_s1)*x1(t-tau1) - a*D*x1',
            's2': 'D*(s2_in - s2) + k2*mu1(s1, m1, k_s1)*x1 - k3*mu2(s2, m2, k_s2, k_I)*x2',
            'x2': 'mu2(s2(t-tau2), m2, k_s2, k_I)*x2(t-tau2) - a*D*x2'
        }
        
        # Define the parameters
        eqns_params = {
            'k1'    : params.k1,
            'k2'    : params.k2,
            'k3'    : params.k3,
            's1_in' : params.s1_in,
            's2_in' : params.s2_in,
            'a'     : params.a,
            'm1'    : params.m1,
            'm2'    : params.m2,
            'k_s1'  : params.k_s1,
            'k_s2'  : params.k_s2,
            'k_I'   : params.k_I,
            'D'     : params.D,
            'tau1'  : params.tau1,
            'tau2'  : params.tau2,
        }
        
        # Initialize the solver
        self.dde = dde23(eqns=eqns, params=eqns_params, supportcode=support_c_code)

        # Set the initial conditions (i.e. set the history of the state variables)
        histfunc = {
            's1': lambda t: params.s1_hist_vals,
            'x1': lambda t: params.x1_hist_vals,
            's2': lambda t: params.s2_hist_vals,
            'x2': lambda t: params.x2_hist_vals
            }
        self.dde.hist_from_funcs(histfunc, 10.) #:TRICKY: 10. is 'nn' - sample in the interval
Example #13
0
import numpy as np
import pylab as pl
from pydelay import dde23

eqns = { 'x' : '0.25 * x(t-tau) / (1.0 + pow(x(t-tau),10.0)) -0.1*x' }

dde = dde23(eqns=eqns, params={'tau': 15})
dde.set_sim_params(tfinal=1000, dtmax=1.0, AbsTol=10**-6, RelTol=10**-3)

histfunc = {'x': lambda t: 0.5 } 
dde.hist_from_funcs(histfunc, 51)
dde.run()

sol1 = dde.sample(515, 1000, 0.1)
x1 = sol1['x']
sol2 = dde.sample(500, 1000-15, 0.1)
x2 = sol2['x']

pl.plot(x1, x2)
pl.xlabel('$x(t)$')
pl.ylabel('$x(t-15)$')

pl.show()
Example #14
0
    I1_hist = np.random.uniform(0.0, 1., n_t)
    I2_hist = np.random.uniform(0.0, 1., n_t)
    histdic = {
        't': t_hist,
        'Exc1': E1_hist,
        'Exc2': E2_hist,
        'Inh1': I1_hist,
        'Inh2': I2_hist
    }
    eqns = {
        'Exc1': func(0, 'E'),
        'Inh1': func(0, 'I'),
        'Exc2': func(1, 'E'),
        'Inh2': func(1, 'I')
    }
    dde = dde23(eqns, pardict)
    dde.set_sim_params(dtmin=1.e-3,
                       AbsTol=9.e-5,
                       RelTol=0.001,
                       tfinal=t_final,
                       dtmax=0.1,
                       MaxIter=1000000,
                       dt0=0.001)
    dde.hist_from_arrays(histdic)
    dde.run()
    sol = dde.sample(tstart=tc, tfinal=None, dt=dt1)

    t = sol['t']
    E1[i, :] = sol['Exc1']
    E2[i, :] = sol['Exc2']
    corEE[i] = find_corr(E1[i, :], E2[i, :])
# Programs 12c: The Mackey-Glass DDE.
# See Figure 12.5(a).
# pydelay must be on your computer.

import pylab as pl
from pydelay import dde23

# define the equations
eqns = {'x': '2 * x(t-tau) / (1.0 + pow(x(t-tau),p)) - x'}

#define the parameters
params = {'tau': 2, 'p': 10}

# Initialise the solver
dde = dde23(eqns=eqns, params=params)

# set the simulation parameters
# (solve from t=0 to t=1000 and limit the maximum step size to 1.0)
dde.set_sim_params(tfinal=1000, dtmax=1.0)

# set the history of to the constant function 0.5 (using a python lambda function)
histfunc = {'x': lambda t: 0.5}
dde.hist_from_funcs(histfunc, 51)

# run the simulator
dde.run()

# Make a plot of x(t) vs x(t-tau):
# Sample the solution twice with a stepsize of dt=0.1:

# once in the interval [515, 1000]
Example #16
0
import pylab as pl
from pydelay import dde23

# define the equations
eqns = { 
    'x' : '0.25 * x(t-tau) / (1.0 + pow(x(t-tau),p)) -0.1*x' 
    }

#define the parameters
params = {
    'tau': 15,
    'p'  : 10
    }

# Initialise the solver
dde = dde23(eqns=eqns, params=params)

# set the simulation parameters 
# (solve from t=0 to t=1000 and limit the maximum step size to 1.0)
dde.set_sim_params(tfinal=1000, dtmax=1.0)

# set the history of to the constant function 0.5 (using a python lambda function)
histfunc = {
    'x': lambda t: 0.5 
    } 
dde.hist_from_funcs(histfunc, 51)

# run the simulator
dde.run()

# Make a plot of x(t) vs x(t-tau):
Example #17
0
         if( c==n ){
               work = false;
           }else{ c++; }
 }
fclose(fr);
return narma;
}
"""

print(params)

tau_real = 7.958e-6  # tau(s)
theta_real = 1.59e-3  # theta(s)

# Initialise the solver
dde = dde23(eqns=eqns, params=params, supportcode=inputcode)

#set the simulation parameters
# (solve from t=0 to t=tfinal and limit the maximum step size to dtmax)
T = params['T']
tfinal = 55 * T
tcut = 10 * T
dde.set_sim_params(tfinal=tfinal, dtmax=0.05, AbsTol=10**-3, RelTol=10**-2)

# set the history  using a python lambda function
histfunc = {
    'x': lambda t: -0.01 * np.sin(185.0 * t),
    'y': lambda t: -0.01 * np.cos(223.0 * t)
}
dde.hist_from_funcs(histfunc, 1000)
	def do_pydelay(
				self,
				**_KwargVariablesDict
			):	

		#debug
		'''
		self.debug(('self.',self,[]))
		'''

		#network first
		self.network(
			**{
				'RecruitingConcludeConditionTuplesList':[
					(
						'MroClassesList',
						operator.contains,
						Equationer.EquationerClass
					)
				]
			}
		)

		#link
		self.PydelayedDeriveEquationersList=self.NetworkedDeriveConnectersList

		#map populate and neurongroup
		self.PydelayedEquationDictsList=map(
			lambda __PydelayedDeriveEquationer:
			__PydelayedDeriveEquationer.populate(
				).equation(
				).EquationingDifferentialDict,
			self.PydelayedDeriveEquationersList
		)

		#Check
		if 'eqns' not in self.PydelayingKwargVariablesDict:
			self.PydelayingKwargVariablesDict['eqns']={}

		#update
		map(
				lambda __PydelayedEquationDict:
				self.PydelayingKwargVariablesDict['eqns'].update(__PydelayedEquationDict),
				self.PydelayedEquationDictsList
			)

		#map populate and neurongroup
		self.PydelayedParamDictsList=map(
			lambda __PydelayedDeriveEquationer:
			__PydelayedDeriveEquationer.EquationingParamDict,
			self.PydelayedDeriveEquationersList
		)

		#Check
		if 'params' not in self.PydelayingKwargVariablesDict:
			self.PydelayingKwargVariablesDict['params']={}

		#update
		map(
				lambda __PydelayedParamDict:
				self.PydelayingKwargVariablesDict['params'].update(__PydelayedParamDict),
				self.PydelayedParamDictsList
			)

		#map populate and neurongroup
		self.PydelayedCodeStrsList=map(
			lambda __PydelayedDeriveEquationer:
			__PydelayedDeriveEquationer.EquationingCodeStr,
			self.PydelayedDeriveEquationersList
		)

		#Check
		if 'supportcode' not in self.PydelayingKwargVariablesDict:
			self.PydelayingKwargVariablesDict['supportcode']=""

		#update
		map(
				lambda __PydelayedCodeStr:
				self.PydelayingKwargVariablesDict.__setitem__(
					'supportcode',
					self.PydelayingKwargVariablesDict['supportcode']+'\n'+__PydelayedCodeStr
				),
				self.PydelayedCodeStrsList
			)

		#debug
		'''
		self.debug(('self.',self,['PydelayingKwargVariablesDict']))
		'''

		#bind
		self.PydelayedUnitsInt=len(self.PydelayingKwargVariablesDict['eqns'])

		#set
		self.PydelayedVariableStrsList=self.PydelayingKwargVariablesDict['eqns'].keys()

		#Initialise the solver
		self.PydelayedDde23Variable = dde23(
			**self.PydelayingKwargVariablesDict
		)

		#Set params inside the solver
		self.PydelayedDde23Variable.set_sim_params(
				dtmax=self.PydelayingSampleStepTimeFloat
			)

		#Check if the init conditions was not yet define else give them equal to 0
		if type(self.SimulatingInitFloatsArray)==None.__class__:
			self.SimulatingInitFloatsArray=np.zeros(1,dtype=float)
		if len(self.SimulatingInitFloatsArray)!=self.PydelayedUnitsInt:
			self.SimulatingInitFloatsArray=np.array([0.]*self.PydelayedUnitsInt)
		
		#Check if there is an history setted, else give the history as just the constant value of initial conditions
		if len(self.PydelayingHistoryFunctionsDict)!=self.PydelayedUnitsInt:

			#dict
			self.PydelayingHistoryFunctionsDict=dict(
				map(
					lambda __Int,__KeyStr:
					(__KeyStr,lambda _Time:self.SimulatingInitFloatsArray[__Int]),
					xrange(self.PydelayedUnitsInt),
					self.PydelayingKwargVariablesDict['eqns'].keys()
				)
			)

			#hist_from_funcs
			self.PydelayedDde23Variable.hist_from_funcs(self.PydelayingHistoryFunctionsDict)

		#Set the size of the Buffer
		if self.PydelayingStopTimeFloat<self.PydelayingBufferStepTimeFloat:
			self.PydelayedBufferStepsInt=(int)(
				self.PydelayingStopTimeFloat/self.PydelayingSampleStepTimeFloat
			)
		else:
			self.PydelayedBufferStepsInt=(int)(
				self.PydelayingBufferStepTimeFloat/self.PydelayingSampleStepTimeFloat
			)

		#debug
		'''
		self.debug(('self.',self,[
						'PydelayedBufferStepsInt',
						'SimulatingStopTimeFloat',
						'PydelayingBufferStepTimeFloat'
					]))
		'''
		
		#init the buffer array
		self.PydelayedBufferFloatsArray=np.array(
				(
					self.PydelayedUnitsInt,
					self.PydelayedBufferStepsInt
				),
				dtype=float
			)

		#set
		self.PydelayedMoniterSampleTimeIndexIntsArray=np.array(
			xrange(self.PydelayedBufferStepsInt)
		)

		#Check
		if self.PydelayingMoniterVariableIndexIntsArray==None:
			self.PydelayingMoniterVariableIndexIntsArray=np.array(xrange(self.PydelayedUnitsInt))

		#collect the global monitor
		self.collect(
			"StateMoniters",
			"Variable",
			SYS.MoniterClass().update(
					{
						'MoniteringVariableStr':'PydelayedBufferFloatsArray',
						'MoniteringSampleTimeIndexIntsArray':self.PydelayedMoniterSampleTimeIndexIntsArray,
						'MoniteringVariableIndexIntsArray':self.PydelayingMoniterVariableIndexIntsArray,
						'MoniteredTotalVariablesArray':np.zeros(
									(
										self.PydelayedUnitsInt,
										(int)(
											self.PydelayingStopTimeFloat-self.SimulatingStartTimeFloat
										)/self.PydelayingSampleStepTimeFloat
									)
								,dtype=float
							)	
					}
				)
		)

		#Debug
		'''
  
# calculate the intersection of nullclines
def intersection(X):
  return nullcl_01(X) - nullcl_02(X)

X0    = 0
X_int = fsolve(intersection,X0)
Y_int = nullcl_01(X_int)

print "intersection of nullclines x_0 , y_0 : ", X_int, Y_int

## initalise the solver, without noise!
#dde = dde23(eqns=eqns, params=params)

# with noise :
dde = dde23(eqns=eqns,params=params, noise=noise)

tfinal = 250
dde.set_sim_params(tfinal)

dde.hist_from_funcs({'x1': lambda t : -0.05 , 'y1': lambda t: -0.75,
					 'x2': lambda t :  0 ,    'y2': lambda t: 0	})

dde.run()

# sampling the numerical solution with sample size dt
sol = dde.sample(0,tfinal,dt=0.01)

# save the solution
x1 = sol['x1']
y1 = sol['y1']
Example #20
0
import numpy as np
import pylab as pl
from pydelay import dde23

eqns = {'x': '0.25 * x(t-tau) / (1.0 + pow(x(t-tau),10.0)) -0.1*x'}

dde = dde23(eqns=eqns, params={'tau': 15})
dde.set_sim_params(tfinal=1000, dtmax=1.0, AbsTol=10**-6, RelTol=10**-3)

histfunc = {'x': lambda t: 0.5}
dde.hist_from_funcs(histfunc, 51)
dde.run()

sol1 = dde.sample(515, 1000, 0.1)
x1 = sol1['x']
sol2 = dde.sample(500, 1000 - 15, 0.1)
x2 = sol2['x']

pl.plot(x1, x2)
pl.xlabel('$x(t)$')
pl.ylabel('$x(t-15)$')

pl.show()
Example #21
0
eqns = { 'E:C': '0.5*(1.0+ii*a)*E*n + K*E(t-tau)',
         'n'  : '(p - n - (1.0 +n) * pow(abs(E),2))/T'}

params = { 'a'  : 4.0, 
           'p'  : 1.0, 
           'T'  : 1000.0, 
           'K'  : 0.1, 
           'tau': 1000,
           'nu' : 10**-5,
           'n0' : 10.0
         }

noise = { 'E': 'sqrt(0.5*nu*(n+n0)) * (gwn() + ii*gwn())' }

dde = dde23(eqns=eqns, params=params, noise=noise)

tfinal = 20000
dde.set_sim_params(tfinal=tfinal)

# use a dictionary to set the history
thist = np.linspace(0, 1000, 10000)
Ehist = np.sin(0.01*thist)*np.exp(1.0j*0.001*thist)
nhist = np.sin(0.01*thist)-1

dic = {'t' : thist, 'E': Ehist, 'n': nhist}
dde.hist_from_arrays(dic)

dde.run()

t = dde.sol['t']
def dde_initializer(Ac_i,Am_i,Bc_i,Bm_i,Rm_i,AB_i,AR_i,tf,dt):
    # the model equations 
    eqns = { 
        'Ac' : '-k1*Rm*Ac',
        'Am' : 'k1*Rm(t-tau1)*Ac(t-tau1)*Heavi(t-tau1) - k2*Am*Rm + k2*AR - k2*Am*Bm + k3*AB',
        'Bc' : '-k4*Am*Bc',
        'Bm' : 'k4*Am(t-tau2)*Bc(t-tau2)*Heavi(t-tau2) - k2*Am*Bm + k3*AB',
        'Rm' : 'qR - k2*Am*Rm + k2*AR',
        'AB' : 'k2*Am*Bm - k3*AB',
        'AR' : 'k2*Am*Rm - k2*AR',
        }

    # define parameters
    params = {
        'k1' : const.k1,           
        'k2' : const.k2,
        'k3' : const.k3,
        'k4' : const.k4,
        'qR' : const.qR,
        'tau1' : const.tau1,
        'tau2' : const.tau2,
        }

    # initial conditions
    init_cond = {
        'Ac' : Ac_i,
        'Am' : Am_i,
        'Bc' : Bc_i,
        'Bm' : Bm_i,
        'Rm' : Rm_i,
        'AB' : AB_i,
        'AR' : AR_i,
        }
    
    # intialize the solver
    dde = dde23(eqns=eqns, params=params)

    # set the simulation parameters
    # (solve from t=0 to t=tf and limit the maximum step size to 1.0) 
    dde.set_sim_params(tfinal=tf, dtmax=1.0)

    # set the history of the proteins
    histfunc = {
        'Ac' : lambda t: init_cond['Ac'], 
        'Am' : lambda t: init_cond['Am'],
        'Bc' : lambda t: init_cond['Bc'],
        'Bm' : lambda t: init_cond['Bm'],
        'Rm' : lambda t: init_cond['Rm'],
        'AB' : lambda t: init_cond['AB'],
        'AR' : lambda t: init_cond['AR'],
        }
    
    dde.hist_from_funcs(histfunc,500)

    # run the simulator
    dde.run()

    # Get solution at every t=0.1
    sol1 = dde.sample(0,tf,0.1)

    # get the solutions from the history dict
#    t = dde.sol['t']
#    Ac= dde.sol['Ac']
#    Am= dde.sol['Am']
#    Bc = dde.sol['Bc']
#    Bm = dde.sol['Bm']
#    Rm = dde.sol['Rm']
#    AB = dde.sol['AB']
#    AR = dde.sol['AR']

    t = sol1['t']
    Ac= sol1['Ac']
    Am= sol1['Am']
    Bc = sol1['Bc']
    Bm = sol1['Bm']
    Rm = sol1['Rm']
    AB = sol1['AB']
    AR = sol1['AR']

    return(t,Ac,Am,Bc,Bm,Rm,AB,AR) 
Example #23
0
    def __init__(self, params = None, **kwargs):   
        if params == None:
            params = AttributeDict(kwargs)
        self.params = params
        
        #Calculate the equilibrium point
        def mu1(s, m, k):
            return (m*s)/(k + s)
        
        def mu2(s, m, k, k_I):
            return (m*s)/(k + s + (s/k_I)*(s/k_I))
        
        def eq_s1(s1, *args):
            (_k1, _k2, _k3, _s1_in, _s2_in, a, m1, _m2, k_s1, _k_s2, _k_I, D, tau1, _tau2) = args
            return a*D - np.exp(-a*D*tau1) * mu1(s1, m1, k_s1)
        
        def eq_s2(s2, *args):
            (_k1, _k2, _k3, _s1_in, _s2_in, a, _m1, m2, _k_s1, k_s2, k_I, D, _tau1, tau2) = args
            return a*D - np.exp(-a*D*tau2) * mu2(s2, m2, k_s2, k_I)
        
        eqs_args = (
            params.k1, params.k2, params.k3, 
            params.s1_in, params.s2_in, params.a, 
            params.m1, params.m2, 
            params.k_s1, params.k_s2, params.k_I, 
            params.D, params.tau1, params.tau2)
        
        s1_eqpnt = fsolve(eq_s1, 1.0, args = eqs_args)[0]
        x1_eqpnt = np.exp(-params.a*params.D*params.tau1) * (params.s1_in - s1_eqpnt)/(params.a*params.k1)
        if x1_eqpnt < 0:
            s1_eqpnt = params.s1_in
            x1_eqpnt = 0.0
        
        s2_eqpnt_sol, _info, ier, _msg  = fsolve(eq_s2, 1.0, args = eqs_args, full_output = True)
        if ier != 1 or s2_eqpnt_sol[0] < 0:
            x2_eqpnt = 0.0
            s2_eqpnt = params.s2_in + params.k2*mu1(s1_eqpnt, params.m1, params.k_s1) * x1_eqpnt / params.D
        else:
            s2_eqpnt = s2_eqpnt_sol[0]
            x2_eqpnt = ((params.s2_in - s2_eqpnt)*params.D + params.k2*mu1(s1_eqpnt, params.m1, params.k_s1)*x1_eqpnt) \
                / (params.k3 * mu2(s2_eqpnt, params.m2, params.k_s2, params.k_I))
            
        self.equilibriumPoint = [s1_eqpnt, x1_eqpnt, s2_eqpnt, x2_eqpnt]
        if plotEqulibriumValuesAtTheEnd:
            print "equilibrium point (s1, x1, s2, x2) = ", self.equilibriumPoint   
        
        # Define the specific growth rates (in 'C' source code)
        support_c_code = """
        double mu1(double s, double m, double k) {
            return (m*s)/(k + s);
        }
        
        double mu2(double s, double m, double k, double k_I) {
            return (m*s)/(k + s + (s/k_I)*(s/k_I));
        }
        """
        
        # Define the equations
        eqns = {
            's1': 'D*(s1_in - s1) - k1*mu1(s1, m1, k_s1)*x1',
            'x1': 'exp(-a*D*tau1)*mu1(s1(t-tau1), m1, k_s1)*x1(t-tau1) - a*D*x1',
            's2': 'D*(s2_in - s2) + k2*mu1(s1, m1, k_s1)*x1 - k3*mu2(s2, m2, k_s2, k_I)*x2',
            'x2': 'exp(-a*D*tau2)*mu2(s2(t-tau2), m2, k_s2, k_I)*x2(t-tau2) - a*D*x2'
        }
        
        # Define the parameters
        eqns_params = {
            'k1'    : params.k1,
            'k2'    : params.k2,
            'k3'    : params.k3,
            's1_in' : params.s1_in,
            's2_in' : params.s2_in,
            'a'     : params.a,
            'm1'    : params.m1,
            'm2'    : params.m2,
            'k_s1'  : params.k_s1,
            'k_s2'  : params.k_s2,
            'k_I'   : params.k_I,
            'D'     : params.D,
            'tau1'  : params.tau1,
            'tau2'  : params.tau2,
        }
        
        # Initialize the solver
        self.dde = dde23(eqns=eqns, params=eqns_params, supportcode=support_c_code)

        # Set the initial conditions (i.e. set the history of the state variables)
        histfunc = {
            's1': lambda t: params.s1_hist_vals,
            'x1': lambda t: params.x1_hist_vals,
            's2': lambda t: params.s2_hist_vals,
            'x2': lambda t: params.x2_hist_vals
            }
        self.dde.hist_from_funcs(histfunc, 10.) #:TRICKY: 10. is 'nn' - sample in the interval
Example #24
0
    d1 = {E_keys[i]: E_values}
    d2 = {I_keys[i]: I_values}
    histdic.update(d1)
    histdic.update(d2)

#build dictionaty of equations
d3 = dict(zip(E_keys, funcE(N, Cij, dij)))
d4 = dict(zip(I_keys, funcI(N)))
eqns = {}
eqns.update(d3)
eqns.update(d4)

print 'Computing ...'
start = timer()

dde = dde23(eqns)
dde.set_sim_params(dtmin=1.e-3,
                   AbsTol=9.e-5,
                   RelTol=0.001,
                   tfinal=t_final,
                   dtmax=0.1,
                   MaxIter=1000000,
                   dt0=0.001)
dde.hist_from_arrays(histdic)
dde.run()
sol = dde.sample(tstart=tc, tfinal=None, dt=dt1)
t = sol['t']
columns = int((t_final - tc) / dt1)
EE = np.zeros((N, columns))
for i in range(N):
    EE[i, :] = sol[E_keys[i]]