Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use loguru #303

Merged
merged 13 commits into from
Jun 6, 2023
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,6 @@ jobs:
extra-specs: |
python=${{ matrix.python-version }}

- name: Install alchemtest
run: |
python -m pip install https://github.com/alchemistry/alchemtest/archive/master.zip

- name: Install package (with no dependencies)
run: |
python -m pip install . --no-deps
Expand Down
5 changes: 4 additions & 1 deletion CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,16 @@ The rules for this file:

* 2.1.0

Changes
- Use loguru instead of logging for log (issue #301, PR #303).

Enhancements
- Add a parser to read serialised pandas dataframe (parquet) (issue #316, PR#317).
- workflow.ABFE allow parquet as input (issue #316, PR#317).

Fixes
- Fix the case where visualisation.plot_convergence would fail when the final
error is NaN (issue #318, PR#317).
error is NaN (issue #318, PR#319).


06/04/2023 xiki-tempula
Expand Down
11 changes: 10 additions & 1 deletion devtools/conda-envs/test_env.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,20 @@ dependencies:
- scipy
- scikit-learn
- matplotlib
- loguru
- pyarrow

# Testing
# Testing
- pytest
- pytest-cov
- pytest-xdist
- pytest-black
- codecov

# Doc
- sphinx
- sphinx_rtd_theme

- pip:
- alchemtest @ https://github.com/alchemistry/alchemtest/archive/master.zip

83 changes: 44 additions & 39 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,31 +30,33 @@
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.mathjax',
'sphinx.ext.autosummary',
'sphinx.ext.napoleon']
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.mathjax",
"sphinx.ext.autosummary",
"sphinx.ext.napoleon",
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"

# The master toctree document.
master_doc = 'index'
master_doc = "index"

# General information about the project.
project = u'alchemlyb'
author = u'''Irfan Alibay, Bryce Allen, Mohammad S. Barhaghi, Oliver
project = "alchemlyb"
author = """Irfan Alibay, Bryce Allen, Mohammad S. Barhaghi, Oliver
Beckstein, David Dotson, Jérôme Hénin, Travis Jensen, Thomas
T. Joseph, Ian Kenney, Hyungro Lee, Victoria Lim, Shuai Liu, Domenico
Marson, Pascal Merz, Alexander Schlaich, Dominik Wille, Zhiyi Wu'''
copyright = u'2017-2022, ' + author
Marson, Pascal Merz, Alexander Schlaich, Dominik Wille, Zhiyi Wu"""
copyright = "2017-2022, " + author


# The version info for the project you're documenting, acts as replacement for
Expand All @@ -67,12 +69,13 @@
# desired, see the commented out code

from alchemlyb._version import get_versions
release = get_versions()['version']

release = get_versions()["version"]
del get_versions

version = release
#version = release.split("+")[0] # only major.minor.patch
#version = "."join(release.split(".")[:2]) # only major.minor
# version = release.split("+")[0] # only major.minor.patch
# version = "."join(release.split(".")[:2]) # only major.minor

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand All @@ -84,10 +87,10 @@
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
Expand All @@ -99,7 +102,8 @@
# a list of builtin themes.
#
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'

html_theme = "sphinx_rtd_theme"

html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
Expand All @@ -117,7 +121,7 @@
# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'alchemlybdoc'
htmlhelp_basename = "alchemlybdoc"


# -- Options for LaTeX output ---------------------------------------------
Expand All @@ -126,15 +130,12 @@
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',

# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
Expand All @@ -144,19 +145,15 @@
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'alchemlyb.tex', u'alchemlyb Documentation',
author, 'manual'),
(master_doc, "alchemlyb.tex", "alchemlyb Documentation", author, "manual"),
]


# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'alchemlyb', u'alchemlyb Documentation',
[author], 1)
]
man_pages = [(master_doc, "alchemlyb", "alchemlyb Documentation", [author], 1)]


# -- Options for Texinfo output -------------------------------------------
Expand All @@ -165,22 +162,30 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'alchemlyb', u'alchemlyb Documentation',
author, 'alchemlyb', 'The simple alchemistry library.',
'Miscellaneous'),
(
master_doc,
"alchemlyb",
"alchemlyb Documentation",
author,
"alchemlyb",
"The simple alchemistry library.",
"Miscellaneous",
),
]


# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None,
'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None),
'pymbar': ('https://pymbar.readthedocs.io/en/latest/', None),
'alchemtest': (
'https://alchemtest.readthedocs.io/en/latest/', None),
'scipy': ('https://docs.scipy.org/doc/scipy/reference/', None)}
intersphinx_mapping = {
"https://docs.python.org/": None,
"pandas": ("https://pandas.pydata.org/pandas-docs/stable/", None),
"pymbar": ("https://pymbar.readthedocs.io/en/latest/", None),
"alchemtest": ("https://alchemtest.readthedocs.io/en/latest/", None),
"scipy": ("https://docs.scipy.org/doc/scipy/reference/", None),
"loguru": ("https://loguru.readthedocs.io/en/stable/", None),
}

# generate stub pages where directed with autosummary
#autosummary_generate = True
# autosummary_generate = True
autosummary_generate_overwrite = False
# Ensure that the documentation is generated not by alphabetic order.
autodoc_member_order = 'bysource'
autodoc_member_order = "bysource"
6 changes: 0 additions & 6 deletions docs/estimators/alchemlyb.estimators.MBAR.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,10 @@ MBAR
The :class:`~alchemlyb.estimators.MBAR` estimator is a light wrapper around the reference implementation of MBAR [Shirts2008]_ from :mod:`pymbar` (:class:`pymbar.mbar.MBAR`).
As a generalization of BAR, it uses information from all sampled states to generate an estimate for the free energy difference between each state.

A more robust version of :class:`~alchemlyb.estimators.MBAR` is provided as
:class:`~alchemlyb.estimators.AutoMBAR`, where the class will iteratively
try different means of solving the MBAR estimate to avoid unconverged results.
The process of iterating different methods is documented in the logger
*alchemlyb.estimators.AutoMBAR*.

API Reference
-------------
.. autoclass:: alchemlyb.estimators.MBAR
:members:
:inherited-members:

.. autoclass:: alchemlyb.estimators.AutoMBAR
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ We also welcome code contributions: have a look at our `Developer Guide`_. Open
postprocessing
visualisation
workflows
miscellaneous
references

.. toctree::
Expand Down
10 changes: 10 additions & 0 deletions docs/miscellaneous.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Miscellaneous
=============

This page includes aspects that would improve your usage of **alchemlyb**.

.. toctree::
:maxdepth: 2

miscellaneous/logging

37 changes: 37 additions & 0 deletions docs/miscellaneous/logging.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
.. _logging_section:

Logging
=======

In **alchemlyb**, we use :mod:`loguru` for logging. By default, the
orbeckst marked this conversation as resolved.
Show resolved Hide resolved
:mod:`loguru` will print the logging information into the
`sys.stderr <https://docs.python.org/3/library/sys.html#sys.stderr>`_.

orbeckst marked this conversation as resolved.
Show resolved Hide resolved
Print to the stderr
-------------------

If you want to customise the printing to the `stderr`, you could remove the
existing sink first ::

from loguru import logger
logger.remove()

Then add other custom sink ::
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Link to a page that explains what the format does, filter etc — basically the docs for logger.add


logger.add(sys.stderr, format="{time} {level} {message}", level="INFO")

The loguru logger is compatible with the :mod:`logging` module of the Python
standard library and can easily be
`configured to log to a *logging* handler <https://loguru.readthedocs.io/en/stable/overview.html#entirely-compatible-with-standard-logging>`_.
orbeckst marked this conversation as resolved.
Show resolved Hide resolved


Save to a file
--------------

Alternatively, one could save to a file simply with ::

from loguru import logger
logger.add("file_{time}.log")

See `configure to log to a file <https://loguru.readthedocs.io/en/stable/overview.html#easier-file-logging-with-rotation-retention-compression>`_
for more explanation.
5 changes: 1 addition & 4 deletions docs/workflows/alchemlyb.workflows.ABFE.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,10 @@ are to
complete workflow.

For a GROMACS ABFE simulation, executing the workflow would look similar
to the following code (The log is configured by logger). ::
to the following code (:ref:`See how to configure the logger <logging_section>`). ::

>>> from alchemtest.gmx import load_ABFE
>>> from alchemlyb.workflows import ABFE
>>> # Enable the logger
>>> import logging
>>> logging.basicConfig(filename='ABFE.log', level=logging.INFO)
>>> # Obtain the path of the data
>>> import os
>>> dir = os.path.dirname(load_ABFE()['data']['complex'][0])
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"scipy",
"scikit-learn",
"matplotlib",
"loguru",
"pyarrow",
],
)
4 changes: 1 addition & 3 deletions src/alchemlyb/convergence/convergence.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""Functions for assessing convergence of free energy estimates and raw data."""

import logging
from warnings import warn

import numpy as np
import pandas as pd
from loguru import logger

from .. import concat
from ..estimators import BAR, TI, MBAR, FEP_ESTIMATORS, TI_ESTIMATORS
Expand Down Expand Up @@ -65,7 +65,6 @@ def forward_backward_convergence(df_list, estimator="MBAR", num=10, **kwargs):
Use pymbar.MBAR instead of the AutoMBAR option.

"""
logger = logging.getLogger("alchemlyb.convergence." "forward_backward_convergence")
logger.info("Start convergence analysis.")
logger.info("Check data availability.")
if estimator.upper() != estimator:
Expand Down Expand Up @@ -335,7 +334,6 @@ def A_c(series_list, precision=0.01, tol=2):
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8397498/#FD18

"""
logger = logging.getLogger("alchemlyb.convergence.A_c")
n_R_c = len(series_list)
R_c_list = [fwdrev_cumavg_Rc(series, precision, tol)[0] for series in series_list]
logger.info(f"R_c list: {R_c_list}")
Expand Down
6 changes: 1 addition & 5 deletions src/alchemlyb/estimators/mbar_.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import logging

import pandas as pd
import pymbar
from sklearn.base import BaseEstimator
Expand All @@ -25,12 +23,11 @@ class MBAR(BaseEstimator, _EstimatorMixOut):

method : str, optional, default="robust"
The optimization routine to use. This can be any of the methods
available via :func:`scipy.optimize.minimize` or
available via :func:`scipy.optimize.minimize` or
:func:`scipy.optimize.root`.

verbose : bool, optional
Set to ``True`` if verbose debug output from :mod:`pymbar` is desired.
Output from alchemlyb is logged via :mod:`logging`.

Attributes
----------
Expand Down Expand Up @@ -77,7 +74,6 @@ def __init__(
self.initial_f_k = initial_f_k
self.method = method
self.verbose = verbose
self.logger = logging.getLogger("alchemlyb.estimators.MBAR")

# handle for pymbar.MBAR object
self._mbar = None
Expand Down
Loading