Example #1
0
def param_sensitivity_bars(list_pars, ODE, DSargs, var, fig_name=False, 
                           fs=[10,5], delta=[0.0, 0.1, -0.1]):
    change = {}
    for pars in list_pars:
        if DSargs.pars[pars] != 0:
            a = []
            for d in delta:
                ODE.set(pars = {pars: (1.0 + d)*DSargs.pars[pars]} ) 
                a += [eliminate_redundants(pp.find_fixedpoints(ODE, n=2, 
                                           maxsearch=1e+4, eps=1e-12),
                                           6)[0][var]]
            change[pars] = [100*(a[2] - a[0])/a[0],100*(a[1] - a[0])/a[0]] 
        else:
            change[pars] = [0,0] 
    l = change.keys()
    isort = np.argsort([np.abs(change[i][0])+
                        np.abs(change[i][1]) for i in l])[::-1]

    figure(figsize=(fs[0],fs[1]), dpi=200)
    plt.bar(range(len(change.keys())), [change[l[i]][0] for i in isort], 
            color='r', align='center', alpha=0.8)
    plt.bar(range(len(change.keys())), [change[l[i]][1] for i in isort], 
            color='b', align='center', alpha=0.8)
    plt.xticks(np.arange(len(list_pars)+1), [l[i] for i in isort])
    plt.xlim([-1,len(list_pars)])
    plt.ylabel('Change in the signal (%)', fontsize= 18)
    plt.legend( ('- 10%', '+10%'), loc='upper right')
    if fig_name:
        plt.savefig(fig_name, format='pdf', dpi=200) 
    plt.show()
def plot_PhaseDiagram(ODE, nmodel, names, freepar, vfreepar, par, rpar, xlim, ylim, figname, keys=['N','D','J','I'],
		      saveeigen=False, maxstep=5e-1, minstep=1e-2, step=1e-1, silence=False, LimitPoints='LP', showBif=True):
    if silence:
        class NullDevice():
            def write(self, s):
                pass
        original_stdout = sys.stdout
        sys.stdout = NullDevice()

    x  = []
    for i in rpar:
        ODE.set(pars = {freepar: vfreepar, par: i} )
        fp = eliminate_redundants(pp.find_fixedpoints(ODE, n=2, maxsearch=1e+3, eps=1e-10),6)
        ODE.set(ics  = fp[0]) 
        PCargs = PyCont_args(nmodel, freepar, 10000, saveeigen=saveeigen, maxstep=maxstep, minstep=minstep, step=step)
        p = plot_continuation(ODE, PCargs, nmodel,keys, freepar, names, FPs=[fp[0]], showcurve=showBif,
			      off_points=True, fontsize=20, xlim=xlim, LimitPoints=LimitPoints)
        for j in range(len(p)):
            x += [[i,p[j],j]]

    figure(figsize=(6,5), dpi=500)
    plt.xlabel(freepar, fontsize= 18)
    plt.ylabel(par, fontsize= 18)

    plt.xlim(xlim)
    plt.ylim(ylim)

    x = asarray(x)
    color = ['k', 'r', 'r', 'b']
    for i in range(int(max(x[:,2]))+1):
        plot(x[x[:,2]==i][:,1],x[x[:,2]==i][:,0], color=color[i])
    plt.savefig(figname, format='pdf', dpi=500)
    if silence:
        sys.stdout = original_stdout
#-------------------------------------------------------------------------------------------------------------------#
Example #3
0
def getNullClines(DSargs, ode):
    from PyDSTool.Toolbox import phaseplane as pp
    vlim = {'X': [1, 700], 'Y': [1, 700]}
    fp = aux.eliminate_redundants(
        pp.find_fixedpoints(ode, n=2, maxsearch=1e+4, eps=1e-12), 4)
    stab = aux.stability(fp, ode)

    for i in range(len(fp)):
        print(stab[i], fp[i])
    nfp = 0
    aux.nullclines(['X', 'Y'],
                   DSargs,
                   stab,
                   fp,
                   nfp=nfp,
                   vlim=vlim,
                   maxpoints=[800, 800],
                   xticks=[0, 100, 200, 300, 400, 500, 600, 700],
                   yticks=[0, 100, 200, 300, 400, 500, 600, 700],
                   step=0.01,
                   minstep=0.001,
                   maxstep=10,
                   fs=[3, 3],
                   fontsize=8,
                   silence=False)
def param_sensitivity_bars(list_pars, ODE, DSargs, var, save_fig=False, fs=[10,5], delta=[0.0, 0.1, -0.1]):
### Plot the changes in one variable as changes of the values of the paramters
    change = {}
    for pars in list_pars:
        if DSargs.pars[pars] != 0:
            a = []
            for d in delta:
                ODE.set(pars = {pars: (1.0 + d)*DSargs.pars[pars]} ) 
                a += [eliminate_redundants(pp.find_fixedpoints(ODE, n=4, maxsearch=1e+4, eps=1e-12),6)[0][var]]
            change[pars] = [100*(a[2] - a[0])/a[0],100*(a[1] - a[0])/a[0]] 
        else:
            change[pars] = [0,0] 
    l = change.keys()
    isort = np.argsort([np.abs(change[i][0])+np.abs(change[i][1]) for i in l])[::-1]

    figure(figsize=(fs[0],fs[1]), dpi=500)
    plt.bar(range(len(change.keys())), [change[l[i]][0] for i in isort], color='r', align='center', alpha=0.8)
    plt.bar(range(len(change.keys())), [change[l[i]][1] for i in isort], color='b', align='center', alpha=0.8)
    plt.xticks(np.arange(len(list_pars)+1), [l[i] for i in isort])
    plt.xlim([-1,len(list_pars)])
    plt.ylabel('Change in the signal (%)', fontsize= 18)
    plt.legend( ('- 10%', '+10%'), loc='upper right')
    if save_fig:
        plt.savefig(save_fig, format='pdf', dpi=900) 
    plt.show()
