def finalize(self): """Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ # The NetCDF output file is opened for writing. outputFile = NetCDFFile(self.output, 'w') outputFile.title = self.__class__.__name__ outputFile.jobinfo = self.information + '\nOutput file written on: %s\n\n' % asctime( ) # Dictionnary whose keys are of the form Gi where i is the group number # and the entries are the list of the index of the atoms building the group. comp = 1 for g in self.group: outputFile.jobinfo += 'Group %d: %s\n' % (comp, [index for index in g]) comp += 1 # Some dimensions are created. outputFile.createDimension('NFRAMES', self.nFrames) # Creation of the NetCDF output variables. # The time. TIMES = outputFile.createVariable('time', N.Float, ('NFRAMES', )) TIMES[:] = self.times[:] TIMES.units = 'ps' avacfTotal = N.zeros((self.nFrames), typecode=N.Float) for k in self.AVACF.keys(): AVACF = outputFile.createVariable('avacf-group%s' % k, N.Float, ('NFRAMES', )) AVACF[:] = self.AVACF[k][:] AVACF.units = 'rad^2*ps^-2' N.add(avacfTotal, self.AVACF[k], avacfTotal) avacfTotal /= self.nGroups AVACF = outputFile.createVariable('avacf-total', N.Float, ('NFRAMES', )) AVACF[:] = avacfTotal[:] AVACF.units = 'rad^2*ps^-2' asciiVar = sorted(outputFile.variables.keys()) outputFile.close() self.toPlot = { 'netcdf': self.output, 'xVar': 'time', 'yVar': 'avacf-total' } # Create an ASCII version of the NetCDF output file. convertNetCDFToASCII(inputFile = self.output,\ outputFile = os.path.splitext(self.output)[0] + '.cdl',\ variables = asciiVar)
def finalize(self): """Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ outputFile = NetCDFFile(self.output, 'w') outputFile.title = self.__class__.__name__ outputFile.jobinfo = self.information + '\nOutput file written on: %s\n\n' % asctime( ) outputFile.createDimension('NGROUPS', self.nGroups) outputFile.createDimension('NFRAMES', self.nFrames) TIMES = outputFile.createVariable('time', N.Float, ('NFRAMES', )) TIMES[:] = self.times TIMES.units = 'ps' GROUPNUMBER = outputFile.createVariable('group_number', N.Int32, ('NGROUPS', )) P2 = outputFile.createVariable('p2', N.Float, ('NGROUPS', 'NFRAMES')) P2AVG = outputFile.createVariable('p2-groupavg', N.Float, ('NFRAMES', )) S2 = outputFile.createVariable('s2', N.Float, ('NGROUPS', )) p2Avg = N.zeros((self.nFrames), typecode=N.Float) comp = 0 for bKey in sorted(self.bondNames.keys()): bName = self.bondNames[bKey] GROUPNUMBER[comp] = bName S2[comp] = self.S2[bName] P2[comp, :] = self.P2[bName] N.add(p2Avg, self.P2[bName], p2Avg) comp += 1 P2AVG[:] = p2Avg / float(self.nGroups) asciiVar = sorted(outputFile.variables.keys()) outputFile.close() self.toPlot = {'netcdf': self.output, 'xVar': 'pair', 'yVar': 'S2'} # Creates an ASCII version of the NetCDF output file. convertNetCDFToASCII(inputFile = self.output,\ outputFile = os.path.splitext(self.output)[0] + '.cdl',\ variables = asciiVar)
def saveNetCDF(data, filename, title): file = NetCDFFile(filename, 'w', 'Created ') file.title = title file.createDimension('TIME', len(data[2])) file.createDimension('LENGTH', len(data[1])) SF = file.createVariable('SF', N.Float, ('LENGTH', 'TIME')) time = file.createVariable('time', N.Float, ('TIME', )) qlenght = file.createVariable('qlenght', N.Float, ('LENGTH', )) for i in range(len(data[0])): for j in range(len(data[1])): SF[j, i] = data[2][i][j] for i in range(len(data[0])): time[i] = data[0][i] for i in range(len(data[1])): qlenght[i] = data[1][i] file.close()
def finalize(self): """Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ # The NetCDF output file is opened for writing. outputFile = NetCDFFile(self.output, 'w') outputFile.title = self.__class__.__name__ outputFile.jobinfo = self.information + '\nOutput file written on: %s\n\n' % asctime( ) outputFile.createDimension('NFRAMES', self.nFrames) TIMES = outputFile.createVariable('time', N.Float, ('NFRAMES', )) TIMES[:] = self.times[:] TIMES.units = 'ps' for oName, seq in self.sequence.items(): outputFile.createDimension('SEQ%s' % oName, len(seq)) SEQUENCE = outputFile.createVariable('%s_sequence' % oName, N.Int32, ('SEQ%s' % oName, )) SEQUENCE[:] = N.array(seq) SEQUENCE.units = 'unitless' S2 = outputFile.createVariable('%s_s2' % oName, N.Float, ('SEQ%s' % oName, 'NFRAMES')) S2[:] = self.S2[oName][:, :] S2.units = 'unitless' S2AVG = outputFile.createVariable('%s_s2_timeavg' % oName, N.Float, ('SEQ%s' % oName, )) S2AVG[:] = self.S2[oName][:, :].sum(1) / float(self.nFrames) S2AVG.units = 'unitless' asciiVar = sorted(outputFile.variables.keys()) outputFile.close() self.toPlot = None # Creates an ASCII version of the NetCDF output file. convertNetCDFToASCII(inputFile = self.output,\ outputFile = os.path.splitext(self.output)[0] + '.cdl',\ variables = asciiVar)
def write_netcdf(self,filename,rlon,rlat,z,title=None): # from Scientific.IO.NetCDF import NetCDFFile #nc = Dataset(filename,'w',format='NETCDF3_CLASSIC') print 'netcdf filename: ', filename print rlon[0], rlon[-1], rlat[0], rlat[-1], z.min(), z.max() print len(rlon), len(rlat), z.shape #nc = netcdf.netcdf_file(filename,'w') nc = NetCDFFile(filename,'w') if title is None: title='' nc.title = title nc.source = '' nc.createDimension('side',2) nc.createDimension('xysize',len(rlon)*len(rlat)) y_range = nc.createVariable('y_range','d', ('side',)) y_range.units = 'y' y_range[:] = [rlat[0],rlat[-1]] x_range = nc.createVariable('x_range','d', ('side',)) x_range.units = 'x' x_range[:] = [rlon[0],rlon[-1]] z_range = nc.createVariable('z_range','d', ('side',)) z_range.units = 'z' z_range[:] = [z.min(),z.max()] spacing = nc.createVariable('spacing','d',('side',)) spacing[:] = [rlon[1]-rlon[0],rlat[1]-rlat[0]] dimension = nc.createVariable('dimension','i',('side',)) dimension[:] = [len(rlon),len(rlat)] grid_data = nc.createVariable('z','f', ('xysize',)) grid_data.scale_factor = np.array([1.]) grid_data.add_offset = np.array([0.]) grid_data.node_offset = np.array([0]) q = np.flipud(z) q = q.flatten() grid_data[:] = q.astype('float32') nc.close()
def internalRun(self): """Runs the analysis.""" self.chrono = default_timer() orderedAtoms = sorted(self.universe.atomList(), key = operator.attrgetter('index')) selectedAtoms = Collection([orderedAtoms[ind] for ind in self.subset]) M1_2 = N.zeros((3*self.nSelectedAtoms,), N.Float) weightList = [N.sqrt(el[1]) for el in sorted([(at.index, at.mass()) for at in selectedAtoms])] for i in range(len(weightList)): M1_2[3*i:3*(i+1)] = weightList[i] invM1_2 = (1.0/M1_2)*N.identity(3*self.nSelectedAtoms, typecode = N.Float) # The initial structure configuration. initialStructure = self.trajectory.configuration[self.first] averageStructure = ParticleVector(self.universe) for conf in self.trajectory.configuration[self.first:self.last:self.skip]: averageStructure += self.universe.configurationDifference(initialStructure, conf) averageStructure = averageStructure/self.nFrames averageStructure = initialStructure + averageStructure mdr = N.zeros((self.nFrames, 3*self.nSelectedAtoms), N.Float) # Calculate the fluctuation matrix. sigmaPrim = N.zeros((3*self.nSelectedAtoms, 3*self.nSelectedAtoms), N.Float) comp = 0 for conf in self.trajectory.configuration[self.first:self.last:self.skip]: mdr[comp,:] = M1_2*N.ravel(N.compress(self.mask,(conf-averageStructure).array,0)) sigmaPrim += mdr[comp,:, N.NewAxis] * mdr[N.NewAxis, comp, :] comp += 1 sigmaPrim = sigmaPrim/float(self.nFrames) try: # Calculate the quasiharmonic modes omega, dx = Heigenvectors(sigmaPrim) except MemoryError: raise Error('Not enough memory to diagonalize the %sx%s fluctuation matrix.' % sigmaPrim.shape) # Due to numerical imprecisions, the result can have imaginary parts. # In that case, throw the imaginary parts away. # Conversion from uma*nm2 to kg*m2 (SI) omega = omega.real/(Units.kg*Units.m**2) omega = (Units.Hz/Units.invcm)*N.sqrt((Units.k_B*Units.K*self.temperature/Units.J)*(1.0/omega)) dx = dx.real dx = N.dot(invM1_2, dx) # Sort eigen vectors by decreasing fluctuation amplitude. indices = N.argsort(omega)[::-1] omega = N.take(omega, indices) dx = N.take(dx, indices) # Eq 66 of the reference paper. mdr = N.take(mdr, indices, axis = 1) at = N.dot(mdr,N.transpose(dx)) # The NetCDF output file is opened. outputFile = NetCDFFile(self.output, 'w') outputFile.title = self.__class__.__name__ outputFile.jobinfo = self.information + '\nOutput file written on: %s\n\n' % asctime() # The universe is emptied from its objects keeping just its topology. self.universe.removeObject(self.universe.objectList()[:]) # The atoms of the subset are copied atoms = copy.deepcopy(selectedAtoms.atomList()) # And their parent attribute removed to allow their transfer in the empty universe. for a in atoms: a.parent = None ac = AtomCluster(atoms,name='QHACluster') self.universe.addObject(ac) # Some dimensions are created. # NEIVALS = the number eigen values outputFile.createDimension('NEIGENVALS', len(omega)) # UDESCR = the universe description length outputFile.createDimension('UDESCR', len(self.universe.description())) # NATOMS = the number of atoms of the universe outputFile.createDimension('NATOMS', self.nSelectedAtoms) # NFRAMES = the number of frames. outputFile.createDimension('NFRAMES', self.nFrames) # NCOORDS = the number of coordinates (always = 3). outputFile.createDimension('NCOORDS', 3) # 3N. outputFile.createDimension('3N', 3*self.nSelectedAtoms) if self.universe.cellParameters() is not None: outputFile.createDimension('BOXDIM', len(self.universe.cellParameters())) # Creation of the NetCDF output variables. # EIVALS = the eigen values. OMEGA = outputFile.createVariable('omega', N.Float, ('NEIGENVALS',)) OMEGA[:] = omega # EIVECS = array of eigen vectors. DX = outputFile.createVariable('dx', N.Float, ('NEIGENVALS','NEIGENVALS')) DX[:,:] = dx # The time. TIMES = outputFile.createVariable('time', N.Float, ('NFRAMES',)) TIMES[:] = self.times[:] TIMES.units = 'ps' # MODE = the mode number. MODE = outputFile.createVariable('mode', N.Float, ('3N',)) MODE[:] = 1 + N.arange(3*self.nSelectedAtoms) # LCI = local character indicator. See eq 56. LCI = outputFile.createVariable('local_character_indicator', N.Float, ('3N',)) LCI[:] = (dx**4).sum(0) # GCI = global character indicator. See eq 57. GCI = outputFile.createVariable('global_character_indicator', N.Float, ('3N',)) GCI[:] = (N.sqrt(3.0*self.nSelectedAtoms)/(N.absolute(dx)).sum(0))**4 # Projection of MD traj onto normal modes. See eq 66.. AT = outputFile.createVariable('at', N.Float, ('NFRAMES','3N')) AT[:,:] = at[:,:] # DESCRIPTION = the universe description. DESCRIPTION = outputFile.createVariable('description', N.Character, ('UDESCR',)) DESCRIPTION[:] = self.universe.description() # AVGSTRUCT = the average structure. AVGSTRUCT = outputFile.createVariable('avgstruct', N.Float, ('NATOMS','NCOORDS')) AVGSTRUCT[:,:] = N.compress(self.mask,averageStructure.array,0) # If the universe is periodic, create an extra variable storing the box size. if self.universe.cellParameters() is not None: BOXSIZE = outputFile.createVariable('box_size', N.Float, ('BOXDIM',)) BOXSIZE[:] = self.universe.cellParameters() outputFile.close() self.toPlot = None self.chrono = default_timer() - self.chrono return None
def finalize(self): """Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ if self.architecture == 'monoprocessor': t = self.trajectory else: # Load the whole trajectory set. t = Trajectory(None, self.trajectoryFilename, 'r') orderedAtoms = sorted(t.universe.atomList(), key=operator.attrgetter('index')) groups = [ Collection([orderedAtoms[ind] for ind in g]) for g in self.group ] # 'freqencies' = 1D Numeric array. Frequencies at which the DOS was computed frequencies = N.arange(self.nFrames) / (2.0 * self.nFrames * self.dt) # The NetCDF output file is opened for writing. outputFile = NetCDFFile(self.output, 'w') outputFile.title = self.__class__.__name__ outputFile.jobinfo = self.information + '\nOutput file written on: %s\n\n' % asctime( ) # Dictionnary whose keys are of the form Gi where i is the group number # and the entries are the list of the index of the atoms building the group. comp = 1 for g in self.group: outputFile.jobinfo += 'Group %d: %s\n' % (comp, [index for index in g]) comp += 1 # Some dimensions are created. outputFile.createDimension('NFRAMES', self.nFrames) # Creation of the NetCDF output variables. # The time. TIMES = outputFile.createVariable('time', N.Float, ('NFRAMES', )) TIMES[:] = self.times[:] TIMES.units = 'ps' # The resolution function. RESOLUTIONFUNCTION = outputFile.createVariable('resolution_function', N.Float, ('NFRAMES', )) RESOLUTIONFUNCTION[:] = self.resolutionFunction[:] RESOLUTIONFUNCTION.units = 'unitless' # Creation of the NetCDF output variables. # The frequencies. FREQUENCIES = outputFile.createVariable('frequency', N.Float, ('NFRAMES', )) FREQUENCIES[:] = frequencies[:] FREQUENCIES.units = 'THz' OMEGAS = outputFile.createVariable('angular_frequency', N.Float, ('NFRAMES', )) OMEGAS[:] = 2.0 * N.pi * frequencies[:] OMEGAS.units = 'rad ps-1' avacfTotal = N.zeros((self.nFrames), typecode=N.Float) adosTotal = N.zeros((self.nFrames), typecode=N.Float) comp = 1 totalMass = 0.0 for g in groups: AVACF = outputFile.createVariable('avacf-group%s' % comp, N.Float, ('NFRAMES', )) AVACF[:] = self.AVACF[comp][:] AVACF.units = 'rad^2*ps^-2' N.add(avacfTotal, self.AVACF[comp], avacfTotal) ADOS = outputFile.createVariable('ados-group%s' % comp, N.Float, ('NFRAMES', )) ADOS[:] = self.ADOS[comp][:] ADOS.units = 'rad^2*ps^-1' N.add(adosTotal, g.mass() * self.ADOS[comp], adosTotal) comp += 1 totalMass += g.mass() adosTotal *= 0.5 * self.dt / (self.nGroups * totalMass) AVACF = outputFile.createVariable('avacf-total', N.Float, ('NFRAMES', )) AVACF[:] = avacfTotal AVACF.units = 'rad^2*ps^-2' ADOS = outputFile.createVariable('ados-total', N.Float, ('NFRAMES', )) ADOS[:] = adosTotal ADOS.units = 'rad^2*ps^-1' asciiVar = sorted(outputFile.variables.keys()) outputFile.close() self.toPlot = { 'netcdf': self.output, 'xVar': 'angular_frequency', 'yVar': 'ados-total' } # Create an ASCII version of the NetCDF output file. convertNetCDFToASCII(inputFile = self.output,\ outputFile = os.path.splitext(self.output)[0] + '.cdl',\ variables = asciiVar)