From a39fc0d53c5e5c7d79d7fcb40d9c72fa0fac9d5b Mon Sep 17 00:00:00 2001 From: Tomas Lenc Date: Wed, 24 Nov 2021 10:54:13 +0100 Subject: [PATCH] fix mirrorpad buffer when too long Adding a try/except to mirrorpad_1d() so that when the arr has less elements than requested buffer, a warning is issued and the buffer size is fixed to be equal to the size of arr (i.e. the longest possible). --- phys2denoise/metrics/utils.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/phys2denoise/metrics/utils.py b/phys2denoise/metrics/utils.py index 7426a5c..7fb7a23 100644 --- a/phys2denoise/metrics/utils.py +++ b/phys2denoise/metrics/utils.py @@ -1,5 +1,6 @@ """Miscellaneous utility functions for metric calculation.""" import logging +import warnings import numpy as np @@ -45,11 +46,23 @@ def mirrorpad_1d(arr, buffer=250): ------- arr_out """ + mirror = np.flip(arr, axis=0) - idx = range(arr.shape[0] - buffer, arr.shape[0]) - pre_mirror = np.take(mirror, idx, axis=0) - idx = range(0, buffer) - post_mirror = np.take(mirror, idx, axis=0) + # If buffer is too long, fix it and issue a warning + try: + idx = range(arr.shape[0] - buffer, arr.shape[0]) + pre_mirror = np.take(mirror, idx, axis=0) + idx = range(0, buffer) + post_mirror = np.take(mirror, idx, axis=0) + except IndexError: + fixed_buffer = len(arr) + warnings.warn('Requested buffer size ({}) is longer than arr length ({}). Fixing buffer size to {}.'.format( + buffer, len(arr), fixed_buffer + )) + idx = range(arr.shape[0] - fixed_buffer, arr.shape[0]) + pre_mirror = np.take(mirror, idx, axis=0) + idx = range(0, fixed_buffer) + post_mirror = np.take(mirror, idx, axis=0) arr_out = np.concatenate((pre_mirror, arr, post_mirror), axis=0) return arr_out