Added mask interface accessible from the UI, with it you can create slices from your masks or your images of the samples, included masking in the main processing, on the spectra creation, and on the 3d surface plot, started with interface for pre processing spectral data
This commit is contained in:
+65
-3
@@ -1,16 +1,80 @@
|
||||
module ImageProcessing
|
||||
# src/ImageProcessing
|
||||
|
||||
using Images
|
||||
using ImageBinarization
|
||||
using ImageMorphology
|
||||
using ImageComponentAnalysis
|
||||
using Colors # For converting to grayscale
|
||||
|
||||
export process_image_pipeline
|
||||
export load_and_prepare_mask # Export the new function
|
||||
|
||||
"""
|
||||
load_and_prepare_mask(mask_path::String, target_dims::Tuple{Int, Int})
|
||||
|
||||
Loads a PNG image mask, converts it to a binary (Boolean) matrix,
|
||||
and resizes it to the specified `target_dims`. White pixels in the mask
|
||||
are considered `true` (part of the ROI), and black pixels are `false`.
|
||||
|
||||
# Arguments
|
||||
- `mask_path`: Absolute path to the PNG mask file.
|
||||
- `target_dims`: A tuple `(width, height)` representing the desired output dimensions.
|
||||
|
||||
# Returns
|
||||
- A `BitMatrix` of `target_dims` where `true` indicates the ROI.
|
||||
"""
|
||||
function load_and_prepare_mask(mask_path::String, target_dims::Tuple{Int, Int})
|
||||
if !isfile(mask_path)
|
||||
error("Mask file not found: $(mask_path)")
|
||||
end
|
||||
|
||||
# Load the image
|
||||
img = Images.load(mask_path)
|
||||
|
||||
# Convert to grayscale if it's a color image
|
||||
gray_img = Gray.(img)
|
||||
|
||||
# Binarize using Otsu's method - white regions become 'true'
|
||||
binary_img = binarize(gray_img, Otsu())
|
||||
|
||||
# Resize to target dimensions
|
||||
resized_img = imresize(binary_img, (target_dims[2], target_dims[1]))
|
||||
|
||||
# Ensure the output is a BitMatrix, as imresize can change the type
|
||||
return resized_img .> 0.5
|
||||
end
|
||||
|
||||
# ===================================================================
|
||||
# CORE PROCESSING PIPELINE
|
||||
# ===================================================================
|
||||
|
||||
"""
|
||||
process_image_pipeline(gray_img; otsu_scale=1.0, noise_size_percent=0.1, hole_size_percent=0.05, smoothing=2)
|
||||
|
||||
Applies a multi-step image processing pipeline to a grayscale image to segment regions of interest.
|
||||
|
||||
The pipeline consists of:
|
||||
1. **Binarization**: An adjusted Otsu's threshold is used to create a binary image.
|
||||
2. **Noise Removal**: Small white regions (noise) are removed using an area opening operation.
|
||||
3. **Hole Filling**: Small black regions (holes) within larger objects are filled.
|
||||
4. **Edge Smoothing**: The edges of the final regions are smoothed using a morphological closing operation.
|
||||
|
||||
# Arguments
|
||||
- `gray_img`: The input grayscale image (`Matrix{<:Gray}`).
|
||||
|
||||
# Keyword Arguments
|
||||
- `otsu_scale`: A factor to scale the automatically determined Otsu threshold. Values > 1.0 make the threshold stricter (less white), < 1.0 make it more lenient (more white). Default: `1.0`.
|
||||
- `noise_size_percent`: The percentage of the total image area used as a threshold to remove small white noise components. Default: `0.1`.
|
||||
- `hole_size_percent`: The percentage of the total image area used as a threshold to fill black holes in white components. Default: `0.05`.
|
||||
- `smoothing`: The size of the kernel for the final edge smoothing (closing) operation. Default: `2`.
|
||||
|
||||
# Returns
|
||||
- A tuple containing four images representing the intermediate steps of the pipeline:
|
||||
1. `binary_img`: The result of the initial binarization.
|
||||
2. `noise_removed_img`: The image after noise removal.
|
||||
3. `holes_filled_img`: The image after filling holes.
|
||||
4. `smoothed_img`: The final smoothed image.
|
||||
"""
|
||||
function process_image_pipeline(gray_img;
|
||||
otsu_scale=1.0,
|
||||
noise_size_percent=0.1,
|
||||
@@ -43,5 +107,3 @@ function process_image_pipeline(gray_img;
|
||||
# --- Return all intermediate steps for visualization ---
|
||||
return binary_img, noise_removed_img, holes_filled_img, smoothed_img
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
+92
-30
@@ -143,6 +143,45 @@ mutable struct MSIData
|
||||
end
|
||||
end
|
||||
|
||||
"""
|
||||
get_masked_spectrum_indices(data::MSIData, mask_matrix::BitMatrix) -> Set{Int}
|
||||
|
||||
Converts a 2D boolean mask matrix (e.g., loaded from a PNG) into a `Set` of linear
|
||||
spectrum indices that fall within the `true` regions of the mask.
|
||||
|
||||
# Arguments
|
||||
- `data`: The `MSIData` object containing the `coordinate_map`.
|
||||
- `mask_matrix`: A `BitMatrix` where `true` indicates a pixel is part of the ROI.
|
||||
|
||||
# Returns
|
||||
- A `Set{Int}` containing the linear indices of spectra within the mask.
|
||||
"""
|
||||
function get_masked_spectrum_indices(data::MSIData, mask_matrix::BitMatrix)
|
||||
if data.coordinate_map === nothing
|
||||
error("Coordinate map not available. Cannot apply mask to non-imaging data.")
|
||||
end
|
||||
|
||||
width, height = data.image_dims
|
||||
mask_height, mask_width = size(mask_matrix)
|
||||
|
||||
if mask_width != width || mask_height != height
|
||||
error("Mask dimensions ($(mask_width)x$(mask_height)) do not match image dimensions ($(width)x$(height)).")
|
||||
end
|
||||
|
||||
masked_indices = Set{Int}()
|
||||
for y in 1:height
|
||||
for x in 1:width
|
||||
if mask_matrix[y, x] # If this pixel is part of the mask
|
||||
idx = data.coordinate_map[x, y]
|
||||
if idx != 0 # Ensure there's an actual spectrum at this coordinate
|
||||
push!(masked_indices, idx)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return masked_indices
|
||||
end
|
||||
|
||||
|
||||
# --- Internal function for reading binary data --- #
|
||||
|
||||
@@ -513,7 +552,7 @@ It uses a fast, two-pass approach:
|
||||
This function is highly optimized for `.imzML` by leveraging direct binary
|
||||
reading and optimized binning logic. It is called by `get_total_spectrum`.
|
||||
"""
|
||||
function get_total_spectrum_imzml(msi_data::MSIData; num_bins::Int=2000)
|
||||
function get_total_spectrum_imzml(msi_data::MSIData; num_bins::Int=2000, masked_indices::Union{Set{Int}, Nothing}=nothing)
|
||||
println("Calculating total spectrum for imzML (2-pass method)...")
|
||||
total_start_time = time_ns()
|
||||
|
||||
@@ -529,7 +568,7 @@ function get_total_spectrum_imzml(msi_data::MSIData; num_bins::Int=2000)
|
||||
println(" Pass 1: Finding global m/z range...")
|
||||
g_min_mz = Inf
|
||||
g_max_mz = -Inf
|
||||
_iterate_spectra_fast(msi_data) do idx, mz, _
|
||||
_iterate_spectra_fast(msi_data, masked_indices === nothing ? nothing : collect(masked_indices)) do idx, mz, _
|
||||
if !isempty(mz)
|
||||
local_min, local_max = extrema(mz)
|
||||
g_min_mz = min(g_min_mz, local_min)
|
||||
@@ -539,7 +578,7 @@ function get_total_spectrum_imzml(msi_data::MSIData; num_bins::Int=2000)
|
||||
pass1_duration = (time_ns() - pass1_start_time) / 1e9
|
||||
if !isfinite(g_min_mz)
|
||||
@warn "Could not determine a valid m/z range for imzML. All spectra might be empty."
|
||||
return (Float64[], Float64[])
|
||||
return (Float64[], Float64[], 0)
|
||||
end
|
||||
|
||||
# Use and cache the result
|
||||
@@ -560,7 +599,9 @@ function get_total_spectrum_imzml(msi_data::MSIData; num_bins::Int=2000)
|
||||
# 3. Second Pass: Optimized binning
|
||||
pass2_start_time = time_ns()
|
||||
println(" Pass 2: Summing intensities into $num_bins bins...")
|
||||
_iterate_spectra_fast(msi_data) do idx, mz, intensity
|
||||
num_spectra_processed = 0
|
||||
_iterate_spectra_fast(msi_data, masked_indices === nothing ? nothing : collect(masked_indices)) do idx, mz, intensity
|
||||
num_spectra_processed += 1
|
||||
if isempty(mz)
|
||||
return
|
||||
end
|
||||
@@ -594,7 +635,7 @@ function get_total_spectrum_imzml(msi_data::MSIData; num_bins::Int=2000)
|
||||
println("----------------------------------------\n")
|
||||
|
||||
println("Total spectrum calculation complete for imzML.")
|
||||
return (collect(mz_bins), intensity_sum)
|
||||
return (collect(mz_bins), intensity_sum, num_spectra_processed)
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -608,7 +649,7 @@ It uses a two-pass approach analogous to the `imzML` implementation:
|
||||
|
||||
This function is called by `get_total_spectrum`.
|
||||
"""
|
||||
function get_total_spectrum_mzml(msi_data::MSIData; num_bins::Int=2000)
|
||||
function get_total_spectrum_mzml(msi_data::MSIData; num_bins::Int=2000, masked_indices::Union{Set{Int}, Nothing}=nothing)
|
||||
println("Calculating total spectrum for mzML (2-pass method)...")
|
||||
total_start_time = time_ns()
|
||||
|
||||
@@ -624,7 +665,7 @@ function get_total_spectrum_mzml(msi_data::MSIData; num_bins::Int=2000)
|
||||
println(" Pass 1: Finding global m/z range...")
|
||||
g_min_mz = Inf
|
||||
g_max_mz = -Inf
|
||||
_iterate_spectra_fast(msi_data) do idx, mz, intensity
|
||||
_iterate_spectra_fast(msi_data, masked_indices === nothing ? nothing : collect(masked_indices)) do idx, mz, intensity
|
||||
if !isempty(mz)
|
||||
local_min, local_max = extrema(mz)
|
||||
g_min_mz = min(g_min_mz, local_min)
|
||||
@@ -635,7 +676,7 @@ function get_total_spectrum_mzml(msi_data::MSIData; num_bins::Int=2000)
|
||||
|
||||
if !isfinite(g_min_mz)
|
||||
@warn "Could not determine a valid m/z range for mzML. All spectra might be empty."
|
||||
return (Float64[], Float64[])
|
||||
return (Float64[], Float64[], 0)
|
||||
end
|
||||
|
||||
# Use and cache the result
|
||||
@@ -658,7 +699,9 @@ function get_total_spectrum_mzml(msi_data::MSIData; num_bins::Int=2000)
|
||||
inv_bin_step = 1.0 / bin_step # Precompute reciprocal
|
||||
min_mz = global_min_mz
|
||||
|
||||
_iterate_spectra_fast(msi_data) do idx, mz, intensity
|
||||
num_spectra_processed = 0
|
||||
_iterate_spectra_fast(msi_data, masked_indices === nothing ? nothing : collect(masked_indices)) do idx, mz, intensity
|
||||
num_spectra_processed += 1
|
||||
if isempty(mz)
|
||||
return
|
||||
end
|
||||
@@ -687,7 +730,7 @@ function get_total_spectrum_mzml(msi_data::MSIData; num_bins::Int=2000)
|
||||
println("----------------------------------------\n")
|
||||
|
||||
println("Total spectrum calculation complete for mzML.")
|
||||
return (collect(mz_bins), intensity_sum)
|
||||
return (collect(mz_bins), intensity_sum, num_spectra_processed)
|
||||
end
|
||||
|
||||
"""
|
||||
@@ -699,11 +742,18 @@ This function dispatches to a specialized implementation based on the file type
|
||||
|
||||
Returns a tuple containing two vectors: the binned m/z axis and the summed intensities.
|
||||
"""
|
||||
function get_total_spectrum(msi_data::MSIData; num_bins::Int=2000)
|
||||
function get_total_spectrum(msi_data::MSIData; num_bins::Int=2000, mask_path::Union{String, Nothing}=nothing)::Tuple{Vector{Float64}, Vector{Float64}, Int}
|
||||
local masked_indices::Union{Set{Int}, Nothing} = nothing
|
||||
if mask_path !== nothing
|
||||
mask_matrix = load_and_prepare_mask(mask_path, msi_data.image_dims)
|
||||
masked_indices = get_masked_spectrum_indices(msi_data, mask_matrix)
|
||||
println("Calculating total spectrum for masked region (mask from: $(mask_path))")
|
||||
end
|
||||
|
||||
if msi_data.source isa ImzMLSource
|
||||
return get_total_spectrum_imzml(msi_data, num_bins=num_bins)
|
||||
return get_total_spectrum_imzml(msi_data, num_bins=num_bins, masked_indices=masked_indices)
|
||||
else # MzMLSource
|
||||
return get_total_spectrum_mzml(msi_data, num_bins=num_bins)
|
||||
return get_total_spectrum_mzml(msi_data, num_bins=num_bins, masked_indices=masked_indices)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -715,14 +765,15 @@ This is effectively the total spectrum divided by the number of spectra.
|
||||
|
||||
Returns a tuple containing two vectors: the binned m/z axis and the averaged intensities.
|
||||
"""
|
||||
function get_average_spectrum(msi_data::MSIData; num_bins::Int=2000)
|
||||
mz_bins, intensity_sum = get_total_spectrum(msi_data, num_bins=num_bins)
|
||||
function get_average_spectrum(msi_data::MSIData; num_bins::Int=2000, mask_path::Union{String, Nothing}=nothing)::Tuple{Vector{Float64}, Vector{Float64}}
|
||||
mz_bins, intensity_sum, num_spectra_processed = get_total_spectrum(msi_data, num_bins=num_bins, mask_path=mask_path)
|
||||
|
||||
if isempty(intensity_sum)
|
||||
return (mz_bins, intensity_sum)
|
||||
if isempty(intensity_sum) || num_spectra_processed == 0
|
||||
@warn "Cannot calculate average spectrum: no spectra were processed."
|
||||
return (mz_bins, Float64[])
|
||||
end
|
||||
num_spectra = length(msi_data.spectra_metadata)
|
||||
average_intensity = intensity_sum ./ num_spectra
|
||||
|
||||
average_intensity = intensity_sum ./ num_spectra_processed
|
||||
|
||||
return (mz_bins, average_intensity)
|
||||
end
|
||||
@@ -855,13 +906,16 @@ is significantly faster for bulk processing than reading spectra one by one.
|
||||
- `data`: The `MSIData` object.
|
||||
- `source`: The `ImzMLSource`.
|
||||
"""
|
||||
function _iterate_uncompressed_fast(f::Function, data::MSIData, source::ImzMLSource)
|
||||
function _iterate_uncompressed_fast(f::Function, data::MSIData, source::ImzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing})
|
||||
# Optimized path for uncompressed data using buffer reuse
|
||||
max_points = maximum(meta -> meta.mz_asset.encoded_length, data.spectra_metadata)
|
||||
mz_buffer = Vector{source.mz_format}(undef, max_points)
|
||||
int_buffer = Vector{source.intensity_format}(undef, max_points)
|
||||
|
||||
for i in 1:length(data.spectra_metadata)
|
||||
# Determine which indices to iterate over
|
||||
spectrum_indices = (indices_to_iterate === nothing) ? (1:length(data.spectra_metadata)) : indices_to_iterate
|
||||
|
||||
for i in spectrum_indices
|
||||
meta = data.spectra_metadata[i]
|
||||
nPoints = meta.mz_asset.encoded_length
|
||||
|
||||
@@ -904,10 +958,14 @@ and will be slower and allocate more memory than `_iterate_uncompressed_fast`.
|
||||
- `data`: The `MSIData` object.
|
||||
- `source`: The `ImzMLSource`.
|
||||
"""
|
||||
function _iterate_compressed_fast(f::Function, data::MSIData, source::ImzMLSource)
|
||||
function _iterate_compressed_fast(f::Function, data::MSIData, source::ImzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing})
|
||||
# Path for datasets containing at least one compressed spectrum.
|
||||
# This path reads and decompresses each spectrum individually.
|
||||
for i in 1:length(data.spectra_metadata)
|
||||
|
||||
# Determine which indices to iterate over
|
||||
spectrum_indices = (indices_to_iterate === nothing) ? (1:length(data.spectra_metadata)) : indices_to_iterate
|
||||
|
||||
for i in spectrum_indices
|
||||
meta = data.spectra_metadata[i]
|
||||
|
||||
if meta.mz_asset.encoded_length == 0 && meta.int_asset.encoded_length == 0
|
||||
@@ -937,7 +995,7 @@ This function acts as a dispatcher:
|
||||
- If all spectra are uncompressed, it uses a highly optimized path that reuses pre-allocated
|
||||
buffers to minimize memory allocations and overhead.
|
||||
"""
|
||||
function _iterate_spectra_fast_impl(f::Function, data::MSIData, source::ImzMLSource)
|
||||
function _iterate_spectra_fast_impl(f::Function, data::MSIData, source::ImzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing})
|
||||
if isempty(data.spectra_metadata)
|
||||
return
|
||||
end
|
||||
@@ -947,9 +1005,9 @@ function _iterate_spectra_fast_impl(f::Function, data::MSIData, source::ImzMLSou
|
||||
data.spectra_metadata)
|
||||
|
||||
if any_compressed
|
||||
_iterate_compressed_fast(f, data, source)
|
||||
_iterate_compressed_fast(f, data, source, indices_to_iterate)
|
||||
else
|
||||
_iterate_uncompressed_fast(f, data, source)
|
||||
_iterate_uncompressed_fast(f, data, source, indices_to_iterate)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -961,12 +1019,16 @@ through each spectrum, decodes the Base64 data on the fly, and calls the
|
||||
provided function. It bypasses the `GetSpectrum` cache to avoid storing
|
||||
all decoded spectra in memory.
|
||||
"""
|
||||
function _iterate_spectra_fast_impl(f::Function, data::MSIData, source::MzMLSource)
|
||||
function _iterate_spectra_fast_impl(f::Function, data::MSIData, source::MzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing})
|
||||
# This implementation is for mzML. It iterates through each spectrum,
|
||||
# decodes it, and then calls the function `f`. It's less performant than
|
||||
# the imzML version because we cannot pre-allocate buffers of a known size,
|
||||
# but it is correct and still faster than using GetSpectrum due to bypassing the cache.
|
||||
for i in 1:length(data.spectra_metadata)
|
||||
|
||||
# Determine which indices to iterate over
|
||||
spectrum_indices = (indices_to_iterate === nothing) ? (1:length(data.spectra_metadata)) : indices_to_iterate
|
||||
|
||||
for i in spectrum_indices
|
||||
meta = data.spectra_metadata[i]
|
||||
|
||||
mz = read_binary_vector(source.file_handle, meta.mz_asset)
|
||||
@@ -986,7 +1048,7 @@ It dispatches to a specialized implementation based on the data source type
|
||||
- `f`: A function to call for each spectrum, with signature `f(index, mz, intensity)`.
|
||||
- `data`: The `MSIData` object.
|
||||
"""
|
||||
function _iterate_spectra_fast(f::Function, data::MSIData)
|
||||
function _iterate_spectra_fast(f::Function, data::MSIData, indices_to_iterate::Union{AbstractVector{Int}, Nothing}=nothing)
|
||||
# Dispatch to the correct implementation based on the source type
|
||||
_iterate_spectra_fast_impl(f, data, data.source)
|
||||
_iterate_spectra_fast_impl(f, data, data.source, indices_to_iterate)
|
||||
end
|
||||
+5
-1
@@ -14,7 +14,10 @@ export OpenMSIData,
|
||||
get_average_spectrum,
|
||||
LoadMzml,
|
||||
precompute_analytics,
|
||||
process_spectrum
|
||||
process_spectrum,
|
||||
generate_colorbar_image,
|
||||
process_image_pipeline,
|
||||
load_and_prepare_mask
|
||||
|
||||
# Export the public Preprocessing API
|
||||
export FeatureMatrix,
|
||||
@@ -43,6 +46,7 @@ include("mzML.jl")
|
||||
include("imzML.jl")
|
||||
include("MzmlConverter.jl")
|
||||
include("Preprocessing.jl")
|
||||
include("ImageProcessing.jl")
|
||||
|
||||
|
||||
# --- Main Entry Point --- #
|
||||
|
||||
+161
-60
@@ -744,10 +744,17 @@ This is a performant function that iterates through spectra once.
|
||||
# Returns
|
||||
- A `Matrix{Float64}` representing the intensity slice.
|
||||
"""
|
||||
function get_mz_slice(data::MSIData, mass::Real, tolerance::Real)
|
||||
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 data.spectrum_stats_df === nothing || !hasproperty(data.spectrum_stats_df, :MinMZ)
|
||||
println("Per-spectrum metadata not found. Running one-time analytics computation...")
|
||||
@@ -761,7 +768,9 @@ function get_mz_slice(data::MSIData, mass::Real, tolerance::Real)
|
||||
|
||||
# 1. Find all candidate spectra first for efficient filtering
|
||||
candidate_indices = Set{Int}()
|
||||
for i in 1:length(data.spectra_metadata)
|
||||
indices_to_check = masked_indices === nothing ? (1:length(data.spectra_metadata)) : masked_indices
|
||||
|
||||
for i in indices_to_check
|
||||
spec_min_mz = stats_df.MinMZ[i]
|
||||
spec_max_mz = stats_df.MaxMZ[i]
|
||||
if target_max >= spec_min_mz && target_min <= spec_max_mz
|
||||
@@ -769,20 +778,17 @@ function get_mz_slice(data::MSIData, mass::Real, tolerance::Real)
|
||||
end
|
||||
end
|
||||
|
||||
println("Found $(length(candidate_indices)) candidate spectra (filtered from $(length(data.spectra_metadata)))")
|
||||
println("Found $(length(candidate_indices)) candidate spectra (filtered from $(length(indices_to_check)) initial spectra)")
|
||||
|
||||
# 2. Iterate using the optimized, low-allocation iterator
|
||||
results_count = 0
|
||||
_iterate_spectra_fast(data) do idx, mz_array, intensity_array
|
||||
# Process only the spectra that are candidates
|
||||
if idx in candidate_indices
|
||||
intensity = find_mass(mz_array, intensity_array, mass, tolerance)
|
||||
if intensity > 0.0
|
||||
meta = data.spectra_metadata[idx]
|
||||
if 1 <= meta.x <= width && 1 <= meta.y <= height
|
||||
slice_matrix[meta.y, meta.x] = intensity
|
||||
results_count += 1
|
||||
end
|
||||
_iterate_spectra_fast(data, collect(candidate_indices)) do idx, mz_array, intensity_array
|
||||
meta = data.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
|
||||
slice_matrix[meta.y, meta.x] = intensity
|
||||
results_count += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -802,7 +808,7 @@ This is a highly performant function that iterates through the full dataset only
|
||||
# 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)
|
||||
function get_multiple_mz_slices(data::MSIData, masses::AbstractVector{<:Real}, tolerance::Real; mask_path::Union{String, Nothing}=nothing)
|
||||
width, height = data.image_dims
|
||||
|
||||
# 1. Initialize a dictionary to hold the output slice matrices
|
||||
@@ -811,6 +817,13 @@ function get_multiple_mz_slices(data::MSIData, masses::AbstractVector{<:Real}, t
|
||||
slice_dict[mass] = zeros(Float64, 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 data.spectrum_stats_df === nothing || !hasproperty(data.spectrum_stats_df, :MinMZ)
|
||||
println("Per-spectrum metadata not found. Running one-time analytics computation...")
|
||||
@@ -820,12 +833,13 @@ function get_multiple_mz_slices(data::MSIData, masses::AbstractVector{<:Real}, t
|
||||
println("Filtering candidate spectra for $(length(masses)) m/z values...")
|
||||
stats_df = data.spectrum_stats_df
|
||||
candidate_indices = Set{Int}()
|
||||
indices_to_check = masked_indices === nothing ? (1:length(data.spectra_metadata)) : masked_indices
|
||||
|
||||
# 3. Find all spectra that could contain *any* of the requested masses.
|
||||
for mass in masses
|
||||
target_min = mass - tolerance
|
||||
target_max = mass + tolerance
|
||||
for i in 1:length(data.spectra_metadata)
|
||||
for i in indices_to_check
|
||||
# If already a candidate, no need to check again
|
||||
if i in candidate_indices
|
||||
continue
|
||||
@@ -841,20 +855,17 @@ function get_multiple_mz_slices(data::MSIData, masses::AbstractVector{<:Real}, t
|
||||
println("Found $(length(candidate_indices)) total candidate spectra.")
|
||||
|
||||
# 4. Iterate through the data a single time using the optimized iterator.
|
||||
_iterate_spectra_fast(data) do idx, mz_array, intensity_array
|
||||
# Process only the spectra that are candidates
|
||||
if idx in candidate_indices
|
||||
meta = data.spectra_metadata[idx]
|
||||
# For this single spectrum, check all masses of interest
|
||||
for mass in masses
|
||||
# Check if this spectrum's range actually covers the current mass
|
||||
# This is a finer-grained check than the initial filtering
|
||||
if !isempty(mz_array) && (mass + tolerance) >= first(mz_array) && (mass - tolerance) <= last(mz_array)
|
||||
intensity = find_mass(mz_array, intensity_array, mass, tolerance)
|
||||
if intensity > 0.0
|
||||
if 1 <= meta.x <= width && 1 <= meta.y <= height
|
||||
slice_dict[mass][meta.y, meta.x] = intensity
|
||||
end
|
||||
_iterate_spectra_fast(data, collect(candidate_indices)) do idx, mz_array, intensity_array
|
||||
meta = data.spectra_metadata[idx]
|
||||
# For this single spectrum, check all masses of interest
|
||||
for mass in masses
|
||||
# Check if this spectrum's range actually covers the current mass
|
||||
# This is a finer-grained check than the initial filtering
|
||||
if !isempty(mz_array) && (mass + tolerance) >= first(mz_array) && (mass - tolerance) <= last(mz_array)
|
||||
intensity = find_mass(mz_array, intensity_array, mass, tolerance)
|
||||
if intensity > 0.0
|
||||
if 1 <= meta.x <= width && 1 <= meta.y <= height
|
||||
slice_dict[mass][meta.y, meta.x] = intensity
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -878,30 +889,15 @@ Generates and saves a plot of a single image slice for a given m/z value.
|
||||
This function closely imitates the logic of the original `GetSlice` but uses
|
||||
the modern `MSIData` access patterns and robust peak finding.
|
||||
"""
|
||||
function plot_slice(msi_data::MSIData, mass::Real, tolerance::Real, output_dir::String; stage_name="slice_mz_$(mass)", bins=256)
|
||||
function plot_slice(msi_data::MSIData, mass::Real, tolerance::Real, output_dir::String;
|
||||
stage_name="slice_mz_$(mass)", bins=256, mask_path::Union{String, Nothing}=nothing)
|
||||
|
||||
# 1. Create an empty image for the slice, with dimensions matching plotting expectations
|
||||
width, height = msi_data.image_dims
|
||||
slice_matrix = zeros(Float64, height, width)
|
||||
|
||||
# 2. Iterate through each spectrum to build the slice
|
||||
# 1. Generate the slice, applying the mask if provided.
|
||||
println("Generating slice for m/z $mass...")
|
||||
_iterate_spectra_fast(msi_data) do spec_idx, mz_array, intensity_array
|
||||
meta = msi_data.spectra_metadata[spec_idx]
|
||||
|
||||
# Find the peak intensity using the modern, robust find_mass
|
||||
intensity = find_mass(mz_array, intensity_array, mass, tolerance)
|
||||
|
||||
if intensity > 0.0
|
||||
# Populate the matrix using (y, x) indexing
|
||||
if 1 <= meta.x <= width && 1 <= meta.y <= height
|
||||
slice_matrix[meta.y, meta.x] = intensity
|
||||
end
|
||||
end
|
||||
end
|
||||
slice_matrix = get_mz_slice(msi_data, mass, tolerance, mask_path=mask_path)
|
||||
println("Slice generation complete.")
|
||||
|
||||
# 3. Plot the resulting slice matrix using CairoMakie
|
||||
# 2. Plot the resulting slice matrix using CairoMakie
|
||||
println("Plotting slice...")
|
||||
|
||||
fig = Figure(size = (600, 500))
|
||||
@@ -925,7 +921,7 @@ function plot_slice(msi_data::MSIData, mass::Real, tolerance::Real, output_dir::
|
||||
Colorbar(fig[1, 2], hm, label="Intensity")
|
||||
colgap!(fig.layout, 5)
|
||||
|
||||
# 4. Save the plot
|
||||
# 3. Save the plot
|
||||
mkpath(output_dir)
|
||||
filename = "$(stage_name).png"
|
||||
save_path = joinpath(output_dir, filename)
|
||||
@@ -957,9 +953,9 @@ is used to exclude outliers before normalization.
|
||||
# Returns
|
||||
- A tuple `(low, high)` representing the calculated lower and upper intensity bounds.
|
||||
"""
|
||||
function get_outlier_thres(img::AbstractMatrix{<:Real}, prob::Real=0.98)
|
||||
function get_outlier_thres(img::AbstractVector{<:Real}, prob::Real=0.98)
|
||||
# DO NOT filter zeros. Use all pixel values like R does.
|
||||
int_values = vec(img)
|
||||
int_values = img
|
||||
low = minimum(int_values)
|
||||
upp = maximum(int_values)
|
||||
|
||||
@@ -1001,6 +997,10 @@ function get_outlier_thres(img::AbstractMatrix{<:Real}, prob::Real=0.98)
|
||||
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)
|
||||
|
||||
@@ -1063,11 +1063,26 @@ within these bounds.
|
||||
# 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)
|
||||
# Compute new dynamic range
|
||||
bounds = get_outlier_thres(pixMap, prob)
|
||||
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
|
||||
# Extract values only from the masked region for threshold calculation
|
||||
values_for_thres = pixMap[mask_matrix]
|
||||
# Filter out only zeros created by the mask.
|
||||
filter!(x -> x != 0, values_for_thres)
|
||||
else
|
||||
values_for_thres = pixMap
|
||||
end
|
||||
|
||||
# If the relevant values are empty or all zero, return a zero matrix
|
||||
if isempty(values_for_thres) || all(iszero, values_for_thres)
|
||||
bounds = (0.0, 0.0)
|
||||
else
|
||||
# Compute new dynamic range from the (potentially filtered) values
|
||||
bounds = get_outlier_thres(values_for_thres, prob)
|
||||
end
|
||||
|
||||
# Set intensity dynamic range
|
||||
# Set intensity dynamic range for the *entire* pixMap, using bounds derived from masked data
|
||||
return set_pixel_depth(pixMap, bounds, depth)
|
||||
end
|
||||
|
||||
@@ -1107,8 +1122,17 @@ 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 `IntQuantCl`.
|
||||
"""
|
||||
function quantize_intensity(slice::AbstractMatrix{<:Real}, levels::Integer=256)
|
||||
max_val = maximum(slice)
|
||||
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
|
||||
return zeros(UInt8, size(slice))
|
||||
end
|
||||
@@ -1208,7 +1232,7 @@ function display_statistics(slices::AbstractArray{<:AbstractMatrix{<:Real}, 2},
|
||||
stats_to_calc = Dict{String, Function}("Mean" => mean)
|
||||
all_dfs = Dict{String, DataFrame}()
|
||||
|
||||
for (stat_name, stat_func) in stats_to_to_calc
|
||||
for (stat_name, stat_func) in stats_to_calc
|
||||
# Pre-allocate matrix for better performance
|
||||
stat_matrix = zeros(Float64, n_files, n_masses)
|
||||
|
||||
@@ -1497,4 +1521,81 @@ function process_columns_first!(A::AbstractMatrix)
|
||||
end
|
||||
|
||||
# Viridis color palette (256 colors) - defined as constant
|
||||
const ViridisPalette = generate_palette(ColorSchemes.viridis)
|
||||
const ViridisPalette = generate_palette(ColorSchemes.viridis)
|
||||
|
||||
function generate_colorbar_image(slice_data::AbstractMatrix, color_levels::Int, output_path::String; use_triq::Bool=false, triq_prob::Float64=0.98, mask_path::Union{String, Nothing}=nothing)
|
||||
# 1. Determine bounds based on whether TrIQ is used and if a mask is applied
|
||||
local data_for_bounds
|
||||
if mask_path !== nothing
|
||||
height, width = size(slice_data)
|
||||
mask_matrix = load_and_prepare_mask(mask_path, (width, height))
|
||||
# Extract only the non-zero values within the mask to accurately calculate the range
|
||||
data_for_bounds = slice_data[mask_matrix]
|
||||
filter!(x -> x > 0, data_for_bounds)
|
||||
else
|
||||
data_for_bounds = vec(slice_data)
|
||||
end
|
||||
|
||||
# Handle cases where data_for_bounds might be empty after filtering
|
||||
if isempty(data_for_bounds)
|
||||
min_val, max_val = 0.0, 1.0 # Default range if no data in ROI
|
||||
else
|
||||
min_val, max_val = if use_triq
|
||||
get_outlier_thres(data_for_bounds, triq_prob)
|
||||
else
|
||||
extrema(data_for_bounds)
|
||||
end
|
||||
end
|
||||
|
||||
# 2. Replicate the tick calculation logic from plot_slices
|
||||
bins = color_levels
|
||||
levels = range(min_val, stop=max_val, length=bins + 1)
|
||||
level_range = levels[end] - levels[1]
|
||||
|
||||
if level_range == 0
|
||||
levels = range(min_val - 0.1, stop=max_val + 0.1, length=bins + 1)
|
||||
level_range = 0.2
|
||||
end
|
||||
|
||||
exponent = level_range > 0 ? floor(log10(level_range)) / 3 : 0
|
||||
scale = 10^(3 * exponent)
|
||||
scaled_levels = levels ./ scale
|
||||
|
||||
format_num = level_range > 0 ? floor(log10(level_range)) % 3 : 0
|
||||
labels = if format_num == 0
|
||||
[ @sprintf("%3.2f", lvl) for lvl in scaled_levels]
|
||||
elseif format_num == 1
|
||||
[ @sprintf("%3.2f", lvl) for lvl in scaled_levels]
|
||||
else
|
||||
[ @sprintf("%3.2f", lvl) for lvl in scaled_levels]
|
||||
end
|
||||
|
||||
divisors = 2:7
|
||||
remainders = (bins - 1) .% divisors
|
||||
best_divisor = divisors[findlast(x -> x == minimum(remainders), remainders)]
|
||||
tick_indices = round.(Int, range(1, stop=bins + 1, length=best_divisor + 1))
|
||||
|
||||
if !(1 in tick_indices)
|
||||
pushfirst!(tick_indices, 1)
|
||||
end
|
||||
if !((bins + 1) in tick_indices)
|
||||
push!(tick_indices, bins + 1)
|
||||
end
|
||||
unique!(sort!(tick_indices))
|
||||
|
||||
tick_positions = levels[tick_indices]
|
||||
tick_labels = labels[tick_indices]
|
||||
|
||||
# 3. Create and save the colorbar image
|
||||
fig = Figure(size=(150, 250))
|
||||
Colorbar(fig[1, 1],
|
||||
colormap=cgrad(:viridis, bins, categorical=true),
|
||||
# limits=(min_val, max_val),
|
||||
limits=(levels[1], levels[end]),
|
||||
label=(scale == 1 ? "Intensity" : "Intensity ×10^$(round(Int, 3 * exponent))"),
|
||||
ticks=(tick_positions, tick_labels),
|
||||
labelsize=20,
|
||||
ticklabelsize=16
|
||||
)
|
||||
save(output_path, fig)
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user