-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsubmit.py
executable file
·2103 lines (1798 loc) · 81.7 KB
/
submit.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 python
# This python environment line will need to be changed for ACI-b
# For ACI-b, replace crunchbang patch with the path below
# /usr/bin/env python --- Use this for aci-b and local
#! /usr/global/python/2.7.3/bin/python ---- Use this for LionX
import sys, os
from textwrap import dedent
# NOTE: This script deliberately does not contain calls to
# non-standard library modules, and should remain one file long
"""
NOTE: This is written in an object-oriented way. There are two
main classes, Host and Submittable.
Host controls everything having to do with the environment that
the job will be submitted on. It is subclassed by two classes,
Queue and Interactive, each used for hosts with a PBS queueing
system and ones that are interactive, respectively. Then, each
host (i.e. LionXF, Cyberstar, Local, etc.) are derived from
Queue or Interactive. Thus each class shares as much in common
with the parent class which cuts down on programming-by exception.
Each class may override the parent class's methods, allowing for
greater flexability.
The same approach is taken with Submittable. Submittable controls
the input file and how it will be submitted. Submittable is
subclassed by Scratch and Noscratch, which are for programs that
require explicit handling of the scratch directory and those that
don't, respectively. Each program is then a subclass of these
(i.e. Dalton and POVRay of Noscratch, ADF, NWChem, etc. of Scratch).
Although this file is twice as long as the old procedural approach,
it is twice as easy to maintain. For example, in the old method,
the submit_interactive_scratch routine was very long, but mostly
because of multiple if statements required for each program type.
In this new method, each class implements its own versions of
methods when necessary, making it easier to maintain a specific
program's submit properties.
"""
def main():
'''\
Submit a job. The program automatically determines what program type
and how to submit based on the extention, the contents of the input file,
and the name of the host you are submitting on. The input filenames may
be given explicitly or piped in from the standard input.
If list_limits is given on the command line, the job limits on the current
host will be given, and the program will terminate.
See man page for more info.
'''
## Determine the host file system and it's properties
#host = determine_host(os.uname()[1])
# get the fully qualified domain name and use that to determine host
import socket
host = determine_host(socket.getfqdn())
# Check arguments
from argparse import ArgumentParser, RawDescriptionHelpFormatter
parser = ArgumentParser(description=dedent(main.__doc__),
formatter_class=RawDescriptionHelpFormatter,
prefix_chars='-+')
parser.add_argument('--version', action='version', version='%(prog)s 1.5')
parser.add_argument('input_files', nargs='*', default=sys.stdin,
help='The input files to submit.')
parser.add_argument('-o', '--out', help='Specifies a non-default output '
'file to use. You must include the extention you '
'want.', metavar='LOGFILE')
parser.add_argument('-s', '--scratch', help='Change the scratch directory '
"from the default '%(default)s' to %(metavar)s.",
default=host.scratch)
# Options for Abinit only
abinit = parser.add_argument_group('opts for ABINIT')
abinit.add_argument('--psp', help='Define the paths for the '
'psuedopotentials to add to the .files file', nargs='+')
# Options for Dalton only
dalton = parser.add_argument_group('opts for Dalton')
dalton.add_argument('-r', '--restart', help='Restart file to use. Do not '
'include the .tar.gz extention.')
dalton.add_argument('-R', '--restartdir', help='Directory of restart files. '
'This option is most useful for globbing to generate Raman '
'spectra. Use the exact path!')
# Options for POV-Ray only
povray = parser.add_argument_group('opts for POV-Ray')
povray.add_argument('--vmd', help='Use a multiple of the default height '
'and width for VMD.', type=float)
# Options for jobs submitted on a queueing system
queue = parser.add_argument_group('opts for hosts with queueing systems',
'These have no effect on an interactive system')
queue.add_argument('-n', '--nodes', help='The number of nodes to run on.',
type=int)
queue.add_argument('-p', '--ppn', help='The processors per node to use. '
'To explicitly not use this (an option on LionXF and '
'LionXG) then use -1', type=int)
queue.add_argument('-w', '--wall', help='The wall time to request in '
'any of: sec, min:sec, hour:min:sec, day:hour:min:sec.',
metavar='WALLTIME')
queue.add_argument('-m', '--mem', help='Request a particular amount of'
'memory per processor. Not required. Given in MB.',
type=int)
queue.add_argument('-a', '--all', help='Specify nodes, ppn, wall and mem '
'with one option, in that order. i.e., '
'--all 8 1 48:00:00 2000 to specify 8 nodes, 1 ppn,'
'48:00:00 walltime and 2000 MB. ',
nargs=4, metavar=('NODES', 'PPN', 'WALLTIME', 'MEM'))
queue.add_argument('-e', '--exclusive', help='Specify nodes and wall'
'with one option, in that order. i.e., '
'--all 1 48:00:00 to specify all resources from 2 nodes'
'and 48:00:00 walltime. ',
nargs=2, metavar=('NODES', 'WALLTIME'))
queue.add_argument('-d', '--default', help='Chooses the default values '
'for nodes, ppn, wall and mem for this host. You '
'may override the hard-coded defaults with a .submitrc '
'file in your home directory', action='store_true',
default=False)
queue.add_argument('--nolimit', default=True, dest='check_limits',
action='store_false', help='By default, this program '
'will check your job parameters to make sure they are '
'within the limits of the computer. This switch will '
'disable that check.')
queue.add_argument('-S', '--script', help='Creates the script file '
'without submitting. Useful if you want to edit the '
'job.', action='store_true', default=False)
queue.add_argument('-ex', '--exact', help='Use exact node arrangement'
'on LionXF or LionXG.', action='store_true', default=False)
queue.add_argument('-O', '--open', help='Use the open queue on ACI-b',
action='store_true', default=False)
queue.add_argument('-A', '--allocation', help="Select allocation to submit to, "
"'a', 'e', or 'c'. Default is 'o', open queue;"
"'a' is our standard, paid allocation; "
"'e' is basic computing nodes, lxj18_e_g_bc_default; "
"'c' is another allocation of standard computing nodes, lxj18_c_t_sc_default;",
type=str, default='o' )
# Options for jobs submitted on an interactive system
inter = parser.add_argument_group('opts for interactive hosts',
'These have no effect on a queueing system')
inter.add_argument('-D', '--debug', action='store_true', default=False,
help='Open output file with less upon completion.')
inter.add_argument('--pid', action='store_true', default=False,
help='Adds the process ID number to the output file '
'name.')
inter.add_argument('--nice', help='The niceness (0 to 20), '
'%(default)i is default.', default=19, type=int,
choices=range(21), metavar='NICE')
inter.add_argument('-q', '--quiet', action='store_true', default=False,
help='Do not print anything to screen.')
args, subopts = parser.parse_known_args()
# store input arguments as integers for possible manipulation later
if args.all:
args.all[0] = int(args.all[0])
args.all[1] = int(args.all[1])
args.all[3] = int(args.all[3])
args.lexclusive = False
if args.exclusive:
args.exclusive[0] = int(args.exclusive[0])
args.lexclusive = True
# Verify the options based on the host
opts, input_files = host.verify_options(args)
# Select the designated allocation on ACI/HPC
import json
try:
with open(os.getenv('ALLOCATIONS')) as f:
data = f.read()
allocations = json.loads(data)
args.allocation = args.allocation.lower()
try:
host.queue = allocations[args.allocation]
except KeyError:
sys.exit("Unrecognized allocation. Current allocations available: " + ', '.join(list(allocations.keys())))
except TypeError:
if not host.local:
sys.exit("You need to set the environment variable ALLOCATIONS and point it to the correct file")
except IOError:
if not host.local:
sys.exit("You need to set the environment variable ALLOCATIONS and point it to the correct file")
# Loop over files, submitting each one
for f in input_files:
# Make sure the file exists
try:
with open(f) as dummy:
pass
except IOError as i:
print(str(i), file=sys.stderr)
print('Skipping...', file=sys.stderr)
# Determine the file type
input_file = determine_file_type(f, host, opts, subopts)
# Submit this file
try:
input_file.submit()
except AttributeError:
# Skip if an unrecognized extention was given
pass
def abs_file_path(filename, env=None):
'''This function takes a filename with a path and returns the
absolute path.
'''
from os.path import expanduser, expandvars, abspath
absfile = abspath(expandvars(expanduser(filename)))
# Now replace front with $HOME if requested
if env:
if os.environ['HOME'] in absfile:
i = len(os.environ['HOME']) + 1
# Assemble absolute path, using the $HOME variable
absfile = os.path.join('$HOME', absfile[i:])
return absfile
def determine_file_type(input_file, host, opts, subopts):
'''Determine the program based on it's extention.
Returns the class associated witt this program.'''
# Determine what job type this is. Use the extension
try:
program = { 'pov' : 'povray', 'ini': 'povray',
'inp' : 'adf', 'run': 'adf',
'nw' : 'nwchem', 'dal': 'dalton',
'g09' : 'gaussian', 'qchem' : 'qchem',
'in' : 'abinit', 'dim': 'dim',
'script' : None,
}[os.path.splitext(input_file)[1][1:]]
except KeyError:
print('Unrecognized extention:',
os.path.splitext(input_file)[1][1:]+'.', 'Skipping...',
file=sys.stderr)
return
else:
# BAND could be mistaken as ADF. Check and change as necessary.
# Do this by looking in file to find the band executable command.
if program == 'adf':
# Read in file as a single string and search string as a whole.
try:
fs = open(input_file).read()
except IOError:
print('File', input_file, 'does not exist. Skipping...',
file=sys.stderr)
return
if '$ADFBIN/band' in fs:
program = 'band'
elif "$ADFBIN/reaxff" in fs:
program = 'reaxff'
# Now make a submittable object out of this file
if program == 'adf':
return ADF(input_file, host, opts, subopts)
elif program == 'nwchem':
return NWChem(input_file, host, opts, subopts)
elif program == 'band':
return BAND(input_file, host, opts, subopts)
elif program == 'reaxff':
return ReaxFF(input_file, host, opts, subopts)
elif program == 'povray':
return POVRay(input_file, host, opts, subopts)
elif program == 'abinit':
return ABINIT(input_file, host, opts, subopts)
elif program == 'dalton':
return Dalton(input_file, host, opts, subopts)
elif program == 'qchem':
return QChem(input_file, host, opts, subopts)
elif program == 'gaussian':
return Gaussian(input_file, host, opts, subopts)
elif program == 'dim':
return DIM(input_file, host, opts, subopts)
elif program is None:
return PBSScript(input_file, host, opts, subopts)
def determine_host(hostname):
'''Return the correct host class based on the name'''
if 'chem.psu.edu' in hostname:
return Local(hostname)
elif 'science.psu.edu' in hostname:
return Local(hostname)
elif 'stampede3.tacc.utexas.edu' in hostname:
return Stampede(hostname)
elif 'acib.production.int.aci.ics.psu.edu' in hostname:
return ACIb(hostname)
elif 'hpc.psu.edu' in hostname:
return Hpc(hostname)
else:
sys.exit('Unknown host! Speak to your sysadmin.')
class Submittable(object):
'''Base class that implemets basic functionality for objects
that are submittable. This is intended to be subclassed and many
of the methods may be overwritten.'''
def __init__(self, filename, host, opts, subopts):
'''Initiallizes the Submittable class, accepting the
command-line arguments.'''
from os.path import relpath, split, splitext, basename
# Store the options
self.out = opts.out
self.psp = opts.psp
self.restart = opts.restart
self.restartdir = opts.restartdir
self.nodes = opts.nodes
self.ppn = opts.ppn
self.wall = opts.wall
self.mem = opts.mem
self.check_limits = opts.check_limits
self.debug = opts.debug
self.pid = opts.pid
self.nice = opts.nice
self.quiet = opts.quiet
self.script = opts.script
self.exact = opts.exact
self.open = opts.open
self.lexclusive = opts.lexclusive
# Keep the suboptions
self.subopts = subopts
# Store the host information
self.host = host
# Grab the filename and extention separetely
self.noext, self.ext = splitext(filename)
self.ext = self.ext[1:]
# Find the base file name (no path, no ext) and the path
self.path, base = split(self.noext)
# Store both noextension names under one heading
self.noext = { 'full' : self.noext, 'base' : base }
# Full input filename and base of the input filename
self.input = { 'full' : filename, 'base' : basename(filename) }
# Make output filename and the base of the input filename
if self.out:
self.output = abs_file_path(self.out)
# Make sure all names match the output.
self.noext['full'] = splitext(self.output)[0]
self.noext['base'] = basename(self.noext['full'])
else:
self.output = self.output_name()
# Define output base and store both full and base name in one
self.output = { 'full' : self.output, 'base' : basename(self.output) }
# Add pid to output extention if appropriate
if self.pid:
self.output['full'] = '.'.join([self.noext['full'],
str(os.getpid()), 'out'])
self.output['base'] = basename(self.output['full'])
self.noext['full'] = splitext(self.output['full'])[0]
self.noext['base'] = basename(self.noext['full'])
def output_name(self):
'''Creates the full output file name. Should be overridden
in the sub class if the program does not use .out files.'''
return '.'.join([self.noext['full'], 'out'])
def edit_input(self):
'''Edits the input file, changing location-specific things.'''
# Read in file as a single string
fs = open(self.input['full']).read()
rewrite = False
# See if we need to replace references to gpfs with amp or vice versa
if self.host.local and 'gpfs/work' in fs:
fs = fs.replace('gpfs/work', 'amphome')
rewrite = True
elif not self.host.local and 'amphome' in fs:
fs = fs.replace('amphome', 'gpfs/work')
rewrite = True
# Re-write to file if something changed
if rewrite:
with open(self.input['full'], 'w') as f:
print(fs, file=f)
def submit(self):
'''Submits the job'''
# See if the input file must be edited, and do so if necessary
self.edit_input()
# Submit interactively
if self.host.submit_type == 'interactive':
self.submit_interactive()
# Pull up output file if debugging
if self.debug:
from subprocess import call
call([self.display_prog(), self.output['full']])
# Submit by queue
else:
if self.host.queue_type == 'PBS':
self.submit_PBS_queue()
elif self.host.queue_type == 'SBATCH':
self.submit_SBATCH_queue()
def create_script(self, **kwargs) -> str:
'''Creates the .script file used for submitting on queueing hosts.
Must be overridden in the subclass.'''
return "Modified part of the input script"
def executable(self):
'''The executable to use to submit this script interactively.
Must be overridden in the subclass.'''
pass
def copy_input(self, tmpdir):
'''Copies input to the temp directory.
May be overwritten by the subclass'''
from shutil import copy
import os.path
from os.path import join
# hack to get TAPE21 and TAPE16 files into scratch for densf calculations
bases = os.path.splitext(self.input['full'])[0]
if (os.path.isfile(bases+".t21")):
copy(bases+".t21", join(tmpdir, "TAPE21"))
if (os.path.isfile(bases+".t16")):
copy(bases+".t16", join(tmpdir, "TAPE16"))
copy(self.input['full'], join(tmpdir, self.input['base']))
def add_input(self, arguments):
'''Appends the input files to the executable statement
in the appropriate way. May be overwritten by the subclass'''
return arguments + [self.input['full']]
def stdstreams(self, **kwargs):
'''Returns the proper standard in, out and error.
May be overwritten by the subclass'''
if self.quiet:
return None, open(self.output['full'], 'w'), open('logfile', 'w')
else:
return None, open(self.output['full'], 'w'), sys.stderr
def clean(self, **kwargs):
'''Used to clean up after a job. Returns the sources and destinations
of files to copy. May be overwritten by the subclass'''
return None, None
def display_prog(self):
'''The program to display the results of execution (for debugging).
May be overwritten by the subclass'''
return 'less'
def submit_PBS_queue(self):
'''Submits the file on the PBS queueing system.'''
from subprocess import call
from os import chmod, environ
# If a required argument is missing, request it from the user now
n = 'How many nodes do you want assigned? [{0}] '
n = n.format(self.host.defaultnodes)
p = 'How many processors per node? [{0}] '.format(self.host.defaultppn)
w = 'Requested wall clock time? [{0}] '.format(self.host.defaultwall)
m = 'How much memory per processor do you want (MB) [{0}] '
m = m.format(self.host.defaultmem)
print('File', self.input['full'])
nodes = self.nodes if self.nodes else raw_input(n)
ppn = self.ppn if self.ppn else raw_input(p)
wall = self.wall if self.wall else raw_input(w)
mem = self.mem if self.mem else raw_input(m)
# Default the values if none are still given
nodes = nodes if nodes else self.host.defaultnodes
ppn = ppn if ppn else self.host.defaultppn
wall = wall if wall else self.host.defaultwall
mem = mem if mem else self.host.defaultmem
# Make sure that the options are the correct type
nodes, ppn, wall, mem = self.host.type_check(nodes, ppn, wall, mem)
# Check that the values are OK and format them
if self.check_limits: self.host.check_limits(nodes, ppn, wall, mem)
# Open the submit script and create it
script = '.'.join([self.noext['full'], 'script'])
with open(script, 'w') as sc:
# Q-Chem is a little more particular
if self.ext == 'qchem':
print('#!/bin/csh', file=sc)
print('#', file=sc)
if self.exact: print('#PBS -W x=nmatchpolicy:exactnode', file=sc)
if ppn == -1:
procs = '#PBS -l nodes={0[0]:d}'
else:
procs = '#PBS -l nodes={0[0]:d}:ppn={0[1]:d}'
print(procs.format([nodes, ppn]), file=sc)
print('#PBS -l walltime={0}'.format(self.host.td2hms(wall)),
file=sc)
# Add memory request if necessary
if mem is not None:
print('#PBS -l pmem={0:d}mb'.format(mem), file=sc)
# Direct output to correct files
print('#PBS -j eo', file=sc)
print('#PBS -e {name}.err'.format(name=self.noext['full']), file=sc)
# Add email options
#print('#PBS -m ae', file=sc)
#print('#PBS -M {user}@psu.edu'.format(user=environ['USER']),
# file=sc)
# Create the remainder of the script
print(self.create_script(pp=abs(nodes*ppn)), file=sc)
# Make the script executable
chmod(script, 0o755)
# The job name can only be 15 bytes and must begin with a letter
jobname = self.noext['base'][0:15]
if jobname[0].isdigit(): jobname = 'q'+jobname[1:]
# Submit the script unless otherwise directed
if not self.script:
print('Submitting {0} job {1}...'.format(type(self).__name__,
self.noext['base']))
if self.open:
call(['qsub', '-N', jobname, script])
else:
call(['qsub', '-A','%s'%(self.host.queue),'-N',jobname, script])
print()
else:
from os.path import relpath
script = relpath(script)
print('Wrote {0} job script {1}...'.format(type(self).__name__,
script))
print('Submit with "qsub -N {0} {1}"'.format(jobname, script))
print()
def submit_SBATCH_queue(self):
'''Submits the file on the SBATCH queueing system.'''
from subprocess import call
from os import chmod, environ
# If a required argument is missing, request it from the user now
n = 'How many nodes do you want assigned? [{0}] '
n = n.format(self.host.defaultnodes)
p = 'How many processors per node? [{0}] '.format(self.host.defaultppn)
w = 'Requested wall clock time? [{0}] '.format(self.host.defaultwall)
m = 'How much memory per processor do you want (MB) [{0}] '
m = m.format(self.host.defaultmem)
print('File', self.input['full'])
if 'stampede3.tacc.utexas.edu' in self.host.name:
self.lexclusive = True
if self.lexclusive:
nodes = self.nodes if self.nodes else raw_input(n)
wall = self.wall if self.wall else raw_input(w)
# ppn = self.ppn if self.ppn else raw_input(p)
# mem = self.mem if self.mem else raw_input(m)
ppn = 0
mem = 0
else:
nodes = self.nodes if self.nodes else raw_input(n)
ppn = self.ppn if self.ppn else raw_input(p)
wall = self.wall if self.wall else raw_input(w)
mem = self.mem if self.mem else raw_input(m)
# Default the values if none are still given
nodes = nodes if nodes else self.host.defaultnodes
ppn = ppn if ppn else self.host.defaultppn
wall = wall if wall else self.host.defaultwall
# mem = mem if mem else self.host.defaultmem
# Make sure that the options are the correct type
nodes, ppn, wall, mem = self.host.type_check(nodes, ppn, wall, mem)
# Check that the values are OK and format them
if self.check_limits: self.host.check_limits(nodes, ppn, wall, mem)
# Open the submit script and create it
script = '.'.join([self.noext['full'], 'script'])
with open(script, 'w') as sc:
# Q-Chem is a little more particular
if self.ext == 'qchem':
print('#!/bin/csh', file=sc)
else:
print('#!/bin/bash', file=sc)
print('#', file=sc)
# print(self.lexclusive)
print('#SBATCH --time={0}'.format(self.host.td2hms(wall)),
file=sc)
print("#SBATCH --nodes={0:}".format(nodes), file=sc)
if self.lexclusive:
print("#SBATCH --exclusive", file=sc)
#else:
if ppn != -1:
print("#SBATCH --ntasks-per-node={0:}".format(ppn), file=sc)
# Add memory request if necessary
if mem is not None:
print('#SBATCH --mem-per-cpu={0:d}mb'.format(mem), file=sc)
if 'hpc.psu.edu' in self.host.name:
if self.host.queue != 'open':
print('#SBATCH --account={}'.format(self.host.queue), file=sc)
print('#SBATCH --partition={}'.format('sla-prio'), file=sc)
else :
print('#SBATCH --account={}'.format(self.host.queue), file=sc)
print('#SBATCH --partition={}'.format('open'), file=sc)
elif 'stampede3.tacc.utexas.edu' in self.host.name:
print('#SBATCH -p {}'.format(self.host.queue), file=sc)
# Create the remainder of the script
print('#SBATCH --error {name}.err'.format(name=self.noext['full']), file=sc)
print(self.create_script(pp=abs(nodes*ppn)), file=sc)
# Make the script executable
chmod(script, 0o755)
# The job name can only be 15 bytes and must begin with a letter
jobname = self.noext['base'][0:15]
if jobname[0].isdigit(): jobname = 'q'+jobname[1:]
# Submit the script unless otherwise directed
if not self.script:
print('Submitting {0} job {1}...'.format(type(self).__name__,
self.noext['base']))
call(['sbatch', '--job-name',jobname, script])
else:
from os.path import relpath
script = relpath(script)
print('Wrote {0} job script {1}...'.format(type(self).__name__,
script))
print('Submit with "sbatch --job-name {0} {1}"'.format(jobname, script))
print()
class PBSScript(Submittable):
'''Class to submit a PBS job script directly'''
def __init__(self, host, filename, opts, subopts):
'''Initiallizes the PBSScript class'''
Submittable.__init__(self, host, filename, opts, subopts)
self.debug = False
def submit_interactive(self):
'''It is not possible to submit a PBS job interactively'''
string = 'File {0} is a PBS job file.'.format(self.input['base'])
print(string, 'Submitting interactively makes no sense.',
file=sys.stderr)
print('Skipping...', file=sys.stderr)
def submit_PBS_queue(self):
'''Submit to the PBS queueing system'''
from subprocess import call
# The job name can only be 15 bytes and must begin with a letter
jobname = self.noext['base'][0:15]
if jobname[0].isdigit(): jobname = 'q'+jobname[1:]
# Submit the script
print('Submitting {0} job {1}...'.format(type(self).__name__,
self.noext['base']))
call(['qsub', '-N', jobname, self.input['full']])
print()
class Scratch(Submittable):
'''This provides the submit_interactive class for programs
that required explicit scratch handling.'''
def __init__(self, host, filename, opts, subopts):
'''Initiallizes the Scratch class'''
Submittable.__init__(self, host, filename, opts, subopts)
def submit_interactive(self):
'''Submits a job interactively
with an excplicit scratch directory'''
from shutil import rmtree, copy, Error
from subprocess import call
from os.path import join
from os import getpid, mkdir, remove
# Make a temp dir in the scratch directory
tmpdir = '.'.join([type(self).__name__, str(getpid())])
tmpdir = join(self.host.scratch, tmpdir)
# Print head if not quiet
if not self.quiet:
from time import strftime
head = '''\
***********************************************************************
****************** OUTPUT FROM SUBMIT SHELL SCRIPT ******************
***********************************************************************
Invocation : {submit} {params}
Job submitted at : {date}
Input file : {file}
Output file : {output}
PID : {pid:d}
Nice : {nice:d}
Input dir : {input}
Scratch dir : {scratch}
Program : {progexe}
'''
print(head.format(
submit=sys.argv[0], params=' '.join(sys.argv[1:]),
date=strftime('%c'), file=self.input['full'],
output=self.output['full'], pid=getpid(), nice=self.nice,
input=self.path, scratch=tmpdir, progexe=self.executable()),
file=sys.stderr)
# Make the temp directory
mkdir(tmpdir)
# if TAPE16 or TAPE21 files exist move them into temp dir
import os.path
if (os.path.isfile("TAPE21")):
copy("TAPE21", tmpdir)
if (os.path.isfile("TAPE16")):
copy("TAPE16", tmpdir)
# Copy input file into that directory
self.copy_input(tmpdir)
# Return where the output is going (in input is coming from)
stdin, stdout, stderr = self.stdstreams(tmpdir=tmpdir)
# Make a soft link of the logfile if appropriate
self.link_log(tmpdir)
# Make the submittable argument list
arguments = self.add_input(['nice', '-n', str(self.nice)])
# Submit
call(arguments, stdout=stdout, stderr=stderr, stdin=stdin, cwd=tmpdir)
# Clean up
sources, dests = self.clean(tmpdir=tmpdir)
# Copy the sources to the dest
for source, dest in zip(sources, dests):
try:
copy(source, dest)
except (IOError, OSError):
pass
except Error:
# If there is a link, remove the link before continuing
remove(dest)
try:
copy(source, dest)
except (IOError, OSError):
pass
# Remove the temporary directory
rmtree(tmpdir, True)
# Print tail
if not self.quiet:
print('''\
Job finish at : {date}
***********************************************************************
***********************************************************************
***********************************************************************
'''.format(date=strftime('%c')))
def link_log(self, tmpdir):
'''Make a soft link to the logfile in the submitted directory.
Does nothing by default'''
pass
class ABINIT(Scratch):
'''Class that handles the submission of ABINIT files.
It is a subclass of Submittable and overrides some methods.'''
def __init__(self, host, filename, opts, subopts):
'''Initiallizes the ABINIT submission class'''
# Initiallize the parent
Scratch.__init__(self, host, filename, opts, subopts)
# Format the psuedopotential files
if self.psp:
for i in xrange(len(self.psp)):
self.psp[i] = abs_file_path(self.psp[i])
else:
sys.exit('ABINIT requires psuedopotential files with --psp')
def output_name(self):
'''Creates the full output file name. Overrides the base
class's method.'''
return '.'.join([self.noext['full'], 'logfile'])
def executable(self):
'''The executable to use for interactive jobs.
Overrides the base class'''
return 'abinis' if 'hammer' in self.host.name else 'abinit'
def copy_input(self, tmpdir):
'''Copies input files to the temp directory.'''
from glob import glob
from shutil import copy
from os.path import join, splitext
# Construct a .files file
self.files = '.'.join([self.noext['base'], 'files'])
self.files = { 'full' : join(self.path, self.files),
'base' : self.files }
with open(self.files['full'], 'w') as f:
print(self.input['full'], file=f)
print('.'.join([self.noext['base'], 'out']), file=f)
print(splitext(self.input['base'])[0]+'i', file=f)
print(self.noext['base']+'0', file=f)
print('tmp', file=f)
for p in self.psp:
print(p, file=f)
# Copy auxillary files
for x in glob(splitext(self.input['full'])[0]+'i*'):
x = x.strip()
copy(x, tmpdir)
# Copy the .files file
copy(self.files['full'], join(tmpdir, self.files['base']))
def stdstreams(self, **kwargs):
'''Returns the proper standard in, out and error.'''
from os.path import join
try:
tmpdir = kwargs['tmpdir']
except KeyError:
sys.exit('Missing key "tmpdir" from stdstreams')
return (open(join(tmpdir, self.files['base'])),
open(self.output['full'], 'w'),
open('.'.join([self.noext['full'], 'err']), 'w'))
def add_input(self, arguments):
'''Appends the input files to the executable statement
in the appropriate way. This overrides the base class.'''
return arguments + [self.executable()]
def clean(self, **kwargs):
'''Cleans up after a job. Returns the sources and destinations
of files to copy.'''
from os.path import join
from os import chdir
from glob import glob
import tarfile
try:
tmpdir = kwargs['tmpdir']
except KeyError:
sys.exit('Missing key "tmpdir" in clean')
# Change to temp and tar all files together
chdir(tmpdir)
tarname = '.'.join([self.noext['base'], 'tar.gz'])
tar = tarfile.open(tarname, 'w:gz')
for f in glob(self.noext['base']+'o*'): tar.add(f)
tar.close()
# Go back to the input dir
chdir(self.path)
# Create a list of the sources and the dest files
sources = [join(tmpdir, tarname),
join(tmpdir, '.'.join([self.noext['base'], 'out']))]
dests = [join(self.path, tarname),
'.'.join([self.noext['full'], 'out'])]
return sources, dests
def create_script(self, **kwargs):
'''Write the ABINIT script to file.'''
from os.path import splitext
try:
prog = 'mpirun abinip' if kwargs['pp'] > 1 else 'abinis'
except KeyError:
sys.exit('Missing key "pp" in create_script')
return dedent('''\
#PBS -e {noext}.err
module load abinit
cd $TMPDIR
# Create the .files file
touch {name}.files
echo "{inp}" >> {name}.files
echo "{name}.out" >> {name}.files
echo "{inpname}i" >> {name}.files
echo "{name}o" >> {name}.files
echo "tmp" >> {name}.files
echo "{psp}" >> {name}.files
# Copy possible in files here
if [ -e {inpnoext}i* ]; then
cp {inpnoext}i* .
fi
{prog} < {name}.files > {out}
tar -czf {name}.tar.gz {name}o*
cp {name}.tar.gz {name}.out {name}.files {dir}\
''').format(name=self.noext['base'], out=self.output['full'],
inp=self.input['full'], noext=self.noext['full'],
psp='\n'.join(self.psp), dir=self.path, prog=prog,
inpname=splitext(self.input['base'])[0],
inpnoext=splitext(self.input['full'])[0])
class ADF(Scratch):
'''Class that handles the submission of ADF files.
It is a subclass of Submittable and overrides some methods.'''
def __init__(self, host, filename, opts, subopts):
'''Initiallizes the ADF submission class'''
# Initiallize the parent
Scratch.__init__(self, host, filename, opts, subopts)
# Files to save
self.save_files = {'logfile' : 'logfile', 'TAPE21' : 't21',
'TAPE13' : 't13', 'TAPE41' : 't41',
'dftb.chk': 'chk', 'dftb.rkf': 'rkf',
'TAPE15' : 't15', 'TAPE10' : 't10',
'TAPE16' : 't16'}
# The raw logfile name
self.rawlog = 'logfile'
# Issue a simple warning for .inp files.
if self.ext == 'inp':
print('Warning: .inp extention for ADF is being '
'depreciated for .run.', file=sys.stderr)
self.script_type = {
Hpc: self.create_script_hpc,
Stampede: self.create_script_stampede,
}
def edit_input(self):
'''Examines the input file and checks if it needs to be edited.
This overrides the base class's method.'''
# Read in file as a single string
fs = open(self.input['full']).read()
rewrite = False
# See if we need to replace references to gpfs with amp or vice versa
if self.host.local and 'gpfs/work' in fs:
fs = fs.replace('gpfs/work', 'amphome')
rewrite = True
elif not self.host.local and 'amphome' in fs:
fs = fs.replace('amphome', 'gpfs/work')
rewrite = True
# Remove $SCM_OUTPUT as it is a relic of old
if r'>>$SCM_OUTPUT' in fs:
fs = fs.replace(r'>>$SCM_OUTPUT', '')
rewrite = True
elif r'>$SCM_OUTPUT' in fs:
fs = fs.replace(r'>$SCM_OUTPUT', '')
rewrite = True
# Get rid of a pesky touch call in ReaxFF
if 'touch "$SCM_LINK_SUMMARY_TXT"' in fs:
s = 'touch "$SCM_LINK_SUMMARY_TXT"'
n = s+' 2>/dev/null'
# Don't change anything if we have already edited this
if n in fs:
pass
else:
fs = fs.replace(s, n)
rewrite = True
# Re-write to file if something changed
if rewrite:
with open(self.input['full'], 'w') as f:
print(fs, file=f)
def link_log(self, tmpdir):
'''Makes a soft link to the logfile'''
from subprocess import call
logname = '.'.join([self.noext['base'], 'logfile'])
call(['ln', '-sfT', os.path.join(tmpdir, self.rawlog),
os.path.join(self.path, logname)])
def executable(self):
'''The executable to use for interactive jobs.
Overrides the base class'''
try:
return os.environ['ADFHOME']
except KeyError:
sys.exit('$ADFHOME environment variable is not defined!')
def add_input(self, arguments):
'''Appends the input files to the executable statement
in the appropriate way. This overrides the base class.'''
return arguments + ['bash', self.input['base']]
def clean(self, **kwargs):
'''Cleans up after a job. Returns the sources and destinations
of files to copy.'''
from os.path import join, basename