Skip to content

Commit ea89a78

Browse files
committed
cq: update warnings with automatic stack_level
1 parent bc39954 commit ea89a78

20 files changed

+118
-52
lines changed

lumicks/pylake/detail/confocal.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from .image import reconstruct_image, reconstruct_image_sum
1010
from .mixin import PhotonCounts, ExcitationLaserPower
1111
from .plotting import parse_color_channel
12-
from .utilities import method_cache, could_sum_overflow
12+
from .utilities import method_cache, find_stack_level, could_sum_overflow
1313
from ..adjustments import no_adjustment
1414
from .imaging_mixins import TiffExport
1515

@@ -350,7 +350,8 @@ def _tiff_image_metadata(self) -> dict:
350350
except NotImplementedError:
351351
warnings.warn(
352352
f"Pixel times are not defined for this {self.__class__.__name__}. "
353-
"The corresponding metadata in the output file is set to `None`."
353+
"The corresponding metadata in the output file is set to `None`.",
354+
stacklevel=find_stack_level(),
354355
)
355356
pixel_time_seconds = None
356357

lumicks/pylake/detail/image.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
import numpy as np
66

7+
from .utilities import find_stack_level
8+
79

810
class InfowaveCode(enum.IntEnum):
911
discard = 0 # this data sample does not contain useful information
@@ -197,7 +199,9 @@ def histogram_rows(image, pixels_per_bin, pixel_width):
197199
remainder = n_rows % pixels_per_bin
198200
if remainder != 0:
199201
warnings.warn(
200-
f"{n_rows} pixels is not divisible by {pixels_per_bin}, final bin only contains {remainder} pixels"
202+
f"{n_rows} pixels is not divisible by {pixels_per_bin}, final bin only contains "
203+
f"{remainder} pixels",
204+
stacklevel=find_stack_level(),
201205
)
202206
pad = np.zeros((pixels_per_bin - remainder, image.shape[1]))
203207
image = np.vstack((image, pad))

lumicks/pylake/detail/plotting.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import warnings
22

33
from ..adjustments import no_adjustment
4+
from ..detail.utilities import find_stack_level
45

56

67
def get_axes(axes=None, image_handle=None):
@@ -36,8 +37,9 @@ def parse_color_channel(channel):
3637
warnings.warn(
3738
DeprecationWarning(
3839
"In future versions, the `channel` argument will be restricted to lowercase "
39-
f"letters only. Use '{channel}' instead of '{input_channel}'."
40-
)
40+
f"letters only. Use '{channel}' instead of '{input_channel}'.",
41+
),
42+
stacklevel=find_stack_level(),
4143
)
4244

4345
# check rgb order

lumicks/pylake/detail/utilities.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import math
2-
import contextlib
3-
import pathlib
42
import inspect
3+
import pathlib
4+
import contextlib
55

66
import numpy as np
77
import cachetools

lumicks/pylake/detail/widefield.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import tifffile
1010

1111
from .plotting import parse_color_channel
12+
from .utilities import find_stack_level
1213
from ..adjustments import no_adjustment
1314

1415

@@ -205,7 +206,7 @@ def __init__(self, tiff_files, align_requested, roi=None, tether=None):
205206
# warn on file open if alignment is requested, but not possible
206207
# stacklevel=4 corresponds to ImageStack.__init__()
207208
if self._description._alignment.has_problem:
208-
warnings.warn(self._description._alignment.status.value, stacklevel=4)
209+
warnings.warn(self._description._alignment.status.value, stacklevel=find_stack_level())
209210

210211
if roi is None:
211212
self._roi = Roi(0, self._description.width, 0, self._description.height)

lumicks/pylake/file.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from .calibration import ForceCalibration
1515
from .detail.mixin import Force, PhotonCounts, DownsampledFD, PhotonTimeTags, BaselineCorrectedForce
1616
from .detail.h5_helper import write_h5
17+
from .detail.utilities import find_stack_level
1718

1819
__all__ = ["File"]
1920

@@ -276,7 +277,7 @@ def try_from_dataset(*args):
276277
try:
277278
return cls.from_dataset(*args)
278279
except Exception as e:
279-
warnings.warn(e.args[0])
280+
warnings.warn(e.args[0], stacklevel=find_stack_level())
280281
return None
281282

282283
if field not in self.h5:

lumicks/pylake/fitting/detail/derivative_manipulation.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import numpy as np
44
import scipy
55

6+
from ...detail.utilities import find_stack_level
7+
68

