integrated MSI_src API into the UI, fixed interface elements, made some processes asynchronous, modified spectrum plots, added sum spectrum, removed use of obsolete julia_mzML_imzML library

This commit is contained in:
Pixelguy14
2025-10-02 13:28:15 -06:00
parent cd1115368f
commit 22c8d9637b
10 changed files with 1076 additions and 708 deletions
+82 -15
View File
@@ -6,7 +6,7 @@ including caching and iteration logic, for handling large mzML and imzML dataset
efficiently.
"""
using Base64, Libz # For reading binary data
using Base64, Libz, Serialization # For reading binary data
# Abstract type for different data sources (e.g., mzML, imzML)
# This allows dispatching to the correct binary reading logic.
@@ -179,17 +179,10 @@ function GetSpectrum(data::MSIData, x::Int, y::Int)
return GetSpectrum(data, index) # Call the existing method
end
"""
get_total_spectrum(msi_data::MSIData; num_bins::Int=20000) -> Tuple{Vector{Float64}, Vector{Float64}}
using Serialization
Calculates the sum of all spectra in the dataset by binning.
The m/z range is determined dynamically by finding the global min/max m/z values
across the entire dataset.
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=20000)
println("Calculating total spectrum...")
function get_total_spectrum_imzml(msi_data::MSIData; num_bins::Int=2000)
println("Calculating total spectrum (2-pass method for imzML)...")
# 1. First Pass: Find the global m/z range
println(" Pass 1: Finding global m/z range...")
@@ -222,7 +215,6 @@ function get_total_spectrum(msi_data::MSIData; num_bins::Int=20000)
return # continue equivalent
end
for i in eachindex(mz)
# Find the correct bin for the current m/z value
bin_index = clamp(round(Int, (mz[i] - global_min_mz) / bin_step) + 1, 1, num_bins)
intensity_sum[bin_index] += intensity[i]
end
@@ -232,6 +224,83 @@ function get_total_spectrum(msi_data::MSIData; num_bins::Int=20000)
return (collect(mz_bins), intensity_sum)
end
function get_total_spectrum_mzml(msi_data::MSIData; num_bins::Int=2000)
println("Calculating total spectrum (single-pass optimization for mzML)...")
num_spectra = length(msi_data.spectra_metadata)
if num_spectra == 0
return (Float64[], Float64[])
end
temp_path, temp_io = mktemp()
try
# --- Pass 1: Write spectra to temp file and find min/max m/z ---
println(" Pass 1: Caching spectra and finding global m/z range...")
global_min_mz = Inf
global_max_mz = -Inf
_iterate_spectra_fast(msi_data) do idx, mz, intensity
Serialization.serialize(temp_io, (mz, intensity))
if !isempty(mz)
local_min, local_max = extrema(mz)
global_min_mz = min(global_min_mz, local_min)
global_max_mz = max(global_max_mz, local_max)
end
end
flush(temp_io)
if !isfinite(global_min_mz)
@warn "Could not determine a valid m/z range. All spectra might be empty."
return (Float64[], Float64[])
end
println(" Global m/z range found: [$(global_min_mz), $(global_max_mz)]")
# --- Pass 2: Read from temp file and bin intensities ---
println(" Pass 2: Reading from cache and summing intensities into $num_bins bins...")
seekstart(temp_io)
mz_bins = range(global_min_mz, stop=global_max_mz, length=num_bins)
intensity_sum = zeros(Float64, num_bins)
bin_step = step(mz_bins)
while !eof(temp_io)
mz, intensity = Serialization.deserialize(temp_io)::Tuple{AbstractVector, AbstractVector}
if isempty(mz)
continue
end
for i in eachindex(mz)
bin_index = clamp(round(Int, (mz[i] - global_min_mz) / bin_step) + 1, 1, num_bins)
intensity_sum[bin_index] += intensity[i]
end
end
println("Total spectrum calculation complete.")
return (collect(mz_bins), intensity_sum)
finally
close(temp_io)
rm(temp_path, force=true)
end
end
"""
get_total_spectrum(msi_data::MSIData; num_bins::Int=20000) -> Tuple{Vector{Float64}, Vector{Float64}}
Calculates the sum of all spectra in the dataset by binning.
This function dispatches to a specialized implementation based on the file type
(.imzML or .mzML) for optimal performance.
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)
if msi_data.source isa ImzMLSource
return get_total_spectrum_imzml(msi_data, num_bins=num_bins)
else # MzMLSource
return get_total_spectrum_mzml(msi_data, num_bins=num_bins)
end
end
"""
get_average_spectrum(msi_data::MSIData; num_bins::Int=20000) -> Tuple{Vector{Float64}, Vector{Float64}}
@@ -241,7 +310,7 @@ This is effectively the total ion chromatogram (TIC) divided by the number of sp
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=20000)
function get_average_spectrum(msi_data::MSIData; num_bins::Int=2000)
# This function uses the exact same logic as get_total_spectrum...
mz_bins, intensity_sum = get_total_spectrum(msi_data, num_bins=num_bins)
@@ -365,5 +434,3 @@ function _iterate_spectra_fast(f::Function, data::MSIData)
# Dispatch to the correct implementation based on the source type
_iterate_spectra_fast_impl(f, data, data.source)
end
+177 -127
View File
@@ -26,26 +26,19 @@ struct BinaryMetadata
end
"""
GetMzmlScanTime(fileName::String)
GetMzmlScanTime_linebyline(fileName::String)
Parses a .mzML file to extract the scan start time for each spectrum.
# Arguments
* `fileName`: Path to the .mzML file.
# Returns
- A `Matrix{Int64}` where each row is `[spectrum_index, time_in_milliseconds]`.
(Internal) Slow, line-by-line parser for scan times. Used as a fallback if
the .mzML file index is missing or corrupt.
"""
function GetMzmlScanTime(fileName::String)
function GetMzmlScanTime_linebyline(fileName::String)
times = Tuple{Int64, Int64}[]
# Pre-allocate based on an estimate to reduce re-allocations
try
file_size = filesize(fileName)
estimated_spectra = max(1000, file_size ÷ 10000) # Heuristic
estimated_spectra = max(1000, file_size ÷ 10000)
sizehint!(times, estimated_spectra)
catch
# Ignore if filesize fails, sizehint! is just an optimization
end
open(fileName, "r") do stream
@@ -60,27 +53,23 @@ function GetMzmlScanTime(fileName::String)
current_index = 0
current_time = nothing
# Process index from the start tag itself
idx_match = match(r"index=\"(\d+)\"", line)
if idx_match !== nothing
current_index = parse(Int, idx_match.captures[1]) + 1
end
end
elseif state == :in_spectrum
# Look for time cvParam
if occursin("<cvParam", line)
if occursin("MS:1000016", line) || occursin("MS:1000015", line)
time_match = match(r"value=\"([\d\.]+)\"", line)
if time_match !== nothing
time_val = parse(Float64, time_match.captures[1])
# MS:1000016 is minutes, MS:1000015 is seconds
unit_scale = occursin("MS:1000016", line) ? 60000 : 1000
current_time = round(Int64, time_val * unit_scale)
end
end
end
# Check for end of spectrum
if occursin("</spectrum>", line)
state = :outside_spectrum
if current_index > 0 && current_time !== nothing
@@ -91,9 +80,100 @@ function GetMzmlScanTime(fileName::String)
end
end
# Sort by spectrum index to ensure correct order before normalization
sort!(times, by = x -> x[1])
if !isempty(times)
first_time = times[1][2]
for i in eachindex(times)
times[i] = (times[i][1], times[i][2] - first_time)
end
end
if isempty(times)
return Matrix{Int64}(undef, 0, 2)
end
return permutedims(hcat(collect.(times)...))
end
"""
GetMzmlScanTime(fileName::String)
Parses a .mzML file to extract the scan start time for each spectrum.
Uses the indexed part of the .mzML file for fast access, falling back to
a slower line-by-line parse if the index is not present.
# Arguments
* `fileName`: Path to the .mzML file.
# Returns
- A `Matrix{Int64}` where each row is `[spectrum_index, time_in_milliseconds]`.
"""
function GetMzmlScanTime(fileName::String)
times = Tuple{Int64, Int64}[]
try
open(fileName, "r") do stream
# 1. Find and parse the spectrum index offsets
seekend(stream)
end_chunk_size = min(filesize(stream), 8192)
seek(stream, filesize(stream) - end_chunk_size)
footer = read(stream, String)
index_offset_match = match(r"<indexListOffset>(\d+)</indexListOffset>", footer)
if index_offset_match === nothing
@warn "No <indexListOffset> found. Falling back to slow line-by-line parsing for scan times. This may be memory intensive."
return GetMzmlScanTime_linebyline(fileName)
end
index_offset = parse(Int64, index_offset_match.captures[1])
seek(stream, index_offset)
# The find_tag function is defined in ParserHelpers.jl
if find_tag(stream, r"<index\s+name=\"spectrum\"") === nothing
@warn "Could not find spectrum index. Falling back to slow line-by-line parsing."
return GetMzmlScanTime_linebyline(fileName)
end
# The parse_offset_list function is defined in mzML.jl
spectrum_offsets = parse_offset_list(stream)
# 2. Iterate through offsets and parse time for each spectrum
for (idx, offset) in enumerate(spectrum_offsets)
seek(stream, offset)
current_time = nothing
# Read a limited number of lines to find the time
for _ in 1:100
if eof(stream) break end
line = readline(stream)
if occursin("MS:1000016", line) || occursin("MS:1000015", line) # scan start time
time_match = match(r"value=\"([\d\.]+)\"", line)
if time_match !== nothing
time_val = parse(Float64, time_match.captures[1])
unit_scale = occursin("MS:1000016", line) ? 60000 : 1000 # minutes vs seconds
current_time = round(Int64, time_val * unit_scale)
break
end
end
if occursin("<binary>", line) || occursin("</spectrum>", line)
break
end
end
if current_time !== nothing
push!(times, (idx, current_time))
end
end
end
catch e
@error "Failed to parse scan times with indexed method. Falling back to line-by-line." exception=(e, catch_backtrace())
return GetMzmlScanTime_linebyline(fileName)
end
# The index is already sorted by spectrum index, so no need to sort `times`.
# Normalize times relative to the first scan
if !isempty(times)
first_time = times[1][2]
@@ -102,7 +182,6 @@ function GetMzmlScanTime(fileName::String)
end
end
# Convert vector of tuples to a matrix
if isempty(times)
return Matrix{Int64}(undef, 0, 2)
end
@@ -329,131 +408,113 @@ function RenderPixel(pixel_info, scans, msi_data::MSIData, scan_time_deltas, pix
return (mz_array, new_intensity)
end
function ConvertMzmlToImzml(source_file::String, timing_matrix::Matrix{Int64}, scans::Matrix{Int64})
function ConvertMzmlToImzml(source_file::String, target_ibd_file::String, timing_matrix::Matrix{Int64}, scans::Matrix{Int64})
if size(timing_matrix, 1) == 0
return ProcessedPixel[], (0, 0)
# Create an empty .ibd file if there's nothing to process
open(target_ibd_file, "w") do ibd_stream
write(ibd_stream, zeros(UInt8, 16)) # UUID placeholder
end
return BinaryMetadata[], Tuple{Int, Int}[], (0, 0)
end
# Get image dimensions from timing_matrix (assuming columns 1 and 2 are X and Y)
width = maximum(timing_matrix[:, 1])
height = maximum(timing_matrix[:, 2])
# Open the mzML file using the new memory-efficient API
msi_data = OpenMSIData(source_file)
# Pre-calculate time deltas robustly
scan_time_deltas = zeros(Int64, size(scans, 1))
if size(scans, 1) > 1
for i in 1:(size(scans, 1) - 1)
delta = scans[i+1, 2] - scans[i, 2]
scan_time_deltas[i] = max(1, delta) # Ensure delta is at least 1
scan_time_deltas[i] = max(1, delta)
end
scan_time_deltas[end] = max(1, scan_time_deltas[end-1]) # Use previous delta for last scan, ensure at least 1
scan_time_deltas[end] = max(1, scan_time_deltas[end-1])
end
pixel_time_deltas = zeros(Int64, size(timing_matrix, 1))
if size(timing_matrix, 1) > 1
for i in 1:(size(timing_matrix, 1) - 1)
# Assumes time is in the 3rd column of the timing_matrix
delta = timing_matrix[i+1, 3] - timing_matrix[i, 3]
pixel_time_deltas[i] = max(1, delta) # Ensure delta is at least 1
pixel_time_deltas[i] = max(1, delta)
end
pixel_time_deltas[end] = max(1, pixel_time_deltas[end-1]) # Use previous delta for last pixel, ensure at least 1
pixel_time_deltas[end] = max(1, pixel_time_deltas[end-1])
end
processed_pixels = ProcessedPixel[]
sizehint!(processed_pixels, size(timing_matrix, 1))
binary_meta_vec = BinaryMetadata[]
sizehint!(binary_meta_vec, size(timing_matrix, 1))
coords_vec = Tuple{Int, Int}[]
sizehint!(coords_vec, size(timing_matrix, 1))
empty_pixel_count = 0
# DEBUG: Scan coverage analysis
println("DEBUG: Scan coverage analysis:")
covered_pixels_count = 0
for i in 1:size(timing_matrix, 1)
first_scan = timing_matrix[i, 4]
last_scan = timing_matrix[i, 5]
if first_scan <= last_scan && first_scan >= 1 && last_scan <= size(scans, 1)
covered_pixels_count += 1
open(target_ibd_file, "w") do ibd_stream
write(ibd_stream, zeros(UInt8, 16)) # UUID placeholder
for i in 1:size(timing_matrix, 1)
pixel_info = timing_matrix[i, :]
x, y = pixel_info[1], pixel_info[2]
push!(coords_vec, (x, y))
first_scan = pixel_info[4]
last_scan = pixel_info[5]
if first_scan > last_scan || first_scan < 1 || last_scan > size(scans, 1)
empty_pixel_count += 1
# For empty pixels, offsets point to the current end of file, with zero length
current_pos = position(ibd_stream)
push!(binary_meta_vec, BinaryMetadata(current_pos, 0, current_pos, 0))
continue
end
mz, intensity = RenderPixel(pixel_info, scans, msi_data, scan_time_deltas, pixel_time_deltas)
# Write m/z array
mz_offset = position(ibd_stream)
for val in mz
write(ibd_stream, htol(Float64(val)))
end
mz_length = position(ibd_stream) - mz_offset
# Write intensity array
int_offset = position(ibd_stream)
for val in intensity
write(ibd_stream, htol(Float32(val)))
end
int_length = position(ibd_stream) - int_offset
push!(binary_meta_vec, BinaryMetadata(mz_offset, mz_length, int_offset, int_length))
end
end
println(" Pixels with potential scans: $covered_pixels_count/$(size(timing_matrix, 1))")
println(" Total scans available: $(size(scans, 1))")
for i in 1:size(timing_matrix, 1)
pixel_info = timing_matrix[i, :]
x = pixel_info[1]
y = pixel_info[2]
first_scan = pixel_info[4]
last_scan = pixel_info[5]
if first_scan > last_scan || first_scan < 1 || last_scan > size(scans, 1)
empty_pixel_count += 1
push!(processed_pixels, ProcessedPixel((x, y), Float64[], Float32[]))
continue
end
mz, intensity = RenderPixel(pixel_info, scans, msi_data, scan_time_deltas, pixel_time_deltas)
push!(processed_pixels, ProcessedPixel((x, y), mz, intensity))
end
@info "Found and created $empty_pixel_count empty pixels out of $(size(timing_matrix, 1)) total."
return processed_pixels, (width, height)
@info "Found and processed $empty_pixel_count empty pixels out of $(size(timing_matrix, 1)) total."
return binary_meta_vec, coords_vec, (width, height)
end
function ExportImzml(target_file::String, pixels::Vector{ProcessedPixel}, dims::Tuple{Int, Int})
function ExportImzml(target_file::String, binary_meta::Vector{BinaryMetadata}, coords::Vector{Tuple{Int, Int}}, dims::Tuple{Int, Int})
ibd_file = replace(target_file, r"\.imzML$"i => ".ibd")
# Ensure we have valid pixels
if isempty(pixels)
@error "No pixels to export"
return false
if isempty(binary_meta)
@warn "No binary metadata to export; creating empty imzML file."
# Still create a valid, empty imzML file
end
binary_meta = BinaryMetadata[]
sizehint!(binary_meta, length(pixels))
try
# Step 1: Write .ibd file with proper binary format
open(ibd_file, "w") do ibd_stream
# Write UUID as first 16 bytes (placeholder)
write(ibd_stream, zeros(UInt8, 16))
# The .ibd file is now written by ConvertMzmlToImzml.
# This function is only responsible for the .imzML XML metadata file.
# Write in little-endian format (standard for imzML)
for pixel in pixels
# Write m/z array as 64-bit little-endian floats
mz_offset = position(ibd_stream)
for val in pixel.mz
write(ibd_stream, htol(Float64(val))) # Host to little-endian
end
mz_length = position(ibd_stream) - mz_offset
# Write intensity array as 32-bit little-endian floats
int_offset = position(ibd_stream)
for val in pixel.intensity
write(ibd_stream, htol(Float32(val))) # Host to little-endian
end
int_length = position(ibd_stream) - int_offset
push!(binary_meta, BinaryMetadata(mz_offset, mz_length, int_offset, int_length))
end
end
# Step 2: Write proper .imzML XML file
open(target_file, "w") do imzml_stream
# Use indexedmzML wrapper
# XML Header
write(imzml_stream, """<?xml version="1.0" encoding="ISO-8859-1"?>
<indexedmzML xmlns="http://psi.hupo.org/ms/mzml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://psi.hupo.org/ms/mzml http://psidev.info/files/ms/mzML/xsd/mzML1.1.0_idx.xsd">
<mzML version="1.1" id="$(splitext(basename(target_file))[1])">
""")
# CV List
# CV List, File Description, etc. (static parts)
write(imzml_stream, """ <cvList count="3">
<cv id="MS" fullName="Proteomics Standards Initiative Mass Spectrometry Ontology" version="1.3.1" URI="http://psidev.info/ms/mzML/psi-ms.obo"/>
<cv id="UO" fullName="Unit Ontology" version="1.15" URI="http://obo.cvs.sourceforge.net/obo/obo/ontology/phenotype/unit.obo"/>
<cv id="IMS" fullName="Imaging MS Ontology" version="0.9.1" URI="http://www.maldi-msi.org/download/imzml/imagingMS.obo"/>
</cvList>
""")
# File Description
write(imzml_stream, """ <fileDescription>
<fileContent>
<cvParam cvRef="MS" accession="MS:1000579" name="MS1 spectrum"/>
@@ -462,8 +523,6 @@ function ExportImzml(target_file::String, pixels::Vector{ProcessedPixel}, dims::
</fileContent>
</fileDescription>
""")
# Referenceable Param Groups
write(imzml_stream, """ <referenceableParamGroupList count="2">
<referenceableParamGroup id="mzArray">
<cvParam cvRef="MS" accession="MS:1000576" name="no compression"/>
@@ -479,24 +538,18 @@ function ExportImzml(target_file::String, pixels::Vector{ProcessedPixel}, dims::
</referenceableParamGroup>
</referenceableParamGroupList>
""")
# Sample List
write(imzml_stream, """ <sampleList count="1">
<sample id="sample1" name="ImagingSample">
<cvParam cvRef="MS" accession="MS:1000001" name="sample number" value="1"/>
</sample>
</sampleList>
""")
# Software List - OPEN SOURCE
write(imzml_stream, """ <softwareList count="1">
<software id="MSIConverter" version="1.0">
<cvParam cvRef="MS" accession="MS:1000799" name="custom unreleased software tool" value="mzML to imzML converter"/>
</software>
</softwareList>
""")
# Scan Settings IMAGING
write(imzml_stream, """ <scanSettingsList count="1">
<scanSettings id="scanSettings1">
<cvParam cvRef="IMS" accession="IMS:1000042" name="max count of pixel x" value="$(dims[1])"/>
@@ -506,8 +559,6 @@ function ExportImzml(target_file::String, pixels::Vector{ProcessedPixel}, dims::
</scanSettings>
</scanSettingsList>
""")
# Instrument Configuration MALDI/TOF
write(imzml_stream, """ <instrumentConfigurationList count="1">
<instrumentConfiguration id="instrument1">
<componentList count="3">
@@ -525,8 +576,6 @@ function ExportImzml(target_file::String, pixels::Vector{ProcessedPixel}, dims::
</instrumentConfiguration>
</instrumentConfigurationList>
""")
# Data Processing
write(imzml_stream, """ <dataProcessingList count="1">
<dataProcessing id="conversionProcessing">
<processingMethod order="1" softwareRef="MSIConverter">
@@ -539,18 +588,21 @@ function ExportImzml(target_file::String, pixels::Vector{ProcessedPixel}, dims::
# Run and Spectrum List
spectrum_offsets = UInt64[]
write(imzml_stream, """ <run defaultInstrumentConfigurationRef="instrument1" id="run1" sampleRef="sample1">
<spectrumList count="$(length(pixels))" defaultDataProcessingRef="conversionProcessing">
<spectrumList count="$(length(binary_meta))" defaultDataProcessingRef="conversionProcessing">
""")
# Write each spectrum
for (i, pixel) in enumerate(pixels)
meta = binary_meta[i]
x, y = pixel.coords
# Write each spectrum's metadata
for (i, meta) in enumerate(binary_meta)
x, y = coords[i]
spectrum_start = position(imzml_stream)
push!(spectrum_offsets, spectrum_start)
write(imzml_stream, """ <spectrum id="Scan=$(i)" defaultArrayLength="$(length(pixel.mz))" index="$(i-1)">
# Calculate number of points from byte length
mz_points = meta.mz_length ÷ sizeof(Float64)
int_points = meta.int_length ÷ sizeof(Float32)
write(imzml_stream, """ <spectrum id="Scan=$(i)" defaultArrayLength="$(mz_points)" index="$(i-1)">
<cvParam cvRef="MS" accession="MS:1000511" name="ms level" value="1"/>
<cvParam cvRef="MS" accession="MS:1000128" name="profile spectrum"/>
<scanList count="1">
@@ -563,14 +615,14 @@ function ExportImzml(target_file::String, pixels::Vector{ProcessedPixel}, dims::
<binaryDataArray encodedLength="0">
<referenceableParamGroupRef ref="mzArray"/>
<cvParam cvRef="IMS" accession="IMS:1000102" name="external offset" value="$(meta.mz_offset)"/>
<cvParam cvRef="IMS" accession="IMS:1000103" name="external array length" value="$(length(pixel.mz))"/>
<cvParam cvRef="IMS" accession="IMS:1000103" name="external array length" value="$(mz_points)"/>
<cvParam cvRef="IMS" accession="IMS:1000104" name="external encoded length" value="$(meta.mz_length)"/>
<binary/>
</binaryDataArray>
<binaryDataArray encodedLength="0">
<referenceableParamGroupRef ref="intensityArray"/>
<cvParam cvRef="IMS" accession="IMS:1000102" name="external offset" value="$(meta.int_offset)"/>
<cvParam cvRef="IMS" accession="IMS:1000103" name="external array length" value="$(length(pixel.intensity))"/>
<cvParam cvRef="IMS" accession="IMS:1000103" name="external array length" value="$(int_points)"/>
<cvParam cvRef="IMS" accession="IMS:1000104" name="external encoded length" value="$(meta.int_length)"/>
<binary/>
</binaryDataArray>
@@ -603,10 +655,10 @@ function ExportImzml(target_file::String, pixels::Vector{ProcessedPixel}, dims::
return true
catch e
@error "Failed to export imzML files" exception=(e, catch_backtrace())
# Clean up partial files
isfile(ibd_file) && rm(ibd_file, force=true)
@error "Failed to export imzML metadata file" exception=(e, catch_backtrace())
# Clean up partial .imzML file
isfile(target_file) && rm(target_file, force=true)
# Do not delete the .ibd file as it might be useful for debugging
return false
end
end
@@ -630,17 +682,15 @@ function ImportMzmlFile(source_file::String, sync_file::String, target_file::Str
println("Step 2: Matching acquisition times...")
timing_matrix = MatchAcquireTime(sync_file, scans; img_width=img_width, img_height=img_height)
println("Step 3: Converting spectra...")
processed_pixels, (width, height) = ConvertMzmlToImzml(source_file, timing_matrix, scans)
println("Step 3: Converting spectra and writing .ibd file...")
ibd_file = replace(target_file, r"\.imzML$"i => ".ibd")
binary_meta, coords, (width, height) = ConvertMzmlToImzml(source_file, ibd_file, timing_matrix, scans)
# Flip image vertically to match R script output
for i in eachindex(processed_pixels)
x, y = processed_pixels[i].coords
processed_pixels[i] = ProcessedPixel((x, height - y + 1), processed_pixels[i].mz, processed_pixels[i].intensity)
end
flipped_coords = [(x, height - y + 1) for (x, y) in coords]
println("Step 4: Exporting to .imzML/.ibd format...")
success = ExportImzml(target_file, processed_pixels, (width, height))
println("Step 4: Exporting .imzML metadata file...")
success = ExportImzml(target_file, binary_meta, flipped_coords, (width, height))
if success
println("Conversion successful: $target_file")
+213 -1
View File
@@ -1,4 +1,4 @@
using Images, Statistics, CairoMakie, DataFrames, Printf, ColorSchemes
using Images, Statistics, CairoMakie, DataFrames, Printf, ColorSchemes, StatsBase
# --- Extracted from imzML.jl ---
@@ -347,6 +347,38 @@ function load_slices(folder, masses, tolerance)
end
"""
get_mz_slice(data::MSIData, mass::Real, tolerance::Real)
Extracts an image slice for a given m/z value without plotting.
This is a performant function that iterates through spectra once.
# Returns
- A `Matrix{Float64}` representing the intensity slice.
"""
function get_mz_slice(data::MSIData, mass::Real, tolerance::Real)
width, height = data.image_dims
slice_matrix = zeros(Float64, height, width) # Note: height, width for (y,x) indexing
_iterate_spectra_fast(data) do spec_idx, mz_array, intensity_array
meta = data.spectra_metadata[spec_idx]
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
# The original function had a NaN replacement, which is good practice to keep.
replace!(slice_matrix, NaN => 0.0)
return slice_matrix
end
"""
plot_slice(msi_data::MSIData, mass::Float64, tolerance::Float64, output_dir::String; stage_name="slice", bins=256)
@@ -486,6 +518,30 @@ function set_pixel_depth(img, bounds, depth)
return result
end
"""
TrIQ(pixMap, depth, prob=0.98)
Applies TrIQ (Treshold Intensity Quantization) normalization to an image.
This function first computes dynamic intensity range bounds by identifying outliers
based on a cumulative probability, then sets the pixel depth (quantizes intensities)
within these bounds.
# Arguments
- `pixMap`: The input image matrix (e.g., a slice from `GetMzSliceJl`).
- `depth`: The number of grey levels (bins) to quantize the intensities into.
- `prob`: The target cumulative probability (e.g., 0.98) used to determine outlier thresholds.
# Returns
- A new image matrix with intensities quantized to the specified depth within the TrIQ bounds.
"""
function TrIQ(pixMap, depth, prob=0.98)
# Compute new dynamic range
bounds = get_outlier_thres(pixMap, prob)
# Set intensity dynamic range
return set_pixel_depth(pixMap, bounds, depth)
end
"""
norm_slices_hist(slices, bins; prob=0.98)
@@ -515,11 +571,73 @@ function norm_slices_hist(slices, bins; prob=0.98)
return (norm_img=norm_img, bounds=mass_bounds) # bounds is now a vector, one per mass
end
"""
quantize_intensity(slice::AbstractMatrix{<:Real}, levels::Integer=256)
Linearly scales the intensity values in a slice to a specified number of levels.
The output is an array of `UInt8` values.
This is a modernized version of `IntQuantCl`.
"""
function quantize_intensity(slice::AbstractMatrix{<:Real}, levels::Integer=256)
max_val = maximum(slice)
if max_val <= 0
return zeros(UInt8, size(slice))
end
# Scale relative to the absolute maximum value to preserve the zero point.
# The original logic used 'colorLevel' which was the max value (e.g., 255).
scale = (levels - 1) / max_val
# round is equivalent to floor(x+0.5) for positive numbers.
# clamp is used for robustness against floating point inaccuracies.
image = round.(UInt8, clamp.(slice .* scale, 0, levels - 1))
return image
end
function median_filter(img)
# 3x3 median filter implementation
return mapwindow(median, img, (3, 3))
end
"""
downsample_spectrum(mz, intensity, n_points=2000)
Reduces the number of points in a spectrum for faster plotting, while preserving peaks.
It divides the m/z range into `n_points` bins and keeps only the most intense point from each bin.
"""
function downsample_spectrum(mz::AbstractVector, intensity::AbstractVector, n_points::Integer=2000)
if isempty(mz) || length(mz) <= n_points
return mz, intensity
end
mz_min, mz_max = extrema(mz)
bin_width = (mz_max - mz_min) / n_points
# We use a vector of tuples to store the max intensity and its corresponding mz for each bin
# (max_intensity, mz_value)
bins = fill((0.0, 0.0), n_points)
for i in eachindex(mz)
# Determine the bin for the current point
# Bin indices are 1-based
bin_index = min(n_points, floor(Int, (mz[i] - mz_min) / bin_width) + 1)
# If the current point's intensity is higher than what's in the bin, replace it
if intensity[i] > bins[bin_index][1]
bins[bin_index] = (intensity[i], mz[i])
end
end
# Filter out empty bins and separate the mz and intensity values
final_mz = [b[2] for b in bins if b[1] > 0.0]
final_intensity = [b[1] for b in bins if b[1] > 0.0]
return final_mz, final_intensity
end
# ============================================================================
#
#
@@ -678,3 +796,97 @@ function plot_slices(slices, names, masses, output_dir; stage_name, bins=256, dp
end
return fig
end
"""
save_bitmap(name::String, pixMap::Matrix{UInt8}, colorTable::Vector{UInt32})
Saves an 8-bit indexed image as a BMP file.
This is a modernized version of `SaveBitmapCl`.
"""
function save_bitmap(name::String, pixMap::Matrix{UInt8}, colorTable::Vector{UInt32})
# Get image dimensions
height, width = size(pixMap)
# Normalize pixel values to stretch contrast, as in the original SaveBitmapCl
minVal, maxVal = extrema(pixMap)
if maxVal > minVal
pixMap = round.(UInt8, 255 * (pixMap .- minVal) ./ (maxVal - minVal))
end
# Compute row padding (each row must be a multiple of 4 bytes)
padding = (4 - (width % 4)) % 4
# BMP color table must have 256 entries for 8-bit images
fullColorTable = Vector{UInt32}(undef, 256)
if length(colorTable) <= 256
fullColorTable[1:length(colorTable)] .= colorTable
fullColorTable[length(colorTable)+1:end] .= 0
else
fullColorTable .= colorTable[1:256]
end
# Compute file dimensions
offset = 14 + 40 + (256 * 4) # 14(file) + 40(info) + 1024(palette) = 1078
imgBytes = height * (width + padding)
fileSize = offset + imgBytes
open(name, "w") do stream
# === File Header (14 bytes) ===
write(stream, UInt16(0x4D42)) # "BM"
write(stream, UInt32(fileSize))
write(stream, UInt16(0)) # Reserved
write(stream, UInt16(0)) # Reserved
write(stream, UInt32(offset))
# === Info Header (40 bytes) ===
write(stream, UInt32(40)) # Info header size
write(stream, Int32(width))
write(stream, Int32(height)) # Positive for bottom-up storage
write(stream, UInt16(1)) # Number of color planes
write(stream, UInt16(8)) # Bits per pixel
write(stream, UInt32(0)) # Compression (BI_RGB)
write(stream, UInt32(imgBytes))
write(stream, Int32(2835)) # Pels per meter X (~72 DPI)
write(stream, Int32(2835)) # Pels per meter Y (~72 DPI)
write(stream, UInt32(256)) # Colors in color table
write(stream, UInt32(0)) # Important colors (0 = all)
# === Color Table ===
write(stream, fullColorTable)
# === Image Pixels (written bottom-up) ===
row_buffer = Vector{UInt8}(undef, width + padding)
row_buffer[width+1:end] .= 0 # pre-fill padding bytes
for i in height:-1:1
row_data = @view pixMap[i, :]
row_buffer[1:width] = row_data
write(stream, row_buffer)
end
end
end
# ********************************************************************
# Viridis color palette (256 colors)
# ********************************************************************
"""
generate_palette(colorscheme, n_colors=256)
Generates a BMP-compatible UInt32 color palette from a ColorScheme.
"""
function generate_palette(colorscheme, n_colors=256)
palette = Vector{UInt32}(undef, n_colors)
colors = get(colorscheme, range(0, 1, length=n_colors))
for i in 1:n_colors
c = colors[i]
r = round(UInt8, c.r * 255)
g = round(UInt8, c.g * 255)
b = round(UInt8, c.b * 255)
# BMP color table format is 0x00RRGGBB, written little-endian becomes BB GG RR 00
palette[i] = (UInt32(r) << 16) | (UInt32(g) << 8) | UInt32(b)
end
return palette
end
const ViridisPalette = generate_palette(ColorSchemes.viridis)