282 lines
12 KiB
Julia
282 lines
12 KiB
Julia
using Pkg
|
|
script_dir = @__DIR__
|
|
project_root = joinpath(script_dir, "..", "..")
|
|
|
|
Pkg.activate(joinpath(project_root, "environment"))
|
|
|
|
push!(LOAD_PATH, joinpath(project_root, "src"))
|
|
include(joinpath(project_root, "src", "MSI_src.jl"))
|
|
using .MSI_src
|
|
using Statistics, Images, Interpolations, BenchmarkTools
|
|
import julia_mzML_imzML
|
|
|
|
data_dir = length(ARGS) >= 1 ? ARGS[1] : joinpath(project_root, "data")
|
|
dataset_name = length(ARGS) >= 2 ? ARGS[2] : splitdir(data_dir)[2]
|
|
|
|
# Find first .imzML file
|
|
imzml_files = filter(f -> endswith(lowercase(f), ".imzml"), readdir(data_dir))
|
|
if isempty(imzml_files)
|
|
error("No .imzML file found in $data_dir")
|
|
end
|
|
data_path = joinpath(data_dir, imzml_files[1])
|
|
|
|
# Find ROI mask
|
|
mask_path = joinpath(data_dir, "region_of_interest.png")
|
|
if !isfile(mask_path)
|
|
alt_masks = filter(f -> endswith(lowercase(f), ".png") && occursin(r"roi|mask|region", lowercase(f)), readdir(data_dir))
|
|
mask_path = isempty(alt_masks) ? "" : joinpath(data_dir, alt_masks[1])
|
|
end
|
|
|
|
output_folder = joinpath(project_root, "outputs", "ion_images", dataset_name)
|
|
viridis_folder = joinpath(project_root, "outputs", "ion_images_viridis", dataset_name)
|
|
tolerance = 0.05
|
|
mkpath(output_folder)
|
|
mkpath(viridis_folder)
|
|
|
|
println("--- JULIA BATCH ENGINE: $dataset_name ---")
|
|
println("Data: $data_path")
|
|
println("Mask: $(isempty(mask_path) ? "none" : mask_path)")
|
|
println("Output (grayscale): $output_folder")
|
|
println("Output (viridis): $viridis_folder")
|
|
|
|
println("--- JULIA BATCH ENGINE ---")
|
|
|
|
# Apply Julia's native ViridisPalette (256-entry, 0xRRGGBB) to a 0..255 intensity map.
|
|
function apply_viridis(intensity_matrix::AbstractMatrix{Float32})
|
|
palette = julia_mzML_imzML.ViridisPalette
|
|
h, w = size(intensity_matrix)
|
|
rgb = Matrix{RGB{N0f8}}(undef, h, w)
|
|
@inbounds for j in 1:w, i in 1:h
|
|
v = intensity_matrix[i, j]
|
|
v = isfinite(v) ? v : 0.0f0
|
|
idx = clamp(round(Int, v) + 1, 1, 256)
|
|
c = palette[idx]
|
|
r = Float64((c >> 16) & 0xFF) / 255.0
|
|
g = Float64((c >> 8) & 0xFF) / 255.0
|
|
b = Float64(c & 0xFF) / 255.0
|
|
rgb[i, j] = RGB{N0f8}(r, g, b)
|
|
end
|
|
return rgb
|
|
end
|
|
|
|
function run_production_pipeline()
|
|
println("Step 1: Ingesting Data...")
|
|
data = OpenMSIData(data_path)
|
|
|
|
orig_height = data.image_dims[2]
|
|
orig_width = data.image_dims[1]
|
|
target_size = (256, 256)
|
|
if orig_height <= 256 && orig_width <= 256
|
|
final_img_size = (orig_height, orig_width)
|
|
println(" [Notice] Original image is smaller than or equal to 256x256. Keeping original size: ", final_img_size)
|
|
else
|
|
scale = min(256 / orig_height, 256 / orig_width)
|
|
final_img_size = (max(1, round(Int, orig_height * scale)), max(1, round(Int, orig_width * scale)))
|
|
println(" [Notice] Resizing from ($orig_height, $orig_width) to $final_img_size")
|
|
end
|
|
|
|
println("Step 2: Checking Dataset Precomputed Boundaries...")
|
|
MSI_src.precompute_analytics(data)
|
|
|
|
println("Step 3: Calculating Average Spectrum...")
|
|
# MSI_BIN_AVG (Da) bin width: for high-resolution ToF datasets the per-pixel m/z
|
|
# values are essentially unique doubles, so an exact-key average spectrum never
|
|
# accumulates signal across pixels and starves peak picking (e.g. Mouse_Liver got
|
|
# only 23 ions). Binning onto a fixed grid (as in the 3-way benchmark) fixes that.
|
|
bin_avg = get(ENV, "MSI_BIN_AVG", "")
|
|
if !isempty(bin_avg)
|
|
bin_step = parse(Float64, bin_avg)
|
|
lo = data.global_min_mz[] > 0.0 ? data.global_min_mz[] : 50.0
|
|
hi = data.global_max_mz[] > 0.0 ? data.global_max_mz[] : 1000.0
|
|
nb = max(1, Int(floor((hi - lo) / bin_step)) + 1)
|
|
mz_axis_bin = collect(lo .+ (0:nb-1) .* bin_step)
|
|
avg_int_bin = zeros(nb)
|
|
npx_bin = size(data.imzml_data, 2)
|
|
for i in 1:npx_bin
|
|
pm = data.imzml_data[3, i]
|
|
pi = data.imzml_data[4, i]
|
|
idx = floor.(Int, (pm .- lo) ./ bin_step) .+ 1
|
|
for j in eachindex(pm)
|
|
k = idx[j]
|
|
if k >= 1 && k <= nb
|
|
avg_int_bin[k] += pi[j]
|
|
end
|
|
end
|
|
end
|
|
mzs = mz_axis_bin
|
|
avg_ints = avg_int_bin
|
|
println(" Binned average spectrum: $bin_step Da grid over $(round(lo,digits=2))-$(round(hi,digits=2)) m/z ($nb channels)")
|
|
else
|
|
mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=mask_path)
|
|
end
|
|
|
|
println(" True Dataset Min m/z: ", round(minimum(mzs), digits=2))
|
|
println(" True Dataset Max m/z: ", round(maximum(mzs), digits=2))
|
|
|
|
println("Step 4: Peak Picking...")
|
|
min_vis_mz = data.global_min_mz[] > 0.0 ? data.global_min_mz[] : 50.0
|
|
max_vis_mz = data.global_max_mz[] > 0.0 ? data.global_max_mz[] : 1000.0
|
|
|
|
# Configurable peak-picking policy (via env vars so older datasets stay at 2%).
|
|
# MSI_PEAK_FRAC - threshold as fraction of base-peak max (default 0.02)
|
|
# MSI_PEAK_MIN_MZ_GAP - minimum m/z separation between distinct ions; 0 disables
|
|
# (e.g. 0.25 for high-dynamic-range ToF spectra)
|
|
peak_frac = get(ENV, "MSI_PEAK_FRAC", "0.02")
|
|
peak_frac = parse(Float64, peak_frac)
|
|
peak_gap = get(ENV, "MSI_PEAK_MIN_MZ_GAP", "0.0")
|
|
peak_gap = parse(Float64, peak_gap)
|
|
println(" Peak policy: threshold = $peak_frac of base max, min m/z separation = $peak_gap")
|
|
|
|
threshold = maximum(avg_ints) * peak_frac
|
|
peak_indices = findall(x -> x > threshold, avg_ints)
|
|
println(" Raw candidates above threshold: ", length(peak_indices))
|
|
|
|
in_range = Int[]
|
|
for idx in peak_indices
|
|
mz_val = mzs[idx]
|
|
if mz_val >= min_vis_mz && mz_val <= max_vis_mz
|
|
push!(in_range, idx)
|
|
end
|
|
end
|
|
|
|
if peak_gap > 0.0 && !isempty(in_range)
|
|
# Select local maxima first, then greedily take highest-intensity peaks
|
|
# that are at least `peak_gap` m/z apart (collapse adjacent samples of the
|
|
# same wide peak into a single ion). Used for dense/high-dynamic-range data.
|
|
in_range_set = Set(in_range)
|
|
local_max = Int[]
|
|
for i in in_range
|
|
above_lo = i == 1 || avg_ints[i] >= avg_ints[i - 1] || !(i - 1 in in_range_set)
|
|
above_hi = i == length(avg_ints) || avg_ints[i] >= avg_ints[i + 1] || !(i + 1 in in_range_set)
|
|
if above_lo && above_hi
|
|
push!(local_max, i)
|
|
end
|
|
end
|
|
if isempty(local_max)
|
|
local_max = copy(in_range)
|
|
end
|
|
order = sortperm(local_max, by = i -> avg_ints[i], rev = true)
|
|
selected = Int[]
|
|
for i in order
|
|
mz_i = mzs[local_max[i]]
|
|
keep = true
|
|
for j in selected
|
|
if abs(mz_i - mzs[j]) < peak_gap
|
|
keep = false
|
|
break
|
|
end
|
|
end
|
|
if keep
|
|
push!(selected, local_max[i])
|
|
end
|
|
end
|
|
in_range = selected
|
|
end
|
|
|
|
target_masses = sort([mzs[i] for i in in_range])
|
|
|
|
n_collapsed = length(peak_indices) - length(target_masses)
|
|
println(" Kept $(length(target_masses)) peaks after threshold/range/separation filtering ($n_collapsed collapsed).")
|
|
|
|
total_ions = length(target_masses)
|
|
println("Found $total_ions ions within training range ($(min_vis_mz) to $(max_vis_mz) m/z) above threshold.")
|
|
if total_ions == 0
|
|
println("Warning: No peaks met the criteria. Check your threshold or mask alignment.")
|
|
return
|
|
end
|
|
|
|
println("Step 5+6: Batched Ion Extraction, TrIQ Normalization & 256x256 Zero-Padding...")
|
|
mask_matrix = MSI_src.load_and_prepare_mask(mask_path, (data.image_dims[1], data.image_dims[2]))
|
|
exported_count = Threads.Atomic{Int}(0)
|
|
|
|
target_size = (256, 256)
|
|
|
|
# Memory-bounded batching: only `batch_size` full-resolution slices are resident
|
|
# in RAM at once, instead of materializing every ion image simultaneously. This
|
|
# keeps peak memory flat and independent of the total number of detected peaks
|
|
# (the cause of OOM kills on large datasets such as Mouse_Stomach).
|
|
batch_size = parse(Int, get(ENV, "MSI_ION_BATCH", "32"))
|
|
total_batches = cld(length(target_masses), batch_size)
|
|
|
|
for (bi, start_idx) in enumerate(1:batch_size:length(target_masses))
|
|
end_idx = min(start_idx + batch_size - 1, length(target_masses))
|
|
batch = target_masses[start_idx:end_idx]
|
|
|
|
slices = Dict{Float64, Matrix{Float64}}()
|
|
for mz_val in batch
|
|
slices[mz_val] = MSI_src.get_mz_slice(data, mz_val, tolerance; mask_path=mask_path)
|
|
end
|
|
|
|
Threads.@threads for mz_val in batch
|
|
slice = get(slices, mz_val, nothing)
|
|
if slice === nothing continue end
|
|
# Blank/off-tissue pixels are stored as NaN in the imzML; TrIQ's
|
|
# GetOutlierThres(min(slice)) would then hit floor(Int, NaN) and abort.
|
|
# Replace non-finite intensities with 0 before quantization.
|
|
if !all(isfinite, slice)
|
|
slice = ifelse.(isfinite.(slice), slice, 0.0)
|
|
end
|
|
if all(iszero, slice) continue end
|
|
|
|
try
|
|
slice_quant, _ = MSI_src.TrIQ(slice, 256, 0.98, mask_matrix=mask_matrix)
|
|
slice_quant = permutedims(slice_quant)
|
|
|
|
h_orig, w_orig = size(slice_quant, 1), size(slice_quant, 2)
|
|
|
|
padded_matrix = if h_orig > 256 || w_orig > 256
|
|
scale = min(256 / h_orig, 256 / w_orig)
|
|
new_h = round(Int, h_orig * scale)
|
|
new_w = round(Int, w_orig * scale)
|
|
resized = imresize(slice_quant, (new_h, new_w))
|
|
m = zeros(Float32, target_size)
|
|
oh = div(256 - new_h, 2) + 1
|
|
ow = div(256 - new_w, 2) + 1
|
|
m[oh:oh+new_h-1, ow:ow+new_w-1] .= resized
|
|
m
|
|
else
|
|
m = zeros(Float32, target_size)
|
|
offset_y = div(256 - h_orig, 2) + 1
|
|
offset_x = div(256 - w_orig, 2) + 1
|
|
m[offset_y:offset_y+h_orig-1, offset_x:offset_x+w_orig-1] .= slice_quant
|
|
m
|
|
end
|
|
|
|
if !all(isfinite, padded_matrix)
|
|
padded_matrix = ifelse.(isfinite.(padded_matrix), padded_matrix, 0.0f0)
|
|
end
|
|
|
|
normalized_gray = padded_matrix ./ 255.0
|
|
|
|
filename = "ion_$(round(mz_val, digits=5)).png"
|
|
save(joinpath(output_folder, filename), Gray.(normalized_gray))
|
|
save(joinpath(viridis_folder, filename), apply_viridis(padded_matrix))
|
|
|
|
Threads.atomic_add!(exported_count, 1)
|
|
catch err
|
|
# A single ion whose intensity distribution degenerates (e.g. every
|
|
# nonzero pixel identical -> TrIQ bounds collapse) must not abort the
|
|
# whole extraction; log and skip it.
|
|
lo = minimum(slice); hi = maximum(slice)
|
|
println(" [skip] ion m/z $mz_val: $(sprint(showerror, err)) (slice min=$lo max=$hi nz=$(count(!iszero, slice)))")
|
|
dbg = get(ENV, "MSI_DUMP_FAILS", "")
|
|
if !isempty(dbg) && ispath(dbg)
|
|
fn = joinpath(dbg, "fail_$(round(mz_val, digits=3)).bin")
|
|
open(fn, "w") do f
|
|
write(f, size(slice, 1)); write(f, size(slice, 2)); write(f, slice)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
empty!(slices)
|
|
GC.gc(false)
|
|
println(" batch $bi/$total_batches done (ions $start_idx..$end_idx of $(length(target_masses)); exported $(exported_count[]) so far)")
|
|
end
|
|
|
|
println("\nSuccess: $(exported_count[]) target image maps exported to $output_folder.")
|
|
println("Success: $(exported_count[]) viridis maps exported to $viridis_folder.")
|
|
end
|
|
|
|
@time run_production_pipeline()
|