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

This commit is contained in:
Pixelguy14
2026-11-17 11:26:39 -06:00
parent 89de5a56e0
commit bc71b9ce94
34 changed files with 2124 additions and 654 deletions
+267
View File
@@ -0,0 +1,267 @@
# test/benchmark_comparison.jl
# ===================================================================
# Cross-Language Performance Benchmark Suite: JuliaMSI vs R (MALDIquant & Cardinal)
# ===================================================================
# This script runs the performance benchmarks for:
# 1. JuliaMSI (New Engine)
# 2. R - MALDIquant (isolated run)
# 3. R - Cardinal (isolated run)
#
# It saves the results to `test/results/cross_language_benchmark.csv` and
# creates a comparison plot.
# ===================================================================
using Pkg
Pkg.activate(joinpath(@__DIR__, ".."))
using BenchmarkTools
using DataFrames
using CSV
using CairoMakie
using Statistics
using MSI_src
struct BenchmarkCase
filepath::String
mz_value::Float64
mz_tolerance::Float64
name::String
end
const RESULTS_DIR = joinpath(@__DIR__, "results")
const NUM_REPETITIONS = 10 # Number of slice repetitions for averaging
const BENCHMARK_CASES = [
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML", 436.04, 0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Chilli/ltpmsi-chilli.imzML", 420.0, 0.1, "Chilli Pepper"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/40TopL,10TopR,30BottomL,20BottomR/40TopL,10TopR,30BottomL,20BottomR-centroid.imzML", 885.5, 0.1, "Human Colon Cancer"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053, 0.1, "Mouse Urinary Bladder"),
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML", 306.1, 0.1, "Leaf"), # Este leaf es diferente de taliana!
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Liv2_imzML_TIMSConvert-selected/Liv2.imzML", 796.18, 0.1, "Liver Cut"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida_Tims/Stomach_DHB.imzML", 804.3, 0.1, "Mouse Stomach 4GB")
]
function get_total_file_size_mb(filepath::String)
imzml_size = isfile(filepath) ? filesize(filepath) : 0
ibd_path = replace(filepath, r"\.(imzML|imzml)$" => ".ibd")
ibd_size = isfile(ibd_path) ? filesize(ibd_path) : 0
return round((imzml_size + ibd_size) / 1024^2, digits=2)
end
function flush_memory()
GC.gc(true)
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
end
end
function run_cross_benchmarks()
mkpath(RESULTS_DIR)
results = DataFrame()
println("="^60)
println("STARTING CROSS-LANGUAGE BENCHMARK (JuliaMSI vs R)")
println("="^60)
# Check if Rscript is available
has_r = try
success(`Rscript --version`)
catch
false
end
if !has_r
@warn "Rscript is not available. Please install R first to compare with MALDIquant/Cardinal."
end
for case in BENCHMARK_CASES
if !isfile(case.filepath)
@warn "File not found: $(case.filepath). Skipping."
continue
end
println("\n--- Target Dataset: $(case.name) ---")
file_size = get_total_file_size_mb(case.filepath)
# ------------------------------------------------------------
# 1. JuliaMSI (New Engine)
# ------------------------------------------------------------
println("[JuliaMSI - New Engine]")
flush_memory()
load_stats_new = @timed OpenMSIData(case.filepath)
msi_data = load_stats_new.value
load_time_new_s = load_stats_new.time
mem_load_new_mb = load_stats_new.bytes / 1024^2
# Benchmark slice generation
b_slice_new = @benchmark get_mz_slice($msi_data, $(case.mz_value), $(case.mz_tolerance)) samples=NUM_REPETITIONS seconds=10
mean_time_new_s = mean(b_slice_new.times) / 1e9
close(msi_data)
flush_memory()
# Record JuliaMSI results
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "JuliaMSI",
LoadTime_s = load_time_new_s,
LoadMem_MB = mem_load_new_mb,
AvgSliceTime_s = mean_time_new_s,
Status = "Success"
))
# ------------------------------------------------------------
# 2. Run R MALDIquant (Isolated process)
# ------------------------------------------------------------
if has_r
println("[R - MALDIquant (centroid=TRUE)]")
temp_r_csv = joinpath(RESULTS_DIR, "temp_r_mq.csv")
r_script_path = joinpath(@__DIR__, "benchmark_r.R")
try
cmd = `Rscript $r_script_path maldiquant $(case.filepath) $(case.mz_value) $(case.mz_tolerance) $NUM_REPETITIONS $temp_r_csv`
process_status = run(cmd, wait=true)
if success(process_status) && isfile(temp_r_csv)
r_df = CSV.read(temp_r_csv, DataFrame)
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "MALDIquant",
LoadTime_s = r_df.LoadTime_s[1],
LoadMem_MB = r_df.LoadMem_MB[1],
AvgSliceTime_s = r_df.AvgSliceTime_s[1],
Status = "Success"
))
rm(temp_r_csv, force=true)
else
throw(ErrorException("R process failed with exit code $(process_status.exitcode)"))
end
catch e
@warn "MALDIquant benchmark failed/OOMed for $(case.name): $e"
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "MALDIquant",
LoadTime_s = NaN,
LoadMem_MB = NaN,
AvgSliceTime_s = NaN,
Status = "OOM / Failed"
))
end
# ------------------------------------------------------------
# 3. Run R Cardinal (Isolated process)
# ------------------------------------------------------------
println("[R - Cardinal (matter lazy-loading)]")
temp_r_csv_card = joinpath(RESULTS_DIR, "temp_r_card.csv")
try
cmd = `Rscript $r_script_path cardinal $(case.filepath) $(case.mz_value) $(case.mz_tolerance) $NUM_REPETITIONS $temp_r_csv_card`
process_status = run(cmd, wait=true)
if success(process_status) && isfile(temp_r_csv_card)
r_df = CSV.read(temp_r_csv_card, DataFrame)
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "Cardinal",
LoadTime_s = r_df.LoadTime_s[1],
LoadMem_MB = r_df.LoadMem_MB[1],
AvgSliceTime_s = r_df.AvgSliceTime_s[1],
Status = "Success"
))
rm(temp_r_csv_card, force=true)
else
throw(ErrorException("R process failed with exit code $(process_status.exitcode)"))
end
catch e
@warn "Cardinal benchmark failed/OOMed for $(case.name): $e"
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "Cardinal",
LoadTime_s = NaN,
LoadMem_MB = NaN,
AvgSliceTime_s = NaN,
Status = "OOM / Failed"
))
end
end
end
csv_path = joinpath(RESULTS_DIR, "cross_language_benchmark.csv")
CSV.write(csv_path, results)
println("\nDetailed cross-language results saved to $csv_path")
if nrow(results) > 0
plot_cross_results(results)
end
return results
end
function plot_cross_results(df::DataFrame)
# Filter datasets
unique_datasets = unique(df.Dataset)
if isempty(unique_datasets) return end
fig = Figure(size=(1800, 1200), fontsize=20)
libraries = ["JuliaMSI", "MALDIquant", "Cardinal"]
colors = ["#10b981", "#3b82f6", "#8b5cf6"] # green, blue, purple
x_pos = 1:length(unique_datasets)
# Axis 1: Slice Generation Time
ax1 = Axis(fig[1, 1],
title="Average Slice Generation Time (Lower is Better)",
ylabel="Time (seconds)",
xticks=(x_pos, unique_datasets), xticklabelrotation=π/8)
# Axis 2: RAM overhead during load
ax2 = Axis(fig[1, 2],
title="Memory Consumption during Load (Lower is Better)",
ylabel="Memory (MB)",
xticks=(x_pos, unique_datasets), xticklabelrotation=π/8)
# Plot grouped bars
width = 0.25
offsets = [-width, 0.0, width]
for (idx, lib) in enumerate(libraries)
lib_df = df[df.Library .== lib, :]
if isempty(lib_df) continue end
# Match rows with unique_datasets order
slice_times = Float64[]
load_mems = Float64[]
for ds in unique_datasets
row = lib_df[lib_df.Dataset .== ds, :]
if nrow(row) > 0 && row.Status[1] == "Success"
push!(slice_times, coalesce(row.AvgSliceTime_s[1], 0.0))
push!(load_mems, coalesce(row.LoadMem_MB[1], 0.0))
else
push!(slice_times, 0.0)
push!(load_mems, 0.0)
end
end
barplot!(ax1, x_pos .+ offsets[idx], slice_times, color=colors[idx], width=width, label=lib)
barplot!(ax2, x_pos .+ offsets[idx], load_mems, color=colors[idx], width=width, label=lib)
end
axislegend(ax1, position=:rt)
axislegend(ax2, position=:rt)
save(joinpath(RESULTS_DIR, "cross_language_comparison.png"), fig)
println("Comparison dashboard saved to $(joinpath(RESULTS_DIR, "cross_language_comparison.png"))")
end
if abspath(PROGRAM_FILE) == @__FILE__
run_cross_benchmarks()
end
+216
View File
@@ -0,0 +1,216 @@
# test/benchmark_v3.jl
# ===================================================================
# High-Precision Performance Benchmark Suite (v3)
# ===================================================================
# This script integrates the robust statistical sampling of `BenchmarkTools`
# with the visual comparative mechanics against the legacy library.
# It captures the paradigm shift from "Time per slice" to "Pipeline Throughput".
# ===================================================================
using Pkg
Pkg.activate(joinpath(@__DIR__, ".."))
using BenchmarkTools
using DataFrames
using CSV
using CairoMakie
using Statistics
using MSI_src
using julia_mzML_imzML
struct BenchmarkCase
filepath::String
mz_value::Float64
mz_tolerance::Float64
name::String
end
const RESULTS_DIR = joinpath(@__DIR__, "results")
# List to benchmark
const BENCHMARK_CASES = [
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML", 436.04, 0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Chilli/ltpmsi-chilli.imzML", 420.0, 0.1, "Chilli Pepper"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/40TopL,10TopR,30BottomL,20BottomR/40TopL,10TopR,30BottomL,20BottomR-centroid.imzML", 885.5, 0.1, "Colon Cancer Human"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053, 0.1, "Mouse Urinary Bladder"),
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML", 306.1, 0.1, "Leaf"), # Este leaf es diferente de taliana!
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Liv2_imzML_TIMSConvert-selected/Liv2.imzML", 796.18, 0.1, "Liver Cut"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida_Tims/Stomach_DHB.imzML", 804.3, 0.1, "Mouse Stomach 4GB")
]
function get_total_file_size_mb(filepath::String)
imzml_size = isfile(filepath) ? filesize(filepath) : 0
ibd_path = replace(filepath, r"\.(imzML|imzml)$" => ".ibd")
ibd_size = isfile(ibd_path) ? filesize(ibd_path) : 0
return round((imzml_size + ibd_size) / 1024^2, digits=2)
end
function flush_memory()
GC.gc(true)
if Sys.islinux()
# Force the OS to reclaim memory from the glibc allocator
ccall(:malloc_trim, Int32, (Int32,), 0)
end
end
function run_v3_benchmarks()
mkpath(RESULTS_DIR)
results = DataFrame()
println("="^60)
println("STARTING ENTERPRISE BENCHMARK SUITE (v3)")
println("="^60)
for case in BENCHMARK_CASES
if !isfile(case.filepath)
@warn "File not found: $(case.filepath). Skipping."
continue
end
println("\n--- Target: $(case.name) ---")
file_size = get_total_file_size_mb(case.filepath)
# ------------------------------------------------------------
# 1. JuliaMSI (New Architecture)
# ------------------------------------------------------------
println("[JuliaMSI - New Engine]")
flush_memory()
# Load Phase (Metadata Only / Memory Mapping)
load_stats_new = @timed OpenMSIData(case.filepath)
msi_data = load_stats_new.value
load_time_new_s = load_stats_new.time
mem_load_new_mb = load_stats_new.bytes / 1024^2
# Slicing Phase (High Precision)
b_slice_new = @benchmark get_mz_slice($msi_data, $(case.mz_value), $(case.mz_tolerance)) samples=10 seconds=5
mean_time_new_s = mean(b_slice_new.times) / 1e9
# Calculate Amortized Throughput (10 slices)
# Includes the 'Loading Wall' penalty
total_time_10_new = load_time_new_s + (10 * mean_time_new_s)
amortized_sps_new = 10.0 / total_time_10_new
close(msi_data)
flush_memory()
# ------------------------------------------------------------
# 2. julia_mzML_imzML (Legacy Architecture)
# ------------------------------------------------------------
println("[julia_mzML_imzML - Legacy]")
load_stats_old = try
@timed LoadImzml(case.filepath)
catch e
@warn "Legacy load failed: $e"
(time=Inf, bytes=Inf, value=nothing)
end
old_data = load_stats_old.value
mem_load_old_mb = load_stats_old.bytes / 1024^2
load_time_old_s = Inf
mean_time_old_s = Inf
amortized_sps_old = 0.0
if old_data !== nothing
b_slice_old = try
# Legacy can be extremely slow, constrain it heavily
@benchmark GetSlice($old_data, $(case.mz_value), $(case.mz_tolerance)) samples=3 seconds=10
catch e
@warn "Legacy slice failed: $e"
nothing
end
if b_slice_old !== nothing
mean_time_old_s = mean(b_slice_old.times) / 1e9
# Accurately reflect the massive load time in the throughput
load_time_old_s = load_stats_old.time
total_time_10_old = load_time_old_s + (10 * mean_time_old_s)
amortized_sps_old = 10.0 / total_time_10_old
end
end
flush_memory()
# ------------------------------------------------------------
# Record
# ------------------------------------------------------------
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
# Legacy Metrics
Legacy_LoadMem_MB = mem_load_old_mb,
Legacy_LoadTime_s = load_stats_old.time,
Legacy_Amortized_SPS_10 = amortized_sps_old,
# New Metrics
New_LoadMem_MB = mem_load_new_mb,
New_LoadTime_s = load_time_new_s,
New_Amortized_SPS_10 = amortized_sps_new,
# Competitive Deltas
RAM_Reduction_Pct = isfinite(mem_load_old_mb) ? ((mem_load_old_mb - mem_load_new_mb) / mem_load_old_mb)*100 : NaN,
UX_Speedup_Factor = isfinite(amortized_sps_old) ? (amortized_sps_new / amortized_sps_old) : NaN
))
println(" > RAM Reduction: $(round(results[end, :RAM_Reduction_Pct], digits=2))%")
println(" > Amortized Throughput (10 Slices): $(round(amortized_sps_old, digits=2)) -> $(round(amortized_sps_new, digits=2)) slices/sec")
end
csv_path = joinpath(RESULTS_DIR, "v3_enterprise_benchmarks.csv")
CSV.write(csv_path, results)
println("\nData saved to $csv_path")
plot_v3_results(results)
return results
end
function plot_v3_results(df::DataFrame)
if isempty(df) return end
fig = Figure(size=(1800, 1200), fontsize=24)
x_pos = 1:nrow(df)
labels = df.Dataset
# ---------- Plot 1: The RAM Revolution ----------
ax1 = Axis(fig[1, 1],
title="Initial RAM Cost (Loading & Mmap)",
ylabel="Memory (MB)",
xticks=(x_pos, labels), xticklabelrotation=π/8)
barplot!(ax1, x_pos .- 0.2, df.New_LoadMem_MB, color="#10b981", width=0.4, label="JuliaMSI (Mmap Lazy)")
barplot!(ax1, x_pos .+ 0.2, df.Legacy_LoadMem_MB, color="#ef4444", width=0.4, label="Legacy (Dense Matrix)")
axislegend(ax1, position=:lt)
# ---------- Plot 2: Throughput Leap ----------
ax2 = Axis(fig[1, 2],
title="Amortized Throughput (10 Slices - Higher is Better)",
ylabel="Slices / Second (Inc. Load Time)",
xticks=(x_pos, labels), xticklabelrotation=π/8)
barplot!(ax2, x_pos .- 0.2, df.New_Amortized_SPS_10, color="#10b981", width=0.4, label="JuliaMSI")
barplot!(ax2, x_pos .+ 0.2, df.Legacy_Amortized_SPS_10, color="#ef4444", width=0.4, label="Legacy")
axislegend(ax2, position=:lt)
# ---------- Plot 3: The Scaling Wall (File Size vs Throughput) ----------
ax3 = Axis(fig[2, 1:2],
title="Performance Scaling: UX Throughput vs Dataset Size",
xlabel="Dataset File Size (MB)",
ylabel="Amortized Throughput (Slices/sec)")
scatterlines!(ax3, df.FileSize_MB, df.New_Amortized_SPS_10, color="#10b981", markersize=15, linewidth=4, label="JuliaMSI Engine")
scatterlines!(ax3, df.FileSize_MB, df.Legacy_Amortized_SPS_10, color="#ef4444", markersize=15, linewidth=4, label="Legacy Engine")
axislegend(ax3, position=:rt)
save(joinpath(RESULTS_DIR, "v3_enterprise_dashboard.png"), fig)
println("\nDashboards saved successfully.")
end
# Ensure we process if run as the main script
if abspath(PROGRAM_FILE) == @__FILE__
run_v3_benchmarks()
end
+3 -3
View File
@@ -49,13 +49,13 @@ const BENCHMARK_CASES = [
# BenchmarkCase("/path/to/your/small_file.imzML", 309.06, 0.1),
# BenchmarkCase("/path/to/your/medium_file.imzML", 896.0, 1.0),
# BenchmarkCase("/path/to/your/large_file.imzML", 100.0, 0.1),
# BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML",116.07,0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML",116.07,0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Chilli/ltpmsi-chilli.imzML",420,0.1, "Chilli Pepper"), # Chilli
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/40TopL,10TopR,30BottomL,20BottomR/40TopL,10TopR,30BottomL,20BottomR-centroid.imzML",885.5,0.1, "Colon Cancer Human"), # Human Cancer
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053,0.1, "Mouse Urinary Bladder"), # Mouse bladder
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML",306.1,0.1, "Leaf"),
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML",306.1,0.1, "Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Liv2_imzML_TIMSConvert-selected/Liv2.imzML",796.18,0.1, "Liver Cut"), #Lib2
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida/Stomach_DHB_uncompressed.imzML",804.3,0.1, "Mouse Stomach 2GB"), # Mouse Stomach
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida/Stomach_DHB_uncompressed.imzML",804.3,0.1, "Mouse Stomach 2GB"), # Mouse Stomach
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida_Tims/Stomach_DHB.imzML",804.3,0.1, "Mouse Stomach 4GB"), # Mouse Stomach
+320
View File
@@ -0,0 +1,320 @@
# test/benchmark_comparison.jl
# ===================================================================
# Cross-Language Performance Benchmark Suite: JuliaMSI vs R (MALDIquant & Cardinal)
# ===================================================================
# Compares JuliaMSI (Julia) vs MALDIquant (R) vs Cardinal (R)
# Integrates formal academic metrics, error bars, and log-scale plots.
# ===================================================================
using Pkg
Pkg.activate(joinpath(@__DIR__, ".."))
using BenchmarkTools
using DataFrames
using CSV
using CairoMakie
using Statistics
using MSI_src
struct BenchmarkCase
filepath::String
mz_value::Float64
mz_tolerance::Float64
name::String
end
const RESULTS_DIR = joinpath(@__DIR__, "results")
const NUM_REPETITIONS = 10
const BENCHMARK_CASES = [
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML", 436.04, 0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Chilli/ltpmsi-chilli.imzML", 420.0, 0.1, "Chilli Pepper"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/40TopL,10TopR,30BottomL,20BottomR/40TopL,10TopR,30BottomL,20BottomR-centroid.imzML", 885.5, 0.1, "Colon Cancer Human"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053, 0.1, "Mouse Urinary Bladder"),
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML", 306.1, 0.1, "Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Liv2_imzML_TIMSConvert-selected/Liv2.imzML", 796.18, 0.1, "Liver Cut"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida_Tims/Stomach_DHB.imzML", 804.3, 0.1, "Mouse Stomach 4GB")
]
function get_total_file_size_mb(filepath::String)
imzml_size = isfile(filepath) ? filesize(filepath) : 0
ibd_path = replace(filepath, r"\.(imzML|imzml)$" => ".ibd")
ibd_size = isfile(ibd_path) ? filesize(ibd_path) : 0
return round((imzml_size + ibd_size) / 1024^2, digits=2)
end
function flush_memory()
GC.gc(true)
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
end
end
function run_cross_benchmarks()
mkpath(RESULTS_DIR)
results = DataFrame()
println("="^60)
println("STARTING CROSS-LANGUAGE BENCHMARK (JuliaMSI vs R)")
println("="^60)
has_r = try
success(`Rscript --version`)
catch
false
end
if !has_r
@warn "Rscript is not available. Please install R first to compare with MALDIquant/Cardinal."
end
for case in BENCHMARK_CASES
if !isfile(case.filepath)
@warn "File not found: $(case.filepath). Skipping."
continue
end
println("\n--- Target Dataset: $(case.name) ---")
file_size = get_total_file_size_mb(case.filepath)
# ------------------------------------------------------------
# 1. JuliaMSI (New Engine)
# ------------------------------------------------------------
println("[JuliaMSI - New Engine]")
flush_memory()
load_stats_new = @timed OpenMSIData(case.filepath)
msi_data = load_stats_new.value
load_time_new_s = load_stats_new.time
mem_load_new_mb = load_stats_new.bytes / 1024^2
# Benchmark slice generation
b_slice_new = @benchmark get_mz_slice($msi_data, $(case.mz_value), $(case.mz_tolerance)) samples=NUM_REPETITIONS seconds=10
times_new_s = b_slice_new.times ./ 1e9
mean_time_new_s = mean(times_new_s)
std_time_new_s = std(times_new_s)
close(msi_data)
flush_memory()
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "JuliaMSI",
LoadTime_s = load_time_new_s,
LoadMem_MB = mem_load_new_mb,
AvgSliceTime_s = mean_time_new_s,
SliceStd_s = std_time_new_s,
Status = "Success"
))
# ------------------------------------------------------------
# 2. Run R MALDIquant (Isolated process)
# ------------------------------------------------------------
if has_r
# Skip MALDIquant for files > 3 GB to prevent system SIGKILL
if file_size > 5000
println("Skipping MALDIquant benchmark for $(case.name) to prevent SIGKILL OOM.")
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "MALDIquant",
LoadTime_s = NaN,
LoadMem_MB = NaN,
AvgSliceTime_s = NaN,
SliceStd_s = 0.0,
Status = "OOM / Skipped"
))
else
println("[R - MALDIquant (centroid=TRUE)]")
temp_r_csv = joinpath(RESULTS_DIR, "temp_r_mq.csv")
r_script_path = joinpath(@__DIR__, "benchmark_r.R")
try
cmd = `Rscript $r_script_path maldiquant $(case.filepath) $(case.mz_value) $(case.mz_tolerance) $NUM_REPETITIONS $temp_r_csv`
process_status = run(cmd, wait=true)
if success(process_status) && isfile(temp_r_csv)
r_df = CSV.read(temp_r_csv, DataFrame)
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "MALDIquant",
LoadTime_s = r_df.LoadTime_s[1],
LoadMem_MB = r_df.LoadMem_MB[1],
AvgSliceTime_s = r_df.AvgSliceTime_s[1],
SliceStd_s = 0.0, # R script simplified to mean
Status = "Success"
))
rm(temp_r_csv, force=true)
else
throw(ErrorException("R process failed"))
end
catch e
@warn "MALDIquant benchmark failed/OOMed: $e"
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "MALDIquant",
LoadTime_s = NaN,
LoadMem_MB = NaN,
AvgSliceTime_s = NaN,
SliceStd_s = 0.0,
Status = "OOM / Failed"
))
end
end
# ------------------------------------------------------------
# 3. Run R Cardinal (Isolated process)
# ------------------------------------------------------------
println("[R - Cardinal (matter lazy-loading)]")
temp_r_csv_card = joinpath(RESULTS_DIR, "temp_r_card.csv")
r_script_path = joinpath(@__DIR__, "benchmark_r.R")
try
cmd = `Rscript $r_script_path cardinal $(case.filepath) $(case.mz_value) $(case.mz_tolerance) $NUM_REPETITIONS $temp_r_csv_card`
process_status = run(cmd, wait=true)
if success(process_status) && isfile(temp_r_csv_card)
r_df = CSV.read(temp_r_csv_card, DataFrame)
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "Cardinal",
LoadTime_s = r_df.LoadTime_s[1],
LoadMem_MB = r_df.LoadMem_MB[1],
AvgSliceTime_s = r_df.AvgSliceTime_s[1],
SliceStd_s = 0.0,
Status = "Success"
))
rm(temp_r_csv_card, force=true)
else
throw(ErrorException("R process failed"))
end
catch e
@warn "Cardinal benchmark failed/OOMed: $e"
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
Library = "Cardinal",
LoadTime_s = NaN,
LoadMem_MB = NaN,
AvgSliceTime_s = NaN,
SliceStd_s = 0.0,
Status = "OOM / Failed"
))
end
end
end
# Calculate Derived Academic Metrics
# Throughput, MemEfficiency, FoldSpeedup (rel. to Cardinal), LoadBandwidth
results.Throughput_SPS = 1.0 ./ results.AvgSliceTime_s
results.MemEff_MB_GB = results.LoadMem_MB ./ (results.FileSize_MB ./ 1024.0)
results.LoadBandwidth_MBs = results.FileSize_MB ./ results.LoadTime_s
# Fold Speedup calculation using Cardinal as Baseline
results.Fold_Speedup = fill(NaN, nrow(results))
for ds in unique(results.Dataset)
ds_rows = results[results.Dataset .== ds, :]
cardinal_row = ds_rows[ds_rows.Library .== "Cardinal", :]
julia_row = ds_rows[ds_rows.Library .== "JuliaMSI", :]
if nrow(cardinal_row) > 0 && nrow(julia_row) > 0 && cardinal_row.Status[1] == "Success"
card_time = cardinal_row.AvgSliceTime_s[1]
julia_time = julia_row.AvgSliceTime_s[1]
# Speedup = Cardinal Time / JuliaMSI Time
speedup = card_time / julia_time
results[ (results.Dataset .== ds) .& (results.Library .== "JuliaMSI"), :Fold_Speedup ] .= speedup
end
end
csv_path = joinpath(RESULTS_DIR, "cross_language_benchmark.csv")
CSV.write(csv_path, results)
println("\nDetailed cross-language results saved to $csv_path")
if nrow(results) > 0
plot_cross_results(results)
end
return results
end
function plot_cross_results(df::DataFrame)
unique_datasets = unique(df.Dataset)
if isempty(unique_datasets) return end
fig = Figure(size=(1800, 1200), fontsize=22)
libraries = ["JuliaMSI", "MALDIquant", "Cardinal"]
colors = ["#10b981", "#3b82f6", "#8b5cf6"] # green, blue, purple
x_pos = 1:length(unique_datasets)
# ---------- Panel A: Load Time (Log Scale) ----------
ax1 = Axis(fig[1, 1],
title="Panel A: Metadata/File Load Time",
ylabel="Time (seconds) - Log Scale",
yscale=log10,
xticks=(x_pos, unique_datasets), xticklabelrotation=π/8)
# ---------- Panel B: Memory Consumption (Log Scale) ----------
ax2 = Axis(fig[1, 2],
title="Panel B: Max RAM Footprint",
ylabel="Memory (MB) - Log Scale",
yscale=log10,
xticks=(x_pos, unique_datasets), xticklabelrotation=π/8)
# ---------- Panel C: Slice Generation Time (Log Scale) ----------
ax3 = Axis(fig[2, 1:2],
title="Panel C: Slice Generation Time (Mean ± SD)",
ylabel="Time (seconds) - Log Scale",
yscale=log10,
xticks=(x_pos, unique_datasets), xticklabelrotation=π/8)
width = 0.25
offsets = [-width, 0.0, width]
for (idx, lib) in enumerate(libraries)
lib_df = df[df.Library .== lib, :]
if isempty(lib_df) continue end
load_times = Float64[]
load_mems = Float64[]
slice_means = Float64[]
slice_stds = Float64[]
for ds in unique_datasets
row = lib_df[lib_df.Dataset .== ds, :]
if nrow(row) > 0 && row.Status[1] == "Success"
push!(load_times, coalesce(row.LoadTime_s[1], 1e-3))
push!(load_mems, coalesce(row.LoadMem_MB[1], 1e-1))
push!(slice_means, coalesce(row.AvgSliceTime_s[1], 1e-4))
push!(slice_stds, coalesce(row.SliceStd_s[1], 0.0))
else
# Default tiny values for log plot positioning of missing runs
push!(load_times, 1e-3)
push!(load_mems, 1e-1)
push!(slice_means, 1e-4)
push!(slice_stds, 0.0)
end
end
barplot!(ax1, x_pos .+ offsets[idx], load_times, color=colors[idx], width=width, label=lib)
barplot!(ax2, x_pos .+ offsets[idx], load_mems, color=colors[idx], width=width, label=lib)
barplot!(ax3, x_pos .+ offsets[idx], slice_means, color=colors[idx], width=width, label=lib)
errorbars!(ax3, x_pos .+ offsets[idx], slice_means, slice_stds, color=:black, whiskerwidth=10)
end
axislegend(ax1, position=:lt)
axislegend(ax2, position=:lt)
axislegend(ax3, position=:rt)
save(joinpath(RESULTS_DIR, "cross_language_comparison.png"), fig)
println("Comparison dashboard saved to $(joinpath(RESULTS_DIR, "cross_language_comparison.png"))")
end
if abspath(PROGRAM_FILE) == @__FILE__
run_cross_benchmarks()
end
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env Rscript
# test/benchmark_r.R
args <- commandArgs(trailingOnly = TRUE)
if (length(args) < 6) {
stop("Usage: Rscript benchmark_r.R <library> <filepath> <mz> <tol> <num_reps> <output_csv>")
}
target_lib <- tolower(args[1])
filepath <- args[2]
mz_value <- as.numeric(args[3])
mz_tolerance <- as.numeric(args[4])
num_reps <- as.numeric(args[5])
output_csv <- args[6]
get_rss <- function() {
if (file.exists("/proc/self/status")) {
lines <- readLines("/proc/self/status")
vm_rss <- lines[grep("^VmRSS:", lines)]
if (length(vm_rss) > 0) {
rss_kb <- as.numeric(gsub("[^0-9]", "", vm_rss))
return(rss_kb / 1024) # MB
}
}
return(0)
}
# Ensure output directory exists
dir.create(dirname(output_csv), showWarnings = FALSE, recursive = TRUE)
if (target_lib == "maldiquant") {
# ------------------------------------------------------------
# Benchmarking MALDIquant
# ------------------------------------------------------------
message("\n[R] Loading MALDIquant and MALDIquantForeign...")
library(MALDIquant)
library(MALDIquantForeign)
gc()
rss_start <- get_rss()
message(paste("[R] MALDIquant - Loading:", basename(filepath)))
t_load_mq <- system.time({
spectra <- MALDIquantForeign::importImzMl(filepath, centroided = TRUE)
})["elapsed"]
rss_loaded_mq <- get_rss()
mem_load_mq <- max(0, rss_loaded_mq - rss_start)
message(paste("[R] MALDIquant - Generating slices (repetitions:", num_reps, ")..."))
t_slices_mq <- numeric(num_reps)
for (i in 1:num_reps) {
t_slices_mq[i] <- system.time({
slices <- MALDIquant::msiSlices(spectra, center = mz_value, tolerance = mz_tolerance)
})["elapsed"]
}
mean_time_mq <- mean(t_slices_mq)
results <- data.frame(
Library = "MALDIquant",
LoadTime_s = t_load_mq,
LoadMem_MB = mem_load_mq,
AvgSliceTime_s = mean_time_mq
)
write.csv(results, output_csv, row.names = FALSE)
message(paste("[R] MALDIquant results written to", output_csv))
} else if (target_lib == "cardinal") {
# ------------------------------------------------------------
# Benchmarking Cardinal
# ------------------------------------------------------------
message("\n[R] Loading Cardinal...")
library(Cardinal)
gc()
rss_start_card <- get_rss()
message(paste("[R] Cardinal - Loading:", basename(filepath)))
t_load_card <- system.time({
mse <- Cardinal::readMSIData(filepath)
})["elapsed"]
rss_loaded_card <- get_rss()
mem_load_card <- max(0, rss_loaded_card - rss_start_card)
message(paste("[R] Cardinal - Generating slices (repetitions:", num_reps, ")..."))
t_slices_card <- numeric(num_reps)
# Determine if we have MSImagingArrays (processed/unaligned spectra) or MSImagingExperiment
is_arrays <- inherits(mse, "MSImagingArrays")
for (i in 1:num_reps) {
t_slices_card[i] <- system.time({
if (is_arrays) {
# Processed dataset pathway (each pixel has different m/z values)
# Iterate over all spectra in parallel/loop and find target mass
slice_data <- sapply(seq_along(mse), function(idx) {
mzs <- Cardinal::mz(mse)[[idx]]
ints <- Cardinal::intensity(mse)[[idx]]
in_tol <- which(abs(mzs - mz_value) <= mz_tolerance)
if (length(in_tol) > 0) {
max(ints[in_tol])
} else {
0.0
}
})
} else {
# Continuous dataset pathway (shared m/z grid)
feat_idx <- Cardinal::features(mse, mz = mz_value, tolerance = mz_tolerance, units = "mz")
if (length(feat_idx) > 0) {
raw_data <- Cardinal::iData(mse)[feat_idx, , drop = FALSE]
if (length(feat_idx) > 1) {
slice_data <- apply(raw_data, 2, max)
} else {
slice_data <- as.numeric(raw_data)
}
} else {
slice_data <- rep(0, ncol(mse))
}
}
})["elapsed"]
}
mean_time_card <- mean(t_slices_card)
results <- data.frame(
Library = "Cardinal",
LoadTime_s = t_load_card,
LoadMem_MB = mem_load_card,
AvgSliceTime_s = mean_time_card
)
write.csv(results, output_csv, row.names = FALSE)
message(paste("[R] Cardinal results written to", output_csv))
} else {
stop(paste("Unknown library requested:", target_lib))
}
+137 -71
View File
@@ -1,11 +1,10 @@
# test/benchmark_v3.jl
# ===================================================================
# High-Precision Performance Benchmark Suite (v3)
# High-Precision Performance Benchmark Suite (v3) - Cross-Engine
# ===================================================================
# This script integrates the robust statistical sampling of `BenchmarkTools`
# with the visual comparative mechanics against the legacy library.
# It captures the paradigm shift from "Time per slice" to "Pipeline Throughput".
# Compares JuliaMSI (New) vs julia_mzML_imzML (Legacy)
# Integrates formal academic metrics, error bars, and log-scale plots.
# ===================================================================
using Pkg
@@ -17,7 +16,6 @@ using CSV
using CairoMakie
using Statistics
using MSI_src
using julia_mzML_imzML
struct BenchmarkCase
filepath::String
@@ -27,13 +25,14 @@ struct BenchmarkCase
end
const RESULTS_DIR = joinpath(@__DIR__, "results")
const NUM_REPETITIONS = 10
# List to benchmark
const BENCHMARK_CASES = [
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_LA-ESI/180817_NEG_Thaliana_Leaf_bottom_1_0841.imzML", 436.04, 0.1, "Thaliana Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Chilli/ltpmsi-chilli.imzML", 420.0, 0.1, "Chilli Pepper"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_DESI/40TopL,10TopR,30BottomL,20BottomR/40TopL,10TopR,30BottomL,20BottomR-centroid.imzML", 885.5, 0.1, "Colon Cancer Human"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML", 716.053, 0.1, "Mouse Urinary Bladder"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML", 306.1, 0.1, "Leaf"),
#BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Leafs/CE1_Leaf_R3.imzML", 306.1, 0.1, "Leaf"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/Liv2_imzML_TIMSConvert-selected/Liv2.imzML", 796.18, 0.1, "Liver Cut"),
BenchmarkCase("/home/pixel/Documents/Cinvestav_2025/Analisis/salida_Tims/Stomach_DHB.imzML", 804.3, 0.1, "Mouse Stomach 4GB")
]
@@ -48,7 +47,6 @@ end
function flush_memory()
GC.gc(true)
if Sys.islinux()
# Force the OS to reclaim memory from the glibc allocator
ccall(:malloc_trim, Int32, (Int32,), 0)
end
end
@@ -76,18 +74,17 @@ function run_v3_benchmarks()
println("[JuliaMSI - New Engine]")
flush_memory()
# Load Phase (Metadata Only / Memory Mapping)
load_stats_new = @timed OpenMSIData(case.filepath)
msi_data = load_stats_new.value
load_time_new_s = load_stats_new.time
mem_load_new_mb = load_stats_new.bytes / 1024^2
# Slicing Phase (High Precision)
b_slice_new = @benchmark get_mz_slice($msi_data, $(case.mz_value), $(case.mz_tolerance)) samples=10 seconds=5
mean_time_new_s = mean(b_slice_new.times) / 1e9
# Benchmark slice generation and capture variability
b_slice_new = @benchmark get_mz_slice($msi_data, $(case.mz_value), $(case.mz_tolerance)) samples=NUM_REPETITIONS seconds=10
times_new_s = b_slice_new.times ./ 1e9
mean_time_new_s = mean(times_new_s)
std_time_new_s = std(times_new_s)
# Calculate Amortized Throughput (10 slices)
# Includes the 'Loading Wall' penalty
total_time_10_new = load_time_new_s + (10 * mean_time_new_s)
amortized_sps_new = 10.0 / total_time_10_new
@@ -99,65 +96,120 @@ function run_v3_benchmarks()
# ------------------------------------------------------------
println("[julia_mzML_imzML - Legacy]")
load_stats_old = try
@timed LoadImzml(case.filepath)
catch e
@warn "Legacy load failed: $e"
(time=Inf, bytes=Inf, value=nothing)
end
old_data = load_stats_old.value
mem_load_old_mb = load_stats_old.bytes / 1024^2
mem_load_old_mb = NaN
load_time_old_s = Inf
mean_time_old_s = Inf
std_time_old_s = 0.0
amortized_sps_old = 0.0
legacy_status = "Success"
if old_data !== nothing
b_slice_old = try
# Legacy can be extremely slow, constrain it heavily
@benchmark GetSlice($old_data, $(case.mz_value), $(case.mz_tolerance)) samples=3 seconds=10
catch e
@warn "Legacy slice failed: $e"
nothing
end
# 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)
if b_slice_old !== nothing
mean_time_old_s = mean(b_slice_old.times) / 1e9
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
# 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
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()
# ------------------------------------------------------------
# Record
# Derived Metrics Calculation
# ------------------------------------------------------------
# Throughput (Slices per second)
tput_new = 1.0 / mean_time_new_s
tput_old = isfinite(mean_time_old_s) ? (1.0 / mean_time_old_s) : 0.0
# Memory Efficiency (MB RAM / GB File)
gb_file = file_size / 1024.0
mem_eff_new = mem_load_new_mb / gb_file
mem_eff_old = isfinite(mem_load_old_mb) ? (mem_load_old_mb / gb_file) : NaN
# Fold Speedup (Legacy / JuliaMSI)
speedup = isfinite(mean_time_old_s) ? (mean_time_old_s / mean_time_new_s) : NaN
# Load Bandwidth (MB/s)
bandwidth_new = file_size / load_time_new_s
bandwidth_old = isfinite(load_time_old_s) ? (file_size / load_time_old_s) : 0.0
push!(results, (
Dataset = case.name,
FileSize_MB = file_size,
# Legacy Metrics
Legacy_LoadMem_MB = mem_load_old_mb,
Legacy_LoadTime_s = load_stats_old.time,
Legacy_Amortized_SPS_10 = amortized_sps_old,
# New Metrics
New_LoadMem_MB = mem_load_new_mb,
# New Engine (JuliaMSI)
New_LoadTime_s = load_time_new_s,
New_LoadMem_MB = mem_load_new_mb,
New_SliceMean_s = mean_time_new_s,
New_SliceStd_s = std_time_new_s,
New_Throughput_SPS = tput_new,
New_MemEff_MB_GB = mem_eff_new,
New_Bandwidth_MBs = bandwidth_new,
New_Amortized_SPS_10 = amortized_sps_new,
# Competitive Deltas
# 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,
UX_Speedup_Factor = isfinite(amortized_sps_old) ? (amortized_sps_new / amortized_sps_old) : NaN
Legacy_Status = legacy_status
))
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")
@@ -171,45 +223,59 @@ end
function plot_v3_results(df::DataFrame)
if isempty(df) return end
fig = Figure(size=(1800, 1200), fontsize=24)
fig = Figure(size=(1800, 1200), fontsize=22)
x_pos = 1:nrow(df)
labels = df.Dataset
# ---------- Plot 1: The RAM Revolution ----------
# ---------- Panel A: Initial Load Time (Log Scale) ----------
ax1 = Axis(fig[1, 1],
title="Initial RAM Cost (Loading & Mmap)",
ylabel="Memory (MB)",
title="Panel A: Metadata/File Load Time",
ylabel="Time (seconds) - Log Scale",
yscale=log10,
xticks=(x_pos, labels), xticklabelrotation=π/8)
barplot!(ax1, x_pos .- 0.2, df.New_LoadMem_MB, color="#10b981", width=0.4, label="JuliaMSI (Mmap Lazy)")
barplot!(ax1, x_pos .+ 0.2, df.Legacy_LoadMem_MB, color="#ef4444", width=0.4, label="Legacy (Dense Matrix)")
barplot!(ax1, x_pos .- 0.2, df.New_LoadTime_s, color="#10b981", width=0.4, label="JuliaMSI")
# Only plot legacy if it succeeded
legacy_times = [row.Legacy_Status == "Success" ? row.Legacy_LoadTime_s : 1e-3 for row in eachrow(df)]
barplot!(ax1, x_pos .+ 0.2, legacy_times, color="#ef4444", width=0.4, label="Legacy")
axislegend(ax1, position=:lt)
# ---------- Plot 2: Throughput Leap ----------
# ---------- Panel B: Initial RAM Cost (Log Scale) ----------
ax2 = Axis(fig[1, 2],
title="Amortized Throughput (10 Slices - Higher is Better)",
ylabel="Slices / Second (Inc. Load Time)",
title="Panel B: Memory Footprint (RAM)",
ylabel="Memory (MB) - Log Scale",
yscale=log10,
xticks=(x_pos, labels), xticklabelrotation=π/8)
barplot!(ax2, x_pos .- 0.2, df.New_Amortized_SPS_10, color="#10b981", width=0.4, label="JuliaMSI")
barplot!(ax2, x_pos .+ 0.2, df.Legacy_Amortized_SPS_10, color="#ef4444", width=0.4, label="Legacy")
barplot!(ax2, x_pos .- 0.2, df.New_LoadMem_MB, color="#10b981", width=0.4, label="JuliaMSI (Mmap)")
legacy_mems = [row.Legacy_Status == "Success" ? row.Legacy_LoadMem_MB : 1e-1 for row in eachrow(df)]
barplot!(ax2, x_pos .+ 0.2, legacy_mems, color="#ef4444", width=0.4, label="Legacy (Dense)")
axislegend(ax2, position=:lt)
# ---------- Plot 3: The Scaling Wall (File Size vs Throughput) ----------
# ---------- Panel C: Slice Throughput & Error Bars ----------
ax3 = Axis(fig[2, 1:2],
title="Performance Scaling: UX Throughput vs Dataset Size",
xlabel="Dataset File Size (MB)",
ylabel="Amortized Throughput (Slices/sec)")
title="Panel C: Slice Generation Time (Mean ± SD)",
ylabel="Time (seconds) - Log Scale",
yscale=log10,
xticks=(x_pos, labels), xticklabelrotation=π/8)
scatterlines!(ax3, df.FileSize_MB, df.New_Amortized_SPS_10, color="#10b981", markersize=15, linewidth=4, label="JuliaMSI Engine")
scatterlines!(ax3, df.FileSize_MB, df.Legacy_Amortized_SPS_10, color="#ef4444", markersize=15, linewidth=4, label="Legacy Engine")
# Plot JuliaMSI times and error bars
barplot!(ax3, x_pos .- 0.2, df.New_SliceMean_s, color="#10b981", width=0.4, label="JuliaMSI")
errorbars!(ax3, x_pos .- 0.2, df.New_SliceMean_s, df.New_SliceStd_s, color=:black, whiskerwidth=15)
# Plot Legacy times and error bars (where successful)
legacy_means = [row.Legacy_Status == "Success" ? row.Legacy_SliceMean_s : 1e-4 for row in eachrow(df)]
legacy_stds = [row.Legacy_Status == "Success" ? row.Legacy_SliceStd_s : 0.0 for row in eachrow(df)]
barplot!(ax3, x_pos .+ 0.2, legacy_means, color="#ef4444", width=0.4, label="Legacy")
errorbars!(ax3, x_pos .+ 0.2, legacy_means, legacy_stds, color=:black, whiskerwidth=15)
axislegend(ax3, position=:rt)
save(joinpath(RESULTS_DIR, "v3_enterprise_dashboard.png"), fig)
println("\nDashboards saved successfully.")
println("\nDashboards saved successfully to $(joinpath(RESULTS_DIR, "v3_enterprise_dashboard.png"))")
end
# Ensure we process if run as the main script
if abspath(PROGRAM_FILE) == @__FILE__
run_v3_benchmarks()
end
+1 -1
View File
@@ -5,7 +5,7 @@ This document provides instructions on how to set up and run the test suite for
## Local Installation and Setup
### 1. Prerequisites
Make sure you have Julia installed (at least version 1.6). If not, we recommend using `juliaup` for installation.
Make sure you have Julia 1.11 or 1.12 installed. If not, we recommend using `juliaup` for installation.
- **juliaup**: [https://github.com/JuliaLang/juliaup](https://github.com/JuliaLang/juliaup)
- **Official binaries**: [https://julialang.org/downloads/](https://julialang.org/downloads/)
+10 -2
View File
@@ -15,13 +15,21 @@
# ===================================================================
using Printf
using CairoMakie
import Pkg
# --- Load the MSI_src Module ---
# Activate the project environment at the parent directory of this test script
# Activate the project environment before loading any project package.
Pkg.activate(joinpath(@__DIR__, ".."))
using MSI_src
using CairoMakie
using PlotlyBase
using Base.Threads
using MSI_src: ViridisPalette, save_bitmap, quantize_intensity, median_filter, TrIQ,
get_multiple_mz_slices, precompute_analytics, MutableSpectrum
# GUI-only plotting helpers (plot_slice, generate_colorbar_image, ...) live in
# the app layer so `using MSI_src` stays lightweight for headless use.
include(joinpath(@__DIR__, "..", "julia_imzML_visual.jl"))
# ===================================================================
+19 -4
View File
@@ -1,8 +1,5 @@
using Test
# We need to simulate loading the MSI_src module directly
include("../src/MSI_src.jl")
using .MSI_src
using MSI_src
@testset "JuliaMSI Core Systems" begin
@testset "Basic Instantiation" begin
@@ -55,4 +52,22 @@ using .MSI_src
buf2 = get_buffer!(pool, 1024)
@test buf === buf2 # Should return the EXACT same buffer object
end
@testset "Bloom Filter Hashing and Probing" begin
bf = MSI_src.BloomFilter{Int}(1000, 0.01)
inserted = collect(1:1000)
foreach(x -> push!(bf, x), inserted)
# Bloom filters must never produce false negatives.
@test all(x -> x in bf, inserted)
@test all(x -> MSI_src.contains(bf, x), inserted)
@test MSI_src.false_positive_rate(bf) > 0.0
@test MSI_src.fill_ratio(bf) > 0.0
end
@testset "Application Paths" begin
# `PUBLIC_DIR` must be absolute and independent of the caller's cwd.
@test isabspath(MSI_src.PUBLIC_DIR)
@test MSI_src.ensure_public_dir() == MSI_src.PUBLIC_DIR
end
end
+2 -1
View File
@@ -6,7 +6,8 @@ using Test
using Base.Threads
# --- Test Configuration ---
const TEST_FILE = "/home/pixel/Documents/Cinvestav_2025/Analisis/Stomach/Stomach_DHB_uncompressed.imzML"
const TEST_FILE = get(ENV, "JULIA_MSI_TEST_IMZML",
"/home/pixel/Documents/Cinvestav_2025/Analisis/Stomach/Stomach_DHB_uncompressed.imzML")
println("Starting concurrency test with file: $TEST_FILE")
+3 -2
View File
@@ -12,7 +12,7 @@
# ============================================================================
using Pkg
Pkg.activate(".")
Pkg.activate(joinpath(@__DIR__, ".."))
using MSI_src
using SparseArrays
@@ -21,7 +21,8 @@ using SparseArrays
# Configuration
# =============================================================================
const IMZML_PATH = "/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML"
const IMZML_PATH = get(ENV, "JULIA_MSI_TEST_IMZML",
"/home/pixel/Documents/Cinvestav_2025/Analisis/imzML_AP_SMALDI/HR2MSImouseurinarybladderS096.imzML")
function main()
println("=" ^ 60)