Interface ready for preprocessing steps handling. style altered to support modular preprocessing pipeline, finished precalculations and preprocessing code, and its respective testing script, added preprocessingpipeline, a handler for the low level functions of preprocessing to work with the high level MSIData in the genie environment.

This commit is contained in:
Pixelguy14
2025-11-29 21:47:51 -06:00
parent bdd9315796
commit 11c181b3b3
13 changed files with 5039 additions and 988 deletions
+680 -69
View File
@@ -2,7 +2,7 @@
module App
# ==Packages ==
using GenieFramework # Set up Genie development environment.
using GenieFramework
using Pkg
using Libz
using PlotlyBase
@@ -22,7 +22,7 @@ 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!
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
if !@isdefined(increment_image)
include("./julia_imzML_visual.jl")
@@ -72,6 +72,10 @@ end
# == Reactive code ==
# Reactive code to make the UI interactive
@app begin
# == Loading Screen Variables ==
@in is_initializing = true
@in initialization_message = "Initializing..."
# == Reactive variables ==
# reactive variables exist in both the Julia backend and the browser with two-way synchronization
# @out variables can only be modified by the backend
@@ -207,6 +211,139 @@ end
# == Pre Processing Variables ==
@in pre_tab = "stabilization"
## Preprocessing Parameters
@in progressPrep=false
@in stabilization_method="sqrt"
@in smoothing_method="sg"
@in smoothing_window = ""
@in smoothing_order = ""
@in baseline_method="snip"
@in baseline_iterations = ""
@in baseline_window = ""
@in normalization_method="tic"
@in alignment_method="lowess"
@in alignment_span = ""
@in alignment_tolerance = ""
@in alignment_tolerance_unit="mz"
@in alignment_max_shift_ppm = ""
@in alignment_min_matched_peaks = ""
@in peak_picking_method="profile"
@in peak_picking_snr_threshold = ""
@in peak_picking_half_window = ""
@in peak_picking_min_peak_prominence = ""
@in peak_picking_merge_peaks_tolerance = ""
@in peak_picking_min_peak_width_ppm = ""
@in peak_picking_max_peak_width_ppm = ""
@in peak_picking_min_peak_shape_r2 = ""
@in binning_method="adaptive"
@in binning_tolerance = ""
@in binning_tolerance_unit="ppm"
@in binning_frequency_threshold = ""
@in binning_min_peak_per_bin = ""
@in binning_max_bin_width_ppm = ""
@in binning_intensity_weighted_centers=true
@in binning_num_uniform_bins = ""
@in calibration_fit_order = ""
@in calibration_ppm_tolerance = ""
@in peak_selection_min_snr = ""
@in peak_selection_min_fwhm_ppm = ""
@in peak_selection_max_fwhm_ppm = ""
@in peak_selection_min_shape_r2 = ""
@in peak_selection_frequency_threshold = ""
@in peak_selection_correlation_threshold = ""
# == Pipeline Step Order and Mask Route Variables ==
@in pipeline_step_order = [
Dict("name" => "stabilization", "label" => "Stabilization", "enabled" => true),
Dict("name" => "smoothing", "label" => "Smoothing", "enabled" => true),
Dict("name" => "baseline_correction", "label" => "Baseline Correction", "enabled" => true),
Dict("name" => "peak_picking", "label" => "Peak Picking", "enabled" => true),
Dict("name" => "peak_selection", "label" => "Peak Selection", "enabled" => true),
Dict("name" => "calibration", "label" => "Calibration", "enabled" => true),
Dict("name" => "peak_alignment", "label" => "Peak Alignment", "enabled" => true),
Dict("name" => "normalization", "label" => "Normalization", "enabled" => true),
Dict("name" => "peak_binning", "label" => "Peak Binning", "enabled" => true)
]
@in preprocessing_mask_route = ""
@in selected_spectrum_id_for_plot = 1
@in feature_matrix_result = nothing
@in bin_info_result = nothing
@in reference_peaks_list = [
Dict("mz" => 137.0244, "label" => "DHB_fragment"),
Dict("mz" => 155.0349, "label" => "DHB_M+H"),
]
# --- Methods for Reference Peaks List ---
function addReferencePeak()
push!(reference_peaks_list, Dict("mz" => 0.0, "label" => ""))
reference_peaks_list = deepcopy(reference_peaks_list) # Force reactivity
end
function removeReferencePeak(index::Int)
deleteat!(reference_peaks_list, index)
reference_peaks_list = deepcopy(reference_peaks_list) # Force reactivity
end
# Step reordering functions
function moveStepUp(index::Int)
if index > 1
pipeline_step_order = deepcopy(pipeline_step_order)
temp = pipeline_step_order[index]
pipeline_step_order[index] = pipeline_step_order[index-1]
pipeline_step_order[index-1] = temp
pipeline_step_order = pipeline_step_order # Force reactivity
end
end
function moveStepDown(index::Int)
if index < length(pipeline_step_order)
pipeline_step_order = deepcopy(pipeline_step_order)
temp = pipeline_step_order[index]
pipeline_step_order[index] = pipeline_step_order[index+1]
pipeline_step_order[index+1] = temp
pipeline_step_order = pipeline_step_order # Force reactivity
end
end
@in save_feature_matrix_btn = false
# Trigger for running the full pipeline
@in run_full_pipeline = false
@out current_pipeline_step = "" # To indicate which step is currently running in the full pipeline
@in export_params_btn = false
@in import_params_btn = false
@in imported_params_file = nothing
@in suggested_smoothing_window = ""
@in suggested_smoothing_order = ""
@in suggested_baseline_iterations = ""
@in suggested_baseline_window = ""
@in suggested_alignment_span = ""
@in suggested_alignment_tolerance = ""
@in suggested_alignment_max_shift_ppm = ""
@in suggested_alignment_min_matched_peaks = ""
@in suggested_peak_picking_snr_threshold = ""
@in suggested_peak_picking_half_window = ""
@in suggested_peak_picking_min_peak_prominence = ""
@in suggested_peak_picking_merge_peaks_tolerance = ""
@in suggested_peak_picking_min_peak_width_ppm = ""
@in suggested_peak_picking_max_peak_width_ppm = ""
@in suggested_peak_picking_min_peak_shape_r2 = ""
@in suggested_binning_tolerance = ""
@in suggested_binning_frequency_threshold = ""
@in suggested_binning_min_peak_per_bin = ""
@in suggested_binning_max_bin_width_ppm = ""
@in suggested_binning_num_uniform_bins = ""
@in suggested_calibration_fit_order = ""
@in suggested_calibration_ppm_tolerance = ""
@in suggested_peak_selection_min_snr = ""
@in suggested_peak_selection_min_fwhm_ppm = ""
@in suggested_peak_selection_max_fwhm_ppm = ""
@in suggested_peak_selection_min_shape_r2 = ""
@in suggested_peak_selection_frequency_threshold = ""
@in suggested_peak_selection_correlation_threshold = ""
# == Batch Summary Dialog ==
@in showBatchSummary = false
@out batch_summary = ""
@@ -323,11 +460,19 @@ end
# Create conection to frontend
@out plotdata=[traceSpectra]
@out plotlayout=layoutSpectra
@in idSpectrum=0
@in xCoord=0
@in yCoord=0
@out xSpectraMz = Vector{Float64}()
@out ySpectraMz = Vector{Float64}()
# UI plot data for Preprocessing
@out plotdata_before = [traceSpectra]
@out plotlayout_before = layoutSpectra
@out plotdata_after = [traceSpectra]
@out plotlayout_after = layoutSpectra
# Interactive plot reactions
@in data_click=Dict{String,Any}()
#@in data_selected=Dict{String,Any}() # Selected is for areas, this can work for the masks
@@ -413,7 +558,7 @@ end
msg = "Opening file: $(basename(picked_route))..."
try
dataset_name = replace(basename(picked_route), r"(\.(imzML|imzml|mzML|mzml))$"i => "")
dataset_name = replace(basename(picked_route), r"(\.(imzML|imzml|mzML|mzml))$ "i => "")
registry = load_registry(registry_path)
existing_entry = get(registry, dataset_name, nothing)
@@ -469,6 +614,188 @@ end
precompute_analytics(loaded_data)
# Auto-suggest parameters
try
println("Calling main_precalculation to get recommended parameters...")
recommended_params = main_precalculation(loaded_data)
for (step_name, params) in recommended_params
for (param_key, value) in params
# Convert value to appropriate type before assignment
processed_value = if value === nothing
nothing
elseif value isa Tuple
@warn "Skipping invalid parameter suggestion (tuple): $value for $param_key"
"" # Set to empty string for safety
elseif value isa Number
value
else
string(value)
end
if processed_value !== nothing
if step_name == :Smoothing
if param_key == :window
suggested_smoothing_window = string(processed_value)
smoothing_window = string(processed_value)
println(" suggested_smoothing_window set to $(suggested_smoothing_window)")
elseif param_key == :order
suggested_smoothing_order = string(processed_value)
smoothing_order = string(processed_value)
println(" suggested_smoothing_order set to $(suggested_smoothing_order)")
end
elseif step_name == :BaselineCorrection
if param_key == :iterations
suggested_baseline_iterations = string(processed_value)
baseline_iterations = string(processed_value)
println(" suggested_baseline_iterations set to $(suggested_baseline_iterations)")
elseif param_key == :window
suggested_baseline_window = string(processed_value)
baseline_window = string(processed_value)
println(" suggested_baseline_window set to $(suggested_baseline_window)")
end
elseif step_name == :PeakAlignment
if param_key == :span
suggested_alignment_span = string(processed_value)
alignment_span = string(processed_value)
println(" suggested_alignment_span set to $(suggested_alignment_span)")
elseif param_key == :tolerance
suggested_alignment_tolerance = string(processed_value)
alignment_tolerance = string(processed_value)
println(" suggested_alignment_tolerance set to $(suggested_alignment_tolerance)")
elseif param_key == :max_shift_ppm
suggested_alignment_max_shift_ppm = string(processed_value)
alignment_max_shift_ppm = string(processed_value)
println(" suggested_alignment_max_shift_ppm set to $(suggested_alignment_max_shift_ppm)")
elseif param_key == :min_matched_peaks
suggested_alignment_min_matched_peaks = string(processed_value)
alignment_min_matched_peaks = string(processed_value)
println(" suggested_alignment_min_matched_peaks set to $(suggested_alignment_min_matched_peaks)")
end
elseif step_name == :Calibration
if param_key == :fit_order
suggested_calibration_fit_order = string(processed_value)
calibration_fit_order = string(processed_value)
println(" suggested_calibration_fit_order set to $(suggested_calibration_fit_order)")
elseif param_key == :ppm_tolerance
suggested_calibration_ppm_tolerance = string(processed_value)
calibration_ppm_tolerance = string(processed_value)
println(" suggested_calibration_ppm_tolerance set to $(suggested_calibration_ppm_tolerance)")
end
elseif step_name == :PeakPicking
if param_key == :snr_threshold
suggested_peak_picking_snr_threshold = string(processed_value)
peak_picking_snr_threshold = string(processed_value)
println(" suggested_peak_picking_snr_threshold set to $(suggested_peak_picking_snr_threshold)")
elseif param_key == :half_window
suggested_peak_picking_half_window = string(processed_value)
peak_picking_half_window = string(processed_value)
println(" suggested_peak_picking_half_window set to $(suggested_peak_picking_half_window)")
elseif param_key == :min_peak_prominence
suggested_peak_picking_min_peak_prominence = string(processed_value)
peak_picking_min_peak_prominence = string(processed_value)
println(" suggested_peak_picking_min_peak_prominence set to $(suggested_peak_picking_min_peak_prominence)")
elseif param_key == :merge_peaks_tolerance
suggested_peak_picking_merge_peaks_tolerance = string(processed_value)
peak_picking_merge_peaks_tolerance = string(processed_value)
println(" suggested_peak_picking_merge_peaks_tolerance set to $(suggested_peak_picking_merge_peaks_tolerance)")
elseif param_key == :min_peak_width_ppm
suggested_peak_picking_min_peak_width_ppm = string(processed_value)
peak_picking_min_peak_width_ppm = string(processed_value)
println(" suggested_peak_picking_min_peak_width_ppm set to $(suggested_peak_picking_min_peak_width_ppm)")
elseif param_key == :max_peak_width_ppm
suggested_peak_picking_max_peak_width_ppm = string(processed_value)
peak_picking_max_peak_width_ppm = string(processed_value)
println(" suggested_peak_picking_max_peak_width_ppm set to $(suggested_peak_picking_max_peak_width_ppm)")
elseif param_key == :min_peak_shape_r2
suggested_peak_picking_min_peak_shape_r2 = string(processed_value)
peak_picking_min_peak_shape_r2 = string(processed_value)
println(" suggested_peak_picking_min_peak_shape_r2 set to $(suggested_peak_picking_min_peak_shape_r2)")
end
elseif step_name == :PeakSelection
if param_key == :min_snr
suggested_peak_selection_min_snr = string(processed_value)
peak_selection_min_snr = string(processed_value)
println(" suggested_peak_selection_min_snr set to $(suggested_peak_selection_min_snr)")
elseif param_key == :min_fwhm_ppm
suggested_peak_selection_min_fwhm_ppm = string(processed_value)
peak_selection_min_fwhm_ppm = string(processed_value)
println(" suggested_peak_selection_min_fwhm_ppm set to $(suggested_peak_selection_min_fwhm_ppm)")
elseif param_key == :max_fwhm_ppm
suggested_peak_selection_max_fwhm_ppm = string(processed_value)
peak_selection_max_fwhm_ppm = string(processed_value)
println(" suggested_peak_selection_max_fwhm_ppm set to $(suggested_peak_selection_max_fwhm_ppm)")
elseif param_key == :min_shape_r2
suggested_peak_selection_min_shape_r2 = string(processed_value)
peak_selection_min_shape_r2 = string(processed_value)
println(" suggested_peak_selection_min_shape_r2 set to $(suggested_peak_selection_min_shape_r2)")
elseif param_key == :frequency_threshold
suggested_peak_selection_frequency_threshold = string(processed_value)
peak_selection_frequency_threshold = string(processed_value)
println(" suggested_peak_selection_frequency_threshold set to $(suggested_peak_selection_frequency_threshold)")
elseif param_key == :correlation_threshold
suggested_peak_selection_correlation_threshold = string(processed_value)
peak_selection_correlation_threshold = string(processed_value)
println(" suggested_peak_selection_correlation_threshold set to $(suggested_peak_selection_correlation_threshold)")
end
elseif step_name == :PeakBinning
if param_key == :tolerance
suggested_binning_tolerance = string(processed_value)
binning_tolerance = string(processed_value)
println(" suggested_binning_tolerance set to $(suggested_binning_tolerance)")
elseif param_key == :frequency_threshold
suggested_binning_frequency_threshold = string(processed_value)
binning_frequency_threshold = string(processed_value)
println(" suggested_binning_frequency_threshold set to $(suggested_binning_frequency_threshold)")
elseif param_key == :min_peak_per_bin
suggested_binning_min_peak_per_bin = string(processed_value)
binning_min_peak_per_bin = string(processed_value)
println(" suggested_binning_min_peak_per_bin set to $(suggested_binning_min_peak_per_bin)")
elseif param_key == :max_bin_width_ppm
suggested_binning_max_bin_width_ppm = string(processed_value)
binning_max_bin_width_ppm = string(processed_value)
println(" suggested_binning_max_bin_width_ppm set to $(suggested_binning_max_bin_width_ppm)")
elseif param_key == :num_uniform_bins
suggested_binning_num_uniform_bins = string(processed_value)
binning_num_uniform_bins = string(processed_value)
println(" suggested_binning_num_uniform_bins set to $(suggested_binning_num_uniform_bins)")
end
end
end
end
end
# Also set method types for steps
if haskey(recommended_params, :Smoothing) && haskey(recommended_params[:Smoothing], :method)
smoothing_method = string(recommended_params[:Smoothing][:method])
end
if haskey(recommended_params, :BaselineCorrection) && haskey(recommended_params[:BaselineCorrection], :method)
baseline_method = string(recommended_params[:BaselineCorrection][:method])
end
if haskey(recommended_params, :Normalization) && haskey(recommended_params[:Normalization], :method)
normalization_method = string(recommended_params[:Normalization][:method])
end
if haskey(recommended_params, :PeakAlignment) && haskey(recommended_params[:PeakAlignment], :method)
alignment_method = string(recommended_params[:PeakAlignment][:method])
end
if haskey(recommended_params, :PeakPicking) && haskey(recommended_params[:PeakPicking], :method)
peak_picking_method = string(recommended_params[:PeakPicking][:method])
end
if haskey(recommended_params, :PeakBinning) && haskey(recommended_params[:PeakBinning], :method)
binning_method = string(recommended_params[:PeakBinning][:method])
end
if haskey(recommended_params, :PeakAlignment) && haskey(recommended_params[:PeakAlignment], :tolerance_unit)
alignment_tolerance_unit = string(recommended_params[:PeakAlignment][:tolerance_unit])
end
if haskey(recommended_params, :PeakBinning) && haskey(recommended_params[:PeakBinning], :tolerance_unit)
binning_tolerance_unit = string(recommended_params[:PeakBinning][:tolerance_unit])
end
msg = "File loaded and parameters suggested."
catch e
@warn "Could not suggest parameters. Using defaults. Error: $e"
end
metadata_columns = [
Dict("name" => "parameter", "label" => "Parameter", "field" => "parameter", "align" => "left"),
Dict("name" => "value", "label" => "Value", "field" => "value", "align" => "left"),
@@ -511,15 +838,271 @@ end
btnMetadataDisable = true
@error "File loading failed" exception=(e, catch_backtrace())
finally
GC.gc()
GC.gc() # Trigger garbage collection
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
ccall(:malloc_trim, Int32, (Int32,), 0) # Ensure Julia returns the freed memory to OS
end
progress = false
progressSpectraPlot = false
end
end
@onbutton export_params_btn begin
params_to_export = Dict(
"pipeline_step_order" => pipeline_step_order,
"enable_standards" => enable_standards, # Export global flag
"stabilization_method" => stabilization_method,
"smoothing_method" => smoothing_method,
"smoothing_window" => smoothing_window,
"smoothing_order" => smoothing_order,
"baseline_method" => baseline_method,
"baseline_iterations" => baseline_iterations,
"baseline_window" => baseline_window,
"normalization_method" => normalization_method,
"alignment_method" => alignment_method,
"alignment_span" => alignment_span,
"alignment_tolerance" => alignment_tolerance,
"alignment_tolerance_unit" => alignment_tolerance_unit,
"alignment_max_shift_ppm" => alignment_max_shift_ppm,
"alignment_min_matched_peaks" => alignment_min_matched_peaks,
"peak_picking_method" => peak_picking_method,
"peak_picking_snr_threshold" => peak_picking_snr_threshold,
"peak_picking_half_window" => peak_picking_half_window,
"peak_picking_min_peak_prominence" => peak_picking_min_peak_prominence,
"peak_picking_merge_peaks_tolerance" => peak_picking_merge_peaks_tolerance,
"peak_picking_min_peak_width_ppm" => peak_picking_min_peak_width_ppm,
"peak_picking_max_peak_width_ppm" => peak_picking_max_peak_width_ppm,
"peak_picking_min_peak_shape_r2" => peak_picking_min_peak_shape_r2,
"binning_method" => binning_method,
"binning_tolerance" => binning_tolerance,
"binning_tolerance_unit" => binning_tolerance_unit,
"binning_frequency_threshold" => binning_frequency_threshold,
"binning_min_peak_per_bin" => binning_min_peak_per_bin,
"binning_max_bin_width_ppm" => binning_max_bin_width_ppm,
"binning_intensity_weighted_centers" => binning_intensity_weighted_centers,
"binning_num_uniform_bins" => binning_num_uniform_bins,
"calibration_fit_order" => calibration_fit_order,
"calibration_ppm_tolerance" => calibration_ppm_tolerance,
"peak_selection_min_snr" => peak_selection_min_snr,
"peak_selection_min_fwhm_ppm" => peak_selection_min_fwhm_ppm,
"peak_selection_max_fwhm_ppm" => peak_selection_max_fwhm_ppm,
"peak_selection_min_shape_r2" => peak_selection_min_shape_r2,
"peak_selection_frequency_threshold" => peak_selection_frequency_threshold,
"peak_selection_correlation_threshold" => peak_selection_correlation_threshold,
"reference_peaks_list" => reference_peaks_list
)
json_string = JSON.json(params_to_export)
js_script = """
var element = document.createElement('a');
element.setAttribute('href', 'data:text/json;charset=utf-8,' + encodeURIComponent(`$json_string`));
element.setAttribute('download', 'preprocessing_params.json');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
"""
run_js(js_script)
msg = "Parameters exported."
end
@onchange import_params_btn begin
if import_params_btn
try
json_string = String(imported_params_file.data)
params = JSON.parse(json_string)
for (key, value) in params
if key == "reference_peaks_list"
reference_peaks_list = value
elseif key == "pipeline_step_order"
pipeline_step_order = value
elseif key == "enable_standards" # Import global flag
enable_standards = value
else
# Use getfield and setproperty! to update reactive variables by name
if hasfield(typeof(@__MODULE__), Symbol(key))
getfield(@__MODULE__, Symbol(key))[] = value
end
end
end
msg = "Parameters imported successfully."
catch e
msg = "Failed to import parameters: $e"
warning_msg = true
finally
import_params_btn = false # Reset button state
end
end
end
@onbutton run_full_pipeline begin
progressPrep = true
current_pipeline_step = "Initializing..."
try
# 1. Data Preparation
if isempty(selected_folder_main)
msg = "No dataset selected. Please process a file first."
warning_msg = true
return
end
registry = load_registry(registry_path)
entry = registry[selected_folder_main]
target_path = entry["source_path"]
if msi_data === nothing || full_route != target_path
if msi_data !== nothing
close(msi_data)
end
full_route = target_path
msi_data = OpenMSIData(target_path)
end
# Apply mask if enabled
spectrum_indices_to_process = collect(1:length(msi_data.spectra_metadata))
if maskEnabled && !isempty(preprocessing_mask_route) && isfile(preprocessing_mask_route)
current_pipeline_step = "Loading mask..."
mask_matrix = load_and_prepare_mask(preprocessing_mask_route, msi_data.image_dims)
masked_indices_set = get_masked_spectrum_indices(msi_data, mask_matrix)
spectrum_indices_to_process = collect(masked_indices_set)
end
# Initialize spectra data structure
current_pipeline_step = "Loading spectra..."
current_spectra = Vector{MutableSpectrum}(undef, length(spectrum_indices_to_process))
Threads. @threads for i in 1:length(spectrum_indices_to_process)
original_idx = spectrum_indices_to_process[i]
mz, intensity = GetSpectrum(msi_data, original_idx)
current_spectra[i] = MutableSpectrum(original_idx, mz, intensity, [])
end
# 2. Parameter Assembly
current_pipeline_step = "Configuring parameters..."
final_params = Dict(
:Stabilization => Dict(:method => Symbol(stabilization_method)),
:Smoothing => Dict(
:method => Symbol(smoothing_method),
:window => parse(Int, smoothing_window),
:order => parse(Int, smoothing_order)
),
:BaselineCorrection => Dict(
:method => Symbol(baseline_method),
:iterations => parse(Int, baseline_iterations),
:window => parse(Int, baseline_window)
),
:Normalization => Dict(:method => Symbol(normalization_method)),
:PeakPicking => Dict(
:method => Symbol(peak_picking_method),
:snr_threshold => parse(Float64, peak_picking_snr_threshold),
:half_window => parse(Int, peak_picking_half_window),
:min_peak_prominence => parse(Float64, peak_picking_min_peak_prominence),
:merge_peaks_tolerance => parse(Float64, peak_picking_merge_peaks_tolerance)
),
:PeakSelection => Dict(
:min_snr => parse(Float64, peak_selection_min_snr),
:min_fwhm_ppm => parse(Float64, peak_selection_min_fwhm_ppm),
:max_fwhm_ppm => parse(Float64, peak_selection_max_fwhm_ppm),
:min_shape_r2 => parse(Float64, peak_selection_min_shape_r2)
),
:Calibration => Dict(
:method => :internal_standards,
:ppm_tolerance => parse(Float64, calibration_ppm_tolerance),
:fit_order => parse(Int, calibration_fit_order)
),
:PeakAlignment => Dict(
:method => Symbol(alignment_method),
:tolerance => parse(Float64, alignment_tolerance),
:tolerance_unit => Symbol(alignment_tolerance_unit)
),
:PeakBinning => Dict(
:method => Symbol(binning_method),
:tolerance => parse(Float64, binning_tolerance),
:tolerance_unit => Symbol(binning_tolerance_unit),
:min_peak_per_bin => parse(Int, binning_min_peak_per_bin)
)
)
# Build pipeline steps from enabled steps in order
pipeline_stp = [step["name"] for step in pipeline_step_order if step["enabled"]]
# Convert reference peaks
ref_peaks = Dict(p["mz"] => p["label"] for p in reference_peaks_list)
# 3. Execute Pipeline
current_pipeline_step = "Running preprocessing pipeline..."
feature_matrix_result, bin_info_result = execute_full_preprocessing(
current_spectra,
final_params,
pipeline_stp,
ref_peaks,
maskEnabled ? preprocessing_mask_route : nothing
) do step
current_pipeline_step = "Processing: $step"
end
# 4. Update Results Display
current_pipeline_step = "Updating results..."
# Find the spectrum to display in "after" plot
display_spectrum_idx = findfirst(s -> s.id == selected_spectrum_id_for_plot, current_spectra)
if display_spectrum_idx !== nothing
processed_spectrum = current_spectra[display_spectrum_idx]
# Create "after" plot data
after_trace = PlotlyBase.scatter(
x=processed_spectrum.mz,
y=processed_spectrum.intensity,
mode="lines",
name="Processed Spectrum"
)
traces_after = [after_trace]
# Add peaks if they exist
if !isempty(processed_spectrum.peaks)
peak_mzs = [p.mz for p in processed_spectrum.peaks]
peak_intensities = [p.intensity for p in processed_spectrum.peaks] # Fixed: Should be peak.intensity
peak_trace = PlotlyBase.scatter(
x=peak_mzs,
y=peak_intensities,
mode="markers",
name="Picked Peaks",
marker=attr(color="red", size=8)
)
push!(traces_after, peak_trace)
end
plotdata_after = traces_after
plotlayout_after = PlotlyBase.Layout(
title="After Preprocessing (Spectrum $selected_spectrum_id_for_plot)",
xaxis_title="m/z",
yaxis_title="Intensity"
)
end
# Save feature matrix if binning was performed
if feature_matrix_result !== nothing
output_dir = joinpath("public", 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."
else
msg = "Pipeline completed successfully."
end
catch e
msg = "Error during pipeline execution: $e"
warning_msg = true
@error "Pipeline failed" exception=(e, catch_backtrace())
finally
progressPrep = false
current_pipeline_step = ""
GC.gc()
end
end
# This new handler correctly adds the file from full_route to the batch list.
@onbutton btnAddBatch begin
if isempty(full_route) || full_route == "unknown (manually added)"
@@ -704,7 +1287,7 @@ end
files_without_mask = 0
for (file_idx, file_path) in enumerate(current_selected_files)
progress_message = "Processing file $file_idx/$num_files: $(basename(file_path))"
progress_message = "Processing file $(file_idx)/$(num_files): $(basename(file_path))"
overall_progress = current_step / total_steps
all_params = (
@@ -759,7 +1342,7 @@ end
Errors by category:
• Load failures: $(length(errors["load_errors"]))
• Slice generation: $(length(errors["slice_errors"]))
• Slice generation: $(length(errors["slice_errors"]))
• I/O issues: $(length(errors["io_errors"]))
Detailed errors:
@@ -832,9 +1415,9 @@ end
SpectraEnabled = true
overall_progress = 0.0
println("Done")
GC.gc()
GC.gc() # Trigger garbage collection
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
ccall(:malloc_trim, Int32, (Int32,), 0) # Ensure Julia returns the freed memory to OS
end
end
end
@@ -891,6 +1474,8 @@ end
end
plotdata, plotlayout, xSpectraMz, ySpectraMz = meanSpectrumPlot(msi_data, selected_folder_main, mask_path=mask_path_for_plot)
plotdata_before = plotdata
plotlayout_before = plotlayout
selectedTab = "tab2"
fTime = time()
eTime = round(fTime - sTime, digits=3)
@@ -905,9 +1490,9 @@ end
btnPlotDisable = false
btnSpectraDisable = false
btnStartDisable = false
GC.gc()
GC.gc() # Trigger garbage collection
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
ccall(:malloc_trim, Int32, (Int32,), 0) # Ensure Julia returns the freed memory to OS
end
end
end
@@ -922,37 +1507,37 @@ end
progressSpectraPlot = true
btnPlotDisable = true
btnStartDisable = true
msg = "Loading total spectrum plot for $(selected_folder_main)..."
msg = "Loading total spectrum plot for $(selected_folder_main)..."
try
sTime = time()
registry = load_registry(registry_path)
entry = registry[selected_folder_main]
target_path = entry["source_path"]
if target_path == "unknown (manually added)"
msg = "Dataset selected contained no route."
warning_msg = true
return
end
if msi_data === nothing || full_route != target_path
if msi_data !== nothing
close(msi_data)
end
msg = "Reloading $(basename(target_path)) for analysis..."
full_route = target_path
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))
else
precompute_analytics(msi_data)
end
end
try
sTime = time()
registry = load_registry(registry_path)
entry = registry[selected_folder_main]
target_path = entry["source_path"]
if target_path == "unknown (manually added)"
msg = "Dataset selected contained no route."
warning_msg = true
return
end
if msi_data === nothing || full_route != target_path
if msi_data !== nothing
close(msi_data)
end
msg = "Reloading $(basename(target_path)) for analysis..."
full_route = target_path
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))
else
precompute_analytics(msi_data)
end
end
local mask_path_for_plot::Union{String, Nothing} = nothing
if maskEnabled && get(entry, "has_mask", false)
mask_path_for_plot = get(entry, "mask_path", "")
@@ -963,6 +1548,8 @@ end
end
plotdata, plotlayout, xSpectraMz, ySpectraMz = sumSpectrumPlot(msi_data, selected_folder_main, mask_path=mask_path_for_plot)
plotdata_before = plotdata
plotlayout_before = plotlayout
selectedTab = "tab2"
fTime = time()
eTime = round(fTime - sTime, digits=3)
@@ -977,9 +1564,9 @@ end
btnPlotDisable = false
btnSpectraDisable = false
btnStartDisable = false
GC.gc()
GC.gc() # Trigger garbage collection
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
ccall(:malloc_trim, Int32, (Int32,), 0) # Ensure Julia returns the freed memory to OS
end
end
end
@@ -1003,7 +1590,7 @@ end
# Add error handling for registry access
if !haskey(registry, selected_folder_main)
msg = "Dataset '$selected_folder_main' not found in registry."
msg = "Dataset '$(selected_folder_main)' not found in registry."
warning_msg = true
return
end
@@ -1047,6 +1634,8 @@ end
# Convert to positive coordinates for processing
y_positive = yCoord < 0 ? abs(yCoord) : yCoord
plotdata, plotlayout, xSpectraMz, ySpectraMz = xySpectrumPlot(msi_data, xCoord, y_positive, imgWidth, imgHeight, selected_folder_main, mask_path=mask_path_for_plot)
plotdata_before = plotdata
plotlayout_before = plotlayout
# Update coordinates based on actual plot title
# Extract title text from the Dict safely
@@ -1092,9 +1681,9 @@ end
btnPlotDisable = false
btnSpectraDisable = false
btnStartDisable = false
GC.gc()
GC.gc() # Trigger garbage collection
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
ccall(:malloc_trim, Int32, (Int32,), 0) # Ensure Julia returns the freed memory to OS
end
end
end
@@ -1375,9 +1964,9 @@ end
end
msi_data = nothing
log_memory_usage("Folder Changed (msi_data cleared)", msi_data)
GC.gc()
GC.gc() # Trigger garbage collection
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
ccall(:malloc_trim, Int32, (Int32,), 0) # Ensure Julia returns the freed memory to OS
end
if !isempty(selected_folder_main)
@@ -1623,9 +2212,9 @@ end
btnStartDisable=false
btnSpectraDisable=false
SpectraEnabled=true
GC.gc()
GC.gc() # Trigger garbage collection
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
ccall(:malloc_trim, Int32, (Int32,), 0) # Ensure Julia returns the freed memory to OS
end
end
end
@@ -1650,7 +2239,7 @@ end
try
# --- Get Mask Path ---
local mask_path_for_plot::Union{String, Nothing} = nothing
if maskEnabled[] && !isempty(selected_folder_main)
if maskEnabled && !isempty(selected_folder_main)
registry = load_registry(registry_path)
entry = get(registry, selected_folder_main, nothing)
if entry !== nothing && get(entry, "has_mask", false)
@@ -1686,9 +2275,9 @@ end
btnStartDisable=false
btnSpectraDisable=false
SpectraEnabled=true
GC.gc()
GC.gc() # Trigger garbage collection
if Sys.islinux()
ccall(:malloc_trim, Int32, (Int32,), 0)
ccall(:malloc_trim, Int32, (Int32,), 0) # Ensure Julia returns the freed memory to OS
end
end
end
@@ -1789,16 +2378,35 @@ end
# To include a visualization in the spectrum plot indicating where is the selected mass
@onchange Nmass begin
if !isempty(xSpectraMz)
# Main spectrum trace
traceSpectra = PlotlyBase.stem(
x=xSpectraMz,
y=ySpectraMz,
marker=attr(size=1, color="blue", opacity=0.5),
name="Spectrum",
hoverinfo="x",
hovertemplate="<b>m/z</b>: %{x:.4f}<extra></extra>",
showlegend=false
)
df = msi_data.spectrum_stats_df
profile_count = 0
if df !== nothing && hasproperty(df, :Mode)
profile_count = count(==(MSI_src.PROFILE), df.Mode)
end
if profile_count > 0
# Main spectrum trace
traceSpectra = PlotlyBase.scatter(
x=xSpectraMz,
y=ySpectraMz,
marker=attr(size=1, color="blue", opacity=0.5),
name="Spectrum",
hoverinfo="x",
hovertemplate="<b>m/z</b>: %{x:.4f}<extra></extra>",
showlegend=false
)
else
# Main spectrum trace
traceSpectra = PlotlyBase.stem(
x=xSpectraMz,
y=ySpectraMz,
marker=attr(size=1, color="blue", opacity=0.5),
name="Spectrum",
hoverinfo="x",
hovertemplate="<b>m/z</b>: %{x:.4f}<extra></extra>",
showlegend=false
)
end
# Parse all valid masses from the comma-separated string
mass_strs = split(Nmass, ',', keepempty=false)
@@ -1955,9 +2563,11 @@ end
@onchange isready @time begin
if isready && !registry_init_done
initialization_message = "Pre-compiling functions at startup..."
warmup_init()
initialization_message = "Pre-compilation finished."
try
println("Synchronizing registry with filesystem on backend init...")
initialization_message = "Synchronizing registry with filesystem on backend init..."
reg_path = abspath(joinpath(@__DIR__, "public", "registry.json"))
registry = isfile(reg_path) ? load_registry(reg_path) : Dict{String, Any}()
@@ -1986,10 +2596,8 @@ end
end
if !isempty(new_folders) || !isempty(removed_folders)
println("Registry changed, saving...")
open(reg_path, "w") do f
JSON.print(f, registry, 4)
end
initialization_message = "Registry changed, saving..."
save_registry(reg_path, registry)
end
all_folders = sort(collect(keys(registry)), lt=natural)
@@ -2006,8 +2614,11 @@ end
selected_files = String[]
finally
registry_init_done = true
is_initializing = false # Hide loading screen when initialization is complete
end
end
is_initializing = false # Hide loading screen when initialization is complete (current code is hidden due to incompatibility)
initialization_message = "Done."
log_memory_usage("App Ready", msi_data)
end
@@ -2019,4 +2630,4 @@ end
# == Pages ==
# Register a new route and the page that will be loaded on access
@page("/", "app.jl.html")
end
end