-
Notifications
You must be signed in to change notification settings - Fork 24
/
night_qa.py
1313 lines (1240 loc) · 53.8 KB
/
night_qa.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 python
# AR general
import sys
import os
from glob import glob
import tempfile
import textwrap
from desiutil.log import get_logger
# AR scientifical
import numpy as np
import fitsio
# AR astropy
from astropy.table import Table, vstack
from astropy.io import fits
# AR desitarget
from desitarget.targetmask import desi_mask, bgs_mask
from desitarget.targetmask import zwarn_mask as desitarget_zwarn_mask
from desitarget.targets import main_cmx_or_sv
from desitarget.targets import zcut as lya_zcut
# AR desispec
from desispec.fiberbitmasking import get_skysub_fiberbitmask_val
# AR matplotlib
import matplotlib
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from matplotlib import gridspec
from matplotlib.ticker import MultipleLocator
# AR PIL (to create pdf from pngs)
from PIL import Image
log = get_logger()
def get_nightqa_outfns(outdir, night):
"""
Utility function to get nightqa file names.
Args:
outdir: output folder name (string)
night: night (int)
Returns:
dictionary with file names
"""
return {
"html" : os.path.join(outdir, "nightqa-{}.html".format(night)),
"dark" : os.path.join(outdir, "dark-{}.pdf".format(night)),
"badcol" : os.path.join(outdir, "badcol-{}.png".format(night)),
"ctedet" : os.path.join(outdir, "ctedet-{}.pdf".format(night)),
"sframesky" : os.path.join(outdir, "sframesky-{}.pdf".format(night)),
"tileqa" : os.path.join(outdir, "tileqa-{}.pdf".format(night)),
"skyzfiber" : os.path.join(outdir, "skyzfiber-{}.png".format(night)),
"petalnz" : os.path.join(outdir, "petalnz-{}.pdf".format(night)),
}
def get_surveys_night_expids(
night,
datadir = None):
"""
List the (EXPIDs, TILEIDs) from a given night for a given survey.
Args:
night: night (int)
surveys: comma-separated list of surveys to consider, in lower-cases, e.g. "sv1,sv2,sv3,main" (str)
datadir (optional, defaults to $DESI_SPECTRO_DATA): full path where the {NIGHT}/desi-{EXPID}.fits.fz files are (str)
Returns:
expids: list of the EXPIDs (np.array())
tileids: list of the TILEIDs (np.array())
surveys: list of the SURVEYs (np.array())
Notes:
Based on:
- parsing the OBSTYPE keywords from the SPEC extension header of the desi-{EXPID}.fits.fz files;
- for OBSTYPE="SCIENCE", parsing the fiberassign-TILEID.fits* header
"""
if datadir is None:
datadir = os.getenv("DESI_SPECTRO_DATA")
fns = sorted(
glob(
os.path.join(
datadir,
"{}".format(night),
"????????",
"desi-????????.fits.fz",
)
)
)
expids, tileids, surveys = [], [], []
for i in range(len(fns)):
hdr = fits.getheader(fns[i], "SPEC")
if hdr["OBSTYPE"] == "SCIENCE":
survey = "unknown"
# AR look for the fiberassign file
# AR - used wildcard, because early files (pre-SV1?) were not gzipped
# AR - first check SURVEY keyword (should work for SV3 and later)
# AR - if not present, take FA_SURV
fafns = glob(os.path.join(os.path.dirname(fns[i]), "fiberassign-??????.fits*"))
if len(fafns) > 0:
fahdr = fits.getheader(fafns[0], 0)
if "SURVEY" in fahdr:
survey = fahdr["SURVEY"]
else:
survey = fahdr["FA_SURV"]
if survey == "unknown":
log.warning("SURVEY could not be identified for {}; setting to 'unknown'".format(fns[i]))
# AR append
expids.append(hdr["EXPID"])
tileids.append(hdr["TILEID"])
surveys.append(survey)
expids, tileids, surveys = np.array(expids), np.array(tileids), np.array(surveys)
per_surv = []
for survey in np.unique(surveys):
sel = surveys == survey
per_surv.append(
"{} exposures from {} tiles for SURVEY={}".format(
sel.sum(), np.unique(tileids[sel]).size, survey,
)
)
log.info("for NIGHT={} found {}".format(night, " and ".join(per_surv)))
return expids, tileids, surveys
def get_dark_night_expid(night, datadir = None):
"""
Returns the EXPID of the 300s DARK exposure for a given night.
Args:
night: night (int)
datadir (optional, defaults to $DESI_SPECTRO_DATA): full path where the {NIGHT}/desi-{EXPID}.fits.fz files are (str)
Returns:
expid: EXPID (int)
Notes:
If nothing found, returns None.
"""
if datadir is None:
datadir = os.getenv("DESI_SPECTRO_DATA")
#
fns = sorted(
glob(
os.path.join(
datadir,
"{}".format(night),
"????????",
"desi-????????.fits.fz",
)
)
)
expid = None
for i in range(len(fns)):
hdr = fits.getheader(fns[i], "SPEC")
if (hdr["OBSTYPE"] == "DARK") & (hdr["REQTIME"] == 300):
expid = hdr["EXPID"]
break
if expid is None:
log.warning(
"no EXPID found as the 300s DARK for NIGHT={}".format(night)
)
else:
log.info(
"found EXPID={} as the 300s DARK for NIGHT={}".format(
expid, night,
)
)
return expid
def get_ctedet_night_expid(night, prod):
"""
Returns the EXPID of the 1s FLAT exposure for a given night.
If not present, takes the science exposure with the lowest sky counts.
Args:
night: night (int)
prod: full path to prod folder, e.g. /global/cfs/cdirs/desi/spectro/redux/blanc/ (string)
Returns:
expid: EXPID (int)
Notes:
If nothing found, returns None.
We look for preproc files.
As we are looking for a faint signal, we want the image with the less electrons,
thus it could be picking a BRIGHT short exposure against a longer DARK exposure.
"""
expids = np.array(
[
int(os.path.basename(fn))
for fn in sorted(
glob(
os.path.join(
prod,
"preproc",
"{}".format(night),
"*",
)
)
)
]
)
ctedet_expid = None
# AR checking preproc-??-{EXPID}.fits
for expid in expids:
fns = sorted(
glob(
os.path.join(
prod,
"preproc",
"{}".format(night),
"{:08d}".format(expid),
"preproc-??-{:08d}.fits".format(expid),
)
)
)
# AR if some preproc files, just pick the first one
if len(fns) > 0:
hdr = fits.getheader(fns[0], "IMAGE")
if (hdr["OBSTYPE"] == "FLAT") & (hdr["REQTIME"] == 1):
ctedet_expid = hdr["EXPID"]
break
if ctedet_expid is not None:
log.info(
"found EXPID={} as the 1s FLAT for NIGHT={}".format(
expid, night,
)
)
# AR if no 1s FLAT, go for the SCIENCE exposure with the lowest sky counts
# AR using the r-band sky
else:
log.warning(
"no EXPID found as the 1s FLAT for NIGHT={}; going for SCIENCE exposures".format(night)
)
minsky = 1e10
# AR checking sky-r?-{EXPID}.fits
for expid in expids:
fns = sorted(
glob(
os.path.join(
prod,
"exposures",
"{}".format(night),
"{:08d}".format(expid),
"sky-r?-{:08d}.fits".format(expid),
)
)
)
# AR if some sky files, just pick the first one
if len(fns) > 0:
hdr = fits.getheader(fns[0], "SKY")
if hdr["OBSTYPE"] == "SCIENCE":
sky = np.median(fits.open(fns[0])["SKY"].data)
log.info("{} r-sky = {:.1f}".format(os.path.basename(fns[0]), sky))
if sky < minsky:
ctedet_expid, minsky = expid, sky
log.info("\t=> pick {}".format(expid))
#
if ctedet_expid is not None:
log.info(
"found EXPID={} as the sky image with the lowest counts for NIGHT={}".format(
ctedet_expid, night,
)
)
else:
log.warning(
"no SCIENCE EXPID with sky-r?-*fits file found for NIGHT={}; returning None".format(night)
)
return ctedet_expid
def create_mp4(fns, outmp4, duration=15):
"""
Create an animated .mp4 from a set of input files (usually pngs).
Args:
fns: list of input filenames, in the correct order (list of strings)
outmp4: output .mp4 filename
duration (optional, defaults to 15): video duration in seconds (float)
Notes:
Requires ffmpeg to be installed.
At NERSC, run in the bash command line: "module load ffmpeg".
The movie uses fns in the provided order.
"""
# AR is ffmpeg installed
if os.system("which ffmpeg") != 0:
log.error("ffmpeg needs to be installed to create the mp4 movies; it can be installed at nersc with 'module load ffmpeg'")
raise RuntimeError("ffmpeg needs to be installed to run create_mp4()")
# AR deleting existing video mp4, if any
if os.path.isfile(outmp4):
log.info("deleting existing {}".format(outmp4))
os.remove(outmp4)
# AR temporary folder
tmpoutdir = tempfile.mkdtemp()
# AR copying files to tmpoutdir
n_img = len(fns)
for i in range(n_img):
_ = os.system("cp {} {}/tmp-{:04d}.png".format(fns[i], tmpoutdir, i))
print(fns)
# AR ffmpeg settings
default_fps = 25. # ffmpeg default fps
pts_fac = "{:.1f}".format(duration / (n_img / default_fps))
# cmd = "ffmpeg -i {}/tmp-%04d.png -filter:v 'setpts={}*PTS' {}".format(tmpoutdir, pts_fac, outmp4)
# AR following encoding so that mp4 are displayed in safari, firefox
cmd = "ffmpeg -i {}/tmp-%04d.png -vf 'setpts={}*PTS,crop=trunc(iw/2)*2:trunc(ih/2)*2' -vcodec libx264 -pix_fmt yuv420p {}".format(tmpoutdir, pts_fac, outmp4)
_ = os.system(cmd)
# AR deleting temporary tmp*png files
for i in range(n_img):
os.remove("{}/tmp-{:04d}.png".format(tmpoutdir, i))
def create_dark_pdf(outpdf, night, prod, dark_expid, binning=4):
"""
For a given night, create a pdf with the 300s binned dark.
Args:
outpdf: output pdf file (string)
night: night (int)
prod: full path to prod folder, e.g. /global/cfs/cdirs/desi/spectro/redux/blanc/ (string)
dark_expid: EXPID of the 300s DARK exposure to display (int)
binning (optional, defaults to 4): binning of the image (which will be beforehand trimmed) (int)
"""
cameras = ["b", "r", "z"]
petals = np.arange(10, dtype=int)
clim = (-5, 5)
with PdfPages(outpdf) as pdf:
for petal in petals:
fig = plt.figure(figsize=(20, 10))
gs = gridspec.GridSpec(1, len(cameras), wspace=0.1)
for ic, camera in enumerate(cameras):
ax = plt.subplot(gs[ic])
fn = os.path.join(
prod,
"preproc",
"{}".format(night),
"{:08d}".format(dark_expid),
"preproc-{}{}-{:08d}.fits".format(camera, petal, dark_expid),
)
ax.set_title("EXPID={} {}{}".format(dark_expid, camera, petal))
if os.path.isfile(fn):
log.info("reading {}".format(fn))
h = fits.open(fn)
image, ivar, mask = h["IMAGE"].data, h["IVAR"].data, h["MASK"].data
# AR setting to np.nan pixels with ivar = 0 or mask > 0
# AR hence, when binning, any binned pixel with a masked pixel
# AR will appear as np.nan (easy way to go)
d = image.copy()
sel = (ivar == 0) | (mask > 0)
d[sel] = np.nan
# AR trimming
shape_orig = d.shape
if shape_orig[0] % binning != 0:
d = d[shape_orig[0] % binning:, :]
if shape_orig[1] % binning != 0:
d = d[:, shape_orig[1] % binning:]
log.info(
"{} trimmed from ({}, {}) to ({}, {})".format(
fn, shape_orig[0], shape_orig[1], d.shape[0], d.shape[1],
)
)
d_reshape = d.reshape(
d.shape[0] // binning,
binning,
d.shape[1] // binning,
binning
)
d_bin = d_reshape.mean(axis=1).mean(axis=-1)
# AR displaying masked pixels (np.nan) in red
d_bin_msk = np.ma.masked_where(d_bin == np.nan, d_bin)
cmap = matplotlib.cm.Greys_r
cmap.set_bad(color="r")
im = ax.imshow(d_bin_msk, cmap=cmap, vmin=clim[0], vmax=clim[1])
if camera == cameras[-1]:
p = ax.get_position().get_points().flatten()
cax = fig.add_axes([
p[0] + 1.05 * (p[2] - p[0]),
p[1],
0.05 * (p[2] - p[0]),
1.0 * (p[3]-p[1])
])
cbar = plt.colorbar(im, cax=cax, orientation="vertical", ticklocation="right", pad=0, extend="both")
cbar.set_label("Units : ?")
cbar.mappable.set_clim(clim)
else:
log.warning("missing {}".format(fn))
pdf.savefig(fig, bbox_inches="tight")
plt.close()
def create_badcol_png(outpng, night, prod, n_previous_nights=10):
"""
For a given night, create a png file with displaying the number of bad columns per {camera}{petal}.
Args:
outpng: output png file (string)
night: night (int)
prod: full path to prod folder, e.g. /global/cfs/cdirs/desi/spectro/redux/blanc/ (string)
n_previous_nights (optional, defaults to 10): number of previous nights to plot (int)
"""
cameras = ["b", "r", "z"]
colors = ["b", "r", "k"]
petals = np.arange(10, dtype=int)
# AR grabbing the n_previous_nights previous nights
nights = np.array(
[int(os.path.basename(fn))
for fn in sorted(
glob(
os.path.join(
prod,
"exposures",
"*"
)
)
)
]
)
nights = nights[nights < night]
nights = nights[-n_previous_nights:]
all_nights = nights.tolist() + [night]
# AR reading
badcols = {}
for nite in all_nights:
badcols[nite] = {
camera : np.nan + np.zeros(len(petals)) for camera in cameras
}
for camera in cameras:
for petal in petals:
fn = os.path.join(
prod,
"calibnight",
"{}".format(nite),
"badcolumns-{}{}-{}.csv".format(camera, petal, nite),
)
if os.path.isfile(fn):
log.info("reading {}".format(fn))
badcols[nite][camera][petal] = len(Table.read(fn))
# AR plotting
fig, ax = plt.subplots()
for nite in all_nights:
for camera, color in zip(cameras, colors):
if nite == night:
marker, alpha, lw, label = "-o", 1.0, 2.0, "{}-camera".format(camera)
else:
marker, alpha, lw, label = "-", 0.3, 0.8, None
ax.plot(petals, badcols[nite][camera], marker, lw=lw, alpha=alpha, color=color, label=label)
ax.legend(loc=2)
ax.text(
0.98, 0.95, "Thin: {} previous nights ({}-{})".format(
n_previous_nights, nights.min(), nights.max(),
), color="k", fontsize=10, ha="right", transform=ax.transAxes,
)
ax.set_title("{}".format(night))
ax.set_xlabel("PETAL_LOC")
ax.set_xlim(petals[0] - 1, petals[-1] + 1)
ax.set_ylabel("N(badcolumn)")
ax.set_ylim(0, 50)
ax.grid()
plt.savefig(outpng, bbox_inches="tight")
plt.close()
def create_ctedet_pdf(outpdf, night, prod, ctedet_expid, nrow=21, xmin=None, xmax=None, ylim=(-5, 10)):
"""
For a given night, create a pdf with a CTE diagnosis (from preproc files).
Args:
outpdf: output pdf file (string)
night: night (int)
prod: full path to prod folder, e.g. /global/cfs/cdirs/desi/spectro/redux/blanc/ (string)
ctedet_expid: EXPID for the CTE diagnosis (1s FLAT, or darker science exposure) (int)
nrow (optional, defaults to 21): number of rows to include in median (int)
xmin (optional, defaults to None): minimum column to display (int)
xmax (optional, defaults to None): maximum column to display (int)
ylim (optional, default to (-5, 10)): ylim for the median plot (duplet)
Notes:
Credits to S. Bailey.
Copied-pasted-adapted from /global/homes/s/sjbailey/desi/dev/ccd/plot-amp-cte.py
"""
cameras = ["b", "r", "z"]
petals = np.arange(10, dtype=int)
clim = (-5, 5)
with PdfPages(outpdf) as pdf:
for petal in petals:
for camera in cameras:
petcam_xmin, petcam_xmax = xmin, xmax
fig = plt.figure(figsize=(30, 5))
gs = gridspec.GridSpec(2, 1, wspace=0.1, height_ratios = [1, 4])
ax2d = plt.subplot(gs[0])
ax1d = plt.subplot(gs[1])
#
fn = os.path.join(
prod,
"preproc",
"{}".format(night),
"{:08d}".format(ctedet_expid),
"preproc-{}{}-{:08d}.fits".format(camera, petal, ctedet_expid),
)
ax1d.set_title(
"{}\nMedian of {} rows above/below CCD amp boundary".format(
fn, nrow,
)
)
if os.path.isfile(fn):
# AR read
img = fits.open(fn)["IMAGE"].data
ny, nx = img.shape
if petcam_xmin is None:
petcam_xmin = 0
if petcam_xmax is None:
petcam_xmax = nx
above = np.median(img[ny // 2: ny // 2 + nrow, petcam_xmin : petcam_xmax], axis=0)
below = np.median(img[ny // 2 - nrow : ny // 2, petcam_xmin : petcam_xmax], axis=0)
xx = np.arange(petcam_xmin, petcam_xmax)
# AR plot 2d image
extent = [petcam_xmin - 0.5, petcam_xmax - 0.5, ny // 2 - nrow - 0.5, ny // 2 + nrow - 0.5]
vmax = {"b" : 20, "r" : 40, "z" : 60}[camera]
ax2d.imshow(img[ny // 2 - nrow : ny // 2 + nrow, petcam_xmin : petcam_xmax], vmin=-5, vmax=vmax, extent=extent)
ax2d.xaxis.tick_top()
# AR plot 1d median
ax1d.plot(xx, above, alpha=0.5, label="above (AMPC : x < {}; AMPD : x > {}".format(nx // 2 - 1, nx // 2 -1))
ax1d.plot(xx, below, alpha=0.5, label="below (AMPA : x < {}; AMPB : x > {}".format(nx // 2 - 1, nx // 2 -1))
ax1d.legend(loc=2)
# AR amplifier x-boundary
ax1d.axvline(nx // 2 - 1, color="k", ls="--")
ax1d.set_xlabel("CCD column")
ax1d.set_xlim(petcam_xmin, petcam_xmax)
ax1d.set_ylim(ylim)
ax1d.grid()
pdf.savefig(fig, bbox_inches="tight")
plt.close()
def create_sframesky_pdf(outpdf, night, prod, expids):
"""
For a given night, create a pdf from per-expid sframe for the sky fibers only.
Args:
outpdf: output pdf file (string)
night: night (int)
prod: full path to prod folder, e.g. /global/cfs/cdirs/desi/spectro/redux/blanc/ (string)
expids: expids to display (list or np.array)
"""
#
cameras = ["b", "r", "z"]
petals = np.arange(10, dtype=int)
#
nightdir = os.path.join(prod, "exposures", "{}".format(night))
# AR sorting the EXPIDs by increasing order
expids = np.sort(expids)
#
with PdfPages(outpdf) as pdf:
for expid in expids:
tileid = None
fns = sorted(
glob(
os.path.join(
nightdir,
"{:08d}".format(expid),
"sframe-??-{:08d}.fits".format(expid),
)
)
)
if len(fns) > 0:
#
mydict = {camera : {} for camera in cameras}
for ic, camera in enumerate(cameras):
for petal in petals:
fn = os.path.join(
nightdir,
"{:08d}".format(expid),
"sframe-{}{}-{:08d}.fits".format(camera, petal, expid),
)
if os.path.isfile(fn):
h = fits.open(fn)
sel = h["FIBERMAP"].data["OBJTYPE"] == "SKY"
h["FLUX"].data = h["FLUX"].data[sel, :]
h["FIBERMAP"].data = h["FIBERMAP"].data[sel]
if "flux" not in mydict[camera]:
mydict[camera]["wave"] = h["WAVELENGTH"].data
nwave = len(mydict[camera]["wave"])
mydict[camera]["petals"] = np.zeros(0, dtype=int)
mydict[camera]["flux"] = np.zeros(0).reshape((0, nwave))
mydict[camera]["isflag"] = np.zeros(0, dtype=bool)
mydict[camera]["flux"] = np.append(mydict[camera]["flux"], h["FLUX"].data, axis=0)
mydict[camera]["petals"] = np.append(mydict[camera]["petals"], petal + np.zeros(h["FLUX"].data.shape[0], dtype=int))
mydict[camera]["isflag"] = np.append(mydict[camera]["isflag"], (h["FIBERMAP"].data["FIBERSTATUS"] & get_skysub_fiberbitmask_val()) > 0)
if tileid is None:
tileid = h["FIBERMAP"].header["TILEID"]
print("\t", night, expid, camera+str(petal), ((h["FIBERMAP"].data["FIBERSTATUS"] & get_skysub_fiberbitmask_val()) > 0).sum(), "/", sel.sum())
print(night, expid, camera, mydict[camera]["isflag"].sum(), "/", mydict[camera]["isflag"].size)
#
fig = plt.figure(figsize=(20, 10))
gs = gridspec.GridSpec(len(cameras), 1, hspace=0.025)
clim = (-100, 100)
xlim = (0, 3000)
for ic, camera in enumerate(cameras):
ax = plt.subplot(gs[ic])
nsky = 0
if "flux" in mydict[camera]:
nsky = mydict[camera]["flux"].shape[0]
im = ax.imshow(mydict[camera]["flux"], cmap=matplotlib.cm.Greys_r, vmin=clim[0], vmax=clim[1], zorder=0)
for petal in petals:
ii = np.where(mydict[camera]["petals"] == petal)[0]
if len(ii) > 0:
ax.plot([0, mydict[camera]["flux"].shape[1]], [ii.min(), ii.min()], color="r", lw=1, zorder=1)
ax.text(10, ii.mean(), "{}".format(petal), color="r", fontsize=10, va="center")
ax.set_ylim(0, mydict[cameras[0]]["flux"].shape[0])
if ic == 1:
p = ax.get_position().get_points().flatten()
cax = fig.add_axes([
p[0] + 0.85 * (p[2] - p[0]),
p[1],
0.01 * (p[2] - p[0]),
1.0 * (p[3]-p[1])
])
cbar = plt.colorbar(im, cax=cax, orientation="vertical", ticklocation="right", pad=0, extend="both")
cbar.set_label("FLUX [{}]".format(h["FLUX"].header["BUNIT"]))
cbar.mappable.set_clim(clim)
ax.text(0.99, 0.92, "CAMERA={}".format(camera), color="k", fontsize=15, fontweight="bold", ha="right", transform=ax.transAxes)
if ic == 0:
ax.set_title("EXPID={:08d} NIGHT={} TILED={} {} SKY fibers".format(
expid, night, tileid, nsky)
)
ax.set_xlim(xlim)
if ic == 2:
ax.set_xlabel("WAVELENGTH direction")
ax.set_yticklabels([])
ax.set_ylabel("FIBER direction")
pdf.savefig(fig, bbox_inches="tight")
plt.close()
def create_tileqa_pdf(outpdf, night, prod, expids, tileids):
"""
For a given night, create a pdf from the tile-qa*png files, sorted by increasing EXPID.
Args:
outpdf: output pdf file (string)
night: night (int)
prod: full path to prod folder, e.g. /global/cfs/cdirs/desi/spectro/redux/blanc/ (string)
expids: expids of the tiles to display (list or np.array)
tileids: tiles to display (list or np.array)
"""
# AR exps, to sort by increasing EXPID for that night
expids, tileids = np.array(expids), np.array(tileids)
ii = expids.argsort()
# AR protecting against the empty exposure list case
if len(expids) > 0:
expids, tileids = expids[ii], tileids[ii]
ii = np.array([np.where(tileids == tileid)[0][0] for tileid in np.unique(tileids)])
expids, tileids = expids[ii], tileids[ii]
ii = expids.argsort()
expids, tileids = expids[ii], tileids[ii]
#
fns = []
for tileid in tileids:
fn = os.path.join(
prod,
"tiles",
"cumulative",
"{}".format(tileid),
"{}".format(night),
"tile-qa-{}-thru{}.png".format(tileid, night))
if os.path.isfile(fn):
fns.append(fn)
else:
log.warning("no {}".format(fn))
# AR creating pdf
with PdfPages(outpdf) as pdf:
for fn in fns:
fig, ax = plt.subplots()
img = Image.open(fn)
ax.imshow(img)
ax.axis("off")
pdf.savefig(fig, bbox_inches="tight", dpi=300)
plt.close()
def create_skyzfiber_png(outpng, night, prod, tileids, dchi2_threshold=9):
"""
For a given night, create a Z vs. FIBER plot for all SKY fibers.
Args:
outpdf: output pdf file (string)
night: night (int)
prod: full path to prod folder, e.g. /global/cfs/cdirs/desi/spectro/redux/blanc/ (string)
tileids: list of tileids to consider (list or numpy array)
dchi2_threshold (optional, defaults to 9): DELTACHI2 value to split the sample (float)
Notes:
Work from the redrock*fits files.
"""
# AR safe
tileids = np.unique(tileids)
# AR gather all infos from the redrock*fits files
fibers, zs, dchi2s = [], [], []
nfn = 0
for tileid in tileids:
fns = sorted(
glob(
os.path.join(
prod,
"tiles",
"cumulative",
"{}".format(tileid),
"{}".format(night),
"redrock-?-{}-thru{}.fits".format(tileid, night),
)
)
)
nfn += len(fns)
for fn in fns:
fm = fitsio.read(fn, ext="FIBERMAP", columns=["OBJTYPE", "FIBER"])
rr = fitsio.read(fn, ext="REDSHIFTS", columns=["Z", "DELTACHI2"])
sel = fm["OBJTYPE"] == "SKY"
log.info("selecting {} / {} SKY fibers in {}".format(sel.sum(), len(rr), fn))
fibers += fm["FIBER"][sel].tolist()
zs += rr["Z"][sel].tolist()
dchi2s += rr["DELTACHI2"][sel].tolist()
fibers, zs, dchi2s = np.array(fibers), np.array(zs), np.array(dchi2s)
# AR plot
fig, ax = plt.subplots()
for sel, selname, color in zip(
[
dchi2s < dchi2_threshold,
dchi2s > dchi2_threshold
],
[
"OBJTYPE=SKY and DELTACHI2<{}".format(dchi2_threshold),
"OBJTYPE=SKY and DELTACHI2 > {}".format(dchi2_threshold),
],
["orange", "b"]
):
ax.scatter(fibers[sel], zs[sel], c=color, s=1, alpha=0.1, label="{} ({} fibers)".format(selname, sel.sum()))
ax.grid()
ax.set_title("NIGHT = {} ({} fibers from {} redrock*fits files)".format(night, len(fibers), nfn))
ax.set_xlabel("FIBER")
ax.set_xlim(-100, 5100)
ax.set_label("Z")
ax.set_ylim(-0.1, 6.0)
ax.legend(loc=2, markerscale=10)
plt.savefig(outpng, bbox_inches="tight")
plt.close()
def create_petalnz_pdf(outpdf, night, prod, tileids, surveys, dchi2_threshold=25):
"""
For a given night, create a per-petal, per-tracer n(z) pdf file.
Args:
outpdf: output pdf file (string)
night: night (int)
prod: full path to prod folder, e.g. /global/cfs/cdirs/desi/spectro/redux/blanc/ (string)
tileids: list of tileids to consider (list or numpy array)
surveys: list of the surveys for each tileid of tileids (list or numpy array)
dchi2_threshold (optional, defaults to 9): DELTACHI2 value to split the sample (float)
Notes:
Only displays:
- sv1, sv2, sv3, main, as otherwise the plotted tracers are not relevant;
- FAPRGRM="bright" or "dark" tileids.
If the tile-qa-TILEID-thruNIGHT.fits file is missing, that tileid is skipped.
For the Lya, work from the zmtl*fits files, trying to mimick what is done in desitarget.mtl.make_mtl().
The LRG, ELG, QSO, BGS_BRIGHT, BGS_FAINT bit are the same for sv1, sv2, sv3, main,
so ok to simply use the bit mask values from the main.
TBD : we query the FAPRGRM of the tile-qa-*fits header, not sure that properly works for
surveys other than main..
"""
petals = np.arange(10, dtype=int)
# AR safe
tileids, ii = np.unique(tileids, return_index=True)
surveys = surveys[ii]
# AR cutting on sv1, sv2, sv3, main
sel = np.in1d(surveys, ["sv1", "sv2", "sv3", "main"])
if sel.sum() > 0:
log.info(
"removing {}/{} tileids corresponding to surveys={}, different than sv1, sv2, sv3, main".format(
(~sel).sum(), tileids.size, ",".join(np.unique(surveys[~sel]).astype(str)),
)
)
tileids, surveys = tileids[sel], surveys[sel]
#
# AR gather all infos from the zmtl*fits files
ds = {"bright" : [], "dark" : []}
ntiles = {"bright" : 0, "dark" : 0}
for tileid, survey in zip(tileids, surveys):
# AR bright or dark?
fn = os.path.join(
prod,
"tiles",
"cumulative",
"{}".format(tileid),
"{}".format(night),
"tile-qa-{}-thru{}.fits".format(tileid, night),
)
# AR if no tile-qa*fits, we skip the tileid
if not os.path.isfile(fn):
log.warning("no {} file, proceeding to next tile".format(fn))
continue
hdr = fits.getheader(fn, "FIBERQA")
if "FAPRGRM" not in hdr:
log.warning("no FAPRGRM in {} header, proceeding to next tile".format(fn))
continue
faprgrm = hdr["FAPRGRM"].lower()
if faprgrm not in ["bright", "dark"]:
log.warning("{} : FAPRGRM={} not in bright, dark, proceeding to next tile".format(fn, faprgrm))
continue
# AR reading zmtl files
istileid = False
for petal in petals:
fn = os.path.join(
prod,
"tiles",
"cumulative",
"{}".format(tileid),
"{}".format(night),
"zmtl-{}-{}-thru{}.fits".format(petal, tileid, night),
)
if not os.path.isfile(fn):
log.warning("{} : no file".format(fn))
else:
istileid = True
d = Table.read(fn, hdu="ZMTL")
# AR rename *DESI_TARGET and *BGS_TARGET to DESI_TARGET and BGS_TARGET
keys, _, _ = main_cmx_or_sv(d)
d.rename_column(keys[0], "DESI_TARGET")
d.rename_column(keys[1], "BGS_TARGET")
# AR cutting on columns
d = d[
"TARGETID", "DESI_TARGET", "BGS_TARGET",
"Z", "ZWARN", "SPECTYPE", "DELTACHI2",
"Z_QN", "Z_QN_CONF", "IS_QSO_QN",
]
d["SURVEY"] = np.array([survey for x in range(len(d))], dtype=object)
d["TILEID"] = np.array([tileid for x in range(len(d))], dtype=int)
d["PETAL_LOC"] = petal + np.zeros(len(d), dtype=int)
sel = np.zeros(len(d), dtype=bool)
if faprgrm == "bright":
for msk in ["BGS_BRIGHT", "BGS_FAINT"]:
sel |= (d["BGS_TARGET"] & bgs_mask[msk]) > 0
if faprgrm == "dark":
for msk in ["LRG", "ELG", "QSO"]:
sel |= (d["DESI_TARGET"] & desi_mask[msk]) > 0
log.info("selecting {} tracer targets from {}".format(sel.sum(), fn))
d = d[sel]
ds[faprgrm].append(d)
if istileid:
ntiles[faprgrm] += 1
# AR stack
faprgrms, tracers = [], []
for faprgrm, faprgrm_tracers in zip(
["bright", "dark"],
[["BGS_BRIGHT", "BGS_FAINT"], ["LRG", "ELG", "QSO"]],
):
if len(ds[faprgrm]) > 0:
ds[faprgrm] = vstack(ds[faprgrm])
faprgrms += [faprgrm]
tracers += faprgrm_tracers
# AR define subsamples
for faprgrm in faprgrms:
# AR valid fiber
valid = np.ones(len(ds[faprgrm]), dtype=bool)
nodata = ds[faprgrm]["ZWARN"] & desitarget_zwarn_mask["NODATA"] != 0
badqa = ds[faprgrm]["ZWARN"] & desitarget_zwarn_mask.mask("BAD_SPECQA|BAD_PETALQA") != 0
ds[faprgrm]["VALID"] = (~nodata) & (~badqa)
# AR DELTACHI2 above threshold
ds[faprgrm]["ZOK"] = ds[faprgrm]["DELTACHI2"] > dchi2_threshold
# AR Lya
if faprgrm == "dark":
ds[faprgrm]["LYA"] = (
(ds[faprgrm]["Z"] >= lya_zcut)
|
((ds[faprgrm]["Z_QN"] >= lya_zcut) & (ds[faprgrm]["IS_QSO_QN"] == 1))
)
# AR small internal plot utility function
def get_tracer_props(tracer):
if tracer in ["BGS_BRIGHT", "BGS_FAINT"]:
faprgrm, mask, dtkey = "bright", bgs_mask, "BGS_TARGET"
xlim, ylim = (-0.2, 1.5), (0, 5.0)
else:
faprgrm, mask, dtkey = "dark", desi_mask, "DESI_TARGET"
if tracer == "LRG":
xlim, ylim = (-0.2, 2), (0, 3.0)
elif tracer == "ELG":
xlim, ylim = (-0.2, 3), (0, 3.0)
else: # AR QSO
xlim, ylim = (-0.2, 6), (0, 3.0)
return faprgrm, mask, dtkey, xlim, ylim
# AR plot
#
# AR color for each tracer
colors = {
"BGS_BRIGHT" : "purple",
"BGS_FAINT" : "c",
"LRG" : "r",
"ELG" : "b",
"QSO" : "orange",
}
with PdfPages(outpdf) as pdf:
# AR we need some tiles to plot!
if ntiles["bright"] + ntiles["dark"] > 0:
for survey in np.unique(surveys):
ntiles_surv = {
"bright" : np.unique(ds["bright"]["TILEID"][ds["bright"]["SURVEY"] == survey]).size,
"dark" : np.unique(ds["dark"]["TILEID"][ds["dark"]["SURVEY"] == survey]).size,
}
# AR plotting only if some tiles
if ntiles_surv["bright"] + ntiles_surv["dark"] == 0:
continue
# AR three plots:
# AR - fraction of VALID fibers, bright+dark together
# AR - fraction of ZOK fibers, per tracer
# AR - fraction of LYA candidates for QSOs
fig = plt.figure(figsize=(40, 5))
gs = gridspec.GridSpec(1, 3, wspace=0.5)
title = "SURVEY={} : {} BRIGHT and {} DARK tiles from {}".format(
survey, ntiles_surv["bright"], ntiles_surv["dark"], night
)
# AR fraction of ~VALID fibers, bright+dark together
ax = plt.subplot(gs[0])
ys = np.nan + np.zeros(len(petals))
for petal in petals:
npet, nvalid = 0, 0
for faprgrm in faprgrms:
issurvpet = (ds[faprgrm]["SURVEY"] == survey) & (ds[faprgrm]["PETAL_LOC"] == petal)
npet += issurvpet.sum()
nvalid += ((issurvpet) & (ds[faprgrm]["VALID"])).sum()
ys[petal] = nvalid / npet
ax.plot(petals, ys, "-o", color="k")
ax.set_title(title)
ax.set_xlabel("PETAL_LOC")
ax.set_ylabel("fraction of VALID_fibers")
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.set_ylim(0.5, 1.0)
ax.grid()
# AR - fraction of ZOK fibers, per tracer (VALID fibers only)
ax = plt.subplot(gs[1])
for tracer in tracers:
faprgrm, mask, dtkey, _, _ = get_tracer_props(tracer)
istracer = ds[faprgrm]["SURVEY"] == survey
istracer &= (ds[faprgrm][dtkey] & mask[tracer]) > 0
istracer &= ds[faprgrm]["VALID"]
ys = np.nan + np.zeros(len(petals))
for petal in petals:
ispetal = (istracer) & (ds[faprgrm]["PETAL_LOC"] == petal)
iszok = (ispetal) & (ds[faprgrm]["ZOK"])
ys[petal] = iszok.sum() / ispetal.sum()
ax.plot(petals, ys, "-o", color=colors[tracer], label=tracer)
ax.set_title(title)
ax.set_xlabel("PETAL_LOC")
ax.set_ylabel("fraction of DELTACHI2 >_{}\n(VALID fibers only)".format(dchi2_threshold))
ax.xaxis.set_major_locator(MultipleLocator(1))
if survey == "main":
ax.set_ylim(0.7, 1.0)
else:
ax.set_ylim(0.0, 1.0)
ax.grid()
ax.legend()
# AR - fraction of LYA candidates for QSOs
ax = plt.subplot(gs[2])
if "dark" in faprgrms:
faprgrm = "dark"
ys = np.nan + np.zeros(len(petals))
for petal in petals:
ispetsurv = (ds[faprgrm]["SURVEY"] == survey) & (ds[faprgrm]["PETAL_LOC"] == petal) & (ds[faprgrm]["VALID"])
isqso = (ispetsurv) & ((ds[faprgrm][dtkey] & desi_mask["QSO"]) > 0)
islya = (isqso) & (ds[faprgrm]["LYA"])
ys[petal] = islya.sum() / isqso.sum()
ax.plot(petals, ys, "-o", color=colors["QSO"])
ax.set_title(title)
ax.set_xlabel("PETAL_LOC")
ax.set_ylabel("fraction of LYA candidates\n(VALID QSO fibers only)")
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.set_ylim(0, 1)
ax.grid()
#
pdf.savefig(fig, bbox_inches="tight")
plt.close()
# AR per-petal, per-tracer n(z)
for tracer in tracers:
faprgrm, mask, dtkey, xlim, ylim = get_tracer_props(tracer)
istracer = ds[faprgrm]["SURVEY"] == survey
istracer &= (ds[faprgrm][dtkey] & mask[tracer]) > 0
istracer &= ds[faprgrm]["VALID"]
istracer_zok = (istracer) & (ds[faprgrm]["ZOK"])
bins = np.arange(xlim[0], xlim[1] + 0.05, 0.05)
#
if ntiles_surv[faprgrm] > 0:
fig = plt.figure(figsize=(40, 5))
gs = gridspec.GridSpec(1, 10, wspace=0.3)
for petal in petals:
ax = plt.subplot(gs[petal])
_ = ax.hist(
ds[faprgrm]["Z"][istracer_zok],
bins=bins,
density=True,