-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaDisplayTools.m
More file actions
1387 lines (1175 loc) · 60.1 KB
/
maDisplayTools.m
File metadata and controls
1387 lines (1175 loc) · 60.1 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 maDisplayTools < handle
% The code inside several of these functions was translated into matlab
% from a corresponding python file by Claude sonnet 4.5. It was then
% reviewed, edited, reorganized, and tested as needed.
properties
end
methods (Static)
%% Pattern Creation Tools
function generate_pattern_from_array(Pats, save_dir, patName, gs_val, stretch, arena_pitch)
% Create and save a pattern from array
% Main user-facing function to create a .pat file from a pattern array
%
% Args:
% Pats: 4D array (PatR, PatC, NumPatsX, NumPatsY) with pixel values
% save_dir: Directory path where pattern will be saved
% patName: Base name for the pattern file
% gs_val: (optional) Grayscale value: 2 (binary) or 16 (grayscale). Default: 16
% Legacy values 4 and 1 are also accepted for backwards compatibility.
% stretch: (optional) 2D array (NumPatsX, NumPatsY). Default: all ones
% arena_pitch: (optional) Arena pitch parameter. Default: 0
%
% The pattern array dimensions must be multiples of 16 (panel size).
% Pattern ID is automatically assigned based on existing files.
% Handle optional arguments
if nargin < 4 || isempty(gs_val)
gs_val = 16;
end
% Backwards compatibility: Convert legacy values
% Legacy: 4 meant "4-bit grayscale" → 16 (16 levels)
% Legacy: 16 meant "binary" → 2 (2 levels) [confusingly named!]
% Legacy: 1 also meant "binary" → 2
if gs_val == 4
warning('gs_val=4 is deprecated. Use gs_val=16 for grayscale patterns.');
gs_val = 16;
elseif gs_val == 1
warning('gs_val=1 is deprecated. Use gs_val=2 for binary patterns.');
gs_val = 2;
end
% Validate gs_val
if ~ismember(gs_val, [2, 16])
error('gs_val must be 2 (binary) or 16 (grayscale). Got: %d', gs_val);
end
if nargin < 5 || isempty(stretch)
stretch = ones(size(Pats, 3), size(Pats, 4), 'uint8');
end
if nargin < 6 || isempty(arena_pitch)
arena_pitch = 0;
end
% Get dimensions
[PatR, PatC, NumPatsX, NumPatsY] = size(Pats);
% Validate dimensions
if mod(PatR, 16) ~= 0
error('Number of rows (%d) must be a multiple of 16. Each panel row is 16 pixels.', PatR);
end
if mod(PatC, 16) ~= 0
error('Number of columns (%d) must be a multiple of 16. Each panel column is 16 pixels.', PatC);
end
% Validate pixel values based on gs_val
if gs_val == 2
% Binary: values must be 0 or 1
if any(Pats(:) < 0) || any(Pats(:) > 1)
error('For binary patterns (gs_val=2), pixel values must be 0 or 1');
end
elseif gs_val == 16
% Grayscale: values must be 0-15
if any(Pats(:) < 0) || any(Pats(:) > 15)
error('For grayscale patterns (gs_val=16), pixel values must be 0-15');
end
end
% Get next available ID
ID = maDisplayTools.get_pattern_id(save_dir);
% Create parameter structure
param = struct();
param.gs_val = gs_val;
param.arena_pitch = arena_pitch;
param.ID = ID;
param.px_rng = 0;
% Save the pattern
maDisplayTools.save_pattern_g4(Pats, param, stretch, save_dir, patName);
end
function save_pattern_g4(Pats, param, stretch, save_dir, filename)
% Save a pattern as a .pat binary file
% Creates a pattern structure, generates the binary data, and saves it
%
% Args:
% Pats: 4D array (PatR, PatC, NumPatsX, NumPatsY)
% param: Structure with fields gs_val, arena_pitch, ID, px_rng
% stretch: 2D array (NumPatsX, NumPatsY)
% save_dir: Directory path to save the file
% filename: Base filename (without ID prefix or extension)
% Create pattern structure
pattern = struct();
pattern.Pats = Pats;
pattern.x_num = size(Pats, 3);
pattern.y_num = size(Pats, 4);
pattern.gs_val = param.gs_val;
pattern.stretch = stretch;
pattern.param = param;
% Generate binary pattern vector for hardware
pattern.data = maDisplayTools.make_pattern_vector_g4(pattern);
% Create save directory if needed
if ~exist(save_dir, 'dir')
mkdir(save_dir);
end
% Format file name
pattern_id = param.ID;
pat_basename = sprintf('pat%04d_%s.pat', pattern_id, filename);
pat_path = fullfile(save_dir, pat_basename);
% Save .pat binary file
fid = fopen(pat_path, 'wb');
if fid == -1
error('Could not open file for writing: %s', pat_path);
end
fwrite(fid, pattern.data, 'uint8');
fclose(fid);
fprintf('Saved: %s\n', pat_path);
end
function next_id = get_pattern_id(save_dir)
% GET_PATTERN_ID Finds the next available 4-digit pattern ID
% Scans the given directory for .pat files and finds the next
% available ID. Matches files named like 'pat####.pat' or
% 'pat####_something.pat'.
%
% Args:
% save_dir (string): The directory to scan for .pat files
%
% Returns:
% next_id (int): The next available ID (starting from 1)
% Create directory if it doesn't exist
if ~exist(save_dir, 'dir')
mkdir(save_dir);
end
taken_ids = [];
% Get all .pat files in directory
files = dir(fullfile(save_dir, '*.pat'));
for i = 1:length(files)
filename = files(i).name;
% Match "pat" followed by 4 digits, then either "_" or ".pat"
% Pattern: pat####_ or pat####.pat
tokens = regexp(filename, '^pat(\d{4})(?:_|\.pat)', 'tokens', 'ignorecase');
if isempty(tokens)
error('File ''%s'' does not match expected pattern ''pat####[_...].pat''', filename);
end
% Extract the ID from the first match
id_str = tokens{1}{1};
taken_ids = [taken_ids, str2double(id_str)];
end
if isempty(taken_ids)
next_id = 1;
else
next_id = max(taken_ids) + 1;
end
end
function pat_vector = make_pattern_vector_g4(pattern)
% MAKE_PATTERN_VECTOR_G4 Generate binary pattern vector for G4 hardware
% Takes in a pattern structure with fields:
% - Pats: 4D array (PatR, PatC, NumPatsX, NumPatsY)
% - stretch: 2D array (NumPatsX, NumPatsY)
% - gs_val: grayscale value (2 for binary, 16 for grayscale)
% - generation_id: (optional) Generation ID for V2 header
% - arena_id: (optional) Arena config ID for V2 header
%
% Returns:
% - pat_vector: 1D uint8 array with header and all encoded frames
Pats = pattern.Pats; % shape: (PatR, PatC, NumPatsX, NumPatsY)
stretch = pattern.stretch;
gs_val = pattern.gs_val; % Should be 2 or 16
[PatR, PatC, NumPatsX, NumPatsY] = size(Pats);
RowN = PatR / 16;
ColN = PatC / 16;
% Check for V2 header fields
if isfield(pattern, 'generation_id') && isfield(pattern, 'arena_id')
% Use V2 header with generation and arena metadata
header = write_g4_header_v2(NumPatsX, NumPatsY, gs_val, RowN, ColN, ...
pattern.generation_id, pattern.arena_id);
else
% Use V1 header (legacy format)
header = write_g4_header_v2(NumPatsX, NumPatsY, gs_val, RowN, ColN);
end
pat_vector = header(:); % Ensure column vector
for j = 1:NumPatsY
for i = 1:NumPatsX
frame = squeeze(Pats(:, :, i, j));
stretch_val = stretch(i, j);
% Validate and cap stretch values based on mode
if gs_val == 16
% Grayscale mode
stretch_val = min(stretch_val, 20);
elseif gs_val == 2
% Binary mode
stretch_val = min(stretch_val, 107);
else
error('Invalid gs_val');
end
% Call appropriate encoder based on mode
if gs_val == 16
frameOut = maDisplayTools.make_framevector_gs16(frame, stretch_val);
elseif gs_val == 2
frameOut = maDisplayTools.make_framevector_binary(frame, stretch_val);
end
pat_vector = [pat_vector; uint8(frameOut(:))];
end
end
end
function convertedPatternData = make_framevector_gs16(framein, stretch)
% MAKE_FRAMEVECTOR_GS16 Encode a 2D frame into hardware format
% This is the inverse of decode_framevector_gs16
% Encodes a grayscale frame with 4 bits per pixel (values 0-15)
%
% Parameters:
% - framein: 2D array of shape (dataRow, dataCol) with values 0-15
% - stretch: optional int (0 or 1), default is 0
%
% Returns:
% - 1D uint8 array encoded for hardware (33 bytes per subpanel message)
if nargin < 2
stretch = 0;
end
[dataRow, dataCol] = size(framein);
numSubpanel = 4;
subpanelMsgLength = 33;
idGrayScale16 = 1;
panelCol = dataCol / 16;
panelRow = dataRow / 16;
outputVectorLength = (panelCol * subpanelMsgLength + 1) * panelRow * numSubpanel;
convertedPatternData = zeros(outputVectorLength, 1, 'uint8');
stretch = uint8(stretch);
n = 1; % MATLAB uses 1-based indexing
for i = 0:(panelRow-1)
for j = 1:numSubpanel
% Row header
convertedPatternData(n) = i + 1;
n = n + 1;
for k = 1:subpanelMsgLength
for m = 0:(panelCol-1)
if k == 1
convertedPatternData(n) = bitor(idGrayScale16, bitshift(stretch, 1));
n = n + 1;
else
% k ranges from 2 to 33, so (k-2) ranges from 0 to 31
% This matches Python's k-1 when Python k ranges 1-32
panelStartRowBeforeInvert = i * 16 + mod(j-1, 2) * 8 + floor((k-2) / 4);
panelStartRow = floor(panelStartRowBeforeInvert / 16) * 16 + 15 - mod(panelStartRowBeforeInvert, 16);
panelStartCol = m * 16 + floor(j / 3) * 8 + mod(k-2, 4) * 2;
% MATLAB uses 1-based indexing
tmp1 = uint8(framein(panelStartRow + 1, panelStartCol + 1));
tmp2 = uint8(framein(panelStartRow + 1, panelStartCol + 2));
if tmp1 < 0 || tmp1 > 15 || tmp2 < 0 || tmp2 > 15
error('Frame values must be >= 0 and <= 15');
end
convertedPatternData(n) = bitor(tmp1, bitshift(tmp2, 4));
n = n + 1;
end
end
end
end
end
convertedPatternData = convertedPatternData'; %Transpose for compatibility with panelsController
end
function convertedPatternData = make_framevector_binary(framein, stretch)
% MAKE_FRAMEVECTOR_BINARY Encode a 2D frame into hardware format (binary)
% Encodes a binary frame with 1 bit per pixel (values 0-1)
% Uses 8x8 addressing: each data byte encodes one row of 8 pixels
%
% Parameters:
% - framein: 2D array of shape (dataRow, dataCol) with values 0-1
% - stretch: optional int (default 0), controls frame display duration
%
% Returns:
% - 1D uint8 array encoded for hardware (9 bytes per subpanel message)
%
% Note: This implementation matches the original C code (make_framevector_gs2.c)
% which uses 8x8 addressing (8 rows of 8 pixels each = 64 pixels per subpanel).
if nargin < 2
stretch = 0;
end
[dataRow, dataCol] = size(framein);
numSubpanel = 4;
subpanelMsgLength = 9; % Binary uses 9 bytes per subpanel
idBinary = 0; % Binary mode identifier
panelCol = dataCol / 16;
panelRow = dataRow / 16;
outputVectorLength = (panelCol * subpanelMsgLength + 1) * panelRow * numSubpanel;
convertedPatternData = zeros(outputVectorLength, 1, 'uint8');
stretch = uint8(stretch);
n = 1; % MATLAB uses 1-based indexing
for i = 0:(panelRow-1)
for j = 1:numSubpanel
% Row header
convertedPatternData(n) = i + 1;
n = n + 1;
for k = 1:subpanelMsgLength
for m = 0:(panelCol-1)
if k == 1
% Command byte: binary mode ID with stretch value
convertedPatternData(n) = bitor(idBinary, bitshift(stretch, 1));
n = n + 1;
else
% Each data byte (k=2 to 9) encodes ONE row of 8 pixels
% This is 8x8 addressing: 8 bytes × 8 pixels = 64 pixels
row_offset = k - 2; % 0-7 (which row within the 8x8 subpanel)
% Calculate row position
panelStartRowBeforeInvert = i * 16 + mod(j-1, 2) * 8 + row_offset;
panelStartRow = floor(panelStartRowBeforeInvert / 16) * 16 + 15 - mod(panelStartRowBeforeInvert, 16);
% Calculate base column for this subpanel
panelStartCol = m * 16 + floor(j / 3) * 8;
% Pack 8 consecutive pixels from this row into one byte
byte_val = uint8(0);
for p = 0:7 % 8 pixels (columns) in this row
pixel_val = framein(panelStartRow + 1, panelStartCol + p + 1);
if pixel_val < 0 || pixel_val > 1
error('Frame values must be 0 or 1 for binary patterns');
end
% Pack bit into byte
if pixel_val == 1
byte_val = bitor(byte_val, bitshift(1, p));
end
end
convertedPatternData(n) = byte_val;
n = n + 1;
end
end
end
end
end
convertedPatternData = convertedPatternData'; %Transpose for compatibility with panelsController
end
function bytes = pack_uint16_le(val)
% PACK_UINT16_LE Pack unsigned 16-bit int as little-endian bytes
% Takes in a uint16 value and returns a 1x2 uint8 array
% representing the little-endian byte representation
bytes = typecast(uint16(val), 'uint8');
% Ensure it's in row vector format
if size(bytes, 1) > size(bytes, 2)
bytes = bytes';
end
end
%% Experiment Creation Tools
function create_experiment_folder_g41(yaml_file_path, experiment_folder_path)
% CREATE_EXPERIMENT_FOLDER_G41 Create experiment folder with renumbered patterns from YAML
% *This function was translated from a functionally identical python
% function by Claude AI, model Sonnet 4.5, and then adjusted for
% accuracy. Updated to include pattern dimension validation.
%
% This function reads a YAML experiment protocol file, validates that all
% patterns match the arena dimensions, collects all patterns in order, assigns
% sequential IDs, renames them, and saves everything in the experiment folder.
%
% INPUTS:
% yaml_file_path - Path to the YAML experiment protocol file (string or char)
% experiment_folder_path - Path where experiment folder should be created (string or char)
%
% YAML LIBRARY REQUIREMENT:
% This function requires the 'yaml' package by Martin Koch
% Available on File Exchange: https://www.mathworks.com/matlabcentral/fileexchange/106765-yaml
% Install via MATLAB Add-On Explorer or download from File Exchange
%
% EXAMPLES:
% % Create experiment folder from YAML file
% create_experiment_folder_g41('experiment.yaml', './my_experiment');
%
% % Using full paths
% create_experiment_folder_g41('/path/to/experiment.yaml', '/path/to/experiment_folder');
%
% The function will:
% 1. Read the YAML file
% 2. Extract arena dimensions from the YAML
% 3. Collect all pattern paths (checking 'include' flags)
% 4. Validate that all patterns match the arena dimensions
% 5. Remove duplicates while preserving order
% 6. Copy patterns to experiment folder with sequential IDs
% 7. Update pattern paths in the YAML file copy
% 8. Save the updated YAML in the experiment folder
% Convert to char if string
if isstring(yaml_file_path)
yaml_file_path = char(yaml_file_path);
end
if isstring(experiment_folder_path)
experiment_folder_path = char(experiment_folder_path);
end
% Validate YAML file exists
if ~isfile(yaml_file_path)
error('YAML file not found: %s', yaml_file_path);
end
% Load YAML file
fprintf('Reading YAML file: %s\n', yaml_file_path);
experiment_data = yaml.loadFile(yaml_file_path);
% Extract arena dimensions
if ~isfield(experiment_data, 'arena_info')
error('YAML file missing ''arena_info'' section');
end
arena_info = experiment_data.arena_info;
if ~isfield(arena_info, 'num_rows') || ~isfield(arena_info, 'num_cols')
error('''arena_info'' must contain ''num_rows'' and ''num_cols''');
end
expected_rows = arena_info.num_rows;
expected_cols = arena_info.num_cols;
% Create experiment folder if it doesn't exist
if ~isfolder(experiment_folder_path)
mkdir(experiment_folder_path);
fprintf('Created experiment folder: %s\n', experiment_folder_path);
else
fprintf('Experiment folder exists: %s\n', experiment_folder_path);
end
% Collect pattern paths in order
pattern_paths = maDisplayTools.collect_pattern_paths(experiment_data);
% Remove duplicates while preserving order
[unique_patterns, ~, ~] = unique(pattern_paths, 'stable');
fprintf('\nFound %d total patterns and %d unique patterns\n', ...
length(pattern_paths), length(unique_patterns));
% Validate all patterns match arena dimensions
maDisplayTools.validate_all_patterns(unique_patterns, expected_rows, expected_cols);
fprintf('✓ All patterns validated successfully\n');
% Copy and rename patterns
old_paths = cell(length(unique_patterns), 1);
new_names = cell(length(unique_patterns), 1);
for idx = 1:length(unique_patterns)
old_pattern_path = unique_patterns{idx};
% Get old filename
[~, old_name, old_ext] = fileparts(old_pattern_path);
old_filename = [old_name, old_ext];
% Generate new filename
new_filename = maDisplayTools.generate_new_filename(old_filename, idx);
new_file_path = fullfile(experiment_folder_path, new_filename);
% Copy the file
copyfile(old_pattern_path, new_file_path);
fprintf('Copied: %s -> %s\n', old_filename, new_filename);
% Store mapping
old_paths{idx} = old_pattern_path;
new_names{idx} = new_filename;
end
% Create pattern mapping structure
mappings = cell(length(old_paths), 1);
for idx = 1:length(old_paths)
mappings{idx} = struct('original', old_paths{idx}, 'renamed', new_names{idx});
end
pattern_mapping.description = 'Mapping of original pattern paths to renamed pattern files';
pattern_mapping.mappings = mappings;
% Add pattern mapping to experiment data
experiment_data.pattern_mapping = pattern_mapping;
% Update pattern paths in the YAML data
experiment_data = maDisplayTools.update_pattern_paths_in_yaml(experiment_data, old_paths, new_names);
% Save updated YAML to experiment folder
[~, yaml_name, yaml_ext] = fileparts(yaml_file_path);
yaml_output_path = fullfile(experiment_folder_path, [yaml_name, yaml_ext]);
yaml.dumpFile(yaml_output_path, experiment_data, "block");
fprintf('\nSaved updated YAML file: %s\n', yaml_output_path);
fprintf('\nExperiment folder setup complete!\n');
end
function pattern_paths = collect_pattern_paths(experiment_data)
% Collect all pattern paths from YAML in order
%
% INPUTS:
% experiment_data - Parsed YAML data structure
%
% OUTPUTS:
% pattern_paths - Cell array of pattern file paths as char vectors in order
pattern_paths = {};
% Check pretrial
if isfield(experiment_data, 'pretrial') && ...
isfield(experiment_data.pretrial, 'include') && ...
experiment_data.pretrial.include
if ~isempty(experiment_data.pretrial.commands)
for c = 1:length(experiment_data.pretrial.commands)
if isfield(experiment_data.pretrial.commands{c}, 'pattern') && ...
~isempty(experiment_data.pretrial.commands{c}.pattern)
pattern_paths{end+1} = char(experiment_data.pretrial.commands{c}.pattern);
end
end
end
end
% Check block conditions
if isfield(experiment_data, 'block') && ...
isfield(experiment_data.block, 'conditions')
conditions = experiment_data.block.conditions;
for idx = 1:length(conditions)
condition = conditions{idx};
if isfield(condition, 'commands') && ~isempty(condition.commands)
for c = 1:length(condition.commands)
if isfield(condition.commands{c}, 'pattern') && ...
~isempty(condition.commands{c}.pattern)
pattern_paths{end+1} = char(condition.commands{c}.pattern);
end
end
end
end
end
% Check intertrial
if isfield(experiment_data, 'intertrial') && ...
isfield(experiment_data.intertrial, 'include') && ...
experiment_data.intertrial.include
if isfield(experiment_data.intertrial, 'commands') && ...
~isempty(experiment_data.intertrial.commands)
for c = 1:length(experiment_data.intertrial.commands)
if isfield(experiment_data.intertrial.commands{c}, 'pattern') && ...
~isempty(experiment_data.intertrial.commands{c}.pattern)
pattern_paths{end+1} = char(experiment_data.intertrial.commands{c}.pattern);
end
end
end
end
% Check posttrial
if isfield(experiment_data, 'posttrial') && ...
isfield(experiment_data.posttrial, 'include') && ...
experiment_data.posttrial.include
if isfield(experiment_data.posttrial, 'commands') && ...
~isempty(experiment_data.posttrial.commands)
for c = 1:length(experiment_data.posttrial.commands)
if isfield(experiment_data.posttrial.commands{c}, 'pattern') && ...
~isempty(experiment_data.posttrial.commands{c}.pattern)
pattern_paths{end+1} = char(experiment_data.posttrial.commands{c}.pattern);
end
end
end
end
end
function new_filename = generate_new_filename(old_filename, new_id)
% GENERATE_NEW_FILENAME Generate new pattern filename with updated ID
%
% INPUTS:
% old_filename - Original pattern filename (e.g., 'pat0005_motion.pat')
% new_id - New ID number to assign (e.g., 1)
%
% OUTPUTS:
% new_filename - New filename with updated ID (e.g., 'pat0001_motion.pat')
% Remove .pat extension
if endsWith(old_filename, '.pat')
name_without_ext = old_filename(1:end-4);
else
name_without_ext = old_filename;
end
% Check if filename matches pattern: pat####_descriptiveName
pattern = '^pat(\d{4})_(.+)$';
tokens = regexp(name_without_ext, pattern, 'tokens');
if ~isempty(tokens)
% Extract descriptive name and replace ID
descriptive_name = tokens{1}{2};
new_filename = sprintf('pat%04d_%s.pat', new_id, descriptive_name);
else
% No ID number present, add it to the front
new_filename = sprintf('pat%04d_%s.pat', new_id, name_without_ext);
end
end
function experiment_data = update_pattern_paths_in_yaml(experiment_data, old_paths, new_names)
% Replace old pattern paths with new filenames in YAML
%
% INPUTS:
% experiment_data - Parsed YAML data structure
% old_paths - Cell array of original pattern paths
% new_names - Cell array of new pattern filenames
%
% OUTPUTS:
% experiment_data - Updated YAML data structure with new pattern paths
% Create lookup map
path_map = containers.Map(old_paths, new_names);
%% TODO: Needs re-factoring - assumes only one command per trial has a pattern
% but doesn't confirm this, so could cause issues if someone
% gave two controller commands with patterns in one trial.
% Update pretrial
if isfield(experiment_data, 'pretrial') && ...
isfield(experiment_data.pretrial, 'include') && ...
experiment_data.pretrial.include
if ~isempty(experiment_data.pretrial.commands)
old_path = '';
c = 1;
%get index of command in command list that has a
%pattern - assuming only one
while c < length(experiment_data.pretrial.commands) && ...
~isfield(experiment_data.pretrial.commands{c}, 'pattern')
c = c + 1;
end
if isfield(experiment_data.pretrial.commands{c}, 'pattern') && ...
~isempty(experiment_data.pretrial.commands{c}.pattern)
old_path = experiment_data.pretrial.commands{c}.pattern;
end
if isKey(path_map, old_path)
experiment_data.pretrial.commands{c}.pattern = path_map(old_path);
end
end
end
% Update block conditions
if isfield(experiment_data, 'block') && ...
isfield(experiment_data.block, 'conditions')
conditions = experiment_data.block.conditions;
for idx = 1:length(conditions)
condition = conditions{idx};
if isfield(condition, 'commands') && ~isempty(condition.commands)
old_path = '';
c = 1;
%get index of command in command list that has a
%pattern - assuming only one
while c < length(condition.commands) && ...
~isfield(condition.commands{c}, 'pattern')
c = c + 1;
end
if isfield(condition.commands{c}, 'pattern') && ...
~isempty(condition.commands{c}.pattern)
old_path = condition.commands{c}.pattern;
end
if isKey(path_map, old_path)
experiment_data.block.conditions{idx}.commands{c}.pattern = path_map(old_path);
end
end
end
end
% Update intertrial
if isfield(experiment_data, 'intertrial') && ...
isfield(experiment_data.intertrial, 'include') && ...
experiment_data.intertrial.include
if isfield(experiment_data.intertrial, 'commands') && ...
~isempty(experiment_data.intertrial.commands)
old_path = '';
c = 1;
%get index of command in command list that has a
%pattern - assuming only one
while c < length(experiment_data.intertrial.commands) && ...
~isfield(experiment_data.intertrial.commands{c}, 'pattern')
c = c + 1;
end
if isfield(experiment_data.intertrial.commands{c}, 'pattern') && ...
~isempty(experiment_data.intertrial.commands{c}.pattern)
old_path = experiment_data.intertrial.commands{c}.pattern;
end
if isKey(path_map, old_path)
experiment_data.intertrial.commands{c}.pattern = path_map(old_path);
end
end
end
% Update posttrial
if isfield(experiment_data, 'posttrial') && ...
isfield(experiment_data.posttrial, 'include') && ...
experiment_data.posttrial.include
if isfield(experiment_data.posttrial, 'commands') && ...
~isempty(experiment_data.posttrial.commands)
old_path = '';
c = 1;
%get index of command in command list that has a
%pattern - assuming only one
while c < length(experiment_data.posttrial.commands) && ...
~isfield(experiment_data.posttrial.commands{c}, 'pattern')
c = c + 1;
end
if isfield(experiment_data.posttrial.commands{c}, 'pattern') && ...
~isempty(experiment_data.posttrial.commands{c}.pattern)
old_path = experiment_data.posttrial.commands{c}.pattern;
end
if isKey(path_map, old_path)
experiment_data.posttrial.commands{c}.pattern = path_map(old_path);
end
end
end
end
function validate_all_patterns(pattern_paths, expected_rows, expected_cols)
% VALIDATE_ALL_PATTERNS Validate that all patterns match expected arena dimensions
%
% INPUTS:
% pattern_paths - Cell array of pattern file paths
% expected_rows - Expected number of panel rows
% expected_cols - Expected number of panel columns
%
% Raises an error if any pattern has mismatched dimensions or if a pattern
% file is not found.
mismatches = {};
for idx = 1:length(pattern_paths)
pattern_path = pattern_paths{idx};
try
[is_valid, error_msg] = maDisplayTools.validate_pattern_dimensions( ...
pattern_path, expected_rows, expected_cols);
if ~is_valid
mismatches{end+1} = error_msg; %#ok<AGROW>
end
catch ME
% Handle FileNotFound or ReadFailed errors
if strcmp(ME.identifier, 'maDisplayTools:FileNotFound')
[~, name, ext] = fileparts(pattern_path);
filename = [name, ext];
mismatches{end+1} = sprintf('Pattern file not found: %s', filename); %#ok<AGROW>
elseif strcmp(ME.identifier, 'maDisplayTools:ReadFailed')
mismatches{end+1} = ME.message; %#ok<AGROW>
else
rethrow(ME);
end
end
end
if ~isempty(mismatches)
error_message = sprintf('\nPattern dimension validation failed:\n');
for idx = 1:length(mismatches)
error_message = [error_message, sprintf(' - %s\n', mismatches{idx})]; %#ok<AGROW>
end
error('create_experiment_folder_g41:ValidationFailed', '%s', error_message);
end
end
%% Pattern Loading and Decoding
function [img, stretch] = decode_framevector_gs16(framevec, rows, cols)
% DECODE_FRAMEVECTOR_GS16 Decode a grayscale (4-bit) frame vector
% Takes in framevec (1D uint8 array for a single frame), pixel height
% and width of arena. Returns 2D uint8 image of shape (rows, cols)
% and the stretch value for this frame.
%
% This is the inverse of make_framevector_gs16.
numSubpanel = 4;
subpanelMsgLength = 33;
panelCol = cols / 16;
panelRow = rows / 16;
img = zeros(rows, cols, 'uint8');
stretch = 0; % Will be extracted from first command byte
stretchExtracted = false;
n = 1; % MATLAB uses 1-based indexing
for i = 0:(panelRow-1)
for j = 1:numSubpanel
n = n + 1; % Skip row header
for k = 1:subpanelMsgLength
for m = 0:(panelCol-1)
if k == 1
% Extract stretch from first command byte
if ~stretchExtracted
cmd_byte = framevec(n);
stretch = bitshift(cmd_byte, -1); % stretch is in bits 1-7
stretchExtracted = true;
end
n = n + 1; % Skip command byte
else
byte = framevec(n);
n = n + 1;
tmp1 = bitand(byte, 15);
tmp2 = bitand(bitshift(byte, -4), 15);
% k ranges from 2 to 33, so (k-2) ranges from 0 to 31
% This matches the encoder and Python implementation
panelStartRowBeforeInvert = i * 16 + mod(j-1, 2) * 8 + floor((k-2) / 4);
panelStartRow = floor(panelStartRowBeforeInvert / 16) * 16 + 15 - mod(panelStartRowBeforeInvert, 16);
panelStartCol = m * 16 + floor(j / 3) * 8 + mod(k-2, 4) * 2;
% MATLAB uses 1-based indexing
img(panelStartRow + 1, panelStartCol + 1) = tmp1;
img(panelStartRow + 1, panelStartCol + 2) = tmp2;
end
end
end
end
end
%fprintf('img shape: %d x %d\n', size(img, 1), size(img, 2));
end
function [img, stretch] = decode_framevector_binary(framevec, rows, cols)
% DECODE_FRAMEVECTOR_BINARY Decode a binary (1-bit) frame vector
% Similar to gs16 but processes 1 bit per pixel instead of 4 bits.
% Takes in framevec (1D uint8 array for a single frame), pixel height
% and width of arena. Returns 2D uint8 image of shape (rows, cols)
% and the stretch value for this frame.
numSubpanel = 4;
subpanelMsgLength = 9; % 1 command + 8 row-bytes
panelCol = cols / 16;
panelRow = rows / 16;
img = zeros(rows, cols, 'uint8');
stretch = 0; % Will be extracted from first command byte
stretchExtracted = false;
n = 1; % MATLAB uses 1-based indexing
for i = 0:(panelRow-1)
for j = 1:numSubpanel
n = n + 1; % Skip row header
for k = 1:subpanelMsgLength
for m = 0:(panelCol-1)
if k == 1
% Extract stretch from first command byte
if ~stretchExtracted
cmd_byte = framevec(n);
stretch = bitshift(cmd_byte, -1); % stretch is in bits 1-7
stretchExtracted = true;
end
n = n + 1; % Skip command byte
else
byte = framevec(n);
n = n + 1;
row_offset = k - 2; % 0–7 (which row inside 8×8 block)
panelStartRowBeforeInvert = i * 16 + mod(j-1, 2) * 8 + row_offset;
panelStartRow = floor(panelStartRowBeforeInvert / 16) * 16 + 15 - mod(panelStartRowBeforeInvert, 16);
panelStartCol = m * 16 + floor(j / 3) * 8;
% For binary, each bit represents one pixel
% Process 8 pixels per byte
for p = 0:7
pixel_val = bitand(bitshift(byte, -p), 1);
col = panelStartCol + p;
row = panelStartRow;
% Bounds safety
% if row+1 <= rows && col+1 <= cols
img(row+1, col+1) = pixel_val;
% end
end
end
end
end
end
end
%fprintf('img shape: %d x %d\n', size(img, 1), size(img, 2));
end
function [frames, meta] = load_pat(filepath)
% LOAD_PAT Load and decode all frames from a .pat file
% Takes in the path to a pattern file and loads it and decodes all frames.
% Automatically detects G4 vs G6 format based on header.
%
% Returns:
% - frames: 4D array (NumPatsY, NumPatsX, rows, cols)
% - meta: Structure with pattern metadata:
% NumPatsX, NumPatsY, rows, cols, vmax, stretch (per-frame array)
% Read first few bytes to detect format
fid = fopen(filepath, 'rb');
if fid == -1
error('Could not open file: %s', filepath);
end
header_peek = fread(fid, 4, 'uint8');
fclose(fid);
% Detect G6 format: starts with "G6PT" magic bytes
% G4 format: first 2 bytes form NumPatsX (uint16)
magic = char(header_peek');
if strcmp(magic, 'G6PT')
% G6 format detected
[frames, meta] = maDisplayTools.load_pat_g6(filepath);
else
% G4 format (original)
[frames, meta] = maDisplayTools.load_pat_g4(filepath);
end
end
function [frames, meta] = load_pat_g4(filepath)
% LOAD_PAT_G4 Load G4 format .pat file
% Internal function for loading G4/G4.1/G3 pattern files.
[NumPatsX, NumPatsY, gs_val, RowN, ColN, raw, header_info] = maDisplayTools.read_header_and_raw(filepath);
% Debug output removed - info now displayed in GUI
% fprintf('G4 format: %d %d %d %d %d %d\n', NumPatsX, NumPatsY, gs_val, RowN, ColN, length(raw));
rows = RowN * 16;
cols = ColN * 16;
num_frames = NumPatsX * NumPatsY;
fsize = maDisplayTools.frame_size_bytes(RowN, ColN, gs_val);
expected = fsize * num_frames;
if length(raw) < expected
error('File too short: got %d, expected %d', length(raw), expected);
end
% Initialize 4D array: (NumPatsY, NumPatsX, rows, cols)
frames = zeros(NumPatsY, NumPatsX, rows, cols, 'uint8');
stretch_values = zeros(NumPatsY, NumPatsX, 'uint8');
frame_idx = 0;
for y = 1:NumPatsY
for x = 1:NumPatsX
vec = raw((frame_idx * fsize + 1):((frame_idx + 1) * fsize));
if gs_val == 1 || gs_val == 2
[img, stretch] = maDisplayTools.decode_framevector_binary(vec, rows, cols);
elseif gs_val == 4 || gs_val == 16
[img, stretch] = maDisplayTools.decode_framevector_gs16(vec, rows, cols);
else
error('Unsupported gs_val: %d', gs_val);
end