TINKERParser.py 132 KB
Newer Older
Berk Onat's avatar
Berk Onat committed
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
from builtins import map
from builtins import range
from builtins import object
import setup_paths
import numpy as np
import nomadcore.ActivateLogging
from nomadcore.caching_backend import CachingLevel
from nomadcore.simple_parser import SimpleMatcher as SM
from nomadcore.smart_parser import SmartParserCommon as SmartParser
from nomadcore.smart_parser.SmartParserCommon import get_metaInfo, conv_str, conv_int, conv_float, open_section
from nomadcore.smart_parser.SmartParserDictionary import getList_MetaStrInDict, getDict_MetaStrInDict
from nomadcore.smart_parser.SmartParserDictionary import isMetaStrInDict, setMetaStrInDict, copyMetaDictToDict
from TINKERDictionary import get_updateDictionary, set_Dictionaries
from TINKERCommon import PARSERNAME, PROGRAMNAME, PARSERVERSION, PARSERTAG, LOGGER
from TINKERCommon import PARSER_INFO_DEFAULT, META_INFO_PATH, set_excludeList, set_includeList
from nomadcore.md_data_access import MDDataAccess as MDDA
#from nomadcore.md_data_access.MDDataAccess import is_file_binary, is_binary_string
import argparse
import logging
import os
import re
import sys
import datetime
import io
import fnmatch

############################################################
# This is the parser for the main file of TINKER.
############################################################

#PRINTABLE = re.compile(r"\W+")

TEXTCHARS = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})

def is_file_binary(fName, checkBytes=None):
    if checkBytes is None:
        checkBytes = 1024 
    with open(fName, 'rb') as fin:
        testin = fin.read(checkBytes)
    if is_binary_string(testin):
        return True
    else:
        return False

def is_binary_string(inbytes):
    return bool(inbytes.translate(None, TEXTCHARS))

class TINKERParser(SmartParser.ParserBase):
    """Context for parsing TINKER main file.

    This class keeps tracks of several TINKER settings to adjust the parsing to them.
    The onClose_ functions allow processing and writing of cached values after a section is closed.
    They take the following arguments:
        backend: Class that takes care of writing and caching of metadata.
        gIndex: Index of the section that is closed.
        section: The cached values and sections that were found in the section that is closed.
    """
    def __init__(self):
        # dictionary of energy values, which are tracked between SCF iterations and written after convergence
        self.totalEnergyList = {
                                'energy_electrostatic': None,
                                'energy_total_T0_per_atom': None,
                                'energy_free_per_atom': None,
                               }
        SmartParser.ParserBase.__init__(
            self, re_program_name=re.compile(r"\s*"+PROGRAMNAME+"$"),
            parsertag=PARSERTAG, metainfopath=META_INFO_PATH, 
            parserinfodef=PARSER_INFO_DEFAULT, recorderOn=True)

        set_Dictionaries(self)
        self.metaInfoEnv = get_metaInfo(self)
        self.secGIndexDict = {}

        self.cachingLevelForMetaName = {
                               PARSERTAG + '_trajectory_file_detect': CachingLevel.Cache,
                               PARSERTAG + '_geometry_optimization_cdetect': CachingLevel.Cache,
                               PARSERTAG + '_mdin_finline': CachingLevel.Ignore,
                               #PARSERTAG + '_section_input_output_files': CachingLevel.Ignore,
                               PARSERTAG + '_single_configuration_calculation_detect': CachingLevel.Cache,
                              }
        for name in self.metaInfoEnv.infoKinds:
            metaInfo = self.metaInfoEnv.infoKinds[name]
            if (name.startswith(PARSERTAG + '_mdin_') and
                metaInfo.kindStr == "type_document_content" and
                (PARSERTAG + "_mdin_method" in metaInfo.superNames or 
                 PARSERTAG + "_mdin_run" in metaInfo.superNames or 
                 PARSERTAG + "_mdin_system" in metaInfo.superNames) or
                name.startswith(PARSERTAG + '_parm_') and
                metaInfo.kindStr == "type_document_content" and
                (PARSERTAG + "_mdin_method" in metaInfo.superNames or 
                 PARSERTAG + "_mdin_run" in metaInfo.superNames or
                 PARSERTAG + "_mdin_system" in metaInfo.superNames) or
                #name.startswith(PARSERTAG + '_mdin_file_') and
                name.startswith(PARSERTAG + '_inout_file_') or
                #metaInfo.kindStr == "type_document_content" and
                #(PARSERTAG + "_section_input_output_files" in metaInfo.superNames or 
                # "section_run" in metaInfo.superNames) or
                name.startswith(PARSERTAG + '_inout_control_') or
                #(PARSERTAG + "_section_control_parameters" in metaInfo.superNames) or 
                #name.startswith(PARSERTAG + '_mdin_') and
                #(PARSERTAG + "_section_control_parameters" in metaInfo.superNames) or
                name.startswith(PARSERTAG + '_mdout_') or
                name.startswith(PARSERTAG + '_mdout_') and
                #metaInfo.kindStr == "type_document_content" and
                (PARSERTAG + "_mdout_method" in metaInfo.superNames or 
                 PARSERTAG + "_mdout_system" in metaInfo.superNames or
                 "section_run" in metaInfo.superNames or
                 PARSERTAG + "_mdout_single_configuration_calculation" in metaInfo.superNames)
                or name.startswith('section_single_configuration_calculation')
                or PARSERTAG + '_mdout' in metaInfo.superNames
                or 'section_sampling_method' in metaInfo.superNames
                or 'section_single_configuration_calculation' in metaInfo.superNames
               ):
                self.cachingLevelForMetaName[name] = CachingLevel.Cache
            if name in self.extraDict.keys():
                self.cachingLevelForMetaName[name] = CachingLevel.Ignore


    def initialize_values(self):
        """Initializes the values of certain variables.

        This allows a consistent setting and resetting of the variables,
        when the parsing starts and when a section_run closes.
        """
        set_Dictionaries(self)
        self.secGIndexDict.clear()
        self.fileUnitDict = {}
        self.tinkerBaseName = None
        self.secMethodGIndex = None
        self.secSystemGIndex = None
        self.secTopologyGIndex = None
        self.secSamplingGIndex = None
        self.secSingleGIndex = None
        self.secVDWGIndex = None
        self.secAtomType = None
        self.inputMethodIndex = None
        self.inputControlIndex = None
        self.mainMethodIndex = None
        self.mainCalcIndex = None
        self.MD = True
        self.topoDict = None
        self.topologyTable = None
        self.topologyBonds = None
        self.topology = None
        self.newTopo = False
        self.topologyFormat = None
        self.topologyFile = None
        self.trajectory = None
        self.trajectoryFormat = None
        self.trajectoryFile = None
        self.readChunk = 300
        self.boxlengths = None
        self.latticevectors = None
        self.atompositions = None
        self.inputcoords = None
        self.inputpositions = None
        self.outputcoords = None
        self.outputpositions = None
        # start with -1 since zeroth iteration is the initialization
        self.MDiter = -1
        self.MDstep = 1
        self.MDcurrentstep = -1
        self.MDreadstep = 0
        self.cntrlparmstep = [-1]
        self.opencntrlstep = [-1]
        self.samplingstep = 0
        self.MDnextstep = 0
        self.singleConfCalcs = []
        self.minConverged = None
        self.parsedLogFile = False
        self.LogSuperContext = None
        self.forces_raw = []
        self.ffparams = []
        self.lastCalculationGIndex = None
        self.logFileName = None
        self.lastfInLine = None
        self.lastfInMatcher = None
        self.recordList = None
        self.stopControl = None
        self.numatoms = None
        self.secOpen = open_section
        self.superP = self.parser.backend.superBackend
        self.MDData = MDDA.MDDataAccess()
        self.inputCntrlFile = None
        if self.recordList:
            self.recordList.close()
        self.recordList = io.StringIO()

    def reset_values(self):
        self.minConverged = None
        self.trajectory = None
        self.newTopo = False
        self.newTraj = False
        self.newIncoord = False
        #self.secMethodGIndex = 0
        self.secSystemGIndex = 0
        #self.secTopologyGIndex = 0
        self.secSamplingGIndex = 0
        self.secSingleGIndex = 0
        self.secVDWGIndex = 0
        self.secAtomType = 0
        self.inputMethodIndex = 0
        self.inputControlIndex = 0
        self.mainMethodIndex = 0
        self.mainCalcIndex = 0
        self.MD = True
        self.MDiter = -1
        self.MDstep = 1
        self.MDcurrentstep = -1
        self.MDreadstep = 0
        self.MDnextstep = 0
        self.cntrlparmstep = [-1]
        self.opencntrlstep = [-1]
        self.samplingstep = 0
        self.singleConfCalcs = []
        self.lastCalculationGIndex = None
        self.inputCntrlFile = None
        set_Dictionaries(self)
        if self.recordList:
            self.recordList.close()
        self.recordList = io.StringIO()

    def startedParsing(self, fInName, parser):
        """Function is called when the parsing starts.

        Get compiled parser, filename and metadata.

        Args:
            fInName: The file name on which the current parser is running.
            parser: The compiled parser. Is an object of the class SimpleParser in nomadcore.simple_parser.py.
        """
        self.parser = parser
        self.fName = fInName
        self.working_dir_name = os.path.dirname(os.path.abspath(self.fName))
        # save metadata
        self.metaInfoEnv = self.parser.parserBuilder.metaInfoEnv
        # allows to reset values if the same superContext is used to parse different files
        self.initialize_values()

#    def peekline(self, parser):
#        pos = parser.fIn.fIn.tell()
#        line = parser.fIn.fIn.readline()
#        parser.fIn.fIn.seek(pos)
#        return line

    def onOpen_section_run(self, backend, gIndex, section):
        # keep track of the latest section
        self.secRunGIndex = gIndex
        self.secRunOpen = True

    def onClose_section_run(self, backend, gIndex, section):
        """Trigger called when section_run is closed.

        Write the keywords from control parametres and 
        the TINKER output from the parsed log output, 
        which belong to settings_run.
        Variables are reset to ensure clean start for new run.
        """
        frameSequenceGIndex = backend.openSection("section_frame_sequence")
        section_frameseq_Dict = get_updateDictionary(self, 'frameseqend')
        updateFrameDict = {
                'startSection' : [
                    ['section_frame_sequence']],
                #'muteSections' : [['section_sampling_method']],
                'dictionary' : section_frameseq_Dict
                }
        self.metaStorage.update(updateFrameDict)
        self.metaStorage.updateBackend(backend.superBackend, 
                startsection=['section_frame_sequence'],
                autoopenclose=False)
        backend.addValue("frame_sequence_to_sampling_ref", self.secSamplingGIndex)
        backend.addArrayValues("frame_sequence_local_frames_ref", np.asarray(self.singleConfCalcs))
        backend.closeSection("section_frame_sequence", frameSequenceGIndex)

        # reset all variables
        #self.initialize_values()
        self.secRunOpen = False
        self.metaStorage.reset({'startSection' : [['section_run']]})
Berk Onat's avatar
Berk Onat committed
279
        self.metaStorageRestrict.reset({'startSection' : [['section_restricted_uri']]})
Berk Onat's avatar
Berk Onat committed
280
281
        self.reset_values()

Berk Onat's avatar
Berk Onat committed
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
    def parameter_file_name(self, cntrldict, itemdict):
        """ Function to generate data for parameter files list
        """
        working_dir_name = os.path.dirname(os.path.normpath(os.path.abspath(self.fName)))
        parmmeta = isMetaStrInDict("parameters",self.cntrlDict)
        filename = []
        if parmmeta is not None:
            if self.cntrlDict[parmmeta].value is not None:
                fname = self.cntrlDict[parmmeta].value
                filename.append(fname.replace(working_dir_name, '.'+os.path.sep))
        if filename:
            return False, filename, itemdict
        else:
            return False, None, itemdict