def param_sensitivity_bifurcations(DSargs, pars, freepar, var, nmodel, delta=[0.0, 0.1, -0.1], c=['k', 'b', 'r'], 
                                   ylim=None, save_fig=None, maxstep=1e+1, minstep=1e-3, step=5e+0):
### plot bifurcation curves for changes in 10% in the parameters 
    figure(figsize=(6*len(pars),5), dpi=500)
    for i in range(len(pars)):
        ODE = Vode_ODEsystem(DSargs)
        for j in range(len(delta)):
            ODE.set(pars = {pars[i]: (1.0 + delta[j])*DSargs.pars[pars[i]]} ) 
            fp_coord = eliminate_redundants(pp.find_fixedpoints(ODE, n=4, maxsearch=1e+4, eps=1e-10),6)
            ODE.set(ics  = fp_coord[0])  
            PCargs = PyCont_args(nmodel, freepar, 200, saveeigen=True, maxstep=maxstep, minstep=minstep, step=step)
            PyCont = PyDSTool.ContClass(ODE)     
            PyCont.newCurve(PCargs)
            PyCont[nmodel].forward()
            PyCont[nmodel].backward()
            PyCont.display((freepar,var), stability=True, axes=(1,len(pars),i+1), color=c[j], linewidth=3)
            plt.plot(0,0, linewidth=3, color=c[j])
            PyCont.plot.toggleLabels('off')
        plt.title(pars[i])
        if i == 0:
            plt.legend(('0%','+10%','- 10%'))
        if ylim != None:
            plt.ylim(ylim)
    if save_fig:
        plt.savefig(save_fig, format='pdf', dpi=900) 
Example #6
0
def plot_phasediagram(ODE, freepar, v, r_v, bif_startpoint, keys=False, 
                      xlim=False, ylim=False, xticks=False, yticks=False, 
		      show_continuation=False, maxstep=1e+2, minstep=1e-2, 
                      step=5e+1, maxpoints=500, nrow=None, ncol=None,
		      LocBifPoints=['LP','B'], BifPoints=['LP'], silence=False,
                      fig_name=False, fast_fp=False, returnLPs=False):
    if silence:
        class NullDevice():
            def write(self, s):
                pass
        original_stdout = sys.stdout
        sys.stdout = NullDevice()
    if keys==False:
        keys = ODE.variables.keys()
        
    x = []
    for i in r_v:
        ODE.set(pars = {v: i, freepar: bif_startpoint})
        if fast_fp:
            fp = fast_fixedpoint(ODE)
        else:
            fp = eliminate_redundants(pp.find_fixedpoints(ODE, n=2, 
                                      maxsearch=1e+4, eps=1e-12),
                                      4)[0]
        ODE.set(ics  = fp)        
        PCargs = PyCont_args(ODE.name, freepar, maxpoints, saveeigen=True, 
                             maxstep=maxstep, minstep=minstep, step=step, 
                             LocBifPoints=LocBifPoints) 
        lp = plot_continuation(ODE, freepar, keys, bif_startpoint, 
                               PCargs=PCargs, returnLP=BifPoints, 
                               showcurve=show_continuation, ics=[fp],
			       fs=[4,3], fontsize=12,nrow=nrow, ncol=ncol)
        x += [lp]
        plt.show()
    if silence:
        sys.stdout = original_stdout

    figure(figsize=(6,5), dpi=200)
    x = np.asarray(x)
    for i in range(shape(x)[1]):
        plot(x[:,i], r_v, color='k')
    
    plt.xlabel(freepar, fontsize= 18)
    plt.ylabel(v, fontsize= 18)
    if xlim:
        plt.xlim(xlim)
    if xticks:
        plt.xticks(xticks)
    if ylim:
        plt.ylim(ylim)
    if yticks:
        plt.yticks(yticks)
    if fig_name:
        plt.savefig(fig_name, format='pdf', dpi=200)
    plt.show()
    if returnLPs:
        return x
Example #7
0
def param_sensitivity_bifurcations(DSargs, freepar, key, list_pars, 
                                   bif_startpoint, d=[0.0, 0.1, -0.1], 
                                   c=['k', 'b', 'r'], ylim=False, xlim=False, 
                                   xticks=False, yticks=False, fig_name=False, 
                                   ncol=False, nrow=False, maxstep=1e+2, 
                                   minstep=1e-2, step=5e+1, silence=False):
    if silence:
        class NullDevice():
            def write(self, s):
                pass
        original_stdout = sys.stdout
        sys.stdout = NullDevice()
    if ncol==False:
        nrow=1
        ncol=len(list_pars)
    else:
        plt.figure(figsize=(6*ncol,5*nrow), dpi=200)
    for i in range(len(list_pars)):
        ODE = Vode_ODEsystem(DSargs)
        for j in range(len(d)):
            ODE.set(pars={list_pars[i]:(1.0 + d[j])*DSargs.pars[list_pars[i]]}) 
            fp_coord = eliminate_redundants(pp.find_fixedpoints(ODE, n=2, 
                                                                maxsearch=1e+4,                                                                 eps=1e-10),
                                                                6)
            ODE.set(ics  = fp_coord[0])  
            PCargs = PyCont_args('psensit', freepar, 200, saveeigen=True, 
                                  maxstep=maxstep, minstep=minstep, step=step,
				  LocBifPoints=['B','LP'])
            PyCont = PyDSTool.ContClass(ODE)     
            PyCont.newCurve(PCargs)
            PyCont['psensit'].forward()
            PyCont['psensit'].backward()
            
            PyCont.display((freepar,key), stability=True, axes=(nrow,ncol,i+1),
                            color=c[j], linewidth=3)
            plot(0, 0, linewidth=3, color=c[j])
            PyCont.plot.toggleLabels('off')
        plt.title(list_pars[i])
        if i == 0:
            plt.legend(('0%','+10%','- 10%'))
        if ylim:
            plt.ylim(ylim)
        if ylim:
            plt.ylim(ylim)
        if xticks:
            plt.xticks(xticks)
        if yticks:
            plt.yticks(yticks)
    if fig_name:
        plt.savefig(fig_name, format='pdf', dpi=200) 
    if silence:
        sys.stdout = original_stdout
