def direct2cartesian(self): """Convert atom coordinates from direct to cartesian""" if self.cartesian: return self.atoms = m.transpose(m.dot(self.lattice_constant*self.basis_vectors, \ m.transpose(self.atoms))) self.cartesian = True
def rotate_molecule(coords, rotp = m.array((0.,0.,0.)), phi = 0., \ theta = 0., psi = 0.): """Rotate a molecule via Euler angles. See http://mathworld.wolfram.com/EulerAngles.html for definition. Input arguments: coords: Atom coordinates, as Nx3 2d pylab array. rotp: The point to rotate about, as a 1d 3-element pylab array phi: The 1st rotation angle around z axis. theta: Rotation around x axis. psi: 2nd rotation around z axis. """ # First move the molecule to the origin # In contrast to MATLAB, numpy broadcasts the smaller array to the larger # row-wise, so there is no need to play with the Kronecker product. rcoords = coords - rotp # First Euler rotation about z in matrix form D = m.array(((m.cos(phi), m.sin(phi), 0.), (-m.sin(phi), m.cos(phi), 0.), \ (0., 0., 1.))) # Second Euler rotation about x: C = m.array(((1., 0., 0.), (0., m.cos(theta), m.sin(theta)), \ (0., -m.sin(theta), m.cos(theta)))) # Third Euler rotation, 2nd rotation about z: B = m.array(((m.cos(psi), m.sin(psi), 0.), (-m.sin(psi), m.cos(psi), 0.), \ (0., 0., 1.))) # Total Euler rotation A = m.dot(B, m.dot(C, D)) # Do the rotation rcoords = m.dot(A, m.transpose(rcoords)) # Move back to the rotation point return m.transpose(rcoords) + rotp
def plotEnsemble2D(ens,v1,v2,colordata=None,hess=None,\ size=50,labelBest=True,ensembleAlpha=0.75,contourAlpha=1.0): """ Plots a 2-dimensional projection of a given parameter ensemble, along given directions: -- If v1 and v2 are scalars, project onto plane given by those two bare parameter directions. -- If v1 and v2 are vectors, project onto those two vectors. When given colordata (either a single color, or an array of different colors the length of ensemble size), each point will be assigned a color based on the colordata. With labelBest set, the first point in the ensemble is plotted larger (to show the 'best fit' point for a usual parameter ensemble). If a Hessian is given, cost contours will be plotted using plotContours2D. """ if pylab.shape(v1) is (): xdata = pylab.transpose(ens)[v1] ydata = pylab.transpose(ens)[v2] # label axes param1name, param2name = '','' try: paramLabels = ens[0].keys() except: paramLabels = None if paramLabels is not None: param1name = ' ('+paramLabels[param1]+')' param2name = ' ('+paramLabels[param2]+')' pylab.xlabel('Parameter '+str(v1)+param1name) pylab.ylabel('Parameter '+str(v2)+param2name) else: xdata = pylab.dot(ens,v1) ydata = pylab.dot(ens,v2) if colordata==None: colordata = pylab.ones(len(xdata)) if labelBest: # plot first as larger circle if pylab.shape(colordata) is (): # single color colordata0 = colordata colordataRest = colordata else: # specified colors colordata0 = [colordata[0]] colordataRest = colordata[1:] scatterColors(xdata[1:],ydata[1:],colordataRest, \ size,alpha=ensembleAlpha) scatterColors([xdata[0]],[ydata[0]],colordata0, \ size*4,alpha=ensembleAlpha) else: scatterColors(xdata,ydata,colordata,size,alpha=ensembleAlpha) if hess is not None: plotApproxContours2D(hess,param1,param2,pylab.array(ens[0]), \ alpha=contourAlpha)
def cartesian2direct(self): """Convert atom coordinates from cartesian to direct""" if not self.cartesian: return self.atoms = m.transpose(m.linalg.solve(self.lattice_constant * \ self.basis_vectors, \ m.transpose(self.atoms))) self.cartesian = False
def save_rsj_params(self): mat = pl.vstack((pl.array(self.idx), pl.transpose(self.c),\ self.icarr, self.rnarr, self.ioarr, self.voarr,\ self.ic_err_arr, self.rn_err_arr, self.io_err_arr, self.vo_err_arr)) header_c = '' for n in range(self.cdim): header_c = header_c + 'Control%d '%(n+1) header_ = 'Index ' + header_c + \ 'Ic Rn Io Vo Ic_err Rn_err Io_err Vo_err' pl.savetxt(self.get_fullpath(self.fn_rsjparams), pl.transpose(mat),\ header=header_)
def degraderesolution(prefix,factor,dlogstring): covar = M.load(prefix+'covar.dat') pnl = M.load(prefix+'pnl.dat') dlog = M.load(prefix+dlogstring)[:,1] k = pnl[:,0]*1. p = pnl[:,1]*1. gausspart = M.load(prefix+'gausspart.dat') nbins = len(k) nongausspart = covar - gausspart nongausspartnew = nongausspart[:nbins-factor:factor,:nbins-factor:factor]*0. knew = k[:nbins-factor:factor]*0. pnew = p[:nbins-factor:factor]*0. gausspartnew = gausspart[:nbins-factor:factor,:nbins-factor:factor]*0. nbinsnew = len(knew) dlognew = dlog[:nbins-factor:factor]*0. for i1 in range(0,nbins-factor,factor): i1new = i1/factor print i1,i1+factor-1,nbins print i1new,nbinsnew weights = k[i1:i1+factor-1]**3 sumweights = M.sum(weights) pnew[i1new] = M.sum(p[i1:i1+factor-1]*weights)/sumweights knew[i1new] = M.sum(k[i1:i1+factor-1]*weights)/sumweights dlognew[i1new] = M.sum(dlog[i1:i1+factor-1]*weights)/sumweights sqrtkfact = M.sqrt(k[1]/k[0]) for i1 in range(0,nbins-factor,factor): i1new = i1/factor for i2 in range(0,nbins-factor,factor): i2new = i2/factor weights2 = M.outer(k[i1:i1+factor-1]**3,k[i2:i2+factor-1]**3) sumweights2 = M.sum(M.sum(weights2)) nongausspartnew[i1new,i2new] = M.sum(M.sum(nongausspart[i1:i1+factor-1,i2:i2+factor-1]*weights2))/sumweights2 if i1new == i2new: vk = (4.*M.pi/3.)*((k[i1+factor-1]*sqrtkfact)**3 - (k[i1]/sqrtkfact)**3) gausspartnew[i1new,i2new] = (2.*M.pi)**3 * 2.*(pnew[i1new]**2)/vk covarnew = gausspartnew + nongausspartnew prefixnew = prefix+'degrade'+str(factor)+'/' os.system('mkdir '+prefixnew) M.save(prefixnew+'pnl.dat',M.transpose([knew,pnew]), fmt = '%18.16e') M.save(prefixnew+'covar.dat',covarnew, fmt = '%18.16e') M.save(prefixnew+'gausspart.dat',gausspartnew, fmt = '%18.16e') M.save(prefixnew+dlogstring,M.transpose([knew,dlognew]), fmt = '%18.16e') M.save(prefix+'nbins.dat',M.array([nbinsnew],shape=(1,1,)), fmt = '%d')
def Q_calc(self,X): """ calculates Q (n_x by n_theta) matrix of the IDE model at each time step Arguments ---------- X: list of ndarray state vectors Returns --------- Q : list of ndarray (n_x by n_theta) """ Q=[] T=len(X) Psi=self.model.Gamma_inv_psi_conv_Phi Psi_T=pb.transpose(self.model.Gamma_inv_psi_conv_Phi,(0,2,1)) for t in range(T): firing_rate_temp=pb.dot(X[t].T,self.model.Phi_values) firing_rate=self.model.act_fun.fmax/(1.+pb.exp(self.model.act_fun.varsigma*(self.model.act_fun.v0-firing_rate_temp))) #calculate q g=pb.dot(firing_rate,Psi_T) g *=(self.model.spacestep**2) q=self.model.Ts*g q=q.reshape(self.model.nx,self.model.n_theta) Q.append(q) return Q
def f(filename, theClass=1): fs, data = wavfile.read(filename) # load the data # b=[(ele/2**8.)*2-1 for ele in data] # this is 8-bit track, b is now normalized on [-1,1) print "Sample rates is: " print fs X = stft(data, fs, 256.0 / fs, 256.0 / fs) X = X[:, 0:(X.shape[1] / 2)] shortTimeFFT = scipy.absolute(X.T) shortTimeFFT = scipy.log10(shortTimeFFT) # Plot the magnitude spectrogram. pylab.figure() pylab.imshow(shortTimeFFT, origin='lower', aspect='auto', interpolation='nearest') pylab.xlabel('Time') pylab.ylabel('Frequency') savefig(filename + 'SFFT.png', bbox_inches='tight') features = mean(shortTimeFFT, axis=1) pylab.figure() pylab.plot(features, 'r') savefig(filename + 'AFFT.png', bbox_inches='tight') with open(filename + '.csv', 'w') as fp: a = csv.writer(fp, delimiter=',') row = pylab.transpose(features) row = pylab.append(row, theClass) a.writerow(row)
def loadMNISTImages(filename): f = open(filename, 'rb') # Verify Magic Number s = f.read(4) magic = int(s.encode('hex'),16) assert(magic == 2051) # Get Number of Images s = f.read(4) numImages = int(s.encode('hex'),16) s = f.read(4) numRows = int(s.encode('hex'),16) s = f.read(4) numCols = int(s.encode('hex'),16) # Get Data s = f.read() a = frombuffer(s, uint8) # Use 'F' to ensure that we read by column a = reshape(a, (numCols , numRows, numImages), order='F'); images = transpose(a, (1, 0, 2)) f.close() # Reshape to #pixels * #examples images = reshape(a, (shape(images)[0] * shape(images)[1], numImages), order='F'); images = double(images)/255 return images
def load_data(filename=None, datastr=None, skip_rows=False,use_cols=False): """Load a file with numeric column data into a numpy array. Automatically skips header unless "skip_rows" is specified. Loads all columns unless "use_cols" is specified.""" if filename is not None: textiter = open(filename, 'r') else: textiter = iter(datastr.split("\n")) #datare=re.compile('\s*(-?\d+(\.\d+)?([Ee][+-]?\d+)?(\s+|$)){2,}') if skip_rows == False: skip_rows=0 nx=textiter.next() while datare.match(nx)==None: # print "skipping row ", skip_rows skip_rows+=1 print nx nx=textiter.next() if filename is not None: textiter.close() textiter = open(filename, 'r') # else: # textiter=iter(datastr.split("\n")) if use_cols: tmp_data=load(textiter,datastr,skiprows=skip_rows,usecols=use_cols) else: tmp_data=load(textiter,datastr,skiprows=skip_rows) if filename is not None: textiter.close() return transpose(tmp_data)
def Global_Stiffness(self): ''' Generates Global Stiffness Matrix for the plane structure ''' elem = self.element; B = py.zeros((6,6)) for i in range (0,py.size(elem,0)): #for each element find the stifness matrix K = py.zeros((self.n_nodes*2,self.n_nodes*2)) el = elem[i] #nodes formatted for input [node1, node2, node3] = el; node1x = 2*(node1-1);node2x = 2*(node2-1);node3x = 2*(node3-1); node1y = 2*(node1-1)+1;node2y = 2*(node2-1)+1;node3y = 2*(node3-1)+1; #Area, Strain Matrix and E Matrix multiplied to get element stiffness [J,B] = self.B(el) local_k =0.5*abs(J)*py.dot(py.transpose(B),py.dot(self.E_matrix,B)) if self.debug: print 'K for elem', el, '\n', local_k #Element K-Matrix converted into Global K-Matrix format K[py.ix_([node1x,node1y,node2x,node2y,node3x,node3y],[node1x,node1y,node2x,node2y,node3x,node3y])] = K[py.ix_([node1x,node1y,node2x,node2y,node3x,node3y],[node1x,node1y,node2x,node2y,node3x,node3y])]+local_k #Adding contibution into Global Stiffness self.k_global = self.k_global + K if self.debug: print 'Global Stiffness','\n', self.k_global
def read_all_csc(data_folder, dtype='int16', assume_same_fs=True, memmap=False, memmap_folder=None, save_for_spikedetekt=False, channels_to_save=None, return_sliced_data=False): if sys.version_info[0] > 2: mode = 'br' else: mode = 'r' os_name = platform.system() if os_name == 'Windows': sep = '\\' elif os_name=='Linux': sep = r'/' files = [os.path.join(data_folder, f) for f in os.listdir(data_folder) if f.endswith('.ncs')] order = [int(file.split('.')[0].split('CSC')[1]) for file in files] sort_order = sorted(range(len(order)),key=order.__getitem__) ordered_files = [files[i] for i in sort_order] if memmap: if not memmap_folder: raise NameError("A memmap_folder should be defined for memmapped data") out_filename = data_folder.split(sep)[-1]+'.dat' out_full_filename = os.path.join(memmap_folder, out_filename) data = None i = 0; for file in ordered_files: fin = open(file, mode=mode) x = read_single_csc(fin, assume_same_fs=assume_same_fs, memmap=memmap) if not assume_same_fs or memmap: channel_data = x['packets']['samp'].ravel() if data is None: data = pylab.memmap(out_full_filename, dtype=dtype, mode='w+', shape=(pylab.size(files), channel_data.size)) else: data[i,:] = channel_data data.flush() i = i+1 print(i) else: channel_data = x['trace'] if data is None: data = pylab.zeros(shape=(pylab.size(files), channel_data.size), dtype=dtype) else: data[i,:] = channel_data i = i+1 print(i) data_to_return = data if save_for_spikedetekt: if channels_to_save: data2 = data[channels_to_save,:] if return_sliced_data: data_to_return = data2 else: data2 = data data2 = pylab.transpose(data2) data2.reshape(data2.size) filename = os.path.join(memmap_folder, 'spikedetekt_'+out_filename) data2.astype(dtype).tofile(filename) return data_to_return
def datagen(N): """ Produces N pairs of training data and desired output; each sample of training data contains -1 in its first position, this corresponds to the interpretation of the threshold as first element of the weight vector """ fun1 = lambda x1,x2: -2*x1**3-x2+.5*x1**2 fun2 = lambda x1,x2: x1**2*x2+2*x1*x2+1 fun3 = lambda x1,x2: .5*x1*x2**2+x2**2-2*x1**2 rarr1 = rand(1,N) rarr2 = rand(1,N) teacher = sign(rand(1,N)-.5) idplus = (teacher<0) idminus = -idplus rarr1[idplus] = rarr1[idplus]-1 y1=fun1(rarr1,rarr2) y2=fun2(rarr1,rarr2) y3=fun3(rarr1,rarr2) x=transpose(concatenate((-ones((1,N)),y1,y2))) return x, teacher[0]
def f(filename, theClass=1): fs, data = wavfile.read(filename) # load the data # b=[(ele/2**8.)*2-1 for ele in data] # this is 8-bit track, b is now normalized on [-1,1) print "Sample rates is: " print fs X = stft(data, fs, 256.0 / fs, 256.0 / fs) X = X[:, 0 : (X.shape[1] / 2)] shortTimeFFT = scipy.absolute(X.T) shortTimeFFT = scipy.log10(shortTimeFFT) # Plot the magnitude spectrogram. pylab.figure() pylab.imshow(shortTimeFFT, origin="lower", aspect="auto", interpolation="nearest") pylab.xlabel("Time") pylab.ylabel("Frequency") savefig(filename + "SFFT.png", bbox_inches="tight") features = mean(shortTimeFFT, axis=1) pylab.figure() pylab.plot(features, "r") savefig(filename + "AFFT.png", bbox_inches="tight") with open(filename + ".csv", "w") as fp: a = csv.writer(fp, delimiter=",") row = pylab.transpose(features) row = pylab.append(row, theClass) a.writerow(row)
def datafit2ah_ic_rn(self, tn): self.read_rsj_params(step=self.step) self.tnarr = pl.ones(self.ndata2) * tn guess_arr = pl.transpose( pl.array( [self.icarr, self.rnarr, self.ioarr, self.voarr, self.tnarr])) self.fit2ah_ic_rn_array(guess_arr, self.reportprog)
def solve(f1, f2, f3, f4, a, b, h, tol, max_steps): """ uxx(x,yt) + uyy(x,y) = 0 on R = {(x,y): 0 <= x <= a, 0 <= y <= b}, u(x,0) = f1(x), u(x,b) = f2(x) for 0 <= x <= a, u(0,y) = f3(y), u(a,y) = f4(y) for 0 <= y <= b, :param f1: u(x,0) :param f2: u(x,b) :param f3: u(0,y) :param f4: u(a,y) :param a: right boundary for x :param b: right boundary for y :param h: step :param tol: maximum delta :param max_steps: max count of steps :return: x - vector of x coordinates, y - vector of y coordinates, u - result (matrix of z coordinates) """ # initialize parameters in u n = int(a / h) + 1 m = int(b / h) + 1 ave = (a * (f1(0) + f2(0)) + b * (f3(0) + f4(0))) / (2 * a + 2 * b) u = ave * pylab.ones((n, m)) # boundary conditions u[0, :] = [f3(i * h) for i in range(0, m)] u[n - 1, :] = [f4(i * h) for i in range(0, m)] u[:, 0] = [f1(i * h) for i in range(0, n)] u[:, m - 1] = [f2(i * h) for i in range(0, n)] u[0, 0] = (u[0, 1] + u[1, 0]) / 2 u[0, m - 1] = (u[0, m - 2] + u[1, m - 1]) / 2 u[n - 1, 0] = (u[n - 2, 0] + u[n - 1, 1]) / 2 u[n - 1, m - 1] = (u[n - 2, m - 1] + u[n - 1, m - 2]) / 2 # The parameter of consistent method of relax w = 4 / (2 + math.sqrt(4 - (math.cos(math.pi / (n - 1)) + math.cos(math.pi / (m - 1)))**2)) # Improved approximation operator purification throughout the lattice error = 1 count = 0 while error > tol and count <= max_steps: error = 0 for j in range(1, m - 1): for i in range(1, n - 1): relax = w * (u[i][j + 1] + u[i][j - 1] + u[i + 1][j] + u[i - 1, j] - 4 * u[i][j]) / 4 u[i, j] += relax if error <= math.fabs(relax): error = math.fabs(relax) count += 1 x = [i * h for i in range(n)] y = [i * h for i in range(m)] u = pylab.flipud(pylab.transpose(u)) return x, y, u
def load_data(directory, file_): # load the data matrix from the data file data = loadtxt(directory + "data/" + file_ + ".txt", unpack=True) if type(data[0]) is float64: # check if the first column is a column data = array(transpose(matrix(data))) return data
def save_ah_params(self, n): n += 1 mat = pl.vstack((pl.array(self.idx)[:n], pl.transpose(self.c[:n]),\ self.icarr[:n], self.rnarr[:n], self.ioarr[:n], self.voarr[:n],\ self.tnarr[:n],\ self.ic_err_arr[:n], self.rn_err_arr[:n], self.io_err_arr[:n],\ self.vo_err_arr[:n], self.tn_err_arr[:n])) n -= 1 header_c = '' for m in range(self.cdim): header_c = header_c + 'Control%d '%(m+1) header_ = 'Index ' + header_c + \ 'Ic Rn Io Vo Tn Ic_err Rn_err Io_err Vo_err Tn_err' pl.savetxt(self.get_fullpath(self.fn_ahparams), pl.transpose(mat),\ header=header_)
def getInfoCurve(): """ Various functions to calculate example parameter error bars as in Neyrinck & Szapudi 2007, MNRAS 375, L51 """ c = pt.Camb(hubble = 70., ombh2 = 0.05*(0.7)**2, omch2 = 0.25*(0.7)**2) c.run() c.kextend(-10,60) # necessary to make sigma(m) integral converge well. pt.normalizePk(c,0.8) #sigma_8 outputdir = 'example/' #Sheth-Tormen h = halo.HaloModel(c,st_big_a = 0., st_little_a=0.707, stq = 0.3, k = 10.**M.arange(-2,1.01,0.25),massdivsperdex=5) #For final calculations, should use more massdivsperdex, e.g. 20 (maybe 10 is ok) #also, k is really coarse, as you'll see if you run this. # get covariance matrix from halo-model trispectrum (saves it in the 'prefix' directory) # it also automatically runs halo.getHaloPknl halo.getHaloCov(outputdir,c,h) # power spectrum at h.k (range of k at which halo model quantities are evaluated) M.loglog(h.k,h.pnl) M.show() # get derivs wrt ln A, tilt h.dloga = halo.getdlogPnldCosmoParam(c,h,'scalar_amp',linlog='log') h.dtilt = halo.getdlogPnldCosmoParam(c,h,'scalar_spectral_index',linlog='lin') M.loglog(h.k,h.dloga**2,label='ln A') M.loglog(h.k,h.dtilt**2,label='tilt') M.legend() M.show() M.save(outputdir+'dlogpnldloga.dat',M.transpose([h.k,h.dloga]),fmt='%6.5e') M.save(outputdir+'dlogpnldtilt.dat',M.transpose([h.k,h.dtilt]),fmt='%6.5e') # get parameter covariance matrix (just a function of k, since there's only one variable) k, covmat = info.getParamCovMat(outputdir,dlogfilenames=['dlogpnldloga.dat','dlogpnldtilt.dat']) # plot the unmarginalized error bars in ln A and the tilt, # if the matter power spectrum is analyzed from k= k[0] to k. M.loglog(k, M.sqrt(covmat[0,0,:]),label='ln A') M.loglog(k, M.sqrt(covmat[1,1,:]),label='tilt') M.legend() M.show()
def plot_simple(in_file): try: data = pylab.loadtxt(sys.argv[1]) except: raise IOError("Can't read %s." % in_file) for i in pylab.transpose(data): pylab.plot(i)
def read_poscar(self, filename): """Parses a POSCAR file""" f = open(filename) poscar = f.readlines() f.close() # First line should contain the atom names , eg. "Ag Ge" in # the same order # as later in the file (and POTCAR for the full vasp run) atomNames = poscar[0].split() self.lattice_constant = float(poscar[1]) # Now the lattice vectors a = [] for vector in poscar[2:5]: s = vector.split() floatvect = float(s[0]), float(s[1]), float(s[2]) a.append( floatvect) # Transpose to make natural ordering for linear algebra self.basis_vectors = m.transpose(m.array(a)) # Number of atoms. Again this must be in the same order as # in the first line # and in the POTCAR file numofatoms = poscar[5].split() for i in xrange(len(numofatoms)): numofatoms[i] = int(numofatoms[i]) if (len(atomNames) < i + 1): atomNames.append("Unknown") [self.atom_symbols.append(atomNames[i]) for n in xrange(numofatoms[i])] # Check if Selective dynamics is switched on sdyn = poscar[6] add = 0 if sdyn[0] == "S" or sdyn[0] == "s": add = 1 self.selective_dynamics = True # Check if atom coordinates are cartesian or direct acType = poscar[6+add] if acType[0] == "C" or acType[0] == "c" or acType[0] == "K" or acType[0] == "k": self.cartesian = 1 else: self.cartesian = 0 offset = add+7 tot_natoms = sum(numofatoms) self.atoms = m.zeros((tot_natoms, 3)) self.selective_flags = [] for atom in xrange(tot_natoms): ac = poscar[atom+offset].split() self.atoms[atom] = (float(ac[0]), float(ac[1]), float(ac[2])) if self.selective_dynamics: self.selective_flags.append((ac[3], ac[4], ac[5])) if self.cartesian: self.atoms *= self.lattice_constant
def plot_slice( self, value, logplot=True, colorbar=False, box=[0,0], nx=200, ny=200, center=False, axes=[0,1], minimum=1e-8, newfig=True ): if type( center ) == list: center = pylab.array( center ) elif type( center ) != np.ndarray: center = self.center dim0 = axes[0] dim1 = axes[1] if (box[0] == 0 and box[1] == 0): box[0] = max( abs( self.data[ "pos" ][:,dim0] ) ) * 2 box[1] = max( abs( self.data[ "pos" ][:,dim1] ) ) * 2 slice = self.get_slice( value, box, nx, ny, center, axes ) x = (pylab.array( range( nx+1 ) ) - nx/2.) / nx * box[0] y = (pylab.array( range( ny+1 ) ) - ny/2.) / ny * box[1] if (newfig): fig = pylab.figure( figsize = ( 13, int(12*box[1]/box[0] + 0.5) ) ) pylab.spectral() if logplot: pc = pylab.pcolor( x, y, pylab.transpose( pylab.log10( pylab.maximum( slice, minimum ) ) ), shading='flat' ) else: pc = pylab.pcolor( x, y, pylab.transpose( slice ), shading='flat' ) if colorbar: cb = pylab.colorbar() pylab.axis( "image" ) xticklabels = [] for tick in pc.axes.get_xticks(): if (tick == 0): xticklabels += [ r'$0.0$' ] else: xticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick/10**(ceil(log10(abs(tick)))), ceil(log10(abs(tick)))) ] pc.axes.set_xticklabels( xticklabels, size=16, y=-0.1, va='baseline' ) yticklabels = [] for tick in pc.axes.get_yticks(): if (tick == 0): yticklabels += [ r'$0.0$' ] else: yticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick/10**(ceil(log10(abs(tick)))), ceil(log10(abs(tick)))) ] pc.axes.set_yticklabels( yticklabels, size=16, ha='right' ) return pc
def plot_simple(in_file): try: data = pylab.loadtxt(sys.argv[1]) except: print "Error %s is not a readable file.\n" % (sys.argv[1]) return for i in pylab.transpose(data): pylab.plot(i)
def peakLocations(date, hd): mode = "fiber" flatname = "/tous/mir7/flats/chi"+date+"."+mode+"flat.fits" flat = pyfits.getdata(flatname) peakarr = np.zeros(flat.shape[1]) for zaidx in range(flat.shape[1]): maxspot = pylab.transpose(pylab.where(flat[2,zaidx,:] == max(flat[2,zaidx,:]))) peakarr[zaidx] = maxspot[0] return peakarr
def solve(f1, f2, f3, f4, a, b, h, tol, max_steps): """ uxx(x,yt) + uyy(x,y) = 0 on R = {(x,y): 0 <= x <= a, 0 <= y <= b}, u(x,0) = f1(x), u(x,b) = f2(x) for 0 <= x <= a, u(0,y) = f3(y), u(a,y) = f4(y) for 0 <= y <= b, :param f1: u(x,0) :param f2: u(x,b) :param f3: u(0,y) :param f4: u(a,y) :param a: right boundary for x :param b: right boundary for y :param h: step :param tol: maximum delta :param max_steps: max count of steps :return: x - vector of x coordinates, y - vector of y coordinates, u - result (matrix of z coordinates) """ # initialize parameters in u n = int(a / h) + 1 m = int(b / h) + 1 ave = (a * (f1(0) + f2(0)) + b * (f3(0) + f4(0))) / (2 * a + 2 * b) u = ave * pylab.ones((n, m)) # boundary conditions u[0, :] = [f3(i * h) for i in range(0, m)] u[n - 1, :] = [f4(i * h) for i in range(0, m)] u[:, 0] = [f1(i * h) for i in range(0, n)] u[:, m - 1] = [f2(i * h) for i in range(0, n)] u[0, 0] = (u[0, 1] + u[1, 0]) / 2 u[0, m - 1] = (u[0, m - 2] + u[1, m - 1]) / 2 u[n - 1, 0] = (u[n - 2, 0] + u[n - 1, 1]) / 2 u[n - 1, m - 1] = (u[n - 2, m - 1] + u[n - 1, m - 2]) / 2 # The parameter of consistent method of relax w = 4 / (2 + math.sqrt(4 - (math.cos(math.pi / (n - 1)) + math.cos(math.pi / (m - 1))) ** 2)) # Improved approximation operator purification throughout the lattice error = 1 count = 0 while error > tol and count <= max_steps: error = 0 for j in range(1, m - 1): for i in range(1, n - 1): relax = w * (u[i][j + 1] + u[i][j - 1] + u[i + 1][j] + u[i - 1, j] - 4 * u[i][j]) / 4 u[i, j] += relax if error <= math.fabs(relax): error = math.fabs(relax) count += 1 x = [i * h for i in range(n)] y = [i * h for i in range(m)] u = pylab.flipud(pylab.transpose(u)) return x, y, u
def readColumns(fname,ignore=0): """ read columns of a file into a (newly created) array optionally ignore the first ingnore lines comments with # allowed """ data = M.transpose(readRaws(fname,ignore)) return data
def peakLocations(date, hd): mode = "fiber" flatname = "/tous/mir7/flats/chi" + date + "." + mode + "flat.fits" flat = pyfits.getdata(flatname) peakarr = np.zeros(flat.shape[1]) for zaidx in range(flat.shape[1]): maxspot = pylab.transpose( pylab.where(flat[2, zaidx, :] == max(flat[2, zaidx, :]))) peakarr[zaidx] = maxspot[0] return peakarr
def calculate_mslp(p,pb,ph,phb,t,qvapor): ''' calculate sea level pressure starting from 'raw' wrf output fields usage: >>> calculate_mslp(p,pb,ph,phb,t,qvapor) where the arguments names correspond to the variable names in the wrfout files e.g. p(lvl,lat,lon) or p(time,lvl,lat,lon) ''' import from_wrf_to_grads as fw2g cs = fw2g.from_wrf_to_grads.compute_seaprs if len(p.shape) == 3: # recover the full pressure field by adding perturbation and base p = p + pb p_t = p.transpose() # same geopotential height ph = (ph + phb) / 9.81 ph_t = ph.transpose() qvapor_t = qvapor.transpose() # do not add the wrf specified 300 factor as the wrapped fortran code # does that for us t_t = t.transpose() nz = ph_t.shape[2] # populate the geopotential_height at mid_levels array with # averages between layers below and above z = (ph_t[:,:,:nz-1] + ph_t[:,:,1:nz]) / 2.0 # finally "in one fell sweep" # the zero is for debug purposes return cs(z,t_t,p_t,qvapor_t,0).transpose() elif len(p.shape) == 4: mslp_shape = (p.shape[0], p.shape[2], p.shape[3]) mslp = n.zeros(mslp_shape) for time_idx in range(p.shape[0]): # recover the full pressure field by adding perturbation and base dummy_p = p[time_idx] + pb[time_idx] dummy_p_t = dummy_p.transpose() # same geopotential height dummy_ph = (ph[time_idx] + phb[time_idx]) / 9.81 dummy_ph_t = dummy_ph.transpose() dummy_qvapor_t = qvapor[time_idx].transpose() # do not add the wrf specified 300 factor as the wrapped fortran code # does that for us dummy_t_t = t[time_idx].transpose() nz = dummy_ph_t.shape[2] # populate the geopotential_height at mid_levels array with # averages between layers below and above z = (dummy_ph_t[:,:,:nz-1] + dummy_ph_t[:,:,1:nz]) / 2.0 # finally "in one fell sweep" # the zero is for debug purposes mslp[time_idx] = cs(z,dummy_t_t,dummy_p_t,dummy_qvapor_t,0).transpose() return mslp else: print 'Wrong shape of the array' return
def calcCorrcoef(widget, msg): global g_frhist, g_behavhist, g_corrcoef print("length of history %d\n" % len(g_frhist)); a = pylab.zeros((len(g_frhist),256+4)) i = 0 for v in g_frhist: j=0 for u in v: a[i,j] = u j = j+1 i = i+1 g_corrcoef = pylab.corrcoef(pylab.transpose(a))
def plot_raw(self): self.fig = pl.figure(figsize=(8,6)) self.fig.clf() xv, yv = pl.meshgrid(pl.array(self.idx) + 1, self.iarr[0]) self.ax = self.fig.add_subplot(211) #self.ax.hold(True) im = self.ax.pcolormesh(xv, pl.transpose(self.iarr),\ pl.transpose(self.varr)) self.fig.colorbar(im) self.ax.set_ylabel('I (A)') self.ax.set_xlabel('Index') self.ax2 = self.fig.add_subplot(212) #self.ax2.hold(True) self.ax2.plot(pl.array(self.idx) + 1, self.c[:,0]) self.ax2.set_ylabel('Control 1') self.ax2.set_xlabel('Index') self.ax2.grid(True) pl.show()
def plot_cylav( self, value, logplot=True, box=[0,0], nx=512, ny=512, center=False, minimum=1e-8 ): if type( center ) == list: center = pylab.array( center ) elif type( center ) != np.ndarray: center = self.center if (box[0] == 0 and box[1] == 0): box[0] = max( abs( self.data[ "pos" ][:,0] ) ) * 2 box[1] = max( abs( self.data[ "pos" ][:,1:] ) ) * 2 grid = calcGrid.calcGrid( self.pos.astype('float64'), self.data["hsml"].astype('float64'), self.data["mass"].astype('float64'), self.data["rho"].astype('float64'), self.data[value].astype('float64').astype('float64'), nx, ny, ny, box[0], box[1], box[1], 0, 0, 0 ) cylav = calcGrid.calcCylinderAverage( grid ) x = (pylab.array( range( nx+1 ) ) - nx/2.) / nx * box[0] y = (pylab.array( range( ny+1 ) ) - ny/2.) / ny * box[1] fig = pylab.figure( figsize = ( 13, int(12*box[1]/box[0] + 0.5) ) ) pylab.spectral() if logplot: pc = pylab.pcolor( x, y, pylab.transpose( pylab.log10( pylab.maximum( cylav, minimum ) ) ), shading='flat' ) else: pc = pylab.pcolor( x, y, pylab.transpose( slice ), shading='flat' ) pylab.axis( "image" ) xticklabels = [] for tick in pc.axes.get_xticks(): if (tick == 0): xticklabels += [ r'$0.0$' ] else: xticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick/10**(ceil(log10(abs(tick)))), ceil(log10(abs(tick)))) ] pc.axes.set_xticklabels( xticklabels, size=16, y=-0.1, va='baseline' ) yticklabels = [] for tick in pc.axes.get_yticks(): if (tick == 0): yticklabels += [ r'$0.0$' ] else: yticklabels += [ r'$%.2f \cdot 10^{%d}$' % (tick/10**(ceil(log10(abs(tick)))), ceil(log10(abs(tick)))) ] pc.axes.set_yticklabels( yticklabels, size=16, ha='right' ) return pc
def main(): XC = loadtxt('iris.data', delimiter=',', dtype=float, converters={4: cnvt}) ind = arange(150) # indices into the dataset ind = permutation(ind) # random permutation L = ind[0:90] # learning set indices T = ind[90:] # test set indices # Learning Set X = transpose(XC[L, 0:4]) nnc = NNb(X, XC[L, -1]) # Classification of Test Set c = zeros(len(T)) for i in arange(len(T)): print sys.argv[1] print int(sys.argv[1]) c[i] = nnc.classify(XC[T[i], 0:4], int(sys.argv[1])) # Confusion Matrix CM = zeros((3, 3)) for i in range(3): for j in range(3): CM[i, j] = sum(logical_and(XC[T, 4] == (i + 1), c == (j + 1))) print(CM) # Plot Test Set figure(1) color = array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) for i in range(4): for j in range(4): subplot(4, 4, 4 * i + j + 1) if i == j: continue print color[XC[T, 4].astype(int) - 1] print[1, 1, 1] * len(T) print color[c.astype(int) - 1] scatter(XC[T, i], XC[T, j], s=100, marker='s', edgecolor=color[XC[T, 4].astype(int) - 1], facecolor=[1, 1, 1] * len(T)) scatter(XC[T, i], XC[T, j], s=30, marker='+', edgecolor=color[c.astype(int) - 1]) savefig('figures/nnbtest.pdf')
def read_data(f): try: data = pylab.loadtxt(f) except: print "Error %s is not a readable file.\n" % (f) return 0 data = pylab.transpose(data) if len(data) < 2: print "Data %s doesn't have at least two dimensions\n" % (f) return 0 return data
def plotFrame(f): gkd = gkedata.GkeData("s3-dg-euler-rt_q_%d.h5" % f) dgd = gkedgbasis.GkeDgSerendip2DPolyOrder2Basis(gkd) Xc, Yc, rho = dgd.project(0) pylab.figure(1) pylab.pcolormesh(Xc, Yc, pylab.transpose(rho)) pylab.axis('image') pylab.gca().set_xticks([]) pylab.gca().set_yticks([]) pylab.axis('image') pylab.clim(35000, 65000) pylab.title('t = %g' % gkd.time) pylab.savefig('s3-dg-euler-rt_rho_%05d.png' % f, bbox_inches='tight') pylab.close()
def load(fname=None,datastr=None,comments='#',delimiter=None, converters=None,skiprows=0, usecols=None, userows=-1, unpack=False): """ Norped from matplotlib/mlab.py and modified... """ if converters is None: converters = {} if type(fname)==str: if fname.endswith('.gz'): import gzip fh = gzip.open(fname) else: fh = file(fname) elif hasattr(fname, 'seek'): fh = fname else: #raise ValueError('fname must be a string or file handle') fh=datastr.split("\n") X = [] converterseq = None for i,ln in enumerate(fh): if i<skiprows: continue #print ln line = ln #[:ln.find(comments)].strip() #print line if (not len(line)) or (datare.match(line) is None): # print "nix" continue if converterseq is None: # print "making converterseq..." converterseq = [converters.get(j,float) for j,val in enumerate(map(lambda s: s.strip(", \t"), line.split(delimiter)))] if usecols is not None: vals = line.split(delimiter) row = [converterseq[j](vals[j]) for j in usecols] else: row = [converterseq[j](val) for j,val in enumerate(map(lambda s: s.strip(", \t"), line.split(delimiter)))] thisLen = len(row) #print row X.append(row) X = array(X, float) r,c = X.shape if r==1 or c==1: X.shape = max([r,c]), if unpack: return transpose(X) else: return X
def plothuv(xh, yh, xu, yu, xv, yv, h, h0, u, v): "plot the height and velocity for A- or C-grid variables" dx = xh[-1] - xh[-2] dy = yh[-1] - yh[-2] py.clf() py.ion() x = py.append(xh - 0.5 * dx, xh[-1] + 0.5 * dx) y = py.append(yh - 0.5 * dy, yh[-1] + 0.5 * dy) py.colorbar(py.pcolormesh(x, y, py.transpose(h + h0))) if (np.max(h0) > np.min(h0)): py.contour(xh, yh, py.transpose(h0)) if (xh == xu).all(): py.quiver(xu, yu, py.transpose(u), py.transpose(v), scale=1e3) else: py.quiver(xu, yu, py.transpose(u), py.transpose(vatu(v)), scale=1e3) py.quiver(xv, yv, py.transpose(uatv(u)), py.transpose(v), scale=1e3) py.axis([np.min(x), np.max(x), np.min(y), np.max(y)])
def QuadArr(Func, a, b, args=()): """Integrates Func from a to b for args. One element of args may be array. Outputs array of integrated values. args is tuple of floats and/or ints and/or numpy arrays. Currently only one element of args may be array. The purpose of this function is to calculate an array of values where each element requires an integral.""" l = 1 for arg in args: if type(arg) is not float and type(arg) is not int: l = len(arg) break argarr = py.transpose(py.array([py.ones(l) * arg for arg in args])) return py.array( [integrate.quad(Func, a, b, args=tuple(ars))[0] for ars in argarr])
def __init__(self, x, y, cov, deg): self.deg = deg self.x = x self.y = y self.cov = cov self.icov = pl.linalg.inv(cov) self.M = pl.zeros([deg + 1, len(x)]) for i in range(deg + 1): self.M[i, :] = x**(deg - i) self.MC = pl.dot(self.M, self.icov) self.MCM = pl.dot(self.M, pl.transpose(self.MC)) self.fit()
def __init__(self,x,y,cov,deg): self.deg = deg self.x = x self.y = y self.cov = cov self.icov = pl.linalg.inv(cov) self.M = pl.zeros([deg+1,len(x)]) for i in range(deg+1): self.M[i,:]=x**(deg-i) self.MC = pl.dot(self.M,self.icov) self.MCM = pl.dot(self.M,pl.transpose(self.MC)) self.fit()
def pcolor_matrix_pylab(A, fname='pcolor_matrix_matplotlib'): """ pcolor_matrix_pylab() implements a matlab-like 'pcolor' function to display the large elements of a matrix in pseudocolor using the Python Imaging Library. """ try: import matplotlib matplotlib.use('Agg') import pylab except ImportError: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/pcolor_matrix_pylab() was unable to import the matplotlib module!' logging.error( 'pyp_graphics/pcolor_matrix_pylab() was unable to import the matplotlib module!' ) return 0 try: import numpy pylab.clf() x = pylab.arange(A.shape[0]) X, Y = pylab.meshgrid(x, x) xmin = min(pylab.ravel(X)) xmax = max(pylab.ravel(X)) pylab.xlim(xmin, xmax) ymin = min(pylab.ravel(Y)) ymax = max(pylab.ravel(Y)) pylab.ylim(ymin, ymax) pylab.axis('off') pylab.pcolor(X, Y, pylab.transpose(A)) #, shading='flat') pylab.clim(0.0, 1.0) plotfile = '%s.png' % (fname) myplotfile = open(plotfile, 'w') pylab.savefig(myplotfile) myplotfile.close() return 1 except: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/pcolor_matrix_pylab() was unable to create the plot %s.' % ( plotfile) logging.error( 'pyp_graphics/pcolor_matrix_pylab() was unable to create the plot %s.', (plotfile)) return 0
def simulationWithDruga(numViruses, maxPop, maxBirthProb, clearProb, resistances, mutProb, numTrials): """ Runs simulations and plots graphs for problem 5. For each of numTrials trials, instantiates a patient, runs a simulation for 150 timesteps, adds guttagonol, and runs the simulation for an additional 150 timesteps. At the end plots the average virus population size (for both the total virus population and the guttagonol-resistant virus population) as a function of time. numViruses: number of ResistantVirus to create for patient (an integer) maxPop: maximum virus population for patient (an integer) maxBirthProb: Maximum reproduction probability (a float between 0-1) clearProb: maximum clearance probability (a float between 0-1) resistances: a dictionary of drugs that each ResistantVirus is resistant to (e.g., {'guttagonol': False}) mutProb: mutation probability for each ResistantVirus particle (a float between 0-1). numTrials: number of simulation runs to execute (an integer) """ pop = pylab.zeros([300, 2]) for _ in range(numTrials): viruses = [ ResistantVirus(maxBirthProb, clearProb, resistances, mutProb) for _ in range(numViruses) ] patient = TreatedPatient(viruses, maxPop) result1 = [[patient.update(), patient.getResistPop(['guttagonol'])] for _ in range(150)] patient.addPrescription('guttagonol') result2 = [[patient.update(), patient.getResistPop(['guttagonol'])] for _ in range(150)] pop += pylab.concatenate((result1, result2)) pop = pylab.transpose(pop) / numTrials pylab.plot(pop[0], label="avg_pop") pylab.plot(pop[1], label="resistant_pop") pylab.title("ResistantVirus Simulation") pylab.xlabel("Time Steps") pylab.ylabel("Average Virus Population") pylab.legend(loc="best") pylab.show()
def pcolor_matrix_pylab(A, fname='pcolor_matrix_matplotlib'): """ pcolor_matrix_pylab() implements a matlab-like 'pcolor' function to display the large elements of a matrix in pseudocolor using the Python Imaging Library. """ try: import matplotlib matplotlib.use('Agg') import pylab except ImportError: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/pcolor_matrix_pylab() was unable to import the matplotlib module!' logging.error('pyp_graphics/pcolor_matrix_pylab() was unable to import the matplotlib module!') return 0 try: import numpy pylab.clf() x = pylab.arange(A.shape[0]) X, Y = pylab.meshgrid(x,x) xmin = min(pylab.ravel(X)) xmax = max(pylab.ravel(X)) pylab.xlim(xmin, xmax) ymin = min(pylab.ravel(Y)) ymax = max(pylab.ravel(Y)) pylab.ylim(ymin, ymax) pylab.axis('off') pylab.pcolor(X, Y, pylab.transpose(A))#, shading='flat') pylab.clim(0.0, 1.0) plotfile = '%s.png' % (fname) myplotfile = open(plotfile,'w') pylab.savefig(myplotfile) myplotfile.close() return 1 except: if pedobj.kw['messages'] == 'verbose': print '[ERROR]: pyp_graphics/pcolor_matrix_pylab() was unable to create the plot %s.' % (plotfile) logging.error('pyp_graphics/pcolor_matrix_pylab() was unable to create the plot %s.', (plotfile)) return 0
def main(k): XC = loadtxt('data/iris.data', delimiter=',', dtype=float, converters={4: cnvt}) ind = arange(150) # indices into the dataset ind = permutation(ind) # random permutation L = ind[0:90] # learning set indices T = ind[90:] # test set indices # Learning Set # The k-NNb classifier is called for given k. X = transpose(XC[L, 0:4]) nnc = NNb(X, XC[L, -1], k) # Classification of Test Set c = zeros(len(T)) for i in range(len(T)): c[i] = nnc.classify(XC[T[i], 0:4]) # Confusion Matrix CM = zeros((3, 3)) for i in range(3): for j in range(3): CM[i, j] = sum(logical_and(XC[T, 4] == (i + 1), c == (j + 1))) print(CM) # Plot Test Set plt.figure(1) color = array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) for i in range(4): for j in range(4): plt.subplot(4, 4, 4 * i + j + 1) if i == j: continue plt.scatter(XC[T, i], XC[T, j], s=100, marker='s', edgecolor=color[XC[T, 4].astype(int) - 1], facecolor=[1, 1, 1] * len(T)) plt.scatter(XC[T, i], XC[T, j], s=30, marker='+', edgecolor=color[c.astype(int) - 1]) plt.savefig('lab_42.png')
def StiffnessAndStrain(self): ''' Function to obtain stiffness matrix and strains in each element ''' for el in range(self.n_element): #enumerate through all the elements K = py.zeros((self.n_nodes*2,self.n_nodes*2))#Full stiffness matrix for one element if self._debug: print 'bar element:', el+1 startNode = self._connectivity[el,0]-1 #start and end node of the element endNode = self._connectivity[el,1]-1 startXY = self._xy[startNode] #start and end coordinates of the element endXY = self._xy[endNode] L = py.norm(endXY - startXY) # Length of the element self.L[el]= L #new start and end coordinates of the element newstartXY=self._xy[startNode]+self._displacement[startNode] newendXY=self._xy[endNode]+self._displacement[endNode] newL=py.norm(newendXY - newstartXY) # Deformed Length of the element self.strain_global.append((newL-L)/L); # Axial Strain in element T = py.zeros((4,2)) T = self.Transform2D(startXY,endXY) #get the Transformation matrix for the element if self._debug: print startNode, endNode, startXY, endXY print 'T' print T L_inv = 1.0/L k0=py.array([[L_inv, -L_inv],[-L_inv, L_inv]])#Stiffness matrix in 1D k_element = py.dot(T,py.dot(k0,py.transpose(T)) )#Stiffness matrix in 2D #Convert from 2x2 local K matrix to a full stiffness matrix but for single element K[py.ix_([2*startNode,2*startNode+1,2*endNode,2*endNode+1],[2*startNode,2*startNode+1,2*endNode,2*endNode+1])] = K[py.ix_([2*startNode,2*startNode+1,2*endNode,2*endNode+1],[2*startNode,2*startNode+1,2*endNode,2*endNode+1])]+k_element if self._debug: print 'element stiffness', 'L_inv', L_inv print k_element print 'K' print K self.k_global = self.k_global + K # Assemble all the stiffness into one Global Stiffness return self.k_global,self.strain_global
# get final solution q1 = getRaw(fh.root.StructGridField, 2, 8, 4) Xn, Yn, qn_1 = projectOnFinerGrid_f(Xc, Yc, q1) # get intial solution fh = tables.openFile("s17-dg-maxwell_q_0.h5") q0 = getRaw(fh.root.StructGridField, 2, 8, 4) Xn, Yn, qn_0 = projectOnFinerGrid_f(Xc, Yc, q0) nx, ny = Xn.shape[0], Yn.shape[0] # make plot pylab.figure(1) im = pylab.pcolormesh(Xn, Yn, pylab.transpose(qn_1)) pylab.axis('tight') colorbar_adj(im) pylab.savefig('s17-dg-maxwell-Ez.png') def calcAverage(fld): wt = pylab.array([1.0, 1.0, 1.0, 1.0]) return (fld[:, :, 0:4] * wt).sum(axis=-1) # compute error q0avg = calcAverage(q0) q1avg = calcAverage(q1) vol = dx * dy / 4.0
cells = grid._v_attrs.vsNumCells dx = (upper[0] - lower[0]) / cells[0] dy = (upper[1] - lower[1]) / cells[1] Xc = pylab.linspace(lower[0] + 0.5 * dx, upper[0] - 0.5 * dx, cells[0]) Yc = pylab.linspace(lower[1] + 0.5 * dy, upper[1] - 0.5 * dy, cells[1]) # get final solution qn_1 = fh.root.StructGridField[:, :, 2] # get intial solution fh = tables.openFile("s0-fv-maxwell_q_0.h5") qn_0 = fh.root.StructGridField[:, :, 2] nx, ny = Xc.shape[0], Yc.shape[0] # make plot pylab.figure(1) im = pylab.pcolormesh(Xc, Yc, pylab.transpose(qn_1)) pylab.axis('tight') colorbar_adj(im) pylab.savefig('s1-fv-maxwell-Ez.png') # compute error err = numpy.abs(qn_1 - qn_0).sum() / (nx * ny) print math.sqrt(dx * dy), err pylab.show()
def yfit(self): return pl.dot(pl.transpose(self.M), self.pars)
xup, yup = 10, 10 nx, ny = 64, 64 dx = (xup - xlo) / nx dy = (yup - ylo) / ny Xc = pylab.linspace(xlo + 0.5 * dx, xup - 0.5 * dx, nx) Yc = pylab.linspace(ylo + 0.5 * dy, yup - 0.5 * dy, ny) tEnd = 100.0 nFrame = 11 T = pylab.linspace(0, tEnd, nFrame) for i in range(nFrame): print "Working on ", i fh = tables.openFile("s141-vortex-waltz_chi_%d.h5" % i) q = fh.root.StructGridField Xn, Yn, qn = projectOnFinerGrid_f(Xc, Yc, q) fig = pylab.figure(1) pylab.pcolormesh(Xn, Yn, pylab.transpose(qn), vmin=0.0, vmax=1.0) pylab.axis('image') pylab.title('T=%f' % T[i]) pylab.savefig('s141-vortex-waltz_%05d.png' % i) pylab.close() fh.close()
def ReperageAcc(): ax = (reperageSpeed[1:, 0] - reperageSpeed[0:-1, 0]) / dt[0:-1] ay = (reperageSpeed[1:, 1] - reperageSpeed[0:-1, 1]) / dt[0:-1] return pylab.transpose(pylab.array([ax, ay]))
return Eval, Evec #------------------------------------------------------------------------------- # End - defining functions ----------------------------------------------------- #------------------------------------------------------------------------------- h = len(S) s, U = jacobi(S, h) iss = pylab.zeros((h,h), dtype = float) # inverse square-root of s for i in range (h): for j in range(h): if j == i : iss[i,j] = 1.0 / (math.sqrt(s[i])) V = pylab.dot(U, iss) # hamiltonian matrix when equation reduced to standard eigenvalue problem Hbar = pylab.dot(pylab.transpose(V),pylab.dot(H,V)) n1 = len(Hbar) Eval, Evec = jacobi(Hbar, n1) # sorting output from Jacobi diagonalization n2 = len(Eval) for i in range(n2-1): index = i val = Eval[i] for j in range(i+1, n2): if Eval[j] < val: index = j val = Eval[j] if index != i: swap1(Eval, i, index) swap2(Evec, i, index)
def fit_emp_prior(id, param_type, fast_fit=False, generate_emp_priors=True, zero_re=True, alt_prior=False, global_heterogeneity='Slightly'): """ Fit empirical prior of specified type for specified model Parameters ---------- id : int The model id number for the job to fit param_type : str, one of incidence, prevalence, remission, excess-mortality, prevalence_x_excess-mortality The disease parameter to generate empirical priors for Example ------- >>> import fit_emp_prior >>> fit_emp_prior.fit_emp_prior(2552, 'incidence') """ dir = dismod3.settings.JOB_WORKING_DIR % id ## load the model from disk or from web import simplejson as json import data reload(data) dm = dismod3.load_disease_model(id) try: model = data.ModelData.load(dir) print 'loaded data from new format from %s' % dir except (IOError, AssertionError): model = data.ModelData.from_gbd_jsons(json.loads(dm.to_json())) #model.save(dir) print 'loaded data from json, saved in new format for next time in %s' % dir ## next block fills in missing covariates with zero for col in model.input_data.columns: if col.startswith('x_'): model.input_data[col] = model.input_data[col].fillna(0.) # also fill all covariates missing in output template with zeros model.output_template = model.output_template.fillna(0) # set all heterogeneity priors to Slightly for the global fit for t in model.parameters: if 'heterogeneity' in model.parameters[t]: model.parameters[t]['heterogeneity'] = global_heterogeneity t = { 'incidence': 'i', 'prevalence': 'p', 'remission': 'r', 'excess-mortality': 'f', 'prevalence_x_excess-mortality': 'pf' }[param_type] model.input_data = model.get_data(t) if len(model.input_data) == 0: print 'No data for type %s, exiting' % param_type return dm ### For testing: ## speed up computation by reducing number of knots ## model.parameters[t]['parameter_age_mesh'] = [0, 10, 20, 40, 60, 100] ## smooth Slightly, Moderately, or Very ## model.parameters[t]['smoothness'] = dict(age_start=0, age_end=100, amount='Very') ## speed up computation be reducing data size ## predict_area = 'super-region_0' ## predict_year=2005 ## predict_sex='total' ## subtree = nx.traversal.bfs_tree(model.hierarchy, predict_area) ## relevant_rows = [i for i, r in model.input_data.T.iteritems() \ ## if (r['area'] in subtree or r['area'] == 'all')\ ## and (r['year_end'] >= 1997) \ ## and r['sex'] in [predict_sex, 'total']] ## model.input_data = model.input_data.ix[relevant_rows] # testing changes #model.input_data['effective_sample_size'] = pl.minimum(1.e3, model.input_data['effective_sample_size']) #missing_ess = pl.isnan(model.input_data['effective_sample_size']) #model.input_data['effective_sample_size'][missing_ess] = 1. #model.input_data['z_overdisperse'] = 1. #print model.describe(t) #model.input_data = model.input_data[model.input_data['area'].map(lambda x: x in nx.bfs_tree(model.hierarchy, 'super-region_5'))] #model.input_data = model.input_data = model.input_data.drop(['x_LDI_id_Updated_7July2011'], axis=1) #model.input_data = model.input_data.filter([model.input_data['x_nottroponinuse'] == 0.] #model.input_data = model.input_data[:100] ## speed up output by not making predictions for empirical priors #generate_emp_priors = False print 'fitting', t model.vars += ism.age_specific_rate(model, t, reference_area='all', reference_sex='total', reference_year='all', mu_age=None, mu_age_parent=None, sigma_age_parent=None, rate_type=(t == 'rr') and 'log_normal' or 'neg_binom', zero_re=zero_re) # for backwards compatibility, should be removed eventually dm.model = model dm.vars = model.vars[t] vars = dm.vars if fast_fit: dm.map, dm.mcmc = dismod3.fit.fit_asr(model, t, iter=101, burn=0, thin=1, tune_interval=100) else: dm.map, dm.mcmc = dismod3.fit.fit_asr(model, t, iter=50000, burn=10000, thin=40, tune_interval=1000, verbose=True) stats = dm.vars['p_pred'].stats(batches=5) dm.vars['data']['mu_pred'] = stats['mean'] dm.vars['data']['sigma_pred'] = stats['standard deviation'] stats = dm.vars['pi'].stats(batches=5) dm.vars['data']['mc_error'] = stats['mc error'] dm.vars['data'][ 'residual'] = dm.vars['data']['value'] - dm.vars['data']['mu_pred'] dm.vars['data']['abs_residual'] = pl.absolute(dm.vars['data']['residual']) graphics.plot_fit(model, data_types=[t], ylab=['PY'], plot_config=(1, 1), fig_size=(8, 8)) if generate_emp_priors: for a in [ dismod3.utils.clean(a) for a in dismod3.settings.gbd_regions ]: print 'generating empirical prior for %s' % a for s in dismod3.settings.gbd_sexes: for y in dismod3.settings.gbd_years: key = dismod3.utils.gbd_key_for(param_type, a, y, s) if t in model.parameters and 'level_bounds' in model.parameters[ t]: lower = model.parameters[t]['level_bounds']['lower'] upper = model.parameters[t]['level_bounds']['upper'] else: lower = 0 upper = pl.inf emp_priors = covariate_model.predict_for( model, model.parameters[t], 'all', 'total', 'all', a, dismod3.utils.clean(s), int(y), alt_prior, vars, lower, upper) dm.set_mcmc('emp_prior_mean', key, emp_priors.mean(0)) if 'eta' in vars: N, A = emp_priors.shape # N samples, for A age groups delta_trace = pl.transpose([ pl.exp(vars['eta'].trace()) for _ in range(A) ]) # shape delta matrix to match prediction matrix emp_prior_std = pl.sqrt( emp_priors.var(0) + (emp_priors**2 / delta_trace).mean(0)) else: emp_prior_std = emp_priors.std(0) dm.set_mcmc('emp_prior_std', key, emp_prior_std) pl.plot(model.parameters['ages'], dm.get_mcmc('emp_prior_mean', key), color='grey', label=a, zorder=-10, alpha=.5) pl.savefig(dir + '/prior-%s.png' % param_type) store_effect_coefficients(dm, vars, param_type) #graphics.plot_one_ppc(vars, t) #pl.savefig(dir + '/prior-%s-ppc.png'%param_type) graphics.plot_acorr(model) pl.savefig(dir + '/prior-%s-convergence.png' % param_type) graphics.plot_trace(model) pl.savefig(dir + '/prior-%s-trace.png' % param_type) graphics.plot_one_effects(model, t) pl.savefig(dir + '/prior-%s-effects.png' % param_type) # save results (do this last, because it removes things from the disease model that plotting function, etc, might need try: dm.save('dm-%d-prior-%s.json' % (id, param_type)) except IOError, e: print e
def main(): import optparse from numpy import sum # Parse command line parser = optparse.OptionParser(usage=USAGE) parser.add_option("-p", "--plot", action="store_true", help="Generate pdf with IR-spectrum") parser.add_option("-i", "--info", action="store_true", help="Set up/ Calculate vibrations & quit") parser.add_option("-s", "--suffix", action="store", help="Call suffix for binary e.g. 'mpirun -n 4 '", default='') parser.add_option("-r", "--run", action="store", help="path to FHI-aims binary", default='') parser.add_option("-x", "--relax", action="store_true", help="Relax initial geometry") parser.add_option("-m", "--molden", action="store_true", help="Output in molden format") parser.add_option("-w", "--distort", action="store_true", help="Output geometry distorted along imaginary modes") parser.add_option("-t", "--submit", action="store", help="""\ Path to submission script, string <jobname> will be replaced by name + counter, string <outfile> will be replaced by filename""") parser.add_option("-d", "--delta", action="store", type="float", help="Displacement", default=0.0025) options, args = parser.parse_args() if options.info: print __doc__ sys.exit(0) if len(args) != 2: parser.error("Need exactly two arguments") AIMS_CALL = options.suffix + ' ' + options.run hessian_thresh = -1 name = args[0] mode = args[1] delta = options.delta run_aims = False if options.run != '': run_aims = True submit_script = options.submit is not None if options.plot: import matplotlib as mpl mpl.use('Agg') from pylab import figure if options.plot or mode == '1': from pylab import savetxt, transpose, eig, argsort, sort,\ sign, pi, dot, sum, linspace, argmin, r_, convolve # Constant from scipy.constants bohr = constants.value('Bohr radius') * 1.e10 hartree = constants.value('Hartree energy in eV') at_u = constants.value('atomic mass unit-kilogram relationship') eV = constants.value('electron volt-joule relationship') c = constants.value('speed of light in vacuum') Ang = 1.0e-10 hbar = constants.value('Planck constant over 2 pi') Avo = constants.value('Avogadro constant') kb = constants.value('Boltzmann constant in eV/K') hessian_factor = eV / (at_u * Ang * Ang) grad_dipole_factor = (eV / (1. / (10 * c))) / Ang #(eV/Ang -> D/Ang) ir_factor = 1 # Asign all filenames inputgeomerty = 'geometry.in.' + name inputcontrol = 'control.in.' + name atomicmasses = 'masses.' + name + '.dat' xyzfile = name + '.xyz' moldenname = name + '.molden' hessianname = 'hessian.' + name + '.dat' graddipolename = 'grad_dipole.' + name + '.dat' irname = 'ir.' + name + '.dat' deltas = array([-delta, delta]) coeff = array([-1, 1]) c_zero = -1. / (2. * delta) f = open('control.in', 'r') # read control.in template template_control = f.read() f.close if submit_script: f = open(options.submit, 'r') # read submission script template template_job = f.read() f.close folder = '' # Dummy ########### Central Point ################################################## if options.relax and mode == '0': # First relax input geometry filename = name + '.out' folder = name + '_relaxation' if not os.path.exists(folder): os.mkdir(folder) # Create folder shutil.copy('geometry.in', folder + '/geometry.in') # Copy geometry new_control = open(folder + '/control.in', 'w') new_control.write(template_control + 'relax_geometry trm 1E-3\n') # Relax! new_control.close() os.chdir(folder) # Change directoy print 'Central Point' if run_aims: os.system(AIMS_CALL + ' > ' + filename) # Run aims and pipe the output # into a file named 'filename' if submit_script: replace_submission(template_job, name, 0, filename) os.chdir('..') ############################################################################ # Check for relaxed geometry if os.path.exists(folder + '/geometry.in.next_step'): geometry = open(folder + '/geometry.in.next_step', 'r') else: geometry = open('geometry.in', 'r') # Read input geometry n_line = 0 struc = structure() lines = geometry.readlines() for line in lines: n_line = n_line + 1 if line.rfind('set_vacuum_level') != -1: # Vacuum Level struc.vacuum_level = float(split_line(line)[-1]) if line.rfind('lattice_vector') != -1: # Lattice vectors and periodic lat = split_line(line)[1:] struc.lattic_vector = append(struc.lattic_vector, float64(array(lat))[newaxis, :], axis=0) struc.periodic = True if line.rfind('atom') != -1: # Set atoms line_vals = split_line(line) at = Atom(line_vals[-1], line_vals[1:-1]) if n_line < len(lines): nextline = lines[n_line] if nextline.rfind( 'constrain_relaxation') != -1: # constrained? at = Atom(line_vals[-1], line_vals[1:-1], True) else: at = Atom(line_vals[-1], line_vals[1:-1]) struc.join(at) geometry.close() n_atoms = struc.n() n_constrained = n_atoms - sum(struc.constrained) # Atomic mass file mass_file = open(atomicmasses, 'w') mass_vector = zeros([0]) for at_unconstrained in struc.atoms[struc.constrained == False]: mass_vector = append(mass_vector, ones(3) * 1. / sqrt(at_unconstrained.mass())) line = '{0:10.5f}'.format(at_unconstrained.mass()) for i in range(3): line = line + '{0:11.4f}'.format(at_unconstrained.coord[i]) line = line + '{0:}\n'.format(at_unconstrained.kind) mass_file.writelines(line) mass_file.close() # Init dip = zeros([n_constrained * 3, 3]) hessian = zeros([n_constrained * 3, n_constrained * 3]) index = 0 counter = 1 # Set up / Read folders for displaced atoms for atom in arange(n_atoms)[struc.constrained == False]: for coord in arange(3): for delta in deltas: filename=name+'.i_atom_'+str(atom)+'.i_coord_'+str(coord)+'.displ_'+\ str(delta)+'.out' folder=name+'.i_atom_'+str(atom)+'.i_coord_'+str(coord)+'.displ_'+\ str(delta) if mode == '0': # Put new geometry and control.in into folder struc_new = copy.deepcopy(struc) struc_new.atoms[atom].coord[coord]=\ struc_new.atoms[atom].coord[coord]+delta geoname='geometry.i_atom_'+str(atom)+'.i_coord_'+str(coord)+\ '.displ_'+str(delta)+'.in' if not os.path.exists(folder): os.mkdir(folder) new_geo = open(folder + '/geometry.in', 'w') newline='#\n# temporary structure-file for finite-difference '+\ 'calculation of forces\n' newline=newline+'# displacement {0:8.4f} of \# atom '.format(delta)+\ '{0:5} direction {1:5}\n#\n'.format(atom,coord) new_geo.writelines(newline + struc_new.to_str()) new_geo.close() new_control = open(folder + '/control.in', 'w') template_control = template_control.replace( 'relax_geometry', '#relax_geometry') new_control.write(template_control+'compute_forces .true. \n'+\ 'final_forces_cleaned '+\ '.true. \noutput dipole \n') new_control.close() os.chdir(folder) # Change directoy print 'Processing atom: '+str(atom+1)+'/'+str(n_atoms)+', coord.: '+\ str(coord+1)+'/'+str(3)+', delta: '+str(delta) if run_aims: os.system(AIMS_CALL + ' > ' + filename) # Run aims and pipe the output # into a file named 'filename' if submit_script: replace_submission(template_job, name, counter, filename) # os.system('qsub job.sh') # Mind the environment variables os.chdir('..') if mode == '1': # Read output forces_reached = False atom_count = 0 data = open(folder + '/' + filename) for line in data.readlines(): if line.rfind( 'Dipole correction potential jump') != -1: dip_jump = float(split_line(line)[-2]) # Periodic if line.rfind('| Total dipole moment [eAng]') != -1: dip_jump = float64( split_line(line)[-3:]) # Cluster if forces_reached and atom_count < n_atoms: # Read Forces struc.atoms[atom_count].force = float64( split_line(line)[2:]) atom_count = atom_count + 1 if atom_count == n_atoms: forces_reached = False if line.rfind('Total atomic forces') != -1: forces_reached = True data.close() if struc.periodic: dip[index, 2] = dip[ index, 2] + dip_jump * coeff[deltas == delta] * c_zero else: dip[index, :] = dip[index, :] + dip_jump * coeff[ deltas == delta] * c_zero forces = array([]) for at_unconstrained in struc.atoms[struc.constrained == False]: forces = append( forces, coeff[deltas == delta] * at_unconstrained.force) hessian[index, :] = hessian[index, :] + forces * c_zero counter = counter + 1 index = index + 1 if mode == '1': # Calculate vibrations print 'Entering hessian diagonalization' print 'Number of atoms = ' + str(n_atoms) print 'Name of Hessian input file = ' + hessianname print 'Name of grad dipole input file = ' + graddipolename print 'Name of Masses input file = ' + atomicmasses print 'Name of XYZ output file = ' + xyzfile print 'Threshold for Matrix elements = ' + str(hessian_thresh) if (hessian_thresh < 0.0): print ' All matrix elements are taken'+\ ' into account by default\n' savetxt(hessianname, hessian) savetxt(graddipolename, dip) mass_mat = mass_vector[:, newaxis] * mass_vector[newaxis, :] hessian[abs(hessian) < hessian_thresh] = 0.0 hessian = hessian * mass_mat * hessian_factor hessian = (hessian + transpose(hessian)) / 2. # Diagonalize hessian (scipy) print 'Solving eigenvalue system for Hessian Matrix' freq, eig_vec = eig(hessian) print 'Done ... ' eig_vec = eig_vec[:, argsort(freq)] freq = sort(sign(freq) * sqrt(abs(freq))) ZPE = hbar * (freq) / (2.0 * eV) freq = (freq) / (200. * pi * c) grad_dipole = dip * grad_dipole_factor eig_vec = eig_vec * mass_vector[:, newaxis] * ones( len(mass_vector))[newaxis, :] infrared_intensity = sum(dot(transpose(grad_dipole),eig_vec)**2,axis=0)*\ ir_factor reduced_mass = sum(eig_vec**2, axis=0) norm = sqrt(reduced_mass) eig_vec = eig_vec / norm # The rest is output, xyz, IR,... print 'Results\n' print 'List of all frequencies found:' print 'Mode number Frequency [cm^(-1)] Zero point energy [eV] '+\ 'IR-intensity [D^2/Ang^2]' for i in range(len(freq)): print '{0:11}{1:25.8f}{2:25.8f}{3:25.8f}'.format( i + 1, freq[i], ZPE[i], infrared_intensity[i]) print '\n' print 'Summary of zero point energy for entire system:' print '| Cumulative ZPE = {0:15.8f} eV'.format(sum(ZPE)) print '| without first six eigenmodes = {0:15.8f} eV\n'.format( sum(ZPE) - sum(ZPE[:6])) print 'Stability checking - eigenvalues should all be positive for a '+\ 'stable structure. ' print 'The six smallest frequencies should be (almost) zero:' string = '' for zz in ZPE[:6]: string = string + '{0:25.8f}'.format(zz) print string print 'Compare this with the largest eigenvalue, ' print '{0:25.8f}'.format(freq[-1]) nums = arange(n_atoms)[struc.constrained == False] nums2 = arange(n_atoms)[struc.constrained] newline = '' newline_ir = '[INT]\n' if options.molden: newline_molden = '[Molden Format]\n[GEOMETRIES] XYZ\n' newline_molden = newline_molden + '{0:6}\n'.format(n_atoms) + '\n' for i_atoms in range(n_constrained): newline_molden = newline_molden + '{0:6}'.format( struc.atoms[nums[i_atoms]].kind) for i_coord in range(3): newline_molden = newline_molden + '{0:10.4f}'.format( struc.atoms[nums[i_atoms]].coord[i_coord]) newline_molden = newline_molden + '\n' newline_molden = newline_molden + '[FREQ]\n' for i in range(len(freq)): newline_molden = newline_molden + '{0:10.3f}\n'.format(freq[i]) newline_molden = newline_molden + '[INT]\n' for i in range(len(freq)): newline_molden = newline_molden + '{0:17.6e}\n'.format( infrared_intensity[i]) newline_molden = newline_molden + '[FR-COORD]\n' newline_molden = newline_molden + '{0:6}\n'.format(n_atoms) + '\n' for i_atoms in range(n_constrained): newline_molden = newline_molden + '{0:6}'.format( struc.atoms[nums[i_atoms]].kind) for i_coord in range(3): newline_molden = newline_molden + '{0:10.4f}'.format( struc.atoms[nums[i_atoms]].coord[i_coord] / bohr) newline_molden = newline_molden + '\n' newline_molden = newline_molden + '[FR-NORM-COORD]\n' for i in range(len(freq)): newline = newline + '{0:6}\n'.format(n_atoms) if freq[i] > 0: newline = newline + 'stable frequency at ' elif freq[i] < 0: newline = newline + 'unstable frequency at ' if options.distort and freq[i] < -50: struc_new = copy.deepcopy(struc) for i_atoms in range(n_constrained): for i_coord in range(3): struc_new.atoms[i_atoms].coord[i_coord]=\ struc_new.atoms[i_atoms].coord[i_coord]+\ eig_vec[(i_atoms)*3+i_coord,i] geoname = name + '.distorted.vibration_' + str( i + 1) + '.geometry.in' new_geo = open(geoname, 'w') newline_geo = '#\n# distorted structure-file for based on eigenmodes\n' newline_geo=newline_geo+\ '# vibration {0:5} :{1:10.3f} 1/cm\n#\n'.format(i+1,freq[i]) new_geo.writelines(newline_geo + struc_new.to_str()) new_geo.close() elif freq[i] == 0: newline = newline + 'translation or rotation ' newline = newline + '{0:10.3f} 1/cm IR int. is '.format(freq[i]) newline = newline + '{0:10.4e} D^2/Ang^2; red. mass is '.format( infrared_intensity[i]) newline = newline + '{0:5.3f} a.m.u.; force const. is '.format( 1.0 / reduced_mass[i]) newline = newline + '{0:5.3f} mDyne/Ang.\n'.format( ((freq[i] * (200 * pi * c))**2) * (1.0 / reduced_mass[i]) * at_u * 1.e-2) if options.molden: newline_molden=newline_molden+\ 'vibration {0:6}\n'.format(i+1) for i_atoms in range(n_constrained): newline = newline + '{0:6}'.format( struc.atoms[nums[i_atoms]].kind) for i_coord in range(3): newline = newline + '{0:10.4f}'.format( struc.atoms[nums[i_atoms]].coord[i_coord]) for i_coord in range(3): newline = newline + '{0:10.4f}'.format( eig_vec[(i_atoms) * 3 + i_coord, i]) if options.molden: newline_molden = newline_molden + '{0:10.4f}'.format( eig_vec[(i_atoms) * 3 + i_coord, i] / bohr) newline = newline + '\n' if options.molden: newline_molden = newline_molden + '\n' for i_atoms in range(n_atoms - n_constrained): newline = newline + '{0:6}'.format( struc.atoms[nums2[i_atoms]].kind) for i_coord in range(3): newline = newline + '{0:10.4f}'.format( struc.atoms[nums2[i_atoms]].coord[i_coord]) for i_coord in range(3): newline = newline + '{0:10.4f}'.format(0.0) newline = newline + '\n' newline_ir = newline_ir + '{0:10.4e}\n'.format( infrared_intensity[i]) xyz = open(xyzfile, 'w') xyz.writelines(newline) xyz.close() ir = open(irname, 'w') ir.writelines(newline_ir) ir.close() if options.molden: molden = open(moldenname, 'w') molden.writelines(newline_molden) molden.close() if mode == '1' and options.plot: x = linspace(freq.min() - 500, freq.max() + 500, 1000) z = zeros(len(x)) for i in range(len(freq)): z[argmin(abs(x - freq[i]))] = infrared_intensity[i] window_len = 150 gauss = signal.gaussian(window_len, 10) s = r_[z[window_len - 1:0:-1], z, z[-1:-window_len:-1]] z_convolve = convolve(gauss / gauss.sum(), s, mode='same')[window_len - 1:-window_len + 1] fig = figure(0) ax = fig.add_subplot(111) ax.plot(x, z_convolve, 'r', lw=2) ax.set_xlim([freq.min() - 500, freq.max() + 500]) ax.set_ylim([-0.01, ax.get_ylim()[1]]) ax.set_yticks([]) ax.set_xlabel('Frequency [1/cm]', size=20) ax.set_ylabel('Intensity [a.u.]', size=20) fig.savefig(name + '_IR_spectrum.pdf') print '\n Done. '
frames = [100] sims = [215, 217, 218, 219] alpha = [0.1, 0.3, 1.0, 2.0] fig = pylab.figure(1) count = 1 for s in sims: print "Working on sim %s (count %d)" % (s, count) f = 100 fh = tables.openFile("../s%d/s%d-hw_phi_%d.h5" % (s, s, f)) q = fh.root.StructGridField Xn, Yn, qn = projectOnFinerGrid_f39(Xc, Yc, q) pylab.subplot(2, 2, count) pylab.title('Adiabacity %g' % alpha[count - 1]) pylab.pcolormesh(Xn, Yn, -pylab.transpose(qn)) pylab.axis('image') count = count + 1 pylab.savefig("hw-cmp-phi_%d.png" % s, dpi=400) pylab.close() fig = pylab.figure(2) count = 1 for s in sims: print "Working on sim %s (count %d)" % (s, count) f = 100 fh = tables.openFile("../s%d/s%d-hw_chi_%d.h5" % (s, s, f)) q = fh.root.StructGridField Xn, Yn, qn = projectOnFinerGrid_f39(Xc, Yc, q)
fi = FiltFiltOctave(source=t, band=freq, fraction='Third octave') bt = BeamformerTimeSq(source=fi, grid=g, mpos=m, r_diag=True, c=c0) avgt = TimeAverage(source=bt, naverage=int(sfreq * tmax / 16)) # 16 single images cacht = TimeCache(source=avgt) # cache to prevent recalculation map2 = zeros(g.shape) # accumulator for average # plot single frames figure(1, (8, 7)) i = 1 for res in cacht.result(1): res0 = res[0].reshape(g.shape) map2 += res0 # average i += 1 subplot(4, 4, i) mx = L_p(res0.max()) imshow(L_p(transpose(res0)), vmax=mx, vmin=mx-10, interpolation='nearest',\ extent=g.extend(), origin='lower') colorbar() map2 /= i subplot(4, 4, 1) text(0.4, 0.25, 'fixed\nfocus', fontsize=15, ha='center') axis('off') tight_layout() #=============================================================================== # moving focus time domain beamforming #=============================================================================== # new grid needed, the trajectory starts at origin and is oriented towards +x # thus, with the circular movement assumed, the center of rotation is at (0,2.5)
Xf_8 = pylab.linspace(0, 1, nx) Yf_8 = pylab.linspace(0.5 * dy, 1 - 0.5 * dy, ny - 1) q_8 = q[:, :-1, 2] Xhr = pylab.linspace(0, 1, 101) Yhr = pylab.linspace(0, 1, 101) fhr = exactSol(2, 5, Xhr, Yhr) vmin, vmax = fhr.min(), fhr.max() # make plots f1 = pylab.figure(1) pylab.subplot(1, 2, 1) cax = pylab.pcolormesh(Xf, Yf, pylab.transpose(q[:, :, 0]), vmin=vmin, vmax=vmax) pylab.axis('image') pylab.subplot(1, 2, 2) cax = pylab.pcolormesh(Xhr, Yhr, fhr) pylab.axis('image') # compute error fex = exactSol(2, 5, Xf, Yf) error = numpy.abs(fex - pylab.transpose(q_1)).sum() fex = exactSol(2, 5, Xf_5, Yf_5) error = error + numpy.abs(fex - pylab.transpose(q_5)).sum()
def yfit(self): return pl.dot(pl.transpose(self.M),self.pars)
d = gkedata.GkeData("s1-em-landau_distfElc_0.h5") dg1_0 = gkedgbasis.GkeDgSerendipNorm2DPolyOrder2Basis(d) d = gkedata.GkeData("s1-em-landau_distfElc_1.h5") dg1_1 = gkedgbasis.GkeDgSerendipNorm2DPolyOrder2Basis(d) d = gkedata.GkeData("s1-em-landau_distfElc_2.h5") dg1_2 = gkedgbasis.GkeDgSerendipNorm2DPolyOrder2Basis(d) Xc, Yc, fve_0 = dg1_0.project(0) Xc, Yc, fve_1 = dg1_1.project(0) Xc, Yc, fve_2 = dg1_2.project(0) figure(1) subplot(2, 1, 1) im = pcolormesh(Xc, Yc, pylab.transpose(fve_1 - fve_0)) axis('tight') colorbar_adj(im) subplot(2, 1, 2) im = pcolormesh(Xc, Yc, pylab.transpose(fve_2 - fve_0)) axis('tight') colorbar_adj(im) savefig('s1-em-landau-deltaF.png') figure(2) im = pcolormesh(Xc, Yc, pylab.transpose(fve_2)) axis('tight') colorbar_adj(im) savefig('s1-em-landau-deltaF.png')
X, V = getXv(Xc, Yc) figure(1) plot(V, fve[fve.shape[0]/2, :], 'r-') ylo, yup = gca().get_ylim() plot([1.0, 1.0], [ylo, yup], '--k') plot([2.0, 2.0], [ylo, yup], '--k') gca().set_ylim([0, 0.4]) title('Time %g' % d.time) xlabel('V') ylabel('f(V)') savefig('r3-es-resonance-fve1_%05d.png' % i) close() figure(2) subplot(2,1,1) im = pcolormesh(Xc, Yc, pylab.transpose(fve)) plot([-2*pi,2*pi], [1.0, 1.0], 'k--', linewidth=2.0) plot([-2*pi,2*pi], [2.0, 2.0], 'k--', linewidth=2.0) axis('tight') colorbar_adj(im) subplot(2,1,2) im = pcolormesh(Xc, Yc, pylab.transpose(fve-fve0)) plot([-2*pi,2*pi], [1.0, 1.0], 'k--', linewidth=2.0) plot([-2*pi,2*pi], [2.0, 2.0], 'k--', linewidth=2.0) #axis('tight') gca().set_ylim([0.0, 4.0]) gca().set_xlim([-2*pi, 2*pi]) colorbar_adj(im) suptitle('Time %g' % d.time)