297
    def tinker_input_output_files(self, backend, gIndex, section, call_level):
Berk Onat's avatar
Berk Onat committed
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
        """Called with onClose_x_tinker_section_control_parameters to setup
            topology and trajectory inputs/outputs

        Determine whether topology, trajectory and input coordinate files are
        supplied to the parser
        
        Initiates topology and trajectory file handles.

        Captures topology, atomic positions, atom labels, lattice vectors and 
        stores them before section_system and 
        section_single_configuration_calculation are encountered.
        """
        # Checking whether topology, input 
        # coordinates and trajectory files exist
        fileList=None
        fKey = PARSERTAG + '_inout_file_'
        working_dir_name = os.path.dirname(os.path.abspath(self.fName))
        try:
            getattr(self, "filesInOutputDir")
        except AttributeError:
            self.filesInOutputDir = {}
            fileList = [x for x in os.walk(os.path.abspath(working_dir_name))]
            for fdir, fchilds, fnames in fileList:
                for fname in fnames:
                    fkeyname = os.path.normpath(os.path.join(fdir, fname))
                    self.filesInOutputDir.update({fkeyname.upper():fkeyname})

        # Reset all file definitions to None and inactive
        atLeastOneFileExist = False # also be used to check any updates
        for k,v in self.fileDict.items():
            if k.startswith(fKey):
                self.fileDict[k].value = None
                self.fileDict[k].activeInfo = False
                self.fileDict[k].fileSupplied = False

        #inputOK = self.findInputCmdFileAndRead(parser)


        # Here we update topology info
        # Check if topology files can be loaded
        self.newTopo = False
        self.newIncoord=False
        self.newOutcoord=False
        topoDone=False
        IncoordDone=False
        OutcoordDone=False
        topoFile = self.findFileInDir(parser, "topology file", "filecntrlDict")
        #confFile = self.findFileInDir(parser, "configuration file", "filecntrlDict")
        inconfFile = self.findFileInDir(parser, "initial configuration file", "filecntrlDict")
        outcoorFile = self.findFileInDir(parser, "restart file", "filecntrlDict")
        outconfFile = self.findFileInDir(parser, "final configuration file", "filecntrlDict")
        arcFile = self.findFileInDir(parser, "archive file", "filecntrlDict")
        if topoFile is not None:
            if topoFile.upper() in self.filesInOutputDir:
                file_name = self.filesInOutputDir[topoFile.upper()]
                self.fileDict[fKey+'structure'].value = file_name.replace(
                        working_dir_name+os.path.sep, '')
                self.fileDict[fKey+'structure'].fileName = file_name
                self.fileDict[fKey+'structure'].activeInfo = True
                self.fileDict[fKey+'structure'].fileSupplied = True
                atLeastOneFileExist = True
                topoDone = True
                self.newTopo = True
                self.newIncoord=True

        if inconfFile is not None:
            if inconfFile.upper() in self.filesInOutputDir:
                file_name = self.filesInOutputDir[inconfFile.upper()]
                self.fileDict[fKey+'input_coord'].value = file_name.replace(
                        working_dir_name+os.path.sep, '')
                self.fileDict[fKey+'input_coord'].fileName = file_name
                self.fileDict[fKey+'input_coord'].activeInfo = True
                self.fileDict[fKey+'input_coord'].fileSupplied = True
                atLeastOneFileExist = True
                IncoordDone = True
                self.newIncoord=True

        if outconfFile is not None:
            if outconfFile.upper() in self.filesInOutputDir:
                file_name = self.filesInOutputDir[outconfFile.upper()]
                self.fileDict[fKey+'output_coord'].value = file_name.replace(
                        working_dir_name+os.path.sep, '')
                self.fileDict[fKey+'output_coord'].fileName = file_name
                self.fileDict[fKey+'output_coord'].activeInfo = True
                self.fileDict[fKey+'output_coord'].fileSupplied = True
                atLeastOneFileExist = True
                OutcoordDone = True
                self.newOutcoord=True

        if OutcoordDone is False:
            if outcoorFile is not None:
                if outcoorFile.upper() in self.filesInOutputDir:
                    file_name = self.filesInOutputDir[outcoorFile.upper()]
                    self.fileDict[fKey+'output_coord'].value = file_name.replace(
                            working_dir_name+os.path.sep, '')
                    self.fileDict[fKey+'output_coord'].fileName = file_name
                    self.fileDict[fKey+'output_coord'].activeInfo = True
                    self.fileDict[fKey+'output_coord'].fileSupplied = True
                    atLeastOneFileExist = True
                    OutcoordDone = True
                    self.newOutcoord=True

        self.newTraj = False
        trajDone=False
        if arcFile is not None:
            file_name = arcFile
            self.fileDict[fKey+'trajectory'].value = file_name.replace(
                    working_dir_name+os.path.sep, '')
            self.fileDict[fKey+'trajectory'].fileName = file_name
            self.fileDict[fKey+'trajectory'].activeInfo = True
            self.fileDict[fKey+'trajectory'].fileSupplied = True
            atLeastOneFileExist = True
            trajDone = True
            self.newTraj = True

        if self.newTopo:
            if topoDone and atLeastOneFileExist:
                self.MDData.initializeTopologyFileHandlers(self)
                if self.topology:
                    self.topoDict = self.topology.topoDict
        if self.newTraj:
            if trajDone and atLeastOneFileExist:
                self.MDData.initializeTrajectoryFileHandlers(self)
                if self.trajectory:
                    self.atompositions = self.trajectory.positions()
        if self.newIncoord:
            if IncoordDone and atLeastOneFileExist:
                self.MDData.initializeInputCoordinateFileHandlers(self)
                if self.inputcoords:
                    self.inputpositions = self.inputcoords.positions()
                    self.numatoms = len(self.inputpositions)
        if self.newOutcoord:
            if OutcoordDone and atLeastOneFileExist:
                self.MDData.initializeInputCoordinateFileHandlers(self)
                if self.outputcoords:
                    self.outputpositions = self.outputcoords.positions()
                    self.numatoms = len(self.outputpositions)
        if self.topology:
            if self.topology.n_atoms is not None:
                if self.atompositions:
                    self.topology.n_atoms = len(self.atompositions)
                elif self.inputpositions:
                    self.topology.n_atoms = len(self.inputpositions)
                elif self.numatoms:
                    self.topology.n_atoms = self.numatoms
                #self.MDData.initializeOutputCoordinateFileHandlers(self)
                #self.MDData.initializeFileHandlers(self)
                #if self.outputcoords:
                #    self.outputpositions = self.outputcoords.positions()
                #self.MDiter += self.MDstep
                #self.MDiter += 1
                #self.MDcurrentstep = int(self.MDiter)
                #self.stepcontrolDict.update({"MDcurrentstep" : int(self.MDcurrentstep)})
                #pass
452
        return atLeastOneFileExist
Berk Onat's avatar
Berk Onat committed
453
454
455
456
457
458
459

    def onOpen_x_tinker_section_control_parameters(self, backend, gIndex, section):
        # keep track of the latest section
        if self.inputControlIndex is None:
            self.inputControlIndex = gIndex

    def onClose_x_tinker_section_control_parameters(self, backend, gIndex, section):
460
461
        # Find input and output files. Read input control parameters
        atLeastOneFileExist = self.tinker_input_output_files(backend, gIndex, section, "control")
Berk Onat's avatar
Berk Onat committed
462
463
464
465
466
467
468
469
470
471
472
473
474
        section_control_Dict = {}
        section_control_Dict.update(self.mdcntrlDict)
        section_control_Dict.update(self.filecntrlDict)
        section_control_Dict.update(self.cntrlDict)
        updateDict = {
            'startSection' : [[PARSERTAG+'_section_control_parameters']],
            'dictionary'   : section_control_Dict
            }
        self.metaStorage.update(updateDict)
        self.metaStorage.updateBackend(backend.superBackend, 
                startsection=[PARSERTAG+'_section_control_parameters'],
                autoopenclose=False)

475
476
477
478
479
480
481
482
483
484
485
        #if atLeastOneFileExist:
        #    secIOGIndex = backend.openSection(PARSERTAG+'_section_input_output_files')
        #    updateFileDict = {
        #            'startSection'   : [[PARSERTAG+'_section_input_output_files']],
        #            'dictionary'     : self.fileDict
        #            }
        #    self.metaStorage.update(updateFileDict)
        #    self.metaStorage.updateBackend(backend.superBackend,
        #            startsection=[PARSERTAG+'_section_input_output_files'],
        #            autoopenclose=False)
        #    backend.closeSection(PARSERTAG+'_section_input_output_files', secIOGIndex)
