From ba4a252a0a61c67220a24a9c97241f980fcda125 Mon Sep 17 00:00:00 2001 From: Pixelguy14 Date: Tue, 17 Nov 2026 20:56:57 -0600 Subject: [PATCH] Added pairity with latest JuliaMSI changes --- src/BloomFilters.jl | 7 +- src/Common.jl | 4 +- src/ImageProcessing.jl | 17 +- src/MSIData.jl | 148 +++++++++++----- src/MSI_src.jl | 10 +- src/Paths.jl | 49 ++++++ src/PlottingStubs.jl | 30 ++++ src/StreamingPipeline.jl | 3 +- src/imzML.jl | 356 ++++++--------------------------------- src/mzML.jl | 2 +- 10 files changed, 266 insertions(+), 360 deletions(-) create mode 100644 src/Paths.jl create mode 100644 src/PlottingStubs.jl diff --git a/src/BloomFilters.jl b/src/BloomFilters.jl index 3570da7..96c5acf 100644 --- a/src/BloomFilters.jl +++ b/src/BloomFilters.jl @@ -116,9 +116,10 @@ function hash_functions(item::T, count::Int, size::Int, seed::UInt64) where T # Use Julia's built-in hash with different seeds hashes = Vector{Int}(undef, count) - # First hash with the main seed - h1 = hash(item, seed) - h2 = hash(item, seed + 1) + # First hash with the main seed. Convert to `UInt` so the same code works + # on 32-bit Julia, where `hash(x, h::UInt)` does not accept a UInt64. + h1 = hash(item, UInt(seed)) + h2 = hash(item, UInt(seed + 1)) for i in 1:count # Double hashing: h_i = h1 + i * h2 diff --git a/src/Common.jl b/src/Common.jl index 629aed2..9196d8e 100644 --- a/src/Common.jl +++ b/src/Common.jl @@ -204,12 +204,12 @@ function create_bloom_filter_for_spectrum(mz::AbstractVector{<:Real})::BloomFilt end """ - empty_bloom_filter() -> BloomFilter{Float64} + empty_bloom_filter() -> BloomFilter{Int} Creates an empty Bloom filter for spectra with no data. # Returns: -- An empty `BloomFilter{Float64}`. +- An empty `BloomFilter{Int}`. """ function empty_bloom_filter()::BloomFilter{Int} return BloomFilter{Int}(size=DEFAULT_BLOOM_FILTER_SIZE, hash_count=3) diff --git a/src/ImageProcessing.jl b/src/ImageProcessing.jl index d47ea6a..2518406 100644 --- a/src/ImageProcessing.jl +++ b/src/ImageProcessing.jl @@ -31,8 +31,15 @@ function load_and_prepare_mask(mask_path::String, target_dims::Tuple{Int, Int}) # Load the image img = Images.load(mask_path) - # Convert to grayscale if it's a color image - gray_img = Gray.(img) + # Convert to grayscale. Most images are already Colorant arrays, but TIFFs + # with extra samples (e.g. the optical reference images shipped with MSI + # datasets) load as TiffImages.WidePixel, for which Gray.(img) has no method. + # Fall back to the embedded color channel in that case. + gray_img = if eltype(img) <: Colorant + Gray.(img) + else + Gray.([getproperty(p, :color) for p in img]) + end # Binarize using Otsu's method - white regions become 'true' binary_img = binarize(gray_img, Otsu()) @@ -101,7 +108,11 @@ function process_image_pipeline(gray_img; # --- Step 4: Smooth Edges --- # A morphological closing with a small disk smooths outlines. - smoothing_kernel = ones(Bool, (smoothing, smoothing)) + # ImageMorphology requires odd-sized structuring elements; the historical + # default smoothing=2 produced a 2×2 matrix and threw "connectivity must be + # odd-sized". Normalize to the next odd size (minimum 3). + smooth_size = max(3, isodd(smoothing) ? smoothing : smoothing + 1) + smoothing_kernel = ones(Bool, (smooth_size, smooth_size)) smoothed_img = closing(holes_filled_img, smoothing_kernel) # --- Return all intermediate steps for visualization --- diff --git a/src/MSIData.jl b/src/MSIData.jl index 1e88fa3..b67d07c 100644 --- a/src/MSIData.jl +++ b/src/MSIData.jl @@ -243,14 +243,16 @@ mutable struct MSIData function MSIData(source, metadata, instrument_meta, dims, coordinate_map, cache_size) obj = new(source, metadata, instrument_meta, dims, coordinate_map, - Dict(), [], min(10, cache_size), ReentrantLock(), + Dict(), [], max(0, cache_size), ReentrantLock(), SimpleBufferPool(), Base.Threads.Atomic{Float64}(0.0), Base.Threads.Atomic{Float64}(0.0), nothing, nothing, AtomicFlag(), nothing) - # Initialize mz bounds cleanly instead of Inf - Base.Threads.atomic_xchg!(obj.global_min_mz, 1e9) - Base.Threads.atomic_xchg!(obj.global_max_mz, -1e9) + # Use the conventional invalid sentinel so callers can detect an + # uncomputed range. (The previous 1e9/-1e9 pair was finite, which made + # `!== Inf` checks always true and produced bogus bin ranges.) + Base.Threads.atomic_xchg!(obj.global_min_mz, Inf) + Base.Threads.atomic_xchg!(obj.global_max_mz, -Inf) # Ensure all file handles in the pool are closed when the object is garbage collected @@ -380,10 +382,17 @@ function Base.close(data::MSIData) for handle in data.source.ibd_handles isopen(handle) && close(handle) end + # Drop the mmap reference so Windows can release the file mapping + # (otherwise the source file cannot be moved/deleted until GC). + data.source = ImzMLSource(IO[], data.source.mz_format, + data.source.intensity_format, nothing, + data.source.is_any_compressed) elseif data.source isa MzMLSource for handle in data.source.file_handles isopen(handle) && close(handle) end + data.source = MzMLSource(IO[], data.source.mz_format, + data.source.intensity_format, nothing) end # Clear cache @@ -880,10 +889,23 @@ function precompute_analytics(msi_data::MSIData) start_time = time_ns() num_spectra = length(msi_data.spectra_metadata) - + + if num_spectra == 0 + msi_data.spectrum_stats_df = DataFrame( + SpectrumID = Int[], TIC = Float64[], BPI = Float64[], + BasePeakMZ = Float64[], NumPoints = Int[], + MinMZ = Float64[], MaxMZ = Float64[], Mode = SpectrumMode[] + ) + set!(msi_data.analytics_ready) + return + end + + # `maxthreadid()` also covers threads from the interactive pool. + n_slots = max(1, Base.Threads.maxthreadid()) + # Initialize thread-local variables for global stats - thread_local_min_mz = [Inf for _ in 1:Base.Threads.nthreads()] - thread_local_max_mz = [-Inf for _ in 1:Base.Threads.nthreads()] + thread_local_min_mz = [Inf for _ in 1:n_slots] + thread_local_max_mz = [-Inf for _ in 1:n_slots] # Initialize vectors for per-spectrum stats tics = Vector{Float64}(undef, num_spectra) @@ -996,6 +1018,40 @@ end +""" + compute_global_mz_range!(msi_data::MSIData; indices=nothing) + +Computes and caches the global m/z range using per-thread accumulators. + +This is the thread-safe equivalent of an OpenMP `reduction(min:...)` / +`reduction(max:...)`: every thread owns one slot, and the slots are combined +after the parallel iterator returns. It also works with the interactive thread +pool, unlike arrays sized with `Threads.nthreads()`. +""" +function compute_global_mz_range!(msi_data::MSIData; indices=nothing, cache::Bool=true) + n_slots = max(1, Base.Threads.maxthreadid()) + thread_local_min = fill(Inf, n_slots) + thread_local_max = fill(-Inf, n_slots) + + _iterate_spectra_fast(msi_data, indices) do idx, mz, _ + isempty(mz) && return + lo, hi = extrema(mz) + tid = Base.Threads.threadid() + thread_local_min[tid] = min(thread_local_min[tid], lo) + thread_local_max[tid] = max(thread_local_max[tid], hi) + end + + g_min = minimum(thread_local_min) + g_max = maximum(thread_local_max) + + if isfinite(g_min) && isfinite(g_max) && g_min < g_max + cache && set_global_mz_range!(msi_data, g_min, g_max) + return (g_min, g_max) + end + + return nothing +end + """ get_total_spectrum_core(msi_data::MSIData; num_bins::Int=2000, masked_indices::Union{Set{Int}, Nothing}=nothing) @@ -1022,51 +1078,60 @@ function get_total_spectrum_core(msi_data::MSIData; num_bins::Int=2000, masked_i local global_min_mz, global_max_mz - if Base.Threads.atomic_add!(msi_data.global_min_mz, 0.0) !== Inf - println(" Using pre-computed m/z range.") - global_min_mz = Base.Threads.atomic_add!(msi_data.global_min_mz, 0.0) - global_max_mz = Base.Threads.atomic_add!(msi_data.global_max_mz, 0.0) + # Use a cached range only when it is valid. The old sentinel check + # (`!== Inf`) was always true because the fields are initialized to 1e9. + if masked_indices === nothing + cached_min, cached_max = get_global_mz_range(msi_data) + if isfinite(cached_min) && isfinite(cached_max) && cached_min < cached_max + println(" Using pre-computed m/z range.") + global_min_mz = cached_min + global_max_mz = cached_max + else + range_result = compute_global_mz_range!(msi_data) + range_result === nothing && return (Float64[], Float64[], 0) + global_min_mz, global_max_mz = range_result + end else - # 1. First Pass: Find the global m/z range + # Compute the range over the requested subset. This path is also used + # for masked spectra, where using the full-dataset range would be wrong. pass1_start_time = time_ns() println(" Pass 1: Finding global m/z range...") - g_min_mz = Inf - g_max_mz = -Inf - _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) - g_max_mz = max(g_max_mz, local_max) - end - end + indices = masked_indices === nothing ? nothing : collect(masked_indices) + range_result = compute_global_mz_range!(msi_data; indices=indices, cache=(masked_indices === nothing)) pass1_duration = (time_ns() - pass1_start_time) / 1e9 - - if !isfinite(g_min_mz) + + if range_result === nothing @warn "Could not determine a valid m/z range. All spectra might be empty." return (Float64[], Float64[], 0) end - - # Use and cache the result - global_min_mz = g_min_mz - global_max_mz = g_max_mz - set_global_mz_range!(msi_data, global_min_mz, global_max_mz) + + global_min_mz, global_max_mz = range_result println(" Global m/z range found and cached: [$(global_min_mz), $(global_max_mz)]") @printf " (Pass 1 took %.2f seconds)\n" pass1_duration end - + + # A single-point (or degenerate) range would give a zero bin width. + if !(isfinite(global_min_mz) && isfinite(global_max_mz)) || global_min_mz >= global_max_mz + @warn "Invalid global m/z range [$global_min_mz, $global_max_mz]." + return (Float64[], Float64[], 0) + end + # 2. Define Bins and precompute constants - mz_bins = range(global_min_mz, stop=global_max_mz, length=num_bins) + bins = max(2, Int(num_bins)) + mz_bins = range(global_min_mz, stop=global_max_mz, length=bins) bin_step = step(mz_bins) inv_bin_step = 1.0 / bin_step # Precompute reciprocal to avoid division min_mz = global_min_mz - # Initialize thread-local intensity sums - thread_local_intensity_sums = [zeros(Float64, num_bins) for _ in 1:Base.Threads.nthreads()] - thread_local_spectra_processed = [0 for _ in 1:Base.Threads.nthreads()] + # Initialize thread-local intensity sums. `maxthreadid()` keeps this safe + # for tasks scheduled on the interactive thread pool. + n_slots = max(1, Base.Threads.maxthreadid()) + thread_local_intensity_sums = [zeros(Float64, bins) for _ in 1:n_slots] + thread_local_spectra_processed = [0 for _ in 1:n_slots] # 3. Second Pass: Optimized binning pass2_start_time = time_ns() - println(" Pass 2: Summing intensities into $num_bins bins...") + println(" Pass 2: Summing intensities into $bins bins...") _iterate_spectra_fast(msi_data, masked_indices === nothing ? nothing : collect(masked_indices)) do idx, mz, intensity thread_id = Base.Threads.threadid() thread_local_spectra_processed[thread_id] += 1 @@ -1085,15 +1150,15 @@ function get_total_spectrum_core(msi_data::MSIData; num_bins::Int=2000, masked_i bin_index = trunc(Int, raw_index) # Branchless version using clamp - final_index = clamp(bin_index, 1, num_bins) + final_index = clamp(bin_index, 1, bins) thread_local_intensity_sums[thread_id][final_index] += intensity_view[i] end end # Combine thread-local results - intensity_sum = zeros(Float64, num_bins) + intensity_sum = zeros(Float64, bins) num_spectra_processed = 0 - for i in 1:Base.Threads.nthreads() + for i in 1:n_slots intensity_sum .+= thread_local_intensity_sums[i] num_spectra_processed += thread_local_spectra_processed[i] end @@ -1532,9 +1597,12 @@ end function _iterate_uncompressed_fast(f::Function, data::MSIData, source::ImzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing}) spectrum_indices = (indices_to_iterate === nothing) ? (1:length(data.spectra_metadata)) : indices_to_iterate - # Intialize local buffers for this thread's sequential iteration - mz_buf = Vector{Float64}() - int_buf = Vector{Float64}() + # Initialize local buffers for this thread's sequential iteration. + # IMPORTANT: the element type must match the on-disk format. Using Float64 + # buffers here made `read!` consume twice as many bytes for Float32 datasets + # and misinterpret them as Float64 garbage (breaking use_mmap=false). + mz_buf = Vector{source.mz_format}() + int_buf = Vector{source.intensity_format}() for i in spectrum_indices meta = data.spectra_metadata[i] diff --git a/src/MSI_src.jl b/src/MSI_src.jl index 95d1206..886c987 100644 --- a/src/MSI_src.jl +++ b/src/MSI_src.jl @@ -7,12 +7,10 @@ export OpenMSIData, GetSpectrum, IterateSpectra, ImportMzmlFile, - plot_slice, get_total_spectrum, get_average_spectrum, precompute_analytics, process_spectrum, - generate_colorbar_image, process_image_pipeline, load_and_prepare_mask, set_global_mz_range!, @@ -31,7 +29,11 @@ export OpenMSIData, ImzMLSource, SimpleBufferPool, get_buffer!, - release_buffer! + release_buffer!, + PROJECT_ROOT, + PUBLIC_DIR, + DEFAULT_REGISTRY_PATH, + ensure_public_dir # Define shared registry lock const REGISTRY_LOCK = ReentrantLock() @@ -83,6 +85,7 @@ export process_dataset!, calibrate_inplace! # Include all source files directly into the main module +include("Paths.jl") include("BloomFilters.jl") include("Common.jl") include("ResourcePool.jl") @@ -90,6 +93,7 @@ include("MSIData.jl") include("ParserHelpers.jl") include("mzML.jl") include("imzML.jl") +include("PlottingStubs.jl") include("MzmlConverter.jl") include("Preprocessing.jl") include("ImageProcessing.jl") diff --git a/src/Paths.jl b/src/Paths.jl new file mode 100644 index 0000000..e874495 --- /dev/null +++ b/src/Paths.jl @@ -0,0 +1,49 @@ +# src/Paths.jl +# Shared filesystem locations for JuliaMSI. +# +# All application-owned files live under the project's `public/` directory. +# Keeping those paths in one place avoids mixing `pwd()`-relative and +# `@__DIR__`-relative paths (which is especially fragile on Windows). + +const PROJECT_ROOT = normpath(joinpath(@__DIR__, "..")) +const PUBLIC_DIR = joinpath(PROJECT_ROOT, "public") +const DEFAULT_REGISTRY_PATH = joinpath(PUBLIC_DIR, "registry.json") + +""" + ensure_public_dir(; path::AbstractString = PUBLIC_DIR) -> String + +Ensures that the application's `public/` directory exists and is writable. + +JuliaMSI writes generated bitmaps, masks, and `registry.json` into this +directory, so a read-only or missing directory is a fatal configuration error. +A short write probe is used instead of relying only on permission bits, because +Windows ACLs and read-only attributes are not reliably reflected by `iswritable`. +""" +function ensure_public_dir(; path::AbstractString = PUBLIC_DIR) + try + mkpath(path) + catch e + error("JuliaMSI cannot create the public directory at \"$path\". " * + "Move the project to a writable location or fix the directory permissions. " * + "Original error: $(sprint(showerror, e))") + end + + isdir(path) || + error("JuliaMSI expected a directory at \"$path\", but it is not a directory.") + + probe = joinpath(path, ".juliamsi_write_probe_$(getpid())") + try + open(probe, "w") do io + write(io, "ok") + end + catch e + error("JuliaMSI cannot write to \"$path\". The application requires write " * + "access to its public directory for generated images, masks, and " * + "registry.json. Move the project to a writable location or fix the " * + "directory permissions. Original error: $(sprint(showerror, e))") + finally + isfile(probe) && rm(probe; force=true) + end + + return String(path) +end diff --git a/src/PlottingStubs.jl b/src/PlottingStubs.jl new file mode 100644 index 0000000..a094563 --- /dev/null +++ b/src/PlottingStubs.jl @@ -0,0 +1,30 @@ +# src/PlottingStubs.jl +# +# These names used to live in MSI_src and were exported from the core module. +# They are GUI/plotting helpers that require CairoMakie, so their +# implementations now live in julia_imzML_visual.jl. Keeping explicit stubs +# here gives downstream code an actionable error instead of an UndefVarError, +# while keeping `using MSI_src` lightweight for headless use. +# +# The stubs are intentionally NOT exported. + +const _PLOTTING_MOVED_MESSAGE = """ +This function is a GUI/plotting helper and is no longer implemented in the +MSI_src core. It moved to the GUI layer (julia_imzML_visual.jl) so that +`using MSI_src` does not load CairoMakie. + +Load the GUI module that defines it, or call the corresponding helper from your +application/plotting layer. See the JuliaMSI README for the migration note. +""" + +function plot_slice(args...; kwargs...) + error(_PLOTTING_MOVED_MESSAGE) +end + +function plot_slices(args...; kwargs...) + error(_PLOTTING_MOVED_MESSAGE) +end + +function generate_colorbar_image(args...; kwargs...) + error(_PLOTTING_MOVED_MESSAGE) +end diff --git a/src/StreamingPipeline.jl b/src/StreamingPipeline.jl index ee97ac4..de17830 100644 --- a/src/StreamingPipeline.jl +++ b/src/StreamingPipeline.jl @@ -178,7 +178,8 @@ function process_dataset!(data::MSIData, config::PipelineConfig; indices_to_process = masked_indices === nothing ? nothing : masked_indices # --- Step 2: Create thread-local accumulators --- - n_threads = Base.Threads.nthreads() + # `maxthreadid()` also covers the interactive thread pool. + n_threads = max(1, Base.Threads.maxthreadid()) accumulators = [SparseAccumulator(num_spectra * 10) for _ in 1:n_threads] spectra_processed = Base.Threads.Atomic{Int}(0) diff --git a/src/imzML.jl b/src/imzML.jl index a144893..8d12fab 100644 --- a/src/imzML.jl +++ b/src/imzML.jl @@ -1,4 +1,4 @@ -using Images, Statistics, CairoMakie, DataFrames, Printf, ColorSchemes, StatsBase, Mmap +using Statistics, DataFrames, ColorSchemes, StatsBase, Mmap """ This file provides a library for parsing `.imzML` and `.ibd` files in pure Julia. @@ -314,7 +314,8 @@ Helper function to parse binary data arrays from a spectrum block. """ 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) + 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[] @@ -322,14 +323,28 @@ function parse_binary_data_arrays(spectrum_block::String, spectrum_start_line::S for bda_match in eachmatch(r"(.*?)"sm, spectrum_block) bda_content = bda_match.match # This will be the full block - is_mz = occursin("MS:1000514", bda_content) || occursin("mzArray", bda_content) + # Many imzML writers put the m/z and intensity cvParams in a + # and only reference it from the spectrum. + # Resolve the reference first so those files are classified correctly. + ref_match = match(r" 0 && offset > 0 + + 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 @@ -423,7 +444,8 @@ function parse_imzml_spectrum_block(stream::IO, hIbd::IO, param_groups::Dict{Str 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) + 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) @@ -491,7 +513,7 @@ function load_imzml_lazy(file_path::String; cache_size::Int=100, use_mmap::Bool= # --- Handle Pool Optimization --- # We open multiple handles to the same .ibd file to avoid lock contention in parallel code. - num_handles = Threads.nthreads() + num_handles = max(1, Threads.maxthreadid()) ibd_handles = [open(ibd_path, "r") for _ in 1:num_handles] # --- Mmap Optimization with RAM Safety --- @@ -559,10 +581,21 @@ function load_imzml_lazy(file_path::String; cache_size::Int=100, use_mmap::Bool= 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 - tmp_source = ImzMLSource(ibd_handles, default_mz_format, default_intensity_format, mmap_data, any_comp) + # 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) - save_metadata_cache(tmp_msi, cache_path) + 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 ... @@ -726,7 +759,7 @@ function get_mz_slice(data::MSIData, mass::Real, tolerance::Real; mask_path::Uni # Bloom filter rejection (very fast) if bloom_filters !== nothing bf = bloom_filters[i] - if !is_empty(bf) + if bf !== nothing && !is_empty(bf) min_mass_int = round(Int, (mass - tolerance) * discretization_factor) max_mass_int = round(Int, (mass + tolerance) * discretization_factor) @@ -841,7 +874,7 @@ function get_multiple_mz_slices(data::MSIData, masses::AbstractVector{<:Real}, t if m_start_idx <= m_end_idx # Range overlap found, now check Bloom filter if available - if bloom_filters !== nothing && !is_empty(bloom_filters[i]) + 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] @@ -906,68 +939,6 @@ function get_multiple_mz_slices(data::MSIData, masses::AbstractVector{<:Real}, t end -""" - plot_slice(msi_data::MSIData, mass::Float64, tolerance::Float64, output_dir::String; stage_name="slice", bins=256) - -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. - -# Arguments - -- `msi_data::MSIData`: The MSIData object. -- `mass::Real`: The target mass. -- `tolerance::Real`: The tolerance. -- `output_dir::String`: The output directory. -- `stage_name::String`: The name of the stage. -- `bins::Int`: The number of bins. -- `mask_path::Union{String, Nothing}`: The path to the mask. - -# Returns -- `fig::Figure`: A figure with the data plotted with colors applied. -""" -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. Generate the slice, applying the mask if provided. - println("Generating slice for m/z $mass...") - slice_matrix = get_mz_slice(msi_data, mass, tolerance, mask_path=mask_path) - println("Slice generation complete.") - - # 2. Plot the resulting slice matrix using CairoMakie - println("Plotting slice...") - - fig = Figure(size = (600, 500)) - ax = CairoMakie.Axis(fig[1, 1], - aspect=DataAspect(), - title=@sprintf("Slice for m/z: %.2f", mass), - yreversed=true - ) - hidedecorations!(ax) - - # Use mass-specific bounds for colorrange, ensuring a valid range - min_val, max_val = extrema(slice_matrix) - if min_val == max_val - max_val = min_val + 1.0 # Ensure the color range has a non-zero width - end - hm = heatmap!(ax, slice_matrix, - colormap=cgrad(ColorSchemes.viridis, bins), - colorrange=(min_val, max_val) - ) - - Colorbar(fig[1, 2], hm, label="Intensity") - colgap!(fig.layout, 5) - - # 3. Save the plot - mkpath(output_dir) - filename = "$(stage_name).png" - save_path = joinpath(output_dir, filename) - save(save_path, fig) - @info "Saved slice plot to $save_path" - - return fig -end - # ============================================================================ # # @@ -1275,140 +1246,6 @@ end # # ============================================================================ -""" - plot_slices(slices, names, masses, output_dir; stage_name, bins=256, dpi=150, global_bounds=nothing) - -Generates and saves a grid of image slice plots. Each row corresponds to a -file and each column to a mass, creating a comprehensive overview. - -# Arguments -- `slices`: A 2D array of image slice matrices (`n_files` x `n_masses`). -- `names`: A vector of file names, used for titling rows. -- `masses`: A vector of m/z values, used for titling columns. -- `output_dir`: The directory where the output plots will be saved. - -# Keyword Arguments -- `stage_name`: A string used to name the output files (e.g., "raw", "normalized"). -- `bins`: The number of color levels in the heatmap palette. -- `dpi`: The resolution for the saved image files. -- `global_bounds`: A vector of `(min, max)` tuples, one for each mass, to ensure a consistent - color scale across all files for a given mass. If `nothing`, bounds are calculated automatically. - -# Returns -- The generated `Figure` object from Makie. -""" -function plot_slices(slices, names, masses, output_dir; stage_name, bins=256, dpi=150, global_bounds=nothing) - n_files, n_masses = size(slices) - - mkpath(output_dir) - - # If global_bounds is provided, it should now be a VECTOR of bounds (one per mass) - # If not provided, calculate per-mass bounds - if global_bounds === nothing - global_bounds = [] - for mass_idx in 1:n_masses - mass_slices = [slices[i, mass_idx] for i in 1:n_files] - all_vals = reduce(vcat, [vec(s) for s in mass_slices]) - filter!(isfinite, all_vals) - mass_bounds = isempty(all_vals) ? (0.0, 1.0) : extrema(all_vals) - push!(global_bounds, mass_bounds) - end - end - - # With Makie, we define a Figure and a layout. - fig = Figure(size = (400 * n_masses, 330 * n_files)) # Adjusted size calculation - - # Add a title for the entire figure. - Label(fig[0, 1:(2*n_masses)], "Image Slices - $(stage_name)", fontsize=24, font=:bold, tellwidth=false, padding=(0,0,10,0)) - - for file_idx in 1:n_files - for mass_idx in 1:n_masses - img = slices[file_idx, mass_idx] - mass = masses[mass_idx] - name = names[file_idx] - mass_global_bounds = global_bounds[mass_idx] # Get bounds for THIS specific mass - - # --- Calculate tick properties for THIS mass --- - min_val, max_val = mass_global_bounds - 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] - # --- End of mass-specific tick calculation --- - - # Create an Axis for the heatmap - ax = CairoMakie.Axis(fig[file_idx, 2*mass_idx-1], - aspect=DataAspect(), - title=@sprintf("%s\nm/z: %.2f", basename(name), mass), - titlesize=14 - ) - hidedecorations!(ax) - - # Use mass-specific bounds for colorrange - hm = heatmap!(ax, transpose(img), - colormap=cgrad(ColorSchemes.viridis, bins), - colorrange=mass_global_bounds # ← This is mass-specific - ) - - # Add a colorbar with mass-specific scale - cb = Colorbar(fig[file_idx, 2*mass_idx], hm, - label=(scale == 1 ? "" : "×10^$(round(Int, 3 * exponent))"), - labelpadding=2, - labelsize=12, - ticks=(tick_positions, tick_labels), - ticklabelsize=10 - ) - colsize!(fig.layout, 2*mass_idx, 30) - end - end - - colgap!(fig.layout, 5) - rowgap!(fig.layout, 10) - - # Save in multiple formats. - formats = ["png", "pdf"] - - for fmt in formats - filename = "$(stage_name)_overview.$(fmt)" - save_path = joinpath(output_dir, filename) - save(save_path, fig, px_per_unit = dpi / 96.0) - @info "Saved $(fmt) overview plot to $save_path" - end - return fig -end - """ save_bitmap(name::String, pixMap::Matrix{UInt8}, colorTable::Vector{UInt32}) @@ -1516,98 +1353,3 @@ end # Viridis color palette (256 colors) - defined as constant const ViridisPalette = generate_palette(ColorSchemes.viridis) - -""" - generate_colorbar_image(slice_data::AbstractMatrix, color_levels::Int, output_path::String, - bounds::Tuple{Float64, Float64}; - use_triq::Bool=false, triq_prob::Float64=0.98, - mask_path::Union{String, Nothing}=nothing) - -Generates a colorbar image for a given slice of data. - -# Arguments - -- `slice_data`: The slice data. -- `color_levels`: The number of color levels. -- `output_path`: The output path. -- `bounds`: The bounds for the colorbar. -- `use_triq`: Whether to use triq. -- `triq_prob`: The probability of using triq. -- `mask_path`: The path to the mask. - -# Returns -- `fig::Figure`: A figure with the colorbar. -""" -function generate_colorbar_image(slice_data::AbstractMatrix, color_levels::Int, output_path::String, - bounds::Tuple{Real, Real}; - use_triq::Bool=false, triq_prob::Float64=0.98, - mask_path::Union{String, Nothing}=nothing) - # Use the provided bounds instead of recalculating - min_val, max_val = bounds - - # If bounds are invalid, calculate fallback - if min_val == max_val == 0.0 - local data_for_bounds - if mask_path !== nothing - height, width = size(slice_data) - mask_matrix = load_and_prepare_mask(mask_path, (width, height)) - data_for_bounds = slice_data[mask_matrix] - filter!(x -> x > 0, data_for_bounds) - else - data_for_bounds = vec(slice_data) - end - min_val, max_val = isempty(data_for_bounds) ? (0.0, 1.0) : extrema(data_for_bounds) - 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 diff --git a/src/mzML.jl b/src/mzML.jl index d3afd94..b269189 100644 --- a/src/mzML.jl +++ b/src/mzML.jl @@ -397,7 +397,7 @@ function load_mzml_lazy(file_path::String; cache_size::Int=100) # --- Handle Pool Optimization --- # Open multiple handles to the .mzML file to avoid lock contention - num_handles = Threads.nthreads() + num_handles = max(1, Threads.maxthreadid()) mzml_handles = [open(file_path, "r") for _ in 1:num_handles] # Use the first handle for initial parsing -- 2.53.0