79
def numerical_diff(fn, x, dx=1e-6):
810
return (fn(x + dx) - fn(x - dx)) / (2.0 * dx)
@@ -126,7 +128,8 @@ def invert_function_interpolation(
126128
except Exception as e:
127129
warnings.warn(
128130
f"Interpolation failed. Cause: {e}. Falling back to brute force evaluation. "
129-
f"Results should be fine, but slower."
131+
f"Results should be fine, but slower.",
132+
stacklevel=find_stack_level(),
130133
)
131134
result[interpolated_idx] = manual_inversion(d[interpolated_idx], initial)
132135
else:

lumicks/pylake/fitting/detail/model_implementation.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from .utilities import latex_frac, latex_sqrt, solve_formatter, solve_formatter_tex
66
from ..parameters import Parameter
7+
from ...detail.utilities import find_stack_level
78
from .derivative_manipulation import invert_function, invert_jacobian, invert_function_interpolation
89

910

@@ -103,8 +104,10 @@ def wlc_marko_siggia_force(d, Lp, Lc, kT):
103104

104105
if np.any(d > Lc):
105106
warnings.warn(
106-
"Marko Siggia model is only defined properly up to the contour length (d = Lc)",
107-
RuntimeWarning,
107+
RuntimeWarning(
108+
"Marko Siggia model is only defined properly up to the contour length (d = Lc)"
109+
),
110+
stacklevel=find_stack_level(),
108111
)
109112

110113
d_div_Lc = d / Lc

lumicks/pylake/force_calibration/power_spectrum.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import numpy as np
66

7-
from lumicks.pylake.detail.utilities import downsample
7+
from lumicks.pylake.detail.utilities import downsample, find_stack_level
88

99

1010
class PowerSpectrum:
@@ -52,7 +52,10 @@ def squared_fft(d):
5252
int(np.round(window_seconds * sample_rate)) if window_seconds else len(data)
5353
)
5454
if num_points_per_window > len(data):
55-
warnings.warn(RuntimeWarning("Longer window than data duration: not using windowing."))
55+
warnings.warn(
56+
RuntimeWarning("Longer window than data duration: not using windowing."),
57+
stacklevel=find_stack_level(),
58+
)
5659
num_points_per_window = len(data)
5760

5861
squared_fft_chunks = [

lumicks/pylake/force_calibration/touchdown.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import numpy as np
55
import scipy
66

7-
from lumicks.pylake.detail.utilities import downsample
7+
from lumicks.pylake.detail.utilities import downsample, find_stack_level
88

99

1010
def mack_model(
@@ -82,7 +82,8 @@ def f_test(sse_restricted, sse_unrestricted, num_data, num_pars_difference, num_
8282
RuntimeWarning(
8383
"Denominator in F-Test is zero. "
8484
"This may be caused by using noise-free data or fewer than 4 data points."
85-
)
85+
),
86+
stacklevel=find_stack_level(),
8687
)
8788
return 0.0
8889
else:
@@ -310,15 +311,17 @@ def touchdown(
310311
RuntimeWarning(
311312
"Insufficient data available to reliably fit touchdown curve. We need at least two "
312313
"oscillations to reliably fit the interference pattern."
313-
)
314+
),
315+
stacklevel=find_stack_level(),
314316
)
315317
focal_shift = None
316318

317319
if p_value > maximum_p_value:
318320
warnings.warn(
319321
RuntimeWarning(
320322
"Surface detection failed (piecewise linear fit not better than linear fit)"
321-
)
323+
),
324+
stacklevel=find_stack_level(),
322325
)
323326
surface_position = None
324327

lumicks/pylake/group.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import warnings
22

33
from .channel import channel_class
4+
from .detail.utilities import find_stack_level
45

56

67
class Group:
@@ -34,9 +35,11 @@ def __getitem__(self, item):
3435
redirect_location, redirect_class = self._lk_file.redirect_list.get(item_type, (None, None))
3536
if redirect_location and not redirect_class:
3637
warnings.warn(
37-
f"Direct access to this field is deprecated. Use file.{redirect_location} "
38-
"instead. In case raw access is needed, go through the fn.h5 directly.",
39-
FutureWarning,
38+
FutureWarning(
39+
f"Direct access to this field is deprecated. Use file.{redirect_location} "
40+
"instead. In case raw access is needed, go through the fn.h5 directly.",
41+
),
42+
stacklevel=find_stack_level(),
4043
)
4144

4245
if type(thing) is h5py.Group:

lumicks/pylake/image_stack.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from .adjustments import no_adjustment
1111
from .detail.image import make_image_title
1212
from .detail.plotting import get_axes, show_image
13+
from .detail.utilities import find_stack_level
1314
from .detail.widefield import TiffStack, _frame_timestamps_from_exposure_timestamps
1415
from .detail.imaging_mixins import FrameIndex, TiffExport, VideoExport
1516

@@ -658,7 +659,8 @@ def frame_timestamp_ranges(self, *, include_dead_time=False):
658659
"lag behind. This means that when you average data over the frame, some frames "
659660
"after the switch may take an incorrect exposure time into account in the "
660661
"averaging."
661-
)
662+
),
663+
stacklevel=find_stack_level(),
662664
)
663665

