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 7 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
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
1 change: 1 addition & 0 deletions devtools/conda-envs/test_env.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ dependencies:
- scipy
- scikit-learn
- matplotlib
- loguru
- pyarrow

# Testing
Expand Down
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
11 changes: 11 additions & 0 deletions docs/miscellaneous.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Miscellaneous
=============

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

.. toctree::
:maxdepth: 2
:caption: Miscellaneous
Copy link
Member

Choose a reason for hiding this comment

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

I'd remove the TOC caption — looks superfluous as it is repeated, see https://alchemlyb--303.org.readthedocs.build/en/303/miscellaneous.html

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Sorry, what do you mean by this? I could change the :maxdepth: 2 to 1, if Print to the stderr and Save to a file is superfluous?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Oh, I see.


miscellaneous/logging

29 changes: 29 additions & 0 deletions docs/miscellaneous/logging.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
.. _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 `stderr`.
Copy link
Member

Choose a reason for hiding this comment

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

Can you link to sys.stderr in the Python docs?


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}", filter="my_module", level="INFO")

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

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

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

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
7 changes: 2 additions & 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,12 @@ 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`.
Output from alchemlyb is logged via :mod:`loguru`.
Copy link
Member

Choose a reason for hiding this comment

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

remove as no logging done here?


Attributes
----------
Expand Down Expand Up @@ -77,7 +75,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
6 changes: 2 additions & 4 deletions src/alchemlyb/parsing/amber.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,16 @@

"""

import logging
import re

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

from . import _init_attrs_dict
from .util import anyopen
from ..postprocessors.units import R_kJmol, kJ2kcal

logger = logging.getLogger("alchemlyb.parsers.Amber")

k_b = R_kJmol * kJ2kcal

_FP_RE = r"[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?"
Expand Down Expand Up @@ -345,7 +343,7 @@ def extract(outfile, T):
if None in mbar:
msg = "Something strange parsing the following MBAR section."
msg += "\nMaybe the mbar_lambda values are incorrect?"
logger.error("%s\n%s", msg, mbar)
logger.error("{}\n{}", msg, mbar)
raise ValueError(msg)

reference_energy = mbar[file_datum.mbar_lambda_idx]
Expand Down
4 changes: 1 addition & 3 deletions src/alchemlyb/parsing/namd.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
"""Parsers for extracting alchemical data from `NAMD <http://www.ks.uiuc.edu/Research/namd/>`_ output files.

"""
import logging
from os.path import basename
from re import split

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

from . import _init_attrs
from .util import anyopen
from ..postprocessors.units import R_kJmol, kJ2kcal

logger = logging.getLogger("alchemlyb.parsers.NAMD")

k_b = R_kJmol * kJ2kcal


Expand Down
9 changes: 9 additions & 0 deletions src/alchemlyb/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
concat should be done at local level."""

import pytest
from _pytest.logging import LogCaptureFixture
from alchemtest.amber import load_bace_example, load_simplesolvated
from alchemtest.gmx import (
load_benzene,
Expand All @@ -21,6 +22,7 @@
load_restarted,
load_restarted_reversed,
)
from loguru import logger

from alchemlyb.parsing import gmx, amber, gomc, namd

Expand Down Expand Up @@ -269,3 +271,10 @@ def namd_idws_restarted_reversed():
u_nk = namd.extract_u_nk(dataset["data"]["both"], T=300)

return u_nk


@pytest.fixture
def caplog(caplog: LogCaptureFixture):
handler_id = logger.add(caplog.handler, format="{message}")
yield caplog
logger.remove(handler_id)
Loading