Skip to content

Commit

Permalink
Update documentation setup, correcting little buglets
Browse files Browse the repository at this point in the history
  • Loading branch information
mhvk committed Feb 21, 2025
1 parent be8984a commit e2e3f06
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 79 deletions.
97 changes: 42 additions & 55 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,79 +27,68 @@

import os
import sys
import datetime
import tomllib
import warnings
from datetime import UTC, datetime
from importlib import import_module
from pathlib import Path

try:
with warnings.catch_warnings():
# Remove warning about matplotlib - we don't use it.
warnings.filterwarnings("ignore", "matplotlib")
from sphinx_astropy.conf.v1 import * # noqa
except ImportError:
print('ERROR: the documentation requires the sphinx-astropy package to be installed')
sys.exit(1)

# Get configuration information from setup.cfg
from configparser import ConfigParser
conf = ConfigParser()

conf.read([os.path.join(os.path.dirname(__file__), '..', 'setup.cfg')])
setup_cfg = dict(conf.items('metadata'))
# -- Get user configuration from pyproject.toml -------------------------------
with (Path(__file__).parents[1] / "pyproject.toml").open("rb") as f:
pyproject = tomllib.load(f)

# -- General configuration ----------------------------------------------------

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns.append('_templates')

# add any custom intersphinx mappings
# intersphinx_mapping |= {}

# -- Plot options (adapted from Astropy docs/conf.py) -------------------------

plot_rcparams = {}
plot_rcparams['savefig.facecolor'] = 'none'
plot_rcparams['savefig.bbox'] = 'tight'
plot_rcparams['font.size'] = 12
plot_rcparams = {
"savefig.facecolor": "none",
"savefig.bbox": "tight",
"font.size": 12,
}
plot_apply_rcparams = True

plot_html_show_source_link = False
plot_html_show_formats = False
plot_formats = ['png']
# Don't use the default - which includes a numpy and matplotlib import
plot_pre_code = ""


# -- General configuration ----------------------------------------------------

# By default, highlight as Python 3.
highlight_language = 'python3'

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.2'

# To perform a Sphinx version check that needs to be more specific than
# major.minor, call `check_sphinx_version("x.y.z")` here.
# check_sphinx_version("1.2.1")

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns.append('_templates')

# This is added to the end of RST files - a good place to put substitutions to
# be used globally.
rst_epilog += """
"""

# -- Project information ------------------------------------------------------

# This does not *have* to match the package name, but typically does
project = setup_cfg['name']
author = setup_cfg['author']
copyright = '{0}, {1}'.format(
datetime.datetime.now().year, setup_cfg['author'])
project = pyproject["project"]["name"]
author = " & ".join(auth["name"] for auth in pyproject["project"]["authors"])
copyright = f"{datetime.now(tz=UTC).year}, {author}"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.

import_module(setup_cfg['name'])
package = sys.modules[setup_cfg['name']]
import_module(project)
package = sys.modules[project]

# The short X.Y version.
version = package.__version__.split('-', 1)[0]
# The full version, including alpha/beta/rc tags.
release = package.__version__

# This is added to the end of RST files - a good place to put substitutions to
# be used globally.
rst_epilog += """
"""

# -- Options for HTML output --------------------------------------------------

Expand Down Expand Up @@ -182,23 +171,18 @@

# -- Options for the edit_on_github extension ---------------------------------

if setup_cfg.get('edit_on_github').lower() == 'true':

extensions += ['sphinx_astropy.ext.edit_on_github']

edit_on_github_project = setup_cfg['github_project']
edit_on_github_branch = "master"

edit_on_github_source_root = ""
edit_on_github_doc_root = "docs"
extensions += ['sphinx_astropy.ext.edit_on_github']
edit_on_github_project = pyproject["project"]["urls"]["repository"].replace("https://github.com/", "")
edit_on_github_source_root = ""
edit_on_github_doc_root = "docs"

# -- Resolving issue number to links in changelog -----------------------------
github_issues_url = 'https://github.com/{0}/issues/'.format(setup_cfg['github_project'])
github_issues_url = pyproject["project"]["urls"]["repository"] + "/issues/"

