-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLASLS.m
More file actions
1221 lines (1053 loc) · 49.2 KB
/
Copy pathLASLS.m
File metadata and controls
1221 lines (1053 loc) · 49.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef LASLS < matlab.apps.AppBase
% LASLS - HTML-based GUI for Local Asymmetric Least Squares (LAsLS)
% baseline correction.
%
% Interactive graphical interface for LAsLS baseline correction with
% per-interval asymmetry and smoothing parameters, signal-by-signal
% navigation, per-signal parameter mode, peak detection, interactive
% interval drawing, and first-derivative penalty (mu).
%
% Architecture: MATLAB AppBase + uihtml (HTML/JS frontend, MATLAB backend)
%
% REFERENCES:
% Eilers, Paul H.C., and Hans F.M. Boelens.
% "Baseline correction with asymmetric least squares smoothing."
% Leiden University Medical Centre Report 1.1 (2005): 5.
%
% Authors: Adrián Gómez-Sánchez, Berta Torres-Cobos, Rodrigo Rocha de Oliveira
% Date Created: 2024-12-16
% License: MIT
% Repository: https://github.com/LovelaceSquare/lovelacesquare
% Version: 1.4
properties (Access = public)
UIFigure matlab.ui.Figure
HTMLComponent matlab.ui.control.HTML
end
properties (Access = private)
Corrector % LASLSCorrector instance
Validator % DataValidator instance
OriginalData double = [] % Raw spectra matrix (nRows x nCols)
CorrectedData double = [] % Corrected spectra
BaselineData double = [] % Estimated baselines
WeightsData double = [] % IRLS weights
Wavelength double = [] % Channel axis (1:nCols)
DataLoaded logical = false
IsClosed logical = false
UIUpdateCounter double = 0
LoadedVarName char = ''
end
% ====================================================================
% CONSTRUCTOR / DESTRUCTOR
% ====================================================================
methods (Access = public)
function app = LASLS()
createComponents(app);
initializeBusinessLogic(app);
registerApp(app, app.UIFigure);
runStartupFcn(app, @startupFcn);
if nargout == 0
clear app
end
end
function delete(app)
app.IsClosed = true;
if isvalid(app.UIFigure)
delete(app.UIFigure);
end
end
end
% ====================================================================
% COMPONENT CREATION
% ====================================================================
methods (Access = private)
function createComponents(app)
app.UIFigure = uifigure('Visible', 'off');
app.UIFigure.Position = [100 100 1400 900];
app.UIFigure.Name = 'LASLS Baseline Correction';
app.UIFigure.Color = [0.91 0.92 0.93];
app.UIFigure.AutoResizeChildren = 'off';
app.UIFigure.CloseRequestFcn = createCallbackFcn(app, @UIFigureCloseRequest, true);
app.UIFigure.SizeChangedFcn = createCallbackFcn(app, @UIFigureSizeChanged, true);
modulePath = fileparts(mfilename('fullpath'));
htmlPath = fullfile(modulePath, 'ui', 'lasls_baseline_correction_ui.html');
app.HTMLComponent = uihtml(app.UIFigure);
app.HTMLComponent.Position = [1 1 1400 900];
app.HTMLComponent.HTMLSource = htmlPath;
app.HTMLComponent.DataChangedFcn = createCallbackFcn(app, @HTMLDataChanged, true);
app.UIFigure.Visible = 'on';
app.UIFigure.WindowState = 'maximized';
end
function initializeBusinessLogic(app)
modulePath = fileparts(mfilename('fullpath'));
blPath = fullfile(modulePath, 'business_logic');
addpath(blPath);
app.Corrector = LASLSCorrector();
app.Validator = DataValidator();
end
function startupFcn(app)
movegui(app.UIFigure, 'center');
pause(0.3);
sendResponse(app, 'statusUpdate', struct('type', 'idle', 'message', 'Ready'));
end
end
% ====================================================================
% UI CALLBACKS
% ====================================================================
methods (Access = private)
function UIFigureCloseRequest(app, ~)
app.IsClosed = true;
delete(app);
end
function UIFigureSizeChanged(app, ~)
pos = app.UIFigure.Position;
app.HTMLComponent.Position = [1 1 pos(3) pos(4)];
end
% ----------------------------------------------------------------
% HTML DataChanged dispatcher
% IMPORTANT: Each handler must send exactly ONE sendResponse call.
% Two rapid .Data writes cause the first to be lost (race condition).
% ----------------------------------------------------------------
function HTMLDataChanged(app, ~)
try
data = app.HTMLComponent.Data;
if isempty(data) || ~isstruct(data), return; end
if isfield(data, 'response'), return; end
if ~isfield(data, 'action') || isempty(data.action), return; end
action = data.action;
if ~ischar(action)
try, action = char(action); catch, return; end
end
switch action
case 'loadData', handleLoadData(app);
case 'loadVariable', handleLoadVariable(app, data);
case 'getSpectrum', handleGetSpectrum(app, data);
case 'previewBaseline', handlePreviewBaseline(app, data);
case 'apply', handleApply(app, data);
case 'prepareExport', handlePrepareExport(app);
case 'checkExportNames', handleCheckExportNames(app, data);
case 'doExport', handleDoExport(app, data);
case 'prepareImport', handlePrepareImport(app);
case 'doImport', handleDoImport(app, data);
case 'exportIntervals', handleExportIntervals(app, data);
case 'loadIntervals', handleLoadIntervals(app);
case 'loadIntervalTable', handleLoadIntervalTable(app, data);
case 'createDemoData', handleCreateDemoData(app, data);
otherwise
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Unknown action: ' action]));
end
catch ME
disp('=== LASLS Action Error ===');
disp(ME.getReport());
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Error: ' ME.message]));
end
end
end
% ====================================================================
% ACTION HANDLERS
% RULE: Each handler sends exactly ONE sendResponse with ALL data
% embedded (including status). Never two consecutive sendResponse calls.
% ====================================================================
methods (Access = private)
% ---- Load data from workspace (send variable list to JS) -----------
function handleLoadData(app)
try
vars = evalin('base', 'whos');
varList = {};
vectorList = {};
for i = 1:length(vars)
if (strcmp(vars(i).class, 'double') || ...
strcmp(vars(i).class, 'single')) && ...
length(vars(i).size) == 2 && all(vars(i).size > 0)
nR = vars(i).size(1);
nC = vars(i).size(2);
if nR == 1 || nC == 1
% 1D vector — candidate for x-axis
vecLen = max(nR, nC);
vectorList{end+1} = struct(...
'name', vars(i).name, ...
'length', vecLen); %#ok<AGROW>
if vecLen >= 4
if nR == 1
displaySize = sprintf('1x%d', vecLen);
else
displaySize = sprintf('%dx1 → 1x%d', vecLen, vecLen);
end
varList{end+1} = struct(...
'name', vars(i).name, ...
'size', displaySize, ...
'rows', 1, ...
'cols', vecLen); %#ok<AGROW>
end
elseif min(nR, nC) >= 2
% 2D matrix — candidate for data
varList{end+1} = struct(...
'name', vars(i).name, ...
'size', sprintf('%dx%d', nR, nC), ...
'rows', nR, ...
'cols', nC); %#ok<AGROW>
end
end
end
payload = struct('variables', {varList}, 'vectors', {vectorList});
sendResponse(app, 'showVarList', payload);
catch ME
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Error: ' ME.message]));
end
end
% ---- Load a specific variable by name -----------------------------
function handleLoadVariable(app, data)
try
selectedName = data.varName;
if ~isvarname(selectedName)
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Invalid variable name: "' selectedName '"']));
return;
end
if ~evalin('base', ['exist(''' selectedName ''', ''var'')'])
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Variable "' selectedName '" not found']));
return;
end
rawData = evalin('base', selectedName);
if ~isreal(rawData), rawData = real(rawData); end
if isvector(rawData)
rawData = rawData(:)';
end
[isValid, msg] = app.Validator.validateData(rawData);
if ~isValid
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', msg));
return;
end
app.OriginalData = double(rawData);
[nRows, nCols] = size(rawData);
% Load x-axis vector if specified, otherwise use indices
if isfield(data, 'xAxisVar') && ~isempty(data.xAxisVar)
xName = data.xAxisVar;
if ischar(xName), xName = char(xName); end
if evalin('base', ['exist(''' xName ''', ''var'')'])
xRaw = evalin('base', xName);
xVec = double(xRaw(:))';
if length(xVec) == nCols
app.Wavelength = xVec';
else
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ...
sprintf('X-axis length (%d) does not match data columns (%d). Using indices.', length(xVec), nCols)));
app.Wavelength = (1:nCols)';
end
else
app.Wavelength = (1:nCols)';
end
else
app.Wavelength = (1:nCols)';
end
app.DataLoaded = true;
app.LoadedVarName = selectedName;
app.CorrectedData = [];
app.BaselineData = [];
app.WeightsData = [];
% Build payload with all needed data
payload = struct();
payload.wavelength = app.Wavelength';
payload.meanSpectrum = mean(app.OriginalData, 1);
payload.nSamples = nRows;
payload.nChannels = nCols;
payload.varName = selectedName;
payload.statusType = 'success';
payload.statusMessage = sprintf('Loaded "%s": %dx%d', selectedName, nRows, nCols);
% Send first spectrum for signal mode
if nRows >= 1
payload.firstSpectrum = app.OriginalData(1, :);
end
% If dataset small enough, send all spectra for "show all data"
if nRows <= 500 && nRows * nCols <= 500000
allData = cell(1, nRows);
for i = 1:nRows
allData{i} = app.OriginalData(i, :);
end
payload.allSpectra = allData;
end
sendResponse(app, 'dataLoaded', payload);
catch ME
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Load error: ' ME.message]));
end
end
% ---- Get specific spectrum ----------------------------------------
function handleGetSpectrum(app, data)
if ~app.DataLoaded
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', 'No data loaded'));
return;
end
idx = round(safeDouble(app, data, 'signalIndex', 1));
nRows = size(app.OriginalData, 1);
idx = max(1, min(nRows, idx));
payload = struct();
payload.signalIndex = idx;
payload.spectrum = app.OriginalData(idx, :);
payload.wavelength = app.Wavelength';
payload.nSamples = nRows;
payload.statusType = 'success';
payload.statusMessage = sprintf('Signal %d/%d', idx, nRows);
sendResponse(app, 'spectrumLoaded', payload);
end
% ---- Preview baseline on displayed spectrum -----------------------
function handlePreviewBaseline(app, data)
if ~app.DataLoaded
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', 'No data loaded'));
return;
end
lambda = safeDouble(app, data, 'lambda', 10);
p = safeDouble(app, data, 'p', 0.5);
mu = safeDouble(app, data, 'mu', 10);
maxIter = round(safeDouble(app, data, 'maxIter', 50));
tolerance = safeDouble(app, data, 'tolerance', 1e-6);
% Get the spectrum to use for preview
signalMode = false;
if isfield(data, 'signalMode')
signalMode = logical(data.signalMode);
end
signalIndex = round(safeDouble(app, data, 'signalIndex', 1));
if signalMode && signalIndex >= 1 && signalIndex <= size(app.OriginalData, 1)
y = app.OriginalData(signalIndex, :)';
else
y = mean(app.OriginalData, 1)';
end
% Build interval arrays from JS data (now using flat arrays)
intervals = [];
pVals = [];
lambdasAsym = [];
if isfield(data, 'intStarts') && isfield(data, 'intEnds')
starts = toDoubleArray(app, data.intStarts);
ends = toDoubleArray(app, data.intEnds);
lambdas = toDoubleArray(app, data.intLambdas);
ps = toDoubleArray(app, data.intPs);
nInt = numel(starts);
if nInt > 0
intervals = [starts(:), ends(:)];
lambdasAsym = lambdas(:);
pVals = ps(:);
end
else
% Fallback to old format
[intervals, pVals, lambdasAsym] = buildIntervalsFromData(app, data);
end
try
[baseline, ~] = app.Corrector.computeBaseline(y, intervals, pVals, ...
lambdasAsym, lambda, mu, maxIter, tolerance, p);
result = struct();
result.baseline = baseline';
result.corrected = y' - baseline';
result.wavelength = app.Wavelength';
result.statusType = 'success';
result.statusMessage = 'Baseline updated';
sendResponse(app, 'previewUpdated', result);
catch ME
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Preview: ' ME.message]));
end
end
% ---- Apply correction to all spectra ------------------------------
function handleApply(app, data)
if ~app.DataLoaded
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', 'No data loaded'));
return;
end
lambda = safeDouble(app, data, 'lambda', 10);
p = safeDouble(app, data, 'p', 0.5);
mu = safeDouble(app, data, 'mu', 10);
maxIter = round(safeDouble(app, data, 'maxIter', 50));
tolerance = safeDouble(app, data, 'tolerance', 1e-6);
perSignalMode = false;
if isfield(data, 'perSignalMode')
perSignalMode = logical(data.perSignalMode);
end
nRows = size(app.OriginalData, 1);
nCols = size(app.OriginalData, 2);
app.CorrectedData = zeros(nRows, nCols);
app.BaselineData = zeros(nRows, nCols);
app.WeightsData = zeros(nRows, nCols);
try
% Send progress updates every N samples (or at least 20 updates total)
progressInterval = max(1, floor(nRows / 20));
% Send initial progress (0 of total) so user sees the total
sendResponse(app, 'correctionProgress', struct(...
'current', 0, 'total', nRows));
drawnow limitrate;
if perSignalMode && isfield(data, 'psIntervalSignalIdx')
% Per-signal mode: flat arrays encode per-signal intervals
allSigIdx = toDoubleArray(app, data.psIntervalSignalIdx);
allStarts = toDoubleArray(app, data.psIntervalStart);
allEnds = toDoubleArray(app, data.psIntervalEnd);
allLam = toDoubleArray(app, data.psIntervalLambda);
allPv = toDoubleArray(app, data.psIntervalP);
% Per-signal global params
psLambda = toDoubleArray(app, data.psGlobalLambda);
psP = toDoubleArray(app, data.psGlobalP);
psMu = toDoubleArray(app, data.psGlobalMu);
for i = 1:nRows
y = app.OriginalData(i, :)';
% Get intervals for this signal
mask = (allSigIdx == i);
sigStarts = allStarts(mask);
sigEnds = allEnds(mask);
sigLam = allLam(mask);
sigPv = allPv(mask);
nInt = numel(sigStarts);
if nInt > 0
sigIntervals = [sigStarts(:), sigEnds(:)];
else
sigIntervals = [];
end
% Get global params for this signal
if i <= numel(psLambda)
sigLambda = psLambda(i);
sigGlobalP = psP(i);
sigMu = psMu(i);
else
sigLambda = lambda;
sigGlobalP = p;
sigMu = mu;
end
[bl, w] = app.Corrector.computeBaseline(y, sigIntervals, ...
sigPv(:), sigLam(:), sigLambda, sigMu, maxIter, tolerance, sigGlobalP);
app.BaselineData(i, :) = bl';
app.WeightsData(i, :) = w';
app.CorrectedData(i, :) = app.OriginalData(i, :) - bl';
% Send progress update
if mod(i, progressInterval) == 0 || i == nRows
sendResponse(app, 'correctionProgress', struct(...
'current', i, 'total', nRows));
drawnow limitrate;
end
end
else
% Global mode: same intervals/params for all spectra
[intervals, pVals, lambdasAsym] = buildIntervalsFromData(app, data);
for i = 1:nRows
y = app.OriginalData(i, :)';
[bl, w] = app.Corrector.computeBaseline(y, intervals, pVals, ...
lambdasAsym, lambda, mu, maxIter, tolerance, p);
app.BaselineData(i, :) = bl';
app.WeightsData(i, :) = w';
app.CorrectedData(i, :) = app.OriginalData(i, :) - bl';
% Send progress update
if mod(i, progressInterval) == 0 || i == nRows
sendResponse(app, 'correctionProgress', struct(...
'current', i, 'total', nRows));
drawnow limitrate;
end
end
end
result = struct();
result.correctedMean = mean(app.CorrectedData, 1);
result.nCorrected = nRows;
result.wavelength = app.Wavelength';
result.statusType = 'success';
result.statusMessage = sprintf('Corrected %d spectra', nRows);
% Send all corrected data if small enough for "show all"
if nRows <= 500 && nRows * nCols <= 500000
allCorr = cell(1, nRows);
for i = 1:nRows
allCorr{i} = app.CorrectedData(i, :);
end
result.allCorrected = allCorr;
end
sendResponse(app, 'correctionApplied', result);
catch ME
% Show error in MATLAB command window for debugging
disp('=== LASLS Apply Error ===');
disp(ME.message);
disp(ME.getReport());
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Apply error: ' ME.message]));
end
end
% ---- Prepare export (check existing vars) --------------------------
function handlePrepareExport(app)
% Check what data is available
hasCorrected = ~isempty(app.CorrectedData);
hasBaseline = ~isempty(app.BaselineData);
hasWeights = ~isempty(app.WeightsData);
% Send current workspace variable names so the UI can check
% the names the user actually types, not only the defaults.
workspaceVars = evalin('base', 'who');
% Send info to JS to show export dialog
sendResponse(app, 'showExportDialog', struct(...
'hasCorrected', hasCorrected, ...
'hasBaseline', hasBaseline, ...
'hasWeights', hasWeights, ...
'workspaceVars', {workspaceVars}));
end
% ---- Live export-name validation for the open modal --------------
function handleCheckExportNames(app, data)
requestedNames = {};
fieldNames = {'correctedName', 'baselineName', 'weightsName', 'paramsName'};
for i = 1:numel(fieldNames)
fieldName = fieldNames{i};
if isfield(data, fieldName) && ~isempty(data.(fieldName))
thisName = data.(fieldName);
if ~ischar(thisName)
try
thisName = char(thisName);
catch
continue;
end
end
requestedNames{end+1} = strtrim(thisName); %#ok<AGROW>
end
end
invalidNames = {};
existingNames = {};
if ~isempty(requestedNames)
invalidMask = ~cellfun(@isvarname, requestedNames);
invalidNames = unique(requestedNames(invalidMask));
validNames = unique(requestedNames(~invalidMask));
for i = 1:numel(validNames)
if evalin('base', ['exist(''' validNames{i} ''', ''var'')'])
existingNames{end+1} = validNames{i}; %#ok<AGROW>
end
end
end
requestId = safeDouble(app, data, 'requestId', 0);
sessionId = safeDouble(app, data, 'sessionId', 0);
sendResponse(app, 'exportNamesChecked', struct(...
'sessionId', sessionId, ...
'requestId', requestId, ...
'existingNames', {unique(existingNames)}, ...
'invalidNames', {invalidNames}));
end
% ---- Do the actual export with user-specified names ----------------
function handleDoExport(app, data)
if isempty(app.CorrectedData)
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', 'No corrected data. Apply first.'));
return;
end
% Selection flags default to true for compatibility with older
% frontends that did not send per-output export choices.
includeCorrected = true;
includeBaseline = true;
includeWeights = true;
includeParams = true;
if isfield(data, 'includeCorrected'), includeCorrected = logical(data.includeCorrected); end
if isfield(data, 'includeBaseline'), includeBaseline = logical(data.includeBaseline); end
if isfield(data, 'includeWeights'), includeWeights = logical(data.includeWeights); end
if isfield(data, 'includeParams'), includeParams = logical(data.includeParams); end
includeBaseline = includeBaseline && ~isempty(app.BaselineData);
includeWeights = includeWeights && ~isempty(app.WeightsData);
% Resolve requested export names first so we can validate them
% before writing anything to the workspace.
requestedNames = {};
correctedName = '';
if includeCorrected
correctedName = 'correctedData';
if isfield(data, 'correctedName') && ~isempty(data.correctedName)
correctedName = data.correctedName;
end
requestedNames{end+1} = correctedName;
end
baselineName = '';
if includeBaseline
baselineName = 'baselineData';
if isfield(data, 'baselineName') && ~isempty(data.baselineName)
baselineName = data.baselineName;
end
requestedNames{end+1} = baselineName;
end
weightsName = '';
if includeWeights
weightsName = 'weightsData';
if isfield(data, 'weightsName') && ~isempty(data.weightsName)
weightsName = data.weightsName;
end
requestedNames{end+1} = weightsName;
end
paramsName = '';
if includeParams && isfield(data, 'params')
paramsName = 'laslsParams';
if isfield(data, 'paramsName') && ~isempty(data.paramsName)
paramsName = data.paramsName;
end
requestedNames{end+1} = paramsName;
end
if isempty(requestedNames)
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', 'Select at least one item to export.'));
return;
end
invalidNames = requestedNames(~cellfun(@isvarname, requestedNames));
if ~isempty(invalidNames)
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', ...
'message', ['Invalid variable name(s): ' strjoin(unique(invalidNames), ', ')]));
return;
end
if numel(unique(requestedNames)) ~= numel(requestedNames)
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', ...
'message', 'Export names must be different from each other.'));
return;
end
existingNames = {};
for i = 1:numel(requestedNames)
if evalin('base', ['exist(''' requestedNames{i} ''', ''var'')'])
existingNames{end+1} = requestedNames{i}; %#ok<AGROW>
end
end
overwriteConfirmed = isfield(data, 'overwriteConfirmed') && ...
~isempty(data.overwriteConfirmed) && logical(data.overwriteConfirmed);
if ~isempty(existingNames) && ~overwriteConfirmed
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', ...
'message', ['Variables already exist in the workspace: ' ...
strjoin(unique(existingNames), ', ') ...
'. Confirm overwrite to export.']));
return;
end
exported = {};
% Export only the outputs selected in the dialog.
if includeCorrected
assignin('base', correctedName, app.CorrectedData);
exported{end+1} = correctedName;
end
% Export baseline if available
if includeBaseline
assignin('base', baselineName, app.BaselineData);
exported{end+1} = baselineName;
end
% Export weights if available
if includeWeights
assignin('base', weightsName, app.WeightsData);
exported{end+1} = weightsName;
end
% Export parameters struct for reproducibility
if ~isempty(paramsName)
% Convert JS params to MATLAB struct
params = struct();
jsParams = data.params;
if isfield(jsParams, 'lambda'), params.lambda = jsParams.lambda; end
if isfield(jsParams, 'p'), params.p = jsParams.p; end
if isfield(jsParams, 'mu'), params.mu = jsParams.mu; end
if isfield(jsParams, 'maxIter'), params.maxIter = jsParams.maxIter; end
if isfield(jsParams, 'tolerance'), params.tolerance = jsParams.tolerance; end
if isfield(jsParams, 'perSignalMode'), params.perSignalMode = jsParams.perSignalMode; end
% Convert intervals
if isfield(jsParams, 'intervals')
params.intervals = jsParams.intervals;
end
% Per-signal data
if isfield(jsParams, 'perSignalIntervals')
params.perSignalIntervals = jsParams.perSignalIntervals;
end
if isfield(jsParams, 'perSignalGlobalParams')
params.perSignalGlobalParams = jsParams.perSignalGlobalParams;
end
assignin('base', paramsName, params);
exported{end+1} = paramsName;
end
sendResponse(app, 'exportCompleted', struct('exportedNames', {exported}));
end
% ---- Prepare import (list param structs in workspace) --------------
function handlePrepareImport(app) %#ok<INUSL>
try
vars = evalin('base', 'whos');
varList = {};
for i = 1:length(vars)
if strcmp(vars(i).class, 'struct')
% Check if it looks like a LASLS params struct
try
val = evalin('base', vars(i).name);
if isfield(val, 'lambda') || isfield(val, 'intervals')
nInt = 0;
perSig = false;
if isfield(val, 'intervals')
if isstruct(val.intervals)
nInt = numel(val.intervals);
elseif iscell(val.intervals)
nInt = numel(val.intervals);
end
end
if isfield(val, 'perSignalMode')
perSig = logical(val.perSignalMode);
end
varList{end+1} = struct(...
'name', vars(i).name, ...
'nIntervals', nInt, ...
'perSignalMode', perSig); %#ok<AGROW>
end
catch
% Skip if can't read
end
end
end
sendResponse(app, 'showImportDialog', struct('variables', {varList}));
catch ME
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Import error: ' ME.message]));
end
end
% ---- Do the actual import ------------------------------------------
function handleDoImport(app, data) %#ok<INUSL>
try
varName = data.varName;
if ~isvarname(varName)
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Invalid variable name: "' varName '"']));
return;
end
if ~evalin('base', ['exist(''' varName ''', ''var'')'])
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Variable "' varName '" not found']));
return;
end
params = evalin('base', varName);
sendResponse(app, 'paramsImported', params);
catch ME
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Import error: ' ME.message]));
end
end
% ---- Export interval table to workspace ---------------------------
function handleExportIntervals(app, data)
if ~isfield(data, 'tableStarts') || isempty(data.tableStarts)
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', 'No intervals to export'));
return;
end
try
starts = toDoubleArray(app, data.tableStarts);
ends = toDoubleArray(app, data.tableEnds);
lams = toDoubleArray(app, data.tableLambdas);
ps = toDoubleArray(app, data.tablePs);
nInt = numel(starts);
T = table();
hasPerSignal = isfield(data, 'tableSignalIdx') && ~isempty(data.tableSignalIdx);
if hasPerSignal
sigIdx = toDoubleArray(app, data.tableSignalIdx);
T.SignalIndex = sigIdx(:);
if isfield(data, 'tableLambdaOut')
T.LambdaOut = toDoubleArray(app, data.tableLambdaOut);
T.LambdaOut = T.LambdaOut(:);
end
if isfield(data, 'tablePOut')
T.pOut = toDoubleArray(app, data.tablePOut);
T.pOut = T.pOut(:);
end
if isfield(data, 'tableMu')
T.Mu = toDoubleArray(app, data.tableMu);
T.Mu = T.Mu(:);
end
else
T.ID = (1:nInt)';
end
T.Start = starts(:);
T.End = ends(:);
T.Lambda = lams(:);
T.p = ps(:);
assignin('base', 'intervalTable', T);
sendResponse(app, 'statusUpdate', ...
struct('type', 'success', ...
'message', sprintf('Exported %d intervals as "intervalTable"', nInt)));
catch ME
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Export intervals: ' ME.message]));
end
end
% ---- Load interval table - send table list to JS -------------------
function handleLoadIntervals(app)
if ~app.DataLoaded
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', 'Load data first'));
return;
end
try
vars = evalin('base', 'whos');
tableList = {};
for i = 1:length(vars)
if strcmp(vars(i).class, 'table')
tableList{end+1} = struct(...
'name', vars(i).name, ...
'size', sprintf('%dx%d', vars(i).size(1), vars(i).size(2)), ...
'rows', vars(i).size(1)); %#ok<AGROW>
end
end
if isempty(tableList)
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', 'No tables in workspace'));
return;
end
% Send table list to JavaScript for modal display
sendResponse(app, 'showTableList', struct('tables', {tableList}));
catch ME
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Error: ' ME.message]));
end
end
% ---- Load a specific interval table by name -----------------------
function handleLoadIntervalTable(app, data)
try
tableName = data.tableName;
if ~isvarname(tableName)
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Invalid table name: "' tableName '"']));
return;
end
if ~evalin('base', ['exist(''' tableName ''', ''var'')'])
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Table "' tableName '" not found']));
return;
end
T = evalin('base', tableName);
if ~istable(T) || ~ismember('Start', T.Properties.VariableNames) || ...
~ismember('End', T.Properties.VariableNames)
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', 'Table must have Start and End columns'));
return;
end
% Convert table to struct arrays for HTML
hasPerSignal = ismember('SignalIndex', T.Properties.VariableNames);
hasLam = ismember('Lambda', T.Properties.VariableNames);
hasP = ismember('p', T.Properties.VariableNames);
nRows = height(T);
nCh = size(app.OriginalData, 2);
intervals = cell(1, nRows);
for i = 1:nRows
intv = struct();
s = round(double(T.Start(i)));
e = round(double(T.End(i)));
s = max(1, min(nCh, s));
e = max(1, min(nCh, e));
if e < s, tmp=s; s=e; e=tmp; end
intv.startIdx = s;
intv.endIdx = e;
intv.lambda = 1000;
intv.p = 0.01;
if hasLam, intv.lambda = double(T.Lambda(i)); end
if hasP, intv.p = double(T.p(i)); end
if hasPerSignal
intv.signalIndex = double(T.SignalIndex(i));
end
if ismember('LambdaOut', T.Properties.VariableNames)
intv.lambdaOut = double(T.LambdaOut(i));
end
if ismember('pOut', T.Properties.VariableNames)
intv.pOut = double(T.pOut(i));
end
if ismember('Mu', T.Properties.VariableNames)
intv.mu = double(T.Mu(i));
end
intervals{i} = intv;
end
payload = struct();
payload.intervals = intervals;
payload.perSignalFormat = hasPerSignal;
payload.statusType = 'success';
payload.statusMessage = sprintf('Loaded %d intervals from "%s"', nRows, tableName);
sendResponse(app, 'intervalsLoaded', payload);
catch ME
sendResponse(app, 'statusUpdate', ...
struct('type', 'error', 'message', ['Load intervals: ' ME.message]));
end
end
end
% ====================================================================
% COMMUNICATION HELPERS
% ====================================================================
methods (Access = private)