pimfdocumentation

Intrinsic multiscale filtering

Decompose a one-dimensional signal into coarse-to-fine components using a weighted mean or a robust fit.

y=S1 + S2 + ··· + SK+rK+1 observationcomponents, coarse to fineremaining residual

Each stage smooths what remains of the signal, extracts that component, and passes the residual to the next stage.

Install & quickstart

pip install pimf
import numpy as np
from pimf import IMF
from pimf.contrasts import SmoothAbs
from pimf.kernels import epanechnikov

t = np.arange(1000) / 1000
rng = np.random.default_rng(0)
y = np.sin(2 * np.pi * t) + rng.normal(0, 0.1, len(t))

method = IMF(contrast=SmoothAbs(H=0.2), kernel=epanechnikov)
result = method.decompose(y, h1=0.25, a=np.sqrt(2), k_max=8)

result.imfs      # eight components, each with 1,000 samples
result.residual  # what remains after extracting them

IMF() uses a weighted mean with the squared-triangular kernel. Reuse an object with a different signal or schedule:

linear = IMF().decompose(y)
second_result = method.decompose(y, h1=0.15, k_max=5)

Reading the result

AttributeWhat it contains
result.imfsA (K, n) array of components, coarsest first.
result.residualThe final (n,) residual, separate from the component count.
result.reconstructionimfs.sum(axis=0) + residual.
result.bandwidthsThe normalized half-width used at each stage.
result.window_sizesThe actual odd support sizes, in samples.
result.stagesPer-stage stage, window_size, bandwidth, iterations, final_max_delta, converged and unconverged_windows. Also includes bisection_fallbacks and max_abs_score.

Sum selected components to keep particular scales. Adding every component and the residual reconstructs the original signal, including its noise.

unfinished = [stage.stage for stage in result.stages if not stage.converged]
coarse_signal = result.imfs[:2].sum(axis=0)

Stage diagnostics

StageInfo fieldMeaning
stageStage number, starting at one.
window_sizeOdd support size in samples.
bandwidthNormalized window half-width.
iterationsMaximum iteration count across windows or GD chunks.
final_max_deltaLargest final absolute update, propagating NaN across workers.
convergedWhether unconverged_windows is zero.
unconverged_windowsGD rows failing their chunk's final update threshold, or Newton rows still active at the cap. Non-finite Newton scores or estimates remain unconverged. Counts sum across workers.
bisection_fallbacksTotal Newton bisections, including both flat-boundary searches; zero for GD and direct fits.
max_abs_scoreLargest absolute normalized weighted score. GD uses the last evaluated iterate, before the final update; Newton uses the returned estimates. Maxima across workers propagate NaN.

GD reports max_abs_score from the last evaluated iterate, before the final update, without an extra score pass. Its updates, stopping iterations and final deltas are unchanged. Direct fits report one iteration, zero unconverged windows, and NaN for final_max_delta and max_abs_score.

Window schedule

A bandwidth h sets how far a window reaches on each side, as a fraction of the signal length. With 1,000 samples, h1=0.25 reaches 250 samples each way: a 501-sample window.

hk+1 = hk / a
ArgumentDefaultMeaning
h10.25First half-width, in (0, 0.5]. The default covers about half the samples.
asqrt(2)Divide the bandwidth by this factor after each stage. Must exceed one. Larger values skip more intermediate scales.
k_max8Maximum number of components. A positive integer, or None when h_min is supplied.
h_minNoneOptional minimum half-width in (0, h1], inclusive.
window_sizesNoneAlternative explicit sequence of positive odd sample counts.

Stop after k_max components, before the next bandwidth falls below h_min, or after a window shrinks to one sample. The result may therefore contain fewer than k_max components.

# A fixed maximum number of scales.
four_scales = method.decompose(y, h1=0.2, a=2, k_max=4)

# Bandwidths: 0.25, 0.125, 0.0625.
to_minimum = method.decompose(y, a=2, k_max=None, h_min=0.0625)

# Specify window sizes in samples.
explicit = method.decompose(y, window_sizes=[151, 75, 31])

window_sizes replaces the generated schedule. Use positive odd integers and leave the other schedule arguments at their defaults.

Kernels

The kernel controls how much each sample in a window contributes to the fit. Weights sum to one.

from pimf.kernels import epanechnikov, squared_triangle, triangle, uniform

weighted_mean = IMF(kernel=epanechnikov).decompose(y)
weights = epanechnikov.weights(31)
KernelProfile on [−1, 1]How it weights the window
squared_triangle¾ (1 − |u|)²Concentrates weight near the center more strongly than triangle. Default.
epanechnikov¾ (1 − u²)Gives samples away from the center more relative weight than triangle, tapering to zero at the edges.
triangle1 − |u|Decreases weight linearly from the center to zero at the edges.
uniform½Gives every sample inside the window equal weight.

Contrasts

The contrast controls how the fit responds to differences in sample values, including outliers.

Quadratic()

Computes a weighted mean directly. A large spike can pull the fitted value toward it.

SmoothAbs(H)

Limits the influence of large differences. Smaller H gives a more median-like fit; larger H moves it toward the weighted mean.

