/
fba_launch_io.py
executable file
·3488 lines (3197 loc) · 126 KB
/
fba_launch_io.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
"""
fiberassign.fba_launch_io
=============
Utility functions for fba_launch
"""
from __future__ import absolute_import, division
# system
import os
import subprocess
import sys
import tempfile
import shutil
import re
from glob import glob
# time
from time import time
from datetime import datetime, timedelta, timezone
#
import numpy as np
import fitsio
import healpy as hp
# astropy
from astropy.io import fits
from astropy.table import Table, vstack
from astropy.time import Time
from astropy import units
from astropy.coordinates import SkyCoord, Distance
from astropy.time import Time
# desitarget
import desitarget
from desitarget.gaiamatch import gaia_psflike
from desitarget.io import read_targets_in_tiles, write_targets, write_skies, read_keyword_from_mtl_header, find_mtl_file_format_from_header
if desitarget.__version__ < "1.2.2":
from desitarget.mtl import inflate_ledger
else:
from desitarget.mtl import match_ledger_to_targets
from desitarget.targetmask import desi_mask, obsconditions
from desitarget.targets import set_obsconditions
from desitarget.geomask import match, pixarea2nside, nside2nside
# desimodel
import desimodel
from desimodel.footprint import is_point_in_desi, tiles2pix
from desimodel.io import datadir
# desimeter
import desimeter
# fiberassign
import fiberassign
from fiberassign.utils import Logger, assert_isoformat_utc, get_svn_version, get_last_line, read_ecsv_keys, get_date_cutoff
from fiberassign.targets import default_survey_target_masks
# matplotlib
import matplotlib.pyplot as plt
from matplotlib import gridspec
import matplotlib
import matplotlib.image as mpimg
# AR default REF_EPOCH for PMRA=PMDEC=REF_EPOCH=0 objects
gaia_ref_epochs = {"dr2": 2015.5}
# AR tile radius in degrees
tile_radius_deg = 1.628
# AR approx. tile area in degrees
tile_area = np.pi * tile_radius_deg ** 2
def get_latest_rundate(log=Logger.get(), step="", start=time()):
"""
Returns the latest TIME value of the latest desi-state_*ecsv file in $DESIMODEL.
Args:
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
Notes:
If not UTC-formatted, we add "+00:00".
"""
# AR need DESIMODEL to be defined
if os.getenv("DESIMODEL") is None:
log.error("DESIMODEL environment variable is not defined; exiting")
sys.exit(1)
# AR take the latest desi-state_*ecsv file
fn = sorted(glob(os.path.join(datadir(), "focalplane", "desi-state_*ecsv")))[-1]
log.info("{:.1f}s\t{}\tusing {} to get the latest rundate".format(time() - start, step, fn))
d = Table.read(fn, include_names = ["TIME"])
# AR take the latest timestamp (should be the last line, but safe here)
rundate = np.unique(d["TIME"])[-1]
# AR if not UTC formatted, we add +00:00
if not assert_isoformat_utc(rundate):
rundate += "+00:00"
log.info("{:.1f}s\t{}\tlatest rundate: {}".format(time() - start, step, rundate))
return rundate
def get_program_latest_timestamp(
survey, program, tilera, tiledec, log=Logger.get(), step="", start=time(),
):
"""
Get the latest timestamp for a given tile, from the MTL per-tile file and the
primary/secondary/ToO ledgers touching that tile.
Args:
survey: survey (string; e.g. "sv1", "sv2", "sv3", "main")
program: ideally "dark", "bright", or "backup" (string)
though if different will return None
tilera: tile center R.A. (float)
tiledec: tile center Dec. (float)
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
Returns:
if some entries for input program: UTC YYYY-MM-DDThh:mm:ss+00:00 formatted timestamp (string)
else: None
Notes:
20210831: remove the +1min (and added "leq=True" in the read_targets_.. routines for ledgers)
"""
# AR check DESI_SURVEYOPS is defined
assert_env_vars(
required_env_vars=["DESI_SURVEYOPS"], log=log, step=step, start=start,
)
# AR defaults to None (returned if no file or no selected rows)
timestamp = None
tms = []
# AR check if the per-tile file is here
# AR no need to check the scnd-mtl-done-tiles.ecsv file,
# AR as we restrict to a given program ([desi-survey 2434])
fn = os.path.join(os.getenv("DESI_SURVEYOPS"), "mtl", "mtl-done-tiles.ecsv")
if os.path.isfile(fn):
d = Table.read(fn)
keep = d["PROGRAM"] == program.upper()
# AR add a cut on TILEID
if survey == "sv3":
keep &= (d["TILEID"] < 1000)
if survey == "main":
keep &= (d["TILEID"] >= 1000) & (d["TILEID"] < 59000)
if keep.sum() > 0:
d = d[keep]
# AR taking the latest timestamp
tm = np.unique(d["TIMESTAMP"])[-1]
log.info("{:.1f}s\t{}\tlatest TIMESTAMP from {}: {}".format(time() - start, step, fn, tm))
tms.append(tm)
# AR now checking the healpix pixels touching the tile
mtldir, scndmtldir, too = get_ledger_paths(
survey.lower(),
program.lower(),
log=log,
step=step,
start=start,
)
# AR existing folders?
hpdirnames = []
for hpdirname in [mtldir, scndmtldir]:
if hpdirname is not None:
if os.path.isdir(hpdirname):
hpdirnames.append(hpdirname)
else:
log.warning("{:.1f}s\t{}\tno existing {}".format(time() - start, step, hpdirname))
# ADM/AR determine the pixels that touch the tiles.
# AR assume same filenside for primary and secondary
if len(hpdirnames) > 0:
hpdirname = hpdirnames[0]
tiles = Table()
tiles["RA"], tiles["DEC"] = [tilera], [tiledec]
nside = pixarea2nside(7.)
pixlist = tiles2pix(nside, tiles=tiles)
fileform = find_mtl_file_format_from_header(hpdirname)
filenside = int(read_keyword_from_mtl_header(hpdirname, "FILENSID"))
filepixlist = nside2nside(nside, filenside, pixlist)
log.info(
"{:.1f}s\t{}\tconsider tilera={}, tiledec={}".format(
time() - start, step, tilera, tiledec,
)
)
log.info(
"{:.1f}s\t{}\ttouching healpix pixels (nside={}): {}".format(
time() - start, step, filenside, ", ".join(["{}".format(pix) for pix in filepixlist]),
)
)
# AR build list of files to check
fns = [too]
for hpdirname in hpdirnames:
fileform = find_mtl_file_format_from_header(hpdirname)
for pix in filepixlist:
fns.append(fileform.format(pix))
# AR check the last-line TIMESTAMP for each file
for fn in fns:
if os.path.isfile(fn):
ii = np.where(np.array(read_ecsv_keys(fn)) == "TIMESTAMP")[0]
if len(ii) > 1:
log.error("{:.1f}s\t{}\t{}: unexpected column content; exiting".format(time() - start, step, fn))
sys.exit(1)
elif len(ii) == 0:
log.warning("{:.1f}s\t{}\t{}: no TIMESTAMP column; passing".format(time() - start, step, fn))
else:
i = ii[0]
line = get_last_line(fn)
tm = line.split()[i]
log.info("{:.1f}s\t{}\t{} last-line TIMESTAMP : {}".format(time() - start, step, fn, tm))
tms.append(tm)
else:
log.warning("{:.1f}s\t{}\t{}: no file, passing".format(time() - start, step, fn))
# AR take the latest TIMESTAMP
if len(tms) > 0:
timestamp = np.sort(tms)[-1]
# AR does not end with +NN:MM timezone?
if re.search('\+\d{2}:\d{2}$', timestamp) is None:
timestamp = "{}+00:00".format(timestamp)
log.info("{:.1f}s\t{}\tlatest timestamp : {}".format(time() - start, step, timestamp))
return timestamp
def mv_write_targets_out(infn, targdir, outfn, log=Logger.get(), step="", start=time()):
"""
Moves the file created by desitarget.io.write_targets
and removes folder created by desitarget.io.write_targets
Args:
infn: filename output by desitarget.io.write_targets
targdir: folder provided as desitarget.io.write_targets input
outfn: desired renaming of infn
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
"""
# AR renaming
# Try to remove file before overwriting; somehow this avoids some permissions issues at KPNO.
try:
os.remove(outfn)
except FileNotFoundError:
pass
_ = shutil.move(infn, outfn)
log.info("{:.1f}s\t{}\trenaming {} to {}".format(time() - start, step, infn, outfn))
# AR removing folders
if targdir[-1] != "/":
targdir = "{}/".format(targdir)
tmpdirs = infn.replace(targdir, "").split("/")[:-1]
for i in range(len(tmpdirs))[::-1]:
os.rmdir(os.path.join(*[targdir] + tmpdirs[: i + 1]))
def get_nowradec(ra, dec, pmra, pmdec, parallax, ref_year, pmtime_utc_str, scnd=False):
"""
Apply proper motion correction
Args:
ra: numpy array of RAs (deg)
dec: numpy array of DECs (deg)
pmra: numpy array of projected proper-motion in RA (mas/year)
pmdec: numpy array of projected proper-motion in DEC (mas/year)
parallax: numpy array of parallax (mas)
ref_year: reference epoch (e.g. 2015.5 for Gaia/DR2)
pmtime_utc_str: date to update position to (format: YYYY-MM-DDThh:mm:ss+00:00)
scnd (optional, defaults to False): secondary target? (boolean; if True, sets parallax=0)
Returns:
ra: numpy array of RAs updated to pmtime_utc_str (deg)
dec: numpy array of DECs updated to pmtime_utc_str (deg)
Notes:
Courtesy of DL; adapted from legacypipe.survey
Originally named radec_at_mjd()
"""
# AR pmtime_utc : UTC time of the new ref_epoch; "%Y-%m-%dT%H:%M:%S%z", e.g. "2021-04-21T00:00:00+00:00"
# AR scnd=True -> parallax is set to 0, i.e. not used
"""
Units:
- matches Gaia DR1/DR2
- pmra,pmdec are in mas/yr.
pmra is in angular speed (ie, has a cos(dec) factor)
- parallax is in mas.
Returns: RA,Dec
"""
equinox = 53084.28 # mjd of the spring equinox in 2004
equinox_jyear = Time(equinox, format="mjd").jyear
axistilt = 23.44 # degrees
arcsecperrad = 3600.0 * 180.0 / np.pi
# AR pmtime
pmtime_utc = datetime.strptime(pmtime_utc_str, "%Y-%m-%dT%H:%M:%S%z")
pmtime_utc_jyear = Time(pmtime_utc).jyear
pmtime_utc_mjd = Time(pmtime_utc).mjd
def xyztoradec(xyz):
assert len(xyz.shape) == 2
ra = np.arctan2(xyz[:, 1], xyz[:, 0]) # AR added "np." in front of arctan2...
ra += 2 * np.pi * (ra < 0)
norm = np.sqrt(np.sum(xyz ** 2, axis=1))
dec = np.arcsin(xyz[:, 2] / norm)
return np.rad2deg(ra), np.rad2deg(dec)
def radectoxyz(ra_deg, dec_deg): # AR changed inputs from ra,dec to ra_deg,dec_deg
ra = np.deg2rad(ra_deg)
dec = np.deg2rad(dec_deg)
cosd = np.cos(dec)
return np.vstack((cosd * np.cos(ra), cosd * np.sin(ra), np.sin(dec))).T
dt = pmtime_utc_jyear - ref_year
cosdec = np.cos(np.deg2rad(dec))
dec = dec + dt * pmdec / (3600.0 * 1000.0)
ra = ra + (dt * pmra / (3600.0 * 1000.0)) / cosdec
parallax = np.atleast_1d(parallax)
# AR discards parallax for scnd=True
if scnd == True:
parallax *= 0.0
I = np.flatnonzero(parallax)
if len(I):
suntheta = 2.0 * np.pi * np.fmod(pmtime_utc_jyear - equinox_jyear, 1.0)
# Finite differences on the unit sphere -- xyztoradec handles
# points that are not exactly on the surface of the sphere.
axis = np.deg2rad(axistilt)
scale = parallax[I] / 1000.0 / arcsecperrad
xyz = radectoxyz(ra[I], dec[I])
xyz[:, 0] += scale * np.cos(suntheta)
xyz[:, 1] += scale * np.sin(suntheta) * np.cos(axis)
xyz[:, 2] += scale * np.sin(suntheta) * np.sin(axis)
r, d = xyztoradec(xyz)
ra[I] = r
dec[I] = d
return ra, dec
def force_finite_pm(
d, pmra_key="PMRA", pmdec_key="PMDEC", log=Logger.get(), step="", start=time()
):
"""
Replaces NaN PMRA, PMDEC by 0
Args:
d: array with at least proper-motion columns
pmra_key (optional, defaults to PMRA): column name for PMRA
pmdec_key (optional, defaults to PMDEC): column name for PMDEC
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
Returns:
d: same as input d, but NaN proper motions replaced by 0
"""
for key in [pmra_key, pmdec_key]:
keep = ~np.isfinite(d[key])
if keep.sum() > 0:
d[key][keep] = 0.0
log.info(
"{:.1f}s\t{}\t replacing NaN by 0 for {} targets".format(
time() - start, step, keep.sum()
)
)
return d
def force_nonzero_refepoch(
d,
force_ref_epoch,
ref_epoch_key="REF_EPOCH",
pmra_key="PMRA",
pmdec_key="PMDEC",
log=Logger.get(),
step="",
start=time(),
):
"""
Replaces 0 by force_ref_epoch in ref_epoch
Args:
d: array with at least proper-motion columns
force_ref_epoch: float, ref_epoch to replace 0 by
ref_epoch_key (optional, defaults to REF_EPOCH): column name for the ref_epoch
pmra_key (optional, defaults to PMRA): column name for PMRA
pmdec_key (optional, defaults to PMDEC): column name for PMDEC
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
Returns:
d: same as input d, but 0 ref_epochs replaced by force_ref_epoch
Notes:
Will exit with error if ref_epoch=0, but pmra or pmdec != 0
"""
keep = d[ref_epoch_key] == 0
n = ((d[pmra_key][keep] != 0) | (d[pmra_key][keep] != 0)).sum()
if n > 0:
log.error(
"{:.1f}s\t{}\t{} targets have {}=0 but {} or {} != 0; exiting".format(
time() - start, step, n, ref_epoch_key, pmra_key, pmdec_key,
)
)
sys.exit(1)
d[ref_epoch_key][keep] = force_ref_epoch
log.info(
"{:.1f}s\t{}\tsetting {}={} for {} objects with {}=0".format(
time() - start,
step,
ref_epoch_key,
force_ref_epoch,
keep.sum(),
ref_epoch_key,
)
)
return d
def update_nowradec(
d,
gaiadr,
pmtime_utc_str,
ra_key="RA",
dec_key="DEC",
pmra_key="PMRA",
pmdec_key="PMDEC",
parallax_key="PARALLAX",
ref_epoch_key="REF_EPOCH",
gaiag_key="GAIA_PHOT_G_MEAN_MAG",
gaiaaen_key="GAIA_ASTROMETRIC_EXCESS_NOISE",
scnd=False,
log=Logger.get(),
step="",
start=time(),
):
"""
Update (RA, DEC, REF_EPOCH) using proper motion
Args:
d: array with at least proper-motion columns
pmtime_utc_str: date to update position to (format: YYYY-MM-DDThh:mm:ss+00:00)
gaiadr: Gaia dr ("dr2" or "edr3")
ra_key (optional, defaults to RA): column name for RA
dec_key (optional, defaults to DEC): column name for DEC
pmra_key (optional, defaults to PMRA): column name for PMRA
pmdec_key (optional, defaults to PMDEC): column name for PMDEC
parallax_key (optional, defaults to PARALLAX): column name for PARALLAX
ref_epoch_key (optional, defaults to REF_EPOCH): column name for the REF_EPOCH
gaia_key (optional, defaults to GAIA_PHOT_G_MEAN_MAG): column name for Gaia g-mag
gaiaaen_key (optional, defaults to GAIA_ASTROMETRIC_EXCESS_NOISE): column name for Gaia GAIA_ASTROMETRIC_EXCESS_NOISE
scnd (optional, defaults to False): secondary target? (boolean);
if False, update for REF_EPOCH>0 + AEN only
if True, update for REF_EPOCH>0 + finite(PMRA,PMDEC) ; forces PARALLAX=0
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
Returns:
d: same as input, but with RA, DEC updated to pmtime_utc_str
Notes:
REF_EPOCH is updated for *all* objects
"""
# AR
pmtime_utc = datetime.strptime(pmtime_utc_str, "%Y-%m-%dT%H:%M:%S%z")
pmtime_utc_jyear = Time(pmtime_utc).jyear
# AR computing positions at pmtime_utc_str using Gaia PMRA, PMDEC
nowra, nowdec = get_nowradec(
d[ra_key],
d[dec_key],
d[pmra_key],
d[pmdec_key],
d[parallax_key],
d[ref_epoch_key],
pmtime_utc_str,
scnd=scnd,
)
if scnd == True:
# AR secondary: REF_EPOCH>0
keep = d["REF_EPOCH"] > 0
else:
# AR targets with REF_EPOCH>0 and passing the AEN criterion
keep = d["REF_EPOCH"] > 0
# AR gaia_psflike arguments changed at desitarget-0.58.0
if desitarget.__version__ < "0.58.0":
keep &= gaia_psflike(d[gaiag_key], d[gaiaaen_key])
else:
keep &= gaia_psflike(d[gaiag_key], d[gaiaaen_key], dr=gaiadr)
# AR storing changes to report extrema in the log
dra = nowra - d[ra_key]
ddec = nowdec - d[dec_key]
# AR updating positions to pmtime_utc_str for targets passing the AEN criterion
d[ra_key][keep] = nowra[keep]
d[dec_key][keep] = nowdec[keep]
log.info(
"{:.1f}s\t{}\tupdating RA,DEC at {} with PM for {:.0f}/{:.0f} targets passing AEN; maximum changes: RA={:.1f},{:.1f} arcsec, DEC={:.1f},{:.1f} arcsec".format(
time() - start,
step,
pmtime_utc_jyear,
keep.sum(),
len(keep),
3600.0 * dra.min(),
3600.0 * dra.max(),
3600 * ddec.min(),
3600.0 * ddec.max(),
)
)
# AR updating REF_EPOCH for *all* objects (for PlateMaker)
d[ref_epoch_key] = pmtime_utc_jyear
log.info(
"{:.1f}s\tupdating REF_EPOCH to {} for all {} targets".format(
time() - start, pmtime_utc_jyear, len(keep)
)
)
return d
def assert_env_vars(
required_env_vars=[
"DESI_ROOT",
"DESI_TARGET",
"DESIMODEL",
"DESI_SURVEYOPS",
"SKYBRICKS_DIR",
"DUST_DIR",
"SKYHEALPIXS_DIR",
],
log=Logger.get(),
step="settings",
start=time(),
):
"""
Assert the environment variables required by fba_launch
Args:
required_env_vars (optional, defaults to ["DESI_ROOT",
"DESI_TARGET",
"DESIMODEL",
"DESI_SURVEYOPS",
"SKYBRICKS_DIR",
"DUST_DIR",
"SKYHEALPIXS_DIR",]): list of environment variables required by fba_launch
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
Notes:
Will exit with error if some assertions are not verified.
20210928 : add DUST_DIR, as assign.merge_results_tile() requires it to populate EBV=0 values.
20211109 : add SKYHEALPIXS_DIR
"""
# AR safe: DESI environment variables
for required_env_var in required_env_vars:
if os.getenv(required_env_var) is None:
log.error(
"{:.1f}s\t{}\tenvironment variable {} not defined; exiting".format(
time() - start, step, required_env_var
)
)
sys.exit(1)
def assert_arg_dates(
args,
dates=["pmtime_utc_str", "rundate", "mtltime"],
log=Logger.get(),
step="settings",
start=time(),
):
"""
Assert the fba_launch date arguments are correctly formatted ("YYYY-MM-DDThh:mm:ss+00:00")
Args:
args: fba_launch parser.parse_args() output
dates (optional, defaults to ["pmtime_utc_str", "rundate", "mtltime"]): list of date fba_launch argument names to check
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
Notes:
will exit with error if some assertions are not verified
"""
# AR dates properly formatted?
for kwargs in args._get_kwargs():
if kwargs[0] in dates:
if not assert_isoformat_utc(kwargs[1]):
log.error(
"{:.1f}s\t{}\t{}={} is not yyyy-mm-ddThh:mm:ss+00:00; exiting".format(
time() - start, step, kwargs[0], kwargs[1],
)
)
sys.exit(1)
def assert_svn_tileid(
tileid, forcetileid="n", log=Logger.get(), step="settings", start=time(),
):
"""
Asserts if TILEID already exists in the SVN tile folder
Args:
tileid: TILEID to check (int)
forcetileid (optional, defaults to "n"): "y" or "n";
if "n", will trigger a warning + an error
if "y", e will trigger a warning only
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
"""
svn_trunk = os.path.join(os.getenv("DESI_TARGET"), "fiberassign/tiles/trunk")
# AR needs a wildcard to verify .fits and fits.gz files
# AR as the gzipping was not done before ~SV1
svn_fn = os.path.join(
svn_trunk, "{:06d}".format(tileid)[:3], "fiberassign-{:06d}.fits".format(tileid)
)
if os.path.isfile(svn_fn) | os.path.isfile("{}.gz".format(svn_fn)):
log.warning(
"{:.1f}s\t{}\tTILEID={} already exists in SVN folder {}".format(
time() - start, step, tileid, svn_trunk
)
)
if forcetileid == "y":
log.warning(
"{:.1f}s\t{}\tproceeding as forcetileid == y".format(
time() - start, step
)
)
else:
log.error(
"{:.1f}s\tsettings\texiting as forcetileid == n".format(time() - start)
)
sys.exit(1)
else:
log.info(
"{:.1f}s\t{}\tTILEID={} does not exist in SVN folder {}; proceeding".format(
time() - start, step, tileid, svn_trunk
)
)
def print_config_infos(
required_env_vars=[
"DESI_ROOT",
"DESI_TARGET",
"DESIMODEL",
"DESI_SURVEYOPS",
"SKYBRICKS_DIR",
"DUST_DIR",
"SKYHEALPIXS_DIR",
],
log=Logger.get(),
step="settings",
start=time(),
):
"""
Print various configuration informations (machine, modules version/path, DESI environment variables).
Args:
required_env_vars (optional, defaults to ["DESI_ROOT",
"DESI_TARGET",
"DESIMODEL",
"DESI_SURVEYOPS",
"SKYBRICKS_DIR",
"DUST_DIR",]): list of environment variables required by fba_launch
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
Notes:
20210928 : add DUST_DIR, as assign.merge_results_tile() requires it to populate EBV=0 values.
20211109 : add SKYHEALPIXS_DIR
"""
# AR machine
log.info(
"{:.1f}s\t{}\tHOSTNAME={}".format(time() - start, step, os.getenv("HOSTNAME"))
)
# AR fiberassign, desitarget, desimodel, desimeter code version/path
for module, name in zip(
[fiberassign, desitarget, desimodel, desimeter], ["fiberassign", "desitarget", "desimodel", "desimeter"]
):
log.info(
"{:.1f}s\t{}\trunning with {} code version: {}".format(
time() - start, step, name, module.__version__
)
)
log.info(
"{:.1f}s\t{}\trunning with {} code path: {}".format(
time() - start, step, name, module.__path__
)
)
# AR DESI environment variables
for required_env_var in required_env_vars:
log.info(
"{:.1f}s\t{}\t{}={}".format(
time() - start, step, required_env_var, os.getenv(required_env_var)
)
)
def get_ledger_paths(
survey,
program,
log=Logger.get(),
step="settings",
start=time(),
):
"""
Obtain the folder/file full paths for the primary/secondary/ToO ledgers.
Args:
survey: survey (string; e.g. "sv1", "sv2", "sv3", "main")
program: "dark", "bright", or "backup" (string)
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
Returns:
- mtl: primary ledgers MTL folder (string)
- scndmtl: secondary ledgers MTL folder (string)
- too: ToO ecsv ledger file (string)
Notes:
if survey not in ["sv1", "sv2", "sv3", "main"]
or program not in ["dark", "bright", or "backup"], will return a warning only
same warning only if the built paths/files do not exist.
"""
# AR expected survey, program?
exp_surveys = ["sv1", "sv2", "sv3", "main"]
exp_programs = ["dark", "bright", "backup"]
if survey.lower() not in exp_surveys:
log.warning(
"{:.1f}s\t{}\tunexpected survey={} ({}; proceeding anyway)".format(
time() - start, step, survey.lower(), exp_surveys
)
)
if program.lower() not in exp_programs:
log.warning(
"{:.1f}s\t{}\tunexpected program={} ({}; proceeding anyway)".format(
time() - start, step, program.lower(), exp_programs
)
)
# AR check DESI_SURVEYOPS is defined
assert_env_vars(
required_env_vars=["DESI_SURVEYOPS"], log=log, step=step, start=start,
)
# AR same (svn) ledger paths at NERSC/KPNO
mtl = os.path.join(
os.getenv("DESI_SURVEYOPS"), "mtl", survey.lower(), program.lower(),
)
# AR secondary (dark, bright; no secondary for backup)
if program.lower() in ["dark", "bright"]:
scndmtl = os.path.join(
os.getenv("DESI_SURVEYOPS"),
"mtl",
survey.lower(),
"secondary",
program.lower(),
)
else:
scndmtl = None
# AR ToO (same for dark, bright)
too = os.path.join(
os.getenv("DESI_SURVEYOPS"), "mtl", survey.lower(), "ToO", "ToO.ecsv",
)
# AR log
for name, path in zip(["mtl", "scndmtl", "too"], [mtl, scndmtl, too]):
log.info(
"{:.1f}s\t{}\tdirectory for {}: {}".format(
time() - start, step, name, path,
)
)
if path is not None:
if not os.path.exists(path):
log.warning(
"{:.1f}s\t{}\tdirectory for {}: {} does not exist".format(
time() - start, step, name, path,
)
)
#
return mtl, scndmtl, too
def get_desitarget_paths(
dtver,
survey,
program,
dr="dr9",
gaiadr="gaiadr2",
custom_too_file=None,
log=Logger.get(),
step="settings",
start=time(),
):
"""
Obtain the folder/file full paths for desitarget products
Args:
dtver: desitarget catalog version (string; e.g., "0.57.0")
survey: survey (string; e.g. "sv1", "sv2", "sv3", "main")
program: "dark", "bright", or "backup" (string)
dr (optional, defaults to "dr9"): legacypipe dr (string)
gaiadr (optional, defaults to "gaiadr2"): gaia dr (string)
custom_too_file (default=None): full path to a custom ToO file, for development work, which overrides the official one (string)
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start (optional, defaults to time()): start time for log (in seconds; output of time.time())
Returns:
Dictionary with the following keys:
- sky: sky folder
- skysupp: skysupp folder
- gfa: GFA folder
- targ: targets folder (static catalogs, with all columns)
- mtl: MTL folder
- scnd: secondary fits catalog (static, with all columns)
- scndmtl: MTL folder for secondary targets
- scnd2, scnd3, etc: any other existing secondary fits catalog (static, with all columns)
- too: ToO ecsv catalog
Notes:
if survey not in ["sv1", "sv2", "sv3", "main"]
or program not in ["dark", "bright", or "backup"], will return a warning only
same warning only if the built paths/files do not exist.
20210917 : secondary -> add all existing folders (e.g., main2/) (backward-compatible change)
20220318 : add custom_too_file optional argument
"""
# AR expected survey, program?
exp_surveys = ["sv1", "sv2", "sv3", "main"]
exp_programs = ["dark", "bright", "backup"]
if survey.lower() not in exp_surveys:
log.warning(
"{:.1f}s\t{}\tunexpected survey={} ({}; proceeding anyway)".format(
time() - start, step, survey.lower(), exp_surveys
)
)
if program.lower() not in exp_programs:
log.warning(
"{:.1f}s\t{}\tunexpected program={} ({}; proceeding anyway)".format(
time() - start, step, program.lower(), exp_programs
)
)
# AR folder architecture is now the same at NERSC/KPNO (https://github.com/desihub/fiberassign/issues/302)
mydirs = {}
mydirs["sky"] = os.path.join(
os.getenv("DESI_TARGET"), "catalogs", dr, dtver, "skies"
)
mydirs["skysupp"] = os.path.join(
os.getenv("DESI_TARGET"), "catalogs", gaiadr, dtver, "skies-supp"
)
mydirs["gfa"] = os.path.join(
os.getenv("DESI_TARGET"), "catalogs", dr, dtver, "gfas"
)
if program.lower() == "backup":
dtcat = gaiadr
else:
dtcat = dr
mydirs["targ"] = os.path.join(
os.getenv("DESI_TARGET"),
"catalogs",
dtcat,
dtver,
"targets",
survey.lower(),
"resolve",
program.lower(),
)
# AR secondary (dark, bright; no secondary for backup)
if program.lower() in ["dark", "bright"]:
if survey.lower() == "main":
basename = "targets-{}-secondary.fits".format(program.lower())
else:
basename = "{}targets-{}-secondary.fits".format(survey.lower(), program.lower())
mydirs["scnd"] = os.path.join(
os.getenv("DESI_TARGET"),
"catalogs",
dr,
dtver,
"targets",
survey.lower(),
"secondary",
program.lower(),
basename,
)
# AR check possible extra folders, like main2/, main3/, etc
# AR and store the file path in keys like scnd2, scnd3, etc
# AR note: the index in the key name is not related to the extra folder name,
# AR it is just the order of appearance
extradirs = sorted(
[os.path.basename(fn)
for fn in glob(
os.path.join(
os.getenv("DESI_TARGET"), "catalogs", dr, dtver, "targets", "{}*".format(survey.lower())
)
)
if os.path.basename(fn) != survey
]
)
count = 2
for extradir in extradirs:
fn = os.path.join(
os.getenv("DESI_TARGET"),
"catalogs",
dr,
dtver,
"targets",
extradir,
"secondary",
program.lower(),
"{}{}".format(extradir, basename),
)
if os.path.isfile(fn):
mydirs["scnd{}".format(count)] = fn
count += 1
# AR log
for key in list(mydirs.keys()):
log.info(
"{:.1f}s\t{}\tdirectory for {}: {}".format(
time() - start, step, key, mydirs[key]
)
)
if not os.path.exists(mydirs[key]):
log.warning(
"{:.1f}s\t{}\tdirectory for {}: {} does not exist".format(
time() - start, step, key, mydirs[key]
)
)
# AR ledgers
mydirs["mtl"], scndmtl, mydirs["too"] = get_ledger_paths(
survey.lower(),
program.lower(),
log=log,
step=step,
start=start,
)
if scndmtl is not None:
mydirs["scndmtl"] = scndmtl
# AR custom ToO file?
if custom_too_file is not None:
mydirs["too"] = custom_too_file
log.warning(
"{:.1f}s\t{}\tusing custom ToO file {} -> this is for tertiary program or development only!".format(
time() - start, step, custom_too_file,
)
)
return mydirs
def create_tile(
tileid,
tilera,
tiledec,
outfn,
survey,
obscon="DARK|GRAY|BRIGHT|BACKUP",
log=Logger.get(),
step="",
start=time(),
):
"""
Create a tiles fits file.
Args:
tileid: TILEID (int)
tilera: tile center R.A. (float)
tiledec: tile center Dec. (float)
outfn: fits file name to be written
survey: survey (string; e.g. "sv1", "sv2", "sv3", "main")
obscon (optional, defaults to "DARK|GRAY|BRIGHT|BACKUP"): tile allowed observing conditions (string)
log (optional, defaults to Logger.get()): Logger object
step (optional, defaults to ""): corresponding step, for fba_launch log recording
(e.g. dotiles, dosky, dogfa, domtl, doscnd, dotoo)
start(optional, defaults to time()): start time for log (in seconds; output of time.time()
"""
hdr = fitsio.FITSHDR()
log.info("")
log.info("")
log.info("{:.1f}s\t{}\tTIMESTAMP={}".format(time() - start, step, Time.now().isot))
log.info("{:.1f}s\t{}\tstart generating {}".format(time() - start, step, outfn))
log.info(
"{:.1f}s\t{}\ttileid={}, tilera={}, tiledec={}, survey={}, obscon={}".format(
time() - start, step, tileid, tilera, tiledec, survey, obscon
)