# -- Turn on nitpicky mode for sphinx (to warn about references not found) ----
#
# nitpicky = True
# nitpick_ignore = []
nitpicky = True
nitpick_ignore = []
#
# Some warnings are impossible to suppress, and you can list specific references
# that should be ignored in a nitpick-exceptions file which should be inside
Expand All @@ -220,3 +204,6 @@
# dtype, target = line.split(None, 1)
# target = target.strip()
# nitpick_ignore.append((dtype, six.u(target)))

# -- Include inherited members in class documentation -------------------------
automodsumm_inherited_members = True
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ equation appearing in these tutorials.
Reference/API
=============

.. automodapi:: screens
.. automodapi:: screens.screen
.. automodapi:: screens.fields
.. automodapi:: screens.dynspec
Expand Down
36 changes: 20 additions & 16 deletions docs/tutorials/error_analysis.rst
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,11 @@ Set a seed for the random number generator to make the results reproducable.

Set some defaults for plotting functions, including the levels at which to draw
confidence contours in 2D (see the `note about sigmas
<https://corner.readthedocs.io/en/latest/pages/sigmas.html>`_
in the documentation of the :py:mod:`corner` package)
<https://corner.readthedocs.io/en/latest/pages/sigmas>`_
in the documentation of the |corner|_ package)

.. |corner| replace:: ``corner``
.. _corner: https://corner.readthedocs.io/en/stable

.. jupyter-execute::

Expand Down Expand Up @@ -296,9 +299,9 @@ This tutorial deals with three different sets of parameters:

Here, we simply define (lists of) strings used for printing results and
labelling plots later. First, use :py:func:`~collections.namedtuple` to create
the `ParString` class that stores the LaTeX math-mode strings of the symbol and
the unit for a parameter, and define a function that combines those symbol and
unit strings into label strings for a list of parameters.
the ``ParString`` class that stores the LaTeX math-mode strings of the symbol
and the unit for a parameter, and define a function that combines those symbol
and unit strings into label strings for a list of parameters.

.. jupyter-execute::

