Skip to content

Commit

Permalink
ruff and docstrings
Browse files Browse the repository at this point in the history
ruff cleanup

ruff and docstrings in metric_bundles

Ruff and docstrings
  • Loading branch information
rhiannonlynne committed Feb 27, 2024
1 parent 3c8330e commit ea45bf0
Show file tree
Hide file tree
Showing 49 changed files with 1,558 additions and 1,276 deletions.
1 change: 0 additions & 1 deletion rubin_sim/maf/maf_contrib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
from .tdes_pop_metric import *
from .triplet_metric import *
from .var_depth_metric import *
from .var_metrics import *
from .xrb_metrics import *
from .young_stellar_objects_metric import *
from .calculate_lsst_field_visibility_astropy import *
3 changes: 2 additions & 1 deletion rubin_sim/maf/maf_contrib/lss_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@


class GalaxyCountsMetric(BaseMetric):
"""Estimate the number of galaxies expected at a particular coadded depth.
"""Estimate the number of galaxies expected at a particular (extragalactic)
coadded depth.
"""

def __init__(self, m5_col="fiveSigmaDepth", nside=128, metric_name="GalaxyCounts", **kwargs):
Expand Down
5 changes: 0 additions & 5 deletions rubin_sim/maf/maf_contrib/lss_obs_strategy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
from .alm_plots import *
from .artificial_structure_calculation import *
from .coadd_m5_analysis import *
from .constants_for_pipeline import *
from .galaxy_counts_metric_extended import *
from .galaxy_counts_with_pixel_calibration import *
from .masking_algorithm_generalized import *
from .os_bias_analysis import *
140 changes: 79 additions & 61 deletions rubin_sim/maf/maf_contrib/lv_dwarfs/lv_dwarfs_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import os

import astropy.units as u
import healpy as hp
import numpy as np
from astropy.coordinates import SkyCoord
from astropy.io import ascii, fits
Expand All @@ -20,13 +19,14 @@


def generate_known_lv_dwarf_slicer():
"""Read the Karachentsev+ catalog of nearby galaxies, and put the info about them
into a UserPointSlicer object.
"""Read the Karachentsev+ catalog of nearby galaxies,
and put the info about them into a UserPointSlicer object.
"""
filename = os.path.join(get_data_dir(), "maf/lvdwarfs", "lsst_galaxies_1p25to9Mpc_table.fits")
lv_dat0 = fits.getdata(filename)

# Keep only galaxies at dec < 35 deg., and with stellar masses > 10^7 M_Sun (and <1e14).
# Keep only galaxies at dec < 35 deg.,
# and with stellar masses > 10^7 M_Sun (and <1e14).
lv_dat_cuts = (lv_dat0["dec"] < 35.0) & (lv_dat0["MStars"] > 1e7) & (lv_dat0["MStars"] < 1e14)
lv_dat = lv_dat0[lv_dat_cuts]

Expand All @@ -38,11 +38,13 @@ def generate_known_lv_dwarf_slicer():
return slicer