Example #8
0
def plot_continuation_twocells(ODE, freepar, keys, bif_startpoint, LocBifPoints=['LP','BP','B'], xlim=False, ylim=False,
			       maxpoints=500, fig_name=False, saveeigen=True, maxstep=1e-0, minstep=1e-2, step=5e-2, silence=False):
	if silence:
		class NullDevice():
			def write(self, s):
				pass
		original_stdout = sys.stdout
		sys.stdout = NullDevice()
	fp = eliminate_redundants(pp.find_fixedpoints(ODE, n=2, maxsearch=1e+4, eps=1e-10),6)
	p = plot_continuation(ODE, freepar, keys, bif_startpoint, ics=[fp[0]], maxstep=maxstep, minstep=minstep,step=step, off_points=True,  LocBifPoints=LocBifPoints, returnLP='BP')
	figure(figsize=(6*len(keys),5))
	l = sorted(p + ODE.pdomain[freepar])
	for i in range(len(p)):
		plt.axvline(x=p[i],color='k')

	for i in range(len(l)-1):
		ODE.set(pars = {freepar: (l[i] + l[i+1])/2} )
		fp = eliminate_redundants(pp.find_fixedpoints(ODE, n=2, maxsearch=1e+4, eps=1e-10),6)
		print(len(fp), fp)
		PCargs = PyCont_args(ODE.name, freepar, maxpoints, stopAt=['B','BP'], maxstep=maxstep, minstep=minstep, step=minstep)
		for j in range(len(fp)):
			ODE.set(ics  = fp[j])
			PyCont = PyDSTool.ContClass(ODE)
			PyCont.newCurve(PCargs)
			PyCont[ODE.name].forward()
			PyCont[ODE.name].backward()
			for k in range(len(keys)):
				PyCont.display((freepar,keys[k]), axes=(1,len(keys),k+1), stability=True, linewidth=2)
				PyCont.plot.toggleLabels('off')
				plt.title('')
				plt.xlim(xlim)
				if ylim:
					plt.ylim(ylim)
	plt.tight_layout()
	if fig_name:
		plt.savefig(fig_name, format='pdf', dpi=200)
	if silence:
		sys.stdout = original_stdout
def plot_continuation_twocells(ODE, freepar, keys, bif_startpoint, LocBifPoints=['LP','BP','B'], xlim=False, ylim=False, 
			       maxpoints=500, fig_name=False, saveeigen=True, maxstep=1e-0, minstep=1e-2, step=5e-2, silence=False):
    if silence:
        class NullDevice():
            def write(self, s):
                pass
        original_stdout = sys.stdout
        sys.stdout = NullDevice()
    fp = eliminate_redundants(pp.find_fixedpoints(ODE, n=2, maxsearch=1e+4, eps=1e-10),6)
    p = plot_continuation(ODE, freepar, keys, bif_startpoint, ics=[fp[0]], maxstep=maxstep, minstep=minstep, 
                          step=step, off_points=True,  LocBifPoints=LocBifPoints, returnLP='BP')
    figure(figsize=(6*len(keys),5))
    l = sorted(p + ODE.pdomain[freepar])
    for i in range(len(p)):
        plt.axvline(x=p[i],color='k')
    
    for i in range(len(l)-1):
        ODE.set(pars = {freepar: (l[i] + l[i+1])/2} )
        fp = eliminate_redundants(pp.find_fixedpoints(ODE, n=2, maxsearch=1e+4, eps=1e-10),6)
        print(len(fp), fp)
        PCargs = PyCont_args(ODE.name, freepar, maxpoints, stopAt=['B','BP'], maxstep=maxstep, minstep=minstep, step=minstep)
        for j in range(len(fp)):
            ODE.set(ics  = fp[j])
            PyCont = PyDSTool.ContClass(ODE)     
            PyCont.newCurve(PCargs)
            PyCont[ODE.name].forward()
            PyCont[ODE.name].backward()
            for k in range(len(keys)):
                PyCont.display((freepar,keys[k]), axes=(1,len(keys),k+1), stability=True, linewidth=2)
                PyCont.plot.toggleLabels('off')
                plt.title('')
                plt.xlim(xlim)
                if ylim:
                    plt.ylim(ylim)
    if fig_name:
        plt.savefig(fig_name, format='pdf', dpi=200)
    if silence:
        sys.stdout = original_stdout
