Beispiel #1
0
    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)
Beispiel #2
0
    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)
Beispiel #3
0
    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)
Beispiel #4
0
    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
Beispiel #5
0
    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)