Repository navigation
Expand file tree
/
Copy pathperceptGT_RR_folder.m
More file actions
685 lines (604 loc) · 29.5 KB
/
Copy pathperceptGT_RR_folder.m
File metadata and controls
685 lines (604 loc) · 29.5 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
% === Percept PC/RC JSON pipeline (deep scan; tidy summary) ===
% Extracts settings from Percept JSONs, writes a tidy spreadsheet
% (one row per file/acquisition), and extracts BrainSense Survey
% PSD/TD into Result/sub-XXXX when present.
%%%%%%%%%%%%%%%%%%% Change pathname to perceptGT %%%%%%%%%%%%%%%%%%%%
addpath(genpath('/Users/rebeccaroth/Documents/MATLAB/perceptGT-master_Updated'))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Keep MATLAB figures from popping up (and auto-restore at end) ---
suppressFigures = true;
if suppressFigures
prevFigVis = get(groot,'defaultFigureVisible');
set(groot,'defaultFigureVisible','off');
set(groot,'DefaultFigureCreateFcn','set(gcf,''Visible'',''off'')');
cleanupFigVis = onCleanup(@() set(groot, ...
'defaultFigureVisible',prevFigVis, ...
'DefaultFigureCreateFcn',''));
end
% === TEMP enable UI for bigmenu ===
prevCF = get(groot,'DefaultFigureCreateFcn');
set(groot,'DefaultFigureCreateFcn','');
set(groot,'defaultFigureVisible','on');
choice = bigmenu('Select input mode:', ...
{'A folder (scan for all JSONs)', ...
'JSON files (pick manually)', ...
'A parent folder with many subject subfolders'}, ...
'Title','Input Mode','FontSize',20,'ButtonWidth',480,'Gap',48);
if choice == 1
disp('User picked: All JSON files in a folder (recursive)');
elseif choice == 2
disp('User picked: Manual file selection');
elseif choice == 3
disp('User picked: Parent directory containing many subject folders');
else
disp('No option selected (user closed dialog)'); return
end
% === restore UI suppression after bigmenu ===
set(groot,'defaultFigureVisible','off');
set(groot,'DefaultFigureCreateFcn', prevCF);
%% Select inputs (supports parent-folder-of-subjects)
filenames = {};
if choice == 1
rootPath = uigetdir('', 'Select the folder containing JSON files');
if rootPath == 0, disp('No folder selected'); return; end
L = dir(fullfile(rootPath, '**', '*'));
L = L(~[L.isdir]);
paths = cellfun(@fullfile, {L.folder}, {L.name}, 'UniformOutput', false);
filenames = paths(endsWith(lower(paths), '.json'));
if isempty(filenames), disp('No JSON files found in selected folder.'); return; end
fprintf('Found %d JSON files under %s\n', numel(filenames), rootPath);
elseif choice == 2
[filenames, data_pathname] = uigetfile('*.json', 'MultiSelect', 'on');
if isequal(filenames, 0), disp('No file selected'); return; end
if ~iscell(filenames), filenames = {filenames}; end
filenames = cellfun(@(n) fullfile(data_pathname, n), filenames, 'UniformOutput', false);
elseif choice == 3
parentPath = uigetdir('', 'Select the PARENT folder (containing sub-* folders)');
if parentPath == 0, disp('No folder selected'); return; end
prevCF2 = get(groot,'DefaultFigureCreateFcn');
set(groot,'DefaultFigureCreateFcn',''); set(groot,'defaultFigureVisible','on');
answer = inputdlg({'Subfolder name pattern (glob):'}, 'Subject Folder Pattern', 1, {'sub-*'});
set(groot,'defaultFigureVisible','off'); set(groot,'DefaultFigureCreateFcn', prevCF2);
if isempty(answer), disp('Cancelled'); return; end
subPattern = strtrim(answer{1}); if isempty(subPattern), subPattern = 'sub-*'; end
subjDirs = dir(fullfile(parentPath, subPattern)); subjDirs = subjDirs([subjDirs.isdir]);
if isempty(subjDirs)
warning('No subject folders matching "%s" found under %s', subPattern, parentPath);
return;
end
allFiles = {};
for k = 1:numel(subjDirs)
thisSub = fullfile(parentPath, subjDirs(k).name);
L = dir(fullfile(thisSub, '**', '*'));
L = L(~[L.isdir]);
paths = cellfun(@fullfile, {L.folder}, {L.name}, 'UniformOutput', false);
jf = paths(endsWith(lower(paths), '.json'));
if ~isempty(jf)
allFiles = [allFiles, jf]; %#ok<AGROW>
else
fprintf('No JSON files found in %s\n', thisSub);
end
end
filenames = unique(allFiles);
if isempty(filenames), disp('No JSON files found in any subject folder.'); return; end
fprintf('Found %d JSON files across %d subject folders under %s\n', numel(filenames), numel(subjDirs), parentPath);
end
% --- Tidy summary collector (one row per file) ---
rows = struct([]); % collected records
masterOutputPath = ''; % first file's Result/ becomes the write location
%% Process each JSON
for fileId = 1:numel(filenames)
fname = filenames{fileId};
% ---------- Put outputs in Result next to nearest sub-* ancestor ----------
[fileDir, ~, ~] = fileparts(fname);
p = fileDir;
while true
[parent, base] = fileparts(p);
if startsWith(base, 'sub-'), resultParent = parent; break; end
if isempty(parent) || strcmp(parent, p), resultParent = fileDir; break; end
p = parent;
end
outputPath = fullfile(resultParent, 'Result');
if ~exist(outputPath, 'dir'), mkdir(outputPath); end
if fileId == 1, masterOutputPath = outputPath; end
% -------------------------------------------------------------------------
% Defaults per file
rateInHertz = NaN;
monthsPostImplant_calendar = NaN; % full calendar months between implant & session
daysPostImplant_calendar = NaN; % continuous days between implant & session
lAmplitude = NaN; rAmplitude = NaN; lPulseWidth = NaN; rPulseWidth = NaN;
sss_status = false; sss_duration = NaN;
cycling_status = false; cycling_on = NaN; cycling_off = NaN;
implantDate_formatted = NaT;
jsonSessionDate = NaT;
timeSinceTherapy = NaN; % hours (from device counter)
timeSinceFollowup = NaN; % hours (from device counter)
% Read JSON robustly
try
rawtxt = fileread(fname);
data = jsondecode(rawtxt);
if isfield(data,'SessionDate') && ~isempty(data.SessionDate)
try
jsonSessionDate = datetime(data.SessionDate,'InputFormat','yyyy-MM-dd''T''HH:mm:ss''Z','TimeZone','UTC');
catch
% Try a more flexible parse
try
jsonSessionDate = datetime(data.SessionDate,'TimeZone','UTC');
catch
jsonSessionDate = NaT;
end
end
end
catch ME
warning('Skipping %s (JSON decode failed): %s', fname, ME.message);
continue
end
% ================= Deep scan for Survey fields anywhere =================
foundPSD = isfield(data,'LFPMontage');
foundTD = isfield(data,'LfpMontageTimeDomain');
nodes = {data}; ctxs = {''}; guardCount = 0;
while ~isempty(nodes) && (~foundPSD || ~foundTD) && guardCount < 100000
guardCount = guardCount + 1;
node = nodes{1}; nodes(1) = [];
ctx = ctxs{1}; ctxs(1) = [];
if isstruct(node)
if numel(node) > 1
for ii = 1:numel(node)
nodes{end+1} = node(ii); %#ok<AGROW>
if isempty(ctx)
ctxs{end+1} = sprintf('(%d)', ii); %#ok<AGROW>
else
ctxs{end+1} = sprintf('%s(%d)', ctx, ii); %#ok<AGROW>
end
end
continue
end
fns = fieldnames(node);
fnsLower = lower(fns);
isStreamingContext = contains(ctx, 'indefinitestreaming', 'ignorecase', true);
looksLikeSurveyCtx = any(contains(fnsLower, {'lfpmontage','lpfmontage','montage','survey','brainsense'}));
if ~foundPSD
idx = find(strcmpi(fns,'LFPMontage') | strcmpi(fns,'LfpMontage'), 1);
if ~isempty(idx)
data.LFPMontage = node.(fns{idx});
foundPSD = true;
fprintf('Promoted PSD from %s.%s\n', ctx, fns{idx});
end
end
if ~foundTD
idxTD = find(strcmpi(fns,'LfpMontageTimeDomain') | strcmpi(fns,'LFPMontageTimeDomain') | ...
strcmpi(fns,'TimeDomainData') | strcmpi(fns,'TimeDomain'), 1);
if ~isempty(idxTD)
if ~isStreamingContext && (looksLikeSurveyCtx || any(contains({ctx}, {'survey','brainsense','montage'}, 'IgnoreCase', true)))
data.LfpMontageTimeDomain = node.(fns{idxTD});
foundTD = true;
fprintf('Promoted TD from %s.%s\n', ctx, fns{idxTD});
end
end
end
for k = 1:numel(fns)
val = node.(fns{k});
if isempty(ctx), childCtx = fns{k}; else, childCtx = [ctx '.' fns{k}]; end
if isstruct(val)
if numel(val) > 1
for ii = 1:numel(val)
nodes{end+1} = val(ii); %#ok<AGROW>
ctxs{end+1} = sprintf('%s(%d)', childCtx, ii); %#ok<AGROW>
end
else
nodes{end+1} = val; %#ok<AGROW>
ctxs{end+1} = childCtx; %#ok<AGROW>
end
elseif iscell(val)
for ci = 1:numel(val)
v = val{ci};
if isstruct(v)
if numel(v) > 1
for ii = 1:numel(v)
nodes{end+1} = v(ii); %#ok<AGROW>
ctxs{end+1} = sprintf('%s{%d}', childCtx, ci); %#ok<AGROW>
end
else
nodes{end+1} = v; %#ok<AGROW>
ctxs{end+1} = sprintf('%s{%d}', childCtx, ci); %#ok<AGROW>
end
end
end
end
end
elseif iscell(node)
for ci = 1:numel(node)
v = node{ci};
if isstruct(v)
if numel(v) > 1
for ii = 1:numel(v)
nodes{end+1} = v(ii); %#ok<AGROW>
ctxs{end+1} = sprintf('%s{%d}', ctx, ci); %#ok<AGROW>
end
else
nodes{end+1} = v; %#ok<AGROW>
ctxs{end+1} = sprintf('%s{%d}', ctx, ci); %#ok<AGROW>
end
end
end
end
end
hasPSD = isfield(data,'LFPMontage');
hasTD = isfield(data,'LfpMontageTimeDomain');
hasStreamingTD = isfield(data,'IndefiniteStreaming') && isstruct(data.IndefiniteStreaming) && isfield(data.IndefiniteStreaming,'TimeDomainData');
hasStreamingPower = isfield(data,'IndefiniteStreaming') && isstruct(data.IndefiniteStreaming) && (isfield(data.IndefiniteStreaming,'PowerDomainData') || isfield(data.IndefiniteStreaming,'PowerDomain'));
if hasPSD || hasTD
fprintf('Detected Survey data after deep scan: PSD=%d, TD=%d\n', hasPSD, hasTD);
elseif hasStreamingTD || hasStreamingPower
fprintf('Detected IndefiniteStreaming: TD=%d, Power=%d\n', hasStreamingTD, hasStreamingPower);
else
fprintf('No BrainSense Survey fields found in %s.\n', fname);
try disp('Top-level fields:'), disp(fieldnames(data)'); end
end
% ================= End deep scan =======================================
% ---------- subject, run ----------
params = struct(); params.fname = fname;
[~, baseName, ~] = fileparts(fname);
% subject ID
m = regexpi(baseName, 'sub-([^_]+)', 'tokens', 'once');
if ~isempty(m)
params.subjectID = m{1};
else
m2 = regexpi(fname, 'sub-([^/\\_]+)', 'tokens', 'once');
if ~isempty(m2), params.subjectID = m2{1}; else, params.subjectID = 'unknown'; end
end
subjectID = {params.subjectID};
params.save_pathname = fullfile(outputPath, ['sub-' subjectID{1}]);
if ~exist(params.save_pathname, 'dir'), mkdir(params.save_pathname); end
% ---------- Device info (timing) ----------
if isfield(data,'DeviceInformation') && isfield(data.DeviceInformation,'Initial')
DI = data.DeviceInformation.Initial;
% Implant date
if isfield(DI,'ImplantDate') && ~isempty(DI.ImplantDate)
try
implantDate_formatted = datetime(DI.ImplantDate,'InputFormat','yyyy-MM-dd''T''HH:mm:ss''Z','TimeZone','UTC');
catch
try
implantDate_formatted = datetime(DI.ImplantDate,'TimeZone','UTC');
catch
implantDate_formatted = NaT;
end
end
end
% Counters (seconds -> hours)
if isfield(DI,'AccumulatedTherapyOnTimeSinceImplant')
timeSinceTherapy = DI.AccumulatedTherapyOnTimeSinceImplant / 3600;
end
if isfield(DI,'AccumulatedTherapyOnTimeSinceFollowup')
timeSinceFollowup = DI.AccumulatedTherapyOnTimeSinceFollowup / 3600;
end
% Calendar timepoint from JSON dates (ImplantDate -> SessionDate)
if ~isnat(implantDate_formatted) && ~isnat(jsonSessionDate)
try
% Full calendar months
monthsPostImplant_calendar = double(calmonths(between(implantDate_formatted, jsonSessionDate, 'months')));
catch
monthsPostImplant_calendar = NaN;
end
try
daysPostImplant_calendar = days(jsonSessionDate - implantDate_formatted);
catch
daysPostImplant_calendar = NaN;
end
end
end
% ---------- Labels ----------
% run- label from filename (identifier only)
mRun = regexpi(baseName, 'run-([^_\.]+)', 'tokens', 'once');
if isempty(mRun), mRun = regexpi(fname, 'run-([^/\\_\.]+)', 'tokens', 'once'); end
params.runLabel = 'run-NA';
if ~isempty(mRun), params.runLabel = ['run-' mRun{1}]; end
% acq- label computed from JSON dates ONLY
params.sessionLabel = 'acq-NA';
if ~isnan(monthsPostImplant_calendar)
params.sessionLabel = sprintf('acq-%dm', monthsPostImplant_calendar);
end
acqLabelOut = params.sessionLabel;
runLabelOut = params.runLabel;
% Session date (info only; already parsed)
params.SessionDate = '';
sessionDate_formatted = NaT;
if isfield(data,'SessionDate') && ~isempty(data.SessionDate)
try
params.SessionDate = regexprep(data.SessionDate, {':','-'}, {'',''});
sessionDate_formatted = datetime(data.SessionDate,'InputFormat','yyyy-MM-dd''T''HH:mm:ss''Z','TimeZone','UTC');
catch
params.SessionDate = regexprep(char(data.SessionDate), {':','-'}, {'',''});
end
end
% -------- Groups (program settings) with robust hemisphere extraction ------
if isfield(data, 'Groups')
groupTypes = {'Initial'}; % only "Initial" (Final=plan)
for g = 1:numel(groupTypes)
groupData = data.Groups.(groupTypes{g});
% pick active group element, else first
activeIdx = [];
for idx = 1:numel(groupData)
if isfield(groupData(idx),'ActiveGroup') && isequal(groupData(idx).ActiveGroup, 1)
activeIdx = idx; break;
end
end
if isempty(activeIdx), activeIdx = 1; end
if numel(groupData) < activeIdx, continue; end
block = groupData(activeIdx);
% ProgramSettings might be an array; pick ActiveProgram if present
PS = struct();
if isfield(block,'ProgramSettings')
tempPS = block.ProgramSettings;
if isstruct(tempPS) && ~isempty(tempPS)
if numel(tempPS) > 1
psIdx = 1;
for kps = 1:numel(tempPS)
if isfield(tempPS(kps),'ActiveProgram') && isequal(tempPS(kps).ActiveProgram,1)
psIdx = kps; break;
end
end
PS = tempPS(psIdx);
else
PS = tempPS;
end
end
end
% GroupSettings for soft start / cycling
if isfield(block,'GroupSettings'), groupSettings = block.GroupSettings; else, groupSettings = struct(); end
% Classic: LeftHemisphere/RightHemisphere.Programs
if isfield(PS,'LeftHemisphere') && isfield(PS.LeftHemisphere,'Programs')
L = PS.LeftHemisphere.Programs;
if isstruct(L) && ~isempty(L)
if numel(L) > 1
ai = find(arrayfun(@(x)isfield(x,'ActiveProgram') && isequal(x.ActiveProgram,1), L),1);
if isempty(ai), ai = 1; end
L = L(ai);
end
if isfield(L,'AmplitudeInMilliAmps'), lAmplitude = L.AmplitudeInMilliAmps; end
if isfield(L,'PulseWidthInMicroSecond'), lPulseWidth = L.PulseWidthInMicroSecond; end
if isfield(L,'RateInHertz') && isnan(rateInHertz), rateInHertz = L.RateInHertz; end
end
end
if isfield(PS,'RightHemisphere') && isfield(PS.RightHemisphere,'Programs')
R = PS.RightHemisphere.Programs;
if isstruct(R) && ~isempty(R)
if numel(R) > 1
ai = find(arrayfun(@(x)isfield(x,'ActiveProgram') && isequal(x.ActiveProgram,1), R),1);
if isempty(ai), ai = 1; end
R = R(ai);
end
if isfield(R,'AmplitudeInMilliAmps'), rAmplitude = R.AmplitudeInMilliAmps; end
if isfield(R,'PulseWidthInMicroSecond'), rPulseWidth = R.PulseWidthInMicroSecond; end
if isfield(R,'RateInHertz') && isnan(rateInHertz), rateInHertz = R.RateInHertz; end
end
end
% Flat defaults (mirror if still empty)
if isnan(lAmplitude) && isfield(PS,'AmplitudeInMilliAmps'), lAmplitude = PS.AmplitudeInMilliAmps; end
if isnan(rAmplitude) && isfield(PS,'AmplitudeInMilliAmps'), rAmplitude = PS.AmplitudeInMilliAmps; end
if isnan(lPulseWidth) && isfield(PS,'PulseWidthInMicroSecond'), lPulseWidth = PS.PulseWidthInMicroSecond; end
if isnan(rPulseWidth) && isfield(PS,'PulseWidthInMicroSecond'), rPulseWidth = PS.PulseWidthInMicroSecond; end
if isnan(rateInHertz) && isfield(PS,'RateInHertz'), rateInHertz = PS.RateInHertz; end
% Optional: SensingChannel fallback for rate, amp, pw (rare)
if isfield(PS,'SensingChannel')
sc = PS.SensingChannel;
if isstruct(sc) && numel(sc) >= 1
if isfield(sc(1),'RateInHertz') && isnan(rateInHertz), rateInHertz = sc(1).RateInHertz; end
if isfield(sc(1),'SuspendAmplitudeInMilliAmps')
if isnan(lAmplitude) && isnan(rAmplitude)
lAmplitude = sc(1).SuspendAmplitudeInMilliAmps;
rAmplitude = sc(1).SuspendAmplitudeInMilliAmps;
end
end
if isfield(sc(1),'PulseWidthInMicroSecond') && isnan(lPulseWidth) && isnan(rPulseWidth)
lPulseWidth = sc(1).PulseWidthInMicroSecond;
rPulseWidth = sc(1).PulseWidthInMicroSecond;
end
end
end
% Soft Start/Stop
sss_status = false; sss_duration = NaN;
if isfield(groupSettings,'SoftStartStop')
sss = groupSettings.SoftStartStop;
if isfield(sss,'Enabled'), sss_status = logical(sss.Enabled); end
if isfield(sss,'DurationInSeconds'), sss_duration = sss.DurationInSeconds; end
end
% Cycling
cycling_status = false; cycling_on = NaN; cycling_off = NaN;
if isfield(groupSettings,'Cycling')
cyc = groupSettings.Cycling;
if isfield(cyc,'Enabled'), cycling_status = logical(cyc.Enabled); end
if isfield(cyc,'OnDurationInMilliSeconds'), cycling_on = cyc.OnDurationInMilliSeconds/1e3; end
if isfield(cyc,'OffDurationInMilliSeconds'), cycling_off = cyc.OffDurationInMilliSeconds/1e3; end
end
end
end
% -------------------------------------------------------------------------
% --- Derived durations from hours (device counters) ---
daysSinceImplant = timeSinceTherapy / 24;
monthsSinceImplant = daysSinceImplant / 30.4375; % average month length (therapy-on)
daysSinceFollowup = timeSinceFollowup / 24;
monthsSinceFollowup = daysSinceFollowup / 30.4375;
% ---- Build tidy row for this file ----
rec = struct( ...
'SubjectID', string(subjectID{1}), ...
'AcqLabel', string(acqLabelOut), ...
'MonthsPostImplant_Calendar', monthsPostImplant_calendar, ...
'DaysPostImplant_Calendar', daysPostImplant_calendar, ...
'RunLabel', string(runLabelOut), ...
'SessionDate', jsonSessionDate, ...
'ImplantDate', implantDate_formatted, ...
'HoursSinceImplant', timeSinceTherapy, ...
'DaysSinceImplant', daysSinceImplant, ...
'MonthsTherapyOn', monthsSinceImplant, ...
'HoursSinceFollowup', timeSinceFollowup, ...
'DaysSinceFollowup', daysSinceFollowup, ...
'MonthsSinceFollowup', monthsSinceFollowup, ...
'LeftAmplitude_mA', lAmplitude, ...
'RightAmplitude_mA', rAmplitude, ...
'LeftPulseWidth_us', lPulseWidth, ...
'RightPulseWidth_us', rPulseWidth, ...
'Rate_Hz', rateInHertz, ...
'SoftStartEnabled', logical(sss_status), ...
'SoftStartDuration_s', sss_duration, ...
'CyclingEnabled', logical(cycling_status), ...
'CyclingOn_s', cycling_on, ...
'CyclingOff_s', cycling_off, ...
'SourceFile', string(fname) ...
);
% ---- Schema-safe append to rows (prevents "dissimilar structures") ----
if isempty(rows)
rows = rec; % first row defines the schema
else
f0 = fieldnames(rows); % existing schema
f1 = fieldnames(rec); % new record fields
% Add fields missing in rec (fill with [])
missInRec = setdiff(f0, f1);
for k = 1:numel(missInRec)
rec.(missInRec{k}) = [];
end
% Add fields missing in existing rows (fill [] for all prior elems)
missInRows = setdiff(f1, f0);
if ~isempty(missInRows)
for k = 1:numel(missInRows)
[rows.(missInRows{k})] = deal([]);
end
rows = orderfields(rows, rec);
end
% Final order alignment & append
rec = orderfields(rec, rows);
rows(end+1) = rec; %#ok<SAGROW>
end
% ---------- LFP Data Extraction (Survey only) ----------
createdListBeforeSub = dir(fullfile(params.save_pathname, '**', '*'));
createdListBeforeRoot = dir(fullfile(outputPath, '*'));
if ~(hasPSD || hasTD)
fprintf('No BrainSense Survey fields found in %s.\n', fname);
if hasStreamingTD || hasStreamingPower
fprintf('Detected IndefiniteStreaming (continuous). Survey extractors will not run.\n');
end
else
prev_cwd = pwd;
if ~exist(params.save_pathname, 'dir'), mkdir(params.save_pathname); end
cd(params.save_pathname);
try
if hasPSD
params.recordingMode = 'LFPMontage';
try, extractLFPMontage(data, params); catch ME, warning('extractLFPMontage failed: %s', ME.message); end
print("PSD extracted")
end
if hasTD
params.recordingMode = 'LfpMontageTimeDomain';
params.nChannels = 6;
params.channel_map = [1 2 3 ; 4 5 6];
try, extractLFPMontageTD(data, params); catch ME, warning('extractLFPMontageTD failed: %s', ME.message); end
end
close all
catch ME
cd(prev_cwd); rethrow(ME);
end
cd(prev_cwd);
% Consolidate stray outputs created directly under Result/
createdListAfterRoot = dir(fullfile(outputPath, '*'));
beforeNames = {createdListBeforeRoot.name};
afterNames = {createdListAfterRoot.name};
newTopNames = setdiff(afterNames, beforeNames);
denyList = {'subject_summary.xlsx','subject_summary_combined.xlsx','.','..'};
for i = 1:numel(newTopNames)
nm = newTopNames{i};
if any(strcmpi(nm, denyList)), continue; end
if startsWith(nm, 'sub-','IgnoreCase',true), continue; end
src = fullfile(outputPath, nm);
dst = fullfile(params.save_pathname, nm);
if exist(dst, 'file') || exist(dst, 'dir')
[p0, b0, e0] = fileparts(dst);
dst = fullfile(p0, sprintf('%s_dupe%s', b0, e0));
end
try
movefile(src, dst);
fprintf('Moved stray output "%s" into %s\n', nm, params.save_pathname);
catch mErr
warning('Could not move "%s" to subject folder: %s', nm, mErr.message);
end
end
end
% ---------- Rename only outputs created for THIS acquisition ----------
if ~isempty(params.sessionLabel)
createdListAfterSub = dir(fullfile(params.save_pathname, '**', '*'));
beforePaths = {};
if ~isempty(createdListBeforeSub)
beforePaths = fullfile({createdListBeforeSub.folder}, {createdListBeforeSub.name});
end
afterPaths = fullfile({createdListAfterSub.folder}, {createdListAfterSub.name});
newPaths = setdiff(afterPaths, beforePaths);
hasRun = ~strcmpi(params.runLabel,'') && ~strcmpi(params.runLabel,'run-NA');
datePats = { ...
'\d{8}T\d{6}Z', '\d{8}T\d{6}', '\d{8}_\d{6}', '\d{14}', '\d{8}', ...
'\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z?', ...
'\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}Z?', ...
'\d{8}[-_]\d{2}[-_]\d{2}[-_]\d{2}' };
subPrefix = ['sub-' params.subjectID];
for i = 1:numel(newPaths)
oldFull = newPaths{i};
d = dir(oldFull);
if isempty(d) || d.isdir, continue; end
[oldFolder, oldName, oldExt] = fileparts(oldFull);
newStem = oldName;
newStem = regexprep(newStem, '[\s]+', '_');
newStem = regexprep(newStem, '^sub-[^_]+_', '');
subjEsc = regexptranslate('escape', params.subjectID);
newStem = regexprep(newStem, ['^' subjEsc '[_-]+'], '');
newStem = regexprep(newStem, '(?:^|[_-])acq-[A-Za-z0-9]+', '', 'once');
newStem = regexprep(newStem, '(?:^|[_-])run-[A-Za-z0-9]+', '', 'once');
while ~isempty(regexp(newStem, '(?:^|[_-])(acq|run)-[A-Za-z0-9]+', 'once'))
newStem = regexprep(newStem, '(?:^|[_-])acq-[A-Za-z0-9]+', '');
newStem = regexprep(newStem, '(?:^|[_-])run-[A-Za-z0-9]+', '');
end
for kp = 1:numel(datePats)
tmp = regexprep(newStem, datePats{kp}, '', 'once');
if ~strcmp(tmp, newStem), newStem = tmp; break; end
end
newStem = regexprep(newStem, '[_-]{2,}', '_');
newStem = regexprep(newStem, '^_+|_+$', '');
parts = {subPrefix};
if ~isempty(newStem), parts{end+1} = newStem; end
parts{end+1} = params.sessionLabel;
if hasRun, parts{end+1} = params.runLabel; end
newBase = strjoin(parts, '_');
newBase = regexprep(newBase, '[_-]{2,}', '_');
newName = [newBase oldExt];
if strcmp([oldName oldExt], newName), continue; end
newFull = fullfile(oldFolder, newName);
try
movefile(oldFull, newFull, 'f');
fprintf('Renamed: "%s" -> "%s"\n', [oldName oldExt], newName);
catch re
warning('Could not rename "%s": %s', [oldName oldExt], re.message);
end
end
end
end
% ---------- Write one tidy spreadsheet (one row per JSON/acq) ----------
if isempty(rows)
warning('No rows collected. Nothing to write.');
else
Tidy = struct2table(rows);
% Column order to show in the sheet:
order = {'SubjectID','AcqLabel','MonthsPostImplant_Calendar','DaysPostImplant_Calendar','RunLabel', ...
'SessionDate','ImplantDate', ...
'HoursSinceImplant','DaysSinceImplant','MonthsTherapyOn', ...
'HoursSinceFollowup','DaysSinceFollowup','MonthsSinceFollowup', ...
'LeftAmplitude_mA','RightAmplitude_mA', ...
'LeftPulseWidth_us','RightPulseWidth_us','Rate_Hz', ...
'SoftStartEnabled','SoftStartDuration_s', ...
'CyclingEnabled','CyclingOn_s','CyclingOff_s', ...
'SourceFile'};
present = intersect(order, Tidy.Properties.VariableNames, 'stable');
Tidy = Tidy(:, present);
if ~exist(masterOutputPath,'dir'), mkdir(masterOutputPath); end
outXLSX = fullfile(masterOutputPath, 'subject_summary_tidy.xlsx');
outCSV = fullfile(masterOutputPath, 'subject_summary_tidy.csv');
writetable(Tidy, outXLSX);
writetable(Tidy, outCSV);
fprintf('Wrote tidy summary:\n %s\n %s\n', outXLSX, outCSV);
end