0001 function [redefined, redefined_epoch] = bml_redefinetrial(cfg, raw)
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021 epoch = bml_annot_table(bml_getopt(cfg,'epoch'),'epoch');
0022 t0 = bml_getopt(cfg,'t0');
0023 regularize = bml_getopt(cfg,'regularize',false);
0024 warn = bml_getopt(cfg,'warn',true);
0025
0026 if regularize
0027 keyboard
0028 end
0029
0030 if ~isempty(t0)
0031 if isstring(t0) || ischar(t0)
0032 t0 = cellstr(t0);
0033 end
0034
0035 if iscellstr(t0)
0036 assert(numel(t0)==1,"single t0 variable required");
0037 if ismember(t0,epoch.Properties.VariableNames)
0038 t0 = epoch.(t0{1});
0039 else
0040 error("t0 doesn't match any variable in epoch");
0041 end
0042 end
0043
0044 if isnumeric(t0)
0045 assert(length(t0)==height(epoch),"incorrect length for t0");
0046 else
0047 error("t0 should be a numeric vector, or be the name of a numeric variable in epoch");
0048 end
0049 end
0050
0051
0052 redefined = [];
0053 redefined.trial = {};
0054 redefined.time = {};
0055 redefined_epoch = table();
0056 redefined.label = raw.label;
0057 if ismember('hdr',fields(raw))
0058 redefined.hdr = raw.hdr;
0059 end
0060
0061
0062 raw_trial = bml_annot_table(bml_raw2annot(raw),'raw');
0063 raw_trial.midpoint = (raw_trial.starts + raw_trial.ends)/2;
0064
0065
0066 for i=1:height(epoch)
0067
0068
0069 new_row = epoch(i,:);
0070 i_raw_trial = bml_annot_intersect(struct('keep','x'),raw_trial,epoch(i,:));
0071
0072
0073 if isempty(i_raw_trial)
0074 if warn
0075 warning("epoch
0076 end
0077 continue
0078 end
0079
0080
0081 if height(i_raw_trial)>1
0082 max_duration=max(i_raw_trial.duration);
0083 i_raw_trial = i_raw_trial(i_raw_trial.duration == max_duration,:);
0084 [~,min_i]=min(abs((i_raw_trial.starts+i_raw_trial.ends)/2 - i_raw_trial.midpoint));
0085 i_raw_trial = i_raw_trial(min_i,:);
0086
0087
0088
0089 end
0090
0091
0092 if (epoch.duration(i) > i_raw_trial.duration) && warn
0093 warning('partial epoch %i loaded',i);
0094 end
0095
0096 new_row.starts = i_raw_trial.starts;
0097 new_row.ends = i_raw_trial.ends;
0098
0099
0100 [s,e]=bml_crop_idx(i_raw_trial,i_raw_trial.starts,i_raw_trial.ends);
0101
0102 if s < 1; s=1; end
0103 if e > i_raw_trial.nSamples; e = i_raw_trial.nSamples; end
0104
0105
0106 new_row.id = numel(redefined.trial) + 1;
0107 redefined.trial{new_row.id} = raw.trial{i_raw_trial.raw_id}(:,s:e);
0108 redefined.time{new_row.id} = raw.time{i_raw_trial.raw_id}(:,s:e);
0109 redefined_epoch = [redefined_epoch; new_row];
0110
0111
0112
0113 if ~isempty(t0)
0114 redefined.time{new_row.id} = redefined.time{new_row.id} - t0(i);
0115 end
0116
0117 end
0118
0119
0120