Berk Onat's avatar
Berk Onat committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617

        # TINKER prints the initial and final energies to the log file.
        if self.MDcurrentstep < 0:
            self.MDcurrentstep += 1
            self.MDcurrentstep = int(self.MDcurrentstep)
        self.stepcontrolDict.update({"MDcurrentstep" : int(self.MDcurrentstep)})
        nsteps = 0
        nlogsteps = 0
        nstructstep = 0
        ninputstep = 0
        noutputstep = 0
        ntrajsteps = 0
        nvelsteps = 0 
        nforcesteps = 0 
        filesteps = None
        filefreq = None
        numSecRun = str(self.secRunGIndex)

        if self.secRunGIndex in self.fileUnitDict:
            if 'filesteps' in self.fileUnitDict[self.secRunGIndex]:
                filesteps = self.fileUnitDict[self.secRunGIndex]['filesteps']
                if len(filesteps)>0:
                    filefreq = filesteps[0]

        nstructKey = isMetaStrInDict("topology file",self.filecntrlDict)
        ninputKey = isMetaStrInDict("initial configuration file",self.filecntrlDict)
        nxoutKey = isMetaStrInDict("archive file",self.filecntrlDict)
        if nxoutKey is None:
            nxoutKey = isMetaStrInDict("initial trajectory file",self.filecntrlDict)
        noutputKey = isMetaStrInDict("final configuration file",self.filecntrlDict)
        #nminstepKey = isMetaStrInDict("EMIN-NMIN", self.cntrlDict)
        nstepKey = isMetaStrInDict("NSTEP", self.cntrlDict)
        nlogKey = isMetaStrInDict("PRINTOUT", self.cntrlDict)
        if nstepKey is not None:
            if self.cntrlDict[nstepKey].activeInfo:
                nsteps = conv_int(self.cntrlDict[nstepKey].value, default=0)
            else:
                #nsteps = conv_int(self.cntrlDict[nstepKey].defaultValue, default=0)
                nsteps = 0
        #if nminstepKey is not None:
        #    if self.cntrlDict[nminstepKey].activeInfo:
        #        self.MD = False
        #        nsteps = conv_int(self.cntrlDict[nminstepKey].value, default=0)
        if nlogKey is not None:
            if self.cntrlDict[nlogKey].activeInfo:
                nlogsteps = conv_int(self.cntrlDict[nlogKey].value, default=1)
            else:
                nlogsteps = 1
        else:
            nlogsteps = 1
        #if nxoutKey is not None:
        #    if self.cntrlDict[nxoutKey].activeInfo:
        #        ntrajsteps = conv_int(self.cntrlDict[nxoutKey].value, default=0)
        if nstructKey is not None:
            if self.filecntrlDict[nstructKey].activeInfo:
                nstructstep = 1
        if ninputKey is not None:
            if self.filecntrlDict[ninputKey].activeInfo:
                ninputstep = 1
        if noutputKey is not None:
            if self.filecntrlDict[noutputKey].activeInfo:
                noutputstep = 1
        
        if nlogsteps>0:
            logsteps = [i for i in range(1, nsteps, nlogsteps)]
            logsteps.append(nsteps)
        else:
            logsteps = [1, nsteps]
            #logsteps.append(nsteps)
        trajsteps = []
        if filesteps is not None:
            if(ninputstep>0 or nstructstep>0):
                if 1 not in filesteps:
                    trajsteps.append(1)
                    rtn = setMetaStrInDict(self, 'mddataDict', 'InputCoordStep', int(1))
            for trjs in filesteps:
                trajsteps.append(trjs)
            if noutputstep>0:
                if nsteps not in filesteps:
                    trajsteps.append(nsteps)
                    rtn = setMetaStrInDict(self, 'mddataDict', 'OutputCoordStep', int(nsteps))
        else:
            if(ninputstep>0 or nstructstep>0):
                trajsteps.append(1)
                rtn = setMetaStrInDict(self, 'mddataDict', 'InputCoordStep', int(1))
            if noutputstep>0:
                trajsteps.append(nsteps)
                rtn = setMetaStrInDict(self, 'mddataDict', 'OutputCoordStep', int(nsteps))

        #if ntrajsteps>0:
        #    trajsteps = [i for i in range(1, nsteps, ntrajsteps)]
        #    trajsteps.append(nsteps)
        #else:
        #    trajsteps = []
        #    if(ninputstep>0 or nstructstep>0):
        #        trajsteps.append(0)
        #    if noutputstep>0:
        #        trajsteps.append(nsteps)
        if nvelsteps>0:
            velsteps = [i for i in range(1, nsteps, nvelsteps)]
            velsteps.append(nsteps)
        else:
            velsteps = []
            #velsteps.append(nsteps)
        if nforcesteps>0:
            forcesteps = [i for i in range(1, nsteps, nforcesteps)]
            forcesteps.append(nsteps)
        else:
            forcesteps = []
            #forcesteps.append(nsteps)
        self.stepcontrolDict.update({"logsteps"     : logsteps})
        self.stepcontrolDict.update({"nextlogsteps" : logsteps})
        self.stepcontrolDict.update({"trajsteps"    : trajsteps})
        self.stepcontrolDict.update({"velsteps"     : velsteps})
        self.stepcontrolDict.update({"forcesteps"   : forcesteps})
        steps = []
        for step in range(1,nsteps+1):
            if(step in logsteps or
               step in trajsteps or
               step in velsteps or
               step in forcesteps):
               steps.append(step)
        #steps = logsteps if len(logsteps)>len(trajsteps) else trajsteps
        #followsteps = "log" if len(logsteps)>len(trajsteps) else "traj"
        #steps = steps if len(steps)>len(velsteps) else velsteps
        #followsteps = followsteps if len(steps)>len(velsteps) else "vel"
        #self.stepcontrolDict.update({"steps"  : steps if len(steps)>len(forcesteps) else forcesteps})
        #self.stepcontrolDict.update({"follow" : followsteps if len(steps)>len(enersteps) else "force"})
        self.stepcontrolDict.update({"steps"  : steps})
        #self.stepcontrolDict.update({"follow" : followsteps})
        self.onOpen_section_sampling_method(backend, None, None)
        self.onClose_section_sampling_method(backend, None, None)
Berk Onat's avatar
Berk Onat committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
        section_file_Dict = {}
        section_file_Dict.update(self.fileDict)
        updateDict = {
                'startSection' : [[PARSERTAG+'_section_control_parameters']],
                'dictionary'   : section_file_Dict
                }
        self.metaStorage.update(updateDict)
        self.metaStorage.updateBackend(backend.superBackend, 
                startsection=[PARSERTAG+'_section_control_parameters'],
                autoopenclose=False)
        parmmeta = isMetaStrInDict("parameters",self.cntrlDict)
        if parmmeta is not None:
            if self.cntrlDict[parmmeta].value is not None:
                self.secRestrictGIndex = backend.superBackend.openSection("section_restricted_uri")
                restrictionsDict = get_updateDictionary(self, 'restrictions')
                updateDict = {
                        'startSection' : [['section_restricted_uri']],
                        'dictionary' : restrictionsDict
                        }
                self.metaStorageRestrict.update(updateDict)
                self.metaStorageRestrict.updateBackend(backend.superBackend, 
                        startsection=['section_restricted_uri'],
                        autoopenclose=False)
                backend.superBackend.closeSection("section_restricted_uri", self.secRestrictGIndex)
Berk Onat's avatar
Berk Onat committed
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946

    def onOpen_section_method(self, backend, gIndex, section):
        # keep track of the latest method section
        self.secMethodGIndex = gIndex
        if self.inputMethodIndex is None:
            self.inputMethodIndex = gIndex
        else:
            backend.openNonOverlappingSection("section_method_to_method_refs")
            backend.addValue("method_to_method_kind", "core_settings")
            backend.addValue("method_to_method_ref", self.inputMethodIndex)
            backend.closeNonOverlappingSection("section_method_to_method_refs")
        if self.mainMethodIndex is None:
            self.mainMethodIndex = gIndex

    def onClose_section_method(self, backend, gIndex, section):
        """Trigger called when section_method is closed.
        """
        # input method
        pass

    def onOpen_section_sampling_method(self, backend, gIndex, section):
        # keep track of the latest sampling description section
        if (gIndex is None or gIndex == -1 or gIndex == "-1"):
            self.secSamplingGIndex = backend.superBackend.openSection("section_sampling_method")
        else:
            self.secSamplingGIndex = gIndex
        #self.inputControlIndex = backend.superBackend.openSection(PARSERTAG + '_section_control_parameters')

    def onClose_section_sampling_method(self, backend, gIndex, section):
        """Trigger called when section_sampling_method is closed.

        Writes sampling method details for minimization and molecular dynamics.
        """
        # check control keywords were found throguh dictionary support
        #backend.superBackend.closeSection(PARSERTAG + '_section_control_parameters', self.inputControlIndex)
        section_sampling_Dict = get_updateDictionary(self, 'sampling')
        updateDict = {
            #'startSection' : [['section_sampling_method']],
            'startSection' : [['section_run']],
            'dictionary' : section_sampling_Dict
            }
        self.metaStorage.update(updateDict)
        self.metaStorage.updateBackend(backend.superBackend, 
                startsection=['section_run'],
                #startsection=['section_sampling_method'],
                autoopenclose=False)
        if (gIndex is None or gIndex == -1 or gIndex == "-1"):
            backend.superBackend.closeSection("section_sampling_method", self.secSamplingGIndex)
    
    def onOpen_section_topology(self, backend, gIndex, section):
        # keep track of the latest topology description section
        if (gIndex is None or gIndex == -1 or gIndex == "-1"):
            self.secTopologyGIndex = backend.superBackend.openSection("section_topology")
        else:
            self.secTopologyGIndex = gIndex

    def onClose_section_topology(self, backend, gIndex, section):
        """Trigger called when section_topology is closed.
        """
        section_topology_Dict = get_updateDictionary(self, 'topology')
        updateDict = {
            'startSection' : [
                ['section_topology']],
            #'muteSections' : [['section_sampling_method']],
            'dictionary' : section_topology_Dict
            }
        self.metaStorage.update(updateDict)
        self.metaStorage.updateBackend(backend.superBackend, 
                startsection=['section_topology'],
                autoopenclose=False)
        self.topology_atom_type_and_interactions(backend, gIndex)

        if (gIndex is None or gIndex == -1 or gIndex == "-1"):
            backend.superBackend.closeSection("section_topology", self.secTopologyGIndex)

    def onOpen_section_system(self, backend, gIndex, section):
        # keep track of the latest system description section
        if (gIndex is None or gIndex == -1 or gIndex == "-1"):
            self.secSystemGIndex = backend.superBackend.openSection("section_system")
        else:
            self.secSystemGIndex = gIndex

    def onClose_section_system(self, backend, gIndex, section):
        """Trigger called when section_system is closed.

        Writes atomic positions, atom labels and lattice vectors.
        """
        # Our special recipe for the confused backend and more
        # See our other recipes at the back of this parser: MetaInfoStorage! :)
        if (gIndex is None or gIndex == -1 or gIndex == "-1"):
            SloppyBackend = backend.superBackend
        else:
            SloppyBackend = backend
 
        numatoms = None
        if self.numatoms is not None:
            numatoms = self.numatoms

        # TINKER default unit vectors. If all are zeros than the simulation cell is not periodic.
        unit_vectors = np.asarray(
                [[0.0,0.0,0.0],
                 [0.0,0.0,0.0],
                 [0.0,0.0,0.0]]
                )
        vaKey = isMetaStrInDict("PERIODIC CELL BASIS 1",self.cntrlDict)
        vbKey = isMetaStrInDict("PERIODIC CELL BASIS 2",self.cntrlDict)
        vcKey = isMetaStrInDict("PERIODIC CELL BASIS 3",self.cntrlDict)
        if vaKey is not None:
            if self.cntrlDict[vaKey].value is not None:
                unit_vectors[:,0]=np.asarray([ float(i) for i in self.cntrlDict[vaKey].value.split()])
        if vbKey is not None:
            if self.cntrlDict[vbKey].value is not None:
                unit_vectors[:,1]=np.asarray([ float(i) for i in self.cntrlDict[vbKey].value.split()])
        if vcKey is not None:
            if self.cntrlDict[vcKey].value is not None:
                unit_vectors[:,2]=np.asarray([ float(i) for i in self.cntrlDict[vcKey].value.split()])
        if self.trajectory is not None:
            if self.trajectory.unitcell_vectors is None:
                self.trajectory.unitcell_vectors = unit_vectors
        
        if self.topology:
            if self.newTopo:
