altered imzML parser to be compatible with timsconverter, small improvements on the UI, other small bug fixes done

This commit is contained in:
Pixelguy14
2025-10-13 22:05:56 -06:00
parent f35acd1d0f
commit 2fd2b90513
9 changed files with 916 additions and 240 deletions
+59 -13
View File
@@ -61,6 +61,8 @@ struct SpectrumAsset
axis_type::Symbol
end
@enum SpectrumMode CENTROID=1 PROFILE=2 UNKNOWN=3
"""
SpectrumMetadata
@@ -69,6 +71,7 @@ Contains all metadata for a single spectrum, common to both imzML and mzML forma
# Fields
- `x`, `y`: The spatial coordinates of the spectrum (for imzML only).
- `id`: The unique identifier string for the spectrum (for mzML only).
- `mode`: The spectrum mode (`CENTROID` or `PROFILE`).
- `mz_asset`: A `SpectrumAsset` for the m/z array.
- `int_asset`: A `SpectrumAsset` for the intensity array.
"""
@@ -80,6 +83,7 @@ struct SpectrumMetadata
# For mzML
id::String
mode::SpectrumMode
# Common binary data info
mz_asset::SpectrumAsset
int_asset::SpectrumAsset
@@ -345,25 +349,28 @@ as they can use this cached data. This function modifies the `MSIData` object in
and is idempotent.
"""
function precompute_analytics(msi_data::MSIData)
# Idempotency check: If already computed, do nothing.
# Idempotency check
if msi_data.spectrum_stats_df !== nothing && hasproperty(msi_data.spectrum_stats_df, :MinMZ)
println("Analytics have already been pre-computed.")
return
end
"""
meta = msi_data.spectra_metadata[1]
println("First spectrum:")
println(" mz compressed: $(meta.mz_asset.is_compressed)")
println(" int compressed: $(meta.int_asset.is_compressed)")
println(" mz encoded_length: $(meta.mz_asset.encoded_length)")
println(" int encoded_length: $(meta.int_asset.encoded_length)")
println("Pre-computing analytics (single pass)...")
"""
start_time = time_ns()
num_spectra = length(msi_data.spectra_metadata)
# DEBUG: Check the first spectrum's metadata
if num_spectra > 0
first_meta = msi_data.spectra_metadata[1]
println("DEBUG First spectrum metadata:")
println(" mz_asset: format=$(first_meta.mz_asset.format), compressed=$(first_meta.mz_asset.is_compressed)")
println(" mz_asset: offset=$(first_meta.mz_asset.offset), encoded_length=$(first_meta.mz_asset.encoded_length)")
println(" int_asset: format=$(first_meta.int_asset.format), compressed=$(first_meta.int_asset.is_compressed)")
println(" int_asset: offset=$(first_meta.int_asset.offset), encoded_length=$(first_meta.int_asset.encoded_length)")
println(" mode: $(first_meta.mode)")
end
# Initialize variables for global stats
g_min_mz = Inf
g_max_mz = -Inf
@@ -375,9 +382,21 @@ function precompute_analytics(msi_data::MSIData)
num_points = Vector{Int}(undef, num_spectra)
min_mzs = Vector{Float64}(undef, num_spectra)
max_mzs = Vector{Float64}(undef, num_spectra)
modes = Vector{SpectrumMode}(undef, num_spectra)
is_compressed = Vector{Bool}(undef, num_spectra)
# DEBUG: Add counter to see how many spectra have data
spectra_with_data = 0
empty_spectra = 0
_iterate_spectra_fast(msi_data) do idx, mz, intensity
# Store metadata
modes[idx] = msi_data.spectra_metadata[idx].mode
is_compressed[idx] = msi_data.spectra_metadata[idx].mz_asset.is_compressed ||
msi_data.spectra_metadata[idx].int_asset.is_compressed
if isempty(mz)
empty_spectra += 1
tics[idx] = 0.0
bpis[idx] = 0.0
bp_mzs[idx] = 0.0
@@ -385,6 +404,8 @@ function precompute_analytics(msi_data::MSIData)
min_mzs[idx] = Inf
max_mzs[idx] = -Inf
return
else
spectra_with_data += 1
end
# Update global m/z range
@@ -402,6 +423,27 @@ function precompute_analytics(msi_data::MSIData)
num_points[idx] = length(mz)
end
# Add mode statistics
centroid_count = count(==(CENTROID), modes)
profile_count = count(==(PROFILE), modes)
unknown_count = count(==(UNKNOWN), modes)
println("DEBUG Mode Statistics:")
println(" Centroid spectra: $centroid_count")
println(" Profile spectra: $profile_count")
println(" Unknown mode: $unknown_count")
# DEBUG: Print summary
println("DEBUG Analytics Summary:")
println(" Total spectra: $num_spectra")
println(" Spectra with data: $spectra_with_data")
println(" Empty spectra: $empty_spectra")
println(" Global m/z range: [$g_min_mz, $g_max_mz]")
println(" Centroid spectra: $(count(==(CENTROID), modes))")
println(" Profile spectra: $(count(==(PROFILE), modes))")
println(" Compressed spectra: $(sum(is_compressed))")
println(" Average points per spectrum: $(mean(num_points))")
# Populate the MSIData object
msi_data.global_min_mz = g_min_mz
msi_data.global_max_mz = g_max_mz
@@ -412,7 +454,9 @@ function precompute_analytics(msi_data::MSIData)
BasePeakMZ = bp_mzs,
NumPoints = num_points,
MinMZ = min_mzs,
MaxMZ = max_mzs
MaxMZ = max_mzs,
Mode = modes,
IsCompressed = is_compressed
)
duration = (time_ns() - start_time) / 1e9
@@ -731,12 +775,15 @@ function read_compressed_array(io::IO, asset::SpectrumAsset, format::Type)
seek(io, asset.offset)
if asset.is_compressed
# Read compressed bytes
# Read compressed bytes - use encoded_length as the number of compressed bytes
compressed_bytes = read(io, asset.encoded_length)
println("DEBUG: Decompressing data - offset=$(asset.offset), compressed_bytes=$(length(compressed_bytes))")
local decompressed_bytes
try
decompressed_bytes = Libz.inflate(compressed_bytes)
println("DEBUG: Decompression successful - decompressed_bytes=$(length(decompressed_bytes))")
catch e
@error "ZLIB DECOMPRESSION FAILED. This is likely due to an incorrect offset or corrupt data in the .ibd file."
@error "Asset offset: $(asset.offset), Encoded length: $(asset.encoded_length)"
@@ -747,8 +794,7 @@ function read_compressed_array(io::IO, asset::SpectrumAsset, format::Type)
rethrow(e)
end
# Use an IOBuffer to safely read the data, avoiding reinterpret errors
# if the decompressed size is not a perfect multiple of the element size.
# Use an IOBuffer to safely read the data
bytes_io = IOBuffer(decompressed_bytes)
n_elements = bytes_io.size ÷ sizeof(format)
array = Array{format}(undef, n_elements)
+14 -8
View File
@@ -20,6 +20,7 @@ mutable struct SpecDim
Packed::Bool
Axis::Int
Skip::Int
Mode::SpectrumMode
end
"""
@@ -51,7 +52,7 @@ Retrieves an attribute's value from an XML tag string.
"""
function get_attribute(source::AbstractString, tag::String = "([^=]+)")
# Construct the regex pattern string
pattern_str = "\\s" * tag * "=\"([^\"]*)\""
pattern_str = "\\s*" * tag * "=\"([^\"]*)\""
regStr = Regex(pattern_str)
return match(regStr, source)
end
@@ -70,17 +71,18 @@ compression status (`zlib`), and axis type (m/z vs. intensity).
- A `SpecDim` struct populated with the parsed configuration.
"""
function configure_spec_dim(stream)
axis = SpecDim(Float64, false, 1, 0)
offset = position(stream)
axis = SpecDim(Float64, false, 1, 0, UNKNOWN) # Add UNKNOWN as default mode
while !eof(stream)
currLine = readline(stream)
matchInfo = match(r"^\s*<(cvParam)", currLine)
if matchInfo === nothing
matchInfo = match(r"^\s*", currLine)
axis.Skip = position(stream) - offset - length(currLine) + length(matchInfo.match)
return axis
# Check for end of cvParam block
if match(r"^\s*</", currLine) !== nothing
return axis
end
continue
end
index = length(matchInfo.captures[1])
@@ -98,10 +100,14 @@ function configure_spec_dim(stream)
axis.Format = Int64
elseif accession == "MS:1000574" # zlib compression
axis.Packed = true
elseif accession == "MS:1000127" # centroid spectrum
axis.Mode = CENTROID
elseif accession == "MS:1000128" # profile spectrum
axis.Mode = PROFILE
end
end
end
return axis # Should be unreachable if file is well-formed
return axis
end
# ============================================================================
+457 -76
View File
@@ -26,16 +26,25 @@ Core Functions:
Determines the storage order of the m/z and intensity arrays.
"""
function axes_config_img(stream)
tag = find_tag(stream, r"^\s*<(referenceableParamGroup )")
value = get_attribute(tag.captures[1], "intensityArray")
order = 1 + (value !== nothing)
param_groups = Dict{String, SpecDim}()
find_tag(stream, r"<referenceableParamGroupList")
axis = Array{SpecDim,1}(undef, 2)
axis[order] = configure_spec_dim(stream)
while true
pos = position(stream)
line = readline(stream)
find_tag(stream, r"^\s*<(referenceableParamGroup )")
axis[xor(order, 3)] = configure_spec_dim(stream)
return axis
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
"""
@@ -137,13 +146,57 @@ function get_spectrum_attributes(stream, hIbd)
return skip
end
function determine_parser(stream, mz_is_compressed, int_is_compressed)
start_pos = position(stream)
spectrum_xml = ""
try
# Find the start of the first spectrum tag
while !eof(stream)
line = readline(stream)
if occursin("<spectrum ", line)
spectrum_buffer = IOBuffer()
write(spectrum_buffer, line)
# Read until the end of the spectrum tag
while !eof(stream)
line = readline(stream)
write(spectrum_buffer, line)
if occursin("</spectrum>", line)
break
end
end
spectrum_xml = String(take!(spectrum_buffer))
break # Found the first spectrum, so we can stop
end
end
finally
seek(stream, start_pos) # Always reset stream position
end
"""
load_imzml_lazy(file_path::String; cache_size=100)
if isempty(spectrum_xml)
# Fallback based on compression flags if no spectrum tag found
return (mz_is_compressed || int_is_compressed) ? :compressed : :uncompressed
end
# Inspect the XML content
has_neofx_markers = occursin("encodedLength=\"0\"", spectrum_xml) &&
occursin("external encoded length", spectrum_xml)
has_external_data_markers = occursin("IMS:1000101", spectrum_xml) &&
occursin("IMS:1000102", spectrum_xml) &&
occursin("IMS:1000103", spectrum_xml)
if has_neofx_markers
return :neofx
end
if mz_is_compressed || int_is_compressed || has_external_data_markers
return :compressed
end
return :uncompressed
end
Main function to parse an `.imzML`/.ibd file pair and prepare for lazy loading.
It now returns a unified MSIData object.
"""
function load_imzml_lazy(file_path::String; cache_size=100)
println("DEBUG: Checking for .imzML file at $file_path")
if !isfile(file_path)
@@ -162,71 +215,64 @@ function load_imzml_lazy(file_path::String; cache_size=100)
try
println("DEBUG: Configuring axes...")
axis = axes_config_img(stream)
param_groups = axes_config_img(stream)
println("DEBUG: Getting image dimensions...")
imgDim = get_img_dimensions(stream)
width, height, num_spectra = imgDim
println("DEBUG: Image dimensions: $(width)x$(height), $num_spectra spectra.")
mz_config_idx = findfirst(a -> a.Axis == 1, axis)
int_config_idx = findfirst(a -> a.Axis == 2, axis)
mz_format = axis[mz_config_idx].Format
intensity_format = axis[int_config_idx].Format
mz_is_compressed = axis[mz_config_idx].Packed
int_is_compressed = axis[int_config_idx].Packed
println("DEBUG: m/z format: $mz_format, Intensity format: $intensity_format")
println("DEBUG: m/z compressed: $mz_is_compressed, Intensity compressed: $int_is_compressed")
# Extract default formats from the parsed param_groups
mz_group = nothing
int_group = nothing
# --- NEW PARSING LOGIC based on the old, working code ---
println("DEBUG: Learning file structure from first spectrum...")
start_of_spectra_xml = position(stream)
attr = get_spectrum_attributes(stream, hIbd)
current_ibd_offset = position(hIbd)
seek(stream, start_of_spectra_xml)
println("DEBUG: Initial IBD offset: $current_ibd_offset")
spectra_metadata = Vector{SpectrumMetadata}(undef, num_spectra)
mz_is_first = attr[3] == 3
println("DEBUG: Parsing metadata for $num_spectra spectra using skip-based method...")
for k in 1:num_spectra
# Use skip values learned from the first spectrum, assuming all are identical.
skip(stream, attr[5]) # Skip to X coordinate value
val_tag_x = find_tag(stream, r"value=\"(\d+)\"")
x = parse(Int32, val_tag_x.captures[1])
skip(stream, attr[6]) # Skip to Y coordinate value
val_tag_y = find_tag(stream, r"value=\"(\d+)\"")
y = parse(Int32, val_tag_y.captures[1])
skip(stream, attr[7]) # Skip to array length value
val_tag_len = find_tag(stream, r"value=\"(\d+)\"")
nPoints = parse(Int32, val_tag_len.captures[1])
mz_len_bytes = nPoints * sizeof(mz_format)
int_len_bytes = nPoints * sizeof(intensity_format)
local mz_offset, int_offset
if mz_is_first
mz_offset = current_ibd_offset
int_offset = mz_offset + mz_len_bytes
else
int_offset = current_ibd_offset
mz_offset = int_offset + int_len_bytes
for group in values(param_groups)
if group.Axis == 1
mz_group = group
elseif group.Axis == 2
int_group = group
end
# Create modern SpectrumAsset objects
mz_asset = SpectrumAsset(mz_format, mz_is_compressed, mz_offset, nPoints, :mz)
int_asset = SpectrumAsset(intensity_format, int_is_compressed, int_offset, nPoints, :intensity)
spectra_metadata[k] = SpectrumMetadata(x, y, "", mz_asset, int_asset)
# Advance the offset for the next spectrum's data.
current_ibd_offset += mz_len_bytes + int_len_bytes
skip(stream, attr[8]) # Skip to the end of the spectrum tag
end
# --- END OF NEW PARSING LOGIC ---
if mz_group === nothing || int_group === nothing
@warn "Could not find global definitions for m/z and intensity arrays. Using hardcoded defaults (Float64)."
default_mz_format = Float64
default_intensity_format = Float64
mz_is_compressed = false
int_is_compressed = false
global_mode = UNKNOWN
else
default_mz_format = mz_group.Format
default_intensity_format = int_group.Format
mz_is_compressed = mz_group.Packed
int_is_compressed = int_group.Packed
global_mode = mz_group.Mode != UNKNOWN ? mz_group.Mode : int_group.Mode
end
println("DEBUG: m/z format: $default_mz_format, Intensity format: $default_intensity_format")
println("DEBUG: m/z compressed: $mz_is_compressed, Intensity compressed: $int_is_compressed")
println("DEBUG: Global mode: $global_mode")
# --- Parser Selection ---
parser_type = determine_parser(stream, mz_is_compressed, int_is_compressed)
println("DEBUG: Selected parser: $parser_type")
local spectra_metadata
if parser_type == :neofx
println("DEBUG: Using neofx parser.")
spectra_metadata = parse_neofx(stream, hIbd, param_groups, width, height, num_spectra,
default_mz_format, default_intensity_format,
mz_is_compressed, int_is_compressed, global_mode)
elseif parser_type == :compressed
println("DEBUG: Using compressed parser.")
spectra_metadata = parse_compressed(stream, hIbd, param_groups, width, height, num_spectra,
default_mz_format, default_intensity_format,
mz_is_compressed, int_is_compressed, global_mode)
else # :uncompressed
println("DEBUG: Using uncompressed parser.")
spectra_metadata = parse_uncompressed(stream, hIbd, param_groups, width, height, num_spectra,
default_mz_format, default_intensity_format,
mz_is_compressed, int_is_compressed, global_mode)
end
println("DEBUG: Metadata parsing complete.")
@@ -234,6 +280,9 @@ function load_imzml_lazy(file_path::String; cache_size=100)
println("DEBUG: Building coordinate map...")
coordinate_map = zeros(Int, width, height)
for (idx, meta) in enumerate(spectra_metadata)
if idx == 1
println("DIAGNOSTIC_WRITE: For index 1, attempting to write to coordinate_map[$(meta.x), $(meta.y)]")
end
if 1 <= meta.x <= width && 1 <= meta.y <= height
coordinate_map[meta.x, meta.y] = idx
end
@@ -242,7 +291,7 @@ function load_imzml_lazy(file_path::String; cache_size=100)
close(stream)
source = ImzMLSource(hIbd, mz_format, intensity_format)
source = ImzMLSource(hIbd, default_mz_format, default_intensity_format)
println("DEBUG: Creating MSIData object.")
return MSIData(source, spectra_metadata, (width, height), coordinate_map, cache_size)
@@ -253,11 +302,342 @@ function load_imzml_lazy(file_path::String; cache_size=100)
end
end
function parse_uncompressed(stream, hIbd, param_groups, width, height, num_spectra,
mz_format, intensity_format, mz_is_compressed, int_is_compressed, global_mode)
# Your existing working skip-based parser
println("DEBUG: Learning file structure from first spectrum...")
start_of_spectra_xml = position(stream)
attr = get_spectrum_attributes(stream, hIbd)
current_ibd_offset = position(hIbd)
seek(stream, start_of_spectra_xml)
println("DEBUG: Initial IBD offset: $current_ibd_offset")
spectra_metadata = Vector{SpectrumMetadata}(undef, num_spectra)
mz_is_first = attr[3] == 3
for k in 1:num_spectra
# Store the start position of this spectrum for mode detection
spectrum_start_pos = position(stream)
# Use skip values learned from the first spectrum
skip(stream, attr[5]) # Skip to X coordinate value
val_tag_x = find_tag(stream, r"value=\"(\d+)\"")
x = parse(Int32, val_tag_x.captures[1])
skip(stream, attr[6]) # Skip to Y coordinate value
val_tag_y = find_tag(stream, r"value=\"(\d+)\"")
y = parse(Int32, val_tag_y.captures[1])
skip(stream, attr[7]) # Skip to array length value
val_tag_len = find_tag(stream, r"value=\"(\d+)\"")
nPoints = parse(Int32, val_tag_len.captures[1])
# For uncompressed data, use simple calculation
mz_len_bytes = nPoints * sizeof(mz_format)
int_len_bytes = nPoints * sizeof(intensity_format)
local mz_offset, int_offset
if mz_is_first
mz_offset = current_ibd_offset
int_offset = mz_offset + mz_len_bytes
else
int_offset = current_ibd_offset
mz_offset = int_offset + int_len_bytes
end
# Mode detection from spectrum XML
current_pos = position(stream)
seek(stream, spectrum_start_pos)
spectrum_buffer = IOBuffer()
line = ""
while !eof(stream)
line = readline(stream)
write(spectrum_buffer, line)
if occursin("</spectrum>", line)
break
end
end
spectrum_xml = String(take!(spectrum_buffer))
spectrum_mode = global_mode
if occursin("MS:1000127", spectrum_xml)
spectrum_mode = CENTROID
elseif occursin("MS:1000128", spectrum_xml)
spectrum_mode = PROFILE
end
seek(stream, current_pos)
# Create SpectrumAsset objects
mz_asset = SpectrumAsset(mz_format, mz_is_compressed, mz_offset, nPoints, :mz)
int_asset = SpectrumAsset(intensity_format, int_is_compressed, int_offset, nPoints, :intensity)
spectra_metadata[k] = SpectrumMetadata(x, y, "", spectrum_mode, mz_asset, int_asset)
current_ibd_offset += mz_len_bytes + int_len_bytes
skip(stream, attr[8]) # Skip to the end of the spectrum tag
end
return spectra_metadata
end
function parse_compressed(stream, hIbd, param_groups, width, height, num_spectra,
default_mz_format, default_intensity_format,
mz_is_compressed, int_is_compressed, global_mode)
# New parser for compressed data
spectra_metadata = Vector{SpectrumMetadata}(undef, num_spectra)
for k in 1:num_spectra
# Read the full spectrum XML block
spectrum_buffer = IOBuffer()
line = ""
while !eof(stream)
line = readline(stream)
if occursin("<spectrum ", line)
write(spectrum_buffer, line)
break
end
end
while !eof(stream)
line = readline(stream)
write(spectrum_buffer, line)
if occursin("</spectrum>", line)
break
end
end
spectrum_xml = String(take!(spectrum_buffer))
# Parse coordinates
x_match = match(r"IMS:1000050.*?value=\"(\d+)\"", spectrum_xml)
y_match = match(r"IMS:1000051.*?value=\"(\d+)\"", spectrum_xml)
x = x_match !== nothing ? parse(Int32, x_match.captures[1]) : Int32(0)
y = y_match !== nothing ? parse(Int32, y_match.captures[1]) : Int32(0)
# Parse mode
spectrum_mode = global_mode
if occursin("MS:1000127", spectrum_xml)
spectrum_mode = CENTROID
elseif occursin("MS:1000128", spectrum_xml)
spectrum_mode = PROFILE
end
# Parse binary data arrays
array_data = []
# Find all binaryDataArray blocks
array_matches = eachmatch(r"<binaryDataArray.*?<\/binaryDataArray>"s, spectrum_xml)
for array_match in array_matches
array_xml = array_match.match
# Determine if this is m/z or intensity array
is_mz = occursin("MS:1000514", array_xml) || occursin("mzArray", array_xml)
# Parse external data parameters
# Get array_length (nPoints)
array_len_cv_match = match(r"IMS:1000103.*?value=\"(\d+)\"", array_xml)
array_length = 0
if array_len_cv_match !== nothing
array_length = parse(Int32, array_len_cv_match.captures[1])
end
if array_length == 0
nPoints_match = match(r"defaultArrayLength=\"(\d+)\"", spectrum_xml)
if nPoints_match !== nothing
array_length = parse(Int32, nPoints_match.captures[1])
end
end
# Get encoded_length
encoded_len_cv_match = match(r"IMS:1000104.*?value=\"(\d+)\"", array_xml)
encoded_length = 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+)\"", array_xml)
if encoded_len_attr_match !== nothing
encoded_length = parse(Int64, encoded_len_attr_match.captures[1])
end
end
# Get offset
offset_match = match(r"IMS:1000102.*?value=\"(\d+)\"", array_xml)
offset = 0
if offset_match !== nothing
offset = parse(Int64, offset_match.captures[1])
end
if array_length > 0 && offset > 0
push!(array_data, (
is_mz = is_mz,
array_length = array_length,
encoded_length = encoded_length,
offset = offset
))
end
end
# Separate m/z and intensity arrays
mz_data = filter(d -> d.is_mz, array_data)
int_data = filter(d -> !d.is_mz, array_data)
if length(mz_data) != 1 || length(int_data) != 1
error("Spectrum $k: Expected exactly one m/z and one intensity array")
end
mz_info = mz_data[1]
int_info = int_data[1]
# DEBUG: Print first spectrum details
if k == 1
println("DEBUG First spectrum parsed:")
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)")
println(" Expected m/z bytes: $(mz_info.array_length * sizeof(default_mz_format))")
println(" Expected intensity bytes: $(int_info.array_length * sizeof(default_intensity_format))")
end
# Create SpectrumAsset objects
mz_asset = SpectrumAsset(default_mz_format, mz_is_compressed, mz_info.offset,
mz_is_compressed ? mz_info.encoded_length : mz_info.array_length, :mz)
int_asset = SpectrumAsset(default_intensity_format, int_is_compressed, int_info.offset,
int_is_compressed ? int_info.encoded_length : int_info.array_length, :intensity)
spectra_metadata[k] = SpectrumMetadata(x, y, "", spectrum_mode, mz_asset, int_asset)
end
return spectra_metadata
end
function parse_neofx(stream, hIbd, param_groups, width, height, num_spectra,
default_mz_format, default_intensity_format,
mz_is_compressed, int_is_compressed, global_mode)
# New parser for compressed data
spectra_metadata = Vector{SpectrumMetadata}(undef, num_spectra)
for k in 1:num_spectra
# Read the full spectrum XML block
spectrum_buffer = IOBuffer()
line = ""
while !eof(stream)
line = readline(stream)
if occursin("<spectrum ", line)
write(spectrum_buffer, line)
break
end
end
while !eof(stream)
line = readline(stream)
write(spectrum_buffer, line)
if occursin("</spectrum>", line)
break
end
end
spectrum_xml = String(take!(spectrum_buffer))
# Parse coordinates
x_match = match(r"IMS:1000050.*?value=\"(\d+)\"", spectrum_xml)
y_match = match(r"IMS:1000051.*?value=\"(\d+)\"", spectrum_xml)
x = x_match !== nothing ? parse(Int32, x_match.captures[1]) : Int32(0)
y = y_match !== nothing ? parse(Int32, y_match.captures[1]) : Int32(0)
# Parse mode
spectrum_mode = global_mode
if occursin("MS:1000127", spectrum_xml)
spectrum_mode = CENTROID
elseif occursin("MS:1000128", spectrum_xml)
spectrum_mode = PROFILE
end
# Parse binary data arrays
array_data = []
# Find all binaryDataArray blocks
array_matches = eachmatch(r"<binaryDataArray.*?<\/binaryDataArray>"s, spectrum_xml)
for array_match in array_matches
array_xml = array_match.match
# Determine if this is m/z or intensity array
is_mz = occursin("MS:1000514", array_xml) || occursin("mzArray", array_xml)
# Parse external data parameters
# Get array_length (nPoints)
array_len_cv_match = match(r"IMS:1000103.*?value=\"(\d+)\"", array_xml)
array_length = 0
if array_len_cv_match !== nothing
array_length = parse(Int32, array_len_cv_match.captures[1])
end
if array_length == 0
nPoints_match = match(r"defaultArrayLength=\"(\d+)\"", spectrum_xml)
if nPoints_match !== nothing
array_length = parse(Int32, nPoints_match.captures[1])
end
end
# Get encoded_length
encoded_len_cv_match = match(r"IMS:1000104.*?value=\"(\d+)\"", array_xml)
encoded_length = 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+)\"", array_xml)
if encoded_len_attr_match !== nothing
encoded_length = parse(Int64, encoded_len_attr_match.captures[1])
end
end
# Get offset
offset_match = match(r"IMS:1000102.*?value=\"(\d+)\"", array_xml)
offset = 0
if offset_match !== nothing
offset = parse(Int64, offset_match.captures[1])
end
if array_length > 0 && offset > 0
push!(array_data, (
is_mz = is_mz,
array_length = array_length,
encoded_length = encoded_length,
offset = offset
))
end
end
# Separate m/z and intensity arrays
mz_data = filter(d -> d.is_mz, array_data)
int_data = filter(d -> !d.is_mz, array_data)
if length(mz_data) != 1 || length(int_data) != 1
error("Spectrum $k: Expected exactly one m/z and one intensity array")
end
mz_info = mz_data[1]
int_info = int_data[1]
# DEBUG: Print first spectrum details
if k == 1
println("DEBUG First spectrum parsed:")
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)")
println(" Expected m/z bytes: $(mz_info.array_length * sizeof(default_mz_format))")
println(" Expected intensity bytes: $(int_info.array_length * sizeof(default_intensity_format))")
end
# Create SpectrumAsset objects
mz_asset = SpectrumAsset(default_mz_format, mz_is_compressed, mz_info.offset,
mz_is_compressed ? mz_info.encoded_length : mz_info.array_length, :mz)
int_asset = SpectrumAsset(default_intensity_format, int_is_compressed, int_info.offset,
int_is_compressed ? int_info.encoded_length : int_info.array_length, :intensity)
spectra_metadata[k] = SpectrumMetadata(x, y, "", spectrum_mode, mz_asset, int_asset)
end
return spectra_metadata
end
# --- End of content from imzML.jl ---
# --- Start of content from Imaging_Normalization.jl ---
# =============================================================================
#
# Image Slice Extraction
@@ -446,7 +826,8 @@ function plot_slice(msi_data::MSIData, mass::Real, tolerance::Real, output_dir::
fig = Figure(size = (600, 500))
ax = CairoMakie.Axis(fig[1, 1],
aspect=DataAspect(),
title=@sprintf("Slice for m/z: %.2f", mass)
title=@sprintf("Slice for m/z: %.2f", mass),
yreversed=true
)
hidedecorations!(ax)
@@ -985,4 +1366,4 @@ function generate_palette(colorscheme, n_colors=256)
return palette
end
const ViridisPalette = generate_palette(ColorSchemes.viridis)
const ViridisPalette = generate_palette(ColorSchemes.viridis)