findpeaks

repository·master·Indexed 43 days ago

https://github.com/erdogant/findpeaks

A Python library for the detection and analysis of peaks and valleys in 1D vectors and 2D arrays (images). It supports multiple detection methodologies including topology (persistent homology), peakdetect, mask (local maximum filtering for images), and Caerus (optimized for financial time series). The library also includes a comprehensive suite of denoising filters such as Frost, Lee, Kuan, and Bilateral filtering for image preprocessing.

Tokens
22.2K
Snippets
87
Records
105
Agent score
53%

What's inside findpeaks

  1. Overview of Denoising Methods in findpeaks

    master

    Denoising is a recommended pre-processing step before using findpeaks.findpeaks.findpeaks.preprocessing to improve image analysis. The library implements several well-known filtering methods to suppress noise (such as speckle noise in SAR images):

    • Frost: findpeaks.filters.frost.frost_filter
    • Lee: findpeaks.filters.lee.lee_filter
    • Lee Enhanced: findpeaks.filters.lee_enhanced.lee_enhanced_filter
    • Lee Sigma: findpeaks.filters.lee_sigma.lee_sigma_filter
    • Kuan: findpeaks.filters.kuan.kuan_filter
    • Mean: findpeaks.filters.mean.mean_filter
    • Median: findpeaks.filters.median.median_filter
    • FastNL: findpeaks.stats.denoise(method='fastnl', ...)
    • Bilateral: findpeaks.stats.denoise(method='bilateral', ...)
  2. Overview of findpeaks capabilities

    master

    findpeaks is a Python library designed for robust detection and analysis of peaks and valleys in both 1D signals (time series) and 2D arrays (images/spatial data).

    Core Capabilities:

    • Multiple Detection Methods: Includes topology-based persistent homology (the most robust method), mask-based local maximum filtering, and traditional peakdetect approaches.
    • Advanced Preprocessing: Supports denoising, scaling, interpolation, and image-specific preprocessing.
    • Rich Visualization: Provides tools for generating persistence diagrams, 3D mesh plots, preprocessing step visualizations, and masking plots.
    • Mathematical Stability: Uses topology (persistent homology) to provide mathematically grounded peak detection.
    • Computer Vision Support: Includes Hough Transform applications for enhanced robustness in image processing tasks.
  3. Available findpeaks modules

    master

    The findpeaks library is organized into several functional modules:

    • findpeaks.findpeaks: Core peak detection functionality.
    • findpeaks.stats: Statistical tools for signal analysis.
    • findpeaks.interpolate: Interpolation methods for signal processing.
    • findpeaks.filters: A collection of signal filters including:
      • frost
      • lee
      • kuan
      • lee_enhanced
      • mean
      • median
  4. Overview of peak detection methods

    master

    The findpeaks library supports several core detection methodologies depending on your data type and noise levels:

    • Topology Detection: Uses persistent homology from topological data analysis. It is the most robust method, quantifying peak significance through persistence scores. Best for noisy data where mathematical stability is required.
    • Peakdetect Method: A traditional algorithm using a lookahead approach. It excels at finding local maxima and minima in noisy signals without extensive preprocessing.
    • Mask Detection: A local maximum filtering approach designed specifically for 2D data (images). It uses 8-connected neighborhood analysis and background removal.
    • Caerus Method: A specialized algorithm optimized for financial time series analysis.
  5. How the topology method works using Persistent Homology

    master

    The topology method uses Topological Data Analysis (TDA), specifically persistent homology, to detect and quantify peaks.

    Core Concept

    Instead of just finding local maxima, it treats the signal as a landscape where a 'water level' descends.

    • Birth: A local maximum (island) appears as the water level drops.
    • Death: Two islands merge at a saddle point; the lower island is considered to have 'died'.
    • Persistence: The difference between the birth level and the death level.

    This method quantifies the 'significance' of a peak. Peaks with low persistence (those close to the diagonal in a persistence diagram) are often noise, while high-persistence peaks are significant features. The time complexity is O(n log n) due to the initial sorting of values.

    from findpeaks import findpeaks
    
    # Initialize with the topology method
    fp = findpeaks(method='topology')
    
    # Fit the method to your data
    results = fp.fit(X)
    
    # Visualize the persistence diagram
    fp.plot_persistence()
  6. Select a peak detection method

    master

    Depending on your data type and requirements, you can choose from several core detection algorithms:

    • Topology-based: Uses persistent homology. Use findpeaks.stats.topology for 1D or findpeaks.stats.topology2d for 2D data.
    • Traditional: Use findpeaks.peakdetect.peakdetect for standard peak detection.
    • Mask-based: Uses local maximum filtering for 2D data via findpeaks.stats.mask.
    • Financial: Use findpeaks.stats.caerus for financial time series analysis.
  7. Quickstart: Basic peak detection workflow

    master

    The standard workflow for using findpeaks involves initializing the library with a specific method, importing or providing data, fitting the model to detect peaks, and then visualizing the results.

    For the most robust results, initialize the findpeaks object using method='topology'. You can then use .fit(X) to perform peak detection and .plot() or .plot_persistence() for visualization.

    # Import library
    from findpeaks import findpeaks
    
    # Initialize with topology method (most robust)
    fp = findpeaks(method='topology')
    
    # Example data:
    X = fp.import_example('1dpeaks')
    
    # Peak detection
    results = fp.fit(X)
    
    # Plot results
    fp.plot()
    
    # Plot persistence diagram
    fp.plot_persistence()
  8. Detect peaks in SAR images with denoising and topology

    master

    SAR (Synthetic Aperture Radar) images often contain speckle noise. To detect peaks effectively, you should apply denoising and use the topology method.

    Workflow:

    1. Initialize findpeaks with method='topology', denoise (e.g., 'lee_sigma'), and scale=True.
    2. Load the image with import_example().
    3. Call fit().
    4. Use plot_preprocessing() to inspect denoising steps.
    5. Use plot_mesh() or plot_mesh(view=(90,0)) for 3D/top-down visualization.
    6. Use plot_persistence() to analyze persistence-homology scores to filter out noise-induced peaks.
    from findpeaks import findpeaks
    
    # Initialize with topology method and Lee Sigma denoising
    fp = findpeaks(
        method='topology', 
        limit=160, 
        scale=True, 
        togray=True, 
        imsize=(150, 150), 
        denoise='lee_sigma', 
        params={'window': 17}
    )
    
    # Load SAR image example
    img = fp.import_example('2dpeaks_image')
    
    # Fit and visualize
    fp.fit(img)
    fp.plot_preprocessing()
    fp.plot(figure_order='horizontal')
    fp.plot_mesh()
    fp.plot_persistence()
  9. Visualize 2D pre-processing pipelines

    master

    For 2D arrays (images), use fp.plot_preprocessing() to visualize the transformation steps. The function dynamically adjusts the number of subplots based on the preprocessing steps defined during initialization. This is useful for debugging the pipeline applied to an image.

    # Import library
    from findpeaks import findpeaks
    # Initialize with peak detection only
    fp = findpeaks(method='topology', whitelist=['peak'])
    # Import example
    X = fp.import_example("2dpeaks")
    # Detect peaks
    results = fp.fit(X)
    # Plot preprocessing steps
    fp.plot_preprocessing()
  10. Quick Start: Detect peaks in 1D data

    master

    This example demonstrates the standard workflow: initializing the findpeaks object with a specific method, importing data, fitting the model, and visualizing the results.

    # Import library
    from findpeaks import findpeaks
    
    # Initialize with topology method (most robust)
    fp = findpeaks(method='topology')
    
    # Example data
    X = fp.import_example('1dpeaks')
    
    # Peak detection
    results = fp.fit(X)
    
    # Plot results
    fp.plot()
    
    # Plot persistence diagram
    fp.plot_persistence()
  11. Detect peaks in 2D images using the topology method

    master

    To detect peaks and valleys in 2D images, use the findpeaks class with method='topology'. This implementation uses persistent homology and a union-find data structure.

    Key behaviors:

    • Both peaks and valleys are detected. Valleys are represented as negative values in the output.
    • Use the whitelist=['peak'] argument if you only want to detect peaks and ignore valleys.
    • Pre-processing can be controlled via several parameters during initialization: togray, imsize, scale, denoise, window, and cu.

    Output Structure: When calling .fit(X), the returned dictionary contains:

    • Xdetect: Array of the same shape as input, containing detected peaks/valleys (high values = best peaks, low values = best valleys).
    • Xranked: Array of the same shape as input, containing ranked peaks/valleys.
    • persistence: A pandas DataFrame containing x, y coordinates and metadata about the detected features.
    • Xraw, Xproc, groups0: Other internal processing variables.
    from findpeaks import findpeaks
    
    # Initialize for 2D peak detection
    fp = findpeaks(method='topology', whitelist=['peak'])
    
    # Load an example 2D image
    X = fp.import_example('2dpeaks')
    
    # Run detection
    results = fp.fit(X)
    
    # Access results
    print(results.keys())
    print(results['persistence'])
  12. Compare peak detection methods using findpeaks.fit

    master

    You can evaluate different peak detection strategies by initializing findpeaks with different method arguments and calling .fit(X) on your data.

    Supported methods include:

    • method='peakdetect': Focuses on significant peaks, often used for cleaner signal extraction.
    • method='topology': Detects local minima and maxima based on topological persistence, which can identify a much larger number of features.

    To improve detection accuracy and consistency, especially in noisy datasets, use the interpolate parameter. Setting interpolate to a positive integer (e.g., 10) applies interpolation via findpeaks.interpolate.interpolate_line1d before detection. Interpolated results are automatically mapped back to the original coordinate system for visualization.

    from findpeaks import findpeaks
    
    # Compare peakdetect with interpolation
    fp_peakdetect_int = findpeaks(method='peakdetect', interpolate=10, lookahead=1)
    
    # Compare topology with interpolation
    fp_topology_int = findpeaks(method='topology', interpolate=10)
    
    # Example data
    X = [1, 1, 1.1, 1, 0.9, 1, 1.1, 1, 3, 2, 5, 3, 2]
    
    # Fit and plot
    fp_topology_int.fit(X)
    fp_topology_int.plot()