-
Notifications
You must be signed in to change notification settings - Fork 0
/
gxx_qsub.py
1512 lines (1435 loc) · 55.1 KB
/
gxx_qsub.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
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
947
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
#!/usr/bin/env python3
import os
import sys
import re
import argparse
from configparser import ConfigParser
from math import inf
import socket # module for the fully qualified named of the headnode
from subprocess import Popen, PIPE
try:
import typing
except ModuleNotFoundError:
print('ERROR: Python 3.5 or later needed.')
sys.exit()
# ====================================
# INSTALLATION-SPECIFIC PARAMETERS
# ====================================
# Server Data
# -----------
# This is used for the emailing system
# Email capabilities can be deactivated by setting EMAILSERVER to None
HEADNODE = socket.gethostname()
EMAILSERVER = "{}.sns.it".format(HEADNODE)
# Gaussian-related definitions
# -----------------------------
# Equivalency between procs archs and Gaussian mach dirs
# machine arch as defined in HPC ini file -> Macs in Gxx ini file.
# This depends on the naming convention adopted on each cluster
GXX_ARCHS = {
'nehalem': 'intel64-nehalem',
'westmere': 'intel64-nehalem',
'sandybridge': 'intel64-sandybridge',
'ivybridge': 'intel64-sandybridge',
'skylake': 'intel64-sandybridge',
'bulldozer': 'amd64-bulldozer'
}
# From early tests, best to use only physical cores
# Anyway, this can be changed depending on preferences
USE_LOGICAL_CORE = False
# Maximum occupation of the total memory on a given node
# By default, Gaussian does a very good job in managing the memory, but there
# is some memory set statically, so besides %Mem
# We limit the user or default requirements to 90% of the available memory.
MEM_OCCUPATION = .9
# By default, Gxx_QSub allows unsupported workings (workings not listed in
# the section of Gaussian versions). If set False, only workings listed
# in `Workings` are allowed.
ANY_WORKING = True
# Aliases can be defined as a dictionary, for instance: g16->g16c01
# By default, the dictionary is created automatically if None here
GXX_ALIAS = None
# Default version of Gaussian to run (must be a keyword)
GDEFAULT = 'g16c01'
# Basic Paths
# -----------
# By default, many path are built, but they can be overridden below
INIPATH = '/fix/me' # Path containing .ini files
LIBPATH = os.path.join(INIPATH, 'lib') # Library path for HPC modules
# TMPPATH is only used if users asked to copy back some speciic files
# but do not provide any specific paths back. To avoid overridding any
# file, Gxx-QSub creates a directory in HOME based on the PID.
# {pid} refers to the job PID, dirs can be added too.
TMPDIR = 'scratch-{pid}'
# Config File Names
# -----------------
# NOTE: By default, Gxx_Qsub lets the user adds their own setup
# This can be deactivated by simply setting the two variables below to
# `None` and setting the full paths for HPCINIPATH and GXXINIPATH
HPCINIFILE = 'hpcnodes.ini'
GXXINIFILE = 'gxxconfig.ini'
# Full Paths
# ----------
# Full paths, normally created but can be hardcoded
HPCINIPATH = os.path.join(INIPATH, HPCINIFILE)
GXXINIPATH = os.path.join(INIPATH, GXXINIFILE)
HPCMODPATH = LIBPATH
# ================
# DEPENDENCIES
# ================
# Provides default paths for the dependencies.
DEFAULT_PATHS = {
'hpc_inifile': HPCINIPATH,
'hpc_modpath': HPCMODPATH,
'gxx_inifile': HPCMODPATH,
}
sys.path.insert(0, DEFAULT_PATHS['hpc_modpath'])
import hpcnodes as hpc # NOQA
# ================
# PROGRAM DATA
# ================
AUTHOR = "Julien Bloino ([email protected])"
VERSION = "2020.08.16"
# Program name is generated from commandline
PROGNAME = os.path.basename(sys.argv[0])
# ====================================
# HPC INFRASTRUCTURE-SPECIFIC DATA
# ====================================
# Environment variables
# ------------------------
jobPID = str(os.getpid())
USERNAME = os.getenv('USER')
DEFAULTDIR = os.path.join(os.getenv('HOME'), TMPDIR.format(pid=jobPID))
STARTDIR = os.getcwd()
# We only support one file for HPC ini data, otherwise it would risk
# creating confusion in case of inconsistent data.
if HPCINIFILE is not None:
res = os.path.join(os.getenv('HOME'), HPCINIFILE)
if os.path.exists(res):
HPCFile = res
else:
HPCFile = DEFAULT_PATHS['hpc_inifile']
# Queue definitions
# -------------------
if not os.path.exists(HPCFile):
print('ERROR: Incorrect path to HPC nodes specification files.')
sys.exit()
HPCNODES = hpc.parse_ini(HPCFile)
HPCQUEUES = hpc.list_queues_nodes(HPCNODES)
HELP_QUEUES = """Sets the queues.
Available queues:
{}
Virtual queues defined as:
<queue>[:[nprocs][:nodeid]]
with:
<queue>: one of the queues above
nprocs: choice for number of processing units
- "H" : uses half of the cores of a single CPU
- "S" : uses a single core
- "0" : auto (same as empty)
- positive integer: total number of cores to use.
- negative integer: number of CPUs to use
""".format(', '.join(sorted(HPCQUEUES.keys())))
# Gaussian-related definitions
# -----------------------------
GXX_FORMAT = re.compile(r'g(dv|\d{2})\.?\w\d{2}[p+]?')
# Sets the Gaussian ini files.
# The user can set their own file to override what the system is providing
GxxFiles = []
if GXXINIFILE is not None:
res = os.path.join(os.getenv('HOME'), GXXINIFILE)
if os.path.exists(res):
GxxFiles.append(res)
GxxFiles.append(DEFAULT_PATHS['gxx_inifile'])
# Get Gaussian data file
gconf = ConfigParser()
gconf.read(GxxFiles)
defvals = gconf.defaults()
WorkTags = []
if 'workinfo' in defvals:
WorkInfo = {}
for info in defvals['workinfo'].split(','):
res = [item.strip() for item in info.split(':', maxsplit=3)]
if len(res) == 3:
key = res[0] or 'def'
name = res[1] or 'System'
mail = res[2] or 'N/A'
else:
print('ERROR: WorkInfo format must contain 2 ":"')
sys.exit(1)
if key in WorkTags:
print('ERROR: Duplicate tags "{}"'.format(key))
sys.exit(1)
WorkTags.append(key)
WorkInfo[key] = (name, mail)
else:
WorkInfo = {'def': ('System', 'N/A')}
if 'workpath' in defvals:
WorkRoots = {0: defvals['workpath']}
for info in defvals['workpath'].split(','):
res = [item.strip() for item in info.split(':', maxsplit=1)]
if len(res) == 2:
key = res[0] or 'def'
path = res[1]
else:
print('ERROR: WorkPath format must contain 1 ":"')
sys.exit(1)
if key in WorkRoots:
print('ERROR: Duplicate tag in WorkPath')
sys.exit(1)
WorkRoots[key] = path
else:
WorkRoots = None
# Extract Gaussian Installation Versions
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Supported formax gXX[.]ABB[p/+]
GVERSIONS = {}
for sec in sorted(gconf.sections()):
if GXX_FORMAT.match(sec):
key = sec.lower().replace('.', '').replace('+', 'p')
GVERSIONS[key] = {}
data = gconf[sec]
# Root path
if 'FullPath' in data:
res = data['FullPath']
else:
if gconf.get(sec, 'RootPath', fallback=None) is None:
print('ERROR: Missing Gaussian root installation dir.')
sys.exit(1)
if 'BaseDir' in data:
res = os.path.join(data['RootPath'], data['BaseDir'])
else:
print('ERROR: Either `BaseDir`+`RootPath` or `FullPath`',
'must be set.')
sys.exit(1)
GVERSIONS[key]['path'] = res
# Gaussian final directory
GVERSIONS[key]['gdir'] = gconf.get(sec, 'GDir',
fallback=sec.split('.')[0].lower())
# Machine architectures
res = gconf.get(sec, 'Machs', fallback=None)
if res.strip() == ' ':
res = None
if res is not None:
res = [item.strip() for item in res.split(',')]
GVERSIONS[key]['mach'] = res
# Gaussian version label
if 'Name' in data:
res = data['Name']
else:
if 'Gaussian' not in data or 'Revision' not in data:
print('ERROR: Gaussian/Revision or Name must be provided.')
sys.exit(1)
res = data['Gaussian'] + ' Rev. ' + data['Revision']
GVERSIONS[key]['name'] = res
# Gaussian release date
GVERSIONS[key]['date'] = gconf.get(sec, 'Date', fallback=None)
# Usage restrictions
res = gconf.get(sec, 'Shared', fallback=None)
if res is not None:
items = [x.strip().lower() for x in res.split(',')]
if {'any', 'all'} & set(items):
res = None
else:
res = [x.strip() for x in res.split(',')]
GVERSIONS[key]['pub'] = res
# Available standard/default workings
if 'Workings' in data:
res = [item.strip() for item in data['Workings'].split(',')]
if set(res) - set(WorkTags):
for item in res:
if item not in WorkTags:
WorkTags.append(item)
else:
res = None
GVERSIONS[key]['work'] = res
if GDEFAULT not in GVERSIONS:
print('ERROR: Default version of Gaussian not present in config files')
sys.exit(1)
# Sort Working Tags
# ^^^^^^^^^^^^^^^^^
WorkTags.sort()
scr = [item.lower() for item in WorkTags]
if len(scr) < len(WorkTags):
print('WARNING: Some tags only differ by the case.',
'Assuming this is correct.')
# Gaussian Working Trees
# ^^^^^^^^^^^^^^^^^^^^^^
WORKINGS = {}
# We select the working-related sections by complementarity:
# everything which does not have the Gaussian version format
# is a priori a possible working
# Gxx_QSub only supports the format "tag.gxx.rev"
for sec in sorted(gconf.sections()):
if not GXX_FORMAT.match(sec):
wtags = sec.lower().replace('+', 'p').split('.')
if len(wtags) != 3:
continue
tag, gxx, rev = wtags
data = gconf[sec]
# Get information on Gaussian version (shortened label and name)
# Then compare if part of the versions
gver = gxx + rev
# Gaussian version label
if 'Name' in data:
gname = data['Name']
else:
if 'Gaussian' not in data or 'Revision' not in data:
print('ERROR: Gaussian/Revision or Name must be provided.')
sys.exit(1)
gname = data['Gaussian'] + ' Rev. ' + data['Revision']
# Check if reference Gaussian version installed
gkey = None
if gver in GVERSIONS:
gkey = gver
else:
for key in GVERSIONS:
if GVERSIONS[key]['name'] == gname:
gkey = key
# Check if missing Gaussian installation or working not allowed
if gkey is None:
print('ERROR: Reference Gaussian version not found.')
sys.exit(1)
elif not ANY_WORKING:
if tag not in GVERSIONS[gkey]['Workings']:
break
# Build key
# For GDV, since rev unique, use tagrev
# For Gxx, there may be overlap, so taggxxrev
if wtags[1] == 'gdv':
key = tag + rev
else:
key = tag + gxx + rev
WORKINGS[key] = {'gref': gkey}
# Root path
if 'FullPath' in data:
res = data['FullPath']
else:
if gconf.get(sec, 'WorkPath', fallback=None) is None:
print('ERROR: Missing working root directory.')
sys.exit(1)
else:
# Check if workpath startswith the tag (for DEFAULT)
if WorkRoots is not None:
if data['WorkPath'] == WorkRoots[0]:
if tag not in WorkRoots:
fmt = 'ERROR: Missing default WorkPath for "{}"'
print(fmt.format(tag))
sys.exit(1)
wroot = WorkRoots[tag]
else:
wroot = data['WorkPath']
else:
wroot = data['WorkPath']
if 'BaseDir' in data:
res = os.path.join(wroot, data['BaseDir'])
else:
print('ERROR: Either `BaseDir`+`WorkPath` or `FullPath`',
'must be set.')
sys.exit(1)
WORKINGS[key]['path'] = res
# Gaussian version label
WORKINGS[key]['name'] = gname
# Version
WORKINGS[key]['ver'] = gconf.get(sec, 'Version', fallback=None)
# Update date
WORKINGS[key]['date'] = gconf.get(sec, 'Date', fallback=None)
# Machine architectures
res = gconf.get(sec, 'Machs', fallback=None)
if res.strip() == ' ':
res = None
if res is not None:
res = [item.strip() for item in res.split(',')]
WORKINGS[key]['mach'] = res
# Usage restrictions
res = gconf.get(sec, 'Shared', fallback=None)
if res is not None:
items = [x.strip().lower() for x in res.split(',')]
if {'any', 'all'} & set(items):
res = None
else:
res = [x.strip() for x in res.split(',')]
WORKINGS[key]['pub'] = res
# Author information
if tag in WorkInfo:
WORKINGS[key]['auth'] = WorkInfo[tag][0]
WORKINGS[key]['mail'] = WorkInfo[tag][1]
else:
WORKINGS[key]['auth'] = None
WORKINGS[key]['mail'] = None
# Changelog
if 'changelog' in data:
vers = data['changelog'].split(',')
WORKINGS[key]['clog'] = []
for item in vers:
res = item.split(':')
if len(res) == 2:
fname, ftype = [s.strip() for s in res]
else:
fname = res[0].strip()
ftype = os.path.splitext(fname)[0][1:].upper()
if fname.strip().startswith('.'):
if fname.count('.') == 1:
if len(WORKINGS[key]['clog']) == 0:
print('ERROR: Changelog alternative format but no',
'main format.')
sys.exit()
else:
fname = None
if fname is not None:
fname = fname.format(fullpath=WORKINGS[key]['path'])
WORKINGS[key]['clog'].append((fname, ftype))
else:
WORKINGS[key]['clog'] = None
# Other documentations
if 'docs' in data:
WORKINGS[key]['docs'] = {}
docs = data['docs'].split('\n')
for item0 in docs:
try:
keydoc, paths = item0.split(':', maxsplit=1)
except ValueError:
print('ERROR: Format for docs should be:',
'DOCTYPE:path[:format][,[altpath]ext[:format]].')
sys.exit(1)
WORKINGS[key]['docs'][keydoc] = []
vers = paths.split(',')
for item1 in vers:
res = item1.split(':')
if len(res) == 2:
fname, ftype = [s.strip() for s in res]
else:
fname = res[0].strip()
ftype = os.path.splitext(fname)[0][1:].upper()
if fname.strip().startswith('.'):
if fname.count('.') == 1:
if len(WORKINGS[key]['docs'][keydoc]) == 0:
print('ERROR: {} alternative'.format(keydoc),
'format but no main format.')
sys.exit()
else:
fname = None
if fname is not None:
fname = fname.format(fullpath=WORKINGS[key]['path'])
WORKINGS[key]['docs'][keydoc].append((fname, ftype))
else:
WORKINGS[key]['docs'] = None
# Gaussian Keyword Aliases
# ^^^^^^^^^^^^^^^^^^^^^^^^
if GXX_ALIAS is None:
GXX_ALIAS = {}
for gxx in GVERSIONS:
# Alias to the latest version
# This assumes that GVERSIONS is sorted by increasin
key = gxx[:3]
GXX_ALIAS[key] = gxx
# Automatic Documentation
# ^^^^^^^^^^^^^^^^^^^^^^^
HELP_GXX = 'Absolute paths or the following keywords are supported:\n'
# Gaussian versions
fmt = '+ {kword:7s}: {label:22s} ({date}){extra}\n'
for gxx in GVERSIONS:
gname = GVERSIONS[gxx]['name']
gdate = GVERSIONS[gxx]['date'] or 'N/A'
if gxx == GDEFAULT:
ginfo = ' - default'
else:
ginfo = ''
HELP_GXX += fmt.format(kword=gxx, label=gname, date=gdate, extra=ginfo)
# Aliases
fmt = '+ {kword:7s}: Alias for "{gtag}"\n'
for gxx in GXX_ALIAS:
HELP_GXX += fmt.format(kword=gxx, gtag=GXX_ALIAS[gxx])
# Workings
fmt = '+ {kword:7s}: Working by {auth} for {label} (updated: {date})\n'
fmt2 = ' {{dtype:{:d}s}}: {{path}}{{extra}}\n'
for gxx in WORKINGS:
gname = WORKINGS[gxx]['name']
gdate = WORKINGS[gxx]['date'] or 'N/A'
gauth = WORKINGS[gxx]['auth'] or '<Unknown>'
HELP_GXX += fmt.format(kword=gxx, auth=gauth, label=gname, date=gdate)
# For a prettier output, try to align the colons between the different docs
# So we calculate first the longest doctype.
if WORKINGS[gxx]['clog'] is not None:
l_doctype = 9
else:
l_doctype = 0
if WORKINGS[gxx]['docs'] is not None:
l_doctype = max(l_doctype, *[len(x) for x in WORKINGS[gxx]['docs']])
# Build format only if l_doctype > 0:
if l_doctype > 0:
dfmt = fmt2.format(l_doctype)
if WORKINGS[gxx]['clog'] is not None:
prt = []
for path, ftype in WORKINGS[gxx]['clog']:
if path is not None:
prt.append([path, []])
else:
prt[-1][1].append(ftype)
for item in prt:
if item[1]:
extra = ' ({} available)'.format(', '.join(item[1]))
else:
extra = ''
HELP_GXX += dfmt.format(dtype='CHANGELOG', path=item[0],
extra=extra)
if WORKINGS[gxx]['docs'] is not None:
for dtype in WORKINGS[gxx]['docs']:
prt = []
for path, ftype in WORKINGS[gxx]['docs'][dtype]:
if path is not None:
prt.append([path, []])
else:
prt[-1][1].append(ftype)
for item in prt:
if item[1]:
extra = ' ({} available)'.format(', '.join(item[1]))
else:
extra = ''
HELP_GXX += dfmt.format(dtype=dtype, path=item[0],
extra=extra)
# End of documentation block
HELP_GXX += '+ Arbitrary path given by user\n'
# ====================
# PARSER DEFINITON
# ====================
def build_parser():
"""Builds options parser.
Builds the full option parser.
Returns
-------
:obj:`ArgumentParser`
`ArgumentParser` object
"""
parser = argparse.ArgumentParser(
prog=PROGNAME,
formatter_class=argparse.RawTextHelpFormatter)
# MANDATORY ARGUMENTS
# ---------------------
parser.add_argument('infile', help="Gaussian input file(s)", nargs='*')
# OPTIONS
# ---------
# Qsub-related options
# ^^^^^^^^^^^^^^^^^^^^
queue = parser.add_argument_group('queue-related options')
queue.add_argument(
'-j', '--job', dest='job',
help='Sets the job name. (NOTE: PBS truncates after 15 characaters')
queue.add_argument(
'-m', '--mail', dest='mail', action='store_true',
help='Sends notification emails')
queue.add_argument(
'--mailto', dest='mailto',
help='Sends notification emails')
queue.add_argument(
'-M', '--mach', dest='mach', action='store_true',
help='Prints technical info on the machines available in the cluster')
queue.add_argument(
'--multi', choices=('parallel', 'serial'),
help='Runs multiple jobs in a single submission')
queue.add_argument(
'--node', dest='node', type=int,
help='Name of a specific node (ex: curie01)')
queue.add_argument(
'--group', dest='group', type=str,
help='User group')
queue.add_argument(
'-p', '--project', dest='project',
help='Defines the project to run the calculation')
queue.add_argument(
'-P', '--print', dest='prtinfo', action='store_true',
help='Print information about the submission process')
queue.add_argument(
'-q', '--queue', dest='queue', default='q02zewail',
help='{}\n{}'.format('Sets the queue type.', HELP_QUEUES),
metavar='QUEUE')
queue.add_argument(
'-S', '--silent', dest='silent', action='store_true',
help='''\
Do not save standard output and error in files
WARNING: The consequence will be a loss of these outputs''')
# Expert options
# ^^^^^^^^^^^^^^
expert = parser.add_argument_group('expert usage')
expert.add_argument(
'--cpto', dest='cpto', nargs='+',
help='Files to be copied to the local scratch (dumb copy, no check)')
expert.add_argument(
'--cpfrom', dest='cpfrom', nargs='+',
help='Files to be copied from the local scratch (dumb copy, no check)')
expert.add_argument(
'--nojob', dest='nojob', action='store_true',
help='Do not run job. Simply generate the input sequence.')
expert.add_argument(
'-X', '--expert', dest='expert', action='count',
help='''\
Expert use. Can be cumulated.
- 1: bypass input analysis
''')
# Gaussian-related options
# ^^^^^^^^^^^^^^^^^^^^^^^^
gaussian = parser.add_argument_group('Gaussian-related options')
gaussian.add_argument(
'-c', '--chk', dest='gxxchk', metavar='CHK_FILENAME',
help='Sets the checkpoint filename')
gaussian.add_argument(
'-g', '--gxxroot', dest='gxxver', metavar='GAUSSIAN',
default=GDEFAULT,
help='{}\n{}'.format('Sets the path to the Gaussian executables.',
HELP_GXX))
gaussian.add_argument(
'-i', '--ignore', dest='gxxl0I', nargs='+', metavar='L0_IGNORE',
choices=['c', 'chk', 'r', 'rwf', 'a', 'all'],
help='''\
Ignore the following options in input and command list:
+ c, chk: ignore the checkpoint file (omit it in the input, do not copy it)
+ r, rwf: ignore the read-write file (omit it in the input, do not copy it)
+ a, all: ignore both checkpoint and read-write files
''')
gaussian.add_argument(
'-k', '--keep', dest='gxxl0K', action='append', metavar='L0_KEEP',
default=[],
choices=['c', 'chk', 'm', 'mem', 'p', 'proc', 'r', 'rwf', 'a', 'all'],
help='''\
Keeps user-given parameters to control the Gaussian job in input file.
The possible options are:
+ c, chk: Keeps checkpoint filename given in input
+ m, mem: Keeps memory requirements given in input
+ p, proc: Keeps number of proc. required in input
+ r, rwf: Keeps read-write file given in input
+ a, all: Keeps all data list above
''')
gaussian.add_argument(
'-o', '--out', dest='gxxlog', metavar='LOG_FILENAME',
help='Sets the output filename')
gaussian.add_argument(
'-r', '--rwf', dest='gxxrwf', metavar='RWF_FILENAME',
help='''\
Sets the read-write filename (Expert use!).
"auto" sets automatically the rwf from the input filename.''')
gaussian.add_argument(
'-t', '--tmpdir', dest='tmpdir', metavar='TEMP_DIR',
help='''\
Sets the temporary directory where calculations will be run.
This is set automatically based on the node configuration.
"{username}" can be used as a placeholder for the username.''')
gaussian.add_argument(
'-w', '--wrkdir', dest='gxxwrk', nargs='+', metavar='WORKDIR',
help='''\
Appends a working directory to the Gaussian path to look for executables.
Several working directories can be given by using multiple times the -w
option. In this case, the last given working directory is the first one
using during the path search.
NOTE: Only the path to the working root directory is needed. The script
automatically selects the correct directories from there.
WARNING: The script expects a working tree structure as intended in the
Gaussian developer manual.
''')
return parser
# ==========================
# PATH-RELATED FUNCTIONS
# ==========================
def set_gxx_env(gxxroot: str) -> typing.List[str]:
"""Sets Gaussian-related environment variables.
Sets Gaussian-related environment variables and returns the list
of environment variables to be passed by PBS.
Parameters
----------
gxxroot : str
Gaussian root directory
Returns
-------
list
List of environment variables to be passed by PBS to node.
"""
dirlist = [os.path.join(gxxroot, f)
for f in ['bsd', 'local', 'extras', '']]
GAUSS_EXEDIR = os.pathsep.join(dirlist)
os.environ['GAUSS_EXEDIR'] = GAUSS_EXEDIR
os.environ['GAU_ARCHDIR'] = os.path.join(gxxroot, 'arch')
if 'PATH' in os.environ:
os.environ['PATH'] = os.pathsep.join([GAUSS_EXEDIR,
os.environ['PATH']])
else:
os.environ['PATH'] = GAUSS_EXEDIR
if 'LD_LIBRARY_PATH' in os.environ:
os.environ['LD_LIBRARY_PATH'] = \
os.pathsep.join([GAUSS_EXEDIR, os.environ['LD_LIBRARY_PATH']])
else:
os.environ['LD_LIBRARY_PATH'] = GAUSS_EXEDIR
return ["PATH", "LD_LIBRARY_PATH", "GAUSS_EXEDIR", "GAU_ARCHDIR"]
def check_gjf(gjf_ref: str,
gjf_new: str,
dat_P: typing.Optional[int] = None,
dat_M: typing.Optional[str] = None,
file_chk: typing.Optional[typing.Union[str, bool]] = None,
file_rwf: typing.Optional[typing.Union[str, bool]] = None,
rootdir: typing.Optional[str] = None
) -> typing.Tuple[int, str, typing.List[typing.List[str]]]:
"""Analyses and completes Gaussian input.
Checks and modifies a Gaussian input file and extracts relevant
information for the submission script:
- Hardware resources to be be read from the input file
- Files to copy.
Parameters
----------
gjf_ref : str
Reference input file
gjf_new : str
New input file where completed Gaussian directives are stored.
dat_P : int, optional
Number of processors to request in Gaussian job.
Otherwise, use the value in reference input file.
dat_M : str, optional
Memory requirement.
Otherwise, use the value in reference input file.
file_chk : str or bool, optional
Checkpoint file to use.
If None, do not specify it in input
file_rwf : str or bool, optional
Checkpoint file to use
If None, do not specify it in input
rootdir : str, optional
Root directory to look for files
Returns
-------
tuple
The following information are returned:
- number of processors actually requested
- actual memory requirements
- list of files to copy from/to the computing node
"""
def write_hdr(fobj: typing.IO[str],
dat_P: typing.Optional[int] = None,
dat_M: typing.Optional[str] = None,
file_chk: typing.Optional[typing.Union[str, bool]] = None,
file_rwf: typing.Optional[typing.Union[str, bool]] = None
) -> None:
"""Small function to write Link0 header.
Parameters
----------
dat_P : int, optional
Number of processors to request in Gaussian job.
dat_M : str, optional
Memory requirement.
file_chk : str or bool, optional
Checkpoint file to use.
file_rwf : str or bool, optional
Checkpoint file to use
"""
if dat_M is not None:
fobj.write('%Mem={}\n'.format(dat_M))
if dat_P is not None:
fobj.write('%NProcShared={}\n'.format(dat_P))
if file_chk is not None and file_chk:
fobj.write('%Chk={}\n'.format(file_chk))
if file_rwf is not None and file_rwf:
fobj.write('%Rwf={}\n'.format(file_rwf))
def process_route(route: str
) -> typing.Union[bool, bool, bool, bool,
typing.List[str]]:
"""Processes Gaussian's route specification section.
Parses a route specification and checks relevant parameters.
Parameters
----------
route : str
Route specification
Returns
-------
tuple
The following information are returned:
- bool if Link717 will be used
- bool if Link717 option section present in input
- bool if Link718 will be used
- bool if Link718 option section present in input
- list of files to copy from/to the computing node
"""
fmt_frq = r'\bfreq\w*=?(?P<delim>\()?\S*{}\S*(?(delim)\))\b'
# ! fmt_geom = r'\bgeom\w*=?(?P<delim>\()?\S*{}\S*(?(delim)\))\b'
# ! key_FC = re.compile(str_FC, re.I)
str_FC = r'\b(fc|fcht|ht)\b'
key_718 = re.compile(fmt_frq.format(str_FC), re.I)
key_718o = re.compile(fmt_frq.format(r'\breadfcht\b'), re.I)
key_717 = re.compile(fmt_frq.format(r'\breadanh'), re.I)
key_717o = re.compile(fmt_frq.format(r'\banharm(|onic)\b'), re.I)
use717, use718, opt717, opt718 = False, False, False, False
extra_cp = []
# Check if we need to copy back
keyGeomView = re.compile(r'\bgeomview\b')
if keyGeomView.search(route):
extra_cp.append(['cpfrom', 'points.off'])
key_fchk = re.compile(r'\b(FChk|FCheck|FormCheck)\b')
if key_fchk.search(route):
extra_cp.append(['cpfrom', 'Test.FChk'])
if key_718.search(route):
use718 = True
if key_718o.search(route):
use718 = True
opt718 = True
if not key_718:
s = 'WARNING: It is not yet possible to run FCHT ' \
+ 'calculations with ReadFCHT only'
print(s)
if key_717.search(route):
use717 = True
if key_717o.search(route):
use717 = True
opt717 = True
return use717, opt717, use718, opt718, extra_cp
nprocs = dat_P
mem = dat_M
ops_copy = []
ls_exts = ['.chk', '.dat', '.log', '.out', '.fch', '.rwf']
ls_chks = []
# ls_chks should be given as tuples (op, file) with:
# op = 0: cpto/cpfrom
# 1: cpto
# 2: cpfrom
# Reference for `op`: scratch dir
# file: checkpoint file of interest
if file_chk:
ls_chks.append((0, file_chk))
ls_rwfs = []
if file_rwf:
ls_rwfs.append(file_rwf)
ls_files = []
newlnk = True
inroute = False
use717 = [None]
use718 = [None]
opt717 = [None]
opt718 = [None]
route = ['']
with open(gjf_new, 'w') as fobjw:
write_hdr(fobjw, dat_P, dat_M, file_chk, file_rwf)
with open(gjf_ref, 'r') as fobjr:
for line in fobjr:
line_lo = line.strip().lower()
# END-OF-BLOCK
if not line_lo:
fobjw.write(line)
if inroute:
use717[-1], opt717[-1], use718[-1], opt718[-1], dat =\
process_route(route[-1])
if dat:
ops_copy.extend(dat)
inroute = False
continue
# NEW BLOCK
if line_lo == '--link1--':
fobjw.write(line)
newlnk = True
route.append('')
use717.append(None)
use718.append(None)
opt717.append(None)
opt718.append(None)
write_hdr(fobjw, dat_P, dat_M, file_chk, file_rwf)
# INSTRUCTIONS
else:
if line_lo.startswith(r'%'):
if line_lo != '%nosave':
keyval = line.split('=')[1].strip()
# LINK0 INSTRUCTION
if line_lo.startswith(r'%chk'):
if file_chk is None:
ls_chks.append((0, keyval))
else:
line = ''
elif line_lo.startswith(r'%oldchk'):
ls_chks.append((1, keyval))
elif line_lo.startswith(r'%rwf'):
if file_rwf is not False:
ls_rwfs.append(keyval)
else:
line = ''
elif line_lo.startswith('%mem'):
if dat_M is None:
mem = keyval
else:
line = ''
elif line_lo.startswith('%nproc'):
if dat_P is None:
nprocs = int(keyval)
else:
line = ''
elif (line_lo.startswith('#') and newlnk) or inroute:
# ROUTE SECTION
newlnk = False
inroute = True
route[-1] += ' ' + line.strip()
else:
# REST OF INPUT
# The input files should not contain any spaces
# We assume that extensions are provided
if use717[-1] or use718[-1]:
if len(line_lo.split()) == 1 and \
line_lo.find('.') > 0:
ext = os.path.splitext(line.strip())[1]
if ext[:4] in ls_exts:
ls_files.append(line.strip())
fobjw.write(line)
# Copy files for CHK
if ls_chks:
# set is there to remove duplicate files
for oper, chk in set(ls_chks):
if oper in [0, 1] and os.path.exists(chk):
ops_copy.append(['cpto', chk, rootdir])
if oper in [0, 2]:
ops_copy.append(['cpfrom', chk, rootdir])
if ls_rwfs:
# set is there to remove duplicate files
for rwf in set(ls_rwfs):
if os.path.exists(rwf):
ops_copy.append(['cpto', rwf, rootdir])
ops_copy.append(['cpfrom', rwf, rootdir])
if ls_files:
for fname in set(ls_files):
if os.path.exists(fname):
ops_copy.append(['cpto', fname, rootdir])
if ops_copy:
for cmd, what, _ in ops_copy:
if cmd == 'cpto':
dname, fname = os.path.split(what)
if dname:
print('Will copy file: {} from {}'.format(fname, dname))
else:
print('Will copy file: {}'.format(what))
return nprocs, mem, ops_copy
# ============================
# QUEUES-RELATED FUNCTIONS
# ============================
def get_queue_data(full_queue: str,
) -> typing.Tuple[str, hpc.NodeFamily, int,
typing.Union[str, None]]:
"""Returns the queue specification and node-specific information.
Based on the full_queue specification, defines and returns:
- the actual queue (if virtual queue specified)
- the node family specifications
- the number of processing units to use
- a specific node definition (if relevant)
Parameters
----------
full_queue : str
full queue specifications as "queue[:[nproc_spec]:[node_id]]"
Returns
-------
tuple
Tuple containing the following information
- actual queue (same as full_queue if not latter not virtual)
- node family specification (as a `NodeFamily` object)
- number of processors actually requested
- name of a specific node
Raises
------
ValueError
Incorrect definition of the virtual queue
KeyError
Unsupported queue
"""
# Queue specification parsing
# ---------------------------
data = full_queue.split(':')
if len(data) == 1:
queue = data[0]
nprocs = None
nodeid = None
elif len(data) == 2: