def objective_func(x, target=target_v): try: npa, vn = xpprun('hh.ode', parameters={'i': x[0]}, clean_after=True) computed = npa[:, 1 + vn.index('v')] return np.mean((computed - target)**2) except: return 1e10 # return huge error if something went wrong
def oct_lc(steps_per_cycle=5000,ode_ver='fast'): """ return the limit cycle. """ T = 1. dt = float(T)/steps_per_cycle total=steps_per_cycle*dt if ode_ver == 'fast': fn = 'limit_cycle_pw_const_coupled.ode' T = 1. elif ode_ver == 'slow': fn = 'limit_cycle_pw_const_coupled_slower.ode' T = 16. else: raise ValueError('invalid choice =',ode_ver) npa,vn = xpprun(fn, inits={'x1':-1.,'y1':2.41421}, parameters={'meth':'euler', 'dt':dt, 'eps':0., 'total':total}, clean_after=True) t = npa[:,0] vals = npa[:,1:3] return t,vals
def objective_func(x, target=target_v): try: npa, vn = xpprun('hh.ode', parameters={'i':x[0]}, clean_after=True) computed = npa[:, 1+vn.index('v')] return np.mean( (computed-target)**2 ) except: return 1e10 # return huge error if something went wrong
def run_experiment(fname, pars, inits, return_all=False): npa, vn = xpprun(fname, xppname='xppaut', inits=inits, parameters=pars, clean_after=True) t = npa[:, 0] sv = npa[:, 1:] total_time = t[-1] u1 = sv[:, vn.index('u1')] u2 = sv[:, vn.index('u2')] u3 = sv[:, vn.index('u3')] print vn if return_all: tonelist = [] t0 = float(pars['t0']) dur = float(pars['dur']) isi = float(pars['isi']) for i in range(5): tonelist.append( (t0 + i * (dur + isi), t0 + (i + 1) * dur + i * isi)) #tonelist = [(float(pars['tone1on']),float(pars['tone1off'])), # (float(pars['tone2on']),float(pars['tone2off'])), # (float(pars['tone3on']),float(pars['tone3off'])), # (float(pars['tone4on']),float(pars['tone4off'])), # (float(pars['tone5on']),float(pars['tone5off'])) #] # implement parameter return dict. return { 't': t, 'u1': u1, 'u2': u2, 'u3': u3, 'inits': inits, 'parameters': pars, 'tonelist': tonelist, 'sv': sv, 'vn': vn } else: return {'t': t, 'u1': u1, 'u2': u2, 'u3': u3}
def run_experiment(fname, pars, inits, return_all=False): npa, vn = xpprun(fname, xppname='xppaut', inits=inits, parameters=pars, clean_after=True) t = npa[:, 0] sv = npa[:, 1:] total_time = t[-1] u = sv[:, vn.index('u')] v1 = sv[:, vn.index('v1')] v2 = sv[:, vn.index('v2')] ia = sv[:, vn.index('ia')] g = sv[:, vn.index('g')] if return_all: tonelist = [(float(pars['tone1on']), float(pars['tone1off'])), (float(pars['tone2on']), float(pars['tone2off'])), (float(pars['tone3on']), float(pars['tone3off'])), (float(pars['tone4on']), float(pars['tone4off'])), (float(pars['tone5on']), float(pars['tone5off']))] # implement parameter return dict. return { 't': t, 'u': u, 'v1': v1, 'v2': v2, 'inits': inits, 'parameters': pars, 'tonelist': tonelist, 'sv': sv, 'vn': vn, 'ia': ia, 'g': g } else: return {'t': t, 'u': u, 'v1': v1, 'v2': v2}
def phase_vs_full(): fname = 'izk2.ode' pars = read_pars(fname) eps = 0.1 T = 2000 dt = 0.02 t = np.linspace(0, T, int(T / dt)) y = np.zeros(len(t)) # three different initial conditions # solution values of each phase phase_inits = [ 11, # quarter phase -16, # negative quarter phase 20 # near antiphase ] colors = ['tab:blue', 'tab:orange', 'tab:green'] # negative quarter phase (a bit closer to antiphase) # almost antiphase fig = plt.figure(figsize=(4, 3)) ax1 = fig.add_subplot(111) for j in range(len(phase_inits)): if j == 0: label1 = 'Theory' label2 = 'Numerics' else: label1 = None label2 = None y[0] = -phase_inits[j] for i in range(1, len(t)): y[i] = y[i - 1] + dt * H2odd(y[i - 1], t[i]) ax1.plot(t / eps, np.mod(y / period, 1), label=label1, color=colors[j]) v1, u1 = phase2var(phase_inits[j]) v2, u2 = phase2var(0) #print v1,u1,v2,u2,type(v1) npa, vn = xpprun(fname, xppname='xppaut', inits={ 'v1': float(v1), 'u1': float(u1), 'v2': float(v2), 'u2': float(u2) }, parameters={ 'eps': eps, 'total': t[-1] / eps }, clean_after=True) t_full = npa[:, 0] sv = npa[:, 1:] skip = 10000 ax1.scatter(t_full[::skip][1:], np.mod(sv[:, vn.index('psi')][::skip][1:], 1), facecolors='none', edgecolors=colors[j], label=label2) ax1.plot([0, T / eps], [0, 0], color='k') ax1.plot([0, T / eps], [1, 1], color='k') #ax1.plot([0,T/eps],[-.5,-.5],color='gray',ls='--') ax1.plot([0, T / eps], [.5, .5], color='gray', ls='--') ax1.set_yticks([0, .5, 1]) #ax1.set_yticks([-.5,0,.5]) ax1.set_yticklabels([r'$0$', r'$\pi$', r'$2\pi$' ]) #ax1.set_yticklabels([r'$-T/2$',r'$0$',r'$T/2$']) #ax1.yticks([-.5,0,.5],[r'$-T/2$',r'$0$',r'$T/2$']) ax1.set_ylim(-.1, 1.1) ax1.set_xlim(0, T / eps) ax1.set_xlabel(r'$t$', fontsize=fontsize) ax1.set_ylabel(r'$\phi$', fontsize=fontsize) ax1.legend()
# import some modules including Py_XPPCALL import matplotlib.pylab as plt import numpy as np from xppcall import xpprun, read_pars, read_inits, read_numerics # load file with partially defined initial conditions and define new initial conditions npa, vn = xpprun('simple_partial_inits.ode', inits={'u':-.1,'v':-.2}, clean_after=True) t = npa[:,0] sv = npa[:,1:]
# check if parameters with label 'p' will work # add function to change inits. # Let's check what are the parameters of the model pars = read_pars('simple2.ode') print 'pars', pars # print inits inits = read_inits('simple2.ode') print 'default inits', inits # print options numerics = read_numerics('simple2.ode') print 'numerics', numerics # example with different initial conditions npa, vn = xpprun('simple2.ode', inits={'u': -.1, 'v': -.2}, clean_after=False) t = npa[:, 0] sv = npa[:, 1:] fig = plt.figure() ax3 = fig.add_subplot(111) ax3.plot(sv[:, vn.index('u')], sv[:, vn.index('v')]) ax3.set_xlim([-1.05, 1.05]) ax3.set_ylim([-1.05, 1.05]) ax3.set_title('Lambda-Omega System') plt.show()
## Py_XPPCALL Example # import some modules including Py_XPPCALL import matplotlib.pylab as plt import numpy as np from xppcall import xpprun, read_pars_values_from_file # Let's check what are the parameters of the model pars = read_pars_values_from_file('hh.ode') print pars # Note: XPPAUT is not case sensitive. In Py_XPPCALL, the names of parameters and variables were chosen to be in lower case. # Let's plot solution for membrane potential with parameters specified in .ODE file npa, vn = xpprun('hh.ode', clean_after=True) plt.figure() plt.plot(npa[:, 0], npa[:, 1 + vn.index('v')]) # Let's modify constant input current npa, vn = xpprun('hh.ode', parameters={'i': 20.0}, clean_after=True) plt.figure() plt.plot(npa[:, 0], npa[:, 1 + vn.index('v')]) # Example of an optimization using fmin from SciPy from scipy.optimize import fmin # define desired V graph target_v = -80.0 + 20 * npa[:, 0] * (np.sign(-npa[:, 0] + 4) + 1) plt.figure() plt.plot(npa[:, 0], target_v)
# import some modules including Py_XPPCALL import matplotlib.pylab as plt import numpy as np from xppcall import xpprun, read_pars, read_inits, read_numerics # load file with partially defined initial conditions and define new initial conditions npa, vn = xpprun('simple_partial_inits.ode', inits={ 'u': -.1, 'v': -.2 }, clean_after=True) t = npa[:, 0] sv = npa[:, 1:]
## Py_XPPCALL Example # import some modules including Py_XPPCALL import matplotlib.pylab as plt import numpy as np from xppcall import xpprun, read_pars_values_from_file # Let's check what are the parameters of the model pars = read_pars_values_from_file('hh.ode') print pars # Note: XPPAUT is not case sensitive. In Py_XPPCALL, the names of parameters and variables were chosen to be in lower case. # Let's plot solution for membrane potential with parameters specified in .ODE file npa, vn = xpprun('hh.ode', clean_after=True) plt.figure() plt.plot(npa[:,0], npa[:, 1+vn.index('v')]) # Let's modify constant input current npa, vn = xpprun('hh.ode', parameters={'i':20.0}, clean_after=True) plt.figure() plt.plot(npa[:,0], npa[:, 1+vn.index('v')]) # Example of an optimization using fmin from SciPy from scipy.optimize import fmin # define desired V graph target_v = -80.0+20*npa[:,0]*(np.sign(-npa[:,0]+4)+1) plt.figure() plt.plot(npa[:,0], target_v)
def oct_phase_reset(phi, dx=0., dy=0., steps_per_cycle = 200000, num_cycles = 3, return_intermediates=False, ode_ver='fast'): if ode_ver == 'fast': fn = 'limit_cycle_pw_const_coupled.ode' T = 1. elif ode_ver == 'slow': fn = 'limit_cycle_pw_const_coupled_slower.ode' T = 16. else: raise ValueError('invalid choice =', ode_ver) print phi # total period dt = float(T)/steps_per_cycle steps_before = int(phi/(2*math.pi) * steps_per_cycle) + 1 # run up to perturbation npa,vn = xpprun(fn, inits={'x1':1,'y1':2.41421}, parameters={'meth':'euler', 'dt':dt, 'eps':0., 'total':steps_before*dt}, clean_after=True) t1 = npa[:,0] vals1 = npa[:,1:3] # run after perturbation steps_after = steps_per_cycle * num_cycles - steps_before npa,vn = xpprun(fn, inits={'x1':vals1[-1,0]+dx,'y1':vals1[-1,1]+dy}, parameters={'meth':'euler', 'dt':dt, 'eps':0., 'total':steps_after*dt}, clean_after=True) t2 = npa[:,0]+T*phi/(2*math.pi) vals2 = npa[:,1:3] x_section = 1. crossings = ((vals2[:-1,0] <= x_section) * (vals2[1:,0] > x_section) * (vals2[1:,1] > 0)) if len(crossings) == 0: raise RuntimeError("No complete cycles after the perturbation") crossing_fs = ((vals2[1:,0][crossings] - x_section) / (vals2[1:,0][crossings]-vals2[:-1,0][crossings]) ) crossing_times = (crossing_fs * t2[:-1][crossings] + (1-crossing_fs) * t2[1:][crossings]) #crossing_times = crossing_times - crossing_times[0] crossing_phases = np.fmod(crossing_times, T)# * 2 * math.pi print crossing_phases #crossing_phases[crossing_phases > math.pi] -= 2*math.pi crossing_phases[crossing_phases > T/2.] -= T crossing_phases /= T if return_intermediates: return dict(t1=t1, vals1=vals1, t2=t2, vals2=vals2, crossings=crossings, crossing_times=crossing_times, crossing_phases=crossing_phases) else: return -crossing_phases[-1]
pars = read_pars('wc.ode') print 'pars',pars # print inits inits = read_inits('wc.ode') print 'default inits',inits # print options numerics = read_numerics('wc.ode') print 'numerics', numerics # run ODE and get solution with default inits # Let's plot a solution with default parameters and inits specified in the .ODE file npa, vn = xpprun('wc.ode', clean_after=True) t = npa[:,0] sv = npa[:,1:] #(501 time steps, 202 variables) # the way that xpp defined the ODEs, the varnames alternate like u0,v0,u1,v1,u2,v2,... u99,v99,u100,v100 #print np.shape(sv) fig = plt.figure(figsize=(10,5)) ax1 = fig.add_subplot(121) ax1.set_title('default inits and params') ax1.plot(sv[:,0],sv[:,1],lw=2) #ax1.set_xlim([-1.05,1.05]) #ax1.set_ylim([-1.05,1.05]) #ax1.set_title('q=1')
def RunAndSave(self,e): if self.filenameDisplay.GetLabel() == "No ODE file loaded.": dlg = wx.MessageDialog( self, "Please load an ODE file first.", "Error", wx.OK) dlg.ShowModal() # Show it dlg.Destroy() # finally destroy it when finished. return try: # get parameter values from windows self.params = self.h2xppcall(self.paramDisplay.GetValue()) self.opts = self.h2xppcall(self.optDisplay.GetValue()) self.inits = self.h2xppcall(self.initDisplay.GetValue(),return_float=True) #print 'self.inits,getvalue',self.inits,self.initDisplay.GetValue() # http://stackoverflow.com/questions/1781571/how-to-concatenate-two-dictionaries-to-create-a-new-one-in-python # parameters and options are input in the same dictionary. combinedin = dict(self.params.items() + self.opts.items()) print 'running xpp with options',combinedin, self.inits self.npa, self.vn, fullfilename,outputfilepath = xpprun(self.fullname, parameters=combinedin, inits=self.inits, clean_after=False,return_tempname=True) #print self.npa, self.vn self.t = self.npa[:,0] self.sv = self.npa[:,1:] #print self.sv[0,self.vn.index('sx')],self.sv[0,self.vn.index('sy')] #time.sleep(10) if self.firstrun: # show simple plot by default # set default plot choice self.choicex = 't' self.choicey = self.vn[0] self.plotx = self.t self.ploty = self.npa[:,1] else: if self.choicex == 't': self.plotx = self.t else: self.plotx = self.sv[:,self.vn.index(self.choicex)] self.ploty = self.sv[:,self.vn.index(self.choicey)] # update graph tab self.plotpanel.init_plot(self.plotx,self.ploty, ls=self.ls, marker=self.marker, color=self.color) # update data tab f = open(outputfilepath, 'r') self.outDisplay.SetValue(f.read()) f.close() # clean temporary ode files os.remove(outputfilepath) os.remove(fullfilename) #os.remove(fullfilename) # set x vs y plot options # loop over dictionary to extract state variables svlist = ['t'] for i in self.vn: svlist.append(i) # update the drop-down menus if self.firstrun: self.sv_choicex.SetItems(svlist) self.sv_choicey.SetItems(svlist) self.firstrun = False except IOError: # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets. dlg = wx.MessageDialog( self, "Please load an ODE file first.", "Error", wx.OK) dlg.ShowModal() # Show it dlg.Destroy() # finally destroy it when finished.
# Let's check what are the parameters of the model pars = read_pars('simple.ode') print pars # print inits inits = read_inits('simple.ode') print inits # print options numerics = read_numerics('simple.ode') print numerics # Note: XPPAUT is not case sensitive. In Py_XPPCALL, the names of parameters and variables were chosen to be in lower case. # Let's plot a solution with default parameters and inits specified in the .ODE file npa, vn = xpprun('simple.ode', clean_after=False) t = npa[:,0] sv = npa[:,1:] fig = plt.figure(figsize=(10,5)) ax1 = fig.add_subplot(121) ax1.plot(sv[:,vn.index('u')],sv[:,vn.index('v')],lw=2) ax1.set_xlim([-1.05,1.05]) ax1.set_ylim([-1.05,1.05]) ax1.set_title('q=1') # Let's modify one of the parameters npa, vn = xpprun('simple.ode', parameters={'q':5.0}, clean_after=False) t = npa[:,0] sv = npa[:,1:]