def campana(f0, A0, I0, duracion, fsampl): ts = pyl.arange(0, duracion, 1 / fsampl) # creo el espacio temporal Tao = duracion / 3 fc = f0 fm = 2 * f0 I_t = I0 * pyl.exp(-ts / Tao) # para la campana A_t = A0 * pyl.exp(-ts / Tao) # para la campana ym = pyl.sin(2 * pyl.pi * fm * ts) # función modulada # Señal FM final con sus componentes que varían en el tiempo yc = A_t * pyl.sin(2 * pyl.pi * fc * ts + (I_t * ym)) return yc
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 violin(f0, A0, I0, duracion, fsampl): fc = 2 * f0 fm = 3 * f0 ts = pyl.arange(0, duracion, 1 / fsampl) # creo el espacio temporal [A_t, I_t] = clarinet_funct(0.2 * duracion, 0.7 * duracion, 0.1 * duracion, fsampl, A0, I0) # el ataque es igual ts = ts[:len( A_t )] # pongo todos los tiempos con la misma cant de puntos (Tengo que ver de hacerlo mejor) ym = pyl.sin(2 * pyl.pi * fm * ts) # función modulada # Señal FM final con sus componentes que varían en el tiempo yc = A_t * pyl.sin(2 * pyl.pi * fc * ts + (I_t * ym)) return yc
def custom_modulation(fc, bits, add_first_bit): # this custom ASK modulation (amplitude-shift modulation) is for support # for CDMA, in this case: 0, -2, 2. Each number will have certain amplitude lenghtBits = len(bits) final_time = lenghtBits / 2 global ts ts = pyl.arange(0, final_time, sampling_period) global lenghtChunk lenghtChunk = int(len(ts) / lenghtBits) global A A = [] if (add_first_bit): # When add_first_bit is activated, a "2" bit is added # at the beginning of the data ts = pyl.arange(0, final_time + 0.5, sampling_period) for j in range(lenghtChunk): A.append(5) for i in range(lenghtBits): for j in range(lenghtChunk): A_for_Bit_i = 0 if (bits[i] == 0): A_for_Bit_i = 0 elif (bits[i] == 2): A_for_Bit_i = 5 elif (bits[i] == -2): A_for_Bit_i = 1 A.append(A_for_Bit_i) return A * pyl.sin(2.0 * pyl.pi * fc * ts)
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 main(): pl.ion() # interactive mode fig1 = pl.figure() ax1 = fig1.add_axes([0.1, 0.1, 0.8, 0.8]) pl.draw() ax1.plot(pl.arange(5), [30, 40, 55, 80, 100]) pl.draw() ax1.set_xlabel('x') ax1.set_ylabel('y') pl.draw() for label in ax1.get_xticklabels(): label.set_color('red') pl.draw() for label in ax1.get_yticklabels(): label.set_color('green') pl.draw() ax1.grid(True) pl.draw() ax1.patch.set_facecolor('yellow') pl.draw() fig2 = pl.figure() pl.draw() ax2 = fig2.add_axes([0.1, 0.1, 0.8, 0.8]) pl.draw() t = pl.arange(0.0, 1.0, 0.01) s = pl.sin(2 * pl.pi * t) ax2.plot(t, s, color='blue', lw=2) pl.draw() print "done"
def noise(noise_fun=pylab.rand, **params): """ :: Generate noise according to params dict params - parameter dict containing sr, and num_harmonics elements [None=default_noise_params()] noise_fun - the noise generating function [pylab.rand] """ params = _check_noise_params(**params) noise_dB = params['noise_dB'] num_harmonics = params['num_harmonics'] num_points = params['num_points'] cf = params['cf'] bw = params['bw'] sr = params['sr'] g = 10**(noise_dB / 20.0) * noise_fun(num_points) [b, a] = scipy.signal.filter_design.butter(4, bw * 2 * pylab.pi / sr, btype='low', analog=0, output='ba') g = scipy.signal.lfilter(b, a, g) # Phase modulation with *filtered* noise (side-band modulation should be narrow-band at bw) x = pylab.sin((2.0 * pylab.pi * cf / sr) * pylab.arange(num_points) + g) return x
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 getOOKModulation(ts, fc, bits): lenghtBits = len(bits) lenghtChunk = int(len(ts) / lenghtBits) A = [] for i in range(lenghtBits): for j in range(lenghtChunk): A_for_Bit_i = bits[i] A.append(A_for_Bit_i) return A * pyl.sin(2.0 * pyl.pi * fc * ts)
def sinusoid(**params): """ :: Generate a sinusoidal audio signal from signal_params: see default_signal_params() **params - signal_params dict, see default_signal_params() """ params = _check_signal_params(**params) t = pylab.arange(params['num_points']) x = pylab.sin(TWO_PI * params['f0'] / params['sr'] * t + params['phase_offset']) return x
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 get_4PAM_modulation(ts, fc, bits): lenghtBits = len(bits) lenghtChunk = 2 * len(ts) // lenghtBits # Chunks now are double sized A = [] # Amplitudes currentBit = 0 while (currentBit < lenghtBits): oneBit = bits[currentBit] currentBit += 1 anotherBit = bits[currentBit] currentBit += 1 for j in range(lenghtChunk): A_for_current_bits = 0 if (oneBit == 0 and anotherBit == 0): # 00 A_for_current_bits = 0 elif (oneBit == 0 and anotherBit == 1): # 01 A_for_current_bits = 0.5 elif (oneBit == 1 and anotherBit == 0): # 10 A_for_current_bits = 2 else: # 11 A_for_current_bits = 4 A.append(A_for_current_bits) return A * pyl.sin(2.0 * pyl.pi * fc * ts)
from math import pi from matplotlib import pylab as pl x = pl.linspace(-pi, pi, 200) y = pl.sin(x) y1 = pl.sin(x * x) pl.plot(x, y) pl.plot(x, y1, 'r') pl.show()
C = array(C) #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
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
from matplotlib import rc import matplotlib.pylab as plt rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) rc('text', usetex=True) x = plt.linspace(0, 5) plt.plot(x, plt.sin(x)) plt.ylabel(r"This is $\sin(x)$", size=20) plt.show()
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
Do the following: 1) Encode the signal ym by varying the frequency (fc) of the sinusoid Yc using FM modulation 2) Decode whatever information is represented by the varying frequency of Yc using FM de-modulation . """ import matplotlib.pylab as pyl # time between samples sampling_period = 0.0001 ts = pyl.arange(0, 1, sampling_period) # This is the modulating signal (Think slider position See video) ym = pyl.sin(2.0 * pyl.pi * 1.0 * ts) # High frequency carrier with slider pos encoded into it's frequency # Demod doesn't solve for negative values, so make information signal positve ym = ym + 1 # Carrier properties fc = 100.0 # Let T represent the period T = 1 / fc mod_fact = 1.0 / 100.0 original_theta = 2.0 * pyl.pi * (fc + mod_fact * ym) * ts yc = pyl.sin(original_theta)
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()
#line, = plt.plot(x, '--', linewidth=2) # #dashes = [10, 5, 100, 5] # 10 points on, 5 off, 100 on, 5 off #line.set_dashes(dashes) # #plt.show() # # ----------------------------- New Test ------------------------------------- # import matplotlib.pylab as plt fs = 512 t = plt.arange(0.0, 2.0, 1 / fs) s = plt.sin(250 * plt.pi * t) plt.figure() plt.plot(t, s) plt.xlabel('time (s)') plt.ylabel('voltage (mV)') plt.title('About as simple as it gets, folks') plt.grid(True) # plt.savefig("test.png") plt.show() # -------------------------------------------------------------- # 3d print script test # Method 1: # http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html
""" 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()
from matplotlib import pylab as plt # xseries = list(range(0, 30)) -> replace for better plot of sin() function xseries = plt.arange(0, 30, 0.1) # print(xseries) series1 = [] series2 = [] series3 = plt.sin(xseries) maxvalues_xaxis = plt.arange(plt.pi / 2, 30, plt.pi) maxvalues_yaxis = plt.sin(maxvalues_xaxis) for i in xseries: series1.append(i) series2.append(i / 2) # Create individual figures using subplot() plt.subplot(211) # xyz -> row, column, position plt.plot(xseries, series1, label="Faster Linear Progression") plt.plot(xseries, series2, "y:", label="Slower Linear Progression") plt.legend() plt.subplot(212) # xyz -> row, column, position # style(color(r, g, b, c, m, y, k), line(:, --), marker(^)) plt.plot(xseries, series3, "k--", label="sin() function") plt.plot(maxvalues_xaxis, maxvalues_yaxis, "r^",
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import matplotlib.pylab as pyl sampling_period = 0.0001 ts = pyl.arange(0, 1, sampling_period) ym = pyl.sin(2.0 * pyl.pi * 1.0 * ts) fc = 100.0 mod_fact = 15.0 yc = pyl.sin(2.0 * pyl.pi * (fc + mod_fact * ym) * ts) pyl.plot(ts, yc) pyl.show()
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