Skip to content

Commit d7e433e

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 1c7dfc3 commit d7e433e

18 files changed

+41
-87
lines changed

peakdet/_version.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=
8484
stderr=(subprocess.PIPE if hide_stderr else None),
8585
)
8686
break
87-
except EnvironmentError:
87+
except OSError:
8888
e = sys.exc_info()[1]
8989
if e.errno == errno.ENOENT:
9090
continue
@@ -147,7 +147,7 @@ def git_get_keywords(versionfile_abs):
147147
# _version.py.
148148
keywords = {}
149149
try:
150-
f = open(versionfile_abs, "r")
150+
f = open(versionfile_abs)
151151
for line in f.readlines():
152152
if line.strip().startswith("git_refnames ="):
153153
mo = re.search(r'=\s*"(.*)"', line)
@@ -162,7 +162,7 @@ def git_get_keywords(versionfile_abs):
162162
if mo:
163163
keywords["date"] = mo.group(1)
164164
f.close()
165-
except EnvironmentError:
165+
except OSError:
166166
pass
167167
return keywords
168168

peakdet/analytics.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
Functions and classes for generating analytics on physiological data
43
"""

peakdet/cli/run.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
import argparse
32
import datetime
43
import glob
@@ -53,7 +52,7 @@ def get_parser():
5352
)
5453

5554
inp_group = parser.add_argument_group(
56-
"Inputs", "Options to specify " "format of input files"
55+
"Inputs", "Options to specify format of input files"
5756
)
5857
inp_group.add_argument(
5958
"--modality",
@@ -83,7 +82,7 @@ def get_parser():
8382
)
8483

8584
out_group = parser.add_argument_group(
86-
"Outputs", "Options to specify " "format of output files"
85+
"Outputs", "Options to specify format of output files"
8786
)
8887
out_group.add_argument(
8988
"-o",
@@ -104,12 +103,12 @@ def get_parser():
104103
"-s",
105104
"--savehistory",
106105
action="store_true",
107-
help="Whether to save history of data processing " "for each file.",
106+
help="Whether to save history of data processing for each file.",
108107
)
109108

110109
edit_group = parser.add_argument_group(
111110
"Workflow arguments (optional!)",
112-
"Options to specify modifications " "to workflow",
111+
"Options to specify modifications to workflow",
113112
)
114113
edit_group.add_argument(
115114
"-n",
@@ -255,9 +254,9 @@ def workflow(
255254
)
256255

257256
# output file
258-
logger.info("OUTPUT FILE:\t\t{}".format(output))
257+
logger.info(f"OUTPUT FILE:\t\t{output}")
259258
# grab files from file template
260-
logger.info("FILE TEMPLATE:\t{}".format(file_template))
259+
logger.info(f"FILE TEMPLATE:\t{file_template}")
261260
files = glob.glob(file_template, recursive=True)
262261

263262
# convert measurements to peakdet.HRV attribute friendly names
@@ -277,7 +276,7 @@ def workflow(
277276
# check if output file exists -- if so, ensure headers will match
278277
head = "filename," + ",".join(measurements)
279278
if os.path.exists(output):
280-
with open(output, "r") as src:
279+
with open(output) as src:
281280
eheader = src.readlines()[0]
282281
# if existing output file does not have same measurements are those
283282
# requested on command line, warn and use existing measurements so
@@ -300,7 +299,7 @@ def workflow(
300299
# iterate through all files and do peak detection with manual editing
301300
for fname in files:
302301
fname = os.path.relpath(fname)
303-
logger.info("Currently processing {}".format(fname))
302+
logger.info(f"Currently processing {fname}")
304303

305304
# if we want to save history, this is the output name it would take
306305
outname = os.path.join(

peakdet/editor.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""Functions and class for performing interactive editing of physiological data."""
32

43
import functools

peakdet/external.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
Functions for interacting with physiological data acquired by external packages
43
"""
@@ -37,18 +36,17 @@ def load_rtpeaks(fname, channel, fs):
3736
data : :class:`peakdet.Physio`
3837
Loaded physiological data
3938
"""
40-
4139
if fname.startswith("/"):
4240
logger.warning(
4341
"Provided file seems to be an absolute path. In order "
4442
"to ensure full reproducibility it is recommended that "
4543
"a relative path is provided."
4644
)
4745

48-
with open(fname, "r") as src:
46+
with open(fname) as src:
4947
header = src.readline().strip().split(",")
5048

