Compare commits

..
Author SHA1 Message Date
Pixelguy14 bc71b9ce94 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 2026-11-17 11:26:39 -06:00
Pixelguy14 89de5a56e0 Fixed small issues within the file load and the precompiler script, added a final test benchmark suit to compare old Julia MSI library with current
CI / Julia 1.10 - macOS-latest - x64 - (pull_request) Has been cancelled
CI / Julia 1.10 - ubuntu-latest - x64 - (pull_request) Has been cancelled
CI / Julia 1.10 - windows-latest - x64 - (pull_request) Has been cancelled
2026-04-16 16:39:31 -06:00
Pixelguy14 05cb79253f cleaned the repository from dead code, simplified some functions, users can now create a system image of the JuliaMSI repo that runs the core dependencies faster without compiler time, alongside a docker environment for running scripts, the instructions are on the readme 2026-04-09 13:46:30 -06:00
Pixelguy14 8c37ea64aa fixed disk and memory bloat when loading several files, created zero-copy mmaps for msidata type objects for easier cache storage and less memory overhead, improved load times for files in general across the whole JuliaMSI environment 2026-04-09 12:30:43 -06:00
Pixelguy14 70fff16170 more secure locks and a script to create a system image of juliaMSI for faster boot times, still experimental but everything else remains pristine 2026-04-07 14:06:02 -06:00
Pixelguy14 e0ef601a9b hopefully fixed the JSON Lock for Windows 2026-04-06 15:41:38 -06:00
Pixelguy14 8b6bed0ff5 Hot fix to the precalculation atomic variable accountability, and other base threads safety 2026-03-12 12:51:16 -06:00
43 changed files with 4689 additions and 1864 deletions
BIN
View File
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
install.packages(c("XML", "readMzXmlData", "MALDIquantForeign"))
q()
+33
View File
@@ -0,0 +1,33 @@
name: CI
on:
push:
branches:
- main
pull_request:
jobs:
test:
name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ matrix.arch }} - ${{ github.event_name }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
version:
- '1.11'
- '1.12'
os:
- ubuntu-latest
- windows-latest
- macOS-latest
arch:
- x64
steps:
- uses: actions/checkout@v4
- uses: julia-actions/setup-julia@v2
with:
version: ${{ matrix.version }}
arch: ${{ matrix.arch }}
- uses: julia-actions/cache@v2
- uses: julia-actions/julia-buildpkg@v1
- uses: julia-actions/julia-runtest@v1
+3 -1
View File
@@ -7,4 +7,6 @@ log/*
R_original_scripts/
test/results/
test/binarization_results/
Manifest.toml
Manifest.toml
MSI_sysimage.dll
MSI_sysimage.so
+31
View File
@@ -0,0 +1,31 @@
# Dockerfile.headless
# This Dockerfile creates a minimal, high-speed container solely intended
# for running JuliaMSI scripts via the pre-compiled headless sysimage.
# It explicitly excludes the Genie UI and graphical routing to optimize size and start speed.
FROM julia:1.11
# System dependencies for core MSI math libraries
RUN apt-get update && apt-get install -y \
build-essential \
zlib1g-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Only copy essential library files (no UI or app.jl required)
COPY Project.toml Manifest.toml ./
COPY src/ ./src/
COPY build_sysimage.jl precompile_script.jl ./
COPY test/ ./test/
# Instantiate the environment
RUN julia --project=. -e 'import Pkg; Pkg.instantiate(); Pkg.precompile()'
# Build the headless sysimage
# This command strips out Genie and plot libraries, creating a pure data-engine .so
RUN julia --project=. build_sysimage.jl --headless
# The resulting image is heavily optimized for zero-JIT execution.
# Default command simply enters a fast REPL.
CMD ["julia", "--project=.", "--threads", "auto", "-J", "sys_msi_headless.so"]
+13 -4
View File
@@ -1,4 +1,5 @@
name = "MSI_src"
uuid = "8f395f85-3b9c-4f7f-bf7e-12345678abcd"
authors = ["JJSA"]
version = "0.1.0"
@@ -14,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"
@@ -35,6 +35,7 @@ Loess = "4345ca2d-374a-55d4-8d30-97f9976e7612"
Mmap = "a63ad114-7e13-5084-954f-fe012c677804"
NativeFileDialog = "e1fe445b-aa65-4df4-81c1-2041507f0fd4"
NaturalSort = "c020b1a1-e9b0-503a-9c33-f039bfc54a85"
PackageCompiler = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d"
Parameters = "d96e819e-fc66-5662-9728-84c9c7592b0a"
PlotlyBase = "a03496cd-edff-5a9b-9e67-9cda94a718b5"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
@@ -42,6 +43,7 @@ ProgressMeter = "92933f4c-e287-5a05-a399-4b506db050ca"
SavitzkyGolay = "c4bf5708-b6a6-4fbe-bcd0-6850ed671584"
Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
Setfield = "efcf1570-3423-57d1-acb7-fd33fddbac46"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
StipplePlotly = "ec984513-233d-481d-95b0-a3b58b97af2b"
@@ -52,18 +54,16 @@ Accessors = "0.1"
Base64 = "1.11"
CSV = "0.10"
CairoMakie = "0.13"
CodecBase = "0.3"
ColorSchemes = "3.30"
Colors = "0.12"
CodecBase = "0.3"
ContinuousWavelets = "1.1"
DataFrames = "1.7"
Dates = "1.11"
FileIO = "1.17"
GLMakie = "0.11"
Genie = "5.31"
GenieFramework = "2.8"
HistogramThresholding = "0.3"
Interpolations = "0.15"
ImageBinarization = "0.3"
ImageComponentAnalysis = "0.2"
ImageContrastAdjustment = "0.3"
@@ -72,6 +72,7 @@ ImageFiltering = "0.7"
ImageMorphology = "0.4"
ImageSegmentation = "1.9"
Images = "0.26"
Interpolations = "0.15"
JLD2 = "0.6"
JSON = "0.21"
Libz = "1.0"
@@ -80,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"
@@ -90,5 +92,12 @@ Setfield = "1.1"
Statistics = "1.11"
StatsBase = "0.34"
StipplePlotly = "0.13"
Test = "1.11.0"
UUIDs = "1.11"
julia = "1.11, 1.12"
[extras]
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[targets]
test = ["Test"]
+64 -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>
@@ -34,6 +45,47 @@ Minimum system requirements: 4 core processor, 8 GB RAM<br>
JuliaMSI is a Graphical User Interface for a library of MSI tools in Julia: https://github.com/CINVESTAV-LABI/julia_mzML_imzML
## Build the System Image (One-time)
Alternatively, you can generate custom pre-compiled `.so` / `.dll` system images by running the build script in your directory. This bakes the heavy mass-spectrometry kernels and UI dependencies into a single machine-code binary for ultra-fast startup times.
### 1. Build the GUI Sysimage (for full App usage)
```bash
julia --project=. build_sysimage.jl
```
This may take 5–15 minutes. The resulting `sys_msi_gui.so` (or `.dll` on Windows) file will be around **300MB–600MB** because it contains the pre-compiled machine code for your entire graphical environment.
*Note: A sysimage built on Linux (.so) will not work on Windows. You must run the build script once on each target operating system.*
Once `sys_msi_gui.so` is created in your directory, adapt your launch command:
```bash
julia --project=. -e 'using Pkg; Pkg.precompile()'
# Adjust the .so extension to .dll if on Windows or .dylib if on macOS
julia --threads auto --project=. --sysimage sys_msi_gui.so start_MSI_GUI.jl
```
### 2. Build the Headless Sysimage (for Scripts & Data Scientists)
If you only want to run scripts or the core `MSI_src` engine without the overhead of the Genie web server and Plotly, you can build a stripped-down, high-speed system image:
```bash
julia --project=. build_sysimage.jl --headless
```
Launch your automated tests or custom processing scripts using the headless image to bypass virtually all compilation overhead:
```bash
julia --threads auto --project=. --sysimage sys_msi_headless.so test/test_streaming_pipeline.jl
```
### 3. Docker Option for High-Speed Processing
For maximum portability and execution speed without clutter, we provide a `Dockerfile.headless`. This option creates a minimal, ultra-fast container that completely omits `app.jl` and the web interface.
It automatically builds and bundles the headless sysimage, giving researchers an instant-start engine ready for heavy-duty `.imzML` batch pipelines with zero JIT latency.
To build and run the Docker image:
```bash
docker build -t juliamsi-headless -f Dockerfile.headless .
# Run a script mapped from your local data folder:
docker run -it -v /my/local/data:/data juliamsi-headless julia -J sys_msi_headless.so /data/my_processing_script.jl
```
## License
JuliaMSI is published under the terms of the MIT License.
@@ -43,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).
+233 -135
View File
@@ -23,28 +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
# 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)
rss_kb = parse(Int, strip(rss_kb_str))
return round(rss_kb / 1024, digits=2)
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)
end
catch e
@warn "Could not get RSS via `ps` command. Error: $e"
return 0.0
@debug "Could not determine RSS" exception=e
end
return 0.0
end
function log_memory_usage(context::String, msi_data_val)
@@ -55,12 +64,13 @@ 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())")
println(" Process RSS: $(rss_mb) MB")
println(" msi_data size: $(msi_data_size_mb) MB")
println(" global_msi_data[] size: $(msi_data_size_mb) MB")
println(" Cumulative GC time: $(gc_time_s) s")
println("--------------------------")
end
@@ -193,6 +203,21 @@ macro ui_log(message, level="INFO", log_entries)
end
=#
# --- CRITICAL: Disable Stipple's session-to-disk persistence ---
# Stipple's ModelStorage registers on(field) handlers that serialize the ENTIRE
# ReactiveModel to disk via GenieSessionFileSession on every UI state change.
# With 253 reactive variables including multi-MB Plotly traces, this generates
# 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)
# 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
# == Notification & Logs ==
@@ -387,6 +412,7 @@ end
@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
@@ -451,7 +477,7 @@ end
@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 = ""
@@ -476,14 +502,14 @@ end
# == DATA MANAGEMENT VARIABLES ==
# Centralized MSIData object
@out msi_data::Union{MSIData, Nothing} = nothing
# global_msi_data[] is now global to avoid Genie Session memory leaks
# 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=""
@@ -655,13 +681,30 @@ end
# 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__)
try
# 1. Clear large data objects explicitly
msi_data = nothing
global_msi_data[] = nothing
feature_matrix_result = nothing
bin_info_result = nothing
@@ -676,10 +719,10 @@ end
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"
@@ -717,35 +760,49 @@ end
sure the file can be processed by later steps like mainProcess
=#
@onbutton btnSearch begin
is_processing = true
push!(__model__)
# 0. Robustness Guard: Prevent double-trigger during processing
if is_processing
println("DEBUG: btnSearch ignored because another process is already running.")
return
end
btnSearch = false # Manual reset of the trigger
# 1. Grab the file path from the main task
picked_route = pick_file(; filterlist="imzML,imzml,mzML,mzml")
if isnothing(picked_route) || isempty(picked_route)
is_processing = false
return
end
# --- Close previous dataset if one is open ---
if msi_data !== nothing
println("DEBUG: Closing previously loaded dataset before opening new one: $(basename(full_route))")
close(msi_data)
msi_data = nothing
GC.gc()
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
end
end
# 2. Update reactive state synchronously
is_processing = true
msg = "Opening file: $(basename(picked_route))..."
SpectraEnabled = false
btnMetadataDisable = true
push!(__model__)
try
dataset_name = replace(basename(picked_route), r"(\.(imzML|imzml|mzML|mzml))$"i => "")
# 3. Spawn background computational thread
Threads.@spawn begin
try
# --- Close previous dataset if one is open ---
if global_msi_data[] !== nothing
println("DEBUG: Closing previously loaded dataset before opening new one...")
close(global_msi_data[])
global_msi_data[] = nothing
GC.gc()
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
end
end
dataset_name = replace(basename(picked_route), r"(\.(imzML|imzml|mzML|mzml))$"i => "")
registry = load_registry(registry_path)
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)
@@ -757,8 +814,8 @@ end
dims = parse.(Int, split(dims_str, " x "))
imgWidth, imgHeight = dims[1], dims[2]
msi_data = nothing # Ensure data is not held in memory
log_memory_usage("Fast Load (msi_data cleared)", msi_data)
global_msi_data[] = nothing # Ensure data is not held in memory
log_memory_usage("Fast Load (global_msi_data[] cleared)", global_msi_data[])
btnMetadataDisable = false
SpectraEnabled = true
selected_folder_main = dataset_name
@@ -775,16 +832,11 @@ end
# --- 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
local_full_route = picked_route
end
# 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
full_route = local_full_route
sTime = time()
@@ -990,7 +1042,8 @@ end
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)
@@ -1000,10 +1053,10 @@ end
image_available_folders = deepcopy(img_folders)
selected_folder_main = dataset_name
msi_data = loaded_data
global_msi_data[] = loaded_data
# Determine plot mode from loaded data
df = msi_data.spectrum_stats_df
df = global_msi_data[].spectrum_stats_df
if df !== nothing && "Mode" in names(df)
profile_count = count(==(MSI_src.PROFILE), df.Mode)
total_count = length(df.Mode)
@@ -1013,26 +1066,29 @@ end
last_plot_mode = "lines" # Default
end
log_memory_usage("Full Load", msi_data)
log_memory_usage("Full Load", global_msi_data[])
eTime = round(time() - sTime, digits=3)
msg = "Active file loaded in $(eTime) seconds. Dataset '$(dataset_name)' is ready for analysis."
SpectraEnabled = true
catch e
msi_data = nothing
msg = "Error loading active file: $e"
warning_msg = true
SpectraEnabled = false
btnMetadataDisable = true
@error "File loading failed" exception=(e, catch_backtrace())
finally
GC.gc() # Trigger garbage collection
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0) # Ensure Julia returns the freed memory to OS
catch e
global_msi_data[] = nothing
msg = "Error loading active file: $e"
warning_msg = true
SpectraEnabled = false
btnMetadataDisable = true
@error "File loading failed" exception=(e, catch_backtrace())
push!(__model__) # Force sending error back to UI immediately
finally
GC.gc() # Trigger garbage collection
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0) # Ensure Julia returns the freed memory to OS
end
is_processing = false
push!(__model__) # Clear spinner loop
end
is_processing = false
end
end
@@ -1232,6 +1288,11 @@ end
This reactive handler job is to run the full preprocessing pipeline on the selected dataset.
=#
@onbutton run_full_pipeline begin
if is_processing
println("DEBUG: run_full_pipeline ignored because another process is already running.")
return
end
run_full_pipeline = false # Manual reset
is_processing = true
push!(__model__)
overall_progress = 0.0
@@ -1259,9 +1320,9 @@ end
end
target_path = entry["source_path"]
# Ensure msi_data is for the currently selected file and load if needed
# Ensure global_msi_data[] is for the currently selected file and load if needed
# NOTE: For the pipeline, we will open a DEDICATED instance to avoid race conditions
# with the global msi_data used for plotting/interactive exploration.
# with the global global_msi_data[] used for plotting/interactive exploration.
println("DEBUG: Opening isolated MSIData instance for pipeline stability...")
pipeline_msi_data = OpenMSIData(target_path)
@@ -1434,7 +1495,11 @@ end
# --- 2. Parameter Assembly with Validation ---
current_pipeline_step = "Configuring parameters..."
println("DEBUG: Configuring parameters and validating enabled steps...")
ref_peaks = Dict{Float64, String}(p["mz"] => p["label"] for p in reference_peaks_list)
ref_peaks = Dict{Float64, String}(
parse(Float64, string(p["mz"])) => string(get(p, "label", ""))
for p in reference_peaks_list
if tryparse(Float64, string(p["mz"])) !== nothing
)
final_params = Dict{Symbol, Dict{Symbol, Any}}()
validation_errors = String[]
@@ -1682,9 +1747,9 @@ end
# Determine plot mode for this specific spectrum
spectrum_mode_for_plot = "lines" # Default to lines
if msi_data.spectrum_stats_df !== nothing && "Mode" in names(msi_data.spectrum_stats_df)
if selected_spectrum_id_for_plot > 0 && selected_spectrum_id_for_plot <= length(msi_data.spectrum_stats_df.Mode)
mode = msi_data.spectrum_stats_df.Mode[selected_spectrum_id_for_plot]
if global_msi_data[].spectrum_stats_df !== nothing && "Mode" in names(global_msi_data[].spectrum_stats_df)
if selected_spectrum_id_for_plot > 0 && selected_spectrum_id_for_plot <= length(global_msi_data[].spectrum_stats_df.Mode)
mode = global_msi_data[].spectrum_stats_df.Mode[selected_spectrum_id_for_plot]
if mode == MSI_src.CENTROID
spectrum_mode_for_plot = "stem"
end
@@ -1849,7 +1914,7 @@ end
# 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."
@@ -1935,7 +2000,7 @@ end
@onbutton recalculate_suggestions_btn begin
is_processing = true
push!(__model__)
if msi_data === nothing
if global_msi_data[] === nothing
msg = "Please load a file first."
warning_msg = true
return
@@ -1944,8 +2009,12 @@ end
try
msg = "Recalculating suggestions..."
ref_peaks = Dict(p["mz"] => p["label"] for p in reference_peaks_list)
recommended_params = main_precalculation(msi_data, reference_peaks=ref_peaks)
ref_peaks = Dict{Float64, String}(
parse(Float64, string(p["mz"])) => string(get(p, "label", ""))
for p in reference_peaks_list
if tryparse(Float64, string(p["mz"])) !== nothing
)
recommended_params = main_precalculation(global_msi_data[], reference_peaks=ref_peaks)
for (step_name, params) in recommended_params
@@ -2340,6 +2409,11 @@ end
end
@onbutton mainProcess @time begin
if is_processing
println("DEBUG: mainProcess ignored because another process is already running.")
return
end
mainProcess = false # Manual reset
# --- UI State Update ---
overall_progress = 0.0
progress_message = "Preparing batch process..."
@@ -2414,8 +2488,22 @@ end
else
push!(newly_created_folders, replace(basename(file_path), r"\.imzML$"i => ""))
end
# --- Periodic Memory Reclamation ---
# Force GC and return memory to the OS after processing each large file
GC.gc(true)
if Sys.islinux()
ccall(:malloc_trim, Cint, (Cint,), 0)
end
current_step += 1
end
# Final memory cleanup for the batch
GC.gc(true)
if Sys.islinux()
ccall(:malloc_trim, Cint, (Cint,), 0)
end
# --- 3. Final Report ---
total_time_end = round(time() - total_time_start, digits=3)
@@ -2459,7 +2547,7 @@ end
# 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))
@@ -2550,21 +2638,21 @@ end
return
end
if msi_data === nothing || full_route != target_path
if msi_data !== nothing
close(msi_data)
if global_msi_data[] === nothing || full_route != target_path
if global_msi_data[] !== nothing
close(global_msi_data[])
end
msg = "Reloading $(basename(target_path)) for analysis..."
full_route = target_path
msi_data = OpenMSIData(target_path)
global_msi_data[] = OpenMSIData(target_path)
if haskey(get(entry, "metadata", Dict()), "global_min_mz") && entry["metadata"]["global_min_mz"] !== nothing
raw_min = entry["metadata"]["global_min_mz"]
raw_max = entry["metadata"]["global_max_mz"]
min_val = isa(raw_min, Dict) ? get(raw_min, "value", raw_min) : raw_min
max_val = isa(raw_max, Dict) ? get(raw_max, "value", raw_max) : raw_max
set_global_mz_range!(msi_data, convert(Float64, min_val), convert(Float64, max_val))
set_global_mz_range!(global_msi_data[], convert(Float64, min_val), convert(Float64, max_val))
else
precompute_analytics(msi_data)
precompute_analytics(global_msi_data[])
end
end
@@ -2577,7 +2665,7 @@ end
end
end
plotdata, plotlayout, xSpectraMz, ySpectraMz = meanSpectrumPlot(msi_data, selected_folder_main, mask_path=mask_path_for_plot)
plotdata, plotlayout, xSpectraMz, ySpectraMz = meanSpectrumPlot(global_msi_data[], selected_folder_main, mask_path=mask_path_for_plot)
plotdata_before = plotdata
plotlayout_before = plotlayout
last_plot_type = "mean"
@@ -2585,7 +2673,7 @@ end
fTime = time()
eTime = round(fTime - sTime, digits=3)
msg = "Plot loaded in $(eTime) seconds"
log_memory_usage("Mean Plot Generated", msi_data)
log_memory_usage("Mean Plot Generated", global_msi_data[])
catch e
msg = "Could not generate mean spectrum plot: $e"
warning_msg = true
@@ -2639,21 +2727,21 @@ end
return
end
if msi_data === nothing || full_route != target_path
if msi_data !== nothing
close(msi_data)
if global_msi_data[] === nothing || full_route != target_path
if global_msi_data[] !== nothing
close(global_msi_data[])
end
msg = "Reloading $(basename(target_path)) for analysis..."
full_route = target_path
msi_data = OpenMSIData(target_path)
global_msi_data[] = OpenMSIData(target_path)
if haskey(get(entry, "metadata", Dict()), "global_min_mz") && entry["metadata"]["global_min_mz"] !== nothing
raw_min = entry["metadata"]["global_min_mz"]
raw_max = entry["metadata"]["global_max_mz"]
min_val = isa(raw_min, Dict) ? get(raw_min, "value", raw_min) : raw_min
max_val = isa(raw_max, Dict) ? get(raw_max, "value", raw_max) : raw_max
set_global_mz_range!(msi_data, convert(Float64, min_val), convert(Float64, max_val))
set_global_mz_range!(global_msi_data[], convert(Float64, min_val), convert(Float64, max_val))
else
precompute_analytics(msi_data)
precompute_analytics(global_msi_data[])
end
end
local mask_path_for_plot::Union{String, Nothing} = nothing
@@ -2665,7 +2753,7 @@ end
end
end
plotdata, plotlayout, xSpectraMz, ySpectraMz = sumSpectrumPlot(msi_data, selected_folder_main, mask_path=mask_path_for_plot)
plotdata, plotlayout, xSpectraMz, ySpectraMz = sumSpectrumPlot(global_msi_data[], selected_folder_main, mask_path=mask_path_for_plot)
plotdata_before = plotdata
plotlayout_before = plotlayout
last_plot_type = "sum"
@@ -2673,7 +2761,7 @@ end
fTime = time()
eTime = round(fTime - sTime, digits=3)
msg = "Total plot loaded in $(eTime) seconds"
log_memory_usage("Sum Plot Generated", msi_data)
log_memory_usage("Sum Plot Generated", global_msi_data[])
catch e
msg = "Could not generate total spectrum plot: $e"
warning_msg = true
@@ -2730,21 +2818,21 @@ end
return
end
if msi_data === nothing || full_route != target_path
if msi_data !== nothing
close(msi_data)
if global_msi_data[] === nothing || full_route != target_path
if global_msi_data[] !== nothing
close(global_msi_data[])
end
msg = "Reloading $(basename(target_path)) for analysis..."
full_route = target_path
msi_data = OpenMSIData(target_path)
global_msi_data[] = OpenMSIData(target_path)
if haskey(get(entry, "metadata", Dict()), "global_min_mz") && entry["metadata"]["global_min_mz"] !== nothing
raw_min = entry["metadata"]["global_min_mz"]
raw_max = entry["metadata"]["global_max_mz"]
min_val = isa(raw_min, Dict) ? get(raw_min, "value", raw_min) : raw_min
max_val = isa(raw_max, Dict) ? get(raw_max, "value", raw_max) : raw_max
set_global_mz_range!(msi_data, convert(Float64, min_val), convert(Float64, max_val))
set_global_mz_range!(global_msi_data[], convert(Float64, min_val), convert(Float64, max_val))
else
precompute_analytics(msi_data)
precompute_analytics(global_msi_data[])
end
end
@@ -2759,7 +2847,7 @@ end
# Convert to positive coordinates for processing
y_positive = yCoord < 0 ? abs(yCoord) : yCoord
plotdata, plotlayout, xSpectraMz, ySpectraMz, spectrum_id = xySpectrumPlot(msi_data, xCoord, y_positive, imgWidth, imgHeight, selected_folder_main, mask_path=mask_path_for_plot)
plotdata, plotlayout, xSpectraMz, ySpectraMz, spectrum_id = xySpectrumPlot(global_msi_data[], xCoord, y_positive, imgWidth, imgHeight, selected_folder_main, mask_path=mask_path_for_plot)
plotdata_before = plotdata
plotlayout_before = plotlayout
last_plot_type = "single"
@@ -2800,7 +2888,7 @@ end
fTime = time()
eTime = round(fTime - sTime, digits=3)
msg = "Plot loaded in $(eTime) seconds"
log_memory_usage("XY Plot Generated", msi_data)
log_memory_usage("XY Plot Generated", global_msi_data[])
catch e
msg = "Could not retrieve spectrum: $e"
warning_msg = true
@@ -2845,21 +2933,21 @@ end
return
end
if msi_data === nothing || full_route != target_path
if msi_data !== nothing
close(msi_data)
if global_msi_data[] === nothing || full_route != target_path
if global_msi_data[] !== nothing
close(global_msi_data[])
end
msg = "Reloading $(basename(target_path)) for analysis..."
full_route = target_path
msi_data = OpenMSIData(target_path)
global_msi_data[] = OpenMSIData(target_path)
if haskey(get(entry, "metadata", Dict()), "global_min_mz") && entry["metadata"]["global_min_mz"] !== nothing
raw_min = entry["metadata"]["global_min_mz"]
raw_max = entry["metadata"]["global_max_mz"]
min_val = isa(raw_min, Dict) ? get(raw_min, "value", raw_min) : raw_min
max_val = isa(raw_max, Dict) ? get(raw_max, "value", raw_max) : raw_max
set_global_mz_range!(msi_data, convert(Float64, min_val), convert(Float64, max_val))
set_global_mz_range!(global_msi_data[], convert(Float64, min_val), convert(Float64, max_val))
else
precompute_analytics(msi_data)
precompute_analytics(global_msi_data[])
end
end
@@ -2873,7 +2961,7 @@ end
end
# Call the new nSpectrumPlot function
plotdata, plotlayout, xSpectraMz, ySpectraMz, spectrum_id = nSpectrumPlot(msi_data, idSpectrum, selected_folder_main, mask_path=mask_path_for_plot)
plotdata, plotlayout, xSpectraMz, ySpectraMz, spectrum_id = nSpectrumPlot(global_msi_data[], idSpectrum, selected_folder_main, mask_path=mask_path_for_plot)
plotdata_before = plotdata
plotlayout_before = plotlayout
last_plot_type = "single"
@@ -2883,7 +2971,7 @@ end
fTime = time()
eTime = round(fTime - sTime, digits=3)
msg = "Plot loaded in $(eTime) seconds"
log_memory_usage("nSpectrum Plot Generated", msi_data)
log_memory_usage("nSpectrum Plot Generated", global_msi_data[])
catch e
msg = "Could not retrieve spectrum: $e"
warning_msg = true
@@ -2901,7 +2989,7 @@ end
@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
@@ -2923,7 +3011,7 @@ end
@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)
@@ -2945,7 +3033,7 @@ end
@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)
@@ -2966,7 +3054,7 @@ end
@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)
@@ -2989,7 +3077,7 @@ end
@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)
@@ -3011,7 +3099,7 @@ end
@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)
@@ -3033,7 +3121,7 @@ end
@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)
@@ -3055,7 +3143,7 @@ end
@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)
@@ -3077,7 +3165,7 @@ end
@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)
@@ -3099,7 +3187,7 @@ end
@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)
@@ -3121,7 +3209,7 @@ end
@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)
@@ -3143,7 +3231,7 @@ end
@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)
@@ -3164,11 +3252,11 @@ end
# This handler will now correctly load the first image from the newly selected folder.
@onchange selected_folder_main begin
# The msi_data object lifecycle is managed by the btnSearch handler.
# The global_msi_data[] object lifecycle is managed by the btnSearch handler.
# 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 = ""
@@ -3246,7 +3334,7 @@ end
@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 = "", "", "", ""
@@ -3301,7 +3389,7 @@ end
@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."
@@ -3396,7 +3484,7 @@ end
fTime = time()
eTime = round(fTime - sTime, digits=3)
msg = "Plot loaded in $(eTime) seconds"
log_memory_usage("Mean Plot Generated", msi_data)
log_memory_usage("Mean Plot Generated", global_msi_data[])
catch e
msg = "Failed to load and process image: $e"
warning_msg = true
@@ -3454,7 +3542,7 @@ end
fTime = time()
eTime = round(fTime - sTime, digits=3)
msg = "Plot loaded in $(eTime) seconds"
log_memory_usage("Mean Plot Generated", msi_data)
log_memory_usage("Mean Plot Generated", global_msi_data[])
catch e
msg = "Failed to load and process image: $e"
warning_msg = true
@@ -3555,7 +3643,7 @@ end
# To include a visualization in the spectrum plot indicating where is the selected mass
@onchange Nmass begin
if !isempty(xSpectraMz)
df = msi_data.spectrum_stats_df
df = global_msi_data[].spectrum_stats_df
plot_as_lines = false # Default to stem
if df !== nothing && hasproperty(df, :Mode) && !isempty(df.Mode)
profile_count = count(==(MSI_src.PROFILE), df.Mode)
@@ -3761,13 +3849,22 @@ end
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)
@@ -3790,7 +3887,8 @@ end
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)
@@ -3814,7 +3912,7 @@ end
eTime=round(fTime-sTime,digits=3)
is_initializing = false # Hide loading screen when initialization is complete (current code is hidden due to incompatibility)
msg = "The app took $(eTime) seconds to get ready."
log_memory_usage("App Ready", msi_data)
log_memory_usage("App Ready", global_msi_data[])
end
# is_processing = false
GC.gc() # Trigger garbage collection
+16 -7
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>
@@ -546,13 +549,19 @@
</q-list>
<!-- Pipeline Controls -->
<div class="row justify-end items-center q-mt-md">
<q-btn class="q-ma-sm" icon="get_app" v-on:click="export_params_btn=true" label="Export Params" outline
:disable="is_processing" />
<q-btn class="q-ma-sm" icon="upload_file" v-on:click="import_params_btn=true" label="Import Params" outline
:disable="is_processing" />
<q-btn :loading="is_processing" class="q-ma-sm btn-style" icon="play_arrow"
v-on:click="run_full_pipeline=true" padding="lg" label="Run Pipeline" :disable="is_processing" />
<div class="row q-mt-md justify-between items-center text-caption text-grey">
<div>
<q-icon name="info" class="q-mr-xs" /> Feature matrices are exported in highly optimized MatrixMarket Coordinate format (<b>.mtx</b>).
<br/><i>Python:</i> <code>scipy.io.mmread('filtered_data.mtx')</code> | <i>R:</i> <code>Matrix::readMM('filtered_data.mtx')</code>
</div>
<div>
<q-btn class="q-ma-sm" icon="get_app" v-on:click="export_params_btn=true" label="Export Params" outline
:disable="is_processing" />
<q-btn class="q-ma-sm" icon="upload_file" v-on:click="import_params_btn=true" label="Import Params" outline
:disable="is_processing" />
<q-btn :loading="is_processing" class="q-ma-sm btn-style" icon="play_arrow"
v-on:click="run_full_pipeline=true" padding="lg" label="Run Pipeline" :disable="is_processing" />
</div>
</div>
</q-tab-panel>
<q-tab-panel name="generator">
+51
View File
@@ -0,0 +1,51 @@
# build_sysimage.jl
using Pkg
Pkg.activate(@__DIR__)
using PackageCompiler
headless = "--headless" in ARGS
println("--- Starting Custom System Image Build ---")
println("Mode: ", headless ? "Headless (Scripting/Docker)" : "Full GUI (Genie App)")
println("This process can take 5-15 minutes.")
ext = Sys.iswindows() ? ".dll" : Sys.isapple() ? ".dylib" : ".so"
sysimage_name = headless ? "sys_msi_headless" * ext : "sys_msi_gui" * ext
sysimage_path = joinpath(@__DIR__, sysimage_name)
packages_to_include = Symbol[
:MSI_src, # <--- Bake our core library
:DataFrames,
:SparseArrays,
:Mmap,
:Libz,
:Serialization,
:Printf,
:JSON
]
if !headless
append!(packages_to_include, [
:Genie,
:GenieFramework,
:PlotlyBase
])
end
create_sysimage(
packages_to_include,
sysimage_path = sysimage_path,
precompile_execution_file = joinpath(@__DIR__, "precompile_script.jl"),
incremental = true,
filter_stdlibs = false
)
println("--- System Image Build Successful! ---")
println("Created: $(sysimage_path)")
if headless
println("To use in a headles script:")
println("julia --threads auto --project=. --sysimage $(sysimage_name) my_script.jl")
else
println("To start Julia with the GUI image, use:")
println("julia --threads auto --project=. --sysimage $(sysimage_name) start_MSI_GUI.jl")
end
+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
+526 -157
View File
@@ -1,5 +1,7 @@
# julia_imzML_visual.jl
using Dates, JSON, Printf
"""
increment_image(current_image, image_list)
@@ -269,7 +271,7 @@ function loadContourPlot(interfaceImg::String)
img_gray=Gray.(img)
img_array=Array(img_gray)
elevation=Float32.(Array(img_array))./ 255.0 # Normalize between 0 and 1
# Smooth the image
sigma=3.0
kernel=Kernel.gaussian(sigma)
@@ -278,7 +280,7 @@ function loadContourPlot(interfaceImg::String)
# --- DOWNSAMPLING FOR PERFORMANCE ---
elevation_smoothed = downsample_image(elevation_smoothed, 512)
# ---
# Create the X, Y meshgrid coordinates
x=1:size(elevation_smoothed, 2)
y=1:size(elevation_smoothed, 1)
@@ -290,7 +292,7 @@ function loadContourPlot(interfaceImg::String)
max_val = maximum(elevation_smoothed)
tickV = range(min_val, stop=max_val, length=8)
tickT = log_tick_formatter(collect(tickV))
layout=PlotlyBase.Layout(
title=PlotlyBase.attr(
text="2D topographic map of $cleaned_img (downsampled)",
@@ -313,7 +315,7 @@ function loadContourPlot(interfaceImg::String)
z=elevation_smoothed,
x=X[1, :], # Use the first row
y=-Y[:, 1], # Use the first column
contours_coloring="Viridis",
contours_coloring="Viridis",
colorscale="Viridis",
colorbar = attr(
tickvals = tickV,
@@ -347,8 +349,8 @@ function loadSurfacePlot(interfaceImg::String)
img_gray=Gray.(img) # Convert to grayscale
img_array=Array(img_gray)
elevation=Float32.(Array(img_array)) ./ 255.0 # Normalize between 0 and 1
# Smooth the image
# Smooth the image
sigma=3.0
kernel=Kernel.gaussian(sigma)
elevation_smoothed=imfilter(elevation, kernel)
@@ -356,9 +358,9 @@ function loadSurfacePlot(interfaceImg::String)
# --- DOWNSAMPLING FOR PERFORMANCE ---
elevation_smoothed = downsample_image(elevation_smoothed, 256)
# ---
# Create the X, Y meshgrid coordinates
x=1:size(elevation_smoothed, 2)
# Create the X, Y meshgrid coordinates
x=1:size(elevation_smoothed, 2)
y=1:size(elevation_smoothed, 1)
X=repeat(reshape(x, 1, length(x)), length(y), 1)
Y=repeat(reshape(y, length(y), 1), 1, length(x))
@@ -387,8 +389,8 @@ function loadSurfacePlot(interfaceImg::String)
scene=attr(
xaxis_nticks=x_nticks,
yaxis_nticks=y_nticks,
zaxis_nticks=z_nticks,
camera=attr(eye=attr(x=0, y=1, z=0.5)),
zaxis_nticks=z_nticks,
camera=attr(eye=attr(x=0, y=1, z=0.5)),
aspectratio=aspect_ratio
),
margin=attr(l=0,r=0,t=120,b=0,pad=0)
@@ -402,15 +404,15 @@ function loadSurfacePlot(interfaceImg::String)
end
trace3D=PlotlyBase.surface(
x=X[1, :],
y=Y[:, 1],
x=X[1, :],
y=Y[:, 1],
z=elevation_smoothed,
contours_z=attr(
show=true,
usecolormap=true,
highlightcolor="limegreen",
project_z=true
),
),
colorscale="Viridis",
colorbar = attr(
tickvals = tickV,
@@ -508,9 +510,9 @@ function meanSpectrumPlot(data::MSIData, dataset_name::String=""; mask_path::Uni
else
"Average Spectrum"
end
title_text = isempty(dataset_name) ? base_title : "$base_title for: $dataset_name"
layout = PlotlyBase.Layout(
title=PlotlyBase.attr(
text=title_text,
@@ -532,9 +534,9 @@ function meanSpectrumPlot(data::MSIData, dataset_name::String=""; mask_path::Uni
),
margin=attr(l=0, r=0, t=120, b=0, pad=0),
legend=attr(
x=1.0,
y=1.0,
xanchor="right",
x=1.0,
y=1.0,
xanchor="right",
yanchor="top"
)
)
@@ -672,9 +674,9 @@ function xySpectrumPlot(data::MSIData, xCoord::Int, yCoord::Int, imgWidth::Int,
),
margin=attr(l=0, r=0, t=120, b=0, pad=0),
legend=attr(
x=1.0,
y=1.0,
xanchor="right",
x=1.0,
y=1.0,
xanchor="right",
yanchor="top"
)
)
@@ -763,9 +765,9 @@ function nSpectrumPlot(data::MSIData, id::Int, dataset_name::String=""; mask_pat
),
margin=attr(l=0, r=0, t=120, b=0, pad=0),
legend=attr(
x=1.0,
y=1.0,
xanchor="right",
x=1.0,
y=1.0,
xanchor="right",
yanchor="top"
)
)
@@ -807,9 +809,9 @@ function sumSpectrumPlot(data::MSIData, dataset_name::String=""; mask_path::Unio
else
"Total Spectrum"
end
title_text = isempty(dataset_name) ? base_title : "$base_title for: $dataset_name"
layout = PlotlyBase.Layout(
title=PlotlyBase.attr(
text=title_text,
@@ -831,9 +833,9 @@ function sumSpectrumPlot(data::MSIData, dataset_name::String=""; mask_path::Unio
),
margin=attr(l=0, r=0, t=120, b=0, pad=0),
legend=attr(
x=1.0,
y=1.0,
xanchor="right",
x=1.0,
y=1.0,
xanchor="right",
yanchor="top"
)
)
@@ -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")
@@ -903,6 +905,54 @@ function warmup_init()
end
end
"""
clean_registry_path(registry_path::String)
Sanitizes the file path to prevent OS/file system issues, particularly on Windows,
by standardizing separators and removing stripping whitespace.
"""
function clean_registry_path(registry_path::String)
# Standardize to forward slashes internally for uniformity, then normpath formats for OS
clean_path = normpath(strip(replace(registry_path, "\\" => "/")))
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)
@@ -912,125 +962,157 @@ 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)
function load_registry(registry_path::String)
return lock(REGISTRY_LOCK) do
clean_path = abspath(registry_path)
if isfile(clean_path)
for attempt in 1:5
try
return JSON.parsefile(clean_path, dicttype=Dict{String,Any})
catch e
if attempt == 5
@error "Final attempt failed to parse registry.json: $(sprint(showerror, e))"
return Dict{String,Any}()
else
@warn "Attempt $attempt to read registry.json failed, retrying in 0.2s... Error: $(sprint(showerror, e))"
sleep(0.2)
clean_path = clean_registry_path(registry_path)
isfile(clean_path) || return Dict{String,Any}()
for attempt in 1:6
try
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 == 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}()
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
"""
extract_metadata(msi_data::MSIData, source_path::String)
extract_metadata(loaded_data::MSIData, full_route::String)
Extracts key metadata from an `MSIData` object for display.
# Arguments
- `msi_data`: The `MSIData` object.
- `source_path`: The path to the source data file.
# Returns
- A dictionary containing summary statistics and metadata.
Extracts key metadata from an MSIData object and file path for UI display.
Returns a dictionary with a "summary" key containing parameter-value pairs.
"""
function extract_metadata(msi_data::MSIData, source_path::String)
df = msi_data.spectrum_stats_df
if df === nothing
# This can happen if precompute_analytics hasn't been run
# We can still return basic info
return Dict(
"summary" => [
Dict("parameter" => "File Name", "value" => basename(source_path)),
Dict("parameter" => "Number of Spectra", "value" => length(msi_data.spectra_metadata)),
Dict("parameter" => "Image Dimensions", "value" => "$(msi_data.image_dims[1]) x $(msi_data.image_dims[2])"),
],
"global_min_mz" => nothing,
"global_max_mz" => nothing
)
function extract_metadata(loaded_data::MSIData, full_route::String)
stats = []
# Basic File Info
push!(stats, Dict("parameter" => "Filename", "value" => basename(full_route)))
push!(stats, Dict("parameter" => "Source Path", "value" => full_route))
# Image Dimensions
w, h = loaded_data.image_dims
if w > 0 && h > 0
push!(stats, Dict("parameter" => "Image Dimensions", "value" => "$w x $h"))
else
push!(stats, Dict("parameter" => "Image Dimensions", "value" => "N/A (Non-imaging)"))
end
summary_stats = [
Dict("parameter" => "File Name", "value" => basename(source_path)),
Dict("parameter" => "Number of Spectra", "value" => length(msi_data.spectra_metadata)),
Dict("parameter" => "Image Dimensions", "value" => "$(msi_data.image_dims[1]) x $(msi_data.image_dims[2])"),
Dict("parameter" => "Global Min m/z", "value" => @sprintf("%.4f", Threads.atomic_add!(msi_data.global_min_mz, 0.0))),
Dict("parameter" => "Global Max m/z", "value" => @sprintf("%.4f", Threads.atomic_add!(msi_data.global_max_mz, 0.0))),
Dict("parameter" => "Mean TIC", "value" => @sprintf("%.2e", mean(df.TIC))),
Dict("parameter" => "Mean BPI", "value" => @sprintf("%.2e", mean(df.BPI))),
Dict("parameter" => "Mean # Points", "value" => @sprintf("%.1f", mean(df.NumPoints))),
]
# Spectrum Counts
num_spectra = length(loaded_data.spectra_metadata)
push!(stats, Dict("parameter" => "Total Spectra", "value" => string(num_spectra)))
if hasproperty(df, :Mode)
centroid_count = count(==(MSI_src.CENTROID), df.Mode)
profile_count = count(==(MSI_src.PROFILE), df.Mode)
unknown_count = count(==(MSI_src.UNKNOWN), df.Mode)
# m/z Range
min_mz, max_mz = get_global_mz_range(loaded_data)
if isfinite(min_mz) && isfinite(max_mz)
push!(stats, Dict("parameter" => "Global m/z Range", "value" => "$(round(min_mz, digits=4)) - $(round(max_mz, digits=4))"))
else
push!(stats, Dict("parameter" => "Global m/z Range", "value" => "Unknown"))
end
push!(summary_stats, Dict("parameter" => "Centroid Spectra", "value" => string(centroid_count)))
push!(summary_stats, Dict("parameter" => "Profile Spectra", "value" => string(profile_count)))
if unknown_count > 0
push!(summary_stats, Dict("parameter" => "Unknown Mode Spectra", "value" => string(unknown_count)))
# Instrument Metadata
if loaded_data.instrument_metadata !== nothing
inst = loaded_data.instrument_metadata
push!(stats, Dict("parameter" => "Instrument Model", "value" => inst.instrument_model))
push!(stats, Dict("parameter" => "Polarity", "value" => titlecase(string(inst.polarity))))
push!(stats, Dict("parameter" => "Acquisition Mode", "value" => titlecase(string(inst.acquisition_mode))))
if inst.resolution !== nothing
push!(stats, Dict("parameter" => "Instrument Resolution", "value" => string(inst.resolution)))
end
end
return Dict(
"summary" => summary_stats,
"global_min_mz" => msi_data.global_min_mz,
"global_max_mz" => msi_data.global_max_mz
)
return Dict("summary" => stats)
end
"""
save_registry(registry_path, registry_data)
save_registry(registry_path::String, registry_data::Dict)
Saves the dataset registry to a JSON file, ensuring thread-safe access and robustness on Windows.
# Arguments
- `registry_path`: Path to the `registry.json` file.
- `registry_data`: The dictionary containing the registry data to save.
Saves the dataset registry to a JSON file atomically to prevent data loss
and sharing violations on Windows. Writes to a `.tmp` file first.
"""
function save_registry(registry_path, registry_data)
function save_registry(registry_path::String, registry_data)
lock(REGISTRY_LOCK) do
# Ensure the path is clean and valid for the OS
clean_path = abspath(registry_path)
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
# On Windows, opening files for writing can occasionally fail if another process
# (like an anti-virus or file indexer) holds a transient lock.
# Retry with a small delay to improve robustness.
for attempt in 1:5
# 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
open(clean_path, "w") do f
JSON.print(f, registry_data, 4)
end
return true # Success
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
if attempt == 5
@error "Final attempt failed to write to registry.json: $(sprint(showerror, e))"
return false
else
@warn "Attempt $attempt to write to registry.json failed (Error: $(sprint(showerror, e))), retrying in 0.2s..."
sleep(0.2)
@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
mv(temp_path, clean_path; force=true)
return true
catch e
if attempt == 6
@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
end
sleep(0.05 * 2.0^(attempt - 1) + 0.05 * rand())
end
end
return false
end
end
@@ -1047,31 +1129,26 @@ Adds or updates an entry in the dataset registry JSON file.
- `metadata`: Optional dictionary of metadata to store.
- `is_imzML`: Boolean indicating if the source is an imzML file.
"""
function update_registry(registry_path, dataset_name, source_path, metadata=nothing, is_imzML=false)
lock(REGISTRY_LOCK) do
function update_registry(registry_path::String, dataset_name::String, source_path::String, metadata=nothing, is_imzML=false)
saved = lock(REGISTRY_LOCK) do
registry = load_registry(registry_path)
# Get existing entry if it exists, otherwise create new one
existing_entry = get(registry, dataset_name, Dict{String,Any}())
# Start with existing data and update only the basic fields
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
# Only update metadata if provided
if metadata !== nothing
entry["metadata"] = metadata
end
# Note: has_mask and mask_path are preserved from existing_entry if they exist
registry[dataset_name] = entry
# Use the robust save function
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
"""
@@ -1095,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
@@ -1138,45 +1215,53 @@ function process_file_safely(file_path, masses, params, progress_message_ref, ov
# --- Extract metadata ---
metadata = extract_metadata(local_msi_data, file_path)
# --- Save Slices ---
# --- Save Slices (Parallelized) ---
mkpath(output_dir)
for (mass_idx, mass) in enumerate(masses)
progress_message_ref = "File $(params.fileIdx)/$(params.nFiles): Saving slice for m/z=$mass"
progress_lock = ReentrantLock()
# Parallelize over the requested masses to fully utilize multi-core CPUs
Threads.@threads for mass in masses
slice = slice_dict[mass]
text_nmass = replace(string(mass), "." => "_")
bitmap_filename = params.triqE ? "TrIQ_$(text_nmass).bmp" : "MSI_$(text_nmass).bmp"
colorbar_filename = params.triqE ? "colorbar_TrIQ_$(text_nmass).png" : "colorbar_MSI_$(text_nmass).png"
local sliceQuant, bounds
if all(iszero, slice)
sliceQuant = zeros(UInt8, size(slice))
bounds = (0.0, 1.0) # Default bounds for empty slice
@warn "No intensity data for m/z = $mass in $(dataset_name)"
else
# Get both quantized data AND bounds in one call
# TrIQ and quantization are computationally intensive and now run in parallel
if params.triqE
sliceQuant, bounds = TrIQ(slice, params.colorL, params.triqP, mask_matrix=mask_matrix_for_triq)
else
sliceQuant, bounds = quantize_intensity(slice, params.colorL, mask_matrix=mask_matrix_for_triq)
end
if params.medianF
sliceQuant = round.(UInt8, median_filter(sliceQuant))
# Note: bounds remain the same after median filter
end
end
# Disk I/O (Saving BMP)
save_bitmap(joinpath(output_dir, bitmap_filename), sliceQuant, ViridisPalette)
if !all(iszero, slice)
# Now pass the precomputed bounds to colorbar generation
generate_colorbar_image(slice, params.colorL, joinpath(output_dir, colorbar_filename),
# CairoMakie colorbar generation is now also parallelized
generate_colorbar_image(slice, params.colorL, joinpath(output_dir, colorbar_filename),
bounds; use_triq=params.triqE, triq_prob=params.triqP, mask_path=mask_path)
end
lock(progress_lock) do
progress_message_ref = "File $(params.fileIdx)/$(params.nFiles): Saved slice for m/z=$mass"
end
end
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
@@ -1194,24 +1279,14 @@ function process_file_safely(file_path, masses, params, progress_message_ref, ov
end
end
function update_registry_mask_fields(registry_path, dataset_name, has_mask, mask_path)
function update_registry_mask_fields(registry_path::String, dataset_name::String, has_mask::Bool, mask_path::String)
lock(REGISTRY_LOCK) do
registry = if isfile(registry_path)
try
JSON.parsefile(registry_path, dicttype=Dict{String,Any})
catch e
@error "Failed to parse registry.json while updating mask fields: $e"
Dict{String,Any}()
end
else
Dict{String,Any}()
end
registry = load_registry(registry_path)
if haskey(registry, dataset_name)
registry[dataset_name]["has_mask"] = has_mask
registry[dataset_name]["mask_path"] = mask_path
else
# Create new entry if it doesn't exist
registry[dataset_name] = Dict{String,Any}(
"has_mask" => has_mask,
"mask_path" => mask_path,
@@ -1221,7 +1296,6 @@ function update_registry_mask_fields(registry_path, dataset_name, has_mask, mask
)
end
# Use the robust save function
save_registry(registry_path, registry)
end
end
@@ -1266,7 +1340,7 @@ function loadSurfacePlot(interfaceImg::String, mask_path::String)
row_indices = [idx[1] for idx in non_nan_indices]
col_indices = [idx[2] for idx in non_nan_indices]
y_range = minimum(row_indices):maximum(row_indices)
x_range = minimum(col_indices):maximum(col_indices)
@@ -1303,7 +1377,7 @@ function loadSurfacePlot(interfaceImg::String, mask_path::String)
y_nticks = min(20, length(y_coords))
z_nticks = 5
aspect_ratio = attr(x=1, y=length(y_coords) / length(x_coords), z=0.5)
# Define the layout for the 3D plot
layout3D = PlotlyBase.Layout(
title=PlotlyBase.attr(
@@ -1344,4 +1418,299 @@ function loadSurfacePlot(interfaceImg::String, mask_path::String)
plotdata = [trace3D]
plotlayout = layout3D
return plotdata, plotlayout
end
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
+37 -31
View File
@@ -9,10 +9,14 @@ 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
include("./julia_imzML_visual.jl")
if !@isdefined(increment_image)
include("./julia_imzML_visual.jl")
end
ensure_public_dir()
# Image Processing Pipeline
using ImageBinarization
@@ -35,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
@@ -48,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"
@@ -68,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
@@ -143,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
@@ -235,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)
@@ -250,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."
@@ -275,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)
@@ -305,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)
@@ -322,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)
@@ -355,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)
@@ -377,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"
@@ -418,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)
@@ -470,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)
@@ -513,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)
@@ -559,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)
@@ -584,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)
@@ -619,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)
@@ -645,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)
@@ -709,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)
@@ -729,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)
@@ -769,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)
@@ -779,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)
@@ -841,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)
+177
View File
@@ -0,0 +1,177 @@
# precompile_script.jl
# This script exercises the core MSI processing kernels (imzML and mzML)
# to ensure they are precompiled into the custom system image.
using MSI_src
using Mmap
using Base64
using PlotlyBase
# --- DYNAMIC WARM-UP WORKLOAD --- #
function create_warmup_datasets(dir, T_mz::Type, T_int::Type)
# 1. Create minimal imzML/ibd
imzml_path = joinpath(dir, "warmup_$(T_mz)_$(T_int).imzML")
ibd_path = joinpath(dir, "warmup_$(T_mz)_$(T_int).ibd")
n_points = 10
n_pixels = 1
mz_bytes = n_points * sizeof(T_mz)
int_bytes = n_points * sizeof(T_int)
# Write some dummy binary data (m/z must be sorted for validation)
open(ibd_path, "w") do f
write(f, sort(rand(T_mz, n_points)))
write(f, rand(T_int, n_points))
end
# Minimal but VALID imzML structure that passes axes_config_img
imzml_content = """<?xml version="1.0" encoding="utf-8"?>
<mzML xmlns="http://psi.hupo.org/ms/mzML" version="1.1.0">
<cvList count="2">
<cv id="MS" fullName="Proteomics Standards Initiative Mass Spectrometry Ontology" version="3.30.0" URI="http://psidev.cvs.sourceforge.net/*checkout*/psidev/ms/mzML/ontology/psi-ms.obo"/>
<cv id="IMS" fullName="Imaging MS Ontology" version="0.9.1" URI="http://www.imzml.org/ontology/imzML1.1.0.obo"/>
</cvList>
<fileDescription>
<fileContent>
<cvParam cvRef="IMS" accession="IMS:1000031" name="processed" value=""/>
<cvParam cvRef="IMS" accession="IMS:1000080" name="universally unique identifier" value="00000000-0000-0000-0000-000000000000"/>
<cvParam cvRef="IMS" accession="IMS:1000091" name="ibd MD5 HTTP" value="00000000000000000000000000000000"/>
</fileContent>
</fileDescription>
<referenceableParamGroupList count="2">
<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=""/>
</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=""/>
</referenceableParamGroup>
</referenceableParamGroupList>
<run id="run_1">
<spectrumList count="1">
<spectrum index="0" id="scan=1" defaultArrayLength="$n_points">
<cvParam cvRef="IMS" accession="IMS:1000050" name="coordinate x" value="1"/>
<cvParam cvRef="IMS" accession="IMS:1000051" name="coordinate y" value="1"/>
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="0">
<referenceableParamGroupRef ref="mz_array_settings"/>
<cvParam cvRef="IMS" accession="IMS:1000102" name="external data" value=""/>
<cvParam cvRef="IMS" accession="IMS:1000103" name="external offset" value="0"/>
<cvParam cvRef="IMS" accession="IMS:1000104" name="external array length" value="$n_points"/>
<cvParam cvRef="IMS" accession="IMS:1000101" name="external encoded length" value="$mz_bytes"/>
<binary/>
</binaryDataArray>
<binaryDataArray encodedLength="0">
<referenceableParamGroupRef ref="intensity_array_settings"/>
<cvParam cvRef="IMS" accession="IMS:1000102" name="external data" value=""/>
<cvParam cvRef="IMS" accession="IMS:1000103" name="external offset" value="$mz_bytes"/>
<cvParam cvRef="IMS" accession="IMS:1000104" name="external array length" value="$n_points"/>
<cvParam cvRef="IMS" accession="IMS:1000101" name="external encoded length" value="$int_bytes"/>
<binary/>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
</spectrumList>
</run>
</mzML>
"""
write(imzml_path, imzml_content)
# 2. Create minimal mzML (Base64)
mzml_path = joinpath(dir, "warmup_$(T_mz)_$(T_int).mzML")
b64_mz = base64encode(sort(rand(T_mz, n_points)))
b64_int = base64encode(rand(T_int, n_points))
mzml_content = """<?xml version="1.0" encoding="utf-8"?>
<mzML xmlns="http://psi.hupo.org/ms/mzML" version="1.1.0">
<run id="run_1">
<spectrumList count="1">
<spectrum index="0" id="scan=1" defaultArrayLength="$n_points">
<binaryDataArrayList count="2">
<binaryDataArray encodedLength="$(length(b64_mz))">
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" value=""/>
<cvParam cvRef="MS" accession="MS:$(T_mz == Float64 ? "1000523" : "1000521")" name="" value=""/>
<binary>$b64_mz</binary>
</binaryDataArray>
<binaryDataArray encodedLength="$(length(b64_int))">
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value=""/>
<cvParam cvRef="MS" accession="MS:$(T_int == Float64 ? "1000523" : "1000521")" name="" value=""/>
<binary>$b64_int</binary>
</binaryDataArray>
</binaryDataArrayList>
</spectrum>
</spectrumList>
</run>
<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
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)
return imzml_path, mzml_path
end
println("Starting robust precompilation warmup (imzML + mzML)...")
try
mktempdir() do tmp_dir
for (T_mz, T_int) in [(Float32, Float32), (Float64, Float32)]
println("Exercising pathways for $T_mz and $T_int...")
imzml_path, mzml_path = create_warmup_datasets(tmp_dir, T_mz, T_int)
try
# Exercise imzML pathway
imzml_data = MSI_src.load_imzml_lazy(imzml_path; use_mmap=true)
MSI_src.get_multiple_mz_slices(imzml_data, [10.0, 20.0], 0.1)
# Exercise Sprint 2 Streaming Pipeline
config = MSI_src.PipelineConfig(
steps=[
MSI_src.StreamingStep(:baseline_correction, Dict(:method => :snip, :iterations => 5)),
MSI_src.StreamingStep(:normalization, Dict(:method => :tic)),
MSI_src.StreamingStep(:peak_picking, Dict(:method => :profile, :snr_threshold => 3.0))
],
num_bins=2000
)
try
MSI_src.process_dataset!(imzml_data, config)
catch
# Ignore matrix mismatch errors from tiny random data
end
# Exercise mzML pathway
mzml_data = MSI_src.load_mzml_lazy(mzml_path)
MSI_src.GetSpectrum(mzml_data, 1)
catch e
@warn "Warmup failed for $T_mz/$T_int: $e"
end
end
# --- COMMON KERNELS ---
println("Precompiling image processing kernels...")
dummy_slice = rand(Float32, 4, 4)
MSI_src.TrIQ(dummy_slice, 256, 1.0)
MSI_src.save_bitmap(joinpath(tmp_dir, "d.bmp"), zeros(UInt8, 4, 4), MSI_src.ViridisPalette)
# Plotly Warmup
p = PlotlyBase.Plot(PlotlyBase.scatter(x=1:2, y=[1,2]))
end
catch e
if !(e isa InterruptException)
@warn "Global Warmup failed: $e"
end
end
println("Precompilation workload completed.")
+4 -26
View File
@@ -20,30 +20,7 @@ mutable struct BloomFilter{T}
count::Int
end
"""
StreamingBloomFilter
A memory-efficient Bloom filter that doesn't store all values at once.
# Fields
- `bits::BitVector`: The underlying bit array
- `size::Int`: Number of bits in the filter
- `hash_count::Int`: Number of hash functions to use
- `seed::UInt64`: Random seed for hash functions
- `count::Int`: Number of elements added (for monitoring)
- `current_chunk::Vector{Int}`: Current chunk of data being processed
- `chunk_size::Int`: Size of each chunk
"""
mutable struct StreamingBloomFilter
bits::BitVector
size::Int
hash_count::Int
seed::UInt64
count::Int
# Streaming state
current_chunk::Vector{Int}
chunk_size::Int
end
"""
BloomFilter{T}(expected_elements::Int, false_positive_rate::Float64=0.01; kwargs...) -> Return type
@@ -139,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
+38 -73
View File
@@ -1,77 +1,37 @@
# src/Common.jl - Updated with BloomFilter
using Base.Threads
using Mmap
# POSIX madvise constants
const MADV_NORMAL = 0
const MADV_RANDOM = 1
const MADV_SEQUENTIAL = 2
const MADV_WILLNEED = 3
const MADV_DONTNEED = 4
"""
posix_madvise(buffer::AbstractArray, advice::Integer)
A safe wrapper for the OS `madvise` system call. Signals the kernel about the
access pattern for a memory-mapped region. Currently supports Linux/Unix systems.
"""
function posix_madvise(buffer::AbstractArray, advice::Integer)
@static if Sys.isunix()
try
ptr = pointer(buffer)
len = sizeof(buffer)
# ccall(:madvise, return_type, (arg_types...), args...)
ret = ccall(:madvise, Int32, (Ptr{Cvoid}, Csize_t, Int32), ptr, len, Int32(advice))
return ret == 0
catch
return false
end
else
return false # Not supported on this OS
end
end
# --- Buffer Pooling ---
"""
BufferPool
A thread-safe pool of `Vector{UInt8}` buffers, categorized by their size.
This helps reduce memory allocations and garbage collection overhead by reusing buffers.
# Arguments:
- `lock`: A `ReentrantLock` to ensure thread-safe access to the pool.
- `buffers`: A dictionary mapping buffer size (in bytes) to a list of available buffers of that size.
"""
mutable struct BufferPool
lock::ReentrantLock
buffers::Dict{Int, Vector{Vector{UInt8}}}
function BufferPool()
new(ReentrantLock(), Dict{Int, Vector{Vector{UInt8}}}())
end
end
"""
get_buffer!(pool::BufferPool, size::Int) -> Vector{UInt8}
Retrieves a `Vector{UInt8}` buffer of at least `size` bytes from the pool.
If no suitable buffer is available, a new one is allocated.
# Arguments:
- `pool`: The `BufferPool` to retrieve the buffer from.
- `size`: The minimum desired size of the buffer in bytes.
# Returns:
- A `Vector{UInt8}` buffer.
"""
function get_buffer!(pool::BufferPool, size::Int)::Vector{UInt8}
lock(pool.lock) do
# Find an existing buffer that is large enough
for (buffer_size, buffer_list) in pool.buffers
if buffer_size >= size && !isempty(buffer_list)
buffer = pop!(buffer_list)
# Resize if necessary (and if it's significantly larger than needed)
if length(buffer) > size * 2 # Heuristic: if buffer is more than twice the requested size
return Vector{UInt8}(undef, size) # Allocate new smaller buffer
else
return buffer
end
end
end
# No suitable buffer found, allocate a new one
return Vector{UInt8}(undef, size)
end
end
"""
release_buffer!(pool::BufferPool, buffer::Vector{UInt8})
Returns a `Vector{UInt8}` buffer to the pool for future reuse.
# Arguments:
- `pool`: The `BufferPool` to return the buffer to.
- `buffer`: The `Vector{UInt8}` buffer to release.
"""
function release_buffer!(pool::BufferPool, buffer::Vector{UInt8})
lock(pool.lock) do
buffer_size = length(buffer)
if !haskey(pool.buffers, buffer_size)
pool.buffers[buffer_size] = Vector{Vector{UInt8}}()
end
push!(pool.buffers[buffer_size], buffer)
end
return nothing
end
"""
@@ -111,11 +71,16 @@ If no suitable buffer is available, a new one is allocated.
- A `Vector{UInt8}` buffer.
"""
function get_buffer!(pool::SimpleBufferPool, size::Int)::Vector{UInt8}
lock(pool.lock) do
buf = lock(pool.lock) do
# Check for existing buffers of exact size first
if haskey(pool.buffers, size) && !isempty(pool.buffers[size])
return pop!(pool.buffers[size])
end
return nothing
end
if buf !== nothing
return buf
end
# No suitable buffer found, allocate new one (outside lock to reduce contention)
@@ -239,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 ---
+495 -565
View File
File diff suppressed because it is too large Load Diff
+41 -8
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!,
@@ -20,7 +18,22 @@ export OpenMSIData,
MSIData,
_iterate_spectra_fast,
validate_spectrum,
REGISTRY_LOCK
get_mz_slice,
REGISTRY_LOCK,
SpectrumMetadata,
SpectrumAsset,
SpectrumMode,
CENTROID,
PROFILE,
MzMLSource,
ImzMLSource,
SimpleBufferPool,
get_buffer!,
release_buffer!,
PROJECT_ROOT,
PUBLIC_DIR,
DEFAULT_REGISTRY_PATH,
ensure_public_dir
# Define shared registry lock
const REGISTRY_LOCK = ReentrantLock()
@@ -60,18 +73,34 @@ export apply_baseline_correction,
apply_intensity_transformation,
save_feature_matrix
# Sprint 2: Streaming Pipeline API
export process_dataset!,
PipelineConfig,
StreamingStep,
normalize_inplace!,
transform_inplace!,
smooth_inplace!,
baseline_subtract_inplace!,
detect_peaks_streaming,
calibrate_inplace!
# Include all source files directly into the main module
include("Paths.jl")
include("BloomFilters.jl")
include("Common.jl")
include("ResourcePool.jl")
include("MSIData.jl")
include("ParserHelpers.jl")
include("mzML.jl")
include("imzML.jl")
include("PlottingStubs.jl")
include("MzmlConverter.jl")
include("Preprocessing.jl")
include("ImageProcessing.jl")
include("Precalculations.jl")
include("PreprocessingPipeline.jl")
include("StreamingKernels.jl")
include("StreamingPipeline.jl")
using Setfield # For immutable struct updates
@@ -95,13 +124,17 @@ This is the main entry point for the new data access API.
- An `MSIData` object.
"""
function OpenMSIData(filepath::String; cache_size=300, spectrum_type_map::Union{Dict{Int, Symbol}, Nothing}=nothing)
# Apply standard path normalization for cross-platform compatibility
# Ensure Windows backslashes are converted to OS-native separators
norm_filepath = normpath(replace(filepath, "\\" => "/"))
local msi_data
if endswith(lowercase(filepath), ".mzml")
msi_data = load_mzml_lazy(filepath, cache_size=cache_size)
elseif endswith(lowercase(filepath), ".imzml")
msi_data = load_imzml_lazy(filepath, cache_size=cache_size)
if endswith(lowercase(norm_filepath), ".mzml")
msi_data = load_mzml_lazy(norm_filepath, cache_size=cache_size)
elseif endswith(lowercase(norm_filepath), ".imzml")
msi_data = load_imzml_lazy(norm_filepath, cache_size=cache_size)
else
error("Unsupported file type: $filepath. Please provide a .mzML or .imzML file.")
error("Unsupported file type: $norm_filepath. Please provide a .mzML or .imzML file.")
end
# Apply spectrum type map if provided
+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
+32 -26
View File
@@ -81,12 +81,12 @@ function analyze_mass_accuracy(
println("Analyzing mass accuracy for $(length(spectrum_indices)) spectra...")
all_ppm_errors = Float64[]
total_matched_peaks = Atomic{Int}(0)
total_spectra_processed = Atomic{Int}(0)
total_matched_peaks = Base.Threads.Atomic{Int}(0)
total_spectra_processed = Base.Threads.Atomic{Int}(0)
results_lock = ReentrantLock()
_iterate_spectra_fast(msi_data, spectrum_indices) do idx, mz, intensity
atomic_add!(total_spectra_processed, 1)
Base.Threads.atomic_add!(total_spectra_processed, 1)
if !validate_spectrum(mz, intensity)
@warn "Spectrum $idx is invalid, skipping mass accuracy analysis for it."
return
@@ -111,7 +111,7 @@ function analyze_mass_accuracy(
lock(results_lock) do
push!(all_ppm_errors, min_ppm_error)
end
atomic_add!(total_matched_peaks, 1)
Base.Threads.atomic_add!(total_matched_peaks, 1)
end
end
end
@@ -671,8 +671,8 @@ function analyze_peak_characteristics(msi_data::MSIData, instrument_analysis::Di
peak_counts = Int[]
fwhm_values = Float64[]
spectra_analyzed = Atomic{Int}(0)
peaks_analyzed = Atomic{Int}(0)
spectra_analyzed = Base.Threads.Atomic{Int}(0)
peaks_analyzed = Base.Threads.Atomic{Int}(0)
results_lock = ReentrantLock()
_iterate_spectra_fast(msi_data, spectrum_indices) do idx, mz, intensity
@@ -680,7 +680,7 @@ function analyze_peak_characteristics(msi_data::MSIData, instrument_analysis::Di
return
end
atomic_add!(spectra_analyzed, 1)
Base.Threads.atomic_add!(spectra_analyzed, 1)
meta = msi_data.spectra_metadata[idx]
# Detect peaks with lower SNR threshold to find more peaks
@@ -709,7 +709,7 @@ function analyze_peak_characteristics(msi_data::MSIData, instrument_analysis::Di
r2 = _fit_gaussian_and_r2(mz, intensity, peak_idx, 5)
push!(r_squared_values, r2)
end
atomic_add!(peaks_analyzed, 1)
Base.Threads.atomic_add!(peaks_analyzed, 1)
if peaks_analyzed[] <= 3
println("DEBUG: Peak at m/z $(peak.mz), FWHM = $(fwhm_ppm) ppm, R² = $(r_squared_values[end])")
@@ -1314,18 +1314,16 @@ function _fit_gaussian_and_r2(mz::AbstractVector{<:Real}, intensity::AbstractVec
end_idx = min(n, peak_idx + half_window)
# Ensure there's enough data to fit
if (end_idx - start_idx + 1) < 3
count = end_idx - start_idx + 1
if count < 3
return 0.0
end
x_data = mz[start_idx:end_idx]
y_data = intensity[start_idx:end_idx]
# Estimate Gaussian parameters
# Amplitude (A): peak intensity
A_est = intensity[peak_idx]
A_est = float(intensity[peak_idx])
# Mean (μ): m/z at peak intensity
mu_est = mz[peak_idx]
mu_est = float(mz[peak_idx])
# Standard deviation (σ): related to FWHM. FWHM = 2 * sqrt(2 * ln(2)) * σ ≈ 2.355 * σ
# So, σ ≈ FWHM / 2.355
fwhm_delta_m = _calculate_fwhm_delta_m(mz, intensity, peak_idx)
@@ -1339,19 +1337,27 @@ function _fit_gaussian_and_r2(mz::AbstractVector{<:Real}, intensity::AbstractVec
return 0.0
end
# Gaussian function
gaussian(x, A, mu, sigma) = A * exp.(-(x .- mu).^2 ./ (2 * sigma^2))
# Calculate SS_res, mean_y in a single pass to avoid allocations
SS_res = 0.0
sum_y = 0.0
@inbounds for i in start_idx:end_idx
x_val = float(mz[i])
y_val = float(intensity[i])
# Gaussian function estimate
y_est = A_est * exp(-((x_val - mu_est)^2) / (2 * sigma_est^2))
SS_res += (y_val - y_est)^2
sum_y += y_val
end
# Generate estimated Gaussian curve
y_est = gaussian(x_data, A_est, mu_est, sigma_est)
# Calculate pseudo R-squared
# R^2 = 1 - (SS_res / SS_tot)
# SS_res = sum((y_data - y_est).^2)
# SS_tot = sum((y_data - mean(y_data)).^2)
SS_res = sum((y_data .- y_est).^2)
SS_tot = sum((y_data .- mean(y_data)).^2)
mean_y = sum_y / count
SS_tot = 0.0
@inbounds for i in start_idx:end_idx
SS_tot += (float(intensity[i]) - mean_y)^2
end
if SS_tot == 0
return 1.0 # Perfect fit if all y_data are the same
+41 -28
View File
@@ -12,6 +12,7 @@ generation.
# =============================================================================
using Statistics # For mean, median
using SparseArrays
using StatsBase # For mad (Median Absolute Deviation)
using SavitzkyGolay # For SavitzkyGolay filtering
using Dates # For now()
@@ -40,7 +41,7 @@ A struct to hold the final feature matrix generated from the preprocessing pipel
- `sample_ids::Vector{Int}`: A vector of identifiers for each sample (row) in the `matrix`.
"""
struct FeatureMatrix
matrix::Array{Float64,2}
matrix::AbstractMatrix{Float64}
mz_bins::Vector{Tuple{Float64,Float64}}
sample_ids::Vector{Int}
end
@@ -487,32 +488,23 @@ Estimates the baseline of a spectrum using the SNIP algorithm (internal implemen
function _snip_baseline_impl(y::AbstractVector{<:Real}; iterations::Int=100)
n = length(y)
# Initialize two buffers. b1 holds the current baseline estimate, b2 for the next.
# Always convert to Float64 to ensure type stability and avoid copying if already correct type
# Initialize the baseline estimate array once
b1 = collect(float.(y))
b2 = similar(b1)
current_b = b1
next_b = b2
for k in 1:iterations
# Calculate next baseline estimate into `next_b` based on `current_b`
# Boundary conditions
if n > 1
next_b[1] = min(current_b[1], current_b[2])
next_b[n] = min(current_b[n], current_b[n-1])
end
@inbounds for i in 2:n-1
next_b[i] = min(current_b[i], 0.5 * (current_b[i-1] + current_b[i+1]))
end
prev_val = b1[1]
b1[1] = min(b1[1], b1[2])
# Swap references for the next iteration (no data copy here)
current_b, next_b = next_b, current_b
@inbounds for i in 2:n-1
curr_val = b1[i]
b1[i] = min(curr_val, 0.5 * (prev_val + b1[i+1]))
prev_val = curr_val
end
b1[n] = min(b1[n], prev_val)
end
# Return the final baseline estimate (which is in current_b after the last swap)
return current_b
# Return the final baseline estimate
return b1
end
"""
@@ -720,18 +712,32 @@ function detect_peaks_profile_core(mz::AbstractVector{<:Real}, y::AbstractVector
n = length(y)
n < 3 && return NamedTuple{(:mz, :intensity, :fwhm, :shape_r2, :snr, :prominence), Tuple{Float64, Float64, Float64, Float64, Float64, Float64}}[]
noise_level = mad(y, normalize=true) + eps(Float64)
ys = smooth_spectrum_core(y; method=:savitzky_golay, window=max(5, 2*half_window+1), order=2) # Use smoothed data for detection
# Fast, non-allocating noise estimation
mean_y = sum(y) / n
noise_level = (sum(abs.(y .- mean_y)) / n) * 1.5 + eps(Float64)
ys = smooth_spectrum_core(y; method=:savitzky_golay, window=max(5, 2*half_window+1), order=2)
candidate_peak_indices = Int[]
for i in 2:n-1
sizehint!(candidate_peak_indices, div(n, 10)) # Pre-allocate memory capacity
@inbounds for i in 2:n-1
left = max(1, i - half_window)
right = min(n, i + half_window)
# Prominence check
prominence = ys[i] - max(minimum(@view ys[left:i]), minimum(@view ys[i:right]))
# Avoid @view allocation in tight loop by manually computing minimums and maximums
min_left = ys[left]
for j in left:i; min_left = min(min_left, ys[j]); end
if ys[i] >= maximum(@view ys[left:right]) &&
min_right = ys[i]
for j in i:right; min_right = min(min_right, ys[j]); end
prominence = ys[i] - max(min_left, min_right)
max_local = ys[left]
for j in left:right; max_local = max(max_local, ys[j]); end
if ys[i] >= max_local &&
(ys[i] > snr_threshold * noise_level) &&
(prominence > min_peak_prominence * ys[i])
push!(candidate_peak_indices, i)
@@ -768,7 +774,14 @@ function detect_peaks_profile_core(mz::AbstractVector{<:Real}, y::AbstractVector
left = max(1, p_idx - half_window)
right = min(n, p_idx + half_window)
prominence = ys[p_idx] - max(minimum(@view ys[left:p_idx]), minimum(@view ys[p_idx:right]))
min_left = ys[left]
for j in left:p_idx; min_left = min(min_left, ys[j]); end
min_right = ys[p_idx]
for j in p_idx:right; min_right = min(min_right, ys[j]); end
prominence = ys[p_idx] - max(min_left, min_right)
push!(detected_peaks, (mz=peak_mz, intensity=peak_int, fwhm=fwhm_ppm, shape_r2=shape_r2, snr=peak_snr, prominence=prominence))
end
+79
View File
@@ -0,0 +1,79 @@
# src/ResourcePool.jl
using Base.Threads
"""
ResourcePool{T}
A thread-safe pool for reusing objects of type `T` to minimize allocations and GC pressure.
Specifically designed for high-performance computing tasks where large buffers are needed
repeatedly across multiple threads.
# Fields:
- `pool::Vector{T}`: The underlying storage for idle resources.
- `lock::ReentrantLock`: Ensures thread-safe access to the pool.
- `max_size::Int`: Maximum number of resources to hold in the pool.
- `constructor::Function`: A function to create a new resource if the pool is empty.
"""
mutable struct ResourcePool{T}
pool::Vector{T}
lock::ReentrantLock
max_size::Int
constructor::Function
end
"""
ResourcePool{T}(constructor::Function; max_size::Int=2 * nthreads())
Creates a new `ResourcePool` for resources of type `T`.
"""
function ResourcePool{T}(constructor::Function; max_size::Int=2 * nthreads()) where T
return ResourcePool{T}(T[], ReentrantLock(), max_size, constructor)
end
"""
acquire(pool::ResourcePool{T}) -> T
Retrieves a resource from the pool. If the pool is empty, a new resource is created
using the constructor.
"""
function acquire(pool::ResourcePool{T}) where T
lock(pool.lock) do
if !isempty(pool.pool)
return pop!(pool.pool)
end
end
# Create new resource outside of lock to minimize contention
return pool.constructor()
end
"""
release!(pool::ResourcePool{T}, resource::T)
Returns a resource to the pool for later reuse. If the pool is already at `max_size`,
the resource is allowed to be garbage collected.
"""
function release!(pool::ResourcePool{T}, resource::T) where T
lock(pool.lock) do
if length(pool.pool) < pool.max_size
push!(pool.pool, resource)
end
end
return nothing
end
"""
with_resource(f::Function, pool::ResourcePool{T})
Acquires a resource from the pool, executes the function `f(resource)`, and
automatically releases the resource back to the pool when finished.
"""
function with_resource(f::Function, pool::ResourcePool{T}) where T
resource = acquire(pool)
try
return f(resource)
finally
release!(pool, resource)
end
end
+317
View File
@@ -0,0 +1,317 @@
# src/StreamingKernels.jl
# ============================================================================
# In-Place Spectral Kernels for the Streaming Pipeline
#
# These functions operate on raw (mz, intensity) views from the Sprint 1
# Mmap engine. They write results back to the input buffers using .= to
# achieve zero-allocation processing per spectrum.
#
# Design contract:
# - All !-suffixed functions modify their arguments in-place
# - If a kernel needs temporary storage, it borrows from data.resource_pool
# - No function creates MutableSpectrum objects
# ============================================================================
using Statistics: mean, median
# =============================================================================
# Category A: Purely Streamable Kernels
# =============================================================================
"""
normalize_inplace!(intensity::AbstractVector{<:Real}, method::Symbol)
Normalizes intensity values in-place. Supports :tic, :median, :rms.
Zero-allocation for the normalization itself.
"""
@inline function normalize_inplace!(intensity::AbstractVector{<:Real}, method::Symbol)
if method === :tic
s = sum(intensity)
if s > 0
intensity ./= s
end
elseif method === :median
m = median(intensity)
if m > 0
intensity ./= m
end
elseif method === :rms
s = sqrt(sum(abs2, intensity) / length(intensity))
if s > 0
intensity ./= s
end
end
return intensity
end
"""
transform_inplace!(intensity::AbstractVector{Float64}, method::Symbol)
Applies intensity transformation in-place. Supports :sqrt, :log1p, :log, :log2, :log10.
"""
@inline function transform_inplace!(intensity::AbstractVector{Float64}, method::Symbol)
if method === :sqrt
@inbounds @simd for i in eachindex(intensity)
intensity[i] = sqrt(max(0.0, intensity[i]))
end
elseif method === :log1p
@inbounds @simd for i in eachindex(intensity)
intensity[i] = log1p(max(0.0, intensity[i]))
end
elseif method === :log
@inbounds @simd for i in eachindex(intensity)
intensity[i] = log(max(eps(Float64), intensity[i]))
end
elseif method === :log2
@inbounds @simd for i in eachindex(intensity)
intensity[i] = log2(max(eps(Float64), intensity[i]))
end
elseif method === :log10
@inbounds @simd for i in eachindex(intensity)
intensity[i] = log10(max(eps(Float64), intensity[i]))
end
end
return intensity
end
"""
smooth_inplace!(intensity::AbstractVector{Float64}, data::MSIData;
method::Symbol=:savitzky_golay, window::Int=9, order::Int=2)
Smooths intensity in-place using a temporary buffer from the resource pool.
The SavitzkyGolay library allocates internally, but we copy the result back
to the original buffer and return the pool buffer.
"""
function smooth_inplace!(intensity::AbstractVector{Float64}, scratch::AbstractVector{Float64}, data::MSIData;
method::Symbol=:savitzky_golay, window::Int=9, order::Int=2)
n = length(intensity)
if n < 3
return intensity
end
if method === :savitzky_golay
win = isodd(window) ? window : window + 1
if n < win
return intensity
end
# SavitzkyGolay handles its own math but causes mild allocation.
res = SavitzkyGolay.savitzky_golay(collect(intensity), win, order)
@inbounds for i in eachindex(intensity)
intensity[i] = max(0.0, res.y[i])
end
elseif method === :moving_average
copyto!(scratch, intensity)
half_w = div(window, 2)
@inbounds for i in 1:n
s_idx = max(1, i - half_w)
e_idx = min(n, i + half_w)
s = 0.0
@simd for j in s_idx:e_idx
s += scratch[j]
end
intensity[i] = max(0.0, s / (e_idx - s_idx + 1))
end
end
return intensity
end
"""
baseline_subtract_inplace!(intensity::AbstractVector{Float64}, data::MSIData;
method::Symbol=:snip, iterations::Int=100, window::Int=20)
Subtracts baseline from intensity in-place. Uses two pool buffers for the
SNIP ping-pong iteration to avoid any heap allocation in the hot loop.
"""
function baseline_subtract_inplace!(intensity::AbstractVector{Float64}, scratch::AbstractVector{Float64}, data::MSIData;
method::Symbol=:snip, iterations::Int=100, window::Int=20)
n = length(intensity)
if n < 3
return intensity
end
if method === :snip
copyto!(scratch, intensity)
for k in 1:iterations
prev_val = scratch[1]
scratch[1] = min(scratch[1], scratch[2])
@inbounds for i in 2:n-1
curr_val = scratch[i]
scratch[i] = min(curr_val, 0.5 * (prev_val + scratch[i+1]))
prev_val = curr_val
end
scratch[n] = min(scratch[n], prev_val)
end
@inbounds @simd for i in 1:n
intensity[i] = max(0.0, intensity[i] - scratch[i])
end
elseif method === :convex_hull
baseline = convex_hull_baseline(intensity)
@inbounds @simd for i in eachindex(intensity)
intensity[i] = max(0.0, intensity[i] - baseline[i])
end
elseif method === :median
baseline = median_baseline(intensity; window=window)
@inbounds @simd for i in eachindex(intensity)
intensity[i] = max(0.0, intensity[i] - baseline[i])
end
end
return intensity
end
"""
detect_peaks_streaming(mz::AbstractVector, intensity::AbstractVector;
method::Symbol=:profile, snr_threshold::Float64=3.0,
half_window::Int=10, min_peak_prominence::Float64=0.1,
merge_peaks_tolerance::Float64=0.002)
Detects peaks and returns a vector of (mz, intensity) tuples.
This delegates to existing _core functions but returns a lightweight format
suitable for sparse accumulation (no NamedTuple overhead in the hot path).
"""
function detect_peaks_streaming(callback::Function, mz::AbstractVector{Float64}, intensity::AbstractVector{Float64}, scratch::AbstractVector{Float64};
method::Symbol=:profile, snr_threshold::Float64=3.0,
half_window::Int=10, min_peak_prominence::Float64=0.1,
merge_peaks_tolerance::Float64=0.002)
n = length(intensity)
if n < 3
return
end
if method === :profile || method === :wavelet
# Zero-allocation noisy estimation (using mean of bottom half)
sum_i = 0.0
@simd for i in 1:n
sum_i += intensity[i]
end
mean_i = sum_i / n
sum_noise = 0.0
count_noise = 0
@inbounds for i in 1:n
if intensity[i] < mean_i
sum_noise += intensity[i]
count_noise += 1
end
end
# Use * 1.5 as an approximation to MAD
noise_level = count_noise > 0 ? (sum_noise / count_noise) * 1.5 + eps(Float64) : mean_i + eps(Float64)
# We will use the scratch buffer to store candidate indices to avoid allocating `Int[]`
# Because scratch is Float64, we can safely store integer indices up to 2^53 exactly.
num_candidates = 0
@inbounds for i in 2:n-1
if intensity[i] > snr_threshold * noise_level
left = max(1, i - half_window)
right = min(n, i + half_window)
is_max = true
for j in left:right
if intensity[j] > intensity[i]
is_max = false
break
end
end
if is_max
# Compute prominence
min_left = intensity[i]
for j in left:i
if intensity[j] < min_left
min_left = intensity[j]
end
end
min_right = intensity[i]
for j in i:right
if intensity[j] < min_right
min_right = intensity[j]
end
end
prominence = intensity[i] - max(min_left, min_right)
if prominence > min_peak_prominence * intensity[i]
num_candidates += 1
scratch[num_candidates] = i
end
end
end
end
# Merge close peaks
if num_candidates > 0
if merge_peaks_tolerance > 0
last_idx = trunc(Int, scratch[1])
# We emit the first peak lazily down below, so let's compact them in place
num_merged = 1
for i in 2:num_candidates
idx = trunc(Int, scratch[i])
if (mz[idx] - mz[last_idx]) > merge_peaks_tolerance
num_merged += 1
scratch[num_merged] = idx
last_idx = idx
elseif intensity[idx] > intensity[last_idx]
scratch[num_merged] = idx
last_idx = idx
end
end
num_candidates = num_merged
end
# Emit merged peaks
for i in 1:num_candidates
idx = trunc(Int, scratch[i])
callback(mz[idx], intensity[idx])
end
end
elseif method === :centroid
# Just use any value over snr_threshold * mean_noise
sum_i = sum(intensity)
mean_i = sum_i / n
noise_level = mean_i + eps(Float64)
@inbounds for i in 1:n
if intensity[i] > snr_threshold * noise_level
callback(mz[i], intensity[i])
end
end
end
end
# =============================================================================
# Category B: Conditionally Streamable Kernels (Fixed-Reference)
# =============================================================================
"""
calibrate_inplace!(mz::Vector{Float64}, intensity::AbstractVector,
reference_masses::Vector{Float64}; ppm_tolerance::Float64=20.0)
Calibrates the m/z axis in-place using a fixed dictionary of internal standard
reference masses. This is streamable because the reference is constant.
Returns `true` if calibration was applied, `false` if insufficient peaks were found.
"""
function calibrate_inplace!(mz::Vector{Float64}, intensity::AbstractVector,
reference_masses::Vector{Float64}; ppm_tolerance::Float64=20.0)
matched_peaks = find_calibration_peaks_core(mz, intensity, reference_masses;
ppm_tolerance=ppm_tolerance)
if length(matched_peaks) < 2
return false # Insufficient reference peaks
end
measured = sort(collect(values(matched_peaks)))
theoretical = sort(collect(keys(matched_peaks)))
itp = linear_interpolation(measured, theoretical, extrapolation_bc=Line())
# Apply calibration in-place
@inbounds for i in eachindex(mz)
mz[i] = itp(mz[i])
end
return true
end
+403
View File
@@ -0,0 +1,403 @@
# src/StreamingPipeline.jl
# ============================================================================
# The Streaming Pipeline Executor
#
# This module provides `process_dataset!`, the Sprint 2 master function that
# streams spectral data through an in-place kernel chain and accumulates
# results into a SparseMatrixCSC without ever holding more than 1 spectrum
# per thread in RAM.
#
# Architecture:
# 1. _iterate_spectra_fast → Mmap zero-copy views
# 2. copyto!(writable_buf, view) → makes mutable copy for kernels
# 3. Kernel chain: smooth! → baseline! → peaks → bin
# 4. Thread-local (I, J, V) sparse accumulators
# 5. Final sparse(I, J, V, num_bins, num_spectra) assembly
#
# This works alongside the existing execute_full_preprocessing in
# PreprocessingPipeline.jl — it does NOT replace the app.jl integration.
# ============================================================================
using SparseArrays
using Printf
# =============================================================================
# Configuration Structs
# =============================================================================
"""
StreamingStep
Represents a single step in the streaming pipeline.
"""
struct StreamingStep
name::Symbol
params::Dict{Symbol, Any}
end
"""
PipelineConfig
Holds the complete configuration for a streaming pipeline execution.
# Fields
- `steps::Vector{StreamingStep}` — ordered sequence of processing steps
- `reference_peaks::Vector{Float64}` — fixed m/z values for calibration (Category B)
- `num_bins::Int` — number of bins for the output feature matrix
- `min_peaks_per_bin::Int` — minimum peak count to keep a bin
- `frequency_threshold::Float64` — minimum fraction of spectra a bin must appear in (0.0-1.0)
# Example
```julia
config = PipelineConfig(
steps = [
StreamingStep(:smoothing, Dict(:method => :savitzky_golay, :window => 9, :order => 2)),
StreamingStep(:baseline_correction, Dict(:method => :snip, :iterations => 100)),
StreamingStep(:normalization, Dict(:method => :tic)),
StreamingStep(:peak_picking, Dict(:method => :profile, :snr_threshold => 3.0)),
],
num_bins = 2000
)
```
"""
struct PipelineConfig
steps::Vector{StreamingStep}
reference_peaks::Vector{Float64}
num_bins::Int
min_peaks_per_bin::Int
frequency_threshold::Float64
end
# Convenience constructor with defaults
function PipelineConfig(; steps::Vector{StreamingStep}=StreamingStep[],
reference_peaks::Vector{Float64}=Float64[],
num_bins::Int=2000,
min_peaks_per_bin::Int=3,
frequency_threshold::Float64=0.0)
return PipelineConfig(steps, reference_peaks, num_bins, min_peaks_per_bin, frequency_threshold)
end
# =============================================================================
# Sparse Accumulator (Thread-Local)
# =============================================================================
"""
SparseAccumulator
Thread-local accumulator for sparse matrix construction.
Collects (row, col, val) triplets that will be assembled into
a SparseMatrixCSC at the end of the pipeline.
"""
mutable struct SparseAccumulator
I::Vector{Int} # Row indices (bin indices)
J::Vector{Int} # Column indices (spectrum indices)
V::Vector{Float64} # Values (intensities)
lck::Base.Threads.SpinLock
function SparseAccumulator(capacity_hint::Int=10000)
acc = new(
Vector{Int}(undef, 0),
Vector{Int}(undef, 0),
Vector{Float64}(undef, 0),
Base.Threads.SpinLock()
)
sizehint!(acc.I, capacity_hint)
sizehint!(acc.J, capacity_hint)
sizehint!(acc.V, capacity_hint)
return acc
end
end
"""
accumulate!(acc::SparseAccumulator, spectrum_idx::Int, bin_indices::AbstractVector{Int},
intensities::AbstractVector{Float64})
Appends peak data for one spectrum into the sparse accumulator.
"""
@inline function accumulate!(acc::SparseAccumulator, spectrum_idx::Int,
bin_indices::AbstractVector{Int},
intensities::AbstractVector{Float64})
n = length(bin_indices)
for k in 1:n
@inbounds begin
push!(acc.I, bin_indices[k])
push!(acc.J, spectrum_idx)
push!(acc.V, intensities[k])
end
end
end
# =============================================================================
# The Pipeline Executor
# =============================================================================
"""
process_dataset!(data::MSIData, config::PipelineConfig;
progress_callback::Union{Function, Nothing}=nothing,
masked_indices::Union{AbstractVector{Int}, Nothing}=nothing)
The Sprint 2 master streaming function. Processes an entire MSI dataset through
a kernel chain without holding more than 1 spectrum per thread in RAM.
# Returns
- `SparseMatrixCSC{Float64, Int}`: The feature matrix (bins × spectra)
- `Vector{Float64}`: The m/z bin centers
# Architecture
1. Ensures analytics are computed (for global m/z range)
2. Creates thread-local SparseAccumulators
3. Streams spectra via `_iterate_spectra_fast`
4. Per spectrum: copy view → kernel chain → peak detect → bin → accumulate
5. Merges accumulators → `sparse(I, J, V)`
"""
function process_dataset!(data::MSIData, config::PipelineConfig;
progress_callback::Union{Function, Nothing}=nothing,
masked_indices::Union{AbstractVector{Int}, Nothing}=nothing)
# --- Step 1: Ensure analytics are computed (provides global m/z range) ---
if !is_set(data.analytics_ready)
println("Pre-computing analytics for streaming pipeline...")
precompute_analytics(data)
end
# Determine global m/z range for binning
global_min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0)
global_max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0)
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]. Cannot bin peaks."
return spzeros(0, 0), Float64[]
end
num_bins = config.num_bins
bin_edges = range(global_min_mz, stop=global_max_mz, length=num_bins + 1)
bin_centers = [(bin_edges[i] + bin_edges[i+1]) / 2 for i in 1:num_bins]
inv_bin_width = 1.0 / step(bin_edges)
num_spectra = length(data.spectra_metadata)
indices_to_process = masked_indices === nothing ? nothing : masked_indices
# --- Step 2: Create thread-local accumulators ---
# `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)
# NEW: Create dedicated workspace buffers for each thread.
# This completely eliminates the need for acquire/release and prevents deadlocks.
workspaces_mz = [Vector{Float64}(undef, 0) for _ in 1:n_threads]
workspaces_int = [Vector{Float64}(undef, 0) for _ in 1:n_threads]
workspaces_scratch = [Vector{Float64}(undef, 0) for _ in 1:n_threads]
# Pre-parse step configuration for fast dispatch in the hot loop
has_smoothing = false
has_baseline = false
has_normalization = false
has_transform = false
has_peak_picking = false
has_calibration = false
smooth_params = Dict{Symbol, Any}()
baseline_params = Dict{Symbol, Any}()
norm_params = Dict{Symbol, Any}()
transform_params = Dict{Symbol, Any}()
peak_params = Dict{Symbol, Any}()
for s in config.steps
if s.name === :smoothing
has_smoothing = true
smooth_params = s.params
elseif s.name === :baseline_correction
has_baseline = true
baseline_params = s.params
elseif s.name === :normalization
has_normalization = true
norm_params = s.params
elseif s.name === :stabilization || s.name === :intensity_transformation
has_transform = true
transform_params = s.params
elseif s.name === :peak_picking
has_peak_picking = true
peak_params = s.params
elseif s.name === :calibration
has_calibration = true
end
end
reference_masses = config.reference_peaks
# --- Step 3: Stream and process ---
start_time = time_ns()
# Use let block to capture all variables cleanly for the closure
let data=data, accumulators=accumulators, spectra_processed=spectra_processed,
bin_edges=bin_edges, num_bins=num_bins, inv_bin_width=inv_bin_width,
global_min_mz=global_min_mz,
workspaces_mz=workspaces_mz, workspaces_int=workspaces_int, workspaces_scratch=workspaces_scratch,
has_smoothing=has_smoothing, has_baseline=has_baseline,
has_normalization=has_normalization, has_transform=has_transform,
has_peak_picking=has_peak_picking, has_calibration=has_calibration,
smooth_params=smooth_params, baseline_params=baseline_params,
norm_params=norm_params, transform_params=transform_params,
peak_params=peak_params, reference_masses=reference_masses
_iterate_spectra_fast(data, indices_to_process) do idx, mz_view, int_view
thread_id = Base.Threads.threadid()
acc = accumulators[thread_id]
# --- Grab Thread-Local Workspaces ---
# No locking, no blocking, guaranteed to be available
mz_buf = workspaces_mz[thread_id]
int_buf = workspaces_int[thread_id]
scratch_buf = workspaces_scratch[thread_id]
resize!(mz_buf, length(mz_view))
resize!(int_buf, length(int_view))
resize!(scratch_buf, length(int_view))
copyto!(mz_buf, mz_view)
copyto!(int_buf, int_view)
# --- Kernel Chain (in pipeline order) ---
# Category B: Fixed-reference calibration
if has_calibration && !isempty(reference_masses)
calibrate_inplace!(mz_buf, int_buf, reference_masses)
end
# Category A: Intensity transformation
if has_transform
transform_inplace!(int_buf, get(transform_params, :method, :sqrt))
end
# Category A: Smoothing
if has_smoothing
smooth_inplace!(int_buf, scratch_buf, data;
method=get(smooth_params, :method, :savitzky_golay),
window=get(smooth_params, :window, 9),
order=get(smooth_params, :order, 2))
end
# Category A: Baseline correction
if has_baseline
baseline_subtract_inplace!(int_buf, scratch_buf, data;
method=get(baseline_params, :method, :snip),
iterations=get(baseline_params, :iterations, 100),
window=get(baseline_params, :window, 20))
end
# Category A: Normalization
if has_normalization
normalize_inplace!(int_buf, get(norm_params, :method, :tic))
end
# --- Peak Detection & Binning ---
if has_peak_picking
detect_peaks_streaming(mz_buf, int_buf, scratch_buf;
method=get(peak_params, :method, :profile),
snr_threshold=Float64(get(peak_params, :snr_threshold, 3.0)),
half_window=Int(get(peak_params, :half_window, 10)),
min_peak_prominence=Float64(get(peak_params, :min_peak_prominence, 0.1)),
merge_peaks_tolerance=Float64(get(peak_params, :merge_peaks_tolerance, 0.002))) do peak_mz, peak_int
# Bin each discovered peak directly
bin_idx = trunc(Int, (peak_mz - global_min_mz) * inv_bin_width) + 1
bin_idx = clamp(bin_idx, 1, num_bins)
push!(acc.I, bin_idx)
push!(acc.J, idx)
push!(acc.V, peak_int)
end
else
# No peak picking: bin raw intensity directly
@inbounds for i in eachindex(mz_buf)
bin_idx = trunc(Int, (mz_buf[i] - global_min_mz) * inv_bin_width) + 1
bin_idx = clamp(bin_idx, 1, num_bins)
push!(acc.I, bin_idx)
push!(acc.J, idx)
push!(acc.V, int_buf[i])
end
end
Base.Threads.atomic_add!(spectra_processed, 1)
end
end
# --- Step 4: Merge thread-local accumulators ---
total_entries = sum(length(acc.I) for acc in accumulators)
merged_I = Vector{Int}(undef, total_entries)
merged_J = Vector{Int}(undef, total_entries)
merged_V = Vector{Float64}(undef, total_entries)
offset = 0
for acc in accumulators
n = length(acc.I)
if n > 0
copyto!(merged_I, offset + 1, acc.I, 1, n)
copyto!(merged_J, offset + 1, acc.J, 1, n)
copyto!(merged_V, offset + 1, acc.V, 1, n)
offset += n
end
end
# --- Step 5: Assemble sparse matrix ---
# Use max combiner: when multiple peaks map to the same bin for same spectrum,
# keep the maximum intensity
feature_matrix = sparse(merged_I, merged_J, merged_V, num_bins, num_spectra, max)
# --- Step 6: Apply frequency threshold if configured ---
if config.frequency_threshold > 0.0
# Count how many spectra have a non-zero value in each bin
bin_presence = vec(sum(feature_matrix .> 0, dims=2))
min_count = ceil(Int, config.frequency_threshold * num_spectra)
keep_bins = findall(bin_presence .>= min_count)
feature_matrix = feature_matrix[keep_bins, :]
bin_centers = bin_centers[keep_bins]
end
duration = (time_ns() - start_time) / 1e9
n_processed = spectra_processed[]
n_nonzeros = nnz(feature_matrix)
sparsity = 1.0 - n_nonzeros / (size(feature_matrix, 1) * size(feature_matrix, 2) + 1)
@printf "Streaming pipeline complete: %d spectra processed in %.2f seconds.\n" n_processed duration
@printf "Feature matrix: %d bins × %d spectra, %d non-zeros (%.1f%% sparse)\n" size(feature_matrix, 1) size(feature_matrix, 2) n_nonzeros sparsity * 100
@printf "RAM: %.1f MB (vs %.1f MB dense)\n" (n_nonzeros * 16) / 1e6 (size(feature_matrix, 1) * size(feature_matrix, 2) * 8) / 1e6
if progress_callback !== nothing
progress_callback(1.0)
end
return feature_matrix, collect(Float64, bin_centers)
end
"""
save_sparse_matrix(matrix::SparseMatrixCSC, output_path::String)
Exports a highly optimized SparseMatrixCSC array to disk using the standard
Matrix Market Coordinate format (`.mtx`), guaranteeing no bottleneck or OOM crashes
for extremely large MS dataset persistence.
"""
function save_sparse_matrix(matrix::SparseMatrixCSC{Float64, Int}, output_path::String)
m, n = size(matrix)
nnz_val = nnz(matrix)
# Use streaming I/O with a large buffer for ultra-fast persistence
open(output_path, "w") do io
# Write Matrix Market Header
write(io, "%%MatrixMarket matrix coordinate real general\n")
write(io, "$m $n $nnz_val\n")
# Directly extract CSC properties (O(1) memory, zero allocation)
row_indices = rowvals(matrix)
values_array = nonzeros(matrix)
@inbounds for filter_j in 1:n
# nzrange returns the index bounds for non-zero elements in column 'j'
for idx in nzrange(matrix, filter_j)
i = row_indices[idx]
v = values_array[idx]
write(io, "$i $filter_j $v\n")
end
end
end
end
+267 -719
View File
File diff suppressed because it is too large Load Diff
+41 -35
View File
@@ -231,7 +231,7 @@ function get_spectrum_asset_metadata(stream::IO)
#println("DEBUG: Exiting get_spectrum_asset_metadata.")
# Create SpectrumAsset directly from the variables
return SpectrumAsset(data_format, compression_flag, binary_offset, encoded_length, axis)
return SpectrumAsset(data_format, compression_flag, binary_offset, encoded_length, axis, 0.0, 0.0)
end
# This function is updated to return the generic SpectrumMetadata struct
@@ -394,38 +394,48 @@ then parses the metadata for each spectrum without loading the binary data.
"""
function load_mzml_lazy(file_path::String; cache_size::Int=100)
println("DEBUG: Opening file stream for $file_path")
ts_stream = ThreadSafeFileHandle(file_path, "r")
# --- Handle Pool Optimization ---
# Open multiple handles to the .mzML file to avoid lock contention
num_handles = max(1, Threads.maxthreadid())
mzml_handles = [open(file_path, "r") for _ in 1:num_handles]
# Use the first handle for initial parsing
primary_handle = mzml_handles[1]
try
# --- NEW: Parse instrument metadata from header ---
println("DEBUG: Parsing instrument metadata from header...")
instrument_meta = parse_instrument_metadata_mzml(ts_stream.handle)
instrument_meta = parse_instrument_metadata_mzml(primary_handle)
println("--- Extracted Instrument Metadata ---")
println("Resolution: ", instrument_meta.resolution)
println("Acquisition Mode (pre-check): ", instrument_meta.acquisition_mode)
println("Calibration Status: ", instrument_meta.calibration_status)
println("Instrument Model: ", instrument_meta.instrument_model)
println("Mass Accuracy (ppm): ", instrument_meta.mass_accuracy_ppm)
println("Laser Settings: ", instrument_meta.laser_settings)
println("Polarity: ", instrument_meta.polarity)
println("------------------------------------")
seekstart(ts_stream.handle) # Reset stream after header parsing
seekstart(primary_handle) # Reset stream after header parsing
println("DEBUG: Finding index offset...")
index_offset = find_index_offset(ts_stream.handle)
index_offset = find_index_offset(primary_handle)
# --- NEW: Mmap Optimization with RAM Safety ---
mmap_data = nothing
try
file_size = filesize(file_path)
println("DEBUG: Memory mapping .mzML file...")
seekstart(primary_handle) # Anchor Mmap to the beginning of the file to prevent overflow
mmap_data = Mmap.mmap(primary_handle, Vector{UInt8}, (file_size,))
println("DEBUG: .mzML file mmapped successfully.")
catch e
@warn "Memory mapping failed for mzML, falling back to standard I/O: $e"
end
println("DEBUG: Seeking to index list at offset $index_offset.")
seek(ts_stream.handle, index_offset)
seek(primary_handle, index_offset)
println("DEBUG: Searching for '<index name=\"spectrum\">'.")
if find_tag(ts_stream.handle, r"<index\s+name=\"spectrum\"") === nothing
if find_tag(primary_handle, r"<index\s+name=\"spectrum\"") === nothing
throw(FileFormatError("Could not find spectrum index."))
end
println("DEBUG: Found spectrum index tag.")
println("DEBUG: Parsing spectrum offsets...")
spectrum_offsets = parse_offset_list(ts_stream.handle)
spectrum_offsets = parse_offset_list(primary_handle)
if isempty(spectrum_offsets)
throw(FileFormatError("No spectrum offsets found."))
end
@@ -433,31 +443,25 @@ function load_mzml_lazy(file_path::String; cache_size::Int=100)
println("DEBUG: Found $num_spectra spectrum offsets.")
println("DEBUG: Parsing metadata for each spectrum...")
# Pre-allocate the metadata vector for better performance
spectra_metadata = Vector{SpectrumMetadata}(undef, num_spectra)
# Use @inbounds for faster indexing in the loop
@inbounds for i in 1:num_spectra
spectra_metadata[i] = parse_spectrum_metadata(ts_stream.handle, spectrum_offsets[i])
spectra_metadata[i] = parse_spectrum_metadata(primary_handle, spectrum_offsets[i])
# Progress reporting for large files
if i % 1000 == 0
println("DEBUG: Processed $i/$num_spectra spectra")
end
end
println("DEBUG: Metadata parsing complete for all $num_spectra spectra.")
# Assuming uniform data formats, take from the first spectrum
# Inferred global formats from first spectrum
first_meta = spectra_metadata[1]
mz_format = first_meta.mz_asset.format
intensity_format = first_meta.int_asset.format
println("DEBUG: Inferred global m/z format: $mz_format")
println("DEBUG: Inferred global intensity format: $intensity_format")
# --- NEW: Determine overall acquisition mode ---
modes = [meta.mode for meta in spectra_metadata]
num_centroid = count(m -> m == CENTROID, modes)
num_profile = count(m -> m == PROFILE, modes)
# Determine overall acquisition mode ...
num_centroid = count(m -> m.mode == CENTROID, spectra_metadata)
num_profile = count(m -> m.mode == PROFILE, spectra_metadata)
acq_mode_symbol = if num_centroid > 0 && num_profile == 0
:centroid
@@ -468,26 +472,28 @@ function load_mzml_lazy(file_path::String; cache_size::Int=100)
else
:unknown
end
println("DEBUG: Inferred overall acquisition mode: $acq_mode_symbol (Centroid: $num_centroid, Profile: $num_profile)")
final_instrument_meta = InstrumentMetadata(
instrument_meta.resolution,
acq_mode_symbol, # Update with parsed mode
acq_mode_symbol,
instrument_meta.mz_axis_type,
instrument_meta.calibration_status,
instrument_meta.instrument_model,
instrument_meta.mass_accuracy_ppm,
instrument_meta.laser_settings,
instrument_meta.polarity,
instrument_meta.vendor_preprocessing_steps # Add this new field
instrument_meta.vendor_preprocessing_steps
)
source = MzMLSource(ts_stream, mz_format, intensity_format)
source = MzMLSource(mzml_handles, mz_format, intensity_format, mmap_data)
println("DEBUG: Creating MSIData object.")
return MSIData(source, spectra_metadata, final_instrument_meta, (0, 0), nothing, cache_size)
catch e
close(ts_stream) # Ensure stream is closed on error
# Close all handles in the pool if initialization fails
for h in mzml_handles
isopen(h) && close(h)
end
rethrow(e)
end
end
+147 -23
View File
@@ -1,29 +1,141 @@
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
# Load and configure Genie
Genie.loadapp()
# --- Cross-Platform Startup Cleanup ---
# Remove orphaned GenieSessionFileSession directories from previous runs.
# These accumulate in the OS temp directory as jl_XXXXXX folders containing
# serialized session files (64-char hex filenames). Over long sessions or
# after crashes, they can consume gigabytes of disk space.
function cleanup_orphaned_sessions()
tmp = Base.tempdir()
cleaned_count = 0
cleaned_bytes = 0
# Remove html parser error discrepancy
redirect_stderr(devnull)
for entry in readdir(tmp; join=false)
# Only target directories matching Julia's temp naming pattern
startswith(entry, "jl_") || continue
full_path = joinpath(tmp, entry)
isdir(full_path) || continue
# Validate: a Genie session dir contains files with 64-char hex names
try
contents = readdir(full_path)
isempty(contents) && continue
# Check if at least one file matches the 64-char hex session ID pattern
is_session_dir = any(contents) do f
length(f) == 64 && all(c -> c in "0123456789abcdef", f)
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)
cleaned_count += 1
cleaned_bytes += dir_size
catch e
@debug "Skipping $entry during cleanup: $e"
end
end
if cleaned_count > 0
size_mb = round(cleaned_bytes / (1024^2), digits=1)
@info "Startup cleanup: removed $cleaned_count orphaned session dir(s), freed $(size_mb) MB"
end
end
cleanup_orphaned_sessions()
# Load and configure Genie. Do not redirect stderr: errors must remain visible
# to the user and to the log/diagnostics workflow.
Genie.loadapp()
# Start the Genie server
@async begin
@@ -31,15 +143,27 @@ redirect_stderr(devnull)
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()
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
+7 -3
View File
@@ -50,11 +50,15 @@ const BENCHMARK_CASES = [
# 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_LTP/ltpmsi-chilli.imzML",420,0.1, "Chilli Pepper"), # Chilli
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/ColAd_Individual/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/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/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"), # 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
]
const NUM_REPETITIONS = 50 # Number of times to generate the image for averaging
+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))
}
+281
View File
@@ -0,0 +1,281 @@
# test/benchmark_v3.jl
# ===================================================================
# High-Precision Performance Benchmark Suite (v3) - Cross-Engine
# ===================================================================
# Compares JuliaMSI (New) vs julia_mzML_imzML (Legacy)
# 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_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_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 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)
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]")
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"
# 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
df = DataFrame(LoadMem_MB=[NaN], LoadTime_s=[Inf], SliceMean_s=[NaN], SliceStd_s=[0.0])
CSV.write("$(temp_legacy_csv)", df)
end
"""
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]
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()
# ------------------------------------------------------------
# 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,
# 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,
# 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,
# 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")
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=22)
x_pos = 1:nrow(df)
labels = df.Dataset
# ---------- Panel A: Initial 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, labels), xticklabelrotation=π/8)
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)
# ---------- Panel B: Initial RAM Cost (Log Scale) ----------
ax2 = Axis(fig[1, 2],
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_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)
# ---------- Panel C: Slice Throughput & Error Bars ----------
ax3 = Axis(fig[2, 1:2],
title="Panel C: Slice Generation Time (Mean ± SD)",
ylabel="Time (seconds) - Log Scale",
yscale=log10,
xticks=(x_pos, labels), xticklabelrotation=π/8)
# 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 to $(joinpath(RESULTS_DIR, "v3_enterprise_dashboard.png"))")
end
if abspath(PROGRAM_FILE) == @__FILE__
run_v3_benchmarks()
end
+48
View File
@@ -0,0 +1,48 @@
using BenchmarkTools
using MSI_src
using Statistics
using DataFrames
# ===================================================================
# HIGH-PRECISION COMPARATIVE SUITE
# ===================================================================
function run_advanced_benchmark(path, mz, tol)
println("\n" * "="^40)
println("TARGET: $(basename(path))")
println("="^40)
# 1. NEW LIBRARY: Metadata Load (The "Control Tower" startup)
# This measures how fast the Mmap and Cache system works
t_load_new = @belapsed OpenMSIData($path)
# 2. NEW LIBRARY: Slice Generation (The "Streaming" speed)
msi_new = OpenMSIData(path)
# We use @benchmark to get a distribution (min, mean, max)
b_slice_new = @benchmark get_mz_slice($msi_new, $mz, $tol)
# --- Metrics Table ---
results = DataFrame(
Metric = ["Metadata Load", "Slice Gen (Min)", "Slice Gen (Mean)", "Allocations"],
JuliaMSI = [
"$(round(t_load_new * 1000, digits=2)) ms",
"$(round(minimum(b_slice_new.times)/1e6, digits=2)) ms",
"$(round(mean(b_slice_new.times)/1e6, digits=2)) ms",
"$(b_slice_new.allocs) allocs"
]
)
println(results)
# --- The "Throughput" Test ---
# How many slices per second can we handle?
throughput_new = 1.0 / mean(b_slice_new.times/1e9)
println("\nThroughput: $(round(throughput_new, digits=1)) slices/sec")
return results
end
# Example Run
@time run_advanced_benchmark("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053, 0.1)
# For multithread: julia --threads auto --project=. test/new_benchmark_mmap.jl
+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/)
+2 -1
View File
@@ -16,8 +16,9 @@ using MSI_src
const TEST_MZML_FILE = ""
# const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/CE4_BF_R1/CE4_BF_R1.imzML"
#const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/salida/Stomach_DHB_uncompressed.imzML"
const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/Thricoderma_etc/Imaging_interaccion_trichoderma_vs_streptomyces.imzML"
# const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/Thricoderma_etc/Imaging_interaccion_trichoderma_vs_streptomyces.imzML"
#const MASK_ROUTE = "/home/pixel/Documents/Cinvestav_2025/JuliaMSI/public/css/masks/Stomach_DHB_uncompressed.png"
const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML"
const MASK_ROUTE = ""
#=
+4 -4
View File
@@ -19,11 +19,11 @@ using MSI_src
# const TEST_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/Thricoderma_etc/Imaging_interaccion_trichoderma_vs_streptomyces.imzML"
# const TEST_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/set de datos MS/Atropina_tuneo_fraq_20ev.mzML"
const TEST_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/salida/Stomach_DHB_uncompressed.imzML"
# const TEST_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML"
# const TEST_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/salida/Stomach_DHB_uncompressed.imzML"
const TEST_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML"
const MASK_ROUTE = "/home/pixel/Documents/Cinvestav_2025/JuliaMSI/public/css/masks/Stomach_DHB_uncompressed.png"
# const MASK_ROUTE = ""
# const MASK_ROUTE = "/home/pixel/Documents/Cinvestav_2025/JuliaMSI/public/css/masks/Stomach_DHB_uncompressed.png"
const MASK_ROUTE = ""
const OUTPUT_DIR = "./test/results/preprocessing_results"
+17 -7
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"))
# ===================================================================
@@ -31,9 +39,10 @@ using MSI_src
# --- Test Case 1: Standard .mzML file ---
# A regular, non-imaging mzML file.
# const TEST_MZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/mzML/T9_A1.mzML"
const TEST_MZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/CE4_BF_R1/CE4_BF_R1.mzML"
# const TEST_MZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/CE4_BF_R1/CE4_BF_R1.mzML"
# const TEST_MZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/Imaging_paper_spray/Imaging_paper_spray.mzML"
# const TEST_MZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/Imaging prueba Roya 1/Roya.mzML"
const TEST_MZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/mzML"
const SPECTRUM_TO_PLOT = 1 # Which spectrum to plot from the file
# --- Test Case 2: .mzML + Sync File for Conversion ---
@@ -58,16 +67,17 @@ const CONVERSION_TARGET_IMZML = "test/results/converted_mzml.imzML"
# const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/Imaging prueba Roya 1/royaimg.imzML"
# const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/salida/ltpmsi-chilli.imzML" # centroid aparently?
# const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/salida/Stomach_DHB_compressed.imzML" # centroid compressed
const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/salida/Stomach_DHB_uncompressed.imzML" # centroid
# const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/salida/Stomach_DHB_uncompressed.imzML" # centroid
const TEST_IMZML_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML"
# The m/z value to use for creating an image slice.
# const MZ_VALUE_FOR_SLICE = 309.06 # BF
# const MZ_VALUE_FOR_SLICE = 896.0 # HR2MSI
const MZ_VALUE_FOR_SLICE = 896.0 # HR2MSI
# const MZ_VALUE_FOR_SLICE = 76.03 # I PS
# const MZ_VALUE_FOR_SLICE = 313 # ROYA
const MZ_VALUE_FOR_SLICE = 100 # advanced processing
# const MZ_VALUE_FOR_SLICE = 100 # advanced processing
# const MZ_TOLERANCE = 0.1
# const MZ_TOLERANCE = 1
const MZ_TOLERANCE = 0.1
const MZ_TOLERANCE = 0.2
# Coordinates to plot a specific spectrum from imzML
const COORDS_TO_PLOT = (50, 50) # Example coordinates (X, Y)
+73
View File
@@ -0,0 +1,73 @@
using Test
using MSI_src
@testset "JuliaMSI Core Systems" begin
@testset "Basic Instantiation" begin
# 1. Test basic metadata structure initialization
meta = SpectrumMetadata(
Int32(1), Int32(2),
"test_id",
:sample,
CENTROID,
SpectrumAsset(Float64, false, Int64(0), 100, :mz, 0.0, 0.0),
SpectrumAsset(Float32, true, Int64(100), 50, :intensity, 0.0, 0.0)
)
@test meta.x == 1
@test meta.y == 2
@test meta.mode == CENTROID
@test meta.mz_asset.format == Float64
@test meta.int_asset.format == Float32
@test meta.int_asset.is_compressed == true
# 2. Test cache pool and MSIData structural stability
source = MzMLSource([], Float64, Float32, nothing) # Empty source for structural testing
# Test constructor doesn't throw
# Constructor signature: (source, metadata, instrument_meta, dims, coordinate_map, cache_size)
msi_data = MSIData(
source,
[meta],
nothing, # instrument_meta
(100, 100), # dims
nothing, # coord map
10 # cache size
)
@test msi_data.image_dims == (100, 100)
@test length(msi_data.spectra_metadata) == 1
@test msi_data.cache_size == 10
end
@testset "Buffer & Cache Subsystems" begin
pool = SimpleBufferPool()
# Test basic retrieval
buf = get_buffer!(pool, 1024)
@test length(buf) == 1024
# Test release
release_buffer!(pool, buf)
@test length(pool.buffers[1024]) == 1
# Test reuse
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")
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env julia
# test/test_streaming_pipeline.jl
# ============================================================================
# Validation test for Sprint 2: The Streaming Pipeline
#
# This test exercises process_dataset! against the HR2MSI mouse bladder
# dataset and verifies:
# 1. Correct sparse matrix creation
# 2. Non-zero peak population
# 3. RAM savings vs dense equivalent
# 4. Allocation count and throughput
# ============================================================================
using Pkg
Pkg.activate(joinpath(@__DIR__, ".."))
using MSI_src
using SparseArrays
# =============================================================================
# Configuration
# =============================================================================
const IMZML_PATH = get(ENV, "JULIA_MSI_TEST_IMZML",
"/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML")
function main()
println("=" ^ 60)
println("SPRINT 2: Streaming Pipeline Validation")
println("=" ^ 60)
if !isfile(IMZML_PATH)
println("SKIPPED: Dataset not found at $IMZML_PATH")
return
end
# --- 1. Load dataset ---
println("\n--- Step 1: Loading dataset ---")
data = OpenMSIData(IMZML_PATH)
println("Loaded: $(length(data.spectra_metadata)) spectra")
# --- 2. Configure the streaming pipeline ---
println("\n--- Step 2: Configuring pipeline ---")
config = PipelineConfig(
steps = [
StreamingStep(:baseline_correction, Dict{Symbol,Any}(:method => :snip, :iterations => 50)),
StreamingStep(:normalization, Dict{Symbol,Any}(:method => :tic)),
StreamingStep(:peak_picking, Dict{Symbol,Any}(
:method => :profile,
:snr_threshold => 3.0,
:half_window => 10,
:min_peak_prominence => 0.1,
:merge_peaks_tolerance => 0.002
)),
],
num_bins = 2000,
frequency_threshold = 0.01 # Bins must appear in at least 1% of spectra
)
println("Steps: $(join([s.name for s in config.steps], " → "))")
println("Bins: $(config.num_bins), Frequency threshold: $(config.frequency_threshold)")
# --- 3. Run the streaming pipeline ---
println("\n--- Step 3: Running streaming pipeline ---")
stats = @timed begin
feature_matrix, bin_centers = process_dataset!(data, config)
end
feature_matrix = stats.value[1]
bin_centers = stats.value[2]
println("\n--- Results ---")
println(" Feature matrix size: $(size(feature_matrix))")
println(" Non-zeros: $(nnz(feature_matrix))")
println(" Bin centers: $(length(bin_centers))")
println(" Time: $(round(stats.time, digits=2))s")
println(" Allocations: $(stats.bytes ÷ 1_000_000) MB")
println(" GC time: $(round(stats.gctime, digits=2))s")
# --- 4. Validate ---
println("\n--- Step 4: Validation ---")
passed = true
# Check matrix dimensions
if size(feature_matrix, 1) > 0 && size(feature_matrix, 2) > 0
println(" ✓ Matrix has valid dimensions")
else
println(" ✗ Matrix has invalid dimensions: $(size(feature_matrix))")
passed = false
end
# Check non-zeros
if nnz(feature_matrix) > 0
println(" ✓ Matrix has $(nnz(feature_matrix)) non-zero entries")
else
println(" ✗ Matrix is completely empty")
passed = false
end
# Check sparsity savings
dense_mb = size(feature_matrix, 1) * size(feature_matrix, 2) * 8 / 1e6
sparse_mb = nnz(feature_matrix) * 16 / 1e6 # index + value per entry
if dense_mb > 0
savings = (1.0 - sparse_mb / dense_mb) * 100
println(" ✓ RAM savings: $(round(savings, digits=1))% ($(round(sparse_mb, digits=1)) MB vs $(round(dense_mb, digits=1)) MB dense)")
end
# Check bin centers alignment
if length(bin_centers) == size(feature_matrix, 1)
println(" ✓ Bin centers match matrix rows")
else
println(" ✗ Bin center count ($(length(bin_centers))) != matrix rows ($(size(feature_matrix, 1)))")
passed = false
end
println("\n" * "=" ^ 60)
if passed
println("ALL VALIDATIONS PASSED ✓")
else
println("SOME VALIDATIONS FAILED ✗")
end
println("=" ^ 60)
end
@time main()