def _index_where(arr, value, reverse=False): if not reverse: idx = pl.argmin(abs(arr - value)) else: revidx = pl.argmin(abs(arr[::-1] - value)) idx = len(arr) - (revidx + 1) return idx
def _mean_spectra(sim, tmin=0, tmax=1000): f = h5py.File(sim.output.spectra.path_file2D, "r") dset_times = f["times"] # nb_spectra = dset_times.shape[0] times = dset_times[...] # nt = len(times) dset_khE = f["khE"] kh = dset_khE[...] dset_spectrumEK = f["spectrum2D_EK"] dset_spectrumEA = f["spectrum2D_EA"] imin_plot = pl.argmin(abs(times - tmin)) imax_plot = pl.argmin(abs(times - tmax)) # tmin_plot = times[imin_plot] # tmax_plot = times[imax_plot] machine_zero = 1e-15 EK = dset_spectrumEK[imin_plot:imax_plot + 1].mean(0) EA = dset_spectrumEA[imin_plot:imax_plot + 1].mean(0) EK[abs(EK) < 1e-15] = machine_zero EA[abs(EA) < 1e-15] = machine_zero E_tot = EK + EA f.close() return kh, E_tot, EK, EA
def pick_handler(event): artist = event.artist mouseevent = event.mouseevent i = argmin(sum((array(artist.get_data()).T - array([mouseevent.xdata, mouseevent.ydata]))**2, axis=1)) x,y = array(artist.get_data()).T[i] Nelements = len(artist.get_data()[0]) d = str(artist.get_url()[i]) if Nelements > 1 else str(artist.get_url()) ax = artist.axes if not hasattr(ax, "annotation"): ax.annotation = ax.annotate(d, xy=(x,y), xycoords='data', xytext=(0,30), textcoords="offset points", size="larger", va="bottom", ha="center", bbox=dict(boxstyle="round", fc="w", alpha=0.5), arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=-0.2"), ) ax.annotation.xy = (x,y) ax.annotation.set_text(d) artist.figure.canvas.draw()
def getPreceedingNoise(self,tdData,timePreceedingSignal=-1): #retruns the preceeding noise in X and Y channel of tdData #it uses timePreceedingSignal to evaluate the noise, if not given, #it autodetects a "good" time #we should crop the data at least 2.5 ps before the main peak nearestdistancetopeak=2.5e-12 if min(tdData[:,0])+timePreceedingSignal>-nearestdistancetopeak: timePreceedingSignal=-min(tdData[:,0])-nearestdistancetopeak print("Time Interval of preceeding noise to long, reset done") #dont use user input if higher than peak #get the first time starttime=min(tdData[:,0]) if timePreceedingSignal<0: #determine length automatically ratio=2 ix_max=py.argmax(tdData[:,1]) ix_min=py.argmin(tdData[:,1]) earlier=min(ix_max,ix_min) #take only the first nts part endtime=tdData[int(earlier/ratio),0] else: endtime=starttime+timePreceedingSignal #cut the data from starttime to endtime noise=self.getShorterData(tdData,starttime,endtime) #detrend the noise noise=signal.detrend(noise[:,1:3],axis=0) return noise
def pick_handler(event): artist = event.artist mouseevent = event.mouseevent i = argmin( sum((array(artist.get_data()).T - array([mouseevent.xdata, mouseevent.ydata]))**2, axis=1)) x, y = array(artist.get_data()).T[i] Nelements = len(artist.get_data()[0]) d = str(artist.get_url()[i]) if Nelements > 1 else str(artist.get_url()) ax = artist.axes if not hasattr(ax, "annotation"): ax.annotation = ax.annotate( d, xy=(x, y), xycoords='data', xytext=(0, 30), textcoords="offset points", size="larger", va="bottom", ha="center", bbox=dict(boxstyle="round", fc="w", alpha=0.5), arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=-0.2"), ) ax.annotation.xy = (x, y) ax.annotation.set_text(d) artist.figure.canvas.draw()
def extrude_mesh(self, l, z_offset): # accepts the number of layers and the length of extrusion mesh = self.mesh # Extrude vertices all_coords = [] for i in linspace(0, z_offset, l): all_coords.append( hstack((mesh.coordinates(), i * ones((self.n_v2, 1))))) self.global_vertices = vstack(all_coords) # Extrude cells (tris to tetrahedra) for i in range(l - 1): for c in self.mesh.cells(): # Make a prism out of 2 stacked triangles vertices = hstack((c + i * self.n_v2, c + (i + 1) * self.n_v2)) # Determine prism orientation smallest_vertex_index = argmin(vertices) # Map to I-ordering of Dompierre et al. mapping = self.indirection_table[smallest_vertex_index] # Determine which subdivision scheme to use. if min(vertices[mapping][[1, 5]]) < min( vertices[mapping][[2, 4]]): local_tets = vstack((vertices[mapping][[0,1,2,5]],\ vertices[mapping][[0,1,5,4]],\ vertices[mapping][[0,4,5,3]])) else: local_tets = vstack((vertices[mapping][[0,1,2,4]],\ vertices[mapping][[0,4,2,5]],\ vertices[mapping][[0,4,5,3]])) # Concatenate local tet to cell array self.global_tets = vstack((self.global_tets, local_tets)) # Eliminate phantom initialization tet self.global_tets = self.global_tets[1:, :] # Query number of vertices and tets in new mesh self.n_verts = self.global_vertices.shape[0] self.n_tets = self.global_tets.shape[0] # Initialize new dolfin mesh of dimension 3 self.new_mesh = Mesh() m = MeshEditor() m.open(self.new_mesh, 3, 3) m.init_vertices(self.n_verts, self.n_verts) m.init_cells(self.n_tets, self.n_tets) # Copy vertex data into new mesh for i, v in enumerate(self.global_vertices): m.add_vertex(i, Point(*v)) # Copy cell data into new mesh for j, c in enumerate(self.global_tets): m.add_cell(j, *c) m.close()
def spline_interpolate(tck, r_in): if not (type(r_in) in [list, py.ndarray]): r_in = [r_in] scaler_in = True else: scaler_in = False out_list = [] for r in r_in: i_intp = py.argmin(abs(r - tck[0][:, 0])) if (r < tck[0][0, 0]): out = tck[1][0, -1] elif (r > tck[0][-1, -1]): out = 0.0 #tck[1][-1,-1] else: for i_intp, [r_min, r_max] in enumerate(tck[0]): if (r > r_min and r <= r_max): break out = 0 for ii in range(tck[2]): out += (r - tck[0][i_intp, 0])**(tck[2] - (ii + 1)) * tck[1][i_intp, ii] out_list.append(out) if scaler_in: return out_list[0] else: return py.array(out_list)
def classify(self, x, k): d = self.X - tile(x.reshape(self.n, 1), self.N) dsq = sum(d * d, 0) minindex = argmin(dsq) temp = argsort(dsq) ### Custom code starting here ### # Save the data for each class around the point in a array score = [0, 0, 0] # With the help of k surrounding points score each class for x in range(0, k): if ((self.c[temp[x]]) == 1.0): score[0] += 1 elif ((self.c[temp[x]]) == 2.0): score[1] += 1 elif ((self.c[temp[x]]) == 3.0): score[2] += 1 # Check to which class the point is classified if (score[0] > score[1] and score[0] > score[2]): return 1.0 elif (score[1] > score[2]): return 2.0 # If there are points with the same value, assign the class of the nearest neighbour. elif (score[0] == score[1] and score[0] == score[2]): return self.c[minindex] else: return 3.0
def extrude_mesh(self,l,z_offset): # accepts the number of layers and the length of extrusion # Extrude vertices all_coords = [] for i in linspace(0,z_offset,l): all_coords.append(hstack((mesh.coordinates(),i*ones((self.n_v2,1))))) self.global_vertices = vstack(all_coords) # Extrude cells (tris to tetrahedra) for i in range(l-1): for c in self.mesh.cells(): # Make a prism out of 2 stacked triangles vertices = hstack((c+i*self.n_v2,c+(i+1)*self.n_v2)) # Determine prism orientation smallest_vertex_index = argmin(vertices) # Map to I-ordering of Dompierre et al. mapping = self.indirection_table[smallest_vertex_index] # Determine which subdivision scheme to use. if min(vertices[mapping][[1,5]]) < min(vertices[mapping][[2,4]]): local_tets = vstack((vertices[mapping][[0,1,2,5]],\ vertices[mapping][[0,1,5,4]],\ vertices[mapping][[0,4,5,3]])) else: local_tets = vstack((vertices[mapping][[0,1,2,4]],\ vertices[mapping][[0,4,2,5]],\ vertices[mapping][[0,4,5,3]])) # Concatenate local tet to cell array self.global_tets = vstack((self.global_tets,local_tets)) # Eliminate phantom initialization tet self.global_tets = self.global_tets[1:,:] # Query number of vertices and tets in new mesh self.n_verts = self.global_vertices.shape[0] self.n_tets = self.global_tets.shape[0] # Initialize new dolfin mesh of dimension 3 self.new_mesh = Mesh() m = MeshEditor() m.open(self.new_mesh,3,3) m.init_vertices(self.n_verts,self.n_verts) m.init_cells(self.n_tets,self.n_tets) # Copy vertex data into new mesh for i,v in enumerate(self.global_vertices): m.add_vertex(i,Point(*v)) # Copy cell data into new mesh for j,c in enumerate(self.global_tets): m.add_cell(j,*c) m.close()
def get_kin_apex(self, phases, return_times = False): """ returns the kinematic state at the apices which are close to the given phases. Apex is re-calculated. :args: self: kin object (-> later: "self") phases (list): list of lists of apex phases. must match with length of "kin.raw_data". The n'th list of apex phases will be assigned to the nth "<object>.raw_data" element. return_times (bool): if true, return only the times at which apex occurred. :returns: if lr_split is True: [[r_apices], [l_apices]] else: [[apices], ] where apices is the kinematic (from <object>.selection at the apices *around* the given phases. *NOTE* The apices themselves are re-computed for higher accuracy. """ all_kin = [] all_kin_orig = self.get_kin() all_apex_times = [] if len(self.raw_dat) != len(phases): raise ValueError("length of phases list does not match number of datasets") for raw, phase, kin_orig in zip(self.raw_dat, phases, all_kin_orig): kin_apex = [] kin_time = arange(len(raw['phi2'].squeeze()), dtype=float) / 250. # 1st: compute apex *times* apex_times = [] for phi_apex in phase: # 1a: get "rough" estimate idx_apex = argmin(abs(raw['phi2'].squeeze() - phi_apex)) # 1b: fit quadratic function to com_y idx_low = max(0, idx_apex - 4) idx_high = min(raw['com'].shape[0] - 1, idx_apex + 4) com_y_pt = raw['com'][idx_low:idx_high + 1, 2] tp = arange(idx_high - idx_low + 1) # improve numerical accuracy: do not take absolute time p = polyfit(tp, com_y_pt, 2) # p: polynomial, highest power coeff first t0 = -p[1] / (2.*p[0]) # "real" index of apex (offset is 2: a value of 2 # indicates that apex is exactly at the measured frame t_apex = kin_time[idx_apex] + (t0 - 4.) / 250. apex_times.append(t_apex) if return_times: all_apex_times.append(array(apex_times)) else: # 2nd: interpolate data dat = vstack([interp(apex_times, kin_time, kin_orig[row, :]) for row in arange(kin_orig.shape[0])]) all_kin.append(dat) if return_times: return all_apex_times return all_kin
def sort_ratios(self, ratios): """ :: Sort and select tuning system ratios in ascending order by proximity to equal tempered pitch classes. """ ratios.append(Fraction(2,1)) res = list(set(ratios)) # eliminate duplicates res.sort() # in-place sort idx = [pylab.argmin( abs( pylab.array(res) - j) ) for j in self.pitch_ratios_eq] res = [res[i] for i in idx] return res
def plotErrorFunction(self,l,freq): #plots the error function py.figure() resolution=300 ix=py.argmin(abs(freq-self.H.getfreqs())) n_i=py.linspace(0.0,0.05,int(resolution/2)) n_r=py.linspace(1,3,resolution) N_R,N_I=py.meshgrid(n_r,n_i) E_fu=py.zeros((len(n_i),len(n_r))) for i in range(len(n_r)): for k in range(len(n_i)): E_fu[k,i]=self.error_func([n_r[i],n_i[k]],self.H.fdData[ix,:3],l) # print(E_fu[:,2]) py.pcolor(N_R,N_I,py.log10(E_fu)) py.colorbar()
def classify(self, x, k): d = self.X - tile(x.reshape(self.n,1), self.N) # Occurrence of a class occd = {} for i in range(k): dsq = sum(d*d,0) minindex = argmin(dsq) if self.c[minindex] in occd: occd[self.c[minindex]] += 1 else: occd[self.c[minindex]] = 1 # Prevent next iter giving this index again d[:, minindex] = self.max + 1 # Return the name of the class that occurred most return max(occd.iteritems(), key=operator.itemgetter(1))[0]
def minimize_residual_variances(self, **kwargs): """ Syst. residuals behave as an underpartition measures, i.e. the larger is K the lower is the residual( the more are patches the better ) stat. residuals behave as an overpartition measures, i.e. the larger is K the higher is the residuals (the lesser are the patches the worse, because you have less signal-to-noise in each patch) """ self.Vu = pl.zeros_like(self.Kvals).reshape(-1, 1) * 1.0 self.Vo = pl.zeros_like(self.Kvals).reshape(-1, 1) * 1.0 nvals = len(self.Kvals) for j, K in enumerate(self.Kvals): if self.verbose: print(f"Running with K={K} clusters") clusters = AgglomerativeClustering( n_clusters=K, affinity="precomputed", linkage="average", connectivity=self.connectivity, ) clusters.fit_predict(self._Affinity) msys, mstat = estimate_Stat_and_Sys_residuals( clusters.labels_, galactic_binmask=self.galactic_mask, **kwargs) m1 = pl.ma.masked_equal(msys[1], hp.UNSEEN).mask m2 = pl.ma.masked_equal(mstat[1], hp.UNSEEN).mask _, _, var_sys, var_stat = estimate_spectra(msys, mstat) self.Vo[j], self.Vu[j] = var_stat, var_sys # We have to match Vo and Vu, we rescale Vo so that it ranges as Vu min_max_scaler = preprocessing.MinMaxScaler( feature_range=(self.Vu.min(), self.Vu.max())) self.Vu = min_max_scaler.fit_transform((self.Vu)).reshape(nvals) self.Vo = min_max_scaler.fit_transform((self.Vo)).reshape(nvals) Vsv = interp1d(self.Kvals, pl.sqrt(self.Vu**2 + self.Vo**2).T, kind="slinear") Krange = pl.arange(self.Kvals.min(), self.Kvals.max()) minval = pl.argmin(Vsv(Krange) - Vsv(Krange).min()) Kopt = Krange[minval] return Kopt
def minimize_partition_measures(self): self.Vu = pl.zeros_like(self.Kvals).reshape(-1, 1) * 1.0 self.Vo = pl.zeros_like(self.Kvals).reshape(-1, 1) * 1.0 nvals = len(self.Kvals) for j, K in enumerate(self.Kvals): if self.verbose: print(f"Running with K={K} clusters") clusters = AgglomerativeClustering( n_clusters=K, affinity="precomputed", linkage="average", connectivity=self.connectivity, ) clusters.fit_predict(self._Affinity) mu, MD = self.intracluster_distance(K, clusters.labels_) dmu = self._metric.pairwise(mu[:, :self._nfeat]) dmu = pl.ma.fix_invalid(dmu, fill_value=1.0).data if self._has_angles: dmuang = self.haversine.pairwise(mu[:, self._nfeat:]) # dmuang =pl.ma.fix_invalid(dmuang, fill_value=pl.pi).data dmu = pl.multiply(dmu, dmuang) pl.fill_diagonal(dmu, pl.inf) self.Vo[j] = K / dmu.min() # overpartition meas. self.Vu[j] = MD.sum() / K # underpartition meas. # We have to match Vo and Vu, we rescale Vo so that it ranges as Vu min_max_scaler = preprocessing.MinMaxScaler( feature_range=(self.Vu.min(), self.Vu.max())) self.Vu = min_max_scaler.fit_transform((self.Vu)).reshape(nvals) self.Vo = min_max_scaler.fit_transform((self.Vo)).reshape(nvals) # minimizing the squared sum Vsv = interp1d(self.Kvals, pl.sqrt(self.Vu**2 + self.Vo**2).T, kind="slinear") Krange = pl.arange(self.Kvals.min(), self.Kvals.max()) minval = pl.argmin(Vsv(Krange) - Vsv(Krange).min()) Kopt = Krange[minval] return Kopt
def compute_registeration(P0, Yk): ''' compute the registeration. which is transformation martix ref: http://www.cs.virginia.edu/~mjh7v/bib/Besl92.pdf Input: P0: Point set Yk: P0 corresponding Point set Output: qk: transform matrix ''' # compute mu p and mu x mup = np.mean(P0, axis=0) Nx = len(P0) mux = np.mean(Yk, axis=0) # Cross-covariance martix sigma_px sigma_px = (np.dot(P0.T,Yk) - np.dot(mup.T,mux))/Nx Aij = sigma_px - sigma_px.T tr = trace(sigma_px) Sym = sigma_px + sigma_px.T - tr*identity(3) Q_sigma_px = np.array([ [tr, Aij[1][2], Aij[2][0], Aij[0][1]], [Aij[1][2], Sym[0][0], 0, 0], [Aij[2][0], 0, Sym[1][1], 0], [Aij[0][1], 0, 0, Sym[2][2]]]) # eigenvalue to get optimal R and T w, v = np.linalg.eig(Q_sigma_px) qR = v[:, argmin(w)] R = get_rotation_matrix(qR) qT = (mux.T - R.dot(mup.T)).T return qR, qT
for e in fl[1:]: data_add = pd.read_table(e, sep = ",") data_add.columns = ["Time", e[3:8]] means[k] = pd.merge(means[k], data_add, on = "Time") means[k]["0.435"] -= 273.15 means[k]["0.455"] -= 273.15 heights = pl.array(means[k].keys())[1:].astype(float) pl.figure() for level in filling_levels: index = pl.argmin(abs(means[k]["Time"] - (level / massflows[k]))) pl.plot(means[k].loc[index][1:][0:].values, heights, \ label = "filling level = " + str(level) + " kg" ) pl.xlim([58.0, 76.0]) pl.ylim([0.0, 2.4]) pl.grid(True) pl.ylabel("Height (m)") pl.xlabel("Temperature ($^{\circ}$C)") pl.legend(loc="lower right") pl.title("Mean temperature per stratum in " + sim) pl.savefig(basedir + "fig_mean_per_sim/" + sim + ".png", bbox_inches='tight')
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. '
def fig3_struct(path, fig, ax1, tmin=0, tmax=1000): sim = fls.load_sim_for_plot(path, merge_missing_params=True) path_file = os.path.join(path, "increments.h5") f = h5py.File(path_file, "r") dset_times = f["times"] times = dset_times[...] if tmax is None: tmax = times.max() rxs = f["rxs"][...] oper = f["/info_simul/params/oper"] nx = oper.attrs["nx"] Lx = oper.attrs["Lx"] deltax = Lx / nx rxs = pl.array(rxs, dtype=pl.float64) * deltax imin_plot = pl.argmin(abs(times - tmin)) imax_plot = pl.argmin(abs(times - tmax)) S_uL2JL = f["struc_func_uL2JL"][imin_plot:imax_plot + 1].mean(0) S_uT2JL = f["struc_func_uT2JL"][imin_plot:imax_plot + 1].mean(0) S_c2h2uL = f["struc_func_c2h2uL"][imin_plot:imax_plot + 1].mean(0) S_Kolmo = f["struc_func_Kolmo"][imin_plot:imax_plot + 1].mean(0) # S_uT2uL = f['struc_func_uT2uL'][imin_plot:imax_plot + 1].mean(0) eps = _eps(sim, tmin) S_Kolmo_theo = -4 * eps * rxs Lf = pl.pi / _k_f(sim.params) ax1.set_xscale("log") ax1.set_yscale("linear") # ax1.plot(rxs / Lf, # (S_uL2JL+S_uT2JL+S_c2h2uL)/S_Kolmo_theo, # 'y', linewidth=1, label='sum check') def _label(x, y): pre = "" if y == "uu": y = r"\mathbf{u}" y2 = r"|\delta {}|^2".format(y) else: if y == "h": pre = "c ^ 2" y2 = r"(\delta {})^2".format(y) return "$ -\langle {} \delta {} {} \\rangle $".format(pre, x, y2) ax1.set_xlabel("$r/L_f$") label1 = _label("J_L", "uu") label2 = _label("u_L", "h") label3 = label1[:-10] + " + " + label2[10:] def label_norm(label): str_norm = " / (4\epsilon r)$" return label.rstrip(" $") + str_norm ax1.set_ylabel(label_norm(label3)) ax1.plot(rxs / Lf, S_Kolmo / S_Kolmo_theo, "k", linewidth=2, label=(label3)) ax1.plot( rxs / Lf, (S_uL2JL + S_uT2JL) / S_Kolmo_theo, "r:", linewidth=2, label=(label1), ) ax1.plot(rxs / Lf, S_c2h2uL / S_Kolmo_theo, "b--", linewidth=2, label=(label2)) # ax1.plot(rxs / Lf, S_uL2JL / S_Kolmo_theo, # 'r--', linewidth=2, label=_label('J_L', 'u_L')) # ax1.plot(rxs / Lf, S_uT2JL / S_Kolmo_theo, # 'r-.', linewidth=2, label=_label('J_L', 'u_T')) # cond = rxs < 6 * deltax # ax1.plot(rxs[cond] / Lf, 1.e0 * rxs[cond] ** 3 / S_Kolmo_theo[cond], # 'y', linewidth=2, label='$r^3/S; r<6dx$') ax1.axhline(1.0, color="k", ls=":") # ax1.plot(rxs, pl.ones(rxs.shape), 'k:', linewidth=1) ax1.set_xlim([None, 2]) ax1.set_ylim([-0.1, 1.1]) ax1.legend(loc=8)
w=eval('p.'+window+'(window_len)') y=p.convolve(w/w.sum(),s,mode='same') return y[window_len:-window_len+1] for peak in set(index['peak']): lf = [index['files'][(index['peak']==peak)*(index['beam']==i)] for i in [0,1]] d = [[p.genfromtxt(f,skip_header=2,delimiter=',') for f in x] for x in lf] d = [[[x[s:e,:] for s,e in [get_tri_range(x[:,4])]][0] for x in y] for y in d] sc = 30 dsr = [smooth(x[:,3],sc) for x in d[1][1:]] ddr = [smooth(x[:,3],sc) for x in d[0]] p.figure() p.title("peak:%i"%(peak)) [plot(x) for x in ddr] dsx = [p.argmin(x[1500:]).flatten()[0] for x in dsr] ddx = [p.argmin(x[1500:]).flatten()[0] for x in ddr] dcut = min(dsx+ddx) ds = [smooth(x[:,2]-x[:,3],sc)[s-dcut:] for x,s in zip(d[1][1:],dsx)] dd = [smooth(x[:,2]-x[:,3],sc)[s-dcut:] for x,s in zip(d[0],ddx)] dsr = [x[s-dcut:] for x,s in zip(dsr,dsx)] ddr = [x[s-dcut:] for x,s in zip(ddr,ddx)] avg_range = range(min(map(len,ds+dd))) dsa = p.array([p.mean([x[i] for x in ds]) for i in avg_range]) dda = p.array([p.mean([x[i] for x in dd]) for i in avg_range]) [plot(x,'r') for x in ds] [plot(x,'b') for x in dd] plot(dsa) plot(dda) plot(dsa-dda)
def classify(self, x): d = self.X - tile(x.reshape(self.n,1), self.N) dsq = sum(d*d,0) minindex = argmin(dsq) return self.c[minindex]
means[k] = pd.merge(means[k], data_add, on = "Time") if (sim == "m1_dt25_upper_inlet") & (e == "qt_0.095.csv"): means[k][e[3:8]] += (273.15 + 60.0) means[k]["0.435"] -= 273.15 means[k]["0.455"] -= 273.15 heights = pl.array(means[k].keys())[1:].astype(float) for level in filling_levels: # Huhn index = pl.argmin(abs(means[k]["Time"] - (level / massflows[k]))) means_index = means[k].loc[index][1:] Tmin = means_index.min() Tmax = means_index.max() Tlb = Tmin + 0.1 * (Tmax - Tmin) Tub = Tmin + 0.9 * (Tmax - Tmin) pTlb = pl.argmin(means_index[means_index >= Tlb]) pTub = pl.argmax(means_index[means_index <= Tub]) eTlb = means_index[pTlb] eTub = means_index[pTub]
for e in fl[1:]: data_add = pd.read_table(e, sep = ",") data_add.columns = ["Time", e[3:8]] means[k] = pd.merge(means[k], data_add, on = "Time") means[k]["0.435"] -= 273.15 means[k]["0.455"] -= 273.15 heights = pl.array(means[k].keys())[1:].astype(float) pl.figure() for level in filling_levels: index = pl.argmin(abs(means[k]["Time"] - (level / massflows[k]))) pl.plot(means[k].loc[index][1:][0:].values, heights, \ label = "filling level = " + str(level) + " kg" ) pl.xlim(58, 76) pl.ylim([0.0, 2.4]) pl.grid(True) pl.legend(loc="lower right") pl.title("Mean temperature per stratum in " + sim) pl.xlabel("Temperature ($^{\circ}$C)") pl.ylabel("Height (m)") pl.savefig(basedir + "fig_comp_baffle_m035_dt25/" + sim + ".png", \ bbox_inches='tight')
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, broadened with Lorentzian") 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) parser.add_option("-b", "--broadening", action="store", type="float", help="Broadening for IR-spectrum in cm^{-1}", default=5) 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 broadening=options.broadening 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' or mode=='2': 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') pi=constants.pi 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' or mode=='2'): # 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.lattice_vector=append(struc.lattice_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' or mode=='2': # 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. \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' or mode=='2': # 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: pass #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' or mode=='2': # 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' or mode=='2') 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 lorentzian=lorentz(pi,broadening,arange(250))#signal.gaussian(window_len,broadening) s=r_[z[window_len-1:0:-1],z,z[-1:-window_len:-1]] z_convolve=convolve(lorentzian/lorentzian.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. '
def GetMostAbundantPseudoisomer(self, pH, I, pMg, T): v_dG0, v_dG0_tag, v_nH, v_z, v_nMg = self._Transform(pH, pMg, I, T) i = pylab.argmin(v_dG0_tag) return v_dG0[i], v_dG0_tag[i], v_nH[i], v_z[i], v_nMg[i]
def plotVirial(posdat, endat, bodycount, dt, eps, tot_time): """ makes the virial comparison plot and everything else """ bodycount, pos_length, postype = posdat.shape pos_timelen = pl.linspace(0, tot_time, pos_length) # component wise energies kin_en_comp = posdat[:, :, 4] # (100 bodies, kin energies at timestep).shape pot_en_comp = posdat[:, :, 5] # pot energies kin_en_ejec_comp = pl.zeros((bodycount, pos_length)) pot_en_ejec_comp = pl.zeros((bodycount, pos_length)) masses = posdat[:, 0, 3] # now to exclude ejected bodies ejecta_body_array = pl.zeros( bodycount) # identifies which bodies become ejected at which time ejecta_time_array = pl.zeros( pos_length) # measures no. of ejecta at time incr. # body summed energies, for use in en. consv. and virial test kin_en_sum = pl.zeros(pos_length) pot_en_sum = pl.zeros(pos_length) kin_en_ejec_sum = pl.zeros(pos_length) pot_en_ejec_sum = pl.zeros(pos_length) # task f) relevant eq_time = pl.array([4.52]) eq_pos = [] eq_arg = int(pl.where(pos_timelen >= eq_time[0])[0][0]) # running through the lists for step in pl.arange(0, pos_length): for body in pl.arange(0, bodycount): if kin_en_comp[body, step] + pot_en_comp[body, step] > 0: # move to ejected lists kin_en_ejec_comp[body, step] = kin_en_comp[body, step] pot_en_ejec_comp[body, step] = pot_en_comp[body, step] ejecta_body_array[body] = 1 # identification ejecta_time_array[step] = sum(ejecta_body_array) # stores no. of ejecta at time incr. kin_en_comp[body, step] = 0. # necessary for elimination pot_en_comp[body, step] = 0. kin_en_sum[step] = sum(kin_en_comp[:, step]) pot_en_sum[step] = sum(pot_en_comp[:, step]) / 2. # factor of 1/2 because system kin_en_ejec_sum[step] = sum(kin_en_ejec_comp[:, step]) pot_en_ejec_sum[step] = sum(pot_en_ejec_comp[:, step]) / .2 """print type(pos_timelen[step]), pos_timelen[step] print type(eq_time[0]), eq_time[0] print """ if step == eq_arg: for i in range(len(ejecta_body_array)): if int(ejecta_body_array[i]) == 0: eq_pos.append(posdat[i, eq_arg, :3]) # equilibrium positions, (bodies, positions).shape eq_pos = pl.array(eq_pos) eq_radia = pl.zeros(len(eq_pos)) for i in range(len(eq_pos)): eq_radia[i] = (eq_pos[i, 0]**2 + eq_pos[i, 1]**2 + eq_pos[i, 2]**2)**.5 consv_bound_ejec_sum = kin_en_sum + pot_en_sum \ + kin_en_ejec_sum + pot_en_ejec_sum # --- tasks b) through e) --- # pl.figure() pl.subplot(2, 1, 1) pl.plot(pos_timelen, kin_en_sum, label="Kinetic") pl.legend(loc='best') pl.ylabel("Kinetic energy") pl.xlim([0.0, tot_time]) pl.title(r"Bound energy over time, %dbody %gdt %g$\varepsilon$" % (bodycount, dt, eps)) pl.grid("on") pl.subplot(2, 1, 2) pl.plot(pos_timelen, pot_en_sum, label="Potential") pl.legend(loc='best') pl.xlabel(r"Time $\tau_c$") pl.ylabel("Potential energy") pl.xlim([0.0, tot_time]) pl.grid("on") pl.savefig("../figs/ClusterEnergiesComp_" + str(bodycount) + "body_dt" + str(int(dt * 1000)) + "_eps" + str(int(eps * 100)) + "_dur" + str(int(tot_time)) + ".png") ### --- ### pl.figure() pl.subplot(2, 1, 1) pl.title(r"No. of ejecta, %dbody %gdt %g$\varepsilon$" % (bodycount, dt, eps)) pl.ylabel(r"Ejection fraction") pl.xlim([0.0, tot_time]) pl.plot(pos_timelen, ejecta_time_array / bodycount, label="Ejecta/Tot") pl.legend(loc='best') pl.grid("on") pl.subplot(2, 1, 2) pl.plot(pos_timelen, kin_en_ejec_sum - pot_en_ejec_sum, label=r"$K_e - V_e$") pl.legend(loc='best') pl.xlabel(r"Time $\tau_c$") pl.ylabel("Energy") pl.xlim([0., tot_time]) pl.title(r"Ejected bodies' energy, %dbody %gdt %g$\varepsilon$" % (bodycount, dt, eps)) pl.grid("on") pl.savefig("../figs/ClusterEnergiesEjecEn_" + str(bodycount) + "body_dt" + str(int(dt * 1000)) + "_eps" + str(int(eps * 100)) + "_dur" + str(int(tot_time)) + ".png") ### --- ### pl.figure() pl.subplot(2, 1, 1) pl.plot(pos_timelen, consv_bound_ejec_sum, label=r"$K_b + V_b + K_e + V_e$") pl.plot(pos_timelen, pl.ones(pos_length) * pot_en_sum[0], linestyle="dashed", color="black", label="Conserved ideal") pl.legend(loc='best') pl.ylabel("Energy sum") pl.xlim([0., tot_time]) # pl.ylim([pot_en_sum[0] - 0.1*max(consv_bound_ejec_sum), max(consv_bound_ejec_sum) + 0.1*max(consv_bound_ejec_sum)]) pl.title(r"Energy conservation test, %dbody %gdt %g$\varepsilon$" % (bodycount, dt, eps)) pl.grid("on") pl.subplot(2, 1, 2) pl.plot(pos_timelen, 2 * kin_en_sum / (bodycount - ejecta_time_array) + pot_en_sum / (bodycount - ejecta_time_array), label=r"$2K_b + V_b$") pl.plot(pos_timelen, pl.zeros(pos_length), linestyle="dashed", color="black", label="Virial ideal") pl.legend(loc='best') pl.xlabel(r"Time $\tau_c$") pl.ylabel("Virial energy comparison") pl.xlim([0.0, tot_time]) pl.title(r"Virial comparison fit, %dbody %gdt %g$\varepsilon$" % (bodycount, dt, eps)) pl.grid("on") pl.savefig("../figs/ClusterEnConsvVirial_" + str(bodycount) + "body_dt" + str(int(dt * 1000)) + "_eps" + str(int(eps * 100)) + "_dur" + str(int(tot_time)) + ".png") ################################ # --- beginning of task f) --- # ################################ # colorlist = [] for i in range(bodycount): colorlist.append(random.rand(3, 1)) fig3D = pl.figure() ax3D = fig3D.add_subplot(111, projection='3d') for body in range(len(eq_pos)): ax3D.plot([eq_pos[body, 0]], [eq_pos[body, 1]], [eq_pos[body, 2]], marker="o", color=colorlist[body]) ax3D.set_title( r"Star cluster 3D %dbody %gdt %g$\varepsilon$, t=%g$\tau_c$" % (bodycount, dt, eps, eq_time)) ax3D.set_xlabel("X-axis [ly]") ax3D.set_ylabel("Y-axis [ly]") ax3D.set_zlabel("Z-axis [ly]") ax3D.set_xlim([-25, 25]) ax3D.set_ylim([-25, 25]) ax3D.set_zlim([-25, 25]) fig3D.savefig("../moviefigs/eps" + str(int(eps * 100)) + "/ClusterPos_" + str(bodycount) + "body_dt" + str(int(dt * 1000)) + "_eps" + str(int(eps * 100)) + "_dur" + str(int(tot_time)) + ".png") print "mean eq. radius:", pl.mean(eq_radia) print "std dev. radius:", pl.std(eq_radia) bincount = 60 weights, edges = pl.histogram(eq_radia, bins=bincount, normed=False) radia = edges + 0.5 * (edges[1] - edges[0]) # lsm finds correct r0 lengthnumber = 1000 alphalower = 0.01 alphaupper = 2. alpha = pl.linspace(alphalower, alphaupper, lengthnumber) r0lower = 0.0001 r0upper = 10. r0 = pl.linspace(r0lower, r0upper, lengthnumber) n0 = max(weights) n0arg = pl.argmax(weights) r0final = bodycount**( 1. / 3) # assuming it depends somehow on total body number in volume nsums = pl.zeros(lengthnumber) for alphacount in range(lengthnumber): nset = n(edges[:-1] - edges[n0arg], alpha[alphacount] * r0final, n0) nsums[alphacount] = sum((nset - weights)**2) minarg = pl.argmin(nsums) r0final *= alpha[minarg] print "n0", n0 print "r0", r0final """ pl.figure() pl.subplot(2,1,1) pl.hist(eq_radia, label="Histogram of bodies", bins=bincount) pl.legend(loc='best') pl.ylabel(r"Bodies in the data") pl.title(r"Radial density of bound bodies, %dbody %gdt %g$\varepsilon$" % (bodycount, dt, eps) ) pl.grid('on') pl.subplot(2,1,2) pl.plot(edges + edges[pl.argmax(weights)], n(edges, r0final, n0), label=r"$n(r)$", color='blue', linewidth=2) pl.xlabel(r"Radius $R_0$") pl.ylabel(r"Radial distribution model") pl.legend(loc='best') pl.grid('on') pl.savefig("../figs/ClusterRadDens_"+str(bodycount)+"body_dt"+str(int(dt*1000))+"_eps"+str(int(eps*100))+"_dur"+str(int(tot_time))+".png") """ pl.figure() pl.hist(eq_radia, label="Histogram of bodies", color='cyan', bins=bincount) pl.title(r"Radial density of bound bodies, %dbody %gdt %g$\varepsilon$" % (bodycount, dt, eps)) pl.plot(edges + edges[pl.argmax(weights)], n(edges, r0final, n0), label=r"$n(r)$", color='magenta', linewidth=2) pl.xlabel(r"Radius $R_0$") pl.ylabel(r"Radial distribution") pl.legend(loc='best') pl.grid('on') pl.savefig("../figs/ClusterRadDens_" + str(bodycount) + "body_dt" + str(int(dt * 1000)) + "_eps" + str(int(eps * 100)) + "_dur" + str(int(tot_time)) + ".png")
for e in fl[1:]: data_add = pd.read_table(e, sep = ",") data_add.columns = ["Time", e[3:8]] means[k] = pd.merge(means[k], data_add, on = "Time") means[k]["0.435"] -= 273.15 means[k]["0.455"] -= 273.15 heights = pl.array(means[k].keys())[1:].astype(float) pl.figure() for level in filling_levels: index = pl.argmin(abs(means[k]["Time"] - (level / massflows[k]))) pl.plot(means[k].loc[index][1:][0:].values, heights, \ label = "filling level = " + str(level) + " kg" ) pl.xlim([58.0, 86.0]) pl.ylim([0.2, 2.4]) pl.grid(True) pl.ylabel("Height (m)") pl.xlabel("Temperature ($^{\circ}$C)") pl.legend(loc="lower right") pl.title("Mean temperature per stratum in " + sim) pl.savefig(basedir + "fig_mean_per_sim_upper_inlet/" + sim + ".png", bbox_inches='tight')
def argmindist_py(a, v): from pylab import randn, newaxis, sum, argmin return argmin(sum((a - v[newaxis, :])**2, axis=1))