DCDConverter.py 12 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
#MDANSE : Molecular Dynamics Analysis for Neutron Scattering Experiments
#------------------------------------------------------------------------------------------
#Copyright (C)
#2015- Eric C. Pellegrini Institut Laue-Langevin
#BP 156
#6, rue Jules Horowitz
#38042 Grenoble Cedex 9
#France
#pellegrini[at]ill.fr
#goret[at]ill.fr
#aoun[at]ill.fr
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU Lesser General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#Lesser General Public License for more details.
#
#You should have received a copy of the GNU Lesser General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

''' 
Created on Apr 10, 2015

@author: pellegrini
'''

import struct

import numpy

from MMTK import Units
from MMTK.ParticleProperties import Configuration
from MMTK.PDB import PDBConfiguration
from MMTK.Trajectory import Trajectory, SnapshotGenerator, TrajectoryOutput
from MMTK.Universe import InfiniteUniverse, ParallelepipedicPeriodicUniverse

from MDANSE.Core.Error import Error
from MDANSE.Framework.Jobs.IJob import IJob
from MDANSE.Mathematics.Geometry import get_basis_vectors_from_cell_parameters
from MDANSE.MolecularDynamics.Trajectory import resolve_undefined_molecules_name

PI_2 = 0.5*numpy.pi
RECSCALE32BIT = 1
RECSCALE64BIT = 2

class DCDFileError(Error):
    pass
  
class ByteOrderError(Error):
    pass

class InputOutputError(Error):
    pass

class EndOfFile(Error):
    pass

class FortranBinaryFileError(Error):
    pass

def get_byte_order(filename):

    # Identity the byte order of the file by trial-and-error
    byteOrder = None

    # The DCD file is opened for reading in binary mode.
    data = file(filename, 'rb').read(4)

    # Check for low and big endianness byte orders.
    for order in ['<', '>']:
        reclen = struct.unpack(order + 'i', data)[0]
        if reclen == 84:
            byteOrder = order
            break

        if byteOrder is None:
            raise ByteOrderError("Invalid byte order. %s is not a valid DCD file" % filename)
                
    return byteOrder

class FortranBinaryFile(object):
    """Sets up a Fortran binary file reader. 

    @note: written by Konrad Hinsen.
    """
    def __init__(self, filename):
        """The constructor.

        @param filename: the input file.
        @type filename: string.

        @param byte_order: the byte order to read the binary file.
        @type byte_order: string being one '@', '=', '<', '>' or '!'.
        """
        self.file = file(filename, 'rb')
        self.byteOrder = get_byte_order(filename)

    def __iter__(self):
        return self

    def next_record(self):
        data = self.file.read(struct.calcsize("i"))
        if not data:
            raise StopIteration
        reclen = struct.unpack(self.byteOrder + 'i', data)[0]
        data = self.file.read(reclen)
        reclen2 = struct.unpack(self.byteOrder + 'i', self.file.read(struct.calcsize("i")))[0]
        if reclen != reclen2:
            FortranBinaryFileError("Invalid block")
            
        return data

    def skip_record(self):
        data = self.file.read(struct.calcsize("i"))
        reclen = struct.unpack(self.byteOrder + 'i', data)[0]
        self.file.seek(reclen, 1)
        reclen2 = struct.unpack(self.byteOrder + 'i', self.file.read(4))[0]
        assert reclen==reclen2

    def get_record(self, fmt, repeat = False):
        """Reads a record of the binary file.

        @param format: the format corresponding to the binray structure to read.
        @type format: string.        

        @param repeat: if True, will repeat the reading.
        @type repeat: bool.        
        """

        try:
            data = self.next_record()
        except StopIteration:
            raise EndOfFile()
        if repeat:
            unit = struct.calcsize(self.byteOrder + fmt)
            assert len(data) % unit == 0
            fmt = (len(data)/unit) * fmt
        try:
            return struct.unpack(self.byteOrder + fmt, data)
        except:
            raise                
  