def plot_phasediagram(ODE, freepar, v, r_v, bif_startpoint, keys=False, xlim=False, ylim=False, xticks=False, yticks=False, 
		      show_continuation=False, maxstep=1e+2, minstep=1e-2, step=5e+1, maxpoints=500, nrow=None, ncol=None,
		      LocBifPoints=['LP','B'], BifPoints=['LP'], silence=False, fig_name=False, fast_fp=False, returnLPs=False):
    if silence:
        class NullDevice():
            def write(self, s):
                pass
        original_stdout = sys.stdout
        sys.stdout = NullDevice()
    if keys==False:
        keys = ODE.variables.keys()
        
    x = []
    for i in r_v:
        ODE.set(pars = {v: i, freepar: bif_startpoint})
        if fast_fp:
	    fp = fast_fixedpoint(ODE)
	else:
	    fp = eliminate_redundants(pp.find_fixedpoints(ODE, n=2, maxsearch=1e+4, eps=1e-12),4)[0]
        ODE.set(ics  = fp)        
        PCargs = PyCont_args(ODE.name, freepar, maxpoints, saveeigen=True, maxstep=maxstep, minstep=minstep, step=step, LocBifPoints=LocBifPoints) 
        lp = plot_continuation(ODE, freepar, keys, bif_startpoint, PCargs=PCargs, returnLP=BifPoints, showcurve=show_continuation, ics=[fp],
			       fs=[4,3], fontsize=12,nrow=nrow, ncol=ncol)
	x += [lp]
        plt.show()
    if silence:
        sys.stdout = original_stdout

    figure(figsize=(6,5), dpi=200)
    x = np.asarray(x)
    for i in range(shape(x)[1]):
        plot(x[:,i], r_v, color='k')
    
    plt.xlabel(freepar, fontsize= 18)
    plt.ylabel(v, fontsize= 18)
    if xlim:
        plt.xlim(xlim)
    if xticks:
        plt.xticks(xticks)
    if ylim:
        plt.ylim(ylim)
    if yticks:
        plt.yticks(yticks)
    if fig_name:
        plt.savefig(fig_name, format='pdf', dpi=200)
    plt.show()
    if returnLPs:
	return x
def param_sensitivity_bifurcations(DSargs, freepar, key, list_pars, bif_startpoint, d=[0.0, 0.1, -0.1], c=['k', 'b', 'r'], 
                                   ylim=False, xlim=False, xticks=False, yticks=False, fig_name=False, ncol=False, 
                                   nrow=False, maxstep=1e+2, minstep=1e-2, step=5e+1, silence=False):
    if silence:
        class NullDevice():
            def write(self, s):
                pass
        original_stdout = sys.stdout
        sys.stdout = NullDevice()
    if ncol==False:
        nrow=1
        ncol=len(list_pars)
    else:
        plt.figure(figsize=(6*ncol,5*nrow), dpi=200)
    for i in range(len(list_pars)):
        ODE = Vode_ODEsystem(DSargs)
        for j in range(len(d)):
            ODE.set(pars = {list_pars[i]: (1.0 + d[j])*DSargs.pars[list_pars[i]]} ) 
            fp_coord = eliminate_redundants(pp.find_fixedpoints(ODE, n=2, maxsearch=1e+4, eps=1e-10),6)
            ODE.set(ics  = fp_coord[0])  
            PCargs = PyCont_args('psensit', freepar, 200, saveeigen=True, maxstep=maxstep, minstep=minstep, step=step,
				 LocBifPoints=['B','LP'])
            PyCont = PyDSTool.ContClass(ODE)     
            PyCont.newCurve(PCargs)
            PyCont['psensit'].forward()
            PyCont['psensit'].backward()
            
            PyCont.display((freepar,key), stability=True, axes=(nrow,ncol,i+1), color=c[j], linewidth=3)
            plot(0, 0, linewidth=3, color=c[j])
            PyCont.plot.toggleLabels('off')
        plt.title(list_pars[i])
        if i == 0:
            plt.legend(('0%','+10%','- 10%'))
        if ylim:
            plt.ylim(ylim)
        if ylim:
            plt.ylim(ylim)
        if xticks:
            plt.xticks(xticks)
        if yticks:
            plt.yticks(yticks)
    if fig_name:
        plt.savefig(fig_name, format='pdf', dpi=200) 
    if silence:
        sys.stdout = original_stdout
Example #12
0
    def __init__(self, ode):
        """
        Saves ODE as self.ode
        Sets fixed points as self.fixed_points
        Verifies if the parameters are in the resonance region

        Parameters
        ----------
        ode : PyDSTool.Generator.Vode_ODEsystem.Vode_ODEsystem
            DESCRIPTION. BMK type ODE
        """
        
        
        self.ode = ode
        self.fixed_points = pp.find_fixedpoints(self.ode, n=10, eps=1e-5)
        self.in_resonance_region = True
        if len(self.fixed_points) != 2:
            print("Not in resonance region")
            self.in_resonance_region = False
Example #13
0
							's2': 0.06}

# set the range of integration
DSargs.tdomain = [0,30]

# variable domain for the phase plane analysis
DSargs.xdomain = {'s1': [0,1], 's2': [0,1]}

# create model object
dmModel = dst.Vode_ODEsystem(DSargs)

# plot vector field
pp.plot_PP_vf(dmModel, 's1', 's2', scale_exp=-1.5)

# find dixed points of the model
fp_coord = pp.find_fixedpoints(dmModel, n=4, eps=1e-8)

# plot the null-clines
nulls_x, nulls_y = pp.find_nullclines(dmModel, 's1', 's2', n=3, \
										eps=1e-8, max_step=0.01, fps=fp_coord)

plot(nulls_x[:,0], nulls_x[:,1], 'b')
plot(nulls_y[:,0], nulls_y[:,1], 'g')

# compute the jacobian matrix
jac, new_fnspecs = dst.prepJacobian(dmModel.funcspec._initargs['varspecs'],
			['s1','s2'],dmModel.funcspec._initargs['fnspecs'])
scope = dst.copy(dmModel.pars)
scope.update(new_fnspecs)
jac_fn = dst.expr2fun(jac, ensure_args=['t'],**scope)
    # let solution settle
    transient = fhn.compute('trans')
    fhn.set(ics=transient(10),
            tdata=[0,20])

    # More of your code here


# Your code here for the frequency plot



1/0  # comment this to apply phase plane picture to whatever
# are the current parameters of FHN model

## Optional code

fp_coord = pp.find_fixedpoints(fhn, n=25, eps=1e-6)[0]
fp = pp.fixedpoint_2D(fhn, Point(fp_coord), eps=1e-6)

nulls_x, nulls_y = pp.find_nullclines(fhn, 'x', 'y', n=3, eps=1e-6,
                                      max_step=0.1, fps=[fp_coord])