664666
return frame_timestamps

lumicks/pylake/kymo.py

+9-4
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from .detail.confocal import ScanAxis, ScanMetaData, ConfocalImage
1616
from .detail.plotting import get_axes, show_image
1717
from .detail.timeindex import to_timestamp
18-
from .detail.utilities import method_cache
18+
from .detail.utilities import method_cache, find_stack_level
1919
from .detail.bead_cropping import find_beads_template, find_beads_brightness
2020

2121

@@ -279,8 +279,10 @@ def _fix_incorrect_start(self):
279279
self.start = seek_timestamp_next_line(self.infowave[self.start :])
280280
self._cache = {}
281281
warnings.warn(
282-
"Start of the kymograph was truncated. Omitting the truncated first line.",
283-
RuntimeWarning,
282+
RuntimeWarning(
283+
"Start of the kymograph was truncated. Omitting the truncated first line."
284+
),
285+
stacklevel=find_stack_level(),
284286
)
285287

286288
def _to_spatial(self, data):
@@ -475,7 +477,10 @@ def set_aspect_ratio(axis, ar):
475477
)
476478

477479
warnings.warn(
478-
RuntimeWarning("Using downsampled force since high frequency force is unavailable.")
480+
RuntimeWarning(
481+
"Using downsampled force since high frequency force is unavailable."
482+
),
483+
stacklevel=find_stack_level(),
479484
)
480485

481486
time_ranges = self.line_timestamp_ranges(include_dead_time=False)

lumicks/pylake/kymotracker/detail/msd_estimation.py

+15-6
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import numpy as np
66
import numpy.typing as npt
77

8+
from ...detail.utilities import find_stack_level
9+
810

911
@dataclass(frozen=True)
1012
class DiffusionEstimate:
@@ -472,7 +474,10 @@ def _diffusion_gls(lag_idx, mean_squared_displacements, num_points, tolerance=1e
472474

473475
def fallback(warning_message):
474476
"""Fallback method if the GLS fails"""
475-
warnings.warn(RuntimeWarning(f"{warning_message} Reverting to two-point OLS."))
477+
warnings.warn(
478+
RuntimeWarning(f"{warning_message} Reverting to two-point OLS."),
479+
stacklevel=find_stack_level(),
480+
)
476481
return _diffusion_ols(lag_idx[:2], mean_squared_displacements[:2], num_points)
477482

478483
# Since the covariance matrix depends on the parameters for the intercept and slope, we obtain
@@ -600,7 +605,7 @@ def estimate_diffusion_constant_simple(
600605
"`help(lk.refine_tracks_centroid)` or `help(lk.refine_tracks_gaussian)` for "
601606
"more information."
602607
),
603-
stacklevel=2,
608+
stacklevel=find_stack_level(),
604609
)
605610

606611
frame_lags, msd = calculate_msd(frame_idx, coordinate, max_lag)
@@ -718,7 +723,8 @@ def determine_optimal_points(frame_idx, coordinate, max_iterations=100):
718723
RuntimeWarning(
719724
"Your tracks have missing frames. Note that this can lead to a suboptimal "
720725
"estimate of the optimal number of lags when using OLS."
721-
)
726+
),
727+
stacklevel=find_stack_level(),
722728
)
723729

724730
num_slope = max(2, len(coordinate) // 10) # Need at least two points for a linear regression!
@@ -750,7 +756,8 @@ def determine_optimal_points(frame_idx, coordinate, max_iterations=100):
750756
return num_slope, num_intercept
751757

752758
warnings.warn(
753-
RuntimeWarning("Warning, maximum number of iterations exceeded. Returning best solution.")
759+
RuntimeWarning("Warning, maximum number of iterations exceeded. Returning best solution."),
760+
stacklevel=find_stack_level(),
754761
)
755762
return num_slope, num_intercept
756763

@@ -1129,7 +1136,8 @@ def _determine_optimal_points_ensemble(frame_lags, msds, n_coord, max_iterations
11291136
return num_slope
11301137

11311138
warnings.warn(
1132-
RuntimeWarning("Warning, maximum number of iterations exceeded. Returning best solution.")
1139+
RuntimeWarning("Warning, maximum number of iterations exceeded. Returning best solution."),
1140+
stacklevel=find_stack_level(),
11331141
)
11341142

11351143
return num_slope
@@ -1143,7 +1151,8 @@ def ensemble_ols(kymotracks, max_lag):
11431151
warnings.warn(
11441152
RuntimeWarning(
11451153
"Your tracks have missing frames. Note that this can lead to a suboptimal estimates"
1146-
)
1154+
),
1155+
stacklevel=find_stack_level(),
11471156
)
11481157

11491158
optimal_lags = (

0 commit comments

Comments
 (0)