class DCDFile(FortranBinaryFile, dict):
        
    def __init__(self, filename):
        
        FortranBinaryFile.__init__(self, filename)
                        
        self['filename'] = filename
                                        
        self.read_header()
        
    def read_header(self):
        
        # Read a block
        data = self.next_record()
                
        if data[:4] != 'CORD':
            raise DCDFileError("Unrecognized DCD format")

        temp = struct.unpack(self.byteOrder + '20i', data[4:])
        
        self['charmm'] = temp[-1]
                
        if self['charmm']:
            temp = struct.unpack(self.byteOrder + '9if10i', data[4:])
        else:
            temp = struct.unpack(self.byteOrder + '9id9i', data[4:])

        # Store the number of sets of coordinates
        self['nset'] = self['n_frames'] = temp[0]
        
        # Store the starting time step
        self['istart'] = temp[1]
        
        # Store the number of timesteps between dcd saves
        self['nsavc'] = temp[2]
        
        # Stores the number of fixed atoms
        self['namnf'] = temp[8]

        # Stop if there are fixed atoms.
        if self['namnf'] > 0:
            raise DCDFileError('Can not handle fixed atoms yet.')
                                        
        self['delta'] = temp[9]
                                            
        self["time_step"] = self['nsavc']*self['delta']*Units.akma_time           

        self['has_pbc_data'] = temp[10]

        self['has_4d'] = temp[11]
        
        # Read a block
        data = self.next_record()
                
        nLines = struct.unpack(self.byteOrder + b'I', data[0:4])[0]
            
        self["title"] = []
        for i in range(nLines):                
            temp = struct.unpack(self.byteOrder + '80c', data[4+80*i:4+80*(i+1)])
            self["title"].append("".join(temp).strip())
        
        self["title"] = "\n".join(self["title"])
        
        # Read a block
        data = self.next_record()
        
        # Read the number of atoms.
        self['natoms'] = struct.unpack(self.byteOrder + b'I', data)[0]
                                                            
    def read_step(self):
        """
        Reads a frame of the DCD file.
        """
                
        if self['has_pbc_data']:
            unitCell = numpy.array(self.get_record('6d'), dtype = numpy.float64)
            unitCell = unitCell[[0,2,5,1,3,4]]
            unitCell[0:3] *= Units.Ang
            # This file was generated by CHARMM, or by NAMD > 2.5, with the angle
            # cosines of the periodic cell angles written to the DCD file.       
            # This formulation improves rounding behavior for orthogonal cells   
            # so that the angles end up at precisely 90 degrees, unlike acos().            
            if numpy.all(abs(unitCell[3:]) <= 1):
                unitCell[3:] = PI_2 - numpy.arcsin(unitCell[3:])
            else:
                # assume the angles are stored in degrees (NAMD <= 2.5)
                unitCell[3:] *= Units.deg
            

        else:
            unitCell = None

        fmt = '%df' % self['natoms']
        config = numpy.empty((self["natoms"],3),dtype=numpy.float64)
        config[:,0] = numpy.array(self.get_record(fmt), dtype=numpy.float64)
        config[:,1] = numpy.array(self.get_record(fmt), dtype=numpy.float64)
        config[:,2] = numpy.array(self.get_record(fmt), dtype=numpy.float64)
        config *= Units.Ang
        
        if self['has_4d']:
            self.skip_record()
            
        return unitCell, config

    def skip_step(self):
        """Skips a frame of the DCD file.
        """
        nrecords = 3
        if self['has_pbc_data']:
            nrecords += 1
        if self['has_4d']:
            nrecords += 1
        for _ in range(nrecords):
            self['binary'].skip_record()

    def __iter__(self):
        return self

    def next_step(self):
        try:
            return self.read_step()
        except EndOfFile:
            raise StopIteration

class DCDConverter(IJob):
    """
    Converts a DCD trajectory to a MMTK trajectory.
    """

    def initialize(self):
        """
        Initialize the input parameters and analysis self variables
        """

        self.configuration["dcd_file"]["instance"] = DCDFile(self.configuration["dcd_file"]['filename'])

        # The number of steps of the analysis.
        self.numberOfSteps = self.configuration['dcd_file']['instance']['n_frames']
 
        # Create all objects from the PDB file.  
        conf = PDBConfiguration(self.configuration['pdb_file']['filename'])

        # Creates a collection of all the chemical objects stored in the PDB file
        molecules = conf.createAll()
                        
        # If the input trajectory has PBC create a periodic universe.
        if self.configuration['dcd_file']['instance']['has_pbc_data']:
            self._universe = ParallelepipedicPeriodicUniverse()
            
        # Otherwise create an infinite universe.
        else:
            self._universe = InfiniteUniverse()
                    
        # The chemical objects found in the PDB file introduced into the universe.
        self._universe.addObject(molecules)

        resolve_undefined_molecules_name(self._universe)
        
        # A MMTK trajectory is opened for writing.
        self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w')
        
        # A frame generator is created.        
        self._snapshot = SnapshotGenerator(self._universe, actions=[TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)])

    def run_step(self, index):
        """
        Runs a single step of the job.\n
 
        :Parameters:
            #. index (int): The index of the step.
        :Returns:
            #. index (int): The index of the step. 
        """
                        
        # The x, y and z values of the current frame.
        unitCell, config = self.configuration["dcd_file"]["instance"].read_step()
        
        conf = Configuration(self._universe,config)
        
        # If the universe is periodic set its shape with the current dimensions of the unit cell.
        if self._universe.is_periodic:
            self._universe.setShape(get_basis_vectors_from_cell_parameters(unitCell))
        
        self._universe.setConfiguration(conf)
        
        if self.configuration['fold']["value"]:        
            self._universe.foldCoordinatesIntoBox()
                                                   
        # The current time.
        t = (index+1)*self.configuration["dcd_file"]["instance"]['time_step']

        # Store a snapshot of the current configuration in the output trajectory.
        self._snapshot(data={'time': t})
                                        
        return index, None

    def combine(self, index, x):
        """
        Combines returned results of run_step.\n
        :Parameters:
            #. index (int): The index of the step.\n
            #. x (any): The returned result(s) of run_step
        """   
        
        pass
    
    def finalize(self):
        """
        Finalizes the calculations (e.g. averaging the total term, output files creations ...).
        """ 

        # Close the output trajectory.
        self._trajectory.close()