/
cuts.py
3214 lines (2691 loc) · 127 KB
/
cuts.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
"""
desitarget.cuts
===============
Target Selection for Legacy Surveys catalogue data derived from `the wiki`_.
A collection of helpful (static) methods to check whether an object's
flux passes a given selection criterion (*e.g.* LRG, ELG or QSO).
.. _`the Gaia data model`: https://gea.esac.esa.int/archive/documentation/GDR2/Gaia_archive/chap_datamodel/sec_dm_main_tables/ssec_dm_gaia_source.html
.. _`the Legacy Surveys`: http://www.legacysurvey.org/
.. _`the wiki`: https://desi.lbl.gov/trac/wiki/TargetSelectionWG/TargetSelection
.. _`the SV3 wiki`: https://desi.lbl.gov/trac/wiki/TargetSelectionWG/SV3
.. _`Legacy Surveys mask`: http://www.legacysurvey.org/dr8/bitmasks/
"""
import warnings
from time import time
import os.path
import numbers
import sys
import fitsio
import numpy as np
import healpy as hp
from pkg_resources import resource_filename
import numpy.lib.recfunctions as rfn
from importlib import import_module
import astropy.units as u
from astropy.coordinates import SkyCoord
from astropy.table import Table, Row
from desitarget import io
from desitarget.internal import sharedmem
from desitarget.gaiamatch import match_gaia_to_primary, find_gaia_files_hp
from desitarget.gaiamatch import pop_gaia_coords, pop_gaia_columns, unextinct_gaia_mags
from desitarget.gaiamatch import gaia_dr_from_ref_cat, is_in_Galaxy, gaia_psflike
from desitarget.targets import finalize, resolve
from desitarget.geomask import bundle_bricks, pixarea2nside, sweep_files_touch_hp
from desitarget.geomask import box_area, hp_in_box, is_in_box, is_in_hp
from desitarget.geomask import cap_area, hp_in_cap, is_in_cap, imaging_mask
# ADM set up the DESI default logger
from desiutil.log import get_logger
log = get_logger()
# ADM start the clock
start = time()
def MWS_too_bright(gaiagmag=None, zfibertotflux=None):
"""Whether a target is too bright to include for MWS observations.
Parameters
----------
gaiagmag : :class:`~numpy.ndarray`
Gaia-based g-band MAGNITUDE.
zfibertotflux : :class:`~numpy.ndarray`
Predicted fiber flux from ALL sources at object's location in 1
arcsecond seeing in z. NOT corrected for Galactic extinction.
Returns
-------
:class:`array_like`
``True`` if and only if the object is FAINTER than the MWS
bright-cut limits.
Notes
-----
- Current version (04/02/21) is version 17 on `the SV3 wiki`_.
"""
# ADM set up an array to store objects that is all True.
too_bright = np.ones_like(gaiagmag, dtype='?')
# ADM True if Gaia G is too bright.
# ADM remember that gaiagmag of 0 corresponds to missing sources.
too_bright &= (gaiagmag < 15) & (gaiagmag != 0)
# ADM or True if the Legacy Surveys zfibertot is too bright.
# ADM remember that zflux of 0 corresponds to missing sources.
zmag = 22.5-2.5*np.log10(zfibertotflux.clip(1e-7))
too_bright |= (zmag < 15) & (zfibertotflux != 0)
return too_bright
def random_fraction_of_trues(fraction, bool_array):
"""Return True for a random subset of array entries that are True.
Parameters
----------
fraction : :class:`float`
The fraction of the True entries to retain as True. Should be
between 0 and 1.
bool_array : :class:`array_like` or `bool`
A boolean array, or scalar.
Returns
-------
:class:`array_like`
The original `bool_array`, with a random `fraction` of ``True``
entries retained as ``True`` and the others set to ``False``.
If a scalar is passed, then a scalar is returned.
"""
# ADM check that the input fraction was between 0 and 1.
if not np.all((0 <= fraction) & (fraction <= 1)):
msg = "fraction must be between 0 and 1, not {}".format(fraction)
log.critical(msg)
raise ValueError(msg)
if np.isscalar(bool_array):
# ADM catch the corner case that a scalar was passed.
chosen = np.random.uniform(0, 1) < fraction
else:
# ADM create a random array with the correct fraction of Trues.
chosen = np.random.random(len(bool_array)) < fraction
# ADM return True for the subset in bool_array that was chosen.
return bool_array & chosen
def _gal_coords(ra, dec):
"""Shift RA, Dec to Galactic coordinates.
Parameters
----------
ra, dec : :class:`array_like` or `float`
RA, Dec coordinates (degrees)
Returns
-------
The Galactic longitude and latitude (l, b)
"""
import astropy.units as u
from astropy.coordinates import SkyCoord
if hasattr(ra, 'unit') and hasattr(dec, 'unit') and ra.unit is not None and dec.unit is not None:
c = SkyCoord(ra.to(u.deg), dec.to(u.deg))
else:
c = SkyCoord(ra*u.deg, dec*u.deg)
gc = c.transform_to('galactic')
return gc.l.value, gc.b.value
def shift_photo_north_pure(gflux=None, rflux=None, zflux=None):
"""Same as :func:`~desitarget.cuts.shift_photo_north_pure` accounting for zero fluxes.
Parameters
----------
gflux, rflux, zflux : :class:`array_like` or `float`
The flux in nano-maggies of g, r, z bands.
Returns
-------
The equivalent fluxes shifted to the southern system.
Notes
-----
- see also https://desi.lbl.gov/DocDB/cgi-bin/private/RetrieveFile?docid=3390;filename=Raichoor_DESI_05Dec2017.pdf;version=1
- Update for DR9 https://desi.lbl.gov/trac/attachment/wiki/TargetSelectionWG/TargetSelection/North_vs_South_dr9.png
"""
gshift = gflux * 10**(-0.4*0.004) * (gflux/rflux)**(-0.059)
rshift = rflux * 10**(0.4*0.003) * (rflux/zflux)**(-0.024)
zshift = zflux * 10**(0.4*0.013) * (rflux/zflux)**(+0.015)
return gshift, rshift, zshift
def shift_photo_north(gflux=None, rflux=None, zflux=None):
"""Convert fluxes in the northern (BASS/MzLS) to the southern (DECaLS) system.
Parameters
----------
gflux, rflux, zflux : :class:`array_like` or `float`
The flux in nano-maggies of g, r, z bands.
Returns
-------
The equivalent fluxes shifted to the southern system.
Notes
-----
- see also https://desi.lbl.gov/DocDB/cgi-bin/private/RetrieveFile?docid=3390;filename=Raichoor_DESI_05Dec2017.pdf;version=1
- Update for DR9 https://desi.lbl.gov/trac/attachment/wiki/TargetSelectionWG/TargetSelection/North_vs_South_dr9.png
"""
# ADM if floats were sent, treat them like arrays.
flt = False
if _is_row(gflux):
flt = True
gflux = np.atleast_1d(gflux)
rflux = np.atleast_1d(rflux)
zflux = np.atleast_1d(zflux)
# ADM only use the g-band color shift when r and g are non-zero
gshift = gflux * 10**(-0.4*0.004)
w = np.where((gflux != 0) & (rflux != 0))
gshift[w] = (gflux[w] * 10**(-0.4*0.004) * (gflux[w]/rflux[w])**complex(-0.059)).real
# ADM only use the r-band color shift when r and z are non-zero
# ADM and only use the z-band color shift when r and z are non-zero
w = np.where((rflux != 0) & (zflux != 0))
rshift = rflux * 10**(0.4*0.003)
zshift = zflux * 10**(0.4*0.013)
rshift[w] = (rflux[w] * 10**(0.4*0.003) * (rflux[w]/zflux[w])**complex(-0.024)).real
zshift[w] = (zflux[w] * 10**(0.4*0.013) * (rflux[w]/zflux[w])**complex(+0.015)).real
if flt:
return gshift[0], rshift[0], zshift[0]
return gshift, rshift, zshift
def isGAIA_STD(ra=None, dec=None, galb=None, gaiaaen=None, pmra=None, pmdec=None,
parallax=None, parallaxovererror=None, ebv=None, gaiabprpfactor=None,
gaiasigma5dmax=None, gaiagmag=None, gaiabmag=None, gaiarmag=None,
gaiadupsource=None, gaiaparamssolved=None,
primary=None, test=False, nside=2):
"""Standards based solely on Gaia data.
Parameters
----------
ebv : :class:`array_like`
E(B-V) values from the SFD dust maps.
test : :class:`bool`, optional, defaults to ``False``
If ``True``, then we're running unit tests and don't have to
find and read every possible Gaia file.
nside : :class:`int`, optional, defaults to 2
(NESTED) HEALPix nside, if targets are being parallelized.
The default of 2 should be benign for serial processing.
Returns
-------
:class:`array_like`
``True`` if the object is a bright "GAIA_STD_FAINT" target.
:class:`array_like`
``True`` if the object is a faint "GAIA_STD_BRIGHT" target.
:class:`array_like`
``True`` if the object is a white dwarf "GAIA_STD_WD" target.
Notes
-----
- Current version (01/28/21) is version 244 on `the wiki`_.
- See :func:`~desitarget.cuts.set_target_bits` for other parameters.
"""
if primary is None:
primary = np.ones_like(gaiagmag, dtype='?')
# ADM restrict all classes to dec >= -30.
primary &= dec >= -30.
std = primary.copy()
# ADM the regular "standards" codes need to know whether something has
# ADM a Gaia match. Here, everything is a Gaia match.
gaia = np.ones_like(gaiagmag, dtype='?')
# ADM determine the Gaia-based white dwarf standards.
std_wd = isMWS_WD(
primary=primary, gaia=gaia, galb=galb, astrometricexcessnoise=gaiaaen,
pmra=pmra, pmdec=pmdec, parallax=parallax,
parallaxovererror=parallaxovererror, photbprpexcessfactor=gaiabprpfactor,
astrometricsigma5dmax=gaiasigma5dmax, gaiagmag=gaiagmag,
gaiabmag=gaiabmag, gaiarmag=gaiarmag, paramssolved=gaiaparamssolved
)
# ADM apply the Gaia quality cuts for standards.
std &= isSTD_gaia(primary=primary, gaia=gaia, astrometricexcessnoise=gaiaaen,
pmra=pmra, pmdec=pmdec, parallax=parallax,
dupsource=gaiadupsource, paramssolved=gaiaparamssolved,
gaiagmag=gaiagmag, gaiabmag=gaiabmag, gaiarmag=gaiarmag)
# ADM restrict to point sources.
ispsf = gaia_psflike(gaiaaen, gaiagmag)
std &= ispsf
# ADM de-extinct the magnitudes before applying color cuts.
gd, bd, rd = unextinct_gaia_mags(gaiagmag, gaiabmag, gaiarmag, ebv)
# ADM apply the Gaia color cuts for standards.
bprp = bd - rd
gbp = gd - bd
std &= bprp > 0.2
std &= bprp < 0.9
std &= gbp > -1.*bprp/2.0
std &= gbp < 0.3-bprp/2.0
# ADM remove any sources that have neighbors in Gaia within 3.5"...
# ADM for speed, run only sources for which std is still True.
log.info("Isolating Gaia-only standards...t={:.1f}s".format(time()-start))
ii_true = np.where(std)[0]
if len(ii_true) > 0:
# ADM determine the pixels of interest.
theta, phi = np.radians(90-dec), np.radians(ra)
pixlist = list(set(hp.ang2pix(nside, theta, phi, nest=True)))
# ADM read in the necessary Gaia files.
fns = find_gaia_files_hp(nside, pixlist, neighbors=True)
gaiaobjs = []
gaiacols = ["RA", "DEC", "PHOT_G_MEAN_MAG", "PHOT_RP_MEAN_MAG"]
for i, fn in enumerate(fns):
if i % 25 == 0:
log.info("Read {}/{} files for Gaia-only standards...t={:.1f}s"
.format(i, len(fns), time()-start))
try:
gaiaobjs.append(fitsio.read(fn, columns=gaiacols))
except OSError:
if test:
pass
else:
msg = "failed to find or open the following file: (ffopen) "
msg += fn
log.critical(msg)
raise OSError
gaiaobjs = np.concatenate(gaiaobjs)
# ADM match the standards to the broader Gaia sources at 3.5".
matchrad = 3.5*u.arcsec
cstd = SkyCoord(ra[ii_true]*u.degree, dec[ii_true]*u.degree)
cgaia = SkyCoord(gaiaobjs["RA"]*u.degree, gaiaobjs["DEC"]*u.degree)
idstd, idgaia, d2d, _ = cgaia.search_around_sky(cstd, matchrad)
# ADM remove source matches with d2d=0 (i.e. the source itself!).
idgaia, idstd = idgaia[d2d > 0], idstd[d2d > 0]
# ADM remove matches within 5 mags of a Gaia source.
badmag = (
(gaiagmag[ii_true][idstd] + 5 > gaiaobjs["PHOT_G_MEAN_MAG"][idgaia]) |
(gaiarmag[ii_true][idstd] + 5 > gaiaobjs["PHOT_RP_MEAN_MAG"][idgaia]))
std[ii_true[idstd][badmag]] = False
# ADM add the brightness cuts in Gaia G-band.
std_bright = std.copy()
std_bright &= gaiagmag >= 16
std_bright &= gaiagmag < 18
std_faint = std.copy()
std_faint &= gaiagmag >= 16
std_faint &= gaiagmag < 19
return std_faint, std_bright, std_wd
def backupGiantDownsample(l, b):
"""
Return the downsampling factor as a function of l,b
Parameters
----------
l: array
Galactic longitude
b: array
Galactic latitude
Returns
-------
frac: array
The fraction of objects to select
"""
p = [6.9529434, 0.18786695, -2.6621607, -3.05095354, 8.10060927]
# this is approximately log density
ldens = p[0] + p[1] * np.cos(np.deg2rad(l)) + p[2] * np.log10(
np.abs(np.abs(b) + p[3] * np.cos(np.deg2rad(l)) + p[4]))
# this just maps x -> x when x<th
# and then x-> (1+alpha)*(x-th)+th when x>th
# The purpose is that in high density regions, it gives a
# high envelope
mapper = lambda x, alpha, th: (x * (x < th) + ((1 + alpha) * (x - th) + th) * (x > th))
subsamp = np.minimum(100 / 10**mapper(ldens, .1, .0), 1)
return subsamp
def isBACKUP(ra=None, dec=None,
gaiagmag=None, gaiabmag=None, gaiarmag=None,
parallax=None, parallaxerr=None,
primary=None):
"""BACKUP targets based on Gaia magnitudes.
Parameters
----------
ra, dec: :class:`array_like` or :class:`None`
Right Ascension and Declination in degrees.
gaiagmag, gaiabmag, gaiarmag: :class:`array_like` or :class:`None`
Gaia-based g, b and r MAGNITUDES (not corrected for Galactic
extinction (same units as `the Gaia data model`_).
parallax, parallaxerr: :class:`array_like` or :class:`None`
Gaia parallax and error (same units as `the Gaia data model`_)
primary : :class:`array_like` or :class:`None`
``True`` for objects that should be passed through the selection.
Returns
-------
:class:`array_like`
``True`` if and only if the object is a bright "BACKUP" target.
:class:`array_like`
``True`` if and only if the object is a faint "BACKUP" target.
:class:`array_like`
``True`` if and only if the object is a very faint "BACKUP"
target.
:class:`array_like`
``True`` if and only if the object is a gaia-selected giant
"BACKUP" target.
Notes
-----
- Current version (10/22/21) is version 273 on `the wiki`_.
"""
if primary is None:
primary = np.ones_like(gaiagmag, dtype='?')
# APC In this case the BP-RP relations use the fluxes without
# APC any correction for extinction, by design.
bprp = gaiabmag - gaiarmag
# ADM restrict all classes to dec >= -30.
primary &= dec >= -30.
# APC require measured gaia color.
primary &= ~np.isnan(bprp)
# APC hard bright limits
# See https://github.com/desihub/desitarget/pull/766
primary &= gaiagmag >= 11.2
primary &= gaiabmag >= 11.2
primary &= gaiarmag >= 11.2
isbackupbright = primary.copy()
isbackupfaint = primary.copy()
isbackupveryfaint = primary.copy()
is_backup_giant = primary.copy()
is_backup_lowp_giant = primary.copy()
# ADM determine which sources are close to the Galaxy.
in_gal = is_in_Galaxy([ra, dec], radec=True)
# APC bright targets are 11.2 + 0.6(BP-RP) < G < 16.
isbackupbright &= gaiagmag >= 11.2 + 0.6 * bprp
isbackupbright &= gaiagmag < 16.0
# APC giant targets are min(17.5 + 0.6 (BP-RP), 19) < G < 16
giant_sel = (gaiagmag >= 16.0)
giant_sel &= gaiagmag < np.minimum(17.5 + 0.6 * bprp, 19)
# APC Giant candidates have low parallax
giant_sel &= parallax < (3 * parallaxerr + 0.1)
# less contaminated giant selection
giant_hp_sel = giant_sel & (parallax < (2 * parallaxerr + 0.1))
# APC and are likely giants
gal = SkyCoord(ra*u.degree, dec*u.degree).galactic
l, b = gal.l.to_value(u.degree), gal.b.to_value(u.degree)
lowlat_fraction = backupGiantDownsample(l, b)
giant_hpsub_sel = random_fraction_of_trues(lowlat_fraction, giant_hp_sel)
# Subsampled subset of high priority giants
is_backup_giant &= giant_hpsub_sel
is_backup_lowp_giant &= (giant_sel & (~giant_hpsub_sel))
# do not select low priority distant giants in the galactic plane
is_backup_lowp_giant &= (~in_gal)
# APC faint targets are 16 < G < 18
isbackupfaint &= gaiagmag >= 16.0
isbackupfaint &= gaiagmag < 18.0
# APC and are not halo giant candidates
isbackupfaint &= (~is_backup_giant) & (~is_backup_lowp_giant)
# ADM and are "far from" the Galaxy.
isbackupfaint &= ~in_gal
# ADM very faint targets are 18. < G < 19.
isbackupveryfaint &= gaiagmag >= 18.
isbackupveryfaint &= gaiagmag < 19
# APC and are not halo giant candidates
isbackupveryfaint &= ~is_backup_giant
isbackupveryfaint &= ~is_backup_lowp_giant
# ADM and are "far from" the Galaxy.
isbackupveryfaint &= ~in_gal
return (isbackupbright, isbackupfaint, isbackupveryfaint,
is_backup_giant, is_backup_lowp_giant)
def isLRG(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None,
zfiberflux=None, rfluxivar=None, zfluxivar=None, w1fluxivar=None,
gaiagmag=None, gnobs=None, rnobs=None, znobs=None, maskbits=None,
zfibertotflux=None, primary=None, south=True):
"""
Parameters
----------
south: boolean, defaults to ``True``
Use cuts appropriate to the Northern imaging surveys (BASS/MzLS)
if ``south=False``, otherwise use cuts appropriate to the
Southern imaging survey (DECaLS).
Returns
-------
:class:`array_like`
``True`` if and only if the object is an LRG target.
Notes
-----
- Current version (05/07/21) is version 260 on `the wiki`_.
- See :func:`~desitarget.cuts.set_target_bits` for other parameters.
"""
# ADM LRG targets.
if primary is None:
primary = np.ones_like(rflux, dtype='?')
lrg_quality = primary.copy()
# ADM basic quality cuts.
lrg_quality &= notinLRG_mask(
primary=primary, rflux=rflux, zflux=zflux, w1flux=w1flux,
zfiberflux=zfiberflux, gnobs=gnobs, rnobs=rnobs, znobs=znobs,
rfluxivar=rfluxivar, zfluxivar=zfluxivar, w1fluxivar=w1fluxivar,
gaiagmag=gaiagmag, maskbits=maskbits, zfibertotflux=zfibertotflux
)
# ADM color-based selection of LRGs.
lrg = isLRG_colors(
gflux=gflux, rflux=rflux, zflux=zflux, w1flux=w1flux,
zfiberflux=zfiberflux, south=south, primary=primary
)
lrg &= lrg_quality
return lrg
def notinLRG_mask(primary=None, rflux=None, zflux=None, w1flux=None,
zfiberflux=None, gnobs=None, rnobs=None, znobs=None,
rfluxivar=None, zfluxivar=None, w1fluxivar=None,
gaiagmag=None, maskbits=None, zfibertotflux=None):
"""See :func:`~desitarget.cuts.isLRG` for details.
Returns
-------
:class:`array_like`
``True`` if and only if the object is NOT masked for poor quality.
"""
if primary is None:
primary = np.ones_like(rflux, dtype='?')
lrg = primary.copy()
lrg &= (rfluxivar > 0) & (rflux > 0) # ADM quality in r.
lrg &= (zfluxivar > 0) & (zflux > 0) & (zfiberflux > 0) # ADM quality in z.
lrg &= (w1fluxivar > 0) & (w1flux > 0) # ADM quality in W1.
lrg &= (gaiagmag == 0) | (gaiagmag > 18) # remove bright GAIA sources
# ADM remove stars with zfibertot < 17.5 that are missing from GAIA.
lrg &= zfibertotflux < 10**(-0.4*(17.5-22.5))
# ADM observed in every band.
lrg &= (gnobs > 0) & (rnobs > 0) & (znobs > 0)
# ADM default mask bits from the Legacy Surveys not set.
lrg &= imaging_mask(maskbits)
return lrg
def isLRG_colors(gflux=None, rflux=None, zflux=None, w1flux=None,
gfiberflux=None, rfiberflux=None, zfiberflux=None,
ggood=None, w2flux=None, primary=None, south=True):
"""(see, e.g., :func:`~desitarget.cuts.isLRG`).
Notes:
- the `ggood` and `w2flux` inputs are an attempt to maintain
backwards-compatibility with the mocks.
"""
if primary is None:
primary = np.ones_like(rflux, dtype='?')
lrg = primary.copy()
gmag = 22.5 - 2.5 * np.log10(gflux.clip(1e-7))
# ADM safe as these fluxes are set to > 0 in notinLRG_mask.
rmag = 22.5 - 2.5 * np.log10(rflux.clip(1e-7))
zmag = 22.5 - 2.5 * np.log10(zflux.clip(1e-7))
w1mag = 22.5 - 2.5 * np.log10(w1flux.clip(1e-7))
zfibermag = 22.5 - 2.5 * np.log10(zfiberflux.clip(1e-7))
if south:
lrg &= zmag - w1mag > 0.8 * (rmag - zmag) - 0.6 # non-stellar cut
lrg &= zfibermag < 21.6 # faint limit
lrg &= (gmag - w1mag > 2.9) | (rmag - w1mag > 1.8) # low-z cuts
lrg &= (
((rmag - w1mag > (w1mag - 17.14) * 1.8)
& (rmag - w1mag > (w1mag - 16.33) * 1.))
| (rmag - w1mag > 3.3)
) # double sliding cuts and high-z extension
else:
lrg &= zmag - w1mag > 0.8 * (rmag - zmag) - 0.6 # non-stellar cut
lrg &= zfibermag < 21.61 # faint limit
lrg &= (gmag - w1mag > 2.97) | (rmag - w1mag > 1.8) # low-z cuts
lrg &= (
((rmag - w1mag > (w1mag - 17.13) * 1.83)
& (rmag - w1mag > (w1mag - 16.31) * 1.))
| (rmag - w1mag > 3.4)
) # double sliding cuts and high-z extension
return lrg
def isELG(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None,
gfiberflux=None, gsnr=None, rsnr=None, zsnr=None,
gnobs=None, rnobs=None, znobs=None,
maskbits=None, south=True, primary=None):
"""Definition of ELG target classes. Returns a boolean array.
(see :func:`~desitarget.cuts.set_target_bits` for parameters).
Notes:
- Current version (03/27/21) is version 8 on `the SV3 wiki`_.
"""
if primary is None:
primary = np.ones_like(rflux, dtype='?')
nomask = notinELG_mask(
maskbits=maskbits, gsnr=gsnr, rsnr=rsnr, zsnr=zsnr,
gnobs=gnobs, rnobs=rnobs, znobs=znobs, primary=primary)
elgvlo, elg = isELG_colors(gflux=gflux, rflux=rflux, zflux=zflux,
w1flux=w1flux, w2flux=w2flux,
gfiberflux=gfiberflux, south=south,
primary=primary)
return elgvlo & nomask, elg & nomask
def notinELG_mask(maskbits=None, gsnr=None, rsnr=None, zsnr=None,
gnobs=None, rnobs=None, znobs=None, primary=None):
"""Standard set of masking cuts used by all ELG target selection classes.
(see :func:`~desitarget.cuts.set_target_bits` for parameters).
"""
if primary is None:
primary = np.ones_like(maskbits, dtype='?')
elg = primary.copy()
# ADM good signal-to-noise in all bands.
elg &= (gsnr > 0) & (rsnr > 0) & (zsnr > 0)
# ADM observed in every band.
elg &= (gnobs > 0) & (rnobs > 0) & (znobs > 0)
# ADM default mask bits from the Legacy Surveys not set.
elg &= imaging_mask(maskbits)
return elg
def isELG_colors(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None,
gfiberflux=None, rfiberflux=None, zfiberflux=None,
south=True, primary=None):
"""Color cuts for ELG target selection classes
(see, e.g., :func:`~desitarget.cuts.set_target_bits` for parameters).
"""
if primary is None:
primary = np.ones_like(rflux, dtype='?')
elg = primary.copy()
# ADM work in magnitudes instead of fluxes. NOTE THIS IS ONLY OK AS
# ADM the snr masking in ALL OF g, r AND z ENSURES positive fluxes.
g = 22.5 - 2.5*np.log10(gflux.clip(1e-16))
r = 22.5 - 2.5*np.log10(rflux.clip(1e-16))
z = 22.5 - 2.5*np.log10(zflux.clip(1e-16))
gfib = 22.5 - 2.5*np.log10(gfiberflux.clip(1e-16))
# ADM cuts shared by the northern and southern selections.
elg &= g > 20 # bright cut.
elg &= r - z > 0.15 # blue cut.
# elg &= r - z < 1.6 # red cut.
# ADM cuts that are unique to the north or south. Identical for sv3
# ADM but keep the north/south formalism in case we use it later.
if south:
elg &= gfib < 24.1 # faint cut.
elg &= g - r < 0.5*(r - z) + 0.1 # remove stars, low-z galaxies.
else:
elg &= gfib < 24.1 # faint cut.
elg &= g - r < 0.5*(r - z) + 0.1 # remove stars, low-z galaxies.
# ADM separate a low-priority and a regular sample.
elgvlo = elg.copy()
# ADM low-priority OII flux cut.
elgvlo &= g - r < -1.2*(r - z) + 1.6
elgvlo &= g - r >= -1.2*(r - z) + 1.3
# ADM high-priority OII flux cut.
elg &= g - r < -1.2*(r - z) + 1.3
return elgvlo, elg
def isSTD_colors(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None,
primary=None, south=True):
"""Select STD stars based on Legacy Surveys. Returns a boolean array.
Args:
gflux, rflux, zflux, w1flux, w2flux: array_like
The flux in nano-maggies of g, r, z, w1, and w2 bands.
primary: array_like or None
Set to ``True`` for objects to consider as possible STDs.
Defaults to everything being ``True``.
south: boolean, defaults to ``True``
Use color-cuts based on photometry from the "south" (DECaLS)
as opposed to the "north" (MzLS+BASS).
Returns:
mask : boolean array, True if the object has colors like a STD
star target.
Notes:
- Current version (08/01/18) is version 121 on `the wiki`_.
"""
if primary is None:
primary = np.ones_like(gflux, dtype='?')
std = primary.copy()
# Clip to avoid warnings from negative numbers.
# ADM we're pretty bright for the STDs, so this should be safe.
gflux = gflux.clip(1e-16)
rflux = rflux.clip(1e-16)
zflux = zflux.clip(1e-16)
# ADM optical colors for halo TO or bluer.
grcolor = 2.5 * np.log10(rflux / gflux)
rzcolor = 2.5 * np.log10(zflux / rflux)
# Currently no difference in north vs south color-cuts.
if south:
std &= rzcolor < 0.2
std &= grcolor > 0.
std &= grcolor < 0.35
else:
std &= rzcolor < 0.2
std &= grcolor > 0.
std &= grcolor < 0.35
return std
def isSTD_gaia(primary=None, gaia=None, astrometricexcessnoise=None,
pmra=None, pmdec=None, parallax=None,
dupsource=None, paramssolved=None,
gaiagmag=None, gaiabmag=None, gaiarmag=None):
"""Gaia quality cuts used to define STD star targets.
Args:
primary: array_like or None
Set to ``True`` for objects to consider as possible STDs.
Defaults to everything being ``True``.
gaia: boolean array_like or None
True if there is a match between this object in
`the Legacy Surveys`_ and in Gaia.
astrometricexcessnoise: array_like or None
Excess noise of the source in Gaia
pmra, pmdec, parallax: array_like or None
Gaia-based proper motion in RA and Dec and parallax
(same units as the Gaia data model).
dupsource: array_like or None
Whether the source is a duplicate in Gaia.
paramssolved: array_like or None
How many parameters were solved for in Gaia.
gaiagmag, gaiabmag, gaiarmag: array_like or None
Gaia-based g, b and r MAGNITUDES (not corrected for Galactic
extinction (same units as `the Gaia data model`_).
Returns:
mask : boolean array, True if the object passes Gaia quality cuts.
Notes:
- Current version (08/01/18) is version 121 on `the wiki`_.
"""
if primary is None:
primary = np.ones_like(gaiagmag, dtype='?')
std = primary.copy()
# ADM Bp and Rp are both measured.
std &= ~np.isnan(gaiabmag - gaiarmag)
# ADM no obvious issues with the astrometry solution.
std &= astrometricexcessnoise < 1
std &= paramssolved >= 31
# ADM finite proper motions.
std &= np.isfinite(pmra)
std &= np.isfinite(pmdec)
# ADM a parallax smaller than 1 mas.
std &= parallax < 1.
# ADM calculate the overall proper motion magnitude
pm = np.sqrt(pmra**2. + pmdec**2.)
# ADM a proper motion larger than 2 mas/yr.
std &= pm > 2.
# ADM fail if dupsource is not Boolean, as was the case for the 7.0
# ADM sweeps, otherwise logic checks on dupsource will be misleading.
if not (dupsource.dtype.type == np.bool_):
log.error('GAIA_DUPLICATED_SOURCE (dupsource) should be boolean!')
raise IOError
# ADM a unique Gaia source.
std &= ~dupsource
return std
def isSTD(gflux=None, rflux=None, zflux=None, primary=None,
gfracflux=None, rfracflux=None, zfracflux=None,
gfracmasked=None, rfracmasked=None, zfracmasked=None,
gnobs=None, rnobs=None, znobs=None,
gfluxivar=None, rfluxivar=None, zfluxivar=None, objtype=None,
gaia=None, astrometricexcessnoise=None, paramssolved=None,
pmra=None, pmdec=None, parallax=None, dupsource=None,
gaiagmag=None, gaiabmag=None, gaiarmag=None, bright=False,
usegaia=True, maskbits=None, south=True):
"""Select STD targets using color, photometric quality cuts (PSF-like
and fracflux). See isSTD_colors() for additional info.
Args:
gflux, rflux, zflux: array_like
The flux in nano-maggies of g, r, z bands.
primary: array_like or None
``True`` for possible targets. Defaults to ``True`` for all.
gfracflux, rfracflux, zfracflux: array_like
Profile-weighted fraction of the flux from other sources
divided by the total flux in g, r and z bands.
gfracmasked, rfracmasked, zfracmasked: array_like
Fraction of masked pixels in the g, r and z bands.
gnobs, rnobs, znobs: array_like
Number of observations (in the central pixel) in g, r and z.
gfluxivar, rfluxivar, zfluxivar: array_like
The flux inverse variances in g, r, and z bands.
objtype: array_like or None
TYPE column of the catalogue to restrict to point sources.
gaia: boolean array_like or None
True if there is a match between this object in
`the Legacy Surveys`_ and in Gaia.
astrometricexcessnoise: array_like or None
Excess noise of the source in Gaia.
paramssolved: array_like or None
How many parameters were solved for in Gaia.
pmra, pmdec, parallax: array_like or None
Gaia-based proper motion in RA and Dec and parallax
dupsource: array_like or None
Whether the source is a duplicate in Gaia.
gaiagmag, gaiabmag, gaiarmag: array_like or None
Gaia-based g-, b- and r-band MAGNITUDES.
bright: boolean, defaults to ``False``
if ``True`` apply mag cuts for "bright" conditions; otherwise,
for "dark" conditions. Cut is performed on `gaiagmag`.
usegaia: boolean, defaults to ``True``
if ``True`` then call :func:`~desitarget.cuts.isSTD_gaia` to
set the logic cuts. If Gaia is not available (perhaps if
you're using mocks) then send ``False``, in which case we use
the LS r-band as a proxy for Gaia G. ``False`` ignores that we
have already corrected for Galactic extinction (incorrectly).
south: boolean, defaults to ``True``
Use color-cuts based on photometry from the "south" (DECaLS)
as opposed to the "north" (MzLS+BASS).
Returns:
mask : boolean array, True if the object has colors like a STD.
Notes:
- Gaia-based quantities are as in `the Gaia data model`_.
- Current version (02/18/21) is version 246 on `the wiki`_.
"""
if primary is None:
primary = np.ones_like(gflux, dtype='?')
std = primary.copy()
# ADM apply the Legacy Surveys (optical) magnitude and color cuts.
std &= isSTD_colors(primary=primary, zflux=zflux, rflux=rflux, gflux=gflux,
south=south)
# ADM apply the Gaia quality cuts.
if usegaia:
std &= isSTD_gaia(primary=primary, gaia=gaia,
astrometricexcessnoise=astrometricexcessnoise,
pmra=pmra, pmdec=pmdec, parallax=parallax,
dupsource=dupsource, paramssolved=paramssolved,
gaiagmag=gaiagmag, gaiabmag=gaiabmag, gaiarmag=gaiarmag)
# ADM apply type=PSF cut
std &= _psflike(objtype)
# ADM don't target standards in Legacy Surveys mask regions.
std &= imaging_mask(maskbits, mwsmask=True)
# ADM apply fracflux, S/N cuts and number of observations cuts.
fracflux = [gfracflux, rfracflux, zfracflux]
fluxivar = [gfluxivar, rfluxivar, zfluxivar]
nobs = [gnobs, rnobs, znobs]
fracmasked = [gfracmasked, rfracmasked, zfracmasked]
with warnings.catch_warnings():
warnings.simplefilter('ignore') # fracflux can be Inf/NaN
for bandint in (0, 1, 2): # g, r, z
std &= fracflux[bandint] < 0.01
std &= fluxivar[bandint] > 0
std &= nobs[bandint] > 0
std &= fracmasked[bandint] < 0.6
# ADM brightness cuts in Gaia G-band
if bright:
gbright = 16.
gfaint = 18.
else:
gbright = 16.
gfaint = 19.
if usegaia:
std &= gaiagmag >= gbright
std &= gaiagmag < gfaint
else:
# Use LS r-band as a Gaia G-band proxy.
gaiamag_proxy = 22.5 - 2.5 * np.log10(rflux.clip(1e-16))
std &= gaiamag_proxy >= gbright
std &= gaiamag_proxy < gfaint
return std
def isMWS_main(gflux=None, rflux=None, zflux=None, w1flux=None, w2flux=None,
gnobs=None, rnobs=None, gfracmasked=None, rfracmasked=None,
pmra=None, pmdec=None, parallax=None, parallaxerr=None,
obs_rflux=None, objtype=None, gaia=None,
gaiagmag=None, gaiabmag=None, gaiarmag=None,
gaiaaen=None, gaiadupsource=None, paramssolved=None,
primary=None, south=True, maskbits=None):
"""Set bits for main ``MWS`` targets.
Args:
see :func:`~desitarget.cuts.set_target_bits` for parameters.
Returns:
mask1 : array_like.
``True`` if the object is a ``MWS_BROAD`` target.
mask2 : array_like.
``True`` if the object is a ``MWS_MAIN_RED`` target.
mask3 : array_like.
``True`` if the object is a ``MWS_MAIN_BLUE`` target.
mask4 : array_like.
``True`` if the object is a ``MWS_FAINT_RED`` target.
mask5 : array_like.
``True`` if the object is a ``MWS_FAINT_BLUE`` target.
Notes:
- Current version (05/04/21) is version 256 on `the wiki`_.
"""
if primary is None:
primary = np.ones_like(gaia, dtype='?')
mws = primary.copy()
# ADM currently no difference between N/S for MWS, so easiest
# ADM just to use one selection
# if south:
mws &= notinMWS_main_mask(gaia=gaia, gfracmasked=gfracmasked, gnobs=gnobs,
gflux=gflux, rfracmasked=rfracmasked, rnobs=rnobs,
rflux=rflux, gaiadupsource=gaiadupsource,
primary=primary, maskbits=maskbits)
# APC Copy cuts up to this point for later use in faint selection
mws_faint = mws.copy()
# ADM pass the mws that pass cuts as primary, to restrict to the
# ADM sources that weren't in a mask/logic cut.
mws, red, blue = isMWS_main_colors(
gflux=gflux, rflux=rflux, zflux=zflux, w1flux=w1flux, w2flux=w2flux,
pmra=pmra, pmdec=pmdec, parallax=parallax, parallaxerr=parallaxerr,
obs_rflux=obs_rflux, objtype=objtype, gaiagmag=gaiagmag,
gaiabmag=gaiabmag, gaiarmag=gaiarmag, gaiaaen=gaiaaen,
paramssolved=paramssolved, primary=mws, south=south
)
faint_red, faint_blue = isMWS_faint_colors(
gflux=gflux, rflux=rflux, zflux=zflux, w1flux=w1flux, w2flux=w2flux,
pmra=pmra, pmdec=pmdec, parallax=parallax, parallaxerr=parallaxerr,
obs_rflux=obs_rflux, objtype=objtype, gaiagmag=gaiagmag,
gaiabmag=gaiabmag, gaiarmag=gaiarmag, gaiaaen=gaiaaen,
paramssolved=paramssolved, primary=mws_faint, south=south
)
return mws, red, blue, faint_red, faint_blue
def notinMWS_main_mask(gaia=None, gfracmasked=None, gnobs=None, gflux=None,
rfracmasked=None, rnobs=None, rflux=None, maskbits=None,
gaiadupsource=None, primary=None):
"""Standard set of masking-based cuts used by MWS target classes
(see, e.g., :func:`~desitarget.cuts.isMWS_main` for parameters).
"""
if primary is None:
primary = np.ones_like(gaia, dtype='?')
mws = primary.copy()
# ADM don't target MWS-like targets in Legacy Surveys mask regions.
mws &= imaging_mask(maskbits, mwsmask=True)
# ADM apply the mask/logic selection for all MWS-MAIN targets
# ADM main targets match to a Gaia source
mws &= gaia