Files
JuliaMSI/src/imzML.jl
T

1356 lines
52 KiB
Julia

using Statistics, DataFrames, ColorSchemes, StatsBase, Mmap
"""
This file provides a library for parsing `.imzML` and `.ibd` files in pure Julia.
Core Functions:
- `load_imzml_lazy`: The main function that orchestrates the parsing.
- Helper functions for reading XML metadata and binary spectral data.
"""
# ============================================================================
#
#
# imzML Parser Implementation
#
# ============================================================================
"""
parse_imzml_header(stream::IO)
Parses the header of an imzML file.
# Arguments
- `stream::IO`: The stream to parse.
# Returns
- `instrument_meta::InstrumentMetadata`: The instrument metadata.
- `param_groups::Dict{String, SpecDim}`: The parameter groups.
- `img_dims::Vector{Int32}`: The image dimensions.
"""
function parse_imzml_header(stream::IO)
# Initialize all return values and temporary variables
instrument_meta = InstrumentMetadata()
param_groups = Dict{String, SpecDim}()
img_dims = zeros(Int32, 3)
vendor_preprocessing_steps = String[] # Initialize vendor_preprocessing_steps
# Temp vars for parsing
resolution = instrument_meta.resolution
instrument_model = instrument_meta.instrument_model
mass_accuracy_ppm = instrument_meta.mass_accuracy_ppm
polarity = instrument_meta.polarity
calibration_status = instrument_meta.calibration_status
laser_settings = Dict{String, Any}()
try
seekstart(stream)
in_scan_settings = false
dim_axes_found = 0
found_spectrum_count = false
# This loop performs a single pass to get most metadata
while !eof(stream)
line = readline(stream)
# State-machine like logic to enter/exit sections
if occursin("<scanSettings", line)
in_scan_settings = true
elseif occursin("</scanSettings>", line)
in_scan_settings = false
end
# --- Parse Scan Settings for Image Dimensions ---
if in_scan_settings && occursin("<cvParam", line) && dim_axes_found < 2
accession_match = get_attribute(line, "accession")
if accession_match !== nothing
accession = accession_match.captures[1]
if accession == "IMS:1000042" || accession == "IMS:1000043" # max dimension x or y
value_match = get_attribute(line, "value")
if value_match !== nothing
axis_idx = (accession == "IMS:1000042") ? 1 : 2
img_dims[axis_idx] = parse(Int32, value_match.captures[1])
dim_axes_found += 1
end
end
end
end
# --- Parse Spectrum List for total count ---
if occursin("<spectrumList", line)
count_match = get_attribute(line, "count")
if count_match !== nothing
img_dims[3] = parse(Int32, count_match.captures[1])
found_spectrum_count = true
end
end
# --- Parse general CV params for InstrumentMetadata ---
if occursin("<cvParam", line)
accession_match = get_attribute(line, "accession")
value_match = get_attribute(line, "value")
name_match = get_attribute(line, "name") # For laser attributes and vendor_preprocessing names
if accession_match !== nothing
acc = accession_match.captures[1]
val = (value_match !== nothing) ? value_match.captures[1] : ""
cv_name = (name_match !== nothing) ? name_match.captures[1] : "" # Use cv_name to avoid conflict
if acc == "MS:1000031" # instrument model
instrument_model = val
elseif acc == "MS:1001496" # mass resolving power (more specific)
resolution = tryparse(Float64, val)
elseif acc == "MS:1000011" && resolution === nothing # resolution (less specific)
resolution = tryparse(Float64, val)
elseif acc == "MS:1000016" # mass accuracy (ppm)
mass_accuracy_ppm = tryparse(Float64, val)
elseif acc == "MS:1000130" # positive scan
polarity = :positive
elseif acc == "MS:1000129" # negative scan
polarity = :negative
elseif acc == "MS:1000592" # external calibration
calibration_status = :external
elseif acc == "MS:1000593" # internal calibration
calibration_status = :internal
elseif acc == "MS:1000747" && calibration_status == :uncalibrated # instrument specific calibration
calibration_status = :internal # Assume as a form of internal calibration
elseif acc == "MS:1000867" # laser wavelength
laser_settings["wavelength_nm"] = tryparse(Float64, val)
elseif acc == "MS:1000868" # laser fluence
laser_settings["fluence"] = tryparse(Float64, val)
elseif acc == "MS:1000869" # laser repetition rate
laser_settings["repetition_rate_hz"] = tryparse(Float64, val)
# NEW: Vendor Preprocessing terms
elseif acc == "MS:1000579" # baseline correction
push!(vendor_preprocessing_steps, "Baseline Correction")
elseif acc == "MS:1000580" # smoothing
push!(vendor_preprocessing_steps, "Smoothing")
elseif acc == "MS:1000578" # data transformation (e.g., centroiding)
push!(vendor_preprocessing_steps, "Data Transformation: $(cv_name)") # Use cv_name here
elseif acc == "MS:1000800" # deisotoping
push!(vendor_preprocessing_steps, "Deisotoping")
end
end
end
if found_spectrum_count && dim_axes_found == 2
break
end
end
catch e
@warn "Could not fully parse imzML header in single pass. Error: $e"
end
# The axes_config_img logic is complex to merge; we run it as a second, small pass.
seekstart(stream)
param_groups = axes_config_img(stream)
final_instrument_meta = InstrumentMetadata(
resolution, :unknown, :unknown, calibration_status,
instrument_model, mass_accuracy_ppm,
isempty(laser_settings) ? nothing : laser_settings,
polarity,
isempty(vendor_preprocessing_steps) ? nothing : vendor_preprocessing_steps # NEW field
)
return (final_instrument_meta, param_groups, img_dims)
end
"""
axes_config_img(stream)
Determines the storage order of the m/z and intensity arrays.
# Arguments
- `stream::IO`: The stream to parse.
# Returns
- `param_groups::Dict{String, SpecDim}`: The parameter groups.
"""
function axes_config_img(stream::IO)
param_groups = Dict{String, SpecDim}()
find_tag(stream, r"<referenceableParamGroupList")
while true
pos = position(stream)
line = readline(stream)
if eof(stream) || occursin("</referenceableParamGroupList>", line)
break
end
id_match = match(r"<referenceableParamGroup id=\"([^\"]+)\"", line)
if id_match !== nothing
id = id_match.captures[1]
spec_dim = configure_spec_dim(stream)
param_groups[id] = spec_dim
end
end
return param_groups
end
"""
read_spectrum_block(stream::IO)
Helper function to read an entire spectrum block from the stream.
# Arguments
- `stream::IO`: The stream to parse.
# Returns
- `lines::Vector{String}`: The lines of the spectrum block.
"""
function read_spectrum_block(stream::IO)
lines = String[]
in_spectrum = false
# Store the stream's position before starting to read this block.
# This is important for determining if a block was successfully read.
start_pos = position(stream)
while !eof(stream)
line = readline(stream)
if occursin("<spectrum ", line)
in_spectrum = true
push!(lines, line)
elseif in_spectrum
push!(lines, line)
if occursin("</spectrum>", line)
return join(lines, "\n")
end
end
end
# If we reach EOF without finding </spectrum> for a started block,
# or if no <spectrum> was found at all, return empty.
if isempty(lines)
seek(stream, start_pos) # Reset stream position if no block was found
return ""
else
# Should not happen if XML is well-formed, but just in case
@warn "Reached EOF while parsing spectrum block without finding </spectrum> tag. Returning partial block."
return join(lines, "\n")
end
end
"""
parse_coordinates(spectrum_block::String)
Helper function to parse coordinates from a spectrum block.
# Arguments
- `spectrum_block::String`: The spectrum block to parse.
# Returns
- `x::Int32`: The x-coordinate.
- `y::Int32`: The y-coordinate.
"""
function parse_coordinates(spectrum_block::String)
x = Int32(0)
y = Int32(0)
x_match = match(r"IMS:1000050[^>]*value=\"(\d+)\"", spectrum_block)
y_match = match(r"IMS:1000051[^>]*value=\"(\d+)\"", spectrum_block)
x = x_match !== nothing ? parse(Int32, x_match.captures[1]) : x
y = y_match !== nothing ? parse(Int32, y_match.captures[1]) : y
return x, y
end
"""
parse_spectrum_mode(spectrum_block::String, global_mode::SpectrumMode)
Helper function to parse spectrum mode from a spectrum block.
# Arguments
- `spectrum_block::String`: The spectrum block to parse.
- `global_mode::SpectrumMode`: The global mode.
# Returns
- `mode::SpectrumMode`: The spectrum mode.
"""
function parse_spectrum_mode(spectrum_block::String, global_mode::SpectrumMode)
if occursin("MS:1000127", spectrum_block)
return CENTROID
elseif occursin("MS:1000128", spectrum_block)
return PROFILE
else
return global_mode
end
end
"""
parse_binary_data_arrays(spectrum_block::String, spectrum_start_line::String,
default_mz_format::DataType, default_intensity_format::DataType,
mz_is_compressed::Bool, int_is_compressed::Bool)
Helper function to parse binary data arrays from a spectrum block.
# Arguments
- `spectrum_block::String`: The spectrum block to parse.
- `spectrum_start_line::String`: The start line of the spectrum.
- `default_mz_format::DataType`: The default data type for mz arrays.
- `default_intensity_format::DataType`: The default data type for intensity arrays.
- `mz_is_compressed::Bool`: Whether mz arrays are compressed.
- `int_is_compressed::Bool`: Whether intensity arrays are compressed.
# Returns
- `array_data::Vector{Tuple{Bool, Int32, Int64, Int64}}`: The array data.
"""
function parse_binary_data_arrays(spectrum_block::String, spectrum_start_line::String,
default_mz_format::DataType, default_intensity_format::DataType,
mz_is_compressed::Bool, int_is_compressed::Bool;
param_groups::Dict{String, SpecDim}=Dict{String, SpecDim}())
array_data_type = @NamedTuple{is_mz::Bool, array_length::Int32, encoded_length::Int64, offset::Int64}
current_array_data = array_data_type[]
for bda_match in eachmatch(r"<binaryDataArray.*?>(.*?)</binaryDataArray>"sm, spectrum_block)
bda_content = bda_match.match # This will be the full <binaryDataArray> block
# Many imzML writers put the m/z and intensity cvParams in a
# <referenceableParamGroup> and only reference it from the spectrum.
# Resolve the reference first so those files are classified correctly.
ref_match = match(r"<referenceableParamGroupRef\s+ref=\"([^\"]+)\"", bda_content)
is_mz = if ref_match !== nothing && haskey(param_groups, ref_match.captures[1])
param_groups[ref_match.captures[1]].Axis == 1
else
occursin("MS:1000514", bda_content) || occursin("mzArray", bda_content)
end
# imzML 1.1 external-array accessions:
# IMS:1000101 external encoded length
# IMS:1000102 external data
# IMS:1000103 external offset
# IMS:1000104 external array length
# The previous order mapped offset/array-length/encoded-length incorrectly.
array_len_cv_match = match(r"IMS:1000104.*?value=\"(\d+)\"", bda_content)
array_length = Int32(0)
if array_len_cv_match !== nothing
array_length = parse(Int32, array_len_cv_match.captures[1])
end
# Fallback for defaultArrayLength from the spectrum_start_line
if array_length == 0
default_match = match(r"defaultArrayLength=\"(\d+)\"", spectrum_start_line)
if default_match !== nothing
array_length = parse(Int32, default_match.captures[1])
end
end
encoded_len_cv_match = match(r"IMS:1000101.*?value=\"(\d+)\"", bda_content)
encoded_length = Int64(0)
if encoded_len_cv_match !== nothing
encoded_length = parse(Int64, encoded_len_cv_match.captures[1])
else
encoded_len_attr_match = match(r"encodedLength=\"(\d+)\"", bda_content)
if encoded_len_attr_match !== nothing
encoded_length = parse(Int64, encoded_len_attr_match.captures[1])
end
end
offset_match = match(r"IMS:1000103.*?value=\"(\d+)\"", bda_content)
offset = Int64(0)
if offset_match !== nothing
offset = parse(Int64, offset_match.captures[1])
else
# Legacy files sometimes put the offset directly in IMS:1000102.
legacy_offset_match = match(r"IMS:1000102.*?value=\"(\d+)\"", bda_content)
if legacy_offset_match !== nothing
offset = parse(Int64, legacy_offset_match.captures[1])
end
end
if array_length > 0 && offset >= 0
push!(current_array_data, (is_mz=is_mz, array_length=array_length,
encoded_length=encoded_length, offset=offset))
end
end
return current_array_data
end
"""
parse_imzml_spectrum_block(stream::IO, hIbd::Union{IO, ThreadSafeFileHandle}, param_groups::Dict{String, SpecDim},
width::Int32, height::Int32, num_spectra::Int32,
default_mz_format::DataType, default_intensity_format::DataType,
mz_is_compressed::Bool, int_is_compressed::Bool, global_mode::SpectrumMode)
Unified function to parse spectrum metadata
# Arguments
- `stream::IO`: The stream to parse.
- `hIbd::IO`: The IBD file handle.
- `param_groups::Dict{String, SpecDim}`: The parameter groups.
- `width::Int32`: The width of the image.
- `height::Int32`: The height of the image.
- `num_spectra::Int32`: The number of spectra.
- `default_mz_format::DataType`: The default data type for mz arrays.
- `default_intensity_format::DataType`: The default data type for intensity arrays.
- `mz_is_compressed::Bool`: Whether mz arrays are compressed.
- `int_is_compressed::Bool`: Whether intensity arrays are compressed.
- `global_mode::SpectrumMode`: The global mode.
# Returns
- `spectra_metadata::Vector{SpectrumMetadata}`: The spectrum metadata.
"""
function parse_imzml_spectrum_block(stream::IO, hIbd::IO, param_groups::Dict{String, SpecDim},
width::Int32, height::Int32, num_spectra::Int32,
default_mz_format::DataType, default_intensity_format::DataType,
mz_is_compressed::Bool, int_is_compressed::Bool, global_mode::SpectrumMode)
spectra_metadata = Vector{SpectrumMetadata}(undef, num_spectra)
# Store the initial position of the stream, in case read_spectrum_block fails to find a spectrum.
# This helps reset the stream for subsequent debugging if needed, though typically it should find a spectrum.
initial_stream_pos = position(stream)
for k in 1:num_spectra
spectrum_block_content = read_spectrum_block(stream)
if isempty(spectrum_block_content)
@warn "Expected spectrum block $k but found none or reached EOF prematurely. Stopping parsing."
# Fill remaining spectra_metadata with placeholder or error.
for j in k:num_spectra
mz_asset = SpectrumAsset(default_mz_format, mz_is_compressed, Int64(0), 0, :mz, 0.0, 0.0)
int_asset = SpectrumAsset(default_intensity_format, int_is_compressed, Int64(0), 0, :intensity, 0.0, 0.0)
spectra_metadata[j] = SpectrumMetadata(Int32(0), Int32(0), "", :sample, global_mode, mz_asset, int_asset)
end
break
end
x, y = parse_coordinates(spectrum_block_content)
spectrum_mode = parse_spectrum_mode(spectrum_block_content, global_mode)
# The spectrum_start_line is needed for defaultArrayLength fallback in parse_binary_data_arrays
# We need to extract it from spectrum_block_content or pass the first line of the spectrum_block_content
# Let's assume the first line of spectrum_block_content is the spectrum_start_line for this purpose
spectrum_start_line_from_block = String(split(spectrum_block_content, '\n')[1])
current_array_data = parse_binary_data_arrays(spectrum_block_content, spectrum_start_line_from_block,
default_mz_format, default_intensity_format,
mz_is_compressed, int_is_compressed;
param_groups=param_groups)
# Separate m/z and intensity arrays
mz_data = filter(d -> d.is_mz, current_array_data)
int_data = filter(d -> !d.is_mz, current_array_data)
if length(mz_data) != 1 || length(int_data) != 1
println("DEBUG: Spectrum $k is empty or invalid - creating placeholder metadata")
mz_asset = SpectrumAsset(default_mz_format, mz_is_compressed, Int64(0), 0, :mz, 0.0, 0.0)
int_asset = SpectrumAsset(default_intensity_format, int_is_compressed, Int64(0), 0, :intensity, 0.0, 0.0)
else
mz_info = mz_data[1]
int_info = int_data[1]
if k == 1 # Only print debug for the first spectrum
println("DEBUG First spectrum parsed (unified):")
println(" Coordinates: x=$x, y=$y")
println(" Mode: $spectrum_mode")
println(" m/z array: array_length=$(mz_info.array_length), encoded_length=$(mz_info.encoded_length), offset=$(mz_info.offset)")
println(" intensity array: array_length=$(int_info.array_length), encoded_length=$(int_info.encoded_length), offset=$(int_info.offset)")
end
mz_asset = SpectrumAsset(default_mz_format, mz_is_compressed, mz_info.offset,
mz_is_compressed ? mz_info.encoded_length : mz_info.array_length, :mz, 0.0, 0.0)
int_asset = SpectrumAsset(default_intensity_format, int_is_compressed, int_info.offset,
int_is_compressed ? int_info.encoded_length : int_info.array_length, :intensity, 0.0, 0.0)
end
spectra_metadata[k] = SpectrumMetadata(x, y, "", :sample, spectrum_mode, mz_asset, int_asset)
end
return spectra_metadata
end
"""
load_imzml_lazy(file_path::String; cache_size::Int=100)
The main entry point for loading an imzML file.
It works by locating the .ibd file and parsing the .imzML file
Lazily loads the data and then creating a MSIData object with the
parsed information acquired by the helper functions.
# Arguments
- `file_path::String`: The path to the imzML file.
- `cache_size::Int`: The size of the cache.
# Returns
- `msi_data::MSIData`: The MSI data.
"""
function load_imzml_lazy(file_path::String; cache_size::Int=100, use_mmap::Bool=true)
println("DEBUG: Checking for .imzML file at $file_path")
if !isfile(file_path)
throw(FileFormatError("Provided path is not a file: $(file_path)"))
end
ibd_path = replace(file_path, r"\.(imzML|mzML)"i => ".ibd")
println("DEBUG: Checking for .ibd file at $ibd_path")
if !isfile(ibd_path)
throw(FileFormatError("Corresponding .ibd file not found for: $(file_path)"))
end
println("DEBUG: Opening file streams for .imzML and .ibd")
stream = open(file_path, "r")
# --- Handle Pool Optimization ---
# We open multiple handles to the same .ibd file to avoid lock contention in parallel code.
num_handles = max(1, Threads.maxthreadid())
ibd_handles = [open(ibd_path, "r") for _ in 1:num_handles]
# --- Mmap Optimization with RAM Safety ---
mmap_data = nothing
if use_mmap
try
file_size = filesize(ibd_path)
@debug "Memory mapping .ibd file..."
# We use the first handle for mmapping
mmap_data = Mmap.mmap(ibd_handles[1], Vector{UInt8}, file_size)
# Use POSIX shim for sequential access optimization
posix_madvise(mmap_data, MADV_SEQUENTIAL)
@debug ".ibd file mmapped successfully."
catch e
@warn "Memory mapping failed, falling back to standard I/O: $e"
end
end
try
@debug "Parsing imzML header..."
(instrument_meta, param_groups, imgDim) = parse_imzml_header(stream)
width, height, num_spectra = imgDim
@debug "Image dimensions: $(width)x$(height), $num_spectra spectra."
# ... (format extraction logic stays the same) ...
# [Simplified for brevity in replacement chunk, but keeping the logic]
mz_group = nothing
int_group = nothing
for group in values(param_groups)
if group.Axis == 1; mz_group = group; elseif group.Axis == 2; int_group = group; end
end
default_mz_format = (mz_group !== nothing) ? mz_group.Format : Float64
default_intensity_format = (int_group !== nothing) ? int_group.Format : Float64
mz_is_compressed = (mz_group !== nothing) ? mz_group.Packed : false
int_is_compressed = (int_group !== nothing) ? int_group.Packed : false
global_mode = (mz_group !== nothing && mz_group.Mode != UNKNOWN) ? mz_group.Mode : UNKNOWN
# Use the first handle for metadata parsing (sequential)
# --- Metadata Caching Strategy (Sprint 1) ---
cache_path = file_path * ".cache"
use_cache = isfile(cache_path) && (mtime(cache_path) > mtime(file_path))
local spectra_metadata
if use_cache
@debug "Found valid metadata cache at $cache_path. Loading..."
try
spectra_metadata = load_metadata_cache(cache_path, default_mz_format, default_intensity_format)
@debug "Metadata loaded from cache in O(1) time."
catch e
@warn "Failed to load cache: $e. Falling back to full XML parsing."
use_cache = false
end
end
# Check for compression status once
any_comp = mz_is_compressed || int_is_compressed
if !use_cache
@debug "Parsing spectrum block from XML (this may take time for large files)..."
spectra_metadata = parse_imzml_spectrum_block(stream, ibd_handles[1], param_groups, width, height, num_spectra,
default_mz_format, default_intensity_format,
mz_is_compressed, int_is_compressed, global_mode)
@debug "Metadata parsing complete. Saving cache for next time..."
# We create a temporary MSIData just for save_metadata_cache.
# IMPORTANT: do NOT share the real `ibd_handles` vector here. MSIData
# installs a finalizer that closes every handle in `source.ibd_handles`;
# when this temporary object is garbage-collected it would close the
# handles owned by the real dataset (breaking use_mmap=false reads with
# "Bad file descriptor"). The cache writer only needs the formats.
tmp_source = ImzMLSource(IO[], default_mz_format, default_intensity_format, nothing, any_comp)
tmp_msi = MSIData(tmp_source, spectra_metadata, instrument_meta, (width, height), nothing, cache_size)
try
save_metadata_cache(tmp_msi, cache_path)
catch e
# Read-only media, network shares, and locked files must not
# prevent opening the dataset. The cache is an optimization.
@warn "Could not write the metadata cache; continuing without it" path=cache_path exception=e
end
end
# Build coordinate map ...
coordinate_map = zeros(Int, width, height)
for (idx, meta) in enumerate(spectra_metadata)
if 1 <= meta.x <= width && 1 <= meta.y <= height
coordinate_map[meta.x, meta.y] = idx
end
end
source = ImzMLSource(ibd_handles, default_mz_format, default_intensity_format, mmap_data, any_comp)
@debug "Creating MSIData object."
msi_data = MSIData(source, spectra_metadata, instrument_meta, (width, height), coordinate_map, cache_size)
# NOTE: Do NOT set analytics_ready here even though the cache provides fast metadata loading.
# The cache only stores binary offsets (SpectrumMetadataBinary). It does NOT populate
# msi_data.spectrum_stats_df (TIC, BPI, BasePeakMZ, MinMZ, MaxMZ), which requires a
# streaming pass via precompute_analytics(). Setting the flag prematurely causes
# get_mz_slice to skip that pass, leaving stats_df=nothing and all min/max bounds at 0.0,
# resulting in zero pixels populated in every image slice.
@debug "Metadata loaded from cache — analytics scan deferred until first use."
close(stream)
return msi_data
catch e
close(stream)
# Check if handles exist before closing
if @isdefined(ibd_handles)
for h in ibd_handles
isopen(h) && close(h)
end
end
rethrow(e)
end
end
# =============================================================================
#
# Image Slice Extraction
#
# =============================================================================
"""
find_mass(mz_array, intensity_array, target_mass, tolerance)
Finds the intensity of the most intense peak within a mass tolerance window.
This optimized version uses binary search for efficiency.
# Arguments
- `mz_array::AbstractVector{<:Real}`: The m/z array.
- `intensity_array::AbstractVector{<:Real}`: The intensity array.
- `target_mass::Real`: The target mass.
- `tolerance::Real`: The tolerance.
# Returns
- The intensity (`Float64`) of the peak if found, otherwise `0.0`.
"""
@inline function find_mass(mz_array::AbstractVector{<:Real}, intensity_array::AbstractVector{<:Real},
target_mass::Real, tolerance::Real)
# Fast-path rejection: if the array is empty or the target is out of range
if isempty(mz_array) || target_mass + tolerance < first(mz_array) || target_mass - tolerance > last(mz_array)
return 0.0
end
lower_bound = target_mass - tolerance
upper_bound = target_mass + tolerance
# Use binary search to find the start and end of the m/z window
start_idx = searchsortedfirst(mz_array, lower_bound)
end_idx = searchsortedlast(mz_array, upper_bound)
# If the window is empty, return 0.0
if start_idx > end_idx
return 0.0
end
# Find the maximum intensity within the identified window, optimized with @inbounds and @simd
max_intensity = intensity_array[start_idx]
@inbounds @simd for i in (start_idx + 1):end_idx
max_intensity = max(max_intensity, intensity_array[i])
end
return max_intensity
end
"""
get_mz_slice(data::MSIData, mass::Real, tolerance::Real)
Extracts an image slice for a given m/z value without plotting.
This is a performant function that iterates through spectra once.
# Arguments
- `data::MSIData`: The MSIData object.
- `mass::Real`: The target mass.
- `tolerance::Real`: The tolerance.
- `mask_path::Union{String, Nothing}`: The path to the mask.
# Returns
- A `Matrix{Float64}` representing the intensity slice.
"""
function get_mz_slice(data::MSIData, mass::Real, tolerance::Real; mask_path::Union{String, Nothing}=nothing)
width, height = data.image_dims
slice_matrix = zeros(Float64, height, width)
local masked_indices::Union{Set{Int}, Nothing} = nothing
if mask_path !== nothing
mask_matrix = load_and_prepare_mask(mask_path, (width, height))
masked_indices = get_masked_spectrum_indices(data, mask_matrix)
println("Applying mask from: $(mask_path), found $(length(masked_indices)) spectra in ROI.")
end
# INTELLIGENT LOADING: Ensure analytics are computed for filtering.
if !is_set(data.analytics_ready)
println("Per-spectrum metadata not found. Running one-time analytics computation...")
precompute_analytics(data)
end
target_min = mass - tolerance
target_max = mass + tolerance
# PERFORMANCE: Access raw vectors from metadata to avoid DataFrame dependency
# If stats_df exists, use it; otherwise, use the pre-computed bounds in SpectrumAsset
stats_df = get_spectrum_stats(data)
n_total = length(data.spectra_metadata)
# Instantiate thread-local buffer locally since global pools are deprecated
candidate_indices = Vector{Int}(undef, n_total)
# We'll use local views of min/max if stats_df is missing to represent zero-allocation fallback
# But for extreme performance, we avoid list comprehensions [m... for m in ...] as they allocate.
local min_mzs::Vector{Float64}
local max_mzs::Vector{Float64}
if stats_df !== nothing
min_mzs = stats_df.MinMZ
max_mzs = stats_df.MaxMZ
else
# Fallback path: extract to local buffers or use metadata directly in loop
# For now, let's assume stats_df is usually populated by precompute_analytics.
# If not, we'll access it directly inside the filter loop.
end
candidate_count = 0
indices_to_check = masked_indices === nothing ? (1:n_total) : masked_indices
discretization_factor = 100.0
bloom_filters = get_bloom_filters(data)
for i in indices_to_check
# Range check first (cheapest)
# Access metadata directly if stats_df is missing to ensure zero-allocation
@inbounds meta = data.spectra_metadata[i]
s_min, s_max = (stats_df !== nothing) ? (min_mzs[i], max_mzs[i]) : (meta.mz_asset.min_val, meta.mz_asset.max_val)
if target_max < s_min || target_min > s_max
continue
end
# Bloom filter rejection (very fast)
if bloom_filters !== nothing
bf = bloom_filters[i]
if bf !== nothing && !is_empty(bf)
min_mass_int = round(Int, (mass - tolerance) * discretization_factor)
max_mass_int = round(Int, (mass + tolerance) * discretization_factor)
found = false
@inbounds for mass_int in min_mass_int:max_mass_int
if mass_int in bf
found = true
break
end
end
!found && continue
end
end
candidate_count += 1
@inbounds candidate_indices[candidate_count] = i
end
# Use a view of the pre-allocated vector to avoid collect() allocations
valid_candidates = view(candidate_indices, 1:candidate_count)
# 2. Iterate using the optimized, low-allocation iterator
# Use Atomic for thread-safe increment and avoid Ref-boxing
results_count = Base.Threads.Atomic{Int}(0)
# Use let block to ensure closure captures are optimized (avoid boxing)
let slice_matrix=slice_matrix, results_count=results_count, width=width, height=height,
spectra_metadata=data.spectra_metadata, mass=mass, tolerance=tolerance
_iterate_spectra_fast(data, valid_candidates) do idx, mz_array, intensity_array
@inbounds meta = spectra_metadata[idx]
intensity = find_mass(mz_array, intensity_array, mass, tolerance)
if intensity > 0.0
if 1 <= meta.x <= width && 1 <= meta.y <= height
@inbounds slice_matrix[meta.y, meta.x] = intensity
Base.Threads.atomic_add!(results_count, 1)
end
end
end
end
#println("Populated $(results_count[]) pixels with intensity data")
replace!(slice_matrix, NaN => 0.0)
return slice_matrix
end
"""
get_multiple_mz_slices(data::MSIData, masses::AbstractVector{<:Real}, tolerance::Real)
Extracts multiple image slices for a given list of m/z values in a single pass.
This is a highly performant function that iterates through the full dataset only once.
# Arguments
- `data::MSIData`: The MSIData object.
- `masses::AbstractVector{<:Real}`: The target masses.
- `tolerance::Real`: The tolerance.
- `mask_path::Union{String, Nothing}`: The path to the mask.
# Returns
- A `Dict{Real, Matrix{Float64}}` mapping each mass to its intensity slice matrix.
"""
function get_multiple_mz_slices(data::MSIData, masses::AbstractVector{<:Real}, tolerance::Real; mask_path::Union{String, Nothing}=nothing)
width, height = data.image_dims
# Sort masses to improve cache locality and allow binary search
sorted_masses = sort(masses)
n_masses = length(sorted_masses)
# 1. Initialize a dictionary to hold the output slice matrices (using Float32 for 50% RAM savings)
slice_dict = Dict{Real, Matrix{Float32}}()
for mass in sorted_masses
slice_dict[mass] = zeros(Float32, height, width)
end
local masked_indices::Union{Set{Int}, Nothing} = nothing
if mask_path !== nothing
mask_matrix = load_and_prepare_mask(mask_path, (width, height))
masked_indices = get_masked_spectrum_indices(data, mask_matrix)
println("Applying mask from: $(mask_path), found $(length(masked_indices)) spectra in ROI.")
end
# 2. Ensure analytics are computed for filtering.
if !is_set(data.analytics_ready)
println("Per-spectrum metadata not found. Running one-time analytics computation...")
precompute_analytics(data)
end
println("Filtering candidate spectra for $n_masses m/z values...")
stats_df = get_spectrum_stats(data)
bloom_filters = get_bloom_filters(data)
# Use a BitSet for faster index tracking
candidate_indices = BitSet()
indices_to_check = masked_indices === nothing ? (1:length(data.spectra_metadata)) : masked_indices
# 3. Optimized filtering: Iterate through spectra ONCE and check against all masses
# This changes complexity from O(M*N) to O(N * log M) or O(N + M) depending on range overlap
discretization_factor = 100.0
for i in indices_to_check
spec_min = stats_df.MinMZ[i]
spec_max = stats_df.MaxMZ[i]
# Binary search to find masses that might overlap with this spectrum's range
# target_min = mass - tolerance => mass = target_min + tolerance
# We need mass such that mass + tolerance >= spec_min => mass >= spec_min - tolerance
# and mass - tolerance <= spec_max => mass <= spec_max + tolerance
m_start_idx = searchsortedfirst(sorted_masses, spec_min - tolerance)
m_end_idx = searchsortedlast(sorted_masses, spec_max + tolerance)
if m_start_idx <= m_end_idx
# Range overlap found, now check Bloom filter if available
if bloom_filters !== nothing && bloom_filters[i] !== nothing && !is_empty(bloom_filters[i])
found_any = false
@inbounds for m_idx in m_start_idx:m_end_idx
mass = sorted_masses[m_idx]
min_mass_int = round(Int, (mass - tolerance) * discretization_factor)
max_mass_int = round(Int, (mass + tolerance) * discretization_factor)
for mass_int in min_mass_int:max_mass_int
if mass_int in bloom_filters[i]
found_any = true
break
end
end
found_any && break
end
if found_any
push!(candidate_indices, i)
end
else
push!(candidate_indices, i)
end
end
end
println("Found $(length(candidate_indices)) total candidate spectra.")
# 4. Iterate through the data a single time using the optimized iterator.
# We collect candidate_indices to pass to parallel iterator
_iterate_spectra_fast(data, collect(candidate_indices)) do idx, mz_array, intensity_array
meta = data.spectra_metadata[idx]
if isempty(mz_array)
return
end
# Spectrum-level boundaries
spec_first = first(mz_array)
spec_last = last(mz_array)
# Find which of our target masses fall within this specific spectrum's actual range
m_start_idx = searchsortedfirst(sorted_masses, spec_first - tolerance)
m_end_idx = searchsortedlast(sorted_masses, spec_last + tolerance)
@inbounds for m_idx in m_start_idx:m_end_idx
mass = sorted_masses[m_idx]
intensity = find_mass(mz_array, intensity_array, mass, tolerance)
if intensity > 0.0
if 1 <= meta.x <= width && 1 <= meta.y <= height
# Note: Concurrent writes to different matrices/coordinates are safe.
# Dictionary access is safe because it's read-only after initialization.
slice_dict[mass][meta.y, meta.x] = Float32(intensity)
end
end
end
end
# 5. Clean up - replaces NaNs with 0.0 directly in Float32 matrices
for mass in sorted_masses
replace!(slice_dict[mass], NaN32 => 0.0f0)
end
println("Finished generating $n_masses slices in a single pass.")
return slice_dict
end
# ============================================================================
#
#
# Image Processing and Normalization
#
# ============================================================================
"""
get_outlier_thres(img, prob=0.98)
Calculates dynamic intensity range bounds for an image based on a cumulative
probability histogram. This function replicates an R algorithm to find an
intensity threshold that corresponds to a given cumulative probability, which
is used to exclude outliers before normalization.
# Arguments
- `img`: The input image matrix.
- `prob`: The cumulative probability threshold (default: 0.98) for outlier detection.
# Returns
- A tuple `(low, high)` representing the calculated lower and upper intensity bounds.
"""
function get_outlier_thres(img::AbstractVector{<:Real}, prob::Real=0.98)
# DO NOT filter zeros. Use all pixel values like R does.
int_values = img
low = minimum(int_values)
upp = maximum(int_values)
# Create histogram bins
if upp - low + 1 >= 100
bins = 100
brk = range(low, stop=upp + (upp - low)/(bins - 1), length=bins + 1)
else
brk = collect(floor(low):(ceil(upp) + 1))
end
# Compute histogram with RIGHT-CLOSED = FALSE to mimic R's right=FALSE
# This makes intervals [a, b) instead of the default [a, b]
h = fit(Histogram, int_values, brk, closed=:left) # Key change: closed=:left
# Check if histogram is valid
if isempty(h.weights) || sum(h.weights) == 0
return (low, upp)
end
# Replicate R's algorithm exactly
cum_counts = cumsum(h.weights) / sum(h.weights)
# Calculate the difference from the target probability
top = prob .- cum_counts
delta = abs.(top)
# Find the index where the difference is minimized
min_delta_index = findfirst(x -> x == minimum(delta), delta)
# R adds 1 to this index: index <- 1 + which(...)[1]
target_bin_index = min_delta_index + 1
# Get the upper edge of the target bin
target_bin_upper_edge = h.edges[1][target_bin_index]
# Find the maximum data value that is strictly less than this edge
# This mimics: max( intMap[ intMap < h$breaks[index] ] )
values_below_edge = filter(x -> x < target_bin_upper_edge, int_values)
actual_threshold = isempty(values_below_edge) ? low : maximum(values_below_edge)
return (low, actual_threshold)
end
function get_outlier_thres(img::AbstractMatrix{<:Real}, prob::Real=0.98)
return get_outlier_thres(vec(img), prob)
end
"""
set_pixel_depth(img, bounds, depth)
Quantizes the intensity values of an image into a specified number of bins
(`depth`) within a given intensity range (`bounds`). Pixels outside the bounds
are clipped.
# Arguments
- `img`: The input image matrix.
- `bounds`: A tuple `(min, max)` specifying the intensity range for quantization.
- `depth`: The number of quantization levels (bins).
# Returns
- A `Matrix{UInt8}` with pixel values quantized to the specified depth.
"""
function set_pixel_depth(img::AbstractMatrix{<:Real}, bounds::Tuple{<:Real, <:Real}, depth::Integer)
min_val, max_val = bounds
bins = depth - 1
if min_val >= max_val
return zeros(UInt8, size(img))
end
# Create intensity bins - FIXED: use binary search instead of linear scan
range_vals = range(min_val, stop=max_val, length=depth)[2:depth]
# Pre-allocate result for better performance
result = similar(img, UInt8)
# Use binary search for much faster bin assignment
@inbounds for i in eachindex(img)
val = img[i]
if val <= min_val
result[i] = 0
elseif val >= max_val
result[i] = bins
else
# Binary search is much faster than linear scan
bin_idx = searchsortedfirst(range_vals, val)
result[i] = bin_idx
end
end
return result
end
"""
TrIQ(pixMap, depth, prob=0.98)
Applies TrIQ (Treshold Intensity Quantization) normalization to an image.
This function first computes dynamic intensity range bounds by identifying outliers
based on a cumulative probability, then sets the pixel depth (quantizes intensities)
within these bounds.
# Arguments
- `pixMap`: The input image matrix (e.g., a slice from `GetMzSliceJl`).
- `depth`: The number of grey levels (bins) to quantize the intensities into.
- `prob`: The target cumulative probability (e.g., 0.98) used to determine outlier thresholds.
# Returns
- A new image matrix with intensities quantized to the specified depth within the TrIQ bounds.
"""
function TrIQ(pixMap::AbstractMatrix{<:Real}, depth::Integer, prob::Real=0.98; mask_matrix::Union{BitMatrix, Nothing}=nothing)
local values_for_thres
if mask_matrix !== nothing
values_for_thres = pixMap[mask_matrix]
filter!(x -> x != 0, values_for_thres)
else
values_for_thres = pixMap
end
if isempty(values_for_thres) || all(iszero, values_for_thres)
bounds = (0.0, 0.0)
quantized = zeros(UInt8, size(pixMap))
else
bounds = get_outlier_thres(values_for_thres, prob)
quantized = set_pixel_depth(pixMap, bounds, depth)
end
return quantized, bounds # Return both!
end
"""
norm_slices_hist(slices, bins; prob=0.98)
Normalizes a set of image slices based on a shared histogram range.
# Arguments
- `slices`: The image slices.
- `bins`: The number of bins.
- `prob`: The target cumulative probability.
# Returns
- `norm_img`: The normalized image slices.
- `mass_bounds`: The bounds for each mass.
"""
function norm_slices_hist(slices, bins; prob=0.98)
n_files, n_masses = size(slices)
norm_img = similar(slices)
mass_bounds = [] # This will store bounds for EACH mass
# Calculate bounds for each mass across all files
for mass_idx in 1:n_masses
# Get all slices for this specific mass across all files
mass_slices = [slices[i, mass_idx] for i in 1:n_files]
all_vals = reduce(vcat, [vec(s) for s in mass_slices])
# Calculate global bounds for this specific mass
mass_global_bounds = get_outlier_thres(all_vals, prob)
push!(mass_bounds, mass_global_bounds)
# Normalize each file's slice for this mass using its specific bounds
for file_idx in 1:n_files
norm_img[file_idx, mass_idx] = set_pixel_depth(slices[file_idx, mass_idx], mass_global_bounds, bins)
end
end
return (norm_img=norm_img, bounds=mass_bounds) # bounds is now a vector, one per mass
end
"""
quantize_intensity(slice::AbstractMatrix{<:Real}, levels::Integer=256)
Linearly scales the intensity values in a slice to a specified number of levels.
The output is an array of `UInt8` values.
This is a modernized version of the original `IntQuantCl`. by Nacho
# Arguments
- `slice`: The image slice.
- `levels`: The number of levels.
- `mask_matrix`: The mask matrix.
# Returns
- `quantized`: The quantized image slice.
- `bounds`: The bounds for each mass.
"""
function quantize_intensity(slice::AbstractMatrix{<:Real}, levels::Integer=256; mask_matrix::Union{BitMatrix, Nothing}=nothing)
local max_val
if mask_matrix !== nothing
masked_slice = slice[mask_matrix]
# Filter out zeros that might have been introduced by masking, if any
filter!(x -> x != 0, masked_slice)
max_val = isempty(masked_slice) ? 0.0 : maximum(masked_slice)
else
max_val = maximum(slice)
end
if max_val <= 0
bounds = (0.0, 0.0)
quantized = zeros(UInt8, size(slice))
else
bounds = (0.0, max_val)
quantized = similar(slice, UInt8)
scale = (levels - 1) / max_val
@inbounds for i in eachindex(slice)
quantized[i] = round(UInt8, clamp(slice[i] * scale, 0, levels - 1))
end
end
return quantized, bounds # Return both!
end
"""
median_filter(img)
Applies a 3x3 median filter to the input image. This is a simple noise
reduction technique that replaces each pixel's value with the median value of
its 3x3 neighborhood.
# Arguments
- `img`: The input image matrix.
# Returns
- A new matrix containing the filtered image.
"""
function median_filter(img)
# 3x3 median filter implementation
return mapwindow(median, img, (3, 3))
end
"""
downsample_spectrum(mz, intensity, n_points=2000)
Reduces the number of points in a spectrum for faster plotting, while preserving peaks.
It divides the m/z range into `n_points` bins and keeps only the most intense point from each bin.
# Arguments
- `mz`: The m/z values.
- `intensity`: The intensity values.
- `n_points`: The number of points.
# Returns
- `mz`: The downsampled m/z values.
- `intensity`: The downsampled intensity values.
"""
function downsample_spectrum(mz::AbstractVector, intensity::AbstractVector, n_points::Integer=2000)
if isempty(mz) || length(mz) <= n_points
return mz, intensity
end
mz_min, mz_max = extrema(mz)
bin_width = (mz_max - mz_min) / n_points
# We use a vector of tuples to store the max intensity and its corresponding mz for each bin
# (max_intensity, mz_value)
bins = fill((0.0, 0.0), n_points)
for i in eachindex(mz)
# Determine the bin for the current point
# Bin indices are 1-based
bin_index = min(n_points, floor(Int, (mz[i] - mz_min) / bin_width) + 1)
# If the current point's intensity is higher than what's in the bin, replace it
if intensity[i] > bins[bin_index][1]
bins[bin_index] = (intensity[i], mz[i])
end
end
# Filter out empty bins and separate the mz and intensity values
final_mz = [b[2] for b in bins if b[1] > 0.0]
final_intensity = [b[1] for b in bins if b[1] > 0.0]
return final_mz, final_intensity
end
# ============================================================================
#
#
# Analysis and Visualization
#
# ============================================================================
"""
save_bitmap(name::String, pixMap::Matrix{UInt8}, colorTable::Vector{UInt32})
Saves an 8-bit indexed image as a BMP file.
This is a modernized version of `SaveBitmapCl`.
# Arguments
- `name`: The name of the file.
- `pixMap`: The pixel map.
- `colorTable`: The color table.
# Returns
- `nothing`
"""
function save_bitmap(name::String, pixMap::Matrix{UInt8}, colorTable::Vector{UInt32})
# Get image dimensions
height, width = size(pixMap)
# Normalize pixel values to stretch contrast, as in the original SaveBitmapCl
minVal, maxVal = extrema(pixMap)
if maxVal > minVal
pixMap = round.(UInt8, 255 * (pixMap .- minVal) ./ (maxVal - minVal))
end
# Compute row padding (each row must be a multiple of 4 bytes)
padding = (4 - (width % 4)) % 4
# BMP color table must have 256 entries for 8-bit images
fullColorTable = Vector{UInt32}(undef, 256)
if length(colorTable) <= 256
fullColorTable[1:length(colorTable)] .= colorTable
fullColorTable[length(colorTable)+1:end] .= 0
else
fullColorTable .= colorTable[1:256]
end
# Compute file dimensions
offset = 14 + 40 + (256 * 4) # 14(file) + 40(info) + 1024(palette) = 1078
imgBytes = height * (width + padding)
fileSize = offset + imgBytes
open(name, "w") do stream
# === File Header (14 bytes) ===
write(stream, UInt16(0x4D42)) # "BM"
write(stream, UInt32(fileSize))
write(stream, UInt16(0)) # Reserved
write(stream, UInt16(0)) # Reserved
write(stream, UInt32(offset))
# === Info Header (40 bytes) ===
write(stream, UInt32(40)) # Info header size
write(stream, Int32(width))
write(stream, Int32(height)) # Positive for bottom-up storage
write(stream, UInt16(1)) # Number of color planes
write(stream, UInt16(8)) # Bits per pixel
write(stream, UInt32(0)) # Compression (BI_RGB)
write(stream, UInt32(imgBytes))
write(stream, Int32(2835)) # Pels per meter X (~72 DPI)
write(stream, Int32(2835)) # Pels per meter Y (~72 DPI)
write(stream, UInt32(256)) # Colors in color table
write(stream, UInt32(0)) # Important colors (0 = all)
# === Color Table ===
write(stream, fullColorTable)
# === Image Pixels (written bottom-up) ===
row_buffer = Vector{UInt8}(undef, width + padding)
row_buffer[width+1:end] .= 0 # pre-fill padding bytes
for i in height:-1:1
row_data = @view pixMap[i, :]
row_buffer[1:width] = row_data
write(stream, row_buffer)
end
end
end
"""
generate_palette(colorscheme, n_colors=256)
Generates a BMP-compatible UInt32 color palette from a ColorScheme.
# Arguments
- `colorscheme`: The colorscheme.
- `n_colors`: The number of colors.
# Returns
- `palette`: The color palette.
"""
function generate_palette(colorscheme, n_colors=256)
palette = Vector{UInt32}(undef, n_colors)
colors = get(colorscheme, range(0, 1, length=n_colors))
for i in 1:n_colors
c = colors[i]
r = round(UInt8, c.r * 255)
g = round(UInt8, c.g * 255)
b = round(UInt8, c.b * 255)
# BMP color table format is 0x00RRGGBB, written little-endian becomes BB GG RR 00
palette[i] = (UInt32(r) << 16) | (UInt32(g) << 8) | UInt32(b)
end
return palette
end
# Viridis color palette (256 colors) - defined as constant
const ViridisPalette = generate_palette(ColorSchemes.viridis)