#            if (self.secTopologyGIndex is None or
#                (self.secTopologyGIndex == -1 or 
#                self.secTopologyGIndex == "-1")):
                self.onOpen_section_topology(backend, None, None)
                self.onClose_section_topology(backend, None, None)
                self.newTopo=False
        if self.secTopologyGIndex is not None:
            SloppyBackend.addValue("topology_ref", self.secTopologyGIndex)

        coordinates=None
        steps = self.stepcontrolDict["steps"]
        if self.trajectory is not None:
            coordinates=self.trajectory
            positions=self.atompositions
        elif(self.inputcoords is not None and 
             self.MDcurrentstep == steps[0]):
            coordinates=self.inputcoords
            positions=self.inputpositions
        elif(self.outputcoords is not None and
             self.MDcurrentstep == steps[-1]):
            coordinates=self.outputcoords
            positions=self.outputpositions

        if(coordinates is not None and positions is not None):
            self.trajRefSingleConfigurationCalculation = gIndex
            if coordinates.unitcell_vectors is not None:
                unit_cell = np.asarray(self.metaStorage.convertUnits(
                    coordinates.unitcell_vectors, "nano-meter", self.unitDict))
                SloppyBackend.addArrayValues('simulation_cell', unit_cell)
                SloppyBackend.addArrayValues('lattice_vectors', unit_cell)
            if coordinates.unitcell_lengths is not None:
                SloppyBackend.addArrayValues(PARSERTAG + '_lattice_lengths', coordinates.unitcell_lengths)
            if coordinates.unitcell_angles is not None:
                SloppyBackend.addArrayValues(PARSERTAG + '_lattice_angles', coordinates.unitcell_angles)
            # TINKER Guide says: (See http://www.ks.uiuc.edu/Research/tinker/2.12/ug/node11.html)
            # Positions in PDB/TINKER binary/DCD files are stored in A.
            #pos_obj = getattr(self.trajectory, 'positions', None)
            #if callable(pos_obj):
            SloppyBackend.addArrayValues('atom_positions', np.transpose(np.asarray(
                self.metaStorage.convertUnits(positions, "nano-meter", self.unitDict))))
            if coordinates.velocities is not None:
                # Velocities in PDB files are stored in A/ps units.(PDB files are read for input 
                #     coordinates, velocities, and forces)
                # Velocities in TINKER binary/DCD files are stored in TINKER internal units and must be multiplied 
                #     by PDBVELFACTOR=20.45482706 to convert to A/ps. (These files are used for output trajectory)
                SloppyBackend.addArrayValues('atom_velocities', np.transpose(np.asarray(
                    self.metaStorage.convertUnits(
                        coordinates.velocities, "(nano-meter)/(pico-second)", self.unitDict))))
                # need to transpose array since its shape is [number_of_atoms,3] in the metadata

            if self.topology is not None:
                atom_labels = self.topoDict["atom_element_list"]
                numatoms = len(atom_labels)
                self.numatoms
                SloppyBackend.addArrayValues('atom_labels', np.asarray(atom_labels))
                pass
        else:
            if unit_vectors is not None:
                unit_cell = np.asarray(self.metaStorage.convertUnits(
                    unit_vectors, "nano-meter", self.unitDict))
                SloppyBackend.addArrayValues('simulation_cell', unit_cell)
                SloppyBackend.addArrayValues('lattice_vectors', unit_cell)

        if self.trajectory is not None:
            # Read the next step at trajectory in advance
            # If iread returns None, it will be the last step
            try:
                self.atompositions = self.trajectory.positions()
                if self.atompositions is not None:
                    numatoms = len(self.atompositions)
                #self.MDiter += self.MDstep
                #self.MDiter += 1
            except AttributeError:
                self.atompositions = None
                pass

        if unit_vectors is not None:
            unit_periodicity=np.asarray([False,False,False])
            if np.linalg.norm(unit_vectors[0])>0.0:
                unit_periodicity[0]=True
            if np.linalg.norm(unit_vectors[1])>0.0:
                unit_periodicity[1]=True
            if np.linalg.norm(unit_vectors[2])>0.0:
                unit_periodicity[2]=True
            SloppyBackend.addArrayValues('configuration_periodic_dimensions', unit_periodicity)
 
        if self.topology is not None:
            self.topology_system_name(backend, gIndex)

        if numatoms:
            SloppyBackend.addValue("number_of_atoms", numatoms)

        if (gIndex is None or gIndex == -1 or gIndex == "-1"):
            SloppyBackend.closeSection("section_system", self.secSystemGIndex)

    def onOpen_section_single_configuration_calculation(self, backend, gIndex, section):
        # write the references to section_method and section_system
        self.singleConfCalcs.append(gIndex)
        self.secSingleGIndex = backend.superBackend.openSection("section_single_configuration_calculation")

    def onClose_section_single_configuration_calculation(self, backend, gIndex, section):
        """Trigger called when section_single_configuration_calculation is closed.

        Write number of steps in MD or Minimization.
        Check for convergence of geometry optimization.
        Write energy values at MD and with error in Minimization.
        Write reference to section_method and section_system
        """

        self.lastCalculationGIndex = gIndex
        steps = self.stepcontrolDict["steps"]
        logsteps = self.stepcontrolDict["logsteps"]
        velsteps = self.stepcontrolDict["velsteps"]
        forcesteps = self.stepcontrolDict["forcesteps"]
        trajsteps = self.stepcontrolDict["trajsteps"]
        try:
            self.MDcurrentstep = int(self.stepcontrolDict["MDcurrentstep"])
        except KeyError:
            self.stepcontrolDict.update({"MDcurrentstep" : int(self.MDcurrentstep)})
        #if len(steps)>1:
        #    self.MDstep = steps[1]-steps[0]
        #if self.MDiter<len(steps):
        #    self.MDcurrentstep = steps[self.MDiter]
        #else:
        #    self.MDcurrentstep += 1
        #if self.MDiter+1<len(steps):
        #    self.MDnextstep = steps[self.MDiter+1]
        #    self.stepcontrolDict.update({"nextlogsteps":logsteps[self.MDiter+1:]})
        #else:
        #    self.MDnextstep = steps[-1] + 1
        #self.stepcontrolDict.update({"MDcurrentstep" : self.MDcurrentstep})

        if self.MDcurrentstep in logsteps:
            section_frameseq_Dict = get_updateDictionary(self, 'frameseq')
            updateFrameDict = {
                'startSection' : [
                    ['section_frame_sequence']],
                #'muteSections' : [['section_sampling_method']],
                'dictionary' : section_frameseq_Dict
                }
            self.metaStorage.update(updateFrameDict)
            section_singlevdw_Dict = get_updateDictionary(self, 'singlevdw')
            #updateDictVDW = {
            #    'startSection' : [
            #        ['section_energy_van_der_Waals']],
            #    #'muteSections' : [['section_sampling_method']],
            #    'dictionary' : section_singlevdw_Dict
            #    }
            #self.secVDWGIndex = backend.superBackend.openSection("section_energy_van_der_Waals")
            #self.metaStorage.update(updateDictVDW)
            #self.metaStorage.updateBackend(backend.superBackend, 
            #        startsection=['section_energy_van_der_Waals'],
            #        autoopenclose=False)
            #backend.superBackend.closeSection("section_energy_van_der_Waals", self.secVDWGIndex)
            section_singlecalc_Dict = get_updateDictionary(self, 'singleconfcalc')
            updateDict = {
                'startSection' : [
                    ['section_single_configuration_calculation']],
                #'muteSections' : [['section_sampling_method']],
                'dictionary' : section_singlecalc_Dict
                }
            self.metaStorage.update(updateDict)
            self.metaStorage.updateBackend(backend.superBackend, 
                    startsection=['section_single_configuration_calculation'],
                    autoopenclose=False)
        if self.MDcurrentstep in forcesteps:
            pos_obj = getattr(self.trajectory, 'positions', None)
            #if callable(pos_obj):
            if self.trajectory.forces is not None:
                # Forces in PDB/TINKER binary/DCD files are stored in kcal/mol/A
                SloppyBackend.addArrayValues('atom_forces', np.transpose(np.asarray(
                    self.metaStorage.convertUnits(
                        self.atompositions.velocities, "kilo-joule/(mol*nano-meter)", self.unitDict))))
                # need to transpose array since its shape is [number_of_atoms,3] in the metadata
        if(self.MDcurrentstep in trajsteps or 
           self.MDcurrentstep in velsteps):
            trajfile = None
            if 'filetrajs' in self.fileUnitDict[self.secRunGIndex]:
                filetrajs = self.fileUnitDict[self.secRunGIndex]['filetrajs']
                if self.MDcurrentstep in filetrajs:
                    trajfile = filetrajs[self.MDcurrentstep]
            if trajfile is not None:
                rtn = setMetaStrInDict(self, 'filecntrlDict', 'archive file', trajfile) 
947
                self.tinker_input_output_files(backend, gIndex, section, "traj")
Berk Onat's avatar
Berk Onat committed
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200

            self.onOpen_section_system(backend, None, None)
            self.onClose_section_system(backend, None, None)
            backend.addValue('single_configuration_calculation_to_system_ref', self.secSystemGIndex)
            self.MDiter += 1
        else:
            if(self.MDcurrentstep in logsteps or 
               self.MDcurrentstep in forcesteps):
                self.MDiter += 1
            if(self.inputcoords is not None and 
               self.MDcurrentstep == steps[0] and
               self.inputpositions is not None):
                self.onOpen_section_system(backend, None, None)
                self.onClose_section_system(backend, None, None)
                backend.addValue('single_configuration_calculation_to_system_ref', self.secSystemGIndex)
                self.MDiter += 1
            if(self.outputcoords is not None and 
               self.MDcurrentstep == steps[-1] and
               self.outputpositions is not None):
                self.onOpen_section_system(backend, None, None)
                self.onClose_section_system(backend, None, None)
                backend.addValue('single_configuration_calculation_to_system_ref', self.secSystemGIndex)
                self.MDiter += 1
            #if((self.MDcurrentstep in logsteps and 
            #    self.MDiter+1 in steps) or 
            #    (self.MDcurrentstep in forcesteps and 
            #    self.MDiter+1 in steps)):
            #    self.MDiter += 1
        #if self.MDiter<len(steps):
        #    self.MDcurrentstep = steps[self.MDiter]
        #else:
        #    self.MDcurrentstep += 1
        if self.MDiter+1<len(steps):
            self.MDnextstep = int(steps[self.MDiter])
            self.stepcontrolDict.update({"nextlogsteps":logsteps[self.MDiter:]})
        else:
            self.MDnextstep = int(steps[-1] + 1)
        self.stepcontrolDict.update({"MDcurrentstep" : int(self.MDcurrentstep)})
        backend.superBackend.closeSection("section_single_configuration_calculation", self.secSingleGIndex)

    def setStartingPointCalculation(self, parser):
        backend = parser.backend
        backend.openSection('section_calculation_to_calculation_refs')
        if self.lastCalculationGIndex:
            backend.addValue('calculation_to_calculation_ref', self.lastCalculationGIndex)
            backend.closeSection('section_calculation_to_calculation_refs')
        return None

    def fileNameTrans(self, fname, value):
        return value
    
    def mdInfoTrans(self, fname, value):
        mdInfoDict = {
                "minimization" : [],
                "thermostat"   : [],
                "barostat"     : []
                }
        cgmin = isMetaStrInDict("MINIMIZATION",self.cntrlDict)
        quench = isMetaStrInDict("VELOCITY QUENCHING",self.cntrlDict)
        tcouple = isMetaStrInDict("TEMPERATURE COUPLING",self.cntrlDict)
        trescale = isMetaStrInDict("VELOCITY RESCALE FREQ",self.cntrlDict)
        treassign = isMetaStrInDict("VELOCITY REASSIGNMENT FREQ",self.cntrlDict)
        tandersen = isMetaStrInDict("LOWE-ANDERSEN DYNAMICS",self.cntrlDict)
        tlangevin = isMetaStrInDict("LANGEVIN DYNAMICS",self.cntrlDict)
        pberendsen = isMetaStrInDict("BERENDSEN PRESSURE COUPLING",self.cntrlDict)
        plangevin = isMetaStrInDict("LANGEVIN PISTON PRESSURE CONTROL",self.cntrlDict)
        mini = None
        thermo = None
        baro = None
        if cgmin is not None:
            if self.cntrlDict[cgmin].value is not None:
                mini = 'cg'
        if quench is not None:
            if self.cntrlDict[quench].value is not None:
                mini = 'quench'
        if tcouple is not None:
            if self.cntrlDict[tcouple].value is not None:
                thermo = 'tcouple'
        if trescale is not None:
            if self.cntrlDict[trescale].value is not None:
                thermo = 'rescale'
        if treassign is not None:
            if self.cntrlDict[treassign].value is not None:
                thermo = 'reassign'
        if tandersen is not None:
            if self.cntrlDict[tandersen].value is not None:
                thermo = 'andersen'
        if tlangevin is not None:
            if self.cntrlDict[tlangevin].value is not None:
                thermo = 'langevin'
        if pberendsen is not None:
            if self.cntrlDict[pberendsen].value is not None:
                baro = 'berendsen'
        if plangevin is not None:
            if self.cntrlDict[plangevin].value is not None:
                baro = 'langevin'
        for k,v in mdInfoDict.items():
            if fname in k:
                if 'thermostat' in fname:
                    return thermo
                elif 'barostat' in fname:
                    return baro
                elif 'minimization' in fname:
                    return mini
                else:
                    return value
        return value
    
    def trueToZero(self, fname, value):
        keyMapper = {
                "Molecular Dynamics" : "MDmainstep",
                "Optimization" : "MDmainstep",
                }
        if value is not None:
            for k,v in keyMapper.items():
                if fname in k:
                    return int(0)
        return value

    def convertInt(self, fname, value):
        keyMapper = {
                "MD Step"        : "MDcurrentstep",
                "Dynamics Steps" : "MDcurrentstep",
                "VM Iter"        : "MDcurrentstep",
                "TN Iter"        : "MDcurrentstep",
                "QN Iter"        : "MDcurrentstep",
                "CG Iter"        : "MDcurrentstep",
                }
        if value is not None:
            for k,v in keyMapper.items():
                if fname in k:
                    if isinstance(value, str):
                        if 'D' in value.upper():
                            value = value.replace('D', 'E').replace('d', 'E')
                    try:
                        return int(value)
                    except ValueError:
                        pass
        return value

    def convertFloat(self, fname, value):
        keyMapper = {
                "F Value"        : "E Potential",
                }
        if value is not None:
            for k,v in keyMapper.items():
                if fname in k:
                    if isinstance(value, str):
                        if 'D' in value.upper():
                            value = value.replace('D', 'E').replace('d', 'E')
                    try:
                        return float(value)
                    except ValueError:
                        pass
        return value

    def updateTime(self, fname, value):
        keyMapper = {
                "TIME" : "MDcurrentstep",
                }
        timestep = 1.0
        istimestep = isMetaStrInDict("STEP-DT",self.cntrlDict)
        if istimestep is not None:
            if self.cntrlDict[istimestep].value is not None:
                timestep = float(self.cntrlDict[istimestep].value)
        if value is not None:
            for k,v in keyMapper.items():
                if fname in k:
                    return value*timestep
        return value

    def filesFoundInDir(self, parser):
        fileList = []
        working_dir_name = os.path.dirname(os.path.abspath(self.fName))
        for afile in os.listdir(working_dir_name):
            if os.path.isfile(os.path.normpath(os.path.join(working_dir_name,afile))):
                fileList.append(afile)
                #fileList.append(os.path.normpath(os.path.join(working_dir_name,afile)))
        if fileList:
            return fileList
        else:
            return None

    def textFileFoundInDir(self, parser):
        fileList = self.filesFoundInDir(parser)
        if fileList is None:
            fileList=[]
        foundList = []
        working_dir_name = os.path.dirname(os.path.abspath(self.fName))
        for afile in fileList:
            if is_file_binary(os.path.normpath(os.path.join(working_dir_name,afile))) is False:
                foundList.append(os.path.normpath(os.path.join(working_dir_name,afile)))
        if foundList:
            return foundList
        else:
            return None

    def matchStrInTextFile(self, parser, file_name, matchReStr):
        matched = False
        matchRe = re.compile(matchReStr)
        with open(file_name, 'r') as fin:
            for line in fin:
               if matchRe.findall(line):
                   matched = True
                   break
        return matched

    def checkTextFilesMatchStr(self, parser, fileList, includeReStrList=None, excludeReStrList=None):
        includedList = []
        excludedList = []
        if includeReStrList is None:
            includeReStrList = []
        if excludeReStrList is None:
            excludeReStrList = []
        # If a match string list is given,
        # find the files have macth Re in the list
        if includeReStrList:
            for fName in fileList:
                for reStr in includeReStrList:
                    if self.matchStrInTextFile(parser,fName,reStr):
                        includedList.append(fName)
        else:
            includedList = fileList 
        # If and exclude list is given,
        # remove the files from list that
        # includes these Regular expression matches
        if excludeReStrList:
            for fName in includedList:
                for reStr in excludeReStrList:
                    if not self.matchStrInTextFile(parser,fName,reStr):
                        excludedList.append(fName)
        else:
            excludedList = includedList 
        return excludedList

    def storeTextFile(self, parser, textDict, storeName, textFile):
        if textDict:
            recordText = []
            with io.open(textFile) as fin:
                recordText.append(fin.readline())
            textDict.update({storeName:recordText})
            return textDict
        else:
            return None

    def prune_list(self, iList):
        oList = []
        for item in iList:
            if item:
                if isinstance(item, (list, tuple)):
                    item = self.prune_list(item)
                oList.append(item)
        return oList