51-
col = header.index("channel{}".format(channel))
49+
col = header.index(f"channel{channel}")
5250
data = np.loadtxt(fname, usecols=col, skiprows=1, delimiter=",")
5351
phys = physio.Physio(data, fs=fs)
5452

peakdet/io.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
Functions for loading and saving data and analyses
43
"""
@@ -42,7 +41,6 @@ def load_physio(data, *, fs=None, dtype=None, history=None, allow_pickle=False):
4241
TypeError
4342
If provided `data` is unable to be loaded
4443
"""
45-
4644
# first check if the file was made with `save_physio`; otherwise, try to
4745
# load it as a plain text file and instantiate a history
4846
if isinstance(data, str):
@@ -53,13 +51,13 @@ def load_physio(data, *, fs=None, dtype=None, history=None, allow_pickle=False):
5351
inp[attr] = inp[attr].dtype.type(inp[attr])
5452
except KeyError:
5553
raise ValueError(
56-
"Provided npz file {} must have all of "
57-
"the following attributes: {}".format(data, EXPECTED)
54+
f"Provided npz file {data} must have all of "
55+
f"the following attributes: {EXPECTED}"
5856
)
5957
# fix history, which needs to be list-of-tuple
6058
if inp["history"] is not None:
6159
inp["history"] = list(map(tuple, inp["history"]))
62-
except (IOError, OSError, ValueError):
60+
except (OSError, ValueError):
6361
inp = dict(data=np.loadtxt(data), history=[utils._get_call(exclude=[])])
6462
logger.debug("Instantiating Physio object from a file")
6563
phys = physio.Physio(**inp)
@@ -81,14 +79,14 @@ def load_physio(data, *, fs=None, dtype=None, history=None, allow_pickle=False):
8179
phys = utils.new_physio_like(data, data.data, fs=fs, dtype=dtype)
8280
phys._history += [utils._get_call()]
8381
else:
84-
raise TypeError("Cannot load data of type {}".format(type(data)))
82+
raise TypeError(f"Cannot load data of type {type(data)}")
8583

8684
# reset sampling rate, as requested
8785
if fs is not None and fs != phys.fs:
8886
if not np.isnan(phys.fs):
8987
logger.warning(
9088
"Provided sampling rate does not match loaded rate. "
91-
"Resetting loaded sampling rate {} to provided {}".format(phys.fs, fs)
89+
f"Resetting loaded sampling rate {phys.fs} to provided {fs}"
9290
)
9391
phys._fs = fs
9492
# coerce datatype, if needed
@@ -114,7 +112,6 @@ def save_physio(fname, data):
114112
fname : str
115113
Full filepath to saved output
116114
"""
117-
118115
from peakdet.utils import check_physio
119116

120117
data = check_physio(data)
@@ -145,21 +142,20 @@ def load_history(file, verbose=False):
145142
file : str
146143
Full filepath to saved output
147144
"""
148-
149145
# import inside function for safety!
150146
# we'll likely be replaying some functions from within this module...
151147
import peakdet
152148

153149
# grab history from provided JSON file
154-
with open(file, "r") as src:
150+
with open(file) as src:
155151
history = json.load(src)
156152

157153
# replay history from beginning and return resultant Physio object
158154
logger.info(f"Replaying history from {file}")
159155
data = None
160156
for func, kwargs in history:
161157
if verbose:
162-
logger.info("Rerunning {}".format(func))
158+
logger.info(f"Rerunning {func}")
163159
# loading functions don't have `data` input because it should be the
164160
# first thing in `history` (when the data was originally loaded!).
165161
# for safety, check if `data` is None; someone could have potentially
@@ -205,7 +201,6 @@ def save_history(file, data):
205201
file : str
206202
Full filepath to saved output
207203
"""
208-
209204
from peakdet.utils import check_physio
210205

211206
data = check_physio(data)

peakdet/modalities.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
31
import numpy as np
42

53

peakdet/operations.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
Functions for processing and interpreting physiological data
43
"""
@@ -35,28 +34,25 @@ def filter_physio(data, cutoffs, method, *, order=3):
3534
filtered : :class:`peakdet.Physio`
3635
Filtered input `data`
3736
"""
38-
3937
_valid_methods = ["lowpass", "highpass", "bandpass", "bandstop"]
4038

4139
data = utils.check_physio(data, ensure_fs=True)
4240
if method not in _valid_methods:
4341
raise ValueError(
44-
"Provided method {} is not permitted; must be in {}.".format(
45-
method, _valid_methods
46-
)
42+
f"Provided method {method} is not permitted; must be in {_valid_methods}."
4743
)
4844

4945
cutoffs = np.array(cutoffs)
5046
if method in ["lowpass", "highpass"] and cutoffs.size != 1:
51-
raise ValueError("Cutoffs must be length 1 when using {} filter".format(method))
47+
raise ValueError(f"Cutoffs must be length 1 when using {method} filter")
5248
elif method in ["bandpass", "bandstop"] and cutoffs.size != 2:
53-
raise ValueError("Cutoffs must be length 2 when using {} filter".format(method))
49+
raise ValueError(f"Cutoffs must be length 2 when using {method} filter")
5450

5551
nyq_cutoff = cutoffs / (data.fs * 0.5)
5652
if np.any(nyq_cutoff > 1):
5753
raise ValueError(
58-
"Provided cutoffs {} are outside of the Nyquist "
59-
"frequency for input data with sampling rate {}.".format(cutoffs, data.fs)
54+
f"Provided cutoffs {cutoffs} are outside of the Nyquist "
55+
f"frequency for input data with sampling rate {data.fs}."
6056
)
6157

6258
if method in ["lowpass", "highpass"]:
@@ -94,7 +90,6 @@ def interpolate_physio(data, target_fs, *, kind="cubic"):
9490
interp : :class:`peakdet.Physio`
9591
Interpolated input `data`
9692
"""
97-
9893
data = utils.check_physio(data, ensure_fs=True)
9994

