/ concept-collection / benchcompress
Sign in
concept-collection / benchcompress
benchcompress / zia_benchmark / src / zia / _analysis.py
61 lines · 1.7 KBBlameHistoryRaw
1import numpy as np
2from ._filters import highpass_filter
5def estimate_noise_level(array: np.ndarray, *, sampling_frequency: float) -> float:
6 """Estimate the noise level of a signal using the median absolute deviation.
8 Args:
9 array: Input signal array
10 sampling_frequency: Sampling frequency in Hz
12 Returns:
13 Estimated noise level
14 """
15 array_filtered = highpass_filter(
16 array, sampling_frequency=sampling_frequency, lowcut=300
17 )
18 MAD = float(
19 np.median(np.abs(array_filtered.ravel() - np.median(array_filtered.ravel())))
20 / 0.6745
21 )
22 return MAD
25def compute_entropy_per_sample(array: np.ndarray) -> float:
26 """Compute the entropy per sample of a signal.
28 Args:
29 array: Input signal array
31 Returns:
32 Entropy per sample in bits
33 """
34 _, counts = np.unique(array, return_counts=True)
35 p = counts / len(array)
36 return float(-np.sum(p * np.log2(p)))
39from typing import Callable
41def linear_fit(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, Callable[[np.ndarray], np.ndarray]]:
42 """Perform linear fit with constant term.
44 Args:
45 x: Input array of shape (N, M-1) containing M-1 predictors for N samples
46 y: Target array of shape (N,) containing values to predict
48 Returns:
49 Tuple containing:
50 - coefficients array of shape (M,)
51 - prediction function that takes x_new and returns predictions
52 """
53 from numpy.linalg import lstsq
54 X = np.column_stack([x, np.ones(len(x))])
55 coeffs = lstsq(X, y, rcond=None)[0]
57 def predict(x_new: np.ndarray) -> np.ndarray:
58 X_new = np.column_stack([x_new, np.ones(len(x_new))])
59 return np.dot(X_new, coeffs)
61 return coeffs, predict
moveopenescclose