resolvit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
resolvit/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ from .resolvit import (
2
+ process_observation,
3
+ process_events_list,
4
+ __version__,
5
+ )
6
+
7
+ __all__ = [
8
+ "process_observation",
9
+ "process_events_list",
10
+ "__version__",
11
+ ]
resolvit/cli.py ADDED
@@ -0,0 +1,60 @@
1
+ import argparse
2
+
3
+ from .resolvit import (
4
+ process_observation,
5
+ DEFAULT_BIN_SIZE,
6
+ DEFAULT_TOTAL_EVENTS_FRACTION,
7
+ __version__,
8
+ )
9
+
10
+
11
+ def main():
12
+
13
+ parser = argparse.ArgumentParser(
14
+ prog="resolvit",
15
+ description=(
16
+ "Improve the PSF of UVIT Level2 event lists and "
17
+ "generate Resolvit data products."
18
+ ),
19
+ )
20
+
21
+ parser.add_argument(
22
+ "observation_dir",
23
+ help="Path to UVIT Level2 observation directory",
24
+ )
25
+
26
+ parser.add_argument(
27
+ "--version",
28
+ action="version",
29
+ version=f"%(prog)s {__version__}",
30
+ )
31
+
32
+ parser.add_argument(
33
+ "--bin-size",
34
+ type=float,
35
+ default=DEFAULT_BIN_SIZE,
36
+ metavar="SECONDS",
37
+ help=(f"Time bin size in seconds (default: {DEFAULT_BIN_SIZE})"),
38
+ )
39
+
40
+ parser.add_argument(
41
+ "--event-fraction",
42
+ type=float,
43
+ default=DEFAULT_TOTAL_EVENTS_FRACTION,
44
+ metavar="FRACTION",
45
+ help=(
46
+ f"Fraction of median events required for a bin (default: {DEFAULT_TOTAL_EVENTS_FRACTION})"
47
+ ),
48
+ )
49
+
50
+ args = parser.parse_args()
51
+
52
+ process_observation(
53
+ args.observation_dir,
54
+ bin_size=args.bin_size,
55
+ total_events_fraction=args.event_fraction,
56
+ )
57
+
58
+
59
+ if __name__ == "__main__":
60
+ main()
resolvit/resolvit.py ADDED
@@ -0,0 +1,734 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+
6
+ from glob import glob
7
+ from shutil import copy
8
+ from pathlib import Path
9
+ from astropy.io import fits
10
+ from astropy.wcs import WCS
11
+ from astropy.convolution import Gaussian2DKernel, convolve, Box2DKernel
12
+ from datetime import datetime
13
+ from scipy import interpolate
14
+
15
+
16
+ __version__ = "0.1.0"
17
+
18
+ DEFAULT_BIN_SIZE = 100.0
19
+ DEFAULT_ITERATION_OFFSETS = [0, 1 / 2, 1 / 4, 1 / 3]
20
+ DEFAULT_TOTAL_EVENTS_FRACTION = 0.75
21
+ DEFAULT_UPPER_LIMIT = 10 # sub-pixels
22
+
23
+
24
+ def write_processing_log(
25
+ paths,
26
+ events_list,
27
+ bin_size,
28
+ total_events_fraction,
29
+ iteration_offsets,
30
+ ):
31
+ with open(paths.log_file, "w") as logfile:
32
+
33
+ logfile.write("Product information\n")
34
+ logfile.write("-------------------\n")
35
+ logfile.write(f"Product ID : {paths.product_id}\n")
36
+ logfile.write(f"Input file : {events_list}\n")
37
+ logfile.write(f"Output file : {paths.corrected_events_list}\n")
38
+
39
+ logfile.write("\n")
40
+
41
+ logfile.write("Run information\n")
42
+ logfile.write("---------------\n")
43
+ logfile.write(f"Resolvit version : {__version__}\n")
44
+ logfile.write(f"Run time : " f"{datetime.utcnow().isoformat()} UTC\n")
45
+
46
+ logfile.write("\n")
47
+
48
+ logfile.write("Algorithm parameters\n")
49
+ logfile.write("--------------------\n")
50
+ logfile.write(f"Bin size : {bin_size}\n")
51
+ logfile.write(f"Event fraction : " f"{total_events_fraction}\n")
52
+ logfile.write(f"Iterations : " f"{len(iteration_offsets)}\n")
53
+
54
+ for i, offset in enumerate(
55
+ iteration_offsets,
56
+ start=1,
57
+ ):
58
+ logfile.write(f"Iteration {i} offset : " f"{offset}\n")
59
+
60
+
61
+ class ResolvitProductPaths:
62
+ def __init__(self, events_list):
63
+
64
+ self.events_list = Path(events_list)
65
+
66
+ self.channel_dir = self.events_list.parent
67
+
68
+ self.uvit_dir = self.events_list.parents[2]
69
+
70
+ self.resolvit_products_dir = self.uvit_dir / "resolvit_data_products"
71
+
72
+ self.channel_name = self.channel_dir.name
73
+
74
+ self.resolvit_channel_dir = self.resolvit_products_dir / self.channel_name
75
+
76
+ self.resolvit_channel_dir.mkdir(
77
+ parents=True,
78
+ exist_ok=True,
79
+ )
80
+
81
+ self.product_id = self.events_list.name.replace("_l2ce.fits", "")
82
+
83
+ self.diagnostics_dir = (
84
+ self.resolvit_products_dir / "diagnostics" / self.product_id
85
+ )
86
+
87
+ self.diagnostics_dir.mkdir(
88
+ parents=True,
89
+ exist_ok=True,
90
+ )
91
+
92
+ self.corrected_events_list = self.resolvit_channel_dir / self.events_list.name
93
+
94
+ def correlation_plot(
95
+ self,
96
+ iteration_no,
97
+ bin_size,
98
+ t_mid,
99
+ ):
100
+ return (
101
+ self.diagnostics_dir
102
+ / f"{iteration_no}_{bin_size:.0f}_{t_mid:.0f}_correlations.png"
103
+ )
104
+
105
+ def residual_plot(
106
+ self,
107
+ iteration_no,
108
+ ):
109
+ return self.diagnostics_dir / f"residuals_iteration_{iteration_no}.png"
110
+
111
+ def residual_file(
112
+ self,
113
+ iteration_no,
114
+ ):
115
+ return self.diagnostics_dir / f"residuals_iteration_{iteration_no}.txt"
116
+
117
+ @property
118
+ def log_file(self):
119
+ return self.diagnostics_dir / "resolvit.log"
120
+
121
+ @property
122
+ def instrument_image(self):
123
+ return self.resolvit_channel_dir / (
124
+ self.events_list.name.replace(
125
+ "_l2ce.fits",
126
+ "I_l2img.fits",
127
+ )
128
+ )
129
+
130
+ @property
131
+ def instrument_error(self):
132
+ return self.resolvit_channel_dir / (
133
+ self.events_list.name.replace(
134
+ "_l2ce.fits",
135
+ "I_l2err.fits",
136
+ )
137
+ )
138
+
139
+ @property
140
+ def astronomical_image(self):
141
+ return self.resolvit_channel_dir / (
142
+ self.events_list.name.replace(
143
+ "_l2ce.fits",
144
+ "A_l2img.fits",
145
+ )
146
+ )
147
+
148
+ @property
149
+ def astronomical_error(self):
150
+ return self.resolvit_channel_dir / (
151
+ self.events_list.name.replace(
152
+ "_l2ce.fits",
153
+ "A_l2err.fits",
154
+ )
155
+ )
156
+
157
+ @property
158
+ def instrument_exposure(self):
159
+ return self.resolvit_channel_dir / (
160
+ self.events_list.name.replace(
161
+ "_l2ce.fits",
162
+ "I_l2exp.fits",
163
+ )
164
+ )
165
+
166
+ @property
167
+ def astronomical_exposure(self):
168
+ return self.resolvit_channel_dir / (
169
+ self.events_list.name.replace(
170
+ "_l2ce.fits",
171
+ "A_l2exp.fits",
172
+ )
173
+ )
174
+
175
+
176
+ def copy_exposure_maps(events_list, paths):
177
+
178
+ exposure_maps = [
179
+ str(events_list).replace(
180
+ "_l2ce.fits",
181
+ "I_l2exp.fits",
182
+ ),
183
+ str(events_list).replace(
184
+ "_l2ce.fits",
185
+ "A_l2exp.fits",
186
+ ),
187
+ ]
188
+
189
+ for exposure_map in exposure_maps:
190
+
191
+ exposure_map = Path(exposure_map)
192
+
193
+ if exposure_map.exists():
194
+
195
+ destination = paths.resolvit_channel_dir / exposure_map.name
196
+
197
+ copy(
198
+ exposure_map,
199
+ destination,
200
+ )
201
+
202
+
203
+ def read_and_filter_events(events_list_hdu):
204
+ time = events_list_hdu[1].data["MJD_L2"]
205
+ fx = events_list_hdu[1].data["Fx"]
206
+ fy = events_list_hdu[1].data["Fy"]
207
+ photons = events_list_hdu[1].data["EFFECTIVE_NUM_PHOTONS"]
208
+ bad_flag = events_list_hdu[1].data["BAD FLAG"]
209
+ mask = photons > 0
210
+ mask = np.logical_and(mask, bad_flag)
211
+ time = time[mask]
212
+ fx = fx[mask]
213
+ fy = fy[mask]
214
+ photons = photons[mask]
215
+ photons = photons / np.median(photons)
216
+ return time, fx, fy, photons
217
+
218
+
219
+ class EventListCorrelator:
220
+ def __init__(self, reference_events_list, to_match_events_list):
221
+ self.reference_events_list = reference_events_list
222
+ self.to_match_events_list = to_match_events_list
223
+ self.upper_limit = DEFAULT_UPPER_LIMIT
224
+
225
+ def get_columns(self, data):
226
+ time = data["time"]
227
+ fx = data["fx"]
228
+ fy = data["fy"]
229
+ photons = data["photons"]
230
+ return time, fx, fy, photons
231
+
232
+ def get_image(self, hdu, bins):
233
+ time, fx, fy, photons = self.get_columns(hdu)
234
+ ndarray, yedges, xedges = np.histogram2d(
235
+ fy, fx, bins=(bins, bins), weights=photons
236
+ )
237
+ return ndarray
238
+
239
+ def get_lag(self, correlations, shift_range):
240
+ f = interpolate.interp1d(shift_range, correlations, kind="quadratic")
241
+ new_range = np.linspace(
242
+ shift_range[0],
243
+ shift_range[-1],
244
+ num=(self.upper_limit * 2 + 1) * 100,
245
+ endpoint=True,
246
+ )
247
+ interpolated_correlations = f(new_range)
248
+ max_index = np.argmax(interpolated_correlations)
249
+ peak_position = new_range[max_index]
250
+ return peak_position
251
+
252
+ def get_shifts(self, bin_size=1, correlation_plot=None):
253
+ # To get shifts
254
+ bins = np.arange(0, 4801, bin_size)
255
+ reference_image = self.get_image(self.reference_events_list, bins)
256
+ to_match_image = self.get_image(self.to_match_events_list, bins)
257
+
258
+ box_kernel = Box2DKernel(5)
259
+ boxed_reference_image = convolve(reference_image, box_kernel)
260
+ reference_image_background_mask = boxed_reference_image <= (4 / 25)
261
+ reference_image[reference_image_background_mask] = 0
262
+
263
+ boxed_to_match_image = convolve(to_match_image, box_kernel)
264
+ to_match_image_background_mask = boxed_to_match_image <= (4 / 25)
265
+ to_match_image[to_match_image_background_mask] = 0
266
+
267
+ kernel = Gaussian2DKernel(x_stddev=1)
268
+ smoothed_reference_image = convolve(reference_image, kernel)
269
+ smoothed_to_match_image = convolve(to_match_image, kernel)
270
+
271
+ smoothed_reference_image = smoothed_reference_image / np.std(
272
+ smoothed_reference_image
273
+ )
274
+ smoothed_to_match_image = smoothed_to_match_image / np.std(
275
+ smoothed_to_match_image
276
+ )
277
+
278
+ smoothed_reference_image[smoothed_reference_image < 0] = 0
279
+ smoothed_to_match_image[smoothed_to_match_image < 0] = 0
280
+
281
+ smoothed_reference_X = np.sum(smoothed_reference_image, axis=0)
282
+ smoothed_reference_Y = np.sum(smoothed_reference_image, axis=1)
283
+
284
+ smoothed_to_match_X = np.sum(smoothed_to_match_image, axis=0)
285
+ smoothed_to_match_Y = np.sum(smoothed_to_match_image, axis=1)
286
+
287
+ shift_limit = int(self.upper_limit / bin_size)
288
+ shift_range = np.arange(-shift_limit, shift_limit + 1)
289
+
290
+ X_correlations = []
291
+ Y_correlations = []
292
+ for shift in shift_range:
293
+ X_product = np.sum(
294
+ smoothed_reference_X * np.roll(smoothed_to_match_X, shift)
295
+ )
296
+ Y_product = np.sum(
297
+ smoothed_reference_Y * np.roll(smoothed_to_match_Y, shift)
298
+ )
299
+ X_correlations.append(X_product)
300
+ Y_correlations.append(Y_product)
301
+
302
+ x_shift = self.get_lag(X_correlations, shift_range) * bin_size
303
+ y_shift = self.get_lag(Y_correlations, shift_range) * bin_size
304
+
305
+ fig, ax = plt.subplots()
306
+ ax.plot(shift_range, X_correlations, label="X correlations")
307
+ ax.plot(shift_range, Y_correlations, label="Y correlations")
308
+ ax.set_xlabel("Shifts in sub-pixels")
309
+ ax.set_ylabel("Correlation")
310
+ ax.legend()
311
+ if correlation_plot is not None:
312
+ fig.savefig(correlation_plot, dpi=150)
313
+ plt.close(fig)
314
+
315
+ return x_shift, y_shift
316
+
317
+
318
+ def plot_residuals(residuals, figure_name):
319
+ t_array = np.array([(b["t_start"] + b["t_end"]) / 2 for b in residuals])
320
+ dx_array = np.array([b["dx"] for b in residuals])
321
+ dy_array = np.array([b["dy"] for b in residuals])
322
+
323
+ fig, ax = plt.subplots()
324
+ ax.plot(t_array, dx_array, label="X", marker=".", alpha=0.8)
325
+ ax.plot(t_array, dy_array, label="Y", marker=".", alpha=0.8)
326
+
327
+ ax.set_ylim(-3, 3)
328
+ ax.set_xlabel("MJD")
329
+ ax.set_ylabel("Residual (sub-pixels)")
330
+ ax.legend()
331
+
332
+ fig.savefig(figure_name, dpi=150)
333
+ plt.close(fig)
334
+
335
+
336
+ def save_residuals_to_file(residuals, filename):
337
+ data = np.array(
338
+ [
339
+ [r["t_start"], r["t_end"], r["total_events"], r["dx"], r["dy"]]
340
+ for r in residuals
341
+ ]
342
+ )
343
+
344
+ np.savetxt(
345
+ filename,
346
+ data,
347
+ header="t_start t_end total_events dx dy",
348
+ fmt=["%.6f", "%.6f", "%d", "%.6f", "%.6f"],
349
+ )
350
+
351
+
352
+ def calculate_residuals(
353
+ events_list,
354
+ bin_size,
355
+ start_offset,
356
+ total_events_fraction,
357
+ iteration_no,
358
+ paths,
359
+ ):
360
+
361
+ with fits.open(events_list) as events_list_hdu:
362
+ time, fx, fy, photons = read_and_filter_events(events_list_hdu)
363
+
364
+ # Define bin edges
365
+ t_start = time.min() + start_offset
366
+ t_end = time.max()
367
+ bins = np.arange(t_start, t_end + bin_size, bin_size)
368
+
369
+ # Digitize: assign each event to a bin index
370
+ bin_indices = np.digitize(time, bins)
371
+
372
+ binned_data = []
373
+ for i in range(1, len(bins)):
374
+ mask = bin_indices == i
375
+
376
+ if np.any(mask):
377
+ binned_data.append(
378
+ {
379
+ "t_start": bins[i - 1],
380
+ "t_end": bins[i],
381
+ "total_events": len(fx[mask]),
382
+ "time": time[mask],
383
+ "fx": fx[mask],
384
+ "fy": fy[mask],
385
+ "photons": photons[mask],
386
+ }
387
+ )
388
+
389
+ total_events = np.array([b["total_events"] for b in binned_data])
390
+ total_events_threshold = np.median(total_events) * total_events_fraction
391
+
392
+ reference_data = None
393
+ residuals = []
394
+ for data in binned_data:
395
+ if data["total_events"] > total_events_threshold:
396
+ if reference_data is None:
397
+ reference_data = {
398
+ "time": data["time"],
399
+ "fx": data["fx"],
400
+ "fy": data["fy"],
401
+ "photons": data["photons"],
402
+ }
403
+
404
+ residuals.append(
405
+ {
406
+ "t_start": data["t_start"],
407
+ "t_end": data["t_end"],
408
+ "total_events": data["total_events"],
409
+ "dx": 0,
410
+ "dy": 0,
411
+ }
412
+ )
413
+ else:
414
+ to_match_data = {
415
+ "time": data["time"],
416
+ "fx": data["fx"],
417
+ "fy": data["fy"],
418
+ "photons": data["photons"],
419
+ }
420
+
421
+ init_correlation = EventListCorrelator(reference_data, to_match_data)
422
+ t_mid = (data["t_start"] + data["t_end"]) / 2
423
+ dx, dy = init_correlation.get_shifts(
424
+ correlation_plot=paths.correlation_plot(
425
+ iteration_no,
426
+ bin_size,
427
+ t_mid,
428
+ )
429
+ )
430
+
431
+ residuals.append(
432
+ {
433
+ "t_start": data["t_start"],
434
+ "t_end": data["t_end"],
435
+ "total_events": data["total_events"],
436
+ "dx": dx,
437
+ "dy": dy,
438
+ }
439
+ )
440
+
441
+ plot_residuals(
442
+ residuals,
443
+ paths.residual_plot(iteration_no),
444
+ )
445
+
446
+ save_residuals_to_file(
447
+ residuals,
448
+ paths.residual_file(iteration_no),
449
+ )
450
+
451
+ return residuals
452
+
453
+
454
+ def apply_residual_corrections(
455
+ events_list,
456
+ residuals,
457
+ corrected_events_list,
458
+ bin_size,
459
+ total_events_fraction,
460
+ iteration_offsets,
461
+ ):
462
+ with fits.open(events_list) as events_list_hdu:
463
+ time = events_list_hdu[1].data["MJD_L2"]
464
+ fx = events_list_hdu[1].data["Fx"]
465
+ fy = events_list_hdu[1].data["Fy"]
466
+ dx_events = np.zeros_like(fx)
467
+ dy_events = np.zeros_like(fx)
468
+
469
+ dx_array = np.array([b["dx"] for b in residuals])
470
+ dy_array = np.array([b["dy"] for b in residuals])
471
+ total_events_array = np.array([b["total_events"] for b in residuals])
472
+
473
+ offset_dx = np.average(dx_array, weights=total_events_array)
474
+ offset_dy = np.average(dy_array, weights=total_events_array)
475
+
476
+ for r in residuals:
477
+ t0 = r["t_start"]
478
+ t1 = r["t_end"]
479
+ dx = r["dx"] - offset_dx
480
+ dy = r["dy"] - offset_dy
481
+
482
+ mask = (time >= t0) & (time < t1)
483
+
484
+ dx_events[mask] = dx
485
+ dy_events[mask] = dy
486
+
487
+ fx_corr = fx + dx_events
488
+ fy_corr = fy + dy_events
489
+
490
+ events_list_hdu[1].data["Fx"] = fx_corr
491
+ events_list_hdu[1].data["Fy"] = fy_corr
492
+
493
+ instrument_exposure = Path(
494
+ str(events_list).replace(
495
+ "_l2ce.fits",
496
+ "I_l2exp.fits",
497
+ )
498
+ )
499
+
500
+ with fits.open(instrument_exposure) as exp_hdu:
501
+ w = WCS(exp_hdu[0].header)
502
+ PC1_1 = exp_hdu[0].header["PC1_1"]
503
+ PC1_2 = exp_hdu[0].header["PC1_2"]
504
+ PC2_1 = exp_hdu[0].header["PC2_1"]
505
+ PC2_2 = exp_hdu[0].header["PC2_2"]
506
+ CDELT1 = exp_hdu[0].header["CDELT1"]
507
+ CDELT2 = exp_hdu[0].header["CDELT2"]
508
+
509
+ sky = w.pixel_to_world(
510
+ fx_corr,
511
+ fy_corr,
512
+ )
513
+
514
+ events_list_hdu[1].data["Sky_RA"] = sky.ra.degree
515
+ events_list_hdu[1].data["Sky_DEC"] = sky.dec.degree
516
+
517
+ if CDELT1 > 0:
518
+ PC1_1 = -1 * PC1_1
519
+ PC1_2 = -1 * PC1_2
520
+
521
+ if CDELT2 < 0:
522
+ PC2_1 = -1 * PC2_1
523
+ PC2_2 = -1 * PC2_2
524
+
525
+ (
526
+ events_list_hdu[1].data["Fx_astronomical"],
527
+ events_list_hdu[1].data["Fy_astronomical"],
528
+ ) = instrument_to_astronomical(
529
+ fx_corr,
530
+ fy_corr,
531
+ PC1_1,
532
+ PC1_2,
533
+ PC2_1,
534
+ PC2_2,
535
+ )
536
+
537
+ events_list_hdu.writeto(corrected_events_list, overwrite=True)
538
+
539
+
540
+ def instrument_to_astronomical(fx, fy, PC1_1, PC1_2, PC2_1, PC2_2):
541
+ fx_prime = (PC1_1 * (fx - 2400)) + (PC1_2 * (fy - 2400)) + 2400
542
+ fy_prime = (PC2_1 * (fx - 2400)) + (PC2_2 * (fy - 2400)) + 2400
543
+ return fx_prime, fy_prime
544
+
545
+
546
+ def generate_image_products(
547
+ events_list,
548
+ exposure_map,
549
+ image_file,
550
+ error_file,
551
+ astronomical=False,
552
+ ):
553
+
554
+ if astronomical:
555
+ fx_keyword = "Fx_astronomical"
556
+ fy_keyword = "Fy_astronomical"
557
+ else:
558
+ fx_keyword = "Fx"
559
+ fy_keyword = "Fy"
560
+
561
+ with fits.open(events_list) as events_hdu, fits.open(exposure_map) as exp_hdu:
562
+
563
+ framecount_per_sec = events_hdu[0].header["AVGFRMRT"]
564
+
565
+ fx = events_hdu[1].data[fx_keyword]
566
+ fy = events_hdu[1].data[fy_keyword]
567
+ photons = events_hdu[1].data["EFFECTIVE_NUM_PHOTONS"]
568
+
569
+ image_header = exp_hdu[0].header.copy()
570
+ for key in events_hdu[0].header:
571
+ if key.startswith("RSLV") or key == "RESOLVIT":
572
+ image_header[key] = events_hdu[0].header[key]
573
+
574
+ bins = np.arange(-0.5, 4800.5, 1)
575
+
576
+ events, _, _ = np.histogram2d(
577
+ fy,
578
+ fx,
579
+ bins=(bins, bins),
580
+ weights=photons,
581
+ )
582
+
583
+ counts, _, _ = np.histogram2d(
584
+ fy,
585
+ fx,
586
+ bins=(bins, bins),
587
+ )
588
+
589
+ exposure = exp_hdu[0].data
590
+
591
+ with np.errstate(divide="ignore", invalid="ignore"):
592
+ cps = events / (exposure * framecount_per_sec)
593
+ cps_error = cps / np.sqrt(counts)
594
+
595
+ cps[exposure == 0] = 0
596
+ cps_error[exposure == 0] = 0
597
+ cps_error[counts == 0] = 0
598
+
599
+ cps = cps.astype(np.float32)
600
+ cps_error = cps_error.astype(np.float32)
601
+
602
+ image_hdu = fits.PrimaryHDU(cps)
603
+ image_hdu.header.update(image_header)
604
+ image_hdu.header["DATATYPE"] = "count-rate image"
605
+
606
+ error_hdu = fits.PrimaryHDU(cps_error)
607
+ error_hdu.header.update(image_header)
608
+ error_hdu.header["DATATYPE"] = "count-rate error image"
609
+
610
+ image_hdu.writeto(
611
+ image_file,
612
+ overwrite=True,
613
+ )
614
+
615
+ error_hdu.writeto(
616
+ error_file,
617
+ overwrite=True,
618
+ )
619
+
620
+
621
+ def process_observation(
622
+ observation_dir,
623
+ bin_size=DEFAULT_BIN_SIZE,
624
+ iteration_offsets=None,
625
+ total_events_fraction=DEFAULT_TOTAL_EVENTS_FRACTION,
626
+ ):
627
+
628
+ if iteration_offsets is None:
629
+ iteration_offsets = DEFAULT_ITERATION_OFFSETS
630
+
631
+ events_lists = glob(
632
+ f"{observation_dir}/**/data_products/*_data/**/AS1*l2ce.fits",
633
+ recursive=True,
634
+ )
635
+
636
+ events_lists = sorted(events_lists)
637
+
638
+ for events_list in events_lists:
639
+ process_events_list(
640
+ events_list, bin_size, iteration_offsets, total_events_fraction
641
+ )
642
+
643
+
644
+ def process_events_list(
645
+ events_list, bin_size, iteration_offsets, total_events_fraction
646
+ ):
647
+
648
+ print(f"Processing {Path(events_list).name}")
649
+
650
+ paths = ResolvitProductPaths(events_list)
651
+
652
+ write_processing_log(
653
+ paths,
654
+ events_list,
655
+ bin_size,
656
+ total_events_fraction,
657
+ iteration_offsets,
658
+ )
659
+
660
+ current_file = events_list
661
+
662
+ for i, frac in enumerate(
663
+ iteration_offsets,
664
+ start=1,
665
+ ):
666
+
667
+ offset = bin_size * frac
668
+
669
+ residuals = calculate_residuals(
670
+ current_file,
671
+ bin_size,
672
+ offset,
673
+ total_events_fraction,
674
+ i,
675
+ paths,
676
+ )
677
+
678
+ apply_residual_corrections(
679
+ current_file,
680
+ residuals,
681
+ paths.corrected_events_list,
682
+ bin_size,
683
+ total_events_fraction,
684
+ iteration_offsets,
685
+ )
686
+
687
+ current_file = paths.corrected_events_list
688
+
689
+ with fits.open(paths.corrected_events_list, mode="update") as events_list_hdu:
690
+ events_list_hdu[0].header.add_blank()
691
+ events_list_hdu[0].header.add_comment("Resolvit processing information")
692
+ events_list_hdu[0].header.add_blank()
693
+
694
+ events_list_hdu[0].header["RESOLVIT"] = (True, "Processed using Resolvit")
695
+ events_list_hdu[0].header["RSLV_VER"] = (__version__, "Resolvit version")
696
+ events_list_hdu[0].header["RSLV_BIN"] = (bin_size, "Time bin size (s)")
697
+
698
+ events_list_hdu[0].header["RSLV_FR"] = (
699
+ total_events_fraction,
700
+ "Event fraction threshold",
701
+ )
702
+
703
+ events_list_hdu[0].header["RSLV_ITL"] = (
704
+ len(iteration_offsets),
705
+ "Number of iterations",
706
+ )
707
+
708
+ for i, offset in enumerate(iteration_offsets, start=1):
709
+ events_list_hdu[0].header[f"RSLV_IT{i}"] = (
710
+ float(offset),
711
+ f"Iteration {i} offset fraction",
712
+ )
713
+
714
+ events_list_hdu.flush()
715
+
716
+ copy_exposure_maps(
717
+ events_list,
718
+ paths,
719
+ )
720
+
721
+ generate_image_products(
722
+ paths.corrected_events_list,
723
+ paths.instrument_exposure,
724
+ paths.instrument_image,
725
+ paths.instrument_error,
726
+ )
727
+
728
+ generate_image_products(
729
+ paths.corrected_events_list,
730
+ paths.astronomical_exposure,
731
+ paths.astronomical_image,
732
+ paths.astronomical_error,
733
+ astronomical=True,
734
+ )
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: resolvit
3
+ Version: 0.1.0
4
+ Summary: Improve the PSF of UVIT data products
5
+ Project-URL: Homepage, https://github.com/prajwel/resolvit
6
+ Project-URL: Issues, https://github.com/prajwel/resolvit/issues
7
+ Author-email: Prajwel Joseph <prajwel.pj@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.9
13
+ Requires-Dist: astropy
14
+ Requires-Dist: matplotlib
15
+ Requires-Dist: numpy
16
+ Requires-Dist: scipy
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Resolvit
20
+
21
+ Resolvit improves the point spread function (PSF) of UVIT Level2 products by applying sub-pixel corrections to the Level2 events list and generating a new set of derived data products.
22
+
23
+ The corrected events list is treated as the primary Resolvit product. All other Resolvit products are derived from it.
24
+
25
+ ## Installation
26
+
27
+ ```bash
28
+ pip install resolvit
29
+ ```
30
+
31
+ ## Python usage
32
+
33
+ ```python
34
+ from resolvit import process_observation
35
+
36
+ process_observation(
37
+ "20160101_A01_123T01_0123456789_level2"
38
+ )
39
+ ```
40
+
41
+ ### Custom parameters
42
+
43
+ ```python
44
+ from resolvit import process_observation
45
+
46
+ process_observation(
47
+ "20160101_A01_123T01_0123456789_level2",
48
+ bin_size=50,
49
+ )
50
+ ```
51
+
52
+ ## Command-line usage
53
+
54
+ Process a UVIT Level2 observation directory:
55
+
56
+ ```bash
57
+ resolvit 20160101_A01_123T01_0123456789_level2
58
+ ```
59
+
60
+ Specify a custom time bin size:
61
+
62
+ ```bash
63
+ resolvit 20160101_A01_123T01_0123456789_level2 \
64
+ --bin-size 50
65
+ ```
66
+
67
+ Show the installed version:
68
+
69
+ ```bash
70
+ resolvit --version
71
+ ```
72
+
73
+ ## Output products
74
+
75
+ Resolvit creates a new directory alongside the original UVIT products:
76
+
77
+ ```text
78
+ uvit/
79
+ ├── data_products/
80
+ └── resolvit_data_products/
81
+ ```
82
+
83
+ The original UVIT products are never modified.
84
+
85
+ ## Diagnostics
86
+
87
+ Resolvit generates diagnostic plots and residual tables for each channel-filter-window combination:
88
+
89
+ ```text
90
+ resolvit_data_products/
91
+ └── diagnostics/
92
+ └── <product_id>/
93
+ ├── resolvit.log
94
+ ├── residuals_iteration_1.txt
95
+ ├── residuals_iteration_1.png
96
+ ├── residuals_iteration_2.txt
97
+ ├── residuals_iteration_2.png
98
+ └── *_correlations.png
99
+ ```
@@ -0,0 +1,8 @@
1
+ resolvit/__init__.py,sha256=t5xiTnUMJynNvRvS6ECSBQ7hJF5Qv37RvZQFyHvNhls,181
2
+ resolvit/cli.py,sha256=lPrzaZPZIcrEosx1eE0Zk9I853yaBuYt7NQBI9-K6go,1317
3
+ resolvit/resolvit.py,sha256=D5Zs_KSLQKp93Pj4TN-XieAGNzUnI9YUQvvnwKcQjew,21151
4
+ resolvit-0.1.0.dist-info/METADATA,sha256=WFWhCU2c3RgjallUHHyy9c2S89K9xrVsplFKe5EkG6U,2221
5
+ resolvit-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
6
+ resolvit-0.1.0.dist-info/entry_points.txt,sha256=Vc3DO6JPPbqrQdnssifJ26fv3Gfq3cVkKCfz17gYZ4s,47
7
+ resolvit-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
8
+ resolvit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ resolvit = resolvit.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.