plt.figure(3)
pp.plot_PP_fps(fp)
plt.plot(nulls_x[:,0], nulls_x[:,1], 'b')
plt.plot(nulls_y[:,0], nulls_y[:,1], 'g')

plt.show()


# -----------------------------------

ode_sys = build_sys()

plt.figure(1)

# phase plane tools are in the Toolbox module aliased as 'pp'

# plot vector field, using a scale exponent to ensure arrows are well spaced
# and sized
plot_PP_vf_custom(ode_sys, 'phi', 'nu', scale_exp=-0.25)

# find fixed points
fp_coords = pp.find_fixedpoints(ode_sys, eps=1e-6)

# n=3 uses three starting points in the domain to find nullcline parts, to an
# accuracy of eps=1e-8, and a maximum step for the solver of 0.1 units.
# The fixed points found is also provided to help locate the nullclines.
nulls_x, nulls_y = pp.find_nullclines(ode_sys,
                                      'phi',
                                      'nu',
                                      n=3,
                                      eps=1e-6,
                                      max_step=0.1,
                                      fps=fp_coords)

# plot the fixed points
fps = []
for fp_coord in fp_coords:
Example #16
0
plt.plot(pts['t'], pts['x'], 'b', linewidth=2)
plt.plot(pts['t'], pts['y'], 'r', linewidth=2)

# figure 2 is the phase plane
plt.figure(2)
# phase plane tools are in the Toolbox module
from PyDSTool.Toolbox import phaseplane as pp

# plot vector field, using a scale exponent to ensure arrows are well spaced
# and sized
pp.plot_PP_vf(vdp, 'x', 'y', scale_exp=-1)

# only one fixed point, hence [0] at end.
# n=4 uses three starting points in the domain to find any fixed points, to an
# accuracy of eps=1e-8.
fp_coord = pp.find_fixedpoints(vdp, n=4, eps=1e-8)[0]
fp = pp.fixedpoint_2D(vdp, dst.Point(fp_coord), eps=1e-8)

# n=3 uses three starting points in the domain to find nullcline parts, to an
# accuracy of eps=1e-8, and a maximum step for the solver of 0.1 units.
# The fixed point found is also provided to help locate the nullclines.
nulls_x, nulls_y = pp.find_nullclines(vdp, 'x', 'y', n=3, eps=1e-8,
                                      max_step=0.1, fps=[fp_coord])


# plot the fixed point
pp.plot_PP_fps(fp)

# plot the nullclines
plt.plot(nulls_x[:,0], nulls_x[:,1], 'b')
plt.plot(nulls_y[:,0], nulls_y[:,1], 'g')
Example #17
0
def plot_continuation(ODE, freepar, keys, bif_startpoint, 
                      LocBifPoints=['LP','B'], PCargs=None, returnLP=None, 
                      ics=None, xlim=None, ylim=None, xticks=False, 
                      yticks=False, maxstep=1e+2, minstep=1e-2, step=5e+1, 
                      maxpoints=500, off_points=True, nrow=None, ncol=None, 
                      showcurve=True, n_form_coef=False, silence=False, 
		      fs=[6,5], fontsize=18, fig_name=False):

    plt.rcParams.update({'font.size': fontsize})
    ODE.set(pars = {freepar: bif_startpoint})

    if silence:
        class NullDevice():
            def write(self, s):
                pass
        original_stdout = sys.stdout
        sys.stdout = NullDevice()

    if showcurve:
        if ncol == None:
            ncol = len(keys)
        if nrow == None:
            nrow = 1
        plt.figure(figsize=(fs[0]*ncol,fs[1]*nrow), dpi=200)
    if ics==None:
        ics = [eliminate_redundants(pp.find_fixedpoints(ODE, n=2, 
                                    maxsearch=1e+4, eps=1e-12), 4)[0]]
    if PCargs==None:
        PCargs = PyCont_args(ODE.name, freepar, maxpoints, saveeigen=True, 
                             LocBifPoints=LocBifPoints, maxstep=maxstep, 
                             minstep=minstep, step=step) 
 
    for j in range(len(ics)):
        ODE.set(ics  = ics[j])
        PyCont = PyDSTool.ContClass(ODE)     
        PyCont.newCurve(PCargs)
        PyCont[ODE.name].forward()
        PyCont[ODE.name].backward()
        if showcurve:        
            for i in range(len(keys)):
                PyCont.display((freepar,keys[i]), stability=True, 
                               axes=(nrow,ncol,i+1), color='k', linewidth=3)
                if off_points:
                    PyCont.plot.toggleLabels('off')
                plt.xlabel(freepar, fontsize=12)
                plt.ylabel(keys[i], fontsize=12)
                plt.title('')
                if xlim != None:
                    plt.xlim([xlim[0],xlim[1]])
                if ylim != None:
                    plt.ylim([ylim[0],ylim[1]])
                if xticks:
                    plt.xticks(xticks)
                if yticks:
                    plt.yticks(yticks)
    if n_form_coef:
        i = 1
        while PyCont[ODE.name].getSpecialPoint('LP'+str(i)):
            tmpStr = 'LP'+str(i)
            print(tmpStr, 
                  PyCont[ODE.name].getSpecialPoint(tmpStr).labels['LP']['data'])
            i += 1
    if fig_name:
        plt.savefig(fig_name, format='pdf', dpi=200)
    if silence:
        sys.stdout = original_stdout

    if returnLP!=None:
        P = []
        for k in returnLP:
            i=1
            while PyCont[ODE.name].getSpecialPoint(k+str(i)):
                P += [PyCont[ODE.name].getSpecialPoint(k+str(i))[freepar]]
                i +=1
        return P
    plt.show()
Example #18
0
# phase plane tools are in the Toolbox module aliased as 'pp'

# plot vector field, using a scale exponent to ensure arrows are well spaced
# and sized
if all_plots:
    plot_PP_vf_custom(ode_sys, 'vf_data', scale_exp=-0.25)

