-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathharvest.py
executable file
·204 lines (167 loc) · 4.85 KB
/
harvest.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
#!/usr/bin/env python3
import subprocess
from subprocess import PIPE
import glob
import os
# from time import sleep
import argparse
# from functions import file_exists
from natsort import natsorted as ns
# from pprint import pprint
# ------------------------------------------------------------------------------
def get_args():
"""
Get command-line arguments
"""
descrp = 'Tool for FLUKA output fort files processing'
parser = argparse.ArgumentParser(
description=descrp,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'input',
metavar='example.inp',
help='FLUKA input file name (for result name)')
parser.add_argument(
'-fp',
'--fortpath',
help=f'Path to the directory with FLUKA fort files',
metavar='path_to_fort',
type=str,
default='autores')
try:
parser.add_argument(
'-bp',
'--binpath',
help=f'Path to the bin FLUKA directory with tools for processing',
metavar='path_to_bin',
type=str,
default=f'{os.environ["FLUKA"]}/bin')
except KeyError:
info = 'Please export path to FLUKA:'
info += '\n"export FLUKA=~/path_to_fluka" in .bashrc'
exit(info)
parser.add_argument(
'-trk',
'--usrtrack',
help='Units of output FLUKA fort files with usrtrack type scoring',
metavar='usrtrack',
type=int,
nargs='+',
default=None)
parser.add_argument(
'-yie',
'--usryield',
help='Units of output FLUKA fort files with usryield type scoring',
metavar='usryield',
type=int,
nargs='+',
default=None)
# TODO USRBDX and RESNUCLEi scorings
# TODO maybe refactor code
parser.add_argument(
'-dtc',
'--detect',
help='Process DETECT scoring files (*.17 fort files)',
action='store_true')
parser.add_argument(
'-bnn',
'--usrbin',
help='Units of output FLUKA fort files with usrbin type scoring',
metavar='usrbin',
type=int,
nargs='+',
default=None)
# TODO noprint version
# parser.add_argument(
# '-nh',
# '--nohup',
# help='No information while execution',
# action='store_true')
args = parser.parse_args()
# If no args except input file
if args.usrtrack is None and args.usryield is None and args.usrbin is None:
if not args.detect:
parser.error(f'Please provide at least one unit!')
args.input = args.input.split(".")[0] # Get rid of extension
# Check if directory with FLUKA bins exists, rise error if not
if not os.path.isdir(args.binpath):
parser.error(f'Directory "{args.binpath}" does not exist!')
else:
print(f'Directory {args.binpath} will be used for processing...')
for score in ['ustsuw', 'usysuw', 'usbsuw', 'detsuw']:
if not os.path.isfile(f'{args.binpath}/{score}'):
parser.error(
f'Tool "{score}" does not exist under {args.binpath}!')
# Check if directory with FLUKA fort files exists, rise error if not
if not os.path.isdir(args.fortpath):
parser.error(f'Directory "{args.fortpath}" does not exist!')
else:
print(
f'FLUKA fort files from {args.fortpath} directory will be used for processing...')
for arg in [args.usrtrack, args.usryield, args.usrbin]:
if arg is not None:
arg.sort() # sort units
for unit in arg:
if 20 < unit < 100:
if get_pathnames(f'{args.fortpath}/*.{unit}'):
pass
else:
parser.error(
f'Unit number {unit} is not in the specified folder!')
else:
parser.error(
f'Some of provided units are not correct! (20 < unit < 100)')
return args
def get_pathnames(path: str):
"""
Find all pathnames matching a specified pattern, return False if no matches
:param path: pattern
:return: list or False
"""
paths = ns(glob.glob(path), key=lambda y: y.lower())
if paths:
return paths
else:
return False
# TODO process fort files from FLUKA
def ProcessFLUKA(
inp: str,
binpath: str, fortpath: str, unit: int, score: str, noprint=True):
ext = {
'ustsuw': 'trk',
'usysuw': 'yie',
'usbsuw': 'bnn',
'detsuw': 'dtc'
}
paths = get_pathnames(f'{fortpath}/*.{unit}')
paths.append('') # need to press enter
paths.append(f'{inp}_{unit}.{ext[score]}') # need to provide out file name
cmd = f'{binpath}/{score}'
print(f'Data for unit {unit} is merging...')
result = subprocess.run(
[cmd], stderr=PIPE, stdout=PIPE, input="\n".join(paths).encode())
# print("stdout:", result.stdout)
if not result.stderr:
print(f'File {inp}_{unit}.{ext[score]} is created\n')
elif result.stderr:
print(result.stderr)
print('Something went wrong! Please check units and their scoring types!')
def main():
args = get_args() # receive args
print()
score = {
'ustsuw': args.usrtrack,
'usysuw': args.usryield,
'usbsuw': args.usrbin
}
for item in score.keys():
if score[item] is not None:
for unit in score[item]:
ProcessFLUKA(
args.input, args.binpath, args.fortpath, unit, item)
# Special treat for the DETECT scoring
if args.detect:
ProcessFLUKA(
args.input, args.binpath, args.fortpath, 17, 'detsuw')
if __name__ == '__main__':
main()