def _downsample(a, by, fnc=nanmean): """ visible: False desc: Downsamples a single array. """ # Resize the array so that its length is a multiple of by a = a[:by * (a.shape[0] // by)] return fnc(a.reshape(-1, by), axis=1)
def threshold(series, fnc, min_length=1): """ desc: | Finds samples that satisfy some threshold criterion for a given period. __Example:__ %-- python: | import numpy as np from matplotlib import pyplot as plt from datamatrix import DataMatrix, SeriesColumn, series LENGTH = 1 # Number of rows DEPTH = 100 # Depth (or length) of SeriesColumns sinewave = np.sin(np.linspace(0, 2*np.pi, DEPTH)) dm = DataMatrix(length=LENGTH) # First create five identical rows with a sinewave dm.y = SeriesColumn(depth=DEPTH) dm.y.setallrows(sinewave) # And also a bit of random jitter dm.y += np.random.random( (LENGTH, DEPTH) ) # Threshold the signal by > 0 for at least 10 samples dm.t = series.threshold(dm.y, fnc=lambda y: y > 0, min_length=10) plt.clf() # Mark the thresholded signal plt.fill_between(np.arange(DEPTH), dm.t[0], color='black', alpha=.25) plt.plot(dm.y.plottable) plt.savefig('content/pages/img/series/threshold.png') print(dm) --% %-- figure: source: threshold.png id: FigThreshold --% arguments: series: desc: A signal to threshold. type: SeriesColumn fnc: desc: A function that takes a single value and returns True if this value exceeds a threshold, and False otherwise. type: FunctionType keywords: min_length: desc: The minimum number of samples for which `fnc` must return True. type: int returns: desc: A series where 0 indicates below threshold, and 1 indicates above threshold. type: SeriesColumn """ threshold_series = _SeriesColumn(series._datamatrix, series.depth) threshold_series[:] = 0 # First walk through all rows for i, trace in enumerate(series): # Then walk through all samples within a row nhit = 0 for j, val in enumerate(trace): hit = fnc(val) if hit: nhit += 1 continue if nhit >= min_length: threshold_series[i, j - nhit:j] = 1 nhit = 0 if nhit >= min_length: threshold_series[i, j - nhit + 1:j + 1] = 1 return threshold_series