-
Notifications
You must be signed in to change notification settings - Fork 0
/
Firecrown_wrapper_example-2.py
368 lines (340 loc) · 12 KB
/
Firecrown_wrapper_example-2.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
"""
python Firecrown_wrapper_example-2.py /global/homes/a/ayanmitr/Analysis/7_CREATE_COV/LSST_BINNED_COV_BBC_SIMDATA_PHOTOZ_1/output hubble_diagram.txt covsys_000.txt.gz sn_only.ini -O $HOME/trash -p "omega_m = 0.3"
$SNANA_DEBUG/submit_batch_firecrown/NEW_AYAN_DEBUG-3/dist/Firecrown_wrapper_example-2 /global/homes/a/ayanmitr/Analysis/7_CREATE_COV/LSST_BINNED_COV_BBC_SIMDATA_PHOTOZ_1/output hubble_diagram.txt covsys_000.txt.gz sn_only.ini
"""
import pandas as pd
import numpy as np
import os
import sys
import yaml
import signal
import subprocess
from subprocess import Popen
import datetime
import logging
import warnings
import time
import argparse
import pathlib
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter, RawTextHelpFormatter
from contextlib import contextmanager
import textwrap
logging.basicConfig(level=logging.INFO)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
@contextmanager
# https://stackoverflow.com/questions/7152762/how-to-redirect-print-output-to-a-file
def redirected_stdout(outstream):
orig_stdout = sys.stdout
try:
sys.stdout = outstream
yield
finally:
sys.stdout = orig_stdout
# Setting up the 'yaml' file
class CustomHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
def _split_lines(self, text, width):
wrapper = textwrap.TextWrapper(width=width)
lines = []
for line in text.splitlines():
if len(line) > width:
lines.extend(wrapper.wrap(line))
else:
lines.append(line)
return lines
now = datetime.datetime.now()
dt_string = now.strftime("%d%m%Y_%H%M%S/")
ENV = os.environ["SNANA_DEBUG"]
OUTPUT_PATH = (
ENV
+ "/"
+ "submit_batch_firecrown/NEW_AYAN_DEBUG-3/FIRECROWN_OUTPUT/" # + dt_string
) # 1 This can be an user arg ***
usage = "Mandatory arguments required in fixed order"
# parser = argparse.ArgumentParser(formatter_class=CustomHelpFormatter, description=usage)
parser = argparse.ArgumentParser(description=usage)
parser.add_argument("path", help="Path for the HD and COV")
parser.add_argument("hd", help="HD ")
parser.add_argument("cov", help="COV ")
parser.add_argument("ini", help="*.ini file")
parser.add_argument(
"-O",
"--outdir",
type=pathlib.Path,
default=OUTPUT_PATH,
help="-O Output path (Default: %s)" % (OUTPUT_PATH),
)
parser.add_argument(
"-p",
"--param",
# action='store_true',
default="",
nargs="?",
help="-p Override cosmosis parameter values ",
)
parser.add_argument(
"-s",
"--summary",
type=pathlib.Path,
default=OUTPUT_PATH + "/SUMMARY.YAML",
help="-s SUMMARY.YAML output path (Default: %s)" % (OUTPUT_PATH),
)
"""
parser.add_argument(
"-i",
"--info",
type=pathlib.Path,
default=COSMOSIS_PATH + "INPUT.INFO",
help="-i INPUT.INFO output path (Default: %s)" % (OUTPUT_PATH),
)
"""
args = parser.parse_args()
SUBDIRER = "/ERROR_LOGS/"
SUBDIR3 = "/COSMOSIS-CHAINS/"
SUBDIR4 = "/PLOTS"
OUTPUT_PATH = os.path.expandvars(args.outdir)
SUMMARY_PATH = os.path.expandvars(args.summary)
# SUBMIT_PATH = os.path.expandvars(args.info)
ERROR_PATH = os.path.expandvars(OUTPUT_PATH + SUBDIRER)
COSMOSIS_PATH = os.path.expandvars(OUTPUT_PATH + SUBDIR3)
PLOT_PATH = os.path.expandvars(OUTPUT_PATH + SUBDIR4)
try:
os.makedirs(COSMOSIS_PATH)
except FileExistsError:
# directory already exists
pass
SUBMIT_PATH = COSMOSIS_PATH + "INPUT.INFO"
p = args.param
with open(r"%s" % (SUBMIT_PATH), "w", buffering=1) as OF:
with redirected_stdout(OF):
print(
"\n\nSTAGE 0 = ALL PATH AND FILES IN ARGUMENTS CHECK\nSTAGE 1 = 'generate_sn_data.py'\nSTAGE 2 = COSMOSIS\nSTAGE 3 = POST PROCESSING (PLOT)\n\n"
)
Key = [
"STAGE0",
"STAGE1",
"STAGE2",
"STAGE3",
"ABORT_IF_ZERO",
"Ndof",
"CPU_MINUTES",
"chi2",
"sigint",
"label",
"BLIND",
]
data = {}
# -------------------------------
# Function Defintions
# key set to non abort(0) case, guide for sbatch
def path_error(path):
if os.path.exists(path):
data[Key[4]] = 1
pass
else:
data[Key[0]] = "FAILED"
data[Key[4]] = 0
outputs = yaml.dump(data, file_yaml)
raise FileNotFoundError("{0} path does not exist!".format(path))
def file_error(file):
if os.path.isfile(file):
data[Key[4]] = 1
pass
else:
data[Key[0]] = "FAILED"
data[Key[4]] = 0
outputs = yaml.dump(data, file_yaml)
raise FileNotFoundError("{0} file does not exist!".format(file))
# ----------------------------
"""
Creating output folders
"""
if not os.path.exists(ERROR_PATH):
os.makedirs(ERROR_PATH, exist_ok=True)
if not os.path.exists(COSMOSIS_PATH):
os.makedirs(COSMOSIS_PATH, exist_ok=True)
if not os.path.exists(PLOT_PATH):
os.makedirs(PLOT_PATH, exist_ok=True)
"""
Checking Files exists
"""
with open(r"%s" % (SUMMARY_PATH), "w", buffering=1) as file_yaml:
with redirected_stdout(OF):
print("\n#Required Info")
print("CWR:", os.getcwd())
print("ARG_LIST:", sys.argv)
print("TIME_STAMP:", now.strftime("%d-%m-%Y %H:%M:%S"))
print("OUTPUT DIR:", OUTPUT_PATH, "\n")
PWD = os.getcwd()
# arg_error(len(sys.argv))
path = args.path
hd = args.hd
cov = args.cov
ini = os.path.split(args.ini)[1]
# ini_f= args.ini
path_error(path)
f1 = path + "/" + hd
file_error(f1)
f2 = path + "/" + cov
file_error(f2)
data[Key[0]] = "SUCCESS"
# ********************
# --------------------
sacc_path_rm = "rm " + PWD + "/" + "srd-y1-converted.sacc"
job0 = subprocess.Popen(sacc_path_rm, stdout=subprocess.PIPE, shell=True)
# Stage 1
# python $FIRECROWN_EXAMPLES_DIR/srd_sn/generate_sn_data.py ${path} ${HD} ${COV}
# This assumes that the output will be a `sacc' file which
# will be automatically read in by cosmosis input `ini' file.
startTime = time.time()
os.environ["PYTHONUNBUFFERED"] = "1"
Vector = path + " " + hd + " " + cov
with redirected_stdout(OF):
print("SACC Input Vector:", Vector)
with open(
"%sgenerate_sn_data_output_%s.log" % (ERROR_PATH, ini), "wb"
) as gen_file, open(
"%sgenerate_sn_data_output_ERROR_%s.err" % (ERROR_PATH, ini), "wb"
) as gen_file_e:
job1 = Popen(
"python "
+ "$FIRECROWN_EXAMPLES_DIR/srd_sn/generate_sn_data.py "
+ Vector,
shell=True,
text=True,
stdout=gen_file,
stderr=gen_file_e,
)
job1.wait()
file = open("%sgenerate_sn_data_output_%s.log" % (ERROR_PATH, ini), "a")
sys.stdout = file
with redirected_stdout(OF):
print(job1.stdout)
file_e = open("%sgenerate_sn_data_output_ERROR_%s.err" % (ERROR_PATH, ini), "a")
sys.stdout = file_e
with redirected_stdout(OF):
print(job1.stderr)
if job1.returncode != 0:
os.system('echo "STAGE 1 FAILED *** \nCheck generate_sn_data error logs"')
data[Key[1]] = "FAILED"
data[Key[4]] = 0
outputs = yaml.dump(data, file_yaml)
executionTime = np.array(round((time.time() - startTime), 2))
with open("%sTimer_STAGE_1.time" % (ERROR_PATH), "w") as f:
f.write("%s" % executionTime)
sys.exit("BYE")
else:
data[Key[1]] = "SUCCESS"
data[Key[4]] = 1
executionTime = np.array(round((time.time() - startTime), 2))
with open("%sTimer_STAGE_1.time" % (ERROR_PATH), "w") as f:
f.write("%s" % executionTime)
os.system('echo "STAGE 1 COMPLETE"')
## STAGE 2
## python $FIRECROWN_EXAMPLES_DIR/srd_sn/sn_srd.py ${INPUT}
## input_SN_sacc_file.sacc
sacc_path_cp = (
"cp " + PWD + "/" + "srd-y1-converted.sacc $FIRECROWN_EXAMPLES_DIR/srd_sn/"
)
job2 = subprocess.Popen(
sacc_path_cp,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
)
job2.wait()
# STAGE 3
# srun -n 16 --cpu-bind=cores -c 16 cosmosis sn_only.ini -p omega_m = 0.3
startTime = time.time()
jobname = "cosmosis"
arg = "-p "
arg2 = "output.filename="
Vector = (
" "
+ ini
+ " "
+ arg
+ arg2
+ COSMOSIS_PATH
+ os.path.splitext(ini)[0]
+ ".txt --mpi"
)
with redirected_stdout(OF):
print("Cosmosis Input Vector:", Vector)
with open("%sCOSMOSIS_output_%s.log" % (ERROR_PATH, ini), "wb") as file, open(
"%sCOSMOSIS_output_ERROR_%s.err" % (ERROR_PATH, ini), "wb"
) as file_e:
job3 = subprocess.Popen(
["cosmosis" + Vector],
shell=True,
text=True,
stdout=file,
stderr=file_e,
)
job3.wait()
if job3.returncode != 0:
os.system('echo "STAGE 2 FAILED *** \nCheck COSMOSIS error logs"')
data[Key[2]] = "FAILED"
data[Key[4]] = 0
outputs = yaml.dump(data, file_yaml)
executionTime = np.array(round((time.time() - startTime), 2))
with open("%sTimer_COSMOSIS.time" % (ERROR_PATH), "w") as f:
f.write("%s" % executionTime)
sys.exit("BYE")
else:
data[Key[2]] = "SUCCESS"
data[Key[4]] = 1
executionTime = np.array(round((time.time() - startTime), 2))
with open("%sTimer_COSMOSIS.time" % (ERROR_PATH), "w") as f:
f.write("%s" % executionTime)
os.system('echo "STAGE 2 COMPLETE"')
# STAGE 4
# cosmosis-postprocess ${ini} # -o OUTDIR
startTime = time.time()
jobname = "cosmosis-postprocess"
arg = " -o "
Vector = " " + COSMOSIS_PATH + ini.replace(".ini", ".txt") + arg + PLOT_PATH
with redirected_stdout(OF):
print("cosmosis-postprocess Input Vector:", Vector)
with open(
"%sPostProcess_output_%s.log" % (ERROR_PATH, ini), "wb"
) as file_post, open(
"%sPostProcess_output_ERROR_%s.err" % (ERROR_PATH, ini), "wb"
) as file_post_e:
job4 = subprocess.Popen(
jobname + Vector,
shell=True,
text=True,
stdout=file_post,
stderr=file_post_e,
)
job4.wait()
if job4.returncode != 0:
os.system('echo "STAGE 3 FAILED *** \nCheck PostProcess error logs"')
data[Key[3]] = "FAILED"
data[Key[4]] = 0
outputs = yaml.dump(data, file_yaml)
executionTime = np.array(round((time.time() - startTime), 2))
with open("%sTimer_PostProcess.time" % (ERROR_PATH), "w") as f:
f.write("%s" % executionTime)
sys.exit("BYE")
else:
data[Key[3]] = "SUCCESS"
data[Key[4]] = 1
# """
# "XXX"
data["Ndof"] = 99
data["CPU_MINUTES"] = 10
data["chi2"] = 22
data["sigint"] = 0.0
data["label"] = "none"
data["BLIND"] = 0
# "XXX"
# """
os.system('echo "STAGE 3 COMPLETE"')
os.system('echo "ALL DONE"')
outputs = yaml.dump(data, file_yaml)
executionTime = np.array(round((time.time() - startTime), 2))
with open("%sTimer_PostProcess.time" % (ERROR_PATH), "w") as f:
f.write("%s" % executionTime)
# print(outputs)