### Clone and install from source Source: https://github.com/derb12/pybaselines/blob/main/docs/installation.md Clones the repository locally and performs a local installation of the package. ```bash git clone https://github.com/derb12/pybaselines.git cd pybaselines pip install . ``` -------------------------------- ### Install pybaselines Source: https://context7.com/derb12/pybaselines/llms.txt Instructions for installing the pybaselines library using pip or conda. Includes options for basic installation and installation with optional dependencies for enhanced performance. ```bash pip install pybaselines pip install pybaselines[full] conda install -c conda-forge pybaselines ``` -------------------------------- ### Install Matplotlib for Pybaselines Examples Source: https://github.com/derb12/pybaselines/blob/main/docs/examples/README.rst This command installs the Matplotlib library, which is necessary for running the examples provided in the pybaselines documentation. Matplotlib is used for plotting and visualizing the baseline correction results. ```console pip install matplotlib ``` -------------------------------- ### Install pybaselines using pip Source: https://github.com/derb12/pybaselines/blob/main/README.rst Installs the stable release of the pybaselines library from PyPI using pip. This is the recommended method for most users. ```console pip install pybaselines ``` -------------------------------- ### Setup Synthetic Data for Baseline Fitting Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/examples/morphological/plot_half_window_effects.md Initializes synthetic signal data using Gaussian peaks and noise to demonstrate baseline fitting techniques. ```Python import matplotlib.pyplot as plt import numpy as np from pybaselines import Baseline from pybaselines.utils import gaussian x = np.linspace(0, 1000, 2000) signal = ( gaussian(x, 9, 100, 12) + gaussian(x, 6, 180, 5) + gaussian(x, 8, 300, 11) + gaussian(x, 15, 400, 12) + gaussian(x, 6, 550, 6) + gaussian(x, 13, 700, 8) + gaussian(x, 9, 800, 9) + gaussian(x, 9, 880, 7) ) baseline = 5 + gaussian(x, 10, 650, 150) noise = np.random.default_rng(0).normal(0, 0.1, len(x)) y = signal + baseline + noise baseline_fitter = Baseline(x_data=x) ``` -------------------------------- ### Install pybaselines with optional dependencies Source: https://github.com/derb12/pybaselines/blob/main/README.rst Installs pybaselines along with all optional dependencies using pip. This enables advanced functionalities that rely on additional libraries. ```console pip install pybaselines[full] ``` -------------------------------- ### pybaselines Polynomial Methods - modpoly Example Source: https://context7.com/derb12/pybaselines/llms.txt Illustrates the use of the Modified Polynomial (ModPoly) algorithm for baseline fitting. This example shows basic usage, fitting with higher polynomial orders, and applying custom weights to influence the fit. ```python from pybaselines import Baseline import numpy as np x = np.linspace(0, 1000, 500) y = np.sin(x / 50) + 0.5 * np.exp(-x / 200) + np.random.normal(0, 0.05, len(x)) baseline_fitter = Baseline(x_data=x) # Basic modpoly fit with polynomial order 3 baseline, params = baseline_fitter.modpoly(y, poly_order=3) # Access iteration count and tolerance from params print(f"Converged in {params['tol_history'][-1]:.2e} tolerance") # Higher polynomial order for more complex baselines baseline_high, _ = baseline_fitter.modpoly(y, poly_order=5, max_iter=100) # Use custom weights to emphasize certain regions weights = np.ones_like(y) weights[100:200] = 0 # Ignore peak region baseline_weighted, _ = baseline_fitter.modpoly(y, poly_order=3, weights=weights) ``` -------------------------------- ### pybaselines Polynomial Methods - imodpoly Example Source: https://context7.com/derb12/pybaselines/llms.txt Demonstrates the Improved Modified Polynomial (IModPoly) algorithm, which is suitable for noisy data. The examples show default usage, adjusting the `num_std` parameter for tolerance, and retrieving polynomial coefficients. ```python from pybaselines import Baseline import numpy as np x = np.linspace(0, 1000, 500) y = 5 + 10 * np.exp(-x / 300) + np.random.normal(0, 0.3, len(x)) # Noisy data baseline_fitter = Baseline(x_data=x) # imodpoly with default num_std=1 for noisy data baseline, params = baseline_fitter.imodpoly(y, poly_order=3) # Adjust num_std to control baseline fitting aggressiveness # Higher values make the algorithm more tolerant of noise baseline_tolerant, _ = baseline_fitter.imodpoly(y, poly_order=3, num_std=2) # Lower num_std for data with small, well-defined peaks baseline_strict, _ = baseline_fitter.imodpoly(y, poly_order=3, num_std=0.5) # Get polynomial coefficients for external use baseline, params = baseline_fitter.imodpoly(y, poly_order=4, return_coef=True) coefficients = params['coef'] # Can be used with np.polynomial.Polynomial ``` -------------------------------- ### Basic pybaselines usage example Source: https://github.com/derb12/pybaselines/blob/main/README.rst Demonstrates a basic usage of the pybaselines library. It generates sample data with Gaussian peaks and initializes the Baseline object for processing. ```python import matplotlib.pyplot as plt import numpy as np from pybaselines import Baseline, utils x = np.linspace(1, 1000, 1000) # a measured signal containing several Gaussian peaks signal = ( utils.gaussian(x, 4, 120, 5) ) ``` -------------------------------- ### Install pybaselines using conda Source: https://github.com/derb12/pybaselines/blob/main/README.rst Installs the pybaselines library from the conda-forge channel using the conda package manager. This is an alternative installation method. ```console conda install -c conda-forge pybaselines ``` -------------------------------- ### Configuring Process Start Method for Multiprocessing in Python Source: https://github.com/derb12/pybaselines/blob/main/docs/performance.md Illustrates how to explicitly set the process start method to 'spawn' when using `concurrent.futures.ProcessPoolExecutor` with pybaselines. This is a workaround for potential conflicts with the default 'fork' method on POSIX systems, particularly when using methods like `loess` that might spawn internal threads, ensuring compatibility and stability. ```python from multiprocessing import get_context with ProcessPoolExecutor(mp_context=get_context('spawn')) as pool: ... # do the processing ``` -------------------------------- ### Calculate Baseline using MPLS Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/api/pybaselines.Baseline.mpls.md Example usage of the mpls method to calculate a baseline from input data. It demonstrates passing the data array and optional smoothing parameters. ```python from pybaselines import Baseline import numpy as np # Example data data = np.array([1.0, 2.0, 1.5, 3.0, 2.5]) # Initialize Baseline class base = Baseline(data) # Calculate baseline using MPLS baseline, params = base.mpls(data, lam=1e6, p=0.0) ``` -------------------------------- ### pybaselines Baseline Class - Core Interface Example Source: https://context7.com/derb12/pybaselines/llms.txt Demonstrates the core interface of the pybaselines `Baseline` class for 1D data. It shows how to generate sample data, initialize the `Baseline` object, apply various baseline correction algorithms (modpoly, asls, mor, snip), and visualize the results. ```python import numpy as np import matplotlib.pyplot as plt from pybaselines import Baseline, utils # Generate sample data with peaks and baseline x = np.linspace(1, 1000, 1000) signal = ( utils.gaussian(x, 4, 120, 5) + utils.gaussian(x, 5, 220, 12) + utils.gaussian(x, 5, 350, 10) + utils.gaussian(x, 7, 400, 8) + utils.gaussian(x, 4, 550, 6) + utils.gaussian(x, 5, 680, 14) + utils.gaussian(x, 4, 750, 12) + utils.gaussian(x, 5, 880, 8) ) true_baseline = 2 + 10 * np.exp(-x / 400) noise = np.random.default_rng(1).normal(0, 0.2, x.size) y = signal + true_baseline + noise # Create Baseline object with x-data baseline_fitter = Baseline(x_data=x) # Compare different algorithms bkg_modpoly, params_modpoly = baseline_fitter.modpoly(y, poly_order=3) bkg_asls, params_asls = baseline_fitter.asls(y, lam=1e7, p=0.02) bkg_mor, params_mor = baseline_fitter.mor(y, half_window=30) bkg_snip, params_snip = baseline_fitter.snip(y, max_half_window=40, decreasing=True, smooth_half_window=3) # Subtract baseline to get corrected signal corrected_signal = y - bkg_asls # Plot results plt.figure(figsize=(12, 6)) plt.plot(x, y, label='Raw data') plt.plot(x, true_baseline, lw=3, label='True baseline') plt.plot(x, bkg_modpoly, '--', label='modpoly') plt.plot(x, bkg_asls, '--', label='asls') plt.plot(x, bkg_mor, '--', label='mor') plt.plot(x, bkg_snip, '--', label='snip') plt.legend() plt.show() ``` -------------------------------- ### Install pybaselines development version from GitHub Source: https://github.com/derb12/pybaselines/blob/main/README.rst Installs the latest development version of pybaselines directly from its GitHub repository using pip. This is useful for testing the newest features or bug fixes. ```console pip install git+https://github.com/derb12/pybaselines.git ``` -------------------------------- ### BEADS Algorithm with Exponential Baseline and Parabola Subtraction (Python) Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/examples/misc/plot_beads_preprocessing.md This example demonstrates the BEADS algorithm applied to data with an exponentially decaying baseline, which is zero only on one end. It highlights the improvement gained by using parabola subtraction (`fit_parabola=True`) compared to not using it, as the latter incorrectly fits the non-zero end. ```Python y, baseline = make_data(x, baseline_type=1) plt.figure() plt.plot(y) for subtract_parabola in (False, True): fit_baseline = baseline_fitter.beads( y, lam_0=0.015, lam_1=0.1, lam_2=1, fit_parabola=subtract_parabola )[0] plt.plot(fit_baseline, ls=next(linestyles), label=f'parabola subtracted: {subtract_parabola}') plt.plot(baseline, ':', label='true baseline') plt.legend() ``` -------------------------------- ### Data Generation for pybaselines Timing Example Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/examples/general/plot_reuse_Baseline.md Generates synthetic data including multiple Gaussian peaks, a baseline, and noise. This data is used to test the performance of different pybaselines fitting algorithms. ```Python from collections import defaultdict from time import perf_counter import matplotlib.pyplot as plt import numpy as np from pybaselines import Baseline from pybaselines.utils import gaussian num_points = 1000 # number of data points in one set of data num_fits = 1000 # equivalent to the number of data in a dataset x = np.linspace(0, 1000, num_points) signal = ( + gaussian(x, 6, 150, 5) + gaussian(x, 8, 350, 11) + gaussian(x, 6, 550, 6) + gaussian(x, 13, 700, 8) + gaussian(x, 9, 880, 7) ) baseline = 5 + 10 * np.exp(-x / 600) + gaussian(x, 15, 1000, 400) noise = np.random.default_rng(0).normal(0, 0.1, len(x)) y = signal + baseline + noise ``` -------------------------------- ### Implement Golotvin Baseline Identification Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/api/pybaselines.Baseline.golotvin.md Example usage of the Baseline.golotvin method to identify and extract a baseline from signal data. The function requires input data and optional parameters like half_window and num_std to tune the sensitivity of baseline detection. ```python import numpy as np from pybaselines import Baseline # Generate dummy data x = np.linspace(0, 100, 1000) data = np.sin(x) + np.random.normal(0, 0.1, 1000) # Initialize Baseline object base_obj = Baseline(x) # Apply Golotvin method baseline, params = base_obj.golotvin(data, half_window=20, num_std=2.0) # Access the baseline mask mask = params['mask'] ``` -------------------------------- ### Initialize Baseline Class Source: https://github.com/derb12/pybaselines/blob/main/docs/api/Baseline.md Demonstrates how to instantiate the Baseline class for 1D data processing. The class accepts optional parameters for x-axis data, finite value checking, and sorting preferences. ```python from pybaselines import Baseline import numpy as np # Initialize with sample data x = np.linspace(-1, 1, 100) baseline_processor = Baseline(x_data=x, check_finite=True, assume_sorted=True) ``` -------------------------------- ### Initialize Signal and Baseline Fitter Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/examples/classification/plot_fastchrom_threshold.md Sets up a synthetic signal with Gaussian peaks and a baseline, and initializes the Baseline fitter object for processing. ```Python import matplotlib.pyplot as plt import numpy as np from pybaselines import Baseline from pybaselines.utils import gaussian x = np.linspace(0, 1000, 1000) signal = (gaussian(x, 9, 100, 12) + gaussian(x, 6, 180, 5) + gaussian(x, 8, 350, 11) + gaussian(x, 15, 400, 18) + gaussian(x, 6, 550, 6) + gaussian(x, 13, 700, 8) + gaussian(x, 9, 800, 9) + gaussian(x, 9, 880, 7)) baseline = gaussian(x, 6, 400, 500) noise = np.random.default_rng(0).normal(0, 0.2, len(x)) y = signal + baseline + noise baseline_fitter = Baseline(x_data=x) ``` -------------------------------- ### Visualize Baseline Fitting with Varying Half-Window Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/examples/morphological/plot_half_window_effects.md Demonstrates the effect of different half_window values on the baseline fit, showing how it affects baseline stiffness and peak interaction. ```Python plt.figure() plt.plot(y, label='data') for half_window in (30, 60, 120): plt.plot(baseline_fitter.mor(y, half_window=half_window)[0], label=f'half_window={half_window}') plt.legend() plt.show() ``` -------------------------------- ### GET /pybaselines/utils/optimize_window Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/api/pybaselines.utils.optimize_window.md Calculates the optimal morphological half-window size for baseline correction. ```APIDOC ## GET /pybaselines/utils/optimize_window ### Description Optimizes the morphological half-window size for baseline removal algorithms by iterating through potential window sizes until a stable opening is found. ### Method FUNCTION CALL ### Endpoint pybaselines.utils.optimize_window ### Parameters #### Path Parameters - **data** (array-like) - Required - The measured data values (1D or 2D). #### Query Parameters - **increment** (int) - Optional - The step size for iterating half windows. Default is 1. - **max_hits** (int) - Optional - Number of consecutive half windows that must produce the same result. Default is 3. - **window_tol** (float) - Optional - Tolerance for comparing morphological openings. Default is 1e-6. - **max_half_window** (int) - Optional - Maximum allowable half-window size. - **min_half_window** (int) - Optional - Minimum half-window size. ### Request Example optimize_window(data=my_data, increment=2, max_hits=5) ### Response #### Success Response (200) - **half_window** (int/array) - The optimized half window size(s). #### Response Example 15 ``` -------------------------------- ### GET /utils/gaussian Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/api/pybaselines.utils.gaussian.md Generates a Gaussian distribution array based on input x-values and distribution parameters. ```APIDOC ## GET /utils/gaussian ### Description Generates a Gaussian distribution based on height, center, and sigma parameters. ### Method GET ### Endpoint /utils/gaussian ### Parameters #### Query Parameters - **x** (array) - Required - The x-values at which to evaluate the distribution. - **height** (float) - Optional - The maximum height of the distribution. Default is 1.0. - **center** (float) - Optional - The center of the distribution. Default is 0.0. - **sigma** (float) - Optional - The standard deviation of the distribution. Must be > 0. Default is 1.0. ### Request Example GET /utils/gaussian?x=[0,1,2]&height=1.0¢er=0.0&sigma=1.0 ### Response #### Success Response (200) - **data** (numpy.ndarray) - The calculated Gaussian distribution values. #### Response Example { "data": [0.3989, 0.2420, 0.0540] } ### Error Handling - **400 Bad Request**: Raised if sigma is not greater than 0. ``` -------------------------------- ### Compare Baseline Fits with Different Parameters Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/examples/classification/plot_classifier_masks.md Performs baseline estimation using different half_window values to demonstrate how parameter selection affects the resulting baseline fit. ```python half_window_1 = 15 half_window_2 = 45 fit_1, params_1 = baseline_fitter.std_distribution(y, half_window_1, smooth_half_window=10) fit_2, params_2 = baseline_fitter.std_distribution(y, half_window_2, smooth_half_window=10) plt.plot(x, y) plt.plot(x, fit_1, label=f'half_window={half_window_1}') plt.plot(x, fit_2, '--', label=f'half_window={half_window_2}') plt.legend() ``` -------------------------------- ### Perform Baseline Correction using pspline_drpls Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/api/functional/pybaselines.spline.pspline_drpls.md Example usage of the pspline_drpls function to estimate a baseline from input data. It demonstrates passing the data array and optional parameters like lam and num_knots. ```python from pybaselines.spline import pspline_drpls import numpy as np # Generate sample data data = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.1, 100) # Apply pspline_drpls baseline, params = pspline_drpls(data, lam=1000.0, num_knots=50) print("Baseline shape:", baseline.shape) print("Final weights:", params['weights']) ``` -------------------------------- ### Compare ASLS and ASPLS Convergence with Default Settings Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/examples/general/plot_algorithm_convergence.md This code snippet generates synthetic data with Gaussian peaks and an exponential baseline, then fits it using both the ASLS and ASPLS algorithms with default convergence parameters (tolerance and max iterations). It visualizes the fitted baselines and plots the tolerance history for each algorithm to compare their convergence behavior. ```Python import matplotlib.pyplot as plt import numpy as np from pybaselines import Baseline from pybaselines.utils import gaussian x = np.linspace(0, 1000, 1000) signal = ( gaussian(x, 9, 100, 12) + gaussian(x, 6, 180, 5) + gaussian(x, 8, 350, 11) + gaussian(x, 15, 400, 18) + gaussian(x, 6, 550, 6) + gaussian(x, 13, 700, 8) + gaussian(x, 9, 800, 9) + gaussian(x, 9, 880, 7) ) baseline = 5 + 10 * np.exp(-x / 600) noise = np.random.default_rng(0).normal(0, 0.1, len(x)) y = signal + baseline + noise baseline_fitter = Baseline(x_data=x) lam = 5e6 tol = 1e-3 max_iter = 20 fit_1, params_1 = baseline_fitter.asls(y, lam=lam, tol=tol, max_iter=max_iter) fit_2, params_2 = baseline_fitter.aspls(y, lam=lam, tol=tol, max_iter=max_iter) plt.plot(y) plt.plot(fit_1, label='asls') plt.plot(fit_2, label='aspls') plt.legend() ``` -------------------------------- ### Perform 2D asPLS Baseline Correction Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/api/pybaselines.Baseline2D.aspls.md Example usage of the asPLS method within the pybaselines library. This function takes 2D data and applies iterative smoothing to calculate the baseline, returning the baseline and associated parameters. ```python from pybaselines import Baseline2D import numpy as np # Initialize the Baseline2D object base_obj = Baseline2D(data_shape=(100, 100)) # Generate dummy 2D data data = np.random.rand(100, 100) # Apply asPLS baseline correction baseline, params = base_obj.aspls(data, lam=1e5, max_iter=100, tol=0.001) ``` -------------------------------- ### Baseline Fitting with Minimal Eigenvalues Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/examples/two_d/plot_whittaker_2d_dof.md This code demonstrates fitting baselines using a significantly reduced number of eigenvalues (3x3 for polynomial, 5x12 for sinusoidal) to observe the impact on computation time and error. It includes plotting the results and displaying them. ```Python num_eigens_poly = (3, 3) num_eigens_sine = (5, 12) t0 = perf_counter() eigenvalue_poly_baseline_3, params_7 = baseline_fitter.arpls( y, lam=lam_poly, num_eigens=num_eigens_poly, return_dof=True ) eigenvalue_sine_baseline_3, params_8 = baseline_fitter.arpls( y2, lam=lam_sine, num_eigens=num_eigens_sine, return_dof=True ) t1 = perf_counter() mse_analytical_poly = mean_squared_error(eigenvalue_poly_baseline_3, polynomial_baseline) mse_analytical_sine = mean_squared_error(eigenvalue_sine_baseline_3, sine_baseline) print(f'3x3 Eigenvalues for polynomial, 5x12 for sinusoidal:\nTime: {t1 - t0:.3f} seconds') print(f'Mean-squared-error, polynomial: {mse_analytical_poly:.5f}') print(f'Mean-squared-error, sinusoidal: {mse_analytical_sine:.5f}') plot_contour_with_projection( X, Z, eigenvalue_poly_baseline_3, title='3x3 Eigenvalues Polynomial Baseline' ) plot_contour_with_projection( X, Z, eigenvalue_sine_baseline_3, title='5x12 Eigenvalues Sinusoidal Baseline' ) plt.show() ``` -------------------------------- ### Calculate Baseline using pspline_mpls Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/api/pybaselines.Baseline.pspline_mpls.md This snippet demonstrates how to initialize the Baseline class and call the pspline_mpls method to compute a baseline from input data. It highlights the use of optional parameters like lam and num_knots to control the smoothing and spline complexity. ```python from pybaselines import Baseline import numpy as np # Example usage x = np.linspace(0, 100, 1000) y = np.sin(x) + 0.1 * x base = Baseline(y) baseline, params = base.pspline_mpls(lam=1000.0, num_knots=100, spline_degree=3) ``` -------------------------------- ### Perform 2D Baseline Correction using iarpls Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/api/pybaselines.Baseline2D.iarpls.md This example demonstrates how to call the iarpls method on a 2D dataset. It requires a 2D numpy array as input and returns the calculated baseline and a dictionary of parameters including weights and convergence history. ```python from pybaselines import Baseline2D import numpy as np # Initialize the Baseline2D object base_obj = Baseline2D(data) # Perform iarpls baseline correction baseline, params = base_obj.iarpls( data=data, lam=100000.0, max_iter=50, tol=0.001 ) ``` -------------------------------- ### Fit polynomial baseline using pybaselines.polynomial.poly Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/api/functional/pybaselines.polynomial.poly.md This snippet demonstrates how to use the poly function to calculate a baseline for a given dataset. It shows the basic function call and how to handle the returned baseline and parameter dictionary. ```python import numpy as np from pybaselines.polynomial import poly # Sample data y_data = np.array([1.0, 2.1, 1.2, 0.9, 2.0]) # Compute baseline baseline, params = poly(y_data, poly_order=2) print("Calculated baseline:", baseline) ``` -------------------------------- ### Multithreading with ThreadPoolExecutor in Python Source: https://github.com/derb12/pybaselines/blob/main/docs/performance.md Shows an example of using `concurrent.futures.ThreadPoolExecutor` for multithreading with pybaselines, applicable for versions 1.2.0 and later that support free-threaded CPython builds. It demonstrates creating a thread-safe `Baseline` object and using `functools.partial` to apply it across multiple threads, which can reduce computation time for I/O-bound or GIL-releasing operations. ```python from concurrent.futures import ThreadPoolExecutor from functools import partial from pybaselines import Baseline x = ... # the x-values for the data dataset = ... # the total data, with shape (number of datasets, number of data points) kwargs = {...} # any keyword arguments to pass to the method baseline_fitter = Baseline(x) ``` -------------------------------- ### Masked Baseline Fitting with std_distribution and imodpoly Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/examples/general/plot_masked_data.md Demonstrates how to apply masks to baseline fitting algorithms like std_distribution and imodpoly by providing a weights parameter. It compares the results of masked and non-masked baseline fitting. ```Python non_masked_std_distributionc = baseline_fitter.std_distribution( y_bad, half_window=20, num_std=3 )[0] masked_std_distribution = baseline_fitter.std_distribution( y_bad, half_window=20, num_std=3, weights=fit_mask )[0] non_masked_imodpoly = baseline_fitter.imodpoly(y_bad, poly_order=5, num_std=0.1)[0] masked_imodpoly = baseline_fitter.imodpoly(y_bad, poly_order=5, num_std=0.1, weights=fit_mask)[0] _, (ax1, ax2) = plt.subplots(2, layout='constrained') ax1.set_title('std_distribution') ax2.set_title('imodpoly') ax1.plot(x, y_bad, label='data') ax1.plot(x, non_masked_std_distributionc, label='non-masked baseline') ax1.plot(x, masked_std_distribution, label='masked baseline') ax1.legend() ax2.plot(x, y_bad, label='data') ax2.plot(x, non_masked_imodpoly, label='non-masked baseline') ax2.plot(x, masked_imodpoly, label='masked baseline') ax2.legend() ``` -------------------------------- ### SNIP Data Transformation for Log-Log-Square Scale Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/api/pybaselines.Baseline.snip.md Demonstrates how to apply a log-log-square transform to data before using the SNIP algorithm, which can yield better results for data covering several orders of magnitude. It also shows how to revert the calculated baseline back to the original scale using the inverse transform. ```python from pybaselines.baseline import Baseline import numpy as np baseline_fitter = Baseline() data = np.array([...]) # Your data here # Transform data transformed_data = np.log(np.log(np.sqrt(data + 1) + 1)) # Calculate baseline on transformed data baseline_transformed, params = baseline_fitter.snip(transformed_data) # Revert baseline to original scale baseline = -1 + (np.exp(np.exp(baseline_transformed) - 1) - 1)**2 ``` -------------------------------- ### Show Smoothing Edge Effects with Padding Source: https://github.com/derb12/pybaselines/blob/main/docs/generated/examples/general/plot_padding.md This example demonstrates how different padding methods affect the results of a moving average smoothing operation. It applies `uniform_filter1d` to data padded using various modes from `pybaselines.utils.pad_edges`. The comparison highlights how proper padding minimizes undesirable edge effects introduced by smoothing algorithms. ```Python plt.figure() plt.plot(y, label='original') for i, pad_mode in enumerate(('reflect', 'edge', 'extrapolate'), 1): padded_y = pad_edges(y, pad_len, pad_mode, extrapolate_window=int(0.1 * num_points)) plt.plot( uniform_filter1d(padded_y, 2 * half_window + 1)[pad_len:num_points + pad_len], label=pad_mode ) plt.legend() plt.show() ```