Interface ready for preprocessing steps handling. style altered to support modular preprocessing pipeline, finished precalculations and preprocessing code, and its respective testing script, added preprocessingpipeline, a handler for the low level functions of preprocessing to work with the high level MSIData in the genie environment.

This commit is contained in:
Pixelguy14
2025-11-29 21:47:51 -06:00
parent bdd9315796
commit 11c181b3b3
13 changed files with 5039 additions and 988 deletions
+23 -10
View File
@@ -30,19 +30,31 @@ export run_preprocessing_analysis,
BaselineCorrection,
Normalization,
PeakPicking,
PeakBinningParams,
PeakBinning,
get_masked_spectrum_indices,
detect_peaks_profile,
detect_peaks_centroid,
smooth_spectrum,
apply_baseline_correction,
apply_normalization,
bin_peaks,
detect_peaks_profile_core,
detect_peaks_centroid_core,
smooth_spectrum_core,
apply_baseline_correction_core,
apply_normalization_core,
bin_peaks_core,
PeakSelection,
PeakAlignment,
find_calibration_peaks,
align_peaks_lowess,
MutableSpectrum
find_calibration_peaks_core,
align_peaks_lowess_core,
MutableSpectrum,
transform_intensity_core,
calibrate_spectra_core
export apply_baseline_correction,
apply_smoothing,
apply_peak_picking,
apply_calibration,
apply_peak_alignment,
apply_normalization,
apply_peak_binning,
apply_intensity_transformation,
save_feature_matrix
# Include all source files directly into the main module
include("BloomFilters.jl")
@@ -55,6 +67,7 @@ include("MzmlConverter.jl")
include("Preprocessing.jl")
include("ImageProcessing.jl")
include("Precalculations.jl")
include("PreprocessingPipeline.jl")
using Setfield # For immutable struct updates
+349 -127
View File
@@ -5,10 +5,21 @@ using StatsBase # For mean, std, median, quantile, mad
# =============================================================================
"""
find_ppm_error_by_region(msi_data, region_masks, reference_peaks)::Dict
find_ppm_error_by_region(msi_data::MSIData, region_masks::Dict, reference_peaks::Dict) -> Dict
Calculates PPM error statistics for different spatial regions.
`region_masks` is a Dict mapping region names (e.g., :tumor) to BitMatrix masks.
Calculates and reports mass accuracy (PPM error) statistics for different spatial regions
defined by masks. This is useful for identifying spatial variations in calibration.
# Arguments
- `msi_data::MSIData`: The main MSI data object.
- `region_masks::Dict{Symbol, BitMatrix}`: A dictionary mapping region names (e.g., `:tumor`, `:stroma`)
to `BitMatrix` masks. The dimensions of each mask must match `msi_data.image_dims`.
- `reference_peaks::Dict{Float64, String}`: A dictionary of known reference peaks, mapping
theoretical m/z to a name.
# Returns
- `Dict{Symbol, NamedTuple}`: A dictionary where keys are region names and values are `NamedTuple`s
containing the mass accuracy report for that region, as generated by `analyze_mass_accuracy`.
"""
function find_ppm_error_by_region(msi_data::MSIData, region_masks::Dict, reference_peaks::Dict)
regional_reports = Dict{Symbol, NamedTuple}()
@@ -37,6 +48,28 @@ function find_ppm_error_by_region(msi_data::MSIData, region_masks::Dict, referen
return regional_reports
end
"""
analyze_mass_accuracy(msi_data, reference_peaks; ...) -> NamedTuple
Analyzes the mass accuracy for a given subset of spectra by comparing detected peaks
against a list of known reference masses.
# Arguments
- `msi_data::MSIData`: The main MSI data object.
- `reference_peaks::Dict{Float64, String}`: A dictionary of known reference peaks, mapping
theoretical m/z to a name.
- `spectrum_indices::AbstractVector{Int}`: A vector of indices for the spectra to be analyzed.
- `peak_detection_snr_threshold::Float64`: The Signal-to-Noise ratio threshold to use for
detecting peaks within the spectra.
- `ppm_tolerance_for_matching::Float64`: The tolerance in Parts Per Million (PPM) used to match
a detected peak to a reference peak.
# Returns
- `NamedTuple`: A report containing summary statistics of the PPM errors found, including:
- `mean_ppm_error`, `median_ppm_error`, `std_ppm_error`, `min_ppm_error`, `max_ppm_error`
- `total_matched_peaks`: The total count of successful matches between detected and reference peaks.
- `total_spectra_analyzed`: The number of spectra processed.
"""
function analyze_mass_accuracy(
msi_data::MSIData,
reference_peaks::Dict{Float64, String}; # m/z => name
@@ -57,7 +90,7 @@ function analyze_mass_accuracy(
return
end
detected_peaks = detect_peaks_profile(mz, intensity; snr_threshold=peak_detection_snr_threshold)
detected_peaks = detect_peaks_profile_core(mz, intensity; snr_threshold=peak_detection_snr_threshold)
for ref_mz in keys(reference_peaks)
# Find the closest detected peak to this reference m/z within tolerance
@@ -88,7 +121,8 @@ function analyze_mass_accuracy(
min_ppm_error = NaN,
max_ppm_error = NaN,
total_matched_peaks = 0,
total_spectra_analyzed = total_spectra_processed
total_spectra_analyzed = total_spectra_processed,
ppm_error_distribution = Float64[]
)
end
@@ -107,7 +141,8 @@ function analyze_mass_accuracy(
min_ppm_error = min_err,
max_ppm_error = max_err,
total_matched_peaks = total_matched_peaks,
total_spectra_analyzed = total_spectra_processed
total_spectra_analyzed = total_spectra_processed,
ppm_error_distribution = all_ppm_errors
)
end
@@ -118,7 +153,16 @@ end
"""
calculate_adaptive_bin_tolerance(ppm_error_distribution) -> Float64
Calculates an appropriate binning tolerance based on observed mass accuracy.
Calculates an appropriate binning tolerance in PPM based on the observed mass accuracy
distribution. The strategy is to set the tolerance to capture the vast majority of
peaks from the same analyte, typically using `mean + 3 * standard_deviation`.
# Arguments
- `ppm_error_distribution::Vector{Float64}`: A vector of PPM error values from a mass
accuracy analysis.
# Returns
- `Float64`: The suggested binning tolerance in PPM, capped between 10.0 and 100.0.
"""
function calculate_adaptive_bin_tolerance(ppm_error_distribution::Vector{Float64})
if isempty(ppm_error_distribution)
@@ -148,10 +192,20 @@ function calculate_adaptive_bin_tolerance(ppm_error_distribution::Vector{Float64
end
"""
calculate_preprocessing_hints(data::MSIData; sample_size::Int=100)::Dict{Symbol, Any}
calculate_preprocessing_hints(data::MSIData; sample_indices)::Dict{Symbol, Any}
Analyzes a sample of spectra to determine optimal default parameters for
preprocessing steps, returning a dictionary of hints.
Analyzes a sample of spectra to determine initial "hints" for preprocessing parameters.
This function provides quick, data-driven defaults for noise level, SNR, and smoothing.
# Arguments
- `data::MSIData`: The main MSI data object.
- `sample_indices::AbstractVector{Int}`: The indices of spectra to sample for the analysis.
# Returns
- `Dict{Symbol, Any}`: A dictionary of hints, including:
- `:estimated_noise`: The mean noise level estimated using Median Absolute Deviation (MAD).
- `:suggested_snr`: A default SNR threshold (typically 3.0).
- `:suggested_smoothing_window`: A suggested window size for smoothing, based on instrument resolution if available.
"""
function calculate_preprocessing_hints(data::MSIData; sample_indices::AbstractVector{Int})::Dict{Symbol, Any}
println("Calculating preprocessing hints from a sample of $(length(sample_indices)) spectra...")
@@ -218,9 +272,22 @@ function calculate_preprocessing_hints(data::MSIData; sample_indices::AbstractVe
end
"""
analyze_instrument_characteristics(msi_data::MSIData)::Dict
analyze_instrument_characteristics(msi_data::MSIData; sample_indices)::Dict
Analyzes instrument metadata and data characteristics to determine acquisition properties.
Analyzes instrument metadata and spectral data to infer key acquisition properties.
It combines information from the `msi_data.instrument_metadata` with direct analysis
of the spectra.
# Arguments
- `msi_data::MSIData`: The main MSI data object.
- `sample_indices::AbstractVector{Int}`: The indices of spectra to sample for the analysis.
# Returns
- `Dict{Symbol, Any}`: A dictionary summarizing instrument characteristics:
- `:acquisition_mode`: Inferred as `:profile`, `:centroid`, or `:mixed`.
- `:mz_axis_type`: Inferred as `:regular` or `:irregular` based on m/z step consistency.
- `:dynamic_range`: An estimate of the intensity dynamic range in orders of magnitude.
- Other fields from `instrument_metadata` like `:resolution`, `:polarity`, etc.
"""
function analyze_instrument_characteristics(msi_data::MSIData; sample_indices::AbstractVector{Int})::Dict
results = Dict{Symbol, Any}()
@@ -337,9 +404,20 @@ function analyze_instrument_characteristics(msi_data::MSIData; sample_indices::A
end
"""
analyze_signal_quality(msi_data::MSIData; sample_size::Int=100)::Dict
analyze_signal_quality(msi_data::MSIData; sample_indices)::Dict
Analyzes noise characteristics, signal-to-noise ratios, and overall signal quality.
Analyzes a sample of spectra to assess signal quality, including noise levels,
Signal-to-Noise Ratio (SNR), and Total Ion Current (TIC) variation.
# Arguments
- `msi_data::MSIData`: The main MSI data object.
- `sample_indices::AbstractVector{Int}`: The indices of spectra to sample for the analysis.
# Returns
- `Dict{Symbol, Any}`: A dictionary of signal quality metrics:
- `:noise_mean`, `:noise_std`, `:noise_cv`: Statistics of the noise level.
- `:snr_mean`, `:snr_median`, `:snr_95th`: Distribution statistics of the estimated SNR.
- `:tic_mean`, `:tic_std`, `:tic_cv`: Statistics of the Total Ion Current.
"""
function analyze_signal_quality(msi_data::MSIData; sample_indices::AbstractVector{Int})::Dict
results = Dict{Symbol, Any}()
@@ -415,9 +493,21 @@ function analyze_signal_quality(msi_data::MSIData; sample_indices::AbstractVecto
end
"""
analyze_mass_accuracy_global(msi_data::MSIData, reference_peaks::Dict, sample_size::Int)::Dict
analyze_mass_accuracy_global(msi_data, reference_peaks; spectrum_indices)::Dict
Analyzes mass accuracy across the dataset using reference peaks.
Performs a global mass accuracy analysis across a sample of spectra and suggests an
adaptive binning tolerance.
# Arguments
- `msi_data::MSIData`: The main MSI data object.
- `reference_peaks::Dict`: A dictionary of known reference peaks.
- `spectrum_indices::AbstractVector{Int}`: The indices of spectra to sample for the analysis.
# Returns
- `Dict{Symbol, Any}`: A dictionary containing:
- `:global_accuracy`: The `NamedTuple` report from `analyze_mass_accuracy`.
- `:suggested_bin_tolerance`: An adaptive tolerance in PPM for peak binning, derived
from the mass accuracy results.
"""
function analyze_mass_accuracy_global(msi_data::MSIData, reference_peaks::Dict;
spectrum_indices::AbstractVector{Int})::Dict
@@ -431,7 +521,7 @@ function analyze_mass_accuracy_global(msi_data::MSIData, reference_peaks::Dict;
empty_report = (
mean_ppm_error = NaN, median_ppm_error = NaN, std_ppm_error = NaN,
min_ppm_error = NaN, max_ppm_error = NaN, total_matched_peaks = 0,
total_spectra_analyzed = 0
total_spectra_analyzed = 0, ppm_error_distribution = Float64[]
)
results[:global_accuracy] = empty_report
results[:suggested_bin_tolerance] = 20.0 # Default
@@ -444,7 +534,7 @@ function analyze_mass_accuracy_global(msi_data::MSIData, reference_peaks::Dict;
results[:global_accuracy] = accuracy_report
results[:suggested_bin_tolerance] = calculate_adaptive_bin_tolerance(
collect(Iterators.flatten([accuracy_report.mean_ppm_error])) # Simplified - would need actual distribution
accuracy_report.ppm_error_distribution
)
println(" - Mean PPM error: $(round(accuracy_report.mean_ppm_error, digits=2))")
@@ -454,9 +544,21 @@ function analyze_mass_accuracy_global(msi_data::MSIData, reference_peaks::Dict;
end
"""
analyze_spatial_regions(msi_data::MSIData, region_masks::Dict, reference_peaks::Dict)::Dict
analyze_spatial_regions(msi_data, region_masks, reference_peaks)::Dict
Analyzes different spatial regions for variations in signal quality and mass accuracy.
Analyzes different spatial regions for variations in mass accuracy. This function is a
wrapper around `find_ppm_error_by_region` and summarizes the results.
# Arguments
- `msi_data::MSIData`: The main MSI data object.
- `region_masks::Dict`: A dictionary of named `BitMatrix` masks for each region.
- `reference_peaks::Dict`: A dictionary of known reference peaks.
# Returns
- `Dict{Symbol, Any}`: A dictionary containing:
- `:regional_ppm_errors`: A dictionary mapping each region name to its mass accuracy report.
- `:max_regional_ppm_difference`: The difference between the highest and lowest mean PPM
error across all analyzed regions.
"""
function analyze_spatial_regions(msi_data::MSIData, region_masks::Dict, reference_peaks::Dict)::Dict
results = Dict{Symbol, Any}()
@@ -484,9 +586,24 @@ function analyze_spatial_regions(msi_data::MSIData, region_masks::Dict, referenc
end
"""
analyze_peak_characteristics(msi_data::MSIData, sample_size::Int)::Dict
analyze_peak_characteristics(msi_data, instrument_analysis, mass_accuracy_results; spectrum_indices)::Dict
Analyzes peak shape, width, and quality characteristics.
Analyzes peak shape, width, and quality from a sample of spectra. The behavior
adapts based on whether the data is in `:profile` or `:centroid` mode.
# Arguments
- `msi_data::MSIData`: The main MSI data object.
- `instrument_analysis::Dict`: The output from `analyze_instrument_characteristics`.
- `mass_accuracy_results`: The output from `analyze_mass_accuracy_global`.
- `spectrum_indices::AbstractVector{Int}`: The indices of spectra to sample.
# Returns
- `Dict{Symbol, Any}`: A dictionary of peak metrics:
- `:mean_fwhm_ppm`, `:median_fwhm_ppm`: Statistics of Full Width at Half Maximum (FWHM).
For centroid data, this is estimated from mass accuracy.
- `:mean_gaussian_r2`: The average goodness-of-fit to a Gaussian shape (profile data only).
- `:peak_resolution_estimate`: An estimate of instrument resolution based on FWHM.
- `:mean_peaks_per_spectrum`: The average number of peaks detected per spectrum.
"""
function analyze_peak_characteristics(msi_data::MSIData, instrument_analysis::Dict, mass_accuracy_results;
spectrum_indices::AbstractVector{Int})::Dict
@@ -508,12 +625,21 @@ function analyze_peak_characteristics(msi_data::MSIData, instrument_analysis::Di
if isempty(spectrum_indices)
@warn "No indices to sample for peak characteristics analysis."
# Provide sensible defaults if no analysis can be run
estimated_fwhm = estimated_mean_ppm_error * (acquisition_mode == :profile ? 3 : 2)
results[:mean_fwhm_ppm] = estimated_fwhm
results[:median_fwhm_ppm] = estimated_fwhm
results[:mean_gaussian_r2] = acquisition_mode == :profile ? 0.7 : 0.9
results[:peak_resolution_estimate] = 1e6 / estimated_fwhm
results[:mean_peaks_per_spectrum] = 0
if acquisition_mode == :centroid
# Much more permissive defaults for centroid data
results[:mean_fwhm_ppm] = 50.0
results[:median_fwhm_ppm] = 50.0
results[:mean_gaussian_r2] = 0.0 # Disable shape filtering for centroids
results[:peak_resolution_estimate] = 20000.0
results[:mean_peaks_per_spectrum] = 1000
else
estimated_fwhm = estimated_mean_ppm_error * (acquisition_mode == :profile ? 3 : 2)
results[:mean_fwhm_ppm] = estimated_fwhm
results[:median_fwhm_ppm] = estimated_fwhm
results[:mean_gaussian_r2] = acquisition_mode == :profile ? 0.7 : 0.9
results[:peak_resolution_estimate] = 1e6 / estimated_fwhm
results[:mean_peaks_per_spectrum] = 0
end
return results
end
@@ -537,7 +663,7 @@ function analyze_peak_characteristics(msi_data::MSIData, instrument_analysis::Di
meta = msi_data.spectra_metadata[idx]
# Detect peaks with lower SNR threshold to find more peaks
peaks = detect_peaks_profile(mz, intensity; snr_threshold=2.0)
peaks = detect_peaks_profile_core(mz, intensity; snr_threshold=2.0)
push!(peak_counts, length(peaks))
if !isempty(peaks)
@@ -600,12 +726,10 @@ function analyze_peak_characteristics(msi_data::MSIData, instrument_analysis::Di
println(" Analyzing peak characteristics for CENTROID mode from $(length(spectrum_indices)) sample spectra...")
peak_counts = Int[]
# peak_intensities = Float64[] # Not strictly needed for these metrics
_iterate_spectra_fast(msi_data, spectrum_indices) do idx, mz, intensity
if !isempty(mz)
push!(peak_counts, length(mz))
# append!(peak_intensities, intensity) # If needed for other metrics
end
end
@@ -619,16 +743,16 @@ function analyze_peak_characteristics(msi_data::MSIData, instrument_analysis::Di
results[:total_peaks_detected] = 0
end
# For centroid data, FWHM is estimated from mass accuracy
estimated_fwhm = estimated_mean_ppm_error * 2 # Centroid peaks are narrower, factor of 2-3 is common
results[:mean_fwhm_ppm] = estimated_fwhm
results[:median_fwhm_ppm] = estimated_fwhm # Defaulting median to mean
results[:mean_gaussian_r2] = 0.9 # Default for centroid, assuming good peak shapes
results[:peak_resolution_estimate] = 1e6 / estimated_fwhm
# For centroid data, use much more permissive parameters
# Don't estimate FWHM from mass accuracy - use reasonable defaults
results[:mean_fwhm_ppm] = 50.0 # Reasonable default for centroid data
results[:median_fwhm_ppm] = 50.0
results[:mean_gaussian_r2] = 0.0 # Disable shape filtering for centroids
results[:peak_resolution_estimate] = 20000.0 # Reasonable estimate
println(" - Mean peaks per spectrum: $(round(results[:mean_peaks_per_spectrum], digits=1))")
println(" - Estimated peak width: $(round(estimated_fwhm, digits=2)) ppm")
println(" - Estimated resolution: $(round(results[:peak_resolution_estimate], digits=0))")
println(" - Using permissive FWHM for centroid data: 50.0 ppm")
println(" - Shape filtering disabled for centroid data")
end
# Common prints
@@ -641,7 +765,16 @@ end
"""
generate_preprocessing_recommendations(analysis_results::Dict)::Dict{Symbol, Any}
Generates intelligent preprocessing recommendations based on the analysis results.
Generates intelligent preprocessing recommendations by synthesizing the results from
various analysis functions (`analyze_instrument_characteristics`, `analyze_signal_quality`, etc.).
# Arguments
- `analysis_results::Dict`: A dictionary containing the comprehensive analysis results from
the `run_preprocessing_analysis` pipeline.
# Returns
- `Dict{Symbol, Any}`: A dictionary where keys are preprocessing step names (e.g., `:smoothing`,
`:peak_picking`) and values are dictionaries of recommended parameters for that step.
"""
function generate_preprocessing_recommendations(analysis_results::Dict)::Dict{Symbol, Any}
recommendations = Dict{Symbol, Any}()
@@ -651,14 +784,17 @@ function generate_preprocessing_recommendations(analysis_results::Dict)::Dict{Sy
mass_accuracy = get(analysis_results, :mass_accuracy, Dict())
peak_analysis = get(analysis_results, :peak_analysis, Dict())
# Stabilization Recommendations
recommendations[:stabilization] = generate_stabilization_recommendations(signal_analysis)
# Baseline Correction Recommendations
recommendations[:baseline_correction] = generate_baseline_recommendations(inst_analysis, signal_analysis)
# Smoothing Recommendations
recommendations[:smoothing] = generate_smoothing_recommendations(inst_analysis, peak_analysis)
# Peak Picking Recommendations
recommendations[:peak_picking] = generate_peak_picking_recommendations(signal_analysis, peak_analysis)
# Peak Picking Recommendations - pass instrument analysis
recommendations[:peak_picking] = generate_peak_picking_recommendations(signal_analysis, peak_analysis, inst_analysis)
# Normalization Recommendations
recommendations[:normalization] = generate_normalization_recommendations(signal_analysis)
@@ -672,6 +808,7 @@ function generate_preprocessing_recommendations(analysis_results::Dict)::Dict{Sy
return recommendations
end
"""Generate baseline correction recommendations based on data properties."""
function generate_baseline_recommendations(inst_analysis, signal_analysis)
recommendations = Dict{Symbol, Any}()
@@ -691,6 +828,7 @@ function generate_baseline_recommendations(inst_analysis, signal_analysis)
return recommendations
end
"""Generate smoothing recommendations based on peak width and m/z step."""
function generate_smoothing_recommendations(inst_analysis, peak_analysis)
recommendations = Dict{Symbol, Any}()
@@ -713,19 +851,33 @@ function generate_smoothing_recommendations(inst_analysis, peak_analysis)
return recommendations
end
function generate_peak_picking_recommendations(signal_analysis, peak_analysis)
"""Generate peak picking recommendations from signal and peak analyses."""
function generate_peak_picking_recommendations(signal_analysis, peak_analysis, inst_analysis)
recommendations = Dict{Symbol, Any}()
snr_threshold = get(signal_analysis, :suggested_snr, 3.0)
fwhm_ppm = get(peak_analysis, :mean_fwhm_ppm, 20.0)
acquisition_mode = get(inst_analysis, :acquisition_mode, :profile)
recommendations[:snr_threshold] = snr_threshold
recommendations[:min_peak_width_ppm] = fwhm_ppm * 0.5 # Avoid detecting noise as peaks
recommendations[:max_peak_width_ppm] = fwhm_ppm * 3.0 # Avoid merging distinct peaks
if acquisition_mode == :centroid
# Much more permissive parameters for centroid data
recommendations[:snr_threshold] = 2.0 # Lower threshold for centroid
recommendations[:min_peak_width_ppm] = 0.0 # No minimum width for centroids
recommendations[:max_peak_width_ppm] = 200.0 # Very wide maximum for centroids
recommendations[:reason] = "Centroid data: using permissive parameters"
else
# Existing profile mode logic
snr_threshold = get(signal_analysis, :suggested_snr, 3.0)
fwhm_ppm = get(peak_analysis, :mean_fwhm_ppm, 20.0)
recommendations[:snr_threshold] = snr_threshold
recommendations[:min_peak_width_ppm] = fwhm_ppm * 0.5
recommendations[:max_peak_width_ppm] = fwhm_ppm * 3.0
recommendations[:reason] = "Profile data: using standard parameters"
end
return recommendations
end
"""Generate normalization recommendations based on TIC variation."""
function generate_normalization_recommendations(signal_analysis)
recommendations = Dict{Symbol, Any}()
@@ -742,6 +894,7 @@ function generate_normalization_recommendations(signal_analysis)
return recommendations
end
"""Generate alignment recommendations based on calibration status and mass error."""
function generate_alignment_recommendations(mass_accuracy, inst_analysis)
recommendations = Dict{Symbol, Any}()
@@ -765,6 +918,7 @@ function generate_alignment_recommendations(mass_accuracy, inst_analysis)
return recommendations
end
"""Generate binning recommendations based on peak width and mass accuracy."""
function generate_binning_recommendations(peak_analysis, mass_accuracy)
recommendations = Dict{Symbol, Any}()
@@ -794,18 +948,47 @@ function generate_binning_recommendations(peak_analysis, mass_accuracy)
return recommendations
end
"""Generate intensity stabilization recommendations."""
function generate_stabilization_recommendations(signal_analysis)
recommendations = Dict{Symbol, Any}()
# Default to sqrt, as it's a common and generally robust transformation.
# More advanced logic could analyze intensity distribution skewness if needed.
recommendations[:method] = :sqrt
return recommendations
end
# =============================================================================
# Pre-Analysis Pipeline for Auto Parameter Determination
# =============================================================================
"""
run_preprocessing_analysis(msi_data::MSIData;
reference_peaks::Dict{Float64, String}=Dict(),
region_masks::Dict=Dict(),
sample_size::Int=100)::Dict{Symbol, Any}
run_preprocessing_analysis(msi_data; ...)
Runs a comprehensive pre-analysis pipeline to determine optimal preprocessing parameters.
This function analyzes the dataset to provide intelligent defaults for preprocessing steps.
This function orchestrates a series of analysis steps on a sample of the dataset to
provide intelligent defaults for a full preprocessing workflow.
The pipeline consists of several phases:
1. **Instrument & Data Characteristics**: Infers acquisition mode, m/z axis type, etc.
2. **Noise & Signal Quality**: Estimates noise, SNR, and TIC variation.
3. **Mass Accuracy**: Calculates PPM error against reference peaks (if provided).
4. **Spatial Regions**: Analyzes regional variations (if masks are provided).
5. **Peak Characteristics**: Measures peak width, shape, and density.
6. **Recommendations**: Synthesizes all analysis results into actionable parameter suggestions.
# Arguments
- `msi_data::MSIData`: The main MSI data object.
- `reference_peaks::Dict`: Optional. Known m/z values for mass accuracy analysis.
- `region_masks::Dict`: Optional. Named `BitMatrix` masks for regional analysis.
- `sample_size::Int`: The number of spectra to sample for the analysis.
- `mask_path::String`: Optional path to a PNG mask to restrict analysis to a specific ROI.
- `spectrum_indices::AbstractVector{Int}`: Optional vector of indices to restrict analysis to,
overriding `mask_path` and `sample_size` for selection.
# Returns
- `Dict{Symbol, Any}`: A nested dictionary containing the results of each analysis phase
and a final `:recommendations` dictionary. The recommendations are also stored in
`msi_data.preprocessing_hints`.
"""
function run_preprocessing_analysis(msi_data::MSIData;
reference_peaks::Dict{Float64, String}=Dict{Float64, String}(),
@@ -1019,7 +1202,7 @@ function calculate_resolution_fwhm(mz::Real, profile_mz::AbstractVector{<:Real},
return fwhm > 0 ? Float64(mz) / fwhm : NaN
end
# Helper functions for FWHM calculation
"""Helper to find the last index in a vector with a value below a threshold, used for FWHM."""
function find_last_below(v::AbstractVector{<:Real}, threshold::Real)
for i in length(v):-1:2
if v[i] >= threshold && v[i-1] < threshold
@@ -1029,6 +1212,7 @@ function find_last_below(v::AbstractVector{<:Real}, threshold::Real)
return 0
end
"""Helper to find the first index in a vector with a value below a threshold, used for FWHM."""
function find_first_below(v::AbstractVector{<:Real}, threshold::Real)
for i in 1:(length(v)-1)
if v[i] >= threshold && v[i+1] < threshold
@@ -1270,10 +1454,11 @@ function main_precalculation(msi_data::MSIData;
recs = get(analysis_results, :recommendations, Dict())
signal_analysis = get(analysis_results, :signal_analysis, Dict())
peak_analysis = get(analysis_results, :peak_analysis, Dict())
mass_accuracy = get(analysis_results, :mass_accuracy, Dict())
mass_accuracy = get(analysis_results, :mass_accuracy, nothing) # Can be nothing
inst_analysis = get(analysis_results, :instrument_analysis, Dict())
# Initialize parameter dictionaries for each step
stab_params = Dict{Symbol, Any}()
cal_params = Dict{Symbol, Any}()
sm_params = Dict{Symbol, Any}()
bc_params = Dict{Symbol, Any}()
@@ -1284,11 +1469,22 @@ function main_precalculation(msi_data::MSIData;
pb_params = Dict{Symbol, Any}()
# --- Populate Parameters for each step ---
# Stabilization
if !isempty(recs) && haskey(recs, :stabilization)
stab_rec = recs[:stabilization]
stab_params[:method] = get(stab_rec, :method, :sqrt)
else
stab_params[:method] = :sqrt # Default
end
# Calibration & Alignment (Note: These are intertwined in the current logic)
calibration_required = false
mean_ppm_error = get(get(mass_accuracy, :global_accuracy, Dict()), :mean_ppm_error, NaN)
suggested_bin_tol = get(mass_accuracy, :suggested_bin_tolerance, NaN)
mean_ppm_error = NaN
suggested_bin_tol = NaN
if mass_accuracy !== nothing
mean_ppm_error = get(get(mass_accuracy, :global_accuracy, Dict()), :mean_ppm_error, NaN)
suggested_bin_tol = get(mass_accuracy, :suggested_bin_tolerance, NaN)
end
if !isempty(recs) && haskey(recs, :alignment) && get(recs[:alignment], :required, false)
calibration_required = true
@@ -1400,89 +1596,114 @@ function main_precalculation(msi_data::MSIData;
end
# Peak Picking
# Robust method selection with fallback
acquisition_mode = get(inst_analysis, :acquisition_mode, :profile) # Default to profile
# Robust method selection based on acquisition mode
acquisition_mode = get(inst_analysis, :acquisition_mode, :unknown)
pp_params[:method] = acquisition_mode == :profile ? :profile : :centroid
if !isempty(recs) && haskey(recs, :peak_picking)
pk_rec = recs[:peak_picking]
pp_params[:snr_threshold] = get(pk_rec, :snr_threshold, 3.0) # Default to 3.0
pp_params[:min_peak_width_ppm] = get(pk_rec, :min_peak_width_ppm, nothing)
pp_params[:max_peak_width_ppm] = get(pk_rec, :max_peak_width_ppm, nothing)
else
pp_params[:snr_threshold] = 3.0 # Default to 3.0
pp_params[:min_peak_width_ppm] = nothing
pp_params[:max_peak_width_ppm] = nothing
end
# Robust prominence calculation with safety cap
estimated_noise = get(signal_analysis, :noise_mean, NaN)
if isfinite(estimated_noise)
# Never be more aggressive than 0.05, a reasonable upper limit
calculated_prominence = round(estimated_noise * 2, digits=4)
pp_params[:min_peak_prominence] = min(calculated_prominence, 0.05)
else
# Fallback to a safe, non-aggressive value if noise couldn't be estimated
pp_params[:min_peak_prominence] = 0.01
end
if acquisition_mode == :centroid
# Much more permissive parameters for centroid data
pp_params[:snr_threshold] = 2.0 # Lower for centroid
pp_params[:min_peak_width_ppm] = 0.0 # No minimum width
pp_params[:max_peak_width_ppm] = 200.0 # Very wide maximum
pp_params[:min_peak_shape_r2] = 0.0 # Disable shape filtering
# Much lower prominence threshold for centroid
estimated_noise = get(signal_analysis, :noise_mean, NaN)
if isfinite(estimated_noise)
pp_params[:min_peak_prominence] = max(estimated_noise * 0.5, 0.001) # Much lower
else
pp_params[:min_peak_prominence] = 0.001 # Very permissive
end
pp_params[:half_window] = 2 # Smaller window for centroid data
pp_params[:merge_peaks_tolerance] = 10.0 # More permissive merging
else # Profile mode logic
if !isempty(recs) && haskey(recs, :peak_picking)
pk_rec = recs[:peak_picking]
pp_params[:snr_threshold] = get(pk_rec, :snr_threshold, 2.0) # Default to 2.0
pp_params[:min_peak_width_ppm] = get(pk_rec, :min_peak_width_ppm, nothing)
pp_params[:max_peak_width_ppm] = get(pk_rec, :max_peak_width_ppm, nothing)
else
pp_params[:snr_threshold] = 2.0 # Default to 2.0
pp_params[:min_peak_width_ppm] = nothing
pp_params[:max_peak_width_ppm] = nothing
end
# Robust prominence calculation with safety cap for profile
estimated_noise = get(signal_analysis, :noise_mean, NaN)
if isfinite(estimated_noise)
calculated_prominence = round(estimated_noise * 2, digits=4)
pp_params[:min_peak_prominence] = min(calculated_prominence, 0.005)
else
pp_params[:min_peak_prominence] = 0.005
end
if isfinite(suggested_bin_tol)
pp_params[:merge_peaks_tolerance] = round(suggested_bin_tol / 2, digits=4)
else
pp_params[:merge_peaks_tolerance] = nothing
end
if isfinite(suggested_bin_tol)
pp_params[:merge_peaks_tolerance] = round(suggested_bin_tol / 2, digits=4)
else
pp_params[:merge_peaks_tolerance] = nothing
end
# Robust half_window calculation with safety floor
mean_fwhm_ppm = get(peak_analysis, :mean_fwhm_ppm, NaN)
avg_mz_step = get(inst_analysis, :average_mz_step, NaN)
if isfinite(mean_fwhm_ppm) && isfinite(avg_mz_step) && avg_mz_step > 0
fwhm_mz = 500.0 * mean_fwhm_ppm / 1e6 # At typical m/z 500
window_points = fwhm_mz / avg_mz_step
calculated_half_window = ceil(Int, window_points / 2)
# Ensure half_window is at least 3, a safe absolute minimum
pp_params[:half_window] = max(calculated_half_window, 3)
else
# Fallback if calculation is not possible
pp_params[:half_window] = 5
end
# Robust R^2 calculation with floor
mean_r2 = get(peak_analysis, :mean_gaussian_r2, NaN)
if isfinite(mean_r2)
pp_params[:min_peak_shape_r2] = round(max(0.5, mean_r2 * 0.8), digits=2)
else
# Fallback to a reasonable default
pp_params[:min_peak_shape_r2] = 0.6
# Robust half_window calculation with safety floor for profile
mean_fwhm_ppm = get(peak_analysis, :mean_fwhm_ppm, NaN)
avg_mz_step = get(inst_analysis, :average_mz_step, NaN)
if isfinite(mean_fwhm_ppm) && isfinite(avg_mz_step) && avg_mz_step > 0
fwhm_mz = 500.0 * mean_fwhm_ppm / 1e6 # At typical m/z 500
window_points = fwhm_mz / avg_mz_step
calculated_half_window = ceil(Int, window_points / 2)
pp_params[:half_window] = max(calculated_half_window, 3)
else
pp_params[:half_window] = 5
end
# Robust R^2 calculation with floor for profile
mean_r2 = get(peak_analysis, :mean_gaussian_r2, NaN)
if isfinite(mean_r2)
pp_params[:min_peak_shape_r2] = round(max(0.0, mean_r2 * 0.8), digits=2)
else
pp_params[:min_peak_shape_r2] = 0.0
end
end
# Peak Selection
if haskey(pp_params, :snr_threshold) && pp_params[:snr_threshold] !== nothing
ps_params[:min_snr] = pp_params[:snr_threshold]
else
ps_params[:min_snr] = nothing
end
if !isempty(peak_analysis)
mean_fwhm = get(peak_analysis, :mean_fwhm_ppm, NaN)
if isfinite(mean_fwhm)
ps_params[:min_fwhm_ppm] = round(mean_fwhm * 0.5, digits=2)
ps_params[:max_fwhm_ppm] = round(mean_fwhm * 2.5, digits=2)
if acquisition_mode == :centroid
# Much more permissive parameters for centroid data
ps_params[:min_snr] = 1.5 # Even lower than picking threshold
ps_params[:min_fwhm_ppm] = 0.0 # No minimum
ps_params[:max_fwhm_ppm] = 500.0 # Very wide maximum
ps_params[:min_shape_r2] = 0.0 # Disable shape filtering
ps_params[:frequency_threshold] = nothing # User input dependent / Hard to determine
ps_params[:correlation_threshold] = nothing # Hard to determine
else # Profile mode logic
if haskey(pp_params, :snr_threshold) && pp_params[:snr_threshold] !== nothing
ps_params[:min_snr] = pp_params[:snr_threshold]
else
ps_params[:min_snr] = nothing
end
if !isempty(peak_analysis)
mean_fwhm = get(peak_analysis, :mean_fwhm_ppm, NaN)
if isfinite(mean_fwhm)
ps_params[:min_fwhm_ppm] = round(mean_fwhm * 0.5, digits=2)
ps_params[:max_fwhm_ppm] = round(mean_fwhm * 2.5, digits=2)
else
ps_params[:min_fwhm_ppm] = nothing
ps_params[:max_fwhm_ppm] = nothing
end
mean_r2 = get(peak_analysis, :mean_gaussian_r2, NaN)
if isfinite(mean_r2)
ps_params[:min_shape_r2] = round(max(0.0, mean_r2 * 0.8), digits=2)
else
ps_params[:min_shape_r2] = 0.0 # Adjusted fallback
end
else
ps_params[:min_fwhm_ppm] = nothing
ps_params[:max_fwhm_ppm] = nothing
end
if isfinite(mean_r2)
ps_params[:min_shape_r2] = round(max(0.5, mean_r2 * 0.8), digits=2)
else
ps_params[:min_shape_r2] = nothing
end
else
ps_params[:min_fwhm_ppm] = nothing
ps_params[:max_fwhm_ppm] = nothing
ps_params[:min_shape_r2] = nothing
ps_params[:frequency_threshold] = nothing
ps_params[:correlation_threshold] = nothing
end
ps_params[:frequency_threshold] = nothing # User input dependent / Hard to determine
ps_params[:correlation_threshold] = nothing # Hard to determine
# Peak Binning
@@ -1525,6 +1746,7 @@ function main_precalculation(msi_data::MSIData;
end
return Dict(
:Stabilization => stab_params,
:Calibration => cal_params,
:Smoothing => sm_params,
:BaselineCorrection => bc_params,
@@ -1532,6 +1754,6 @@ function main_precalculation(msi_data::MSIData;
:PeakPicking => pp_params,
:PeakAlignment => pa_params,
:PeakSelection => ps_params,
:PeakBinningParams => pb_params
:PeakBinning => pb_params
)
end
+199 -226
View File
@@ -21,6 +21,7 @@ using ContinuousWavelets # For CWT peak detection
using ImageFiltering # For localmaxima in detect_peaks_wavelet
using Interpolations # For calibration
using Loess # For robust peak alignment
using Base.Threads # For multithreading in apply functions
# =============================================================================
# Data Structures
@@ -30,6 +31,13 @@ using Loess # For robust peak alignment
FeatureMatrix
A struct to hold the final feature matrix generated from the preprocessing pipeline.
# Fields
- `matrix::Array{Float64,2}`: The feature matrix where rows correspond to samples (spectra)
and columns correspond to features (m/z bins).
- `mz_bins::Vector{Tuple{Float64,Float64}}`: A vector of tuples defining the start and
end m/z for each bin (column) in the `matrix`.
- `sample_ids::Vector{Int}`: A vector of identifiers for each sample (row) in the `matrix`.
"""
struct FeatureMatrix
matrix::Array{Float64,2}
@@ -38,9 +46,18 @@ struct FeatureMatrix
end
"""
MutableSpectrum
A mutable struct to hold spectrum data. Using a mutable struct allows
in-place modification of fields (like intensity or m/z), which dramatically
reduces memory allocations compared to creating new immutable tuples at each step.
# Fields
- `id::Int`: A unique identifier for the spectrum.
- `mz::AbstractVector{Float64}`: The m/z values of the spectrum.
- `intensity::AbstractVector{Float64}`: The intensity values corresponding to the m/z values.
- `peaks::Vector{NamedTuple}`: A vector of detected peaks, each a `NamedTuple` with fields
like `:mz`, `:intensity`, `:fwhm`, etc.
"""
mutable struct MutableSpectrum
id::Int
@@ -62,8 +79,18 @@ abstract type AbstractPreprocessingStep end
"""
Calibration(; method=:internal_standards, ...)
A preprocessing step for mass calibration. Set a parameter to `nothing` to use an
auto-determined value from the data where applicable.
A preprocessing step for mass calibration. Corrects systematic mass errors in the m/z axis.
Set a parameter to `nothing` to use an auto-determined value from the data where applicable.
# Arguments
- `method::Symbol`: The calibration method. Currently supports `:internal_standards`.
- `internal_standards::Union{Dict{Float64, String}, Nothing}`: A dictionary mapping theoretical
m/z values of internal standards to their names.
- `base_peak_mz_references::Union{Vector{Float64}, Nothing}`: A vector of reference m/z values
for base peak calibration (not yet implemented).
- `ppm_tolerance::Union{Float64, Nothing}`: The tolerance in parts-per-million (ppm) for matching
peaks to internal standards.
- `fit_order::Int`: The polynomial order for the calibration fit (e.g., 1 for linear, 2 for quadratic).
"""
struct Calibration <: AbstractPreprocessingStep
method::Symbol
@@ -80,7 +107,16 @@ end
"""
BaselineCorrection(; method=:snip, ...)
A preprocessing step for baseline correction.
A preprocessing step for baseline correction. This step estimates and subtracts the
background noise (baseline) from the spectral intensities.
# Arguments
- `method::Symbol`: The algorithm to use. Options include `:snip` (Sensitive Nonlinear
Iterative Peak clipping), `:convex_hull`, and `:median`.
- `iterations::Union{Int, Nothing}`: The number of iterations for the SNIP algorithm.
A higher number results in a more aggressive baseline.
- `window::Union{Int, Nothing}`: The window size for the `:median` method, determining
the local region for median calculation.
"""
struct BaselineCorrection <: AbstractPreprocessingStep
method::Symbol
@@ -95,7 +131,15 @@ end
"""
Smoothing(; method=:savitzky_golay, ...)
A preprocessing step for spectral smoothing.
A preprocessing step for spectral smoothing. This helps to reduce high-frequency noise
in the intensity data.
# Arguments
- `method::Symbol`: The smoothing algorithm. Options are `:savitzky_golay` and `:moving_average`.
- `window::Union{Int, Nothing}`: The size of the smoothing window. For Savitzky-Golay,
this must be an odd integer.
- `order::Union{Int, Nothing}`: The polynomial order for the Savitzky-Golay filter. Must be
less than the window size.
"""
struct Smoothing <: AbstractPreprocessingStep
method::Symbol
@@ -112,7 +156,15 @@ end
"""
Normalization(; method=:tic)
A preprocessing step for intensity normalization.
A preprocessing step for intensity normalization. This corrects for variations in total
ion current between different spectra, making them more comparable.
# Arguments
- `method::Symbol`: The normalization method. Options include:
- `:tic`: Total Ion Current normalization (divides by the sum of intensities).
- `:median`: Divides by the median intensity.
- `:rms`: Root Mean Square normalization.
- `:none`: No normalization is applied.
"""
struct Normalization <: AbstractPreprocessingStep
method::Symbol
@@ -125,7 +177,25 @@ end
"""
PeakPicking(; method=nothing, ...)
A preprocessing step for peak detection.
A preprocessing step for peak detection. This step identifies peaks (signals of interest)
in the profile or centroided spectra.
# Arguments
- `method::Union{Symbol, Nothing}`: The peak detection algorithm.
- `:profile`: For profile-mode data, using local maxima and quality filters.
- `:wavelet`: Continuous Wavelet Transform (CWT) based peak detection.
- `:centroid`: For centroid-mode data, essentially a filtering step.
- `snr_threshold::Union{Float64, Nothing}`: Signal-to-Noise Ratio threshold. Peaks with SNR
below this value are discarded.
- `half_window::Union{Int, Nothing}`: The number of data points to the left and right of a
potential peak to consider for local maximum detection (for `:profile`).
- `min_peak_prominence::Union{Float64, Nothing}`: The minimum required prominence of a peak,
expressed as a fraction of its height.
- `merge_peaks_tolerance::Union{Float64, Nothing}`: The m/z tolerance within which to merge
adjacent peaks, keeping the more intense one.
- `min_peak_width_ppm, max_peak_width_ppm`: Minimum and maximum acceptable peak width (FWHM) in ppm.
- `min_peak_shape_r2`: Minimum R-squared value from a Gaussian fit to the peak, used as a
quality measure for peak shape.
"""
struct PeakPicking <: AbstractPreprocessingStep
method::Union{Symbol, Nothing} # :profile, :wavelet, :centroid
@@ -145,7 +215,20 @@ end
"""
PeakAlignment(; method=:lowess, ...)
A preprocessing step for peak alignment.
A preprocessing step for peak alignment. This corrects for m/z shifts between spectra,
ensuring that the same analyte peak appears at the same m/z across all samples.
# Arguments
- `method::Symbol`: The alignment algorithm. Options: `:lowess`, `:linear`, `:ransac`.
- `span::Union{Float64, Nothing}`: The span parameter for LOWESS regression, controlling smoothness.
- `tolerance::Union{Float64, Nothing}`: The tolerance for matching peaks between the target
and reference spectrum.
- `tolerance_unit::Union{Symbol, Nothing}`: The unit for `tolerance`, either `:mz` (absolute)
or `:ppm` (relative).
- `max_shift_ppm::Union{Float64, Nothing}`: The maximum allowed m/z shift in ppm to prevent
spurious peak matches.
- `min_matched_peaks::Union{Int, Nothing}`: The minimum number of matching peaks required
to perform the alignment.
"""
struct PeakAlignment <: AbstractPreprocessingStep
method::Symbol
@@ -163,7 +246,19 @@ end
"""
PeakSelection(; frequency_threshold=nothing, ...)
A preprocessing step for peak selection (filtering).
A preprocessing step for peak selection (filtering). After peak detection, this step
filters the detected peaks based on various quality criteria to remove noise and
irrelevant signals.
# Arguments
- `frequency_threshold::Union{Float64, Nothing}`: The minimum fraction of spectra in which a
peak must be present to be kept.
- `min_snr::Union{Float64, Nothing}`: Minimum Signal-to-Noise Ratio.
- `min_fwhm_ppm, max_fwhm_ppm`: Minimum and maximum Full Width at Half Maximum in ppm.
- `min_shape_r2::Union{Float64, Nothing}`: Minimum R-squared value from a Gaussian fit,
filtering for good peak shape.
- `correlation_threshold::Union{Float64, Nothing}`: Minimum correlation with neighboring
peaks (not yet implemented).
"""
struct PeakSelection <: AbstractPreprocessingStep
frequency_threshold::Union{Float64, Nothing}
@@ -179,11 +274,24 @@ struct PeakSelection <: AbstractPreprocessingStep
end
"""
PeakBinningParams(; method=:adaptive, ...)
PeakBinning(; method=:adaptive, ...)
A preprocessing step for peak binning.
A preprocessing step for peak binning. This step groups peaks from all spectra into
common m/z bins to generate a feature matrix.
# Arguments
- `method::Symbol`: The binning strategy.
- `:adaptive`: Creates bins based on the density of detected peaks.
- `:uniform`: Creates a fixed number of equally spaced bins over the m/z range.
- `tolerance, tolerance_unit`: Tolerance for grouping peaks into a bin in `:adaptive` mode.
- `frequency_threshold`: The minimum fraction of spectra a bin must contain a peak in to be kept.
- `min_peak_per_bin`: The minimum number of individual peaks required to form a bin in `:adaptive` mode.
- `max_bin_width_ppm`: Maximum width of a bin in ppm for `:adaptive` mode.
- `intensity_weighted_centers`: If `true`, calculates bin centers as an intensity-weighted
average of the peaks within it.
- `num_uniform_bins`: The number of bins to create for the `:uniform` method.
"""
struct PeakBinningParams <: AbstractPreprocessingStep
struct PeakBinning <: AbstractPreprocessingStep
method::Symbol
tolerance::Union{Float64, Nothing}
tolerance_unit::Union{Symbol, Nothing}
@@ -193,7 +301,7 @@ struct PeakBinningParams <: AbstractPreprocessingStep
intensity_weighted_centers::Bool
num_uniform_bins::Union{Int, Nothing}
function PeakBinningParams(; method=:adaptive, tolerance=nothing, tolerance_unit=nothing, frequency_threshold=nothing, min_peak_per_bin=nothing, max_bin_width_ppm=nothing, intensity_weighted_centers=true, num_uniform_bins=nothing)
function PeakBinning(; method=:adaptive, tolerance=nothing, tolerance_unit=nothing, frequency_threshold=nothing, min_peak_per_bin=nothing, max_bin_width_ppm=nothing, intensity_weighted_centers=true, num_uniform_bins=nothing)
new(method, tolerance, tolerance_unit, frequency_threshold, min_peak_per_bin, max_bin_width_ppm, intensity_weighted_centers, num_uniform_bins)
end
end
@@ -237,7 +345,7 @@ Checks include:
- `mz` and `intensity` have the same length.
- All `m/z` values are finite and non-negative.
- All `intensity` values are finite and non-negative.
- `m/z` values are strictly increasing (no duplicates or decreasing values).
- `m/z` values are monotonically non-decreasing.
"""
function validate_spectrum(mz::AbstractVector{<:Real}, intensity::AbstractVector{<:Real})::Bool
# 1. Check for empty vectors
@@ -278,11 +386,22 @@ end
# =============================================================================
"""
transform_intensity(intensity; method=:sqrt) -> Vector
transform_intensity_core(intensity; method=:sqrt) -> Vector
Applies a variance-stabilizing transformation to the intensity vector.
Applies a variance-stabilizing transformation to the intensity vector. This can
help to make the variance of the signal more constant across the intensity range,
which is often an assumption of downstream statistical methods.
# Arguments
- `intensity::AbstractVector{<:Real}`: The input intensity values.
- `method::Symbol`: The transformation to apply. Options are:
- `:sqrt`: Square root transformation.
- `:log`: Natural log transformation.
- `:log2`: Base-2 log transformation.
- `:log10`: Base-10 log transformation.
- `:log1p`: Natural log of `1 + x`, useful for data with zeros.
"""
function transform_intensity(intensity::AbstractVector{<:Real}; method::Symbol=:sqrt)
function transform_intensity_core(intensity::AbstractVector{<:Real}; method::Symbol=:sqrt)
if method === :sqrt
return sqrt.(max.(zero(eltype(intensity)), intensity))
elseif method === :log1p
@@ -299,7 +418,7 @@ function transform_intensity(intensity::AbstractVector{<:Real}; method::Symbol=:
end
"""
smooth_spectrum(y::AbstractVector{<:Real}; method::Symbol=:savitzky_golay, window::Int=9, order::Int=2) -> Vector
smooth_spectrum_core(y::AbstractVector{<:Real}; method::Symbol=:savitzky_golay, window::Int=9, order::Int=2) -> Vector
Applies a smoothing filter to the intensity data.
@@ -309,7 +428,7 @@ Applies a smoothing filter to the intensity data.
- `window`: The window size for the filter.
- `order`: The polynomial order for Savitzky-Golay
"""
function smooth_spectrum(y::AbstractVector{<:Real}; method::Symbol=:savitzky_golay, window::Int=9, order::Int=2)
function smooth_spectrum_core(y::AbstractVector{<:Real}; method::Symbol=:savitzky_golay, window::Int=9, order::Int=2)
if window < 3
throw(ArgumentError("Window size must be at least 3"))
end
@@ -399,7 +518,9 @@ end
"""
convex_hull_baseline(y) -> Vector
Estimates the baseline of a spectrum using the convex hull algorithm.
Estimates the baseline of a spectrum using the convex hull algorithm. This method
finds the lower convex hull of the spectrum, which is then used as the baseline.
It is generally faster than SNIP but can be less flexible.
"""
function convex_hull_baseline(y::AbstractVector{<:Real})
n = length(y)
@@ -455,7 +576,7 @@ function median_baseline(y::AbstractVector{<:Real}; window::Int=20)
end
"""
apply_baseline_correction(y::AbstractVector{<:Real}; method::Symbol=:snip, iterations::Int=100, window::Int=20) -> Vector
apply_baseline_correction_core(y::AbstractVector{<:Real}; method::Symbol=:snip, iterations::Int=100, window::Int=20) -> Vector
Applies a baseline correction algorithm to the intensity data.
@@ -465,7 +586,7 @@ Applies a baseline correction algorithm to the intensity data.
- `iterations`: Iterations for SNIP method.
- `window`: Window size for median method.
"""
function apply_baseline_correction(y::AbstractVector{<:Real}; method::Symbol=:snip, iterations::Int=100, window::Int=20)
function apply_baseline_correction_core(y::AbstractVector{<:Real}; method::Symbol=:snip, iterations::Int=100, window::Int=20)
if method === :snip
return _snip_baseline_impl(y, iterations=iterations)
elseif method === :convex_hull
@@ -485,7 +606,9 @@ end
"""
tic_normalize(y) -> Vector
Normalizes spectrum intensities to the Total Ion Current (TIC).
Normalizes spectrum intensities to the Total Ion Current (TIC). Each intensity value
is divided by the sum of all intensities in the spectrum. This method assumes that the
total number of ions produced is similar for all samples.
"""
function tic_normalize(y::AbstractVector{<:Real})
s = sum(y)
@@ -496,6 +619,18 @@ end
pqn_normalize(M) -> Matrix
Performs Probabilistic Quotient Normalization (PQN) on a matrix of spectra.
This is a more robust normalization method that is less sensitive to a small
number of highly abundant, variable peaks compared to TIC.
# Steps:
1. A reference spectrum is calculated (typically the median spectrum across all samples).
2. For each spectrum, the quotients of its intensities and the reference spectrum's
intensities are calculated.
3. The median of these quotients is found for each spectrum.
4. Each spectrum is divided by its median quotient.
# Arguments
- `M::AbstractMatrix{<:Real}`: A matrix where columns are spectra and rows are m/z bins.
"""
function pqn_normalize(M::AbstractMatrix{<:Real})
M_float = collect(float.(M))
@@ -532,7 +667,7 @@ function rms_normalize(y::AbstractVector{<:Real})
end
"""
apply_normalization(y::AbstractVector{<:Real}; method::Symbol=:tic) -> Vector
apply_normalization_core(y::AbstractVector{<:Real}; method::Symbol=:tic) -> Vector
Applies a per-spectrum normalization algorithm to the intensity data.
@@ -540,7 +675,7 @@ Applies a per-spectrum normalization algorithm to the intensity data.
- `y`: The intensity data.
- `method`: The normalization method (:tic, :median, :rms, or :none).
"""
function apply_normalization(y::AbstractVector{<:Real}; method::Symbol=:tic)
function apply_normalization_core(y::AbstractVector{<:Real}; method::Symbol=:tic)::Vector
if method === :tic
return tic_normalize(y)
elseif method === :median
@@ -555,188 +690,12 @@ function apply_normalization(y::AbstractVector{<:Real}; method::Symbol=:tic)
end
end
"""
remove_matrix_peaks_from_spectrum(mz::AbstractVector{<:Real}, intensity::AbstractVector{<:Real},
matrix_peak_mzs::AbstractVector{<:Real};
tolerance::Float64=0.002, tolerance_unit::Symbol=:mz,
removal_method::Symbol=:zero_out) -> Vector{Float64}
Removes or reduces intensity around specified matrix peaks in a single spectrum.
# Arguments
- `mz`: The m/z vector of the spectrum.
- `intensity`: The intensity vector of the spectrum.
- `matrix_peak_mzs`: A list of m/z values identified as matrix peaks.
- `tolerance`: The m/z tolerance for matching matrix peaks.
- `tolerance_unit`: Unit of tolerance (:mz or :ppm).
- `removal_method`: How to remove the peaks (:zero_out or :subtract).
# Returns
- `Vector{Float64}`: The modified intensity vector.
"""
function remove_matrix_peaks_from_spectrum(mz::AbstractVector{<:Real}, intensity::AbstractVector{<:Real},
matrix_peak_mzs::AbstractVector{<:Real};
tolerance::Float64=0.002, tolerance_unit::Symbol=:mz,
removal_method::Symbol=:zero_out)
modified_intensity = copy(intensity)
for matrix_mz in matrix_peak_mzs
# Calculate dynamic tolerance if in PPM
current_tolerance = (tolerance_unit == :ppm) ? (matrix_mz * tolerance / 1e6) : tolerance
# Find indices within the tolerance window
indices_to_modify = findall(m -> abs(m - matrix_mz) <= current_tolerance, mz)
if !isempty(indices_to_modify)
if removal_method == :zero_out
modified_intensity[indices_to_modify] .= 0.0
elseif removal_method == :subtract
# Baseline-aware subtraction: replace peak with a line connecting its "feet"
idx_start = indices_to_modify[1]
idx_end = indices_to_modify[end]
# Ensure we are not at the very edge of the spectrum
if idx_start > 1 && idx_end < length(modified_intensity)
y1 = modified_intensity[idx_start - 1]
y2 = modified_intensity[idx_end + 1]
x1 = idx_start - 1
x2 = idx_end + 1
# Linearly interpolate the baseline under the peak
for i in idx_start:idx_end
# y = y1 + (y2 - y1) * (x - x1) / (x2 - x1)
baseline_val = y1 + (y2 - y1) * (i - x1) / (x2 - x1)
# Set the intensity to the baseline, but don't increase it (e.g., if baseline is above signal)
modified_intensity[i] = min(modified_intensity[i], baseline_val)
end
else
# If peak is at the edge, we can't interpolate, so just zero it out
modified_intensity[indices_to_modify] .= 0.0
end
else
@warn "Unsupported matrix peak removal method: $removal_method. Skipping."
end
end
end
return modified_intensity
end
function identify_matrix_peaks_from_blanks(
msi_data::MSIData,
blank_spectrum_tag::Symbol,
snr_threshold::Float64;
frequency_threshold::Float64=0.5, # e.g., peak must be in 50% of blanks
bin_tolerance::Float64=0.005, # m/z tolerance for binning blank peaks
bin_tolerance_unit::Symbol=:mz
)::Vector{Float64}
if !(0 < frequency_threshold <= 1.0)
throw(ArgumentError("`frequency_threshold` must be between 0 and 1 (exclusive of 0). Got: $frequency_threshold"))
end
println("Identifying matrix peaks from blank spectra (tag: $blank_spectrum_tag)...")
blank_indices = Int[]
for (i, meta) in enumerate(msi_data.spectra_metadata)
if meta.type == blank_spectrum_tag
push!(blank_indices, i)
end
end
if isempty(blank_indices)
@warn "No blank spectra found with tag: $blank_spectrum_tag. Cannot identify matrix peaks."
return Float64[]
end
all_blank_peaks = Vector{NamedTuple}[]
num_blank_spectra = 0
# Collect peaks from each blank spectrum
_iterate_spectra_fast(msi_data, blank_indices) do idx, mz, intensity
num_blank_spectra += 1
if !validate_spectrum(mz, intensity)
@warn "Blank spectrum $idx is invalid, skipping peak detection for it."
push!(all_blank_peaks, NamedTuple[]) # Add empty list to maintain count
return
end
# Assuming profile mode for matrix peak detection
peaks = detect_peaks_profile(mz, intensity; snr_threshold=snr_threshold)
push!(all_blank_peaks, peaks)
end
if isempty(all_blank_peaks) || all(isempty, all_blank_peaks)
@warn "No peaks detected in any blank spectra. Cannot identify matrix peaks."
return Float64[]
end
# Flatten all peaks from blank spectra for initial binning
flat_blank_peaks = NamedTuple[]
for peaks_in_spec in all_blank_peaks
append!(flat_blank_peaks, peaks_in_spec)
end
sort!(flat_blank_peaks, by=p->p.mz)
# Bin the detected peaks from all blanks to find common m/z features
# This is a simplified binning for matrix peak identification
binned_matrix_features = Dict{Float64, Int}() # mz_center => count of spectra it appeared in
i = 1
while i <= length(flat_blank_peaks)
current_bin_start_idx = i
current_peak = flat_blank_peaks[i]
# Calculate dynamic tolerance if in PPM
current_bin_mz = current_peak.mz
tol_val = (bin_tolerance_unit == :ppm) ? (current_bin_mz * bin_tolerance / 1e6) : bin_tolerance
j = i + 1
while j <= length(flat_blank_peaks) && (flat_blank_peaks[j].mz - current_peak.mz) <= tol_val
j += 1
end
current_bin_end_idx = j - 1
# Calculate a representative m/z for the bin (e.g., intensity-weighted average)
peaks_in_bin = flat_blank_peaks[current_bin_start_idx:current_bin_end_idx]
if !isempty(peaks_in_bin)
sum_intensity = sum(p.intensity for p in peaks_in_bin)
if sum_intensity > 0
bin_center_mz = sum(p.mz * p.intensity for p in peaks_in_bin) / sum(sum_intensity)
else
bin_center_mz = mean(p.mz for p in peaks_in_bin)
end
# Check how many blank spectra this feature appeared in
spectra_count = 0
# For each blank spectrum, check if it contains a peak within the current bin's tolerance
for spec_peaks in all_blank_peaks
if any(p -> abs(p.mz - bin_center_mz) <= tol_val, spec_peaks)
spectra_count += 1
end
end
binned_matrix_features[bin_center_mz] = spectra_count
end
i = j
end
# Filter based on frequency_threshold
matrix_peak_mzs = Float64[]
min_spectra_count = ceil(Int, num_blank_spectra * frequency_threshold)
for (mz_center, count) in binned_matrix_features
if count >= min_spectra_count
push!(matrix_peak_mzs, mz_center)
end
end
sort!(matrix_peak_mzs)
println("Identified $(length(matrix_peak_mzs)) potential matrix peaks from $(num_blank_spectra) blank spectra.")
return matrix_peak_mzs
end
# =============================================================================
# 4) Peak Detection
# =============================================================================
"""
detect_peaks_profile(mz, y; ...) -> Vector{NamedTuple}
detect_peaks_profile_core(mz, y; ...) -> Vector{NamedTuple}
Enhanced peak detection for profile-mode spectra with advanced filtering and quality metrics.
@@ -748,7 +707,7 @@ Returns a vector of NamedTuples, each representing a detected peak with:
- `snr`: Signal-to-Noise Ratio
- `prominence`: Peak prominence
"""
function detect_peaks_profile(mz::AbstractVector{<:Real}, y::AbstractVector{<:Real};
function detect_peaks_profile_core(mz::AbstractVector{<:Real}, y::AbstractVector{<:Real};
half_window::Int=10,
snr_threshold::Float64=2.0,
min_peak_prominence::Float64=0.1,
@@ -762,7 +721,7 @@ function detect_peaks_profile(mz::AbstractVector{<:Real}, y::AbstractVector{<:Re
n < 3 && return NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}[]
noise_level = mad(y, normalize=true) + eps(Float64)
ys = smooth_spectrum(y; method=:savitzky_golay, window=max(5, 2*half_window+1), order=2) # Use smoothed data for detection
ys = smooth_spectrum_core(y; method=:savitzky_golay, window=max(5, 2*half_window+1), order=2) # Use smoothed data for detection
candidate_peak_indices = Int[]
for i in 2:n-1
@@ -818,16 +777,30 @@ function detect_peaks_profile(mz::AbstractVector{<:Real}, y::AbstractVector{<:Re
end
"""
detect_peaks_wavelet(mz, intensity; ...) -> Vector{NamedTuple}
detect_peaks_wavelet_core(mz, intensity; ...) -> Vector{NamedTuple}
Detects peaks using Continuous Wavelet Transform (CWT).
Detects peaks using Continuous Wavelet Transform (CWT). CWT is effective at
identifying peaks at different scales (widths), making it robust for complex spectra.
Returns a vector of NamedTuples, each representing a detected peak with:
- `mz`: m/z value of the peak
- `intensity`: Intensity of the peak
- `snr`: Signal-to-Noise Ratio (simplified)
# Arguments
- `mz::AbstractVector`: The m/z values of the spectrum.
- `intensity::AbstractVector`: The intensity values of the spectrum.
- `scales`: A range of scales to use for the CWT. Corresponds to the widths of
the features to be detected.
- `snr_threshold`: The minimum Signal-to-Noise Ratio for a CWT-detected local maximum
in the original spectrum to be considered a peak.
- `half_window`: Used for calculating peak quality metrics like FWHM and shape R^2.
# Returns
A vector of `NamedTuple`s, each representing a detected peak with:
- `mz`: m/z value of the peak.
- `intensity`: Intensity of the peak from the original spectrum.
- `fwhm`: Full Width at Half Maximum (in ppm).
- `shape_r2`: Goodness-of-fit to a Gaussian shape.
- `snr`: Signal-to-Noise Ratio.
- `prominence`: Peak prominence (estimated as peak intensity for this method).
"""
function detect_peaks_wavelet(mz::AbstractVector, intensity::AbstractVector; scales=1:10, snr_threshold=3.0, half_window=10)::Vector{NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}}
function detect_peaks_wavelet_core(mz::AbstractVector, intensity::AbstractVector; scales=1:10, snr_threshold=3.0, half_window=10)::Vector{NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}}
n = length(intensity)
n < 10 && return NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}[]
@@ -876,7 +849,7 @@ function detect_peaks_wavelet(mz::AbstractVector, intensity::AbstractVector; sca
end
"""
detect_peaks_centroid(mz, y; ...) -> Vector{NamedTuple}
detect_peaks_centroid_core(mz, y; ...) -> Vector{NamedTuple}
Filters peaks in centroid-mode data based on intensity threshold.
@@ -884,7 +857,7 @@ Returns a vector of NamedTuples, each representing a detected peak with:
- `mz`: m/z value of the peak
- `intensity`: Intensity of the peak
"""
function detect_peaks_centroid(mz::AbstractVector{<:Real}, y::AbstractVector{<:Real}; snr_threshold::Float64=0.0)
function detect_peaks_centroid_core(mz::AbstractVector{<:Real}, y::AbstractVector{<:Real}; snr_threshold::Float64=0.0)
noise_level = mad(y, normalize=true) + eps(Float64)
detected_peaks = NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}[]
@@ -903,11 +876,11 @@ end
# =============================================================================
"""
align_peaks_lowess(ref_mz, tgt_mz; ...)
align_peaks_lowess_core(ref_mz, tgt_mz; ...)
Enhanced peak alignment with PPM tolerance and other constraints.
"""
function align_peaks_lowess(ref_mz::Vector{<:Real}, tgt_mz::Vector{<:Real};
function align_peaks_lowess_core(ref_mz::Vector{<:Real}, tgt_mz::Vector{<:Real};
method::Symbol=:linear, # :linear, :lowess, or :ransac
span::Float64=0.75, # Span for LOWESS
tolerance::Float64=0.002,
@@ -1030,15 +1003,15 @@ function align_peaks_lowess(ref_mz::Vector{<:Real}, tgt_mz::Vector{<:Real};
end
"""
find_calibration_peaks(mz, intensity, reference_masses; ...)
find_calibration_peaks_core(mz, intensity, reference_masses; ...)
Finds peaks that match a list of reference masses.
"""
function find_calibration_peaks(mz::AbstractVector, intensity::AbstractVector, reference_masses::AbstractVector; ppm_tolerance=20.0)
function find_calibration_peaks_core(mz::AbstractVector, intensity::AbstractVector, reference_masses::AbstractVector; ppm_tolerance=20.0)
matched_peaks = Dict{Float64, Float64}()
# detect_peaks_profile returns Vector{NamedTuple}, so we need to extract mz values
detected_peaks_list = detect_peaks_profile(mz, intensity)
# detect_peaks_profile_core returns Vector{NamedTuple}, so we need to extract mz values
detected_peaks_list = detect_peaks_profile_core(mz, intensity)
# Extract only the m/z values into a new vector for easier processing
detected_mz_values = [p.mz for p in detected_peaks_list]
@@ -1057,16 +1030,16 @@ function find_calibration_peaks(mz::AbstractVector, intensity::AbstractVector, r
end
"""
calibrate_spectra(spectra, internal_standards; ...)
calibrate_spectra_core(spectra, internal_standards; ...)
Calibrates spectra using internal standards.
"""
function calibrate_spectra(spectra::Vector, internal_standards::Vector; ppm_tolerance=20.0)
function calibrate_spectra_core(spectra::Vector, internal_standards::Vector; ppm_tolerance=20.0)
calibrated_spectra = similar(spectra)
for (i, spec) in enumerate(spectra)
mz, intensity = spec[1], spec[2]
matched_peaks = find_calibration_peaks(mz, intensity, internal_standards; ppm_tolerance=ppm_tolerance)
matched_peaks = find_calibration_peaks_core(mz, intensity, internal_standards; ppm_tolerance=ppm_tolerance)
if length(matched_peaks) < 2
@warn "Spectrum $i: Not enough calibration peaks found. Skipping."
calibrated_spectra[i] = spec
@@ -1092,16 +1065,16 @@ end
# =============================================================================
"""
bin_peaks(all_pk_mz::Vector{Vector{Float64}},
bin_peaks_core(all_pk_mz::Vector{Vector{Float64}},
all_pk_int::Vector{Vector{Float64}},
params::PeakBinningParams) -> Tuple{FeatureMatrix, Vector{Tuple{Float64,Float64}}}
params::PeakBinning) -> Tuple{FeatureMatrix, Vector{Tuple{Float64,Float64}}}
Enhanced peak binning with adaptive and PPM-based parameters, or uniform binning.
# Arguments
- `all_pk_mz`: A vector of m/z vectors for all spectra.
- `all_pk_int`: A vector of intensity vectors for all spectra.
- `params`: A `PeakBinningParams` struct.
- `params`: A `PeakBinning` struct.
# Returns
- `Tuple{FeatureMatrix, Vector{Tuple{Float64,Float64}}}`: A tuple containing the generated FeatureMatrix and the bin definitions.
@@ -1111,8 +1084,8 @@ The use of `Threads.@threads` in the `:adaptive` and `:uniform` methods is safe.
- In the `:adaptive` method, the loop is over the bins (`j` index). Each thread writes only to its assigned column `X[:, j]`, so there are no write conflicts between threads.
- In the `:uniform` method, the loop is over the spectra (`s_idx`). Writes to `X[s_idx, bin_idx]` could theoretically conflict if different peaks from the same spectrum (`s_idx`) are processed by different threads. However, the loop is over `s_idx`, meaning each thread handles a distinct spectrum, making writes to `X[s_idx, :]` exclusive to that thread and thus safe.
"""
function bin_peaks(spectra::Vector{MutableSpectrum},
params::PeakBinningParams)
function bin_peaks_core(spectra::Vector{MutableSpectrum},
params::PeakBinning)
ns = length(spectra) # Number of spectra
ns == 0 && return FeatureMatrix(zeros(0,0), Tuple{Float64,Float64}[], Int[]), Tuple{Float64,Float64}[]
+455
View File
@@ -0,0 +1,455 @@
# src/PreprocessingPipeline.jl
using Base.Threads # For multithreading
using Printf # For @sprintf
using Interpolations # For linear_interpolation
using DataFrames # For saving feature matrix
using CSV # For saving feature matrix
# This file provides a set of functions that apply preprocessing steps to a vector of
# `MutableSpectrum` objects. Each function takes the vector of spectra and a dictionary
# of parameters, modifying the spectra in-place where appropriate. This mirrors the
# logic from `test/run_preprocessing.jl` but is intended for use in the main application.
# ===================================================================
# PREPROCESSING PIPELINE FUNCTIONS (IN-PLACE)
# ===================================================================
"""
apply_baseline_correction(spectra::Vector{MutableSpectrum}, params::Dict)
Applies baseline correction to the intensity data of each spectrum. This function
modifies the `.intensity` field of each `MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The algorithm to use. Supports `:snip`, `:convex_hull`, `:median`. Defaults to `:snip`.
- `:iterations` (Int): The number of iterations for the SNIP algorithm. Defaults to 100.
- `:window` (Int): The window size for the Median algorithm. Defaults to 20.
"""
function apply_baseline_correction(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :snip)
iterations = get(params, :iterations, 100)
window = get(params, :window, 20)
Threads.@threads for s in spectra
if validate_spectrum(s.mz, s.intensity)
baseline = apply_baseline_correction_core(s.intensity; method=method, iterations=iterations, window=window)
s.intensity = max.(0.0, s.intensity .- baseline)
end
end
end
"""
apply_intensity_transformation(spectra::Vector{MutableSpectrum}, params::Dict)
Applies an intensity transformation to the intensity data of each spectrum. This function
modifies the `.intensity` field of each `MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The transformation to apply. Supports `:sqrt`, `:log`, `:log2`, `:log10`, `:log1p`. Defaults to `:sqrt`.
"""
function apply_intensity_transformation(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :sqrt)
Threads.@threads for s in spectra
if validate_spectrum(s.mz, s.intensity)
s.intensity = transform_intensity_core(s.intensity; method=method)
end
end
end
"""
apply_smoothing(spectra::Vector{MutableSpectrum}, params::Dict)
Applies a smoothing filter to the intensity data of each spectrum. This function
modifies the `.intensity` field of each `MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The smoothing algorithm. Supports `:savitzky_golay`, `:moving_average`. Defaults to `:savitzky_golay`.
- `:window` (Int): The size of the smoothing window. Defaults to 9.
- `:order` (Int): The polynomial order for the Savitzky-Golay filter. Defaults to 2.
"""
function apply_smoothing(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :savitzky_golay)
window = get(params, :window, 9)
order = get(params, :order, 2)
Threads.@threads for s in spectra
if validate_spectrum(s.mz, s.intensity)
smoothed_intensity = max.(0.0, smooth_spectrum_core(s.intensity; method=method, window=window, order=order))
s.intensity = smoothed_intensity
end
end
end
"""
apply_peak_picking(spectra::Vector{MutableSpectrum}, params::Dict)
Detects peaks in each spectrum and stores them in the `.peaks` field of each
`MutableSpectrum` object, modifying it in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The peak detection algorithm. Supports `:profile`, `:wavelet`, `:centroid`. Defaults to `:profile`.
- `:snr_threshold` (Float64): Signal-to-Noise Ratio threshold.
- `:half_window` (Int): Half-window size for local maxima detection.
- `:min_peak_prominence` (Float64): Minimum required prominence for a peak.
- `:merge_peaks_tolerance` (Float64): m/z tolerance to merge adjacent peaks.
"""
function apply_peak_picking(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :profile)
snr_threshold = get(params, :snr_threshold, 3.0)
half_window = get(params, :half_window, 10)
min_peak_prominence = get(params, :min_peak_prominence, 0.1)
merge_peaks_tolerance = get(params, :merge_peaks_tolerance, 0.002)
Threads.@threads for s in spectra
if validate_spectrum(s.mz, s.intensity)
if method == :profile
s.peaks = detect_peaks_profile_core(s.mz, s.intensity; snr_threshold=snr_threshold, half_window=half_window, min_peak_prominence=min_peak_prominence, merge_peaks_tolerance=merge_peaks_tolerance)
elseif method == :wavelet
s.peaks = detect_peaks_wavelet_core(s.mz, s.intensity; snr_threshold=snr_threshold, half_window=half_window)
elseif method == :centroid
s.peaks = detect_peaks_centroid_core(s.mz, s.intensity; snr_threshold=snr_threshold)
else
s.peaks = detect_peaks_profile_core(s.mz, s.intensity; snr_threshold=snr_threshold, half_window=half_window)
end
else
s.peaks = []
end
end
end
"""
apply_peak_selection(spectra::Vector{MutableSpectrum}, params::Dict)
Filters peaks within each spectrum based on quality criteria. This step removes peaks
that do not meet the specified thresholds for signal-to-noise ratio (SNR),
full width at half maximum (FWHM), and peak shape.
This function modifies the `.peaks` field of each `MutableSpectrum` object in the `spectra` vector in-place.
# Parameters from `params` Dict:
- `:min_snr` (Float64): The minimum Signal-to-Noise Ratio required for a peak to be kept.
- `:min_fwhm_ppm` (Float64): The minimum FWHM (in ppm) for a peak.
- `:max_fwhm_ppm` (Float64): The maximum FWHM (in ppm) for a peak.
- `:min_shape_r2` (Float64): The minimum R² value from a Gaussian fit, measuring peak shape quality.
"""
function apply_peak_selection(spectra::Vector{MutableSpectrum}, params::Dict)
min_snr = get(params, :min_snr, 0.0)
min_fwhm = get(params, :min_fwhm_ppm, 0.0)
max_fwhm = get(params, :max_fwhm_ppm, Inf)
min_r2 = get(params, :min_shape_r2, 0.0)
# Handle `nothing` from params, which can happen if pre-calculation fails.
min_snr = isnothing(min_snr) ? 0.0 : min_snr
min_fwhm = isnothing(min_fwhm) ? 0.0 : min_fwhm
max_fwhm = isnothing(max_fwhm) ? Inf : max_fwhm
min_r2 = isnothing(min_r2) ? 0.0 : min_r2
Threads.@threads for s in spectra
if !isempty(s.peaks)
filter!(p ->
p.snr >= min_snr &&
(min_fwhm <= p.fwhm <= max_fwhm) &&
p.shape_r2 >= min_r2,
s.peaks
)
end
end
end
"""
apply_calibration(spectra::Vector{MutableSpectrum}, params::Dict, reference_peaks::Dict)
Performs mass calibration on each spectrum using a list of internal standards.
This function modifies the `.mz` axis of each `MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The calibration method. Only `:internal_standards` is currently meaningful.
- `:ppm_tolerance` (Float64): The tolerance in PPM for matching detected peaks to reference masses.
- `:fit_order` (Int): The polynomial order for the calibration fit (not yet used in this implementation, defaults to linear).
"""
function apply_calibration(spectra::Vector{MutableSpectrum}, params::Dict, reference_peaks::Dict)
method = get(params, :method, :none)
ppm_tolerance = get(params, :ppm_tolerance, 20.0)
if method == :none || isempty(reference_peaks)
return
end
reference_masses = collect(keys(reference_peaks))
Threads.@threads for i in 1:length(spectra)
s = spectra[i]
if validate_spectrum(s.mz, s.intensity)
matched_peaks = find_calibration_peaks_core(s.mz, s.intensity, reference_masses; ppm_tolerance=ppm_tolerance)
if length(matched_peaks) >= 2
measured = sort(collect(values(matched_peaks)))
theoretical = sort(collect(keys(matched_peaks)))
itp = linear_interpolation(measured, theoretical, extrapolation_bc=Line())
s.mz = itp(s.mz) # Modify mz-axis in-place
else
@warn "Spectrum $(s.id): insufficient reference peaks ($(length(matched_peaks)) found), skipping calibration."
end
end
end
end
"""
apply_peak_alignment(spectra::Vector{MutableSpectrum}, params::Dict)
Aligns the m/z axis of all spectra to a chosen reference spectrum. This function
modifies both the `.mz` axis and the m/z values within the `.peaks` field of each
`MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The alignment algorithm. Supports `:lowess`, `:linear`, `:ransac`.
- `:tolerance` (Float64): The tolerance for matching peaks between spectra.
- `:tolerance_unit` (Symbol): The unit for tolerance, `:mz` or `:ppm`.
"""
function apply_peak_alignment(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :none)
tolerance = get(params, :tolerance, 0.002)
tolerance_unit = get(params, :tolerance_unit, :mz)
if method == :none
return
end
ref_find_idx = findfirst(s -> !isempty(s.peaks), spectra)
if ref_find_idx === nothing
@warn "Insufficient spectra with peaks for alignment. Skipping."
return
end
ref_spectrum = spectra[ref_find_idx]
ref_peaks_mz = [p.mz for p in ref_spectrum.peaks]
Threads.@threads for s in spectra
if s.id == ref_spectrum.id || isempty(s.peaks)
continue
end
current_peaks_mz = [p.mz for p in s.peaks]
alignment_func = align_peaks_lowess_core(ref_peaks_mz, current_peaks_mz; method=method, tolerance=tolerance, tolerance_unit=tolerance_unit)
s.mz = alignment_func.(s.mz) # Update m/z axis
# Update peak m/z values
for i in 1:length(s.peaks)
old_peak = s.peaks[i]
aligned_peak_mz = alignment_func(old_peak.mz)
s.peaks[i] = (mz=aligned_peak_mz, intensity=old_peak.intensity, fwhm=old_peak.fwhm, shape_r2=old_peak.shape_r2, snr=old_peak.snr, prominence=old_peak.prominence)
end
end
end
"""
apply_normalization(spectra::Vector{MutableSpectrum}, params::Dict)
Applies intensity normalization to each spectrum. This function modifies the
`.intensity` field of each `MutableSpectrum` object in-place.
# Parameters from `params` Dict:
- `:method` (Symbol): The normalization method. Supports `:tic`, `:median`, `:rms`, `:none`.
"""
function apply_normalization(spectra::Vector{MutableSpectrum}, params::Dict)
method = get(params, :method, :tic)
Threads.@threads for s in spectra
if validate_spectrum(s.mz, s.intensity)
s.intensity = apply_normalization_core(s.intensity; method=method)
end
end
end
function apply_peak_binning(spectra::Vector{MutableSpectrum}, params::Dict)
tolerance = get(params, :tolerance, 20.0)
tolerance_unit = get(params, :tolerance_unit, :ppm)
min_peak_per_bin = get(params, :min_peak_per_bin, 3)
if isempty(spectra) || all(s -> isempty(s.peaks), spectra)
@warn "No peaks found for binning. Returning empty feature matrix."
return nothing, nothing
end
all_peaks = Vector{Tuple{Float64, Float64}}()
for s in spectra
for p in s.peaks
push!(all_peaks, (p.mz, p.intensity))
end
end
if isempty(all_peaks)
@warn "No peaks collected for binning."
return nothing, nothing
end
sort!(all_peaks, by=x->x[1])
bin_centers = Float64[]
bin_intensities = Float64[]
i = 1
while i <= length(all_peaks)
current_bin_start = i
current_peak = all_peaks[i]
j = i + 1
while j <= length(all_peaks)
next_peak = all_peaks[j]
tol = (tolerance_unit == :ppm) ? (current_peak[1] * tolerance / 1e6) : tolerance
if (next_peak[1] - current_peak[1]) <= tol
j += 1
else
break
end
end
current_bin_end = j - 1
bin_size = current_bin_end - current_bin_start + 1
if bin_size >= min_peak_per_bin
bin_peaks = all_peaks[current_bin_start:current_bin_end]
mz_sum = sum(p[1] for p in bin_peaks)
intensity_sum = sum(p[2] for p in bin_peaks)
mz_center = mz_sum / bin_size
avg_intensity = intensity_sum / bin_size
push!(bin_centers, mz_center)
push!(bin_intensities, avg_intensity)
end
i = j
end
if !isempty(bin_centers)
n_bins = length(bin_centers)
feature_matrix = Matrix{Float64}(undef, 2, n_bins)
for i in 1:n_bins
feature_matrix[1, i] = bin_centers[i]
feature_matrix[2, i] = bin_intensities[i]
end
bin_info = [(bin_centers[i], bin_intensities[i]) for i in 1:n_bins]
return feature_matrix, bin_info
else
@warn "No bins created after filtering"
return nothing, nothing
end
end
"""
save_feature_matrix(feature_matrix::Matrix{Float64}, bin_info, output_dir::String) -> Tuple{String, String}
Saves the aggregated `2 x n_bins` feature matrix into two different CSV formats.
1. **Simple Format (`feature_matrix_simple.csv`):** A two-column CSV with "mz" and "intensity".
2. **Standard Format (`feature_matrix_standard.csv`):** A row-based format where m/z values are headers and there is a single data row for the aggregated spectrum.
# Arguments
- `feature_matrix::Matrix{Float64}`: The `2 x n_bins` matrix from `apply_peak_binning`.
- `bin_info`: The associated bin information (currently unused but kept for compatibility).
- `output_dir::String`: The directory where the output CSV files will be saved.
# Returns
- A tuple containing the paths to the two saved files.
"""
function save_feature_matrix(feature_matrix::Matrix{Float64}, bin_info, output_dir::String)
# Save as simple CSV with m/z and intensity rows
csv_path = joinpath(output_dir, "feature_matrix_simple.csv")
open(csv_path, "w") do io
write(io, "mz,intensity\n")
for i in 1:size(feature_matrix, 2)
mz = feature_matrix[1, i]
intensity = feature_matrix[2, i]
write(io, "$mz,$intensity\n")
end
end
@info "Saved simple feature matrix: $csv_path"
# Also save in a more standard format for MSI
csv_path_standard = joinpath(output_dir, "feature_matrix_standard.csv")
open(csv_path_standard, "w") do io
write(io, "sample_type,")
mz_headers = [@sprintf("mz_%.4f", feature_matrix[1, i]) for i in 1:size(feature_matrix, 2)]
write(io, join(mz_headers, ",") * "\n")
write(io, "aggregated_spectrum,")
intensity_values = [feature_matrix[2, i] for i in 1:size(feature_matrix, 2)]
write(io, join(string.(intensity_values), ",") * "\n")
end
@info "Saved standard format matrix: $csv_path_standard"
return csv_path, csv_path_standard
end
function execute_full_preprocessing(spectra::Vector{MutableSpectrum}, params::Dict,
pipeline_steps::Vector{String}, reference_peaks::Dict,
mask_path::Union{String, Nothing}=nothing;
progress_callback::Function=(step -> nothing))
println("Starting preprocessing pipeline with $(length(spectra)) spectra")
println("Steps: $(join(pipeline_steps, " -> "))")
# These variables will be populated by the pipeline steps
feature_matrix = nothing
bin_definitions = nothing
# Apply pipeline steps, modifying `spectra` in-place
for step in pipeline_steps
progress_callback(step)
println("\n" * "-"^60)
println("PROCESSING STEP: $step")
println("-"^60)
if step == "stabilization"
println(" Applying intensity transformation (stabilization)")
apply_intensity_transformation(spectra, get(params, :Stabilization, Dict()))
elseif step == "baseline_correction"
println(" Applying baseline correction")
apply_baseline_correction(spectra, get(params, :BaselineCorrection, Dict()))
elseif step == "smoothing"
println(" Applying smoothing")
apply_smoothing(spectra, get(params, :Smoothing, Dict()))
elseif step == "peak_picking"
println(" Applying peak picking")
apply_peak_picking(spectra, get(params, :PeakPicking, Dict()))
elseif step == "peak_selection"
println(" Applying peak selection")
apply_peak_selection(spectra, get(params, :PeakSelection, Dict()))
elseif step == "calibration"
println(" Applying calibration")
apply_calibration(spectra, get(params, :Calibration, Dict()), reference_peaks)
elseif step == "peak_alignment"
println(" Applying peak alignment")
apply_peak_alignment(spectra, get(params, :PeakAlignment, Dict()))
elseif step == "normalization"
println(" Applying normalization")
apply_normalization(spectra, get(params, :Normalization, Dict()))
elseif step == "peak_binning"
println(" Applying peak binning")
feature_matrix, bin_definitions = apply_peak_binning(spectra, get(params, :PeakBinning, Dict()))
else
@warn "Unknown step: $step, skipping"
end
println("✓ Completed step: $step")
end
return feature_matrix, bin_definitions
end
+45 -8
View File
@@ -20,6 +20,7 @@ const DATA_FORMAT_ACCESSIONS = Dict{String, DataType}(
)
function parse_instrument_metadata_mzml(stream::IO)
println("DEBUG: Starting mzML instrument metadata parsing...")
# Initialize with default values from the InstrumentMetadata constructor
instrument_meta = InstrumentMetadata()
@@ -67,37 +68,53 @@ function parse_instrument_metadata_mzml(stream::IO)
if acc == "MS:1000031" # instrument model
instrument_model = val
#println("DEBUG: Instrument model: $instrument_model")
elseif acc == "MS:1001496" # mass resolving power (more specific)
resolution = tryparse(Float64, val)
#println("DEBUG: Resolution (specific): $resolution")
elseif acc == "MS:1000011" && resolution === nothing # resolution (less specific)
resolution = tryparse(Float64, val)
#println("DEBUG: Resolution (less specific): $resolution")
elseif acc == "MS:1000016" # mass accuracy (ppm)
mass_accuracy_ppm = tryparse(Float64, val)
#println("DEBUG: Mass accuracy (ppm): $mass_accuracy_ppm")
elseif acc == "MS:1000130" # positive scan
polarity = :positive
#println("DEBUG: Polarity: positive")
elseif acc == "MS:1000129" # negative scan
polarity = :negative
#println("DEBUG: Polarity: negative")
elseif acc == "MS:1000592" # external calibration
calibration_status = :external
#println("DEBUG: Calibration status: external")
elseif acc == "MS:1000593" # internal calibration
calibration_status = :internal
#println("DEBUG: Calibration status: internal")
elseif acc == "MS:1000747" && calibration_status == :uncalibrated # instrument specific calibration
calibration_status = :internal # Assume as a form of internal calibration
#println("DEBUG: Calibration status: instrument specific (internal)")
elseif acc == "MS:1000867" # laser wavelength
laser_settings["wavelength_nm"] = tryparse(Float64, val)
#println("DEBUG: Laser wavelength: $(laser_settings["wavelength_nm"]) nm")
elseif acc == "MS:1000868" # laser fluence
laser_settings["fluence"] = tryparse(Float64, val)
#println("DEBUG: Laser fluence: $(laser_settings["fluence"])")
elseif acc == "MS:1000869" # laser repetition rate
laser_settings["repetition_rate_hz"] = tryparse(Float64, val)
#println("DEBUG: Laser repetition rate: $(laser_settings["repetition_rate_hz"]) Hz")
# NEW: Vendor Preprocessing terms
elseif acc == "MS:1000579" # baseline correction
push!(vendor_preprocessing_steps, "Baseline Correction")
#println("DEBUG: Vendor preprocessing step: Baseline Correction")
elseif acc == "MS:1000580" # smoothing
push!(vendor_preprocessing_steps, "Smoothing")
#println("DEBUG: Vendor preprocessing step: Smoothing")
elseif acc == "MS:1000578" # data transformation (e.g., centroiding)
push!(vendor_preprocessing_steps, "Data Transformation: $(name)")
#println("DEBUG: Vendor preprocessing step: Data Transformation: $(name)")
elseif acc == "MS:1000800" # deisotoping
push!(vendor_preprocessing_steps, "Deisotoping")
#println("DEBUG: Vendor preprocessing step: Deisotoping")
end
end
end
@@ -106,6 +123,8 @@ function parse_instrument_metadata_mzml(stream::IO)
@warn "Could not fully parse instrument metadata from mzML header. Using defaults. Error: $e"
end
println("DEBUG: Finished mzML instrument metadata parsing.")
# Always return a valid object
return InstrumentMetadata(
resolution,
@@ -137,14 +156,15 @@ determine the data type, compression, and axis type.
function get_spectrum_asset_metadata(stream::IO)
start_pos = position(stream)
bda_tag = find_tag(stream, r"<binaryDataArray\s+encodedLength=\"(\d+)\"")
if bda_tag === nothing
throw(FileFormatError("Cannot find binaryDataArray"))
end
#println("DEBUG: Entering get_spectrum_asset_metadata to parse binaryDataArray...")
bda_tag = find_tag(stream, r"<binaryDataArray\s+encodedLength=\"(\d+)\"")
if bda_tag === nothing
throw(FileFormatError("Cannot find binaryDataArray"))
end
encoded_length = parse(Int32, bda_tag.captures[1])
#println("DEBUG: Encoded length: $encoded_length")
# Initialize parameters as separate variables with concrete types
data_format::DataType = Float64
@@ -166,14 +186,19 @@ function get_spectrum_asset_metadata(stream::IO)
# Use constant comparisons and dictionary lookup for better performance
if acc_str == MZ_AXIS_ACCESSION
axis = :mz
#println("DEBUG: Axis type identified as: m/z")
elseif acc_str == INTENSITY_AXIS_ACCESSION
axis = :intensity
#println("DEBUG: Axis type identified as: intensity")
elseif haskey(DATA_FORMAT_ACCESSIONS, acc_str)
data_format = DATA_FORMAT_ACCESSIONS[acc_str]
#println("DEBUG: Data format identified as: $data_format")
elseif acc_str == COMPRESSION_ACCESSION
compression_flag = true
#println("DEBUG: Compression: true")
elseif acc_str == NO_COMPRESSION_ACCESSION
compression_flag = false
#println("DEBUG: Compression: false")
end
end
end
@@ -181,9 +206,11 @@ function get_spectrum_asset_metadata(stream::IO)
seek(stream, start_pos)
readuntil(stream, "<binary>")
binary_offset = position(stream)
#println("DEBUG: Binary data offset: $binary_offset")
# Move stream to the end of the binary data array for the next iteration
readuntil(stream, "</binaryDataArray>")
#println("DEBUG: Exiting get_spectrum_asset_metadata.")
# Create SpectrumAsset directly from the variables
return SpectrumAsset(data_format, compression_flag, binary_offset, encoded_length, axis)
@@ -223,13 +250,16 @@ function parse_spectrum_metadata(stream::IO, offset::Int64)
id_match = match(r"<spectrum\s+index=\"\d+\"\s+id=\"([^\"]+)", spectrum_xml)
id = id_match === nothing ? "" : id_match.captures[1]
#println("DEBUG: Parsing spectrum ID: $id")
# Determine mode from the XML block
mode = UNKNOWN
if occursin("MS:1000127", spectrum_xml)
mode = CENTROID
#println("DEBUG: Spectrum mode: CENTROID")
elseif occursin("MS:1000128", spectrum_xml)
mode = PROFILE
#println("DEBUG: Spectrum mode: PROFILE")
end
# Find where the binary data list starts to parse assets
@@ -248,6 +278,10 @@ function parse_spectrum_metadata(stream::IO, offset::Int64)
(asset2, asset1)
end
#println("DEBUG: m/z Asset - Format: $(mz_asset.format), Compressed: $(mz_asset.is_compressed), Offset: $(mz_asset.offset), Encoded Length: $(mz_asset.encoded_length)")
#println("DEBUG: Intensity Asset - Format: $(int_asset.format), Compressed: $(int_asset.is_compressed), Offset: $(int_asset.offset), Encoded Length: $(int_asset.encoded_length)")
#println("DEBUG: Finished parsing spectrum ID: $id metadata.")
# Create the new unified metadata object
# For mzML, x and y coordinates are not applicable, so we use 0.
return SpectrumMetadata(Int32(0), Int32(0), id, :sample, mode, mz_asset, int_asset)
@@ -380,12 +414,14 @@ function load_mzml_lazy(file_path::String; cache_size::Int=100)
println("DEBUG: Processed $i/$num_spectra spectra")
end
end
println("DEBUG: Metadata parsing complete.")
println("DEBUG: Metadata parsing complete for all $num_spectra spectra.")
# Assuming uniform data formats, take from the first spectrum
first_meta = spectra_metadata[1]
mz_format = first_meta.mz_asset.format
intensity_format = first_meta.int_asset.format
println("DEBUG: Inferred global m/z format: $mz_format")
println("DEBUG: Inferred global intensity format: $intensity_format")
# --- NEW: Determine overall acquisition mode ---
modes = [meta.mode for meta in spectra_metadata]
@@ -401,6 +437,7 @@ function load_mzml_lazy(file_path::String; cache_size::Int=100)
else
:unknown
end
println("DEBUG: Inferred overall acquisition mode: $acq_mode_symbol (Centroid: $num_centroid, Profile: $num_profile)")
final_instrument_meta = InstrumentMetadata(
instrument_meta.resolution,