def SMtoGEO(x, y, z, dateTime): """ Converts Solar Magnetic to geographic coordinates """ pyLTR.transform.geopack_08.recalc_08(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second, -400.0, 0.0, 0.0) iSMtoGSM = 1 iGSMtoGEO = -1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 12/2013 ## Note: some f2py results result in 6 outputs, while result in 7; ## this is one of the latter, thus `otypes=[float]*6` v_gp08a = p.vectorize(pyLTR.transform.geopack_08.smgsw_08, otypes=[float] * 6) _, _, _, xgsm, ygsm, zgsm = v_gp08a(x, y, z, 0., 0., 0., iSMtoGSM) v_gp08b = p.vectorize(pyLTR.transform.geopack_08.geogsw_08, otypes=[float] * 6) xgeo, ygeo, zgeo, _, _, _ = v_gp08b(0., 0., 0., xgsm, ygsm, zgsm, iGSMtoGEO) ## if scalar inputs, generate scalar outputs -EJR 12/2013 return ((xgeo, ygeo, zgeo) if isinstance(x, p.ndarray) else tuple( p.asscalar(otmp) for otmp in (xgeo, ygeo, zgeo)))
def GEOtoSM(x, y, z, dateTime): """ Converts geographic to Solar Magnetic coordinates """ ghostpy.transform.geopack_08.recalc_08(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second, -400.0, 0.0, 0.0) iGEOtoGSM = 1 iGSMtoSM = -1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 12/2013 ## v_gp08a = p.vectorize(ghostpy.transform.geopack_08.geogsw_08) _, _, _, xgsm, ygsm, zgsm = v_gp08a(x, y, z, 0., 0., 0., iGEOtoGSM) v_gp08b = p.vectorize(ghostpy.transform.geopack_08.smgsw_08) xsm, ysm, zsm, _, _, _ = v_gp08b(0., 0., 0., xgsm, ygsm, zgsm, iGSMtoSM) ## if scalar inputs, generate scalar outputs -EJR 12/2013 return ((xsm, ysm, zsm) if isinstance(x, p.ndarray) else tuple( p.asscalar(otmp) for otmp in (xsm, ysm, zsm)))
def CARtoSPH(x, y, z, dx=None, dy=None, dz=None): """ convert cartesian coordinates (x,y,z) to spherical (phi,theta,rho) - if 3 inputs, convert position vectors - if 6 inputs, convert directional vectors """ if dx == None or dy == None or dz == None: if dx == None and dy == None and dz == None: ## transform position vectors iSPHtoCAR = -1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 10/2013 ## #output = ghostpy.transform.geopack_08.sphcar_08(0.,0.,0.,x,y,z, iSPHtoCAR) v_gp08 = p.vectorize(ghostpy.transform.geopack_08.sphcar_08) output = v_gp08(0., 0., 0., x, y, z, iSPHtoCAR) ## if scalar inputs, generate scalar outputs -EJR 10/2013 return (tuple(p.asscalar(otmp) for otmp in output[2::-1]) if (p.isscalar(x) and p.isscalar(y) and p.isscalar(z)) else (output[2], output[1], output[0])) else: raise Exception, 'SPHtoCAR requires exactly 3 or 6 inputs' else: iSPHtoCAR = -1 ## transform local directional vectors ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 10/2013 ## #output = ghostpy.transform.geopack_08.sphcar_08(0.,0.,0.,x,y,z, iSPHtoCAR) v_gp08a = p.vectorize(ghostpy.transform.geopack_08.sphcar_08) rho, theta, phi, _, _, _, _ = v_gp08a(0., 0., 0., x, y, z, iSPHtoCAR) #dx,dy,dz = ghostpy.transform.geopack_08.bspcar_08(theta,phi,drho,dtheta,dphi) v_gp08b = p.vectorize(ghostpy.transform.geopack_08.bcarsp_08) drho, dtheta, dphi = v_gp08b(x, y, z, dx, dy, dz) ## if scalar inputs, generate scalar outputs -EJR 10/2013 return (tuple( p.asscalar(otmp) for otmp in (phi, theta, rho, dphi, dtheta, drho)) if (p.isscalar(x) and p.isscalar(y) and p.isscalar(z) and p.isscalar(dx) and p.isscalar(dy) and p.isscalar(dz)) else (phi, theta, rho, dphi, dtheta, drho))
def SPHtoCAR(phi, theta, rho, dphi=None, dtheta=None, drho=None): """ convert spherical coordinates (phi,theta,rho) to cartesian (x,y,z) - if 3 inputs, convert position vectors - if 6 inputs, convert directional vectors """ if dphi == None or dtheta == None or drho == None: if dphi == None and dtheta == None and drho == None: ## transform position vectors iSPHtoCAR = 1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 10/2013 ## #output = ghostpy.transform.geopack_08.sphcar_08(rho,theta,phi,0.,0.,0., iSPHtoCAR) v_gp08 = p.vectorize(ghostpy.transform.geopack_08.sphcar_08) output = v_gp08(rho, theta, phi, 0., 0., 0., iSPHtoCAR) ## if scalar inputs, generate scalar outputs -EJR 10/2013 return (tuple(p.asscalar(otmp) for otmp in output[3:6]) if (p.isscalar(phi) and p.isscalar(theta) and p.isscalar(rho)) else (output[3], output[4], output[5])) else: raise Exception, 'SPHtoCAR requires exactly 3 or 6 inputs' else: iSPHtoCAR = 1 ## transform local directional vectors ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 10/2013 ## #output = ghostpy.transform.geopack_08.sphcar_08(rho,theta,phi,0.,0.,0., iSPHtoCAR) v_gp08a = p.vectorize(ghostpy.transform.geopack_08.sphcar_08) _, _, _, x, y, z, _ = v_gp08a(rho, theta, phi, 0., 0., 0., iSPHtoCAR) #dx,dy,dz = ghostpy.transform.geopack_08.bspcar_08(theta,phi,drho,dtheta,dphi) v_gp08b = p.vectorize(ghostpy.transform.geopack_08.bspcar_08) dx, dy, dz = v_gp08b(theta, phi, drho, dtheta, dphi) ## if all scalar inputs, return scalar outputs, otherwise ndarrays -EJR 10/2013 return (tuple(p.asscalar(otmp) for otmp in (x, y, z, dx, dy, dz)) if (p.isscalar(phi) and p.isscalar(theta) and p.isscalar(rho) and p.isscalar(dphi) and p.isscalar(dtheta) and p.isscalar(drho)) else (x, y, z, dx, dy, dz))
def SMtoMAG(x, y, z, dateTime): """ Converts solar magnetic coordinates to dipole magnetic coordinates """ pyLTR.transform.geopack_08.recalc_08(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second, -400.0, 0.0, 0.0) iSMtoMAG = -1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 12/2013 ## Note: some f2py results result in 6 outputs, while result in 7; ## this is one of the latter, thus `otypes=[float]*7` v_gp08 = p.vectorize(pyLTR.transform.geopack_08.magsm_08, otypes=[float] * 7) output = v_gp08(0., 0., 0., x, y, z, iSMtoMAG) ## if scalar inputs, generate scalar outputs -EJR 12/2013 return ((output[0], output[1], output[2]) if isinstance(x, p.ndarray) else tuple( p.asscalar(otmp) for otmp in output[0:3]))
def GEOtoGSM(x, y, z, dateTime): """ Converts geographic to Geocentric Solar Magnetic coordinates """ pyLTR.transform.geopack_08.recalc_08(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second, -400.0, 0.0, 0.0) iGEOtoGSM = 1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 12/2013 ## Note: some f2py results result in 6 outputs, while result in 7; ## this is one of the latter, thus `otypes=[float]*6` v_gp08 = p.vectorize(pyLTR.transform.geopack_08.geogsw_08, otypes=[float] * 6) output = v_gp08(x, y, z, 0., 0., 0., iGEOtoGSM) ## if scalar inputs, generate scalar outputs -EJR 12/2013 return ((output[3], output[4], output[5]) if isinstance(x, p.ndarray) else tuple( p.asscalar(otmp) for otmp in output[3:6]))
def GEOtoMAG(x, y, z, dateTime): """ Converts geographic to dipole (mag) coordinates. >>> GEOtoMAG(-0.780, -0.613, 0.128, datetime.datetime(2009,1,27,0,0,0)) # doctest:+ELLIPSIS () """ ghostpy.transform.geopack_08.recalc_08(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second, -400.0, 0.0, 0.0) iGEOtoMAG = 1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 10/2013 ## #output = ghostpy.transform.geopack_08.gswgse_08(x, y, z, 0.,0.,0., iGEOtoMAG) v_gp08 = p.vectorize(ghostpy.transform.geopack_08.geomag_08) output = v_gp08(x, y, z, 0., 0., 0., iGEOtoMAG) ## if scalar inputs, generate scalar outputs -EJR 10/2013 return ((output[3], output[4], output[5]) if isinstance(x, p.ndarray) else tuple( p.asscalar(otmp) for otmp in output[3:6]))
def MAGtoGEO(x, y, z, dateTime): """ Converts dipole (mag) to geographic coordinates. >>> MAGtoGEO(0.3133, -0.9313, 0.1857, datetime.datetime(2009,1,27,0,0,0)) # doctest:+ELLIPSIS () """ pyLTR.transform.geopack_08.recalc_08(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second, -400.0, 0.0, 0.0) iGEOtoMAG = -1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 10/2013 ## Note: some f2py results result in 6 outputs, while result in 7; ## this is one of the latter, thus `otypes=[float]*7` #output = pyLTR.transform.geopack_08.gswgse_08(0.,0.,0., x, y, z, iGEOtoMAG) v_gp08 = p.vectorize(pyLTR.transform.geopack_08.geomag_08, otypes=[float] * 7) output = v_gp08(0., 0., 0., x, y, z, iGEOtoMAG) ## if scalar inputs, generate scalar outputs -EJR 10/2013 return ((output[0], output[1], output[2]) if isinstance(x, p.ndarray) else tuple( p.asscalar(otmp) for otmp in output[0:3]))
def chebygen(amps): N = 40000 p = pl.arange(-N, N + 1) c = pl.zeros(len(p)) n = 0 for i in amps: c += sp.eval_chebyu(n - 1, p / N) * i n += 1 return pl.vectorize(lambda x: c[int(x * N + N)])
def formula2(): y0 = int(raw_input("Please enter the initial position of the ball: ")) theta = int(raw_input("Please enter the angle in which you would want to project: ")) v0 = int(raw_input("Please enter the initial velocity of the ball: ")) print "Your initial position y0 is %d metres, angle theta is %d degrees and initial velocity is %d m/s"% (y0,theta,v0) if y0>= 0: d= plt.vectorize(formula) plt.plot( d(np.linspace(0,50 , 1000),y0,v0,theta)) plt.title('Height') plt.xlabel('x') plt.ylabel('y') plt.show()
def mycontour(f, xmin, xmax, ymin, ymax, nx=101, ny=101): from pylab import arange, zeros, vectorize, contourf x = xmin + (xmax - xmin)*arange(float(nx))/float(nx-1) y = ymin + (ymax - ymin)*arange(float(ny))/float(ny-1) z = zeros((ny, nx)) vf = vectorize(f) print type(vf) print vf ion() for i in xrange(nx): z[:, i] = vf(x[i], y) contourf(x, y, z, 96) return z
def img2ascii(filename, map_array=None, blk_siz=2): """ Convert an image file to an ascii plain text file.""" a = file2gray(filename) c = blockify_img(a, blk_siz) if map_array == None: # just linearly map gray level to characters. # giving lowest gray level to space character. f = vectorize(lambda b: chr(32+int((1-b)*94))) c = f(c) write_arr(c, filename, "-lin-", blk_siz) else: # map based on visual density of characters. c = map_img_chars(c, map_array) write_arr(c, filename, "-arr-", blk_siz)
def GSMtoSM(x, y, z, dateTime): """ >>> GSMtoSM(1,2,3, datetime.datetime(2009,1,27,0,0,0)) # doctest:+ELLIPSIS (1.997..., 2.0, 2.451...) """ if pyLTR.transform.transformer == 'CXFORM': (xSM, ySM, zSM) = pyLTR.transform.cxform.transform( 'GSM', 'SM', x, y, z, dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute, dateTime.second) return (xSM, ySM, zSM) elif pyLTR.transform.transformer == 'GEOPACK': pyLTR.transform.geopack.recalc(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second) iSMtoGSM = -1 output = pyLTR.transform.geopack.smgsm(0., 0., 0., x, y, z, iSMtoGSM) return (output[0], output[1], output[2]) elif pyLTR.transform.transformer == 'GEOPACK_08': pyLTR.transform.geopack_08.recalc_08(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second, -400.0, 0.0, 0.0) iSMtoGSM = -1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 10/2013 ## Note: some f2py results result in 6 outputs, while result in 7; ## this is one of the latter, thus `otypes=[float]*6` #output = pyLTR.transform.geopack_08.smgsw_08(0.,0.,0., x, y, z, iSMtoGSM) v_gp08 = p.vectorize(pyLTR.transform.geopack_08.smgsw_08, otypes=[float] * 6) output = v_gp08(0., 0., 0., x, y, z, iSMtoGSM) ## if scalar inputs, generate scalar outputs -EJR 10/2013 return ((output[0], output[1], output[2]) if isinstance(x, p.ndarray) else tuple( p.asscalar(otmp) for otmp in output[0:3])) else: raise Exception('Coordinate system transformer undefined')
def GSEtoGSM(x, y, z, dateTime): """ >>> GSEtoGSM(1,2,3, datetime.datetime(2009,1,27,0,0,0)) # doctest:+ELLIPSIS (0.99..., 0.540..., 3.564...) """ if ghostpy.transform.transformer == 'CXFORM': (xGSM, yGSM, zGSM) = ghostpy.transform.cxform.transform( 'GSE', 'GSM', x, y, z, dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute, dateTime.second) return (xGSM, yGSM, zGSM) elif ghostpy.transform.transformer == 'GEOPACK': ghostpy.transform.geopack.recalc(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second) iGSEtoGSM = -1 output = ghostpy.transform.geopack.gsmgse(0., 0., 0., x, y, z, iGSEtoGSM) return (output[0], output[1], output[2]) elif ghostpy.transform.transformer == 'GEOPACK_08': ghostpy.transform.geopack_08.recalc_08(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second, -400.0, 0.0, 0.0) iGSEtoGSM = -1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 10/2013 ## #output = ghostpy.transform.geopack_08.gswgse_08(0.,0.,0., x,y,z, iGSEtoGSM) v_gp08 = p.vectorize(ghostpy.transform.geopack_08.gswgse_08) output = v_gp08(0., 0., 0., x, y, z, iGSEtoGSM) ## if scalar inputs, generate scalar outputs -EJR 10/2013 return ((output[0], output[1], output[2]) if isinstance(x, p.ndarray) else tuple( p.asscalar(otmp) for otmp in output[0:3])) else: raise Exception, 'Coordinate system transformer undefined'
def PercusYevickHS(phi,plot=True,filename="g_of_r.txt",x=pl.arange(0,5,0.05)): # number density rho=6./pi*phi # getting the direct correlation function c(r) from the analytic Percus-Yevick solution # vectorizing the function c=pl.vectorize(cc) # space discretization dr=0.005 r=pl.arange(1,1024*2+1,1 )*dr # reciprocal space discretization (highest available frequency) dk=1/r[-1] k=pl.arange(1,1024*2+1,1 )*dk # direct correlation function c(r) c_direct=c(r,phi) # getting the Fourier transform ft_c_direct=spherical_FT(c_direct, k,r,dr) # using the Ornstein-Zernike equation, getting the structure factor ft_h=ft_c_direct/(1.-rho*ft_c_direct) # inverse Fourier transform h=inverse_spherical_FT(ft_h, k,r,dk) # print h # # radial distribution function gg=h+1 # clean the r<1 region g=pl.zeros(len(gg)) g[r>=1]=gg[r>=1] # save the cleaned version pl.savetxt(filename, zip(r,g)) from scipy.interpolate import InterpolatedUnivariateSpline spl=InterpolatedUnivariateSpline(r, g) # plots if plot: pl.plot(r,abs((g-1)*r)) # pl.plot(r,g-1) pl.ylabel("|(g(r)-1)r|") pl.xlabel("r") # return abs((spl(x)-1)*x) return spl(x)
def MAGtoSM(x, y, z, dateTime): """ Converts dipole magnetic to solar magnetic coordinates """ ghostpy.transform.geopack_08.recalc_08(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second, -400.0, 0.0, 0.0) iMAGtoSM = 1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 12/2013 ## v_gp08 = p.vectorize(ghostpy.transform.geopack_08.magsm_08) output = v_gp08(x, y, z, 0., 0., 0., iMAGtoSM) ## if scalar inputs, generate scalar outputs -EJR 12/2013 return ((output[3], output[4], output[5]) if isinstance(x, p.ndarray) else tuple( p.asscalar(otmp) for otmp in output[3:6]))
def GSMtoGEO(x, y, z, dateTime): """ Converts Geocentric Solar Magnetic to geographic coordinates """ ghostpy.transform.geopack_08.recalc_08(dateTime.year, dateTime.timetuple().tm_yday, dateTime.hour, dateTime.minute, dateTime.second, -400.0, 0.0, 0.0) iGSMtoGEO = -1 ## vectorize geopack_08 call using NumPy's vectorize() method: ## Note: vectorize()'s doc string states that this is not very speed ## optimized...Geopack should be ported to Python, or re-written ## to accept array inputs, if speed is an issue. -EJR 12/2013 ## v_gp08 = p.vectorize(ghostpy.transform.geopack_08.geogsw_08) output = v_gp08(0., 0., 0., x, y, z, iGEOtoGSM) ## if scalar inputs, generate scalar outputs -EJR 12/2013 return ((output[0], output[1], output[2]) if isinstance(x, p.ndarray) else tuple( p.asscalar(otmp) for otmp in output[0:3]))
a = 0.5 B = 5.0 b = 2.0 # y1 = A*pl.exp(-x**2 /(4*a**2)) # y2 = - B*pl.exp(-x**2/(4*b**2)) fac = 5 # Kernel strength h = 3 # resting level ''' Mexican Hat''' y= A*pl.exp(-x**2 /(4*a**2))- B*pl.exp(-x**2/(4*b**2)) -h ''' Gabor''' # y= A/(pl.sqrt(pl.pi)*b) * pl.exp(-x**2/(4*b**2)) * pl.cos(b*x) -h y = fac * y return y vec_funW = pl.vectorize(funW) s = pl.linspace(-pl.pi,pl.pi,pop) weight = vec_funW(s) # weight matrix 1 by pop ''' Stimulation specs ''' amplitude =1800.0 #pA start = 200.0 stop = 800.0 ''' define the stimulation ''' def funS(x): c =0.6
# defining the weight function def funW(x) : gama = 5 alpha = .7 C = .7 fac = 20e-9 # Kernel strength ''' Weight Kernel ''' y = ((1+math.cos(alpha*x))/2)**gama; ''' ''' # y = fac * (y-C) y = fac * y return y vec_funW = pl.vectorize(funW) s = pl.linspace(-pl.pi,pl.pi,n_ensembles) knl = vec_funW(s) # weight matrix #============================================================================== # ''' define the stimulation ''' # # def funS(x): # c =0.6 # mean = 0.0 # I = 10 # y = I/(pl.sqrt(2*pl.pi)*c) * pl.exp(-(x-mean)**2/(2*c**2)) # return y # # vec_funS = pl.vectorize(funS) # s = pl.linspace(-pl.pi,pl.pi,n_ensembles)
N = len(w) X = pl.rfft(x*w) k = pl.arange(0,N/2+1) return X*pl.exp(-2*pl.pi*1j*k*n/N) def istft(X,w,n): N = len(w) k = pl.arange(0,N/2+1) xn = pl.irfft(X*pl.exp(2*pl.pi*1j*k*n/N)) return xn*w def modpi(x): if x >= pl.pi: x -= 2*pl.pi if x < -pl.pi: x += 2*pl.pi return x unwrap = pl.vectorize(modpi) class Pvoc: def __init__(self,w,h,sr): N = len(w) self.win = w self.phs = pl.zeros(N//2+1) self.h = h self.n = 0 self.fc = pl.arange(N//2+1)*sr/N self.sr = sr def analysis(self,x): X = stft(x,self.win,self.n) delta = pl.angle(X) - self.phs self.phs = pl.angle(X)
def gen_ssmodel(self): """ generates full neural model Attributes: ---------- K: ndarray array of connectivity kernel evaluated over the spatial domain of the kernel Sigma_e: ndarray field disturbance covariance matrix Sigma_e_c: ndarray Cholesky decomposiotion of field disturbance covariance matrix Sigma_epsilon_c: ndarray cholesky decomposiotion of observation noise covariance matrix C: ndarray matrix of sensors evaluated at each spatial location """ print "generating full neural model" K=0 for i in range(len(self.kernel.Lambda)): K_temp=pb.vectorize(self.kernel.Lambda[i,0].__call__) K+=self.kernel.weights[i]*K_temp(self.simulation_space) K.shape=K.shape[0],1 self.K=K #calculate field disturbance covariance matrix and its Cholesky decomposition #initialisation if hasattr(self,'Sigma_e'): pass else: Sigma_e=pb.zeros([self.simulation_space.shape[0],self.simulation_space.shape[0]]) offset=pb.absolute(self.eta.Supp()[1]-self.eta.Supp()[0])/2. eta_translation=(2**self.eta.j)*pb.arange(-pb.absolute(self.simulation_space[0])-offset,(pb.absolute(self.simulation_space[0])-offset)+self.spacestep,self.spacestep) for m,n in enumerate(eta_translation): eta_temp=pb.vectorize(scale(self.eta.j,n).__call__) Sigma_e[m]=eta_temp(self.simulation_space) self.Sigma_e=self.eta_weight*Sigma_e if hasattr(self,'Sigma_e_c'): pass else: self.Sigma_e_c=sp.linalg.cholesky(self.Sigma_e,lower=1) #calculate Cholesky decomposition of observation noise covariance matrix Sigma_epsilon_c=sp.linalg.cholesky(self.Sigma_epsilon,lower=1) self.Sigma_epsilon_c=Sigma_epsilon_c #Calculate sensors at each spatial locations C=pb.zeros([self.ny,self.simulation_space.shape[0]]) offset=pb.absolute(self.sensor_kernel.Supp()[1]-self.sensor_kernel.Supp()[0])/2. sensor_kernel_translation=(2**self.sensor_kernel.j)*pb.arange(-pb.absolute(self.obs_locns[0])-offset,(pb.absolute(self.obs_locns[0])-offset)+self.sensorspace,self.sensorspace) for m,n in enumerate(sensor_kernel_translation): sensor_kernel_temp=pb.vectorize(scale(self.sensor_kernel.j,n).__call__) C[m]=sensor_kernel_temp(self.simulation_space) self.C=C
P=find_real_positive(roots) return P def cs(rho): eta=rho/6.*pl.pi return (1+eta+eta**2-eta**3)/(1-eta)**3*eta*6./pl.pi rhofirst=1.041 print "Starting density",rhofirst print "Starting pressure",find_solid_p(1.105) compressionfactor=0.98 rhos=[rhofirst*compressionfactor**n for n in range(1,12)] print "densities",rhos ps=[find_solid_p(rho) for rho in rhos] pf=[cs(rho) for rho in rhos] print "packing fractions", pl.array(rhos)/6*pl.pi print "solid pressures",ps print "fluid pressures",pf print find_solid_p(d(.555014632)) ds=pl.vectorize(d) almarza=pl.vectorize(find_solid_p) etas=pl.linspace(0.54,1,100) pl.savetxt("almarz.txt", zip(etas,almarza(ds(etas)))) # # pl.plot(p,f) # pl.plot(p,pl.zeros(len(f))) # pl.show()
def gen_ssmodel(self): #calculate U #~~~~~~~~~~~ if not(hasattr(self,'U')): t0=time.time() self.U_Index=[] U=pb.empty((self.nx,self.nx),dtype=object) U_T=pb.empty((self.nx,self.nx),dtype=object) for i in range(self.nx): for j in range(self.nx): u_temp=pb.vectorize(self.field.Mu[j,0].conv)(self.kernel.Lambda) U[i,j]=pb.dot(u_temp.T,self.field.Mu[i,0]).astype(float) U_T[j,i]=U[i,j].T if U[i,j].any(): self.U_Index.append((i,j)) self.U=U self.U_T=U_T print 'Elapsed time in seconds to calculate U is', time.time()-t0 #calculate the inverse of inner product of field basis functions if not(hasattr(self,'Lambda_x_blocks_inverse')): t0=time.time() Lambda_x_blocks_inverse=pb.empty((1,len(self.field.NoatEachLevel)),dtype=object) Lambda_x_inverse_temp=0 for i in range(Lambda_x_blocks_inverse.shape[1]): Lambda_x_blocks_inverse_temp=pb.reshape(self.field.Mu[Lambda_x_inverse_temp:Lambda_x_inverse_temp+self.field.NoatEachLevel[i],0],(1,self.field.NoatEachLevel[i])) Lambda_x_blocks_inverse[0,i]=pb.inv(pb.dot(Lambda_x_blocks_inverse_temp.T,Lambda_x_blocks_inverse_temp)).astype(float) Lambda_x_inverse_temp+=self.field.NoatEachLevel[i] self.Lambda_x_blocks_inverse=Lambda_x_blocks_inverse print 'Elapsed time in seconds to calculate Lambda_x_inverse is',time.time()-t0 #calculate Lambda_x if not(hasattr(self,'Lambda_x')): t0=time.time() Lambda_x=pb.dot(self.field.Mu,self.field.Mu.T) self.Lambda_x=Lambda_x print 'Elapsed time in seconds to calculate Lambda_x is',time.time()-t0 t0=time.time() Lambda_theta = pb.zeros([self.nx,self.nx]) for i in self.U_Index: Lambda_theta[i] = pb.dot(self.U[i],self.kernel.weights) self.Lambda_theta = Lambda_theta #calculate A A_blocks=pb.empty((1,len(self.field.NoatEachLevel)),dtype=object) A_temp=0 for i in range(A_blocks.shape[1]): A_blocks_temp=self.Lambda_theta[A_temp:self.field.NoatEachLevel[i]+A_temp] A_blocks[0,i]=pb.dot(self.Lambda_x_blocks_inverse[0,i],A_blocks_temp) A_temp+=self.field.NoatEachLevel[i] self.A=self.Ts*self.varsigma*pb.vstack(A_blocks[0,:])+self.xi*pb.eye(self.nx) print 'Elapsed time in seconds to calculate Lambda_theta and A is',time.time()-t0 # form the observation matrix if not(hasattr(self,'C')): t0=time.time() t_observation_matrix=time.time() sensor_kernel_convolution_vecrorized=pb.vectorize(self.sensor_kernel.conv) sensor_kernel_conv_Mu=sensor_kernel_convolution_vecrorized(self.field.Mu).T C=pb.empty(([self.ny,self.nx]),dtype=float) for i in range(self.nx): c_temp=pb.vectorize(sensor_kernel_conv_Mu[0,i].__call__) C[:,i]=c_temp(self.obs_locns) self.C=C print 'Elapsed time in seconds to calculate observation matrix C is',time.time()-t_observation_matrix #calculate Sigma_e_c if not(hasattr(self,'Sigma_e_c')): t0=time.time() eta_convolution_vecrorized=pb.vectorize(self.eta.conv) eta_conv_Mu=eta_convolution_vecrorized(self.field.Mu).T Pi=pb.dot(eta_conv_Mu.T,self.field.Mu.T).astype(float).T self.Pi=Pi Sigma_e_blocks=pb.empty((1,len(self.field.NoatEachLevel)),dtype=object) Sigma_e_temp=0 #calculate (LAmbda_x )^-1* Sigma_e) for i in range(Sigma_e_blocks.shape[1]): Sigma_e_blocks_temp=Pi[Sigma_e_temp:self.field.NoatEachLevel[i]+Sigma_e_temp] Sigma_e_blocks[0,i]=pb.dot(self.Lambda_x_blocks_inverse[0,i],Sigma_e_blocks_temp) Sigma_e_temp+=self.field.NoatEachLevel[i] Sigma_e=pb.vstack(Sigma_e_blocks[0,:]) Sigma_e_temp=0 for i in range(Sigma_e_blocks.shape[1]): Sigma_e_blocks_temp=Sigma_e[:,Sigma_e_temp:self.field.NoatEachLevel[i]+Sigma_e_temp] Sigma_e_blocks[0,i]=pb.dot(Sigma_e_blocks_temp,self.Lambda_x_blocks_inverse[0,i].T) Sigma_e_temp+=self.field.NoatEachLevel[i] Sigma_e=pb.hstack(Sigma_e_blocks[0,:]) self.Sigma_e=self.eta_weight*Sigma_e print 'Elapsed time in seconds to calculate Sigma_e is',time.time()-t0 self.Sigma_e_c=sp.linalg.cholesky(self.Sigma_e,lower=1) #calculate Sigma_epsilon_c if not(hasattr(self,'Sigma_epsilon_c')): Sigma_epsilon_c=sp.linalg.cholesky(self.Sigma_epsilon,lower=1) self.Sigma_epsilon_c=Sigma_epsilon_c #calculate EM components for speed if not(hasattr(self,'Delta_upsilon')): t0=time.time() self.Delta_upsilon=dots(pb.inv(self.Sigma_e),directsum(self.Lambda_x_blocks_inverse),self.U) print 'Elapsed time in seconds to calculate Delta_upsilon is',time.time()-t0 if not(hasattr(self,'Delta_Upsilon')): t0=time.time() self.Delta_Upsilon=dots(self.U_T,directsum(self.Lambda_x_blocks_inverse),self.Delta_upsilon) print 'Elapsed time in seconds to calculate Delta_Upsilon is',time.time()-t0
def gen_ssmodel(self): '''Generates non-linear, Integro-Difference, discrete-time state space model. Atributes: ---------- Gamma: ndarray Inner product of field basis functions Gamma_inv: ndarray Inverse of Gamma Sigma_e: ndarray Covariance matrix of the field disturbance Sigma_e_inv: ndarray Inverse of Sigma_e Sigma_e_c: ndarray cholesky decomposiotion of field disturbance covariance matrix Sigma_varepsilon_c: ndarray cholesky decomposiotion of observation noise covariance matrix Phi_values: ndarray nx by number of spatial locations field basis functions values over the spatial field psi_conv_Phi_values: ndarray ; each ndarray is nx by number of spatial locations convolution of the connectivity kernel basis functions with the field basis functions evaluate over space Gamma_inv_psi_conv_Phi:ndarray; each ndarray is nx by number of spatial locations the product of inverse gamme withe psi0_conv_Phi C: ndarray Observation matrix Gamma_inv_Psi_conv_Phi: ndarray nx by number of spatial locations the convolution of the kernel with field basis functions at discritized spatial points ''' #Generate Gamma if hasattr(self,'Gamma'): pass else: t_total=time.time() #calculate Gamma=PhixPhi.T; inner product of the field basis functions Gamma=pb.dot(self.field.Phi,self.field.Phi.T) Gamma_inv=pb.inv(Gamma) self.Gamma=Gamma.astype('float') self.Gamma_inv=Gamma_inv #Generate field covariance matrix if hasattr(self,'Sigma_e'): pass else: gamma_convolution_vecrorized=pb.vectorize(self.gamma.conv) gamma_conv_Phi=gamma_convolution_vecrorized(self.field.Phi).T #[gamma*phi1 gamma*phi2 ... gamma*phin] 1 by nx Pi=pb.dot(self.field.Phi,gamma_conv_Phi) #nx by nx ndarray Pi=Pi.astype('float') Sigma_e=pb.dot(pb.dot(self.gamma_weight*Gamma_inv,Pi),Gamma_inv.T) Sigma_e_c=sp.linalg.cholesky(Sigma_e,lower=1) self.Sigma_e=Sigma_e self.Sigma_e_inv=pb.inv(Sigma_e) self.Sigma_e_c=Sigma_e_c Sigma_varepsilon_c=sp.linalg.cholesky(self.Sigma_varepsilon,lower=1) self.Sigma_varepsilon_c=Sigma_varepsilon_c if hasattr(self,'Phi_values'): pass else: #Generate field meshgrid estimation_field_space_x,estimation_field_space_y=pb.meshgrid(self.estimation_space_x_y,self.estimation_space_x_y) estimation_field_space_x=estimation_field_space_x.ravel() estimation_field_space_y=estimation_field_space_y.ravel() #calculate Phi_values #Phi_values is like [[phi1(r1) phi1(r2)...phi1(rn_r)],[phi2(r1) phi2(r2)...phi2(rn_r)],..[phiL(r1) phiL(r2)...phiL(rn_r)]] Phi_values=[self.field.Phi[i,0](estimation_field_space_x,estimation_field_space_y) for i in range(self.nx)] self.Phi_values=pb.squeeze(Phi_values) #it's nx by number of apatial points #vectorizing kernel convolution method psi_convolution_vectorized=pb.empty((self.n_theta,1),dtype=object) for i in range(self.n_theta): psi_convolution_vectorized[i,0]=pb.vectorize(self.kernel.Psi[i].conv) #find convolution between kernel and field basis functions analytically psi_conv_Phi=pb.empty((self.nx,self.n_theta),dtype=object)#nx by n_theta for i in range(self.n_theta): psi_conv_Phi[:,i]=psi_convolution_vectorized[i,0](self.field.Phi).ravel() #ecaluate convolution between kernel and field basis functions at spatial locations psi_conv_Phi_values=pb.empty((self.n_theta,self.nx,len(self.estimation_space_x_y)**2),dtype=float) for i in range(self.n_theta): for j in range(self.nx): psi_conv_Phi_values[i,j,:]=psi_conv_Phi[j,i](estimation_field_space_x,estimation_field_space_y) self.psi_conv_Phi_values=psi_conv_Phi_values self.Gamma_inv_psi_conv_Phi=pb.dot(self.Gamma_inv,self.psi_conv_Phi_values) #Calculate observation matrix if hasattr(self,'C'): pass else: #Generate Observation locations grid obs_locns_x=self.obs_locns[:,0] obs_locns_y=self.obs_locns[:,1] sensor_kernel_convolution_vecrorized=pb.vectorize(self.sensor_kernel.conv) sensor_kernel_conv_Phi=sensor_kernel_convolution_vecrorized(self.field.Phi).T #first row #[m*phi_1 m*phi2 ... m*phin] C=pb.empty(([self.ny,self.nx]),dtype=float) for i in range(self.nx): C[:,i]=sensor_kernel_conv_Phi[0,i](obs_locns_x,obs_locns_y) self.C=C print 'Elapsed time in seconds to generate the stat-space model',time.time()-t_total #We need to calculate this bit at each iteration #Finding the convolution of the kernel with field basis functions at discritized spatial points self.Gamma_inv_Psi_conv_Phi=pb.sum(self.kernel.weights[pb.newaxis,:,pb.newaxis]*self.Gamma_inv_psi_conv_Phi,axis=1)
def gen_ssmodel(self): '''Generates non-linear, Integro-Difference, discrete-time state space model. Atributes: ---------- Gamma: matrix Inner product of field basis functions Sigma_e: matrix Covariance matrix of the field disturbance Sigma_e_c: matrix cholesky decomposiotion of field disturbance covariance matrix Sigma_varepsilon_c: matrix cholesky decomposiotion of observation noise covariance matrix Phi_values: matrix field basis functions values over the spatial field psi0_conv_Phi_values: list convolution of the central excitatory connectivity kernel basis function with the field basis functions evaluate over space psi1_conv_Phi_values: list convolution of the surround inhibition connectivity kernel basis function with the field basis functions evaluate over space psi2_conv_Phi_values: list convolution of the longer range excitatory connectivity kernel basis function with the field basis functions evaluate over space C: matrix Observation matrix ''' print 'Generating state space model' # unpack the kernel psi0,psi1,psi2=self.kernel.Psi[0],self.kernel.Psi[1],self.kernel.Psi[2] psi0_weight,psi1_weight,psi2_weight=self.kernel.weights[0],self.kernel.weights[1],self.kernel.weights[2] #centers psi0_center=psi0.center psi1_center=psi1.center psi2_center=psi2.center #widths psi0_width=psi0.width psi1_width=psi1.width psi2_width=psi2.width #Generate Gamma if hasattr(self,'Gamma'): pass else: #calculate Gamma=PhixPhi.T; inner product of the field basis functions Gamma=pb.matrix(self.field.Phi*self.field.Phi.T,dtype=float) Gamma_inv=Gamma.I self.Gamma=Gamma self.Gamma_inv=Gamma_inv #Generate field covariance matrix and its Cholesky decomposition if hasattr(self,'Sigma_e'): pass else: gamma_convolution_vecrorized=pb.vectorize(self.gamma.conv) gamma_conv_Phi=gamma_convolution_vecrorized(self.field.Phi).T Pi=pb.matrix(self.field.Phi*gamma_conv_Phi,dtype=float) #nx by nx matrix Sigma_e=self.gamma_weight*Gamma_inv*Pi*Gamma_inv.T Sigma_e_c=pb.matrix(sp.linalg.cholesky(Sigma_e)).T self.Sigma_e=Sigma_e self.Sigma_e_c=Sigma_e_c #calculate Cholesky decomposition of observation noise covariance matrix Sigma_varepsilon_c=pb.matrix(sp.linalg.cholesky(self.Sigma_varepsilon)).T self.Sigma_varepsilon_c=Sigma_varepsilon_c if hasattr(self,'Phi_values'): pass else: #vectorizing convolution function of the kernel basis functions psi0_convolution_vectorized=pb.vectorize(psi0.conv) psi1_convolution_vectorized=pb.vectorize(psi1.conv) psi2_convolution_vectorized=pb.vectorize(psi2.conv) #convolving each kernel basis function with the field basis functions psi0_conv_Phi=psi0_convolution_vectorized(self.field.Phi) psi1_conv_Phi=psi1_convolution_vectorized(self.field.Phi) psi2_conv_Phi=psi2_convolution_vectorized(self.field.Phi) Psi_conv_Phi=pb.hstack((psi0_conv_Phi,psi1_conv_Phi,psi2_conv_Phi)) #Finding the convolution of the kernel basis functions with field basis functions at discritized spatial points psi0_conv_Phi_values=[] psi1_conv_Phi_values=[] psi2_conv_Phi_values=[] Phi_values=[] psi0_conv_Phi_values_temp=[] psi1_conv_Phi_values_temp=[] psi2_conv_Phi_values_temp=[] Phi_values_temp=[] t_Gamma_inv_Psi_sep=time.time() for m in range(self.nx): for i in self.field_space: for j in self.field_space: psi0_conv_Phi_values_temp.append(psi0_conv_Phi[m,0](pb.matrix([[i],[j]]))) psi1_conv_Phi_values_temp.append(psi1_conv_Phi[m,0](pb.matrix([[i],[j]]))) psi2_conv_Phi_values_temp.append(psi2_conv_Phi[m,0](pb.matrix([[i],[j]]))) Phi_values_temp.append(self.field.Phi[m,0](pb.matrix([[i],[j]]))) psi0_conv_Phi_values.append(psi0_conv_Phi_values_temp) psi1_conv_Phi_values.append(psi1_conv_Phi_values_temp) psi2_conv_Phi_values.append(psi2_conv_Phi_values_temp) Phi_values.append(Phi_values_temp) psi0_conv_Phi_values_temp=[] psi1_conv_Phi_values_temp=[] psi2_conv_Phi_values_temp=[] Phi_values_temp=[] Phi_values=pb.matrix(Phi_values) self.psi0_conv_Phi_values=psi0_conv_Phi_values self.psi1_conv_Phi_values=psi1_conv_Phi_values self.psi2_conv_Phi_values=psi2_conv_Phi_values self.Phi_values=Phi_values Gamma_inv_psi0_conv_Phi=self.Gamma_inv*psi0_conv_Phi_values Gamma_inv_psi1_conv_Phi=self.Gamma_inv*psi1_conv_Phi_values Gamma_inv_psi2_conv_Phi=self.Gamma_inv*psi2_conv_Phi_values self.Gamma_inv_psi0_conv_Phi=Gamma_inv_psi0_conv_Phi self.Gamma_inv_psi1_conv_Phi=Gamma_inv_psi1_conv_Phi self.Gamma_inv_psi2_conv_Phi=Gamma_inv_psi2_conv_Phi #Calculate observation matrix if hasattr(self,'C'): pass else: sensor_kernel_convolution_vecrorized=pb.vectorize(self.sensor_kernel.conv) sensor_kernel_conv_Phi=sensor_kernel_convolution_vecrorized(self.field.Phi).T sensor_kernel_conv_Phi_values_temp=[] sensor_kernel_conv_Phi_values=[] for m in range(self.nx): for n in self.obs_locns: sensor_kernel_conv_Phi_values_temp.append(sensor_kernel_conv_Phi[0,m](n)) sensor_kernel_conv_Phi_values.append(sensor_kernel_conv_Phi_values_temp) sensor_kernel_conv_Phi_values_temp=[] C=pb.matrix(pb.squeeze(sensor_kernel_conv_Phi_values).T) self.C=C #Finding the convolution of the kernel with field basis functions at discritized spatial points self.Gamma_inv_Psi_conv_Phi=psi0_weight*self.Gamma_inv_psi0_conv_Phi+ \ psi1_weight*self.Gamma_inv_psi1_conv_Phi+psi2_weight*self.Gamma_inv_psi2_conv_Phi