-
Notifications
You must be signed in to change notification settings - Fork 50
/
recalibrate.py
273 lines (212 loc) · 8.1 KB
/
recalibrate.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
"""
Recalibrate JWST exposures with `snowblind` with the procedure as described there
"""
import os
import inspect
import warnings
import numpy as np
if os.path.exists('/GrizliImaging'):
HOME = '/GrizliImaging'
else:
HOME = os.getcwd()
def test():
from grizli import prep
file = 'jw01727039001_02101_00003_nrca2_rate.fits'
file = 'jw02079004002_09201_00001_nrca2_rate.fits'
file = 'jw01283004001_02201_00009_nrca1_rate.fits'
do_recalibrate(rate_file='../RAW/' + file,
cores='all',
min_radius=3,
after_jumps=20,
context='jwst_1180.pmap',
)
prep.fresh_flt_file(file,
oneoverf_kwargs={'deg_pix':2048, 'dilate_iterations':3,
'thresholds':[5,4,3],
'other_axis':True})
def get_random_reprocess_file():
"""
Get a table row of a file to be processed
Returns
-------
res : None, table row
Returns a single row from `reprocess_rates` with ``status == 0``, or None if
nothing found
"""
from grizli.aws import db
rows = db.SQL(f"""SELECT *
FROM reprocess_rates
WHERE status = 0 order by random() limit 1
""")
if len(rows) == 0:
return None
else:
return rows
def run_one(verbose=True, remove_result=True):
"""
Run a single random file from `reprocess_rates` with ``status == 0``
"""
import os
import time
import boto3
from grizli.aws import db
from grizli import utils
row = get_random_reprocess_file()
if row is None:
with open(os.path.join(HOME, 'reprocess_finished.txt'),'w') as fp:
fp.write(time.ctime() + '\n')
return None
print(f'============ Reprocess exposure ==============')
print(f"{row['rate_file'][0]}")
print(f'========= {time.ctime()} ==========')
with open(os.path.join(HOME, 'reprocess_history.txt'),'a') as fp:
fp.write(f"{time.ctime()} {row['rate_file'][0]}\n")
# Update db
db.execute(f"""update reprocess_rates
set status = 1, ctime={time.time()}
where
rate_file = '{row['rate_file'][0]}'
AND prefix = '{row['prefix'][0]}'
AND bucket = '{row['bucket'][0]}';
""")
#################
# Run it
#################
try:
status = do_recalibrate(**row[0])
except:
row['status'] = 5
# Update db
db.execute(f"""update reprocess_rates
set status = 3, ctime={time.time()}
where
rate_file = '{row['rate_file'][0]}'
AND prefix = '{row['prefix'][0]}'
AND bucket = '{row['bucket'][0]}';
""")
return row
###############
# Copy output
###############
if status & os.path.exists(row['rate_file'][0]):
s3 = boto3.resource('s3')
bkt = s3.Bucket(row['bucket'][0])
local_file = row['rate_file'][0]
s3_prefix = os.path.join(row['prefix'][0], row['rate_file'][0])
msg = f"Send {local_file} > s3://{row['bucket'][0]}/{s3_prefix}"
utils.log_comment(utils.LOGFILE, msg, verbose=verbose)
bkt.upload_file(local_file, s3_prefix, ExtraArgs={'ACL': row['acl'][0]},
Callback=None, Config=None)
row['status'] = 2
row['ctime'] = time.time()
# Update db
db.execute(f"""update reprocess_rates
set status = 2, ctime={time.time()}
where
rate_file = '{row['rate_file'][0]}'
AND prefix = '{row['prefix'][0]}'
AND bucket = '{row['bucket'][0]}';
""")
# Remove result
if remove_result:
msg = f"rm {row['rate_file'][0]}"
utils.log_comment(utils.LOGFILE, msg, verbose=verbose)
os.remove(row['rate_file'][0])
else:
###############
# Problem
###############
row['status'] = 3
# Update db
db.execute(f"""update reprocess_rates
set status = 3, ctime={time.time()}
where
rate_file = '{row['rate_file'][0]}'
AND prefix = '{row['prefix'][0]}'
AND bucket = '{row['bucket'][0]}';
""")
return row
def do_recalibrate(rate_file='jw06541001001_03101_00001_nrs1_rate.fits', cores='half', min_radius=3, after_jumps=20, context=None, clean=True, **kwargs):
"""
Recalibrate JWST uncal exposures with `snowblind` snowball masking
Parameters
----------
rate_file : str
Filename of the output countrate exposure, must end in ``rate.fits``.
The uncalibrated file will be fetched from MAST with
``rate_file.replace('_rate.fits', '_uncal.fits')``
cores : str
Number of cores to use for the JWST pipeline steps, e.g., ``1``, ``quarter``,
``half``, ``all``
min_radius, after_jumps : int, int
`snowblind` parameters
context : str
Optional explicit CRDS context to use
clean : bool
Remove intermediate files
Returns
-------
status : bool
True if completed successfully. False if ``rate_file`` doesn't have the
expected ``rate.fits`` suffix. The ``rate_file`` product will be left in the
working directory.
"""
from snowblind import SnowblindStep
from jwst.pipeline import Detector1Pipeline
from jwst.step import RampFitStep
from jwst.step import GainScaleStep
import mastquery.utils
try:
from .. import jwst_utils
from .. import utils
except ImportError:
from grizli import jwst_utils
from grizli import utils
frame = inspect.currentframe()
_LOGFILE = utils.LOGFILE
warnings.filterwarnings('ignore', category=RuntimeWarning)
utils.LOGFILE = rate_file.split('.fits')[0] + '.log'
utils.log_function_arguments(utils.LOGFILE, frame, 'do_recalibrate',
ignore=['_LOGFILE'])
if not rate_file.endswith('_rate.fits'):
print(f'{rate_file} does not end with _rate.fits')
return False
if context is not None:
jwst_utils.CRDS_CONTEXT = context
jwst_utils.set_crds_context(verbose=False, override_environ=True)
output_path, base_file = os.path.split(rate_file)
mastquery.utils.download_from_mast([base_file.replace('_rate.fits','_uncal.fits')])
steps = {
"jump": {
"save_results": True,
"maximum_cores": cores
},
"ramp_fit": {
"skip": True,
},
"gain_scale": {
"skip": True,
},
}
Detector1Pipeline.call(base_file.replace('_rate','_uncal'), steps=steps)
SnowblindStep.call(base_file.replace('_rate','_jump'),
min_radius=int(min_radius),
after_jumps=int(after_jumps),
save_results=True,
suffix="snowblind")
rate, rateints = RampFitStep.call(base_file.replace('_rate','_snowblind'),
maximum_cores=cores)
rate = GainScaleStep.call(rate)
# Mask out nans and remove DQ=4
bad = ~np.isfinite(rate.data)
rate.dq[bad] |= 1
rate.data[bad] = 0
rate.dq -= (rate.dq & 4)
rate.save(rate_file)
if clean:
for ext in ['_jump', '_snowblind', '_uncal', '_trapsfilled']:
if os.path.exists(base_file.replace('_rate', ext)):
print(f"Remove {base_file.replace('_rate', ext)}")
os.remove(base_file.replace('_rate', ext))
utils.LOGFILE = _LOGFILE
return True