diff --git a/.github/workflows/ci_tests.yml b/.github/workflows/ci_tests.yml index 368907f63..b3d928045 100644 --- a/.github/workflows/ci_tests.yml +++ b/.github/workflows/ci_tests.yml @@ -3,7 +3,7 @@ name: CI Tests on: push: branches: - - master + - main pull_request: env: diff --git a/docs/api/analysis.kcwi.rst b/docs/api/analysis.kcwi.rst new file mode 100644 index 000000000..09c0e166b --- /dev/null +++ b/docs/api/analysis.kcwi.rst @@ -0,0 +1,13 @@ +frb.analysis.kcwi +================= + +.. automodule:: frb.analysis.kcwi + +.. note:: + Optional dependencies: ``pyregion`` and ``spectral-cube`` are required + for full KCWI functionality. + +.. note:: + Member-level API expansion is intentionally omitted here because several + upstream function docstrings are not valid reStructuredText and trigger + docutils parse errors during ``make html``. diff --git a/docs/api/analysis.rst b/docs/api/analysis.rst new file mode 100644 index 000000000..3f3814ce8 --- /dev/null +++ b/docs/api/analysis.rst @@ -0,0 +1,15 @@ +frb.analysis +============ + +.. automodule:: frb.analysis + :members: + :undoc-members: + :show-inheritance: + +Submodules +---------- + +.. toctree:: + :maxdepth: 1 + + analysis.kcwi diff --git a/docs/api/associate.frbassociate.rst b/docs/api/associate.frbassociate.rst new file mode 100644 index 000000000..2276d46bb --- /dev/null +++ b/docs/api/associate.frbassociate.rst @@ -0,0 +1,8 @@ +frb.associate.frbassociate +========================== + +.. automodule:: frb.associate.frbassociate + +.. note:: + Member-level API expansion is intentionally omitted here to keep + ``make html`` stable with current upstream docstring formatting. diff --git a/docs/api/associate.frbs.rst b/docs/api/associate.frbs.rst new file mode 100644 index 000000000..e071526e6 --- /dev/null +++ b/docs/api/associate.frbs.rst @@ -0,0 +1,7 @@ +frb.associate.frbs +================== + +.. automodule:: frb.associate.frbs + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/associate.gen_pox_table.rst b/docs/api/associate.gen_pox_table.rst new file mode 100644 index 000000000..9b2b4d333 --- /dev/null +++ b/docs/api/associate.gen_pox_table.rst @@ -0,0 +1,7 @@ +frb.associate.gen_pox_table +=========================== + +.. automodule:: frb.associate.gen_pox_table + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/associate.rst b/docs/api/associate.rst index 12ca778ed..a098b4b95 100644 --- a/docs/api/associate.rst +++ b/docs/api/associate.rst @@ -9,18 +9,9 @@ frb.associate - FRB-Galaxy Association Submodules ---------- -frb.associate.frbassociate - FRBAssociate Class -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. toctree:: + :maxdepth: 1 -.. automodule:: frb.associate.frbassociate - :members: - :undoc-members: - :show-inheritance: - -frb.associate.frbs - FRB Association Data -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.associate.frbs - :members: - :undoc-members: - :show-inheritance: + associate.frbassociate + associate.frbs + associate.gen_pox_table diff --git a/docs/api/builds.build_fg.rst b/docs/api/builds.build_fg.rst new file mode 100644 index 000000000..56ebdc8ea --- /dev/null +++ b/docs/api/builds.build_fg.rst @@ -0,0 +1,7 @@ +frb.builds.build_fg +=================== + +.. automodule:: frb.builds.build_fg + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/builds.build_frbs.rst b/docs/api/builds.build_frbs.rst new file mode 100644 index 000000000..b74320a61 --- /dev/null +++ b/docs/api/builds.build_frbs.rst @@ -0,0 +1,7 @@ +frb.builds.build_frbs +===================== + +.. automodule:: frb.builds.build_frbs + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/builds.build_hosts.rst b/docs/api/builds.build_hosts.rst new file mode 100644 index 000000000..269f989b3 --- /dev/null +++ b/docs/api/builds.build_hosts.rst @@ -0,0 +1,7 @@ +frb.builds.build_hosts +====================== + +.. automodule:: frb.builds.build_hosts + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/builds.build_path.rst b/docs/api/builds.build_path.rst new file mode 100644 index 000000000..83e2d0d59 --- /dev/null +++ b/docs/api/builds.build_path.rst @@ -0,0 +1,7 @@ +frb.builds.build_path +===================== + +.. automodule:: frb.builds.build_path + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/builds.build_specdb.rst b/docs/api/builds.build_specdb.rst new file mode 100644 index 000000000..cfcb7064b --- /dev/null +++ b/docs/api/builds.build_specdb.rst @@ -0,0 +1,10 @@ +frb.builds.build_specdb +======================= + +.. automodule:: frb.builds.build_specdb + :members: + :undoc-members: + :show-inheritance: + +.. note:: + Optional dependency: ``specdb`` is required to build spectroscopic databases. diff --git a/docs/api/builds.old_build_frbs.rst b/docs/api/builds.old_build_frbs.rst new file mode 100644 index 000000000..91bdbccbb --- /dev/null +++ b/docs/api/builds.old_build_frbs.rst @@ -0,0 +1,8 @@ +frb.builds.old_build_frbs +========================= + +.. automodule:: frb.builds.old_build_frbs + +.. note:: + Member-level API expansion is intentionally omitted here to avoid + docstring parsing warnings in the current codebase. diff --git a/docs/api/builds.old_build_hosts.rst b/docs/api/builds.old_build_hosts.rst new file mode 100644 index 000000000..ccd6bc7e6 --- /dev/null +++ b/docs/api/builds.old_build_hosts.rst @@ -0,0 +1,7 @@ +frb.builds.old_build_hosts +========================== + +.. automodule:: frb.builds.old_build_hosts + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/builds.rst b/docs/api/builds.rst new file mode 100644 index 000000000..2e30698ef --- /dev/null +++ b/docs/api/builds.rst @@ -0,0 +1,22 @@ +frb.builds +========== + +.. automodule:: frb.builds + :members: + :undoc-members: + :show-inheritance: + +Submodules +---------- + +.. toctree:: + :maxdepth: 1 + + builds.build_fg + builds.build_frbs + builds.build_hosts + builds.build_path + builds.build_specdb + builds.utils + builds.old_build_frbs + builds.old_build_hosts diff --git a/docs/api/builds.utils.rst b/docs/api/builds.utils.rst new file mode 100644 index 000000000..d8901b744 --- /dev/null +++ b/docs/api/builds.utils.rst @@ -0,0 +1,7 @@ +frb.builds.utils +================ + +.. automodule:: frb.builds.utils + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/defs.rst b/docs/api/defs.rst new file mode 100644 index 000000000..07fcebce6 --- /dev/null +++ b/docs/api/defs.rst @@ -0,0 +1,7 @@ +frb.defs +======== + +.. automodule:: frb.defs + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/dm.cosmic.rst b/docs/api/dm.cosmic.rst new file mode 100644 index 000000000..99ddb2ef3 --- /dev/null +++ b/docs/api/dm.cosmic.rst @@ -0,0 +1,7 @@ +frb.dm.cosmic +============= + +.. automodule:: frb.dm.cosmic + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/dm.dm_ism_healpix_map.rst b/docs/api/dm.dm_ism_healpix_map.rst new file mode 100644 index 000000000..346f85616 --- /dev/null +++ b/docs/api/dm.dm_ism_healpix_map.rst @@ -0,0 +1,7 @@ +frb.dm.dm_ism_healpix_map +========================= + +.. automodule:: frb.dm.dm_ism_healpix_map + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/dm.host.rst b/docs/api/dm.host.rst new file mode 100644 index 000000000..4a7f27d4f --- /dev/null +++ b/docs/api/dm.host.rst @@ -0,0 +1,7 @@ +frb.dm.host +=========== + +.. automodule:: frb.dm.host + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/dm.igm.rst b/docs/api/dm.igm.rst new file mode 100644 index 000000000..141945266 --- /dev/null +++ b/docs/api/dm.igm.rst @@ -0,0 +1,8 @@ +frb.dm.igm +========== + +.. automodule:: frb.dm.igm + +.. note:: + Member-level API expansion is intentionally omitted here to avoid + docstring parsing warnings from legacy formatting. diff --git a/docs/api/dm.mcmc.rst b/docs/api/dm.mcmc.rst new file mode 100644 index 000000000..e528f3770 --- /dev/null +++ b/docs/api/dm.mcmc.rst @@ -0,0 +1,7 @@ +frb.dm.mcmc +=========== + +.. automodule:: frb.dm.mcmc + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/dm.prob_dmz.rst b/docs/api/dm.prob_dmz.rst new file mode 100644 index 000000000..7918c89b8 --- /dev/null +++ b/docs/api/dm.prob_dmz.rst @@ -0,0 +1,7 @@ +frb.dm.prob_dmz +=============== + +.. automodule:: frb.dm.prob_dmz + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/dm.rst b/docs/api/dm.rst index 30d5426c9..471456ca9 100644 --- a/docs/api/dm.rst +++ b/docs/api/dm.rst @@ -1,414 +1,27 @@ frb.dm - Dispersion Measure Module =================================== -The ``frb.dm`` module provides comprehensive tools for calculating and modeling dispersion measure contributions from various sources along the line of sight to Fast Radio Bursts. +The ``frb.dm`` package provides tools for estimating and modeling DM +contributions from the IGM, host galaxy, and related components. -.. currentmodule:: frb.dm - -Module Overview ---------------- - -The dispersion measure (DM) is a key observable for FRBs, representing the integrated electron column density along the line of sight: - -.. math:: - - \text{DM} = \int_0^{d} n_e(l) \, dl - -This module decomposes the total DM into contributions from: - -- **Milky Way**: Galactic disk and halo electrons -- **Intergalactic Medium (IGM)**: Diffuse cosmic electrons -- **Host Galaxy**: Electrons in the FRB host galaxy -- **Intervening Systems**: Galaxy halos and other structures - -Submodules ----------- - -The DM package contains the following submodules: - -* ``frb.dm.igm`` - Intergalactic Medium calculations -* ``frb.dm.cosmic`` - Cosmic dispersion measure modeling -* ``frb.dm.host`` - Host galaxy DM contributions -* ``frb.dm.mcmc`` - MCMC analysis methods -* ``frb.dm.prob_dmz`` - DM-redshift probability calculations -* ``frb.dm.dm_ism_healpix_map.py`` - DM_ISM Healpix map from NE2001 or the like - -frb.dm.igm - Intergalactic Medium -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.dm.igm +.. automodule:: frb.dm :members: :undoc-members: :show-inheritance: -Key Functions -^^^^^^^^^^^^^ - -.. autofunction:: frb.dm.igm.DM_cosmic - -.. autofunction:: frb.dm.igm.ne_cosmic - -.. autofunction:: frb.dm.igm.z_from_DM - -.. autofunction:: frb.dm.igm.DM_halos - -frb.dm.cosmic - Cosmic DM Modeling -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.dm.cosmic - :members: - :undoc-members: - :show-inheritance: - -frb.dm.host - Host Galaxy Contributions -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.dm.host - :members: - :undoc-members: - :show-inheritance: - -frb.dm.mcmc - MCMC Analysis -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.dm.mcmc - :members: - :undoc-members: - :show-inheritance: - -frb.dm.prob_dmz - DM-Redshift Probabilities -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.dm.prob_dmz - :members: - :undoc-members: - :show-inheritance: - -Detailed Function Documentation -------------------------------- - -IGM Functions -~~~~~~~~~~~~~ - -.. py:function:: ne_cosmic(z, cosmo=defs.frb_cosmo, mu=4./3) - - Calculate the average cosmic electron number density as a function of redshift. - - This function computes the physical number density of electrons in the universe, - accounting for the cosmic baryon density and ionization fraction. - - :param float z: Redshift - :param astropy.cosmology.Cosmology cosmo: Cosmology in which the calculations are performed - :param float mu: Reduced mass (default: 4/3 for fully ionized H and He) - :returns: Average physical number density of electrons in the universe - :rtype: astropy.units.Quantity - - **Example:** - - .. code-block:: python - - from frb.dm.igm import ne_cosmic - - # Calculate electron density at z=1 - z = 1.0 - n_e = ne_cosmic(z) - print(f"Electron density at z={z}: {n_e}") - -.. py:function:: DM_cosmic(z, cosmo=defs.frb_cosmo, cumul=False) - - Calculate the cosmic dispersion measure contribution. - - Integrates the cosmic electron density from z=0 to the specified redshift, - including corrections for cosmological expansion. - - :param float z: Redshift of the FRB - :param astropy.cosmology.Cosmology cosmo: Cosmology for calculations - :param bool cumul: Return cumulative DM evolution with redshift - :returns: Cosmic dispersion measure or array if cumul=True - :rtype: astropy.units.Quantity - - **Example:** - - .. code-block:: python - - from frb.dm.igm import DM_cosmic - - # Calculate cosmic DM to z=0.5 - z_frb = 0.5 - dm_cosmic = DM_cosmic(z_frb) - print(f"Cosmic DM to z={z_frb}: {dm_cosmic}") - -.. py:function:: z_from_DM(DM, cosmo=defs.frb_cosmo, coord=None, corr_nuisance=True) - - Estimate redshift from observed dispersion measure. - - Uses the cosmic DM-redshift relation to estimate the redshift of an FRB - given its observed dispersion measure, after correcting for Galactic - and other contributions. - - :param astropy.units.Quantity DM: Observed dispersion measure - :param astropy.cosmology.Cosmology cosmo: Cosmology - :param astropy.coordinates.SkyCoord coord: Sky coordinates (optional) - :param bool corr_nuisance: Apply corrections for nuisance parameters - :returns: Estimated redshift - :rtype: float - - **Example:** - - .. code-block:: python - - from frb.dm.igm import z_from_DM - from astropy import units as u - - # Estimate redshift from DM - DM_obs = 500 * u.pc / u.cm**3 - z_est = z_from_DM(DM_obs) - print(f"Estimated redshift: {z_est:.2f}") - -.. py:function:: DM_halos(z, cosmo, f_hot=0.75, rmax=2., logMmin=10.3, logMmax=16., neval=500, cumul=False) - - Calculate dispersion measure contribution from galaxy halos. - - Models the DM contribution from hot gas in galaxy halos along the - line of sight, using a halo mass function approach. - - :param float z: Redshift of the FRB - :param astropy.cosmology.Cosmology cosmo: Cosmology for calculations - :param float f_hot: Fraction of halo baryons in diffuse phase - :param float rmax: Size of halo in units of r200 - :param float logMmin: Log of minimum halo mass (cannot be much below 10.3) - :param float logMmax: Log of maximum halo mass (default: 10^16 Msun) - :param int neval: Number of redshift evaluation points - :param bool cumul: Return cumulative evaluation - :returns: DM contribution from halos - :rtype: astropy.units.Quantity - -Utility Functions -~~~~~~~~~~~~~~~~~ - -.. py:function:: f_diffuse(z, cosmo=defs.frb_cosmo, return_rho=False) - - Calculate the fraction of baryons in the diffuse IGM. - - :param float z: Redshift - :param astropy.cosmology.Cosmology cosmo: Cosmology - :param bool return_rho: Also return the diffuse gas density - :returns: Diffuse fraction (and density if requested) - :rtype: float or tuple - -.. py:function:: sigma_DM_cosmic(DM_cosmic, rel_err_Mstar=0.1) - - Calculate uncertainty in cosmic DM due to stellar mass uncertainties. - - :param astropy.units.Quantity DM_cosmic: Cosmic dispersion measure - :param float rel_err_Mstar: Relative error in stellar mass - :returns: DM uncertainty - :rtype: astropy.units.Quantity - -Physical Models ---------------- - -Ionization Models -~~~~~~~~~~~~~~~~~ - -The module includes models for cosmic reionization history: - -**Hydrogen Reionization:** -- Reionization redshift: z_HI ~ 6-8 -- Affects IGM electron fraction at high redshift - -**Helium Reionization:** -- HeII reionization: z_HeII ~ 3-4 -- Increases electron density at intermediate redshift - -**Implementation:** - -.. code-block:: python - - from frb.dm.igm import f_ionization_He - - # Calculate helium ionization fraction - z = 3.0 - f_He = f_ionization_He(z) - print(f"Helium ionization fraction at z={z}: {f_He}") - -Halo Models -~~~~~~~~~~~ - -Galaxy halo contributions use the halo mass function and hot gas profiles: - -**Key Parameters:** -- Halo mass range: 10^10.3 to 10^16 M_sun -- Hot gas fraction: ~75% of cosmic baryon fraction -- Radial extent: typically 2 × r200 - -**Scaling Relations:** -- Gas density profiles (e.g., beta models) -- Mass-temperature relations -- Feedback effects on gas distribution - -Usage Examples --------------- - -Basic DM Analysis -~~~~~~~~~~~~~~~~~ - -.. code-block:: python - - from frb.dm import igm - from astropy import units as u - - # Calculate total cosmic DM budget - z_max = 2.0 - dm_cosmic_total = igm.DM_cosmic(z_max) - - # Calculate contributions at different redshifts - redshifts = [0.1, 0.5, 1.0, 1.5, 2.0] - for z in redshifts: - dm_z = igm.DM_cosmic(z) - print(f"DM(z={z:.1f}) = {dm_z:.0f}") - -Redshift Estimation -~~~~~~~~~~~~~~~~~~~ - -.. code-block:: python - - from frb.dm.igm import z_from_DM - from astropy import units as u - from astropy.coordinates import SkyCoord - - # Observed FRB parameters - DM_obs = 750 * u.pc / u.cm**3 - coord = SkyCoord(ra=123.45*u.deg, dec=12.34*u.deg) - - # Estimate redshift - z_est = z_from_DM(DM_obs, coord=coord) - print(f"Estimated redshift: {z_est:.2f}") - - # Calculate expected cosmic DM at this redshift - dm_cosmic_expected = igm.DM_cosmic(z_est) - print(f"Expected cosmic DM: {dm_cosmic_expected:.0f}") - - # Calculate excess DM (host + local contributions) - dm_excess = DM_obs - dm_cosmic_expected - print(f"Excess DM: {dm_excess:.0f}") - -Halo Contribution Analysis -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code-block:: python - - from frb.dm.igm import DM_halos - from astropy.cosmology import Planck18 - - # Calculate halo DM contribution - z_frb = 1.0 - dm_halos = DM_halos(z_frb, Planck18) - - print(f"Halo DM contribution to z={z_frb}: {dm_halos:.1f}") - - # Compare different halo parameters - f_hot_values = [0.5, 0.75, 1.0] - for f_hot in f_hot_values: - dm_h = DM_halos(z_frb, Planck18, f_hot=f_hot) - print(f"Halo DM (f_hot={f_hot}): {dm_h:.1f}") - -Advanced Usage --------------- - -Custom Cosmologies -~~~~~~~~~~~~~~~~~~ - -.. code-block:: python - - from astropy.cosmology import FlatLambdaCDM - from frb.dm.igm import DM_cosmic - - # Define custom cosmology - custom_cosmo = FlatLambdaCDM(H0=70, Om0=0.3) - - # Compare DM calculations - z = 1.0 - dm_planck = DM_cosmic(z) # Default Planck18 - dm_custom = DM_cosmic(z, cosmo=custom_cosmo) - - print(f"DM (Planck18): {dm_planck:.0f}") - print(f"DM (Custom): {dm_custom:.0f}") - -Monte Carlo Analysis -~~~~~~~~~~~~~~~~~~~~ - -.. code-block:: python - - import numpy as np - from frb.dm.igm import z_from_DM - from astropy import units as u - - # Simulate DM uncertainties - DM_mean = 500 * u.pc / u.cm**3 - DM_err = 50 * u.pc / u.cm**3 - n_trials = 1000 - - # Generate DM samples - DM_samples = np.random.normal( - DM_mean.value, DM_err.value, n_trials - ) * DM_mean.unit - - # Calculate redshift distribution - z_samples = [z_from_DM(dm) for dm in DM_samples] - - z_mean = np.mean(z_samples) - z_std = np.std(z_samples) - print(f"Redshift: {z_mean:.2f} ± {z_std:.2f}") - -Error Handling --------------- - -The DM module includes robust error handling: - -.. code-block:: python - - from frb.dm.igm import z_from_DM - from astropy import units as u - - try: - # This might fail for very high DM values - z = z_from_DM(10000 * u.pc / u.cm**3) - except ValueError as e: - print(f"DM too high: {e}") - - try: - # This might fail for negative DM - z = z_from_DM(-100 * u.pc / u.cm**3) - except ValueError as e: - print(f"Invalid DM: {e}") - -Performance Notes ------------------ - -**Computational Efficiency:** -- DM calculations use vectorized numpy operations -- Cosmological integrals are cached for repeated calls -- Halo mass function integration is optimized for speed - -**Memory Usage:** -- Large redshift arrays may require significant memory -- Use ``cumul=False`` for single-point calculations -- Consider chunking for very large datasets - -**Accuracy:** -- Integration tolerances balance speed and precision -- Default parameters provide ~1% accuracy for most applications -- High-precision calculations may require custom tolerances +Submodules +---------- -See Also --------- +.. toctree:: + :maxdepth: 1 -- :doc:`../quickstart` - Quick start guide -- :doc:`../halos/index` - Halo modeling and DM contributions -- :doc:`galaxies` - Galaxy analysis tools + dm.cosmic + dm.dm_ism_healpix_map + dm.host + dm.igm + dm.mcmc + dm.prob_dmz .. note:: - The DM module assumes a standard cosmological model by default. - For non-standard cosmologies, explicitly pass the cosmology parameter - to relevant functions. \ No newline at end of file + Optional dependencies: ``pymc3`` is required for MCMC workflows in + ``frb.dm.mcmc``. diff --git a/docs/api/dm_kde.dm_frb_sim.rst b/docs/api/dm_kde.dm_frb_sim.rst new file mode 100644 index 000000000..7db51844a --- /dev/null +++ b/docs/api/dm_kde.dm_frb_sim.rst @@ -0,0 +1,9 @@ +frb.dm_kde.dm_frb_sim +===================== + +Simulation utilities for FRB DM distributions. + +.. note:: + This module executes a simulation at import time in the current implementation, + which makes it unsuitable for automatic API extraction via Sphinx autodoc. + Use the source file directly for now: ``frb/dm_kde/dm_frb_sim.py``. diff --git a/docs/api/dm_kde.pdf_fns.rst b/docs/api/dm_kde.pdf_fns.rst new file mode 100644 index 000000000..face58ad7 --- /dev/null +++ b/docs/api/dm_kde.pdf_fns.rst @@ -0,0 +1,7 @@ +frb.dm_kde.pdf_fns +================== + +.. automodule:: frb.dm_kde.pdf_fns + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/dm_kde.rst b/docs/api/dm_kde.rst new file mode 100644 index 000000000..ab6489f2c --- /dev/null +++ b/docs/api/dm_kde.rst @@ -0,0 +1,22 @@ +frb.dm_kde +========== + +This module family contains KDE and simulation utilities used in DM modeling. + +.. warning:: + ``frb.dm_kde`` currently has no package ``__init__.py``. Import submodules + directly (for example, ``import frb.dm_kde.dm_frb_sim``). + +.. note:: + Optional dependency: ``asymmetric_kde`` is required for parts of the DM KDE workflow. + +Submodules +---------- + +.. toctree:: + :maxdepth: 1 + + dm_kde.dm_frb_sim + dm_kde.pdf_fns + dm_kde.sort_transient_data + dm_kde.transient_kdes diff --git a/docs/api/dm_kde.sort_transient_data.rst b/docs/api/dm_kde.sort_transient_data.rst new file mode 100644 index 000000000..62b0b7c17 --- /dev/null +++ b/docs/api/dm_kde.sort_transient_data.rst @@ -0,0 +1,7 @@ +frb.dm_kde.sort_transient_data +============================== + +.. automodule:: frb.dm_kde.sort_transient_data + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/dm_kde.transient_kdes.rst b/docs/api/dm_kde.transient_kdes.rst new file mode 100644 index 000000000..dbc1956f2 --- /dev/null +++ b/docs/api/dm_kde.transient_kdes.rst @@ -0,0 +1,7 @@ +frb.dm_kde.transient_kdes +========================= + +.. automodule:: frb.dm_kde.transient_kdes + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/figures.dm.rst b/docs/api/figures.dm.rst new file mode 100644 index 000000000..3cf6d8f5b --- /dev/null +++ b/docs/api/figures.dm.rst @@ -0,0 +1,7 @@ +frb.figures.dm +============== + +.. automodule:: frb.figures.dm + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/figures.finder.rst b/docs/api/figures.finder.rst new file mode 100644 index 000000000..29d0585aa --- /dev/null +++ b/docs/api/figures.finder.rst @@ -0,0 +1,11 @@ +frb.figures.finder +================== + +.. automodule:: frb.figures.finder + :members: + :undoc-members: + :show-inheritance: + +.. note:: + Finder-chart workflows may require optional imaging dependencies such as + ``photutils`` and ``scikit-image`` in your environment. diff --git a/docs/api/figures.galaxies.rst b/docs/api/figures.galaxies.rst new file mode 100644 index 000000000..eeebd141c --- /dev/null +++ b/docs/api/figures.galaxies.rst @@ -0,0 +1,7 @@ +frb.figures.galaxies +==================== + +.. automodule:: frb.figures.galaxies + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/figures.rst b/docs/api/figures.rst new file mode 100644 index 000000000..03b933d0c --- /dev/null +++ b/docs/api/figures.rst @@ -0,0 +1,18 @@ +frb.figures +=========== + +.. automodule:: frb.figures + :members: + :undoc-members: + :show-inheritance: + +Submodules +---------- + +.. toctree:: + :maxdepth: 1 + + figures.dm + figures.finder + figures.galaxies + figures.utils diff --git a/docs/api/figures.utils.rst b/docs/api/figures.utils.rst new file mode 100644 index 000000000..1254a17de --- /dev/null +++ b/docs/api/figures.utils.rst @@ -0,0 +1,7 @@ +frb.figures.utils +================= + +.. automodule:: frb.figures.utils + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/frb_surveys.chime.rst b/docs/api/frb_surveys.chime.rst new file mode 100644 index 000000000..c58ec09a4 --- /dev/null +++ b/docs/api/frb_surveys.chime.rst @@ -0,0 +1,7 @@ +frb.frb_surveys.chime +===================== + +.. automodule:: frb.frb_surveys.chime + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/frb_surveys.rst b/docs/api/frb_surveys.rst index d940b30fe..6c1f4a7e7 100644 --- a/docs/api/frb_surveys.rst +++ b/docs/api/frb_surveys.rst @@ -11,10 +11,7 @@ FRB survey-specific data and utilities (e.g. CHIME). Submodules ---------- -frb.frb_surveys.chime - CHIME -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. toctree:: + :maxdepth: 1 -.. automodule:: frb.frb_surveys.chime - :members: - :undoc-members: - :show-inheritance: + frb_surveys.chime diff --git a/docs/api/galaxies.cigale.rst b/docs/api/galaxies.cigale.rst index 86bf27882..14f8b884e 100644 --- a/docs/api/galaxies.cigale.rst +++ b/docs/api/galaxies.cigale.rst @@ -2,121 +2,11 @@ CIGALE ====== .. automodule:: frb.galaxies.cigale - :members: - :undoc-members: - :show-inheritance: - -Overview --------- - -This module provides automation for CIGALE (Code Investigating GALaxy Emission) -spectral energy distribution fitting. It generates configuration files and runs -the standard pcigale script for single galaxy analysis. .. note:: - This module requires pcigale to be installed on the system. - -Constants ---------- - -.. autodata:: frb.galaxies.cigale._DEFAULT_SED_MODULES - - Default list of SED modules for CIGALE analysis: - ('sfhdelayed', 'bc03', 'nebular', 'dustatt_calzleit', 'dale2014', - 'restframe_parameters', 'redshifting') - -Functions ---------- - -Main Functions -~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.cigale.run - - Input parameters and run CIGALE analysis for a photometry table. - - This is the main entry point for running CIGALE on a table of photometric - measurements. It handles both single galaxy and multi-galaxy analysis. - -.. autofunction:: frb.galaxies.cigale.gen_cigale_in - - Generate input data file for CIGALE from photometric measurements. - -.. autofunction:: frb.galaxies.cigale._initialise - - Initialize CIGALE configuration with specified parameters. - -Utility Functions -~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.cigale._sed_default_params - - Set the default parameters for CIGALE SED modules. - - Provides default parameter grids for different SED modules including: - - * **sfhdelayed**: Delayed star formation history - * **bc03**: Bruzual & Charlot 2003 stellar population models - * **nebular**: Nebular emission modeling - * **dustatt_calzleit**: Calzetti attenuation law - * **dale2014**: Dust emission templates + This module requires the optional ``pcigale`` package. + Install with: ``pip install pcigale`` -Parameters ----------- - -The module supports extensive customization of CIGALE analysis through various parameters: - -**SED Modules** - - Star formation history models (sfhdelayed, exponential, etc.) - - Stellar population synthesis (bc03, m05, etc.) - - Nebular emission (nebular) - - Dust attenuation (dustatt_calzleit, dustatt_modified_starburst, etc.) - - Dust emission (dale2014, casey2012, etc.) - -**Analysis Parameters** - - Redshift estimation (photometric vs spectroscopic) - - Output variables (stellar mass, SFR, metallicity, etc.) - - Core usage and computational settings - -Examples --------- - -Basic CIGALE analysis: - -.. code-block:: python - - from frb.galaxies import cigale - from astropy.table import Table - - # Load photometry table - photom_table = Table.read('galaxy_photom.fits') - - # Run CIGALE with default settings - cigale.run(photom_table, zcol='z_spec', - data_file='input.fits', - config_file='config.ini', - plot=True) - -Custom SED modules: - -.. code-block:: python - - # Define custom SED modules - custom_modules = ['sfhdelayed', 'bc03', 'nebular', 'dustatt_calzleit'] - - # Run with custom configuration - cigale.run(photom_table, zcol='z_phot', - sed_modules=custom_modules, - save_sed=True, - cores=4) - -Integration with FRBGalaxy: - -.. code-block:: python - - from frb.galaxies.frbgalaxy import FRBGalaxy - - # Assuming galaxy object exists with photometry - galaxy.run_cigale(data_file='frb_galaxy.fits', - wait_for_input=False, - plot=True) \ No newline at end of file +.. note:: + Member-level API expansion is intentionally omitted here to avoid + docutils errors from legacy docstring formatting. diff --git a/docs/api/galaxies.convert_tables.rst b/docs/api/galaxies.convert_tables.rst new file mode 100644 index 000000000..b2440153b --- /dev/null +++ b/docs/api/galaxies.convert_tables.rst @@ -0,0 +1,7 @@ +frb.galaxies.convert_tables +=========================== + +.. automodule:: frb.galaxies.convert_tables + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/galaxies.eazy.rst b/docs/api/galaxies.eazy.rst index 9cba7c445..157d009b0 100644 --- a/docs/api/galaxies.eazy.rst +++ b/docs/api/galaxies.eazy.rst @@ -6,207 +6,7 @@ EAZY :undoc-members: :show-inheritance: -Overview --------- - -This module facilitates scripting of EAZY (Easy and Accurate Z from Yale) -photometric redshift analysis. It provides tools to set up EAZY runs, -generate input files, and process photometric redshift estimates. - .. note:: - This module requires EAZY to be installed and the EAZYDIR environment - variable to be properly set. - -Constants and Configuration ---------------------------- - -Filter Mapping -~~~~~~~~~~~~~~ - -.. autodata:: frb.galaxies.eazy.frb_to_eazy_filters - - Dictionary mapping FRB filter names to EAZY filter indices. Includes filters from: - - * DECaLS/Legacy Survey (g, r, z) - * DES (u, g, r, i, z, Y) - * SDSS (u, g, r, i, z) - * WISE (W1, W2, W3, W4) - * Pan-STARRS (g, r, i, z, y) - * VISTA (Y, J, H, Ks) - * Various ground-based instruments - -Template Sets -~~~~~~~~~~~~~ - -.. autodata:: frb.galaxies.eazy._template_list - - Available EAZY template sets: - ('br07_default', 'br07_goods', 'cww+kin', 'eazy_v1.0', 'eazy_v1.1_lines', - 'eazy_v1.2_dusty', 'eazy_v1.3', 'pegase', 'pegase13') - -Prior Options -~~~~~~~~~~~~~ - -.. autodata:: frb.galaxies.eazy._acceptable_priors - - Available redshift priors: ('prior_R_zmax7', 'prior_K_zmax7', - 'prior_R_extend', 'prior_K_extend') - -Functions ---------- - -Setup Functions -~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.eazy.eazy_setup - - Set up EAZY input directory with required templates and filter files. - -.. autofunction:: frb.galaxies.eazy.eazy_filenames - - Generate standardized filenames for EAZY input files. - -Input File Generation -~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.eazy.eazy_input_files - - Write complete set of input files needed to run EAZY analysis. - - This function creates: - - * Catalog file with photometric measurements - * Translation file mapping columns to EAZY format - * Parameter file with analysis configuration - -Analysis Functions -~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.eazy.eazy_photoz - - Run complete EAZY photometric redshift analysis. - -.. autofunction:: frb.galaxies.eazy.eazy_cat_from_frb_photom - - Convert FRB galaxy photometry to EAZY catalog format. - -File I/O Functions -~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.eazy.eazy_getpz - - Read EAZY photometric redshift results from output files. - -Configuration Parameters ------------------------- - -Key parameters for EAZY analysis include: - -**Redshift Grid** - - `zmin`: Minimum redshift (default: 0.050) - - `zmax`: Maximum redshift (default: 7.000) - - `zstep`: Redshift step size (default: 0.001) - -**Template Settings** - - `templates`: Template set to use (default: 'eazy_v1.3') - - `combo`: Template combination mode (1, 2, 99, -1, 'a') - -**Prior Configuration** - - `prior`: Prior file name (default: 'prior_R_zmax7') - - `prior_filter`: Filter to use for magnitude prior - - `prior_ABZP`: AB magnitude zero-point for prior (default: 23.9) - -**Quality Control** - - `n_min_col`: Minimum number of filter detections required - - `magnitudes`: Use magnitudes instead of fluxes as input - -Examples --------- - -Basic EAZY setup and analysis: - -.. code-block:: python - - from frb.galaxies import eazy - from frb.galaxies.frbgalaxy import FRBGalaxy - - # Set up EAZY working directory - eazy.eazy_setup('eazy_work/') - - # Generate input files from galaxy photometry - eazy.eazy_input_files( - galaxy.photom, - input_dir='eazy_work/', - name='FRB180924_host', - out_dir='output/', - templates='eazy_v1.3', - zmax=4.0 - ) - -Running photometric redshift analysis: - -.. code-block:: python - - # Run complete EAZY analysis - results = eazy.eazy_photoz( - 'galaxy_catalog.fits', - input_dir='eazy_work/', - name='survey_field', - zmax=6.0, - templates='eazy_v1.2_dusty', - prior='prior_K_zmax7' - ) - -Custom configuration: - -.. code-block:: python - - # Advanced configuration with custom parameters - eazy.eazy_input_files( - photom_dict, - input_dir='analysis/', - name='high_z_candidate', - out_dir='results/', - templates='eazy_v1.1_lines', # Line emission templates - combo='a', # All template combinations - zmin=0.1, - zmax=8.0, - zstep=0.002, - prior_filter='i', # Use i-band for prior - n_min_col=4 # Require 4+ band detections - ) - -Integration with FRBGalaxy: - -.. code-block:: python - - from frb.frb import FRB - from frb.galaxies.frbgalaxy import FRBGalaxy - - # Create galaxy object with photometry - frb = FRB.by_name('FRB121102') - galaxy = FRBGalaxy(ra=82.998, dec=33.148, frb=frb) - - # Populate with photometric measurements - galaxy.parse_photom(photom_table) - - # Run EAZY analysis - eazy_results = eazy.eazy_photoz( - galaxy.photom, - input_dir='frb121102_eazy/', - name='host_galaxy' - ) - -Output Processing: - -.. code-block:: python - - # Read EAZY results - zout = eazy.eazy_getpz('OUTPUT/photz.zout.fits') - - # Extract best redshift estimates - zbest = zout['z_peak'] - z_err_lo = zout['z_err_lo'] - z_err_hi = zout['z_err_hi'] - - print(f"Photo-z: {zbest[0]:.3f} +{z_err_hi[0]:.3f} -{z_err_lo[0]:.3f}") \ No newline at end of file + This module requires EAZY to be installed and the ``EAZYDIR`` environment + variable to be set. See the `EAZY documentation `_ + for installation instructions. diff --git a/docs/api/galaxies.extra_data.rst b/docs/api/galaxies.extra_data.rst new file mode 100644 index 000000000..8a167ec64 --- /dev/null +++ b/docs/api/galaxies.extra_data.rst @@ -0,0 +1,7 @@ +frb.galaxies.extra_data +======================= + +.. automodule:: frb.galaxies.extra_data + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/galaxies.frbgalaxy.rst b/docs/api/galaxies.frbgalaxy.rst index 95383aabc..104971977 100644 --- a/docs/api/galaxies.frbgalaxy.rst +++ b/docs/api/galaxies.frbgalaxy.rst @@ -5,118 +5,3 @@ FRBGalaxy Class :members: :undoc-members: :show-inheritance: - -Overview --------- - -This module provides the core functionality for handling galaxies related to Fast Radio Bursts (FRBs). -It contains the main `FRBGalaxy` class which serves as a parent class for galaxies in FRB fields, -providing a simple object to hold key observable and derived quantities. - -Classes -------- - -FRBGalaxy -~~~~~~~~~ - -.. autoclass:: frb.galaxies.frbgalaxy.FRBGalaxy - :members: - :special-members: __init__ - :show-inheritance: - - The `FRBGalaxy` class is designed to hold key observable and derived quantities - for galaxies associated with FRB events. - - **Key Attributes:** - - * `redshift` (dict): Redshift measurements and estimates - * `photom` (dict): Photometric data across multiple bands - * `morphology` (dict): Morphological properties - * `neb_lines` (dict): Nebular emission line measurements - * `kinematics` (dict): Kinematic measurements - * `derived` (dict): Derived physical quantities - * `offsets` (dict): Positional offsets from FRB coordinates - * `positional_error` (dict): Astrometric and source position errors - - .. warning:: - Generating hundreds of these objects will likely be slow, especially - due to SkyCoord generation. A new class will be warranted for that use case. - -Key Methods ------------ - -Class Methods -~~~~~~~~~~~~~ - -.. automethod:: frb.galaxies.frbgalaxy.FRBGalaxy.from_dict - - Instantiate an FRBGalaxy object from a dictionary containing galaxy parameters. - -.. automethod:: frb.galaxies.frbgalaxy.FRBGalaxy.from_json - - Load an FRBGalaxy object from a JSON file. - -Instance Methods -~~~~~~~~~~~~~~~~ - -.. automethod:: frb.galaxies.frbgalaxy.FRBGalaxy.set_z - - Set the redshift value(s) with specified origin (spectroscopic or photometric). - -.. automethod:: frb.galaxies.frbgalaxy.FRBGalaxy.calc_nebular_lum - - Calculate line luminosity with optional dust extinction correction. - -.. automethod:: frb.galaxies.frbgalaxy.FRBGalaxy.run_cigale - - Run CIGALE SED fitting analysis on the galaxy's photometry. - -.. automethod:: frb.galaxies.frbgalaxy.FRBGalaxy.parse_photom - - Parse photometry from an input table and populate the photom dictionary. - -.. automethod:: frb.galaxies.frbgalaxy.FRBGalaxy.vet_one - - Validate one of the main attribute dictionaries against allowed values. - -Properties ----------- - -.. autoproperty:: frb.galaxies.frbgalaxy.FRBGalaxy.z - - Return the preferred redshift of the galaxy. - -.. autoproperty:: frb.galaxies.frbgalaxy.FRBGalaxy.z_err - - Return the error in the preferred redshift. - -Examples --------- - -Creating an FRBGalaxy instance: - -.. code-block:: python - - from frb.frb import FRB - from frb.galaxies.frbgalaxy import FRBGalaxy - - # Create FRB object - frb = FRB.by_name('FRB180924') - - # Create galaxy object - galaxy = FRBGalaxy(ra=349.24, dec=-40.9, frb=frb) - - # Set redshift - galaxy.set_z(0.3214, 'spec', err=0.0001) - -Loading from dictionary: - -.. code-block:: python - - # Load from dictionary - galaxy_dict = { - 'ra': 349.24, - 'dec': -40.9, - 'cosmo': 'Planck18' - } - galaxy = FRBGalaxy.from_dict(frb, galaxy_dict) \ No newline at end of file diff --git a/docs/api/galaxies.galfit.rst b/docs/api/galaxies.galfit.rst new file mode 100644 index 000000000..e8517f37e --- /dev/null +++ b/docs/api/galaxies.galfit.rst @@ -0,0 +1,11 @@ +frb.galaxies.galfit +=================== + +.. automodule:: frb.galaxies.galfit + +.. note:: + Optional dependency: ``galfit`` must be installed separately as an external executable. + +.. note:: + Member-level API expansion is intentionally omitted here to avoid + docutils parsing failures from legacy docstrings. diff --git a/docs/api/galaxies.hosts.rst b/docs/api/galaxies.hosts.rst index be63da38f..5e02b4bd0 100644 --- a/docs/api/galaxies.hosts.rst +++ b/docs/api/galaxies.hosts.rst @@ -2,308 +2,7 @@ FRB Hosts ========= .. automodule:: frb.galaxies.hosts - :members: - :undoc-members: - :show-inheritance: - -Overview --------- - -This module provides specialized functionality for FRB host galaxies, extending -the basic FRBGalaxy class with additional methods specific to confirmed host -associations and enhanced analysis capabilities. .. note:: - This module builds upon `frb.galaxies.frbgalaxy` and provides host-specific - analysis tools and database interfaces. - -Classes -------- - -FRBHost -~~~~~~~ - -.. autoclass:: frb.galaxies.hosts.FRBHost - :members: - :special-members: __init__ - :show-inheritance: - - Specialized class for confirmed FRB host galaxies, extending FRBGalaxy - with additional functionality for: - - * Enhanced database integration - * Host-specific analysis methods - * Association probability calculations - * Literature compilation features - -Host Analysis Functions ------------------------ - -Association Analysis -~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.hosts.calc_association_prob - - Calculate the probability that a galaxy is the true host of an FRB. - - Uses multiple factors including: - - * Angular offset from FRB position - * Galaxy surface density in field - * Magnitude-dependent number counts - * Redshift compatibility with FRB dispersion measure - -.. autofunction:: frb.galaxies.hosts.host_candidate_ranking - - Rank potential host galaxies in an FRB field by association probability. - - Produces ranked list considering: - - * Positional offsets and uncertainties - * Galaxy properties (magnitude, morphology) - * Field galaxy density - * Prior expectations from FRB population studies - -Database Integration -~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.hosts.load_host_database - - Load the FRB host galaxy database with all confirmed associations. - - Provides access to: - - * Photometric measurements across multiple surveys - * Spectroscopic redshifts and derived properties - * Morphological parameters from imaging - * Literature references and discovery papers - -.. autofunction:: frb.galaxies.hosts.update_host_database - - Update host database with new measurements or revised values. - -.. autofunction:: frb.galaxies.hosts.query_hosts_by_property - - Query host database by specific galaxy properties or FRB characteristics. - -Population Analysis -~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.hosts.host_mass_function - - Calculate the stellar mass function of FRB host galaxies. - - Compares host mass distribution to field galaxy populations, - accounting for survey selection effects and completeness. - -.. autofunction:: frb.galaxies.hosts.host_sfr_distribution - - Analyze star formation rate distribution of host galaxies. - -.. autofunction:: frb.galaxies.hosts.offset_distribution_analysis - - Statistical analysis of FRB-host offset distributions. - - Includes: - - * Comparison with galaxy light profiles - * Offset vs. host properties correlations - * Population synthesis modeling - -Literature Compilation -~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.hosts.compile_literature_data - - Compile measurements from literature for specific host galaxies. - - Searches and consolidates: - - * Published photometry across papers - * Spectroscopic measurements and redshifts - * Morphological analyses - * Derived physical properties - -.. autofunction:: frb.galaxies.hosts.cross_match_catalogs - - Cross-match host positions with major survey catalogs. - -Host-Specific Properties ------------------------- - -The FRBHost class includes additional attributes: - -**Association Metadata** - * Discovery paper reference - * Association method (statistical, spectroscopic confirmation) - * Confidence level or probability - * Alternative host candidates - -**Enhanced Measurements** - * Compiled literature photometry - * Multiple redshift estimates with references - * Morphological measurements from different studies - * Environmental context (group/cluster membership) - -**Analysis Results** - * SED fitting results from multiple codes - * Spectral line analysis summaries - * Host-normalized offset measurements - * Population comparison statistics - -Examples --------- - -Creating FRBHost objects: - -.. code-block:: python - - from frb.galaxies.hosts import FRBHost - from frb.frb import FRB - - # Create FRB object - frb = FRB.by_name('FRB180924') - - # Create host object with enhanced functionality - host = FRBHost(ra=349.24, dec=-40.9, frb=frb) - - # Set confirmed host status - host.association_prob = 0.99 - host.discovery_ref = '2019Sci...365..565B' - -Loading from host database: - -.. code-block:: python - - from frb.galaxies.hosts import load_host_database - - # Load complete host database - host_db = load_host_database() - - # Access specific host - frb180924_host = host_db['FRB180924'] - - print(f"Host redshift: {frb180924_host.z:.4f}") - print(f"Stellar mass: {frb180924_host.derived['Mstar']:.2e} Msun") - -Association probability calculation: - -.. code-block:: python - - from frb.galaxies.hosts import calc_association_prob - - # Calculate association probability for candidate - prob = calc_association_prob( - offset_arcsec=1.2, - galaxy_mag=23.1, - field_density=1500, # galaxies per sq arcmin to this depth - survey_depth=25.0 - ) - - print(f"Association probability: {prob:.3f}") - -Host population analysis: - -.. code-block:: python - - from frb.galaxies.hosts import host_mass_function - import matplotlib.pyplot as plt - - # Calculate host stellar mass function - masses, phi, phi_err = host_mass_function( - completeness_limit=1e9, # Msun - volume_correction=True - ) - - # Plot comparison with field galaxies - plt.errorbar(masses, phi, yerr=phi_err, label='FRB hosts') - plt.xlabel('Stellar Mass [Msun]') - plt.ylabel('Φ [Mpc^-3 dex^-1]') - plt.yscale('log') - plt.legend() - -Literature compilation: - -.. code-block:: python - - from frb.galaxies.hosts import compile_literature_data - - # Compile all literature data for specific host - lit_data = compile_literature_data('FRB121102') - - print("Literature photometry:") - for paper, data in lit_data['photometry'].items(): - print(f" {paper}: {len(data)} measurements") - - print("\\nRedshift measurements:") - for z_entry in lit_data['redshifts']: - print(f" z = {z_entry['z']:.4f} ± {z_entry['z_err']:.4f} ({z_entry['ref']})") - -Candidate ranking: - -.. code-block:: python - - from frb.galaxies.hosts import host_candidate_ranking - from astropy.coordinates import SkyCoord - from astropy import units as u - - # Define FRB position and error - frb_coord = SkyCoord(ra=82.998, dec=33.148, unit='deg') - frb_error = 0.1 * u.arcsec # localization uncertainty - - # List of galaxy candidates with positions and magnitudes - candidates = [ - {'coord': SkyCoord(ra=82.999, dec=33.149, unit='deg'), 'mag': 22.1}, - {'coord': SkyCoord(ra=83.001, dec=33.146, unit='deg'), 'mag': 23.8}, - {'coord': SkyCoord(ra=82.995, dec=33.151, unit='deg'), 'mag': 24.2} - ] - - # Rank by association probability - ranked_candidates = host_candidate_ranking( - frb_coord, frb_error, candidates, - field_density=2000, - magnitude_limit=25.0 - ) - - print("Ranked host candidates:") - for i, candidate in enumerate(ranked_candidates): - print(f" {i+1}. P = {candidate['prob']:.3f}, " - f"offset = {candidate['offset']:.2f}\", " - f"mag = {candidate['mag']:.1f}") - -Cross-matching with surveys: - -.. code-block:: python - - from frb.galaxies.hosts import cross_match_catalogs - - # Cross-match host position with major surveys - matches = cross_match_catalogs( - host.coord, - radius=2.0 * u.arcsec, - surveys=['DES', 'Pan-STARRS', 'WISE', 'GALEX'] - ) - - print("Survey matches:") - for survey, data in matches.items(): - if len(data) > 0: - print(f" {survey}: {len(data)} sources") - print(f" Closest: {data[0]['separation']:.2f}\" ") - -Statistical analysis: - -.. code-block:: python - - from frb.galaxies.hosts import offset_distribution_analysis - import numpy as np - - # Analyze offset distribution for all confirmed hosts - analysis_results = offset_distribution_analysis( - normalize_by_size=True, # Normalize by galaxy effective radius - compare_to_light=True, # Compare with surface brightness profiles - bootstrap_errors=True - ) - - print(f"Median normalized offset: {analysis_results['median_norm']:.2f} R_e") - print(f"Fraction within 1 R_e: {analysis_results['frac_1Re']:.2f}") - print(f"KS test vs exponential profile: p = {analysis_results['ks_pvalue']:.3f}") \ No newline at end of file + Member-level API expansion is intentionally omitted here to keep + Sphinx builds stable with current upstream docstrings. diff --git a/docs/api/galaxies.mag_dm.rst b/docs/api/galaxies.mag_dm.rst new file mode 100644 index 000000000..0b7a51d0a --- /dev/null +++ b/docs/api/galaxies.mag_dm.rst @@ -0,0 +1,10 @@ +frb.galaxies.mag_dm +=================== + +.. automodule:: frb.galaxies.mag_dm + :members: + :undoc-members: + :show-inheritance: + +.. note:: + Optional dependency: ``asymmetric_kde`` may be required for KDE-based workflows. diff --git a/docs/api/galaxies.nebular.rst b/docs/api/galaxies.nebular.rst index 1fe8e0990..33df00af0 100644 --- a/docs/api/galaxies.nebular.rst +++ b/docs/api/galaxies.nebular.rst @@ -5,225 +5,3 @@ Nebular Emission Line Analysis :members: :undoc-members: :show-inheritance: - -Overview --------- - -This module provides functions for analyzing nebular emission lines in galaxy spectra, -including line flux measurements, extinction corrections, and star formation rate -calculations from emission line diagnostics. - -Functions ---------- - -Line Analysis Functions -~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.nebular.calc_lum - - Calculate emission line luminosity with optional dust extinction correction. - - This function converts observed line fluxes to intrinsic luminosities, - applying distance corrections and optionally correcting for dust extinction - using the Balmer decrement or other extinction indicators. - -.. autofunction:: frb.galaxies.nebular.measure_lines - - Measure emission line fluxes from galaxy spectra. - - Automated line fitting routine that identifies and measures common - nebular emission lines including: - - * Hydrogen Balmer series (Hα, Hβ, Hγ, Hδ) - * Oxygen lines ([OII] λ3727, [OIII] λλ4959,5007) - * Nitrogen lines ([NII] λλ6548,6583) - * Sulfur lines ([SII] λλ6717,6731) - -Star Formation Rate Functions -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.nebular.sfr_ha - - Calculate star formation rate from Hα luminosity. - - Uses the calibration from Kennicutt (1998) with appropriate corrections - for dust extinction and metallicity effects. - -.. autofunction:: frb.galaxies.nebular.sfr_oii - - Calculate star formation rate from [OII] λ3727 luminosity. - - Useful for higher redshift galaxies where Hα is redshifted out of - optical wavelength range. - -Extinction and Reddening -~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.nebular.calc_extinction - - Calculate dust extinction from Balmer line ratios. - - Uses the Balmer decrement (Hα/Hβ ratio) to determine the dust - extinction affecting nebular emission, assuming case B recombination. - -.. autofunction:: frb.galaxies.nebular.get_ebv - - Get Galactic extinction E(B-V) for given coordinates. - - Queries dust maps to obtain Milky Way foreground extinction values - using Schlegel, Finkbeiner & Davis (1998) or other dust maps. - -Diagnostic Functions -~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.nebular.bpt_classification - - Classify galaxies using BPT (Baldwin, Phillips & Terlevich) diagnostics. - - Uses emission line ratios to distinguish between: - - * Star-forming regions - * Active galactic nuclei (AGN) - * Low-ionization nuclear emission regions (LINERs) - * Composite systems - -.. autofunction:: frb.galaxies.nebular.metallicity_diagnostics - - Calculate gas-phase metallicity from emission line ratios. - - Implements various metallicity calibrations: - - * N2 method ([NII]/Hα) - * O3N2 method ([OIII]/Hβ vs [NII]/Hα) - * R23 method (([OII]+[OIII])/Hβ) - -Physical Properties -~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.nebular.electron_density - - Calculate electron density from [SII] doublet ratio. - - Uses the [SII] λ6717/λ6731 ratio to determine the electron density - in HII regions, sensitive in the range ~10-10^4 cm^-3. - -.. autofunction:: frb.galaxies.nebular.ionization_parameter - - Estimate ionization parameter from emission line diagnostics. - - Uses various line ratio diagnostics to constrain the ionization - parameter in HII regions and AGN narrow-line regions. - -Constants and Calibrations --------------------------- - -The module includes various physical constants and calibration factors: - -**Recombination Constants** - - Case B recombination coefficients - - Temperature and density dependent line ratios - - Intrinsic Balmer line ratios - -**Extinction Laws** - - Cardelli, Clayton & Mathis (1989) extinction curve - - Calzetti et al. (2000) starburst attenuation law - - Fitzpatrick (1999) Milky Way extinction - -**SFR Calibrations** - - Kennicutt (1998) Hα-SFR relation - - Modern IMF-corrected calibrations - - Metallicity-dependent corrections - -Examples --------- - -Basic line analysis: - -.. code-block:: python - - from frb.galaxies import nebular - from frb.galaxies.frbgalaxy import FRBGalaxy - - # Assuming galaxy object with emission line measurements - galaxy = FRBGalaxy(ra=180.0, dec=45.0, frb=frb_object) - - # Set emission line fluxes (in units of erg/s/cm^2) - galaxy.neb_lines['Ha_flux'] = 5.2e-16 - galaxy.neb_lines['Ha_flux_err'] = 0.3e-16 - galaxy.neb_lines['Hb_flux'] = 1.1e-16 - galaxy.neb_lines['OIII_5007_flux'] = 2.8e-16 - - # Calculate luminosity - ha_lum = nebular.calc_lum(galaxy, 'Ha') - print(f"Hα luminosity: {ha_lum:.2e} erg/s") - -Star formation rate calculation: - -.. code-block:: python - - # Calculate extinction from Balmer decrement - extinction = nebular.calc_extinction( - galaxy.neb_lines['Ha_flux'], - galaxy.neb_lines['Hb_flux'] - ) - print(f"A_V = {extinction:.2f} mag") - - # Calculate extinction-corrected SFR - sfr = nebular.sfr_ha(ha_lum, extinction=extinction) - print(f"Star formation rate: {sfr:.2f} Msun/yr") - -BPT classification: - -.. code-block:: python - - # Calculate line ratios for BPT diagram - line_ratios = { - 'NII_Ha': galaxy.neb_lines['NII_6583_flux'] / galaxy.neb_lines['Ha_flux'], - 'OIII_Hb': galaxy.neb_lines['OIII_5007_flux'] / galaxy.neb_lines['Hb_flux'], - 'SII_Ha': galaxy.neb_lines['SII_6717_flux'] / galaxy.neb_lines['Ha_flux'], - 'OI_Ha': galaxy.neb_lines['OI_6300_flux'] / galaxy.neb_lines['Ha_flux'] - } - - # Classify source type - classification = nebular.bpt_classification(line_ratios) - print(f"BPT classification: {classification}") - -Metallicity analysis: - -.. code-block:: python - - # Calculate metallicity using N2 method - n2_ratio = galaxy.neb_lines['NII_6583_flux'] / galaxy.neb_lines['Ha_flux'] - metallicity_n2 = nebular.metallicity_diagnostics(n2_ratio, method='N2') - - # Convert to 12 + log(O/H) scale - oh_abundance = 8.69 + metallicity_n2 - print(f"12 + log(O/H) = {oh_abundance:.2f}") - -Electron density measurement: - -.. code-block:: python - - # Calculate electron density from [SII] doublet - sii_ratio = (galaxy.neb_lines['SII_6717_flux'] / - galaxy.neb_lines['SII_6731_flux']) - - n_e = nebular.electron_density(sii_ratio) - print(f"Electron density: {n_e:.1f} cm^-3") - -Galactic extinction correction: - -.. code-block:: python - - from astropy.coordinates import SkyCoord - - # Get Galactic extinction - coord = SkyCoord(ra=180.0*u.deg, dec=45.0*u.deg) - ebv_gal = nebular.get_ebv(coord) - - # Apply foreground correction to observed fluxes - extinction_corr = 10**(0.4 * 2.5 * ebv_gal) # Hα extinction - intrinsic_flux = galaxy.neb_lines['Ha_flux'] * extinction_corr - - print(f"Galactic E(B-V): {ebv_gal:.3f}") - print(f"Corrected Hα flux: {intrinsic_flux:.2e} erg/s/cm^2") \ No newline at end of file diff --git a/docs/api/galaxies.offsets.rst b/docs/api/galaxies.offsets.rst index 3a8afd0ba..f40fe7cfb 100644 --- a/docs/api/galaxies.offsets.rst +++ b/docs/api/galaxies.offsets.rst @@ -5,243 +5,3 @@ Galaxy Offsets :members: :undoc-members: :show-inheritance: - -Overview --------- - -This module provides functions for calculating positional offsets between -FRBs and their potential host galaxies. It handles both angular and physical -offset measurements, accounting for localization uncertainties and coordinate -transformations. - -Functions ---------- - -Primary Offset Functions -~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.offsets.angular_offset - - Calculate angular offset between FRB position and galaxy coordinates. - - This is the primary function for computing separations, handling: - - * FRB localization error ellipses - * Galaxy position uncertainties - * Statistical error propagation - * Multiple offset definitions (best estimate vs. averaged) - -.. autofunction:: frb.galaxies.offsets.physical_offset - - Convert angular offsets to physical separations using cosmological distances. - - Takes angular separations and converts to proper physical distances - in kpc, accounting for the galaxy redshift and assumed cosmology. - -Error Analysis Functions -~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.offsets.offset_uncertainty - - Calculate uncertainties in offset measurements. - - Propagates errors from: - - * FRB localization uncertainty ellipse - * Galaxy astrometric errors - * Systematic coordinate uncertainties - * Statistical measurement errors - -.. autofunction:: frb.galaxies.offsets.deproject_offset - - Deproject observed offsets to account for galaxy inclination. - - For edge-on or highly inclined galaxies, converts sky-plane offsets - to deprojected separations within the galaxy disk. - -Coordinate System Functions -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.offsets.galactic_coords - - Transform offsets to galaxy-centric coordinate system. - - Rotates offset vectors to align with galaxy major axis, useful - for studying offset distributions relative to galaxy structure. - -.. autofunction:: frb.galaxies.offsets.position_angle - - Calculate position angle of FRB relative to galaxy center. - - Returns the position angle (East of North) of the FRB location - relative to the galaxy centroid. - -Statistical Functions -~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.offsets.offset_probability - - Calculate probability of chance alignment given offset distribution. - - Uses offset measurements and galaxy number density to assess the - likelihood that an apparent FRB-galaxy association is coincidental. - -.. autofunction:: frb.galaxies.offsets.compare_offset_distributions - - Compare offset distributions between different galaxy populations. - - Statistical comparison of FRB offset distributions for different - host galaxy types, redshift ranges, or other sample cuts. - -Offset Types and Definitions ----------------------------- - -The module implements several offset definitions: - -**Angular Offsets** - * `ang_best`: Offset from FRB localization centroid to galaxy center - * `ang_avg`: Offset averaged over FRB localization probability distribution - * Angular offsets reported in arcseconds - -**Physical Offsets** - * Proper physical distance in kpc at galaxy redshift - * Corrected for cosmological expansion - * Uses `ang_best` by default unless specified - -**Deprojected Offsets** - * Corrected for galaxy inclination angle - * Represents true separation within galaxy disk - * Requires morphological information - -Error Propagation ------------------ - -Comprehensive error handling includes: - -**FRB Localization Errors** - - Error ellipse semi-major and semi-minor axes - - Position angle of error ellipse - - Confidence level specification - -**Galaxy Position Errors** - - Astrometric tie uncertainties - - Source extraction errors - - Proper motion corrections (for nearby galaxies) - -**Systematic Uncertainties** - - Absolute astrometric calibration - - Reference frame differences - - Coordinate epoch corrections - -Examples --------- - -Basic offset calculation: - -.. code-block:: python - - from frb.galaxies import offsets - from frb.frb import FRB - from frb.galaxies.frbgalaxy import FRBGalaxy - - # Create FRB and galaxy objects - frb = FRB.by_name('FRB180924') - galaxy = FRBGalaxy(ra=349.24, dec=-40.9, frb=frb) - - # Calculate angular offsets (done automatically in FRBGalaxy.__init__) - ang_avg, ang_avg_err, ang_best, ang_best_err = offsets.angular_offset(frb, galaxy) - - print(f"Angular offset (best): {ang_best:.2f} ± {ang_best_err:.2f} arcsec") - print(f"Angular offset (averaged): {ang_avg:.2f} ± {ang_avg_err:.2f} arcsec") - -Physical offset calculation: - -.. code-block:: python - - # Set galaxy redshift first - galaxy.set_z(0.3214, 'spec', err=0.0001) - - # Calculate physical offset - phys_offset = offsets.physical_offset( - ang_best, # angular offset in arcsec - galaxy.z, # redshift - cosmo=galaxy.cosmo - ) - - print(f"Physical offset: {phys_offset:.1f} kpc") - -Including position errors: - -.. code-block:: python - - # Set galaxy position uncertainties - galaxy.positional_error['ra_astrometric'] = 0.1 # arcsec - galaxy.positional_error['dec_astrometric'] = 0.1 # arcsec - galaxy.positional_error['ra_source'] = 0.05 # arcsec - galaxy.positional_error['dec_source'] = 0.05 # arcsec - - # Recalculate with position errors included - ang_avg, ang_avg_err, ang_best, ang_best_err = offsets.angular_offset(frb, galaxy) - - print(f"Offset with position errors: {ang_best:.2f} ± {ang_best_err:.2f} arcsec") - -Position angle calculation: - -.. code-block:: python - - # Calculate position angle of FRB relative to galaxy - pa = offsets.position_angle(frb.coord, galaxy.coord) - print(f"Position angle: {pa:.1f} degrees East of North") - -Probability assessment: - -.. code-block:: python - - # Assess chance alignment probability - # (requires galaxy surface density information) - prob_chance = offsets.offset_probability( - ang_best, # observed offset - galaxy_density=1000, # galaxies per sq. arcmin - magnitude_limit=25.0 # survey depth - ) - - print(f"Chance alignment probability: {prob_chance:.3f}") - -Working with morphology: - -.. code-block:: python - - # For galaxies with inclination information - if 'inclination' in galaxy.morphology: - # Calculate deprojected offset - deprojected = offsets.deproject_offset( - ang_best, - galaxy.morphology['inclination'], - galaxy.morphology['position_angle'], - frb_pa=pa - ) - - print(f"Deprojected offset: {deprojected:.2f} arcsec") - -Bulk analysis: - -.. code-block:: python - - from frb.galaxies.utils import list_of_hosts - - # Get all hosts and calculate offset distribution - frbs, hosts = list_of_hosts() - - offsets_list = [] - for host in hosts: - if host.z is not None: - phys_off = offsets.physical_offset( - host.offsets['ang_best'], - host.z, - cosmo=host.cosmo - ) - offsets_list.append(phys_off) - - import numpy as np - median_offset = np.median(offsets_list) - print(f"Median host offset: {median_offset:.1f} kpc") \ No newline at end of file diff --git a/docs/api/galaxies.photom.rst b/docs/api/galaxies.photom.rst index 7fefbca30..f5696117c 100644 --- a/docs/api/galaxies.photom.rst +++ b/docs/api/galaxies.photom.rst @@ -1,4 +1,4 @@ -Photometry +Photometry ========== .. automodule:: frb.galaxies.photom @@ -6,240 +6,7 @@ Photometry :undoc-members: :show-inheritance: -Overview --------- - -This module provides functions for photometric analysis of FRB host galaxies, -including magnitude-to-flux conversions, aperture photometry corrections, -and integration with various survey photometric systems. - -Functions ---------- - -Photometric Conversions -~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.photom.mag_to_flux - - Convert magnitudes to flux densities with proper error propagation. - - Handles conversion between AB magnitude system and flux densities - in various units (mJy, μJy, erg/s/cm²/Hz, etc.). - -.. autofunction:: frb.galaxies.photom.flux_to_mag - - Convert flux densities to AB magnitudes with error propagation. - -.. autofunction:: frb.galaxies.photom.extinction_correct - - Apply extinction corrections to photometric measurements. - - Uses various extinction laws: - - * Cardelli, Clayton & Mathis (1989) - Milky Way - * Calzetti et al. (2000) - Starburst galaxies - * Fitzpatrick (1999) - Updated Milky Way - * Gordon et al. (2003) - Small Magellanic Cloud - -Aperture Corrections -~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.photom.aperture_correction - - Apply aperture corrections to photometric measurements. - - Corrects photometry measured in fixed apertures to total - magnitudes using growth curve analysis or model fitting. - -.. autofunction:: frb.galaxies.photom.psf_correction - - Correct point source contamination in galaxy photometry. - - Removes or accounts for foreground stars or AGN point source - contributions to integrated galaxy photometry. - -Survey Integration -~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.photom.match_survey_photometry - - Cross-match and combine photometry from multiple surveys. - - Handles systematic offsets between surveys and provides - combined photometric datasets with proper error handling. - -.. autofunction:: frb.galaxies.photom.synthetic_photometry - - Calculate synthetic photometry from spectra or SED models. - - Convolves input spectra with survey filter response functions - to predict magnitudes in any photometric system. - -Color and SED Analysis -~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.photom.calculate_colors - - Calculate photometric colors with error propagation. - - Computes standard color indices (u-g, g-r, r-i, etc.) and - handles cases with non-detections or upper limits. - -.. autofunction:: frb.galaxies.photom.color_corrections - - Apply K-corrections and evolutionary corrections to photometry. - - Corrects observed photometry to rest-frame values accounting - for redshift effects and cosmological evolution. - -.. autofunction:: frb.galaxies.photom.sed_chi_squared - - Calculate chi-squared goodness of fit for SED models. - - Compares observed photometry with model predictions, - properly handling upper limits and systematic uncertainties. - -Quality Assessment -~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.photom.photom_quality_flags - - Generate quality flags for photometric measurements. - - Identifies potential issues: - - * Saturation effects - * Contamination by nearby sources - * Poor photometric conditions - * Systematic calibration problems - -.. autofunction:: frb.galaxies.photom.detect_outliers - - Detect outlier photometric measurements using statistical tests. - - Flags measurements that are inconsistent with SED expectations - or show systematic deviations from neighboring bands. - -Examples --------- - -Basic magnitude-flux conversions: - -.. code-block:: python - - from frb.galaxies import photom - import numpy as np - - # Convert AB magnitude to flux density in mJy - mag = 22.5 - mag_err = 0.1 - - flux, flux_err = photom.mag_to_flux(mag, mag_err, units='mJy') - print(f"Flux: {flux:.2f} ± {flux_err:.2f} mJy") - - # Convert back to magnitude - mag_check, mag_err_check = photom.flux_to_mag(flux, flux_err) - print(f"Magnitude: {mag_check:.2f} ± {mag_err_check:.3f}") - -Extinction corrections: - -.. code-block:: python - - # Apply Galactic extinction correction - ebv_gal = 0.05 # E(B-V) from dust maps - - # Correct r-band magnitude - r_obs = 22.8 - r_corr = photom.extinction_correct( - r_obs, - ebv_gal, - filter_name='r', - extinction_law='ccm89', - rv=3.1 - ) - - print(f"Observed r: {r_obs:.2f}") - print(f"Corrected r: {r_corr:.2f}") - print(f"Correction: {r_corr - r_obs:.3f} mag") - -Color calculations: - -.. code-block:: python - - # Calculate colors from photometry dictionary - photom_dict = { - 'DES_g': 23.1, 'DES_g_err': 0.05, - 'DES_r': 22.3, 'DES_r_err': 0.03, - 'DES_i': 21.9, 'DES_i_err': 0.04 - } - - # Calculate g-r color - gr_color, gr_err = photom.calculate_colors( - photom_dict, 'DES_g', 'DES_r' - ) - - # Calculate r-i color - ri_color, ri_err = photom.calculate_colors( - photom_dict, 'DES_r', 'DES_i' - ) - - print(f"g-r = {gr_color:.2f} ± {gr_err:.3f}") - print(f"r-i = {ri_color:.2f} ± {ri_err:.3f}") - -Working with galaxy objects: - -.. code-block:: python - - from frb.galaxies.frbgalaxy import FRBGalaxy - - # Assuming galaxy object with photometry loaded - galaxy = FRBGalaxy(ra=180.0, dec=45.0, frb=frb_object) - - # Calculate synthetic V-band magnitude from available photometry - v_synth = photom.synthetic_photometry( - galaxy.photom, - target_filter='V', - method='interpolation' - ) - - print(f"Synthetic V magnitude: {v_synth:.2f}") - -SED fitting preparation: - -.. code-block:: python - - # Prepare photometry for SED fitting - clean_photom = photom.detect_outliers(galaxy.photom) - - # Apply quality flags - quality_flags = photom.photom_quality_flags(galaxy.photom) - - # Remove flagged measurements - sed_photom = {} - for filt, mag in clean_photom.items(): - if quality_flags.get(filt, 0) == 0: # Good quality - sed_photom[filt] = mag - - print(f"Clean photometry: {len(sed_photom)} measurements") - print(f"Rejected: {len(galaxy.photom) - len(sed_photom)} measurements") - -Multi-survey combination: - -.. code-block:: python - - # Combine photometry from multiple surveys - survey_data = { - 'DES': {'g': 22.1, 'r': 21.5, 'i': 21.2}, - 'SDSS': {'g': 22.0, 'r': 21.4, 'i': 21.1}, - 'Pan-STARRS': {'g': 22.05, 'r': 21.45, 'i': 21.15} - } - - combined_photom = photom.match_survey_photometry( - survey_data, - weight_by_error=True, - apply_systematic_corrections=True - ) - - print("Combined photometry:") - for filt, data in combined_photom.items(): - print(f" {filt}: {data['mag']:.2f} ± {data['err']:.3f}") \ No newline at end of file +.. note:: + This module uses ``dust_extinction`` and ``photutils`` for key workflows. + Ensure optional dependencies are available for extinction and + aperture-photometry operations. diff --git a/docs/api/galaxies.ppxf.rst b/docs/api/galaxies.ppxf.rst index 4a0c0fa78..c16bd6b34 100644 --- a/docs/api/galaxies.ppxf.rst +++ b/docs/api/galaxies.ppxf.rst @@ -6,112 +6,6 @@ pPXF :undoc-members: :show-inheritance: -Overview --------- - -This module provides functionality for running pPXF (Penalized Pixel-Fitting) -analyses on galaxy spectra. pPXF is used to extract stellar kinematics and -stellar population information from absorption-line spectra. - -Functions ---------- - -.. autofunction:: frb.galaxies.ppxf.run - - Main wrapper function for running and handling pPXF outputs. - - This function processes galaxy spectra through the pPXF pipeline, handling - input/output and providing a simplified interface to the underlying pPXF code. - -Parameters ----------- - -The `run` function accepts the following key parameters: - -* **spec_file** (str or XSpectrum1D): Input spectrum file or object -* **R** (float): Spectral resolution -* **zgal** (float): Galaxy redshift -* **results_file** (str, optional): Output results filename -* **spec_fit** (str, optional): Fitted spectrum output filename -* **chk** (bool, optional): Enable checking/validation -* **flux_scale** (float, optional): Flux scaling factor -* **atmos** (list, optional): Atmospheric absorption regions to mask -* **gaps** (list, optional): Detector gaps or bad regions to ignore -* **wvmnx** (tuple, optional): Wavelength range limits - -Masking Options -~~~~~~~~~~~~~~~ - -The module provides flexible masking capabilities: - -**Atmospheric Lines** - Regions affected by atmospheric absorption can be masked during analysis: - - .. code-block:: python - - atmos = [[7150., 7300.], [7594., 7621.]] # O2 bands - -**Detector Gaps** - Bad regions or detector gaps can be excluded: - - .. code-block:: python - - gaps = [[6675., 6725.]] # CCD gap - -Usage Examples --------------- - -Basic pPXF analysis: - -.. code-block:: python - - from frb.galaxies import ppxf - - # Run pPXF on a spectrum file - ppxf.run('galaxy_spectrum.fits', - R=3000., # Resolution - zgal=0.1, # Redshift - results_file='ppxf_results.fits') - -With masking: - -.. code-block:: python - - # Define regions to mask - atmos_lines = [[7594., 7621.], [6864., 6884.]] # Telluric features - detector_gaps = [[6675., 6725.]] # Bad detector region - - ppxf.run('spectrum.fits', - R=2500., - zgal=0.25, - atmos=atmos_lines, - gaps=detector_gaps, - wvmnx=(4000., 9000.)) # Wavelength limits - -Output Processing: - -.. code-block:: python - - # Run with custom output files - ppxf.run('galaxy.fits', - R=3500., - zgal=0.15, - results_file='kinematic_results.fits', - spec_fit='best_fit_spectrum.fits', - flux_scale=1e-17, # Scale factor for flux units - chk=True) # Enable validation checks - -Dependencies ------------- - -This module requires: - -* ppxf package (Cappellari 2017, 2023) -* linetools for spectrum handling -* astropy for units and constants -* matplotlib for plotting capabilities -* numpy for numerical computations - .. note:: - The module uses MILES stellar library templates by default for - stellar population fitting. \ No newline at end of file + This module requires the optional ``ppxf`` package. + Install with: ``pip install ppxf`` diff --git a/docs/api/galaxies.rst b/docs/api/galaxies.rst index 3143901a7..1568dd8be 100644 --- a/docs/api/galaxies.rst +++ b/docs/api/galaxies.rst @@ -36,4 +36,8 @@ Submodules galaxies.offsets galaxies.defs galaxies.hosts - galaxies.photom \ No newline at end of file + galaxies.photom + galaxies.convert_tables + galaxies.extra_data + galaxies.galfit + galaxies.mag_dm \ No newline at end of file diff --git a/docs/api/galaxies.utils.rst b/docs/api/galaxies.utils.rst index 98f9af7c8..573433e74 100644 --- a/docs/api/galaxies.utils.rst +++ b/docs/api/galaxies.utils.rst @@ -6,172 +6,6 @@ Galaxy Utilities :undoc-members: :show-inheritance: -Overview --------- - -This module provides utility functions for working with FRB host galaxy data, -including database operations, table building, and various helper functions -for galaxy analysis. - -Functions ---------- - -Database and Loading Functions -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.utils.load_specdb - - Load spectroscopic database for galaxy analysis. - -.. autofunction:: frb.galaxies.utils.list_of_hosts - - Generate a list of FRB host galaxies from the database. - -.. autofunction:: frb.galaxies.utils.build_table_of_hosts - - Generate a Pandas table of FRB host galaxy data. - - This function extracts data from host objects and compiles it into a - comprehensive table including photometry, derived quantities, nebular - line measurements, and morphological parameters. - -Analysis Utilities -~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.utils.load_f_mL - - Generate interpolator from magnitude to luminosity as function of redshift. - - Provides approximate magnitude-luminosity relationship up to z=4 for - galaxy luminosity function analysis. - -.. autofunction:: frb.galaxies.utils.load_PATH - - Load up the PATH (Probabilistic Association of Transients with Hosts) table. - -.. autofunction:: frb.galaxies.utils.deredden_spec - - Apply dereddening correction to galaxy spectra using dust extinction models. - -Data Processing Functions -~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: frb.galaxies.utils.build_photom_table - - Build standardized photometric table from various survey catalogs. - -.. autofunction:: frb.galaxies.utils.parse_galfit_output - - Parse GALFIT morphological analysis output files. - -.. autofunction:: frb.galaxies.utils.update_frbgalaxy_coords - - Update galaxy coordinates with improved astrometry. - -Output and Table Management -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The module provides several functions for managing host galaxy data tables: - -**Table Structure** - - Coordinates stored as RA_host, DEC_host (degrees) - - FRB names and objects included for cross-referencing - - Units tracked in separate dictionary - - Missing values handled with NaN - -**Data Categories** - - Photometric measurements across multiple surveys - - Derived physical properties (mass, SFR, metallicity) - - Nebular emission line fluxes and ratios - - Morphological parameters from imaging analysis - - Redshift measurements (spectroscopic and photometric) - - Offset measurements from FRB positions - -Examples --------- - -Building host galaxy table: - -.. code-block:: python - - from frb.galaxies import utils - - # Build comprehensive host table - host_table, units_dict = utils.build_table_of_hosts( - attrs=['derived', 'photom', 'neb_lines', 'morphology'] - ) - - # Display table info - print(f"Number of hosts: {len(host_table)}") - print(f"Available columns: {list(host_table.columns)}") - print(f"Units: {units_dict}") - -Working with individual hosts: - -.. code-block:: python - - # Get list of host objects - frbs, hosts = utils.list_of_hosts(verbose=True) - - # Access specific host properties - for host in hosts[:5]: # First 5 hosts - print(f"Host: {host.name}") - print(f" RA, Dec: {host.coord.ra.deg:.3f}, {host.coord.dec.deg:.3f}") - print(f" Redshift: {host.z}") - if len(host.derived) > 0: - if 'Mstar' in host.derived: - print(f" Stellar mass: {host.derived['Mstar']:.2e} Msun") - -Loading and using spectroscopic database: - -.. code-block:: python - - # Load spectroscopic database - specdb = utils.load_specdb(specdb_file='custom_specdb.hdf5') - - if specdb is not None: - # Query for spectra - meta = specdb.meta_from_coords(coords, radius=5*u.arcsec) - if len(meta) > 0: - spectra = specdb.spectra_from_meta(meta) - -Dereddening corrections: - -.. code-block:: python - - from linetools.spectra.xspectrum1d import XSpectrum1D - - # Load spectrum - spec = XSpectrum1D.from_file('galaxy_spectrum.fits') - - # Apply dereddening with AV = 0.5 mag - corrected_spec = utils.deredden_spec(spec, AV=0.5) - -PATH analysis integration: - -.. code-block:: python - - # Load PATH results - path_table = utils.load_PATH('adopted.csv') - - # Build host table with PATH probabilities - host_table, units = utils.build_table_of_hosts() - - # PATH probabilities now included as P_Ox, P_O columns - high_prob_hosts = host_table[host_table['P_Ox'] > 0.8] - print(f"High probability associations: {len(high_prob_hosts)}") - -Working with magnitude-luminosity relations: - -.. code-block:: python - - # Load m-L interpolator - f_mL = utils.load_f_mL() - - # Get characteristic magnitude at different redshifts - z_array = [0.1, 0.3, 0.5, 1.0, 2.0] - m_star = f_mL(z_array) - - print("Characteristic magnitudes (r-band):") - for z, m in zip(z_array, m_star): - print(f" z = {z:.1f}: m* = {m:.2f}") \ No newline at end of file +.. note:: + The :func:`~frb.galaxies.utils.load_specdb` function requires the optional + ``specdb`` package. Install with: ``pip install specdb`` diff --git a/docs/api/halos.rst b/docs/api/halos.rst index 445f2762d..1c1d6fef3 100644 --- a/docs/api/halos.rst +++ b/docs/api/halos.rst @@ -1,42 +1,17 @@ frb.halos - Halo Models ======================= -.. automodule:: frb.halos - :members: - :undoc-members: - :show-inheritance: +Package for modelling the dispersion measure contributions from galaxy halos. -Submodules ----------- +.. note:: + Most submodules require the optional ``hmf_emulator`` package. + Install with: ``pip install hmf_emulator`` -frb.halos.hmf - Halo Mass Function -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +See the full halo package documentation at :doc:`../halos/index`. -.. automodule:: frb.halos.hmf - :members: - :undoc-members: - :show-inheritance: +Submodule API Reference +----------------------- -frb.halos.models - Halo Models -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.halos.models - :members: - :undoc-members: - :show-inheritance: - -frb.halos.photoz - Photo-z Utilities -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.halos.photoz - :members: - :undoc-members: - :show-inheritance: - -frb.halos.utils - Utilities -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.halos.utils - :members: - :undoc-members: - :show-inheritance: +* :doc:`../halos/models` — Halo density profiles and mass relations +* :doc:`../halos/photoz` — Photometric redshift-based halo analysis +* :doc:`../halos/hmf` — Halo mass function statistics diff --git a/docs/api/index.rst b/docs/api/index.rst index 81ea0f887..6fbe54949 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -12,12 +12,20 @@ The FRB package is organized into several key modules: :maxdepth: 2 frb + analysis dm galaxies halos surveys associate + builds + figures + scripts + dm_kde frb_surveys + defs + io + utils turb_scattering rm mw @@ -72,12 +80,12 @@ Core Functions by Category .. autosummary:: :nosignatures: - frb.dm.igm.DM_cosmic + frb.dm.igm.average_DM frb.dm.igm.ne_cosmic frb.dm.igm.z_from_DM - frb.dm.igm.DM_halos - frb.dm.cosmic.DM_cosmic - frb.dm.host.DM_host + frb.dm.igm.average_DMhalos + frb.dm.cosmic.DMcosmic_PDF + frb.dm.host.dm_host_from_ssfr **Scattering:** @@ -101,8 +109,8 @@ Core Functions by Category .. autosummary:: :nosignatures: - frb.FRB.by_name - frb.FRB.grab_host + frb.frb.FRB.by_name + frb.frb.FRB.grab_host Class Hierarchy --------------- @@ -162,7 +170,7 @@ The FRB package uses standard Python exception handling: .. code-block:: python try: - frb_obj = ffrb.FRB.by_name('NonExistentFRB') + frb_obj = FRB.by_name('NonExistentFRB') except FileNotFoundError: print("FRB data not found") except ValueError as e: diff --git a/docs/api/io.rst b/docs/api/io.rst new file mode 100644 index 000000000..df2ba4673 --- /dev/null +++ b/docs/api/io.rst @@ -0,0 +1,7 @@ +frb.io +====== + +.. automodule:: frb.io + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/mw.rst b/docs/api/mw.rst index d9bf23c14..a57502d7a 100644 --- a/docs/api/mw.rst +++ b/docs/api/mw.rst @@ -5,6 +5,7 @@ Calculations related to the Milky Way, including ISM DM using the NE2001 electron density model. .. automodule:: frb.mw - :members: - :undoc-members: - :show-inheritance: + +.. note:: + Member-level API expansion is intentionally omitted here to avoid + docstring parsing errors during ``make html``. diff --git a/docs/api/scripts.build.rst b/docs/api/scripts.build.rst new file mode 100644 index 000000000..243201a2e --- /dev/null +++ b/docs/api/scripts.build.rst @@ -0,0 +1,7 @@ +frb.scripts.build +================= + +.. automodule:: frb.scripts.build + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/scripts.dm_ism_hp_map.rst b/docs/api/scripts.dm_ism_hp_map.rst new file mode 100644 index 000000000..dbd23bcc6 --- /dev/null +++ b/docs/api/scripts.dm_ism_hp_map.rst @@ -0,0 +1,7 @@ +frb.scripts.dm_ism_hp_map +========================= + +.. automodule:: frb.scripts.dm_ism_hp_map + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/scripts.frb_summary.rst b/docs/api/scripts.frb_summary.rst new file mode 100644 index 000000000..fe123988d --- /dev/null +++ b/docs/api/scripts.frb_summary.rst @@ -0,0 +1,7 @@ +frb.scripts.frb_summary +======================= + +.. automodule:: frb.scripts.frb_summary + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/scripts.galaxies.rst b/docs/api/scripts.galaxies.rst new file mode 100644 index 000000000..1d69517c3 --- /dev/null +++ b/docs/api/scripts.galaxies.rst @@ -0,0 +1,10 @@ +frb.scripts.galaxies +==================== + +.. automodule:: frb.scripts.galaxies + :members: + :undoc-members: + :show-inheritance: + +.. note:: + Optional dependency: ``specdb`` is required for full spectral-database access. diff --git a/docs/api/scripts.image.rst b/docs/api/scripts.image.rst new file mode 100644 index 000000000..f488096ce --- /dev/null +++ b/docs/api/scripts.image.rst @@ -0,0 +1,7 @@ +frb.scripts.image +================= + +.. automodule:: frb.scripts.image + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/scripts.iteration.rst b/docs/api/scripts.iteration.rst new file mode 100644 index 000000000..773cd15f8 --- /dev/null +++ b/docs/api/scripts.iteration.rst @@ -0,0 +1,8 @@ +frb.scripts.iteration +===================== + +.. automodule:: frb.scripts.iteration + +.. note:: + Member-level API expansion is intentionally omitted here to keep + Sphinx builds robust with existing docstring formatting. diff --git a/docs/api/scripts.pz_given_dm.rst b/docs/api/scripts.pz_given_dm.rst new file mode 100644 index 000000000..86cb20463 --- /dev/null +++ b/docs/api/scripts.pz_given_dm.rst @@ -0,0 +1,7 @@ +frb.scripts.pz_given_dm +======================= + +.. automodule:: frb.scripts.pz_given_dm + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/scripts.pzdm_mag.rst b/docs/api/scripts.pzdm_mag.rst new file mode 100644 index 000000000..1295e2dff --- /dev/null +++ b/docs/api/scripts.pzdm_mag.rst @@ -0,0 +1,7 @@ +frb.scripts.pzdm_mag +==================== + +.. automodule:: frb.scripts.pzdm_mag + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/scripts.pzdm_mag_crossmatch.rst b/docs/api/scripts.pzdm_mag_crossmatch.rst new file mode 100644 index 000000000..caf05dd63 --- /dev/null +++ b/docs/api/scripts.pzdm_mag_crossmatch.rst @@ -0,0 +1,7 @@ +frb.scripts.pzdm_mag_crossmatch +=============================== + +.. automodule:: frb.scripts.pzdm_mag_crossmatch + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/scripts.r_vs_dm.rst b/docs/api/scripts.r_vs_dm.rst new file mode 100644 index 000000000..261950079 --- /dev/null +++ b/docs/api/scripts.r_vs_dm.rst @@ -0,0 +1,7 @@ +frb.scripts.r_vs_dm +=================== + +.. automodule:: frb.scripts.r_vs_dm + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/scripts.random_assoc.rst b/docs/api/scripts.random_assoc.rst new file mode 100644 index 000000000..650486c40 --- /dev/null +++ b/docs/api/scripts.random_assoc.rst @@ -0,0 +1,7 @@ +frb.scripts.random_assoc +======================== + +.. automodule:: frb.scripts.random_assoc + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/scripts.rst b/docs/api/scripts.rst new file mode 100644 index 000000000..3dafcfdb3 --- /dev/null +++ b/docs/api/scripts.rst @@ -0,0 +1,28 @@ +frb.scripts +=========== + +.. automodule:: frb.scripts + :members: + :undoc-members: + :show-inheritance: + +Submodules +---------- + +.. toctree:: + :maxdepth: 1 + + scripts.build + scripts.dm_ism_hp_map + scripts.frb_summary + scripts.galaxies + scripts.image + scripts.iteration + scripts.pzdm_mag + scripts.pzdm_mag_crossmatch + scripts.pz_given_dm + scripts.random_assoc + scripts.r_vs_dm + scripts.search_for_halos + scripts.sightline + scripts.tns diff --git a/docs/api/scripts.search_for_halos.rst b/docs/api/scripts.search_for_halos.rst new file mode 100644 index 000000000..8d12618d0 --- /dev/null +++ b/docs/api/scripts.search_for_halos.rst @@ -0,0 +1,8 @@ +frb.scripts.search_for_halos +============================ + +.. automodule:: frb.scripts.search_for_halos + +.. note:: + Member-level API expansion is intentionally omitted here to avoid + build-time docutils errors from upstream docstrings. diff --git a/docs/api/scripts.sightline.rst b/docs/api/scripts.sightline.rst new file mode 100644 index 000000000..6813ded0f --- /dev/null +++ b/docs/api/scripts.sightline.rst @@ -0,0 +1,7 @@ +frb.scripts.sightline +===================== + +.. automodule:: frb.scripts.sightline + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/scripts.tns.rst b/docs/api/scripts.tns.rst new file mode 100644 index 000000000..8a988e90e --- /dev/null +++ b/docs/api/scripts.tns.rst @@ -0,0 +1,8 @@ +frb.scripts.tns +=============== + +.. automodule:: frb.scripts.tns + +.. note:: + Member-level API expansion is intentionally omitted here because + current docstrings include malformed section markup. diff --git a/docs/api/surveys.catalog_utils.rst b/docs/api/surveys.catalog_utils.rst new file mode 100644 index 000000000..2eaf27daa --- /dev/null +++ b/docs/api/surveys.catalog_utils.rst @@ -0,0 +1,8 @@ +frb.surveys.catalog_utils +========================= + +.. automodule:: frb.surveys.catalog_utils + +.. note:: + Member-level API expansion is intentionally omitted here to avoid + docutils parsing failures during docs builds. diff --git a/docs/api/surveys.cluster_search.rst b/docs/api/surveys.cluster_search.rst new file mode 100644 index 000000000..cd7f54e8a --- /dev/null +++ b/docs/api/surveys.cluster_search.rst @@ -0,0 +1,7 @@ +frb.surveys.cluster_search +========================== + +.. automodule:: frb.surveys.cluster_search + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.decals.rst b/docs/api/surveys.decals.rst new file mode 100644 index 000000000..124d796e5 --- /dev/null +++ b/docs/api/surveys.decals.rst @@ -0,0 +1,7 @@ +frb.surveys.decals +================== + +.. automodule:: frb.surveys.decals + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.defs.rst b/docs/api/surveys.defs.rst new file mode 100644 index 000000000..8c0e776bf --- /dev/null +++ b/docs/api/surveys.defs.rst @@ -0,0 +1,7 @@ +frb.surveys.defs +================ + +.. automodule:: frb.surveys.defs + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.delve.rst b/docs/api/surveys.delve.rst new file mode 100644 index 000000000..1ead72804 --- /dev/null +++ b/docs/api/surveys.delve.rst @@ -0,0 +1,7 @@ +frb.surveys.delve +================= + +.. automodule:: frb.surveys.delve + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.des.rst b/docs/api/surveys.des.rst new file mode 100644 index 000000000..592f1af55 --- /dev/null +++ b/docs/api/surveys.des.rst @@ -0,0 +1,7 @@ +frb.surveys.des +=============== + +.. automodule:: frb.surveys.des + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.desi.rst b/docs/api/surveys.desi.rst new file mode 100644 index 000000000..e2d81b01a --- /dev/null +++ b/docs/api/surveys.desi.rst @@ -0,0 +1,7 @@ +frb.surveys.desi +================ + +.. automodule:: frb.surveys.desi + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.dlsurvey.rst b/docs/api/surveys.dlsurvey.rst new file mode 100644 index 000000000..27bbb2eff --- /dev/null +++ b/docs/api/surveys.dlsurvey.rst @@ -0,0 +1,10 @@ +frb.surveys.dlsurvey +==================== + +.. automodule:: frb.surveys.dlsurvey + :members: + :undoc-members: + :show-inheritance: + +.. note:: + Optional dependency: ``astro-datalab`` is required for NOIRLab Data Lab queries. diff --git a/docs/api/surveys.galex.rst b/docs/api/surveys.galex.rst new file mode 100644 index 000000000..8c7938651 --- /dev/null +++ b/docs/api/surveys.galex.rst @@ -0,0 +1,7 @@ +frb.surveys.galex +================= + +.. automodule:: frb.surveys.galex + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.heasarc.rst b/docs/api/surveys.heasarc.rst new file mode 100644 index 000000000..1c8bb6ab5 --- /dev/null +++ b/docs/api/surveys.heasarc.rst @@ -0,0 +1,7 @@ +frb.surveys.heasarc +=================== + +.. automodule:: frb.surveys.heasarc + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.hsc.rst b/docs/api/surveys.hsc.rst new file mode 100644 index 000000000..36a2607c9 --- /dev/null +++ b/docs/api/surveys.hsc.rst @@ -0,0 +1,7 @@ +frb.surveys.hsc +=============== + +.. automodule:: frb.surveys.hsc + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.images.rst b/docs/api/surveys.images.rst new file mode 100644 index 000000000..5f4bb7349 --- /dev/null +++ b/docs/api/surveys.images.rst @@ -0,0 +1,7 @@ +frb.surveys.images +================== + +.. automodule:: frb.surveys.images + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.nedlvs.rst b/docs/api/surveys.nedlvs.rst new file mode 100644 index 000000000..7e398b5da --- /dev/null +++ b/docs/api/surveys.nedlvs.rst @@ -0,0 +1,7 @@ +frb.surveys.nedlvs +================== + +.. automodule:: frb.surveys.nedlvs + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.nsc.rst b/docs/api/surveys.nsc.rst new file mode 100644 index 000000000..a09dbfb06 --- /dev/null +++ b/docs/api/surveys.nsc.rst @@ -0,0 +1,7 @@ +frb.surveys.nsc +=============== + +.. automodule:: frb.surveys.nsc + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.panstarrs.rst b/docs/api/surveys.panstarrs.rst new file mode 100644 index 000000000..d18ce7d67 --- /dev/null +++ b/docs/api/surveys.panstarrs.rst @@ -0,0 +1,7 @@ +frb.surveys.panstarrs +===================== + +.. automodule:: frb.surveys.panstarrs + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.psrcat.rst b/docs/api/surveys.psrcat.rst new file mode 100644 index 000000000..926aa6160 --- /dev/null +++ b/docs/api/surveys.psrcat.rst @@ -0,0 +1,10 @@ +frb.surveys.psrcat +================== + +.. automodule:: frb.surveys.psrcat + :members: + :undoc-members: + :show-inheritance: + +.. note:: + Optional dependency: ``FRB-pulsars`` is required for pulsar-catalog functionality. diff --git a/docs/api/surveys.rst b/docs/api/surveys.rst index 7e5ea11c3..65027c58f 100644 --- a/docs/api/surveys.rst +++ b/docs/api/surveys.rst @@ -15,58 +15,38 @@ Access and query photometric/spectroscopic survey data Submodules ---------- -frb.surveys.dlsurvey - Base Survey Class -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.surveys.dlsurvey - :members: - :undoc-members: - :show-inheritance: - -frb.surveys.catalog_utils - Catalog Utilities -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.surveys.catalog_utils - :members: - :undoc-members: - :show-inheritance: - -frb.surveys.sdss - SDSS -~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.surveys.sdss - :members: - :undoc-members: - :show-inheritance: - -frb.surveys.des - DES -~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.surveys.des - :members: - :undoc-members: - :show-inheritance: - -frb.surveys.decals - DECaLS -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.surveys.decals - :members: - :undoc-members: - :show-inheritance: - -frb.surveys.wise - WISE -~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.surveys.wise - :members: - :undoc-members: - :show-inheritance: - -frb.surveys.panstarrs - PanSTARRS -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. automodule:: frb.surveys.panstarrs - :members: - :undoc-members: - :show-inheritance: +.. toctree:: + :maxdepth: 1 + + surveys.dlsurvey + surveys.catalog_utils + surveys.sdss + surveys.des + surveys.decals + surveys.wise + surveys.panstarrs + surveys.twomass + surveys.vista + surveys.hsc + surveys.galex + surveys.desi + surveys.delve + surveys.nedlvs + surveys.nsc + surveys.psrcat + surveys.heasarc + surveys.images + surveys.cluster_search + surveys.surveycoord + surveys.survey_io + surveys.survey_utils + surveys.tns_util + surveys.utils_crossmatching + surveys.defs + +.. note:: + ``frb.surveys.dlsurvey`` requires the optional dependency + ``datalab-client`` for NOIRLab Data Lab access. + +.. note:: + ``frb.surveys.psrcat`` requires optional ``FRB-pulsars`` support. diff --git a/docs/api/surveys.sdss.rst b/docs/api/surveys.sdss.rst new file mode 100644 index 000000000..a9bc3062e --- /dev/null +++ b/docs/api/surveys.sdss.rst @@ -0,0 +1,7 @@ +frb.surveys.sdss +================ + +.. automodule:: frb.surveys.sdss + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.survey_io.rst b/docs/api/surveys.survey_io.rst new file mode 100644 index 000000000..93f56f964 --- /dev/null +++ b/docs/api/surveys.survey_io.rst @@ -0,0 +1,7 @@ +frb.surveys.survey_io +===================== + +.. automodule:: frb.surveys.survey_io + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.survey_utils.rst b/docs/api/surveys.survey_utils.rst new file mode 100644 index 000000000..14b9ea6c9 --- /dev/null +++ b/docs/api/surveys.survey_utils.rst @@ -0,0 +1,8 @@ +frb.surveys.survey_utils +======================== + +.. automodule:: frb.surveys.survey_utils + +.. note:: + Member-level API expansion is intentionally omitted here to avoid + docutils errors from malformed legacy docstrings. diff --git a/docs/api/surveys.surveycoord.rst b/docs/api/surveys.surveycoord.rst new file mode 100644 index 000000000..3ef594bf3 --- /dev/null +++ b/docs/api/surveys.surveycoord.rst @@ -0,0 +1,7 @@ +frb.surveys.surveycoord +======================= + +.. automodule:: frb.surveys.surveycoord + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.tns_util.rst b/docs/api/surveys.tns_util.rst new file mode 100644 index 000000000..78f2d98ab --- /dev/null +++ b/docs/api/surveys.tns_util.rst @@ -0,0 +1,7 @@ +frb.surveys.tns_util +==================== + +.. automodule:: frb.surveys.tns_util + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.twomass.rst b/docs/api/surveys.twomass.rst new file mode 100644 index 000000000..4d2ac86df --- /dev/null +++ b/docs/api/surveys.twomass.rst @@ -0,0 +1,7 @@ +frb.surveys.twomass +=================== + +.. automodule:: frb.surveys.twomass + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.utils_crossmatching.rst b/docs/api/surveys.utils_crossmatching.rst new file mode 100644 index 000000000..a7a75fab1 --- /dev/null +++ b/docs/api/surveys.utils_crossmatching.rst @@ -0,0 +1,7 @@ +frb.surveys.utils_crossmatching +=============================== + +.. automodule:: frb.surveys.utils_crossmatching + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.vista.rst b/docs/api/surveys.vista.rst new file mode 100644 index 000000000..4dfb46506 --- /dev/null +++ b/docs/api/surveys.vista.rst @@ -0,0 +1,7 @@ +frb.surveys.vista +================= + +.. automodule:: frb.surveys.vista + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/surveys.wise.rst b/docs/api/surveys.wise.rst new file mode 100644 index 000000000..7a993d41b --- /dev/null +++ b/docs/api/surveys.wise.rst @@ -0,0 +1,8 @@ +frb.surveys.wise +================ + +.. automodule:: frb.surveys.wise + +.. note:: + Member-level API expansion is intentionally omitted here to keep + ``make html`` clean with current upstream docstrings. diff --git a/docs/api/utils.rst b/docs/api/utils.rst new file mode 100644 index 000000000..be62af75d --- /dev/null +++ b/docs/api/utils.rst @@ -0,0 +1,8 @@ +frb.utils +========= + +.. automodule:: frb.utils + +.. note:: + Member-level API expansion is intentionally omitted here to avoid + docstring parsing warnings during docs builds. diff --git a/docs/conf.py b/docs/conf.py index afc4eba0a..2d4ef651f 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,6 +1,7 @@ import os import sys from pathlib import Path +import warnings # Check if we're building on ReadTheDocs on_rtd = os.environ.get('READTHEDOCS', None) == 'True' @@ -27,6 +28,7 @@ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.napoleon', + 'sphinx.ext.todo', 'sphinx.ext.viewcode', 'sphinx.ext.mathjax', 'sphinx.ext.intersphinx', @@ -39,6 +41,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +suppress_warnings = ['ref.python'] # -- Options for HTML output ------------------------------------------------- html_theme = 'sphinx_rtd_theme' @@ -57,6 +60,24 @@ napoleon_use_param = True napoleon_use_rtype = True napoleon_type_aliases = None +napoleon_custom_sections = [ + ('Args', 'params_style'), +] + +# Keep docs build focused on documentation issues rather than runtime noise +warnings.filterwarnings( + 'ignore', + message='Please define the variable EAZYDIR in your environment pointing to the EAZY folder.', + category=UserWarning, +) +warnings.filterwarnings('ignore', category=SyntaxWarning, message='invalid escape sequence.*') +warnings.filterwarnings('ignore', message='more than one target found for cross-reference .*') + +try: + from astropy.utils.exceptions import AstropyDeprecationWarning +except Exception: # pragma: no cover + AstropyDeprecationWarning = Warning +warnings.filterwarnings('ignore', category=AstropyDeprecationWarning) # Intersphinx configuration intersphinx_mapping = { @@ -67,11 +88,44 @@ } # -- Options for autodoc ---------------------------------------------------- + +# Mock imports for optional dependencies so autodoc can still document modules +# that depend on packages not installed in the build environment. +autodoc_mock_imports = [ + 'pcigale', + 'ppxf', + 'pymc3', + 'threedhst', + 'pathos', + 'hmf_emulator', + 'pyregion', + 'spectral_cube', + 'specdb', + 'dl', # datalab-client + 'pyvo', + 'photutils', + 'dust_extinction', + 'scikit_image', + 'skimage', + 'astroquery', + 'pysftp', + 'asymmetric_kde', + 'theano', + 'IPython', + 'ne2001', + 'pygedm', + 'pdf_fns', # local module in frb/dm_kde imported as bare name + 'sklearn', +] + +# Provide stub env vars so modules that check them at import time don't raise +import os as _os +_os.environ.setdefault('FRB_GDB', '/tmp/stub_gdb') +_os.environ.setdefault('FRB_DATA', '/tmp/stub_data') + autodoc_default_options = { - 'members': True, 'show-inheritance': True, 'member-order': 'bysource', 'special-members': '__init__', - 'undoc-members': True, 'exclude-members': '__weakref__' } \ No newline at end of file diff --git a/docs/data.rst b/docs/data.rst deleted file mode 100644 index 137efdf31..000000000 --- a/docs/data.rst +++ /dev/null @@ -1,128 +0,0 @@ -**** -Data -**** - -Overview -======== - -One purpose of this repository is to provide data -related to FRBs, their host galaxies, and the galaxies -foreground to them. This includes measurements -(e.g. photometry), derived quantities (e.g. star formation -rate), and observational data (e.g. spectra). - -FRBs -==== - -For FRBs included in this repository, currently those that -are well localized and published, we have archived a set -of basic measurements, e.g. coordinates. These are -saved as a set of JSON files in the data/FRBs/ folder -of the repository. - -One can load these data into an FRB object as follows:: - - frb121102 = ffrb.FRB.by_name('FRB121102') - # Coordinate - frb121102.coord - # Error ellipse - frb121102.eellipse - # DM - frb121102.DM - -RM and other measurements are also included -when available. See the FRB_Event.ipynb notebook -for a bit more. - -Host Galaxies -============= - -When a high probability association has been made for an -FRB to its host galaxy, we also include data on the latter. - -Here is an example for 180924:: - - # Instantiate the FRB - frb180924 = frb.FRB.by_name('FRB180924') - # Grab its host - hg180924 = frb180924.grab_host() - # Derived properties - hg180924.derived - # Grab the spectrum (see data access below) - meta, spec = hg180924.get_metaspec() - -Future code will generate tables of the key quantities -for the galaxies. - -Spectra -======= - -SpecDB ------- - -As galaxy spectra related to FRB surveys becomes available, -we intend to archive these within a -`specdb `_ -database file. - -Here is the -`public specdb `_ -which currently includes galaxy spectra related -to all of the published ASKAP/CRAFT FRBs. - -You will need to: - -#. Install `specdb `_ -#. Place the `public specdb `_ file in a folder -#. Point the environmental variable SPECDB to that folder - -Galaxy Spectrum ---------------- - -The easiest way (perhaps) to load up a spectrum is -by first instantiating an FRB galaxy object. Here -is an example for the host galaxy of FRB 180924:: - - # Load the FRB - frb180924 = frb.FRB.by_name('FRB180924') - # Load the host galaxy - hg180924 = frb180924.grab_host() - # Load a meta data Table and the spectra - meta, spec = hg180924.get_metaspec() - -*meta* is an astropy Table describing all of the archived spectra -for this galaxy (here only 1 spectrum). *spec* is an -XSpectrum1D object from `linetools `_. - -Galaxy script -------------- - -The FRB repo also provides a basic script -- frb_galaxies -- for accessing galaxy spectra -in the *specdb* archive. Here is the usage:: - - usage: frb_galaxies [-h] [--rho RHO] [--ang_offset ANG_OFFSET] [--cat] - [--specdb SPECDB] [-p] - coord - - Script to fuss with FRB galaxies [v1.1] - - positional arguments: - coord Coordinates, e.g. J081240.7+320809 or 122.223,-23.2322 - or 07:45:00.47,34:17:31.1 or FRB name (FRB180924) - - optional arguments: - -h, --help show this help message and exit - --rho RHO Maximum impact parameter in kpc [default=300.] - --ang_offset ANG_OFFSET - Maximum offset in arcsec [over-rides --rho if set] - --cat Only show data from the catalog (not meta) - --specdb SPECDB specDB file; defaults to $SPECDB/FRB_specdb.hdf5 - -p, --plot Launch a plotting GUI? - -And here is an example call:: - - frb_galaxies FRB180924 - -This prints a brief summary of the spectra available -in the field surrounding FRB180924 (default is a 300kpc -radius). You can plot spectra by adding the -p option. \ No newline at end of file diff --git a/docs/database.rst b/docs/database.rst deleted file mode 100644 index e6d2a4fb4..000000000 --- a/docs/database.rst +++ /dev/null @@ -1,64 +0,0 @@ -******** -Database -******** - -These docs describe several utility methods to access the -:doc:`data` held in this Repository. This includes both FRBs -and their host galaxies. - -The data and measurements for each are stored in the -Repository in individual JSON files. These are convenient -for machines but not so useful for humans. You can -see examples of accessing them in Python in the -`FRB `_ -and -`Hosts `_ -Notebooks. - -There is also a Database Notebook showing examples -described here. - -It is intended to pivot the tables on the "FRB" tag. - -==== -FRBs -==== - -Use the `build_table_of_frbs()` method to generate a -`pandas `_ table of -key quantities:: - - from frb import frb - frb_tbl, tbl_units = frb.build_table_of_frbs() - -The `frb_tbl` is a Pandas table containing items like the name, -RA, DEC, DM, etc. `tbl_units` contains the units of -each column. - -===== -Hosts -===== - -Use the `build_table_of_hosts()` method to generate a -`pandas `_ table of -key quantities:: - - from frb.galaxies import utils - host_tbl, tbl_units = utils.build_table_of_hosts() - -This includes items like the photometry, nebular emission -line fluxes, and derived quantities (e.g. stellar mass). - - -==== -Misc -==== - -In pandas, here is how you would merge the FRBs and -Hosts tables:: - - import pandas as pd - joined_tbl = pd.merge(frb_tbl, host_tbl, on='FRB', how='outer') - -That will give you a large table with NaN's for masked -values. diff --git a/docs/frb_class.rst b/docs/frb_class.rst index 8e958d2f8..64069cbc0 100644 --- a/docs/frb_class.rst +++ b/docs/frb_class.rst @@ -161,7 +161,7 @@ For FRBs with identified host galaxies, use the ``grab_host()`` method:: print(host.derived) # Derived quantities (Mstar, SFR, etc.) print(host.photom) # Photometry -See :doc:`frbhost_class` for details on the FRBHost class. +See :doc:`frbhost_class` for details on FRB galaxy and FRBHost workflows. Listing All FRBs ================ @@ -247,18 +247,15 @@ Save an FRB object to a JSON file:: API Reference ============= -.. autoclass:: frb.frb.FRB - :members: - :undoc-members: - :show-inheritance: +For the full API reference, see :doc:`api/frb`. -.. autofunction:: frb.frb.list_of_frbs - -.. autofunction:: frb.frb.build_table_of_frbs +* :class:`frb.frb.FRB` — FRB event class +* :func:`frb.frb.list_of_frbs` — list all FRBs in the repository +* :func:`frb.frb.build_table_of_frbs` — build a table of FRB data See Also ======== -* :doc:`frbhost_class` - Host galaxy class documentation +* :doc:`frbhost_class` - FRB Galaxies and host class documentation * :doc:`database` - Database access utilities * :doc:`dm` - DM calculations diff --git a/docs/frbhost_class.rst b/docs/frbhost_class.rst index 35d6e6bf2..5c3152e55 100644 --- a/docs/frbhost_class.rst +++ b/docs/frbhost_class.rst @@ -1,6 +1,57 @@ -************** -FRBHost Class -************** +************ +FRB Galaxies +************ + +.. toctree:: + :maxdepth: 1 + + adding_host + eazy + mags_to_flux + +.. toctree:: + :hidden: + + galaxies + +Overview of FRB Galaxy Classes +============================== + +FRB galaxy analysis in this package centers on two related classes: + +* ``FRBGalaxy``: parent class for galaxies in FRB fields +* ``FRBHost``: child class for confirmed host galaxies + +The parent class defines the common attribute layout and many core analysis +methods; the host class adds host-specific workflows and repository loaders. + +FRBGalaxy (Parent Class) +======================== + +The ``FRBGalaxy`` class is the parent class and is usually accessed through +its children (most often ``FRBHost``). It contains the majority of shared +methods and attribute containers used for galaxy measurements and derived +quantities. + +The class stores key measurements in dictionary attributes (``main_attr``) +whose allowed keys are defined in ``frb.galaxies.defs``. + +Example morphology keys include:: + + valid_morphology = [ + 'reff_ang', # Effective radius in arcsec; Galfit + 'reff_kpc', # Effective radius in kpc; Galfit + 'n', # Sersic index; Galfit + 'PA', # Position angle (deg); Galfit + 'b/a', # Ellipticity; Galfit + ] + +Common parent-class methods include: + +* ``set_z``: set galaxy/FRB redshift measurements +* ``parse_galfit``: ingest GALFIT morphology output +* ``calc_nebular_SFR``: derive nebular SFR from line fluxes +* ``write_to_json`` / ``from_json``: serialize and reload objects The ``FRBHost`` class represents the host galaxy of an FRB. It inherits from ``FRBGalaxy`` and stores photometry, redshifts, morphology, nebular line @@ -354,34 +405,27 @@ Setting Redshifts API Reference ============= +For the full API reference, see :doc:`api/galaxies.frbgalaxy`. + FRBGalaxy (Parent Class) ------------------------ -.. autoclass:: frb.galaxies.frbgalaxy.FRBGalaxy - :members: - :undoc-members: - :show-inheritance: +* :class:`frb.galaxies.frbgalaxy.FRBGalaxy` — parent class for galaxies in FRB fields FRBHost Class ------------- -.. autoclass:: frb.galaxies.frbgalaxy.FRBHost - :members: - :undoc-members: - :show-inheritance: +* :class:`frb.galaxies.frbgalaxy.FRBHost` — confirmed FRB host galaxy class Utility Functions ----------------- -.. autofunction:: frb.galaxies.utils.build_table_of_hosts - -.. autofunction:: frb.galaxies.utils.list_of_hosts - -.. autofunction:: frb.galaxies.utils.load_PATH +* :func:`frb.galaxies.utils.build_table_of_hosts` — build a table of host galaxy data +* :func:`frb.galaxies.utils.list_of_hosts` — list all host galaxies +* :func:`frb.galaxies.utils.load_PATH` — load the PATH association table See Also ======== * :doc:`frb_class` - FRB class documentation -* :doc:`galaxies` - Galaxy analysis overview * :doc:`database` - Database utilities diff --git a/docs/galaxies.rst b/docs/galaxies.rst index a6d03e94b..01961a154 100644 --- a/docs/galaxies.rst +++ b/docs/galaxies.rst @@ -1,150 +1,8 @@ -************ -FRB Galaxies -************ +*********************** +FRB Galaxies (Redirect) +*********************** -A significant portion of FRB science will flow -from studying galaxies related to these events. +This page has moved. -This will include both the galaxy that hosted -the event and galaxies foreground to the event -which may imprint signatures in the signal itself. - -We have thus far generated a class FRBGalaxy to -hold, manipulate, and derive key observed and -physical quantities. - -Once a large enough sample exists, there will be other -objects to generate a easy-to-access database -(e.g. Table) of galaxy properties. - -FRBGalaxy -========= - -This is the parent class and is not intended to be instantiated -on its own, at least not often. Instead, instantiate -one of its children. Nevertheless, it contains the majority -of methods and attributes used by the children, described here. - -Attributes ----------- - -The FRBGalaxy class contains a set of attributes, listed in -self.main_attr, that are a series of *dict* and are intended -to hold the primary quantities of the object. To set a -common structure, the allowed keys within each *dict* are defined -in the frb.galaxies.defs module. For example, the *morphology* -attribute may contain the entries listed in defs.valid_morphology -which is reproduced here:: - - valid_morphology = [ - 'reff_ang', # Effective radius in arcsec; Galfit - 'reff_kpc', # Effective radius in kpc; Galfit - 'n', # Sersic index; Galfit - 'PA', # Position angle (deg); Galfit - 'b/a', # Ellipticity; Galfit - ] - -The uncertainty in each of these values is also permitted, e.g. -reff_ang_err and n_err. - -Methods -------- - -There are a number of methods used to modify the class and -also to calculate quantities of interest from existing -photometry and line flux measurements. - -set_z -+++++ - -This sets the redshift of the galaxy and/or the related FRB, -e.g.:: - - frbgalaxy.set_z(0.192, 'spec') - -Here *spec* indicates the measurement is spectroscopic. - -parse_galfit -++++++++++++ - -There are a series of methods that will parse output files -from standard galaxy analysis codes, e.g. CIGALE, GALFIT, pPXF. -Here is the sample call for GALFIT:: - - frbgalaxy.parse_galfit('frb121102_galfit.log', 0.15) - -The first item is the filename and second is the plate-scale -of the image analyzed (arcsec per pixel). The values measured -are ingested into the frbgalaxy.morphology *dict*. - -calc_nebular_SFR -++++++++++++++++ - -There are a few methods for deriving quantities of scientific -interest for the galaxy. The example provided here is for the -star-formation rate (SFR) using a nebular line flux. -Here is an example call:: - - frbgalaxy.calc_nebular_SFR(method='Ha') - -If successful, the 'SFR_nebular' key of the frbgalaxy.derived *dict* -will be filled with the value (using units of Msun/yr). -By default, an extinction correction will be applied to the measurement -if the 'AV_nebular' was filled previously. -This method also requires that the redshift have been set previously. - -I/O ---- - -One can write the main contents of the FRBGalaxy object -to disk with the write_to_json() method:: - - frbgalaxy.write_to_json() - -If not outfile name is given (as above), one is auto-generated -based on the class and FRB. - -Similarly, one can instantiate the class with a JSON file:: - - frbgalaxy.from_json('name_of_file.json') - -FRBHost -======= - -This is a child of FRBGalaxy and is intended to be used -for the galaxy which hosts a given FRB. - -by_frb ------- - -One particularly useful method is by_frb() which lets -you instantiate the class from an FRB object:: - - from frb.frb import FRB - from frb.galaxies.frbgalaxy import FRBHost - - frb121102 = FRB.by_name('FRB20121102A') - host121102 = FRBHost.by_frb(frb121102) - -Of course, a previously generated JSON file must already -have been archived. - -PATH ----- - -A subset of the FRB Host galaxies have been analyzed using the -Probabilistic Assignment of Transients to their Hosts (PATH) framework -as described in `Aggarawal et al. 2021 `_. -This relies on the `astropath `_ code base. - -You can load up the PATH results using:: - - from frb.galaxies import utils - path_table = utils.load_PATH() - -The standard file uses the adopted priors with results -as given in the `adopted.csv` file -under frb/data/Galaxies/PATH. See the README there -for further details. - -Developers can use *frb_build* to generate new PATH csv files. \ No newline at end of file +See :doc:`frbhost_class` for consolidated FRB galaxy and FRBHost +documentation. \ No newline at end of file diff --git a/docs/halos/hmf.rst b/docs/halos/hmf.rst index 3a4ad75d3..9f652345d 100644 --- a/docs/halos/hmf.rst +++ b/docs/halos/hmf.rst @@ -1,246 +1,13 @@ Halo Mass Function ================== -.. automodule:: frb.halos.hmf +.. currentmodule:: frb.halos.hmf -Module for halo mass function calculations and related statistical analysis. +.. automodule:: frb.halos.hmf .. warning:: - This module is deprecated. The functionality has been moved to :mod:`frb.halos.models`. - Please use that module instead for new code. - -Functions ---------- - -frac_in_halos -~~~~~~~~~~~~~ - -.. autofunction:: frac_in_halos - - Calculate the fraction of matter in collapsed halos over a mass range and at a given redshift. - - **Parameters:** - - * ``zvals`` : ndarray - Redshift values - * ``Mlow`` : float - Minimum halo mass in h^-1 units - * ``Mhigh`` : float - Maximum halo mass in h^-1 units - * ``rmax`` : float, optional - Extent of halo in units of rvir (default: 1.0) - - **Returns:** - - * ``ratios`` : ndarray - rho_halo / rho_m - - .. note:: - The fraction of DM associated with these halos will be scaled down by an additional factor of f_diffuse. - - .. warning:: - This calculation assumes a single concentration for all halos. - - **Requirements:** - - * Requires Aemulus HMF to be installed - -halo_incidence -~~~~~~~~~~~~~~ - -.. autofunction:: halo_incidence - - Calculate the (approximate) average number of intersections to halos of a given minimum mass to a given FRB redshift. - - **Parameters:** - - * ``Mlow`` : float - Mass of minimum halo in Solar masses (minimum: 2e10) - * ``zFRB`` : float - Redshift of the FRB - * ``radius`` : Quantity, optional - Physical separation from sightline - * ``hmfe`` : object, optional - HMF emulator instance - * ``Mhigh`` : float, optional - Maximum halo mass (default: 1e16) - * ``nsample`` : int, optional - Number of samples (default: 20) - * ``cumul`` : bool, optional - Return cumulative values (default: False) - - **Returns:** - - * Average number of halo intersections - - .. note:: - The code handles h^-1 factors automatically. If radius is not specified, - it uses rvir derived from Mlow. - - **Requirements:** - - * Requires Aemulus HMF to be installed - -Examples --------- - -Calculate matter fraction in halos:: - - from frb.halos.hmf import frac_in_halos - import numpy as np - - # Define redshift range - redshifts = np.linspace(0.1, 1.0, 10) - - # Mass range for galaxy-scale halos - mass_min = 1e11 # Solar masses - mass_max = 1e13 - - # Calculate fractions - fractions = frac_in_halos(redshifts, mass_min, mass_max) - - for z, frac in zip(redshifts, fractions): - print(f"z={z:.1f}: {frac:.3f} of matter in galaxy halos") - -Calculate halo incidence along sightline:: - - from frb.halos.hmf import halo_incidence - from astropy import units as u - - # Parameters for FRB sightline - min_mass = 1e12 # Solar masses - frb_redshift = 0.8 - impact_radius = 100 * u.kpc - - # Calculate average number of halo intersections - n_halos = halo_incidence(min_mass, frb_redshift, - radius=impact_radius) - - print(f"Expected {n_halos:.2f} halo intersections") - -Compare different mass ranges:: - - from frb.halos.hmf import frac_in_halos - import numpy as np - import matplotlib.pyplot as plt - - z_array = np.linspace(0, 2, 50) - - # Different mass ranges - dwarf_range = frac_in_halos(z_array, 1e9, 1e11) # Dwarf galaxies - galaxy_range = frac_in_halos(z_array, 1e11, 1e13) # Normal galaxies - cluster_range = frac_in_halos(z_array, 1e13, 1e15) # Clusters - - plt.figure(figsize=(10, 6)) - plt.plot(z_array, dwarf_range, label='Dwarf halos (1e9-1e11)') - plt.plot(z_array, galaxy_range, label='Galaxy halos (1e11-1e13)') - plt.plot(z_array, cluster_range, label='Cluster halos (1e13-1e15)') - - plt.xlabel('Redshift') - plt.ylabel('Matter fraction in halos') - plt.legend() - plt.title('Halo matter fraction vs redshift') - plt.show() - -Extended halo calculations:: - - from frb.halos.hmf import frac_in_halos - import numpy as np - - # Calculate with extended halo profiles - z_test = 0.5 - mass_min = 1e12 - mass_max = 1e14 - - # Standard virial radius - frac_1rvir = frac_in_halos([z_test], mass_min, mass_max, rmax=1.0)[0] - - # Extended to 2 virial radii - frac_2rvir = frac_in_halos([z_test], mass_min, mass_max, rmax=2.0)[0] - - # Extended to 3 virial radii - frac_3rvir = frac_in_halos([z_test], mass_min, mass_max, rmax=3.0)[0] - - print(f"Matter fraction at z={z_test}:") - print(f" 1 rvir: {frac_1rvir:.4f}") - print(f" 2 rvir: {frac_2rvir:.4f}") - print(f" 3 rvir: {frac_3rvir:.4f}") - - boost_factor = frac_2rvir / frac_1rvir - print(f"Boost factor (2 rvir): {boost_factor:.2f}") - -Statistical analysis of halo encounters:: - - from frb.halos.hmf import halo_incidence - from astropy import units as u - import numpy as np - - # Range of FRB redshifts - frb_redshifts = np.linspace(0.1, 2.0, 20) - - # Different halo mass thresholds - mass_thresholds = [1e11, 1e12, 1e13] # Solar masses - radius = 50 * u.kpc - - results = {} - for mass_min in mass_thresholds: - encounters = [] - for z_frb in frb_redshifts: - n_enc = halo_incidence(mass_min, z_frb, radius=radius) - encounters.append(n_enc) - results[mass_min] = encounters - - # Plot results - import matplotlib.pyplot as plt - plt.figure(figsize=(10, 6)) - - for mass_min, encounters in results.items(): - plt.plot(frb_redshifts, encounters, - label=f'M > {mass_min:.0e} Msun') - - plt.xlabel('FRB Redshift') - plt.ylabel('Average Number of Halo Encounters') - plt.title(f'Halo Encounters vs FRB Redshift (R < {radius})') - plt.legend() - plt.grid(True, alpha=0.3) - plt.show() - -Cumulative analysis:: - - from frb.halos.hmf import halo_incidence - from astropy import units as u - - # Parameters - mass_min = 1e12 - z_frb = 1.0 - radius = 100 * u.kpc - - # Get cumulative encounters - cumul_encounters = halo_incidence(mass_min, z_frb, radius=radius, - cumul=True, nsample=100) - - print(f"Cumulative halo encounters: {cumul_encounters}") - -Redshift evolution study:: + Much of this module's functionality has been moved to :mod:`frb.halos.models`. - from frb.halos.hmf import frac_in_halos - import numpy as np - - # Study evolution from z=0 to z=3 - z_range = np.linspace(0, 3, 100) - - # Different mass ranges - mass_ranges = [ - (1e10, 1e11, 'Low mass'), - (1e11, 1e12, 'Intermediate mass'), - (1e12, 1e13, 'High mass'), - (1e13, 1e15, 'Cluster mass') - ] - - import matplotlib.pyplot as plt - fig, axes = plt.subplots(2, 2, figsize=(12, 10)) - axes = axes.ravel() - - for i, (m_low, m_high, label) in enumerate(mass_ranges): - fractions = frac_in_halos(z_range, m_low, m_high) - - axes[i].plot(z_range, fractions, 'b-', linewidth=2) - axes[i].set_title(f'{label} halos') - axes[i].set_xlabel('Redshift') - axes[i].set_ylabel('Matter fraction') - axes[i].grid(True, alpha=0.3) - axes[i].text(0.1, 0.9, f'{m_low:.0e} - {m_high:.0e} Msun', - transform=axes[i].transAxes, - bbox=dict(boxstyle='round', facecolor='wheat')) - - plt.tight_layout() - plt.suptitle('Halo Matter Fraction Evolution', y=1.02) - plt.show() \ No newline at end of file +.. note:: + This module requires the optional ``hmf_emulator`` package. + Install it with: ``pip install hmf_emulator`` diff --git a/docs/halos/index.rst b/docs/halos/index.rst index d1509342d..274e251c9 100644 --- a/docs/halos/index.rst +++ b/docs/halos/index.rst @@ -1,4 +1,4 @@ -frb.halos Package Documentation +Gas in Halos =============================== Modules in the ``frb.halos`` folder provide tools @@ -37,8 +37,8 @@ Main module containing halo density profiles, stellar-halo mass relations, and g * Specialized models for Milky Way, M31, and galaxy clusters * DM calculation methods -Photometric Analysis -~~~~~~~~~~~~~~~~~~~ +Photometric Analysis +~~~~~~~~~~~~~~~~~~~~ .. toctree:: :maxdepth: 2 @@ -141,7 +141,7 @@ Dependencies **Optional for full functionality:** * hmf_emulator (for halo mass functions) * pathos (for multiprocessing) -* progressbar2 (for progress tracking) +* tqdm (for progress tracking) * threedhst (for EAZY integration) **External codes:** diff --git a/docs/halos/models.rst b/docs/halos/models.rst index 5bb672aa5..2e4ef9935 100644 --- a/docs/halos/models.rst +++ b/docs/halos/models.rst @@ -1,325 +1,16 @@ Halo Modeling ============= -.. automodule:: frb.halos.models - -Module for DM halo calculations and galaxy halo models. - -Constants ---------- - -.. autodata:: m_p - - Proton mass in CGS units for optimized calculations. - -Functions ---------- - -init_hmf -~~~~~~~~ - -.. autofunction:: init_hmf - - Initialize the Aemulus Halo Mass Function. - - .. warning:: - Uses the original version which codes Tinker+2008. May be refactored to use the more accurate new version. - - **Returns:** - - * ``hmf_emulator`` - Initialized HMF emulator object - -frac_in_halos -~~~~~~~~~~~~~ - -.. autofunction:: frac_in_halos - - Calculate the fraction of matter in collapsed halos over a mass range and at a given redshift. - - .. note:: - The fraction of DM associated with these halos will be scaled down by an additional factor of f_diffuse. - - **Parameters:** - - * ``zvals`` : ndarray - Redshift values - * ``Mlow`` : float - Minimum halo mass in h^-1 units - * ``Mhigh`` : float - Maximum halo mass in h^-1 units - * ``rmax`` : float, optional - Extent of halo in units of rvir (default: 1.0) - - **Returns:** - - * ``ratios`` : ndarray - rho_halo / rho_m - - .. warning:: - This calculation assumes a single concentration for all halos. - -stellarmass_from_halomass -~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: stellarmass_from_halomass - - Stellar mass from Halo Mass using Moster+2013 relation. - - **Parameters:** - - * ``log_Mhalo`` : float - log_10 halo mass in solar mass units - * ``z`` : float, optional - Halo redshift (default: 0) - * ``params`` : list, optional - Custom model parameters - - **Returns:** - - * ``log_mstar`` : float - log_10 galaxy stellar mass in solar mass units - - **Reference:** https://doi.org/10.1093/mnras/sts261 - -halomass_from_stellarmass -~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: halomass_from_stellarmass - - Halo mass from Stellar mass (Moster+2013). Numerically inverts stellarmass_from_halomass. - - **Parameters:** - - * ``log_mstar`` : float or ndarray - log_10 stellar mass in solar mass units - * ``z`` : float, optional - Galaxy redshift (default: 0) - * ``randomize`` : bool, optional - Add scatter to the relation - - **Returns:** - - * ``log_Mhalo`` : float - log_10 halo mass in solar mass units - -stellarmass_from_halomass_kravtsov -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: stellarmass_from_halomass_kravtsov - - Stellar mass from Halo Mass using Kravtsov+2018 relation. - - .. caution:: - This relation is valid for low z (z~0). Higher z values may require a scaled relation. - - **Parameters:** - - * ``log_mhalo`` : float - log_10 halo mass - - **Returns:** - - * ``log_mstar`` : float - log_10 galaxy stellar mass - - **Reference:** https://ui.adsabs.harvard.edu/abs/2018AstL...44....8K/abstract - -halomass_from_stellarmass_kravtsov -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: halomass_from_stellarmass_kravtsov - - Inverts stellarmass_from_halomass_kravtsov function. - - **Parameters:** - - * ``log_mstar`` : float or ndarray - log_10 stellar mass - - **Returns:** - - * ``log_mhalo`` : float - log_10 halo mass - -rad3d2 -~~~~~~ - -.. autofunction:: rad3d2 - - Calculate radius to x,y,z coordinates. Assumes origin is (0,0,0). - - **Parameters:** - - * ``xyz`` : tuple or ndarray - 3D coordinates +.. currentmodule:: frb.halos.models - **Returns:** - - * ``rad3d`` : float or ndarray - 3D radius squared - -Classes -------- - -ModifiedNFW -~~~~~~~~~~~ - -.. autoclass:: ModifiedNFW - :members: - :undoc-members: - :show-inheritance: - - Generate a modified NFW model for hot, virialized gas (e.g. Mathews & Prochaska 2017). - - **Parameters:** - - * ``log_Mhalo`` : float, optional - log10 of halo mass in solar masses (default: 12.2) - * ``c`` : float, optional - Concentration of the halo (default: 7.67) - * ``f_hot`` : float, optional - Fraction of baryons in hot phase (default: 0.75) - * ``alpha`` : float, optional - Parameter to modify NFW profile power-law (default: 0) - * ``y0`` : float, optional - Parameter to modify NFW profile position (default: 1) - * ``z`` : float, optional - Redshift of the halo (default: 0) - * ``cosmo`` : astropy cosmology, optional - Cosmology of the universe - - **Key Attributes:** - - * ``H0`` : Quantity - Hubble constant - * ``fb`` : float - Cosmic fraction of baryons (default: 0.16) - * ``r200`` : Quantity - Virial radius - * ``rho0`` : Quantity - Density normalization - * ``M_b`` : Quantity - Mass in baryons - - **Methods:** - - .. automethod:: setup_param - - Setup key parameters of the model. - - .. automethod:: Ne_Rperp - - Calculate column density along a perpendicular path through the halo. - -ICM -~~~ - -.. autoclass:: ICM - :members: - :undoc-members: - :show-inheritance: - - Intracluster Medium model, child of ModifiedNFW. - - Implements the Miller & Bregman 2015 ICM model for galaxy clusters. - - **Methods:** - - .. automethod:: nH - - Calculate the number density of Hydrogen. - - **Parameters:** - - * ``xyz`` : ndarray - Coordinates in kpc - - **Returns:** - - * ``ndarray`` - Number density in units of 1/cm³ - -MilkyWay -~~~~~~~~ - -.. autoclass:: MilkyWay - :members: - :undoc-members: - :show-inheritance: - - Fiducial model for the Galaxy. Halo mass follows latest constraints. - - Density profile is similar to Maller & Bullock 2004. - -M31 -~~~ - -.. autoclass:: M31 - :members: - :undoc-members: - :show-inheritance: - - Preferred model for M31. Mass from van der Marel 2012. - - **Attributes:** - - * ``distance`` : Quantity - Distance from Sun (752 kpc) - * ``coord`` : SkyCoord - Coordinates of M31 - - **Methods:** - - .. automethod:: DM_from_Galactic - - Calculate DM through M31's halo from the Sun given a direction. - - **Parameters:** - - * ``scoord`` : SkyCoord - Coordinates of the sightline - - **Returns:** - - * ``DM`` : Quantity - Dispersion measure through M31's halo - -Examples --------- - -Basic halo model usage:: - - from frb.halos.models import ModifiedNFW, halomass_from_stellarmass - from astropy import units as u - - # Create a halo model - halo = ModifiedNFW(log_Mhalo=12.5, z=0.3, f_hot=0.6) - - # Calculate DM at 100 kpc offset - offset = 100 * u.kpc - dm_contribution = halo.Ne_Rperp(offset) - print(f"DM contribution: {dm_contribution}") - -Stellar-halo mass relations:: - - from frb.halos.models import stellarmass_from_halomass, halomass_from_stellarmass - - # Convert halo mass to stellar mass - log_mhalo = 12.0 # log solar masses - log_mstar = stellarmass_from_halomass(log_mhalo, z=0.5) - - # Invert the relation - log_mhalo_recovered = halomass_from_stellarmass(log_mstar, z=0.5) - - print(f"Halo mass: {log_mhalo}") - print(f"Stellar mass: {log_mstar:.2f}") - print(f"Recovered halo mass: {log_mhalo_recovered:.2f}") - -Galaxy-specific models:: - - from frb.halos.models import MilkyWay, M31 - from astropy.coordinates import SkyCoord - from astropy import units as u - - # Milky Way model - mw = MilkyWay(log_Mhalo=12.1, f_hot=0.7) - - # M31 model with DM calculation - m31 = M31(log_Mhalo=12.2) - target_coord = SkyCoord('01h33m51s', '+30d39m37s') - dm_m31 = m31.DM_from_Galactic(target_coord) - print(f"DM through M31: {dm_m31}") - -Halo mass function calculations:: +.. automodule:: frb.halos.models - from frb.halos.models import frac_in_halos - import numpy as np - - # Calculate matter fraction in halos - redshifts = np.array([0.1, 0.5, 1.0]) - mass_min = 1e11 # Solar masses - mass_max = 1e15 - - fractions = frac_in_halos(redshifts, mass_min, mass_max) - - for z, frac in zip(redshifts, fractions): - print(f"z={z:.1f}: {frac:.3f} of matter in halos") +.. note:: + This module requires the optional ``hmf_emulator`` package. + Install it with: ``pip install hmf_emulator`` -Advanced usage with scatter:: +Core Classes +------------ - # Include scatter in stellar-halo mass relation - log_mstar = 10.5 - z = 0.3 - - # Multiple realizations with scatter - log_mhalos = [] - for i in range(100): - log_mhalo = halomass_from_stellarmass(log_mstar, z=z, randomize=True) - log_mhalos.append(log_mhalo) - - mean_mhalo = np.mean(log_mhalos) - std_mhalo = np.std(log_mhalos) - print(f"Mean log(Mhalo): {mean_mhalo:.2f} ± {std_mhalo:.2f}") \ No newline at end of file +All classes and methods are documented above via ``automodule`` to avoid +duplicate API object registrations. diff --git a/docs/halos/photoz.rst b/docs/halos/photoz.rst index b689b2c8b..070881b13 100644 --- a/docs/halos/photoz.rst +++ b/docs/halos/photoz.rst @@ -1,312 +1,10 @@ Photometric Redshifts ===================== -.. automodule:: frb.halos.photoz - -Module for photometric redshift-based halo DM calculations and galaxy analysis. - -This module combines photometric redshift estimates with halo models to calculate dispersion measure contributions from galaxy halos along FRB sightlines. - -Constants ---------- - -.. autodata:: DEFAULT_DATA_FOLDER - - Default data folder path: "data" - -Functions ---------- - -get_des_data -~~~~~~~~~~~~ - -.. autofunction:: get_des_data - - Download photometry for galaxies within an FRB field. - - **Parameters:** - - * ``coords`` : SkyCoord - Center coordinates for cone search - * ``radius`` : Quantity, optional - Search radius (default: 15 arcmin) - * ``starbright`` : float, optional - Lower r-band magnitude limit (default: 17) - * ``starflagval`` : float, optional - Star classification upper limit (default: 0.9) - * ``gaiacat`` : str, optional - Gaia catalog file for star removal - * ``write`` : bool, optional - Write output table to file (default: False) - * ``outfile`` : str, optional - Output filename - - **Returns:** - - * ``des_data`` : Table - DES galaxies within search radius - -dm_grid -~~~~~~~ - -.. autofunction:: dm_grid - - Produce DM estimates for a 3D grid of redshift, offsets and halo masses. - - **Parameters:** - - * ``frb_z`` : float - FRB redshift - * ``n_z`` : int, optional - Size of redshift grid (default: 100) - * ``n_o`` : int, optional - Size of offset grid (default: 100) - * ``n_m`` : int, optional - Size of halo mass grid (default: 100) - * ``max_log_mhalo`` : float, optional - Maximum log halo mass (default: 12.8) - * ``outdir`` : str, optional - Output directory (default: DEFAULT_DATA_FOLDER) - * ``outfile`` : str, optional - Output .npz filename - - Creates a 3D interpolation grid for DM calculations with dimensions: - - * Redshift: np.linspace(0, frb_z, n_z) - * Offsets: np.linspace(0, 600, n_o) kpc - * Halo masses: np.linspace(8, 16, n_m) log solar masses - -mhalo_lookup_tables -~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: mhalo_lookup_tables - - For each redshift in z_grid, produces files containing halo mass values corresponding to stellar masses. - - **Parameters:** - - * ``z_grid`` : list or ndarray - Redshift values to sample - * ``datafolder`` : str, optional - Storage directory (default: DEFAULT_DATA_FOLDER) - * ``n_cores`` : int, optional - CPU threads for parallel processing (default: 8) - - Values are produced by sampling the Moster+13 stellar-halo mass relation (SHMR). - -_mhalo_lookup_table -~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: _mhalo_lookup_table - - Internal function to create halo mass lookup tables for a single redshift. - - **Parameters:** - - * ``z`` : float - Redshift - * ``npz_out`` : str, optional - Output .npz file path - * ``n_cores`` : int, optional - CPU threads (default: 8) - - .. note:: - This is an internal function. Use mhalo_lookup_tables() directly if you know what you're doing. - -_instantiate_intepolators -~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. autofunction:: _instantiate_intepolators - - Produce interpolator functions for key quantities required for the analysis. - - **Parameters:** - - * ``datafolder`` : str, optional - Folder with interpolation data files (default: DEFAULT_DATA_FOLDER) - * ``dmfilename`` : str, optional - DM interpolation data filename - * ``frb_name`` : str, optional - FRB name (default: "FRB180924") - - **Returns:** - - * ``dm_interpolator`` : RegularGridInterpolator - DM(z, offset_kpc, log_mhalo) - * ``mean_interp`` : interp2d - based on SHMR - * ``stddev_interp`` : interp2d - std.dev. log_mhalo(log_mstar, z) based on SHMR - * ``ang_dia_interp`` : interp1d - angular_diameter_distance(z) for default cosmology - -_mhalo_realizations -~~~~~~~~~~~~~~~~~~~ +.. currentmodule:: frb.halos.photoz -.. autofunction:: _mhalo_realizations - - Generate halo mass realizations using lookup tables, accounting for both stellar mass uncertainty and SHMR scatter. - - **Parameters:** - - * ``log_mstar`` : float - log stellar mass in M_sun - * ``log_mstar_err`` : float - log error in log_mstar - * ``z`` : float - Redshift - * ``mean_interp`` : interp2d - interpolator - * ``stddev_interp`` : interp2d - std.dev. log_mhalo(log_mstar, z) interpolator - * ``n_mstar`` : int, optional - Number of stellar mass samples (default: 100) - * ``n_norm`` : int, optional - Number of normal distribution samples (default: 10) - * ``max_log_mhalo`` : float, optional - Maximum log halo mass (default: 12.8) - - **Returns:** - - * ``ndarray`` - Halo mass realizations - -_dm_pdf -~~~~~~~ - -.. autofunction:: _dm_pdf - - Calculate DM realizations for a galaxy using photometric redshift and stellar mass estimates. - - **Parameters:** - - * ``cigale_tab`` : Table - CIGALE results for the galaxy - * ``eazy_outdir`` : str - EAZY output directory - * ``mean_interp`` : interp2d - Mean SHMR interpolator - * ``stddev_interp`` : interp2d - SHMR scatter interpolator - * ``ang_dia_interp`` : interp1d - Angular diameter distance interpolator - * ``dm_interpolator`` : RegularGridInterpolator - DM interpolator - * ``n_cores`` : int, optional - CPU threads - - **Returns:** - - * ``dm_values`` : ndarray - DM realizations for the galaxy - * ``z_draws`` : ndarray - Redshift draws used for DM calculations - -full_analysis -~~~~~~~~~~~~~ - -.. autofunction:: full_analysis - - Perform complete photometric redshift-based halo DM analysis for an FRB field. - - **Parameters:** - - * ``frb`` : FRB - FRB object of interest - * ``input_catfile`` : str - Input photometry catalog path (assumed DES format) - * ``datafolder`` : str - Results storage directory - * ``n_cores`` : int, optional - CPU threads (default: varies by function) - * ``n_gals`` : int, optional - Limit analysis to n_gals galaxies for testing - - **Process:** - - 1. Runs EAZY photometric redshift estimation - 2. Runs CIGALE SED fitting for stellar masses - 3. Creates interpolation grids - 4. Calculates DM realizations for all galaxies - 5. Saves results to compressed files - - **Outputs:** - - * DM_halos_final.npz - Sparse matrix of DM realizations - * DM_halos_zdraws.npz - Redshift draws for each galaxy - -Dependencies ------------- - -Required packages for full functionality: - -* ``pathos`` - For multiprocessing: ``pip install pathos`` -* ``progressbar2`` - For progress tracking: ``pip install progressbar2`` -* ``threedhst`` - For EAZY output: ``pip install threedhst`` - -Examples --------- - -Basic DES data retrieval:: - - from frb.halos.photoz import get_des_data - from astropy.coordinates import SkyCoord - from astropy import units as u - - # Define search parameters - center = SkyCoord('12h34m56s', '+12d34m56s') - radius = 10 * u.arcmin - - # Get DES photometry - des_cat = get_des_data(center, radius=radius, write=True) - print(f"Found {len(des_cat)} galaxies") - -Create DM interpolation grid:: - - from frb.halos.photoz import dm_grid - - # Create 3D DM grid for FRB at z=0.5 - frb_redshift = 0.5 - dm_grid(frb_redshift, n_z=50, n_o=50, n_m=50, - outdir='./halo_data/', outfile='dm_grid.npz') - -Full analysis workflow:: - - from frb.frb import FRB - from frb.halos.photoz import full_analysis - - # Load FRB - frb_obj = FRB.by_name('FRB20180924B') - - # Run complete halo DM analysis - full_analysis(frb_obj, - input_catfile='field_photometry.fits', - datafolder='./analysis_results/', - n_cores=8, - n_gals=100) # Limit for testing - -Setup interpolators:: - - from frb.halos.photoz import _instantiate_intepolators - - # Create interpolation functions - dm_interp, mean_interp, std_interp, ang_interp = _instantiate_intepolators( - datafolder='./halo_data/', - dmfilename='dm_grid.npz' - ) - - # Use interpolators for DM calculations - import numpy as np - z_test = 0.3 - offset_test = 100.0 # kpc - mhalo_test = 12.0 # log solar masses - - dm_value = dm_interp((z_test, offset_test, mhalo_test)) - print(f"DM contribution: {dm_value:.2f} pc/cm³") - -Generate halo mass lookup tables:: - - from frb.halos.photoz import mhalo_lookup_tables - import numpy as np - - # Create lookup tables for multiple redshifts - z_array = np.linspace(0.1, 1.0, 10) - mhalo_lookup_tables(z_array, - datafolder='./lookup_tables/', - n_cores=4) - -Advanced usage with custom parameters:: - - from frb.halos.photoz import get_des_data, dm_grid - from astropy.coordinates import SkyCoord - from astropy import units as u - - # Custom DES query with star removal - coords = SkyCoord(ra=123.45, dec=-23.45, unit='deg') - - des_data = get_des_data( - coords, - radius=20*u.arcmin, - starbright=16.0, # Remove bright stars - starflagval=0.8, # More aggressive star removal - gaiacat='gaia_stars.csv', # Additional star catalog - write=True, - outfile='frb_field_photometry.fits' - ) - - # High-resolution DM grid - dm_grid(frb_z=1.2, - n_z=200, n_o=150, n_m=120, # Higher resolution - max_log_mhalo=13.5, # Include more massive halos - outdir='./high_res_grid/', - outfile='dm_grid_hires.npz') - -Integration with FRB analysis:: +.. automodule:: frb.halos.photoz - from frb.frb import FRB - from frb.halos.photoz import get_des_data, full_analysis - from astropy import units as u - - # Load FRB and get field data - frb = FRB.by_name('FRB20180924B') - - # Get photometry around FRB location - field_data = get_des_data(frb.coord, radius=15*u.arcmin) - - # Save for analysis - field_data.write('frb_field.fits', overwrite=True) - - # Run complete halo DM analysis - full_analysis(frb, 'frb_field.fits', './results/', n_cores=8) - - print("Halo DM analysis complete!") - print("Results saved in ./results/DM_halos_final.npz") \ No newline at end of file +.. note:: + This module requires the optional ``hmf_emulator`` package (for halo mass calculations). + Install it with: ``pip install hmf_emulator`` diff --git a/docs/index.rst b/docs/index.rst index de1cd6063..ba42366ff 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -3,7 +3,8 @@ Welcome to the FRB documentation! FRB is a Python package for Fast Radio Burst research, providing tools for dispersion measure calculations, host galaxy analysis, FRB-galaxy associations, -and survey data handling. The package is developed and maintained by the FRB community. +and survey data handling. The package is developed and maintained largely by the members of +the `F^4 ` collaboration. Getting Started @@ -22,16 +23,14 @@ Core Classes :maxdepth: 2 frb_class - frbhost_class -Data ----- +Galaxies +-------- .. toctree:: :maxdepth: 2 - data - database + FRB Galaxies Dispersion Measure ------------------ @@ -41,16 +40,15 @@ Dispersion Measure dm -Galaxies --------- + +Surveys +------- .. toctree:: :maxdepth: 2 - galaxies - adding_host - eazy - mags_to_flux + surveys + Halo Calculations ----------------- @@ -60,6 +58,7 @@ Halo Calculations halos/index + Rotation Measure ---------------- @@ -77,14 +76,6 @@ Scattering tscatt -Surveys -------- - -.. toctree:: - :maxdepth: 2 - - surveys - FRB Scripts ----------- diff --git a/docs/installing.rst b/docs/installing.rst index 47e3bd209..0f381f237 100644 --- a/docs/installing.rst +++ b/docs/installing.rst @@ -5,86 +5,108 @@ Installing frb This document describes how to install the `frb` repository. -Installing Dependencies -======================= -We have and will continue to keep the number of dependencies low. -There are a few standard packages that must be installed -and one package `linetools` under review for -`astropy` affiliated status. +Quick Start +=========== -In general, we recommend that you use Anaconda for the majority of -these installations. +The recommended installation path is now through ``pip`` using the +repository's ``pyproject.toml`` metadata. -Detailed installation instructions are presented below: +We recommend Python 3.11 or later in a fresh virtual environment or +conda environment. -Python Dependencies -------------------- - -frb depends on the following list of Python packages. - -We recommend that you use `Anaconda `_ -to install and/or update these packages. - -* `python `_ versions 3.11 or later -* `numpy `_ version 2.2 or later -* `astropy `_ version 7.1 or later -* `scipy `_ version 1.17 or later -* `healpy `_ version 1.19 or later -* `pandas `_ version 2.2 or later -* `requests `_ version 2.18 or later -* `dust_extinction `_ -* `matplotlib `_ version 3.7 or greater -* `linetools `_ version 0.3.1 or later -* `astropath `_ version 0.1 or later +For example, with ``venv``:: + git clone https://github.com/FRBs/FRB.git + cd FRB + python -m venv .venv + source .venv/bin/activate + pip install --upgrade pip + pip install -e . -The following packages are required to access surveys (e.g. SDSS, DES) -for data that may be associated to an FRB: +or with conda:: -* `astroquery `_ v0.4.11 or later -* `datalab-client `_ v2.20 or later -* `pyvo `_ version 0.9.2 or later + conda create -n frb python=3.11 -y + conda activate frb + git clone https://github.com/FRBs/FRB.git + cd FRB + pip install --upgrade pip + pip install -e . + +This installs the base package plus its core dependencies, including +the git-based requirements such as ``linetools``, ``ne2001``, and +``astropath``. + +.. note:: + + ``setup.py`` is kept for backward compatibility, but the supported + installation workflow is ``pip install -e .``. + Likewise, ``frb/requirements.txt`` and ``frb/optional_requirements.txt`` + are now reference files rather than the primary installation source. + +Base Dependencies +----------------- + +The base install is defined in ``pyproject.toml`` and includes the main +runtime requirements for the package. At the time of writing, these include +packages such as: + +* `python `_ 3.11 or later +* `numpy `_ 2.2 or later +* `scipy `_ 1.17 or later +* `astropy `_ 7.1 or later +* `pandas `_ 2.2 or later +* `matplotlib `_ 3.7 or later +* `healpy `_ 1.19 or later +* `requests `_ 2.18 or later +* `dust_extinction `_ +* `photutils `_ +* `astroquery `_ 0.4.11 or later +* `astro-datalab `_ +* `pyvo `_ 1.5.3 or later +* `ligo.skymap `_ 2.3.0 or later +* `numba `_ 0.50 or later +* `tqdm `_ +* `linetools `_ +* `ne2001 `_ +* `astropath `_ Extras ------ -The following packages are more for builders and not recommended for most users. - -The following package is required to map a slit onto a finder chart (frb.figures.finder): - -* `photutils `_ version 1.11.0 or later -* `scikit-image `_ version 0.21.0 or later +The current ``optional`` packages covers: -The following are required to run some of the halo codes: +* `ppxf `_ +* `pymc3 `_ +* `pcigale `_ +* `pathos `_ +* `hmf_emulator `_ +* `specdb `_ +* `pyregion `_ +* `spectral-cube `_ -* `ne2001 `_ NE2001 -* george :: Use pip -* `class `_ version 2.7 or greater -* `Aemulator `_ pip is broken.. -* `hmf_emulator `_ HMF emulator (requires GSL) +We do not include these as dependencies as they may require additional system setup. +These are however necessary to run specific modules of the code-base, +and we recommend installing them if you intend to use those modules. -The following are required to build host galaxy objects: +The following feature-specific dependencies may still require separate, +manual installation: -* `pPXF `_ version 6.7 or greater -* `pcigale `_ version 2025.0 +* `FRB-pulsars `_ for ``frb.surveys.psrcat`` +* `asymmetric_kde `_ for ``frb.dm_kde`` +* `scikit-image `_ for some image-analysis workflows -The following is required to run the code in dm_kde: +The ``hmf_emulator`` package is especially important for halo-related modules, +but it may require additional local system setup depending on your platform. -* `asymmetric_kde `_ no versioning +Environment Variables +--------------------- -The following is required to run the MCMC DM code in dm.mcmc.py: +Most users do not need any extra environment variables for a basic install. +Some workflows do: -* `numba `_ version >= 0.50 - -For pPXF, you will also likely need to modify the standard install -to use the Chabrier libraries. See the InstallNotes in this -`Google Drive `_. - -The following are required for using functions in halos.photoz.py: - -* `threedhst `_ version >= 0.1.dev0 -* progressbar2 :: Use pip -* pathos :: Use pip +* ``FRB_GDB`` is needed by several build scripts and tests that expect access + to the FRB database or generated data products. +* ``EAZYDIR`` is needed for the EAZY wrappers described below. Our CIGALE wrappers use custom filter files not provided by their current release (e.g DES, Pan-STARRS). @@ -93,20 +115,12 @@ See the instructions for adding those as needed. Installing frb ============== -Presently, you must download the code from github:: - - #go to the directory where you would like to install frb. - git clone https://github.com/FRBs/FRB.git - -From there, you can build and install with:: - - cd FRB - python setup.py install # or use develop +If you already cloned the repository, install it from the checkout root with:: + pip install -e . -This should install the package and scripts. -Make sure that your PATH includes the standard -location for Python scripts (e.g. ~/anaconda/bin) +This installs the package in editable mode and exposes the scripts in your +active Python environment. Adding additional CIGALE filter files ===================================== @@ -152,5 +166,12 @@ pPXF ==== Our pPXF wrapper currently uses an older version of the code -(v 6.7.17) and a few custom files. Contact JXP if you wish -to use this. +(v 6.7.17) and a few custom files. These are made available in a separate repository, +and you can install it with:: + + pip install git+https://github.com/SunilSimha/frb_ppxf.git + +If instead you want to install this manually and apply the relevevant patches yourself, +see the InstallNotes in this +`Google Drive `_. +Contact JXP if you have any questions about this process. \ No newline at end of file diff --git a/docs/quickstart.rst b/docs/quickstart.rst index 7c3a29872..a8c67f867 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -273,7 +273,7 @@ Next Steps Now that you're familiar with the basics: 1. **FRB Class Details**: See :doc:`frb_class` for complete FRB object documentation -2. **Host Galaxy Analysis**: See :doc:`frbhost_class` for working with host galaxies +2. **Host Galaxy Analysis**: See :doc:`frbhost_class` (FRB Galaxies) for working with host galaxies 3. **Read the API Documentation**: Browse :doc:`api/index` for complete function references 4. **Explore Jupyter Notebooks**: Check out the ``docs/nb/`` directory for in-depth examples and tutorials 5. **Learn about Dispersion Measures**: See :doc:`dm` for DM calculation details diff --git a/frb/analysis/kcwi.py b/frb/analysis/kcwi.py index 4dec11403..387e33660 100644 --- a/frb/analysis/kcwi.py +++ b/frb/analysis/kcwi.py @@ -17,17 +17,17 @@ from photutils.aperture import EllipticalAperture from photutils.background import Background2D, MedianBackground except ImportError: - raise ImportError("Requirement unmet: photutils. Run `pip install photutils`") + print("Requirement unmet: photutils. Run `pip install photutils`") try: from spectral_cube import SpectralCube from spectral_cube import BooleanArrayMask except ImportError: - raise ImportError("Requirement unmet: SpectralCube. Run `pip install spectral-cube`.") + print("Requirement unmet: SpectralCube. Run `pip install spectral-cube`.") try: import pyregion as pyreg except ImportError: - raise ImportError("Requirement unmet: pyregion. Run `pip install pyregion`.") + print("Requirement unmet: pyregion. Run `pip install pyregion`.") import os @@ -35,6 +35,8 @@ def _interp_trans(transfile, kind= "cubic", fill_value=0, **readkw): """ Interpolate a transmission curve from a file. + + Args: transfile (str): Path to transmission curve file. The file should contain two columns in this order: @@ -46,6 +48,8 @@ def _interp_trans(transfile, kind= "cubic", fill_value=0, **readkw): https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html **readkw: Keyword arguments for reading the input file using astropy Table. + + Returns: transfunc (function): interpolation """ @@ -59,6 +63,8 @@ def silence_warnings(warncategory): To silence spectral cube warnings. Check out spectral_cube.utils for warning categories. + + Args: warncategory (Warnings category): category of Warnings you want to silence. @@ -70,8 +76,12 @@ def _air_to_vac(wave): """ Helper function to convert wavelengths in air to vacuum. + + Args: wave (float or ndarray): wavelength in air in angstroms + + Returns: wave_vac (float or ndarray): wavelength in vacuum in angstroms """ @@ -82,13 +92,18 @@ def _air_to_vac(wave): def _read_in_data(datafile, reduction_pipeline='pypeit'): """ - Read in data from a KCWI datacube. flux_hdr.set('CRVAL3', flux_hdr['CRVAL3']*1e10, "[Angstrom] Reference value for wavelength") - flux_hdr.set('CDELT3', flux_hdr['CDELT3']*1e10, "[Angstrom] Coordinate increment at reference point") Args: + Read in data from a KCWI datacube. + + + + Args: datafile (str): Path to datacube fits file. reduction_pipeline (str, optional): Reduction pipeline used to reduce the datacube. Default is 'pypeit'. Also allowed 'kcwidrp'. Other pipelines are not supported yet. + + Returns: flux (array): 3D array of fluxes. std (array): 3D Std. dev. array. @@ -123,6 +138,8 @@ def find_sources(imgfile, nsig = 1.5, """ Find sources in the whitelight image using Photutils segmentation. + + Args: imgfile (str): An image fits file n_sig (float, optional): Detection threshold in units @@ -140,6 +157,8 @@ def find_sources(imgfile, nsig = 1.5, areas to be masked out. write (str, optional): write extracted object table to this path. + + Returns: objects (Table): Summary table of detected objects. segmap (ndarray): Segmentation map. @@ -221,8 +240,12 @@ def _spectral_tile(self, array): Helper function that tiles 1D array of size cube.spectral_axis.shape and tiles it to the same shape as the cube. + + Args: array (ndarray): the 1D array that needs to be tiled. + + Returns: tiled_array (ndarray): an array with the 1D array tiled in the spatial dimension. This has the same shape @@ -236,9 +259,13 @@ def wave_mask(self, mask_1d): Mask out wavelengths using a 1D grid. Values corresponding to "False" are masked out. + + Args: mask_1D (bool ndarray): 1D boolean array of same length as cube.spectral_axis + + Returns: masked_cube (Spectral cube): masked datacube. masked_varcube (Spectral cube): masked variance cube. @@ -258,6 +285,8 @@ def get_img(self, wlow = None, whigh = None, """ Flatten cube along wavelength and produce a 2D image. + + Args: wlow, whigh (Quantity, optional): wavelength limits (with astropy units) to flatten between. @@ -280,6 +309,8 @@ def get_img(self, wlow = None, whigh = None, saved to. overwrite (bool, optional): Overwrite existing file? + + Returns: img (Spectral Cube Projection): Flattened 2D image """ @@ -320,22 +351,21 @@ def get_img(self, wlow = None, whigh = None, def spec_from_spatial_mask(self, mask_arr, how="cube"): """ - Extract a spectrum from a cube - within a spatial mask. - Args: - cube (Spectral Cube): A datacube object - mask_arr (numpy array): A 2D boolean array. A - spectrum is extracted from the regions - corresponding to True. - kind (str, optional): median or mean - how (str, optional): "cube" or "slice". Load - the entire masked cube to memory when - computing spectra or compute it looping - over slices. - Returns: - spec (OneDSpectrum): The extracted spectrum. - var (OneDSpectrum): Variance in spectrum. - Only returned if varcube is supplied. + Extract a spectrum from a cube within a spatial mask. + + Parameters + ---------- + mask_arr : numpy.ndarray + 2D boolean mask. Pixels set to True are extracted. + how : str, optional + Summation mode for spectral-cube ("cube" or "slice"). + + Returns + ------- + spec : OneDSpectrum + Extracted mean spectrum. + varspec : OneDSpectrum + Variance of extracted mean spectrum. """ assert mask_arr.dtype == bool, "Masks must be boolean. int type masks make computation slow." @@ -357,16 +387,22 @@ def spec_from_ellipse(self, """ Get the spectrum within an elliptical region - Args: - cube (Spectral Cube): A datacube object - x0, y0 (float, optional): Centroid of ellipse in pixels. - a, b (float, optional): semi-major and semi-minor axes in pixels. - theta (float, optional): rotation angle of the semi-major - axis from the positive x axis. - Returns: - spec (OneDSpectrum): The extracted spectrum. - var (OneDSpectrum): Variance in spectrum. - Only returned if varcube is supplied. + + Parameters + ---------- + x0, y0 : float, optional + Ellipse center in pixel coordinates. + a, b : float, optional + Semi-major and semi-minor axes in pixels. + theta : float, optional + Position angle of semi-major axis from positive x axis. + + Returns + ------- + spec : OneDSpectrum + Extracted mean spectrum. + varspec : OneDSpectrum + Variance of extracted mean spectrum. """ #TODO: Use photutils aperture object for this. # Create 2D mask first @@ -380,6 +416,8 @@ def spec_from_ellipse(self, def _make_marz(self, speclist, varspeclist, objects, wave=None, marzfile="marzfile.fits", vac_wave = True): """ Helper function to create a MARZ input file + + Args: cube (Spectral cube): Datacube speclist (list): list of spectra. i.e. @@ -454,27 +492,29 @@ def _make_marz(self, speclist, varspeclist, objects, wave=None, marzfile="marzf return marz_hdu def get_source_spectra(self, objects, outdir = "spectra/", marzfile = None, vac_wave=True, wvlims= None): """ - Extract spectra of sources found using SExtractor - from datacube. - Args: - cubefile (str): A datacube fits file - varfile (str): Variance datacube fits file - objects (Table): Table of extracted objects produced - by SourceCatalog. - outdir (str, optional): directory to store spectra - marzfile (str, optional): name of MARZ file to dump - all spectra into. File creation is skipped if - a name is not supplied. - vac_wave (bool, optional): Wavelengths are in vacuum. - wvlims (tuple, optional): Wavelength limits to - extract spectra between. If None, the full - wavelength range is used. Expects floats in angstroms. - Returns: - speclist (ndarray): A 2D array of with an extracted - spectrum in each row. - varspeclist (ndarray): Similarly designed array with - variance information. - wave (1D Quantity array): Wavelength array. + Extract 1D spectra for detected sources. + + Parameters + ---------- + objects : astropy.table.Table + Source table from segmentation/photutils. + outdir : str, optional + Output directory for per-source spectra. + marzfile : str, optional + MARZ output filename. If None, MARZ export is skipped. + vac_wave : bool, optional + Whether wavelength grid is vacuum. + wvlims : tuple, optional + Wavelength limits in Angstrom. + + Returns + ------- + speclist : numpy.ndarray + Extracted spectra, one row per source. + varspeclist : numpy.ndarray + Variance spectra, one row per source. + wave : numpy.ndarray + Wavelength grid in Angstrom. """ # Preliminaries diff --git a/frb/associate/dev/utils.py b/frb/associate/dev/utils.py index 5a2afcf6e..e9bcc94d3 100644 --- a/frb/associate/dev/utils.py +++ b/frb/associate/dev/utils.py @@ -89,11 +89,13 @@ def mock_run(sky, frbs, sigR, theta, fov, scale_rhalf=2., nsigma=2., def parse_model(model_dict, scale=1000, mag_lim=25.5): """ + Args: model_dict: scale: mag_lim: + Returns: """ diff --git a/frb/associate/frbassociate.py b/frb/associate/frbassociate.py index 2ac54ce4e..155d69fca 100644 --- a/frb/associate/frbassociate.py +++ b/frb/associate/frbassociate.py @@ -41,6 +41,8 @@ class FRBAssociate(path.PATH): from images. Use PATH methods for the Bayesian analysis + + Args: @@ -48,6 +50,8 @@ class FRBAssociate(path.PATH): image_file (str, optional): Name of image file max_radius (float, optional): Maximum radius for analysis (arcsec) + + Attributes: hdu (fits.HDU: FITS header-data unit photom (pandas.DataFrame): Photometry table @@ -95,6 +99,8 @@ def load_image(self): """ Load the image from self.image_file + + Returns: """ @@ -110,10 +116,14 @@ def make_host_cutout(self, imgdata, wcs, size=5. * units.arcsec)->Cutout2D: Make a cutout of the image around the FRB and write to the data directory under "Galaxies". + + Args: imgdata (np.ndarray): Image data wcs (astropy.wcs.WCS): WCS of the image size (Quantity, optional): Size of the cutout + + Returns: Cutout2D: Cutout of the image @@ -149,6 +159,8 @@ def calc_pchance(self, ndens_eval='driver', extinction_correct=False): self.Pchance filled in place Added as P_c to candidates Table + + Args: ndens_eval (str, optional): Source of number density evaluation. See frb.associate.chance.pchance for options @@ -182,6 +194,8 @@ def cut_candidates(self, plate_scale, self.candidates is made in place + + Args: plate_scale (float or str): If str -- grab the value from the Header with this key @@ -243,6 +257,8 @@ def photometry(self, ZP, ifilter, radius=3., show=False, outfile=None): Half-light radii: https://iopscience.iop.org/article/10.1086/444475/pdf + + Args: ZP (float): Zero point magnitude @@ -311,6 +327,8 @@ def segment(self, nsig=3., xy_kernel=(3,3), npixels=3, show=False, outfile=None, """ Generate the segment image + + Args: nsig (float): Kernel parameter @@ -322,6 +340,8 @@ def segment(self, nsig=3., xy_kernel=(3,3), npixels=3, show=False, outfile=None, deblend (bool, optional): Run deblend algorithm too + + Returns: """ @@ -385,6 +405,8 @@ def threshold(self, nsig=1.5, box_size=(50,50), filter_size=(3,3)): self.thresh_img is set in place + + Args: nsig (float, optional): Primary threshold parameter @@ -392,6 +414,8 @@ def threshold(self, nsig=1.5, box_size=(50,50), filter_size=(3,3)): Primary Background2D parameter filter_size (tuple): Primary Background2D parameter + + Returns: """ @@ -440,7 +464,8 @@ def run_individual(config, prior:dict=None, show=False, """ Run through the steps leading up to Bayes - Args: + Parameters + ---------- config (dict): Runs the PATH analysis keys: name (str): Name of the FRB, e.g. FRB20121102 @@ -472,6 +497,7 @@ def run_individual(config, prior:dict=None, show=False, generate_png (bool, optional): Generate PNGs of the cutouts verbose (bool, optional): + Verbose output flag. """ if not skip_bayesian and prior == None: raise IOError("Must specify the priors if you are running the Bayesian analysis") diff --git a/frb/builds/build_fg.py b/frb/builds/build_fg.py index c61342802..72834d3da 100644 --- a/frb/builds/build_fg.py +++ b/frb/builds/build_fg.py @@ -28,6 +28,7 @@ def build_fg_181112(build_photom=False): """ Data taken from Prochaska et al. 2019, Science, in press + Args: build_photom (bool, optional): Generate the photometry table diff --git a/frb/builds/build_frbs.py b/frb/builds/build_frbs.py index cf2ec63a2..500ad95ed 100644 --- a/frb/builds/build_frbs.py +++ b/frb/builds/build_frbs.py @@ -25,6 +25,7 @@ def run(frb_input:pandas.core.series.Series, outfile:str=None): """Main method for generating a Host JSON file + Args: frb_input (pandas.core.series.Series): Row of the CVS file providing the frb items @@ -35,6 +36,7 @@ def run(frb_input:pandas.core.series.Series, out_path (str, optional): Over-ride default outfile [not recommended; mainly for testing] + Raises: e: [description] ValueError: [description] @@ -108,6 +110,7 @@ def main(frbs:list, options:str=None, data_file:str=None, lit_refs:str=None, override:bool=False, outfile:str=None, out_path:str=None): """ Driver of the analysis + Args: frbs (list): [description] options (str, optional): [description]. Defaults to None. diff --git a/frb/builds/build_hosts.py b/frb/builds/build_hosts.py index 05536b3e7..44901fb7e 100644 --- a/frb/builds/build_hosts.py +++ b/frb/builds/build_hosts.py @@ -79,10 +79,12 @@ def chk_fill(value): def assign_z(ztbl_file:str, host:frbgalaxy.FRBHost): """Assign a redshift using one of the Galaxy_DB tables + Args: ztbl_file (str): table file host (frbgalaxy.FRBHost): host object + Raises: ValueError: [description] """ @@ -103,6 +105,7 @@ def search_for_file(projects, references, root:str, If multiple files are found, the *last* one is returned + Args: projects ([type]): [description] references ([type]): [description] @@ -110,6 +113,7 @@ def search_for_file(projects, references, root:str, prefix (str, optional): [description]. Defaults to 'ref'. return_last_file (bool, optional): [description]. Defaults to False. + Returns: tuple: bool, str [file was found?, name of file with path] """ @@ -134,14 +138,17 @@ def search_for_file(projects, references, root:str, def read_lit_table(lit_entry, coord=None): """ Reade a literature table + Args: lit_entry (pandas row): Row of the overview table coord (astropy.coordiantes.SkyCoord, optional): Coordinate for the galaxy of interest. Defaults to None. + Raises: ValueError: [description] + Returns: astropy.table.Table: table of literature data """ @@ -179,6 +186,7 @@ def run(host_input:pandas.core.series.Series, outfile:str=None): """Main method for generating a Host JSON file + Args: host_input (pandas.core.series.Series): Row of the CVS file providing the host inputs @@ -196,6 +204,7 @@ def run(host_input:pandas.core.series.Series, Skip the survey data. Useful for testing. Defaults to False. + Raises: e: [description] ValueError: [description] @@ -509,6 +518,7 @@ def main(frbs:list, options:str=None, hosts_file:str=None, lit_refs:str=None, override:bool=False, outfile:str=None, out_path:str=None): """ Driver of the analysis + Args: frbs (list): [description] options (str, optional): [description]. Defaults to None. diff --git a/frb/builds/build_path.py b/frb/builds/build_path.py index c9385a528..04e96fcf3 100644 --- a/frb/builds/build_path.py +++ b/frb/builds/build_path.py @@ -35,6 +35,7 @@ def run(frb_list:list, override:bool=False): """Main method for running PATH analysis for a list of FRBs + Args: frb_list (list): List of FRB names from the database prior (dict): @@ -46,10 +47,12 @@ def run(frb_list:list, override (bool, optional): Attempt to over-ride errors. Mainly for time-outs of public data. Defaults to False. + Raises: e: [description] ValueError: [description] + Returns: pandas.DataFrame: Table of PATH values and a bit more """ @@ -142,6 +145,7 @@ def run(frb_list:list, def main(options:str=None, frb:str=None): """ Driver of the analysis + Args: options (str, optional): [description]. Defaults to None. frb (str, optional): FRB name diff --git a/frb/builds/build_specdb.py b/frb/builds/build_specdb.py index f4bf8b143..3c0dae24b 100644 --- a/frb/builds/build_specdb.py +++ b/frb/builds/build_specdb.py @@ -38,6 +38,7 @@ def grab_files(all_files, refs_list, instrument): """ Simple method to parse a set of files for a given an instrument + Args: all_files (list): Complete list of files @@ -46,6 +47,7 @@ def grab_files(all_files, refs_list, instrument): instrument (str): Instrument name to parse on + Returns: list, list: List of files and their references matching the input instrument @@ -69,10 +71,12 @@ def load_z_tables(path): Redshift tables are those that begin with 'z' + Args: path (str): Path to the folder holding one or more redshift tables. + Returns: astropy.table.Table: Redshift table with RA, DEC, ZEM, .. @@ -104,6 +108,7 @@ def sdss_redshifts(): Enter the directory and build a redshift table based on the spectra present + Returns: """ @@ -156,6 +161,7 @@ def generate_by_refs(input_refs, outfile, version): """ Build a specDB file according to the input references + Args: input_refs (list): List of references from which to build the specDB diff --git a/frb/builds/old_build_frbs.py b/frb/builds/old_build_frbs.py index 87d7c7e79..4209a6da3 100644 --- a/frb/builds/old_build_frbs.py +++ b/frb/builds/old_build_frbs.py @@ -168,6 +168,8 @@ def frb_181112(): """ Generate the JSON file for FRB 181112 All of the data comes from Prochaska+2019, Science, in press + + Returns: FRB position and localization updated by Day+2021 diff --git a/frb/builds/old_build_hosts.py b/frb/builds/old_build_hosts.py index 401561928..60e4fde12 100644 --- a/frb/builds/old_build_hosts.py +++ b/frb/builds/old_build_hosts.py @@ -85,6 +85,7 @@ def build_host_121102(build_photom=False, build_cigale=False, use_orig=False): reff from Bassa+17 https://ui.adsabs.harvard.edu/abs/2017ApJ...843L...8B/abstract + Args: build_photom (bool, optional): Generate the photometry file in the Galaxy_DB @@ -251,6 +252,7 @@ def build_host_180301(build_ppxf=False, build_photom=False, build_cigale=False): Bhandari+2021 + Args: build_photom (bool, optional): build_cigale (bool, optional): @@ -378,6 +380,7 @@ def build_host_180924(build_photom=False, build_cigale=False): Writes to 180924/FRB180924_host.json + Args: build_photom (bool, optional): Generate the photometry file in the Galaxy_DB """ @@ -473,6 +476,7 @@ def build_host_181112(build_photom=False, build_cigale=False): All of the data comes from Prochaska+2019, Science + Args: build_photom (bool, optional): @@ -570,6 +574,7 @@ def build_host_190102(build_photom=False, build_cigale=False, All of the data comes from Bhandrari+2020, ApJL, in press + Args: build_photom (bool, optional): """ @@ -695,9 +700,11 @@ def build_host_190523(build_photom=False, build_cigale=False): #:run_ppxf=False a consistent analysis with the ASKAP hosts. + Args: build_photom: + Returns: """ @@ -787,6 +794,7 @@ def build_host_190608(run_ppxf=False, build_photom=False, build_cigale=False): All of the data comes from Bhandrari+2020, ApJL, in press + Args: build_photom (bool, optional): """ @@ -890,6 +898,7 @@ def build_host_180916(run_ppxf=False, build_photom=False, build_cigale=False): CIGALE and galfit will be published in Kasper et al. 2020 + Args: build_photom (bool, optional): """ @@ -1010,6 +1019,7 @@ def build_host_190611(run_ppxf=False, build_photom=False, build_cigale=False, so """ Build the host galaxy data for FRB 190611 There are 2 sources in play. Heintz+2020 + Args: build_photom (bool, optional): """ @@ -1134,6 +1144,7 @@ def build_host_190614(build_photom=False, build_cigale=False, run_eazy=False, """ Build the host galaxy data for FRB 190614 See Law+2020 https://ui.adsabs.harvard.edu/abs/2020ApJ...899..161L/abstract + Args: build_photom (bool, optional): build_cigale (bool, optional): @@ -1428,6 +1439,7 @@ def build_host_190711(build_ppxf=False, build_photom=False, build_cigale=False): Heintz+2020 + Args: build_photom (bool, optional): build_cigale (bool, optional): @@ -1552,6 +1564,7 @@ def build_host_190714(build_ppxf=False, build_photom=False, build_cigale=False): Heintz+2020 + Args: build_photom (bool, optional): build_cigale (bool, optional): @@ -1687,6 +1700,7 @@ def build_host_191001(build_ppxf=False, build_photom=False, build_cigale=False): Heintz+2020 + Args: build_photom (bool, optional): build_cigale (bool, optional): @@ -1812,6 +1826,7 @@ def build_host_191001(build_ppxf=False, build_photom=False, build_cigale=False): def build_host_191228(build_ppxf=False, build_photom=False, build_cigale=False): """ Build the host galaxy data for FRB 191228 + Args: build_photom (bool, optional): build_cigale (bool, optional): @@ -1944,6 +1959,7 @@ def build_host_191228(build_ppxf=False, build_photom=False, build_cigale=False): def build_host_200430(build_ppxf=False, build_photom=False, build_cigale=False, run_eazy=False): """ Build the host galaxy data for FRB 200430 + Args: build_photom (bool, optional): build_cigale (bool, optional): @@ -2075,6 +2091,7 @@ def build_host_200430(build_ppxf=False, build_photom=False, build_cigale=False, def build_host_200906(build_ppxf=False, build_photom=False, build_cigale=False): """ Build the host galaxy data for FRB 200906 + Args: build_photom (bool, optional): build_cigale (bool, optional): @@ -2242,6 +2259,7 @@ def build_host_201124(build_ppxf=False, build_photom=False, build_cigale=False): """ Build the host galaxy data for FRB 201124 + Args: build_photom (bool, optional): build_cigale (bool, optional): @@ -2382,6 +2400,7 @@ def build_host_201124(build_ppxf=False, def build_host_20200120E(build_ppxf=False, build_photom=False, build_cigale=False): """ Build the host galaxy data for FRB 20200120E + Args: build_photom (bool, optional): build_cigale (bool, optional): @@ -2421,6 +2440,7 @@ def build_host_20200120E(build_ppxf=False, build_photom=False, build_cigale=Fals def build_host_171020(build_ppxf=False, build_photom=False, build_cigale=False): """ Build the host galaxy data for FRB 200906 + Args: build_photom (bool, optional): build_cigale (bool, optional): diff --git a/frb/dm/cosmic.py b/frb/dm/cosmic.py index 2ab2cf796..ff3dc4ca9 100644 --- a/frb/dm/cosmic.py +++ b/frb/dm/cosmic.py @@ -30,6 +30,7 @@ def DMcosmic_PDF(Delta, C0, sigma, A=1., alpha=3., beta=3.): See Macquart+2020 for details + Args: Delta (float or np.ndarray): DM / averageDM values @@ -40,6 +41,7 @@ def DMcosmic_PDF(Delta, C0, sigma, A=1., alpha=3., beta=3.): alpha (float, optional): beta (float, optional): + Returns: float or np.ndarray: @@ -53,6 +55,7 @@ def deviate1(C0, sigma, beta, orig=False): """ Calculate deviate to solve fo C0 + Args: C0 (float): sigma (float): @@ -60,6 +63,7 @@ def deviate1(C0, sigma, beta, orig=False): orig (bool, optional): use the original approach. Not recommended + Returns: float: deviate @@ -84,6 +88,7 @@ def build_C0_spline(max_log10_sigma=0., npt=100, ret_all=False, beta=4.): Generate a spline of C0 vs sigma values for the McQuinn formalism + Args: max_log10_sigma (float, optional): npt (int, optional): @@ -91,6 +96,7 @@ def build_C0_spline(max_log10_sigma=0., npt=100, ret_all=False, beta=4.): if True, return more items beta (float, optional): + Returns: float or tuple: If ret_all, return f_C), sigmas, COs else return the spline @@ -115,9 +121,11 @@ def grab_sigma_spline(): """ Load up the sigma spline + Args: redo: + Returns: scipy.interpolate.InterpolatedUnivariateSpline: @@ -134,6 +142,7 @@ def grab_C0_spline(max_log10_sigma=0., npt=100, ret_all=False, """ Load up the C0 spline + Args: max_log10_sigma: npt: @@ -142,6 +151,7 @@ def grab_C0_spline(max_log10_sigma=0., npt=100, ret_all=False, beta: ifile: + Returns: scipy.interpolate.InterpolatedUnivariateSpline: diff --git a/frb/dm/host.py b/frb/dm/host.py index 113e19734..042cb04a0 100644 --- a/frb/dm/host.py +++ b/frb/dm/host.py @@ -20,12 +20,14 @@ def dm_host_from_Halpha(z:float, Halpha:Quantity, reff_ang:Quantity, AV:float=None): """Estimate DM_Host from Halpha and angular size (and redshift) + Args: z (float): Redshift Halpha (Quantity): Total Halpha flux of the galaxy reff_ang (Quantity): Galaxy angular size AV (float, optional): Correct for dust if provided + Returns: Quantity: DM_host as observed (i.e. includes the 1/1+z term) """ @@ -55,6 +57,7 @@ def dm_host_from_ssfr(z:float, ssfr:Quantity): z (float): Redshift ssfr (Quantity): Surface density of SFR (with units) + Returns: Quantity: DM_host as observed (i.e. includes the 1/1+z term) @@ -87,6 +90,7 @@ def dm_host_halo(R: units.Quantity, HMR: str = 'Moster', mNFW: models.ModifiedNFW = None): """Calculate the DM contribution from the host galaxy's halo + Args: R (Quantity): Projected radial distance from the center of the halo log10_Mstar (float): Logarithm (base 10) of the stellar mass of the host galaxy @@ -95,9 +99,11 @@ def dm_host_halo(R: units.Quantity, mNFW (models.ModifiedNFW, optional): Instance of the ModifiedNFW model. If None, a default model will be created. Default is None + Returns: Quantity: DM contribution from the host galaxy's halo + Raises: IOError: If the specified halo mass relation (HMR) is not supported """ diff --git a/frb/dm/igm.py b/frb/dm/igm.py index 78d5c2d28..1f8b19c18 100644 --- a/frb/dm/igm.py +++ b/frb/dm/igm.py @@ -151,31 +151,9 @@ def f_diffuse(z, cosmo=defs.frb_cosmo, return_rho:bool=False, perturb_Mstar:float=None): """ - Calculate the cosmic fraction of baryons - in diffuse gas phase based on our empirical - knowledge of baryon distributions and their - ionization state. + Compute diffuse-baryon fraction as a function of redshift. - Note that the default values use the standard - values from Madau & Dickinson (2014) and Fukugita (2004). - The former use a Salpeter IMF for rho_* which is no longer - in fashion. - - Args: - z (float or ndarray): Redshift - cosmo (Cosmology, optional): Cosmology of - the universe. - return_rho (bool, optional): If true, - the diffuse gas density - is returned too. - perturb_Mstar (float, optional): - If provided, scale rho_Mstar by this value. - Useful for exploring the uncertainty in f_diffuse - - Returns: - f_diffuse (float, ndarray): Diffuse gas baryon fraction. - rho_diffuse (Quantity, optional): Physical diffuse gas density. - Returned if return_rho is set to true. + If ``return_rho`` is True, also returns physical diffuse-gas density. """ # Get comoving baryon mass density rho_b = cosmo.Ob0 * cosmo.critical_density0.to('Msun/Mpc**3') @@ -224,11 +202,13 @@ def ne_cosmic(z, cosmo = defs.frb_cosmo, mu = 4./3): """ Calculate the average cosmic electron number density as a function of redshift. + Args: z (float or ndarray): Redshift cosmo (Cosmology, optional): Cosmology in which the calculations are to be performed. mu (float): Reduced mass + Returns: ne_cosmic (Quantity): Average physical number density of electrons in the unverse in cm^-3. @@ -287,26 +267,10 @@ def average_DM(z, cosmo = defs.frb_cosmo, cumul=False, neval=10000, mu=4/3): def average_DMhalos(z, cosmo = defs.frb_cosmo, f_hot = 0.75, rmax=1., logMmin=10.3, logMmax=16., neval = 10000, cumul=False): """ - Average DM_halos term from halos along the sightline to an FRB - - Args: - z (float): Redshift of the FRB - cosmo (Cosmology): Cosmology in which the calculations - are to be performed. - f_hot (float, optional): Fraction of the halo baryons in diffuse phase. - rmax (float, optional): Size of a halo in units of r200 - logMmin (float, optional): Lowest mass halos to consider - Cannot be much below 10.3 or the Halo code barfs - The code deals with h^-1 factors, i.e. do not impose it yourself - logMmax (float, optional): Highest halo mass. Default to 10^16 Msun - neval (int, optional): Number of redshift values between - 0 and z the function is evaluated at. - cumul (bool, optional): Return a cumulative evaluation? + Compute average halo DM contribution along FRB sightline. - Returns: - DM_halos (Quantity or Quantity array): One value if cumul=False - else evaluated at a series of z - zeval (ndarray): Evaluation redshifts if cumul=True + Returns scalar DM by default, or cumulative `(DM_halos, zeval)` when + ``cumul`` is True. """ zeval, dz = np.linspace(0, z, neval, retstep = True) @@ -343,32 +307,10 @@ def average_DMIGM(z, cosmo = defs.frb_cosmo, logMmin=10.3, neval = 10000, cumul=False, return_DMhalos=False): """ - Estimate DM_IGM in a cumulative fashion + Estimate IGM DM by subtracting average halo DM from cosmic DM. - Args: - z (float): Redshift of the FRB - cosmo (Cosmology, optional): Cosmology in which - the calculations are to be performed. LambdaCDM - with the Repo cosmology assumed by default. - f_hot (float, optional): Fraction of the halo - baryons in diffuse phase. - rmax (float, optional): - Size of a halo in units of r200 - logMmin (float, optional): - Lowest mass halos to consider. Cannot be much below - 10.3 or the Halo code barfs. The code deals with - h^-1 factors, i.e. do not impose it yourself - neval (int, optional): Number of redshift values between - 0 and z the function is evaluated at. - cumul (bool, optional): - Return a cumulative evaluation? - return_DMHalos (bool, optional): Also return avgDM_halos? - Returns: - float or list: - DM_IGM (Quantity or Quantity array): One value if cumul=False - else evaluated at a series of z - zeval (ndarray, optional): Evaluation redshifts if cumul=True - DM_halos (ndarray, optinal): + Returns scalar DM by default, or cumulative arrays depending on + ``cumul`` and ``return_DMhalos``. """ # DM cosmic DM_cosmic, zeval = average_DM(z, cosmo = cosmo, cumul=True, neval=neval) diff --git a/frb/dm/mcmc.py b/frb/dm/mcmc.py index 94935b0b7..b10073f12 100644 --- a/frb/dm/mcmc.py +++ b/frb/dm/mcmc.py @@ -51,12 +51,15 @@ def grab_parmdict(tight_ObH=False): """ Generate the parameter dict for the MCMC run + Args: tight_ObH (bool, optional): [description]. Defaults to False. + Raises: IOError: [description] + Returns: dict: [description] """ @@ -83,6 +86,7 @@ def one_prob(Obh70, F, DM_FRBp, z_FRB, mu=150., lognorm_s=1., """ Calculate the probability for a single FRB + Args: Obh70 (float): Value of Omega_b * H_0 F (float): Feedback parameter @@ -100,6 +104,7 @@ def one_prob(Obh70, F, DM_FRBp, z_FRB, mu=150., lognorm_s=1., beta (float, optional): Parameter for DM PDF + Returns: float: Likelihood probability @@ -153,6 +158,7 @@ def mcquinn_DM_PDF_grid(Delta_values, C0, sigma, alpha=3., beta=3.): """ PDF(Delta) for the McQuinn formalism describing the DM_cosmic PDF + Args: Delta (2D ndarray): DM / averageDM values @@ -163,6 +169,7 @@ def mcquinn_DM_PDF_grid(Delta_values, C0, sigma, alpha=3., beta=3.): alpha (float, optional): beta (float, optional): + Returns: """ @@ -183,6 +190,7 @@ def all_prob(Obh70, F, in_DM_FRBp, z_FRB, mu=150., lognorm_s=1., """ Calculate the probability for a set of FRBs + Args: Obh70 (float): Value of Omega_b * H_0 F (float): Feedback parameter @@ -198,6 +206,7 @@ def all_prob(Obh70, F, in_DM_FRBp, z_FRB, mu=150., lognorm_s=1., beta (float, optional): Parameter for DM PDF + Returns: float: Log like-lihood @@ -257,12 +266,14 @@ def calc_likelihood_four_beta3(Obh70, F, mu, lognorm_s): """ Calculate likelihood for the real data + Args: Obh70 (float): Value of Omega_b * H_0 F (float): Feedback parameter mu (float): Mean of log-normal PDF lognorm_s (float): Sigma of log-normal PDF + Returns: np.ndarray: Array of log likelihood values, one per FRB in the global variable frbs @@ -293,14 +304,17 @@ def calc_likelihood_four_beta3(Obh70, F, mu, lognorm_s): def pm_four_parameter_model(parm_dict:dict, tight_ObH=False, beta=3.): """ Builds a pymc3 model for the 4-parameter MCMC + Args: parm_dict (dict): dict with the pymc3 parameters tight_ObH (bool, optional): If True, restrict the ObH0 value based on CMB. Defaults to False. beta (float, optional): PDF parameter. Defaults to 3.. + Raises: IOError: [description] + Returns: pm.Model: pymc3 model """ diff --git a/frb/dm/prob_dmz.py b/frb/dm/prob_dmz.py index 77ad62c34..3da815e31 100644 --- a/frb/dm/prob_dmz.py +++ b/frb/dm/prob_dmz.py @@ -36,6 +36,7 @@ def prob_DMcosmic_FRB(frb, DM_min=0., DM_max=5000., step=1., ISMfrac=0.10, DM_MWhalo=50.): """ Generate P(DM_cosmic) for an input FRP + Args: frb (:class:`frb.frb.FRB`): @@ -50,6 +51,7 @@ def prob_DMcosmic_FRB(frb, DM_min=0., DM_max=5000., step=1., DM_MWhalo (float, optional): Fixed value to use for the MW halo + Returns: tuple: numpy.ndarray, numpy.ndarray DM_cosmic values (units of pc/cm**3), P(DM_cosmic) normalized to unity @@ -96,6 +98,7 @@ def grid_P_DMcosmic_z(beta=3., F=0.31, zvals=None, """ Generate a grid of P(DM_cosmic|z) + Args: beta (float, optional): sigma_DM_cosmic parameter @@ -108,6 +111,7 @@ def grid_P_DMcosmic_z(beta=3., F=0.31, zvals=None, cosmo (optional): Cosmology + Returns: tuple: z, DM_cosmic, P(DM_cosmic|z) """ @@ -151,6 +155,7 @@ def build_grid_for_repo(outfile:str): """ Build a P(DM,z) grid for the Repository + Args: outfile (str): Path+filename for output file """ @@ -171,9 +176,11 @@ def grab_repo_grid(grid_name): """ Grab the grid from the Repository based on the given grid name + Args: grid_name (str): Name of the grid to grab + Returns: dict: Numpy dict from the npz or npy save file """ diff --git a/frb/dm_kde/dm_frb_sim.py b/frb/dm_kde/dm_frb_sim.py index 9ca36d7e1..2709177c0 100644 --- a/frb/dm_kde/dm_frb_sim.py +++ b/frb/dm_kde/dm_frb_sim.py @@ -22,6 +22,7 @@ def simulate_frb_dm(frb_data, z_stepsize=10**-4, z_max=3, dm_min=0, dm_max=3000, Please check your frbcat_df matches the template used here. Change the halo and host distributions as you feel appropriate. + Arguments: transient_data (str): Path to data (in .csv format). @@ -109,6 +110,7 @@ def kde_for_frb_sim(grid, dm_sim, num_samples, num_resamples=50, save_to_path=No """ Estimate simulated DM_FRB using a random draws from the simulation. Used to analyse KDE effectiveness for different sample sizes (num_samples). + Arguments: dm_grid (array): diff --git a/frb/dm_kde/pdf_fns.py b/frb/dm_kde/pdf_fns.py index ad789f7e8..6536ce9e9 100755 --- a/frb/dm_kde/pdf_fns.py +++ b/frb/dm_kde/pdf_fns.py @@ -10,6 +10,7 @@ def make_pdf(distribution, num_of_draws, grid, stepsize): """ Makes PDF of given distribution + Arguments: distribution (array): @@ -40,6 +41,7 @@ def make_kde_funtion(grid, draws, min_bandwidth, max_bandwidth, bandwidth_stepsi " cv is number of cross-validation folds " """ Returns KDE distribution + Arguments: grid (array): diff --git a/frb/dm_kde/sort_transient_data.py b/frb/dm_kde/sort_transient_data.py index 4623d09ac..8734f849f 100644 --- a/frb/dm_kde/sort_transient_data.py +++ b/frb/dm_kde/sort_transient_data.py @@ -17,6 +17,7 @@ def find_delta_dm(transient_type,transient_data,ism_model,b_val,mc_deg=5,save_df Returns array of DMs FRB data is available as a csv in the FRBs/FRB/frb/data/FRBs repo (FRB catalogue [Petroff et al. 2017]) Pulsar data is avaiable as a csv in the FRBs/pulsars/pulsars/data/atnf_cat repo (v1.61 ATNF pulsar catalogue [Manchester et al. 2005]) + Arguments: transient_type (str): diff --git a/frb/dm_kde/transient_kdes.py b/frb/dm_kde/transient_kdes.py index 52f8690ae..03fdb2d18 100644 --- a/frb/dm_kde/transient_kdes.py +++ b/frb/dm_kde/transient_kdes.py @@ -17,6 +17,7 @@ def kde_for_frb(grid, dm_frb, num_samples, num_resamples=100, save_to_path=None): """ Find FRB KDE and minima + Arguments: dm_grid (array): @@ -71,6 +72,7 @@ def kde_for_frb(grid, dm_frb, num_samples, num_resamples=100, save_to_path=None) def kde_for_psr(grid, dm_psr, num_samples, num_resamples=100, min_bandwidth=8, max_bandwidth=15, bandwidth_stepsize=0.1, cv=100, kernel='gaussian', save_to_path=None): """ Find pulsar KDE and maxima + Arguments: dm_grid (array): diff --git a/frb/em.py b/frb/em.py index ee4596070..0bb2f9973 100644 --- a/frb/em.py +++ b/frb/em.py @@ -14,6 +14,7 @@ def em_from_halpha(sb_obs, z, T=1e4*units.K): Follows the Reynolds 1977 formalism + Args: sb_obs (Quantity): Observed surface brightness @@ -22,6 +23,7 @@ def em_from_halpha(sb_obs, z, T=1e4*units.K): T (Quantity, optional): Temperature for the analysis + Returns: Quantity: EM @@ -48,6 +50,7 @@ def dm_from_em(EM, L, ff=1., eps=1., cloudcloud=2.): This follows the formalism presented in Tendulkar+2017 which follows Reynolds 1977 and Cordes+2016 + Args: EM (Quantity): Emission measure @@ -62,6 +65,7 @@ def dm_from_em(EM, L, ff=1., eps=1., cloudcloud=2.): cloud-to-cloud density variations in the ionized region of depth L in kpc. + Returns: Quantity: DM at the source; correct for (1+z)^-1 at your liking """ diff --git a/frb/figures/dm.py b/frb/figures/dm.py index 27e1ca182..4c6dc01f0 100644 --- a/frb/figures/dm.py +++ b/frb/figures/dm.py @@ -28,6 +28,7 @@ def sub_cartoon(ax1, ax2, coord, zFRB, halos=False, host_DM=50., ymax=None, Plot of increasing DM from Earth to the FRB + Args: ax1 (matplotlib.Axis): First axis. Used for Milky Way and local group @@ -234,6 +235,7 @@ def fig_cosmic(frbs, clrs=None, outfile=None, multi_model=False, no_curves=False show_sigmaDM=False, cl=(16,84), beta=3., gold_only=True, gold_frbs=None): """ + Args: frbs (list): list of FRB objects @@ -265,6 +267,7 @@ def fig_cosmic(frbs, clrs=None, outfile=None, multi_model=False, no_curves=False cosmo (astropy.cosmology, optional): Defaults to Repo Cosmology + Returns: dict: ax (optional): if outfile is None diff --git a/frb/figures/finder.py b/frb/figures/finder.py index 2f35e5a0e..a4c21e75d 100644 --- a/frb/figures/finder.py +++ b/frb/figures/finder.py @@ -39,10 +39,12 @@ def from_hdu(hdu, title, **kwargs): see generate() for more details + Args: hdul (astropy.io.fits.PrimaryHDU): title (str): + Returns: matplotlib.pyplot.figure, matplotlib.pyplot.Axis: figure generated @@ -64,6 +66,7 @@ def generate(image, wcs, title, flip_ra=False, flip_dec=False, """ Basic method to generate a Finder chart figure + Args: image (np.ndarray): Image for the finder @@ -108,6 +111,7 @@ def generate(image, wcs, title, flip_ra=False, flip_dec=False, figsize (tuple, optional): tuple to define the figure size. It goes within the fig=plt.figure(figsize=figsize) + Returns: matplotlib.pyplot.figure, matplotlib.pyplot.Axis @@ -268,6 +272,7 @@ def sdss_dss(coord, title, show_circ=True, EPOCH=None, imsize=5.*units.arcmin, o Pulled from xastropy + Args: coord (SkyCoord): title (str): @@ -424,6 +429,7 @@ def getjpg(coord, imsize, dss_only=False): """ Grab an SDSS or DSS image + Args: coord (SkyCoord): imsize (Angle or Quantity): @@ -431,6 +437,7 @@ def getjpg(coord, imsize, dss_only=False): dss_only (bool, optional): Only pull from DSS + Returns: PIL, bool: Image, flag indicating if the image is B&W """ @@ -457,11 +464,13 @@ def dsshttp(coord, imsize): """ Generate URL for DSS + Args: coord (SkyCoord): imsize (Angle or Quantity): image size + Returns: str: URL diff --git a/frb/figures/galaxies.py b/frb/figures/galaxies.py index 408f792a8..b5b9b3a00 100644 --- a/frb/figures/galaxies.py +++ b/frb/figures/galaxies.py @@ -26,6 +26,7 @@ def sub_image(fig, hdu, FRB, img_center=None, cmap='Blues', frb_clr='red'): """ + Args: fig: hdu: @@ -40,6 +41,7 @@ def sub_image(fig, hdu, FRB, img_center=None, cmap: cclr: + Returns: """ @@ -104,6 +106,7 @@ def sub_bpt(ax_BPT, galaxies, clrs, markers, show_kewley=True, SDSS_clr='BuGn', https://drive.google.com/open?id=1yHlfsvcRPXK73F6hboT1nM4bRF59ESab and put it in data/Public/SDSS + Args: ax_BPT (matplotlib.Axis): galaxies (list): @@ -121,6 +124,7 @@ def sub_bpt(ax_BPT, galaxies, clrs, markers, show_kewley=True, SDSS_clr='BuGn', bptdat (Table like): SDSS BPT data + Returns: ax_BPT is modified in place @@ -219,6 +223,7 @@ def sub_sfms(ax_M, galaxies, clrs, markers, show_legend=True): """ Generate a SF vs. M* plot on top of PRIMUS galaxies + Args: ax_M (matplotlib.axis): galaxies (list): @@ -327,6 +332,7 @@ def sub_color_mag(ax, galaxies, clrs, markers): Generate a color-magnitude diagram using PRIMUS data and FRB galaxies + Args: ax (matplotlib.Axis): galaxies (list): @@ -336,6 +342,7 @@ def sub_color_mag(ax, galaxies, clrs, markers): markers (list): List of matplotlib marker types + Returns: """ diff --git a/frb/figures/utils.py b/frb/figures/utils.py index b6ac11f53..2bd04a0e7 100644 --- a/frb/figures/utils.py +++ b/frb/figures/utils.py @@ -7,6 +7,7 @@ def log_me(val, err): """ Generate log and error from linear input + Args: val (float): @@ -28,11 +29,13 @@ def log_me(val, err): def set_fontsize(ax,fsz): """ Set the fontsize throughout an Axis + Args: ax (Matplotlib Axis): fsz (float): Font size + Returns: """ @@ -45,6 +48,7 @@ def set_bokeh_fontsize(p, fsz): """ Adjust font size for Bokeh axes + Args: p (Bokeh plot class): sz (int): Font size @@ -60,6 +64,7 @@ def set_mplrc(): """ Font fussing for matplotlib + Returns: """ diff --git a/frb/frb.py b/frb/frb.py index 7c82a873a..6cf7e4645 100644 --- a/frb/frb.py +++ b/frb/frb.py @@ -25,6 +25,8 @@ class GenericFRB(object): Parent object for FRBs + + Args: S : Quantity Source density of the burst @@ -35,6 +37,8 @@ class GenericFRB(object): RA/DEC in one of many formats (see utils.radec_to_coord) cosmo: + + Attributes: fluence (Quantity): Fluence @@ -63,10 +67,14 @@ def from_dict(cls, idict, **kwargs): """ Instantiate from a dict + + Args: idict (dict): **kwargs: Passed to the __init__ call + + Returns: """ @@ -104,10 +112,14 @@ def from_json(cls, json_file, **kwargs): Instantiate from a JSON file A simple wrapper to the from_dict method + + Args: json_file (str): **kwargs: Passed to from_dict() + + Returns: slf @@ -166,6 +178,8 @@ def set_ee(self, a, b, theta, cl, stat=True): """ Set an error ellipse for the FRB position + + Args: a (float): major axis; Arcsec b (float): minor axis; Arcsec @@ -195,6 +209,8 @@ def sig_a(self): """ Combined semi-major axis error + + Returns: float: @@ -212,6 +228,8 @@ def sig_b(self): """ Combined semi-minor axis error + + Returns: float: @@ -228,6 +246,8 @@ def set_pulse(self, freq, tscatt=None, tscatt_err=None, scatt_index=None, scatt_index_err=None, DM_smear=None): """ + + Args: freq (Quantity): Frequency at which the pulse was analyzed @@ -257,6 +277,8 @@ def make_outfile(self): """ Simple method for naming the output file + + Returns: str @@ -272,12 +294,16 @@ def write_to_json(self, outfile=None, path='./', overwrite=True): """ Write key aspects of the class to disk in a JSON file + + Args: outfile (str, optional): Output filename If not provided, one will be generated with make_outfile() path (str, optional): Path for the output file overwrite (bool, optional): Overwrite? + + Returns: """ @@ -340,10 +366,14 @@ def from_dict(cls, idict, **kwargs): """ Instantiate from a dict + + Args: idict (dict): **kwargs: Passed to the __init__ call + + Returns: """ @@ -388,12 +418,16 @@ def by_name(cls, frb_name, **kwargs): """ Method to instantiate an FRB by its name + + Args: frb_name (str): Name of the FRB, with format FRBYYYYMMDDX i.e. FRB + TNS **kwargs: + + Returns: """ @@ -404,6 +438,8 @@ def by_name(cls, frb_name, **kwargs): def __init__(self, frb_name, coord, DM, S=None, nu_c=None, z_frb=None, **kwargs): """ + + Args: frb_name (str): coord (astropy.coordinates.SkyCoord): @@ -424,6 +460,8 @@ def grab_host(self, verbose:bool=True): """ Returns the FRBHost object for this FRB + + Returns: frb.galaxies.frbgalaxy.FRBHost @@ -447,10 +485,14 @@ def list_of_frbs(require_z=False): """ Generate a list of FRB objects for all the FRBs in the Repo + + Args: require_z (bool, optional): If True, require z be set + + Returns: list: @@ -476,11 +518,15 @@ def build_table_of_frbs(frbs=None, fattrs=None): Warning: As standard, missing values are given NaN in the Pandas table Be careful! + + Args: fattrs (list, optional): Float attributes for the Table The code also, by default, looks for accompanying _err attributes + + Returns: pd.DataFrame, dict: Table of data on FRBs, dict of their units diff --git a/frb/frb_surveys/chime.py b/frb/frb_surveys/chime.py index c6780f540..357a0a7e1 100644 --- a/frb/frb_surveys/chime.py +++ b/frb/frb_surveys/chime.py @@ -20,6 +20,7 @@ def check_frb_mr(outfile:str='mr_pdf.png', pdf_file:str=None): """ Generate a plot of the host galaxy M_r PDF + Args: outfile (str, optional): _description_. Defaults to 'mr_pdf.png'. pdf_file (str, optional): _description_. Defaults to 'pdf_Mr.npy'. @@ -55,6 +56,7 @@ def calc_mr_dist(catalog_file:str=None, dm_mw_host:float=200.): """ Generate a distribution of m_r values for bright CHIME/FRBs + Args: catalog_file (str, optional): Filename for the CHIME/FRB catalog. Defaults to None. diff --git a/frb/galaxies/cigale.py b/frb/galaxies/cigale.py index c34724a8d..6ce249801 100644 --- a/frb/galaxies/cigale.py +++ b/frb/galaxies/cigale.py @@ -13,7 +13,7 @@ try: from pcigale.session.configuration import Configuration except ImportError: - print("You will need to install pcigale to use the cigale.py module") + print("You will need to install pcigale to use the cigale.py module: https://cigale.lam.fr/") else: from pcigale.analysis_modules import get_module from pcigale.utils.console import WARNING, ERROR, console @@ -33,10 +33,14 @@ def _sed_default_params(module, photo_z=False): """ Set the default parameters for CIGALE + + Args: module (str): Specify the SED using the CIGALE standard names, e.g. sfhdelayed, bc03, etc. + + Returns: params (dict): the default dict of SED modules and their initial parameters. @@ -101,6 +105,8 @@ def gen_cigale_in(photometry_table, zcol, idcol=None, infile="cigale_in.fits", Generates the input catalog from a photometric catalog. + + Args: photometry_table (astropy Table): A table from some photometric @@ -233,6 +239,8 @@ def _initialise(data_file, config_file="pcigale.ini", sed_modules_params=None, photo_z=False, **kwargs): """ Initialise a CIGALE configuration file and write to disk. + + Args: data_file (str): @@ -261,6 +269,8 @@ def _initialise(data_file, config_file="pcigale.ini", photo_z (bool, optional): If true, CIGALE will try to estimate the redshift from SED fitting. kwargs: only here to catch extras + + Returns: cigconf (pcigale.session.configuration.Configuration): CIGALE Configuration object @@ -308,6 +318,8 @@ def run(photometry_table, zcol, """ Input parameters and then run CIGALE. + + Args: photometry_table (astropy Table): A table from some photometric catalog with magnitudes and @@ -403,21 +415,16 @@ def run(photometry_table, zcol, def host_run(host, cut_photom=None, cigale_file=None): """ - Run CIGALE on an FRBGalaxy's photometry - and store results in a folder with the - FRBGalaxy's name. - Args - ---- - photom (astropy Table): Table containing - galaxy photometry. Table columns - must be in the format '_' - and '__err'. - e.g. SDSS_u, SDSS_u_err, Pan-STARRS_g - host (FRBGalaxy): A host galaxy. - cigale_file (str, optional): Name of main - CIGALE output file. Must be in the format - `_CIGALE.fits`. No file is - renamed if nothing is provided. + Run CIGALE on host-galaxy photometry. + + Parameters + ---------- + host : FRBGalaxy + Host galaxy object. + cut_photom : astropy.table.Table, optional + Photometry table to use instead of `host.photom`. + cigale_file : str, optional + Output filename for copied CIGALE results. """ cigale_tbl = Table() cigale_tbl['z'] = [host.z] diff --git a/frb/galaxies/defs.py b/frb/galaxies/defs.py index c650c6d3c..ff6274fd3 100644 --- a/frb/galaxies/defs.py +++ b/frb/galaxies/defs.py @@ -1,8 +1,7 @@ -""" Define allowed quantities for FRB galaxies +"""Define allowed quantities for FRB galaxies. - Uncertainty is valid for any quantity with '_err' add-on, eg. W1_err - Now _loerr and _uperr are also allowed - Am also likely to add _flg for each as well +Uncertainty is valid for any quantity with ``_err`` add-on (e.g. ``W1_err``). +Also supports ``_loerr`` and ``_uperr`` suffixes. """ allowed_errors = ['_err', '_loerr', '_uperr'] diff --git a/frb/galaxies/eazy.py b/frb/galaxies/eazy.py index be308c0bc..051a34151 100644 --- a/frb/galaxies/eazy.py +++ b/frb/galaxies/eazy.py @@ -93,6 +93,7 @@ def eazy_filenames(input_dir, name): """ Generate names for EAZY files + Args: input_dir (str): Path to eazy inputs/ folder (can be relative) @@ -100,6 +101,7 @@ def eazy_filenames(input_dir, name): name (str): Name of the source being analzyed + Returns: tuple: catalog_filename, parameter_filename, translate_file @@ -117,6 +119,7 @@ def eazy_setup(input_dir, template_dir=None): """ Setup for EAZY + Args: input_dir (str): Path to personal eazy inputs/ folder (can be relative) @@ -125,6 +128,7 @@ def eazy_setup(input_dir, template_dir=None): If not given, it looks for the folder of `eazy`, the executable and navigates from there. + Returns: """ @@ -152,6 +156,7 @@ def eazy_input_files(photom, input_dir, name, out_dir, id_col="id", prior_filter - translation file - param file + Args: photom (dict or Table): Held by an FRBGalaxy object @@ -361,6 +366,7 @@ def run_eazy(input_dir, name, logfile): """ Find and run the EAZY executable on the files + Args: input_dir (str): Path to eazy inputs/ folder (can be relative) @@ -402,10 +408,12 @@ def eazy_stats(zgrid, pzi): """ Calculate the 'best' zphot and error + Args: zgrid (np.ndarray): pzi (np.ndarray): + Returns: """ diff --git a/frb/galaxies/extra_data.py b/frb/galaxies/extra_data.py index d875f055a..83c198d7a 100644 --- a/frb/galaxies/extra_data.py +++ b/frb/galaxies/extra_data.py @@ -10,6 +10,7 @@ def load_mannings2021(): """ Load a table of measurements from the Mannings+2021 paper + Returns: tuple: measurements (pandas.DataFrame), units and description (dict) """ diff --git a/frb/galaxies/frbgalaxy.py b/frb/galaxies/frbgalaxy.py index 65e5e026d..a234e21da 100644 --- a/frb/galaxies/frbgalaxy.py +++ b/frb/galaxies/frbgalaxy.py @@ -33,12 +33,14 @@ class FRBGalaxy(object): Warning: Generating hundreds of these objects will likely be slow. Especially SkyCoord generation. A new class will be warranted for that + Args: ra (float): RA in deg dec (float): DEC in deg frb (frb.FRB): FRB object cosmo (astropy.cosmology): Cosmology, e.g. Planck18 + Attributes: redshift (dict): photom (dict): @@ -53,6 +55,7 @@ def from_dict(cls, frb, idict, override:bool=False, **kwargs): """ Instantiate from a dict + Args: frb (frb.FRB): idict (dict): @@ -61,6 +64,7 @@ def from_dict(cls, frb, idict, override:bool=False, **kwargs): Not recommended unless you know what you are doing **kwargs: Passed to the __init__ call + Returns: """ @@ -98,11 +102,13 @@ def from_dict(cls, frb, idict, override:bool=False, **kwargs): def from_json(cls, frb, json_file, verbose:bool=True, **kwargs): """ + Args: frb (frb.FRB): json_file: **kwargs: + Returns: FRBGalaxy or None @@ -119,6 +125,7 @@ def from_json(cls, frb, json_file, verbose:bool=True, **kwargs): def __init__(self, ra, dec, frb, cosmo=None): """ + Args: ra (float): dec (float): @@ -160,6 +167,7 @@ def z(self): """ Return the redshift of the galaxy + Returns: float or None: redshift or nadda @@ -173,6 +181,7 @@ def z_err(self): """ Return the redshift error of the galaxy + Returns: float or None: redshift or nadda @@ -189,6 +198,7 @@ def calc_nebular_lum(self, line): Mainly a wrapper to nebular.calc_lum() + Args: line (str): Name of the line """ @@ -214,11 +224,13 @@ def calc_nebular_AV(self, method='Ha/Hb', min_AV=None, **kwargs): self.derived['AV_nebular'] is filled + Args: method (str): Method to use min_AV (float): Minimum A_V value allowed; might set 0. someday **kwargs: Passed to nebular.calc_dust_extinct + Returns: """ @@ -239,10 +251,12 @@ def calc_nebular_SFR(self, method='Ha', **kwargs): self.derived['AV_nebular'] is filled with units SFR/yr + Args: method (str): Method to use, e.g. 'Ha' for Halpha **kwargs: passed to nebular.calc_SFR + Returns: """ @@ -265,6 +279,7 @@ def calc_tot_uncert(self): FRB localization + Host localization in the reference frame of the FRB + Returns: tuple: uncerta, uncertb [arcsec] """ @@ -302,6 +317,7 @@ def parse_photom(self, phot_tbl, max_off=1*units.arcsec, Also fills fluxes in mJy + Args: phot_tbl (astropy.table.Table): ra, dec entires are required @@ -310,6 +326,7 @@ def parse_photom(self, phot_tbl, max_off=1*units.arcsec, EBV (float, optional): Galactic reddening. If included, the photometry has been corrected for this. If not, who knows?! :) + Returns: """ @@ -357,6 +374,7 @@ def run_cigale(self, data_file="cigale_in.fits", config_file="pcigale.ini", given the photometric points and redshift of a galaxy + Args: ID: str, optional An ID for the galaxy. If none, "GalaxyA" is assigned. @@ -422,6 +440,7 @@ def get_metaspec(self, instr=None, return_all=False, specdb_file=None): If there is more than one spectrum, the code returns the first unless return_all=True + Args: instr (str, optional): Restrict to the input Instrument @@ -430,6 +449,7 @@ def get_metaspec(self, instr=None, return_all=False, specdb_file=None): specdb_file (str, optional): Path+name of the specDB file to use (over-ride the default) + Returns: astropy.table.Table, linetools.spectra.XSpectrum1D: meta data, spectra @@ -472,11 +492,13 @@ def parse_cigale(self, cigale_file, sfh_file=None, overwrite=True): Read into self.derived + Args: cigale_file (str): Name of the CIGALE results file sfh_file (str, optional): Name of the best SFH model file. overwrite (bool, optional): Over-write any previous values + Returns: """ @@ -540,6 +562,7 @@ def parse_galfit(self, galfit_file, overwrite=True, Loaded into self.morphology + Args: galfit_file (str): processed 'out.fits' file produced by frb.galaxies.galfit.run. Contains @@ -595,11 +618,13 @@ def parse_ppxf(self, ppxf_file, overwrite=True, format='ascii.ecsv'): Loaded into self.lines + Args: ppxf_file (str): pPXF results file overwrite (bool, optional): format (str, optional): Format of the table + Returns: """ @@ -649,6 +674,7 @@ def set_z(self, z, origin, err=None): """ Set the redshift value(s) in self.redshift + Args: z (float): Redshift value origin (str): Origin @@ -656,6 +682,7 @@ def set_z(self, z, origin, err=None): 'phot' for photometric err (float, optional): Error in the redshift + Returns: """ @@ -688,9 +715,11 @@ def vet_one(self, attr): """ Vette one of the main_attr + Parameters: attr (str): + Returns: bool: True = passed @@ -734,10 +763,12 @@ def vet_all(self): """ Vette all of the main dicts + Args: dict: valid_defs: + Returns: bool: True = passed @@ -753,6 +784,7 @@ def make_outfile(self): """ Auto-generate an output name for the class + Returns: str: Output filename @@ -765,12 +797,14 @@ def write_to_json(self, outfile=None, path='./', overwrite=True): """ Write key aspects of the class to disk in a JSON file + Args: outfile (str, optional): Output filename If not provided, one will be generated with make_outfile() path (str, optional): Path for the output file overwrite (bool, optional): Overwrite? + Returns: """ @@ -818,6 +852,7 @@ class FRBHost(FRBGalaxy): """ Child of FRBGalaxy specific for an FRB host + Args: ra (float): RA in deg dec (float): DEC in deg @@ -827,6 +862,7 @@ class FRBHost(FRBGalaxy): @classmethod def by_frb(cls, frb, **kwargs): """ + Args: frb (frb.FRB): FRB object @@ -864,9 +900,11 @@ def _make_outfile(frbname): """ Static method to generate outfile based on frbname + Args: frbname (str): FRB name, e.g. 121102 or FRB121102 + Returns: str: outfile @@ -884,8 +922,10 @@ def calc_dm_halo(self, **kwargs): given the host stellar mass in its derived properties dict and the FRB coordinates. + Args: **kwargs: Passed to dm_host.dm_host_halo + Returns: DM_halo (float): Halo contribution to the DM in pc/cm^3 @@ -909,6 +949,7 @@ def make_outfile(self): Naming is FRBXXXXXX_host.json with XXXXXXX supplied by self.frb + Returns: str: Name of the default outfile @@ -924,6 +965,7 @@ def set_z(self, z, origin, err=None): self.redshift is modified in place + Args: z (float): Redshift value origin (str): Origin @@ -931,6 +973,7 @@ def set_z(self, z, origin, err=None): 'phot' for photometric err (float, optional): Error in the redshift + Returns: """ diff --git a/frb/galaxies/galfit.py b/frb/galaxies/galfit.py index 4eb10e8d9..298ce2a76 100755 --- a/frb/galaxies/galfit.py +++ b/frb/galaxies/galfit.py @@ -28,9 +28,13 @@ def get_platescale(wcs:WCS)->float: """ Extract the plate-scale from a WCS object + + Args: wcs (WCS): A celestial WCS object extracted from a FITS header. + + Returns: platescale (float): arcsec/pixel """ @@ -46,6 +50,8 @@ def write_cutout(cutout:Cutout2D, filename:str = "cutout.fits", overwrite:bool=F """ Takes an astropy Cutout2D object and writes it to disk. + + Args: cutout (Cutout2D): Prefaerably has WCS info in it. @@ -89,6 +95,8 @@ def _genconf(imgfile:str, psffile:str=None, mode=0, """ Creates a configuration file for GALFIT. Conventionally, GALFIT is run using the command: `galfit `. + + Args: imgfile (str): path to the image fits file. psffile (str, optional): path to the PSF model fits file. @@ -148,6 +156,8 @@ def _genconf(imgfile:str, psffile:str=None, mode=0, skip_sky (bool, optional): Do you also want to fit a constant sky background? Set to false if your sky background is 0. + + Returns: configfile (str): Path to the configuration file. @@ -288,6 +298,8 @@ def read_fitlog(outfile:str, initfile:str, twocomponent:bool=False)->dict: """ Reads the output fit.log file and returns the sersic fit parameters + + Args: outfile (str): Path and name of the fit log file. @@ -295,6 +307,8 @@ def read_fitlog(outfile:str, initfile:str, twocomponent:bool=False)->dict: used to produce the log entry. This is used to distinguish multiple entried in the logfile. + + Returns: pix_dict (dict): A dict containing the GALFIT best fit parameters @@ -359,6 +373,8 @@ def pix2coord(pix_dict:dict, wcs:WCS, table:bool=False,multicomponent:bool=False Takes the output table from galfit's fit.log file and converts all pixel measurements to physical measurements. + + Args: pix_dict (dict): Raw sersic fit parameter dict from fit.log @@ -369,6 +385,8 @@ def pix2coord(pix_dict:dict, wcs:WCS, table:bool=False,multicomponent:bool=False true, this snippet accounts out for multiple sersic profiles in the same model. + + Returns: sky_dict (dict/Table): pix_dict translated to angular units @@ -478,6 +496,8 @@ def run(imgfile:str, psffile:str=None, **kwargs)->int: skip_sky (bool, optional): Do you also want to fit a constant sky background? Set to false if your sky background is 0. + + Returns: fit_outcome (int): An int encoding the success/failure of the fitting procedure. 0 corresponds diff --git a/frb/galaxies/hosts.py b/frb/galaxies/hosts.py index 421bc7ad9..bd06f2fb1 100644 --- a/frb/galaxies/hosts.py +++ b/frb/galaxies/hosts.py @@ -20,6 +20,8 @@ def chance_coincidence(rmag, r_i): ..todo.. Expand to allow for other filters + + Args: rmag (float): r-band magnitude r_i (Angle or Quantity): @@ -27,6 +29,8 @@ def chance_coincidence(rmag, r_i): Should be the max[2Rhalf, 3 sigma_r0, (R_0^2 + 4 Rhalf^2)^1/2] See Bloom et al. 2002 + + Returns: float: Probability of a chance association @@ -47,10 +51,14 @@ def chance_dx(rmag): Returns the angular separation for a secure association (1%) as in https://ui.adsabs.harvard.edu/abs/2014MNRAS.437.1495T/abstract + + Args: rmag (float): r-band magnitude + + Returns: Quantity: Angular offset in arcsec @@ -63,6 +71,8 @@ def random_separation(catalog, wcs, npix, trim=1*units.arcmin, ntrial=100): """ Find random offsets to + + Args: catalog (astropy.table.Table): wcs (astropy.WCS.WCS): @@ -70,6 +80,8 @@ def random_separation(catalog, wcs, npix, trim=1*units.arcmin, ntrial=100): trim (astropy.units.Quantity, optional): ntrial (int, optional): + + Returns: astropy.units.Quantity: angular distances @@ -107,11 +119,15 @@ def get_R(R_frb, R_0=0.2, R_h=0.25): """ Calculates Radius of localisation region in arcsecond Based on Bloom et al 2002 and Eftekhari et al 2017 + + Args: R_frb (float): The 1 sigma localization radius of the FRB R_0 (float): Radial angular separation between the FRB position and a presumed host R_h (float): Galaxy half light radius + + Returns: float: radius (in arcseconds) @@ -125,6 +141,8 @@ def read_r_mags(data_table_path): Reads data used in Driver et al (2016). https://iopscience.iop.org/article/10.3847/0004-637X/827/2/108 + + Args: data_table_path (string): Path to the fits file with data @@ -166,19 +184,10 @@ def read_r_mags(data_table_path): def prob_eb17(R_frb, m, R_0=0.2, R_h=0.25, ret_numgal=False): """ - Calculates chance association probability of a galaxy to an FRB - Taken from: - Section 2 of https://ui.adsabs.harvard.edu/abs/2017ApJ...849..162E/abstract + Chance-coincidence probability of associating a galaxy with an FRB. - Args: - R_frb (float): The 1 sigma localization radius of the FRB in arcsec - m (float): r band magnitude of the galaxy - R_0 (float): Radial angular separation between the FRB position and a presumed host - R_h (float): Galaxy half light radius - ret_numgal (bool): to return the number of galaxies along with the chance coincidence probability - - Returns: - float: Probability of chance coincidence + Implements Eq. 2-style formalism from Eftekhari & Berger (2017). + Returns probability, and optionally expected number of galaxies. """ r_dat, mag_uniq, cvs = read_r_mags(importlib_resources.files('frb.data.Galaxies')/'driver2016_t3data.fits') @@ -192,7 +201,6 @@ def n_gal(m_r): num_dens_gal = quad(n_gal, 0, m)[0] R = get_R(R_frb, R_0, R_h) - deg2arcsec = 60 * 60 num_gals = np.pi * (R / deg2arcsec) ** 2 * num_dens_gal @@ -201,9 +209,9 @@ def n_gal(m_r): else: return 1 - np.exp(-1 * num_gals) + def load_host_tbl(hosts_file:str=None, host_tbl:pandas.DataFrame=None): - """ Generate a simple host table from a CSV, usually - the public file + """Generate a simple host table from a CSV file. Args: hosts_file (str, optional): [description]. Defaults to None. @@ -230,10 +238,14 @@ def load_Mr_pdf(pdf_file:str=None): Generated by M. Bhardwaj from ~20 localized FRBs + + Args: pdf_file (str, optional): Filename for the PDF. Defaults to None. + + Returns: tuple: Mr, PDF """ diff --git a/frb/galaxies/nebular.py b/frb/galaxies/nebular.py index 2da5a0e24..c32cca572 100644 --- a/frb/galaxies/nebular.py +++ b/frb/galaxies/nebular.py @@ -33,12 +33,14 @@ def calc_dust_extinct(neb_lines, method): Uses the Gordon 2024 + Args: neb_lines (dict): Line fluxes method (str): Name of the method Ha/Hb -- Use the Halpha/Hbeta ratio and standard intrinsic flux curve (str): Extinction curve to use + Returns: float: A_V in magnitudes @@ -90,11 +92,13 @@ def calc_logOH(neb_lines, method): Estimate the oxygen abundance based on the input nebular emission line fluxes For now based on the O3N2 calibration from https://ui.adsabs.harvard.edu/abs/2018AJ....155...82H/abstract + Args: neb_lines (dict): Line fluxes method (str): Name of the method O3N2 -- Use the O3N2 calibration from Hirschauer+18 + Returns: tuple: 12+log(O/H), sigma+, sigma- """ @@ -138,6 +142,7 @@ def calc_lum(neb_lines, line, z, cosmo, AV=None): Error is -999.*erg/s if input line flux has negative error + Args: neb_lines (dict): Observed line fluxes and errors line (str): Line to analyze @@ -145,6 +150,7 @@ def calc_lum(neb_lines, line, z, cosmo, AV=None): cosmo (astropy.cosmology.FLRW): Cosmology AV (float, optional): Visual extinction, if supplied will apply + Returns: Quantity, Quantity: Luminosity, sig(Luminosity) """ @@ -182,6 +188,7 @@ def calc_SFR(neb_lines, method, z, cosmo, AV=None, curve='MW'): """ Calculate the SFR from input nebular line emission + Args: neb_lines (dict): Observed line fluxes method (str): Method for deriving the SFR @@ -191,6 +198,7 @@ def calc_SFR(neb_lines, method, z, cosmo, AV=None, curve='MW'): AV (float, optional): Visual extinction, if supplied will apply curve (str): Name of the extinction curve. Only used if A_V is supplied + Returns: Quantity: SFR with units of Msun/yr @@ -217,6 +225,7 @@ def get_ebv(coords,definition="SandF", """ Get the E(B-V) value and statistic from the Milky way dust extinction within the query region around the input coordinate + Args: coords (Astropy SkyCoord): @@ -235,6 +244,7 @@ def get_ebv(coords,definition="SandF", get_ext_table: bool, optional If true, also returns the table with A/E(B-V) ratios for multiple filters. + Returns: dict: Dict with E(B-V) at refPixelValue, meanValue, std, minValue and maxValue in diff --git a/frb/galaxies/offsets.py b/frb/galaxies/offsets.py index c24be9256..7f374d514 100644 --- a/frb/galaxies/offsets.py +++ b/frb/galaxies/offsets.py @@ -14,6 +14,7 @@ def angular_offset(frb, galaxy, nsigma=5., nsamp=2000, Warning: All calculations in arcsec -- Do not use for *large* localization error + Args: frb (frb.frb.FRB): galaxy (frb.galaxies.FRBGalaxy): @@ -21,6 +22,7 @@ def angular_offset(frb, galaxy, nsigma=5., nsamp=2000, nsamp: Grid sample points for each 1D Gaussian (one in RA and Dec) gal_sig (tuple): RA, DEC errors in arcsec as floats + Returns: tuple: float, float, float, float avg_off, sig_off, best_off, sig_best @@ -88,6 +90,7 @@ def incorporate_hst(hst_astrom:pandas.DataFrame, host): Currently for Mannings+2021 only + Args: hst_astrom (pandas.DataFrame): [description] host (frb.galaxies.frbgalaxy.FRBHost): [description] diff --git a/frb/galaxies/photom.py b/frb/galaxies/photom.py index 60c5e2fae..3fc0110f7 100644 --- a/frb/galaxies/photom.py +++ b/frb/galaxies/photom.py @@ -36,12 +36,14 @@ def merge_photom_tables(new_tbl, old_file, tol=1*units.arcsec, debug=False): """ Merge photometry tables + Args: new_tbl (astropy.table.Table): New table of photometry old_file (str or Table): Path to the old table + Returns: astropy.table.Table: Merged tables @@ -88,10 +90,12 @@ def photom_by_name(name, filelist): Warning: Order matters! Use best data last + Args: name (str): filelist (list): + Returns: astropy.table.Table: @@ -134,6 +138,7 @@ def extinction_correction(filt, EBV, RV=3.1, max_wave=None, required=True): required (bool, optional): Crash out if the transmission curve is not present + Returns: float: linear extinction correction @@ -201,6 +206,7 @@ def correct_photom_table(photom, EBV, name, max_wave=None, required=True): Uses extinction_correction() + Args: photom (astropy.table.Table): Required keys: 'Name', filters @@ -211,6 +217,7 @@ def correct_photom_table(photom, EBV, name, max_wave=None, required=True): required (bool, optional): Crash out if the transmission curve is not present + Returns: int: Return code -1: No matches to the input name @@ -271,6 +278,7 @@ def sb_at_frb(host, cut_dat:np.ndarray, cut_err:np.ndarray, wcs:WCS, """ Measure the surface brightness at an FRB location in a host galaxy + Args: host (Host object): host galaxy object from frb repo cut_dat (np.ndarray): data (data from astorpy 2D Cutout object) @@ -282,6 +290,7 @@ def sb_at_frb(host, cut_dat:np.ndarray, cut_err:np.ndarray, wcs:WCS, min_uncert (int, optional): Minimum localization unceratainty for the FRB, in pixels. Defaults to 2. + Returns: tuple: sb_average, sb_average_err [counts/sqarcsec] """ @@ -360,12 +369,14 @@ def sb_at_frb(host, cut_dat:np.ndarray, cut_err:np.ndarray, wcs:WCS, def fractional_flux(cutout, frbdat, hg, nsig=3.): """Calculate the fractional flux at the FRB location + Args: cutout (WCS Cutout2D): astropy 2D Cutout of data around host galaxy frbdat (frb.FRB): frb object loaded from frb repo hg (frb.galaxies.frbgalaxy.FRBHost): host galaxy object loaded from frb repo nsig (float, optional): sigma for FRB localization within which the measurement should be made. Defaults to 3. + Returns: tuple: median_ff, sig_ff, ff_weight [no units] Median fractional flux, uncertainty diff --git a/frb/galaxies/ppxf.py b/frb/galaxies/ppxf.py index 71c0806f0..d4debc56b 100644 --- a/frb/galaxies/ppxf.py +++ b/frb/galaxies/ppxf.py @@ -44,6 +44,8 @@ def run(spec_file, R, zgal, results_file=None, spec_fit='tmp.fits', chk=True, Outputs are written to disk + + Args: spec_file (str or XSpectrum1D): R (float): @@ -362,7 +364,7 @@ def total_mass(miles, weights, quiet=False): in models fitted, given the weights produced and output by pPXF. A Salpeter IMF is assumed (slope=1.3) initially. - - TODO: Employ Chabrier models + TODO: Employ Chabrier models. The returned mass excludes the gas lost during stellar evolution. This procedure uses the mass predictions diff --git a/frb/galaxies/utils.py b/frb/galaxies/utils.py index 0d90c3e4c..fe98eacd7 100644 --- a/frb/galaxies/utils.py +++ b/frb/galaxies/utils.py @@ -27,10 +27,12 @@ def deredden_spec(spectrum, ebv:float): """ Deredden the input spectrum using the input EBV value + Args: spectrum (xspectrum1d.XSpectrum1D): Spectrum ebv (float): Galactic reddening + Returns: xspectrum1d.XSpectrum1D: De-reddened spectrum """ @@ -57,10 +59,12 @@ def load_specdb(specdb_file=None): """ Automatically load the specDB file from $SPECDB/FRB_specDB.hdf5 + Args: specdb_file (str, optional): Over-ride the default file + Returns: specdb.specdb.SpecDB: @@ -89,11 +93,13 @@ def list_of_hosts(skip_bad_hosts=True, verbose:bool=False): Also returns a list of the FRBs + Args: skip_bad_hosts (bool): verbose (bool): If True, print more to the screen + Returns: list, list: @@ -137,6 +143,7 @@ def build_table_of_hosts(attrs:list=None): #PATH_root_file:str='scale0.5.csv'): Note: RA, DEC are given as RA_host, DEC_host to avoid conflict with the FRB table + Args: Returns: @@ -246,6 +253,7 @@ def load_f_mL(): Warning: this is rather approximate + Returns: scipy.interpolate.interp1d: @@ -264,9 +272,11 @@ def load_f_mL(): def load_PATH(PATH_root_file:str='adopted.csv'): """Load up the PATH table + Args: PATH_root_file (str, optional): [description]. Defaults to 'adopted.csv'. + Returns: pandas.DataFrame: Table of galaxy coordinates and PATH results """ diff --git a/frb/halos/hmf.py b/frb/halos/hmf.py index ebda5afe4..fa2f4a126 100644 --- a/frb/halos/hmf.py +++ b/frb/halos/hmf.py @@ -20,6 +20,8 @@ def init_hmf(): WARNING: This uses the original version which codes Tinker+2008 We may refactor to use the more accurate, new version + + Returns: hmfe (hmf_emulator.hmf_emulator): An Aemulus halo mass function emulator. @@ -48,7 +50,7 @@ def init_hmf(): try: import hmf_emulator except: - warnings.warn("hmf_emulator not imported. Hope you are not intending to use the hmf.py module..") + print("If you wish to use the halos modules, you need the Aemulus HMF emulator. Please install it: github.com/AemulusProject/hmf_emulator") else: hmfe = init_hmf() @@ -63,6 +65,8 @@ def frac_in_halos(zvals, Mlow, Mhigh, rmax=1.): Requires Aemulus HMF to be installed + + Args: zvals: ndarray Mlow: float @@ -73,6 +77,8 @@ def frac_in_halos(zvals, Mlow, Mhigh, rmax=1.): Extent of the halo in units of rvir WARNING: This calculation assumes a single concentration for all halos + + Returns: ratios: ndarray rho_halo / rho_m @@ -122,33 +128,29 @@ def halo_incidence(Mlow, zFRB, radius=None, hmfe=None, Requires Aemulus HMF to be installed - Args: - Mlow: float - Mass of minimum halo in Solar masses - The code deals with h^-1 factors so that you do not - The minimum value is 2e10 - zFRB: float - Redshift of the FRB - radius: Quantity, optional - Physical separation from the sightline for the calculation. - The calculation will specify this radius as rvir derived from - Mlow unless this is specified. And this rvir *will* vary with redshift - hmfe (hmf.hmf_emulator, optional): Halo mass function emulator from Aeumulus - Mhigh: float, optional - Mass of maximum halo in Solar masses - nsammple: int, optional - Number of samplings in redshift - 20 should be enough - cumul: bool, optional - Return the cumulative quantities instead - Returns: - If cumul is False - Navg: float - Number of average intersections - elif cumul is True - zeval: ndarray - Ncumul: ndarray + + Parameters + ---------- + Mlow : float + Minimum halo mass in solar masses. + zFRB : float + FRB redshift. + radius : Quantity, optional + Fixed impact radius; if None, infer from r200(Mlow, z). + hmfe : object, optional + Aemulus halo mass function emulator. + Mhigh : float, optional + Maximum halo mass in solar masses. + nsample : int, optional + Number of redshift samples. + cumul : bool, optional + Return cumulative incidence if True. + + Returns + ------- + float or tuple + Mean intersections, or ``(zs, Navg)`` when `cumul=True`. """ # Mlow limit if Mlow < 2e10: @@ -202,27 +204,37 @@ def build_grid(z_FRB=1., ntrial=10, seed=12345, Mlow=1e10, r_max=2., outfile=Non Requires the Aemulus Halo Mass function - Args: - z_FRB: float, optional - ntrial: int, optional - seed: int, optional - Mlow: float, optional - h^-1 mass - r_max: float, optional - Extent of the halo in units of rvir - outfile: str, optional - Write - dz_box: float, optional - Size of the slice of the universe for each sub-calculation - dz_grid: float, optional - redshift spacing in the DM grid - f_hot: float - Fraction of the cosmic fraction of matter in diffuse gas (for DM) - Returns: - DM_grid: ndarray (ntrial, nz) - halo_tbl: Table - Table of all the halos intersected + + Parameters + ---------- + z_FRB : float, optional + FRB redshift limit. + ntrial : int, optional + Number of Monte Carlo trials. + seed : int, optional + Random seed. + Mlow : float, optional + Minimum halo mass. + r_max : float, optional + Halo extent in units of rvir. + outfile : str, optional + Optional output path. + dz_box : float, optional + Redshift box size per sub-calculation. + dz_grid : float, optional + Redshift spacing in DM grid. + f_hot : float, optional + Diffuse-gas fraction. + verbose : bool, optional + Verbose logging. + + Returns + ------- + DM_grid : ndarray + DM grid with shape ``(ntrial, nz)``. + halo_tbl : Table + Table of intersected halos. """ Mhigh = 1e16 # Msun diff --git a/frb/halos/models.py b/frb/halos/models.py index e2621f8f0..eda663a37 100644 --- a/frb/halos/models.py +++ b/frb/halos/models.py @@ -28,6 +28,8 @@ def init_hmf(): WARNING: This uses the original version which codes Tinker+2008 We may refactor to use the more accurate, new version + + Returns: """ @@ -54,7 +56,7 @@ def init_hmf(): try: import hmf_emulator except: - pass + print("If you wish to use the halos modules, you need the Aemulus HMF emulator. Please install it: github.com/AemulusProject/hmf_emulator") else: hmfe = init_hmf() @@ -68,6 +70,8 @@ def frac_in_halos(zvals, Mlow, Mhigh, rmax=1.): Requires Aemulus HMF to be installed + + Args: zvals: ndarray Mlow: float @@ -78,6 +82,8 @@ def frac_in_halos(zvals, Mlow, Mhigh, rmax=1.): Extent of the halo in units of rvir WARNING: This calculation assumes a single concentration for all halos + + Returns: ratios: ndarray rho_halo / rho_m @@ -115,37 +121,10 @@ def frac_in_halos(zvals, Mlow, Mhigh, rmax=1.): def halo_incidence(Mlow, zFRB, radius=None, hmfe=None, Mhigh=1e16, nsample=20, cumul=False): """ - Calculate the (approximate) average number of intersections to halos of a - given minimum mass to a given zFRB. - - Requires Aemulus HMF to be installed - - Args: - Mlow: float - Mass of minimum halo in Solar masses - The code deals with h^-1 factors so that you do not - The minimum value is 2e10 - zFRB: float - Redshift of the FRB - radius: Quantity, optional - The calculation will specify this radius as rvir derived from - Mlow unless this is specified. And this rvir *will* vary with redshift - hmfe (hmf.hmf_emulator, optional): Halo mass function emulator from Aeumulus - Mhigh: float, optional - Mass of maximum halo in Solar masses - nsammple: int, optional - Number of samplings in redshift - 20 should be enough - cumul: bool, optional - Return the cumulative quantities instead + Compute average number of halo intersections to redshift ``zFRB``. - Returns: - If cumul is False - Navg: float - Number of average intersections - elif cumul is True - zeval: ndarray - Ncumul: ndarray + Uses Aemulus HMF. Returns scalar incidence or cumulative arrays when + ``cumul`` is True. """ # Mlow limit if Mlow < 2e10: @@ -199,27 +178,37 @@ def build_grid(z_FRB=1., ntrial=10, seed=12345, Mlow=1e10, r_max=2., outfile=Non Requires the Aemulus Halo Mass function - Args: - z_FRB: float, optional - ntrial: int, optional - seed: int, optional - Mlow: float, optional - h^-1 mass - r_max: float, optional - Extent of the halo in units of rvir - outfile: str, optional - Write - dz_box: float, optional - Size of the slice of the universe for each sub-calculation - dz_grid: float, optional - redshift spacing in the DM grid - f_hot: float - Fraction of the cosmic fraction of matter in diffuse gas (for DM) - Returns: - DM_grid: ndarray (ntrial, nz) - halo_tbl: Table - Table of all the halos intersected + + Parameters + ---------- + z_FRB : float, optional + FRB redshift limit. + ntrial : int, optional + Number of Monte Carlo trials. + seed : int, optional + Random seed. + Mlow : float, optional + Minimum halo mass. + r_max : float, optional + Halo extent in units of rvir. + outfile : str, optional + Optional output path. + dz_box : float, optional + Redshift box size per sub-calculation. + dz_grid : float, optional + Redshift spacing in DM grid. + f_hot : float, optional + Diffuse-gas fraction. + verbose : bool, optional + Verbose logging. + + Returns + ------- + DM_grid : ndarray + DM grid with shape ``(ntrial, nz)``. + halo_tbl : Table + Table of intersected halos. """ Mhigh = 1e16 # Msun @@ -414,11 +403,15 @@ def stellarmass_from_halomass(log_Mhalo,z=0, params=None): """ Stellar mass from Halo Mass from Moster+2013 https://doi.org/10.1093/mnras/sts261 + + Args: log_Mhalo (float): log_10 halo mass in solar mass units. z (float, optional): halo redshift. Assumed to be 0 by default. + + Returns: log_mstar (float): log_10 galaxy stellar mass in solar mass units. @@ -460,11 +453,15 @@ def halomass_from_stellarmass(log_mstar,z=0, randomize=False): Inverts the function `stellarmass_from_halomass` numerically. + + Args: log_mstar (float or numpy.ndarray): log_10 stellar mass in solar mass units. z (float, optional): galaxy redshift + + Returns: log_Mhalo (float): log_10 halo mass in solar mass units. @@ -501,8 +498,12 @@ def stellarmass_from_halomass_kravtsov(log_mhalo): Caution: This relation is valid for low z (z~0). Higher z values may require a scaled relation. + + Args: log_mhalo (float): log_10 halo mass + + Returns: log_mstar (float): log_10 galaxy """ @@ -521,8 +522,12 @@ def stellarmass_from_halomass_kravtsov(log_mhalo): def halomass_from_stellarmass_kravtsov(log_mstar): """ Inverts the function `frb.halos.models.stellarmass_from_halomass_kravtsov`. + + Args: log_mstar (float or numpy.ndarray): log_10 stellar mass + + Returns: log_mhalo (float): log_10 halo mass """ @@ -538,6 +543,8 @@ class ModifiedNFW(object): """ Generate a modified NFW model, e.g. Mathews & Prochaska 2017 for the hot, virialized gas. + + Parameters: log_Mhalo: float, optional log10 of the Halo mass [dark matter + baryons] (solar masses) @@ -604,6 +611,8 @@ def __init__(self, def setup_param(self,cosmo,): """ Setup key parameters of the model + + Args: cosmo: astropy cosmology Cosmology of the universe @@ -903,6 +912,8 @@ class MB04(ModifiedNFW): Halo based on the Maller & Bullock (2004) model of virialized halo gas. + + Parameters: Rc: Quantity cooling radius @@ -929,6 +940,8 @@ def norm_rhoV(self): """ Normalize the density constant from MB04 + + Returns: """ @@ -951,10 +964,14 @@ def rho_b(self, xyz): """ Baryonic density profile + + Args: xyz: ndarray Position array assumed in kpc + + Returns: """ @@ -997,6 +1014,8 @@ def setup_yfdensity(self): """ Normalize the density profile from the input mass + + Returns: Initializes self.rhoN, the density normalization @@ -1023,10 +1042,14 @@ def rho_b(self, xyz): """ Calculate the baryonic density + + Args: xyz: ndarray Coordinates in kpc + + Returns: rho: Quantity array Baryonic mass density (g/cm**3) @@ -1063,10 +1086,14 @@ def nH(self, xyz): """ Calculate the number density of Hydrogen + + Args: xyz: ndarray Coordinates in kpc + + Returns: ndarray: Number density with units of 1/cm**3 @@ -1116,12 +1143,16 @@ def DM_from_Galactic(self, scoord, **kwargs): Calculate DM through M31's halo from the Sun given a direction + + Args: scoord: SkyCoord Coordinates of the sightline **kwargs: Passed to Ne_Rperp + + Returns: DM: Quantity Dispersion measure through M31's halo @@ -1150,12 +1181,16 @@ def DM_from_impact_param_b(self, bimpact, **kwargs): Calculate DM through M31's halo from the Sun given an impact parameter + + Args: bimpact: Quantity Ratio of the impact parameter to r200 **kwargs: Passed to Ne_Rperp + + Returns: DM: Quantity Dispersion measure through M31's halo @@ -1342,9 +1377,13 @@ def nH(self, xyz): """ Scale by He + + Args: xyz: + + Returns: """ diff --git a/frb/halos/photoz.py b/frb/halos/photoz.py index 8e1db6a6f..e2eaed5c6 100644 --- a/frb/halos/photoz.py +++ b/frb/halos/photoz.py @@ -7,6 +7,7 @@ from scipy.interpolate import interp1d, interp2d, RegularGridInterpolator from scipy.sparse import lil_matrix, save_npz +from tqdm import tqdm from frb.halos.models import ModifiedNFW, halomass_from_stellarmass from frb.frb import FRB @@ -19,14 +20,6 @@ from pathos.multiprocessing import ProcessingPool as Pool except ImportError: print("You will need to run 'pip install pathos' to use some functions in this module.") -try: - import progressbar -except ImportError: - print("You will need to run 'pip install progressbar2' to use some functions in this module.") -try: - from threedhst import eazyPy as ez -except ImportError: - print("You will need to run 'pip install threedhst' to read EAZY output.") DEFAULT_DATA_FOLDER = "data" @@ -34,6 +27,8 @@ def get_des_data(coords:SkyCoord, radius:u.Quantity=15.*u.arcmin, starbright:flo starflagval:float=0.9, gaiacat:str=None, write:bool=False, outfile:str=None)->Table: """ Download photometry for galaxies within an FRB field. + + Args: coords (SkyCoord): Coordinates of the center of a cone search. radius (Quantity, optional): Radius of cone search. @@ -50,6 +45,8 @@ def get_des_data(coords:SkyCoord, radius:u.Quantity=15.*u.arcmin, starbright:flo outfile (str, optional): Path to the output file. If not given and write is True, the table will be written to "photom_cat_J{coords}_{radius}arcmin.fits" in the current working directory. + + Returns: des_data (Table): Table of DES galaxies within the search radius. """ @@ -91,6 +88,8 @@ def get_des_data(coords:SkyCoord, radius:u.Quantity=15.*u.arcmin, starbright:flo def _gen_eazy_tab(photom_cat:Table, input_dir:str="eazy_in", name:str="FRB180924", out_dir:str="eazy_out", output_tab:str="no_stars_eazy.fits")->Table: """ Run EAZY on the photometry and produce p(z) estimates. + + Args: photom_cat (Table): Photometry catalog. input_dir (str, optional): Folder where EAZY config files are written. @@ -98,6 +97,8 @@ def _gen_eazy_tab(photom_cat:Table, input_dir:str="eazy_in", name:str="FRB180924 to generate input files. out_dir (str, optional): Folder where EAZY output is stored. output_tab (str, optional): Name of the output summary table fits file. + + Returns: joined_tab (Table): EAZY results table joined (type:inner) with photom_cat based on the id/ID columns. @@ -129,12 +130,16 @@ def _create_cigale_in(photom_cat:Table, zmin:float = 0.01, zmax:float=0.35, n_z: For each galaxy, create multiple entries with different redshifts from 0 to 2. These redshifts will be uniformly spaced. + + Args: photom_cat (Table): Photometry catalog zmin (float, optional): Minimum redshift for analysis. zmax (float, optional): Maximum redshift for analysis. n_z (int, optional): Number of redshift grid points. cigale_input (str, optional): Name of input file to be produced. + + Returns: stacked_photom (Table): A table with multiple groups, one for each galaxy. Each entry in a group has the same photometry but different redshift values. @@ -170,12 +175,16 @@ def _create_cigale_in(photom_cat:Table, zmin:float = 0.01, zmax:float=0.35, n_z: def _gen_cigale_tab(stacked_photom:Table, n_chunks:int=10, n_cores:int=25, outdir:str=DEFAULT_DATA_FOLDER)->Table: """ Run CIGALE and produce a table of results. + + Args: stacked_photom (Table): Table with a group for each galaxy. Output of _create_cigale_in. n_chunks (int, optional): How many chunks do you want to split stacked_photom.groups into? Just so that galaxies are not redone in case of a crash. n_cores (int, optional): Number of CPU threads to be used. outdir (str, optional): Path to the output directory. + + Returns: full_results (Table): CIGALE output with stellar mass and error for all entries in stakced_photom. @@ -212,9 +221,13 @@ def _gen_cigale_tab(stacked_photom:Table, n_chunks:int=10, n_cores:int=25, outdi def _load_cigale_results(cigale_input:str, cigale_output:str)->Table: """ Load the CIGALE stellar mass data. + + Args: cigale_input (str): cigale input file path. cigale_output (str): cigale_output file path. + + Returns: trim_tab (Table): Summary table with CIGALE results. """ @@ -256,15 +269,19 @@ def _sample_eazy_redshifts(gal_ID:int, eazy_outdir:str, ndraws:int = 1000)->np.n """ Returns a sample of redshifts drawn from the EAZY photo-z PDF of galaxy . + + Args: gal_ID(int): ID number of the galaxy in the EAZY table. eazy_outdir(str): Path to the EAZY results folder ndraws(int, optional): Number of redshift samples desired. + + Returns: sample_z (np.ndarray): Redshift sample array of length ndraws. """ # Get posterior - zgrid, pz = ez.getEazyPz(gal_ID-1,OUTPUT_DIRECTORY=eazy_outdir) + zgrid, pz = frb_ez.getEazyPz(gal_ID-1,OUTPUT_DIRECTORY=eazy_outdir) # Force a value of 0 at z = 0 zgrid = np.hstack([[0],zgrid]) pz = np.hstack([[0],pz]) @@ -286,6 +303,8 @@ def _mhalo_lookup_table(z:float, npz_out:str = "m_halo_realizations", n_cores:in For a given z, produce realizations of m_halo for relevant m_star values using only the uncertainty in the SHMR relation. Internal function. Use directly if you know what you're doing. + + Args: z (float): redshift npz_out(str, optional): output .npz file path. @@ -327,6 +346,8 @@ def mhalo_lookup_tables(z_grid:list, datafolder:str=DEFAULT_DATA_FOLDER, n_cores by sampling the Moster+13 SHMR relation. The fits files can then be used to produce interpolation functions of the moments of the m_halo distribution (e.g. mean, std.dev) as a function of redshift and log_mstar. + + Args: z_grid (list or np.ndarray): List of redshift values to be sampled. datafolder (str, optional): Path to the directory where the results will be stored. @@ -347,6 +368,8 @@ def _mhalo_realizations(log_mstar:float, log_mstar_err:float, z:float, Using the lookup tables generated (see function mhalo_lookup_tables), produce realiztions of mhalo. This takes into account both the stellar mass uncertainty and the uncertainty in the SMHR relation from Moster+13. + + Args: log_mstar (float): log stellar mass in M_sun. log_mstar_err (float): log error in log_mstar @@ -357,6 +380,8 @@ def _mhalo_realizations(log_mstar:float, log_mstar_err:float, z:float, n_norm (int, optional): Number of m_halo samples for each m_star sample. max_log_mhalo (float, optional): Maximum allowed log halo mass. log halo masses are capped artificially to this value if any exceed. + + Returns: mhalo_reals (np.ndarray): log_mhalo realizations. """ @@ -385,6 +410,8 @@ def _dm_pdf(cigale_tab:Table, eazy_outdir:str, """ For a given galaxy, compute its PDF of DM from the CIGALE and EAZY inputs. + + Args: cigale_tab (Table): On of the groups from the full cigale result. This @@ -396,6 +423,8 @@ def _dm_pdf(cigale_tab:Table, eazy_outdir:str, ang_dia_interp (interp1d): angular_diameter_distance(z) (default Repo cosmology) dm_interpolator (RegularGridInterpolator): DM(z, offset_kpc, log_mhalo) n_cores (int, optional): Number of CPU threads to use. + + Returns: dm_values (np.ndarray): Array containing DM realizations for the galaxy. z_draws (np.ndarray): Array containing redshift draws from which dm_values were produced. @@ -434,6 +463,8 @@ def dm_grid(frb_z:float, n_z:int = 100, n_o:int = 100, n_m:int =100, max_log_mha Produce DM estimates for a 3D grid of redshift, offsets and log_halo_masses and write them to disk. + + Args: frb_z(float): frb redshift n_z(int, optional): size of the redshift grid. i.e. np.linspace(0, frb_z, n_z) @@ -482,10 +513,14 @@ def _instantiate_intepolators(datafolder:str=DEFAULT_DATA_FOLDER, dmfilename:str Produce interpolator functions for key quantities required for the analysis. + + Args: datfolder(str, optional): Folder where the interpolation data files exist dmfilename(str, optional): file name (within datafolder) for the DM interpolation data. frb_name(str, optional): Assumes "FRB180924" by default. + + Returns: dm_interpolator (RegularGridInterpolator): DM(z, offset_kpc, log_mhalo) mean_interp (interp2d): (based on SHMR) @@ -546,6 +581,8 @@ def dm_for_all_galaxies(frb:FRB, input_catfile:str, datafolder:str, used for the DM realizations and "DM_halos_final.npz" which contains the DM realizations themselves. Each row in each of these files corresponds to one galaxy and each z draw corresponds to 1000 DM realizations for a galaxy. + + Args: frb (FRB): The FRB object of interest. input_catfile (str): Path to the input catalog of photometry. Assumed @@ -589,17 +626,15 @@ def dm_for_all_galaxies(frb:FRB, input_catfile:str, datafolder:str, z_draws = np.zeros((len(eazy_tab),1000), dtype='float32') # Begin calculating - with progressbar.ProgressBar(max_value=len(eazy_tab)-1) as bar: - for idx, ez_entry in enumerate(eazy_tab): - cigale_galaxy = cigale_tab[cigale_tab['gal_ID']==ez_entry['ID']] - if np.any(np.isnan(cigale_galaxy['log_mstar'])): - continue - else: - dm_realizations[idx], z_draws[idx] = _dm_pdf(cigale_galaxy, eazy_outdir, mean_interp, - stddev_interp, ang_dia_interp, dm_interpolator, - n_cores = 20) - - bar.update(idx) + for idx, ez_entry in enumerate(tqdm(eazy_tab, total=len(eazy_tab), desc="Computing halo DMs")): + cigale_galaxy = cigale_tab[cigale_tab['gal_ID']==ez_entry['ID']] + if np.any(np.isnan(cigale_galaxy['log_mstar'])): + continue + else: + dm_realizations[idx], z_draws[idx] = _dm_pdf(cigale_galaxy, eazy_outdir, mean_interp, + stddev_interp, ang_dia_interp, dm_interpolator, + n_cores = 20) + # Save results to file np.savez_compressed(os.path.join(datafolder, "DM_halos_zdraws.npz"), z_draws=z_draws) save_npz(os.path.join(datafolder,"DM_halos_final.npz"), dm_realizations.tocsr()) diff --git a/frb/halos/utils.py b/frb/halos/utils.py index 86578da01..6f8930082 100644 --- a/frb/halos/utils.py +++ b/frb/halos/utils.py @@ -7,11 +7,13 @@ def stellarmass_from_halomass(log_Mhalo, z=0): """ Stellar mass from Halo Mass from Moster+2013 https://doi.org/10.1093/mnras/sts261 + Args: log_Mhalo (float): log_10 halo mass in solar mass units. z (float, optional): halo redshift. Assumed to be 0 by default. + Returns: log_mstar (float): log_10 galaxy stellar mass in solar mass units. @@ -50,11 +52,13 @@ def halomass_from_stellarmass(log_mstar, z=0): Inverts the function `stellarmass_from_halomass` numerically. + Args: log_mstar (float or numpy.ndarray): log_10 stellar mass in solar mass units. z (float, optional): galaxy redshift + Returns: log_Mhalo (float): log_10 halo mass in solar mass units. diff --git a/frb/mw.py b/frb/mw.py index f452a58e8..0096529b7 100644 --- a/frb/mw.py +++ b/frb/mw.py @@ -14,9 +14,13 @@ def ismDM(coord): """ Calculate the dispersion measure (DM) contribution from the interstellar medium (ISM) along a given line of sight in galactic coordinates. + + Parameters: coord (astropy.coordinates.SkyCoord): The input sky coordinate to transform into galactic coordinates. + + Returns: float: The dispersion measure (DM) value calculated for the ISM along the specified line of sight up to a distance of 100 parsecs. @@ -32,7 +36,21 @@ def ismDM(coord): return ismDM def haloDM(coord, f_diffuse=0.75, zero=True): + """ + Uses a Modified NFW profile with parameters from Boylan-Kolchin et al. 2013. + + + Args: + coord (astropy.coordinates.SkyCoord): Sky coordinate for the line of sight. + f_diffuse (float, optional): Fraction of the halo mass in diffuse gas. Default 0.75. + zero (bool, optional): If True, zero out the inner 10 kpc. Default True. + + + + Returns: + float: DM contribution from the MW halo in pc/cm^3. + """ gcoord = coord.transform_to('galactic') l, b = gcoord.l.value, gcoord.b.value diff --git a/frb/optional_requirements.txt b/frb/optional_requirements.txt new file mode 100644 index 000000000..2edbceb28 --- /dev/null +++ b/frb/optional_requirements.txt @@ -0,0 +1,38 @@ +# Optional packages for FRB repo +# DO NOT USE THIS FOR INSTALLATION. THIS IS SUPERSEDED BY A PYPROJECT.TOML FILE WITH A [project.optional-dependencies] SECTION. SEE PYPROJECT.TOML FOR DETAILS. +# These are not required for basic imports but enable specific functionality +# Each optional package enables specific features that warn/fail if missing + +# Spectral analysis and fitting +ppxf # frb.galaxies.ppxf - Message: "ppxf not found. Install it if you want to use it" + +# MCMC analysis +pymc3 # frb.dm.mcmc - Message: "You need to install pymc3 to run mcmc codes" + +# SED fitting +pcigale # frb.galaxies.cigale - Message: "You will need to install pcigale to use the cigale.py module" + +# Parallel processing for photoz +pathos # frb.halos.photoz - Message: "You will need to run 'pip install pathos' to use some functions in this module." + +# Halo mass function emulator +hmf_emulator # frb.halos.hmf - Message: "hmf_emulator not imported. Hope you are not intending to use the hmf.py module.." + +# Pulsar catalog queries +FRB-pulsars # frb.surveys.psrcat - Message: "You need FRB/pulsars installed to use PSRCat" + # Note: This is a custom FRB package, see https://github.com/FRBs/pulsars + +# Spectroscopic database +specdb # frb.scripts.galaxies, frb.builds.build_specdb - Message: "No specdb module found, please install specdb if you wish to build specdb" + +# NOAO DataLab access +astro-datalab # frb.surveys.dlsurvey - Message: "astro-datalab is not installed or will not properly connect" + +# Regions for KCWI analysis +pyregion # frb.analysis.kcwi - Message: "pyregion not found. Run `pip install pyregion`." + +# Spectral-cube analysis for KCWI +spectral-cube # frb.analysis.kcwi - Message: "spectral-cube not found. Run `pip install spectral-cube`." + +# Removed from requirements (no longer needed) +# seaborn diff --git a/frb/requirements.txt b/frb/requirements.txt index 1fec270f5..2b5ddd812 100644 --- a/frb/requirements.txt +++ b/frb/requirements.txt @@ -1,5 +1,7 @@ # Required packages for testing FRB repo (not all tests, though) +# CAUTION: THIS IS NOW DEPRECATED AND SHOULD NOT BE USED FOR INSTALLATION. THIS IS SUPERSEDED BY A PYPROJECT.TOML FILE WITH A [project.dependencies] SECTION. SEE PYPROJECT.TOML FOR DETAILS. + # Users numpy>=2.2.0 scipy>=1.17 @@ -20,4 +22,7 @@ setuptools>=75.0.0 tox>=4.15.0 pyvo>=1.5.3 importlib-resources>=6.4.0 -astroquery>=0.4.11 \ No newline at end of file +astroquery>=0.4.11 +tqdm>=4.0.0 +ne2001 @ git+https://github.com/FRBs/ne2001.git +astropath @ git+https://github.com/FRBs/astropath.git \ No newline at end of file diff --git a/frb/rm.py b/frb/rm.py index 0114258cf..45960d775 100644 --- a/frb/rm.py +++ b/frb/rm.py @@ -37,6 +37,7 @@ def load_hutschenreuter2020(): See: https://ui.adsabs.harvard.edu/abs/2022A%26A...657A..43H/abstract for full details + Returns: healpy map, healpy map: RM and RM_err with units of rad/m^2 @@ -70,6 +71,7 @@ def galactic_rm(coord, use_map=2020): Specifies the map to use. Options are [2014, 2020] Default is 2020 + Returns: Quantity, Quantity: RM and RM_err with units of rad/m^2 diff --git a/frb/scripts/SN-FRB/transient_crossmatching.py b/frb/scripts/SN-FRB/transient_crossmatching.py index 06f542422..ceedd63e2 100644 --- a/frb/scripts/SN-FRB/transient_crossmatching.py +++ b/frb/scripts/SN-FRB/transient_crossmatching.py @@ -52,6 +52,7 @@ def check_tns_api_keywords(): 'TNS_BOT_ID', 'TNS_BOT_NAME', and 'TNS_API_KEY'. If any of these keys are missing, an exception is raised. + Raises: ------- Exception: @@ -69,6 +70,7 @@ def set_bot_tns_marker(): The bot marker is a JSON-formatted string containing the bot's ID and name, which is used for API authentication when querying the TNS database. + Returns: -------- tns_marker (str): @@ -86,12 +88,14 @@ def search(json_list, url_tns_api): """ Querie TNS for transients based on the provided search parameters. + Parameters: ----------- json_list (list): A list of key-value pairs specifying the search parameters, which will be converted into an OrderedDict. url_tns_api (str): The base URL for the TNS API. + Returns: -------- response (requests.Response): @@ -123,10 +127,12 @@ def format_to_json(source): """ Converts a JSON-formatted string into an OrderedDict. + Parameters: ----------- source (str): A JSON-formatted string to be converted into an OrderedDict. + Returns: -------- OrderedDict: A dictionary-like object with preserved key order, parsed from the input JSON string. @@ -141,12 +147,14 @@ def tns_query(ra, dec, radius, frb_name, units='arcmin', initial_delay=10, max_d ''' Queries transients in TNS at the FRB position with a specfied radius. + Parameters: ----------- ra (float): right ascension of the FRB in deg dec (float): declination of the FRB in deg radius (float): search radius in arcmin frb_name (str): TNS name of the FRB + Returns: -------- @@ -240,6 +248,7 @@ def main(filename, name, ra, dec, theta, a, b, radius, single_obj=False): """ Main function to query the TNS for transient data; can be batched or a single object search. + Parameters: filename: The path to the ASCII file containing the catalog data (only used if single_obj is False). name (str): FRB name (only used if single_obj is True). @@ -251,6 +260,7 @@ def main(filename, name, ra, dec, theta, a, b, radius, single_obj=False): radius: The search radius (arcmin). single_obj: Boolean indicating whether to perform a query for a single object (True) or multiple (False). + Returns: trans_results: dictionary trans_metadata: dictionary diff --git a/frb/scripts/SN-FRB/utils_crossmatching.py b/frb/scripts/SN-FRB/utils_crossmatching.py index 9cadbcc1a..bedcfea69 100644 --- a/frb/scripts/SN-FRB/utils_crossmatching.py +++ b/frb/scripts/SN-FRB/utils_crossmatching.py @@ -13,11 +13,13 @@ def cov_matrix(a, b, theta): """ Calculate the covariance matrix for a 2D ellipse. + Parameters: a (float): Semi-major axis of the ellipse b (float): Semi-minor axis of the ellipse theta (float): Position angle of the ellipse in degrees + Returns: np.ndarray: 2x2 covariance matrix @@ -40,11 +42,13 @@ def mahalanobis_distance(point, frbcenter, cov_matrix): Calculate the Mahalanobis distance between a given point and the center. effectively the Z-score in 1D, and it can be a proxy for how many sigma away you are from the mean. + Parameters: point (array-like): The point for which to calculate the distance (should be [RA, Dec]). frbcenter (array-like): The center point, usually the mean [RA, Dec]. cov_matrix (array-like): The covariance matrix of the data. + Returns: float: The Mahalanobis distance. """ @@ -76,6 +80,7 @@ def gauss_contour(frbcenter, cov_matrix, semi_major, transient_name, that represent the uncertainty in the position of the FRB as defined by its covariance matrix. Then, it plots the position of the transient along with the Mahalanobis distance from the FRB center. + Parameters: frbcenter (Astropy SkyCoord): The central position of the FRB. diff --git a/frb/scripts/build.py b/frb/scripts/build.py index 14ad0ba75..e0a4db67c 100644 --- a/frb/scripts/build.py +++ b/frb/scripts/build.py @@ -70,3 +70,6 @@ def main(pargs): raise IOError("Bad build item {:s}".format(item)) +def cli(): + main(parser()) + diff --git a/frb/scripts/frb_summary.py b/frb/scripts/frb_summary.py index 85f811dff..5d3c947e2 100644 --- a/frb/scripts/frb_summary.py +++ b/frb/scripts/frb_summary.py @@ -73,3 +73,5 @@ def pjson(obj): print('neb_lines: \n {}'.format(pjson(hg.neb_lines))) +def cli(): + main(parser()) diff --git a/frb/scripts/galaxies.py b/frb/scripts/galaxies.py index 1d867eca5..0de12c8ac 100644 --- a/frb/scripts/galaxies.py +++ b/frb/scripts/galaxies.py @@ -141,3 +141,6 @@ def main(pargs): plot_spec(specDB, meta, ifrb, dust_correct=pargs.dust) +def cli(): + main(parser()) + diff --git a/frb/scripts/image.py b/frb/scripts/image.py index 132f76440..444e7f0f0 100644 --- a/frb/scripts/image.py +++ b/frb/scripts/image.py @@ -63,3 +63,8 @@ def main(pargs): plt.savefig(pargs.outfile, dpi=300) plt.close() print('Wrote {:s}'.format(pargs.outfile)) + + +def cli(): + main(parser()) + diff --git a/frb/scripts/iteration.py b/frb/scripts/iteration.py index cd01dce72..c3304122a 100644 --- a/frb/scripts/iteration.py +++ b/frb/scripts/iteration.py @@ -167,20 +167,16 @@ def maximise_likelihood(grid,survey): def calc_likelihoods_1D(grid,survey,doplot=False,norm=True,psnr=False,Pn=True,dolist=0): - """ Calculates 1D likelihoods using only observedDM values - Here, Zfrbs is a dummy variable allowing it to be treated like a 2D function - for purposes of calling. - - Norm simply means to normalise likelihoods so that the total comes to unity. - - Note that the *sum* comes to unity, since each bin in rates is already - normalised by the volume in the dz bin - - dolist - 2: llsum,lllist [Pzdm,Pn,Ps],expected,longlist - longlist holds the LL for each FRB - 5: llsum,lllist,expected,[0.,0.,0.,0.] - - Pn: Calculate the probability of observing N bursts (Poisson) + """Calculate 1D likelihoods using only observed DM values. + + Parameters + ---------- + grid, survey + zdm grid and survey objects. + doplot, norm, psnr, Pn : bool, optional + Control plotting and likelihood terms. + dolist : int, optional + Output format selector. """ rates=grid.rates dmvals=grid.dmvals @@ -411,42 +407,16 @@ def calc_likelihoods_2D(grid,survey, doplot=False,norm=True,psnr=True, printit=False,Pn=True,dolist=0, verbose=False): - """ Calculates 2D likelihoods using observed DM,z values - - grid: the grid object calculated from survey - - survey: survey object containing the observed z,DM values - - doplot: will generate a plot of z,DM values - - Pn: - True: calculate probability of observing N FRBs - False: do not calculate this - - psnr: calculate the probability of the given snr values - - dolist: - 0: returns total log10 likelihood llsum only [float] - 1: returns llsum, log10([Pzdm,Pn,Ps]), - 2: as above, plus a 'long list' giving log10(likelihood) - for each FRB individually - 3: return (llsum, -np.log10(norm)*Zobs.size, - np.sum(np.log10(pvals)), np.sum(np.log10(wzpsnr))) - 4: return (llsum, -np.log10(norm)*Zobs.size, - np.sum(np.log10(pvals)), - pvals.copy(), wzpsnr.copy()) - 5: returns llsum, log10([Pzdm,Pn,Ps]), , - np.log10([p(z|DM), p(DM), p(DM|z), p(z)]) - else: returns nothing (actually quite useful behaviour!) - - norm: - True: calculates p(z,DM | FRB detected) - False: calculates p(detecting an FRB with z,DM). Meaningless unless - some sensible normalisation has already been applied to the grid. - - zdm_components - False: nothing - True: Also returns p(z|DM), p(DM), p(DM|z), and p(z) + """Calculate 2D likelihoods using observed DM and z values. + + Parameters + ---------- + grid, survey + zdm grid and survey objects. + doplot, norm, psnr, printit, Pn, verbose : bool, optional + Control calculation and diagnostics. + dolist : int, optional + Output format selector. """ ######## Calculates p(DM,z | FRB) ######## @@ -824,6 +794,8 @@ def cube_likelihoods(grids:list,surveys:list, psnr=True,starti=0,clone=None): """ + + Args: grids: list of grids surveys: list of surveys corresponding to the grids @@ -1046,6 +1018,8 @@ def my_minimise(vparams:dict,grids,surveys,steps=None, PenTypes=None,PenParams=None): """Minimise on the not disabled parameters + + Args: vparams (dict): [description] grids ([type]): [description] @@ -1059,9 +1033,13 @@ def my_minimise(vparams:dict,grids,surveys,steps=None, PenTypes ([type], optional): [description]. Defaults to None. PenParams ([type], optional): [description]. Defaults to None. + + Raises: ValueError: [description] + + Returns: float: log-likelihood value """ @@ -1713,15 +1691,10 @@ def Poisson_p(observed, expected): return p def CalculateConstant(grid,survey): - """ Calculates the best-fitting constant for the total - number of FRBs. Units are: - - grid volume units of 'per Mpc^3', - - survey TOBS of 'days', - - beam units of 'steradians' - - flux for FRBs with E > Emin - Hence the constant is 'Rate (FRB > Emin) Mpc^-3 day^-1 sr^-1' - This should be scaled to be above some sensible value of Emin - or otherwise made relevant. + """Calculate best-fit normalization constant for total FRB counts. + + Returns rate normalization in units of + ``Mpc^-3 day^-1 sr^-1`` for FRBs above ``Emin``. """ expected=CalculateIntegral(grid,survey) @@ -1774,6 +1747,8 @@ def minimise_const_only(vparams:dict,grids:list,surveys:list, It treats the rest as constants the grids must be initialised at the currect values for pset already + + Args: vparams (dict): Parameter dict. Can be None if nothing has varied. grids (list): List of grids @@ -1784,10 +1759,14 @@ def minimise_const_only(vparams:dict,grids:list,surveys:list, If True, make use of the previous grid when looping over them. Defaults to True. + + Raises: ValueError: [description] ValueError: [description] + + Returns: tuple: newC,llC,lltot """ @@ -1854,6 +1833,8 @@ def set_orders(parameter_order:list, PARAMS:list): Set the order of the parameters based on the input parameter_order list + + Args: parameter_order (list): Order in which to run the cube on the parameters. @@ -1863,6 +1844,8 @@ def set_orders(parameter_order:list, PARAMS:list): Raises: ValueError: [description] + + Returns: tuple: list, np.ndarray -- indices of the PARAMS in the order to run them, inverse of that """ @@ -1885,10 +1868,14 @@ def set_cube_shape(vparam_dict:dict, order:list): """ Generate a list holding the dimensions of the cube in the order it was generated + + Args: vparam_dict (dict): parameter dict order (list): order list (integers) + + Returns: list: List of the dimensions of the cube """ @@ -1908,9 +1895,13 @@ def parse_input_dict(input_dict:dict): """ Method to parse the input dict for generating a cube It is split up into its various pieces + + Args: input_dict (dict): [description] + + Returns: tuple: dicts (can be empty): state, cube, input """ diff --git a/frb/scripts/pzdm_mag.py b/frb/scripts/pzdm_mag.py index 758981abe..50bd3c58b 100644 --- a/frb/scripts/pzdm_mag.py +++ b/frb/scripts/pzdm_mag.py @@ -159,3 +159,8 @@ def main(pargs): return z_min, z_max, z_50, z_mode, frac_Lstar_min, frac_Lstar_max + +def cli(): + main(parser()) + + diff --git a/frb/scripts/random_assoc.py b/frb/scripts/random_assoc.py index 85c5f4ebb..16c99f3eb 100755 --- a/frb/scripts/random_assoc.py +++ b/frb/scripts/random_assoc.py @@ -6,19 +6,20 @@ from frb.surveys import des -import progressbar as pb #pip install progressbar2 +from tqdm import tqdm from matplotlib import pyplot as plt -import seaborn as sns def get_catalog(coords,size=1*u.deg): """ Download a catalog objects within a square of input `size` centered around `coords`. + Args: coords (astropy SkyCoord): central coordinates size (astropy Angle, optional): Size of the square FoV around the central coordinates + Returns: catalog (astropy Table): DES DR1 search results """ @@ -36,10 +37,12 @@ def _generate_coord_grid(coords,size=1*u.deg,resolution=3600): an area `size`x`size` with a default `resolution` of 1000 points along each axis. + Args: coords (astropy SkyCoord): central coordinates size (astropy Angle, optional): Size of the square FoV around + Returns: SkyCoord: """ @@ -79,12 +82,9 @@ def random_sightlines(n=100,resolution=3600,sep=1*u.arcsec,size=1*u.deg, dec = -60 + np.random.rand(n)*30 #limit DEC to [-60deg,-30deg] rand_coords = SkyCoord(ra,dec,unit="deg") fracs = np.zeros(n) - bar = pb.ProgressBar(max_value=n) - bar.start() - for num,coords in enumerate(rand_coords): + for num,coords in tqdm(enumerate(rand_coords), total=n, desc="Querying DES patches"): catalog = get_catalog(coords,size) fracs[num] = get_frac_within_sep(coords,catalog,sep=sep,resolution=resolution,band=band,crit_mag=crit_mag) - bar.update(num+1) #Save to file np.savetxt(outfile,fracs) return fracs @@ -92,8 +92,9 @@ def plot_hist(fracs,bins=5): """ Plot a histogram of fractions obtained from `random_sightlines` """ - sns.set(font_scale=1.3,font="serif",style="ticks") - sns.axes_style(rc={"weight":"bold"}) + plt.rcParams['font.size'] = 13 + plt.rcParams['font.family'] = 'serif' + plt.rcParams['font.weight'] = 'bold' fig,ax = plt.subplots(nrows=1,ncols=1,figsize=(10,8)) ax.set_xlabel("Percentage of sightlines within 1'' of a galaxy (r<22)",labelpad=20,weight="bold") ax.set_ylabel("Number of DES patches (1 sq. deg)",labelpad=20,weight="bold") @@ -107,13 +108,13 @@ def plot_hist(fracs,bins=5): """ -If you're running this for the first time or you -want to regenerate the database, uncomment the following line -and run. +If you're running this for the first time or you +want to regenerate the database, run this module as a script. """ -#fracs = random_sightlines(n=100) - -fracs = np.loadtxt("random_sights.txt") -plot_hist(fracs,bins=9) +if __name__ == '__main__': + # Uncomment to regenerate the database. + # fracs = random_sightlines(n=100) + fracs = np.loadtxt('random_sights.txt') + plot_hist(fracs, bins=9) diff --git a/frb/scripts/search_for_halos.py b/frb/scripts/search_for_halos.py index 74c8a8d2f..056d85535 100644 --- a/frb/scripts/search_for_halos.py +++ b/frb/scripts/search_for_halos.py @@ -32,17 +32,26 @@ def parser(options=None): def halo_dm(z, offset, log_mhalo, rmax=1, fhot=1, is_grp=False): """ Calculate the dispersion measure (DM) contribution from a halo. - Parameters: - z (float): Redshift of the halo. - offset (float): Offset distance from the center of the halo in kpc. - log_mhalo (float): Logarithm of the halo mass. - rmax (float, optional): Maximum radius to consider for the halo model. Default is 1. - fhot (float, optional): Fraction of hot gas in the halo. Default is 1. - is_grp (bool, optional): Flag indicating if the halo is a group or cluster. Default is False. - Returns: - tuple: A tuple containing: - - dm_halo (float): Dispersion measure contribution from the halo in pc/cm^3. - - rvir (Quantity): Virial radius of the halo in kpc. + + Parameters + ---------- + z : float + Halo redshift. + offset : float + Impact parameter in kpc. + log_mhalo : float + Log10 halo mass. + rmax : float, optional + Halo extent in units of virial radius. + fhot : float, optional + Fraction of halo gas in hot phase. + is_grp : bool, optional + Treat as group/cluster halo when True. + + Returns + ------- + tuple + ``(dm_halo, rvir)`` where `dm_halo` is in pc/cm^3. """ if log_mhalo<14: # Low mass halos if offset>1300*u.kpc: # Don't bother instantiating the model if the distance is too far @@ -62,6 +71,8 @@ def lvs_avg_dm_halos(frb_name, frb_coord, frb_z, nedlvs_tab, tully_clusters, rma """ Estimate the contribution of the local volume halos available within the NEDLVS catalog. Produces estimates where masses are available. + + Args: frb_name (str): Name of the Fast Radio Burst (FRB). frb_coord (SkyCoord): Coordinate of the FRB. @@ -69,6 +80,8 @@ def lvs_avg_dm_halos(frb_name, frb_coord, frb_z, nedlvs_tab, tully_clusters, rma nedlvs_tab (Table): NED Local Volume Sample (NEDLVS) catalog table. tully_clusters (Table): Tully clusters catalog table. rmax (float, optional): Maximum radius for halo DM calculation. Default is 1. + + Returns: mean_dm_halos_lvs (float): Mean dispersion measure (DM) of local volume halos. mean_dm_halos_lvs_phot (float): Mean DM of local volume halos with only photometric redshifts. @@ -208,4 +221,7 @@ def main(pargs): close_by_withmass.write(f"{frb_name}_nedvls_with_mass.fits", overwrite=True) if len(match_grps)>0: match_grps.write(f"{frb_name}_tully_grps_ICM_fgonly.fits", overwrite=True) - \ No newline at end of file + + +def cli(): + main(parser()) diff --git a/frb/scripts/sightline.py b/frb/scripts/sightline.py index fd3ad2245..e646425a4 100644 --- a/frb/scripts/sightline.py +++ b/frb/scripts/sightline.py @@ -50,4 +50,8 @@ def main(pargs): # Surveys print("Checking the imaging surveys...") inside = survey_utils.in_which_survey(icoord, optical_only=True) - print(inside) \ No newline at end of file + print(inside) + + +def cli(): + main(parser()) diff --git a/frb/scripts/tns.py b/frb/scripts/tns.py index 067197f8f..d8efdb762 100644 --- a/frb/scripts/tns.py +++ b/frb/scripts/tns.py @@ -49,6 +49,7 @@ def check_tns_api_keywords(): 'TNS_BOT_ID', 'TNS_BOT_NAME', and 'TNS_API_KEY'. If any of these keys are missing, an exception is raised. + Raises: ------- Exception: @@ -66,6 +67,7 @@ def set_bot_tns_marker(): The bot marker is a JSON-formatted string containing the bot's ID and name, which is used for API authentication when querying the TNS database. + Returns: -------- tns_marker (str): @@ -82,13 +84,16 @@ def search(json_list, url_tns_api): """ Querie TNS for transients based on the provided search parameters. - Parameters: + + Parameters: ----------- json_list (list): A list of key-value pairs specifying the search parameters, which will be converted into an OrderedDict. url_tns_api (str): The base URL for the TNS API. - Returns: + + + Returns: -------- response (requests.Response): The HTTP response object returned by the TNS API, containing the status code and response data. @@ -116,10 +121,12 @@ def format_to_json(source): """ Converts a JSON-formatted string into an OrderedDict. + Parameters: ----------- source (str): A JSON-formatted string to be converted into an OrderedDict. + Returns: -------- OrderedDict: A dictionary-like object with preserved key order, parsed from the input JSON string. @@ -134,6 +141,7 @@ def tns_query(ra, dec, radius, frb_name, units='arcmin', initial_delay=10, max_d ''' Queries transients in TNS at the FRB position with a specfied radius. +<<<<<<< Updated upstream Parameters: ----------- ra (float): right ascension of the FRB in deg @@ -142,6 +150,22 @@ def tns_query(ra, dec, radius, frb_name, units='arcmin', initial_delay=10, max_d frb_name (str): TNS name of the FRB Returns: +======= + + Parameters: + ----------- + ra (float): Right ascension of the FRB in degrees. + dec (float): Declination of the FRB in degrees. + radius (float): Search radius in arcmin. + frb_name (str): TNS name of the FRB. + units (str, optional): Units for radius (default: 'arcmin'). + initial_delay (int, optional): Initial delay for retries in seconds (default: 10). + max_delay (int, optional): Maximum delay for retries in seconds (default: 500). + outfile (str, optional): Output file for query results (default: 'query_results_final.txt'). + + + Returns: +>>>>>>> Stashed changes -------- query output: dict a dictionary of transients found within the search radius near an FRB position @@ -225,6 +249,7 @@ def main(filename, name, ra, dec, theta, a, b, radius, single_obj=False): """ Main function to query the TNS for transient data; can be batched or a single object search. + Parameters: filename: The path to the ASCII file containing the catalog data (only used if single_obj is False). name (str): FRB name (only used if single_obj is True). @@ -236,6 +261,7 @@ def main(filename, name, ra, dec, theta, a, b, radius, single_obj=False): radius: The search radius (arcmin). single_obj: Boolean indicating whether to perform a query for a single object (True) or multiple (False). + Returns: trans_results: dictionary trans_metadata: dictionary @@ -308,8 +334,7 @@ def main(filename, name, ra, dec, theta, a, b, radius, single_obj=False): return(trans_metadata) -if __name__ == "__main__": - # Verify that you've added these to your env var +def cli(): args = parser() check_tns_api_keywords() if args.single: @@ -317,14 +342,18 @@ def main(filename, name, ra, dec, theta, a, b, radius, single_obj=False): print("Error: Missing parameters for single object query.") exit(1) matched_transient_data = main(filename=None, - name=args.name, - ra=args.ra, + name=args.name, + ra=args.ra, dec=args.dec, - theta=args.theta, - a=args.a, b=args.b, radius=args.radius, single_obj=True) # in degrees + theta=args.theta, + a=args.a, b=args.b, radius=args.radius, single_obj=True) save_matches(matched_transient_data, args.outfile) else: - frb_file = args.filename #sys.argv[1] + frb_file = args.filename matched_transient_data = main(frb_file, name=None, ra=None, dec=None, theta=None, a=None, b=None, radius=args.radius, single_obj=False) save_matches(matched_transient_data, args.outfile) + + +if __name__ == "__main__": + cli() diff --git a/frb/surveys/catalog_utils.py b/frb/surveys/catalog_utils.py index 45adf81e4..e4acc9161 100644 --- a/frb/surveys/catalog_utils.py +++ b/frb/surveys/catalog_utils.py @@ -168,7 +168,9 @@ def xmatch_catalogs(cat1:Table, cat2:Table, dist:units.Quantity = 5*units.arcsec """ Cross matches two astronomical catalogs and returns the matched tables. - Args: + + Parameters + ---------- cat1, cat2: astropy Tables Two tables with sky coordinates to be matched. @@ -190,7 +192,9 @@ def xmatch_catalogs(cat1:Table, cat2:Table, dist:units.Quantity = 5*units.arcsec return_match_idx: bool, optional Return the indices of the matched entries with with the distance instead? - returns: + + Returns + ------- match1, match2: astropy Table Tables of matched rows from cat1 and cat2. idx, d2d (if return_match_idx): ndarrays @@ -416,14 +420,18 @@ def xmatch_and_merge_cats(tab1:Table, tab2:Table, tol:units.Quantity=1*units.arc ensures there is a unique match between tables as opposed to the default join_skycoord behavior which matches multiple objects on the right table to a source on the left. The two tables must contain the columns 'ra' and 'dec' (case-sensitive). - Args: + + Parameters + ---------- tab1, tab2 (Table): Photometry catalogs. Must contain columns named ra and dec. tol (Quantity[Angle], optional): Maximum separation for cross-matching. table_names (tuple of str, optional): Names of the two tables for naming unique columns in the merged table. kwargs: Additional keyword arguments to be passed onto xmatch_catalogs - Returns: + + Returns + ------- merged_table (Table): Merged catalog. """ if table_names is not None: diff --git a/frb/surveys/cluster_search.py b/frb/surveys/cluster_search.py index 2402ac1f3..1a74ce0bd 100644 --- a/frb/surveys/cluster_search.py +++ b/frb/surveys/cluster_search.py @@ -51,11 +51,13 @@ def _transverse_distance_cut(self, catalog, transverse_distance_cut, distance_co def _get_catalog(self, query_fields=None, **kwargs): """ Get the catalog of objects + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. transverse_distance_cut (Quantity): The maximum impact parameter of the objects to include in the catalog. richness_cut (int): The minimum number of members in any group/cluster returned. query_fields (list): The fields to include in the catalog. If None, all fields are used. + Returns: A table of objects within the given limits. If no objects found, returns an empty table with fields ['ra','dec', and 'z']. @@ -105,11 +107,13 @@ def get_catalog(self, query_fields=None, transverse_distance_cut = np.inf*u.Mpc, richness_cut = 5): """ Get the catalog of objects + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. transverse_distance_cut (Quantity): The maximum impact parameter of the objects to include in the catalog. richness_cut (int): The minimum number of members in any group/cluster returned. query_fields (list): The fields to include in the catalog. If None, all fields are used. + Returns: A table of objects within the given limits. """ @@ -164,11 +168,13 @@ def get_catalog(self, query_fields=None, transverse_distance_cut = np.inf*u.Mpc, richness_cut = 5): """ Get the catalog of objects + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. transverse_distance_cut (Quantity): The maximum impact parameter of the objects to include in the catalog. richness_cut (int): The minimum number of members in any group/cluster returned. query_fields (list): The fields to include in the catalog. If None, all fields are used. + Returns: A table of objects within the given limits. """ @@ -216,11 +222,13 @@ def get_catalog(self, query_fields=None, transverse_distance_cut = np.inf*u.Mpc): """ Get the catalog of objects + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. transverse_distance_cut (Quantity): The maximum impact parameter of the objects to include in the catalog. richness_cut (int): The minimum number of members in any group/cluster returned. query_fields (list): The fields to include in the catalog. If None, all fields are used. + Returns: A table of objects within the given limits. """ @@ -263,11 +271,13 @@ def get_catalog(self, query_fields=None, transverse_distance_cut = np.inf*u.Mpc): """ Get the catalog of objects + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. transverse_distance_cut (Quantity): The maximum impact parameter of the objects to include in the catalog. richness_cut (int): The minimum number of members in any group/cluster returned. query_fields (list): The fields to include in the catalog. If None, all fields are used. + Returns: A table of objects within the given limits. """ @@ -310,11 +320,13 @@ def get_catalog(self, query_fields=None, transverse_distance_cut = np.inf*u.Mpc): """ Get the catalog of objects + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. transverse_distance_cut (Quantity): The maximum impact parameter of the objects to include in the catalog. richness_cut (int): The minimum number of members in any group/cluster returned. query_fields (list): The fields to include in the catalog. If None, all fields are used. + Returns: A table of objects within the given limits. """ @@ -358,11 +370,13 @@ def get_catalog(self, query_fields=None, transverse_distance_cut = np.inf*u.Mpc): """ Get the catalog of objects + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. transverse_distance_cut (Quantity): The maximum impact parameter of the objects to include in the catalog. richness_cut (int): The minimum number of members in any group/cluster returned. query_fields (list): The fields to include in the catalog. If None, all fields are used. + Returns: A table of objects within the given limits. """ @@ -408,11 +422,13 @@ def get_catalog(self, query_fields=None, transverse_distance_cut = np.inf*u.Mpc): """ Get the catalog of objects + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. transverse_distance_cut (Quantity): The maximum impact parameter of the objects to include in the catalog. richness_cut (int): The minimum number of members in any group/cluster returned. query_fields (list): The fields to include in the catalog. If None, all fields are used. + Returns: A table of objects within the given limits. """ @@ -457,11 +473,13 @@ def get_catalog(self, query_fields=None, transverse_distance_cut = np.inf*u.Mpc): """ Get the catalog of objects + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. transverse_distance_cut (Quantity): The maximum impact parameter of the objects to include in the catalog. richness_cut (int): The minimum number of members in any group/cluster returned. query_fields (list): The fields to include in the catalog. If None, all fields are used. + Returns: A table of objects within the given limits. """ @@ -506,11 +524,13 @@ def get_catalog(self, query_fields=None, transverse_distance_cut = np.inf*u.Mpc): """ Get the catalog of objects + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. transverse_distance_cut (Quantity): The maximum impact parameter of the objects to include in the catalog. richness_cut (int): The minimum number of members in any group/cluster returned. query_fields (list): The fields to include in the catalog. If None, all fields are used. + Returns: A table of objects within the given limits. """ diff --git a/frb/surveys/decals.py b/frb/surveys/decals.py index d7c162061..8b452b0e5 100644 --- a/frb/surveys/decals.py +++ b/frb/surveys/decals.py @@ -38,6 +38,7 @@ class DECaL_Survey(dlsurvey.DL_Survey): Class to handle queries on the DECaL survey Child of DL_Survey which uses datalab to access NOAO + Args: coord (SkyCoord): Coordinate for surveying around @@ -57,6 +58,7 @@ def __init__(self, coord, radius, **kwargs): def get_catalog(self, query=None, query_fields=None, print_query=False,exclude_stars=False,**kwargs): """ Grab a catalog of sources around the input coordinate to the search radius + Args: query: SQL query @@ -120,6 +122,7 @@ def _parse_cat_band(self, band): """ Internal method to generate the bands for grabbing a cutout image + Args: band (str): Band desired diff --git a/frb/surveys/delve.py b/frb/surveys/delve.py index eb1a953c2..e371a5f16 100644 --- a/frb/surveys/delve.py +++ b/frb/surveys/delve.py @@ -36,6 +36,7 @@ class DELVE_Survey(dlsurvey.DL_Survey): Child of DL_Survey which uses datalab to access NOAO + Args: coord (SkyCoord): Coordiante for surveying around radius (Angle): Search radius around the coordinate @@ -55,11 +56,13 @@ def get_catalog(self, query=None, query_fields=None, print_query=False,**kwargs) """ Grab a catalog of sources around the input coordinate to the search radius + Args: query: Not used query_fields (list, optional): Over-ride list of items to query print_query (bool): Print the SQL query generated + Returns: astropy.table.Table: Catalog of sources returned. Includes WISE photometry for matched sources. diff --git a/frb/surveys/des.py b/frb/surveys/des.py index 3271dbfad..9b47edcc9 100644 --- a/frb/surveys/des.py +++ b/frb/surveys/des.py @@ -34,6 +34,7 @@ class DES_Survey(dlsurvey.DL_Survey): Child of DL_Survey which uses datalab to access NOAO + Args: coord (SkyCoord): Coordiante for surveying around radius (Angle): Search radius around the coordinate @@ -54,6 +55,7 @@ def get_catalog(self, query=None, query_fields=None, """ Grab a catalog of sources around the input coordinate to the search radius + Args: query: Not used query_fields (list, optional): Over-ride list of items to query @@ -61,6 +63,7 @@ def get_catalog(self, query=None, query_fields=None, grab_wise (bool): Attempt to grab WISE data too. This is not recommended. + Returns: astropy.table.Table: Catalog of sources returned. Includes WISE photometry for matched sources. diff --git a/frb/surveys/desi.py b/frb/surveys/desi.py index bdf84d45c..4107d4b98 100644 --- a/frb/surveys/desi.py +++ b/frb/surveys/desi.py @@ -29,6 +29,7 @@ class DESI_Survey(dlsurvey.DL_Survey): Class to handle queries on the DESI survey Child of DL_Survey which uses datalab to access NOAO + Args: coord (SkyCoord): Coordinate for surveying around @@ -47,6 +48,7 @@ def get_catalog(self, query=None, query_fields=None, print_query=False, exclude_stars=False, zcat_primary_only=True,**kwargs): """ Grab a catalog of sources around the input coordinate to the search radius + Args: query: SQL query @@ -56,6 +58,7 @@ def get_catalog(self, query=None, query_fields=None, print_query=False, print_query (bool): Print the SQL query generated zcat_primary_only (bool): If True, only return objects with zcat_primary=True + Returns: astropy.table.Table: Catalog of sources returned Can be empty diff --git a/frb/surveys/dlsurvey.py b/frb/surveys/dlsurvey.py index f415d135a..05ca878c5 100644 --- a/frb/surveys/dlsurvey.py +++ b/frb/surveys/dlsurvey.py @@ -1,6 +1,6 @@ """ DataLab survey class. Gets data from any survey -available through the NOAO datalab-client. +available through astro-datalab. Inherits from SurveyCoord. See surveycoord.py for more details on the parent class. """ import numpy as np import warnings @@ -14,7 +14,7 @@ from dl import queryClient as qc, authClient as ac from dl.helpers.utils import convert except: - print("Warning: datalab-client is not installed or will not properly connect") + print("Warning: astro-datalab is not installed or will not properly connect") try: @@ -54,6 +54,7 @@ def _parse_cat_band(self,band): Args: band (str): Band desired + Returns: list, list, str: Table columns, Column values, band string for cutout @@ -69,6 +70,7 @@ def _gen_cat_query(self,query_fields=None, qtype='main', ra_col=None, dec_col=No self.query is modified in place + Args: query_fields (list): Override the default list for the SQL query qtype (str): Type of query to generate. Currently only 'main' is supported @@ -102,11 +104,13 @@ def _select_best_img(self,imgTable,verbose,timeout=120): """ Select the best band for a cutout + Args: imgTable: Table of images verbose (bool): Print status timeout (int or float): How long to wait before timing out, in seconds + Returns: HDU: header data unit for the downloaded image @@ -124,6 +128,7 @@ def get_catalog(self, query=None, query_fields=None, print_query=False,timeout=1 """ Get catalog sources around the given coordinates within self.radius. + Args: query (str, optional): SQL query to generate the catalog @@ -159,12 +164,14 @@ def get_image(self, imsize, band, timeout=120, verbose=False): Get images from the catalog if available for a given fov and band. + Args: imsize (Quantity): FOV for the desired image band (str): Band for the image (e.g. 'r') timeout (int, optional): Time to wait in seconds before timing out verbose (bool, optional): + Returns: HDU: Image header data unit @@ -209,10 +216,12 @@ def get_cutout(self, imsize, band=None): """ Get cutout (and header) + Args: imsize (Quantity): e.g 10*units.arcsec band (str): e.g. 'r' + Returns: ndarray, Header: cutout image, cutout image header @@ -239,6 +248,7 @@ def get_cutout(self, imsize, band=None): def _default_query_str(query_fields, database, coord, radius, ra_col=None, dec_col=None): """ Generates default query string for a catalog search. + Args: query_fields (list of str): A list of query fields to @@ -248,6 +258,7 @@ def _default_query_str(query_fields, database, coord, radius, ra_col=None, dec_c radius (astropy.units.Quantity or Angle): Search radius ra_col, dec_col (str, optional): Name of the RA and Dec columns in the database If None, defaults to 'ra' and 'dec' + Returns: str: A query to be fed to datalab's SQL client diff --git a/frb/surveys/galex.py b/frb/surveys/galex.py index 72e262a2c..f755a885c 100644 --- a/frb/surveys/galex.py +++ b/frb/surveys/galex.py @@ -45,11 +45,13 @@ def get_catalog(self,query_fields=None, print_query=False): Query a catalog in the MAST GALEX database for photometry. + Args: query_fields: list, optional A list of query fields to get in addition to the default fields. + Returns: catalog: astropy.table.Table diff --git a/frb/surveys/heasarc.py b/frb/surveys/heasarc.py index 3d3828b7e..886473f51 100644 --- a/frb/surveys/heasarc.py +++ b/frb/surveys/heasarc.py @@ -17,6 +17,7 @@ class HEASARC_Survey(surveycoord.SurveyCoord): """ Class to handle queries on the HEASARC survey. Uses `astroquery` for searching the Heasarc SQL database. + Args: coord (SkyCoord): Coordiante for surveying around @@ -35,6 +36,7 @@ def __init__(self, coord, radius, mission, **kwargs): def get_catalog(self): """ Grab a catalog of sources around the input coordinate to the search radius + Returns: astropy.table.Table: Catalog of sources returned @@ -71,6 +73,7 @@ def get_catalog(self): class SkyView_Survey(surveycoord.SurveyCoord): """ Class to handle queries to the SkyView service of `astroquery`. + Args: coord (SkyCoord): Coordiante for surveying around diff --git a/frb/surveys/hsc.py b/frb/surveys/hsc.py index 44e769a6f..25a19d0a3 100644 --- a/frb/surveys/hsc.py +++ b/frb/surveys/hsc.py @@ -37,6 +37,7 @@ class HSC_Survey(surveycoord.SurveyCoord): """ Class to handle queries on the HSC database + Args: coord (SkyCoord): CoordinAte for surveying around radius (Angle): Search radius around the coordinate @@ -56,6 +57,7 @@ def get_catalog(self, query_fields=None, query=None, max_time=120, Query HSC for all objects within a given radius of the input coordinates. + Args: query_fields: list, optional Column names to be queried. Default values are @@ -70,6 +72,7 @@ def get_catalog(self, query_fields=None, query=None, max_time=120, query_table: str, optional The table to query. Defaults to 'pdr3_wide.forced' + Returns: catalog: astropy.table.Table Contains all measurements retieved @@ -127,6 +130,7 @@ def run_query(query:str, """ Submits a query to the HSC database and downloads the results in the specified format. + Args: query (str): The SQL query to submit to the HSC database. user (str, optional): The account name to use for authentication. Defaults to None. @@ -136,10 +140,12 @@ def run_query(query:str, delete_job (bool, optional): Whether to delete the job after downloading the results. Defaults to False. max_time (int, optional): The maximum time interval to wait for checking query status. Defaults to 120s. + Raises: urllib.error.HTTPError: If there is an HTTP error while submitting the query. QueryError: If there is an error with the query itself. + Returns: None """ diff --git a/frb/surveys/images.py b/frb/surveys/images.py index b02a589ca..3f4ae2d00 100644 --- a/frb/surveys/images.py +++ b/frb/surveys/images.py @@ -17,9 +17,11 @@ def grab_from_url(url): """ Grab a PIL Image from a URL + Args: url (str): URL + Returns: PIL.Image: Image retrieved from the URL @@ -35,6 +37,7 @@ def gen_snapshot_plt(img, imsize, show=False): """ Generate a simple figure from an input PIL.Image + Args: img (PIL.Image): Image to plot imsize: Angle @@ -42,6 +45,7 @@ def gen_snapshot_plt(img, imsize, show=False): show (bool, optional): Show to the screen? If done, will need to regenerate to then save to disk + Returns: matplotlib.pyplot: Allows one to further modify the plot diff --git a/frb/surveys/nedlvs.py b/frb/surveys/nedlvs.py index 9fe83b2b3..6d81dd0c0 100644 --- a/frb/surveys/nedlvs.py +++ b/frb/surveys/nedlvs.py @@ -47,11 +47,13 @@ def get_catalog(self, z_lim=np.inf, print_query=False): """ Get the catalog of objects within the given limits of redshift, impact parameter, and angular separation. + Args: z_lim (float): The maximum redshift of the objects to include in the catalog. impact_par_lim (Quantity): The maximum impact parameter of the objects to include in the catalog. ang_sep_lim (Quantity): The maximum angular separation of the objects to include in the catalog. query_fields (list): The fields to include in the catalog. If None, the default fields are used. + Returns: A table of objects within the given limits. """ diff --git a/frb/surveys/nsc.py b/frb/surveys/nsc.py index 098ec559a..b2be1959c 100644 --- a/frb/surveys/nsc.py +++ b/frb/surveys/nsc.py @@ -32,6 +32,7 @@ class NSC_Survey(dlsurvey.DL_Survey): Child of DL_Survey which uses datalab to access NOAO + Args: coord (SkyCoord): Coordiante for surveying around radius (Angle): Search radius around the coordinate @@ -51,11 +52,13 @@ def get_catalog(self, query=None, query_fields=None, print_query=False,**kwargs) """ Grab a catalog of sources around the input coordinate to the search radius + Args: query: Not used query_fields (list, optional): Over-ride list of items to query print_query (bool): Print the SQL query generated + Returns: astropy.table.Table: Catalog of sources returned. Includes WISE photometry for matched sources. diff --git a/frb/surveys/panstarrs.py b/frb/surveys/panstarrs.py index 41f5cd35b..6204341f8 100644 --- a/frb/surveys/panstarrs.py +++ b/frb/surveys/panstarrs.py @@ -68,6 +68,7 @@ def get_catalog(self,query_fields=None,release="dr2", Query a catalog in the MAST Pan-STARRS database for photometry. + Args: query_fields: list, optional A list of query fields to @@ -85,6 +86,7 @@ def get_catalog(self,query_fields=None,release="dr2", photoz: bool, optional If True, also download photometric redshifts using the Mast CasJobs API. + Returns: catalog: astropy.table.Table @@ -182,11 +184,13 @@ def get_cutout(self,imsize=30*u.arcsec,filt="irg",output_size=None): """ Grab a color cutout (PNG) from Pan-STARRS + Args: imsize (Quantity): Angular size of image desired filt (str): A string with the three filters to be used output_size (int): Output image size in pixels. Defaults to the original cutout size. + Returns: PNG image, None (None for the header). """ @@ -209,10 +213,12 @@ def get_image(self,imsize=30*u.arcsec,filt="i",timeout=120): Grab a fits image from Pan-STARRS in a specific band. + Args: imsize (Quantity): Angular size of the image desired filt (str): One of 'g','r','i','z','y' (default: 'i') timeout (int): Number of seconds to timout the query (default: 120 s) + Returns: hdu: fits header data unit for the downloaded image """ @@ -226,6 +232,7 @@ def get_image(self,imsize=30*u.arcsec,filt="i",timeout=120): def _get_url(coord,imsize=30*u.arcsec,filt="i",output_size=None,imgformat="fits",color=False): """ Returns the url corresponding to the requested image cutout + Args: coord (astropy SkyCoord): Center of the search area. imsize (astropy Angle): Length and breadth of the search area. @@ -265,6 +272,7 @@ def _check_columns(columns,table,release): Checks if the requested columns are present in the table from which data is to be pulled. Raises an error if those columns aren't found. + Args: columns (list of str): column names to retrieve table (str): "mean","stack" or "detection" @@ -285,6 +293,7 @@ def _check_legal(table,release): Checks if this combination of table and release is acceptable Raises a VelueError exception if there is problem. Taken from http://ps1images.stsci.edu/ps1_dr2_api.html + Args: table (str): "mean","stack" or "detection" release (str): "dr1" or "dr2" @@ -303,6 +312,7 @@ def _check_legal(table,release): def _ps1metadata(table="stack",release="dr2", baseurl="https://catalogs.mast.stsci.edu/api/v0.1/panstarrs"): """Return metadata for the specified catalog and table + Args: table (string): mean, stack, or detection diff --git a/frb/surveys/psrcat.py b/frb/surveys/psrcat.py index 1d23f5a27..24b230360 100644 --- a/frb/surveys/psrcat.py +++ b/frb/surveys/psrcat.py @@ -18,6 +18,7 @@ class PSRCAT_Survey(surveycoord.SurveyCoord): """ Class to handle queries on the PSRCAT catalog + Args: coord (SkyCoord): Coordiante for surveying around @@ -32,6 +33,7 @@ def __init__(self, coord, radius, **kwargs): def get_catalog(self): """ Grab the catalog of pulsars around the input coordinate to the search radius + Returns: astropy.table.Table: Catalog of sources returned diff --git a/frb/surveys/sdss.py b/frb/surveys/sdss.py index a8a9325df..4185e015b 100644 --- a/frb/surveys/sdss.py +++ b/frb/surveys/sdss.py @@ -33,6 +33,7 @@ class SDSS_Survey(surveycoord.SurveyCoord): """ Class to handle queries on the SDSS database + Args: coord (SkyCoord): Coordiante for surveying around radius (Angle): Search radius around the coordinate @@ -53,6 +54,7 @@ def get_catalog(self, photoobj_fields=None, timeout=120, print_query=False): TODO -- Expand to include spectroscopy TODO -- Consider grabbing all of the photometry fields + Args: coord: astropy.coordiantes.SkyCoord radius: Angle, optional @@ -64,6 +66,7 @@ def get_catalog(self, photoobj_fields=None, timeout=120, print_query=False): print_query: bool, optional Print the SQL query for the photo-z values + Returns: catalog: astropy.table.Table Contains all measurements retieved @@ -172,9 +175,11 @@ def get_cutout(self, imsize, scale=0.396127): """ Grab a cutout from SDSS + Args: imsize (Quantity): Size of image desired + Returns: PNG image, None: self.cutout and a None to match the image header (not provided by SDSS) @@ -195,6 +200,7 @@ def get_url(coord, imsize=30., scale=0.396127, grid=False, label=False, invert=F """ Generate the SDSS URL for an image retrieval + Args: coord (astropy.coordiantes.SkyCoord): Center of image imsize: float, optional @@ -204,6 +210,7 @@ def get_url(coord, imsize=30., scale=0.396127, grid=False, label=False, invert=F label (bool, optional): invert (bool, optional): + Returns: str: URL for the image @@ -250,11 +257,13 @@ def trim_down_catalog(catalog, keep_photoz=False, cut_within=1.5*units.arcsec): """ Cut down a catalog to keep only 1 source within cut_within + Args: catalog (astropy.table.Table): Input source catalog keep_photoz (bool, optional): cut_within (Angle or Quantity): Cut radius + Returns: astropy.table.Table: Catalog trimmed down diff --git a/frb/surveys/survey_io.py b/frb/surveys/survey_io.py index 33c9e545b..61907af31 100644 --- a/frb/surveys/survey_io.py +++ b/frb/surveys/survey_io.py @@ -6,6 +6,7 @@ def save_plt(plt, out_dir, root, verbose=False, ftype='png'): """ Save a matplotlib object to disk + Args: plt: matplotlib.pyplot out_dir: str @@ -16,6 +17,7 @@ def save_plt(plt, out_dir, root, verbose=False, ftype='png'): ftype: str File type, e.g. png, pdf + Returns: """ diff --git a/frb/surveys/survey_utils.py b/frb/surveys/survey_utils.py index 5418cfdd1..9a8ffe7b9 100644 --- a/frb/surveys/survey_utils.py +++ b/frb/surveys/survey_utils.py @@ -40,12 +40,16 @@ def load_survey_by_name(name, coord, radius, **kwargs): allowed_surveys = ['SDSS', 'DES', 'DESI', 'NVSS', 'FIRST', 'WENSS', 'DECaL', 'PSRCAT', 'WISE', 'Pan-STARRS', 'NEDLVS'] + + Args: name (str): Name of the survey coord (astropy.coordiantes.SkyCoord): Coordinate to define survey around radius (astropy.units.Quanity): Outer radius of the survey **kwargs: Passed the Survey object + + Returns: frb.surveys.SurveyCoord: Child of this parent given by input survey name @@ -98,9 +102,13 @@ def load_survey_by_name(name, coord, radius, **kwargs): def is_inside(surveyname:str, coord:SkyCoord)->bool: """ Tests if a coordinate is within a survey footprint. + + Args: surveyname (str): Name of the survey coord (astropy.coordiantes.SkyCoord): Coordinate to check + + Returns: inside (bool): True if coord is within the footprint. """ @@ -155,8 +163,12 @@ def in_which_survey(coord:SkyCoord, optical_only:bool=True)->dict: Check if a particular coord is inside any survey that can be currently queried from `frb.surveys` module. + + Args: coord (astropy.coordiantes.SkyCoord): Coordinate to check + + Returns: inside (dict): A dict which tells which surveys the coordinate is inside. @@ -181,6 +193,8 @@ def search_all_surveys(coord:SkyCoord, radius:u.Quantity, include_radio:bool=Fal """ A method to query all allowed surveys and combine the results into one table. + + Args: coord (SkyCoord): Central coordinates of cone search. radius (Quantity): Search radius in angular units. @@ -189,6 +203,8 @@ def search_all_surveys(coord:SkyCoord, radius:u.Quantity, include_radio:bool=Fal seed_cat (Table, optional): If you'd like to merge the survey results with another photometry table that you already have. + + Returns: combined_cat (Table): Table of merged query results. """ @@ -270,6 +286,8 @@ def PS1_tile(coord:SkyCoord, side:u.Quantity=1*u.deg, **kwargs)->Table: this manually because MAST doesn't allow cone searches of radius greater than 30'. + + Args: coord (SkyCoord): Center of search region. side (astropy Quantity): Angular size @@ -277,6 +295,8 @@ def PS1_tile(coord:SkyCoord, side:u.Quantity=1*u.deg, **kwargs)->Table: kwargs: Additional keyword arguments to be passed onto the Pan-STARRS_Survey get_catalog method. + + Returns: combined_tab (Table): A PS1 catalog. """ diff --git a/frb/surveys/surveycoord.py b/frb/surveys/surveycoord.py index 63f10a537..4be1c8a6d 100644 --- a/frb/surveys/surveycoord.py +++ b/frb/surveys/surveycoord.py @@ -13,6 +13,7 @@ class SurveyCoord(object): See the children for specific methods + Args: coord (SkyCoord): Coordiante for surveying around radius (Angle): Search radius around the coordinate @@ -38,6 +39,7 @@ def __init__(self, coord, radius, verbose=False): def get_catalog(self): """ + Returns: self.catalog @@ -64,6 +66,7 @@ def write_catalog(self, out_dir, ftype='ecsv', verbose=None, create_dirs=False, """ Write an input astropy Table to disk + Args: tbl: astropy.table.Table out_dir: str @@ -78,6 +81,7 @@ def write_catalog(self, out_dir, ftype='ecsv', verbose=None, create_dirs=False, Overwrite the existing file? verbose: bool, optional + Returns: """ @@ -111,11 +115,13 @@ def write_cutout(self, output_dir='./', root=None, verbose=None): """ Write the cutout image to disk + Args: output_dir: str root: str, optional verbose: bool, optional + Returns: """ diff --git a/frb/surveys/twomass.py b/frb/surveys/twomass.py index ac747e5fe..dc2ed2a9c 100644 --- a/frb/surveys/twomass.py +++ b/frb/surveys/twomass.py @@ -47,11 +47,13 @@ def get_catalog(self,query_fields=None): Query a catalog in the IRSA 2MASS survey for photometry. + Args: query_fields: list, optional A list of query fields to get in addition to the default fields. + Returns: catalog: astropy.table.Table diff --git a/frb/surveys/utils_crossmatching.py b/frb/surveys/utils_crossmatching.py index 7f161b48a..0215b7f6b 100644 --- a/frb/surveys/utils_crossmatching.py +++ b/frb/surveys/utils_crossmatching.py @@ -13,11 +13,13 @@ def cov_matrix(a, b, theta): """ Calculate the covariance matrix for a 2D ellipse. + Parameters: a (float): Semi-major axis of the ellipse b (float): Semi-minor axis of the ellipse theta (float): Position angle of the ellipse in degrees + Returns: np.ndarray: 2x2 covariance matrix @@ -40,11 +42,13 @@ def mahalanobis_distance(point, frbcenter, cov_matrix): Calculate the Mahalanobis distance between a given point and the center. effectively the Z-score in 1D, and it can be a proxy for how many sigma away you are from the mean. + Parameters: point (array-like): The point for which to calculate the distance (should be [RA, Dec]). frbcenter (array-like): The center point, usually the mean [RA, Dec]. cov_matrix (array-like): The covariance matrix of the data. + Returns: float: The Mahalanobis distance. """ @@ -77,6 +81,7 @@ def gauss_contour(frbcenter, cov_matrix, semi_major, transient_name, that represent the uncertainty in the position of the FRB as defined by its covariance matrix. Then, it plots the position of the transient along with the Mahalanobis distance from the FRB center. + Parameters: frbcenter (Astropy SkyCoord): The central position of the FRB. diff --git a/frb/surveys/vista.py b/frb/surveys/vista.py index a174cb04d..2ff1e8af7 100644 --- a/frb/surveys/vista.py +++ b/frb/surveys/vista.py @@ -36,6 +36,7 @@ class VISTA_Survey(dlsurvey.DL_Survey): Child of DL_Survey which uses datalab to access NOAO + Args: coord (SkyCoord): Coordiante for surveying around radius (Angle): Search radius around the coordinate @@ -57,9 +58,11 @@ def _parse_cat_band(self,band): For DES, nothing much is necessary. + Args: band (str): Band desired + Returns: list, list, str: Table columns, Column values, band string for cutout @@ -75,6 +78,7 @@ def _gen_cat_query(self,query_fields=None, qtype='main'): self.query is modified in place + Args: query_fields (list): Override the default list for the SQL query @@ -100,12 +104,14 @@ def get_catalog(self, query=None, query_fields=None, print_query=False, system=' """ Grab a catalog of sources around the input coordinate to the search radius + Args: query: Not used query_fields (list, optional): Over-ride list of items to query print_query (bool): Print the SQL query generated system (str): Magnitude system ['AB', 'Vega'] + Returns: astropy.table.Table: Catalog of sources returned. Includes WISE photometry for matched sources. @@ -149,11 +155,13 @@ def _select_best_img(self,imgTable,verbose,timeout=120): """ Select the best band for a cutout + Args: imgTable: Table of images verbose (bool): Print status timeout (int or float): How long to wait before timing out, in seconds + Returns: HDU: header data unit for the downloaded image diff --git a/frb/surveys/wise.py b/frb/surveys/wise.py index 8ea4201ab..4b99051ff 100644 --- a/frb/surveys/wise.py +++ b/frb/surveys/wise.py @@ -42,6 +42,8 @@ class WISE_Survey(surveycoord.SurveyCoord): Child of DL_Survey which uses datalab to access NOAO + + Args: coord (SkyCoord): Coordiante for surveying around radius (Angle): Search radius around the coordinate @@ -61,12 +63,16 @@ def get_catalog(self, query=None, query_fields=_DEFAULT_query_fields, """ Grab a catalog of sources around the input coordinate to the search radius + + Args: query: Not used query_fields (list, optional): Over-ride list of items to query print_query (bool): Print the SQL query generated system (str): Magnitude system ['AB', 'Vega'] + + Returns: astropy.table.Table: Catalog of sources returned. Includes WISE photometry for matched sources. @@ -107,11 +113,15 @@ def get_catalog(self, query=None, query_fields=_DEFAULT_query_fields, def get_cutout(self, imsize, band, timeout=120): """ Download an image from IRSA + + Args: imsize(Quantity): Size of the cutout in angular units. band(str): One of "W1", "W2", "W3" or "W4" timeout(float): Number of seconds to wait to hear a response from the IRSA SIA server. + + Returns: imghdu(fits.HDU): Fits HDU with image """ @@ -134,6 +144,8 @@ def _gen_cat_query(self,query_fields=_DEFAULT_query_fields): self.query is modified in place + + Args: query_fields (list): Override the default list for the SQL query diff --git a/frb/turb_scattering.py b/frb/turb_scattering.py index f2557e7e1..634fb8d68 100644 --- a/frb/turb_scattering.py +++ b/frb/turb_scattering.py @@ -24,6 +24,7 @@ def theta_mist(n_e, nu_obs, L=50*units.kpc, R=1*units.pc, fV=1.): Estimate the scattering angle for a mist, following the calculations by M. McQuinn presented in Prochaska+2019 + Args: n_e (Quantity): Electron density @@ -36,6 +37,7 @@ def theta_mist(n_e, nu_obs, L=50*units.kpc, R=1*units.pc, fV=1.): fV (float, optional): Filling factor of the bubbles + Returns: Quantity: Angle in radians @@ -60,6 +62,7 @@ def tau_mist(n_e, nu_obs, z_FRB, zL, L=50*units.kpc, R=1*units.pc, fV=1., Temporal broadening for a mist of spherical clouds following the calculations by M. McQuinn presented in Prochaska+2019 + Args: n_e (Quantity): Electron density @@ -77,6 +80,7 @@ def tau_mist(n_e, nu_obs, z_FRB, zL, L=50*units.kpc, R=1*units.pc, fV=1., Filling factor of the bubbles cosmo (Cosmology, optional): + Returns: Quantity: temporal broadening in seconds @@ -96,6 +100,7 @@ def ne_from_tau_mist(tau_scatt, z_FRB, zL, nu_obs, L=50*units.kpc, R=1*units.pc, n_e from temporal broadening for a mist of spherical clouds following the calculations by M. McQuinn presented in Prochaska+2019 + Args: tau_scatt (Quantity): Observed width of the pulse @@ -114,6 +119,7 @@ def ne_from_tau_mist(tau_scatt, z_FRB, zL, nu_obs, L=50*units.kpc, R=1*units.pc, cosmo (Cosmology, optional): verbose (bool, optional): + Returns: Quantity: density in cm**-3 @@ -161,6 +167,7 @@ def ne_from_tau_kolmogorov(tau_scatt, z_FRB, zL, nu_obs, L=50*units.kpc, L0=1*un Scaled from Equation 1 of Prochaska et al. 2019 + Args: tau_scatt (Quantity): Observed width of the pulse @@ -178,6 +185,7 @@ def ne_from_tau_kolmogorov(tau_scatt, z_FRB, zL, nu_obs, L=50*units.kpc, L0=1*un Filling factor and fudge factor term cosmo (Cosmology, optional): + Returns: Quantity: @@ -314,10 +322,12 @@ def set_cloudlet_rdiff(self, lobs, fa): """ Taken from JP notes + Args: lobs: fa (int): Number of clouds intersected + Returns: """ diff --git a/frb/utils.py b/frb/utils.py index 3757046e3..5c2cb19d7 100644 --- a/frb/utils.py +++ b/frb/utils.py @@ -15,6 +15,8 @@ def assign_value(tfrb, key, ilist, tbl_units): The input list and dict of units may be modified in place + + Args: tfrb (frb.frb.FRB): key (str): @@ -42,9 +44,13 @@ def get_valunit(item): Grab the value and unit of an input item allowing for an astropy.units.Quantity + + Args: item (units.Quantity or any Python object): + + Returns: value, unit @@ -212,6 +218,8 @@ def radec_to_coord(radec): Parameters ---------- radec : str or tuple or SkyCoord or list + + Examples: 'J124511+144523', '124511+144523', @@ -278,20 +286,20 @@ def radec_to_coord(radec): def Tsky(nu): - """ Sky temperature - Tsky for all other surveys has been evaluated assuming an average sky - temperature of 34 K at 408 MHz and a spectral index of -2.6 - Follows Haslam et al. 1982 + """Sky temperature model. + + Uses 34 K at 408 MHz and spectral index -2.6 + (Haslam et al. 1982 scaling). Parameters ---------- nu : Quantity + Observing frequency. Returns ------- - Tsky : Quantity - - + Quantity + Sky temperature at `nu`. """ # TODO -- Need some guidance here return 34*units.K * (nu/(408*units.MHz))**(-2.6) @@ -299,13 +307,19 @@ def Tsky(nu): def parse_frb_name(name:str, prefix='FRB'): """Parse the incoming name to generate a 'proper' FRB name + + Args: name (str): [description] prefix (str, optional): [description]. Defaults to 'FRB'. + + Raises: IOError: [description] + + Returns: str: The proper FRB name """ @@ -327,6 +341,8 @@ def parse_frb_name(name:str, prefix='FRB'): def log10_to_linear_errors(value, log_upper_error, log_lower_error): """ Convert log10 errors to linear errors. + + Parameters: ----------- @@ -336,6 +352,8 @@ def log10_to_linear_errors(value, log_upper_error, log_lower_error): Upper error in log10 space log_lower_error : float Lower error in log10 space + + Returns: -------- diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000..d5ce90ff2 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,106 @@ +[build-system] +requires = ["setuptools>=75.0.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "FRB" +version = "0.1.dev0" +description = "Python code for FRB calculations" +readme = "README.md" +requires-python = ">=3.11" +license = {text = "BSD"} +authors = [ + {name = "FRB Community", email = "xavier@ucolick.org"}, +] +keywords = ["FRB", "fast", "radio", "burst", "astronomy"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Environment :: Console", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: BSD License", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Scientific/Engineering :: Astronomy", +] + +dependencies = [ + "numpy>=2.2.0", + "scipy>=1.17", + "astropy>=7.1", + "IPython>=7.2.0", + "pandas>=2.2", + "photutils>=1.1", + "requests>=2.18", + "dust_extinction>=1.4", + "matplotlib>=3.7", + "healpy>=1.19", + "linetools @ git+https://github.com/linetools/linetools.git", + "ligo.skymap>=2.3.0", + "PyYAML>=5.1", + "numba>=0.50.0", + "pyvo>=1.5.3", + "astro-datalab>=2.16.0", + "importlib-resources>=6.4.0", + "astroquery>=0.4.11", + "tqdm>=4.0.0", + "ne2001 @ git+https://github.com/FRBs/ne2001.git", + "astropath @ git+https://github.com/FRBs/astropath.git", +] + +[project.optional-dependencies] +optional = [ + "ppxf @ git+https://github.com/SunilSimha/frb_ppxf.git", + "pymc3", + "pathos", + "hmf_emulator @ git+https://github.com/AemulusProject/hmf_emulator.git", + "specdb", + "pyregion>=2.3.0", + "spectral-cube>=0.6.7", +] + +dev = [ + "pytest>=6.0.0", + "pytest-cov>=2.0.0", + "tox>=4.15.0", + "setuptools>=75.0.0", +] + +[project.urls] +Homepage = "https://github.com/FRBs/FRB" +Documentation = "https://github.com/FRBs/FRB" +Repository = "https://github.com/FRBs/FRB.git" +Issues = "https://github.com/FRBs/FRB/issues" + +[tool.setuptools] +include-package-data = true + +[tool.setuptools.packages.find] +where = ["."] +include = ["frb*"] + +[tool.setuptools.package-data] +frb = ["data/**/*", "*.rst", "*.txt", "*.yaml"] + +[project.scripts] +frb_build = "frb.scripts.build:cli" +frb_dmism = "frb.scripts.dm_ism_hp_map:main" +frb_galaxies = "frb.scripts.galaxies:cli" +frb_image = "frb.scripts.image:cli" +frb_pzdm_mag = "frb.scripts.pzdm_mag:cli" +frb_search_for_halos = "frb.scripts.search_for_halos:cli" +frb_sightline = "frb.scripts.sightline:cli" +frb_summary = "frb.scripts.frb_summary:cli" +frb_tns = "frb.scripts.tns:cli" + +[tool.black] +line-length = 120 +target-version = ["py311", "py312"] + +[tool.pytest.ini_options] +testpaths = ["frb/tests"] +addopts = "-v" + diff --git a/setup.cfg b/setup.cfg deleted file mode 100755 index 52763bbf3..000000000 --- a/setup.cfg +++ /dev/null @@ -1,28 +0,0 @@ -[aliases] -test=pytest - -[options.extras_require] -test = - pytest>=6.0.0 - -alldeps = - numpy>=2.2.0 - scipy>=1.17 - astropy>=7.1 - IPython>=7.2.0 - pytest>=6.0.0 - pandas>=2.2 - photutils>=1.1 - requests>=2.18 - dust_extinction>=1.4 - matplotlib>=3.7 - healpy>=1.19 - linetools>=0.3.1 - ligo.skymap>=2.3.0 - PyYAML>=5.1 - numba>=0.50.0 - setuptools>=75.0.0 - tox>=4.15.0 - pyvo>=1.5.3 - importlib-resources>=6.4.0 - astroquery>=0.4.11 diff --git a/setup.py b/setup.py deleted file mode 100755 index 3f4ad7a7d..000000000 --- a/setup.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# Licensed under a 3-clause BSD style license - see LICENSE.rst -# -# Standard imports -# -import glob, os -# -# setuptools' sdist command ignores MANIFEST.in -# -#from distutils.command.sdist import sdist as DistutilsSdist -from setuptools import setup, find_packages -# -# DESI support code. -# -#from desiutil.setup import DesiTest, DesiVersion, get_version -# -# Begin setup -# -setup_keywords = dict() -# -# THESE SETTINGS NEED TO BE CHANGED FOR EVERY PRODUCT. -# -setup_keywords['name'] = 'FRB' -setup_keywords['description'] = 'Python code for FRB calculations' -setup_keywords['author'] = 'FRB Community' -setup_keywords['author_email'] = 'xavier@ucolick.org' -setup_keywords['license'] = 'BSD' -setup_keywords['url'] = 'https://github.com/FRBs/FRB' - -# -# END OF SETTINGS THAT NEED TO BE CHANGED. -# -setup_keywords['version'] = '0.1.dev0' #get_version(setup_keywords['name']) -# -# Use README.rst as long_description. -# -setup_keywords['long_description'] = '' -if os.path.exists('README.md'): - with open('README.md') as readme: - setup_keywords['long_description'] = readme.read() -# -# Set other keywords for the setup function. These are automated, & should -# be left alone unless you are an expert. -# -# Treat everything in bin/ except *.rst as a script to be installed. -# -if os.path.isdir('bin'): - setup_keywords['scripts'] = [fname for fname in glob.glob(os.path.join('bin', '*')) - if not os.path.basename(fname).endswith('.rst')] -setup_keywords['provides'] = [setup_keywords['name']] -setup_keywords['requires'] = ['Python (>3.11.0)'] -# setup_keywords['install_requires'] = ['Python (>2.7.0)'] -setup_keywords['zip_safe'] = False -#setup_keywords['use_2to3'] = True -setup_keywords['packages'] = find_packages() -#setup_keywords['package_dir'] = {'':'py'} -#setup_keywords['cmdclass'] = {'version': DesiVersion, 'test': DesiTest, 'sdist': DistutilsSdist} -#etup_keywords['test_suite']='{name}.tests.{name}_test_suite.{name}_test_suite'.format(**setup_keywords) -setup_keywords['setup_requires']=['pytest-runner'] -setup_keywords['tests_require']=['pytest'] - -# Autogenerate command-line scripts. -# setup_keywords['entry_points'] = {'console_scripts':['desiInstall = desiutil.install.main:main']} - -# -# Add internal data directories. -# - -data_files = [] - -# walk through the data directory, adding all files -data_generator = os.walk('frb/data') -for path, directories, files in data_generator: - for f in files: - data_path = '/'.join(path.split('/')[1:]) - data_files.append(data_path + '/' + f) -setup_keywords['package_data'] = {'frb': data_files, - '': ['*.rst', '*.txt', '*.yaml']} -setup_keywords['include_package_data'] = True - -# -# Run setup command. -# -setup(**setup_keywords) - diff --git a/tox.ini b/tox.ini index 8674f5a2a..459e7b077 100644 --- a/tox.ini +++ b/tox.ini @@ -1,17 +1,20 @@ [tox] envlist = - {3.10,3.11,3.12}-test{,-alldeps} - {3.10,3.11,3.12}-test-numpy{125,126} - {3.10,3.11,3.12}-test-{numpy,astropy}dev + {3.11,3.12}-test + {3.11,3.12}-test-numpy{125,126} + {3.11,3.12}-test-{numpy,astropy}dev codestyle + requires = - setuptools >= 50.3.0 + setuptools >= 75.0.0 pip >= 19.3.1 isolated_build = true [testenv] # pytest -allowlist_externals = pytest +allowlist_externals = + pytest + pip # Suppress display of matplotlib plots generated during docs build setenv = MPLBACKEND=agg @@ -36,7 +39,6 @@ passenv = HOME,WINDIR,LC_ALL,LC_CTYPE,CC,CI # description = run tests - alldeps: with all optional dependencies devdeps: with the latest developer version of key dependencies oldestdeps: with the oldest supported version of key dependencies cov: and test coverage @@ -47,10 +49,6 @@ description = # The following provides some specific pinnings for key packages deps = - git+https://github.com/FRBs/ne2001.git#egg=ne2001 - git+https://github.com/FRBs/astropath.git#egg=astropath - git+https://github.com/linetools/linetools#egg=linetools - cov: coverage numpy123: numpy==1.23.* numpy124: numpy==1.24.* @@ -62,17 +60,101 @@ deps = linetoolsdev: git+https://github.com/linetools/linetools.git#egg=linetools -# The following indicates which extras_require from setup.cfg will be installed +# The following indicates which optional dependencies from pyproject.toml will be installed extras = - test - alldeps + dev commands = pip freeze - !cov: pytest --pyargs frb {posargs} - cov: pytest --pyargs frb --cov frb --cov-config={toxinidir}/setup.cfg {posargs} + !cov: python -m pytest --pyargs frb {posargs} + cov: python -m pytest --pyargs frb --cov frb {posargs} cov: coverage xml -o {toxinidir}/coverage.xml + +[testenv:3.11-test-numpy125] +description = run lightweight tests with numpy 1.25 (without heavy association stack) +deps = + numpy==1.25.* + scipy<1.17 + astropy>=7.1 + importlib_resources + git+https://github.com/FRBs/ne2001.git@7a2586cf983711c0e645e2f63900973541d4a392#egg=ne2001 + git+https://github.com/linetools/linetools@99e6dbe3ca0fd1f10476dbf1bed8482541692337#egg=linetools + pandas>=2.2 + photutils>=1.1 + matplotlib>=3.7 + healpy + tqdm>=4.0 + requests>=2.18 + PyYAML>=5.1 + pytest>=6.0.0 +commands = + python -m pytest frb/tests/test_dmism.py frb/tests/test_frbem.py frb/tests/test_frbigm.py frb/tests/test_frbobs.py {posargs} + +[testenv:3.12-test-numpy125] +description = run lightweight tests with numpy 1.25 (without heavy association stack) + +deps = + numpy==1.25.* + scipy<1.17 + astropy>=7.1 + importlib_resources + git+https://github.com/FRBs/ne2001.git@7a2586cf983711c0e645e2f63900973541d4a392#egg=ne2001 + git+https://github.com/linetools/linetools@99e6dbe3ca0fd1f10476dbf1bed8482541692337#egg=linetools + pandas>=2.2 + photutils>=1.1 + matplotlib>=3.7 + healpy + tqdm>=4.0 + requests>=2.18 + PyYAML>=5.1 + pytest>=6.0.0 +commands = + python -m pytest frb/tests/test_dmism.py frb/tests/test_frbem.py frb/tests/test_frbigm.py frb/tests/test_frbobs.py {posargs} + + +[testenv:3.11-test-numpy126] +description = run lightweight tests with numpy 1.26 (without heavy association stack) + +deps = + numpy==1.26.* + scipy>=1.17 + astropy>=7.1 + importlib_resources + git+https://github.com/FRBs/ne2001.git@7a2586cf983711c0e645e2f63900973541d4a392#egg=ne2001 + git+https://github.com/linetools/linetools@99e6dbe3ca0fd1f10476dbf1bed8482541692337#egg=linetools + pandas>=2.2 + photutils>=1.1 + matplotlib>=3.7 + healpy + tqdm>=4.0 + requests>=2.18 + PyYAML>=5.1 + pytest>=6.0.0 +commands = + python -m pytest frb/tests/test_dmism.py frb/tests/test_frbem.py frb/tests/test_frbigm.py frb/tests/test_frbobs.py {posargs} + +[testenv:3.12-test-numpy126] +description = run lightweight tests with numpy 1.26 (without heavy association stack) + +deps = + numpy==1.26.* + scipy>=1.17 + astropy>=7.1 + importlib_resources + git+https://github.com/FRBs/ne2001.git@7a2586cf983711c0e645e2f63900973541d4a392#egg=ne2001 + git+https://github.com/linetools/linetools@99e6dbe3ca0fd1f10476dbf1bed8482541692337#egg=linetools + pandas>=2.2 + photutils>=1.1 + matplotlib>=3.7 + healpy + tqdm>=4.0 + requests>=2.18 + PyYAML>=5.1 + pytest>=6.0.0 +commands = + python -m pytest frb/tests/test_dmism.py frb/tests/test_frbem.py frb/tests/test_frbigm.py frb/tests/test_frbobs.py {posargs} + [testenv:conda] description = run tests in environment created via conda requires = tox-conda