-
Notifications
You must be signed in to change notification settings - Fork 4
/
distributed_pipeline_wrapper.py
executable file
·1830 lines (1408 loc) · 75.4 KB
/
distributed_pipeline_wrapper.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
"""
Author : Emmanuel Gonzalez
Date : 2021-12-17
Purpose: PhytoOracle | Scalable, modular phenomic data processing pipelines
"""
import os
import sys
import subprocess as sp
sp.call(f'{sys.executable} -m pip install --user pyyaml requests', shell=True)
import argparse
from genericpath import isfile
import pdb # pdb.set_trace()
import json
import yaml
import shutil
import glob
import tarfile
import multiprocessing
import re
from datetime import datetime
import numpy as np
import platform
import socket
import time
# Our libraries...
import server_utils
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='PhytoOracle | Scalable, modular phenomic data processing pipelines',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-hpc',
'--hpc',
help='Add flag if running on an HPC system.',
action='store_true')
parser.add_argument('-d',
'--date',
help='Date to process',
nargs='*',
type=str)
# required=True)
# Season 12 and on should have a value for experiment set (e.g. sorghum, sunflower)
# For Season 11 it should be left '' (so no experiment dir is created)
parser.add_argument('-x',
'--experiment',
help='Experiment (e.g. Sorghum, Sunflower)',
type=str,
default='')
parser.add_argument('-c',
'--cctools_version',
help='CCTools version',
type=str,
default='7.4.2')
parser.add_argument('-l',
'--local_cores',
help='Percentage of cores to use for local processing',
type=float,
default=1.0)#0.70)
parser.add_argument('-y',
'--yaml',
help='YAML file specifying processing tasks/arguments',
metavar='str',
type=str,
required=True)
parser.add_argument('-wm',
'--workload_manager_yaml',
help='YAML file specifying workload_manager arguments',
metavar='str',
type=str,
required=False)
parser.add_argument('--noclean',
help='Do not rm results locally',
#metavar='noclean',
#default=False,
action='store_true',
)
parser.add_argument('--module_breakpoints',
help='Useful for testing yaml modules. Code will breakpoint() just before each module. You can type `continue` to have it continue like nothing happened, or you can `^d` to stop the script and look at the wf_file_n.json and run it by hand.',
action='store_true',
)
parser.add_argument('--archiveonly',
help='just archive and exit (for testing)',
action='store_true',
)
parser.add_argument('--uploadonly',
help='just do cyverse ul and exit (for testing)',
action='store_true',
)
parser.add_argument('--noupload',
help='do not tar and upload outputs',
action='store_true',
)
parser.add_argument('-r',
'--reverse',
help='Reverse processing date list.',
action='store_true')
parser.add_argument('-sfs',
'--shared_file_system',
help='Shared filesystem.',
action='store_false')
parser.add_argument('-t',
'--timeout',
help='Command timeout in units minute.',
type=float,
default=1)
parser.add_argument('-m',
'--multi_date',
type=int,
help='Choose what date to process in the list 0 for the first element',
default=99)
return parser.parse_args()
# --------------------------------------------------
def build_containers(yaml_dictionary):
"""Build module containers outlined in YAML file
Input:
- yaml_dictionary: Dictionary generated from the YAML file
Output:
- Singularity images (SIMG files)
"""
for k, v in yaml_dictionary['modules'].items():
container = v['container']
if not os.path.isfile(container["simg_name"]):
print(f'Building {container["simg_name"]}.')
sp.call(f'singularity build --disable-cache {container["simg_name"]} {container["dockerhub_path"]}', shell=True)
# --------------------------------------------------
def download_cctools(cctools_version = '7.1.12', architecture = 'x86_64', sys_os = 'centos7'):
'''
Download CCTools (https://cctools.readthedocs.io/en/latest/) and extracts the contents of the file.
Input:
- cctools_version: CCTools version to install
- architecture: Bit software to download
- sys_os: Operating system on current machine
Output:
- path to cctools on working machine
'''
cwd = os.getcwd()
home = os.path.expanduser('~')
# builds from latest stable source if not on a centos system
if server_utils.distro_name() != 'CentOS Linux':
cctools_file = 'cctools-stable-source'
if not os.path.isdir(os.path.join(home, 'cctools')):
print(f'Downloading {cctools_file}.')
cctools_url = ''.join(['http://ccl.cse.nd.edu/software/files/', cctools_file])
print(cctools_url)
cmd1 = f'cd {home} && wget {cctools_url}.tar.gz'
sp.call(cmd1, shell=True)
os.chdir(home)
cmd2 = f'mkdir non_centos_cctools && tar xzvf {cctools_file}.tar.gz -C non_centos_cctools'
sp.call(cmd2, shell = True)
os.chdir('non_centos_cctools')
print('Building cctools from source...')
os.chdir(glob.glob('./*')[0])
cmd3 = './configure --prefix $HOME/cctools && make && make install'
sp.call(cmd3, shell = True)
os.remove(os.path.join(home, f'{cctools_file}.tar.gz'))
print(f'Download complete. CCTools is ready!')
else:
print('Required CCTools version already exists.')
return 'cctools/'
# builds from centos specific package if on centos
else:
cctools_file = '-'.join(['cctools', cctools_version, architecture, sys_os])
if not os.path.isdir(os.path.join(home, cctools_file)):
print(f'Downloading {cctools_file}.')
cctools_url = ''.join(['http://ccl.cse.nd.edu/software/files/', cctools_file])
cmd1 = f'cd {home} && wget {cctools_url}.tar.gz'
sp.call(cmd1, shell=True)
os.chdir(home)
file = tarfile.open(f'{cctools_file}.tar.gz')
file.extractall('.')
file.close()
os.remove(f'{cctools_file}.tar.gz')
try:
shutil.move('-'.join(['cctools', cctools_version, architecture, sys_os+'.tar.gz', 'dir']), '-'.join(['cctools', cctools_version, architecture, sys_os]))
except:
pass
os.chdir(cwd)
print(f'Download complete. CCTools version {cctools_version} is ready!')
else:
print('Required CCTools version already exists.')
return '-'.join(['cctools', cctools_version, architecture, sys_os])
def build_irods_path_to_sensor_from_yaml(yaml_dictionary, args):
"""
Every path (level zero or otherwise) starts the same:
.../phytooracle/season_11_sorghum_yr_2020/level_0/scanner3DTop
"""
cyverse_basename = yaml_dictionary['paths']['cyverse']['basename']
#season_name = yaml_dictionary['tags']['season_name']
season_name = get_season_name()
cyverse_datalevel = yaml_dictionary['paths']['cyverse']['input']['level']
sensor = yaml_dictionary['tags']['sensor']
path = os.path.join(
cyverse_basename,
season_name,
cyverse_datalevel,
sensor
)
experiment = args.experiment
# If level is greater than level zero, then we need to add
# two directories: .../expirment/date
# for example: level_1/scanner3DTop/sunflower/2222-22-22
if cyverse_datalevel > 'level_0':
path = os.path.join(
path,
(experiment if experiment else "")
)
return path
def download_irods_input_dir(yaml_dictionary, date, args):
"""
(0) Make the local input_dir
(1) Download all contents from the cyverse location pointed to
by yaml_dictionary['paths']['cyverse']['input']['input_dir']
(2) Untar stuff if needed
Usecase example... The level 1 3D data after landmark selection is a bunch of tarballs
and a json file that live in a directory called `alignment`. So we have to make that
dir locally, and then DL and untar each tarball and then DL the json file too.
"""
args = get_args()
# print('DOWNLOADING')
# Step (0)
input_dir = yaml_dictionary['paths']['cyverse']['input']['input_dir']
server_utils.make_dir(input_dir)
# Step (1)
sensor_path = build_irods_path_to_sensor_from_yaml(yaml_dictionary, args)
irods_input_dir_path = os.path.join(sensor_path, date, input_dir)
# if args.experiment:
# if int(str(yaml_dictionary['paths']['cyverse']['input']['level']).split('_')[1]) >= 1:
# irods_input_dir_path = os.path.join(sensor_path, date, input_dir, args.experiment)
# print(irods_input_dir_path)
files_in_dir = server_utils.get_filenames_in_dir_from_cyverse(irods_input_dir_path)
file_paths = [os.path.join(irods_input_dir_path, x) for x in files_in_dir]
os.chdir(input_dir)
server_utils.download_files_from_cyverse(files=file_paths, experiment=args.experiment)
# Step (2)
server_utils.untar_files(files_in_dir)
os.chdir('../')
return
# --------------------------------------------------
def find_matching_file_in_irods_dir(yaml_dictionary, date, args, irods_dl_dir):
"""
Get IRODS path to download
Input:
- yaml_dictionary: Dictionary generated from the YAML file
Output:
- irods_path: CyVerse filepath
"""
args = get_args()
experiment = args.experiment
cyverse_datalevel = yaml_dictionary['paths']['cyverse']['input']['level']
prefix = yaml_dictionary['paths']['cyverse']['input']['prefix']
suffix = yaml_dictionary['paths']['cyverse']['input']['suffix']
all_files_in_dir = server_utils.get_filenames_in_dir_from_cyverse(irods_dl_dir)
print(all_files_in_dir)
# Now lets see if our file is in all_files_in_dir
if args.experiment:
date_sub = match = re.search(r'\d{4}-\d{2}-\d{2}', date)
date_sub = str(datetime.strptime(date_sub.group(), '%Y-%m-%d').date())
pattern = (prefix if prefix else "") + date_sub + (suffix if suffix else "")
else:
pattern = (prefix if prefix else "") + date + (suffix if suffix else "")
import pathlib
matching_files = [x for x in all_files_in_dir if pathlib.PurePath(x).match(pattern)]
if len(matching_files) < 1:
print (f"WARNING Could not find appropriate tarball for date: {date}\n \
Found: {matching_files}")
return None
if len(matching_files) > 1:
if args.experiment:
matching_files = [item for item in matching_files if date in item]
else:
return None
# if args.multi_date != 99:
# file_dl_path = os.path.join(irods_dl_dir,matching_files[args.multi_date])
# print(f"multi date used, get_irods_input_path() found a file: {file_dl_path}")
# return file_dl_path
# return None
file_dl_path = os.path.join(
irods_dl_dir,
matching_files[0]
)
print(f"get_irods_input_path() found a file: {file_dl_path}")
return file_dl_path
# --------------------------------------------------
def download_irods_input_file(irods_path):
"""Download raw dataset from CyVerse DataStore
Input:
- irods_path: CyVerse path to the raw data
Does:
- Downloads tarball if it isn't found locally.
- Extracts files from the tarball.
Returns:
- dir_name: name of directory created from tarball.
"""
args = get_args()
tarball_filename = os.path.basename(irods_path)
if not os.path.isfile(tarball_filename):
# We need to DL the tarball.
cmd1 = f'iget -fKPVT {irods_path}'
if args.hpc:
print('>>>>>>Using data transfer node.')
cwd = os.getcwd()
sp.call(f"ssh filexfer 'cd {cwd}' '&& {cmd1}' '&& exit'", shell=True)
else:
sp.call(cmd1, shell=True)
time.sleep(30)
#tarball = tarfile.open(tarball_filename, mode='r')
#print(f"Examining {tarball_filename}, this can take a minute.")
#dir_name = os.path.commonprefix(tarball.getnames())
# We want to find the root directory of the tar ball. It's very large and
# compressed, So using something like os.path.commonprefix(tarball.getnames())
# will take forever. So we do this instead...
import shlex
print(f"Examining {tarball_filename}, this can take a second...")
gzip_extensions = ['.tgz', '.tar.gz']
if any(x in tarball_filename for x in gzip_extensions):
# if gzip_extension in tarball_filename:
command = f"tar -ztf {tarball_filename}"
else:
command = f"tar -tf {tarball_filename}"
with sp.Popen(shlex.split(command),
stdout=sp.PIPE,
bufsize=1,
universal_newlines=True) as process:
first_line = next(process.stdout)
process.kill
if not first_line.strip().endswith('/'):
raise ValueError(f"ERROR. We can't figure out the root dir of {tarball_filename}")
dir_name = first_line.strip()[:-1]
#print(f"... found: {dir_name}")
if not os.path.isdir(dir_name):
# cmd1 = f'iget -fKPVT {irods_path}'
#cmd1 = f'iget -fPVT {irods_path}'
if any(x in tarball_filename for x in gzip_extensions):
cmd2 = f'tar -xzvf {tarball_filename}'
cmd3 = f'rm {tarball_filename}'
else:
cmd2 = f'tar -xvf {tarball_filename}'
cmd3 = f'rm {tarball_filename}'
if args.hpc:
# print('>>>>>>Using data transfer node.')
cwd = os.getcwd()
# sp.call(f"ssh filexfer 'cd {cwd}' '&& {cmd2}' '&& {cmd3}' '&& exit'", shell=True)
sp.call(f"cd {cwd} && {cmd2} && {cmd3}", shell=True)
else:
sp.call(cmd2, shell=True)
sp.call(cmd3, shell=True)
return dir_name
def get_file_list(directory, level, match_string='.ply'):
'''
Walks through a given directory and grabs all files with the given search string.
Input:
- directory: Local directory to search
- match_string: Substring to search and add only elements with items containing
this string being added to the file list.
Output:
- subdir_list: List containing all subdirectories within the raw data.
- files_list: List containing all files within each subdirectory within the raw data.
'''
files_list = []
subdir_list = []
for root, dirs, files in os.walk(directory, topdown=False):
for name in files:
if match_string in name:
files_list.append(os.path.join(root, name))
for name in dirs:
subdir_list.append(os.path.join(root, name))
if level=='subdir':
if 'west' in directory:
directory = directory.replace('west', 'east')
elif 'east' in directory:
directory = directory.replace('east', 'west')
for root, dirs, files in os.walk(directory, topdown=False):
for name in files:
if match_string in name:
files_list.append(os.path.join(root, name))
plant_names = [os.path.basename(os.path.dirname(dir_path)) for dir_path in files_list]
plant_names = list(set(plant_names))
plant_names = [os.path.join(directory, plant_name, 'null.ply') for plant_name in plant_names]
files_list = plant_names
if level == 'whole_subdir':
files_list = []
for root, dirs, files in os.walk(directory, topdown=False):
for d in dirs:
files_list.append(d)
if level == 'dir':
files_list = [directory]
return files_list
if len(files_list) == 0:
print('---------------------------no files found---------------------------------------')
return files_list
# --------------------------------------------------
def write_file_list(input_list, out_path='file.txt'):
'''
Write either files/subdir list to file.
Input:
- input_list: List containing files
- out_path: Filename of the output
Output:
- TXT file.
'''
textfile = open(out_path, "w")
for element in input_list:
textfile.write(element + "\n")
textfile.close()
# --------------------------------------------------
def get_support_files(yaml_dictionary, date):
'''
Input:
- yaml_dictionary: Dictionary variable (YAML file)
- date: Scan date being processed
Output:
- Downloaded files/directories in the current working directory
'''
#season_name = yaml_dictionary['tags']['season_name']
season_name = get_season_name()
cyverse_basename = yaml_dictionary['paths']['cyverse']['basename']
irods_basename = os.path.join(
cyverse_basename,
season_name
)
support_files = yaml_dictionary['paths']['cyverse']['input']['necessary_files']
for file_path in support_files:
print(f"Looking for {file_path}...")
filename = os.path.basename(file_path)
#pdb.set_trace()
if not os.path.isfile(filename):
cyverse_path = os.path.join(irods_basename, file_path)
print(f" We need to get: {cyverse_path}")
server_utils.download_file_from_cyverse(os.path.join(irods_basename, file_path))
else:
print(f"FOUND")
server_utils.untar_files([filename])
sensor = yaml_dictionary["tags"]["sensor"]
if (sensor == "stereoTop") or (sensor == 'flirIrCamera'):
if not os.path.isdir('Lettuce_Image_Stitching'):
sp.call("git clone https://github.com/ariyanzri/Lettuce_Image_Stitching.git", shell=True)
# --------------------------------------------------
def get_season_name():
season_name = yaml_dictionary['tags']['season_name']
if not season_name:
raise ValueError(
f"ERROR. You need to specify yaml_dictionary['tags']['season_name'] in your yaml file. For example: \n" + \
"season_name: season_11_sorghum_yr_2020"
)
return season_name
# --------------------------------------------------
def get_model_files(yaml_dictionary):
"""Download model weights from CyVerse DataStore
Input:
- seg_model_path: CyVerse path to the segmentation model (.pth file)
- det_model_path: CyVerse path to the object detection model (.pth file)
- lid_model_path: CyVerse path to the object detection model specific to lid detection (.pth file)
Output:
- Downloaded model weight files OR nothing if paths are not specified in the YAML file.
- Variables of segmentation, plant detection, and lid detection paths OR np.nan values if not specified in the YAML file.
"""
if 'paths' in yaml_dictionary and 'models' in yaml_dictionary['paths']:
models = yaml_dictionary['paths']['models']
if 'segmentation' in models.keys():
seg_model_path = models['segmentation']
if not os.path.isfile(os.path.basename(seg_model_path)):
cmd1 = f'iget -fKPVT {seg_model_path}'
sp.call(cmd1, shell=True)
else:
seg_model_path = ''
if 'detection' in models.keys():
det_model_path = models['detection']
if not os.path.isfile(os.path.basename(det_model_path)):
cmd1 = f'iget -fKPVT {det_model_path}'
sp.call(cmd1, shell=True)
else:
det_model_path = ''
if 'lid' in models.keys():
lid_model_path = models['lid']
if not os.path.isfile(os.path.basename(lid_model_path)):
cmd1 = f'iget -fKPVT {lid_model_path}'
sp.call(cmd1, shell=True)
else:
lid_model_path = ''
else:
seg_model_path, det_model_path, lid_model_path = '', '', ''
return os.path.basename(seg_model_path), os.path.basename(det_model_path) #, os.path.basename(lid_model_path)
# --------------------------------------------------
def launch_workers(cctools_path, account, job_name, nodes, time, mem_per_core, manager_name, number_worker_array, cores_per_worker, worker_timeout, cwd, outfile='worker.sh', worker_type='work_queue_worker'):
'''
Launches workers on a SLURM workload management system.
Input:
- account: Account to charge compute resources
- partition: Either standard or windfall hours
- job_name: Name for the job
- nodes: Number of nodes to use per Workqueue factory
- time: Time alloted for job to run
- manager_name: Name of workflow manager
- min_worker: Minimum number of workers per Workqueue factory
- max_worker: Maximum number of workers per Workqueue factory
- cores_per_worker: Number of cores per worker
- worker_timeout: Time to wait for worker to receive a task before timing out (units in seconds)
- outfile: Output filename for SLURM submission script
Output:
- Running workers on an HPC system
'''
time_seconds = int(time)*60
if 'worker_type' in yaml_dictionary['workload_manager'].keys():
worker_type=yaml_dictionary['workload_manager']['worker_type']
with open(outfile, 'w') as fh:
fh.writelines("#!/bin/bash\n")
fh.writelines(f"#SBATCH --account={account}\n")
fh.writelines(f"#SBATCH --job-name={job_name}\n")
fh.writelines(f"#SBATCH --nodes={nodes}\n")
fh.writelines(f"#SBATCH --mem-per-cpu={mem_per_core}gb\n")
fh.writelines(f"#SBATCH --time={time}\n")
fh.writelines(f"#SBATCH --array 1-{number_worker_array}\n")
if yaml_dictionary['workload_manager']['standard_settings']['use']==True:
fh.writelines(f"#SBATCH --partition={yaml_dictionary['workload_manager']['standard_settings']['partition']}\n")
elif yaml_dictionary['workload_manager']['high_priority_settings']['use']==True:
fh.writelines(f"#SBATCH --qos={yaml_dictionary['workload_manager']['high_priority_settings']['qos_group']}\n")
fh.writelines(f"#SBATCH --partition={yaml_dictionary['workload_manager']['high_priority_settings']['partition']}\n")
if worker_type == 'work_queue_worker':
fh.writelines(f"#SBATCH --ntasks={int(cores_per_worker)}\n")
fh.writelines("export CCTOOLS_HOME=${HOME}/"+f"{cctools_path}\n")
fh.writelines("export PATH=${CCTOOLS_HOME}/bin:$PATH\n")
fh.writelines(f"{worker_type} -M {manager_name} --cores {cores_per_worker} -t {worker_timeout} --memory {mem_per_core*cores_per_worker*1000}\n")
elif worker_type == 'work_queue_factory':
if 'max_workers' in yaml_dictionary['workload_manager'].keys():
fh.writelines(f"#SBATCH --ntasks={int(yaml_dictionary['workload_manager']['max_workers'])}\n")
fh.writelines("export CCTOOLS_HOME=${HOME}/"+f"{cctools_path}\n")
fh.writelines("export PATH=${CCTOOLS_HOME}/bin:$PATH\n")
fh.writelines(f"{worker_type} -T local -M {manager_name} --max-workers {yaml_dictionary['workload_manager']['max_workers']} --cores {cores_per_worker} -t {worker_timeout} --memory {mem_per_core*cores_per_worker*1000}\n")
else:
fh.writelines(f"#SBATCH --ntasks={cores_per_worker}\n")
fh.writelines("export CCTOOLS_HOME=${HOME}/"+f"{cctools_path}\n")
fh.writelines("export PATH=${CCTOOLS_HOME}/bin:$PATH\n")
fh.writelines(f"{worker_type} -T local -M {manager_name} --max-workers {cores_per_worker} --cores 1 -t {worker_timeout} --memory {mem_per_core*cores_per_worker*1000}\n")
if 'total_submission' in yaml_dictionary['workload_manager'].keys():
num = yaml_dictionary['workload_manager']['total_submission']
for i in range(0, num):
return_code = sp.call(f"sbatch {outfile}", shell=True)
else:
return_code = sp.call(f"sbatch {outfile}", shell=True)
if return_code == 1:
raise Exception(f"sbatch Failed")
# --------------------------------------------------
def kill_workers(job_name):
'''
Kills workers once workflow has terminated.
Input:
- job_name: Name of the job
Output:
- Kills workers on an HPC system
'''
os.system(f"scancel --name {job_name}")
# os.system(f"ocelote && scancel --name {job_name} && puma")
# os.system(f"elgato && scancel --name {job_name} && puma")
# --------------------------------------------------
def generate_makeflow_json(cctools_path, level, files_list, command, container, inputs, outputs, date, sensor, yaml_dictionary, n_rules=1, json_out_path='wf_file.json'):
'''
Generate Makeflow JSON file to distribute tasks.
Input:
- files_list: Either files or subdirectory list
- n_rules: Number of rules per JSON file
- json_out_path: Path to the resulting JSON file
Output:
- json_out_path: Path to the resulting JSON file
'''
args = get_args()
files_list = [file.replace('-west.ply', '').replace('-east.ply', '').replace('-merged.ply', '').replace('__Top-heading-west_0.ply', '') for file in files_list]
timeout = f'timeout -s SIGKILL {args.timeout}h '
cwd = os.getcwd()
command = command.replace('${CWD}', cwd)
date_time = date
if sensor=='scanner3DTop':
match_str = re.search(r'\d{4}-\d{2}-\d{2}', date)
date = str(datetime.strptime(match_str.group(), '%Y-%m-%d').date())
if inputs:
if sensor=='scanner3DTop':
if level == 'subdir':
# if args.hpc:
# kill_workers(dictionary['workload_manager']['job_name'])
# launch_workers(cctools_path=cctools_path,
# account=dictionary['workload_manager']['account'],
# # partition=dictionary['workload_manager']['partition'],
# job_name=dictionary['workload_manager']['job_name'],
# nodes=dictionary['workload_manager']['nodes'],
# #number_tasks=dictionary['workload_manager']['number_tasks'],
# #number_tasks_per_node=dictionary['workload_manager']['number_tasks_per_node'],
# time=dictionary['workload_manager']['time_minutes'],
# mem_per_core=dictionary['workload_manager']['mem_per_core'],
# manager_name=dictionary['workload_manager']['manager_name'],
# number_worker_array=dictionary['workload_manager']['number_worker_array'],
# cores_per_worker=dictionary['workload_manager']['cores_per_worker'],
# worker_timeout=dictionary['workload_manager']['worker_timeout_seconds'],
# cwd=cwd)
# # qos_group=dictionary['workload_manager']['qos_group'])
subdir_list = []
for item in files_list:
subdir = os.path.basename(os.path.dirname(item))
subdir_list.append(subdir)
subdir_list = list(set(subdir_list))
write_file_list(subdir_list)
jx_dict = {
"rules": [
{
"command" : timeout + command.replace('${FILE}', file).replace('${SEG_MODEL_PATH}', seg_model_name).replace('${DET_MODEL_PATH}', det_model_name).replace('${PLANT_NAME}', file).replace('${DATE_TIME}', date_time),
"outputs" : [out.replace('$PLANT_NAME', file) for out in outputs],
"inputs" : [input.replace('$PLANT_NAME', file) for input in inputs if os.path.isdir(input.replace('$PLANT_NAME', file))]
# [container,
# seg_model_name,
# det_model_name] +
} for file in subdir_list
]
}
# This the one for 3D
else:
jx_dict = {
"rules": [
{
"command" : timeout + command.replace('${FILE}', file).replace('${PLANT_PATH}', os.path.dirname(file)).replace('${SEG_MODEL_PATH}', seg_model_name).replace('${PLANT_NAME}', os.path.basename(os.path.dirname(file))).replace('${DET_MODEL_PATH}', det_model_name).replace('${SUBDIR}', os.path.basename(os.path.dirname(file))).replace('${DATE}', date)\
.replace('${INPUT_DIR}', os.path.dirname(file)).replace('${DATE_TIME}', date_time),
"outputs" : [out.replace('$UUID', '_'.join(os.path.basename(file).split('_')[:2])).replace('$PLANT_NAME', os.path.basename(os.path.dirname(file))).replace('$SUBDIR', os.path.join(os.path.basename(os.path.dirname(file)), os.path.basename(file))).replace('${DATE}', date).replace('$BASENAME', os.path.basename(os.path.dirname(file))) for out in outputs],
"inputs" : [input.replace('$PLANT_NAME', os.path.basename(os.path.dirname(file))).replace('$SUBDIR', os.path.join(os.path.basename(os.path.dirname(file)), os.path.basename(file))).replace('${DATE}', date)\
.replace('$FILE', file).replace('$BASENAME', os.path.basename(os.path.dirname(file))) for input in inputs]
# [container,
# seg_model_name,
# det_model_name] +
} for file in files_list
]
}
if sensor == 'ps2Top':
files_list = [item for item in files_list if not 'rawData0101' in item]
jx_dict = {
"rules": [
{
"command" : timeout + command\
.replace('${FILE}', file)\
.replace('${M_DATA_FILE}', file.replace(file[-15:], 'metadata.json'))\
.replace('${FILE_DIR}', os.path.dirname(file))\
.replace('${UUID}', os.path.basename(file).replace('.tif', ''))\
.replace('${DATE}', date)\
.replace('${DATE_TIME}', date_time),
"outputs" : [out\
.replace('$FILE_BASE', os.path.basename(file).replace('.bin', ''))\
.replace('$SEG', os.path.basename(file).replace('.tif', '_segmentation.csv'))\
.replace('$UUID', os.path.basename(file).replace('.tif', ''))\
.replace('$FILE', file)\
.replace('$DATE', date)\
for out in outputs],
"inputs" : [container] + [input\
.replace('$FILE', file)\
.replace('$UUID', os.path.basename(file).replace('.tif', ''))\
.replace('$M_DATA_FILE', file.replace(file[-15:], 'metadata.json'))\
.replace('$FILE_DIR', os.path.dirname(file))\
for input in inputs]
} for file in files_list
]
}
elif (sensor == 'stereoTop') or (sensor == 'flirIrCamera'):
jx_dict = {
'rules': [
{
"command": timeout + command.replace('${FILE}', file).replace('${UUID}', os.path.join(os.path.dirname(file), os.path.basename(file).split("_")[0])).replace('${DATE}', date).replace('${FLIR_META}', file.replace('ir.bin', 'metadata.json')).replace('${DATE_TIME}', date_time),
"outputs": [out.replace('$FILE_BASE', os.path.basename(file).split('.')[0]).replace('$DATE', date).replace('$FLIR_TIF', file.replace('.bin', '.tif')) for out in outputs],
"inputs": [container, seg_model_name, det_model_name] + [input.replace('$FILE', file).replace('$UUID', os.path.join(os.path.dirname(file), os.path.basename(file).split("_")[0])).replace('$FLIR_META', file.replace('ir.bin', 'metadata.json')) for input in inputs]
} for file in files_list
]
}
else:
jx_dict = {
"rules": [
{
"command" : timeout + command.replace('${FILE}', file).replace('${PLANT_PATH}', os.path.dirname(file)).replace('${SEG_MODEL_PATH}', seg_model_name).replace('${PLANT_NAME}', os.path.basename(os.path.dirname(file))).replace('${DET_MODEL_PATH}', det_model_name).replace('${SUBDIR}', os.path.basename(os.path.dirname(file))).replace('${DATE}', date).replace('${INPUT_DIR}', os.path.dirname(file)).replace('${DATE_TIME}', date_time),
"outputs" : [out.replace('$FILEBASE', os.path.splitext(os.path.basename(file))[0]).replace('$UUID', '_'.join(os.path.basename(file).split('_')[:2])).replace('$PLANT_NAME', os.path.basename(os.path.dirname(file))).replace('$SUBDIR', os.path.join(os.path.basename(os.path.dirname(file)), os.path.basename(file))).replace('${DATE}', date).replace('$BASENAME', os.path.basename(os.path.dirname(file))) for out in outputs],
"inputs" : [input.replace('$PLANT_NAME', os.path.basename(os.path.dirname(file))).replace('$SUBDIR', os.path.join(os.path.basename(os.path.dirname(file)), os.path.basename(file))).replace('${DATE}', date).replace('$FILE', file).replace('$BASENAME', os.path.basename(os.path.dirname(file))) for input in inputs]
# [file,
# container,
# seg_model_name,
# det_model_name] +
} for file in files_list
]
}
else:
print('No inputs specified. Assuming local.')
jx_dict = {
"rules": [
{
"command" : timeout + command.replace('${FILE}', file).replace('${PLANT_PATH}', os.path.dirname(file)).replace('${SEG_MODEL_PATH}', seg_model_name).replace('${PLANT_NAME}', os.path.basename(os.path.dirname(file))).replace('${DET_MODEL_PATH}', det_model_name).replace('${SUBDIR}', os.path.basename(os.path.dirname(file))).replace('${DATE}', date).replace('${INPUT_DIR}', os.path.dirname(file)).replace('${DATE_TIME}', date_time),
"outputs" : [out.replace('$PLANT_NAME', os.path.basename(os.path.dirname(file))).replace('$SUBDIR', os.path.join(os.path.basename(os.path.dirname(file)), os.path.basename(file))).replace('${DATE}', date).replace('$BASENAME', os.path.basename(os.path.dirname(file))) for out in outputs],
"inputs" : [seg_model_name,
det_model_name]
#[file,
#container,
#seg_model_name,
#det_model_name]
} for file in files_list
]
}
### Nathan was here...
# Sorry this on got away from me
# Heres the general idea of what's in the substitutions dictionary...
#
# 'STRING THAT IS REPLACED' : [ evaluated variable name, function to manipulate it ]
#
# Then we loop through each jx_dict -> "rules" (i.e. command, outputs, inputs) and replace stuff.
substitutions = {
'{{$FILE_BASE}}' : ['_f', lambda x: os.path.splitext(os.path.basename(x))[0]],
# _f is the file from files_list
}
def do_replacement(substitutions, original_string):
for match_string, _v in substitutions.items():
eval_var = eval(_v[0])
lfunction = _v[1]
replacement_string = lfunction(eval_var)
return original_string.replace(match_string, replacement_string)
_d = jx_dict['rules']
for idx, _f in enumerate(files_list):
for rule_section, entry in _d[idx].items():
# [rule_section] can be a string or a list, so we have to deal with that...
if type(entry) is list:
for _eidx, e in enumerate(entry):
#_d[idx][rule_section][_eidx] = do_replacement(substitutions, e)
for match_string, _v in substitutions.items():
eval_var = eval(_v[0])
lfunction = _v[1]
replacement_string = lfunction(eval_var)
_d[idx][rule_section][_eidx] = e.replace(match_string, replacement_string)
else:
#_d[idx][rule_section] = do_replacement(substitutions, entry)
for match_string, _v in substitutions.items():
eval_var = eval(_v[0])
lfunction = _v[1]
replacement_string = lfunction(eval_var)
_d[idx][rule_section] = entry.replace(match_string, replacement_string)
### ...end Nathan was here.
with open(json_out_path, 'w') as convert_file:
convert_file.write(json.dumps(jx_dict))
#print("BREAK: At end of generate_makeflow_json()")
#pdb.set_trace()
return json_out_path
# --------------------------------------------------
def run_jx2json(json_out_path, cctools_path, batch_type, manager_name, cwd, retries=3, port=0, out_log='dall.log'):
'''
Create a JSON file for Makeflow distributed computing framework.
Input:
- json_out_path: Path to the JSON file containing inputs
- cctools_path: Path to local installation of CCTools
Output:
- Running workflow
'''
args = get_args()
if args.module_breakpoints:
pdb.set_trace()
cores_max = int(multiprocessing.cpu_count()*args.local_cores)
home = os.path.expanduser('~')
cctools = os.path.join(home, cctools_path, 'bin', 'makeflow')
cctools = os.path.join(home, cctools)
arguments = f'-T {batch_type} --json {json_out_path} -a -N {manager_name} -M {manager_name} --local-cores {cores_max} -r {retries} -p {port} -dall -o {out_log} --skip-file-check' #--disable-cache $@'
if args.shared_file_system:
arguments = f'-T {batch_type} --json {json_out_path} -a --shared-fs {cwd} -X {cwd} -N {manager_name} -M {manager_name} --local-cores {cores_max} -r {retries} -p {port} -dall -o {out_log} --skip-file-check' #--disable-cache $@'
cmd1 = ' '.join([cctools, arguments])
sp.call(cmd1, shell=True)
# --------------------------------------------------
def tar_outputs(scan_date, yaml_dictionary):
'''
Bundles outputs for upload to the CyVerse DataStore.
Input:
- scan_date: Date of the scan
- yaml_dictionary: Dictionary variable (YAML file)
Output:
- Tar files containing all output data
'''
cwd = os.getcwd()
for item in yaml_dictionary['paths']['pipeline_outpath']:
if os.path.isdir(item):
os.chdir(item)
outdir = item
if not os.path.isdir(os.path.join(cwd, scan_date, outdir)):
os.makedirs(os.path.join(cwd, scan_date, outdir))
for v in yaml_dictionary['paths']['outpath_subdirs']:
_full_v = os.path.join(cwd, outdir, v)