Berk Onat's avatar
Berk Onat committed
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211

    def checkTinkerParam(self, cmdLine, prmName):
        try:
            prm = cmdLine.split()[-1]
            if "NONE" in prm.upper() or prmName.upper() in prm.upper():
                prm = None
            else:
                prm = ' '.join(cmdLine.split()[1:])
        except ValueError:
            prm = None
        return prm
Berk Onat's avatar
Berk Onat committed
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
 
    def readTinkerParameterFile(self, parser, fileName, cntrlDict):
        success = False
        emptyLine = re.compile(r"^\s*$")
        atom=[]
        vdw=[]
        bond=[]
        angle=[]
        dihedral=[]
        improper=[]
        ureybond=[]
        charge=[]
Berk Onat's avatar
Berk Onat committed
1224
        mutate=[]
Berk Onat's avatar
Berk Onat committed
1225
1226
1227
        if fileName is not None:
            with open(fileName, 'r') as fin:
                for line in fin:
Berk Onat's avatar
Berk Onat committed
1228
                    prm = None
Berk Onat's avatar
Berk Onat committed
1229
1230
                    if emptyLine.findall(line):
                        continue
Berk Onat's avatar
Berk Onat committed
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
                    cmdLine = ' '.join([x for x in line.strip().split() if x])
                    cmdLineUp = cmdLine.upper()
                    if cmdLine.startswith('#') or cmdLine.startswith('echo'):
                        continue
                    elif cmdLineUp.startswith('PARAMETERS'):
                        prm = self.checkTinkerParam(cmdLine, 'parameters')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'parameters', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('VERBOSE'):
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'verbose', True)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('ARCHIVE'):
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'archive', True)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('LIGHTS'):
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'lights', True)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('SADDLEPOINT'):
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'saddlepoint', True)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('ENFORCE-CHIRALITY'):
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'enforce-chirality', True)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('NEIGHBOR-LIST'):
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'neighbor-list', True)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('PRINTOUT'):
                        prm = self.checkTinkerParam(cmdLine, 'printout')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'printout', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('DIGITS'):
                        prm = self.checkTinkerParam(cmdLine, 'digits')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'digit', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('SPACEGROUP'):
                        prm = self.checkTinkerParam(cmdLine, 'spacegroup')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'spacegroup', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('VDWTYPE'):
                        prm = self.checkTinkerParam(cmdLine, 'vdwtype')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'vdwtype', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('VDW-CUTOFF'):
                        prm = self.checkTinkerParam(cmdLine, 'vdw-cutoff')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'vdw-cutoff', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('VDW-CORRECTION'):
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'vdw-correction', True)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('EWALD'):
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'ewald', True)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('ANISO-PRESSURE'):
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'aniso-pressure', True)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('EWALD-CUTOFF'):
                        prm = self.checkTinkerParam(cmdLine, 'ewald-cutoff')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'ewald-cutoff', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('PME-GRID'):
                        prm = self.checkTinkerParam(cmdLine, 'pme-grid')
                        if prm is not None:
                            prm = ','.join(prm.split())
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'pme-grid', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('PME-ORDER'):
                        prm = self.checkTinkerParam(cmdLine, 'pme-order')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'pme-order', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('RADIUSRULE'):
                        prm = self.checkTinkerParam(cmdLine, 'radiusrule')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'radiusrule', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('RADIUSRULE'):
                        prm = self.checkTinkerParam(cmdLine, 'radiusrule')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'radiusrule', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('RADIUSTYPE'):
                        prm = self.checkTinkerParam(cmdLine, 'radiustype')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'radiustype', prm)
                        success = rtn[0] if success is False else True
                        continue
                    elif cmdLineUp.startswith('RADIUSSIZE'):
                        prm = self.checkTinkerParam(cmdLine, 'radiussize')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'radiussize', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1337
                        continue
Berk Onat's avatar
Berk Onat committed
1338
1339
1340
                    elif cmdLineUp.startswith('EPSILONRULE'):
                        prm = self.checkTinkerParam(cmdLine, 'epsilonrule')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'epsilonrule', prm)
Berk Onat's avatar
Berk Onat committed
1341
1342
                        success = rtn[0] if success is False else True
                        continue
Berk Onat's avatar
Berk Onat committed
1343
1344
1345
                    elif cmdLineUp.startswith('DIELECTRIC'):
                        prm = self.checkTinkerParam(cmdLine, 'dielectric')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'dielectric', prm)
Berk Onat's avatar
Berk Onat committed
1346
1347
                        success = rtn[0] if success is False else True
                        continue
Berk Onat's avatar
Berk Onat committed
1348
1349
1350
1351
                    elif cmdLineUp.startswith('A-AXIS'):
                        prm = self.checkTinkerParam(cmdLine, 'a-axis')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'a-axis', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1352
                        continue
Berk Onat's avatar
Berk Onat committed
1353
1354
1355
1356
                    elif cmdLineUp.startswith('B-AXIS'):
                        prm = self.checkTinkerParam(cmdLine, 'b-axis')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'b-axis', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1357
                        continue
Berk Onat's avatar
Berk Onat committed
1358
1359
1360
1361
                    elif cmdLineUp.startswith('C-AXIS'):
                        prm = self.checkTinkerParam(cmdLine, 'c-axis')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'c-axis', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1362
                        continue
Berk Onat's avatar
Berk Onat committed
1363
1364
1365
1366
                    elif cmdLineUp.startswith('ALPHA'):
                        prm = self.checkTinkerParam(cmdLine, 'alpha')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'alpha', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1367
                        continue
Berk Onat's avatar
Berk Onat committed
1368
1369
1370
1371
                    elif cmdLineUp.startswith('BETA'):
                        prm = self.checkTinkerParam(cmdLine, 'beta')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'beta', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1372
                        continue
Berk Onat's avatar
Berk Onat committed
1373
1374
1375
1376
                    elif cmdLineUp.startswith('GAMMA'):
                        prm = self.checkTinkerParam(cmdLine, 'gamma')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'gamma', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1377
                        continue
Berk Onat's avatar
Berk Onat committed
1378
1379
1380
1381
                    elif cmdLineUp.startswith('INTEGRATOR'):
                        prm = self.checkTinkerParam(cmdLine, 'integrator')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'integrator', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1382
                        continue
Berk Onat's avatar
Berk Onat committed
1383
1384
1385
1386
                    elif cmdLineUp.startswith('BAROSTAT'):
                        prm = self.checkTinkerParam(cmdLine, 'barostat')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'barostat', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1387
                        continue
Berk Onat's avatar
Berk Onat committed
1388
1389
1390
1391
                    elif cmdLineUp.startswith('TAU-PRESSURE'):
                        prm = self.checkTinkerParam(cmdLine, 'tau-pressure')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'tau-pressure', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1392
                        continue
Berk Onat's avatar
Berk Onat committed
1393
1394
1395
1396
                    elif cmdLineUp.startswith('TAU-TEMPERATURE'):
                        prm = self.checkTinkerParam(cmdLine, 'tau-temperature')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'tau-temperature', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1397
                        continue
Berk Onat's avatar
Berk Onat committed
1398
1399
1400
1401
                    elif cmdLineUp.startswith('RATTLE'):
                        prm = self.checkTinkerParam(cmdLine, 'rattle')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'rattle', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1402
                        continue
Berk Onat's avatar
Berk Onat committed
1403
1404
1405
1406
                    elif cmdLineUp.startswith('LAMBDA'):
                        prm = self.checkTinkerParam(cmdLine, 'lambda')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'lambda', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1407
                        continue
