def createCellsFixedNum (self): ''' Create population cells based on fixed number of cells''' cells = [] seed(sim.id32('%d'%(sim.cfg.seeds['loc']+self.tags['numCells']+sim.net.lastGid))) randLocs = rand(self.tags['numCells'], 3) # create random x,y,z locations if sim.net.params.shape == 'cylinder': # Use the x,z random vales rho = randLocs[:,0] # use x rand value as the radius rho in the interval [0, 1) phi = 2 * pi * randLocs[:,2] # use z rand value as the angle phi in the interval [0, 2*pi) x = (1 + sqrt(rho) * cos(phi))/2.0 z = (1 + sqrt(rho) * sin(phi))/2.0 randLocs[:,0] = x randLocs[:,2] = z elif sim.net.params.shape == 'ellipsoid': # Use the x,y,z random vales rho = np.power(randLocs[:,0], 1.0/3.0) # use x rand value as the radius rho in the interval [0, 1); cuberoot phi = 2 * pi * randLocs[:,1] # use y rand value as the angle phi in the interval [0, 2*pi) costheta = (2 * randLocs[:,2]) - 1 # use z rand value as cos(theta) in the interval [-1, 1); ensures uniform dist theta = arccos(costheta) # obtain theta from cos(theta) x = (1 + rho * cos(phi) * sin(theta))/2.0 y = (1 + rho * sin(phi) * sin(theta))/2.0 z = (1 + rho * cos(theta))/2.0 randLocs[:,0] = x randLocs[:,1] = y randLocs[:,2] = z for icoord, coord in enumerate(['x', 'y', 'z']): if coord+'Range' in self.tags: # if user provided absolute range, convert to normalized self.tags[coord+'normRange'] = [float(point) / getattr(sim.net.params, 'size'+coord.upper()) for point in self.tags[coord+'Range']] # constrain to range set by user if coord+'normRange' in self.tags: # if normalized range, rescale random locations minv = self.tags[coord+'normRange'][0] maxv = self.tags[coord+'normRange'][1] randLocs[:,icoord] = randLocs[:,icoord] * (maxv-minv) + minv for i in self._distributeCells(int(sim.net.params.scale * self.tags['numCells']))[sim.rank]: gid = sim.net.lastGid+i self.cellGids.append(gid) # add gid list of cells belonging to this population - not needed? cellTags = {k: v for (k, v) in self.tags.iteritems() if k in sim.net.params.popTagsCopiedToCells} # copy all pop tags to cell tags, except those that are pop-specific cellTags['popLabel'] = self.tags['popLabel'] cellTags['xnorm'] = randLocs[i,0] # set x location (um) cellTags['ynorm'] = randLocs[i,1] # set y location (um) cellTags['znorm'] = randLocs[i,2] # set z location (um) cellTags['x'] = sim.net.params.sizeX * randLocs[i,0] # set x location (um) cellTags['y'] = sim.net.params.sizeY * randLocs[i,1] # set y location (um) cellTags['z'] = sim.net.params.sizeZ * randLocs[i,2] # set z location (um) cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object if sim.cfg.verbose: print('Cell %d/%d (gid=%d) of pop %s, on node %d, '%(i, sim.net.params.scale * self.tags['numCells']-1, gid, self.tags['popLabel'], sim.rank)) sim.net.lastGid = sim.net.lastGid + self.tags['numCells'] return cells
def plotimx(self, im): if self.type == "polygon": for reg in ("ap", "bg0", "bg1"): ci = self.imcoords(im, reg=reg) pl.plot(ci[:, 0], ci[:, 1]) elif self.type == "circle": n = 33 t = pl.arange(n) * pl.pi * 2 / n ct = pl.cos(t) st = pl.sin(t) for reg in ("ap", "bg0", "bg1"): ci = self.imcoords(im, reg=reg) #print "center of circle= %f %f" % ci[0:2] r = ci[2] # in pix pl.plot(ci[0] + r * ct, ci[1] + r * st) # point north: XXX TODO make general from astropy import wcs w = wcs.WCS(im.header) # use origin=0 i.e. NOT FITS convention, but pl.imshow sets origin # to 0,0 so do that here so we can overplot on pl.imshow axes origin = 0 c = self.bg1coords # only works below for circle ctr = w.wcs_world2pix([c[0:2]], origin)[0] # north ctr2 = w.wcs_world2pix([c[0:2] + pl.array([c[2], 0])], origin)[0] pl.plot([ctr[0], ctr2[0]], [ctr[1], ctr2[1]])
def setbgcoords(self): if self.type == None: raise Exception("region type=None - has it been set?") if self.type == "circle": if len(self.coords) != 3: raise Exception( "region coords should be ctr_ra, ctr_dec, rad_arcsec - the coord array has unexpected length %d" % len(self.coords)) self.bg0coords = pl.array(self.coords) self.bg1coords = pl.array(self.coords) # set larger radii for annulus self.bg0coords[2] = self.coords[2] * self.bgfact[0] self.bg1coords[2] = self.coords[2] * self.bgfact[1] elif self.type == "polygon": n = self.coords.shape[1] self.coords = pl.array(self.coords) ctr = [self.coords[:, 0].mean(), self.coords[:, 1].mean()] x = self.coords[:, 0] - ctr[0] y = self.coords[:, 1] - ctr[1] r = pl.sqrt(x**2 + y**2) th = pl.arctan2(y, x) ct = pl.cos(th) st = pl.sin(th) # inner and outer background regions b = self.bgfact self.bg0coords = pl.array([r * b[0] * ct, r * b[0] * st]).T + ctr self.bg1coords = pl.array([r * b[1] * ct, r * b[1] * st]).T + ctr else: raise Exception("unknown region type %s" % self.type)
def plotradec(self): if self.type == "polygon": pl.plot(self.coords[:, 0], self.coords[:, 1]) pl.plot(self.bg0coords[:, 0], self.bg0coords[:, 1]) pl.plot(self.bg1coords[:, 0], self.bg1coords[:, 1]) elif self.type == "circle": n = 23 t = pl.arange(n) * pl.pi * 2 / n r = self.coords[2] ct = pl.cos(t) st = pl.sin(t) cdec = pl.cos(self.coords[1] * pl.pi / 180) pl.plot(self.coords[0] + r * ct / cdec, self.coords[1] + r * st) r = self.bg0coords[2] pl.plot(self.bg0coords[0] + r * ct / cdec, self.bg0coords[1] + r * st) r = self.bg1coords[2] pl.plot(self.bg1coords[0] + r * ct / cdec, self.bg1coords[1] + r * st)
def _make_dct(self): """ :: Construct the discrete cosine transform coefficients for the current size of constant-Q transform """ DCT_OFFSET = self.lcoef nm = 1 / P.sqrt(self._cqtN / 2.0) self.DCT = P.empty((self._dctN, self._cqtN)) for i in P.arange(self._dctN): for j in P.arange(self._cqtN): self.DCT[i, j] = nm * P.cos(i * (2 * j + 1) * (P.pi / 2.0) / self._cqtN) for j in P.arange(self._cqtN): self.DCT[0, j] *= P.sqrt(2.0) / 2.0
def test_interp(): # Testing interpolation nn = 33 # number of nodes ne = 65 # number of evaluation points x = cos(pi*(1+array(range(nn)))/(nn+1)) xp = linspace(-1,1,ne) rbf_list = ['mq','gauss','phs'] ep_list = [3.,5.,7.,9.] m = 3 for ep in ep_list: for ff in rbf_list: # 1D d = array([x]).T p = array([xp]).T rhs = testfunction(d) exact = testfunction(p) Pf = rbfinterp(d,rhs,p,ff,shapeparm = ep, power = m) err = norm(Pf-exact) print("1D interp, {}, shape = {}, L2 error = {:e}".format(ff,ep,err)) # 2D d = array([x,x]).T p = array([xp,xp]).T rhs = testfunction(d) exact = testfunction(p) Pf = rbfinterp(d,rhs,p,ff,shapeparm = ep, power = m) err = norm(Pf-exact) print("2D interp, {}, shape = {}, L2 error = {:e}".format(ff,ep,err)) # 3D d = array([x,x,x]).T p = array([xp,xp,xp]).T rhs = testfunction(d) exact = testfunction(p) Pf = rbfinterp(d,rhs,p,ff,shapeparm = ep, power = m) err = norm(Pf-exact) print("3D interp, {}, shape = {}, L2 error = {:e}".format(ff,ep,err)) print("----------------------------------------------------------")
def createCellsDensity (self): ''' Create population cells based on density''' cells = [] shape = sim.net.params.shape sizeX = sim.net.params.sizeX sizeY = sim.net.params.sizeY sizeZ = sim.net.params.sizeZ # calculate volume if shape == 'cuboid': volume = sizeY/1e3 * sizeX/1e3 * sizeZ/1e3 elif shape == 'cylinder': volume = sizeY/1e3 * sizeX/1e3/2 * sizeZ/1e3/2 * pi elif shape == 'ellipsoid': volume = sizeY/1e3/2.0 * sizeX/1e3/2.0 * sizeZ/1e3/2.0 * pi * 4.0 / 3.0 for coord in ['x', 'y', 'z']: if coord+'Range' in self.tags: # if user provided absolute range, convert to normalized self.tags[coord+'normRange'] = [point / sim.net.params['size'+coord.upper()] for point in self.tags[coord+'Range']] if coord+'normRange' in self.tags: # if normalized range, rescale volume minv = self.tags[coord+'normRange'][0] maxv = self.tags[coord+'normRange'][1] volume = volume * (maxv-minv) funcLocs = None # start with no locations as a function of density function if isinstance(self.tags['density'], str): # check if density is given as a function if shape == 'cuboid': # only available for cuboids strFunc = self.tags['density'] # string containing function strVars = [var for var in ['xnorm', 'ynorm', 'znorm'] if var in strFunc] # get list of variables used if not len(strVars) == 1: print 'Error: density function (%s) for population %s does not include "xnorm", "ynorm" or "znorm"'%(strFunc,self.tags['popLabel']) return coordFunc = strVars[0] lambdaStr = 'lambda ' + coordFunc +': ' + strFunc # convert to lambda function densityFunc = eval(lambdaStr) minRange = self.tags[coordFunc+'Range'][0] maxRange = self.tags[coordFunc+'Range'][1] interval = 0.001 # interval of location values to evaluate func in order to find the max cell density maxDensity = max(map(densityFunc, (arange(minRange, maxRange, interval)))) # max cell density maxCells = volume * maxDensity # max number of cells based on max value of density func seed(sim.id32('%d' % sim.cfg.seeds['loc']+sim.net.lastGid)) # reset random number generator locsAll = minRange + ((maxRange-minRange)) * rand(int(maxCells), 1) # random location values locsProb = array(map(densityFunc, locsAll)) / maxDensity # calculate normalized density for each location value (used to prune) allrands = rand(len(locsProb)) # create an array of random numbers for checking each location pos makethiscell = locsProb>allrands # perform test to see whether or not this cell should be included (pruning based on density func) funcLocs = [locsAll[i] for i in range(len(locsAll)) if i in array(makethiscell.nonzero()[0],dtype='int')] # keep only subset of yfuncLocs based on density func self.tags['numCells'] = len(funcLocs) # final number of cells after pruning of location values based on density func if sim.cfg.verbose: print 'Volume=%.2f, maxDensity=%.2f, maxCells=%.0f, numCells=%.0f'%(volume, maxDensity, maxCells, self.tags['numCells']) else: print 'Error: Density functions are only implemented for cuboid shaped networks' exit(0) else: # NO ynorm-dep self.tags['numCells'] = int(self.tags['density'] * volume) # = density (cells/mm^3) * volume (mm^3) # calculate locations of cells seed(sim.id32('%d'%(sim.cfg.seeds['loc']+self.tags['numCells']+sim.net.lastGid))) randLocs = rand(self.tags['numCells'], 3) # create random x,y,z locations if sim.net.params.shape == 'cylinder': # Use the x,z random vales rho = randLocs[:,0] # use x rand value as the radius rho in the interval [0, 1) phi = 2 * pi * randLocs[:,2] # use z rand value as the angle phi in the interval [0, 2*pi) x = (1 + sqrt(rho) * cos(phi))/2.0 z = (1 + sqrt(rho) * sin(phi))/2.0 randLocs[:,0] = x randLocs[:,2] = z elif sim.net.params.shape == 'ellipsoid': # Use the x,y,z random vales rho = np.power(randLocs[:,0], 1.0/3.0) # use x rand value as the radius rho in the interval [0, 1); cuberoot phi = 2 * pi * randLocs[:,1] # use y rand value as the angle phi in the interval [0, 2*pi) costheta = (2 * randLocs[:,2]) - 1 # use z rand value as cos(theta) in the interval [-1, 1); ensures uniform dist theta = arccos(costheta) # obtain theta from cos(theta) x = (1 + rho * cos(phi) * sin(theta))/2.0 y = (1 + rho * sin(phi) * sin(theta))/2.0 z = (1 + rho * cos(theta))/2.0 randLocs[:,0] = x randLocs[:,1] = y randLocs[:,2] = z for icoord, coord in enumerate(['x', 'y', 'z']): if coord+'normRange' in self.tags: # if normalized range, rescale random locations minv = self.tags[coord+'normRange'][0] maxv = self.tags[coord+'normRange'][1] randLocs[:,icoord] = randLocs[:,icoord] * (maxv-minv) + minv if funcLocs and coordFunc == coord+'norm': # if locations for this coordinate calculated using density function randLocs[:,icoord] = funcLocs if sim.cfg.verbose and not funcLocs: print 'Volume=%.4f, density=%.2f, numCells=%.0f'%(volume, self.tags['density'], self.tags['numCells']) for i in self._distributeCells(self.tags['numCells'])[sim.rank]: gid = sim.net.lastGid+i self.cellGids.append(gid) # add gid list of cells belonging to this population - not needed? cellTags = {k: v for (k, v) in self.tags.iteritems() if k in sim.net.params.popTagsCopiedToCells} # copy all pop tags to cell tags, except those that are pop-specific cellTags['popLabel'] = self.tags['popLabel'] cellTags['xnorm'] = randLocs[i,0] # calculate x location (um) cellTags['ynorm'] = randLocs[i,1] # calculate y location (um) cellTags['znorm'] = randLocs[i,2] # calculate z location (um) cellTags['x'] = sizeX * randLocs[i,0] # calculate x location (um) cellTags['y'] = sizeY * randLocs[i,1] # calculate y location (um) cellTags['z'] = sizeZ * randLocs[i,2] # calculate z location (um) cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object if sim.cfg.verbose: print('Cell %d/%d (gid=%d) of pop %s, pos=(%2.f, %2.f, %2.f), on node %d, '%(i, self.tags['numCells']-1, gid, self.tags['popLabel'],cellTags['x'], cellTags['y'], cellTags['z'], sim.rank)) sim.net.lastGid = sim.net.lastGid + self.tags['numCells'] return cells
import matplotlib.pylab as pl import numpy as np x = np.linspace(-np.pi,np.pi,100) y = pl.sin(x) z = pl.cos(x) pl.plot(x,y,'r+',x,z,'k*') #import plot from pylab as pi and plot. pl.xlabel('time') pl.ylabel('value') pl.title('trogonometric data of $Sine(x)$ and $Cos(x)$') pl.show() #show the plot
import matplotlib.pylab as p from mpl_toolkits.mplot3d import Axes3D print("please be patient.....") delta = 0.1 x = p.arange(-3., 3., delta) y = p.arange(-3., 3., delta) X, Y = p.meshgrid(x, y) Z = p.sin(X) * p.cos(Y) fig = p.figure() ax = Axes3D(fig) ax.plot_surface(X, Y, Z) ax.plot_wireframe(X, Y, Z, color='r') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') p.show()
""" From "COMPUTATIONAL PHYSICS" & "COMPUTER PROBLEMS in PHYSICS" by RH Landau, MJ Paez, and CC Bordeianu (deceased) Copyright R Landau, Oregon State Unv, MJ Paez, Univ Antioquia, C Bordeianu, Univ Bucharest, 2018. Please respect copyright & acknowledge our work.""" # Simple3Dplot.py: matplotlib 3D plot, rotate & scale wi mouse import matplotlib.pylab as p from mpl_toolkits.mplot3d import Axes3D print("Please be patient while I do importing & plotting") delta = 0.1 x = p.arange(-3., 3., delta) y = p.arange(-3., 3., delta) X, Y = p.meshgrid(x, y) Z = p.sin(X) * p.cos(Y) # Surface height fig = p.figure() # Create figure ax = Axes3D(fig) # Plots axes ax.plot_surface(X, Y, Z) # Surface ax.plot_wireframe(X, Y, Z, color='r') # Add wireframe ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') p.show() # Output figure
from matplotlib import pylab as plt xaxis = plt.arange(0, plt.pi * 4, 0.1) plt.figure("sin() and cos() animation") for i in xaxis: series1 = plt.sin(xaxis - i) series2 = plt.cos(xaxis - i) # plt.subplot(211) plt.plot(xaxis, series1, "--", label="sin()") # plt.subplot(212) plt.plot(xaxis, series2, ":", label="cos()") plt.legend() plt.draw() #instead of plt.show() plt.pause(0.025) plt.clf()
def phot1(r, imlist, plot=True, names=None, panel=None, debug=None, showmask="both"): """ give me a region and an imlist and tell me whether to plot cutouts """ nim = len(imlist) # TODO alg for how many subpanels. if panel == None: panel = [5, 4, 1] # for vertical page f = [] df = [] raw = [] for j in range(nim): im = imlist[j] # if plotting, need to make image cutouts; even if not, this tells # us if the source is off the edge xtents = r.imextents(imlist[j]) minsize = 5 if (xtents[3] - xtents[1]) < minsize or (xtents[2] - xtents[0]) < minsize: raw0, f0, df0 = 0, 0, 0 print "phot region too small - %f,%f less than %d pixels" % ( (xtents[3] - xtents[1]), (xtents[2] - xtents[0]), minsize) print xtents, r.imcoords(im, reg="bg1") else: if plot: pl.subplot(panel[0], panel[1], panel[2]) im = hextract(imlist[j], xtents)[0] ## ROTATE rotate = True if rotate: from astropy import wcs w = wcs.WCS(im.header) from scipy.ndimage.interpolation import rotate if w.wcs.has_crota(): t0 = w.wcs.crota[1] else: t0 = pl.arctan2(w.wcs.cd[0, 1], -w.wcs.cd[0, 0]) * 180 / pl.pi theta = -1 * t0 im.data = rotate(im.data, theta, reshape=False) ct = pl.cos(pl.pi * theta / 180) st = pl.sin(pl.pi * theta / 180) if w.wcs.has_crota(): w.wcs.crota[1] = w.wcs.crota[1] + theta im.header['CROTA2'] = w.wcs.crota[1] print "rotating crota by " + str(theta) else: w.wcs.cd = pl.matrix(w.wcs.cd) * pl.matrix([[ct, -st], [st, ct]]) im.header['CD1_1'] = w.wcs.cd[0, 0] im.header['CD1_2'] = w.wcs.cd[0, 1] im.header['CD2_1'] = w.wcs.cd[1, 0] im.header['CD2_2'] = w.wcs.cd[1, 1] print "rotating cd by " + str(theta) #pdb.set_trace() # ugh need minmax of aperture region... # estimate as inner 1/2 for now s = im.shape z = im.data[int(s[0] * 0.25):int(s[0] * 0.75), int(s[1] * 0.25):int(s[1] * 0.75)] if len(z[0]) <= 0: print z z = pl.where(pl.isnan(im.data)) if len(z[0]) > 0: z = pl.where(pl.isnan(im.data) == False) std = im.data[z[0], z[1]].std() else: std = im.data.std() rg = pl.median(im.data) + pl.array([-0.5, 5]) * std # marta wants them less saturated rg[1] = pl.nanmax(im.data) if rg[0] < 0: rg[0] = 0 if rg[1] <= rg[0]: rg = [pl.nanmin(z), pl.nanmax(z)] if showmask == False or showmask == "both": # show the jet one pl.imshow(im.data, origin="bottom", interpolation="nearest", vmin=rg[0], vmax=rg[1]) elif showmask == True: # only show the mask pl.imshow(im.data, origin="bottom", interpolation="nearest", vmin=rg[0], vmax=rg[1], cmap="YlGn") ax = pl.gca() ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) if names: pl.text(0.05, 0.99, names[j], horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, bbox=dict(facecolor='white', alpha=0.5)) pl.xlim([-0.5, s[1] - 0.5]) pl.ylim([-0.5, s[0] - 0.5]) if showmask == False: r.plotimx(im) # overplot the apertures if showmask == "both": panel[2] = panel[2] + 1 pl.subplot(panel[0], panel[1], panel[2]) rg = pl.median(im.data) + pl.array([-0.5, 5]) * std if rg[0] < 0: rg[0] = 0 if rg[1] <= rg[0]: rg = [pl.nanmin(z), pl.nanmax(z)] pl.imshow(im.data, origin="bottom", interpolation="nearest", vmin=rg[0], vmax=rg[1], cmap="YlGn") ax = pl.gca() ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) if names: pl.text(0.05, 0.99, names[j], horizontalalignment='left', verticalalignment='top', transform=ax.transAxes, bbox=dict(facecolor='white', alpha=0.5)) pl.xlim([-0.5, s[1] - 0.5]) pl.ylim([-0.5, s[0] - 0.5]) if debug: # r.debug=True if names: print names[j] raw0, bg, f0, df0 = r.phot(im) raw.append(raw0) f.append(f0) df.append(df0) panel[2] = panel[2] + 1 if plot: pl.subplots_adjust(wspace=0.02, hspace=0.02, left=0.1, right=0.97, top=0.95, bottom=0.05) return f, df, raw
#print(C) #9 - Add C to B (think of C as noise) and record the result in D D = B + C[:len(B), ] # capture 500 elements from C to match to size of B #print(D) #SORT IT prior to plotting #Part 2 - plotting: #10 - Create a figure, give it a title and specify your own size and dpi plb.figure('Plotting signals', figsize=(6, 4), dpi=100) #11 - Plot the sin of D, in the (2,1,1) location of the figure #12 - Overlay a plot of cos using D, with different color, thickness and type of line plb.subplot(2, 1, 1) d_sin = plb.sin(D) d_cos = plb.cos(D) plb.title("Function of Sin and Cos") plb.plot(D, d_sin, color="b", linewidth=1.5, linestyle="--", label='sin') plb.plot(D, d_cos, color="r", linewidth=1, linestyle="-.", label='cos') #13. Create some space on top and bottom of the plot (on the y axis) and show the grid plb.ylim(-1.12, 1.12) plb.grid() #14 - Specify the following: title, Y-axis label and legend to fit in the best way plb.ylabel('Y-axis') plb.title('Signals') plb.legend(loc='best') #15. Plot the tan of D, in location (2,1,2) with grid showing, X-axis label, Y-axis label and #legend on top right