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

Integrate Loguru #62

Merged
merged 32 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
6dd3ce2
Add loguru exception catching
maestroque Apr 15, 2024
d33b5ac
Integrate loguru for warning and info logs
maestroque Apr 15, 2024
72c427b
Add loguru in requirements
maestroque Apr 15, 2024
a9b0c18
Add loguru to setup.cfg
maestroque May 13, 2024
acd31cd
Disable loguru logs for library users
maestroque May 22, 2024
537f48a
Add verbose option in CLI
maestroque May 22, 2024
bb7ce79
Fix loguru disabling for library users
maestroque May 23, 2024
7070d70
Add logger enabling and configuring
maestroque May 23, 2024
405254c
Leave logger.catch decorator only for the CLI workflow function
maestroque May 23, 2024
cbfc013
Remove unnecessary imports
maestroque May 23, 2024
4d8ffa3
Add loguru as a main dependency
maestroque May 27, 2024
3724928
Reformat using isort and black
maestroque May 27, 2024
333e94b
CLI: minor fixes for verbose argument
maestroque May 27, 2024
afcc380
Remove Gooey from draft CLI implementation
maestroque Jun 1, 2024
be82040
Minor comment deletion and reformatting
maestroque Jun 1, 2024
7fcb3ab
Add log level choice option in CLI
maestroque Jun 1, 2024
3253566
Add logfile sink
maestroque Jun 1, 2024
8dd3166
Add --verbose flag in the CLI
maestroque Jun 1, 2024
cd22a43
Add log level choosing for module usage
maestroque Jun 1, 2024
2ac91a3
Add info and debug logs physio.py and operations.py functions
maestroque Jun 1, 2024
81750e3
Add info logs on editor.py and io.py
maestroque Jun 2, 2024
7f8fd6a
Fix warning catching assertions in tests
maestroque Jun 4, 2024
86adcf3
Improve warning log assertions when there are multiple expected warni…
maestroque Jun 4, 2024
b52d13a
Style fix
maestroque Jun 4, 2024
5af076b
Updating from master
maestroque Jun 6, 2024
c568cb2
Remove unused imports
maestroque Jun 6, 2024
6c4dcde
Merge remote-tracking branch 'origin/master' into add-loguru
maestroque Jun 12, 2024
a78544c
Fix loguru not detecting module's name
maestroque Jun 13, 2024
a008c72
Add more logger utilities. Fix multiple logger instance bug
maestroque Jun 13, 2024
8f6b944
Remove commented out line
maestroque Jun 14, 2024
b865617
Fix imports in cli/run.py
maestroque Jun 14, 2024
145d48f
Make --quiet and --debug cli options mutually exclusive, remove matpl…
maestroque Jun 14, 2024
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
6 changes: 5 additions & 1 deletion peakdet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@
interpolate_physio, peakfind_physio,
plot_physio, reject_peaks)
from peakdet.physio import (Physio)
from loguru import logger

from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
del get_versions

# TODO: Loguru does not detect the module's name
maestroque marked this conversation as resolved.
Show resolved Hide resolved
logger.disable("")
25 changes: 14 additions & 11 deletions peakdet/cli/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
import glob
import os
import sys
import warnings
import matplotlib
matplotlib.use('WXAgg')
from gooey import Gooey, GooeyParser
import peakdet
from loguru import logger

TARGET = 'pythonw' if sys.platform == 'darwin' else 'python'
TARGET += ' -u ' + os.path.abspath(__file__)
Expand Down Expand Up @@ -105,9 +105,10 @@ def get_parser():
return parser


@logger.catch
def workflow(*, file_template, modality, fs, source='MRI', channel=1,
output='peakdet.csv', savehistory=True, noedit=False, thresh=0.2,
measurements=ATTR_CONV.keys()):
measurements=ATTR_CONV.keys(), verbose=True):
maestroque marked this conversation as resolved.
Show resolved Hide resolved
"""
Basic workflow for physiological data

Expand Down Expand Up @@ -138,16 +139,17 @@ def workflow(*, file_template, modality, fs, source='MRI', channel=1,
Which HRV-related measurements to save from data. See ``peakdet.HRV``
for available measurements. Default: all available measurements.
"""

logger.remove(0)
logger.add(sys.stderr, backtrace=verbose, diagnose=verbose)
# output file
print('OUTPUT FILE:\t\t{}\n'.format(output))
logger.info('OUTPUT FILE:\t\t{}\n'.format(output))
# grab files from file template
print('FILE TEMPLATE:\t{}\n'.format(file_template))
logger.info('FILE TEMPLATE:\t{}\n'.format(file_template))
files = glob.glob(file_template, recursive=True)