Berk Onat's avatar
Berk Onat committed
1408
1409
1410
1411
                    elif cmdLineUp.startswith('POLAR-EPS'):
                        prm = self.checkTinkerParam(cmdLine, 'polar-eps')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'polar-eps', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1412
                        continue
Berk Onat's avatar
Berk Onat committed
1413
1414
1415
1416
                    elif cmdLineUp.startswith('VIB-ROOTS'):
                        prm = self.checkTinkerParam(cmdLine, 'vib-roots')
                        rtn = setMetaStrInDict(self, 'cntrlDict', 'vib-roots', prm)
                        success = rtn[0] if success is False else True
Berk Onat's avatar
Berk Onat committed
1417
                        continue
Berk Onat's avatar
Berk Onat committed
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
        return success

    def findFileInDir(self, parser, fileMetaName, cntrlDictName):
        filecntrlDict = getattr(self, cntrlDictName)
        if filecntrlDict is not None:
            infileKey = isMetaStrInDict(fileMetaName, filecntrlDict)
        infile = None
        paramFile = None
        if infileKey is not None:
            if filecntrlDict[infileKey].value is not None:
                infile = filecntrlDict[infileKey].value
        if infile is not None:
            #self.working_dir_name
            #working_dir_name = os.path.dirname(os.path.abspath(os.getcwd()))
            thisfile=os.path.normpath(infile)
            findfile=os.path.basename(thisfile)
            dirlisti=thisfile.split(os.path.sep)
            dirlist=self.prune_list(dirlisti)
            sepp=os.path.sep

            subdirlist = [sepp.join(dirlist[dr:-1]) for dr in range(len(dirlist))]
            for sid, sdir in enumerate(subdirlist):
                if sdir == '':
                    subdirlist[sid] = os.curdir

            matchdirs = []
            for root, dirnames, filenames in os.walk(self.working_dir_name):
                for possubdir in subdirlist:
                    for subdir in fnmatch.filter(dirnames, possubdir):
                        matchdirs.append(os.path.join(root, subdir))
            if matchdirs:
                pass
            else:
                matchdirs.append(self.working_dir_name)

            matches = []
            for root, dirnames, filenames in os.walk(self.working_dir_name):
                if root == self.working_dir_name:
                    for filename in fnmatch.filter(filenames, findfile):
                        matches.append(os.path.join(root, filename))
                        break
            if matches:
                pass
            else:
                for root, dirnames, filenames in os.walk(self.working_dir_name):
                    for mdir in matchdirs:
                        if mdir+sepp+findfile == root+sepp+findfile:
                            for filename in fnmatch.filter(filenames, findfile):
                                matches.append(os.path.join(root, filename))
                                break
 
            inputFile = None
            if matches:
                inputFile = matches[0]

            if inputFile is not None:
                paramFile = os.path.normpath(os.path.abspath(inputFile))

        return paramFile

    def generateARCfileFromSequenceFiles(self, parser, fileListInDir, arcname):
        xyzSeqList = []
        working_dir_name = os.path.dirname(os.path.abspath(self.fName))
        addfile = os.path.normpath(working_dir_name+os.path.sep+arcname)
        for fname in self.tinkerFiles:
            if('.arc' not in fname and 
               '.xyz' not in fname and 
               fname in fileListInDir):
                xyzSeqList.append(working_dir_name+os.path.sep+fname)
        anyFileExist=False
        for fname in xyzSeqList:
            with open(fname, 'rb') as fin:
                if fin.read():
                    anyFileExist=True
                    fin.close()
        if anyFileExist:
            with open(addfile, 'wb') as fout:
                for fname in xyzSeqList:
                    with open(fname, 'rb') as fin:
                        fout.write(fin.read())

    def fetchInfoFromInputOutput(self, parser):
        self.recordList.write('   #######################################   ')
        working_dir_name = os.path.dirname(os.path.abspath(self.fName))
        fileList = [x for x in os.walk(os.path.abspath(working_dir_name))]
        filesListInDir = []
        try:
            getattr(self, "filesInOutputDir")
        except AttributeError:
            self.filesInOutputDir = {}
            for fdir, fchilds, fnames in fileList:
                for fname in fnames:
                    fkeyname = os.path.normpath(os.path.join(fdir, fname))
                    self.filesInOutputDir.update({fkeyname.upper():fkeyname})
        for fdir, fchilds, fnames in fileList:
            for fname in fnames:
                filesListInDir.append(fname)
        self.tinkerRunFiles = {}
        self.tinkerFiles = []
        self.tinkerFileSteps = []
        self.tinkerFileTimes = []
        self.tinkerAveSteps = []
        self.tinkerAveTimes = []
        self.tinkerFirstStep = None
        self.tinkerRunMD = False
        fileFound = False
        textFiles = None
        self.tinkerKeyFile = None
        self.MDsteps = 0
        self.MDtimestep = None
        step = 0
        mdstart = 0
        mdend = 1
        self.recordList.seek(0)
        runnum=-1
        runstart = 0
        runend = 14
        header = False
        for li, line in enumerate(self.recordList):
            upLine = line.upper()
            if 'OPTIMIZATION' in upLine:
                mdstart = li
            if 'MOLECULAR DYNAMICS TRAJECTORY' in upLine:
                self.tinkerRunMD = True
                mdstart = li
            if 'ITER' in upLine and 'VALUE' in upLine and 'RMS' in upLine:
                mdstart = li
            if 'MD STEP' in upLine:
                self.tinkerRunMD = True
                mdstart = li
            if ''.join(line.strip().split()) == '':
                mdend = li
            if 'AVERAGE' in upLine and 'VALUES' in upLine:
                avestep = int(' '.join(line.strip().split()).split()[-3])
                if self.tinkerFirstStep is None:
                    self.tinkerFirstStep = avestep
                else:
                    if avestep<self.tinkerFirstStep:
                        self.tinkerFirstStep = avestep
                self.tinkerAveSteps.append(avestep)
            if 'SIMULATION' in upLine and 'TIME' in upLine:
                self.tinkerAveTimes.append(float(' '.join(line.strip().split()).split()[2]))
            if 'INSTANTANEOUS' in upLine and 'VALUES' in upLine:
                inststep = int(' '.join(line.strip().split()).split()[-3])
                if self.tinkerFirstStep is None:
                    self.tinkerFirstStep = inststep
                else:
                    if inststep<self.tinkerFirstStep:
                        self.tinkerFirstStep = inststep
                self.tinkerFileSteps.append(inststep)
            if 'CURRENT' in upLine and 'TIME' in upLine:
                self.tinkerFileTimes.append(float(' '.join(line.strip().split()).split()[2]))
            if 'COORDINATE' in upLine and 'FILE' in upLine:
                fileFound = True
                self.tinkerFiles.append(' '.join(line.strip().split()).split()[-1])
            if '#######' in line:
                break

        self.recordList.seek(0)
        mdstep=False
        avestep=False
        inststep=False
        for li, line in enumerate(self.recordList):
            if li >= mdstart and li <= mdend:
                upLine = line.upper()
                if 'MD STEP' in upLine or ('ITER' in upLine and 'VALUE' in upLine):
                    mdstep=True
                if 'AVERAGE VALUES' in upLine:
                    avestep=True
                if 'INSTANTANEOUS VALUES' in upLine:
                    inststep=True
                if mdstep:
                    sl = line.strip().split()
                    if len(sl)>3:
                        try:
                            step = int(sl[0])
                            if step> self.MDsteps:
                                self.MDsteps = step
                        except(ValueError, TypeError):
                            pass
                if avestep or inststep:
                    if 'DYNAMICS STEPS' in upLine:
                        sl = line.strip().split()
                        if len(sl)>3:
                            try:
                                step = int(sl[-3])
                                if step > self.MDsteps:
                                    self.MDsteps = step
                            except(ValueError, TypeError):
                                pass

        if self.MDsteps is not None:
            nstepKey = isMetaStrInDict("NSTEP", self.cntrlDict)
            if nstepKey is not None:
                self.cntrlDict[nstepKey].activeInfo = True
                self.cntrlDict[nstepKey].value = self.MDsteps

        if self.MDtimestep is None:
            if len(self.tinkerFileSteps)>0 and len(self.tinkerFileTimes)>0:
                self.MDtimestep = self.tinkerFileTimes[0]/self.tinkerFileSteps[0]
        if self.MDtimestep is None:
            if len(self.tinkerAveSteps)>0 and len(self.tinkerAveTimes)>0:
                self.MDtimestep = self.tinkerAveTimes[0]/self.tinkerAveSteps[0]

        if self.MDtimestep is not None:
            nstepKey = isMetaStrInDict("STEP-DT", self.cntrlDict)
            if nstepKey is not None:
                self.cntrlDict[nstepKey].activeInfo = True
                self.cntrlDict[nstepKey].value = self.MDtimestep

        # First find tinker run name from output files such as Coordinate File outputs
        # If there is no output file than
        # find all .key files in working dir
        # and try match the base names of these files with the output log file that 
        # parser is working on.
        # If none of the above strategies work, use default key file name tinker.key
        # Finally, try readinf input key file if there is one
        if fileFound is True:
            coordfilename = os.path.basename(self.tinkerFiles[0])
            coordexts = MDDA.get_fileExtensions(coordfilename)
            if len(coordexts)>0:
                self.tinkerBaseName = coordexts[0]
                self.tinkerKeyFile = self.tinkerBaseName + '.key'
        if self.tinkerKeyFile is None:
            for tfile in filesListInDir:
                if '.KEY' in tfile.upper():
                    fname = os.path.basename(tfile)
                    fexts = MDDA.get_fileExtensions(fname)
                    if len(fexts)>0:
                        if fexts[0].upper() in os.path.basename(self.fName).upper():
                            coordfilename = os.path.basename(tfile)
                            coordexts = MDDA.get_fileExtensions(coordfilename)
                            self.tinkerBaseName = coordexts[0]
                            self.tinkerKeyFile = tfile
                            break
        if self.tinkerKeyFile is None and textFiles is not None:
            for tfile in filesListInDir:
                if 'TINKER.KEY' in tfile.upper():
                    coordfilename = os.path.basename(tfile)
                    coordexts = MDDA.get_fileExtensions(coordfilename)
                    self.tinkerBaseName = coordexts[0]
                    self.tinkerKeyFile = tfile
                    break
        if self.tinkerKeyFile is None and textFiles is not None:
            for tfile in filesListInDir:
                if '.KEY' in tfile.upper():
                    coordfilename = os.path.basename(tfile)
                    coordexts = MDDA.get_fileExtensions(coordfilename)
                    self.tinkerBaseName = coordexts[0]
                    self.tinkerKeyFile = tfile
                    break

        self.tinkerTrajSteps = []
        if fileFound is True:
            rtn = setMetaStrInDict(self, 'filecntrlDict', 'coordinate file list', ','.join(self.tinkerFiles)) 
            self.tinkerRunFiles.update({'coordinate file list' : ','.join(self.tinkerFiles)})
        if self.secRunGIndex<1:
            xyzfile = self.tinkerBaseName + '.xyz'
        elif self.secRunGIndex>0:
            xyzfile = self.tinkerBaseName + '.xyz_' + str(self.secRunGIndex+1)
        outxyzfile = self.tinkerBaseName + '.xyz_' + str(self.secRunGIndex+2)
        dynfile = self.tinkerBaseName + '.dyn'
        corfile = self.tinkerBaseName + '.001'
        arcfile = self.tinkerBaseName + '.arc'
        if xyzfile in filesListInDir:
            rtn = setMetaStrInDict(self, 'filecntrlDict', 'topology file', xyzfile) 
            self.tinkerRunFiles.update({'topology file' : xyzfile})
            self.tinkerTrajSteps.append(1)
            if self.tinkerFirstStep not in self.tinkerTrajSteps:
                self.tinkerTrajSteps.append(self.tinkerFirstStep)
        if self.tinkerFileSteps:
            for trajst in self.tinkerFileSteps:
                if trajst not in self.tinkerTrajSteps:
                    self.tinkerTrajSteps.append(trajst)
        if outxyzfile in filesListInDir:
            rtn = setMetaStrInDict(self, 'filecntrlDict', 'final configuration file', outxyzfile) 
            self.tinkerRunFiles.update({'final configuration file' : outxyzfile})
            if self.MDsteps not in self.tinkerTrajSteps:
                self.tinkerTrajSteps.append(self.MDsteps)
        if xyzfile in filesListInDir:
            rtn = setMetaStrInDict(self, 'filecntrlDict', 'initial configuration file', xyzfile) 
            self.tinkerRunFiles.update({'initial configuration file' : xyzfile})
        if self.tinkerRunMD is True:
            if dynfile in filesListInDir:
                rtn = setMetaStrInDict(self, 'filecntrlDict', 'restart file', dynfile) 
                self.tinkerRunFiles.update({'restart file' : dynfile})
                if self.MDsteps not in self.tinkerTrajSteps:
                    self.tinkerTrajSteps.append(self.MDsteps)
            if corfile in filesListInDir:
                rtn = setMetaStrInDict(self, 'filecntrlDict', 'initial trajectory file', corfile) 
                self.tinkerRunFiles.update({'initial trajectory file' : corfile})
            if arcfile in filesListInDir and arcfile in self.tinkerFiles:
                rtn = setMetaStrInDict(self, 'filecntrlDict', 'archive file', arcfile) 
                self.tinkerRunFiles.update({'archive file' : arcfile})

        self.tinkerXYZSeqList = {}
        if arcfile not in self.tinkerFiles:
            trajinstance = 0
            for fname in self.tinkerFiles:
                if('.arc' not in fname and 
                   '.xyz' not in fname and 
                   fname in filesListInDir):
                    self.tinkerXYZSeqList.update({
                        self.tinkerFileSteps[
                            trajinstance] : working_dir_name+os.path.sep+fname
                        })
                    trajinstance += 1
        #    self.generateARCfileFromSequenceFiles(parser, filesListInDir, arcfile)
        #    rtn = setMetaStrInDict(self, 'filecntrlDict', 'archive file', arcfile) 
        #    self.tinkerRunFiles.update({'archive file' : arcfile})

        
        if self.tinkerKeyFile is not None:
            rtn = setMetaStrInDict(self, 'filecntrlDict', 'key file', self.tinkerKeyFile) 
            self.findInputCmdFileAndRead(parser)
