Fixed source errors regarding missplaced package loading, concurrency on pools across the src, parser errors, and general Microsoft and Mac compatibility errors that are pending revision from users

This commit is contained in:
Pixelguy14
2026-11-17 11:26:39 -06:00
parent 89de5a56e0
commit bc71b9ce94
34 changed files with 2124 additions and 654 deletions
BIN
View File
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
install.packages(c("XML", "readMzXmlData", "MALDIquantForeign"))
q()
+2 -1
View File
@@ -14,7 +14,8 @@ jobs:
fail-fast: false
matrix:
version:
- '1.10'
- '1.11'
- '1.12'
os:
- ubuntu-latest
- windows-latest
+2 -4
View File
@@ -15,7 +15,6 @@ ContinuousWavelets = "96eb917e-2868-4417-9cb6-27e7ff17528f"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
GLMakie = "e9467ef8-e4e7-5192-8a1a-b1aee30e663a"
Genie = "c43c736e-a2d1-11e8-161f-af95117fbd1e"
GenieFramework = "a59fdf5c-6bf0-4f5d-949c-a137c9e2f353"
HistogramThresholding = "2c695a8d-9458-5d45-9878-1b8a99cf7853"
@@ -48,7 +47,6 @@ SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
StipplePlotly = "ec984513-233d-481d-95b0-a3b58b97af2b"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[compat]
@@ -63,7 +61,6 @@ ContinuousWavelets = "1.1"
DataFrames = "1.7"
Dates = "1.11"
FileIO = "1.17"
GLMakie = "0.11"
Genie = "5.31"
GenieFramework = "2.8"
HistogramThresholding = "0.3"
@@ -84,6 +81,7 @@ Loess = "0.6"
Mmap = "1.11"
NativeFileDialog = "0.2"
NaturalSort = "1.0"
PackageCompiler = "2"
Parameters = "0.12"
PlotlyBase = "0.8"
Printf = "1.11"
@@ -99,7 +97,7 @@ UUIDs = "1.11"
julia = "1.11, 1.12"
[extras]
Test = "8dfed614-e60c-5e00-aba5-a33c2d43236e"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[targets]
test = ["Test"]
+23 -4
View File
@@ -3,10 +3,11 @@
https://codeberg.org/LabABI/JuliaMSI
## Local Installation
1. Make sure you have Julia installed and at least Julia version 1.6 but not higher than 1.11, If not, follow the next installation guide which contains the latest files and instructions for [juliaup](https://github.com/JuliaLang/juliaup) (recommended) alternatively, you can follow the official Julia installation instructions at [julia](https://julialang.org/downloads/platform/).
1. Make sure you have Julia installed. JuliaMSI supports **Julia 1.11 and 1.12**. If Julia is not installed, follow the [juliaup](https://github.com/JuliaLang/juliaup) guide (recommended), or the official Julia installation instructions at [julia](https://julialang.org/downloads/platform/).
2. Download and decompress the following repository (You can download the repository from [download](https://codeberg.org/LabABI/JuliaMSI/archive/main.zip) or locate the option manually at the top right of the page, in the box with [•••] (More operations). For a more advanced method using Git, use this link: https://codeberg.org/LabABI/JuliaMSI.git).
3. Ensure that you have decompressed the ZIP file and know the working directory where it is located (the folder on your computer where you saved the JuliaMSI files).
4. Julia Version 1.11 is required. You might need to downgrade your whole Julia installation to support it.
4. Julia version 1.11 or 1.12 is required.
5. Ensure that the project's `public/` directory is writable. JuliaMSI writes generated images, masks, and `registry.json` there and will stop with a clear error if it cannot.
## Load User Interface
1. Set the working directory to where JuliaMSI is located (the specific location of the folder on your computer where you decompressed the ZIP) in your terminal.<br>
@@ -21,11 +22,21 @@ https://codeberg.org/LabABI/JuliaMSI
```
Example of a correct route:<br>
~/Downloads/JuliaMSI-main/juliamsi
2. Without entering the Julia environment, launch the project in your terminal with the following command (which works for all operating systems):
2. Install/verify the Julia dependencies once (safe to repeat):
```bash
julia --project=. -e 'using Pkg; Pkg.instantiate()'
```
3. Without entering the Julia environment, launch the project in your terminal with the following command (which works for all operating systems):
```bash
julia --threads auto --project=. start_MSI_GUI.jl
```
3. After the script has finished loading, you can open a [page](http://127.0.0.1:1481/) in your browser with the web app running.
4. After the script has finished loading, you can open a [page](http://127.0.0.1:1481/) in your browser with the web app running.
The GUI starts in production mode by default. For live-reload development use:
```bash
JULIA_MSI_DEV=1 julia --threads auto --project=. start_MSI_GUI.jl
```
Set `JULIA_MSI_VERBOSE=1` to see the otherwise-filtered HTML parser warnings.
Additional notes:<br>
After the first boot, when the packages are initialized on your computer, subsequent uses of the app should take less time to load.<br>
@@ -84,6 +95,14 @@ JuliaMSI is published under the terms of the MIT License.
Robert Winkler. (2023). mzML mass spectrometry and imzML mass spectrometry imaging test data [Data set].
Zenodo. <https://doi.org/10.5281/zenodo.10084132>
## Plotting API note
`plot_slice`, `plot_slices`, and `generate_colorbar_image` are GUI/plotting helpers.
They now live in the GUI layer (`julia_imzML_visual.jl`) so that `using MSI_src`
does not load CairoMakie for headless/console use. They are not exported from
`MSI_src`; calling `MSI_src.plot_slice(...)` returns an actionable migration
error instead of silently failing with `UndefVarError`.
## User Guides
For a general guide on how to use the JuliaMSI platform, please refer to the [JuliaMSI Main Guide](JuliaMSI_MainGuide.md).
+92 -53
View File
@@ -23,31 +23,37 @@ using Dates
using Base.Threads
# Bring MSIData into App module's scope
using .MSI_src: MSIData, OpenMSIData, process_spectrum, IterateSpectra, ImzMLSource, _iterate_spectra_fast, MzMLSource, find_mass, ViridisPalette, get_mz_slice, get_multiple_mz_slices, quantize_intensity, save_bitmap, median_filter, save_bitmap, downsample_spectrum, TrIQ, precompute_analytics, ImportMzmlFile, generate_colorbar_image, load_and_prepare_mask, set_global_mz_range!, main_precalculation, MutableSpectrum, execute_full_preprocessing
using .MSI_src: MSIData, OpenMSIData, process_spectrum, IterateSpectra, ImzMLSource, _iterate_spectra_fast, MzMLSource, find_mass, ViridisPalette, get_mz_slice, get_multiple_mz_slices, quantize_intensity, save_bitmap, median_filter, save_bitmap, downsample_spectrum, TrIQ, precompute_analytics, ImportMzmlFile, load_and_prepare_mask, set_global_mz_range!, main_precalculation, MutableSpectrum, execute_full_preprocessing, PUBLIC_DIR, DEFAULT_REGISTRY_PATH, ensure_public_dir
if !@isdefined(increment_image)
include("./julia_imzML_visual.jl")
end
const global_msi_data = Ref{Union{MSIData, Nothing}}(nothing)
# Fail early with an actionable message if generated assets cannot be written.
ensure_public_dir()
if !@isdefined(global_msi_data)
const global_msi_data = Ref{Union{MSIData, Nothing}}(nothing)
end
# --- Memory Validation Logging ---
if get(ENV, "GENIE_ENV", "dev") != "prod"
function get_rss_mb()
if !Sys.islinux()
return 0.0
end
try
pid = getpid()
cmd = `ps -p $pid -o rss=`
rss_kb_str = read(cmd, String)
if Sys.iswindows()
out = read(`powershell -NoProfile -Command "(Get-Process -Id $pid).WorkingSet64"`, String)
return round(parse(Int, strip(out)) / (1024^2), digits=2)
elseif Sys.islinux() || Sys.isapple()
rss_kb_str = read(`ps -p $pid -o rss=`, String)
rss_kb = parse(Int, strip(rss_kb_str))
return round(rss_kb / 1024, digits=2)
catch e
@warn "Could not get RSS via `ps` command. Error: $e"
return 0.0
end
catch e
@debug "Could not determine RSS" exception=e
end
return 0.0
end
function log_memory_usage(context::String, msi_data_val)
@@ -58,7 +64,8 @@ if get(ENV, "GENIE_ENV", "dev") != "prod"
msi_data_size_mb = round(Base.summarysize(msi_data_val) / (1024^2), digits=2)
end
gc_time_s = round(GC.time(), digits=3)
# GC.time() is reported in nanoseconds in current Julia versions.
gc_time_s = round(GC.time() / 1e9, digits=3)
println("--- MEMORY LOG [$(context)] ---")
println(" Timestamp: $(now())")
@@ -203,7 +210,13 @@ end
# gigabytes of orphaned session files in /tmp/jl_XXXXXX, exhausting disk space.
# For a single-user desktop application, session persistence is unnecessary.
Stipple.enable_model_storage(false)
Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage is disabled") during layout render
# Prevent ErrorException("Model storage is disabled") during layout render.
# Return an EMPTY <meta name="sesstoken" content=""> tag (instead of the empty
# string) so the browser sends `sesstoken: ""` rather than `sesstoken: null`.
# Stipple's watcher handler guards with `!isempty(payload["sesstoken"])`, and
# `isempty(nothing)` falls back to `iterate(nothing)`, which throws the noisy
# `MethodError(iterate, (nothing,))` seen on every browser interaction.
Core.eval(Stipple, :(sesstoken() = meta(name = "sesstoken", content = "")))
# Reactive code to make the UI interactive
@app begin
@@ -399,6 +412,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@in import_params_btn = false # Import parameters from file
@in save_feature_matrix_btn = false # Save feature matrix results
@in reset_session_btn = false # Deep session reset
@in shutdown = false # Gracefully stop the JuliaMSI server
# Preprocessing results
@in selected_spectrum_id_for_plot = 1
@@ -463,7 +477,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@in refetch_folders = false
@in available_folders = String[]
@in image_available_folders = String[]
@out registry_path = abspath(joinpath(@__DIR__, "public", "registry.json"))
@out registry_path = DEFAULT_REGISTRY_PATH
# Folder selection state
@in selected_folder_main = ""
@@ -492,10 +506,10 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
# Image file management
@out text_nmass="" # For specific mass charge image creation
@in msi_bmp=sort(filter(filename -> startswith(filename, "MSI_") && endswith(filename, ".bmp"), readdir("public")),lt=natural)
@in col_msi_png=sort(filter(filename -> startswith(filename, "colorbar_MSI_") && endswith(filename, ".png"), readdir("public")),lt=natural)
@in triq_bmp=sort(filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir("public")),lt=natural)
@in col_triq_png=sort(filter(filename -> startswith(filename, "colorbar_TrIQ_") && endswith(filename, ".png"), readdir("public")),lt=natural)
@in msi_bmp=sort(filter(filename -> startswith(filename, "MSI_") && endswith(filename, ".bmp"), readdir(PUBLIC_DIR)),lt=natural)
@in col_msi_png=sort(filter(filename -> startswith(filename, "colorbar_MSI_") && endswith(filename, ".png"), readdir(PUBLIC_DIR)),lt=natural)
@in triq_bmp=sort(filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir(PUBLIC_DIR)),lt=natural)
@in col_triq_png=sort(filter(filename -> startswith(filename, "colorbar_TrIQ_") && endswith(filename, ".png"), readdir(PUBLIC_DIR)),lt=natural)
# Current image display
@out current_msi=""
@@ -667,6 +681,23 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
# Reactive handlers watch a variable and execute a block of code when its value changes
# The onbutton handler will set the variable to false after the block is executed
# Gracefully stop the server when the "turn off" button is pressed.
# Run the shutdown on a short delay so the websocket response reaches the
# browser before the process exits; `exit(0)` runs Julia's atexit hooks,
# which release the mmap'd MSI data and close open files cleanly.
@onbutton shutdown begin
msg = "Shutting down JuliaMSI..."
@info "Shutdown requested from the GUI"
@async begin
sleep(1)
try
Genie.down!()
catch
end
exit(0)
end
end
@onbutton reset_session_btn begin
is_processing = true
push!(__model__)
@@ -688,10 +719,10 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
end
# 3. Reset file lists (these will be repopulated by normal operation)
msi_bmp = sort(filter(filename -> startswith(filename, "MSI_") && endswith(filename, ".bmp"), readdir("public")), lt=natural)
col_msi_png = sort(filter(filename -> startswith(filename, "colorbar_MSI_") && endswith(filename, ".png"), readdir("public")), lt=natural)
triq_bmp = sort(filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir("public")), lt=natural)
col_triq_png = sort(filter(filename -> startswith(filename, "colorbar_TrIQ_") && endswith(filename, ".png"), readdir("public")), lt=natural)
msi_bmp = sort(filter(filename -> startswith(filename, "MSI_") && endswith(filename, ".bmp"), readdir(PUBLIC_DIR)), lt=natural)
col_msi_png = sort(filter(filename -> startswith(filename, "colorbar_MSI_") && endswith(filename, ".png"), readdir(PUBLIC_DIR)), lt=natural)
triq_bmp = sort(filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir(PUBLIC_DIR)), lt=natural)
col_triq_png = sort(filter(filename -> startswith(filename, "colorbar_TrIQ_") && endswith(filename, ".png"), readdir(PUBLIC_DIR)), lt=natural)
# 4. Clear any cached images/plots
imgInt = "/.bmp"
@@ -769,7 +800,9 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
existing_entry = get(registry, dataset_name, nothing)
# --- Fast Load Path ---
is_same_file = (existing_entry !== nothing && existing_entry["source_path"] == picked_route)
is_same_file = (existing_entry !== nothing &&
normalize_source_path(get(existing_entry, "source_path", "")) ==
normalize_source_path(picked_route))
if is_same_file && !isempty(get(existing_entry, "metadata", Dict()))
msg = "Fast loading pre-processed file: $(dataset_name)"
println(msg)
@@ -799,16 +832,11 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
# --- Full Load Path ---
local local_full_route
if endswith(picked_route, r"imzml"i)
local_full_route = replace(picked_route, r"\.imzml$"i => ".imzML")
if picked_route != local_full_route
mv(picked_route, local_full_route, force=true)
end
else
# Never rename the user's source data. Extension matching is
# case-insensitive in OpenMSIData/load_imzml_lazy, and renaming
# fails on read-only files, network shares, and Windows files that
# are open in another program.
local_full_route = picked_route
end
full_route = local_full_route
sTime = time()
@@ -1014,7 +1042,8 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
w, h = loaded_data.image_dims
imgWidth, imgHeight = w > 0 ? (w, h) : (500, 500)
update_registry(registry_path, dataset_name, local_full_route, summary_stats, is_imzML)
saved = update_registry(registry_path, dataset_name, local_full_route, summary_stats, is_imzML)
saved || @warn "Could not persist the registry entry for this dataset" dataset=dataset_name
# Update folder lists in UI
registry = load_registry(registry_path)
@@ -1885,7 +1914,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
# Save feature matrix if binning was performed
if feature_matrix_result !== nothing
output_dir = joinpath("public", selected_folder_main, "preprocessing_results")
output_dir = joinpath(PUBLIC_DIR, selected_folder_main, "preprocessing_results")
mkpath(output_dir)
save_feature_matrix(feature_matrix_result, bin_info_result, output_dir)
msg = "Pipeline completed successfully. Feature matrix saved."
@@ -2518,7 +2547,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
# Update UI to display the last generated image
if !isempty(newly_created_folders)
timestamp = string(time_ns())
folder_path = joinpath("public", selected_folder_main)
folder_path = joinpath(PUBLIC_DIR, selected_folder_main)
if current_triq_enabled
triq_files = filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir(folder_path))
@@ -2960,7 +2989,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgMinus begin
if isempty(selected_folder_main) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_main)
folder_path = joinpath(PUBLIC_DIR, selected_folder_main)
# Check if folder exists to prevent errors
if !isdir(folder_path) return end
@@ -2982,7 +3011,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgPlus begin
if isempty(selected_folder_main) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_main)
folder_path = joinpath(PUBLIC_DIR, selected_folder_main)
if !isdir(folder_path) return end
msi_bmp=sort(filter(filename -> startswith(filename, "MSI_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3004,7 +3033,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgMinusT begin
if isempty(selected_folder_main) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_main)
folder_path = joinpath(PUBLIC_DIR, selected_folder_main)
if !isdir(folder_path) return end
triq_bmp=sort(filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3025,7 +3054,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgPlusT begin
if isempty(selected_folder_main) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_main)
folder_path = joinpath(PUBLIC_DIR, selected_folder_main)
if !isdir(folder_path) return end
triq_bmp=sort(filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3048,7 +3077,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgMinusCompLeft begin
if isempty(selected_folder_compare_left) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_compare_left)
folder_path = joinpath(PUBLIC_DIR, selected_folder_compare_left)
if !isdir(folder_path) return end
msi_bmp=sort(filter(filename -> startswith(filename, "MSI_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3070,7 +3099,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgPlusCompLeft begin
if isempty(selected_folder_compare_left) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_compare_left)
folder_path = joinpath(PUBLIC_DIR, selected_folder_compare_left)
if !isdir(folder_path) return end
msi_bmp=sort(filter(filename -> startswith(filename, "MSI_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3092,7 +3121,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgMinusTCompLeft begin
if isempty(selected_folder_compare_left) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_compare_left)
folder_path = joinpath(PUBLIC_DIR, selected_folder_compare_left)
if !isdir(folder_path) return end
triq_bmp=sort(filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3114,7 +3143,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgPlusTCompLeft begin
if isempty(selected_folder_compare_left) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_compare_left)
folder_path = joinpath(PUBLIC_DIR, selected_folder_compare_left)
if !isdir(folder_path) return end
triq_bmp=sort(filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3136,7 +3165,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgMinusCompRight begin
if isempty(selected_folder_compare_right) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_compare_right)
folder_path = joinpath(PUBLIC_DIR, selected_folder_compare_right)
if !isdir(folder_path) return end
msi_bmp=sort(filter(filename -> startswith(filename, "MSI_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3158,7 +3187,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgPlusCompRight begin
if isempty(selected_folder_compare_right) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_compare_right)
folder_path = joinpath(PUBLIC_DIR, selected_folder_compare_right)
if !isdir(folder_path) return end
msi_bmp=sort(filter(filename -> startswith(filename, "MSI_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3180,7 +3209,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgMinusTCompRight begin
if isempty(selected_folder_compare_right) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_compare_right)
folder_path = joinpath(PUBLIC_DIR, selected_folder_compare_right)
if !isdir(folder_path) return end
triq_bmp=sort(filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3202,7 +3231,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onbutton imgPlusTCompRight begin
if isempty(selected_folder_compare_right) return end
timestamp=string(time_ns())
folder_path = joinpath("public", selected_folder_compare_right)
folder_path = joinpath(PUBLIC_DIR, selected_folder_compare_right)
if !isdir(folder_path) return end
triq_bmp=sort(filter(filename -> startswith(filename, "TrIQ_") && endswith(filename, ".bmp"), readdir(folder_path)),lt=natural)
@@ -3227,7 +3256,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
# This handler is now only for updating the UI images when the folder changes.
if !isempty(selected_folder_main)
folder_path = joinpath("public", selected_folder_main)
folder_path = joinpath(PUBLIC_DIR, selected_folder_main)
if !isdir(folder_path)
imgInt = ""
colorbar = ""
@@ -3305,7 +3334,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onchange selected_folder_compare_left begin
if !isempty(selected_folder_compare_left)
timestamp = string(time_ns())
folder_path = joinpath("public", selected_folder_compare_left)
folder_path = joinpath(PUBLIC_DIR, selected_folder_compare_left)
if !isdir(folder_path)
imgIntCompLeft, colorbarCompLeft, imgIntTCompLeft, colorbarTCompLeft = "", "", "", ""
@@ -3360,7 +3389,7 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
@onchange selected_folder_compare_right begin
if !isempty(selected_folder_compare_right)
timestamp = string(time_ns())
folder_path = joinpath("public", selected_folder_compare_right)
folder_path = joinpath(PUBLIC_DIR, selected_folder_compare_right)
if !isdir(folder_path)
imgIntCompRight, colorbarCompRight, imgIntTCompRight, colorbarTCompRight = "", "", "", ""
msgimgCompRight, msgtriqCompRight = "Folder not found.", "Folder not found."
@@ -3820,13 +3849,22 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
msg = "Pre-compilation finished."
try
msg = "Synchronizing registry with filesystem on backend init..."
reg_path = abspath(joinpath(@__DIR__, "public", "registry.json"))
reg_path = DEFAULT_REGISTRY_PATH
registry = isfile(reg_path) ? load_registry(reg_path) : Dict{String, Any}()
public_dirs = isdir("public") ? readdir("public") : []
# `ensure_public_dir()` has already verified that this directory
# exists and is writable. A read failure here must not be treated
# as "all folders were deleted".
public_dirs = try
readdir(PUBLIC_DIR)
catch e
error("JuliaMSI cannot read its public directory at \"$PUBLIC_DIR\". " *
"Refusing to synchronize the registry because doing so could " *
"delete valid entries. Original error: $(sprint(showerror, e))")
end
ignored_dirs = ["css", "masks"]
dataset_dirs = filter(d -> isdir(joinpath("public", d)) && !(d in ignored_dirs), public_dirs)
dataset_dirs = filter(d -> isdir(joinpath(PUBLIC_DIR, d)) && !(d in ignored_dirs), public_dirs)
registry_keys = Set(keys(registry))
folder_set = Set(dataset_dirs)
@@ -3849,7 +3887,8 @@ Core.eval(Stipple, :(sesstoken() = "")) # Prevent ErrorException("Model storage
if !isempty(new_folders) || !isempty(removed_folders)
msg = "Registry changed, saving..."
save_registry(reg_path, registry)
saved = save_registry(reg_path, registry)
saved || @error "Registry synchronization could not be persisted" path=reg_path
end
all_folders = sort(collect(keys(registry)), lt=natural)
+3
View File
@@ -11,6 +11,9 @@
<q-btn flat round icon="refresh" color="negative" v-on:click="reset_session_btn = true">
<q-tooltip>Deep Session Reset</q-tooltip>
</q-btn>
<q-btn flat round icon="power_settings_new" color="negative" v-on:click="shutdown = true">
<q-tooltip>Turn off JuliaMSI</q-tooltip>
</q-btn>
</div>
</header>
+3 -1
View File
@@ -1,4 +1,6 @@
# build_sysimage.jl
using Pkg
Pkg.activate(@__DIR__)
using PackageCompiler
headless = "--headless" in ARGS
@@ -33,7 +35,7 @@ end
create_sysimage(
packages_to_include,
sysimage_path = sysimage_path,
precompile_execution_file = "precompile_script.jl",
precompile_execution_file = joinpath(@__DIR__, "precompile_script.jl"),
incremental = true,
filter_stdlibs = false
)
+6 -2
View File
@@ -1,2 +1,6 @@
ENV["GENIE_ENV"] = "dev"
#ENV["GENIE_ENV"] = "prod"
# Respect an explicitly selected environment. This makes
# `GENIE_ENV=prod julia --project=. start_MSI_GUI.jl` actually work;
# previously this file unconditionally forced dev mode.
if !haskey(ENV, "GENIE_ENV")
ENV["GENIE_ENV"] = "prod"
end
+411 -31
View File
@@ -1,5 +1,7 @@
# julia_imzML_visual.jl
using Dates, JSON, Printf
"""
increment_image(current_image, image_list)
@@ -886,8 +888,8 @@ function warmup_init()
catch
end
dummy_bmp_path = joinpath("public", "dummy.bmp")
dummy_png_path = joinpath("public", "dummy.png")
dummy_bmp_path = joinpath(PUBLIC_DIR, "dummy.bmp")
dummy_png_path = joinpath(PUBLIC_DIR, "dummy.png")
try
save_bitmap(dummy_bmp_path, zeros(UInt8, 10, 10), ViridisPalette)
loadImgPlot("/dummy.bmp")
@@ -915,6 +917,42 @@ function clean_registry_path(registry_path::String)
return abspath(clean_path)
end
"""
normalize_source_path(path::AbstractString) -> String
Normalizes a dataset source path for storage and comparison.
Windows treats `/` and `\\` (and usually letter case) as equivalent, so raw
string comparison of a path returned by a native file dialog against a path
stored in `registry.json` can incorrectly trigger a full re-import.
"""
function normalize_source_path(path::AbstractString)
cleaned = strip(replace(String(path), "\\" => "/"))
isempty(cleaned) && return cleaned
return normpath(abspath(cleaned))
end
"""
_read_registry_text(path::String) -> String
Reads `registry.json` as UTF-8 and strips a UTF-8 BOM. A UTF-16 BOM is reported
with an actionable error instead of being parsed as binary garbage.
"""
function _read_registry_text(path::String)
raw = read(path)
isempty(raw) && return ""
if length(raw) >= 3 && raw[1] == 0xEF && raw[2] == 0xBB && raw[3] == 0xBF
raw = raw[4:end]
elseif length(raw) >= 2 && raw[1] == 0xFF && raw[2] == 0xFE
error("registry.json is UTF-16LE encoded. Save it as UTF-8 (without a BOM).")
elseif length(raw) >= 2 && raw[1] == 0xFE && raw[2] == 0xFF
error("registry.json is UTF-16BE encoded. Save it as UTF-8 (without a BOM).")
end
return String(raw)
end
"""
load_registry(registry_path)
@@ -924,26 +962,39 @@ Loads the dataset registry from a JSON file, with retries for robustness on Wind
- `registry_path`: Path to the `registry.json` file.
# Returns
- A dictionary containing the registry data. Returns an empty dictionary if the file doesn't exist or fails to parse.
- A dictionary containing the registry data. Returns an empty dictionary if the
file does not exist. A corrupt file is backed up and an empty dictionary is
returned so the application can continue without overwriting the original.
"""
function load_registry(registry_path::String)
return lock(REGISTRY_LOCK) do
clean_path = clean_registry_path(registry_path)
if isfile(clean_path)
for attempt in 1:5
isfile(clean_path) || return Dict{String,Any}()
for attempt in 1:6
try
return JSON.parsefile(clean_path, dicttype=Dict{String,Any})
text = _read_registry_text(clean_path)
isempty(strip(text)) && return Dict{String,Any}()
parsed = JSON.parse(text; dicttype=Dict{String,Any})
return parsed isa Dict{String,Any} ? parsed : Dict{String,Any}()
catch e
if attempt == 5
@error "Final attempt failed to parse registry.json: $(sprint(showerror, e))"
if attempt == 6
@error "Failed to parse registry.json after 6 attempts" path=clean_path exception=(e, catch_backtrace())
backup = clean_path * ".corrupt-" * string(round(Int, time()))
try
cp(clean_path, backup; force=true)
@error "A copy of the unreadable registry was preserved" backup=backup
catch backup_error
@warn "Could not preserve a copy of the unreadable registry" exception=backup_error
end
return Dict{String,Any}()
else
@warn "Attempt $attempt to read registry.json failed, retrying in 0.2s... Error: $(sprint(showerror, e))"
sleep(0.2)
end
end
end
# Exponential backoff with jitter; Windows AV/OneDrive locks are
# often longer than the previous fixed 1 second budget.
sleep(0.05 * 2.0^(attempt - 1) + 0.05 * rand())
end
end
return Dict{String,Any}()
end
end
@@ -1006,32 +1057,62 @@ function save_registry(registry_path::String, registry_data)
lock(REGISTRY_LOCK) do
clean_path = clean_registry_path(registry_path)
dir = dirname(clean_path)
if !isdir(dir)
try
mkpath(dir)
catch e
@error "Could not create the registry directory" path=dir exception=(e, catch_backtrace())
return false
end
temp_path = clean_path * ".tmp"
# A unique temp file in the same directory avoids collisions between
# two writers or two Julia processes. Writing first and renaming last
# keeps registry.json readable for the whole operation.
temp_path = ""
try
temp_path, io = mktemp(dir; cleanup=false)
try
JSON.print(io, registry_data, 4)
flush(io)
finally
close(io)
end
catch e
isempty(temp_path) || rm(temp_path; force=true)
@error "Could not write the temporary registry file" path=dir exception=(e, catch_backtrace())
return false
end
if isfile(clean_path)
try
cp(clean_path, clean_path * ".bak"; force=true)
catch e
@warn "Could not create a registry backup" path=clean_path exception=e
end
# On Windows, chmod(path, 0o644) clears the read-only attribute.
if !iswritable(clean_path)
try
chmod(clean_path, 0o644)
catch e
@warn "Could not clear the read-only attribute on registry.json" path=clean_path exception=e
end
end
end
for attempt in 1:6
try
open(temp_path, "w") do f
JSON.print(f, registry_data, 4)
end
# Replace final file with temp atomically. Force=true maps to ReplaceFile/MoveFileEx
mv(temp_path, clean_path, force=true)
mv(temp_path, clean_path; force=true)
return true
catch e
if attempt == 6
@error "Final attempt failed to write to registry.json: $(sprint(showerror, e))"
isfile(temp_path) && rm(temp_path, force=true)
@error "Failed to replace registry.json after 6 attempts" path=clean_path exception=(e, catch_backtrace())
isfile(temp_path) && rm(temp_path; force=true)
return false
else
@warn "Attempt $attempt to write to registry.json failed (Error: $(sprint(showerror, e))), retrying in 0.2s..."
sleep(0.2)
end
end
sleep(0.05 * 2.0^(attempt - 1) + 0.05 * rand())
end
end
return false
end
end
@@ -1049,12 +1130,12 @@ Adds or updates an entry in the dataset registry JSON file.
- `is_imzML`: Boolean indicating if the source is an imzML file.
"""
function update_registry(registry_path::String, dataset_name::String, source_path::String, metadata=nothing, is_imzML=false)
lock(REGISTRY_LOCK) do
saved = lock(REGISTRY_LOCK) do
registry = load_registry(registry_path)
existing_entry = get(registry, dataset_name, Dict{String,Any}())
entry = copy(existing_entry)
entry["source_path"] = source_path
entry["source_path"] = normalize_source_path(source_path)
entry["processed_date"] = string(now())
entry["is_imzML"] = is_imzML
@@ -1065,6 +1146,9 @@ function update_registry(registry_path::String, dataset_name::String, source_pat
registry[dataset_name] = entry
save_registry(registry_path, registry)
end
saved || @error "Registry update was not persisted" dataset=dataset_name path=registry_path
return saved
end
"""
@@ -1088,7 +1172,7 @@ and updating the data registry. It includes error handling and memory cleanup.
function process_file_safely(file_path, masses, params, progress_message_ref, overall_progress_ref; use_mask::Bool=false)
local_msi_data = nothing
dataset_name = replace(basename(file_path), r"\.imzML$"i => "")
output_dir = joinpath("public", dataset_name)
output_dir = joinpath(PUBLIC_DIR, dataset_name)
println("Processing: $dataset_name -> $output_dir")
try
@@ -1176,7 +1260,8 @@ function process_file_safely(file_path, masses, params, progress_message_ref, ov
is_imzML = local_msi_data.source isa ImzMLSource
update_registry(params.registry, dataset_name, file_path, metadata, is_imzML)
saved = update_registry(params.registry, dataset_name, file_path, metadata, is_imzML)
saved || return (false, "File: $(basename(file_path)) - registry update could not be saved")
return (true, "")
catch e
@@ -1334,3 +1419,298 @@ function loadSurfacePlot(interfaceImg::String, mask_path::String)
plotlayout = layout3D
return plotdata, plotlayout
end
# ============================================================================
# GUI-only plotting helpers (CairoMakie)
# ============================================================================
"""
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 = 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(: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
"""
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 = 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(: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
"""
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
+34 -30
View File
@@ -9,13 +9,15 @@ using Statistics, NaturalSort, LinearAlgebra, StipplePlotly
using Base.Filesystem: mv
using MSI_src
using .MSI_src: MSIData, process_image_pipeline, REGISTRY_LOCK
using .MSI_src: MSIData, process_image_pipeline, REGISTRY_LOCK, PUBLIC_DIR, DEFAULT_REGISTRY_PATH, ensure_public_dir
# Plot Handling
if !@isdefined(increment_image)
include("./julia_imzML_visual.jl")
end
ensure_public_dir()
# Image Processing Pipeline
using ImageBinarization
@@ -37,7 +39,7 @@ function alter_image(img_path, otsu_scale, noise_size_percent, hole_size_percent
try
# Strip query parameters from img_path
clean_img_path = replace(img_path, r"\?.*" => "")
full_image_path = joinpath("public", lstrip(clean_img_path, '/'))
full_image_path = joinpath(PUBLIC_DIR, lstrip(clean_img_path, '/'))
if !isfile(full_image_path)
return (success=false, message="Image file not found: $(full_image_path)", path="")
end
@@ -50,7 +52,7 @@ function alter_image(img_path, otsu_scale, noise_size_percent, hole_size_percent
otsu_scale=otsu_scale, noise_size_percent=noise_size_percent,
hole_size_percent=hole_size_percent, smoothing=smoothing_level)
output_dir = joinpath("public", "css", "masks")
output_dir = joinpath(PUBLIC_DIR, "css", "masks")
mkpath(output_dir)
path_smooth = "/css/masks/smoothed.png"
@@ -70,7 +72,7 @@ function display_slice(slice_path)
return [PlotlyBase.heatmap(x=Vector{Float64}(), y=Vector{Float64}())], PlotlyBase.Layout(margin=attr(l=0,r=0,t=0,b=0,pad=0)), false
end
full_path = joinpath("public", lstrip(slice_path, '/'))
full_path = joinpath(PUBLIC_DIR, lstrip(slice_path, '/'))
if !isfile(full_path)
return [PlotlyBase.heatmap(x=Vector{Float64}(), y=Vector{Float64}())], PlotlyBase.Layout(margin=attr(l=0,r=0,t=0,b=0,pad=0)), false
end
@@ -145,14 +147,16 @@ function update_main_plot(imgInt::String, smoothed_mask_path::String, imgTrans::
end
end
@genietools
# Genie tools/autoreload are initialized once in App. Marking this module as
# already initialized prevents a second Revise/GenieAutoReload watcher.
const GENIE_TOOLS_LOADED = true
@app begin
# --- State for Slice Selection (from app.jl) ---
@in selected_folder_main = ""
@out available_folders = String[]
@out image_available_folders = String[]
@out registry_path = abspath(joinpath(@__DIR__, "public", "registry.json"))
@out registry_path = DEFAULT_REGISTRY_PATH
@private registry_init_done = false
@in refetch_folders = false
@@ -237,7 +241,7 @@ end
img_from_canvas = load(IOBuffer(decoded_img_bytes))
binary_mask = binarize(ensure_grayscale(img_from_canvas), Otsu())
mask_path = joinpath("public", lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
mask_path = joinpath(PUBLIC_DIR, lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
save(mask_path, binary_mask)
smoothed_mask_path = get_timestamped_path(smoothed_mask_path)
@@ -252,7 +256,7 @@ end
if !isempty(selected_folder_main)
is_browsing_slices = true
is_editing_mask = false
folder_path = joinpath("public", selected_folder_main)
folder_path = joinpath(PUBLIC_DIR, selected_folder_main)
if !isdir(folder_path)
imgInt = ""
msgimg = "Folder not found."
@@ -277,7 +281,7 @@ end
end
# --- Check for mask in registry and update message ---
reg_path = abspath(joinpath(@__DIR__, "public", "registry.json"))
reg_path = DEFAULT_REGISTRY_PATH
if isfile(reg_path)
registry = JSON.parsefile(reg_path) # Assuming JSON.jl is loaded
if haskey(registry, selected_folder_main)
@@ -307,7 +311,7 @@ end
@onbutton btn_img_plus begin
if isempty(selected_folder_main) || is_editing_mask return end
folder_path = joinpath("public", selected_folder_main)
folder_path = joinpath(PUBLIC_DIR, selected_folder_main)
if !isdir(folder_path) return end
msi_bmp = sort(filter(f -> startswith(f, "MSI_") && endswith(f, ".bmp"), readdir(folder_path)), lt=natural)
new_msi = increment_image(current_msi, msi_bmp)
@@ -324,7 +328,7 @@ end
@onbutton btn_img_minus begin
if isempty(selected_folder_main) || is_editing_mask return end
folder_path = joinpath("public", selected_folder_main)
folder_path = joinpath(PUBLIC_DIR, selected_folder_main)
if !isdir(folder_path) return end
msi_bmp = sort(filter(f -> startswith(f, "MSI_") && endswith(f, ".bmp"), readdir(folder_path)), lt=natural)
new_msi = decrement_image(current_msi, msi_bmp)
@@ -357,7 +361,7 @@ end
@onbutton btn_upload_mask begin
picked_path = pick_file(; filterlist="png,bmp,jpg,jpeg")
if !isempty(picked_path)
target_dir = joinpath("public", "css", "masks")
target_dir = joinpath(PUBLIC_DIR, "css", "masks")
mkpath(target_dir)
uploaded_filename = "uploaded_mask_input.png"
destination_path = joinpath(target_dir, uploaded_filename)
@@ -379,7 +383,7 @@ end
@onbutton btn_upload_premade_mask begin
picked_path = pick_file(; filterlist="png,bmp,jpg,jpeg")
if !isempty(picked_path)
target_dir = joinpath("public", "css", "masks")
target_dir = joinpath(PUBLIC_DIR, "css", "masks")
mkpath(target_dir)
uploaded_filename = "premade_mask.png"
@@ -420,7 +424,7 @@ end
# --- Resizing to Slice (if imgInt is present) ---
slice_path_cleaned = replace(imgInt, r"\?.*" => "")
slice_full_path = joinpath("public", lstrip(slice_path_cleaned, '/'))
slice_full_path = joinpath(PUBLIC_DIR, lstrip(slice_path_cleaned, '/'))
if !isempty(imgInt) && isfile(slice_full_path) # Only resize if a slice is present
slice_img = load(slice_full_path)
@@ -472,9 +476,9 @@ end
result = alter_image(mask_input_path, otsu_scale, noise_size_percent, hole_size_percent, smoothing_level)
if result.success
local_smoothed_path = joinpath("public", lstrip(result.path, '/'))
local_smoothed_path = joinpath(PUBLIC_DIR, lstrip(result.path, '/'))
slice_path_cleaned = replace(imgInt, r"\?.*" => "")
slice_full_path = joinpath("public", lstrip(slice_path_cleaned, '/'))
slice_full_path = joinpath(PUBLIC_DIR, lstrip(slice_path_cleaned, '/'))
if isfile(slice_full_path) && isfile(local_smoothed_path)
slice_img = load(slice_full_path)
@@ -515,9 +519,9 @@ end
result = alter_image(mask_input_path, otsu_scale, noise_size_percent, hole_size_percent, smoothing_level)
if result.success
local_smoothed_path = joinpath("public", lstrip(result.path, '/'))
local_smoothed_path = joinpath(PUBLIC_DIR, lstrip(result.path, '/'))
slice_path_cleaned = replace(imgInt, r"\?.*" => "")
slice_full_path = joinpath("public", lstrip(slice_path_cleaned, '/'))
slice_full_path = joinpath(PUBLIC_DIR, lstrip(slice_path_cleaned, '/'))
if isfile(slice_full_path) && isfile(local_smoothed_path)
slice_img = load(slice_full_path)
@@ -561,7 +565,7 @@ end
@onbutton btn_edit_manually begin
if !isempty(smoothed_mask_path)
mask_path = joinpath("public", lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
mask_path = joinpath(PUBLIC_DIR, lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
if isfile(mask_path)
mask_img = load(mask_path)
h, w = size(mask_img)
@@ -586,7 +590,7 @@ end
@onchange mouse_x, mouse_y, is_drawing begin
if show_editor && is_drawing && mouse_x > 0 && mouse_y > 0
try
mask_path = joinpath("public", lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
mask_path = joinpath(PUBLIC_DIR, lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
if !isfile(mask_path) return end
img = load(mask_path)
@@ -621,7 +625,7 @@ end
@onchange bucket_fill_trigger begin
if show_editor && !isempty(bucket_fill_trigger)
try
mask_path = joinpath("public", lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
mask_path = joinpath(PUBLIC_DIR, lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
if !isfile(mask_path) return end
img = load_and_binarize_mask(mask_path)
@@ -647,7 +651,7 @@ end
@onchange rotate_degrees begin
if show_editor && rotate_degrees != 0
try
mask_path = joinpath("public", lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
mask_path = joinpath(PUBLIC_DIR, lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
if !isfile(mask_path) return end
img = load_and_binarize_mask(mask_path)
@@ -711,7 +715,7 @@ end
@onbutton btn_flip_mask begin
if show_editor
try
mask_path = joinpath("public", lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
mask_path = joinpath(PUBLIC_DIR, lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
if !isfile(mask_path) return end
img = load_and_binarize_mask(mask_path)
@@ -731,7 +735,7 @@ end
@onchange move_mask_payload begin
if show_editor && move_pixels > 0 && !isempty(move_mask_payload)
try
mask_path = joinpath("public", lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
mask_path = joinpath(PUBLIC_DIR, lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
if !isfile(mask_path) return end
img = load_and_binarize_mask(mask_path)
@@ -771,8 +775,8 @@ end
parent_folder = split(selected_folder_main, '/')[end]
final_mask_name = "$(parent_folder).png"
source_path = joinpath("public", lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
target_dir = joinpath("public", "css", "masks")
source_path = joinpath(PUBLIC_DIR, lstrip(replace(smoothed_mask_path, r"\?.*" => ""), '/'))
target_dir = joinpath(PUBLIC_DIR, "css", "masks")
mkpath(target_dir)
final_path = joinpath(target_dir, final_mask_name)
@@ -781,7 +785,7 @@ end
cp(source_path, final_path; force=true)
# Update registry directly in the handler
reg_path = abspath(joinpath(@__DIR__, "public", "registry.json"))
reg_path = DEFAULT_REGISTRY_PATH
registry = isfile(reg_path) ? JSON.parsefile(reg_path) : Dict{String, Any}()
full_mask_path = abspath(final_path)
@@ -843,15 +847,15 @@ end
sleep(1.0) # Give frontend time to initialize
try
println("Synchronizing registry for mask editor...")
reg_path = abspath(joinpath(@__DIR__, "public", "registry.json"))
reg_path = DEFAULT_REGISTRY_PATH
# Assuming load_registry is available from MSI_src or a similar utility file
# For now, handle its absence gracefully if it's not explicitly defined here.
registry = isfile(reg_path) ? load_registry(reg_path) : Dict{String, Any}()
public_dirs = isdir("public") ? readdir("public") : []
public_dirs = isdir(PUBLIC_DIR) ? readdir(PUBLIC_DIR) : []
ignored_dirs = ["css", "masks"]
dataset_dirs = filter(d -> isdir(joinpath("public", d)) && !(d in ignored_dirs), public_dirs)
dataset_dirs = filter(d -> isdir(joinpath(PUBLIC_DIR, d)) && !(d in ignored_dirs), public_dirs)
registry_keys = Set(keys(registry))
folder_set = Set(dataset_dirs)
+8 -4
View File
@@ -43,12 +43,10 @@ function create_warmup_datasets(dir, T_mz::Type, T_int::Type)
<referenceableParamGroup id="mz_array_settings">
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" value=""/>
<cvParam cvRef="MS" accession="MS:$(T_mz == Float64 ? "1000523" : "1000521")" name="$(T_mz == Float64 ? "64-bit float" : "32-bit float")" value=""/>
<cvParam cvRef="MS" accession="MS:1000574" name="zlib compression" value=""/>
</referenceableParamGroup>
<referenceableParamGroup id="intensity_array_settings">
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value=""/>
<cvParam cvRef="MS" accession="MS:$(T_int == Float64 ? "1000523" : "1000521")" name="$(T_int == Float64 ? "64-bit float" : "32-bit float")" value=""/>
<cvParam cvRef="MS" accession="MS:1000574" name="zlib compression" value=""/>
</referenceableParamGroup>
</referenceableParamGroupList>
<run id="run_1">
@@ -106,13 +104,19 @@ function create_warmup_datasets(dir, T_mz::Type, T_int::Type)
</spectrum>
</spectrumList>
</run>
<indexList count="1"><index name="spectrum"><offset idRef="scan=1">PLACEHOLDER</offset></index></indexList>
<indexList count="1">
<index name="spectrum">
<offset idRef="scan=1">PLACEHOLDER</offset>
</index>
</indexList>
<indexListOffset>ID_OFFSET</indexListOffset>
</mzML>
"""
# Replace the spectrum offset first. Replacing PLACEHOLDER changes the
# length of the document, so the index offset must be measured afterwards.
spec_start = findfirst("<spectrum", mzml_content).start - 1
index_start = findfirst("<indexList", mzml_content).start - 1
mzml_content = replace(mzml_content, "PLACEHOLDER" => string(spec_start))
index_start = findfirst("<indexList", mzml_content).start - 1
mzml_content = replace(mzml_content, "ID_OFFSET" => string(index_start))
write(mzml_path, mzml_content)
+4 -3
View File
@@ -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
+2 -2
View File
@@ -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)
+14 -3
View File
@@ -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 ---
+103 -35
View File
@@ -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
@@ -881,9 +890,22 @@ function precompute_analytics(msi_data::MSIData)
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
# 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 = 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)
global_min_mz = cached_min
global_max_mz = cached_max
else
# 1. First Pass: Find the global m/z range
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
# 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]
+7 -3
View File
@@ -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")
+49
View File
@@ -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
+30
View File
@@ -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
+2 -1
View File
@@ -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)
+46 -304
View File
@@ -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,9 +323,23 @@ function parse_binary_data_arrays(spectrum_block::String, spectrum_start_line::S
for bda_match in eachmatch(r"<binaryDataArray.*?>(.*?)</binaryDataArray>"sm, spectrum_block)
bda_content = bda_match.match # This will be the full <binaryDataArray> block
is_mz = occursin("MS:1000514", bda_content) || occursin("mzArray", bda_content)
# Many imzML writers put the m/z and intensity cvParams in a
# <referenceableParamGroup> and only reference it from the spectrum.
# Resolve the reference first so those files are classified correctly.
ref_match = match(r"<referenceableParamGroupRef\s+ref=\"([^\"]+)\"", bda_content)
is_mz = if ref_match !== nothing && haskey(param_groups, ref_match.captures[1])
param_groups[ref_match.captures[1]].Axis == 1
else
occursin("MS:1000514", bda_content) || occursin("mzArray", bda_content)
end
array_len_cv_match = match(r"IMS:1000103.*?value=\"(\d+)\"", bda_content)
# imzML 1.1 external-array accessions:
# IMS:1000101 external encoded length
# IMS:1000102 external data
# IMS:1000103 external offset
# IMS:1000104 external array length
# The previous order mapped offset/array-length/encoded-length incorrectly.
array_len_cv_match = match(r"IMS:1000104.*?value=\"(\d+)\"", bda_content)
array_length = Int32(0)
if array_len_cv_match !== nothing
array_length = parse(Int32, array_len_cv_match.captures[1])
@@ -338,7 +353,7 @@ function parse_binary_data_arrays(spectrum_block::String, spectrum_start_line::S
end
end
encoded_len_cv_match = match(r"IMS:1000104.*?value=\"(\d+)\"", bda_content)
encoded_len_cv_match = match(r"IMS:1000101.*?value=\"(\d+)\"", bda_content)
encoded_length = Int64(0)
if encoded_len_cv_match !== nothing
encoded_length = parse(Int64, encoded_len_cv_match.captures[1])
@@ -349,13 +364,19 @@ function parse_binary_data_arrays(spectrum_block::String, spectrum_start_line::S
end
end
offset_match = match(r"IMS:1000102.*?value=\"(\d+)\"", bda_content)
offset_match = match(r"IMS:1000103.*?value=\"(\d+)\"", bda_content)
offset = Int64(0)
if offset_match !== nothing
offset = parse(Int64, offset_match.captures[1])
else
# Legacy files sometimes put the offset directly in IMS:1000102.
legacy_offset_match = match(r"IMS:1000102.*?value=\"(\d+)\"", bda_content)
if legacy_offset_match !== nothing
offset = parse(Int64, legacy_offset_match.captures[1])
end
end
if array_length > 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)
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
+1 -1
View File
@@ -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
+100 -22
View File
@@ -1,22 +1,86 @@
using Pkg
sTime=time()
Pkg.activate(".")
ENV["GENIE_ENV"] = "dev"
#ENV["GENIE_ENV"] = "prod"
sTime = time()
manifest_path = joinpath(@__DIR__, "Manifest.toml")
# Always activate the repository's own project, not the caller's cwd.
Pkg.activate(@__DIR__)
# Selective instantiation for faster startup
if get(ENV, "GENIE_ENV", "dev") != "prod" && !isfile(manifest_path)
@info "Development environment detected and Manifest.toml missing. Instantiating packages..."
# Keep the user's environment choice. Normal GUI launches use production mode:
# dev mode starts Revise/GenieAutoReload watchers, which adds startup cost and
# duplicate "Watching"/"Autoreloading" log lines. Use JULIA_MSI_DEV=1 to opt in.
if !haskey(ENV, "GENIE_ENV")
ENV["GENIE_ENV"] = get(ENV, "JULIA_MSI_DEV", "0") == "1" ? "dev" : "prod"
end
# NativeFileDialog uses GTK on Linux. A C/POSIX locale produces the noisy
# "Locale not supported by C library" warning when the dialog opens.
if Sys.islinux() && get(ENV, "LC_ALL", "") == "" &&
get(ENV, "LANG", "") in ("", "C", "POSIX")
ENV["LC_ALL"] = "C.UTF-8"
end
# `instantiate` is idempotent and is required even when Manifest.toml exists:
# a manifest can be present while packages are missing from the depot.
try
Pkg.instantiate()
catch e
@warn "Pkg.instantiate() failed; retrying after Pkg.resolve()" exception=e
Pkg.resolve()
Pkg.instantiate()
Pkg.gc()
elseif get(ENV, "GENIE_ENV", "dev") != "prod"
@info "Manifest.toml found. Skipping Pkg.instantiate() for faster boot. Delete Manifest.toml if you need to re-instantiate."
ENV["GENIE_ENV"] = "prod"
end
# Fail before Genie loads if generated assets cannot be written.
include(joinpath(@__DIR__, "src", "Paths.jl"))
ensure_public_dir()
using Logging
# Genie/EzXML prints one warning per Vue/Quasar custom tag while parsing the
# Stipple layout. Those warnings are harmless but make the console unreadable.
# Keep real warnings/errors; allow `JULIA_MSI_VERBOSE=1` to see everything.
struct JuliaMSIFilterLogger <: Logging.AbstractLogger
inner::Logging.AbstractLogger
verbose::Bool
end
Logging.min_enabled_level(l::JuliaMSIFilterLogger) =
Logging.min_enabled_level(l.inner)
Logging.shouldlog(l::JuliaMSIFilterLogger, level, _module, group, id) =
Logging.shouldlog(l.inner, level, _module, group, id)
Logging.catch_exceptions(l::JuliaMSIFilterLogger) =
Logging.catch_exceptions(l.inner)
function Logging.handle_message(l::JuliaMSIFilterLogger, level, message, _module,
group, id, file, line; kwargs...)
if !l.verbose
text = try
string(message)
catch
""
end
# EzXML/libxml2 logs one "Tag <x> invalid" warning per Vue/Quasar custom
# tag while Genie parses the Stipple layout. Genie 5.35 already silences
# most of these; keep this guard for older/edge render paths.
if occursin("XMLError:", text) && occursin("HTML parser", text)
return nothing
end
# Safety net for the Stipple watcher `isempty(nothing)` bug (the root
# cause is fixed in app.jl by emitting an empty sesstoken meta tag).
if nameof(_module) === :Stipple &&
occursin("MethodError(iterate, (nothing", text)
return nothing
end
end
return Logging.handle_message(l.inner, level, message, _module, group, id,
file, line; kwargs...)
end
Logging.global_logger(JuliaMSIFilterLogger(
Logging.ConsoleLogger(stderr, Logging.Info),
get(ENV, "JULIA_MSI_VERBOSE", "0") == "1"
))
using Genie
# --- Cross-Platform Startup Cleanup ---
@@ -46,6 +110,10 @@ function cleanup_orphaned_sessions()
end
is_session_dir || continue
# Do not remove sessions from another currently-running instance.
# Only clean directories that have been idle for at least an hour.
(time() - mtime(full_path)) < 3600 && continue
# Safe to remove — this is an orphaned Genie session directory
dir_size = sum(filesize(joinpath(full_path, f)) for f in contents; init=0)
rm(full_path; recursive=true, force=true)
@@ -65,27 +133,37 @@ end
cleanup_orphaned_sessions()
# Load and configure Genie
# Load and configure Genie. Do not redirect stderr: errors must remain visible
# to the user and to the log/diagnostics workflow.
Genie.loadapp()
# Remove html parser error discrepancy
redirect_stderr(devnull)
# Start the Genie server
@async begin
up(host="127.0.0.1", port=1481)
eTime=round(time()-sTime,digits=3)
println("Julia MSI GUI took $(eTime) seconds booting")
url = "http://127.0.0.1:1481"
# Open the URL in the default web browser based on the OS
# Open the URL in the default web browser based on the OS.
# `start` and `Start-Process` are shell built-ins, not executables, so
# Windows must go through `cmd /c`.
if Sys.isapple()
@async run(`open $url`) # For macOS
@async try
run(`open $url`)
catch e
@warn "Could not open the browser automatically" url=url exception=e
end
elseif Sys.islinux()
@async run(`xdg-open $url`) # For Linux
@async try
run(`xdg-open $url`)
catch e
@warn "Could not open the browser automatically" url=url exception=e
end
elseif Sys.iswindows()
@async run(`start $url`) # For Windows
@async run(`explorer $url`)
@async run(`Start-Process $url`) # For Windows
@async try
run(`cmd /c start "" $url`)
catch e
@warn "Could not open the browser automatically" url=url exception=e
end
end
end
wait()
+267
View File
@@ -0,0 +1,267 @@
# test/benchmark_comparison.jl
# ===================================================================
# Cross-Language Performance Benchmark Suite: JuliaMSI vs R (MALDIquant & Cardinal)
# ===================================================================
# This script runs the performance benchmarks for:
# 1. JuliaMSI (New Engine)
# 2. R - MALDIquant (isolated run)
# 3. R - Cardinal (isolated run)
#
# It saves the results to `test/results/cross_language_benchmark.csv` and
# creates a comparison plot.
# ===================================================================
using Pkg
Pkg.activate(joinpath(@__DIR__, ".."))
using BenchmarkTools
using DataFrames
using CSV
using CairoMakie
using Statistics
using MSI_src
struct BenchmarkCase
filepath::String
mz_value::Float64
mz_tolerance::Float64
name::String
end
const RESULTS_DIR = joinpath(@__DIR__, "results")
const NUM_REPETITIONS = 10 # Number of slice repetitions for averaging
const BENCHMARK_CASES = [
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML", 436.04, 0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Chilli/ltpmsi-chilli.imzML", 420.0, 0.1, "Chilli Pepper"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/40TopL,10TopR,30BottomL,20BottomR/40TopL,10TopR,30BottomL,20BottomR-centroid.imzML", 885.5, 0.1, "Human Colon Cancer"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053, 0.1, "Mouse Urinary Bladder"),
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML", 306.1, 0.1, "Leaf"), # Este leaf es diferente de taliana!
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Liv2_imzML_TIMSConvert-selected/Liv2.imzML", 796.18, 0.1, "Liver Cut"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida_Tims/Stomach_DHB.imzML", 804.3, 0.1, "Mouse Stomach 4GB")
]
function get_total_file_size_mb(filepath::String)
imzml_size = isfile(filepath) ? filesize(filepath) : 0
ibd_path = replace(filepath, r"\.(imzML|imzml)$" => ".ibd")
ibd_size = isfile(ibd_path) ? filesize(ibd_path) : 0
return round((imzml_size + ibd_size) / 1024^2, digits=2)
end
function flush_memory()
GC.gc(true)
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
end
end
function run_cross_benchmarks()
mkpath(RESULTS_DIR)
results = DataFrame()
println("="^60)
println("STARTING CROSS-LANGUAGE BENCHMARK (JuliaMSI vs R)")
println("="^60)
# Check if Rscript is available
has_r = try
success(`Rscript --version`)
catch
false
end
if !has_r
@warn "Rscript is not available. Please install R first to compare with MALDIquant/Cardinal."
end
for case in BENCHMARK_CASES
if !isfile(case.filepath)
@warn "File not found: $(case.filepath). Skipping."
continue
end
println("\n--- Target Dataset: $(case.name) ---")
file_size = get_total_file_size_mb(case.filepath)
# ------------------------------------------------------------
# 1. JuliaMSI (New Engine)
# ------------------------------------------------------------
println("[JuliaMSI - New Engine]")
flush_memory()
load_stats_new = @timed OpenMSIData(case.filepath)
msi_data = load_stats_new.value
load_time_new_s = load_stats_new.time
mem_load_new_mb = load_stats_new.bytes / 1024^2
# Benchmark slice generation
b_slice_new = @benchmark get_mz_slice($msi_data, $(case.mz_value), $(case.mz_tolerance)) samples=NUM_REPETITIONS seconds=10
mean_time_new_s = mean(b_slice_new.times) / 1e9
close(msi_data)
flush_memory()
# Record JuliaMSI results
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "JuliaMSI",
LoadTime_s = load_time_new_s,
LoadMem_MB = mem_load_new_mb,
AvgSliceTime_s = mean_time_new_s,
Status = "Success"
))
# ------------------------------------------------------------
# 2. Run R MALDIquant (Isolated process)
# ------------------------------------------------------------
if has_r
println("[R - MALDIquant (centroid=TRUE)]")
temp_r_csv = joinpath(RESULTS_DIR, "temp_r_mq.csv")
r_script_path = joinpath(@__DIR__, "benchmark_r.R")
try
cmd = `Rscript $r_script_path maldiquant $(case.filepath) $(case.mz_value) $(case.mz_tolerance) $NUM_REPETITIONS $temp_r_csv`
process_status = run(cmd, wait=true)
if success(process_status) && isfile(temp_r_csv)
r_df = CSV.read(temp_r_csv, DataFrame)
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "MALDIquant",
LoadTime_s = r_df.LoadTime_s[1],
LoadMem_MB = r_df.LoadMem_MB[1],
AvgSliceTime_s = r_df.AvgSliceTime_s[1],
Status = "Success"
))
rm(temp_r_csv, force=true)
else
throw(ErrorException("R process failed with exit code $(process_status.exitcode)"))
end
catch e
@warn "MALDIquant benchmark failed/OOMed for $(case.name): $e"
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "MALDIquant",
LoadTime_s = NaN,
LoadMem_MB = NaN,
AvgSliceTime_s = NaN,
Status = "OOM / Failed"
))
end
# ------------------------------------------------------------
# 3. Run R Cardinal (Isolated process)
# ------------------------------------------------------------
println("[R - Cardinal (matter lazy-loading)]")
temp_r_csv_card = joinpath(RESULTS_DIR, "temp_r_card.csv")
try
cmd = `Rscript $r_script_path cardinal $(case.filepath) $(case.mz_value) $(case.mz_tolerance) $NUM_REPETITIONS $temp_r_csv_card`
process_status = run(cmd, wait=true)
if success(process_status) && isfile(temp_r_csv_card)
r_df = CSV.read(temp_r_csv_card, DataFrame)
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "Cardinal",
LoadTime_s = r_df.LoadTime_s[1],
LoadMem_MB = r_df.LoadMem_MB[1],
AvgSliceTime_s = r_df.AvgSliceTime_s[1],
Status = "Success"
))
rm(temp_r_csv_card, force=true)
else
throw(ErrorException("R process failed with exit code $(process_status.exitcode)"))
end
catch e
@warn "Cardinal benchmark failed/OOMed for $(case.name): $e"
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "Cardinal",
LoadTime_s = NaN,
LoadMem_MB = NaN,
AvgSliceTime_s = NaN,
Status = "OOM / Failed"
))
end
end
end
csv_path = joinpath(RESULTS_DIR, "cross_language_benchmark.csv")
CSV.write(csv_path, results)
println("\nDetailed cross-language results saved to $csv_path")
if nrow(results) > 0
plot_cross_results(results)
end
return results
end
function plot_cross_results(df::DataFrame)
# Filter datasets
unique_datasets = unique(df.Dataset)
if isempty(unique_datasets) return end
fig = Figure(size=(1800, 1200), fontsize=20)
libraries = ["JuliaMSI", "MALDIquant", "Cardinal"]
colors = ["#10b981", "#3b82f6", "#8b5cf6"] # green, blue, purple
x_pos = 1:length(unique_datasets)
# Axis 1: Slice Generation Time
ax1 = Axis(fig[1, 1],
title="Average Slice Generation Time (Lower is Better)",
ylabel="Time (seconds)",
xticks=(x_pos, unique_datasets), xticklabelrotation=π/8)
# Axis 2: RAM overhead during load
ax2 = Axis(fig[1, 2],
title="Memory Consumption during Load (Lower is Better)",
ylabel="Memory (MB)",
xticks=(x_pos, unique_datasets), xticklabelrotation=π/8)
# Plot grouped bars
width = 0.25
offsets = [-width, 0.0, width]
for (idx, lib) in enumerate(libraries)
lib_df = df[df.Library .== lib, :]
if isempty(lib_df) continue end
# Match rows with unique_datasets order
slice_times = Float64[]
load_mems = Float64[]
for ds in unique_datasets
row = lib_df[lib_df.Dataset .== ds, :]
if nrow(row) > 0 && row.Status[1] == "Success"
push!(slice_times, coalesce(row.AvgSliceTime_s[1], 0.0))
push!(load_mems, coalesce(row.LoadMem_MB[1], 0.0))
else
push!(slice_times, 0.0)
push!(load_mems, 0.0)
end
end
barplot!(ax1, x_pos .+ offsets[idx], slice_times, color=colors[idx], width=width, label=lib)
barplot!(ax2, x_pos .+ offsets[idx], load_mems, color=colors[idx], width=width, label=lib)
end
axislegend(ax1, position=:rt)
axislegend(ax2, position=:rt)
save(joinpath(RESULTS_DIR, "cross_language_comparison.png"), fig)
println("Comparison dashboard saved to $(joinpath(RESULTS_DIR, "cross_language_comparison.png"))")
end
if abspath(PROGRAM_FILE) == @__FILE__
run_cross_benchmarks()
end
+216
View File
@@ -0,0 +1,216 @@
# test/benchmark_v3.jl
# ===================================================================
# High-Precision Performance Benchmark Suite (v3)
# ===================================================================
# This script integrates the robust statistical sampling of `BenchmarkTools`
# with the visual comparative mechanics against the legacy library.
# It captures the paradigm shift from "Time per slice" to "Pipeline Throughput".
# ===================================================================
using Pkg
Pkg.activate(joinpath(@__DIR__, ".."))
using BenchmarkTools
using DataFrames
using CSV
using CairoMakie
using Statistics
using MSI_src
using julia_mzML_imzML
struct BenchmarkCase
filepath::String
mz_value::Float64
mz_tolerance::Float64
name::String
end
const RESULTS_DIR = joinpath(@__DIR__, "results")
# List to benchmark
const BENCHMARK_CASES = [
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML", 436.04, 0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Chilli/ltpmsi-chilli.imzML", 420.0, 0.1, "Chilli Pepper"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/40TopL,10TopR,30BottomL,20BottomR/40TopL,10TopR,30BottomL,20BottomR-centroid.imzML", 885.5, 0.1, "Colon Cancer Human"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053, 0.1, "Mouse Urinary Bladder"),
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML", 306.1, 0.1, "Leaf"), # Este leaf es diferente de taliana!
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Liv2_imzML_TIMSConvert-selected/Liv2.imzML", 796.18, 0.1, "Liver Cut"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida_Tims/Stomach_DHB.imzML", 804.3, 0.1, "Mouse Stomach 4GB")
]
function get_total_file_size_mb(filepath::String)
imzml_size = isfile(filepath) ? filesize(filepath) : 0
ibd_path = replace(filepath, r"\.(imzML|imzml)$" => ".ibd")
ibd_size = isfile(ibd_path) ? filesize(ibd_path) : 0
return round((imzml_size + ibd_size) / 1024^2, digits=2)
end
function flush_memory()
GC.gc(true)
if Sys.islinux()
# Force the OS to reclaim memory from the glibc allocator
ccall(:malloc_trim, Int32, (Int32,), 0)
end
end
function run_v3_benchmarks()
mkpath(RESULTS_DIR)
results = DataFrame()
println("="^60)
println("STARTING ENTERPRISE BENCHMARK SUITE (v3)")
println("="^60)
for case in BENCHMARK_CASES
if !isfile(case.filepath)
@warn "File not found: $(case.filepath). Skipping."
continue
end
println("\n--- Target: $(case.name) ---")
file_size = get_total_file_size_mb(case.filepath)
# ------------------------------------------------------------
# 1. JuliaMSI (New Architecture)
# ------------------------------------------------------------
println("[JuliaMSI - New Engine]")
flush_memory()
# Load Phase (Metadata Only / Memory Mapping)
load_stats_new = @timed OpenMSIData(case.filepath)
msi_data = load_stats_new.value
load_time_new_s = load_stats_new.time
mem_load_new_mb = load_stats_new.bytes / 1024^2
# Slicing Phase (High Precision)
b_slice_new = @benchmark get_mz_slice($msi_data, $(case.mz_value), $(case.mz_tolerance)) samples=10 seconds=5
mean_time_new_s = mean(b_slice_new.times) / 1e9
# Calculate Amortized Throughput (10 slices)
# Includes the 'Loading Wall' penalty
total_time_10_new = load_time_new_s + (10 * mean_time_new_s)
amortized_sps_new = 10.0 / total_time_10_new
close(msi_data)
flush_memory()
# ------------------------------------------------------------
# 2. julia_mzML_imzML (Legacy Architecture)
# ------------------------------------------------------------
println("[julia_mzML_imzML - Legacy]")
load_stats_old = try
@timed LoadImzml(case.filepath)
catch e
@warn "Legacy load failed: $e"
(time=Inf, bytes=Inf, value=nothing)
end
old_data = load_stats_old.value
mem_load_old_mb = load_stats_old.bytes / 1024^2
load_time_old_s = Inf
mean_time_old_s = Inf
amortized_sps_old = 0.0
if old_data !== nothing
b_slice_old = try
# Legacy can be extremely slow, constrain it heavily
@benchmark GetSlice($old_data, $(case.mz_value), $(case.mz_tolerance)) samples=3 seconds=10
catch e
@warn "Legacy slice failed: $e"
nothing
end
if b_slice_old !== nothing
mean_time_old_s = mean(b_slice_old.times) / 1e9
# Accurately reflect the massive load time in the throughput
load_time_old_s = load_stats_old.time
total_time_10_old = load_time_old_s + (10 * mean_time_old_s)
amortized_sps_old = 10.0 / total_time_10_old
end
end
flush_memory()
# ------------------------------------------------------------
# Record
# ------------------------------------------------------------
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
# Legacy Metrics
Legacy_LoadMem_MB = mem_load_old_mb,
Legacy_LoadTime_s = load_stats_old.time,
Legacy_Amortized_SPS_10 = amortized_sps_old,
# New Metrics
New_LoadMem_MB = mem_load_new_mb,
New_LoadTime_s = load_time_new_s,
New_Amortized_SPS_10 = amortized_sps_new,
# Competitive Deltas
RAM_Reduction_Pct = isfinite(mem_load_old_mb) ? ((mem_load_old_mb - mem_load_new_mb) / mem_load_old_mb)*100 : NaN,
UX_Speedup_Factor = isfinite(amortized_sps_old) ? (amortized_sps_new / amortized_sps_old) : NaN
))
println(" > RAM Reduction: $(round(results[end, :RAM_Reduction_Pct], digits=2))%")
println(" > Amortized Throughput (10 Slices): $(round(amortized_sps_old, digits=2)) -> $(round(amortized_sps_new, digits=2)) slices/sec")
end
csv_path = joinpath(RESULTS_DIR, "v3_enterprise_benchmarks.csv")
CSV.write(csv_path, results)
println("\nData saved to $csv_path")
plot_v3_results(results)
return results
end
function plot_v3_results(df::DataFrame)
if isempty(df) return end
fig = Figure(size=(1800, 1200), fontsize=24)
x_pos = 1:nrow(df)
labels = df.Dataset
# ---------- Plot 1: The RAM Revolution ----------
ax1 = Axis(fig[1, 1],
title="Initial RAM Cost (Loading & Mmap)",
ylabel="Memory (MB)",
xticks=(x_pos, labels), xticklabelrotation=π/8)
barplot!(ax1, x_pos .- 0.2, df.New_LoadMem_MB, color="#10b981", width=0.4, label="JuliaMSI (Mmap Lazy)")
barplot!(ax1, x_pos .+ 0.2, df.Legacy_LoadMem_MB, color="#ef4444", width=0.4, label="Legacy (Dense Matrix)")
axislegend(ax1, position=:lt)
# ---------- Plot 2: Throughput Leap ----------
ax2 = Axis(fig[1, 2],
title="Amortized Throughput (10 Slices - Higher is Better)",
ylabel="Slices / Second (Inc. Load Time)",
xticks=(x_pos, labels), xticklabelrotation=π/8)
barplot!(ax2, x_pos .- 0.2, df.New_Amortized_SPS_10, color="#10b981", width=0.4, label="JuliaMSI")
barplot!(ax2, x_pos .+ 0.2, df.Legacy_Amortized_SPS_10, color="#ef4444", width=0.4, label="Legacy")
axislegend(ax2, position=:lt)
# ---------- Plot 3: The Scaling Wall (File Size vs Throughput) ----------
ax3 = Axis(fig[2, 1:2],
title="Performance Scaling: UX Throughput vs Dataset Size",
xlabel="Dataset File Size (MB)",
ylabel="Amortized Throughput (Slices/sec)")
scatterlines!(ax3, df.FileSize_MB, df.New_Amortized_SPS_10, color="#10b981", markersize=15, linewidth=4, label="JuliaMSI Engine")
scatterlines!(ax3, df.FileSize_MB, df.Legacy_Amortized_SPS_10, color="#ef4444", markersize=15, linewidth=4, label="Legacy Engine")
axislegend(ax3, position=:rt)
save(joinpath(RESULTS_DIR, "v3_enterprise_dashboard.png"), fig)
println("\nDashboards saved successfully.")
end
# Ensure we process if run as the main script
if abspath(PROGRAM_FILE) == @__FILE__
run_v3_benchmarks()
end
+3 -3
View File
@@ -49,13 +49,13 @@ const BENCHMARK_CASES = [
# BenchmarkCase("/path/to/your/small_file.imzML", 309.06, 0.1),
# BenchmarkCase("/path/to/your/medium_file.imzML", 896.0, 1.0),
# BenchmarkCase("/path/to/your/large_file.imzML", 100.0, 0.1),
# BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML",116.07,0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML",116.07,0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Chilli/ltpmsi-chilli.imzML",420,0.1, "Chilli Pepper"), # Chilli
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/40TopL,10TopR,30BottomL,20BottomR/40TopL,10TopR,30BottomL,20BottomR-centroid.imzML",885.5,0.1, "Colon Cancer Human"), # Human Cancer
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053,0.1, "Mouse Urinary Bladder"), # Mouse bladder
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML",306.1,0.1, "Leaf"),
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML",306.1,0.1, "Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Liv2_imzML_TIMSConvert-selected/Liv2.imzML",796.18,0.1, "Liver Cut"), #Lib2
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida/Stomach_DHB_uncompressed.imzML",804.3,0.1, "Mouse Stomach 2GB"), # Mouse Stomach
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida/Stomach_DHB_uncompressed.imzML",804.3,0.1, "Mouse Stomach 2GB"), # Mouse Stomach
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida_Tims/Stomach_DHB.imzML",804.3,0.1, "Mouse Stomach 4GB"), # Mouse Stomach
+320
View File
@@ -0,0 +1,320 @@
# test/benchmark_comparison.jl
# ===================================================================
# Cross-Language Performance Benchmark Suite: JuliaMSI vs R (MALDIquant & Cardinal)
# ===================================================================
# Compares JuliaMSI (Julia) vs MALDIquant (R) vs Cardinal (R)
# Integrates formal academic metrics, error bars, and log-scale plots.
# ===================================================================
using Pkg
Pkg.activate(joinpath(@__DIR__, ".."))
using BenchmarkTools
using DataFrames
using CSV
using CairoMakie
using Statistics
using MSI_src
struct BenchmarkCase
filepath::String
mz_value::Float64
mz_tolerance::Float64
name::String
end
const RESULTS_DIR = joinpath(@__DIR__, "results")
const NUM_REPETITIONS = 10
const BENCHMARK_CASES = [
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML", 436.04, 0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Chilli/ltpmsi-chilli.imzML", 420.0, 0.1, "Chilli Pepper"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/40TopL,10TopR,30BottomL,20BottomR/40TopL,10TopR,30BottomL,20BottomR-centroid.imzML", 885.5, 0.1, "Colon Cancer Human"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053, 0.1, "Mouse Urinary Bladder"),
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML", 306.1, 0.1, "Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Liv2_imzML_TIMSConvert-selected/Liv2.imzML", 796.18, 0.1, "Liver Cut"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida_Tims/Stomach_DHB.imzML", 804.3, 0.1, "Mouse Stomach 4GB")
]
function get_total_file_size_mb(filepath::String)
imzml_size = isfile(filepath) ? filesize(filepath) : 0
ibd_path = replace(filepath, r"\.(imzML|imzml)$" => ".ibd")
ibd_size = isfile(ibd_path) ? filesize(ibd_path) : 0
return round((imzml_size + ibd_size) / 1024^2, digits=2)
end
function flush_memory()
GC.gc(true)
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
end
end
function run_cross_benchmarks()
mkpath(RESULTS_DIR)
results = DataFrame()
println("="^60)
println("STARTING CROSS-LANGUAGE BENCHMARK (JuliaMSI vs R)")
println("="^60)
has_r = try
success(`Rscript --version`)
catch
false
end
if !has_r
@warn "Rscript is not available. Please install R first to compare with MALDIquant/Cardinal."
end
for case in BENCHMARK_CASES
if !isfile(case.filepath)
@warn "File not found: $(case.filepath). Skipping."
continue
end
println("\n--- Target Dataset: $(case.name) ---")
file_size = get_total_file_size_mb(case.filepath)
# ------------------------------------------------------------
# 1. JuliaMSI (New Engine)
# ------------------------------------------------------------
println("[JuliaMSI - New Engine]")
flush_memory()
load_stats_new = @timed OpenMSIData(case.filepath)
msi_data = load_stats_new.value
load_time_new_s = load_stats_new.time
mem_load_new_mb = load_stats_new.bytes / 1024^2
# Benchmark slice generation
b_slice_new = @benchmark get_mz_slice($msi_data, $(case.mz_value), $(case.mz_tolerance)) samples=NUM_REPETITIONS seconds=10
times_new_s = b_slice_new.times ./ 1e9
mean_time_new_s = mean(times_new_s)
std_time_new_s = std(times_new_s)
close(msi_data)
flush_memory()
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "JuliaMSI",
LoadTime_s = load_time_new_s,
LoadMem_MB = mem_load_new_mb,
AvgSliceTime_s = mean_time_new_s,
SliceStd_s = std_time_new_s,
Status = "Success"
))
# ------------------------------------------------------------
# 2. Run R MALDIquant (Isolated process)
# ------------------------------------------------------------
if has_r
# Skip MALDIquant for files > 3 GB to prevent system SIGKILL
if file_size > 5000
println("Skipping MALDIquant benchmark for $(case.name) to prevent SIGKILL OOM.")
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "MALDIquant",
LoadTime_s = NaN,
LoadMem_MB = NaN,
AvgSliceTime_s = NaN,
SliceStd_s = 0.0,
Status = "OOM / Skipped"
))
else
println("[R - MALDIquant (centroid=TRUE)]")
temp_r_csv = joinpath(RESULTS_DIR, "temp_r_mq.csv")
r_script_path = joinpath(@__DIR__, "benchmark_r.R")
try
cmd = `Rscript $r_script_path maldiquant $(case.filepath) $(case.mz_value) $(case.mz_tolerance) $NUM_REPETITIONS $temp_r_csv`
process_status = run(cmd, wait=true)
if success(process_status) && isfile(temp_r_csv)
r_df = CSV.read(temp_r_csv, DataFrame)
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "MALDIquant",
LoadTime_s = r_df.LoadTime_s[1],
LoadMem_MB = r_df.LoadMem_MB[1],
AvgSliceTime_s = r_df.AvgSliceTime_s[1],
SliceStd_s = 0.0, # R script simplified to mean
Status = "Success"
))
rm(temp_r_csv, force=true)
else
throw(ErrorException("R process failed"))
end
catch e
@warn "MALDIquant benchmark failed/OOMed: $e"
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "MALDIquant",
LoadTime_s = NaN,
LoadMem_MB = NaN,
AvgSliceTime_s = NaN,
SliceStd_s = 0.0,
Status = "OOM / Failed"
))
end
end
# ------------------------------------------------------------
# 3. Run R Cardinal (Isolated process)
# ------------------------------------------------------------
println("[R - Cardinal (matter lazy-loading)]")
temp_r_csv_card = joinpath(RESULTS_DIR, "temp_r_card.csv")
r_script_path = joinpath(@__DIR__, "benchmark_r.R")
try
cmd = `Rscript $r_script_path cardinal $(case.filepath) $(case.mz_value) $(case.mz_tolerance) $NUM_REPETITIONS $temp_r_csv_card`
process_status = run(cmd, wait=true)
if success(process_status) && isfile(temp_r_csv_card)
r_df = CSV.read(temp_r_csv_card, DataFrame)
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "Cardinal",
LoadTime_s = r_df.LoadTime_s[1],
LoadMem_MB = r_df.LoadMem_MB[1],
AvgSliceTime_s = r_df.AvgSliceTime_s[1],
SliceStd_s = 0.0,
Status = "Success"
))
rm(temp_r_csv_card, force=true)
else
throw(ErrorException("R process failed"))
end
catch e
@warn "Cardinal benchmark failed/OOMed: $e"
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "Cardinal",
LoadTime_s = NaN,
LoadMem_MB = NaN,
AvgSliceTime_s = NaN,
SliceStd_s = 0.0,
Status = "OOM / Failed"
))
end
end
end
# Calculate Derived Academic Metrics
# Throughput, MemEfficiency, FoldSpeedup (rel. to Cardinal), LoadBandwidth
results.Throughput_SPS = 1.0 ./ results.AvgSliceTime_s
results.MemEff_MB_GB = results.LoadMem_MB ./ (results.FileSize_MB ./ 1024.0)
results.LoadBandwidth_MBs = results.FileSize_MB ./ results.LoadTime_s
# Fold Speedup calculation using Cardinal as Baseline
results.Fold_Speedup = fill(NaN, nrow(results))
for ds in unique(results.Dataset)
ds_rows = results[results.Dataset .== ds, :]
cardinal_row = ds_rows[ds_rows.Library .== "Cardinal", :]
julia_row = ds_rows[ds_rows.Library .== "JuliaMSI", :]
if nrow(cardinal_row) > 0 && nrow(julia_row) > 0 && cardinal_row.Status[1] == "Success"
card_time = cardinal_row.AvgSliceTime_s[1]
julia_time = julia_row.AvgSliceTime_s[1]
# Speedup = Cardinal Time / JuliaMSI Time
speedup = card_time / julia_time
results[ (results.Dataset .== ds) .& (results.Library .== "JuliaMSI"), :Fold_Speedup ] .= speedup
end
end
csv_path = joinpath(RESULTS_DIR, "cross_language_benchmark.csv")
CSV.write(csv_path, results)
println("\nDetailed cross-language results saved to $csv_path")
if nrow(results) > 0
plot_cross_results(results)
end
return results
end
function plot_cross_results(df::DataFrame)
unique_datasets = unique(df.Dataset)
if isempty(unique_datasets) return end
fig = Figure(size=(1800, 1200), fontsize=22)
libraries = ["JuliaMSI", "MALDIquant", "Cardinal"]
colors = ["#10b981", "#3b82f6", "#8b5cf6"] # green, blue, purple
x_pos = 1:length(unique_datasets)
# ---------- Panel A: Load Time (Log Scale) ----------
ax1 = Axis(fig[1, 1],
title="Panel A: Metadata/File Load Time",
ylabel="Time (seconds) - Log Scale",
yscale=log10,
xticks=(x_pos, unique_datasets), xticklabelrotation=π/8)
# ---------- Panel B: Memory Consumption (Log Scale) ----------
ax2 = Axis(fig[1, 2],
title="Panel B: Max RAM Footprint",
ylabel="Memory (MB) - Log Scale",
yscale=log10,
xticks=(x_pos, unique_datasets), xticklabelrotation=π/8)
# ---------- Panel C: Slice Generation Time (Log Scale) ----------
ax3 = Axis(fig[2, 1:2],
title="Panel C: Slice Generation Time (Mean ± SD)",
ylabel="Time (seconds) - Log Scale",
yscale=log10,
xticks=(x_pos, unique_datasets), xticklabelrotation=π/8)
width = 0.25
offsets = [-width, 0.0, width]
for (idx, lib) in enumerate(libraries)
lib_df = df[df.Library .== lib, :]
if isempty(lib_df) continue end
load_times = Float64[]
load_mems = Float64[]
slice_means = Float64[]
slice_stds = Float64[]
for ds in unique_datasets
row = lib_df[lib_df.Dataset .== ds, :]
if nrow(row) > 0 && row.Status[1] == "Success"
push!(load_times, coalesce(row.LoadTime_s[1], 1e-3))
push!(load_mems, coalesce(row.LoadMem_MB[1], 1e-1))
push!(slice_means, coalesce(row.AvgSliceTime_s[1], 1e-4))
push!(slice_stds, coalesce(row.SliceStd_s[1], 0.0))
else
# Default tiny values for log plot positioning of missing runs
push!(load_times, 1e-3)
push!(load_mems, 1e-1)
push!(slice_means, 1e-4)
push!(slice_stds, 0.0)
end
end
barplot!(ax1, x_pos .+ offsets[idx], load_times, color=colors[idx], width=width, label=lib)
barplot!(ax2, x_pos .+ offsets[idx], load_mems, color=colors[idx], width=width, label=lib)
barplot!(ax3, x_pos .+ offsets[idx], slice_means, color=colors[idx], width=width, label=lib)
errorbars!(ax3, x_pos .+ offsets[idx], slice_means, slice_stds, color=:black, whiskerwidth=10)
end
axislegend(ax1, position=:lt)
axislegend(ax2, position=:lt)
axislegend(ax3, position=:rt)
save(joinpath(RESULTS_DIR, "cross_language_comparison.png"), fig)
println("Comparison dashboard saved to $(joinpath(RESULTS_DIR, "cross_language_comparison.png"))")
end
if abspath(PROGRAM_FILE) == @__FILE__
run_cross_benchmarks()
end
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env Rscript
# test/benchmark_r.R
args <- commandArgs(trailingOnly = TRUE)
if (length(args) < 6) {
stop("Usage: Rscript benchmark_r.R <library> <filepath> <mz> <tol> <num_reps> <output_csv>")
}
target_lib <- tolower(args[1])
filepath <- args[2]
mz_value <- as.numeric(args[3])
mz_tolerance <- as.numeric(args[4])
num_reps <- as.numeric(args[5])
output_csv <- args[6]
get_rss <- function() {
if (file.exists("/proc/self/status")) {
lines <- readLines("/proc/self/status")
vm_rss <- lines[grep("^VmRSS:", lines)]
if (length(vm_rss) > 0) {
rss_kb <- as.numeric(gsub("[^0-9]", "", vm_rss))
return(rss_kb / 1024) # MB
}
}
return(0)
}
# Ensure output directory exists
dir.create(dirname(output_csv), showWarnings = FALSE, recursive = TRUE)
if (target_lib == "maldiquant") {
# ------------------------------------------------------------
# Benchmarking MALDIquant
# ------------------------------------------------------------
message("\n[R] Loading MALDIquant and MALDIquantForeign...")
library(MALDIquant)
library(MALDIquantForeign)
gc()
rss_start <- get_rss()
message(paste("[R] MALDIquant - Loading:", basename(filepath)))
t_load_mq <- system.time({
spectra <- MALDIquantForeign::importImzMl(filepath, centroided = TRUE)
})["elapsed"]
rss_loaded_mq <- get_rss()
mem_load_mq <- max(0, rss_loaded_mq - rss_start)
message(paste("[R] MALDIquant - Generating slices (repetitions:", num_reps, ")..."))
t_slices_mq <- numeric(num_reps)
for (i in 1:num_reps) {
t_slices_mq[i] <- system.time({
slices <- MALDIquant::msiSlices(spectra, center = mz_value, tolerance = mz_tolerance)
})["elapsed"]
}
mean_time_mq <- mean(t_slices_mq)
results <- data.frame(
Library = "MALDIquant",
LoadTime_s = t_load_mq,
LoadMem_MB = mem_load_mq,
AvgSliceTime_s = mean_time_mq
)
write.csv(results, output_csv, row.names = FALSE)
message(paste("[R] MALDIquant results written to", output_csv))
} else if (target_lib == "cardinal") {
# ------------------------------------------------------------
# Benchmarking Cardinal
# ------------------------------------------------------------
message("\n[R] Loading Cardinal...")
library(Cardinal)
gc()
rss_start_card <- get_rss()
message(paste("[R] Cardinal - Loading:", basename(filepath)))
t_load_card <- system.time({
mse <- Cardinal::readMSIData(filepath)
})["elapsed"]
rss_loaded_card <- get_rss()
mem_load_card <- max(0, rss_loaded_card - rss_start_card)
message(paste("[R] Cardinal - Generating slices (repetitions:", num_reps, ")..."))
t_slices_card <- numeric(num_reps)
# Determine if we have MSImagingArrays (processed/unaligned spectra) or MSImagingExperiment
is_arrays <- inherits(mse, "MSImagingArrays")
for (i in 1:num_reps) {
t_slices_card[i] <- system.time({
if (is_arrays) {
# Processed dataset pathway (each pixel has different m/z values)
# Iterate over all spectra in parallel/loop and find target mass
slice_data <- sapply(seq_along(mse), function(idx) {
mzs <- Cardinal::mz(mse)[[idx]]
ints <- Cardinal::intensity(mse)[[idx]]
in_tol <- which(abs(mzs - mz_value) <= mz_tolerance)
if (length(in_tol) > 0) {
max(ints[in_tol])
} else {
0.0
}
})
} else {
# Continuous dataset pathway (shared m/z grid)
feat_idx <- Cardinal::features(mse, mz = mz_value, tolerance = mz_tolerance, units = "mz")
if (length(feat_idx) > 0) {
raw_data <- Cardinal::iData(mse)[feat_idx, , drop = FALSE]
if (length(feat_idx) > 1) {
slice_data <- apply(raw_data, 2, max)
} else {
slice_data <- as.numeric(raw_data)
}
} else {
slice_data <- rep(0, ncol(mse))
}
}
})["elapsed"]
}
mean_time_card <- mean(t_slices_card)
results <- data.frame(
Library = "Cardinal",
LoadTime_s = t_load_card,
LoadMem_MB = mem_load_card,
AvgSliceTime_s = mean_time_card
)
write.csv(results, output_csv, row.names = FALSE)
message(paste("[R] Cardinal results written to", output_csv))
} else {
stop(paste("Unknown library requested:", target_lib))
}
+133 -67
View File
@@ -1,11 +1,10 @@
# test/benchmark_v3.jl
# ===================================================================
# High-Precision Performance Benchmark Suite (v3)
# High-Precision Performance Benchmark Suite (v3) - Cross-Engine
# ===================================================================
# This script integrates the robust statistical sampling of `BenchmarkTools`
# with the visual comparative mechanics against the legacy library.
# It captures the paradigm shift from "Time per slice" to "Pipeline Throughput".
# Compares JuliaMSI (New) vs julia_mzML_imzML (Legacy)
# Integrates formal academic metrics, error bars, and log-scale plots.
# ===================================================================
using Pkg
@@ -17,7 +16,6 @@ using CSV
using CairoMakie
using Statistics
using MSI_src
using julia_mzML_imzML
struct BenchmarkCase
filepath::String
@@ -27,13 +25,14 @@ struct BenchmarkCase
end
const RESULTS_DIR = joinpath(@__DIR__, "results")
const NUM_REPETITIONS = 10
# List to benchmark
const BENCHMARK_CASES = [
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML", 436.04, 0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Chilli/ltpmsi-chilli.imzML", 420.0, 0.1, "Chilli Pepper"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/40TopL,10TopR,30BottomL,20BottomR/40TopL,10TopR,30BottomL,20BottomR-centroid.imzML", 885.5, 0.1, "Colon Cancer Human"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053, 0.1, "Mouse Urinary Bladder"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML", 306.1, 0.1, "Leaf"),
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML", 306.1, 0.1, "Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Liv2_imzML_TIMSConvert-selected/Liv2.imzML", 796.18, 0.1, "Liver Cut"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida_Tims/Stomach_DHB.imzML", 804.3, 0.1, "Mouse Stomach 4GB")
]
@@ -48,7 +47,6 @@ end
function flush_memory()
GC.gc(true)
if Sys.islinux()
# Force the OS to reclaim memory from the glibc allocator
ccall(:malloc_trim, Int32, (Int32,), 0)
end
end
@@ -76,18 +74,17 @@ function run_v3_benchmarks()
println("[JuliaMSI - New Engine]")
flush_memory()
# Load Phase (Metadata Only / Memory Mapping)
load_stats_new = @timed OpenMSIData(case.filepath)
msi_data = load_stats_new.value
load_time_new_s = load_stats_new.time
mem_load_new_mb = load_stats_new.bytes / 1024^2
# Slicing Phase (High Precision)
b_slice_new = @benchmark get_mz_slice($msi_data, $(case.mz_value), $(case.mz_tolerance)) samples=10 seconds=5
mean_time_new_s = mean(b_slice_new.times) / 1e9
# Benchmark slice generation and capture variability
b_slice_new = @benchmark get_mz_slice($msi_data, $(case.mz_value), $(case.mz_tolerance)) samples=NUM_REPETITIONS seconds=10
times_new_s = b_slice_new.times ./ 1e9
mean_time_new_s = mean(times_new_s)
std_time_new_s = std(times_new_s)
# Calculate Amortized Throughput (10 slices)
# Includes the 'Loading Wall' penalty
total_time_10_new = load_time_new_s + (10 * mean_time_new_s)
amortized_sps_new = 10.0 / total_time_10_new
@@ -99,65 +96,120 @@ function run_v3_benchmarks()
# ------------------------------------------------------------
println("[julia_mzML_imzML - Legacy]")
load_stats_old = try
@timed LoadImzml(case.filepath)
catch e
@warn "Legacy load failed: $e"
(time=Inf, bytes=Inf, value=nothing)
end
old_data = load_stats_old.value
mem_load_old_mb = load_stats_old.bytes / 1024^2
mem_load_old_mb = NaN
load_time_old_s = Inf
mean_time_old_s = Inf
std_time_old_s = 0.0
amortized_sps_old = 0.0
legacy_status = "Success"
if old_data !== nothing
b_slice_old = try
# Legacy can be extremely slow, constrain it heavily
@benchmark GetSlice($old_data, $(case.mz_value), $(case.mz_tolerance)) samples=3 seconds=10
# Skip files > 3 GB in legacy to prevent OOM / SIGKILL
if file_size > 5000
println("Skipping legacy benchmark for $(case.name) to prevent SIGKILL OOM.")
legacy_status = "OOM / Skipped"
else
temp_legacy_csv = joinpath(RESULTS_DIR, "temp_legacy_v3.csv")
rm(temp_legacy_csv, force=true)
legacy_cmd_str = """
using julia_mzML_imzML, Statistics, BenchmarkTools, CSV, DataFrames
try
load_stats = @timed LoadImzml("$(case.filepath)")
old_data = load_stats.value
mem_load_mb = load_stats.bytes / 1024^2
load_time_s = load_stats.time
b_slice = @benchmark GetSlice(\$old_data, $(case.mz_value), $(case.mz_tolerance)) samples=$NUM_REPETITIONS seconds=10
times_s = b_slice.times ./ 1e9
df = DataFrame(
LoadMem_MB=[mem_load_mb],
LoadTime_s=[load_time_s],
SliceMean_s=[mean(times_s)],
SliceStd_s=[std(times_s)]
)
CSV.write("$(temp_legacy_csv)", df)
catch e
@warn "Legacy slice failed: $e"
nothing
df = DataFrame(LoadMem_MB=[NaN], LoadTime_s=[Inf], SliceMean_s=[NaN], SliceStd_s=[0.0])
CSV.write("$(temp_legacy_csv)", df)
end
"""
if b_slice_old !== nothing
mean_time_old_s = mean(b_slice_old.times) / 1e9
try
run(`julia --project=. -e $(legacy_cmd_str)`)
if isfile(temp_legacy_csv)
legacy_df = CSV.read(temp_legacy_csv, DataFrame)
mem_load_old_mb = legacy_df.LoadMem_MB[1]
load_time_old_s = legacy_df.LoadTime_s[1]
mean_time_old_s = legacy_df.SliceMean_s[1]
std_time_old_s = legacy_df.SliceStd_s[1]
# Accurately reflect the massive load time in the throughput
load_time_old_s = load_stats_old.time
if isfinite(mean_time_old_s)
total_time_10_old = load_time_old_s + (10 * mean_time_old_s)
amortized_sps_old = 10.0 / total_time_10_old
else
legacy_status = "Failed"
end
rm(temp_legacy_csv, force=true)
else
legacy_status = "OOM / Failed"
end
catch e
@warn "Legacy process crashed: $e"
legacy_status = "OOM / Failed"
end
end
flush_memory()
# ------------------------------------------------------------
# Record
# Derived Metrics Calculation
# ------------------------------------------------------------
# Throughput (Slices per second)
tput_new = 1.0 / mean_time_new_s
tput_old = isfinite(mean_time_old_s) ? (1.0 / mean_time_old_s) : 0.0
# Memory Efficiency (MB RAM / GB File)
gb_file = file_size / 1024.0
mem_eff_new = mem_load_new_mb / gb_file
mem_eff_old = isfinite(mem_load_old_mb) ? (mem_load_old_mb / gb_file) : NaN
# Fold Speedup (Legacy / JuliaMSI)
speedup = isfinite(mean_time_old_s) ? (mean_time_old_s / mean_time_new_s) : NaN
# Load Bandwidth (MB/s)
bandwidth_new = file_size / load_time_new_s
bandwidth_old = isfinite(load_time_old_s) ? (file_size / load_time_old_s) : 0.0
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
# Legacy Metrics
Legacy_LoadMem_MB = mem_load_old_mb,
Legacy_LoadTime_s = load_stats_old.time,
Legacy_Amortized_SPS_10 = amortized_sps_old,
# New Metrics
New_LoadMem_MB = mem_load_new_mb,
# New Engine (JuliaMSI)
New_LoadTime_s = load_time_new_s,
New_LoadMem_MB = mem_load_new_mb,
New_SliceMean_s = mean_time_new_s,
New_SliceStd_s = std_time_new_s,
New_Throughput_SPS = tput_new,
New_MemEff_MB_GB = mem_eff_new,
New_Bandwidth_MBs = bandwidth_new,
New_Amortized_SPS_10 = amortized_sps_new,
# Competitive Deltas
RAM_Reduction_Pct = isfinite(mem_load_old_mb) ? ((mem_load_old_mb - mem_load_new_mb) / mem_load_old_mb)*100 : NaN,
UX_Speedup_Factor = isfinite(amortized_sps_old) ? (amortized_sps_new / amortized_sps_old) : NaN
))
# Legacy Engine
Legacy_LoadTime_s = load_time_old_s,
Legacy_LoadMem_MB = mem_load_old_mb,
Legacy_SliceMean_s = mean_time_old_s,
Legacy_SliceStd_s = std_time_old_s,
Legacy_Throughput_SPS = tput_old,
Legacy_MemEff_MB_GB = mem_eff_old,
Legacy_Bandwidth_MBs = bandwidth_old,
Legacy_Amortized_SPS_10 = amortized_sps_old,
println(" > RAM Reduction: $(round(results[end, :RAM_Reduction_Pct], digits=2))%")
println(" > Amortized Throughput (10 Slices): $(round(amortized_sps_old, digits=2)) -> $(round(amortized_sps_new, digits=2)) slices/sec")
# Comparative Deltas
Fold_Speedup = speedup,
RAM_Reduction_Pct = isfinite(mem_load_old_mb) ? ((mem_load_old_mb - mem_load_new_mb) / mem_load_old_mb)*100 : NaN,
Legacy_Status = legacy_status
))
end
csv_path = joinpath(RESULTS_DIR, "v3_enterprise_benchmarks.csv")
@@ -171,45 +223,59 @@ end
function plot_v3_results(df::DataFrame)
if isempty(df) return end
fig = Figure(size=(1800, 1200), fontsize=24)
fig = Figure(size=(1800, 1200), fontsize=22)
x_pos = 1:nrow(df)
labels = df.Dataset
# ---------- Plot 1: The RAM Revolution ----------
# ---------- Panel A: Initial Load Time (Log Scale) ----------
ax1 = Axis(fig[1, 1],
title="Initial RAM Cost (Loading & Mmap)",
ylabel="Memory (MB)",
title="Panel A: Metadata/File Load Time",
ylabel="Time (seconds) - Log Scale",
yscale=log10,
xticks=(x_pos, labels), xticklabelrotation=π/8)
barplot!(ax1, x_pos .- 0.2, df.New_LoadMem_MB, color="#10b981", width=0.4, label="JuliaMSI (Mmap Lazy)")
barplot!(ax1, x_pos .+ 0.2, df.Legacy_LoadMem_MB, color="#ef4444", width=0.4, label="Legacy (Dense Matrix)")
barplot!(ax1, x_pos .- 0.2, df.New_LoadTime_s, color="#10b981", width=0.4, label="JuliaMSI")
# Only plot legacy if it succeeded
legacy_times = [row.Legacy_Status == "Success" ? row.Legacy_LoadTime_s : 1e-3 for row in eachrow(df)]
barplot!(ax1, x_pos .+ 0.2, legacy_times, color="#ef4444", width=0.4, label="Legacy")
axislegend(ax1, position=:lt)
# ---------- Plot 2: Throughput Leap ----------
# ---------- Panel B: Initial RAM Cost (Log Scale) ----------
ax2 = Axis(fig[1, 2],
title="Amortized Throughput (10 Slices - Higher is Better)",
ylabel="Slices / Second (Inc. Load Time)",
title="Panel B: Memory Footprint (RAM)",
ylabel="Memory (MB) - Log Scale",
yscale=log10,
xticks=(x_pos, labels), xticklabelrotation=π/8)
barplot!(ax2, x_pos .- 0.2, df.New_Amortized_SPS_10, color="#10b981", width=0.4, label="JuliaMSI")
barplot!(ax2, x_pos .+ 0.2, df.Legacy_Amortized_SPS_10, color="#ef4444", width=0.4, label="Legacy")
barplot!(ax2, x_pos .- 0.2, df.New_LoadMem_MB, color="#10b981", width=0.4, label="JuliaMSI (Mmap)")
legacy_mems = [row.Legacy_Status == "Success" ? row.Legacy_LoadMem_MB : 1e-1 for row in eachrow(df)]
barplot!(ax2, x_pos .+ 0.2, legacy_mems, color="#ef4444", width=0.4, label="Legacy (Dense)")
axislegend(ax2, position=:lt)
# ---------- Plot 3: The Scaling Wall (File Size vs Throughput) ----------
# ---------- Panel C: Slice Throughput & Error Bars ----------
ax3 = Axis(fig[2, 1:2],
title="Performance Scaling: UX Throughput vs Dataset Size",
xlabel="Dataset File Size (MB)",
ylabel="Amortized Throughput (Slices/sec)")
title="Panel C: Slice Generation Time (Mean ± SD)",
ylabel="Time (seconds) - Log Scale",
yscale=log10,
xticks=(x_pos, labels), xticklabelrotation=π/8)
scatterlines!(ax3, df.FileSize_MB, df.New_Amortized_SPS_10, color="#10b981", markersize=15, linewidth=4, label="JuliaMSI Engine")
scatterlines!(ax3, df.FileSize_MB, df.Legacy_Amortized_SPS_10, color="#ef4444", markersize=15, linewidth=4, label="Legacy Engine")
# Plot JuliaMSI times and error bars
barplot!(ax3, x_pos .- 0.2, df.New_SliceMean_s, color="#10b981", width=0.4, label="JuliaMSI")
errorbars!(ax3, x_pos .- 0.2, df.New_SliceMean_s, df.New_SliceStd_s, color=:black, whiskerwidth=15)
# Plot Legacy times and error bars (where successful)
legacy_means = [row.Legacy_Status == "Success" ? row.Legacy_SliceMean_s : 1e-4 for row in eachrow(df)]
legacy_stds = [row.Legacy_Status == "Success" ? row.Legacy_SliceStd_s : 0.0 for row in eachrow(df)]
barplot!(ax3, x_pos .+ 0.2, legacy_means, color="#ef4444", width=0.4, label="Legacy")
errorbars!(ax3, x_pos .+ 0.2, legacy_means, legacy_stds, color=:black, whiskerwidth=15)
axislegend(ax3, position=:rt)
save(joinpath(RESULTS_DIR, "v3_enterprise_dashboard.png"), fig)
println("\nDashboards saved successfully.")
println("\nDashboards saved successfully to $(joinpath(RESULTS_DIR, "v3_enterprise_dashboard.png"))")
end
# Ensure we process if run as the main script
if abspath(PROGRAM_FILE) == @__FILE__
run_v3_benchmarks()
end
+1 -1
View File
@@ -5,7 +5,7 @@ This document provides instructions on how to set up and run the test suite for
## Local Installation and Setup
### 1. Prerequisites
Make sure you have Julia installed (at least version 1.6). If not, we recommend using `juliaup` for installation.
Make sure you have Julia 1.11 or 1.12 installed. If not, we recommend using `juliaup` for installation.
- **juliaup**: [https://github.com/JuliaLang/juliaup](https://github.com/JuliaLang/juliaup)
- **Official binaries**: [https://julialang.org/downloads/](https://julialang.org/downloads/)
+10 -2
View File
@@ -15,13 +15,21 @@
# ===================================================================
using Printf
using CairoMakie
import Pkg
# --- Load the MSI_src Module ---
# Activate the project environment at the parent directory of this test script
# Activate the project environment before loading any project package.
Pkg.activate(joinpath(@__DIR__, ".."))
using MSI_src
using CairoMakie
using PlotlyBase
using Base.Threads
using MSI_src: ViridisPalette, save_bitmap, quantize_intensity, median_filter, TrIQ,
get_multiple_mz_slices, precompute_analytics, MutableSpectrum
# GUI-only plotting helpers (plot_slice, generate_colorbar_image, ...) live in
# the app layer so `using MSI_src` stays lightweight for headless use.
include(joinpath(@__DIR__, "..", "julia_imzML_visual.jl"))
# ===================================================================
+19 -4
View File
@@ -1,8 +1,5 @@
using Test
# We need to simulate loading the MSI_src module directly
include("../src/MSI_src.jl")
using .MSI_src
using MSI_src
@testset "JuliaMSI Core Systems" begin
@testset "Basic Instantiation" begin
@@ -55,4 +52,22 @@ using .MSI_src
buf2 = get_buffer!(pool, 1024)
@test buf === buf2 # Should return the EXACT same buffer object
end
@testset "Bloom Filter Hashing and Probing" begin
bf = MSI_src.BloomFilter{Int}(1000, 0.01)
inserted = collect(1:1000)
foreach(x -> push!(bf, x), inserted)
# Bloom filters must never produce false negatives.
@test all(x -> x in bf, inserted)
@test all(x -> MSI_src.contains(bf, x), inserted)
@test MSI_src.false_positive_rate(bf) > 0.0
@test MSI_src.fill_ratio(bf) > 0.0
end
@testset "Application Paths" begin
# `PUBLIC_DIR` must be absolute and independent of the caller's cwd.
@test isabspath(MSI_src.PUBLIC_DIR)
@test MSI_src.ensure_public_dir() == MSI_src.PUBLIC_DIR
end
end
+2 -1
View File
@@ -6,7 +6,8 @@ using Test
using Base.Threads
# --- Test Configuration ---
const TEST_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/Stomach/Stomach_DHB_uncompressed.imzML"
const TEST_FILE = get(ENV, "JULIA_MSI_TEST_IMZML",
"/home/pixel/Documents/Cinvestav_2025/Analisis/Stomach/Stomach_DHB_uncompressed.imzML")
println("Starting concurrency test with file: $TEST_FILE")
+3 -2
View File
@@ -12,7 +12,7 @@
# ============================================================================
using Pkg
Pkg.activate(".")
Pkg.activate(joinpath(@__DIR__, ".."))
using MSI_src
using SparseArrays
@@ -21,7 +21,8 @@ using SparseArrays
# Configuration
# =============================================================================
const IMZML_PATH = "/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML"
const IMZML_PATH = get(ENV, "JULIA_MSI_TEST_IMZML",
"/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML")
function main()
println("=" ^ 60)