# convert measurements to peakdet.HRV attribute friendly names
try:
print('REQUESTED MEASUREMENTS: {}\n'.format(', '.join(measurements)))
logger.info('REQUESTED MEASUREMENTS: {}\n'.format(', '.join(measurements)))
except TypeError:
raise TypeError('It looks like you didn\'t select any of the options '
'specifying desired output measurements. Please '
Expand All @@ -166,10 +168,10 @@ def workflow(*, file_template, modality, fs, source='MRI', channel=1,
# requested on command line, warn and use existing measurements so
# as not to totally fork up existing file
if eheader != head:
warnings.warn('Desired output file already exists and requested '
'measurements do not match with measurements in '
'existing output file. Using the pre-existing '
'measurements, instead.')
logger.warning('Desired output file already exists and requested '
'measurements do not match with measurements in '
'existing output file. Using the pre-existing '
'measurements, instead.')
measurements = [f.strip() for f in eheader.split(',')[1:]]
head = ''
# if output file doesn't exist, nbd
Expand All @@ -181,7 +183,7 @@ def workflow(*, file_template, modality, fs, source='MRI', channel=1,
# iterate through all files and do peak detection with manual editing
for fname in files:
fname = os.path.relpath(fname)
print('Currently processing {}'.format(fname))
logger.info('Currently processing {}'.format(fname))

# if we want to save history, this is the output name it would take
outname = os.path.join(os.path.dirname(fname),
Expand Down Expand Up @@ -225,6 +227,7 @@ def workflow(*, file_template, modality, fs, source='MRI', channel=1,


def main():
logger.enable("")
opts = get_parser().parse_args()
workflow(**vars(opts))

Expand Down
8 changes: 4 additions & 4 deletions peakdet/external.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
Functions for interacting with physiological data acquired by external packages
"""

import warnings
import numpy as np
from peakdet import physio, utils
from loguru import logger


@utils.make_operation(exclude=[])
Expand Down Expand Up @@ -38,9 +38,9 @@ def load_rtpeaks(fname, channel, fs):
"""

if fname.startswith('/'):
warnings.warn('Provided file seems to be an absolute path. In order '
'to ensure full reproducibility it is recommended that '
'a relative path is provided.')
logger.warning('Provided file seems to be an absolute path. In order '
'to ensure full reproducibility it is recommended that '
'a relative path is provided.')

with open(fname, 'r') as src:
header = src.readline().strip().split(',')
Expand Down
18 changes: 9 additions & 9 deletions peakdet/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

import json
import os.path as op
import warnings
import numpy as np
from peakdet import physio, utils
from loguru import logger

EXPECTED = ['data', 'fs', 'history', 'metadata']

Expand Down Expand Up @@ -64,9 +64,9 @@ def load_physio(data, *, fs=None, dtype=None, history=None,
# if we got a numpy array, load that into a Physio object
elif isinstance(data, np.ndarray):
if history is None:
warnings.warn('Loading data from a numpy array without providing a'
'history will render reproducibility functions '
'useless! Continuing anyways.')
logger.warning('Loading data from a numpy array without providing a'
'history will render reproducibility functions '
'useless! Continuing anyways.')
phys = physio.Physio(np.asarray(data, dtype=dtype), fs=fs,
history=history)
# create a new Physio object out of a provided Physio object
Expand All @@ -79,7 +79,7 @@ def load_physio(data, *, fs=None, dtype=None, history=None,
# reset sampling rate, as requested
if fs is not None and fs != phys.fs:
if not np.isnan(phys.fs):
warnings.warn('Provided sampling rate does not match loaded rate. '
logger.warning('Provided sampling rate does not match loaded rate. '
'Resetting loaded sampling rate {} to provided {}'
.format(phys.fs, fs))
phys._fs = fs
Expand Down Expand Up @@ -148,7 +148,7 @@ def load_history(file, verbose=False):
data = None
for (func, kwargs) in history:
if verbose:
print('Rerunning {}'.format(func))
logger.info('Rerunning {}'.format(func))
# loading functions don't have `data` input because it should be the
# first thing in `history` (when the data was originally loaded!).
# for safety, check if `data` is None; someone could have potentially
Expand Down Expand Up @@ -194,9 +194,9 @@ def save_history(file, data):

data = check_physio(data)
if len(data.history) == 0:
warnings.warn('History of provided Physio object is empty. Saving '
'anyway, but reloading this file will result in an '
'error.')
logger.warning('History of provided Physio object is empty. Saving '
'anyway, but reloading this file will result in an '
'error.')
file += '.json' if not file.endswith('.json') else ''
with open(file, 'w') as dest:
json.dump(data.history, dest, indent=4)
Expand Down
1 change: 0 additions & 1 deletion peakdet/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from scipy import interpolate, signal
from peakdet import editor, utils


@utils.make_operation()
maestroque marked this conversation as resolved.
Show resolved Hide resolved
def filter_physio(data, cutoffs, method, *, order=3):
"""
Expand Down
2 changes: 0 additions & 2 deletions peakdet/physio.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import numpy as np



class Physio():
"""
Class to hold physiological data and relevant information
Expand Down Expand Up @@ -40,7 +39,6 @@ class Physio():
suppdata : :obj:`numpy.ndarray`
Secondary physiological waveform
"""

def __init__(self, data, fs=None, history=None, metadata=None, suppdata=None):
self._data = np.asarray(data).squeeze()
if self.data.ndim > 1:
Expand Down
10 changes: 10 additions & 0 deletions peakdet/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import inspect
import numpy as np
from peakdet import physio
from loguru import logger
import sys
maestroque marked this conversation as resolved.
Show resolved Hide resolved


def make_operation(*, exclude=None):
Expand Down Expand Up @@ -225,3 +227,11 @@ def check_troughs(data, peaks, troughs=None):
all_troughs[f] = idx

return all_troughs

def enable_logger(diagnose=True, backtrace=True):
"""
Toggles the use of the module's logger and configures it
"""
logger.enable("")
logger.remove(0)
logger.add(sys.stderr, backtrace=backtrace, diagnose=diagnose)
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
matplotlib
numpy
scipy
loguru
3 changes: 3 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,14 @@ test =
pytest-cov
%(style)s
%(nk)s
logger =
maestroque marked this conversation as resolved.
Show resolved Hide resolved
loguru
all =
%(doc)s
%(duecredit)s
%(style)s
%(test)s
%(logger)s


[options.package_data]
Expand Down