Berk Onat's avatar
Berk Onat committed
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
        return success

    def findFileInDir(self, parser, fileMetaName, cntrlDictName):
        filecntrlDict = getattr(self, cntrlDictName)
        if filecntrlDict is not None:
            infileKey = isMetaStrInDict(fileMetaName, filecntrlDict)
        infile = None
        paramFile = None
        if infileKey is not None:
            if filecntrlDict[infileKey].value is not None:
                infile = filecntrlDict[infileKey].value
        if infile is not None:
            #self.working_dir_name
            #working_dir_name = os.path.dirname(os.path.abspath(os.getcwd()))
            thisfile=os.path.normpath(infile)
            findfile=os.path.basename(thisfile)
            dirlisti=thisfile.split(os.path.sep)
            dirlist=self.prune_list(dirlisti)
            sepp=os.path.sep

            subdirlist = [sepp.join(dirlist[dr:-1]) for dr in range(len(dirlist))]
            for sid, sdir in enumerate(subdirlist):
                if sdir == '':
                    subdirlist[sid] = os.curdir

            matchdirs = []
            for root, dirnames, filenames in os.walk(self.working_dir_name):
                for possubdir in subdirlist:
                    for subdir in fnmatch.filter(dirnames, possubdir):
                        matchdirs.append(os.path.join(root, subdir))
            if matchdirs:
                pass
            else:
                matchdirs.append(self.working_dir_name)

            matches = []
            for root, dirnames, filenames in os.walk(self.working_dir_name):
                if root == self.working_dir_name:
                    for filename in fnmatch.filter(filenames, findfile):
                        matches.append(os.path.join(root, filename))
                        break
            if matches:
                pass
            else:
                for root, dirnames, filenames in os.walk(self.working_dir_name):
                    for mdir in matchdirs:
                        if mdir+sepp+findfile == root+sepp+findfile:
                            for filename in fnmatch.filter(filenames, findfile):
                                matches.append(os.path.join(root, filename))
                                break
 
            inputFile = None
            if matches:
                inputFile = matches[0]

            if inputFile is not None:
                paramFile = os.path.normpath(os.path.abspath(inputFile))

        return paramFile

    def generateARCfileFromSequenceFiles(self, parser, fileListInDir, arcname):
        xyzSeqList = []
        working_dir_name = os.path.dirname(os.path.abspath(self.fName))
        addfile = os.path.normpath(working_dir_name+os.path.sep+arcname)
        for fname in self.tinkerFiles:
            if('.arc' not in fname and 
               '.xyz' not in fname and 
               fname in fileListInDir):
                xyzSeqList.append(working_dir_name+os.path.sep+fname)
        anyFileExist=False
        for fname in xyzSeqList:
            with open(fname, 'rb') as fin:
                if fin.read():
                    anyFileExist=True
                    fin.close()
        if anyFileExist:
            with open(addfile, 'wb') as fout:
                for fname in xyzSeqList:
                    with open(fname, 'rb') as fin:
                        fout.write(fin.read())

    def fetchInfoFromInputOutput(self, parser):
        self.recordList.write('   #######################################   ')
        working_dir_name = os.path.dirname(os.path.abspath(self.fName))
        fileList = [x for x in os.walk(os.path.abspath(working_dir_name))]
        filesListInDir = []
        try:
            getattr(self, "filesInOutputDir")
        except AttributeError:
            self.filesInOutputDir = {}
            for fdir, fchilds, fnames in fileList:
                for fname in fnames:
                    fkeyname = os.path.normpath(os.path.join(fdir, fname))
                    self.filesInOutputDir.update({fkeyname.upper():fkeyname})
        for fdir, fchilds, fnames in fileList:
            for fname in fnames:
                filesListInDir.append(fname)
        self.tinkerRunFiles = {}
        self.tinkerFiles = []
        self.tinkerFileSteps = []
        self.tinkerFileTimes = []
        self.tinkerAveSteps = []
        self.tinkerAveTimes = []
        self.tinkerFirstStep = None
        self.tinkerRunMD = False
        fileFound = False
        textFiles = None
        self.tinkerKeyFile = None
        self.MDsteps = 0
        self.MDtimestep = None
        step = 0
        mdstart = 0
        mdend = 1
        self.recordList.seek(0)
        runnum=-1
        runstart = 0
        runend = 14
        header = False
        for li, line in enumerate(self.recordList):
            upLine = line.upper()
            if 'OPTIMIZATION' in upLine:
                mdstart = li
            if 'MOLECULAR DYNAMICS TRAJECTORY' in upLine:
                self.tinkerRunMD = True
                mdstart = li
            if 'ITER' in upLine and 'VALUE' in upLine and 'RMS' in upLine:
                mdstart = li
            if 'MD STEP' in upLine:
                self.tinkerRunMD = True
                mdstart = li
            if ''.join(line.strip().split()) == '':
                mdend = li
            if 'AVERAGE' in upLine and 'VALUES' in upLine:
                avestep = int(' '.join(line.strip().split()).split()[-3])
                if self.tinkerFirstStep is None:
                    self.tinkerFirstStep = avestep
                else:
                    if avestep<self.tinkerFirstStep:
                        self.tinkerFirstStep = avestep
                self.tinkerAveSteps.append(avestep)
            if 'SIMULATION' in upLine and 'TIME' in upLine:
                self.tinkerAveTimes.append(float(' '.join(line.strip().split()).split()[2]))
            if 'INSTANTANEOUS' in upLine and 'VALUES' in upLine:
                inststep = int(' '.join(line.strip().split()).split()[-3])
                if self.tinkerFirstStep is None:
                    self.tinkerFirstStep = inststep
                else:
                    if inststep<self.tinkerFirstStep:
                        self.tinkerFirstStep = inststep
                self.tinkerFileSteps.append(inststep)
            if 'CURRENT' in upLine and 'TIME' in upLine:
                self.tinkerFileTimes.append(float(' '.join(line.strip().split()).split()[2]))
            if 'COORDINATE' in upLine and 'FILE' in upLine:
                fileFound = True
                self.tinkerFiles.append(' '.join(line.strip().split()).split()[-1])
            if '#######' in line:
                break

        self.recordList.seek(0)
        mdstep=False
        avestep=False
        inststep=False
        for li, line in enumerate(self.recordList):
            if li >= mdstart and li <= mdend:
                upLine = line.upper()
                if 'MD STEP' in upLine or ('ITER' in upLine and 'VALUE' in upLine):
                    mdstep=True
                if 'AVERAGE VALUES' in upLine:
                    avestep=True
                if 'INSTANTANEOUS VALUES' in upLine:
                    inststep=True
                if mdstep:
                    sl = line.strip().split()
                    if len(sl)>3:
                        try:
                            step = int(sl[0])
                            if step> self.MDsteps:
                                self.MDsteps = step
                        except(ValueError, TypeError):
                            pass
                if avestep or inststep:
                    if 'DYNAMICS STEPS' in upLine:
                        sl = line.strip().split()
                        if len(sl)>3:
                            try:
                                step = int(sl[-3])
                                if step > self.MDsteps:
                                    self.MDsteps = step
                            except(ValueError, TypeError):
                                pass

        if self.MDsteps is not None:
            nstepKey = isMetaStrInDict("NSTEP", self.cntrlDict)
            if nstepKey is not None:
                self.cntrlDict[nstepKey].activeInfo = True
                self.cntrlDict[nstepKey].value = self.MDsteps

        if self.MDtimestep is None:
            if len(self.tinkerFileSteps)>0 and len(self.tinkerFileTimes)>0:
                self.MDtimestep = self.tinkerFileTimes[0]/self.tinkerFileSteps[0]
        if self.MDtimestep is None:
            if len(self.tinkerAveSteps)>0 and len(self.tinkerAveTimes)>0:
                self.MDtimestep = self.tinkerAveTimes[0]/self.tinkerAveSteps[0]

        if self.MDtimestep is not None:
            nstepKey = isMetaStrInDict("STEP-DT", self.cntrlDict)
            if nstepKey is not None:
                self.cntrlDict[nstepKey].activeInfo = True
                self.cntrlDict[nstepKey].value = self.MDtimestep

        # First find tinker run name from output files such as Coordinate File outputs
        # If there is no output file than
        # find all .key files in working dir
        # and try match the base names of these files with the output log file that 
        # parser is working on.
        # If none of the above strategies work, use default key file name tinker.key
        # Finally, try readinf input key file if there is one
        if fileFound is True:
            coordfilename = os.path.basename(self.tinkerFiles[0])
            coordexts = MDDA.get_fileExtensions(coordfilename)
            if len(coordexts)>0:
                self.tinkerBaseName = coordexts[0]
                self.tinkerKeyFile = self.tinkerBaseName + '.key'
        if self.tinkerKeyFile is None:
            for tfile in filesListInDir:
                if '.KEY' in tfile.upper():
                    fname = os.path.basename(tfile)
                    fexts = MDDA.get_fileExtensions(fname)
                    if len(fexts)>0:
                        if fexts[0].upper() in os.path.basename(self.fName).upper():
                            coordfilename = os.path.basename(tfile)
                            coordexts = MDDA.get_fileExtensions(coordfilename)
                            self.tinkerBaseName = coordexts[0]
                            self.tinkerKeyFile = tfile
                            break
        if self.tinkerKeyFile is None and textFiles is not None:
            for tfile in filesListInDir:
                if 'TINKER.KEY' in tfile.upper():
                    coordfilename = os.path.basename(tfile)
                    coordexts = MDDA.get_fileExtensions(coordfilename)
                    self.tinkerBaseName = coordexts[0]
                    self.tinkerKeyFile = tfile
                    break
        if self.tinkerKeyFile is None and textFiles is not None:
            for tfile in filesListInDir:
                if '.KEY' in tfile.upper():
                    coordfilename = os.path.basename(tfile)
                    coordexts = MDDA.get_fileExtensions(coordfilename)
                    self.tinkerBaseName = coordexts[0]
                    self.tinkerKeyFile = tfile
                    break

        self.tinkerTrajSteps = []
        if fileFound is True:
            rtn = setMetaStrInDict(self, 'filecntrlDict', 'coordinate file list', ','.join(self.tinkerFiles)) 
            self.tinkerRunFiles.update({'coordinate file list' : ','.join(self.tinkerFiles)})
        if self.secRunGIndex<1:
            xyzfile = self.tinkerBaseName + '.xyz'
        elif self.secRunGIndex>0:
            xyzfile = self.tinkerBaseName + '.xyz_' + str(self.secRunGIndex+1)
        outxyzfile = self.tinkerBaseName + '.xyz_' + str(self.secRunGIndex+2)
        dynfile = self.tinkerBaseName + '.dyn'
        corfile = self.tinkerBaseName + '.001'
        arcfile = self.tinkerBaseName + '.arc'
        if xyzfile in filesListInDir:
            rtn = setMetaStrInDict(self, 'filecntrlDict', 'topology file', xyzfile) 
            self.tinkerRunFiles.update({'topology file' : xyzfile})
            self.tinkerTrajSteps.append(1)
            if self.tinkerFirstStep not in self.tinkerTrajSteps:
                self.tinkerTrajSteps.append(self.tinkerFirstStep)
        if self.tinkerFileSteps:
            for trajst in self.tinkerFileSteps:
                if trajst not in self.tinkerTrajSteps:
                    self.tinkerTrajSteps.append(trajst)
        if outxyzfile in filesListInDir:
            rtn = setMetaStrInDict(self, 'filecntrlDict', 'final configuration file', outxyzfile) 
            self.tinkerRunFiles.update({'final configuration file' : outxyzfile})
            if self.MDsteps not in self.tinkerTrajSteps:
                self.tinkerTrajSteps.append(self.MDsteps)
        if xyzfile in filesListInDir:
            rtn = setMetaStrInDict(self, 'filecntrlDict', 'initial configuration file', xyzfile) 
            self.tinkerRunFiles.update({'initial configuration file' : xyzfile})
        if self.tinkerRunMD is True:
            if dynfile in filesListInDir:
                rtn = setMetaStrInDict(self, 'filecntrlDict', 'restart file', dynfile) 
                self.tinkerRunFiles.update({'restart file' : dynfile})
                if self.MDsteps not in self.tinkerTrajSteps:
                    self.tinkerTrajSteps.append(self.MDsteps)
            if corfile in filesListInDir:
                rtn = setMetaStrInDict(self, 'filecntrlDict', 'initial trajectory file', corfile) 
                self.tinkerRunFiles.update({'initial trajectory file' : corfile})
            if arcfile in filesListInDir and arcfile in self.tinkerFiles:
                rtn = setMetaStrInDict(self, 'filecntrlDict', 'archive file', arcfile) 
                self.tinkerRunFiles.update({'archive file' : arcfile})

        self.tinkerXYZSeqList = {}
        if arcfile not in self.tinkerFiles:
            trajinstance = 0
            for fname in self.tinkerFiles:
                if('.arc' not in fname and 
                   '.xyz' not in fname and 
                   fname in filesListInDir):
                    self.tinkerXYZSeqList.update({
                        self.tinkerFileSteps[
                            trajinstance] : working_dir_name+os.path.sep+fname
                        })
                    trajinstance += 1
        #    self.generateARCfileFromSequenceFiles(parser, filesListInDir, arcfile)
        #    rtn = setMetaStrInDict(self, 'filecntrlDict', 'archive file', arcfile) 
        #    self.tinkerRunFiles.update({'archive file' : arcfile})

        
        if self.tinkerKeyFile is not None:
            rtn = setMetaStrInDict(self, 'filecntrlDict', 'key file', self.tinkerKeyFile) 
            #self.findInputCmdFileAndRead(parser)

        self.tinkerRunFiles.update({'filesteps' : self.tinkerTrajSteps})
        self.tinkerRunFiles.update({'filetrajs' : self.tinkerXYZSeqList})

        self.fileUnitDict.update({self.secRunGIndex : self.tinkerRunFiles})

        return True

    def findInputCmdFileAndRead(self, parser):
        success = None