10095
factor = target_fs / data.fs
@@ -139,7 +134,6 @@ def peakfind_physio(data, *, thresh=0.2, dist=None):
139134
peaks : :class:`peakdet.Physio`
140135
Input `data` with detected peaks and troughs
141136
"""
142-
143137
ensure_fs = True if dist is None else False
144138
data = utils.check_physio(data, ensure_fs=ensure_fs, copy=True)
145139
# first pass peak detection to get approximate distance between peaks
@@ -252,7 +246,6 @@ def edit_physio(data):
252246
edited : :class:`peakdet.Physio`
253247
Input `data` with manual edits
254248
"""
255-
256249
data = utils.check_physio(data, ensure_fs=True)
257250

258251
# no point in manual edits if peaks/troughs aren't defined

peakdet/physio.py

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
Helper class for holding physiological data and associated metadata information
43
"""
@@ -45,27 +44,21 @@ def __init__(self, data, fs=None, history=None, metadata=None, suppdata=None):
4544
logger.debug("Initializing new Physio object")
4645
self._data = np.asarray(data).squeeze()
4746
if self.data.ndim > 1:
48-
raise ValueError(
49-
"Provided data dimensionality {} > 1.".format(self.data.ndim)
50-
)
47+
raise ValueError(f"Provided data dimensionality {self.data.ndim} > 1.")
5148
if not np.issubdtype(self.data.dtype, np.number):
52-
raise ValueError(
53-
"Provided data of type {} is not numeric.".format(self.data.dtype)
54-
)
49+
raise ValueError(f"Provided data of type {self.data.dtype} is not numeric.")
5550
self._fs = np.float64(fs)
5651
self._history = [] if history is None else history
5752
if not isinstance(self._history, list) or any(
5853
[not isinstance(f, tuple) for f in self._history]
5954
):
6055
raise TypeError(
61-
"Provided history {} must be a list-of-tuples. "
62-
"Please check inputs.".format(history)
56+
f"Provided history {history} must be a list-of-tuples. "
57+
"Please check inputs."
6358
)
6459
if metadata is not None:
6560
if not isinstance(metadata, dict):
66-
raise TypeError(
67-
"Provided metadata {} must be dict-like.".format(metadata)
68-
)
61+
raise TypeError(f"Provided metadata {metadata} must be dict-like.")
6962
for k in ["peaks", "troughs", "reject"]:
7063
metadata.setdefault(k, np.empty(0, dtype=int))
7164
if not isinstance(metadata.get(k), np.ndarray):
@@ -95,9 +88,7 @@ def __len__(self):
9588
return len(self.data)
9689

9790
def __str__(self):
98-
return "{name}(size={size}, fs={fs})".format(
99-
name=self.__class__.__name__, size=self.data.size, fs=self.fs
100-
)
91+
return f"{self.__class__.__name__}(size={self.data.size}, fs={self.fs})"
10192

10293
__repr__ = __str__
10394

peakdet/tests/test_analytics.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# -*- coding: utf-8 -*-
2-
31
from peakdet import analytics
42
from peakdet.tests.utils import get_peak_data
53

0 commit comments

Comments
 (0)