Expand Down Expand Up @@ -800,7 +803,7 @@ effective velocities with the harmonic-coefficients model equation
Here, we load the fit results produced by :py:func:`~scipy.optimize.curve_fit`
(the optimum-fit values and the covariance matrix of the parameters
:math:`A_\mathrm{\oplus,s}, A_\mathrm{\oplus,c}, A_\mathrm{p,s},
A_\mathrm{p,c}, C`) from an `.npz` file (available for download here:
A_\mathrm{p,c}, C`) from an ``.npz`` file (available for download here:
:download:`fit-results-J0437.npz <../data/fit-results-J0437.npz>`).

.. jupyter-execute::
Expand All @@ -816,13 +819,14 @@ Multiple solutions

Because of the absolute-value operation in the model equation, there are two
solutions for the harmonic coefficients: one with positive sign and one with a
negative sign. The solution found by :py:func:`~scipy.optimize.curve_fit` (just
loaded from the `.npz` file) is the one with the positive sign, but this simply
depends on the initial guess used during the fit. The two solutions correspond
to the two possible sky-orientations of the line of lensed images that fit the
data and cannot be distinguished using single-station scintillation
measurements. In terms of the physical parameters, these solutions have a
difference in :math:`\xi` of :math:`180^\circ` and an accompanying sign flip in
negative sign. The solution found by :py:func:`~scipy.optimize.curve_fit`
(just loaded from the ``.npz`` file) is the one with the positive sign, but
this simply depends on the initial guess used during the fit. The two
solutions correspond to the two possible sky-orientations of the line of
lensed images that fit the data and cannot be distinguished using
single-station scintillation measurements. In terms of the physical
parameters, these solutions have a difference in :math:`\xi` of
:math:`180^\circ` and an accompanying sign flip in
:math:`v_\mathrm{lens,\parallel}`, but they correspond to the same physical
picture of the system.

Expand Down Expand Up @@ -1063,8 +1067,8 @@ constraints, external constraints need to be provided for one of the physical
parameters to get narrow constraints on the rest. In this tutorial, we use a
constraint on the pulsar distance :math:`d_\mathrm{p}`, which would also exist
in many real-life applications. In the case of external constraints on a
different parameter, the functions `pars_phen2phys_d_p()` and
`upars_phen2phys_d_p()` defined above would have to be replaced with slightly
different parameter, the functions ``pars_phen2phys_d_p()`` and
``upars_phen2phys_d_p()`` defined above would have to be replaced with slightly
different functions to convert from phenomenological to physical parameters.

The pulsar studied in this example, PSR J0437--4715, has an exceptionally well
Expand Down Expand Up @@ -1111,7 +1115,7 @@ unphysical non-positive distance. Finally, convert the set into an Astropy
Generate random signs of the cosine of the pulsar's orbital inclination,
corresponding to the two possible spatial orientations of the pulsar's orbit.
We create an Astropy :py:class:`~astropy.uncertainty.Distribution` object
consisting of +1 and -1 entries, just like `sol_sign` above.
consisting of +1 and -1 entries, just like ``sol_sign`` above.

.. jupyter-execute::

Expand Down
4 changes: 2 additions & 2 deletions docs/tutorials/infer_phys_pars.rst
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ this solution.
print(f'chi_p: {chi_p[j_sol].to(u.deg):8.2f}')
print(f'dveff_c: {dveff_c[j_sol].to(u.km/u.s/u.pc**0.5):8.2f}')

You can verify that the two solution are equivalent by setting `j_sol` to the
You can verify that the two solution are equivalent by setting ``j_sol`` to the
index of the other solution. Executing the codeblocks below should then give
the same answers for the physical parameters.

Expand Down Expand Up @@ -508,7 +508,7 @@ pulsar's systemic motion to the effective velocity
\right].
To compute a velocity from a proper motion and a distance, we use the
:py:func:`~astropy.units.equivalencies.dimensionless_angles` equivalency. This
:py:func:`~astropy.units.dimensionless_angles` equivalency. This
takes care of handling the units of Astropy :py:class:`~astropy.units.Quantity`
objects correctly when using the small-angle approximation
(for further explanation, see the `Astropy documentation about equivalencies
Expand Down
4 changes: 2 additions & 2 deletions docs/tutorials/single_screen.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ Start with some standard imports.
from astropy import constants as const

Set a colormap to use for phases. Preferably import the perceptually uniform
colormap `phasecmap` from :py:mod:`screens.visualization`.
The `hsv` colormap from :py:mod:`matplotlib.cm` is used as fallback.
colormap ``phasecmap`` from :py:mod:`screens.visualization`.
The ``hsv`` colormap from :py:mod:`matplotlib.cm` is used as fallback.

.. jupyter-execute::

Expand Down
8 changes: 4 additions & 4 deletions screens/modeling.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def theta_theta(self, mu_eff=None, theta_grid=None, **kwargs):
instance.
**kwargs
Any further arguments are passed on to
`~screens.dynspec.DynamicSpectrum.theta_grid`
`~screens.modeling.DynamicSpectrumModel.theta_grid`
"""
if mu_eff is not None:
self.mu_eff = mu_eff
Expand Down Expand Up @@ -297,7 +297,7 @@ def model(self, magnification=None, mu_eff=None):
def residuals(self, magnification=None, mu_eff=None):
"""Residuals compared to the model.
Parameters as for :meth:`~screens.dynspec.DynamicSpectrum.model`:
Parameters as for :meth:`~screens.modeling.DynamicSpectrumModel.model`:
"""
model = self.model(magnification, mu_eff)
return (self.dynspec - model) / self.noise
Expand Down Expand Up @@ -469,7 +469,7 @@ def fit(self, guess=None, verbose=2, **kwargs):
"""Fit the dynamic spectrum directly.
This needs good guesses, such as can be gotten from
:meth:`screens.dynspec.DynamicSpectrum.locate_mu_eff`.
:meth:`screens.modeling.DynamicSpectrumModel.locate_mu_eff`.
Parameters
----------
Expand Down Expand Up @@ -660,7 +660,7 @@ def theta_theta(self, mu_eff=None, conserve=False, theta_grid=True,
instance.
**kwargs
Any further arguments are passed on to
`~screens.dynspec.DynamicSpectrum.theta_grid`
`~screens.modeling.DynamicSpectrumModel.theta_grid`
"""
if mu_eff is None:
mu_eff = self.mu_eff
Expand Down

0 comments on commit e2e3f06

Please sign in to comment.