Berk Onat's avatar
Berk Onat committed
2058
2059
2060
2061
        tkeyFile = self.findFileInDir(parser, "key file", "filecntrlDict")
        if tkeyFile is not None:
            self.inputCntrlFile = tkeyFile
            success = self.readTinkerParameterFile(parser, tkeyFile, 'cntrlDict')
Berk Onat's avatar
Berk Onat committed
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
        return success

    def build_subMatchers(self):
        """Builds the sub matchers to parse the main output file.
        """
        mddataNameList=getList_MetaStrInDict(self.mddataDict)

        self.mdStepHeaderDict={
                'MD Step':0,
                'E Total':1,
                'E Potential':2,
                'E Kinetic':3,
                'Temp':4,
                'Pres':5,
                } 

        #self.minStepHeaderDict={
        #        'MIN Iter' : 0,
        #        'F Value' : 1,
        #        'G RMS' : 2,
        #        'F Move' : 3,
        #        'X Move' : 4,
        #        'Angle' : 5,
        #        'FG Call' : 6,
        #        'Comment' : 7
        #        } 

        cntrlNameList=getList_MetaStrInDict(self.metaDicts['cntrl'])
        filecntrlNameList=getList_MetaStrInDict(self.metaDicts['filecntrl'])
        fileNameList=getList_MetaStrInDict(self.metaDicts['file'])
        extraNameList=getList_MetaStrInDict(self.metaDicts['extra'])

        self.minOutputSubParsers = [
            # Optimization reader
            { "startReStr"        : r"\s*Optimization\s*",
              "parser"            : "namelist_parser",
              "parsername"        : "min_init_parser",
              "waitlist"          : None,
              "stopOnMatchStr"    : r"\s*(?:QN|TN|CG|VM)\s+Iter\s*",
              "quitOnMatchStr"    : r"\s*(?:QN|TN|CG|VM)\s+Iter\s*",
              "metaNameStart"     : PARSERTAG + "_inout_control", 
              "matchNameList"     : cntrlNameList,
              "matchNameDict"     : "mdcntrlDict",
              "updateMatchDict"   : True,
              "onlyCaseSensitive" : False,
              "stopOnFirstLine"   : False,
              "parserOptions"     : {
                  "lineFilter"       : None,
                  "controlsections"  : ["x_tinker_section_control_parameters"], 
                  "controlsave"      : "sectioncontrol", 
                  "controldict"      : "stepcontrolDict",
                  }
              },
            # Optimization end reader
            { "startReStr"        : r"\s*[A-Z]+\s+--\s*",
              "parser"            : "namelist_parser",
              "parsername"        : "min_end_parser",
              "waitlist"          : None,
              "stopOnMatchStr"    : r"^\s*$",
              "quitOnMatchStr"    : r"^\s*$",
              "metaNameStart"     : PARSERTAG + "_inout_control", 
              "matchNameList"     : cntrlNameList,
              "matchNameDict"     : "mdcntrlDict",
              "updateMatchDict"   : True,
              "onlyCaseSensitive" : False,
              "stopOnFirstLine"   : True,
              "parserOptions"     : {
                  "lineFilter"       : None,
                  #"controlsections"  : ["x_tinker_section_control_parameters"], 
                  #"controlsave"      : "sectioncontrol", 
                  #"controldict"      : "stepcontrolDict",
                  }
              },
            # Optimization end reader
            { "startReStr"        : r"\s*Final\s*",
              "parser"            : "namelist_parser",
              "parsername"        : "min_final_parser",
              "waitlist"          : None,
              "stopOnMatchStr"    : r"^\s*$",
              "quitOnMatchStr"    : r"^\s*$",
              "metaNameStart"     : PARSERTAG + "_inout_control", 
              "matchNameList"     : cntrlNameList,
              "matchNameDict"     : "mdcntrlDict",
              "updateMatchDict"   : True,
              "onlyCaseSensitive" : False,
              "stopOnFirstLine"   : False,
              "parserOptions"     : {
                  "lineFilter"       : None,
                  #"controlsections"  : ["x_tinker_section_control_parameters"], 
                  #"controlsave"      : "sectioncontrol", 
                  #"controldict"      : "stepcontrolDict",
                  }
              },
            # Section Control Parser
            { "startReStr"        : "AlwaysRun",
              "parser"            : "section_control_parser",
              "parsername"        : "control_section_parser",
              "waitlist"          : [["min_init_parser"]],
              "stopOnMatchStr"    : "AlwaysStop",
              "quitOnMatchStr"    : "AlwaysStop",
              "metaNameStart"     : None,
              "matchNameList"     : None,
              "matchNameDict"     : None,
              "updateMatchDict"   : False,
              "onlyCaseSensitive" : False,
              "stopOnFirstLine"   : False,
              "parserOptions"     : { 
                  "sectionname"      : "x_tinker_section_control_parameters", 
                  "sectionopen"      : True, 
                  "sectionopenattr"  : "MDcurrentstep", 
                  "sectionopenin"    : "cntrlparmstep", 
                  "sectionclose"     : True, 
                  "sectioncloseattr" : "MDcurrentstep", 
                  "sectionclosein"   : "cntrlparmstep", 
                  "activatesection"  : "sectioncontrol", 
                  "lookupdict"       : "stepcontrolDict" 
                  }
              },
            # Optimization Step header reader
            { "startReStr"        : r"\s*(?:QN|TN|CG|VM)\s+Iter\s*",
              "parser"            : "table_parser",
              "parsername"        : "min_header_parser",
              "waitlist"          : None,
              #"waitlist"          : [["min_init_parser"]],
              "stopOnMatchStr"    : r"^\s*$",
              "quitOnMatchStr"    : r"^\s*$",
              "metaNameStart"     : PARSERTAG + "_mdout_", 
              "matchNameList"     : mddataNameList,
              "matchNameDict"     : "mddataDict",
              "updateMatchDict"   : True,
              "onlyCaseSensitive" : False,
              "stopOnFirstLine"   : False,
              "parserOptions"     : { 
                  "header"           : True, 
                  "headersave"       : "minStepHeaderDict", 
                  "wrap"             : False, 
                  "tablelines"       : 0, 
                  "tablestartsat"    : r"\s*(?:QN|TN|CG|VM)\s*Iter", 
                  "tableendsat"      : r"^\s*$",
                  "lineFilter"       : {
2202
2203
2204
2205
                      'QN Iter' : 'ITER1',
                      'TN Iter' : 'ITER2',
                      'VM Iter' : 'ITER3',
                      'CG Iter' : 'ITER4',
Berk Onat's avatar
Berk Onat committed
2206
                      'F Value' : 'FVALUE',
2207
2208
                      'G RMS'   : 'GRMS1',
                      'RMS G'   : 'GRMS2',
Berk Onat's avatar
Berk Onat committed
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330