from pimf.contrasts import Quadratic, SmoothAbs

linear_method = IMF(contrast=Quadratic())
robust_method = IMF(contrast=SmoothAbs(H=0.2))

H must be finite and positive, in the same units as your sample values. For noise with standard deviation 0.1, H=0.2 is a starting point. Unlike h1, it changes outlier sensitivity, not window size.

Lookup evaluation

By default, SmoothAbs(H) interpolates precomputed values on a uniform grid to approximate the loss and score. Results can differ slightly from direct evaluation. Use SmoothAbs(H, lookup=False) to calculate the functions directly.

Boundaries & convergence

Near either end, a window extends past the available samples. boundary determines which values fill that missing part.

BoundaryHow values outside the signal are filled
"wrap"Takes values from the opposite end, joining the signal into a loop. Use when the ends represent adjacent parts of a repeating cycle. Default.
"reflect"Mirrors the interior values without repeating the endpoint. Each end uses its own nearby samples instead of values from the opposite end.
"edge"Repeats the nearest endpoint value, extending the signal as a constant on each side.

For [1, 2, 3, 4], adding two samples on each side gives:

wrap:     3 4 | 1 2 3 4 | 1 2
reflect:  3 2 | 1 2 3 4 | 3 2
edge:     1 1 | 1 2 3 4 | 4 4

These choices first affect fits near the ends. Those differences can propagate into later components.

Solver accuracy

Robust fits use an iterative solver. The default solver="gd" preserves the research gradient-descent updates, with max_iter=60 and tol=1e-6. A small GD update does not bound the distance to the score root, especially for outliers and separated clusters.

careful = IMF(
    contrast=SmoothAbs(H=0.2),
    kernel=epanechnikov,
    boundary="reflect",
    max_iter=200,
    tol=1e-8,
)
careful_result = careful.decompose(y, k_max=6)

Check stage.converged: False means the stage hit max_iter with unconverged windows. Increase max_iter to allow more work, or increase tol to accept lower accuracy. This is separate from k_max, which limits the number of components.

By default, each stage that hits this cap with unconverged windows emits one RuntimeWarning naming the stage number, window size and total number of unconverged rows across workers. Set IMF(..., on_unconverged="raise") to raise RuntimeError, or on_unconverged="ignore" to stay silent. Invalid policies raise ValueError.

The GD research iteration and its whole-chunk stopping rule are preserved to keep existing numerical results. Each row's final update uses the same threshold as the stop test, tol * (1 + max(abs(x_chunk))), evaluated at the chunk's final estimates. The count ignores NaNs in the maximum so one NaN row does not mark finite rows unconverged; the research stop test is unchanged. For GD, a small update and converged=True do not bound distance to the score root. Non-finite updates also count as unconverged. Exact reconstruction does not prove that the components converged.

Long schedules and repeated decompositions can emit many per-stage warnings. For batch runs, set on_unconverged="ignore" and inspect StageInfo.converged and unconverged_windows, or use a Python warnings filter:

batch = IMF(SmoothAbs(0.2), on_unconverged="ignore").decompose(y)
unfinished_counts = [stage.unconverged_windows for stage in batch.stages]

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore", message=r"Stage .* windows? did not converge", category=RuntimeWarning)
    filtered = IMF(SmoothAbs(0.2)).decompose(y)

Safeguarded Newton

newton = IMF(SmoothAbs(H=0.2), solver="newton")
newton_result = newton.decompose(y)
unfinished_windows = sum(stage.unconverged_windows for stage in newton_result.stages)

Newton defaults to max_iter=100 and tol=1e-12. Explicit values override these defaults. Each window starts at its weighted mean, switching to a weighted median if the initial score slope is zero. A constant window finishes immediately without probes. The bracket spans the minimum and maximum samples having nonzero weight. The solver bisects if a Newton candidate is non-finite, leaves the bracket, or fails to reduce the step below half the step before last. Wide brackets bisect the ordered float64 values, then use arithmetic midpoints near the root. Each ordered midpoint halves the representable range, bounding wide-bracket searches to at most 64 such halvings. Newton steps and positional refinement share the iteration cap. A small step alone cannot stop a row: the scores at x ± tol * (1 + abs(x)) must bracket a root. A narrow bracket also finishes a row when its width is at most tol * (1 + max(abs(lo), abs(hi))).

Use Newton when robust GD fits take too long to reach the root. Its cost depends on the signal, kernel and contrast; compare both solvers on your data. Newton uses pure NumPy and solves the same weighted score equation as GD. Differences beyond stopping roundoff occur where GD has not reached that root, including some fits marked converged by GD's small-update test. When the score is exactly zero on an interval in either lookup mode, Newton bisects to locate both boundaries and returns their midpoint. The boundary searches stop at tol * (1 + max(abs(edges))). GD can return another zero on that interval.

Newton uses the same on_unconverged policy as GD. Non-finite scores or estimates remain unconverged. Its default tolerance resolves root position to about tol * (1 + abs(x)); it does not remove the lookup table's approximation error. When H << tol * abs(x), max_abs_score can remain large because the score is steep, even though the position meets tolerance. This is expected.