# make a simulated LF for old galaxy of given integrated B, distance modulus mu, in any of filters ugrizY
# make a simulated LF for old galaxy of given integrated B,
# distance modulus mu, in any of filters ugrizY
def make__fake_old_galaxy_lf(int_b, mu, filtername):
"""
Make a simulated luminosity function for an old (10 Gyr) dwarf galaxy of given
integrated B magnitude, at a given distance modulus, in any of the filters ugrizY.
Make a simulated luminosity function for an old (10 Gyr) dwarf
galaxy of given integrated B magnitude, at a given distance modulus,
in any of the filters ugrizy.
Parameters
----------
Expand All @@ -56,7 +58,8 @@ def make__fake_old_galaxy_lf(int_b, mu, filtername):
if filtername == "y":
filtername == "Y"
model_bmag = 6.856379 # integrated B mag of the model LF being read
# Read a simulated luminosity function of [M/H]=-1.5, 10 Gyr stellar population:
# Read a simulated luminosity function of [M/H]=-1.5, 10 Gyr stellar
# population:
filename = os.path.join(get_data_dir(), "maf/lvdwarfs", "LF_-1.5_10Gyr.dat")
LF = ascii.read(filename, header_start=12)
mags = LF["magbinc"]
Expand All @@ -73,8 +76,8 @@ def make__fake_old_galaxy_lf(int_b, mu, filtername):
def make_dwarf_lf_dicts():
"""
Create dicts containing g- and i-band LFs for simulated dwarfs between
-10 < M_B < +3, so they can simply be looked up rather than having to
recreate them each time. Dict is keyed on M_B value.
-10 < M_B < +3, so they can simply be looked up rather than having to
recreate them each time. Dict is keyed on M_B value.
"""
lf_dict_i = {}
lf_dict_g = {}
Expand All @@ -96,14 +99,15 @@ def _sum_luminosity(l_fmags, l_fcounts):
"""
Sum the luminosities from a given luminosity function.
Uses the first bin's magnitude as a reference, sums luminosities relative to
that reference star, then converts back to magnitude at the end.
Uses the first bin's magnitude as a reference, sums luminosities
relative to that reference star,
then converts back to magnitude at the end.
Parameters
----------
l_fmags : np.array, `float`
l_fmags : `np.array,` `float`
Magnitude bin values from the simulated LF.
l_fcounts : np.array, `int`
l_fcounts : `np.array`, `int`
Number of stars in each magnitude bin.
"""
magref = l_fmags[0]
Expand Down Expand Up @@ -156,20 +160,21 @@ def _dwarf_sblimit(glim, ilim, nstars, lf_dict_g, lf_dict_i, distlim, rng):
g_l_fmags0, g_l_fcounts0 = lf_dict_g[mbkey]
i_l_fcounts = rng.poisson(i_l_fcounts0)
g_l_fcounts = rng.poisson(g_l_fcounts0)
i_l_fmags = i_l_fmags0 + distmod_lim # Add the distance modulus to make it apparent mags
g_l_fmags = g_l_fmags0 + distmod_lim # Add the distance modulus to make it apparent mags
# print(i_l_fcounts0-i_l_fcounts)
# Add the distance modulus to make it apparent mags
i_l_fmags = i_l_fmags0 + distmod_lim
# Add the distance modulus to make it apparent mags
g_l_fmags = g_l_fmags0 + distmod_lim
gsel = g_l_fmags <= glim
isel = i_l_fmags <= ilim
ng = np.sum(g_l_fcounts[gsel])
ni = np.sum(i_l_fcounts[isel])
# print('fake_mb: ',fake_mb, ' ng: ',ng, ' ni: ', ni, ' nstars: ', nstars)
fake_mb += 0.1

if fake_mb > -9.9 and (ng > 0) and (ni > 0):
gmag_tot = _sum_luminosity(g_l_fmags[gsel], g_l_fcounts[gsel]) - distmod_lim
imag_tot = _sum_luminosity(i_l_fmags[isel], i_l_fcounts[isel]) - distmod_lim
# S = m + 2.5logA, where in this case things are in sq. arcmin, so A = 1 arcmin^2 = 3600 arcsec^2
# S = m + 2.5logA, where in this case things are in sq. arcmin,
# so A = 1 arcmin^2 = 3600 arcsec^2
sbtot_g = distmod_lim + gmag_tot + 2.5 * np.log10(3600.0)
sbtot_i = distmod_lim + imag_tot + 2.5 * np.log10(3600.0)
mg_lim = gmag_tot
Expand Down Expand Up @@ -198,35 +203,39 @@ def _dwarf_sblimit(glim, ilim, nstars, lf_dict_g, lf_dict_i, distlim, rng):

class LVDwarfsMetric(BaseMetric):
"""
Estimate the detection limit in total dwarf luminosity for resolved dwarf galaxies
at a given distance.
Estimate the detection limit in total dwarf luminosity for
resolved dwarf galaxies at a given distance.
This metric class uses simulated luminosity functions of dwarf galaxies with
known (assumed) luminosities to estimate the detection limit (in total dwarf
luminosity, M_V) for resolved dwarf galaxies at a given distance. It can be
applied to either known galaxies with their discrete positions and distances,
or an entire survey simulation with a fixed distance limit.
This metric class uses simulated luminosity functions of dwarf galaxies
with known (assumed) luminosities to estimate the detection limit
(in total dwarf luminosity, M_V) for resolved dwarf galaxies at a
given distance. It can be applied to either known galaxies with their
discrete positions and distances, or an entire survey simulation with
a fixed distance limit.
In the default use (with the KnownLvDwarfsSlicer), it returns detection limits for
a catalog of known local volume dwarfs, from the Karachentsev+ catalog of nearby galaxies.
In the default use (with the KnownLvDwarfsSlicer),
it returns detection limits for a catalog of known local volume dwarfs,
from the Karachentsev+ catalog of nearby galaxies.
Parameters
----------
radius : `float`, default=2.45,
Radius of the field being considered (for discrete fields only). By default,
UserPointSlicer uses a 2.45-deg field radius.
distlim : `float`,
Distance threshold in Mpc for which to calculate the limiting dwarf detection
luminosity. Only needed for healpix slicers, but *required* if healpix is used.
cmd_frac : `float`, default=0.1,
Fraction of the total area of the color-magnitude diagram that is spanned
by the tracer selection criteria. (e.g., the size of a box in color and
magnitude to select RGB-star candidates)
stargal_contamination : `float`, default=0.4,
Fraction of objects in CMD selection region that are actually unresolved
galaxies that were mis-classified as stars.
nsigma : `float`, default=10.0,
Required detection significance to declare a simulated dwarf "detected."
radius : `float`
Radius of the field being considered (for discrete fields only).
By default, UserPointSlicer uses a 2.45-deg field radius.
distlim : `float`
Distance threshold in Mpc for which to calculate the limiting
dwarf detection luminosity. Only needed for healpix slicers,
but *required* if healpix is used.
cmd_frac : `float`
Fraction of the total area of the color-magnitude diagram
that is spanned by the tracer selection criteria. (e.g.,
the size of a box in color and magnitude to select RGB-star candidates)
stargal_contamination : `float`
Fraction of objects in CMD selection region that are actually
unresolved galaxies that were mis-classified as stars.
nsigma : `float`
Required detection significance to declare a simulated
dwarf "detected."
"""

def __init__(
Expand Down Expand Up @@ -256,7 +265,8 @@ def __init__(
self.distlim = None
filename = os.path.join(get_data_dir(), "maf/lvdwarfs", "lsst_galaxies_1p25to9Mpc_table.fits")
lv_dat0 = fits.getdata(filename)
# Keep only galaxies at dec < 35 deg., and with stellar masses > 10^7 M_Sun.
# Keep only galaxies at dec < 35 deg.,
# and with stellar masses > 10^7 M_Sun.
lv_dat_cuts = (lv_dat0["dec"] < 35.0) & (lv_dat0["MStars"] > 1e7) & (lv_dat0["MStars"] < 1e14)
lv_dat = lv_dat0[lv_dat_cuts]
sc_dat = SkyCoord(
Expand All @@ -281,11 +291,13 @@ def __init__(
self.galaxy_counts_metric.scale = 1

cols = [self.m5_col, self.filter_col]
# GalaxyCountsMetric needs the DustMap, and StarDensityMetric needs StellarDensityMap:
# GalaxyCountsMetric needs the DustMap,
# and StarDensityMetric needs StellarDensityMap:
maps = ["DustMap", "StellarDensityMap"]
super().__init__(col=cols, metric_name=metric_name, maps=maps, units="M_V limit", **kwargs)

# Set up a random number generator, so that metric results are repeatable
# Set up a random number generator,
# so that metric results are repeatable
self.rng = np.random.default_rng(seed)

def run(self, data_slice, slice_point=None):
Expand All @@ -296,16 +308,19 @@ def run(self, data_slice, slice_point=None):
if len(np.where(gband)[0]) == 0 or len(np.where(iband)[0]) == 0:
return self.badval

# calculate the dust-extincted coadded 5-sigma limiting mags in the g and i bands:
# calculate the dust-extincted coadded 5-sigma limiting mags
# in the g and i bands:
g5 = self.exgal_coaddm5.run(data_slice[gband], slice_point)
i5 = self.exgal_coaddm5.run(data_slice[iband], slice_point)

if g5 < 15 or i5 < 15:
# If the limiting magnitudes won't even match the stellar density maps, exit
# If the limiting magnitudes won't even match the
# stellar density maps, exit
return self.badval

# Find the number of stars per sq arcsecond at the i band limit
# (this is a bit of a hack to get the starDensityMetric to calculate the nstars at this mag exactly)
# (this is a bit of a hack to get the starDensityMetric to
# calculate the nstars at this mag exactly)
star_i5 = min(27.9, i5)
self.star_density_metric.magLimit = star_i5

Expand All @@ -315,21 +330,25 @@ def run(self, data_slice, slice_point=None):
ngal_sqdeg = self.galaxy_counts_metric.run(data_slice, slice_point)
# GalaxyCountsMetric is undefined in some places. These cases return
# zero; catch these and set the galaxy counts in those regions to a
# very high value. (this may not be true after catching earlier no-visits issues)
# very high value. (this may not be true after catching earlier
# no-visits issues)
if ngal_sqdeg < 10.0:
ngal_sqdeg = 1e7

# Convert from per sq deg and per sq arcsecond into #'s per sq arcminute
# Convert from per sq deg and per sq arcsecond
# into #'s per sq arcminute
ngal_sqarcmin = ngal_sqdeg / 3600
nstar_sqarcmin = nstar_sqarcsec * 3600

if ngal_sqarcmin < 0 or nstar_sqarcmin < 0:
print(
f"Here be a problem - ngals_sqarcmin {ngal_sqarcmin} or nstar_sqarcmin {nstar_sqarcmin} "
f'are negative. depths: {g5}, {i5}. {slice_point["ra"], slice_point["dec"], slice_point["sid"]}'
f'are negative. depths: {g5}, {i5}. '
f'{slice_point["ra"], slice_point["dec"], slice_point["sid"]}'
)
# The number of stars required to reach nsigma is nsigma times the Poisson
# fluctuations of the background (stars+galaxies contamination):
# The number of stars required to reach nsigma is
# nsigma times the Poisson fluctuations of the background
# (stars+galaxies contamination):
nstars_required = self.nsigma * np.sqrt(
(ngal_sqarcmin * self.cmd_frac * self.stargal_contamination) + (nstar_sqarcmin * self.cmd_frac)
)
Expand All @@ -338,13 +357,12 @@ def run(self, data_slice, slice_point=None):
# Use the distlim if a healpix slicer is input
distlim = self.distlim
else:
# Use discrete distances for known galaxies if a UserPointSlicer:
# Use discrete distances for known galaxies if a
# UserPointSlicer:
distlim = slice_point["distance"] * u.Mpc
# sc_slice = SkyCoord(ra=slice_point['ra']*u.rad, dec=slice_point['dec']*u.rad)
# seps = sc_slice.separation(self.sc_dat)
# distlim = self.sc_dat[seps.argmin()].distance

# Calculate the limiting luminosity and surface brightness based on g5 and i5:
# Calculate the limiting luminosity and surface brightness
# based on g5 and i5:
mg_lim, mi_lim, sb_g_lim, sb_i_lim, flag_lim = _dwarf_sblimit(
g5,
i5,
Expand All @@ -359,8 +377,8 @@ def run(self, data_slice, slice_point=None):
mv = self.badval

else:
# To go from HSC g and i bands to V, use the conversion from Appendix A
# of Komiyama+2018, ApJ, 853, 29:
# To go from HSC g and i bands to V, use the conversion
# from Appendix A of Komiyama+2018, ApJ, 853, 29:
# V = g_hsc - 0.371*(gi_hsc)-0.068
mv = mg_lim - 0.371 * (mg_lim - mi_lim) - 0.068
# sbv = sb_g_lim - 0.371 * (sb_g_lim - sb_i_lim) - 0.068
Expand Down
Loading

0 comments on commit ea45bf0

Please sign in to comment.