plotter.arrangeFig([1,1], {'11': {'name': 'PP',
                                  'scale': DOI,
                                  'layers': ['fp_data', 'manifold_data', 'manifold_metadata'],
                                  'axes_vars': ['phi', 'nu']}
                           })

# find fixed points
fp_coords = pp.find_fixedpoints(ode_sys, eps=1e-6)

# n=3 uses three starting points in the domain to find nullcline parts, to an
# accuracy of eps=1e-8, and a maximum step for the solver of 0.1 units.
# The fixed points found is also provided to help locate the nullclines.
if all_plots:
    nulls_x, nulls_y = pp.find_nullclines(ode_sys, 'phi', 'nu', n=3,
                                      eps=1e-6, max_step=0.1, fps=fp_coords)

# plot the nullclines
if all_plots:
    plt.plot(nulls_x[:,0], nulls_x[:,1], 'b')
    plt.plot(nulls_y[:,0], nulls_y[:,1], 'g')

# plot the fixed points
fps = []
Example #19
0
                                    [ -1,  0 ]]""")
}
DSargs.ics = icdict
vdp = Dopri_ODEsystem(DSargs)  # Vode_ODEsystem
vdp_e = Euler_ODEsystem(DSargs)

traj = vdp.compute('v')
pts = traj.sample()

traj_e = vdp_e.compute('e')
pts_e = traj_e.sample()

plt.plot(pts['x'], pts['y'], 'k.-', linewidth=2)
plt.plot(pts_e['x'], pts_e['y'], 'r.-', linewidth=2)

fp_coord = pp.find_fixedpoints(vdp, n=4, eps=1e-8)[0]
fp = pp.fixedpoint_2D(vdp, Point(fp_coord), eps=1e-8)

nulls_x, nulls_y = pp.find_nullclines(vdp,
                                      'x',
                                      'y',
                                      n=3,
                                      eps=1e-8,
                                      max_step=0.1,
                                      fps=[fp_coord])
pp.plot_PP_fps(fp)
plt.plot(nulls_x[:, 0], nulls_x[:, 1], 'b')
plt.plot(nulls_y[:, 0], nulls_y[:, 1], 'g')

plt.show()
Example #20
0
def SPoCK_find_fixedpoints():
    pardict, fndict, vardict, icsdict = init_SPoCK()

    DSargs = dst.args()
    DSargs.pars = pardict
    DSargs.varspecs = vardict
    DSargs.fnspecs = fndict
    DSargs.ics = icsdict

    DSargs.name = 'SPoCK'
    DSargs.tdata = [0, 50000]
    DSargs.xdomain = {
        'X': [0, 10**9],
        'Y': [0, 10**9],
        'A': [0, 10**9],
        'B': [0, 10**9],
    }

    spock_ode = dst.Vode_ODEsystem(DSargs)
    jac_fun = make_jac_pydstool(spock_ode)

    fp_coords = pp.find_fixedpoints(spock_ode,
                                    n=10,
                                    eps=1e-50,
                                    jac=jac_fun,
                                    subdomain={
                                        'X': [0, 10**9],
                                        'Y': [0, 10**9],
                                        'A': [0, 10**9],
                                        'B': [0, 10**9]
                                    })
    fixedpoints_pdf_path = "/Users/behzakarkaria/Documents/UCL/Barnes Lab/PhD Project/research_code/SPoCK_model/parameter_csv/"

    plt.figure(1)
    fig, ax = plt.subplots(figsize=(18, 12.5))
    ax.set_xscale('symlog', basex=10)
    ax.set_yscale('symlog', basey=10)
    ax.set_ylim(0, 10**9)
    ax.set_xlim(0, 10**9)
    good_coords = []
    for fp in fp_coords:
        try:
            fp_obj = pp.fixedpoint_nD(
                spock_ode, dst.Point(fp), coords=fp, jac=jac_fun, eps=1e-20
            )  #Does he tolerance here matter when we find the points above with a good tolerance?
            good_coords.append(fp)
        except:
            continue

        if fp_obj.stability == 'u':
            style = 'wo'
        elif fp_obj.stability == 'c':
            style = 'co'
        else:  # 's'
            style = 'ko'

        print("")
        print(fp_obj.stability)
        print('X:', fp_obj.fp_coords['X'])
        print('Y:', fp_obj.fp_coords['Y'])
        print("")

        try:
            ax.plot(fp_obj.fp_coords['X'], fp_obj.fp_coords['Y'], style)

        except ValueError:
            continue

    plt.xlabel("X")
    plt.ylabel("Y")
    #plt.title('Fixed points \n w = 1*10**-2, D = 0.2 ')

    pdf_page_obj = PdfPages(fixedpoints_pdf_path + "fixedpoints_XY" + ".pdf")
    pdf_page_obj.savefig(ax.get_figure())
    pdf_page_obj.close()

    fixedpoints_csv_path = "/Users/behzakarkaria/Documents/UCL/Barnes Lab/PhD Project/research_code/SPoCK_model/parameter_csv/fixedponts.csv"
    fieldnames = ('index', 'X', 'Y', 'A', 'B')

    index = 0
    for fp_dict in good_coords:
        fp_dict['index'] = index
        index = index + 1

    data_frame = pd.DataFrame.from_records(good_coords)
    data_frame.to_csv(fixedpoints_csv_path)
def plot_continuation(ODE, freepar, keys, bif_startpoint, LocBifPoints=['LP','B'], PCargs=None, returnLP=None, ics=None, 
		      xlim=None, ylim=None, xticks=False, yticks=False, maxstep=1e+2, minstep=1e-2, step=5e+1, maxpoints=500, 
		      off_points=True, nrow=None, ncol=None, showcurve=True, n_form_coef=False, silence=False, 
		      fs=[6,5], fontsize=18, fig_name=False):
    plt.rcParams.update({'font.size': fontsize}) 
    ODE.set(pars = {freepar: bif_startpoint})

    if silence:
        class NullDevice():
            def write(self, s):
                pass
        original_stdout = sys.stdout
        sys.stdout = NullDevice()
    if showcurve:
        if ncol == None:
            ncol = len(keys)
        if nrow == None:
            nrow = 1
        plt.figure(figsize=(fs[0]*ncol,fs[1]*nrow), dpi=200)
    if ics==None:
        ics = [eliminate_redundants(pp.find_fixedpoints(ODE, n=2, maxsearch=1e+4, eps=1e-12), 4)[0]]
    if PCargs==None:
        PCargs = PyCont_args(ODE.name, freepar, maxpoints, saveeigen=True, LocBifPoints=LocBifPoints, 
			     maxstep=maxstep, minstep=minstep, step=step) 
 
    for j in range(len(ics)):
        ODE.set(ics  = ics[j])
        PyCont = PyDSTool.ContClass(ODE)     
        PyCont.newCurve(PCargs)
        PyCont[ODE.name].forward()
        PyCont[ODE.name].backward()
        if showcurve:        
            for i in range(len(keys)):
                PyCont.display((freepar,keys[i]), stability=True, axes=(nrow,ncol,i+1), color='k', linewidth=3)
                if off_points:
                    PyCont.plot.toggleLabels('off')
                plt.xlabel(freepar, fontsize=18)
                plt.ylabel(keys[i], fontsize=18)
                plt.title('')
                if xlim != None:
                    plt.xlim([xlim[0],xlim[1]])
                if ylim != None:
                    plt.ylim([ylim[0],ylim[1]])
                if xticks:
                    plt.xticks(xticks)
                if yticks:
                    plt.yticks(yticks)
    if n_form_coef:
        i = 1
        while PyCont[ODE.name].getSpecialPoint('LP'+str(i)):
            print("LP"+str(i), PyCont[ODE.name].getSpecialPoint('LP'+str(i)).labels['LP']['data'])
            i += 1
    if fig_name:
        plt.savefig(fig_name, format='pdf', dpi=200)
    if silence:
        sys.stdout = original_stdout
    if returnLP!=None:
        P = []
        for k in returnLP:
            i=1
            while PyCont[ODE.name].getSpecialPoint(k+str(i)):
                P += [PyCont[ODE.name].getSpecialPoint(k+str(i))[freepar]]
                i +=1
        return P
    plt.show()
Example #22
0
def computePPlaneObjects(gen, xvar, yvar, state=None, tol=1e-8,
              x_scale=1, max_step=1, subdomain=None, seed_pts=None,
              only_var=None, do_fps=True, num_x_points=100, num_y_points=100,
              strict_domains=True, with_jac=True, fast_vars=None, verbose=0,
              as_array=True):
    """
    THIS VERSION IS HARDWIRED FOR USE WITH HODGKIN-HUXLEY MODELS.

    Compute basic phase plane objects (fixed points and nullclines)
    given certain parameters (system params will come from generator):

    gen         Generator object from which to build nullcline from
    xvar        Variable to be treated as independent
    yvar        Variable to be treated as dependent
    fast_vars   Any fast variables set to their adiabatic equilibrium values
    state       Point or dictionary of state values
    tol         Tolerance scalar
    max_step    Maximum step in arc-length that nullcline computation
                will use
    subdomain   Optional sub-domain of calculation (default to whole
                variable domains given by Generator) given as dictionary
                with [xlo, xhi] values for each x string key.
    seed_pts    Seed points (list of dictionaries or Points)
                for any known nullcline points on either/both nullclines.
    only_var    Select one variable to compute nullclines for only.
    do_fps      Boolean switch (default True) to control computation of
                fixed points.
    num_x_points    number of mesh points for x nullcline (default 100)
    num_y_points    number of mesh points for y nullcline (default 100)
    strict_domains  Boolean switch (default True) to control strict domain
                    cropping of nullclines computed.
    with_jac    Toggle to create Jacobian for use in fixed point and nullcline
                calculations (default True)
    verbose     0 = No text output; No graphic output
                1 = Text output only
                2 = Graphic output from this function only
                    No grahphic output from functions called within
                3+ = Pull output from subsequently lower-level functions
                    called within
    as_array    Optional Boolean to return nullclines as array data rather
                than fully interpolated spline nullcline objects (default True)
    """

    ## ------------------------------------------------------------
    ## JACOBIAN
    ## ------------------------------------------------------------

    state = dict(state)  # ensure updatable!
    yvarFS = gen._FScompatibleNames(yvar)
    xvarFS = gen._FScompatibleNames(xvar)
    stateFS = filteredDict(gen._FScompatibleNames(state), gen.funcspec.vars)
    varPars = filteredDict(stateFS, [xvarFS, yvarFS], neg=True)

    # TEMP
    #with_jac = False
    #do_fps = False

    if with_jac:
        jacFS, new_fnspecsFS = prepJacobian(gen.funcspec._initargs['varspecs'], [xvarFS, yvarFS],
                                    gen.funcspec._initargs['fnspecs'])

        scopeFS = gen.pars.copy()
        scopeFS.update(varPars)
        scopeFS.update(new_fnspecsFS)
        jac_fnFS = expr2fun(jacFS, ensure_args=['t'], **scopeFS)

        jac = gen._FScompatibleNamesInv(jacFS)
        scope = gen._FScompatibleNamesInv(gen.pars)
        scope.update(filteredDict(state, [xvar, yvar], neg=True))
        new_fnspecs = {}
        # don't convert the new_fnspecs keys to . notation
        keymap = Symbolic.symbolMapClass(dict(zip(gen._FScompatibleNamesInv(new_fnspecsFS.keys()), new_fnspecsFS.keys())))
        for k, v in new_fnspecsFS.items():
            new_fnspecs[k] = Symbolic.mapNames(keymap, gen._FScompatibleNamesInv(v))
        scope.update(new_fnspecs)
        jac_fn = expr2fun(jac, ensure_args=['t'], **scope)
    else:
        jac_fn = jac_fnFS = None

    ## ------------------------------------------------------------
    ## FIXED POINTS
    ## ------------------------------------------------------------

    if verbose >= 1:
        print("Computing fixed points")

    if subdomain is not None:
        stateFS.update(filteredDict(gen._FScompatibleNames(subdomain),
                                    (xvarFS, yvarFS)))

    if do_fps:
        # create Intervals to test inclusion in subdomain
        int_x = Interval(xvar, float, subdomain[xvar])
        int_y = Interval(yvar, float, subdomain[yvar])

        # temporarily overwriting state with xdomains from gen,
        # for fussy fsolve in find_fixedpoints
        for v in (xvarFS, yvarFS):
            stateFS[v] = gen.xdomain[v]
        fp_coords = find_fixedpoints(gen, n=10, jac=jac_fnFS, subdomain=stateFS,
                                 eps=tol)

        fps = []
        for fp in fp_coords:
            if fp[xvar] in int_x and fp[yvar] in int_y:
                fps.append(fixedpoint_2D(gen, Point(fp), coords=[xvar, yvar],
                                 jac=jac_fn, description='', eps=1e-5))
        # reset stateFS to use subdomain
        if subdomain is not None:
            stateFS.update(filteredDict(gen._FScompatibleNames(subdomain),
                                    (xvarFS, yvarFS)))
    else:
        fp_coords = None
        fps = []


    ## ------------------------------------------------------------
    ## NULLCLINES
    ## ------------------------------------------------------------

    gen.set(ics=varPars)

    if verbose >= 1:
        print("Computing nullclines")

    assert 'V' in (xvar, yvar)
    if 'V' == xvar:
        #Vs = linspace(gen.xdomain['V'][0], gen.xdomain['V'][1], num_x_points)
        Vs = linspace(stateFS['V'][0], stateFS['V'][1], num_x_points)
        other = yvar
        otherFS = yvarFS
        os = linspace(stateFS[yvarFS][0], stateFS[yvarFS][1], num_y_points)
        n = num_y_points
    else:
        Vs = linspace(stateFS['V'][0], stateFS['V'][1], num_y_points)
        other = xvar
        otherFS = xvarFS
        os = linspace(stateFS[xvarFS][0], stateFS[xvarFS][1], num_x_points)
        n = num_x_points

    # yes, this gets recalc'd even if only_var is 'V' but this is a cheap calc compared to
    # nullcline object creation
    ofn = getattr(gen.auxfns, other.split('.')[0]+'_dssrt_fn_'+other.split('.')[1]+'inf')
    oinfs = [ofn(V) for V in Vs]

    fn_args = gen.funcspec._initargs['fnspecs']['dssrt_fn_Vinf'][0]
    # Dictionary to map Na_m into m, etc.
    model_vars = gen.query('vars')
    varnamemap = Symbolic.symbolMapClass(dict([(v,v.split('.')[-1]) \
                                               for v in model_vars]))
    pt = filteredDict(Symbolic.mapNames(varnamemap,
                                        filteredDict(state, model_vars)),
                      fn_args)
    vinfs = np.zeros((n,),float)

    oarg = varnamemap[other]
    if other not in model_vars and fast_vars is not None and other in fast_vars:
        oarg = oarg.split('.')[-1]
        os = oinfs

    if fast_vars is not None and 'Na.m' in fast_vars:
        pt['m'] = gen.auxfns.Na_dssrt_fn_minf(state['V'])

    for i, o in enumerate(os):
        pt[oarg] = o
        vinfs[i] = gen.auxfns.dssrt_fn_Vinf(**pt)

    if 'V' == xvar:
        nulls_x = array([vinfs, os]).T
        nulls_y = array([Vs, oinfs]).T
    else:
        nulls_y = array([os, vinfs]).T
        nulls_x = array([oinfs, Vs]).T

    if as_array:
        nullcX = nulls_x
        nullcY = nulls_y
    else:
        if only_var is None:
            nullcX = nullcline(xvar, yvar, nulls_x, x_relative_scale=x_scale)
            nullcY = nullcline(xvar, yvar, nulls_y, x_relative_scale=x_scale)
        elif only_var == xvar:
            nullcX = nullcline(xvar, yvar, nulls_x, x_relative_scale=x_scale)
            nullcY = None
        elif only_var == yvar:
            nullcX = None
            nullcY = nullcline(xvar, yvar, nulls_y, x_relative_scale=x_scale)
        else:
            raise ValueError("Invalid variable name for only_var: %s" % only_var)

    return {'nullcX': nullcX, 'nullcY': nullcY, 'fps': fps}
Example #23
0
# Your code here for the frequency plot
Is = linspace(0, 2, 100)
fs = []

for I in Is:
    fs.append(freq(I))

plt.figure(2)
plt.plot(Is, fs, 'k.')
plt.xlabel('I')
plt.ylabel('frequencies')

1/0  # comment this to apply phase plane picture to whatever
# are the current parameters of FHN model

## Optional code

fp_coord = pp.find_fixedpoints(fhn, n=25, eps=1e-6)[0]
fp = pp.fixedpoint_2D(fhn, Point(fp_coord), eps=1e-6)

nulls_x, nulls_y = pp.find_nullclines(fhn, 'x', 'y', n=3, eps=1e-6,
                                      max_step=0.1, fps=[fp_coord])
plt.figure(3)
pp.plot_PP_fps(fp)
plt.plot(nulls_x[:,0], nulls_x[:,1], 'b')
plt.plot(nulls_y[:,0], nulls_y[:,1], 'g')

plt.show()