Each Newton iteration evaluates the score and its slope, and may add score probes or bisections. Fewer iterations can offset that extra cost.

On the bursty benchmark signal at lengths 1024, 2048 and 4096, Newton was 4.20x, 4.63x and 5.20x faster than default GD. Every Newton window converged in at most six iterations, with no bisection fallbacks. These are median wall times from three alternating runs after a warmup, with one worker on an Apple M4 Max, macOS 26.6.2, Python 3.13.13 and NumPy 2.5.1. Reproduce them with uv run python benchmarks/newton.py from the repository; the benchmark README lists thread limits and absolute timings.

Parallel execution

parallel = IMF(contrast=SmoothAbs(H=0.2), kernel=epanechnikov, workers=4)
parallel_result = parallel.decompose(y)

workers is a positive integer and defaults to 1. Larger values fit chunks of windows in separate threads. Stages still run in order because each uses the previous residual. Short signals use fewer threads, with at least 64 windows per chunk except the last.

GD chunks stop independently, so changing workers can change GD results near the solver tolerance. Newton stops windows independently. With the built-in contrasts, its values and diagnostics are bit-identical across worker counts, including singleton chunks. More workers may help large robust fits, but thread overhead can slow small signals or direct weighted means. Compare timings on your data.

Python API

IMF

IMF(contrast=None, kernel=None, *, boundary="wrap", max_iter=None,
    tol=None, workers=1, solver="gd", on_unconverged="warn")

IMF.decompose(y, *, h1=0.25, a=sqrt(2), k_max=8,
              h_min=None, window_sizes=None) -> IMFResult

None selects Quadratic() and squared_triangle. For max_iter and tol, it selects 60 and 1e-6 for GD, or 100 and 1e-12 for Newton. y must be nonempty, finite and one-dimensional. It is converted to floating point without modifying the input. Invalid numerical settings or an unsupported solver raise ValueError.

Kernel

kernel.profile(u)
kernel.weights(window_size, *, bandwidth=None)
kernel(window_size, *, bandwidth=None)

profile(u) returns finite nonnegative values with the same shape as u. Weights outside [−1, 1] are zero; the remaining weights are normalized and must have a positive sum.

Here bandwidth is a radius in samples, unlike the normalized half-widths passed to decompose. Omitting it uses the integer window radius. A one-sample window has weight one.

Contrast

Quadratic()
SmoothAbs(H, *, lookup=True)

contrast(r)                      # loss rho(r)
contrast.psi(r)                  # score rho'(r)
contrast.psi_prime(r)            # slope in raw residual units; required for Newton
contrast.curvature()             # positive global upper bound on rho''
contrast.solve(windows, weights) # optional direct minimizer

Loss and score methods must accept NumPy arrays. A direct solver receives rows of local observations and a normalized weight vector, and returns one estimate per row. It takes precedence over solver. Otherwise, supply a convex contrast with a nondecreasing score and psi(0)=0. GD needs a finite positive curvature bound. Newton needs psi_prime(r); selecting Newton without it raises ValueError. With multiple workers, contrast methods may run concurrently and must not mutate shared state or input arrays.

SmoothAbs.psi_prime(r) includes the factor 1/H. Lookup evaluation returns the exact slope of the piecewise-linear score, using the right-hand slope at knots and zero beyond the grid. With lookup=False it returns sqrt(2/pi)/H * exp(-r**2/(2*H**2)), while psi keeps the research erf approximation.

IMFResult and StageInfo

See Reading the result for all fields. For GD, unconverged_windows counts rows failing delta <= tol * (1 + max(abs(x_chunk))), including NaNs. With one worker, the whole stage is one chunk. For Newton, it counts rows still active at the cap. GD reports max_abs_score at the last evaluated iterate, before the final update; Newton reports it at the returned estimates. final_max_delta and max_abs_score propagate NaN across workers.

Custom kernels & contrasts

Subclass Kernel and define a profile. The base class handles sampling, compact support and normalization.

from pimf import Kernel

class Cosine(Kernel):
    def profile(self, u):
        return np.cos(np.pi * u / 2)

cosine_result = IMF(kernel=Cosine()).decompose(y)

This Huber contrast uses a quadratic loss for small differences and a linear loss beyond delta:

from pimf import Contrast

class Huber(Contrast):
    def __init__(self, delta):
        if not np.isfinite(delta) or delta <= 0:
            raise ValueError("delta must be finite and positive")
        self.delta = delta

    def __call__(self, r):
        r = np.asarray(r, dtype=float)
        magnitude = np.abs(r)
        return np.where(
            magnitude <= self.delta,
            0.5 * r**2,
            self.delta * (magnitude - 0.5 * self.delta),
        )

    def psi(self, r):
        return np.clip(r, -self.delta, self.delta)

    def psi_prime(self, r):
        return (np.abs(r) < self.delta).astype(float)

    def curvature(self):
        return 1.0

huber_result = IMF(contrast=Huber(0.3), solver="newton").decompose(y)

psi_prime is optional for GD. For Newton, it must return the vectorized score slope in raw residual units; this Huber score has slope one inside the quadratic region and zero outside.