plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
lcnbeapp/beapp-master
read_4d_hdr.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_4d_hdr.m
26,521
utf_8
5f0337cc99b66ec955345f869473c4f8
function [header] = read_4d_hdr(datafile, configfile) % hdr=READ_4D_HDR(datafile, configfile) % Collects the required Fieldtrip header data from the data file 'filename' % and the associated 'config' file for that data. % % Adapted from the MSI>>Matlab code written by Eugene Kronberg % Copyright (C) 2008-2009, Centre for Cognitive Neuroimaging, Glasgow, Gavin Paterson & J.M.Schoffelen % Copyright (C) 2010-2011, Donders Institute for Brain, Cognition and Behavior, J.M.Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ %read header if nargin ~= 2 [path, file, ext] = fileparts(datafile); configfile = fullfile(path, 'config'); end if ~isempty(datafile), %always big endian fid = fopen(datafile, 'r', 'b'); if fid == -1 error('Cannot open file %s', datafile); end fseek(fid, 0, 'eof'); header_end = ftell(fid); %last 8 bytes of the pdf is header offset fseek(fid, -8, 'eof'); header_offset = fread(fid,1,'uint64'); %first byte of the header fseek(fid, header_offset, 'bof'); % read header data align_file_pointer(fid) header.header_data.FileType = fread(fid, 1, 'uint16=>uint16'); file_type = char(fread(fid, 5, 'uchar'))'; header.header_data.file_type = file_type(file_type>0); fseek(fid, 1, 'cof'); format = fread(fid, 1, 'int16=>int16'); switch format case 1 header.header_data.Format = 'SHORT'; case 2 header.header_data.Format = 'LONG'; case 3 header.header_data.Format = 'FLOAT'; case 4 header.header_data.Format ='DOUBLE'; end header.header_data.acq_mode = fread(fid, 1, 'uint16=>uint16'); header.header_data.TotalEpochs = fread(fid, 1, 'uint32=>double'); header.header_data.input_epochs = fread(fid, 1, 'uint32=>uint32'); header.header_data.TotalEvents = fread(fid, 1, 'uint32=>uint32'); header.header_data.total_fixed_events = fread(fid, 1, 'uint32=>uint32'); header.header_data.SamplePeriod = fread(fid, 1, 'float32=>float64'); header.header_data.SampleFrequency = 1/header.header_data.SamplePeriod; xaxis_label = char(fread(fid, 16, 'uchar'))'; header.header_data.xaxis_label = xaxis_label(xaxis_label>0); header.header_data.total_processes = fread(fid, 1, 'uint32=>uint32'); header.header_data.TotalChannels = fread(fid, 1, 'uint16=>double'); fseek(fid, 2, 'cof'); header.header_data.checksum = fread(fid, 1, 'int32=>int32'); header.header_data.total_ed_classes = fread(fid, 1, 'uint32=>uint32'); header.header_data.total_associated_files = fread(fid, 1, 'uint16=>uint16'); header.header_data.last_file_index = fread(fid, 1, 'uint16=>uint16'); header.header_data.timestamp = fread(fid, 1, 'uint32=>uint32'); header.header_data.reserved = fread(fid, 20, 'uchar')'; fseek(fid, 4, 'cof'); %read epoch_data for epoch = 1:header.header_data.TotalEpochs; align_file_pointer(fid) header.epoch_data(epoch).pts_in_epoch = fread(fid, 1, 'uint32=>uint32'); header.epoch_data(epoch).epoch_duration = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).expected_iti = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).actual_iti = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).total_var_events = fread(fid, 1, 'uint32=>uint32'); header.epoch_data(epoch).checksum = fread(fid, 1, 'int32=>int32'); header.epoch_data(epoch).epoch_timestamp = fread(fid, 1, 'int32=>int32'); header.epoch_data(epoch).reserved = fread(fid, 28, 'uchar')'; header.header_data.SlicesPerEpoch = double(header.epoch_data(1).pts_in_epoch); %read event data (var_events) for event = 1:header.epoch_data(epoch).total_var_events align_file_pointer(fid) event_name = char(fread(fid, 16, 'uchar'))'; header.epoch_data(epoch).var_event{event}.event_name = event_name(event_name>0); header.epoch_data(epoch).var_event{event}.start_lat = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).var_event{event}.end_lat = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).var_event{event}.step_size = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).var_event{event}.fixed_event = fread(fid, 1, 'uint16=>uint16'); fseek(fid, 2, 'cof'); header.epoch_data(epoch).var_event{event}.checksum = fread(fid, 1, 'int32=>int32'); header.epoch_data(epoch).var_event{event}.reserved = fread(fid, 32, 'uchar')'; fseek(fid, 4, 'cof'); end end %read channel ref data for channel = 1:header.header_data.TotalChannels align_file_pointer(fid) chan_label = (fread(fid, 16, 'uint8=>char'))'; header.channel_data(channel).chan_label = chan_label(chan_label>0); header.channel_data(channel).chan_no = fread(fid, 1, 'uint16=>uint16'); header.channel_data(channel).attributes = fread(fid, 1, 'uint16=>uint16'); header.channel_data(channel).scale = fread(fid, 1, 'float32=>float32'); yaxis_label = char(fread(fid, 16, 'uint8=>char'))'; header.channel_data(channel).yaxis_label = yaxis_label(yaxis_label>0); header.channel_data(channel).valid_min_max = fread(fid, 1, 'uint16=>uint16'); fseek(fid, 6, 'cof'); header.channel_data(channel).ymin = fread(fid, 1, 'float64'); header.channel_data(channel).ymax = fread(fid, 1, 'float64'); header.channel_data(channel).index = fread(fid, 1, 'uint32=>uint32'); header.channel_data(channel).checksum = fread(fid, 1, 'int32=>int32'); header.channel_data(channel).whatisit = char(fread(fid, 4, 'uint8=>char'))'; header.channel_data(channel).reserved = fread(fid, 28, 'uint8')'; end %read event data for event = 1:header.header_data.total_fixed_events align_file_pointer(fid) event_name = char(fread(fid, 16, 'uchar'))'; header.event_data(event).event_name = event_name(event_name>0); header.event_data(event).start_lat = fread(fid, 1, 'float32=>float32'); header.event_data(event).end_lat = fread(fid, 1, 'float32=>float32'); header.event_data(event).step_size = fread(fid, 1, 'float32=>float32'); header.event_data(event).fixed_event = fread(fid, 1, 'uint16=>uint16'); fseek(fid, 2, 'cof'); header.event_data(event).checksum = fread(fid, 1, 'int32=>int32'); header.event_data(event).reserved = fread(fid, 32, 'uchar')'; fseek(fid, 4, 'cof'); end header.header_data.FirstLatency = double(header.event_data(1).start_lat); %experimental: read process information for np = 1:header.header_data.total_processes align_file_pointer(fid) nbytes = fread(fid, 1, 'uint32=>uint32'); fp = ftell(fid); header.process(np).hdr.nbytes = nbytes; type = char(fread(fid, 20, 'uchar'))'; header.process(np).hdr.type = type(type>0); header.process(np).hdr.checksum = fread(fid, 1, 'int32=>int32'); user = char(fread(fid, 32, 'uchar'))'; header.process(np).user = user(user>0); header.process(np).timestamp = fread(fid, 1, 'uint32=>uint32'); fname = char(fread(fid, 32, 'uchar'))'; header.process(np).filename = fname(fname>0); fseek(fid, 28*8, 'cof'); %dont know header.process(np).totalsteps = fread(fid, 1, 'uint32=>uint32'); header.process(np).checksum = fread(fid, 1, 'int32=>int32'); header.process(np).reserved = fread(fid, 32, 'uchar')'; for ns = 1:header.process(np).totalsteps align_file_pointer(fid) nbytes2 = fread(fid, 1, 'uint32=>uint32'); header.process(np).step(ns).hdr.nbytes = nbytes2; type = char(fread(fid, 20, 'uchar'))'; header.process(np).step(ns).hdr.type = type(type>0); %dont know how to interpret the first two header.process(np).step(ns).hdr.checksum = fread(fid, 1, 'int32=>int32'); userblocksize = fread(fid, 1, 'int32=>int32'); %we are at 32 bytes here header.process(np).step(ns).userblocksize = userblocksize; fseek(fid, nbytes2 - 32, 'cof'); if strcmp(header.process(np).step(ns).hdr.type, 'PDF_Weight_Table'), warning('reading in weight table: no warranty that this is correct. it seems to work for the Glasgow 248-magnetometer system. if you have some code yourself, and/or would like to test it on your own data, please contact Jan-Mathijs'); tmpfp = ftell(fid); tmp = fread(fid, 1, 'uint8'); Nchan = fread(fid, 1, 'uint32'); Nref = fread(fid, 1, 'uint32'); for k = 1:Nref name = fread(fid, 17, 'uchar'); %strange number, but seems to be true header.process(np).step(ns).RefChan{k,1} = char(name(name>0))'; end fseek(fid, 152, 'cof'); for k = 1:Nchan name = fread(fid, 17, 'uchar'); header.process(np).step(ns).Chan{k,1} = char(name(name>0))'; end %fseek(fid, 20, 'cof'); %fseek(fid, 4216, 'cof'); header.process(np).step(ns).stuff1 = fread(fid, 4236, 'uint8'); name = fread(fid, 16, 'uchar'); header.process(np).step(ns).Creator = char(name(name>0))'; %some stuff I don't understand yet %fseek(fid, 136, 'cof'); header.process(np).step(ns).stuff2 = fread(fid, 136, 'uint8'); %now something strange is going to happen: the weights are probably little-endian encoded. %here we go: check whether this applies to the whole PDF weight table fp = ftell(fid); fclose(fid); fid = fopen(datafile, 'r', 'l'); fseek(fid, fp, 'bof'); for k = 1:Nchan header.process(np).step(ns).Weights(k,:) = fread(fid, 23, 'float32=>float32')'; fseek(fid, 36, 'cof'); end else if userblocksize < 1e6, %for one reason or another userblocksize can assume strangely high values fseek(fid, userblocksize, 'cof'); end end end end fclose(fid); end %end read header %read config file fid = fopen(configfile, 'r', 'b'); if fid == -1 error('Cannot open config file'); end header.config_data.version = fread(fid, 1, 'uint16=>uint16'); site_name = char(fread(fid, 32, 'uchar'))'; header.config_data.site_name = site_name(site_name>0); dap_hostname = char(fread(fid, 16, 'uchar'))'; header.config_data.dap_hostname = dap_hostname(dap_hostname>0); header.config_data.sys_type = fread(fid, 1, 'uint16=>uint16'); header.config_data.sys_options = fread(fid, 1, 'uint32=>uint32'); header.config_data.supply_freq = fread(fid, 1, 'uint16=>uint16'); header.config_data.total_chans = fread(fid, 1, 'uint16=>uint16'); header.config_data.system_fixed_gain = fread(fid, 1, 'float32=>float32'); header.config_data.volts_per_bit = fread(fid, 1, 'float32=>float32'); header.config_data.total_sensors = fread(fid, 1, 'uint16=>uint16'); header.config_data.total_user_blocks = fread(fid, 1, 'uint16=>uint16'); header.config_data.next_derived_channel_number = fread(fid, 1, 'uint16=>uint16'); fseek(fid, 2, 'cof'); header.config_data.checksum = fread(fid, 1, 'int32=>int32'); header.config_data.reserved = fread(fid, 32, 'uchar=>uchar')'; header.config.Xfm = fread(fid, [4 4], 'double'); %user blocks for ub = 1:header.config_data.total_user_blocks align_file_pointer(fid) header.user_block_data{ub}.hdr.nbytes = fread(fid, 1, 'uint32=>uint32'); type = char(fread(fid, 20, 'uchar'))'; header.user_block_data{ub}.hdr.type = type(type>0); header.user_block_data{ub}.hdr.checksum = fread(fid, 1, 'int32=>int32'); user = char(fread(fid, 32, 'uchar'))'; header.user_block_data{ub}.user = user(user>0); header.user_block_data{ub}.timestamp = fread(fid, 1, 'uint32=>uint32'); header.user_block_data{ub}.user_space_size = fread(fid, 1, 'uint32=>uint32'); header.user_block_data{ub}.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); user_space_size = double(header.user_block_data{ub}.user_space_size); if strcmp(type(type>0), 'B_weights_used'), %warning('reading in weight table: no warranty that this is correct. it seems to work for the Glasgow 248-magnetometer system. if you have some code yourself, and/or would like to test it on your own data, please contact Jan-Mathijs'); tmpfp = ftell(fid); %read user_block_data weights %there is information in the 4th and 8th byte, these might be related to the settings? version = fread(fid, 1, 'uint32'); header.user_block_data{ub}.version = version; if version==1, Nbytes = fread(fid,1,'uint32'); Nchan = fread(fid,1,'uint32'); Position = fread(fid, 32, 'uchar'); header.user_block_data{ub}.position = char(Position(Position>0))'; fseek(fid,tmpfp+user_space_size - Nbytes*Nchan, 'bof'); Ndigital = floor((Nbytes - 4*2) / 4); Nanalog = 3; %lucky guess? % how to know number of analog weights vs digital weights??? for ch = 1:Nchan % for Konstanz -- comment for others? header.user_block_data{ub}.aweights(ch,:) = fread(fid, [1 Nanalog], 'int16')'; fseek(fid,2,'cof'); % alignment header.user_block_data{ub}.dweights(ch,:) = fread(fid, [1 Ndigital], 'single=>double')'; end fseek(fid, tmpfp, 'bof'); %there is no information with respect to the channels here. %the best guess would be to assume the order identical to the order in header.config.channel_data %for the digital weights it would be the order of the references in that list %for the analog weights I would not know elseif version==2, unknown2 = fread(fid, 1, 'uint32'); Nchan = fread(fid, 1, 'uint32'); Position = fread(fid, 32, 'uchar'); header.user_block_data{ub}.position = char(Position(Position>0))'; fseek(fid, tmpfp+124, 'bof'); Nanalog = fread(fid, 1, 'uint32'); Ndigital = fread(fid, 1, 'uint32'); fseek(fid, tmpfp+204, 'bof'); for k = 1:Nchan Name = fread(fid, 16, 'uchar'); header.user_block_data{ub}.channames{k,1} = char(Name(Name>0))'; end for k = 1:Nanalog Name = fread(fid, 16, 'uchar'); header.user_block_data{ub}.arefnames{k,1} = char(Name(Name>0))'; end for k = 1:Ndigital Name = fread(fid, 16, 'uchar'); header.user_block_data{ub}.drefnames{k,1} = char(Name(Name>0))'; end header.user_block_data{ub}.dweights = fread(fid, [Ndigital Nchan], 'single=>double')'; header.user_block_data{ub}.aweights = fread(fid, [Nanalog Nchan], 'int16')'; fseek(fid, tmpfp, 'bof'); end elseif strcmp(type(type>0), 'B_E_table_used'), %warning('reading in weight table: no warranty that this is correct'); %tmpfp = ftell(fid); %fseek(fid, 4, 'cof'); %there's info here dont know how to interpret %Nx = fread(fid, 1, 'uint32'); %Nchan = fread(fid, 1, 'uint32'); %type = fread(fid, 32, 'uchar'); %don't know whether correct %header.user_block_data{ub}.type = char(type(type>0))'; %fseek(fid, 16, 'cof'); %for k = 1:Nchan % name = fread(fid, 16, 'uchar'); % header.user_block_data{ub}.name{k,1} = char(name(name>0))'; %end elseif strcmp(type(type>0), 'B_COH_Points'), tmpfp = ftell(fid); Ncoil = fread(fid, 1, 'uint32'); N = fread(fid, 1, 'uint32'); coils = fread(fid, [7 Ncoil], 'double'); header.user_block_data{ub}.pnt = coils(1:3,:)'; header.user_block_data{ub}.ori = coils(4:6,:)'; header.user_block_data{ub}.Ncoil = Ncoil; header.user_block_data{ub}.N = N; tmp = fread(fid, (904-288)/8, 'double'); header.user_block_data{ub}.tmp = tmp; %FIXME try to find out what these bytes mean fseek(fid, tmpfp, 'bof'); elseif strcmp(type(type>0), 'b_ccp_xfm_block'), tmpfp = ftell(fid); tmp1 = fread(fid, 1, 'uint32'); %tmp = fread(fid, [4 4], 'double'); %tmp = fread(fid, [4 4], 'double'); %the next part seems to be in little endian format (at least when I tried) tmp = fread(fid, 128, 'uint8'); tmp = uint8(reshape(tmp, [8 16])'); xfm = zeros(4,4); for k = 1:size(tmp,1) xfm(k) = typecast(tmp(k,:), 'double'); if abs(xfm(k))<1e-10 || abs(xfm(k))>1e10, xfm(k) = typecast(fliplr(tmp(k,:)), 'double');end end fseek(fid, tmpfp, 'bof'); %FIXME try to find out why this looks so strange elseif strcmp(type(type>0), 'b_eeg_elec_locs'), %this block contains the digitized coil and electrode positions tmpfp = ftell(fid); Npoints = user_space_size./40; for k = 1:Npoints tmp = fread(fid, 16, 'uchar'); %tmplabel = char(tmp(tmp>47 & tmp<128)'); %stick to plain ASCII % store up until the first space tmplabel = char(tmp(1:max(1,(find(tmp==0,1,'first')-1)))'); %stick to plain ASCII %if strmatch('Coil', tmplabel), % label{k} = tmplabel(1:5); %elseif ismember(tmplabel(1), {'L' 'R' 'C' 'N' 'I'}), % label{k} = tmplabel(1); %else % label{k} = ''; %end label{k} = tmplabel; tmp = fread(fid, 3, 'double'); pnt(k,:) = tmp(:)'; end % post-processing of the labels % it seems the following can happen % - a sequence of L R N C I, i.e. the coordinate system defining landmarks for k = 1:numel(label) firstletter(k) = label{k}(1); end sel = strfind(firstletter, 'LRNCI'); if ~isempty(sel) label{sel} = label{sel}(1); label{sel+1} = label{sel+1}(1); label{sel+2} = label{sel+2}(1); label{sel+3} = label{sel+3}(1); label{sel+4} = label{sel+4}(1); end % - a sequence of coil1...coil5 i.e. the localization coils for k = 1:numel(label) if strncmpi(label{k},'coil',4) label{k} = label{k}(1:5); end end % - something else: EEG electrodes? header.user_block_data{ub}.label = label(:); header.user_block_data{ub}.pnt = pnt; fseek(fid, tmpfp, 'bof'); end fseek(fid, user_space_size, 'cof'); end %channels for ch = 1:header.config_data.total_chans align_file_pointer(fid) name = char(fread(fid, 16, 'uchar'))'; header.config.channel_data(ch).name = name(name>0); %FIXME this is a very dirty fix to get the reading in of continuous headlocalization %correct. At the moment, the numbering of the hmt related channels seems to start with 1000 %which I don't understand, but seems rather nonsensical. chan_no = fread(fid, 1, 'uint16=>uint16'); if chan_no > header.config_data.total_chans, %FIXME fix the number in header.channel_data as well sel = find([header.channel_data.chan_no]== chan_no); if ~isempty(sel), chan_no = ch; header.channel_data(sel).chan_no = chan_no; header.channel_data(sel).chan_label = header.config.channel_data(ch).name; else %does not matter end end header.config.channel_data(ch).chan_no = chan_no; header.config.channel_data(ch).type = fread(fid, 1, 'uint16=>uint16'); header.config.channel_data(ch).sensor_no = fread(fid, 1, 'int16=>int16'); fseek(fid, 2, 'cof'); header.config.channel_data(ch).gain = fread(fid, 1, 'float32=>float32'); header.config.channel_data(ch).units_per_bit = fread(fid, 1, 'float32=>float32'); yaxis_label = char(fread(fid, 16, 'uchar'))'; header.config.channel_data(ch).yaxis_label = yaxis_label(yaxis_label>0); header.config.channel_data(ch).aar_val = fread(fid, 1, 'double'); header.config.channel_data(ch).checksum = fread(fid, 1, 'int32=>int32'); header.config.channel_data(ch).reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); align_file_pointer(fid) header.config.channel_data(ch).device_data.hdr.size = fread(fid, 1, 'uint32=>uint32'); header.config.channel_data(ch).device_data.hdr.checksum = fread(fid, 1, 'int32=>int32'); header.config.channel_data(ch).device_data.hdr.reserved = fread(fid, 32, 'uchar=>uchar')'; switch header.config.channel_data(ch).type case {1, 3}%meg/ref header.config.channel_data(ch).device_data.inductance = fread(fid, 1, 'float32=>float32'); fseek(fid, 4, 'cof'); header.config.channel_data(ch).device_data.Xfm = fread(fid, [4 4], 'double'); header.config.channel_data(ch).device_data.xform_flag = fread(fid, 1, 'uint16=>uint16'); header.config.channel_data(ch).device_data.total_loops = fread(fid, 1, 'uint16=>uint16'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); for loop = 1:header.config.channel_data(ch).device_data.total_loops align_file_pointer(fid) header.config.channel_data(ch).device_data.loop_data(loop).position = fread(fid, 3, 'double'); header.config.channel_data(ch).device_data.loop_data(loop).direction = fread(fid, 3, 'double'); header.config.channel_data(ch).device_data.loop_data(loop).radius = fread(fid, 1, 'double'); header.config.channel_data(ch).device_data.loop_data(loop).wire_radius = fread(fid, 1, 'double'); header.config.channel_data(ch).device_data.loop_data(loop).turns = fread(fid, 1, 'uint16=>uint16'); fseek(fid, 2, 'cof'); header.config.channel_data(ch).device_data.loop_data(loop).checksum = fread(fid, 1, 'int32=>int32'); header.config.channel_data(ch).device_data.loop_data(loop).reserved = fread(fid, 32, 'uchar=>uchar')'; end case 2%eeg header.config.channel_data(ch).device_data.impedance = fread(fid, 1, 'float32=>float32'); fseek(fid, 4, 'cof'); header.config.channel_data(ch).device_data.Xfm = fread(fid, [4 4], 'double'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; case 4%external header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); case 5%TRIGGER header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); case 6%utility header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); case 7%derived header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); case 8%shorted header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; otherwise error('Unknown device type: %d\n', header.config.channel_data(ch).type); end end fclose(fid); %end read config file header.header_data.FileDescriptor = 0; %no obvious field to take this from header.header_data.Events = 1;%no obvious field to take this from header.header_data.EventCodes = 0;%no obvious field to take this from if isfield(header, 'channel_data'), header.ChannelGain = double([header.config.channel_data([header.channel_data.chan_no]).gain]'); header.ChannelUnitsPerBit = double([header.config.channel_data([header.channel_data.chan_no]).units_per_bit]'); header.Channel = {header.config.channel_data([header.channel_data.chan_no]).name}'; header.ChannelType = double([header.config.channel_data([header.channel_data.chan_no]).type]'); %header.Channel = {header.channel_data.chan_label}'; %header.Channel = {header.channel_data([header.channel_data.index]+1).chan_label}'; header.Format = header.header_data.Format; % take the EEG labels from the channel_data, and the rest of the labels % from the config.channel_data. Some systems have overloaded MEG channel % labels, which clash with the labels in the grad-structure. This will % lead to problems in forward/inverse modelling. Use the following % convention: keep the ones from the config. % Some systems have overloaded EEG channel % labels, rather than Exxx have a human interpretable form. Use these, % to prevent a clash with the elec-structure, if present. This is a % bit clunky (because EEG is treated different from MEG), but inherent is % inherent in how the header information is organised. header.Channel(header.ChannelType==2) = {header.channel_data(header.ChannelType==2).chan_label}'; end function align_file_pointer(fid) current_position = ftell(fid); if mod(current_position, 8) ~= 0 offset = 8 - mod(current_position,8); fseek(fid, offset, 'cof'); end
github
lcnbeapp/beapp-master
decode_nifti1.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/decode_nifti1.m
3,043
utf_8
e74c0ee902019b3883dbaf1cb0ebda26
function H = decode_nifti1(blob) % DECODE_NIFTI1 is a helper function for real-time processing of MRI data % % Use as % H = decode_nifti1(blob) % % Decodes a NIFTI-1 header given as raw 348 bytes (uint8) into a Matlab structure % that matches the C struct defined in nifti1.h, with the only difference that the % variable length arrays "dim" and "pixdim" are cut off to the right size, e.g., the % "dim" entry will only contain the relevant elements: % dim[0..7]={3,64,64,18,x,x,x,x} in C would become dim=[64,64,18] in Matlab. % % WARNING: This function currently ignores endianness !!! % % See also DECODE_RES4, DECODE_NIFTI1, SAP2MATLAB % (C) 2010 S.Klanke if class(blob)~='uint8' error 'Bad type for blob' end if length(blob)~=348 error 'Blob must be exactly 348 bytes long' end % see nift1.h for information on structure H = []; magic = char(blob(345:347)); if blob(348)~=0 | magic~='ni1' & magic~='n+1' error 'Not a NIFTI-1 header!'; end H.sizeof_hdr = typecast(blob(1:4),'int32'); H.data_type = cstr2matlab(blob(5:14)); H.db_name = cstr2matlab(blob(15:32)); H.extents = typecast(blob(33:36),'int32'); H.session_error = typecast(blob(37:38),'int16'); H.regular = blob(39); H.dim_info = blob(40); dim = typecast(blob(41:56),'int16'); H.dim = dim(2:dim(1)+1); H.intent_p1 = typecast(blob(57:60),'single'); H.intent_p2 = typecast(blob(61:64),'single'); H.intent_p3 = typecast(blob(65:68),'single'); H.intent_code = typecast(blob(69:70),'int16'); H.datatype = typecast(blob(71:72),'int16'); H.bitpix = typecast(blob(73:74),'int16'); H.slice_start = typecast(blob(75:76),'int16'); pixdim = typecast(blob(77:108),'single'); H.qfac = pixdim(1); H.pixdim = pixdim(2:dim(1)+1); H.vox_offset = typecast(blob(109:112),'single'); H.scl_scope = typecast(blob(113:116),'single'); H.scl_inter = typecast(blob(117:120),'single'); H.slice_end = typecast(blob(121:122),'int16'); H.slice_code = blob(123); H.xyzt_units = blob(124); H.cal_max = typecast(blob(125:128),'single'); H.cal_min = typecast(blob(129:132),'single'); H.slice_duration = typecast(blob(133:136),'single'); H.toffset = typecast(blob(137:140),'single'); H.glmax = typecast(blob(141:144),'int32'); H.glmin = typecast(blob(145:148),'int32'); H.descrip = cstr2matlab(blob(149:228)); H.aux_file = cstr2matlab(blob(229:252)); H.qform_code = typecast(blob(253:254),'int16'); H.sform_code = typecast(blob(255:256),'int16'); quats = typecast(blob(257:280),'single'); H.quatern_b = quats(1); H.quatern_c = quats(2); H.quatern_d = quats(3); H.quatern_x = quats(4); H.quatern_y = quats(5); H.quatern_z = quats(6); trafo = typecast(blob(281:328),'single'); H.srow_x = trafo(1:4); H.srow_y = trafo(5:8); H.srow_z = trafo(9:12); %H.S = [H.srow_x; H.srow_y; H.srow_z; 0 0 0 1]; H.intent_name = cstr2matlab(blob(329:344)); H.magic = magic; function ms = cstr2matlab(cs) if cs(1)==0 ms = ''; else ind = find(cs==0); if isempty(ind) ms = char(cs)'; else ms = char(cs(1:ind(1)-1))'; end end
github
lcnbeapp/beapp-master
read_edf.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_edf.m
18,623
utf_8
005c9a5a01178dd1021b25d4b6e9b63a
function [dat] = read_edf(filename, hdr, begsample, endsample, chanindx) % READ_EDF reads specified samples from an EDF continous datafile % It neglects all trial boundaries as if the data was acquired in % non-continous mode. % Note that since FieldTrip only accommodates a single sampling rate in a % given dataset whereas edf allows specification of a sampling rate for % each channel, if there are heterogenous sampling rates then this function % will automatically choose a subset. If the last such channel is % different from the rest, the assumption will be made that it is the % annotation channel and the rest will be selected. If that is not the % case, then the largest subset of channels with a consistent sampling rate % will be chosen. To avoid this automatic selection process, the user may % specify their own choice of channels using chanindx. In this case, the % automatic selection will only occur if the user selected channels % still have heterogenous sampling rates. In this case the automatic % selection will occur amongst the user specified channels. While reading % the header the resulting channel selection decision will be stored in % hdr.orig.chansel and the contents of this field will override chanindx % during data reading. % % Use as % [hdr] = read_edf(filename); % where % filename name of the datafile, including the .edf extension % This returns a header structure with the following elements % hdr.Fs sampling frequency % hdr.nChans number of channels % hdr.nSamples number of samples per trial % hdr.nSamplesPre number of pre-trigger samples in each trial % hdr.nTrials number of trials % hdr.label cell-array with labels of each channel % hdr.orig detailled EDF header information % % Use as % [hdr] = read_edf(filename, [], chanindx); % where % filename name of the datafile, including the .edf extension % chanindx index of channels to read (optional, default is all) % Note that since % This returns a header structure with the following elements % hdr.Fs sampling frequency % hdr.nChans number of channels % hdr.nSamples number of samples per trial % hdr.nSamplesPre number of pre-trigger samples in each trial % hdr.nTrials number of trials % hdr.label cell-array with labels of each channel % hdr.orig detailled EDF header information % % Or use as % [dat] = read_edf(filename, hdr, begsample, endsample, chanindx); % where % filename name of the datafile, including the .edf extension % hdr header structure, see above % begsample index of the first sample to read % endsample index of the last sample to read % chanindx index of channels to read (optional, default is all) % This returns a Nchans X Nsamples data matrix % % Or use as % [evt] = read_edf(filename, hdr); % where % filename name of the datafile, including the .edf extension % hdr header structure, see above % This returns an Nsamples data vector of just the annotation channel % Copyright (C) 2006, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ switch nargin case 1 chanindx=[]; case 2 chanindx=[]; case 3 chanindx=begsample; case 4 end; needhdr = (nargin==1)||(nargin==3); needevt = (nargin==2); needdat = (nargin==5); if needhdr %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the header, this code is from EEGLAB's openbdf %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FILENAME = filename; % defines Seperator for Subdirectories SLASH='/'; BSLASH=char(92); cname=computer; if cname(1:2)=='PC' SLASH=BSLASH; end; fid=fopen(FILENAME,'r','ieee-le'); if fid<0 fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']); return; end; EDF.FILE.FID=fid; EDF.FILE.OPEN = 1; EDF.FileName = FILENAME; PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]); SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]); EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME)); EDF.FILE.Name = FILENAME(SPos+1:PPos-1); if SPos==0 EDF.FILE.Path = pwd; else EDF.FILE.Path = FILENAME(1:SPos-1); end; EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext]; H1=char(fread(EDF.FILE.FID,256,'char')'); % EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer %if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end; EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification %EDF.H.StartDate = H1(169:176); % 8 Byte %EDF.H.StartTime = H1(177:184); % 8 Byte EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ]; % Y2K compatibility until year 2090 if EDF.VERSION(1)=='0' if EDF.T0(1) < 91 EDF.T0(1)=2000+EDF.T0(1); else EDF.T0(1)=1900+EDF.T0(1); end; else ; % in a future version, this is hopefully not needed end; EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header % reserved = H1(193:236); % 44 Byte EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals EDF.Label = char(fread(EDF.FILE.FID,[16,EDF.NS],'char')'); EDF.Transducer = char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); EDF.PhysDim = char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'); EDF.PhysMin= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.PhysMax= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMin = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMax = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); % check validity of DigMin and DigMax if (length(EDF.DigMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n'); EDF.DigMin = -(2^15)*ones(EDF.NS,1); end if (length(EDF.DigMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n'); EDF.DigMax = (2^15-1)*ones(EDF.NS,1); end if (any(EDF.DigMin >= EDF.DigMax)) fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n'); end % check validity of PhysMin and PhysMax if (length(EDF.PhysMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n'); EDF.PhysMin = EDF.DigMin; end if (length(EDF.PhysMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n'); EDF.PhysMax = EDF.DigMax; end if (any(EDF.PhysMin >= EDF.PhysMax)) fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n'); EDF.PhysMin = EDF.DigMin; EDF.PhysMax = EDF.DigMax; end EDF.PreFilt= char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); % tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record EDF.SPR = str2num(char(tmp)); % samples per data record fseek(EDF.FILE.FID,32*EDF.NS,0); EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./(EDF.DigMax-EDF.DigMin); EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin; tmp = find(EDF.Cal < 0); EDF.Cal(tmp) = ones(size(tmp)); EDF.Off(tmp) = zeros(size(tmp)); EDF.Calib=[EDF.Off';(diag(EDF.Cal))]; %EDF.Calib=sparse(diag([1; EDF.Cal])); %EDF.Calib(1,2:EDF.NS+1)=EDF.Off'; EDF.SampleRate = EDF.SPR / EDF.Dur; EDF.FILE.POS = ftell(EDF.FILE.FID); if EDF.NRec == -1 % unknown record size, determine correct NRec fseek(EDF.FILE.FID, 0, 'eof'); endpos = ftell(EDF.FILE.FID); EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2)); fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof'); H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records end; EDF.Chan_Select=(EDF.SPR==max(EDF.SPR)); for k=1:EDF.NS if EDF.Chan_Select(k) EDF.ChanTyp(k)='N'; else EDF.ChanTyp(k)=' '; end; if findstr(upper(EDF.Label(k,:)),'ECG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EKG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EEG') EDF.ChanTyp(k)='E'; elseif findstr(upper(EDF.Label(k,:)),'EOG') EDF.ChanTyp(k)='O'; elseif findstr(upper(EDF.Label(k,:)),'EMG') EDF.ChanTyp(k)='M'; end; end; if isempty(chanindx) chanindx=[1:EDF.NS]; end; EDF.AS.spb = sum(EDF.SPR); % Samples per Block bi=[0;cumsum(EDF.SPR)]; idx=[];idx2=[]; for k=1:EDF.NS, idx2=[idx2, (k-1)*max(EDF.SPR)+(1:EDF.SPR(k))]; end; maxspr=max(EDF.SPR); idx3=zeros(EDF.NS*maxspr,1); for k=1:EDF.NS, idx3(maxspr*(k-1)+(1:maxspr))=bi(k)+ceil((1:maxspr)'/maxspr*EDF.SPR(k));end; %EDF.AS.bi=bi; EDF.AS.IDX2=idx2; %EDF.AS.IDX3=idx3; % close the file fclose(EDF.FILE.FID); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert the header to Fieldtrip-style %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if all(EDF.SampleRate(chanindx)==EDF.SampleRate(chanindx(1))) chansel=chanindx; hdr.Fs = EDF.SampleRate(chanindx(1)); hdr.nChans = length(chansel); hdr.label = cellstr(EDF.Label); hdr.label = hdr.label(chansel); % it is continuous data, therefore append all records in one trial hdr.nSamples = EDF.NRec * EDF.SPR(chansel(1)); hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.orig = EDF; % this will be used on subsequent reading of data if length(chansel) ~= EDF.NS hdr.orig.chansel = chansel; else hdr.orig.chansel = 1:hdr.nChans; end; hdr.orig.annotation = find(strcmp(cellstr(hdr.orig.Label), 'EDF Annotations')); elseif all(EDF.SampleRate(1:end-1)==EDF.SampleRate(1)) % only the last channel has a deviant sampling frequency % this is the case for EGI recorded datasets that have been converted % to EDF+, in which case the annotation channel is the last chansel = find(EDF.SampleRate==EDF.SampleRate(1)); % continue with the subset of channels that has a consistent sampling frequency hdr.Fs = EDF.SampleRate(chansel(1)); hdr.nChans = length(chansel); warning('Skipping "%s" as continuous data channel because of inconsistent sampling frequency (%g Hz)', deblank(EDF.Label(end,:)), EDF.SampleRate(end)); hdr.label = cellstr(EDF.Label); hdr.label = hdr.label(chansel); % it is continuous data, therefore append all records in one trial hdr.nSamples = EDF.NRec * EDF.SPR(chansel(1)); hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.orig = EDF; % this will be used on subsequent reading of data hdr.orig.chansel = chansel; hdr.orig.annotation = find(strcmp(cellstr(hdr.orig.Label), 'EDF Annotations')); else % select the sampling rate that results in the most channels [a, b, c] = unique(EDF.SampleRate); for i=1:length(a) chancount(i) = sum(c==i); end [dum, indx] = max(chancount); chansel = find(EDF.SampleRate == a(indx)); % continue with the subset of channels that has a consistent sampling frequency hdr.Fs = EDF.SampleRate(chansel(1)); hdr.nChans = length(chansel); hdr.label = cellstr(EDF.Label); hdr.label = hdr.label(chansel); % it is continuous data, therefore append all records in one trial hdr.nSamples = EDF.NRec * EDF.SPR(chansel(1)); hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.orig = EDF; % this will be used on subsequent reading of data hdr.orig.chansel = chansel; hdr.orig.annotation = find(strcmp(cellstr(hdr.orig.Label), 'EDF Annotations')); warning('channels with different sampling rate not supported, using a subselection of %d channels at %f Hz', length(hdr.label), hdr.Fs); end % return the header dat = hdr; elseif needdat || needevt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % retrieve the original header EDF = hdr.orig; % There can be an optional chansel field containing a list of predefined % channels. These channels are in that case also the only ones represented in % the FieldTrip header, which means that teh other channels are simply not % visible to the naive user. This field can be present because the user % specified an explicit channel selection in FT_READ_HEADER or because the % read_edf function had to automatically choose a subset to cope with % heterogenous sampling rates or even both. In any case, at this point in the % file reading process the contents of the chansel field has the proper % specification for channel selection, taking into account both the user channel % selection as well as any correction that might have been made due to % heterogenous sampling rates. if ~isempty(chanindx) && ~isfield(EDF, 'chansel') % a subset of channels should been selected from the full list of channels in the file chanindx = chanindx; % keep as it is chanSel = true; elseif ~isempty(chanindx) && isfield(EDF, 'chansel') % a subset of channels should been selected from the predefined list chanindx = EDF.chansel(chanindx); chanSel = true; elseif isempty(chanindx) && isfield(EDF, 'chansel') % all channels from the predefined list should be selected chanindx = EDF.chansel(chanindx); chanSel = true; elseif isempty(chanindx) && ~isfield(EDF, 'chansel') % simply select all channels that are present in the file chanindx = 1:EDF.NS; chanSel = false; else % the code should not end up here error('these were all four possible options') end if needevt % read the annotation channel, not the data channels chanindx = EDF.annotation; begsample = 1; endsample = EDF.SPR(end)*EDF.NRec; end if chanSel epochlength = EDF.SPR(chanindx(1)); % in samples for the selected channel blocksize = sum(EDF.SPR); % in samples for all channels chanoffset = EDF.SPR; chanoffset = round(cumsum([0; chanoffset(1:end-1)])); % get the selection from the subset of channels nchans = length(chanindx); else epochlength = EDF.SPR(1); % in samples for a single channel blocksize = sum(EDF.SPR); % in samples for all channels % use all channels nchans = EDF.NS; end % determine the trial containing the begin and end sample begepoch = floor((begsample-1)/epochlength) + 1; endepoch = floor((endsample-1)/epochlength) + 1; nepochs = endepoch - begepoch + 1; % allocate memory to hold the data dat = zeros(length(chanindx),nepochs*epochlength); % read and concatenate all required data epochs for i=begepoch:endepoch if chanSel % only a subset of channels with consistent sampling frequency is read offset = EDF.HeadLen + (i-1)*blocksize*2; % in bytes % read the complete data block buf = readLowLevel(filename, offset, blocksize); % see below in subfunction for j=1:length(chanindx) % cut out the part that corresponds with a single channel dat(j,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf((1:epochlength) + chanoffset(chanindx(j))); end elseif length(chanindx)==1 % this is more efficient if only one channel has to be read, e.g. the status channel offset = EDF.HeadLen + (i-1)*blocksize*2; % in bytes offset = offset + (chanindx-1)*epochlength*2; % read the data for a single channel buf = readLowLevel(filename, offset, epochlength); % see below in subfunction dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf; else % read the data from all channels, subsequently select the desired channels offset = EDF.HeadLen + (i-1)*blocksize*2; % in bytes % read the complete data block buf = readLowLevel(filename, offset, blocksize); % see below in subfunction buf = reshape(buf, epochlength, nchans); dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf(:,chanindx)'; end end % select the desired samples begsample = begsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped endsample = endsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped dat = dat(:, begsample:endsample); % Calibrate the data if chanSel calib = diag(EDF.Cal(chanindx)); end if length(chanindx)>1 % using a sparse matrix speeds up the multiplication dat = sparse(calib) * dat; else % in case of one channel the sparse multiplication would result in a sparse array dat = calib * dat; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for reading the 16 bit values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buf = readLowLevel(filename, offset, numwords) if offset < 2*1024^2 % use the external mex file, only works for <2GB buf = read_16bit(filename, offset, numwords); else % use plain matlab, thanks to Philip van der Broek fp = fopen(filename,'r','ieee-le'); status = fseek(fp, offset, 'bof'); if status error(['failed seeking ' filename]); end [buf,num] = fread(fp,numwords,'bit16=>double'); fclose(fp); if (num<numwords) error(['failed reading ' filename]); return end end
github
lcnbeapp/beapp-master
yokogawa2grad.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/yokogawa2grad.m
7,146
utf_8
bf4658b4bc8fd39bb57c718ba6ba3be0
function grad = yokogawa2grad(hdr) % YOKOGAWA2GRAD converts the position and weights of all coils that % compromise a gradiometer system into a structure that can be used % by FieldTrip. This implementation uses the old "yokogawa" toolbox. % % See also CTF2GRAD, BTI2GRAD, FIF2GRAD, MNE2GRAD, ITAB2GRAD, % FT_READ_SENS, FT_READ_HEADER % Copyright (C) 2005-2008, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if ~ft_hastoolbox('yokogawa') error('cannot determine whether Yokogawa toolbox is present'); end if isfield(hdr, 'label') label = hdr.label; % keep for later use end if isfield(hdr, 'orig') hdr = hdr.orig; % use the original header, not the FieldTrip header end % The "channel_info" contains % 1 channel number, zero offset % 2 channel type, type of gradiometer % 3 position x (in m) % 4 position y (in m) % 5 position z (in m) % 6 orientation of first coil (theta in deg) % 7 orientation of first coil (phi in deg) % 8 orientation from the 1st to 2nd coil for gradiometer (theta in deg) % 9 orientation from the 1st to 2nd coil for gradiometer (phi in deg) % 10 coil size (in m) % 11 baseline (in m) handles = definehandles; isgrad = (hdr.channel_info(:,2)==handles.AxialGradioMeter | ... hdr.channel_info(:,2)==handles.PlannerGradioMeter | ... hdr.channel_info(:,2)==handles.MagnetoMeter | ... hdr.channel_info(:,2)==handles.RefferenceAxialGradioMeter); % reference channels are excluded because the positions are not specified % hdr.channel_info(:,2)==handles.RefferencePlannerGradioMeter % hdr.channel_info(:,2)==handles.RefferenceMagnetoMeter isgrad_handles = hdr.channel_info(isgrad,2); ismag = (isgrad_handles(:)==handles.MagnetoMeter | isgrad_handles(:)==handles.RefferenceMagnetoMeter); grad.coilpos = hdr.channel_info(isgrad,3:5)*100; % cm grad.unit = 'cm'; % Get orientation of the 1st coil ori_1st = hdr.channel_info(find(isgrad),[6 7]); % polar to x,y,z coordinates ori_1st = ... [sin(ori_1st(:,1)/180*pi).*cos(ori_1st(:,2)/180*pi) ... sin(ori_1st(:,1)/180*pi).*sin(ori_1st(:,2)/180*pi) ... cos(ori_1st(:,1)/180*pi)]; grad.coilori = ori_1st; % Get orientation from the 1st to 2nd coil for gradiometer ori_1st_to_2nd = hdr.channel_info(find(isgrad),[8 9]); % polar to x,y,z coordinates ori_1st_to_2nd = ... [sin(ori_1st_to_2nd(:,1)/180*pi).*cos(ori_1st_to_2nd(:,2)/180*pi) ... sin(ori_1st_to_2nd(:,1)/180*pi).*sin(ori_1st_to_2nd(:,2)/180*pi) ... cos(ori_1st_to_2nd(:,1)/180*pi)]; % Get baseline baseline = hdr.channel_info(isgrad,size(hdr.channel_info,2)); % Define the location and orientation of 2nd coil info = hdr.channel_info(isgrad,2); for i=1:sum(isgrad) if (info(i) == handles.AxialGradioMeter || info(i) == handles.RefferenceAxialGradioMeter ) grad.coilpos(i+sum(isgrad),:) = [grad.coilpos(i,:)+ori_1st(i,:)*baseline(i)*100]; grad.coilori(i+sum(isgrad),:) = -ori_1st(i,:); elseif (info(i) == handles.PlannerGradioMeter || info(i) == handles.RefferencePlannerGradioMeter) grad.coilpos(i+sum(isgrad),:) = [grad.coilpos(i,:)+ori_1st_to_2nd(i,:)*baseline(i)*100]; grad.coilori(i+sum(isgrad),:) = -ori_1st(i,:); else grad.coilpos(i+sum(isgrad),:) = [0 0 0]; grad.coilori(i+sum(isgrad),:) = [0 0 0]; end end % Define the pair of 1st and 2nd coils for each gradiometer grad.tra = repmat(diag(ones(1,size(grad.coilpos,1)/2),0),1,2); % for mangetometers change tra as there is no second coil if any(ismag) sz_pnt = size(grad.coilpos,1)/2; % create logical variable not_2nd_coil = ([diag(zeros(sz_pnt),0)' ismag']~=0); grad.tra(ismag,not_2nd_coil) = 0; end % the gradiometer labels should be consistent with the channel labels in % read_yokogawa_header, the predefined list of channel names in ft_senslabel % and with ft_channelselection % ONLY consistent with read_yokogawa_header as NO FIXED relation between % channel index and type of channel exists for Yokogawa systems. Therefore % all have individual label sequences: No useful support in ft_senslabel possible if ~isempty(label) grad.label = label(isgrad); else % this is only backup, if something goes wrong above. label = cell(size(isgrad)); for i=1:length(label) label{i} = sprintf('AG%03d', i); end grad.label = label(isgrad); end grad.unit = 'cm'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % ????4.0mm???????` handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % ???a15.5mm???~?? handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % ????12.0mm???????` handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
lcnbeapp/beapp-master
read_erplabheader.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_erplabheader.m
2,048
utf_8
c72fab70eaf79706e1f1f452bc50692a
% read_erplabheader() - import ERPLAB dataset files % % Usage: % >> header = read_erplabheader(filename); % % Inputs: % filename - [string] file name % % Outputs: % header - FILEIO toolbox type structure % % Modified from read_eeglabheader %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function header = read_erplabheader(filename) if nargin < 1 help read_erplabheader; return; end; if ~isstruct(filename) load('-mat', filename); else ERP = filename; end; header.Fs = ERP.srate; header.nChans = ERP.nchan; header.nSamples = ERP.pnts; header.nSamplesPre = -ERP.xmin*ERP.srate; header.nTrials = ERP.nbin; try header.label = { ERP.chanlocs.labels }'; catch warning('creating default channel names'); for i=1:header.nChans header.label{i} = sprintf('chan%03d', i); end end ind = 1; for i = 1:length( ERP.chanlocs ) if isfield(ERP.chanlocs(i), 'X') && ~isempty(ERP.chanlocs(i).X) header.elec.label{ind, 1} = ERP.chanlocs(i).labels; % this channel has a position header.elec.pnt(ind,1) = ERP.chanlocs(i).X; header.elec.pnt(ind,2) = ERP.chanlocs(i).Y; header.elec.pnt(ind,3) = ERP.chanlocs(i).Z; ind = ind+1; end; end; header.orig = ERP;
github
lcnbeapp/beapp-master
write_plexon_nex.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/write_plexon_nex.m
9,560
utf_8
be58ed0114e68d6dffe4f005762b5db9
function write_plexon_nex(filename, nex) % WRITE_PLEXON_NEX writes a Plexon *.nex file, which is a file % containing action-potential (spike) timestamps and waveforms (spike % channels), event timestamps (event channels), and continuous variable % data (continuous A/D channels). % % Use as % write_plexon_nex(filename, nex); % % The data structure should contain % nex.hdr.FileHeader.Frequency = TimeStampFreq % nex.hdr.VarHeader.Type = type, 5 for continuous % nex.hdr.VarHeader.Name = label, padded to length 64 % nex.hdr.VarHeader.WFrequency = sampling rate of continuous channel % nex.var.dat = data % nex.var.ts = timestamps % % See also READ_PLEXON_NEX, READ_PLEXON_PLX, READ_PLEXON_DDT % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % get the optional arguments, these are all required % FirstTimeStamp = ft_getopt(varargin, 'FirstTimeStamp'); % TimeStampFreq = ft_getopt(varargin, 'TimeStampFreq'); hdr = nex.hdr; UVtoMV = 1/1000; switch hdr.VarHeader.Type case 5 dat = nex.var.dat; % this is in microVolt buf = zeros(size(dat), 'int16'); nchans = size(dat,1); nsamples = size(dat,2); nwaves = 1; % only one continuous datasegment is supported if length(hdr.VarHeader)~=nchans error('incorrect number of channels'); end % convert the data from floating point into int16 values % each channel gets its own optimal calibration factor for varlop=1:nchans ADMaxValue = double(intmax('int16')); ADMaxUV = max(abs(dat(varlop,:))); % this is in microVolt ADMaxMV = ADMaxUV/1000; % this is in miliVolt if isa(dat, 'int16') % do not rescale data that is already 16 bit MVtoAD = 1; elseif ADMaxMV==0 % do not rescale the data if the data is zero MVtoAD = 1; elseif ADMaxMV>0 % rescale the data so that it fits into the 16 bits with as little loss as possible MVtoAD = ADMaxValue / ADMaxMV; end buf(varlop,:) = int16(double(dat) * UVtoMV * MVtoAD); % remember the calibration value, it should be stored in the variable header ADtoMV(varlop) = 1/MVtoAD; end dat = buf; clear buf; case 3 dat = nex.var.dat; % this is in microVolt nchans = 1; % only one channel is supported nsamples = size(dat,1); nwaves = size(dat,2); if length(hdr.VarHeader)~=nchans error('incorrect number of channels'); end % convert the data from floating point into int16 values ADMaxValue = double(intmax('int16')); ADMaxUV = max(abs(dat(:))); % this is in microVolt ADMaxMV = ADMaxUV/1000; % this is in miliVolt if isa(dat, 'int16') % do not rescale data that is already 16 bit MVtoAD = 1; elseif ADMaxMV==0 % do not rescale the data if the data is zero MVtoAD = 1; elseif ADMaxMV>0 % rescale the data so that it fits into the 16 bits with as little loss as possible MVtoAD = ADMaxValue / ADMaxMV; end dat = int16(double(dat) * UVtoMV * MVtoAD); % remember the calibration value, it should be stored in the variable header ADtoMV = 1/MVtoAD; otherwise error('unsupported data type') end % switch type % determine the first and last timestamp ts = nex.var.ts; ts_beg = min(ts); ts_end = 0; % FIXME fid = fopen(filename, 'wb', 'ieee-le'); % write the file header write_NexFileHeader; % write the variable headers for varlop=1:nchans write_NexVarHeader; end % write the variable data for varlop=1:nchans write_NexVarData; end fclose(fid); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nested function for writing the details %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_NexFileHeader % prepare the two char buffers buf1 = padstr('$Id$', 256); buf2 = char(zeros(1, 256)); % write the stuff to the file fwrite(fid, 'NEX1' , 'char'); % NexFileHeader = string NEX1 fwrite(fid, 100 , 'int32'); % Version = version fwrite(fid, buf1 , 'char'); % Comment = comment, 256 bytes fwrite(fid, hdr.FileHeader.Frequency, 'double'); % Frequency = timestamped freq. - tics per second fwrite(fid, ts_beg, 'int32'); % Beg = usually 0, minimum of all the timestamps in the file fwrite(fid, ts_end, 'int32'); % End = maximum timestamp + 1 fwrite(fid, nchans, 'int32'); % NumVars = number of variables in the first batch fwrite(fid, 0 , 'int32'); % NextFileHeader = position of the next file header in the file, not implemented yet fwrite(fid, buf2 , 'char'); % Padding = future expansion end % of the nested function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nested function for writing the details %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_NexVarHeader filheadersize = 544; varheadersize = 208; offset = filheadersize + nchans*varheadersize + (varlop-1)*nsamples; calib = ADtoMV(varlop); % prepare the two char buffers buf1 = padstr(hdr.VarHeader(varlop).Name, 64); buf2 = char(zeros(1, 68)); % write the continuous variable to the file fwrite(fid, hdr.VarHeader.Type, 'int32'); % Type = 0 - neuron, 1 event, 2- interval, 3 - waveform, 4 - pop. vector, 5 - continuously recorded fwrite(fid, 100, 'int32'); % Version = 100 fwrite(fid, buf1, 'char'); % Name = variable name, 1x64 char fwrite(fid, offset, 'int32'); % DataOffset = where the data array for this variable is located in the file fwrite(fid, nwaves, 'int32'); % Count = number of events, intervals, waveforms or weights fwrite(fid, 0, 'int32'); % WireNumber = neuron only, not used now fwrite(fid, 0, 'int32'); % UnitNumber = neuron only, not used now fwrite(fid, 0, 'int32'); % Gain = neuron only, not used now fwrite(fid, 0, 'int32'); % Filter = neuron only, not used now fwrite(fid, 0, 'double'); % XPos = neuron only, electrode position in (0,100) range, used in 3D fwrite(fid, 0, 'double'); % YPos = neuron only, electrode position in (0,100) range, used in 3D fwrite(fid, hdr.VarHeader.WFrequency, 'double'); % WFrequency = waveform and continuous vars only, w/f sampling frequency fwrite(fid, calib, 'double'); % ADtoMV = waveform continuous vars only, coeff. to convert from A/D values to Millivolts fwrite(fid, nsamples, 'int32'); % NPointsWave = waveform only, number of points in each wave fwrite(fid, 0, 'int32'); % NMarkers = how many values are associated with each marker fwrite(fid, 0, 'int32'); % MarkerLength = how many characters are in each marker value fwrite(fid, buf2, 'char'); % Padding, 1x68 char end % of the nested function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nested function for writing the details %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_NexVarData switch hdr.VarHeader.Type case 5 % this code only supports one continuous segment index = 0; fwrite(fid, ts , 'int32'); % timestamps, one for each continuous segment fwrite(fid, index , 'int32'); % where to cut the segments, zero offset fwrite(fid, dat(varlop,:) , 'int16'); % data case 3 fwrite(fid, ts , 'int32'); % timestamps, one for each spike fwrite(fid, dat , 'int16'); % waveforms, one for each spike otherwise error('unsupported data type'); end % switch end % of the nested function end % of the primary function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction for zero padding a char array to fixed length %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = padstr(str, num) if length(str)>num str = str(1:num); else str((end+1):num) = 0; end end % of the padstr subfunction
github
lcnbeapp/beapp-master
ft_convert_units.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/ft_convert_units.m
10,207
utf_8
d3c04f1222517baf2f069d68e3dd6abe
function [obj] = ft_convert_units(obj, target, varargin) % FT_CONVERT_UNITS changes the geometrical dimension to the specified SI unit. % The units of the input object is determined from the structure field % object.unit, or is estimated based on the spatial extend of the structure, % e.g. a volume conduction model of the head should be approximately 20 cm large. % % Use as % [object] = ft_convert_units(object, target) % % The following geometrical objects are supported as inputs % electrode or gradiometer array, see FT_DATATYPE_SENS % volume conductor, see FT_DATATYPE_HEADMODEL % anatomical mri, see FT_DATATYPE_VOLUME % segmented mri, see FT_DATATYPE_SEGMENTATION % dipole grid definition, see FT_DATATYPE_SOURCE % % Possible target units are 'm', 'dm', 'cm ' or 'mm'. If no target units % are specified, this function will only determine the native geometrical % units of the object. % % See also FT_ESTIMATE_UNITS, FT_READ_VOL, FT_READ_SENS % Copyright (C) 2005-2016, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % This function consists of three parts: % 1) determine the input units % 2) determine the requested scaling factor to obtain the output units % 3) try to apply the scaling to the known geometrical elements in the input object feedback = ft_getopt(varargin, 'feedback', false); if isstruct(obj) && numel(obj)>1 % deal with a structure array for i=1:numel(obj) if nargin>1 tmp(i) = ft_convert_units(obj(i), target, varargin{:}); else tmp(i) = ft_convert_units(obj(i)); end end obj = tmp; return elseif iscell(obj) && numel(obj)>1 % deal with a cell array % this might represent combined EEG, ECoG and/or MEG for i=1:numel(obj) obj{i} = ft_convert_units(obj{i}, target, varargin{:}); end return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % determine the unit-of-dimension of the input object %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(obj, 'unit') && ~isempty(obj.unit) % use the units specified in the object unit = obj.unit; elseif isfield(obj, 'bnd') && isfield(obj.bnd, 'unit') unit = unique({obj.bnd.unit}); if ~all(strcmp(unit, unit{1})) error('inconsistent units in the individual boundaries'); else unit = unit{1}; end % keep one representation of the units rather than keeping it with each boundary % the units will be reassigned further down obj.bnd = rmfield(obj.bnd, 'unit'); else % try to determine the units by looking at the size of the object if isfield(obj, 'chanpos') && ~isempty(obj.chanpos) siz = norm(idrange(obj.chanpos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'elecpos') && ~isempty(obj.elecpos) siz = norm(idrange(obj.elecpos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'coilpos') && ~isempty(obj.coilpos) siz = norm(idrange(obj.coilpos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'pnt') && ~isempty(obj.pnt) siz = norm(idrange(obj.pnt)); unit = ft_estimate_units(siz); elseif isfield(obj, 'pos') && ~isempty(obj.pos) siz = norm(idrange(obj.pos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'transform') && ~isempty(obj.transform) % construct the corner points of the volume in voxel and in head coordinates [pos_voxel, pos_head] = cornerpoints(obj.dim, obj.transform); siz = norm(idrange(pos_head)); unit = ft_estimate_units(siz); elseif isfield(obj, 'fid') && isfield(obj.fid, 'pnt') && ~isempty(obj.fid.pnt) siz = norm(idrange(obj.fid.pnt)); unit = ft_estimate_units(siz); elseif isfield(obj, 'fid') && isfield(obj.fid, 'pos') && ~isempty(obj.fid.pos) siz = norm(idrange(obj.fid.pos)); unit = ft_estimate_units(siz); elseif ft_voltype(obj, 'infinite') % this is an infinite medium volume conductor, which does not care about units unit = 'm'; elseif ft_voltype(obj,'singlesphere') siz = obj.r; unit = ft_estimate_units(siz); elseif ft_voltype(obj,'localspheres') siz = median(obj.r); unit = ft_estimate_units(siz); elseif ft_voltype(obj,'concentricspheres') siz = max(obj.r); unit = ft_estimate_units(siz); elseif isfield(obj, 'bnd') && isstruct(obj.bnd) && isfield(obj.bnd(1), 'pnt') && ~isempty(obj.bnd(1).pnt) siz = norm(idrange(obj.bnd(1).pnt)); unit = ft_estimate_units(siz); elseif isfield(obj, 'bnd') && isstruct(obj.bnd) && isfield(obj.bnd(1), 'pos') && ~isempty(obj.bnd(1).pos) siz = norm(idrange(obj.bnd(1).pos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'nas') && isfield(obj, 'lpa') && isfield(obj, 'rpa') pnt = [obj.nas; obj.lpa; obj.rpa]; siz = norm(idrange(pnt)); unit = ft_estimate_units(siz); else error('cannot determine geometrical units'); end % recognized type of volume conduction model or sensor array end % determine input units if nargin<2 || isempty(target) % just remember the units in the output and return obj.unit = unit; return elseif strcmp(unit, target) % no conversion is needed obj.unit = unit; return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the scaling factor from the input units to the desired ones %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% scale = ft_scalingfactor(unit, target); if istrue(feedback) % give some information about the conversion fprintf('converting units from ''%s'' to ''%s''\n', unit, target) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % apply the scaling factor %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % volume conductor model if isfield(obj, 'r'), obj.r = scale * obj.r; end if isfield(obj, 'o'), obj.o = scale * obj.o; end if isfield(obj, 'bnd') && isfield(obj.bnd, 'pnt') for i=1:length(obj.bnd) obj.bnd(i).pnt = scale * obj.bnd(i).pnt; end end if isfield(obj, 'bnd') && isfield(obj.bnd, 'pos') for i=1:length(obj.bnd) obj.bnd(i).pos = scale * obj.bnd(i).pos; end end % old-fashioned gradiometer array if isfield(obj, 'pnt1'), obj.pnt1 = scale * obj.pnt1; end if isfield(obj, 'pnt2'), obj.pnt2 = scale * obj.pnt2; end if isfield(obj, 'prj'), obj.prj = scale * obj.prj; end % gradiometer array, electrode array, head shape or dipole grid if isfield(obj, 'pnt'), obj.pnt = scale * obj.pnt; end if isfield(obj, 'pos'), obj.pos = scale * obj.pos; end if isfield(obj, 'chanpos'), obj.chanpos = scale * obj.chanpos; end if isfield(obj, 'chanposorg'), obj.chanposold = scale * obj.chanposorg; end % pre-2016 version if isfield(obj, 'chanposold'), obj.chanposold = scale * obj.chanposold; end % 2016 version and later if isfield(obj, 'coilpos'), obj.coilpos = scale * obj.coilpos; end if isfield(obj, 'elecpos'), obj.elecpos = scale * obj.elecpos; end % gradiometer array that combines multiple coils in one channel if isfield(obj, 'tra') && isfield(obj, 'chanunit') % find the gradiometer channels that are expressed as unit of field strength divided by unit of distance, e.g. T/cm for i=1:length(obj.chanunit) tok = tokenize(obj.chanunit{i}, '/'); if ~isempty(regexp(obj.chanunit{i}, 'm$', 'once')) % assume that it is T/m or so obj.tra(i,:) = obj.tra(i,:) / scale; obj.chanunit{i} = [tok{1} '/' target]; elseif ~isempty(regexp(obj.chanunit{i}, '[T|V]$', 'once')) % assume that it is T or V, don't do anything elseif strcmp(obj.chanunit{i}, 'unknown') % assume that it is T or V, don't do anything else error('unexpected units %s', obj.chanunit{i}); end end % for end % if % fiducials if isfield(obj, 'fid') && isfield(obj.fid, 'pnt'), obj.fid.pnt = scale * obj.fid.pnt; end if isfield(obj, 'fid') && isfield(obj.fid, 'pos'), obj.fid.pos = scale * obj.fid.pos; end % dipole grid if isfield(obj, 'resolution'), obj.resolution = scale * obj.resolution; end % x,y,zgrid can also be 'auto' if isfield(obj, 'xgrid') && ~ischar(obj.xgrid), obj.xgrid = scale * obj.xgrid; end if isfield(obj, 'ygrid') && ~ischar(obj.ygrid), obj.ygrid = scale * obj.ygrid; end if isfield(obj, 'zgrid') && ~ischar(obj.zgrid), obj.zgrid = scale * obj.zgrid; end % anatomical MRI or functional volume if isfield(obj, 'transform'), H = diag([scale scale scale 1]); obj.transform = H * obj.transform; end if isfield(obj, 'transformorig'), H = diag([scale scale scale 1]); obj.transformorig = H * obj.transformorig; end % sourcemodel obtained through mne also has a orig-field with the high % number of vertices if isfield(obj, 'orig') if isfield(obj.orig, 'pnt') obj.orig.pnt = scale * obj.orig.pnt; end if isfield(obj.orig, 'pos') obj.orig.pos = scale * obj.orig.pos; end end % remember the unit obj.unit = target; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % IDRANGE interdecile range for more robust range estimation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function r = idrange(x) keeprow=true(size(x,1),1); for l=1:size(x,2) keeprow = keeprow & isfinite(x(:,l)); end sx = sort(x(keeprow,:), 1); ii = round(interp1([0, 1], [1, size(x(keeprow,:), 1)], [.1, .9])); % indices for 10 & 90 percentile r = diff(sx(ii, :));
github
lcnbeapp/beapp-master
ft_datatype.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/ft_datatype.m
10,068
utf_8
0a0165e618d5828bde6132b5a5a7a2f2
function [type, dimord] = ft_datatype(data, desired) % FT_DATATYPE determines the type of data represented in a FieldTrip data % structure and returns a string with raw, freq, timelock source, comp, % spike, source, volume, dip, montage, event. % % Use as % [type, dimord] = ft_datatype(data) % [status] = ft_datatype(data, desired) % % See also FT_DATATYPE_COMP, FT_DATATYPE_FREQ, FT_DATATYPE_MVAR, % FT_DATATYPE_SEGMENTATION, FT_DATATYPE_PARCELLATION, FT_DATATYPE_SOURCE, % FT_DATATYPE_TIMELOCK, FT_DATATYPE_DIP, FT_DATATYPE_HEADMODEL, % FT_DATATYPE_RAW, FT_DATATYPE_SENS, FT_DATATYPE_SPIKE, FT_DATATYPE_VOLUME % Copyright (C) 2008-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin<2 desired = []; end % determine the type of input data israw = isfield(data, 'label') && isfield(data, 'time') && isa(data.time, 'cell') && isfield(data, 'trial') && isa(data.trial, 'cell') && ~isfield(data,'trialtime'); isfreq = (isfield(data, 'label') || isfield(data, 'labelcmb')) && isfield(data, 'freq') && ~isfield(data,'trialtime') && ~isfield(data,'origtrial'); %&& (isfield(data, 'powspctrm') || isfield(data, 'crsspctrm') || isfield(data, 'cohspctrm') || isfield(data, 'fourierspctrm') || isfield(data, 'powcovspctrm')); istimelock = isfield(data, 'label') && isfield(data, 'time') && ~isfield(data, 'freq') && ~isfield(data,'timestamp') && ~isfield(data,'trialtime') && ~(isfield(data, 'trial') && iscell(data.trial)) && ~isfield(data, 'pos'); %&& ((isfield(data, 'avg') && isnumeric(data.avg)) || (isfield(data, 'trial') && isnumeric(data.trial) || (isfield(data, 'cov') && isnumeric(data.cov)))); iscomp = isfield(data, 'label') && isfield(data, 'topo') || isfield(data, 'topolabel'); isvolume = isfield(data, 'transform') && isfield(data, 'dim') && ~isfield(data, 'pos'); issource = (isfield(data, 'pos') || isfield(data, 'pnt')) && isstruct(data) && numel(data)==1; % pnt is deprecated, this does not apply to a mesh array ismesh = (isfield(data, 'pos') || isfield(data, 'pnt')) && (isfield(data, 'tri') || isfield(data, 'tet') || isfield(data, 'hex')); % pnt is deprecated isdip = isfield(data, 'dip'); ismvar = isfield(data, 'dimord') && ~isempty(strfind(data.dimord, 'lag')); isfreqmvar = isfield(data, 'freq') && isfield(data, 'transfer'); ischan = check_chan(data); issegmentation = check_segmentation(data); isparcellation = check_parcellation(data); ismontage = isfield(data, 'labelorg') && isfield(data, 'labelnew') && isfield(data, 'tra'); isevent = isfield(data, 'type') && isfield(data, 'value') && isfield(data, 'sample') && isfield(data, 'offset') && isfield(data, 'duration'); isheadmodel = false; % FIXME this is not yet implemented if issource && isstruct(data) && numel(data)>1 % this applies to struct arrays with meshes, i.e. with a pnt+tri issource = false; end if ~isfreq % this applies to a freq structure from 2003 up to early 2006 isfreq = all(isfield(data, {'foi', 'label', 'dimord'})) && ~isempty(strfind(data.dimord, 'frq')); end % check if it is a spike structure spk_hastimestamp = isfield(data,'label') && isfield(data, 'timestamp') && isa(data.timestamp, 'cell'); spk_hastrials = isfield(data,'label') && isfield(data, 'time') && isa(data.time, 'cell') && isfield(data, 'trial') && isa(data.trial, 'cell') && isfield(data, 'trialtime') && isa(data.trialtime, 'numeric'); spk_hasorig = isfield(data,'origtrial') && isfield(data,'origtime'); % for compatibility isspike = isfield(data, 'label') && (spk_hastimestamp || spk_hastrials || spk_hasorig); % check if it is a sensor array isgrad = isfield(data, 'label') && isfield(data, 'coilpos') && isfield(data, 'coilori'); iselec = isfield(data, 'label') && isfield(data, 'elecpos'); if isspike type = 'spike'; elseif israw && iscomp type = 'raw+comp'; elseif istimelock && iscomp type = 'timelock+comp'; elseif isfreq && iscomp type = 'freq+comp'; elseif israw type = 'raw'; elseif iscomp type = 'comp'; elseif isfreqmvar % freqmvar should conditionally go before freq, otherwise the returned ft_datatype will be freq in the case of frequency mvar data type = 'freqmvar'; elseif isfreq type = 'freq'; elseif ismvar type = 'mvar'; elseif isdip % dip should conditionally go before timelock, otherwise the ft_datatype will be timelock type = 'dip'; elseif istimelock type = 'timelock'; elseif isvolume && issegmentation type = 'volume+label'; elseif isvolume type = 'volume'; elseif ismesh && isparcellation type = 'mesh+label'; elseif ismesh type = 'mesh'; elseif issource && isparcellation type = 'source+label'; elseif issource type = 'source'; elseif ischan % this results from avgovertime/avgoverfreq after timelockstatistics or freqstatistics type = 'chan'; elseif iselec type = 'elec'; elseif isgrad type = 'grad'; elseif ismontage type = 'montage'; elseif isevent type = 'event'; else type = 'unknown'; end if nargin>1 % return a boolean value switch desired case 'raw' type = any(strcmp(type, {'raw', 'raw+comp'})); case 'timelock' type = any(strcmp(type, {'timelock', 'timelock+comp'})); case 'freq' type = any(strcmp(type, {'freq', 'freq+comp'})); case 'comp' type = any(strcmp(type, {'comp', 'raw+comp', 'timelock+comp', 'freq+comp'})); case 'volume' type = any(strcmp(type, {'volume', 'volume+label'})); case 'source' type = any(strcmp(type, {'source', 'source+label', 'mesh', 'mesh+label'})); % a single mesh qualifies as source structure type = type && isstruct(data) && numel(data)==1; % an array of meshes does not qualify case 'mesh' type = any(strcmp(type, {'mesh', 'mesh+label'})); case 'segmentation' type = strcmp(type, 'volume+label'); case 'parcellation' type = any(strcmp(type, {'source+label' 'mesh+label'})); case 'sens' type = any(strcmp(type, {'elec', 'grad'})); otherwise type = strcmp(type, desired); end % switch end if nargout>1 % FIXME this should be replaced with getdimord in the calling code % also return the dimord of the input data if isfield(data, 'dimord') dimord = data.dimord; else dimord = 'unknown'; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [res] = check_chan(data) if ~isstruct(data) || any(isfield(data, {'time', 'freq', 'pos', 'dim', 'transform'})) res = false; elseif isfield(data, 'dimord') && any(strcmp(data.dimord, {'chan', 'chan_chan'})) res = true; else res = false; fn = fieldnames(data); for i=1:numel(fn) if isfield(data, [fn{i} 'dimord']) && any(strcmp(data.([fn{i} 'dimord']), {'chan', 'chan_chan'})) res = true; break; end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [res] = check_segmentation(volume) res = false; if ~isfield(volume, 'dim') && ~isfield(volume, 'transform') return end if isfield(volume, 'pos') return end if any(isfield(volume, {'seg', 'csf', 'white', 'gray', 'skull', 'scalp', 'brain'})) res = true; return end fn = fieldnames(volume); isboolean = []; cnt = 0; for i=1:length(fn) if isfield(volume, [fn{i} 'label']) res = true; return else if (islogical(volume.(fn{i})) || isnumeric(volume.(fn{i}))) && isequal(size(volume.(fn{i})),volume.dim) cnt = cnt+1; if islogical(volume.(fn{i})) isboolean(cnt) = true; else isboolean(cnt) = false; end end end end if ~isempty(isboolean) res = all(isboolean); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [res] = check_parcellation(source) res = false; if numel(source)>1 % this applies to struct arrays with meshes, i.e. with a pnt+tri return end if ~isfield(source, 'pos') return end fn = fieldnames(source); fb = false(size(fn)); npos = size(source.pos,1); for i=1:numel(fn) % for each of the fields check whether it might be a logical array with the size of the number of sources tmp = source.(fn{i}); fb(i) = numel(tmp)==npos && islogical(tmp); end if sum(fb)>1 % the presence of multiple logical arrays suggests it is a parcellation res = true; end if res == false % check if source has more D elements check = 0; for i = 1: length(fn) fname = fn{i}; switch fname case 'tri' npos = size(source.tri,1); check = 1; case 'hex' npos = size(source.hex,1); check = 1; case 'tet' npos = size(source.tet,1); check = 1; end end if check == 1 % check if elements are labelled for i=1:numel(fn) tmp = source.(fn{i}); fb(i) = numel(tmp)==npos && islogical(tmp); end if sum(fb)>1 res = true; end end end fn = fieldnames(source); for i=1:length(fn) if isfield(source, [fn{i} 'label']) && isnumeric(source.(fn{i})) res = true; return end end
github
lcnbeapp/beapp-master
ft_apply_montage.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/ft_apply_montage.m
21,632
utf_8
44431986d20b2a03b833ec06858af91d
function [input] = ft_apply_montage(input, montage, varargin) % FT_APPLY_MONTAGE changes the montage of an electrode or gradiometer array. A % montage can be used for EEG rereferencing, MEG synthetic gradients, MEG % planar gradients or unmixing using ICA. This function applies the montage % to the input EEG or MEG sensor array, which can subsequently be used for % forward computation and source reconstruction of the data. % % Use as % [sens] = ft_apply_montage(sens, montage, ...) % [data] = ft_apply_montage(data, montage, ...) % [freq] = ft_apply_montage(freq, montage, ...) % [montage] = ft_apply_montage(montage1, montage2, ...) % % A montage is specified as a structure with the fields % montage.tra = MxN matrix % montage.labelold = Nx1 cell-array % montage.labelnew = Mx1 cell-array % % As an example, a bipolar montage could look like this % bipolar.labelold = {'1', '2', '3', '4'} % bipolar.labelnew = {'1-2', '2-3', '3-4'} % bipolar.tra = [ % +1 -1 0 0 % 0 +1 -1 0 % 0 0 +1 -1 % ]; % % The montage can optionally also specify the channel type and unit of the input % and output data with % montage.chantypeold = Nx1 cell-array % montage.chantypenew = Mx1 cell-array % montage.chanunitold = Nx1 cell-array % montage.chanunitnew = Mx1 cell-array % % Additional options should be specified in key-value pairs and can be % 'keepunused' string, 'yes' or 'no' (default = 'no') % 'inverse' string, 'yes' or 'no' (default = 'no') % 'balancename' string, name of the montage (default = '') % 'feedback' string, see FT_PROGRESS (default = 'text') % 'warning' boolean, whether to show warnings (default = true) % % If the first input is a montage, then the second input montage will be % applied to the first. In effect, the output montage will first do % montage1, then montage2. % % See also FT_READ_SENS, FT_TRANSFORM_SENS % Copyright (C) 2008-2016, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if iscell(input) && iscell(input) % this represents combined EEG, ECoG and/or MEG for i=1:numel(input) input{i} = ft_apply_montage(input{i}, montage, varargin{:}); end return end % use "old/new" instead of "org/new" montage = fixmontage(montage); input = fixmontage(input); % the input might also be a montage % get optional input arguments keepunused = ft_getopt(varargin, 'keepunused', 'no'); inverse = ft_getopt(varargin, 'inverse', 'no'); feedback = ft_getopt(varargin, 'feedback', 'text'); showwarning = ft_getopt(varargin, 'warning', true); bname = ft_getopt(varargin, 'balancename', ''); if istrue(showwarning) warningfun = @warning; else warningfun = @nowarning; end % these are optional, at the end we will clean up the output in case they did not exist haschantype = (isfield(input, 'chantype') || isfield(input, 'chantypenew')) && all(isfield(montage, {'chantypeold', 'chantypenew'})); haschanunit = (isfield(input, 'chanunit') || isfield(input, 'chanunitnew')) && all(isfield(montage, {'chanunitold', 'chanunitnew'})); % make sure they always exist to facilitate the remainder of the code if ~isfield(montage, 'chantypeold') montage.chantypeold = repmat({'unknown'}, size(montage.labelold)); if isfield(input, 'chantype') && ~istrue(inverse) warning('copying input chantype to montage'); [sel1, sel2] = match_str(montage.labelold, input.label); montage.chantypeold(sel1) = input.chantype(sel2); end end if ~isfield(montage, 'chantypenew') montage.chantypenew = repmat({'unknown'}, size(montage.labelnew)); if isfield(input, 'chantype') && istrue(inverse) warning('copying input chantype to montage'); [sel1, sel2] = match_str(montage.labelnew, input.label); montage.chantypenew(sel1) = input.chantype(sel2); end end if ~isfield(montage, 'chanunitold') montage.chanunitold = repmat({'unknown'}, size(montage.labelold)); if isfield(input, 'chanunit') && ~istrue(inverse) warning('copying input chanunit to montage'); [sel1, sel2] = match_str(montage.labelold, input.label); montage.chanunitold(sel1) = input.chanunit(sel2); end end if ~isfield(montage, 'chanunitnew') montage.chanunitnew = repmat({'unknown'}, size(montage.labelnew)); if isfield(input, 'chanunit') && istrue(inverse) warning('copying input chanunit to montage'); [sel1, sel2] = match_str(montage.labelnew, input.label); montage.chanunitnew(sel1) = input.chanunit(sel2); end end if ~isfield(input, 'label') && isfield(input, 'labelnew') % the input data structure is also a montage inputlabel = input.labelnew; if isfield(input, 'chantypenew') inputchantype = input.chantypenew; else inputchantype = repmat({'unknown'}, size(input.labelnew)); end if isfield(input, 'chanunitnew') inputchanunit = input.chanunitnew; else inputchanunit = repmat({'unknown'}, size(input.labelnew)); end else % the input should describe the channel labels, and optionally the type and unit inputlabel = input.label; if isfield(input, 'chantype') inputchantype = input.chantype; else inputchantype = repmat({'unknown'}, size(input.label)); end if isfield(input, 'chanunit') inputchanunit = input.chanunit; else inputchanunit = repmat({'unknown'}, size(input.label)); end end % check the consistency of the montage if ~iscell(montage.labelold) || ~iscell(montage.labelnew) error('montage labels need to be specified in cell-arrays'); end % check the consistency of the montage if ~all(isfield(montage, {'tra', 'labelold', 'labelnew'})) error('the second input argument does not correspond to a montage'); end % check the consistency of the montage if size(montage.tra,1)~=length(montage.labelnew) error('the number of channels in the montage is inconsistent'); elseif size(montage.tra,2)~=length(montage.labelold) error('the number of channels in the montage is inconsistent'); end % use a default unit transfer from sensors to channels if not otherwise specified if ~isfield(input, 'tra') && isfield(input, 'label') if isfield(input, 'elecpos') && length(input.label)==size(input.elecpos, 1) nchan = length(input.label); input.tra = eye(nchan); elseif isfield(input, 'coilpos') && length(input.label)==size(input.coilpos, 1) nchan = length(input.label); input.tra = eye(nchan); elseif isfield(input, 'chanpos') && length(input.label)==size(input.chanpos, 1) nchan = length(input.label); input.tra = eye(nchan); end end if istrue(inverse) % swap the role of the original and new channels tmp.labelnew = montage.labelold; tmp.labelold = montage.labelnew; tmp.chantypenew = montage.chantypeold; tmp.chantypeold = montage.chantypenew; tmp.chanunitnew = montage.chanunitold; tmp.chanunitold = montage.chanunitnew; % apply the inverse montage, this can be used to undo a previously % applied montage tmp.tra = full(montage.tra); if rank(tmp.tra) < length(tmp.tra) warningfun('the linear projection for the montage is not full-rank, the resulting data will have reduced dimensionality'); tmp.tra = pinv(tmp.tra); else tmp.tra = inv(tmp.tra); end montage = tmp; end % select and keep the columns that are non-empty, i.e. remove the empty columns selcol = find(~all(montage.tra==0, 1)); montage.tra = montage.tra(:,selcol); montage.labelold = montage.labelold(selcol); montage.chantypeold = montage.chantypeold(selcol); montage.chanunitold = montage.chanunitold(selcol); clear selcol % select and remove the columns corresponding to channels that are not present in the % original data remove = setdiff(montage.labelold, intersect(montage.labelold, inputlabel)); selcol = match_str(montage.labelold, remove); % we cannot just remove the colums, all rows that depend on it should also be removed selrow = false(length(montage.labelnew),1); for i=1:length(selcol) selrow = selrow & (montage.tra(:,selcol(i))~=0); end % convert from indices to logical vector selcol = indx2logical(selcol, length(montage.labelold)); % remove rows and columns montage.labelold = montage.labelold(~selcol); montage.labelnew = montage.labelnew(~selrow); montage.chantypeold = montage.chantypeold(~selcol); montage.chantypenew = montage.chantypenew(~selrow); montage.chanunitold = montage.chanunitold(~selcol); montage.chanunitnew = montage.chanunitnew(~selrow); montage.tra = montage.tra(~selrow, ~selcol); clear remove selcol selrow i % add columns for channels that are present in the input data but not specified in % the montage, stick to the original order in the data [dum, ix] = setdiff(inputlabel, montage.labelold); addlabel = inputlabel(sort(ix)); addchantype = inputchantype(sort(ix)); addchanunit = inputchanunit(sort(ix)); m = size(montage.tra,1); n = size(montage.tra,2); k = length(addlabel); % check for NaNs in unused channels; these will be mixed in with the rest % of the channels and result in NaNs in the output even when multiplied % with zeros or identity if k > 0 && isfield(input, 'trial') % check for raw data now only cfg = []; cfg.channel = addlabel; data_unused = ft_selectdata(cfg, input); % use an anonymous function to test for the presence of NaNs in the input data hasnan = @(x) any(isnan(x(:))); if any(cellfun(hasnan, data_unused.trial)) error('FieldTrip:NaNsinInputData', ['Your input data contains NaNs in channels that are unused '... 'in the supplied montage. This would result in undesired NaNs in the '... 'output data. Please remove these channels from the input data (using '... 'ft_selectdata) before attempting to apply the montage.']); end end if istrue(keepunused) % add the channels that are not rereferenced to the input and output of the % montage montage.tra((m+(1:k)),(n+(1:k))) = eye(k); montage.labelold = cat(1, montage.labelold(:), addlabel(:)); montage.labelnew = cat(1, montage.labelnew(:), addlabel(:)); montage.chantypeold = cat(1, montage.chantypeold(:), addchantype(:)); montage.chantypenew = cat(1, montage.chantypenew(:), addchantype(:)); montage.chanunitold = cat(1, montage.chanunitold(:), addchanunit(:)); montage.chanunitnew = cat(1, montage.chanunitnew(:), addchanunit(:)); else % add the channels that are not rereferenced to the input of the montage only montage.tra(:,(n+(1:k))) = zeros(m,k); montage.labelold = cat(1, montage.labelold(:), addlabel(:)); montage.chantypeold = cat(1, montage.chantypeold(:), addchantype(:)); montage.chanunitold = cat(1, montage.chanunitold(:), addchanunit(:)); end clear addlabel addchantype addchanunit m n k % determine whether all channels are unique m = size(montage.tra,1); n = size(montage.tra,2); if length(unique(montage.labelnew))~=m error('not all output channels of the montage are unique'); end if length(unique(montage.labelold))~=n error('not all input channels of the montage are unique'); end % determine whether all channels that have to be rereferenced are available if length(intersect(inputlabel, montage.labelold))~=length(montage.labelold) error('not all channels that are required in the montage are available in the data'); end % reorder the columns of the montage matrix [selinput, selmontage] = match_str(inputlabel, montage.labelold); montage.tra = montage.tra(:,selmontage); montage.labelold = montage.labelold(selmontage); montage.chantypeold = montage.chantypeold(selmontage); montage.chanunitold = montage.chanunitold(selmontage); % ensure that the montage is double precision montage.tra = double(montage.tra); % making the tra matrix sparse will speed up subsequent multiplications, but should % not result in a sparse matrix % note that this only makes sense for matrices with a lot of zero elements, for dense % matrices keeping it full will be much quicker if size(montage.tra,1)>1 && nnz(montage.tra)/numel(montage.tra) < 0.3 montage.tra = sparse(montage.tra); else montage.tra = full(montage.tra); end % update the channel scaling if the input has different units than the montage expects if isfield(input, 'chanunit') && ~isequal(input.chanunit, montage.chanunitold) scale = ft_scalingfactor(input.chanunit, montage.chanunitold); montage.tra = montage.tra * diag(scale); montage.chanunitold = input.chanunit; elseif isfield(input, 'chanunitnew') && ~isequal(input.chanunitnew, montage.chanunitold) scale = ft_scalingfactor(input.chanunitnew, montage.chanunitold); montage.tra = montage.tra * diag(scale); montage.chanunitold = input.chanunitnew; end if isfield(input, 'chantype') && ~isequal(input.chantype, montage.chantypeold) error('inconsistent chantype in data and montage'); elseif isfield(input, 'chantypenew') && ~isequal(input.chantypenew, montage.chantypeold) error('inconsistent chantype in data and montage'); end if isfield(input, 'labelold') && isfield(input, 'labelnew') inputtype = 'montage'; elseif isfield(input, 'tra') inputtype = 'sens'; elseif isfield(input, 'trial') inputtype = 'raw'; elseif isfield(input, 'fourierspctrm') inputtype = 'freq'; else inputtype = 'unknown'; end switch inputtype case 'montage' % apply the montage on top of the other montage if isa(input.tra, 'single') % sparse matrices and single precision do not match input.tra = full(montage.tra) * input.tra; else input.tra = montage.tra * input.tra; end input.labelnew = montage.labelnew; input.chantypenew = montage.chantypenew; input.chanunitnew = montage.chanunitnew; case 'sens' % apply the montage to an electrode or gradiometer description sens = input; clear input % apply the montage to the inputor array if isa(sens.tra, 'single') % sparse matrices and single precision do not match sens.tra = full(montage.tra) * sens.tra; else sens.tra = montage.tra * sens.tra; end % The montage operates on the coil weights in sens.tra, but the output channels % can be different. If possible, we want to keep the original channel positions % and orientations. [sel1, sel2] = match_str(montage.labelnew, inputlabel); keepchans = length(sel1)==length(montage.labelnew); if isfield(sens, 'chanpos') if keepchans sens.chanpos = sens.chanpos(sel2,:); else if ~isfield(sens, 'chanposold') % add a chanposold only if it is not there yet sens.chanposold = sens.chanpos; end sens.chanpos = nan(numel(montage.labelnew),3); end end if isfield(sens, 'chanori') if keepchans sens.chanori = sens.chanori(sel2,:); else if ~isfield(sens, 'chanoriold') sens.chanoriold = sens.chanori; end sens.chanori = nan(numel(montage.labelnew),3); end end sens.label = montage.labelnew; sens.chantype = montage.chantypenew; sens.chanunit = montage.chanunitnew; % keep the % original label, % type and unit % for reference if ~isfield(sens, 'labelold') sens.labelold = inputlabel; end if ~isfield(sens, 'chantypeold') sens.chantypeold = inputchantype; end if ~isfield(sens, 'chanunitold') sens.chanunitold = inputchanunit; end % keep track of the order of the balancing and which one is the current one if istrue(inverse) if isfield(sens, 'balance')% && isfield(sens.balance, 'previous') if isfield(sens.balance, 'previous') && numel(sens.balance.previous)>=1 sens.balance.current = sens.balance.previous{1}; sens.balance.previous = sens.balance.previous(2:end); elseif isfield(sens.balance, 'previous') sens.balance.current = 'none'; sens.balance = rmfield(sens.balance, 'previous'); else sens.balance.current = 'none'; end end elseif ~istrue(inverse) && ~isempty(bname) if isfield(sens, 'balance'), % check whether a balancing montage with name bname already exist, % and if so, how many mnt = fieldnames(sens.balance); sel = strmatch(bname, mnt); if numel(sel)==0, % bname can stay the same elseif numel(sel)==1 % the original should be renamed to 'bname1' and the new one should % be 'bname2' sens.balance.([bname, '1']) = sens.balance.(bname); sens.balance = rmfield(sens.balance, bname); if isfield(sens.balance, 'current') && strcmp(sens.balance.current, bname) sens.balance.current = [bname, '1']; end if isfield(sens.balance, 'previous') sel2 = strmatch(bname, sens.balance.previous); if ~isempty(sel2) sens.balance.previous{sel2} = [bname, '1']; end end bname = [bname, '2']; else bname = [bname, num2str(length(sel)+1)]; end end if isfield(sens, 'balance') && isfield(sens.balance, 'current') if ~isfield(sens.balance, 'previous') sens.balance.previous = {}; end sens.balance.previous = [{sens.balance.current} sens.balance.previous]; sens.balance.current = bname; sens.balance.(bname) = montage; end end % rename the output variable input = sens; clear sens case 'raw'; % apply the montage to the raw data that was preprocessed using fieldtrip data = input; clear input Ntrials = numel(data.trial); ft_progress('init', feedback, 'processing trials'); for i=1:Ntrials ft_progress(i/Ntrials, 'processing trial %d from %d\n', i, Ntrials); if isa(data.trial{i}, 'single') % sparse matrices and single % precision do not match data.trial{i} = full(montage.tra) * data.trial{i}; else data.trial{i} = montage.tra * data.trial{i}; end end ft_progress('close'); data.label = montage.labelnew; data.chantype = montage.chantypenew; data.chanunit = montage.chanunitnew; % rename the output variable input = data; clear data case 'freq' % apply the montage to the spectrally decomposed data freq = input; clear input if strcmp(freq.dimord, 'rpttap_chan_freq') siz = size(freq.fourierspctrm); nrpt = siz(1); nchan = siz(2); nfreq = siz(3); output = zeros(nrpt, size(montage.tra,1), nfreq); for foilop=1:nfreq output(:,:,foilop) = freq.fourierspctrm(:,:,foilop) * montage.tra'; end freq.fourierspctrm = output; % replace the original Fourier spectrum elseif strcmp(freq.dimord, 'rpttap_chan_freq_time') siz = size(freq.fourierspctrm); nrpt = siz(1); nchan = siz(2); nfreq = siz(3); ntime = siz(4); output = zeros(nrpt, size(montage.tra,1), nfreq, ntime); for foilop=1:nfreq for toilop = 1:ntime output(:,:,foilop,toilop) = freq.fourierspctrm(:,:,foilop,toilop) * montage.tra'; end end freq.fourierspctrm = output; % replace the original Fourier spectrum else error('unsupported dimord in frequency data (%s)', freq.dimord); end freq.label = montage.labelnew; freq.chantype = montage.chantypenew; freq.chanunit = montage.chanunitnew; % rename the output variable input = freq; clear freq otherwise error('unrecognized input'); end % switch inputtype % only retain the chantype and/or chanunit if they were present in the input if ~haschantype input = removefields(input, {'chantype', 'chantypeold', 'chantypenew'}); end if ~haschanunit input = removefields(input, {'chanunit', 'chanunitold', 'chanunitnew'}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = indx2logical(x, n) y = false(1,n); y(x) = true; function nowarning(varargin) return function s = removefields(s, fn) for i=1:length(fn) if isfield(s, fn{i}) s = rmfield(s, fn{i}); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION use "old/new" instead of "org/new" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function montage = fixmontage(montage) if isfield(montage, 'labelorg') montage.labelold = montage.labelorg; montage = rmfield(montage, 'labelorg'); end if isfield(montage, 'chantypeorg') montage.chantypeold = montage.chantypeorg; montage = rmfield(montage, 'chantypeorg'); end if isfield(montage, 'chanunitorg') montage.chanunitold = montage.chanunitorg; montage = rmfield(montage, 'chanunitorg'); end
github
lcnbeapp/beapp-master
read_erplabdata.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_erplabdata.m
2,109
utf_8
0bf7476062c683168eb2d5ebeb92dbe3
% read_erplabdata() - import ERPLAB dataset files % % Usage: % >> dat = read_erplabdata(filename); % % Inputs: % filename - [string] file name % % Optional inputs: % 'begtrial' - [integer] first trial to read % 'endtrial' - [integer] last trial to read % 'chanindx' - [integer] list with channel indices to read % 'header' - FILEIO structure header % % Outputs: % dat - data over the specified range % % Modified from read_eeglabheader %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function dat = read_erplabdata(filename, varargin) if nargin < 1 help read_erplabdata; return; end; header = ft_getopt(varargin, 'header'); begsample = ft_getopt(varargin, 'begsample'); endsample = ft_getopt(varargin, 'endsample'); begtrial = ft_getopt(varargin, 'begtrial'); endtrial = ft_getopt(varargin, 'endtrial'); chanindx = ft_getopt(varargin, 'chanindx'); if isempty(header) header = read_erplabheader(filename); end dat = header.orig.bindata; if isempty(begtrial), begtrial = 1; end; if isempty(endtrial), endtrial = header.nTrials; end; if isempty(begsample), begsample = 1; end; if isempty(endsample), endsample = header.nSamples; end; dat = dat(:,begsample:endsample,begtrial:endtrial); if ~isempty(chanindx) % select the desired channels dat = dat(chanindx,:,:); end
github
lcnbeapp/beapp-master
read_besa_besa.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_besa_besa.m
98,170
utf_8
4dbddf31b961d349d9ca2a758d6cae77
function [data] = read_besa_besa(filename, header, begsample, endsample, chanindx) %% Reads BESA .besa format files % See formatting document <a href="matlab:web(http://www.besa.de/downloads/file-formats/)">here</a> % % % Use as % [header] = read_besa_besa(filename); % where % filename name of the datafile, including the .besa extension % This returns a header structure with the following elements % header.Fs sampling frequency % header.nChans number of channels % header.nSamples number of samples per trial % header.nSamplesPre number of pre-trigger samples in each trial % header.nTrials number of trials % header.label cell-array with labels of each channel % header.orig detailled EDF header information % % Use as % [header] = read_besa_besa(filename, [], chanindx); % where % filename name of the datafile, including the .edf extension % chanindx index of channels to read (optional, default is all) % Note that since % This returns a header structure with the following elements % header.Fs sampling frequency % header.nChans number of channels % header.nSamples number of samples per trial % header.nSamplesPre number of pre-trigger samples in each trial % header.nTrials number of trials % header.label cell-array with labels of each channel % header.orig detailled EDF header information % % Or use as % [dat] = read_besa_besa(filename, header, begsample, endsample, chanindx); % where % filename name of the datafile, including the .edf extension % header header structure, see above % begsample index of the first sample to read % endsample index of the last sample to read % chanindx index of channels to read (optional, default is all) % This returns a Nchans X Nsamples data matrix % % % 2016 - Kristopher Anderson, Knight Lab, Helen Wills Neuroscience Institute, University of California, Berkeley % For debugging %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TODO warning on;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TODO switch nargin case 1 chanindx=[]; case 2 chanindx=[]; case 3 chanindx=begsample; case 4 error('ReadBesaMatlab:ErrorInput','Number of input arguments should be 1,2,3, or 5'); end needhdr = (nargin==1)||(nargin==3); needevt = (nargin==2); % Not implemented yet %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TODO needdat = (nargin==5); if needhdr % Return only header data data = read_besa_besa_header(filename); % Empty chanindx means we want all channels if isempty(chanindx) chanindx = 1:data.nChans; end % Return header data for certain channels % Keep original channel info also data.orig.chansel = chanindx; % header.orig.chansel is used for reading channels from data data.nChans = numel(chanindx); data.label = data.label(chanindx); data.orig.channel_info.orig_n_channels = data.orig.channel_info.n_channels; data.orig.channel_info.n_channels = numel(chanindx); data.orig.channel_info.orig_lsbs = data.orig.channel_info.lsbs; data.orig.channel_info.lsbs = data.orig.channel_info.lsbs(chanindx); data.orig.channel_info.orig_channel_labels = data.orig.channel_info.channel_labels; data.orig.channel_info.channel_labels = data.orig.channel_info.channel_labels(chanindx); data.orig.channel_info.orig_channel_states = data.orig.channel_info.channel_states; data.orig.channel_info.channel_states = data.orig.channel_info.channel_states(chanindx); return end % Empty chanindx means we want all channels if isempty(chanindx) chanindx = 1:header.nChans; end %% Determine channels to pull from data % Ignore header.orig.chansel and overwrite with chanindx % Note that header (input) and data [dat] returned from this function may not match as a result channels_to_pull = chanindx; header.orig.chansel = chanindx; header.nChans = numel(chanindx); header.label = header.label(chanindx); header.orig.channel_info.orig_n_channels = header.orig.channel_info.n_channels; header.orig.channel_info.n_channels = numel(chanindx); header.orig.channel_info.orig_lsbs = header.orig.channel_info.lsbs; header.orig.channel_info.lsbs = header.orig.channel_info.lsbs(chanindx); header.orig.channel_info.orig_channel_labels = header.orig.channel_info.channel_labels; header.orig.channel_info.channel_labels = header.orig.channel_info.channel_labels(chanindx); header.orig.channel_info.orig_channel_states = header.orig.channel_info.channel_states; header.orig.channel_info.channel_states = header.orig.channel_info.channel_states(chanindx); %% Open file [fid,msg] = fopen(filename,'r'); assert(fid~=-1,'ReadBesaMatlab:ErrorOpeningFile',msg); % Get length of file fseek(fid,0,'eof'); file_length = ftell(fid); fseek(fid,0,'bof'); %% Data blocks if needdat % Collect data block info data_block_offsets = header.orig.tags.tags.position(strcmp(header.orig.tags.tags.type,'BDAT')); data_block_n_samples = header.orig.tags.tags.n_samples(strcmp(header.orig.tags.tags.type,'BDAT')); data_block_samples_beg = ones(numel(data_block_n_samples),1); data_block_samples_end = ones(numel(data_block_n_samples),1)*data_block_n_samples(1); for block_n = 2:numel(data_block_n_samples) data_block_samples_beg(block_n) = data_block_samples_end(block_n-1) + 1; data_block_samples_end(block_n) = data_block_samples_end(block_n-1) + data_block_n_samples(block_n); end % Choose blocks that contain requested samples if isempty(begsample) || begsample < 1 begsample = 1; end if isempty(endsample) || endsample > sum(data_block_n_samples) endsample = sum(data_block_n_samples); end blocks_to_pull = []; for block_n = 1:numel(data_block_n_samples) if( ~(data_block_samples_beg(block_n)<begsample && data_block_samples_end(block_n)<begsample) && ... ~(data_block_samples_beg(block_n)>endsample && data_block_samples_end(block_n)>endsample) ) blocks_to_pull(end+1) = block_n; %#ok<AGROW> end end % These values correspond to indices in each block samples_to_pull_beg = ones(numel(data_block_n_samples),1); samples_to_pull_end = data_block_n_samples'; for block_n = blocks_to_pull if(data_block_samples_beg(block_n)<begsample) samples_to_pull_beg(block_n) = begsample-data_block_samples_beg(block_n)+1; end if(data_block_samples_end(block_n)>endsample) samples_to_pull_end(block_n) = endsample-data_block_samples_beg(block_n)+1; end end % These values will correspond to the output sample number data_block_samples_beg = max(data_block_samples_beg-begsample+1, 1); data_block_samples_end = min(data_block_samples_end-begsample+1, endsample-begsample+1); % Check for necessary values if(~isfield(header.orig.channel_info,'n_channels')) fclose(fid); error('ReadBesaMatlab:ErrorNoNChannels','header.orig.channel_info.n_channels does not exist. This is needed for reading data blocks'); end if(~isfield(header.orig.channel_info,'lsbs')) % No least significant bit values found, so setting them all to 1.0 header.orig.channel_info.lsbs = ones(header.orig.channel_info.n_channels,1,'double'); end % Loop over all data blocks and add to alldata matrix data = zeros(numel(channels_to_pull), endsample-begsample+1); for block_n = blocks_to_pull blockdata = read_BDAT(fid, file_length, data_block_offsets(block_n), header.orig.channel_info.orig_n_channels, header.orig.channel_info.orig_lsbs); data(:,data_block_samples_beg(block_n):data_block_samples_end(block_n)) = ... blockdata(samples_to_pull_beg(block_n):samples_to_pull_end(block_n),channels_to_pull)'; end % NEED TO IMPLEMENT OVERWRITES %%%%%%%%%%%%%%%%%%%%%%%%%%% TODO end %% DATA BLOCK FUNCTIONS function block_data = read_BDAT(fid, file_length, bdat_offset, n_channels, lsbs) %% Read data block % % fif - file ID % file_length - total length of the file in bytes % bdat_offset - The location of this data block in the file % n_channels - number of channels % lsbs - [1 x n_channels array] - int data is multiplied by this for scaling if min(lsbs < 0) lsbs = ones(size(lsbs)); end % Please note that zero or negative LSB values are not allowed. If a non-positive value is found in the array, a value of "1.f" is used instead. % Constants for data type CONST_FLOAT = 0; CONST_INT16 = 1; CONST_COMPRESSED = 1; CONST_UNCOMPRESSED = 0; % Constants for prefix byte CONST_NOCOMPRESSION = 0; CONST_FIRSTSCHEME = 3; CONST_SECONDSCHEME = 4; CONST_THIRDSCHEME = 5; CONST_NOCOMPRESSION_FIRST2INT = 6; CONST_FIRSTSCHEME_FIRST2INT = 7; CONST_NOCOMPRESSION_ALLINT = 8; CONST_ZLIB_DD = 9; CONST_ZLIB_FIRSTSCHEME = 13; CONST_ZLIB_SECONDSCHEME = 14; CONST_ZLIB_THIRDSCHEME = 15; CONST_ZLIB_FIRSTSCHEME_FIRST2INT = 17; CONST_ZLIB_SECONDSCHEME_FIRST2INT = 18; CONST_ZLIB_THIRDSCHEME_FIRST2INT = 19; CONST_ZLIB_DD_ALLINT = 29; % Skip to start of BDAT section if(fseek(fid,double(bdat_offset),'bof') == -1) % double() because Windows can't seek to uint64 fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [BDAT]',bdat_offset); end % Read BDAT tag and offset [~,ofst_BDAT] = read_tag_offset_pair(fid,'BDAT'); % Check that file is not shorter than expected if(file_length < (ftell(fid)+ofst_BDAT)) expected_length = ftell(fid)+ofst_BDAT; fclose(fid); error('ReadBesaMatlab:ErrorFileTooShortForDataBlock','Data block expected file at least %d bytes long but file is %d bytes long',expected_length,file_length); end % Determine type of data in this block read_tag_offset_pair(fid,'DATT'); flag_BDAT = fread(fid,1,'*uint32'); if bitand(flag_BDAT,uint32(1),'uint32') data_type = CONST_INT16; else data_type = CONST_FLOAT; end if bitand(flag_BDAT,uint32(hex2dec('0010')),'uint32') data_comp = CONST_COMPRESSED; else data_comp = CONST_UNCOMPRESSED; end % Determine number of samples in this block read_tag_offset_pair(fid,'DATS'); n_samples = fread(fid,1,'*uint32'); % Read DATA tag and offset [~,data_block_length] = read_tag_offset_pair(fid,'DATA'); data_block_offset = double(ftell(fid)); % Read data block_data = zeros(n_samples,n_channels,'double'); switch num2str([data_type data_comp]) case num2str([CONST_INT16 CONST_UNCOMPRESSED]) % Read int16s, reshape to [n_samples x n_channels], multiply each channel by LSB block_data = bsxfun(@times,lsbs', ... double(reshape(fread(fid,n_samples*n_channels,'*int16'),[n_samples,n_channels]))); case num2str([CONST_FLOAT CONST_UNCOMPRESSED]) % Read singles, reshape to [n_samples x n_channels] block_data = double(reshape(fread(fid,n_samples*n_channels,'*single'),[n_samples,n_channels])); case {num2str([CONST_FLOAT CONST_COMPRESSED]),num2str([CONST_INT16 CONST_COMPRESSED])} % Compressed data for channel_n = 1:n_channels prefix_val = fread(fid,1,'*uint8'); switch prefix_val case CONST_NOCOMPRESSION % No zlib. No pre-compression. Yes double difference % First two elements are int16. Rest are int16. block_data(:,channel_n) = double(fread(fid,n_samples,'*int16')); % Integrate twice block_data(2:end,channel_n) = cumsum(block_data(2:end,channel_n),1); block_data(:,channel_n) = cumsum(block_data(:,channel_n),1); case CONST_FIRSTSCHEME % No zlib. Yes pre-compression. Yes double difference % First two elements are int16. Rest are int8 (pre-compressed, first scheme) first_2_vals = fread(fid,2,'*int16'); block_data(:,channel_n) = double(decode_firstscheme(fid,fread(fid,data_block_length-4,'*uint8'), n_samples, first_2_vals)); case CONST_SECONDSCHEME % No zlib. Yes pre-compression. Yes double difference % First two elements are int16. Rest are int8 (pre-compressed, second scheme) first_2_vals = fread(fid,2,'*int16'); block_data(:,channel_n) = double(decode_secondscheme(fid,fread(fid,data_block_length-4,'*uint8'), n_samples, first_2_vals)); case CONST_THIRDSCHEME % No zlib. Yes pre-compression. Yes double difference % First two elements are int16. Rest are int8 (pre-compressed, third scheme) first_2_vals = fread(fid,2,'*int16'); block_data(:,channel_n) = double(decode_thirdscheme(fid,fread(fid,data_block_length-4,'*uint8'), n_samples, first_2_vals)); case CONST_NOCOMPRESSION_FIRST2INT % No zlib. No pre-compression. Yes double difference % First two elements are int32. Rest are int16 block_data(1:2,channel_n) = double(fread(fid,2,'*int32')); block_data(3:end,channel_n) = double(fread(fid,n_samples-2,'*int16')); % Integrate twice block_data(2:end,channel_n) = cumsum(block_data(2:end,channel_n),1); block_data(:,channel_n) = cumsum(block_data(:,channel_n),1); case CONST_FIRSTSCHEME_FIRST2INT % No zlib. Yes pre-compression. Yes double difference % First two elements are int32. Rest are int8 (pre-compressed, first scheme) first_2_vals = fread(fid,2,'*int32'); block_data(:,channel_n) = double(decode_firstscheme(fid,fread(fid,data_block_length-8,'*uint8'), n_samples, first_2_vals)); case CONST_NOCOMPRESSION_ALLINT % No zlib. No pre-compression. Yes double difference % First two elements are int32. Rest are int32 block_data(:,channel_n) = double(fread(fid,n_samples,'*int32')); % Integrate twice block_data(2:end,channel_n) = cumsum(block_data(2:end,channel_n),1); block_data(:,channel_n) = cumsum(block_data(:,channel_n),1); case CONST_ZLIB_DD % Yes zlib. No pre-compression. Yes double difference % First two elements are int16. Rest are int16 buffer_len = fread(fid,1,'*uint32'); buffer_data = fread(fid,buffer_len,'*uint8'); buffer_data = typecast(dunzip(buffer_data),'uint8')'; block_data(:,channel_n) = typecast(buffer_data,'int16'); case CONST_ZLIB_FIRSTSCHEME % Yes zlib. Yes pre-compression. Yes double difference % First two elements are int16. Rest are int8 (pre-compressed, first scheme) buffer_len = fread(fid,1,'*uint32'); buffer_data = fread(fid,buffer_len,'*uint8'); buffer_data = typecast(dunzip(buffer_data),'uint8')'; block_data(:,channel_n) = double(decode_firstscheme(fid,buffer_data(5:end), n_samples, typecast(buffer_data(1:4),'int16'))); case CONST_ZLIB_SECONDSCHEME % Yes zlib. Yes pre-compression. Yes double difference % First two elements are int16. Rest are int8 (pre-compressed, second scheme) buffer_len = fread(fid,1,'*uint32'); buffer_data = fread(fid,buffer_len,'*uint8'); buffer_data = typecast(dunzip(buffer_data),'uint8')'; block_data(:,channel_n) = double(decode_secondscheme(fid,buffer_data(5:end), n_samples, typecast(buffer_data(1:4),'int16'))); case CONST_ZLIB_THIRDSCHEME % Yes zlib. Yes pre-compression. Yes double difference % First two elements are int16. Rest are int8 (pre-compressed, third scheme) buffer_len = fread(fid,1,'*uint32'); buffer_data = fread(fid,buffer_len,'*uint8'); buffer_data = typecast(dunzip(buffer_data),'uint8')'; block_data(:,channel_n) = double(decode_thirdscheme(fid,buffer_data(5:end), n_samples, typecast(buffer_data(1:4),'int16'))); case CONST_ZLIB_FIRSTSCHEME_FIRST2INT % Yes zlib. Yes pre-compression. Yes double difference % First two elements are int16. Rest are int8 (pre-compressed, first scheme) buffer_len = fread(fid,1,'*uint32'); buffer_data = fread(fid,buffer_len,'*uint8'); buffer_data = typecast(dunzip(buffer_data),'uint8')'; block_data(:,channel_n) = double(decode_firstscheme(fid,buffer_data(9:end), n_samples, typecast(buffer_data(1:8),'int32'))); case CONST_ZLIB_SECONDSCHEME_FIRST2INT % Yes zlib. Yes pre-compression. Yes double difference % First two elements are int32. Rest are int8 (pre-compressed, second scheme) buffer_len = fread(fid,1,'*uint32'); buffer_data = fread(fid,buffer_len,'*uint8'); buffer_data = typecast(dunzip(buffer_data),'uint8')'; block_data(:,channel_n) = double(decode_secondscheme(fid,buffer_data(9:end), n_samples, typecast(buffer_data(1:8),'int32'))); case CONST_ZLIB_THIRDSCHEME_FIRST2INT % Yes zlib. Yes pre-compression. Yes double difference % First two elements are int32. Rest are int8 (pre-compressed, third scheme) buffer_len = fread(fid,1,'*uint32'); buffer_data = fread(fid,buffer_len,'*uint8'); buffer_data = typecast(dunzip(buffer_data),'uint8')'; block_data(:,channel_n) = double(decode_thirdscheme(fid,buffer_data(9:end), n_samples, typecast(buffer_data(1:8),'int32'))); case CONST_ZLIB_DD_ALLINT % Yes zlib. No pre-compression. Yes double difference % First two elements are int32. Rest are int32 buffer_len = fread(fid,1,'*uint32'); buffer_data = fread(fid,buffer_len,'*int8'); buffer_data = typecast(dunzip(buffer_data),'uint8')'; block_data(:,channel_n) = typecast(buffer_data,'int32'); otherwise current_loc = ftell(fid); fclose(fid); error('ReadBesaMatlab:ErrorBDATReadPrefixValueUnknownScheme','Unknown scheme CH:%d prefix_val:%d File offset:%d',channel_n,prefix_val,current_loc); end end if(strcmp(num2str([data_type data_comp]),num2str([CONST_INT16 CONST_COMPRESSED]))) % Multiply int16 data by lsbs block_data = bsxfun(@times,lsbs',block_data); end end % Check that expected amout of data was read if((data_block_offset+double(data_block_length)) ~= ftell(fid)) warning('ReadBesaMatlab:WarningDidNotReadExactBlockLength','%d bytes off. Read %d bytes from data block. Should have read %d bytes', ... (ftell(fid)-data_block_offset)-double(data_block_length),ftell(fid)-data_block_offset,double(data_block_length)); end function outbuffer = decode_firstscheme(fid, inbuffer, n_samples, first2vals) % Read data in first scheme CONST_MESHGRID_VALS_1 = -7:7; CONST_AB_INT32_RANGE = 241:-1:236; % Reverse order. This is needed to determine n_vals CONST_AB_INT16_RANGE = 247:-1:242; CONST_AB_INT8_RANGE = 254:-1:248; max_lut_val = numel(CONST_MESHGRID_VALS_1)^2-1; % Any buffer value greater than this is an announcing byte % Use persistent variable so lookup table does not need to be recomputed each time persistent firstscheme_lookuptable; if isempty(firstscheme_lookuptable) % Create the lookup grid from -7 to 7 in x and y [firstscheme_lookuptable(:,:,1),firstscheme_lookuptable(:,:,2)] = meshgrid(CONST_MESHGRID_VALS_1,CONST_MESHGRID_VALS_1); % Reshape the lookup grid to be [1:225 x 1:2] firstscheme_lookuptable = reshape(firstscheme_lookuptable,[numel(CONST_MESHGRID_VALS_1)^2 2]); end % Initialize outbuffer outbuffer = zeros(n_samples,1,'int32'); % Fill in the first two values outbuffer(1:2) = first2vals; % Find first announcing byte (AB) (value outside of LUT) ab_idx = find(inbuffer>max_lut_val,1,'first'); last_outbuffer_idx = 2; % first2vals if isempty(ab_idx) % No ABs, just use lookup table for whole inbuffer % Get the output from the lookup table % Transpose and then use linear indexing in the output to put all % elements into a 1-d array try outbuffer((last_outbuffer_idx+1):end) = firstscheme_lookuptable(inbuffer+1); % Plus 1 because indices start at 0 catch ME if(strcmp(ME.identifier,'MATLAB:subsassignnumelmismatch')) expected_samples = numel(outbuffer((last_outbuffer_idx+1):end)); received_samples = numel(firstscheme_lookuptable(inbuffer+1)); fclose(fid); error('ReadBesaMatlab:ErrorUnexpectedNSamplesFromPreCompression','Expected %d samples, but got %d samples. [first scheme, no ABs]', ... expected_samples,received_samples); else rethrow(ME); end end end % Loop until out of announcing bytes possible_abs = inbuffer > max_lut_val; last_ab_idx = 0; while ~isempty(ab_idx) % Fill outbuffer using LUT with all values between the last set of non-encodable values % and the current set of non-encodable values, % starting at the last filled outbuffer index. try outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+2*(ab_idx-last_ab_idx-1))) = ... firstscheme_lookuptable(inbuffer((last_ab_idx+1):(ab_idx-1))+1,:); % Plus 1 because indices start at 0 catch ME if(strcmp(ME.identifier,'MATLAB:subsassignnumelmismatch')) expected_samples = numel(outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+2*(ab_idx-last_ab_idx-1)))); received_samples = numel(firstscheme_lookuptable(inbuffer((last_ab_idx+1):(ab_idx-1))+1,:)); fclose(fid); error('ReadBesaMatlab:ErrorUnexpectedNSamplesFromPreCompression','Expected %d samples, but got %d samples. [first scheme, middle of buffer]', ... expected_samples,received_samples); else rethrow(ME); end end last_outbuffer_idx = (last_outbuffer_idx+2*(ab_idx-last_ab_idx-1)); if(any(CONST_AB_INT32_RANGE == inbuffer(ab_idx))) % AB indicates int32 n_vals = find(CONST_AB_INT32_RANGE==inbuffer(ab_idx),1); n_skip = n_vals*4; % x4 for int32 % Fill outbuffer with n_vals outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+n_vals)) = typecast(inbuffer((ab_idx+1):(ab_idx+n_skip)),'int32'); last_outbuffer_idx = last_outbuffer_idx+n_vals; last_ab_idx = ab_idx+n_skip; elseif(any(CONST_AB_INT16_RANGE == inbuffer(ab_idx))) % AB indicates int16 n_vals = find(CONST_AB_INT16_RANGE==inbuffer(ab_idx),1); n_skip = n_vals*2; % x2 for int16 % Fill outbuffer with n_vals outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+n_vals)) = typecast(inbuffer((ab_idx+1):(ab_idx+n_skip)),'int16'); last_outbuffer_idx = last_outbuffer_idx+n_vals; last_ab_idx = ab_idx+n_skip; elseif(any(CONST_AB_INT8_RANGE == inbuffer(ab_idx))) % AB indicates int8 n_vals = find(CONST_AB_INT8_RANGE==inbuffer(ab_idx),1); n_skip = n_vals; % x1 for int8 % Fill outbuffer with n_vals outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+n_vals)) = typecast(inbuffer((ab_idx+1):(ab_idx+n_skip)),'int8'); last_outbuffer_idx = last_outbuffer_idx+n_vals; last_ab_idx = ab_idx+n_skip; else % not an alowed announcing byte value fclose(fid); error('ReadBesaMatlab:ErrorABOutOfRange','Announcing byte out of range: %d',inbuffer(ab_idx)); end % Go to next AB ab_idx = last_ab_idx + find(possible_abs((last_ab_idx+1):end),1,'first'); % Note: X+[]=[] end if(last_ab_idx<numel(inbuffer)) % Fill outbuffer using LUT with all values after the last set of non-encodable values % starting at the last filled outbuffer index. try outbuffer((last_outbuffer_idx+1):end) = ... firstscheme_lookuptable(inbuffer((last_ab_idx+1):end)+1,:); % Plus 1 because indices start at 0 catch ME if(strcmp(ME.identifier,'MATLAB:subsassignnumelmismatch')) expected_samples = numel(outbuffer((last_outbuffer_idx+1):end)); received_samples = numel(firstscheme_lookuptable(inbuffer((last_ab_idx+1):end)+1,:)); fclose(fid); error('ReadBesaMatlab:ErrorUnexpectedNSamplesFromPreCompression','Expected %d samples, but got %d samples. [first scheme, end of buffer]', ... expected_samples,received_samples); else rethrow(ME); end end end % Integrate twice outbuffer(2:end) = cumsum(outbuffer(2:end)); outbuffer = cumsum(outbuffer); function outbuffer = decode_secondscheme(fid, inbuffer, n_samples, first2vals) % Decode second scheme CONST_MESHGRID_VALS_2A = -2:2; CONST_MESHGRID_VALS_2B = -5:5; CONST_AB_INT16_RANGE = 249:-1:246; % Reverse order. This is needed to determine n_vals CONST_AB_INT8_RANGE = 254:-1:250; meshgrid_vals.A = CONST_MESHGRID_VALS_2A; meshgrid_vals.B = CONST_MESHGRID_VALS_2B; max_lut_val = numel(CONST_MESHGRID_VALS_2A)^3 + numel(CONST_MESHGRID_VALS_2B)^2 - 1; % Any buffer value greater than this is an announcing byte % Initialize outbuffer outbuffer = zeros(n_samples,1,'int32'); % Fill in the first two values outbuffer(1:2) = first2vals; % Find first announcing byte (AB) (value outside of LUT) ab_idx = find(inbuffer>max_lut_val,1,'first'); last_outbuffer_idx = 2; % first2vals if isempty(ab_idx) % No ABs, just use lookup table for whole inbuffer % Get the output from the lookup table try outbuffer((last_outbuffer_idx+1):end) = secondscheme_lookup(inbuffer+1,meshgrid_vals); % Plus 1 because indices start at 0 catch ME if(strcmp(ME.identifier,'MATLAB:subsassignnumelmismatch')) expected_samples = numel(outbuffer((last_outbuffer_idx+1):end)); received_samples = numel(secondscheme_lookup(inbuffer+1,meshgrid_vals)); fclose(fid); error('ReadBesaMatlab:ErrorUnexpectedNSamplesFromPreCompression','Expected %d samples, but got %d samples. [second scheme, no ABs]', ... expected_samples,received_samples); else rethrow(ME); end end end % Loop until out of announcing bytes possible_abs = inbuffer > max_lut_val; last_ab_idx = 0; while ~isempty(ab_idx) % Fill outbuffer using LUT with all values between the last set of non-encodable values % and the current set of non-encodable values, % starting at the last filled outbuffer index. % No error checking, because we don't know how long it should be decoded_buffer = secondscheme_lookup(inbuffer((last_ab_idx+1):(ab_idx-1))+1,meshgrid_vals); % Plus 1 because indices start at 0 outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+numel(decoded_buffer))) = ... decoded_buffer; last_outbuffer_idx = (last_outbuffer_idx+numel(decoded_buffer)); clear decoded_buffer; if(any(CONST_AB_INT16_RANGE == inbuffer(ab_idx))) % AB indicates int16 n_vals = find(CONST_AB_INT16_RANGE==inbuffer(ab_idx),1); n_skip = n_vals*2; % x2 for int16 % Fill outbuffer with n_vals outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+n_vals)) = typecast(inbuffer((ab_idx+1):(ab_idx+n_skip)),'int16'); last_outbuffer_idx = last_outbuffer_idx+n_vals; last_ab_idx = ab_idx+n_skip; elseif(any(CONST_AB_INT8_RANGE == inbuffer(ab_idx))) % AB indicates int8 n_vals = find(CONST_AB_INT8_RANGE==inbuffer(ab_idx),1); n_skip = n_vals; % x1 for int8 % Fill outbuffer with n_vals outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+n_vals)) = typecast(inbuffer((ab_idx+1):(ab_idx+n_skip)),'int8'); last_outbuffer_idx = last_outbuffer_idx+n_vals; last_ab_idx = ab_idx+n_skip; else % not an allowed announcing byte value fclose(fid); error('ReadBesaMatlab:ErrorABOutOfRange','Announcing byte out of range [second scheme]: %d',inbuffer(ab_idx)); end % Go to next AB ab_idx = last_ab_idx + find(possible_abs((last_ab_idx+1):end),1,'first'); % Note: X+[]=[] end if(last_ab_idx<numel(inbuffer)) % Fill outbuffer using LUT with all values after the last set of non-encodable values % starting at the last filled outbuffer index. try outbuffer((last_outbuffer_idx+1):end) = ... secondscheme_lookup(inbuffer((last_ab_idx+1):end)+1,meshgrid_vals); % Plus 1 because indices start at 0 catch ME if(strcmp(ME.identifier,'MATLAB:subsassignnumelmismatch')) expected_samples = numel(outbuffer((last_outbuffer_idx+1):end)); received_samples = numel(secondscheme_lookup(inbuffer((last_ab_idx+1):end)+1,meshgrid_vals)); fclose(fid); error('ReadBesaMatlab:ErrorUnexpectedNSamplesFromPreCompression','Expected %d samples, but got %d samples. [second scheme, end of buffer]', ... expected_samples,received_samples); else rethrow(ME); end end end function output = secondscheme_lookup(input, meshgrid_vals) % Lookup table for second scheme % Use persistent variable so lookup table does not need to be recomputed each time persistent secondscheme_lookuptable; if isempty(secondscheme_lookuptable) % Create the lookup grid from -2 to 2 in x, y, z [secondscheme_lookuptable_a(:,:,:,1),secondscheme_lookuptable_a(:,:,:,2),secondscheme_lookuptable_a(:,:,:,3)] = ... meshgrid(meshgrid_vals.A,meshgrid_vals.A,meshgrid_vals.A); % Reshape the lookup grid to be [1:125 x 1:3] secondscheme_lookuptable_a = reshape(secondscheme_lookuptable_a,[numel(meshgrid_vals.A)^3 3]); % Correct order of x,y,z secondscheme_lookuptable_a(:,[1 2 3]) = secondscheme_lookuptable_a(:,[3 1 2]); % Create the lookup grid from -5 to 5 in x and y [secondscheme_lookuptable_b(:,:,1),secondscheme_lookuptable_b(:,:,2)] = meshgrid(meshgrid_vals.B,meshgrid_vals.B); % Reshape the lookup grid to be [1:121 x 1:2] secondscheme_lookuptable_b = reshape(secondscheme_lookuptable_b,[numel(meshgrid_vals.B)^2 2]); % Put the lookup tables together in a cell array (because of different sized cells) secondscheme_lookuptable = num2cell(secondscheme_lookuptable_a,2); secondscheme_lookuptable = [secondscheme_lookuptable; num2cell(secondscheme_lookuptable_b,2)]; clear secondscheme_lookuptable_a; clear secondscheme_lookuptable_b; end output_cell = secondscheme_lookuptable(input); output = [output_cell{:}]; function outbuffer = decode_thirdscheme(fid, inbuffer, n_samples, first2vals) % Decode third scheme CONST_MESHGRID_VALS_3A = -1:1; CONST_MESHGRID_VALS_3B = -6:6; CONST_AB_INT16_RANGE = 251:-1:250; % Reverse order. This is needed to determine n_vals CONST_AB_INT8_RANGE = 254:-1:252; meshgrid_vals.A = CONST_MESHGRID_VALS_3A; meshgrid_vals.B = CONST_MESHGRID_VALS_3B; max_lut_val = numel(CONST_MESHGRID_VALS_3A)^4 + numel(CONST_MESHGRID_VALS_3B)^2 - 1; % Any buffer value greater than this is an announcing byte % Initialize outbuffer outbuffer = zeros(n_samples,1,'int32'); % Fill in the first two values outbuffer(1:2) = first2vals; % Find first announcing byte (AB) (value outside of LUT) ab_idx = find(inbuffer>max_lut_val,1,'first'); last_outbuffer_idx = 2; % first2vals if isempty(ab_idx) % No ABs, just use lookup table for whole inbuffer % Get the output from the lookup table try outbuffer((last_outbuffer_idx+1):end) = thirdscheme_lookup(inbuffer+1,meshgrid_vals); % Plus 1 because indices start at 0 catch ME if(strcmp(ME.identifier,'MATLAB:subsassignnumelmismatch')) expected_samples = numel(outbuffer((last_outbuffer_idx+1):end)); received_samples = numel(thirdscheme_lookup(inbuffer+1,meshgrid_vals)); fclose(fid); error('ReadBesaMatlab:ErrorUnexpectedNSamplesFromPreCompression','Expected %d samples, but got %d samples. [third scheme, no ABs]', ... expected_samples,received_samples); else rethrow(ME); end end end % Loop until out of announcing bytes possible_abs = inbuffer > max_lut_val; last_ab_idx = 0; while ~isempty(ab_idx) % Fill outbuffer using LUT with all values between the last set of non-encodable values % and the current set of non-encodable values, % starting at the last filled outbuffer index. % No error checking, because we don't know how long it should be decoded_buffer = thirdscheme_lookup(inbuffer((last_ab_idx+1):(ab_idx-1))+1,meshgrid_vals); % Plus 1 because indices start at 0 outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+numel(decoded_buffer))) = ... decoded_buffer; last_outbuffer_idx = (last_outbuffer_idx+numel(decoded_buffer)); clear decoded_buffer; if(any(CONST_AB_INT16_RANGE == inbuffer(ab_idx))) % AB indicates int16 n_vals = find(CONST_AB_INT16_RANGE==inbuffer(ab_idx),1); n_skip = n_vals*2; % x2 for int16 % Fill outbuffer with n_vals outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+n_vals)) = typecast(inbuffer((ab_idx+1):(ab_idx+n_skip)),'int16'); last_outbuffer_idx = last_outbuffer_idx+n_vals; last_ab_idx = ab_idx+n_skip; elseif(any(CONST_AB_INT8_RANGE == inbuffer(ab_idx))) % AB indicates int8 n_vals = find(CONST_AB_INT8_RANGE==inbuffer(ab_idx),1); n_skip = n_vals; % x1 for int8 % Fill outbuffer with n_vals outbuffer((last_outbuffer_idx+1):(last_outbuffer_idx+n_vals)) = typecast(inbuffer((ab_idx+1):(ab_idx+n_skip)),'int8'); last_outbuffer_idx = last_outbuffer_idx+n_vals; last_ab_idx = ab_idx+n_skip; else % not an allowed announcing byte value fclose(fid); error('ReadBesaMatlab:ErrorABOutOfRange','Announcing byte out of range [third scheme]: %d',inbuffer(ab_idx)); end % Go to next AB ab_idx = last_ab_idx + find(possible_abs((last_ab_idx+1):end),1,'first'); % Note: X+[]=[] end if(last_ab_idx<numel(inbuffer)) % Fill outbuffer using LUT with all values after the last set of non-encodable values % starting at the last filled outbuffer index. try outbuffer((last_outbuffer_idx+1):end) = ... thirdscheme_lookup(inbuffer((last_ab_idx+1):end)+1,meshgrid_vals); % Plus 1 because indices start at 0 catch ME if(strcmp(ME.identifier,'MATLAB:subsassignnumelmismatch')) expected_samples = numel(outbuffer((last_outbuffer_idx+1):end)); received_samples = numel(thirdscheme_lookup(inbuffer((last_ab_idx+1):end)+1,meshgrid_vals)); fclose(fid); error('ReadBesaMatlab:ErrorUnexpectedNSamplesFromPreCompression','Expected %d samples, but got %d samples. [third scheme, end of buffer]', ... expected_samples,received_samples); else rethrow(ME); end end end function output = thirdscheme_lookup(input, meshgrid_vals) % Lookup table for third scheme % Use persistent variable so lookup table does not need to be recomputed each time persistent thirdscheme_lookuptable; if isempty(thirdscheme_lookuptable) % Create the lookup grid from -1 to 1 in x, y, z, c [thirdscheme_lookuptable_a(:,:,:,:,1),thirdscheme_lookuptable_a(:,:,:,:,2),thirdscheme_lookuptable_a(:,:,:,:,3),thirdscheme_lookuptable_a(:,:,:,:,4)] = ... ndgrid(meshgrid_vals.A); % Reshape the lookup grid to be [1:81 x 1:4] thirdscheme_lookuptable_a = reshape(thirdscheme_lookuptable_a,[numel(meshgrid_vals.A)^4 4]); % Correct order of x,y,z,c thirdscheme_lookuptable_a(:,[1 2 3 4]) = thirdscheme_lookuptable_a(:,[4 3 2 1]); % Create the lookup grid from -6 to 6 in x and y [thirdscheme_lookuptable_b(:,:,1),thirdscheme_lookuptable_b(:,:,2)] = meshgrid(meshgrid_vals.B,meshgrid_vals.B); % Reshape the lookup grid to be [1:169 x 1:2] thirdscheme_lookuptable_b = reshape(thirdscheme_lookuptable_b,[numel(meshgrid_vals.B)^2 2]); % Put the lookup tables together in a cell array (because of different sized cells) thirdscheme_lookuptable = num2cell(thirdscheme_lookuptable_a,2); thirdscheme_lookuptable = [thirdscheme_lookuptable; num2cell(thirdscheme_lookuptable_b,2)]; clear thirdscheme_lookuptable_a; clear thirdscheme_lookuptable_b; end output_cell = thirdscheme_lookuptable(input); output = [output_cell{:}]; %% HELPER FUNCTIONS function M = dunzip(Z) % DUNZIP - decompress gzipped stream of bytes % FORMAT M = dzip(Z) % Z - compressed variable to decompress (uint8 vector) % M - decompressed output % % See also DZIP % Carefully tested, but no warranty; use at your own risk. % Michael Kleder, Nov 2005 % Modified by Guillaume Flandin, May 2008 import com.mathworks.mlwidgets.io.InterruptibleStreamCopier a = java.io.ByteArrayInputStream(Z); b = java.util.zip.InflaterInputStream(a); isc = InterruptibleStreamCopier.getInterruptibleStreamCopier; c = java.io.ByteArrayOutputStream; isc.copyStream(b,c); M = c.toByteArray; function [out_tag, out_offset] = read_tag_offset_pair(fid,expected_tag) % Read 4 bytes and check if they match expected value out_tag = fread(fid,4,'*char')'; if(nargin>1) % Compare tag with expected tag if ~strcmp(expected_tag,out_tag) curr_offset = ftell(fid); fclose(fid); error('ReadBesaMatlab:ErrorTagMismatch','Expecting [%s] but read [%s] at offset %d',expected_tag,out_tag,curr_offset); end end % Read offset value following tag out_offset = fread(fid,1,'*uint32'); function [header] = read_besa_besa_header(fname) %% Reads BESA .besa format header information and skips data % See formatting document <a href="matlab:web(http://www.besa.de/downloads/file-formats/)">here</a> % % [alldata,file_info,channel_info,tags,events] = readbesa(fname) % % inputs: % fname [string] - path to .besa file % % outputs: % header [structure] - Header information % % % % 2016 - Kristopher Anderson, Knight Lab, Helen Wills Neuroscience Institute, University of California, Berkeley % For debugging %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TODO warning on;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TODO %% Open file [fid,msg] = fopen(fname,'r'); assert(fid~=-1,'ReadBesaMatlab:ErrorOpeningFile',msg); % Get length of file fseek(fid,0,'eof'); file_length = ftell(fid); fseek(fid,0,'bof'); %% Header Block [~,ofst_BCF1] = read_tag_offset_pair(fid,'BCF1'); % Read data in header block while ~feof(fid) && ftell(fid) < (8+ofst_BCF1) % 8 for header tag ('BCF1') and header offset (uint32) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'VERS' % File version header.orig.file_info.besa_file_version = read_chars(fid,current_length); case 'OFFM' % Index of first 'file main info' block (BFMI) BFMI_offset = fread(fid,1,'*int64'); case 'OFTL' % Index of first 'tag list' block (BTAG) BTAG_offset = fread(fid,1,'*int64'); case 'OFBI' % Index of first 'channel and location' block (BCAL) BCAL_offset = fread(fid,1,'*int64'); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if((ftell(fid)+current_length) <= file_length) if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in header block [BCF1]))',current_length); end else fclose(fid); error('ReadBesaMatlab:ErrorSkippingForwardAfterUnexpectedTag','Offset after unexpected [%d] tag points to beyond eof [%d]',current_length,file_length); end end end % Check for necessary header data if ~exist('BFMI_offset','var') fclose(fid); error('ReadBesaMatlab:ErrorNoHeaderBFMI','No BFMI block found in header'); end if ~exist('BTAG_offset','var') fclose(fid); error('ReadBesaMatlab:ErrorNoHeaderBTAG','No BTAG block found in header'); end if ~exist('BCAL_offset','var') fclose(fid); error('ReadBesaMatlab:ErrorNoHeaderBCAL','No BCAL block found in header'); end %% 'tag list' blocks header.orig.tags.next_BTAG_ofst = BTAG_offset; header.orig.tags.offsets = []; header.orig.tags.n_tags = 0; % Keep reading until no more BTAG blocks while header.orig.tags.next_BTAG_ofst > 0 header.orig.tags = read_BTAG(fid, file_length, header.orig.tags); end header.orig.tags = rmfield(header.orig.tags,'next_BTAG_ofst'); % Check that file is not much shorter than expected % This does not take into account length of final block but might still be useful if(file_length <= header.orig.tags.tags.position(end)) fclose(fid); error('ReadBesaMatlab:ErrorFileTooShort','Expected file at least %d bytes long but file is %d bytes long',header.orig.tags.tags(end).position,file_length); end %% 'file main info' blocks header.orig.file_info.next_BFMI_ofst = BFMI_offset; header.orig.file_info.offsets = []; % Keep reading until no more BFMI blocks while header.orig.file_info.next_BFMI_ofst > 0 header.orig.file_info = read_BFMI(fid, file_length, header.orig.file_info); end header.orig.file_info = rmfield(header.orig.file_info,'next_BFMI_ofst'); % NEED TO IMPLEMENT OVERWRITES %%%%%%%%%%%%%%%%%%%%%%%%%%% TODO %% 'channel and location' blocks header.orig.channel_info.next_BCAL_ofst = BCAL_offset; header.orig.channel_info.offsets = []; % Keep reading until no more BCAL blocks while header.orig.channel_info.next_BCAL_ofst > 0 header.orig.channel_info = read_BCAL(fid, file_length, header.orig.channel_info); end header.orig.channel_info = rmfield(header.orig.channel_info,'next_BCAL_ofst'); % NEED TO IMPLEMENT OVERWRITES %%%%%%%%%%%%%%%%%%%%%%%%%%% TODO if ~isfield(header.orig.channel_info,'n_channels') error('ReadBesaMatlab:ErrorNoHeaderNChannels','Missing number of channels in header [BCAL:CHNR]'); end % Combine info from channel_info.coord_data and channel_info.channel_states to get actual coordinate data if(isfield(header.orig.channel_info,'channel_states') && isfield(header.orig.channel_info,'coord_data')) for channel_n = 1:header.orig.channel_info.n_channels %header.orig.channel_info.channel_locations(channel_n) = []; header.orig.channel_info.channel_locations(channel_n).x = NaN; header.orig.channel_info.channel_locations(channel_n).y = NaN; header.orig.channel_info.channel_locations(channel_n).z = NaN; header.orig.channel_info.channel_locations(channel_n).xori = NaN; % Orientation header.orig.channel_info.channel_locations(channel_n).yori = NaN; header.orig.channel_info.channel_locations(channel_n).zori = NaN; header.orig.channel_info.channel_locations(channel_n).x2 = NaN; % Second coil header.orig.channel_info.channel_locations(channel_n).y2 = NaN; header.orig.channel_info.channel_locations(channel_n).z2 = NaN; if( header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_SCALPELECTRODE || ... header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_MAGNETOMETER || ... header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_AXIAL_GRADIOMETER || ... header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_PLANAR_GRADIOMETER || ... header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_MEGREFERENCE ) header.orig.channel_info.channel_locations(channel_n).x = double(header.orig.channel_info.coord_data(channel_n,1)); header.orig.channel_info.channel_locations(channel_n).y = double(header.orig.channel_info.coord_data(channel_n,2)); header.orig.channel_info.channel_locations(channel_n).z = double(header.orig.channel_info.coord_data(channel_n,3)); end if( header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_MAGNETOMETER || ... header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_AXIAL_GRADIOMETER || ... header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_PLANAR_GRADIOMETER || ... header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_MEGREFERENCE ) header.orig.channel_info.channel_locations(channel_n).xori = double(header.orig.channel_info.coord_data(channel_n,7)); header.orig.channel_info.channel_locations(channel_n).yori = double(header.orig.channel_info.coord_data(channel_n,8)); header.orig.channel_info.channel_locations(channel_n).zori = double(header.orig.channel_info.coord_data(channel_n,9)); end if( header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_AXIAL_GRADIOMETER || ... header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_PLANAR_GRADIOMETER || ... header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_MEGREFERENCE ) header.orig.channel_info.channel_locations(channel_n).x2 = double(header.orig.channel_info.coord_data(channel_n,4)); header.orig.channel_info.channel_locations(channel_n).y2 = double(header.orig.channel_info.coord_data(channel_n,5)); header.orig.channel_info.channel_locations(channel_n).z2 = double(header.orig.channel_info.coord_data(channel_n,6)); end if( header.orig.channel_info.channel_states(channel_n).BSA_CHANTYPE_MEGREFERENCE ) if( header.orig.channel_info.channel_locations(channel_n).x2==0 && ... header.orig.channel_info.channel_locations(channel_n).y2==0 && ... header.orig.channel_info.channel_locations(channel_n).z2==0 ) header.orig.channel_info.channel_locations(channel_n).x2 = NaN; header.orig.channel_info.channel_locations(channel_n).y2 = NaN; header.orig.channel_info.channel_locations(channel_n).z2 = NaN; end end end end %% Events % Collect event block info header.orig.events.offsets = header.orig.tags.tags.position(strcmp(header.orig.tags.tags.type,'BEVT')); header.orig.events.offsets = sort(header.orig.events.offsets, 'ascend'); % Later blocks overwrite matching events for block_n = 1:numel(header.orig.events.offsets) header.orig.events = read_BEVT(fid, file_length, header.orig.events, header.orig.events.offsets(block_n)); end % NEED TO IMPLEMENT OVERWRITES %%%%%%%%%%%%%%%%%%%%%%%%%%% TODO %% Reorganize header structure header.nChans = header.orig.channel_info.n_channels; if isfield(header.orig.file_info,'s_rate') header.Fs = header.orig.file_info.s_rate; else warning('ReadBesaMatlab:WarningMissingHeaderInfo','Missing sample rate in header'); header.Fs = []; end if isfield(header.orig.file_info,'n_samples') header.nSamples = header.orig.file_info.n_samples; else warning('ReadBesaMatlab:WarningMissingHeaderInfo','Missing number of samples in header'); header.nSamples = []; end header.nSamplesPre = 0; % Continuous data header.nTrials = 1; % Continuous data % Channel labels if isfield(header.orig.channel_info,'channel_labels') header.label = header.orig.channel_info.channel_labels; else warning('ReadBesaMatlab:WarningMissingHeaderInfo','Missing channel labels in header.orig. Creating default channel names'); for channel_n = 1:header.nChans header.label{channel_n} = sprintf('chan%03d', channel_n); end end % Channel coordinates if isfield(header.orig.channel_info,'channel_locations') for channel_n = 1:header.nChans header.elec.label{channel_n} = header.label{channel_n}; header.elec.pnt(channel_n,1) = header.orig.channel_info.channel_locations(channel_n).x; header.elec.pnt(channel_n,2) = header.orig.channel_info.channel_locations(channel_n).y; header.elec.pnt(channel_n,3) = header.orig.channel_info.channel_locations(channel_n).z; end end function tags = read_BTAG(fid, file_length, tags) %% Read tag block % tags [structure] - Existing or blank BTAG structure % Blank needs fields: % next_BTAG_ofst - file offset for BTAG to be read % offsets = [] % n_tags = 0 % file_length [scalar] - Length of file in bytes % fid [scalar] - File identifier % Skip to start of BTAG section if(fseek(fid,tags.next_BTAG_ofst,'bof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [BTAG]',tags.next_BTAG_ofst); end tags.offsets(end+1) = tags.next_BTAG_ofst; % Read BTAG tag and offset [~,tag_block_length] = read_tag_offset_pair(fid,'BTAG'); % Untagged offset to next BTAG section tags.next_BTAG_ofst = fread(fid,1,'*int64'); % Loop through all tags in data section while ftell(fid) < (uint64(tags.offsets(end))+uint64(tag_block_length)) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'TAGE' % Tag list entry tags.n_tags = tags.n_tags+1; tags.tags.type{tags.n_tags} = fread(fid,4,'*char')'; tags.tags.position(tags.n_tags) = fread(fid,1,'*uint64'); tags.tags.n_samples(tags.n_tags) = double(fread(fid,1,'*uint32')); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if((ftell(fid)+current_length) <= file_length) if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BTAG]))',current_length); end else fclose(fid); error('ReadBesaMatlab:ErrorSkippingForwardAfterUnexpectedTag','Offset after unexpected [%d] tag points to beyond eof [%d]',current_length,file_length); end end end % Check that expected amout of file was read expected_length = double(tag_block_length) + 8; % 8 for tag and offset if((tags.offsets(end)+expected_length) ~= ftell(fid)) warning('ReadBesaMatlab:WarningDidNotReadExactBlockLength','%d bytes off. Read %d bytes from tag block. Should have read %d bytes', ... (ftell(fid)-tags.offsets(end))-expected_length,ftell(fid)-tags.offsets(end),expected_length); end function file_info = read_BFMI(fid, file_length, file_info) %% Read file main info block % file_info [structure] - Existing or blank BFMI structure % Blank needs fields: % next_BFMI_ofst - file offset for BFMI to be read % offsets = [] % file_length [scalar] - Length of file in bytes % fid [scalar] - File identifier % Skip to start of BFMI section if(fseek(fid,file_info.next_BFMI_ofst,'bof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [BFMI]',file_info.next_BFMI_ofst); end file_info.offsets(end+1) = file_info.next_BFMI_ofst; % Read BFMI tag and offset [~,fileinfo_block_length] = read_tag_offset_pair(fid,'BFMI'); % Untagged offset to next BFMI section file_info.next_BFMI_ofst = fread(fid,1,'*int64'); % Create staff field if it doesn't exist already. This is necessary because % there is no indication of how many staff to expect, so to increment an % array, you need an existing array if(~isfield(file_info,'staff')) file_info.staff = []; end % Loop through all tags in data section while ftell(fid) < (uint64(file_info.offsets(end))+uint64(fileinfo_block_length)) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'SAMT' % Total number of samples file_info.n_samples = double(fread(fid,1,'*int64')); case 'SAMP' % Number of samples per second file_info.s_rate = fread(fid,1,'*double'); case 'FINN' % Name of the institution file_info.institution.name = read_chars(fid,current_length); case 'FINA' % Address of the institution fina_end = ftell(fid)+current_length; while ~feof(fid) && ftell(fid) < fina_end [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'ASTR' % Street name file_info.institution.street_name = read_chars(fid,current_length); case 'ASTA' % State file_info.institution.state = read_chars(fid,current_length); case 'ACIT' % City file_info.institution.city = read_chars(fid,current_length); case 'APOS' % Post code file_info.institution.post_code = read_chars(fid,current_length); case 'ACOU' % Country file_info.institution.country = read_chars(fid,current_length); case 'APHO' % Phone number file_info.institution.phone_number = read_chars(fid,current_length); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if((ftell(fid)+current_length) <= file_length) if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BFMI:FINA]))',current_length); end else fclose(fid); error('ReadBesaMatlab:ErrorSkippingForwardAfterUnexpectedTag','Offset after unexpected [%d] tag points to beyond eof [%d]',current_length,file_length); end end end clear fina_end; case 'FENA' % Encryption algorithm file_info.encryption = read_chars(fid,current_length); case 'FCOA' % Compression algorithm file_info.compression = read_chars(fid,current_length); case 'RECD' % Recording start date and time file_info.recording_date.start = read_chars(fid,current_length); case 'RECE' % Recording end date and time file_info.recording_date.end = read_chars(fid,current_length); case 'RECO' % Recording offset to GMT file_info.recording_date.gmt_offset = fread(fid,1,'*single'); case 'RECS' % Recording system file_info.recording_system.name = read_chars(fid,current_length); case 'RIBN' % Name of the input box file_info.recording_system.info = read_chars(fid,current_length); case 'RESW' % Name of recording software file_info.recording_system.software = read_chars(fid,current_length); case 'RATC' % Amplifier time constant file_info.recording_system.time_constant = fread(fid,1,'*single'); case 'RSEQ' % Sequence number file_info.sequence_n = double(fread(fid,1,'*uint32')); case 'RSID' % Session unique identifier file_info.session_id = read_chars(fid,current_length); case 'RSNR' % Session number file_info.sequence_n = double(fread(fid,1,'*int32')); case 'RSTC' % Study comment file_info.comment = read_chars(fid,current_length); case 'RSTA' % Responsible staff % This assumes that, for each staff member, all fields are contiguous % Otherwise, the indices may not line up file_info.staff(end+1).name = ''; file_info.staff(end+1).initials = ''; file_info.staff(end+1).function = ''; rsta_end = ftell(fid)+current_length; while ~feof(fid) && ftell(fid) < rsta_end [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'SNAM' % Name file_info.staff(end).name = read_chars(fid,current_length); case 'ASTA' % Initials file_info.staff(end).initials = read_chars(fid,current_length); case 'ACIT' % Function file_info.staff(end).function = read_chars(fid,current_length); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if((ftell(fid)+current_length) <= file_length) if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BFMI:RSTA]))',current_length); end else fclose(fid); error('ReadBesaMatlab:ErrorSkippingForwardAfterUnexpectedTag','Offset after unexpected [%d] tag points to beyond eof [%d]',current_length,file_length); end end end clear rsta_end; case 'PNAF' % Subject first name file_info.subject.name.first = read_chars(fid,current_length); case 'PNAM' % Subject middle name file_info.subject.name.middle = read_chars(fid,current_length); case 'PATN' % Subject last name file_info.subject.name.last = read_chars(fid,current_length); case 'PNAA' % Anonymized subject name file_info.subject.anon_name = read_chars(fid,current_length); case 'PNAT' % Subject title file_info.subject.title = read_chars(fid,current_length); case 'PATD' % Subject date of birth file_info.subject.birthdate = read_chars(fid,current_length); case 'PDOD' % Subject date of death file_info.subject.deathdate = read_chars(fid,current_length); case 'PAGE' % Subject gender file_info.subject.gender = read_chars(fid,current_length); case 'PAWE' % Subject weight file_info.subject.weight = fread(fid,1,'*single'); case 'PAHE' % Subject height file_info.subject.height = fread(fid,1,'*single'); case 'PAMS' % Subject marital status file_info.subject.marital_status = read_chars(fid,current_length); case 'PAAD' % Subject address paad_end = ftell(fid)+current_length; while ~feof(fid) && ftell(fid) < paad_end [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'ASTR' % Street name file_info.subject.address.street_name = read_chars(fid,current_length); case 'ASTA' % State file_info.subject.address.state = read_chars(fid,current_length); case 'ACIT' % City file_info.subject.address.city = read_chars(fid,current_length); case 'APOS' % Post code file_info.subject.address.post_code = read_chars(fid,current_length); case 'ACOU' % Country file_info.subject.address.country = read_chars(fid,current_length); case 'APHO' % Phone number file_info.subject.address.phone_number = read_chars(fid,current_length); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if((ftell(fid)+current_length) <= file_length) if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BFMI:PAAD]))',current_length); end else fclose(fid); error('ReadBesaMatlab:ErrorSkippingForwardAfterUnexpectedTag','Offset after unexpected [%d] tag points to beyond eof [%d]',current_length,file_length); end end end clear paad_end; case 'PALA' % Subject language file_info.subject.language = read_chars(fid,current_length); case 'PAMH' % Subject medical history file_info.subject.medical_history = read_chars(fid,current_length); case 'PATC' % Subject comment file_info.subject.comment = read_chars(fid,current_length); case 'PATI' % Subject ID file_info.subject.id = read_chars(fid,current_length); case 'INF1' % Additional information 1 file_info.additional_info.inf1 = read_chars(fid,current_length); case 'INF2' % Additional information 2 file_info.additional_info.inf2 = read_chars(fid,current_length); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if((ftell(fid)+current_length) <= file_length) if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BFMI]))',current_length); end else fclose(fid); error('ReadBesaMatlab:ErrorSkippingForwardAfterUnexpectedTag','Offset after unexpected [%d] tag points to beyond eof [%d]',current_length,file_length); end end end % Check that expected amout of file was read expected_length = double(fileinfo_block_length) + 8; % 8 for tag and offset if((file_info.offsets(end)+expected_length) ~= ftell(fid)) warning('ReadBesaMatlab:WarningDidNotReadExactBlockLength','%d bytes off. Read %d bytes from file info block. Should have read %d bytes', ... (ftell(fid)-file_info.offsets(end))-expected_length,ftell(fid)-file_info.offsets(end),expected_length); end function channel_info = read_BCAL(fid, file_length, channel_info) %% Read channel info block % channel_info [structure] - Existing or blank BCAL structure % Blank needs fields: % next_BFMI_ofst - file offset for BCAL to be read % offsets = [] % file_length [scalar] - Length of file in bytes % fid [scalar] - File identifier % Skip to start of BCAL section if(fseek(fid,channel_info.next_BCAL_ofst,'bof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [BCAL]',channel_info.next_BCAL_ofst); end channel_info.offsets(end+1) = channel_info.next_BCAL_ofst; % Read BCAL tag and offset [~,channel_block_length] = read_tag_offset_pair(fid,'BCAL'); % Untagged offset to next BCAL section channel_info.next_BCAL_ofst = fread(fid,1,'*int64'); % Loop through all tags in data section while ftell(fid) < (uint64(channel_info.offsets(end))+uint64(channel_block_length)) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'CHFL' % Channel flag channel_info.channel_flags.flag = fread(fid,1,'*uint32'); channel_info.channel_flags.BSA_ELECTRODE_COORDINATES_FROM_LABELS = logical(bitand(channel_info.channel_flags.flag,uint32(hex2dec('0001')),'uint32')); channel_info.channel_flags.BSA_SUPPRESS_SPHERE_TO_ELLIPSOID_TRANSFORMATION = logical(bitand(channel_info.channel_flags.flag,uint32(hex2dec('0002')),'uint32')); channel_info.channel_flags.BSA_ELECTRODE_COORDINATES_ON_SPHERE = logical(bitand(channel_info.channel_flags.flag,uint32(hex2dec('0004')),'uint32')); channel_info.channel_flags.BSA_ADAPT_SPHERICAL_EEG_TO_MEG_COORDS = logical(bitand(channel_info.channel_flags.flag,uint32(hex2dec('0008')),'uint32')); channel_info.channel_flags.BSA_SOURCE_CHANNELS_DERIVED_FROM_MEG = logical(bitand(channel_info.channel_flags.flag,uint32(hex2dec('0010')),'uint32')); case 'CHTS' % Channel type and states of a channel with the specified index channel_n = double(fread(fid,1,'*uint16'))+1; % Plus 1 because index starts at 0 channel_info.channel_states(channel_n).flag = fread(fid,1,'*uint32'); channel_info.channel_states(channel_n).BSA_CHANTYPE_UNDEFINED = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00000000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_POLYGRAPHIC = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00010000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_TRIGGER = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00020000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_CORTICALGRID = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00040000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_INTRACRANIAL = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00080000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_SCALPELECTRODE = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00100000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_MAGNETOMETER = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00200000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_AXIAL_GRADIOMETER = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00400000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_PLANAR_GRADIOMETER = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('01000000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_MEGREFERENCE = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00800000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_NKC_REFERENCE = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('02000000')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANTYPE_CHANSTATE_BAD = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00000001')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANSTATE_REFERENCE = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00000002')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANSTATE_INTERPOLRECORDED = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00000004')),'uint32')); channel_info.channel_states(channel_n).BSA_CHANSTATE_INVISIBLE = logical(bitand(channel_info.channel_states(channel_n).flag,uint32(hex2dec('00001000')),'uint32')); case 'CHCO' % Channel coordinates in mm n_channels = current_length / 4 / 9; % Divide by 4 for *single and by 9 for number of elements per channel channel_info.coord_data = zeros(n_channels,9,'single'); for channel_n = 1:n_channels channel_info.coord_data(channel_n,:) = fread(fid,9,'*single'); end % More processing done later to obtain actual coordinates case 'CHNR' % Total number of channels channel_info.n_channels = double(fread(fid,1,'*uint16')); case 'CHLA' % Channel label of a channel with the specified index channel_n = double(fread(fid,1,'*uint16'))+1; % Plus 1 because index starts at 0 channel_info.channel_labels{channel_n} = read_chars(fid,current_length-2); % Subtract 2 from offet for channel_n case 'CHET' % Electrode thickness channel_info.electrode_thickness = fread(fid,1,'*single'); case 'CHSI' % Spline interpolation smoothing constant channel_info.spline_smoothing_constant = fread(fid,1,'*single'); case 'CHLS' % Least significant bits of data channel_info.lsbs = double(fread(fid,current_length/4,'*single')); % Please note that zero or negative LSB values are not allowed. If a non-positive value is found in the array, a value of "1.f" is used instead. %%%%%%%%%%%%%%%%%%%%%%%%%%% case 'CHSF' % Sampling frequency channel_info.s_rates = fread(fid,current_length/4,'*double'); case 'HCMM' % Head center in mm channel_info.head_center.x = fread(fid,1,'*single'); channel_info.head_center.y = fread(fid,1,'*single'); channel_info.head_center.z = fread(fid,1,'*single'); case 'HRMM' % Head radius in mm channel_info.head_radius = fread(fid,1,'*single'); case 'FIDC' % Fiducial coordinates in mm channel_info.fiducial.nasion.x = fread(fid,1,'*single'); channel_info.fiducial.nasion.y = fread(fid,1,'*single'); channel_info.fiducial.nasion.z = fread(fid,1,'*single'); channel_info.fiducial.left_preauricular.x = fread(fid,1,'*single'); channel_info.fiducial.left_preauricular.y = fread(fid,1,'*single'); channel_info.fiducial.left_preauricular.z = fread(fid,1,'*single'); channel_info.fiducial.right_preauricular.x = fread(fid,1,'*single'); channel_info.fiducial.right_preauricular.y = fread(fid,1,'*single'); channel_info.fiducial.right_preauricular.z = fread(fid,1,'*single'); case 'HSPN' % Total number of head surface points channel_info.n_addn_surf_pnts = double(fread(fid,1,'*int16')); case 'HSPC' % Head surface point coordinates channel_n = double(fread(fid,1,'*uint16'))+1; % Plus 1 because index starts at 0 channel_info.head_surface_points{channel_n}.x = fread(fid,1,'*single'); channel_info.head_surface_points{channel_n}.y = fread(fid,1,'*single'); channel_info.head_surface_points{channel_n}.z = fread(fid,1,'*single'); case 'HSPD' % Head surface point labels channel_n = double(fread(fid,1,'*uint16'))+1; % Plus 1 because index starts at 0 channel_info.head_surface_points{channel_n}.label = read_chars(fid,current_length-2); % Subtract 2 from offet for channel_n case 'CHCU' % Channel units channel_n = double(fread(fid,1,'*uint16'))+1; % Plus 1 because index starts at 0 channel_info.channel_units{channel_n} = read_chars(fid,current_length-2); % Subtract 2 from offet for channel_n case 'CHFI' % Filter information offset_chfi = ftell(fid); offset_end_chfi = int64(offset_chfi)+int64(current_length); channel_n = 0; while ftell(fid) < offset_end_chfi channel_n=channel_n+1; filter_object_offset = ftell(fid); filter_object_size = fread(fid,1,'*uint32'); channel_info.filter_info(channel_n).state.state = fread(fid,1,'*uint32'); channel_info.filter_info(channel_n).state.FLT_LOWCUTOFF_ACTIVE = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000001')),'uint32')); channel_info.filter_info(channel_n).state.FLT_HIGHCUTOFF_ACTIVE = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000002')),'uint32')); channel_info.filter_info(channel_n).state.FLT_NOTCH_ACTIVE = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000004')),'uint32')); channel_info.filter_info(channel_n).state.FLT_BAND_PASS_ACTIVE = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000008')),'uint32')); channel_info.filter_info(channel_n).state.FLT_PRE_LOWCUTOFF_ACTIVE = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('01000000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_PRE_SUBTRACT_BASELINE = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('02000000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_LOWCUTOFF_TYPE_FORWARD = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_LOWCUTOFF_TYPE_ZERO_PHASE = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000010')),'uint32')); channel_info.filter_info(channel_n).state.FLT_LOWCUTOFF_TYPE_BACKWARD = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000020')),'uint32')); channel_info.filter_info(channel_n).state.FLT_LOWCUTOFF_SLOPE_06DB = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_LOWCUTOFF_SLOPE_12DB = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000100')),'uint32')); channel_info.filter_info(channel_n).state.FLT_LOWCUTOFF_SLOPE_24DB = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000200')),'uint32')); channel_info.filter_info(channel_n).state.FLT_LOWCUTOFF_SLOPE_48DB = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000300')),'uint32')); channel_info.filter_info(channel_n).state.FLT_HIGHCUTOFF_TYPE_ZERO_PHASE = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000300')),'uint32')); channel_info.filter_info(channel_n).state.FLT_HIGHCUTOFF_TYPE_FORWARD = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00001000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_HIGHCUTOFF_TYPE_BACKWARD = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00002000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_HIGHCUTOFF_SLOPE_12DB = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00000000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_HIGHCUTOFF_SLOPE_06DB = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00010000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_HIGHCUTOFF_SLOPE_24DB = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00020000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_HIGHCUTOFF_SLOPE_48DB = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00030000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_NOTCH_REMOVE_2ND_HARMONIC = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00100000')),'uint32')); channel_info.filter_info(channel_n).state.FLT_NOTCH_REMOVE_3RD_HARMONIC = logical(bitand(channel_info.filter_info(channel_n).state.state,uint32(hex2dec('00200000')),'uint32')); channel_info.filter_info(channel_n).low_cutoff = fread(fid,1,'*single'); channel_info.filter_info(channel_n).high_cutoff = fread(fid,1,'*single'); channel_info.filter_info(channel_n).notch_freq = fread(fid,1,'*single'); channel_info.filter_info(channel_n).notch_width = fread(fid,1,'*single'); channel_info.filter_info(channel_n).pass_freq = fread(fid,1,'*single'); channel_info.filter_info(channel_n).pass_width = fread(fid,1,'*single'); if(ftell(fid) ~= filter_object_offset+filter_object_size) warning('ReadBesaMatlab:WarningFilterInfoObject','Did not read expected number bytes in filter object [BCAL:CHFI]. Filter information may be incorrect'); end end % Check that expected amout of file was read and move to correct position if not if(ftell(fid) ~= offset_end_chfi) warning('ReadBesaMatlab:WarningFilterInfoBlock','Did not read expected number of bytes in filter info block [BCAL:CHFI]. Filter information may be incorrect. Skipping to next block'); fseek(fid,offset_end_chfi+1,'bof'); end % Somewhat complicated structure, no test data %%%%%%%%%%%%%%%%%% TODO case 'CHNU' % Channel numbers channel_info.channel_ns = fread(fid,current_length/4,'*int32'); case 'CHCM' % Channel comments channel_n = double(fread(fid,1,'*uint16'))+1; % Plus 1 because index starts at 0 channel_info.channel_comments{channel_n} = read_chars(fid,current_length-2); % Subtract 2 from offet for channel_n case 'COMC' % BESA CTF component. Internal use only if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [BCAL:%s]',current_length,current_tag); end case 'COMH' % BESA head transformation. Internal use only if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [BCAL:%s]',current_length,current_tag); end case 'CHSC' % BESA spatial components. Internal use only if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [BCAL:%s]',current_length,current_tag); end otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if((ftell(fid)+current_length) <= file_length) if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag [BCAL]))',current_length); end else fclose(fid); error('ReadBesaMatlab:ErrorSkippingForwardAfterUnexpectedTag','Offset after unexpected [%d] tag points to beyond eof [%d]',current_length,file_length); end end end % Check that expected amout of file was read expected_length = double(channel_block_length) + 8; % 8 for tag and offset if((channel_info.offsets(end)+expected_length) ~= ftell(fid)) warning('ReadBesaMatlab:WarningDidNotReadExactBlockLength','%d bytes off. Read %d bytes from channel block. Should have read %d bytes', ... (ftell(fid)-channel_info.offsets(end))-expected_length,ftell(fid)-channel_info.offsets(end),expected_length); end %% EVENT BLOCK FUNCTIONS function events = read_BEVT(fid, file_length, events, BEVT_offset) %% Read event block % BEVT_offset [scalar] - offset of current event block start % events [structure] - Existing or blank BEVT structure % Blank needs fields: % offsets - sorted array of location of all event blocks % file_length [scalar] - Length of file in bytes % fid [scalar] - File identifier % Skip to start of BEVT section if(fseek(fid,BEVT_offset,'bof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [BEVT]',BEVT_offset); end % Read BEVT tag and offset [~,event_block_length] = read_tag_offset_pair(fid,'BEVT'); % Read LIST tag and offset but don't save anything read_tag_offset_pair(fid,'LIST'); % Now inside of LIST block % Read HEAD tag - Assuming that it is first tag in LIST block [~,head_length] = read_tag_offset_pair(fid,'HEAD'); head_offset = ftell(fid); % Read data in header block while ~feof(fid) && ftell(fid) < (head_offset+head_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'EVTS' events.n_events = double(fread(fid,1,'*uint32')); case 'VERS' events.version = double(fread(fid,1,'*uint32')); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if((ftell(fid)+current_length) <= file_length) if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:HEAD]))',current_length); end else fclose(fid); error('ReadBesaMatlab:ErrorSkippingForwardAfterUnexpectedTag','Offset after unexpected [%d] tag points to beyond eof [%d]',current_length,file_length); end end end % Read all events as structures and put them into a cell array for event_n = 1:events.n_events [current_tag,current_length] = read_tag_offset_pair(fid); events.events{event_n} = read_event_tag(fid,current_tag,current_length); end % Check that expected amout of file was read expected_length = double(event_block_length) + 8; % 8 for tag and offset if((BEVT_offset+expected_length) ~= ftell(fid)) warning('ReadBesaMatlab:WarningDidNotReadExactBlockLength','%d bytes off. Read %d bytes from event block. Should have read %d bytes', ... (ftell(fid)-BEVT_offset)-expected_length,ftell(fid)-BEVT_offset,expected_length); end function event_obj = read_event_tag(fid,event_tag,event_length) % Read an event into a structure % Create the event object event_obj.evttype = event_tag; switch event_tag case 'BASE' % Base event tag event_obj = read_event_tag_base(fid,ftell(fid),event_length,event_obj); case 'COMM' % Comment event tag event_obj = read_event_tag_comm(fid,ftell(fid),event_length,event_obj); case 'MARK' % Marker event tag event_obj = read_event_tag_mark(fid,ftell(fid),event_length,event_obj); case 'GENE' % Generic event tag event_obj = read_event_tag_gene(fid,ftell(fid),event_length,event_obj); case 'SEGM' % Segment event tag event_obj = read_event_tag_segm(fid,ftell(fid),event_length,event_obj); case 'ASGM' % Average segment start event tag event_obj = read_event_tag_asgm(fid,ftell(fid),event_length,event_obj); case 'MPS ' % Multiple pattern search event tag % used by BESA internally if(fseek(fid,event_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [LIST:MPS]',event_length); end case 'MPSC' % Classified multiple pattern search event tag % used by BESA internally if(fseek(fid,event_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [LIST:MPSC]',event_length); end case 'PATT' % Pattern event tag event_obj = read_event_tag_patt(fid,ftell(fid),event_length,event_obj); case 'TRIG' % Trigger event tag event_obj = read_event_tag_trig(fid,ftell(fid),event_length,event_obj); case 'PAIR' % Paired event tag event_obj = read_event_tag_pair(fid,ftell(fid),event_length,event_obj); case 'ARTI' % Artifact event tag event_obj = read_event_tag_arti(fid,ftell(fid),event_length,event_obj); case 'EPOC' % Epoch event tag event_obj = read_event_tag_epoc(fid,ftell(fid),event_length,event_obj); case 'IMP ' % Impedance event tag event_obj = read_event_tag_imp(fid,ftell(fid),event_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',event_tag,ftell(fid)); if(fseek(fid,event_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [LIST]))',event_length); end end function event_obj = read_event_tag_base(fid,base_offset,base_length, event_obj) % Read data in the COMM event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (base_offset+base_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'SAMP' % Sample index (zero based) event_obj.sample_n = fread(fid,1,'*int64'); case 'TIME' % Event time event_obj.time.year = fread(fid,1,'*int16'); event_obj.time.month = fread(fid,1,'*int16'); event_obj.time.dayOfWeek = fread(fid,1,'*int16'); event_obj.time.day = fread(fid,1,'*int16'); event_obj.time.hour = fread(fid,1,'*int16'); event_obj.time.minute = fread(fid,1,'*int16'); event_obj.time.second = fread(fid,1,'*int16'); event_obj.time.milliseconds = fread(fid,1,'*int16'); event_obj.time.microseconds = fread(fid,1,'*single'); event_obj.time.stateFlag = fread(fid,1,'*uint64'); case 'SIDX' % Segment index (zero based) event_obj.segment_index = fread(fid,1,'*int32'); case 'CODE' % Event code (zero based) % This value is used by events of type Pattern (PATT) and Trigger (TRIG) % to store the pattern number and the trigger code. Note that the number/code minus 1 is stored. % Additionally, events of type Artifact (ARTI) and Epoch (EPOC) use the code value % internally due to historical reasons. Other event types may use the code value to % store additional information. event_obj.code = fread(fid,1,'*int32'); case 'EVID' % Internal BESA event ID (zero based) event_obj.besa_event_id = fread(fid,1,'*int32'); case 'STAT' % Event state event_obj.state.value = fread(fid,1,'*uint32'); event_obj.state.EVT_STATE_MARKED1 = logical(bitand(event_obj.state.value,uint32(hex2dec('00000010')),'uint32')); event_obj.state.EVT_STATE_MARKED2 = logical(bitand(event_obj.state.value,uint32(hex2dec('00000020')),'uint32')); event_obj.state.EVT_STATE_MARKED3 = logical(bitand(event_obj.state.value,uint32(hex2dec('00000040')),'uint32')); event_obj.state.EVT_STATE_MARKED4 = logical(bitand(event_obj.state.value,uint32(hex2dec('00000080')),'uint32')); event_obj.state.EVT_STATE_DELETED = logical(bitand(event_obj.state.value,uint32(hex2dec('01000000')),'uint32')); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:BASE]))',current_length); end end end function event_obj = read_event_tag_comm(fid,comm_offset,comm_length, event_obj) % Read data in the COMM event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (comm_offset+comm_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'TEXT' % Event text event_obj.text = read_chars(fid,current_length); case 'BASE' event_obj = read_event_tag_base(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:COMM]))',current_length); end end end function event_obj = read_event_tag_mark(fid,mark_offset,mark_length, event_obj) % Read data in the MARK event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (mark_offset+mark_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'BASE' event_obj = read_event_tag_base(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:MARK]))',current_length); end end end function event_obj = read_event_tag_gene(fid,gene_offset,gene_length, event_obj) % Read data in the GENE event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (gene_offset+gene_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'COMM' event_obj = read_event_tag_comm(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:GENE]))',current_length); end end end function event_obj = read_event_tag_segm(fid,segm_offset,segm_length, event_obj) % Read data in the SEGM event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (segm_offset+segm_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'SBEG' % Segment start time event_obj.segment_start.year = fread(fid,1,'*int16'); event_obj.segment_start.month = fread(fid,1,'*int16'); event_obj.segment_start.dayOfWeek = fread(fid,1,'*int16'); event_obj.segment_start.day = fread(fid,1,'*int16'); event_obj.segment_start.hour = fread(fid,1,'*int16'); event_obj.segment_start.minute = fread(fid,1,'*int16'); event_obj.segment_start.second = fread(fid,1,'*int16'); event_obj.segment_start.milliseconds = fread(fid,1,'*int16'); event_obj.segment_start.microseconds = fread(fid,1,'*single'); event_obj.segment_start.stateFlag = fread(fid,1,'*uint64'); case 'DAYT' % Day time of segment start in microseconds event_obj.segment_start.dayt = fread(fid,1,'*double'); case 'INTE' % Sampling interval in microseconds event_obj.segment_start.sampling_interval = fread(fid,1,'*double'); case 'COMM' event_obj = read_event_tag_comm(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:SEGM]))',current_length); end end end function event_obj = read_event_tag_asgm(fid,asgm_offset,asgm_length, event_obj) % Read data in the ASGM event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (asgm_offset+asgm_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'STIM' % Prestimulus baseline interval in microseconds event_obj.baseline_interval = fread(fid,1,'*double'); case 'AVRS' % Number of averages event_obj.n_averages = fread(fid,1,'*int32'); case 'COMM' event_obj = read_event_tag_comm(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:ASGM]))',current_length); end end end function event_obj = read_event_tag_patt(fid,patt_offset,patt_length, event_obj) % Read data in the PATT event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (patt_offset+patt_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'BASE' event_obj = read_event_tag_base(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:PATT]))',current_length); end end end function event_obj = read_event_tag_trig(fid,trig_offset,trig_length, event_obj) % Read data in the TRIG event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (trig_offset+trig_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'CODE' % Event reaction code event_obj.reaction_code = fread(fid,1,'*int32'); case 'TIME' % Event reaction time in seconds event_obj.reaction_time = fread(fid,1,'*single'); case 'COMM' event_obj = read_event_tag_comm(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:TRIG]))',current_length); end end end function event_obj = read_event_tag_pair(fid,pair_offset,pair_length, event_obj) % Read data in the PAIR event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (pair_offset+pair_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'PART' % Event information of the partner event. % The data section is used to write the partner event information % as a data element (starting with <eventtype> tag ID of partner event). [event_tag,event_length] = read_tag_offset_pair(fid); switch event_tag case 'BASE' event_obj.partner_event = read_event_tag_base(fid,ftell(fid),event_length,event_obj); case 'COMM' event_obj.partner_event = read_event_tag_comm(fid,ftell(fid),event_length,event_obj); case 'MARK' event_obj.partner_event = read_event_tag_mark(fid,ftell(fid),event_length,event_obj); case 'GENE' event_obj.partner_event = read_event_tag_gene(fid,ftell(fid),event_length,event_obj); case 'SEGM' event_obj.partner_event = read_event_tag_segm(fid,ftell(fid),event_length,event_obj); case 'ASGM' event_obj.partner_event = read_event_tag_asgm(fid,ftell(fid),event_length,event_obj); case 'MPS ' if(fseek(fid,event_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [LIST:MPS]',event_length); end case 'MPSC' if(fseek(fid,event_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed [LIST:MPSC]',event_length); end case 'PATT' event_obj.partner_event = read_event_tag_patt(fid,ftell(fid),event_length,event_obj); case 'TRIG' event_obj.partner_event = read_event_tag_trig(fid,ftell(fid),event_length,event_obj); case 'PAIR' event_obj.partner_event = read_event_tag_pair(fid,ftell(fid),event_length,event_obj); case 'ARTI' event_obj.partner_event = read_event_tag_arti(fid,ftell(fid),event_length,event_obj); case 'EPOC' event_obj.partner_event = read_event_tag_epoc(fid,ftell(fid),event_length,event_obj); case 'IMP ' event_obj.partner_event = read_event_tag_imp(fid,ftell(fid),event_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] in PAIR:PART at offset %d',event_tag,ftell(fid)); if(fseek(fid,event_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:PAIR:PART]))',event_length); end end case 'COMM' event_obj = read_event_tag_comm(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:PAIR]))',current_length); end end end function event_obj = read_event_tag_arti(fid,arti_offset,arti_length, event_obj) % Read data in the ARTI event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (arti_offset+arti_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'PAIR' event_obj = read_event_tag_pair(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:ARTI]))',current_length); end end end function event_obj = read_event_tag_epoc(fid,epoc_offset,epoc_length, event_obj) % Read data in the EPOC event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (epoc_offset+epoc_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'PAIR' event_obj = read_event_tag_pair(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:EPOC]))',current_length); end end end function event_obj = read_event_tag_imp(fid,imp_offset,imp_length, event_obj) % Read data in the IMP event tag block % Loop through all tags in data section while ~feof(fid) && ftell(fid) < (imp_offset+imp_length) [current_tag,current_length] = read_tag_offset_pair(fid); switch current_tag case 'FORM' % Indicates the format used to store impedance values in VAL % Set to 0 if the impedance status (valid/invalid) is stored % Set to 1 if impedance values (in kOhm) are stored event_obj.impedance.format = fread(fid,1,'*int32'); case 'NR ' % Number of channels for which impedance information is stored. % (Number of elements stored in TYPE, LABL and VAL) event_obj.impedance.n_channels = fread(fid,1,'*uint32'); case 'TYPE' % Channel types % The flags used for channel type description are the same as used for the CHTS data elements (specified in chapter 2.3). % Note: Channel type and channel label are used for identification of channel % for which impedance information is set. (Compare to data elements CHTS and CHLA, specified in chapter 2.3). event_obj.impedance.types = fread(fid,event_obj.impedance.n_channels,'*uint32'); % Assumes that n_channels has been set case 'LABL' % Channel labels % Note: Channel type and channel label are used for identification of channel for which impedance information is set. % (Compare to data elements CHTS and CHLA as specified in chapter 2.3). event_obj.impedance.labels = read_chars(fid,current_length); case 'VAL ' % Impedance values % Depending on format set in FORM either an impedance STATUS (ok/not ok) or an impedance VALUE (in kOhm) is stored % A value of -1 means that the impedance is not set or invalid event_obj.impedance.values = fread(fid,event_obj.impedance.n_channels,'*single'); % Assumes that n_channels has been set case 'BASE' event_obj = read_event_tag_base(fid,ftell(fid),current_length,event_obj); otherwise % Unrecognzed tag. Try to skip forward by offset warning('ReadBesaMatlab:WarningUnexpectedTag','Read unexpected tag [%s] at offset %d',current_tag,ftell(fid)); if(fseek(fid,current_length,'cof') == -1) fclose(fid); error('ReadBesaMatlab:ErrorFseek','fseek to %d failed (after unexpected tag in [BEVT:IMP]))',current_length); end end end function outchars = read_chars(fid,n_chars) % Read n_chars characters from file at current position % Replace null character (aka char(0) or '\x0') with '' % Note transpose after fread outchars = regexprep(fread(fid,n_chars,'*char')','\x0','');
github
lcnbeapp/beapp-master
in_fopen_manscan.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/in_fopen_manscan.m
11,806
utf_8
caf4a8d115834da29621c65451b195b2
function sFile = in_fopen_manscan(DataFile) % IN_FOPEN_MANSCAN: Open a MANSCAN file (continuous recordings) % % USAGE: sFile = in_fopen_manscan(DataFile) % @============================================================================= % This software is part of the Brainstorm software: % http://neuroimage.usc.edu/brainstorm % % Copyright (c)2000-2013 Brainstorm by the University of Southern California % This software is distributed under the terms of the GNU General Public License % as published by the Free Software Foundation. Further details on the GPL % license can be found at http://www.gnu.org/copyleft/gpl.html. % % FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE % UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY % WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY % LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE. % % For more information type "brainstorm license" at command prompt. % =============================================================================@ % % Authors: Francois Tadel, 2012 %% ===== READ HEADER ===== % Get text file (.mbi) MbiFile = strrep(DataFile, '.mb2', '.mbi'); % If doesn't exist: error if ~exist(MbiFile, 'file') error('Cannot open file: missing text file .mbi'); end % Initialize header iEpoch = 1; hdr.epoch(iEpoch).Comment = {}; hdr.epoch(iEpoch).Channel = []; hdr.Events = []; curBlock = ''; % Read file line by line fid = fopen(MbiFile,'r'); while(1) % Reached the end of the file: exit the loop if feof(fid) break; end; % Read one line buf = fgetl(fid); if isempty(buf) curBlock = ''; continue; end % Split line based on space characters splitBuf = str_split(buf, [0 9 32]); if isempty(splitBuf) continue; end % Current block if ~isempty(curBlock) switch curBlock case 'event' % Ignore MANSCAN auto events if any(strcmpi(evtProp, 'Channel')) continue; end % New event iEvt = length(hdr.Events) + 1; % Read event name and epoch hdr.Events(iEvt).Name = splitBuf{1}; hdr.Events(iEvt).iEpoch = iEpoch; % Read each property for iProp = 2:length(evtProp) if strcmpi(evtProp{iProp}, 'Channel') hdr.Events(iEvt).Name = [hdr.Events(iEvt).Name '_' splitBuf{iProp}]; elseif strcmpi(evtType{iProp}, 'String') hdr.Events(iEvt).(evtProp{iProp}) = splitBuf{iProp}; else hdr.Events(iEvt).(evtProp{iProp}) = str2num(splitBuf{iProp}); end end case 'channel' % New channel iChan = length(hdr.epoch(iEpoch).Channel) + 1; % Read channel name hdr.epoch(iEpoch).Channel(iChan).Name = splitBuf{1}; % Read each property for iProp = 2:length(chanProp) if strcmpi(chanProp{iProp}, 'UnitDisplayToFile') propValue = str2num(splitBuf{iProp}); else propValue = splitBuf{iProp}; end hdr.epoch(iEpoch).Channel(iChan).(chanProp{iProp}) = propValue; end end % Next line continue; end % Detect keyword switch lower(splitBuf{1}) case 'datatypeid' iEpoch = iEpoch + 1; hdr.epoch(iEpoch).Comment = {}; hdr.epoch(iEpoch).Channel = []; case 'comment' hdr.epoch(iEpoch).Comment{end+1} = strtrim(strrep(buf, splitBuf{1}, '')); case 'event' curBlock = 'event'; evtProp = splitBuf; evtType = str_split(fgetl(fid), [0 9 32]); case 'channel' curBlock = 'channel'; chanProp = splitBuf; case 'offsetdisplayexperiment' hdr.epoch(iEpoch).OffsetDisplay = str2num(splitBuf{2}); case 'experimenttime' hdr.epoch(iEpoch).ExperimentTime = strtrim(strrep(buf, splitBuf{1}, '')); case 'worddatafile' % Read channel order hdr.epoch(iEpoch).ChannelOrder = str_split(fgetl(fid), [0 9 32]); % Read record info datainfo = str_split(fgetl(fid), [0 9 32]); hdr.epoch(iEpoch).StartData1 = str2num(datainfo{1}); hdr.epoch(iEpoch).StartData2 = str2num(datainfo{2}); hdr.epoch(iEpoch).Sweeps = str2num(datainfo{3}); hdr.epoch(iEpoch).BinFile = datainfo{4}; end end %% ===== CREATE BRAINSTORM SFILE STRUCTURE ===== % Initialize returned file structure sFile = [];%db_template('sfile'); % Add information read from header sFile.byteorder = 'l'; sFile.filename = DataFile; sFile.format = 'EEG-MANSCAN'; sFile.device = 'MANSCAN'; sFile.channelmat = []; % Comment: short filename [tmp__, sFile.comment, tmp__] = fileparts(DataFile); % Consider that the sampling rate of the file is the sampling rate of the first signal sFile.prop.sfreq = 256; sFile.prop.nAvg = 1; % No info on bad channels sFile.channelflag = ones(length(hdr.epoch(iEpoch).ChannelOrder), 1); %% ===== EPOCHS ===== if (length(hdr.epoch) <= 1) sFile.prop.samples = [0, hdr.epoch(1).Sweeps-1]; sFile.prop.times = sFile.prop.samples ./ sFile.prop.sfreq; else % Build epochs structure for iEpoch = 1:length(hdr.epoch) sFile.epochs(iEpoch).label = sprintf('Epoch #%02d', iEpoch); sFile.epochs(iEpoch).samples = [0, hdr.epoch(iEpoch).Sweeps-1]; sFile.epochs(iEpoch).times = sFile.epochs(iEpoch).samples ./ sFile.prop.sfreq; sFile.epochs(iEpoch).nAvg = 1; sFile.epochs(iEpoch).select = 1; sFile.epochs(iEpoch).bad = 0; sFile.epochs(iEpoch).channelflag = []; % Check if all the epochs have the same channel list if (iEpoch > 1) && ~isequal(hdr.epoch(iEpoch).ChannelOrder, hdr.epoch(1).ChannelOrder) error('Channel list must remain constant across epochs.'); end end % Extract global min/max for time and samples indices sFile.prop.samples = [min([sFile.epochs.samples]), max([sFile.epochs.samples])]; sFile.prop.times = [min([sFile.epochs.times]), max([sFile.epochs.times])]; end %% ===== CREATE EMPTY CHANNEL FILE ===== nChannels = length(hdr.epoch(1).ChannelOrder); ChannelMat.Comment = [sFile.device ' channels']; %ChannelMat.Channel = repmat(db_template('channeldesc'), [1, nChannels]); hdr.Gains = []; % For each channel for iChan = 1:nChannels % Find channel in description list chName = hdr.epoch(1).ChannelOrder{iChan}; iDesc = find(strcmpi({hdr.epoch(1).Channel.Name}, chName)); sDesc = hdr.epoch(1).Channel(iDesc); % Type if isfield(sDesc, 'IsEEG') && ~isempty(sDesc.IsEEG) if strcmpi(sDesc.IsEEG, 'Yes') ChannelMat.Channel(iChan).Type = 'EEG'; else ChannelMat.Channel(iChan).Type = 'Misc'; end elseif isfield(sDesc, 'IsEEG') ChannelMat.Channel(iChan).Type = 'EEG REF'; else ChannelMat.Channel(iChan).Type = 'EEG'; end % Create structure ChannelMat.Channel(iChan).Name = chName; ChannelMat.Channel(iChan).Loc = [0; 0; 0]; ChannelMat.Channel(iChan).Orient = []; ChannelMat.Channel(iChan).Weight = 1; ChannelMat.Channel(iChan).Comment = ''; % Check that this channel has a gain if isempty(hdr.epoch(1).Channel(iDesc).UnitDisplayToFile) hdr.Gains(iChan,1) = 1; else hdr.Gains(iChan,1) = hdr.epoch(1).Channel(iDesc).UnitDisplayToFile; end end % Return channel structure sFile.channelmat = ChannelMat; %% ===== FORMAT EVENTS ===== if ~isempty(hdr.Events) % Get all the epochs names uniqueEvt = unique({hdr.Events.Name}); % Create one category for each event for iEvt = 1:length(uniqueEvt) % Get all the occurrences iOcc = find(strcmpi({hdr.Events.Name}, uniqueEvt{iEvt})); % Get the samples for all the occurrences sample = [hdr.Events(iOcc).BeginSample]; duration = [hdr.Events(iOcc).DurationSamples]; % Extended event = duration is not 1 for all the markers if ~all(duration == 1) sample = [sample; sample + duration]; end % Create event structure sFile.events(iEvt).label = uniqueEvt{iEvt}; sFile.events(iEvt).samples = sample; sFile.events(iEvt).times = sample ./ sFile.prop.sfreq; sFile.events(iEvt).epochs = [hdr.Events(iOcc).iEpoch]; sFile.events(iEvt).select = 1; end end % Save file header sFile.header = hdr; function splStr = str_split( str, delimiters, isCollapse ) % STR_SPLIT: Split string. % % USAGE: str_split( str, delimiters, isCollapse=1 ) : delimiters in an array of char delimiters % str_split( str ) : default are file delimiters ('\' and '/') % % INPUT: % - str : String to split % - delimiters : String that contains all the characters used to split, default = '/\' % - isCollapse : If 1, remove all the empty entries % % OUTPUT: % - splStr : cell array of blocks found between separators % @============================================================================= % This software is part of the Brainstorm software: % http://neuroimage.usc.edu/brainstorm % % Copyright (c)2000-2013 Brainstorm by the University of Southern California % This software is distributed under the terms of the GNU General Public License % as published by the Free Software Foundation. Further details on the GPL % license can be found at http://www.gnu.org/copyleft/gpl.html. % % FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE % UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY % WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY % LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE. % % For more information type "brainstorm license" at command prompt. % =============================================================================@ % % Authors: Francois Tadel, 2008 % Default delimiters: file delimiters ('\', '/') if (nargin < 3) || isempty(isCollapse) isCollapse = 1; end if (nargin < 2) || isempty(delimiters) delimiters = '/\'; end % Empty input if isempty(str) splStr = {}; return end % Find all delimiters in string iDelim = []; for i=1:length(delimiters) iDelim = [iDelim strfind(str, delimiters(i))]; end iDelim = unique(iDelim); % If no delimiter: return the whole string if isempty(iDelim) splStr = {str}; return end % Allocates the split array splStr = cell(1, length(iDelim)+1); % First part (before first delimiter) if (iDelim(1) ~= 1) iSplitStr = 1; splStr{iSplitStr} = str(1:iDelim(1)-1); else iSplitStr = 0; end % Loop over all other delimiters for i = 2:length(iDelim) if (isCollapse && (iDelim(i) - iDelim(i-1) > 1)) || ... (~isCollapse && (iDelim(i) - iDelim(i-1) >= 1)) iSplitStr = iSplitStr + 1; splStr{iSplitStr} = str(iDelim(i-1)+1:iDelim(i)-1); end end % Last part (after last delimiter) if (iDelim(end) ~= length(str)) iSplitStr = iSplitStr + 1; splStr{iSplitStr} = str(iDelim(end)+1:end); end % Remove all the unused entries if (iSplitStr < length(splStr)) splStr(iSplitStr+1:end) = []; end
github
lcnbeapp/beapp-master
read_biosemi_bdf.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_biosemi_bdf.m
10,808
utf_8
d5b96e460d000a097fcc84b66f4679fd
function dat = read_biosemi_bdf(filename, hdr, begsample, endsample, chanindx) % READ_BIOSEMI_BDF reads specified samples from a BDF continous datafile % It neglects all trial boundaries as if the data was acquired in % non-continous mode. % % Use as % [hdr] = read_biosemi_bdf(filename); % where % filename name of the datafile, including the .bdf extension % This returns a header structure with the following elements % hdr.Fs sampling frequency % hdr.nChans number of channels % hdr.nSamples number of samples per trial % hdr.nSamplesPre number of pre-trigger samples in each trial % hdr.nTrials number of trials % hdr.label cell-array with labels of each channel % hdr.orig detailled EDF header information % % Or use as % [dat] = read_biosemi_bdf(filename, hdr, begsample, endsample, chanindx); % where % filename name of the datafile, including the .bdf extension % hdr header structure, see above % begsample index of the first sample to read % endsample index of the last sample to read % chanindx index of channels to read (optional, default is all) % This returns a Nchans X Nsamples data matrix % Copyright (C) 2006, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin==1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the header, this code is from EEGLAB's openbdf %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FILENAME = filename; % defines Seperator for Subdirectories SLASH='/'; BSLASH=char(92); cname=computer; if cname(1:2)=='PC' SLASH=BSLASH; end; fid=fopen(FILENAME,'r','ieee-le'); if fid<0 fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']); return; end; EDF.FILE.FID=fid; EDF.FILE.OPEN = 1; EDF.FileName = FILENAME; PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]); SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]); EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME)); EDF.FILE.Name = FILENAME(SPos+1:PPos-1); if SPos==0 EDF.FILE.Path = pwd; else EDF.FILE.Path = FILENAME(1:SPos-1); end; EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext]; H1=char(fread(EDF.FILE.FID,256,'char')'); % EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer %if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end; EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification %EDF.H.StartDate = H1(169:176); % 8 Byte %EDF.H.StartTime = H1(177:184); % 8 Byte EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ]; % Y2K compatibility until year 2090 if EDF.VERSION(1)=='0' if EDF.T0(1) < 91 EDF.T0(1)=2000+EDF.T0(1); else EDF.T0(1)=1900+EDF.T0(1); end; else ; % in a future version, this is hopefully not needed end; EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header % reserved = H1(193:236); % 44 Byte EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals EDF.Label = char(fread(EDF.FILE.FID,[16,EDF.NS],'char')'); EDF.Transducer = char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); EDF.PhysDim = char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'); EDF.PhysMin= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.PhysMax= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMin = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMax = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); % check validity of DigMin and DigMax if (length(EDF.DigMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n'); EDF.DigMin = -(2^15)*ones(EDF.NS,1); end if (length(EDF.DigMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n'); EDF.DigMax = (2^15-1)*ones(EDF.NS,1); end if (any(EDF.DigMin >= EDF.DigMax)) fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n'); end % check validity of PhysMin and PhysMax if (length(EDF.PhysMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n'); EDF.PhysMin = EDF.DigMin; end if (length(EDF.PhysMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n'); EDF.PhysMax = EDF.DigMax; end if (any(EDF.PhysMin >= EDF.PhysMax)) fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n'); EDF.PhysMin = EDF.DigMin; EDF.PhysMax = EDF.DigMax; end EDF.PreFilt= char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); % tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record EDF.SPR = str2num(char(tmp)); % samples per data record fseek(EDF.FILE.FID,32*EDF.NS,0); EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./(EDF.DigMax-EDF.DigMin); EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin; tmp = find(EDF.Cal < 0); EDF.Cal(tmp) = ones(size(tmp)); EDF.Off(tmp) = zeros(size(tmp)); EDF.Calib=[EDF.Off';(diag(EDF.Cal))]; %EDF.Calib=sparse(diag([1; EDF.Cal])); %EDF.Calib(1,2:EDF.NS+1)=EDF.Off'; EDF.SampleRate = EDF.SPR / EDF.Dur; EDF.FILE.POS = ftell(EDF.FILE.FID); if EDF.NRec == -1 % unknown record size, determine correct NRec fseek(EDF.FILE.FID, 0, 'eof'); endpos = ftell(EDF.FILE.FID); EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2)); fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof'); H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records end; EDF.Chan_Select=(EDF.SPR==max(EDF.SPR)); for k=1:EDF.NS if EDF.Chan_Select(k) EDF.ChanTyp(k)='N'; else EDF.ChanTyp(k)=' '; end; if findstr(upper(EDF.Label(k,:)),'ECG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EKG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EEG') EDF.ChanTyp(k)='E'; elseif findstr(upper(EDF.Label(k,:)),'EOG') EDF.ChanTyp(k)='O'; elseif findstr(upper(EDF.Label(k,:)),'EMG') EDF.ChanTyp(k)='M'; end; end; EDF.AS.spb = sum(EDF.SPR); % Samples per Block % close the file fclose(EDF.FILE.FID); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert the header to Fieldtrip-style %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(EDF.SampleRate~=EDF.SampleRate(1)) error('channels with different sampling rate not supported'); end hdr.Fs = EDF.SampleRate(1); hdr.nChans = EDF.NS; hdr.label = cellstr(EDF.Label); % it is continuous data, therefore append all records in one trial hdr.nTrials = 1; hdr.nSamples = EDF.NRec * EDF.Dur * EDF.SampleRate(1); hdr.nSamplesPre = 0; hdr.orig = EDF; % return the header dat = hdr; else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % retrieve the original header EDF = hdr.orig; % determine the trial containing the begin and end sample epochlength = EDF.Dur * EDF.SampleRate(1); begepoch = floor((begsample-1)/epochlength) + 1; endepoch = floor((endsample-1)/epochlength) + 1; nepochs = endepoch - begepoch + 1; nchans = EDF.NS; if nargin<5 chanindx = 1:nchans; end % allocate memory to hold the data dat = zeros(length(chanindx),nepochs*epochlength); % read and concatenate all required data epochs for i=begepoch:endepoch offset = EDF.HeadLen + (i-1)*epochlength*nchans*3; if length(chanindx)==1 % this is more efficient if only one channel has to be read, e.g. the status channel offset = offset + (chanindx-1)*epochlength*3; buf = readLowLevel(filename, offset, epochlength); % see below in subfunction dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf; else % read the data from all channels and then select the desired channels buf = readLowLevel(filename, offset, epochlength*nchans); % see below in subfunction buf = reshape(buf, epochlength, nchans); dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf(:,chanindx)'; end end % select the desired samples begsample = begsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped endsample = endsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped dat = dat(:, begsample:endsample); % Calibrate the data calib = diag(EDF.Cal(chanindx)); if length(chanindx)>1 % using a sparse matrix speeds up the multiplication dat = sparse(calib) * dat; else % in case of one channel the sparse multiplication would result in a sparse array dat = calib * dat; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for reading the 24 bit values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buf = readLowLevel(filename, offset, numwords) if offset < 2*1024^3 % use the external mex file, only works for <2GB buf = read_24bit(filename, offset, numwords); % this would be the only difference between the bdf and edf implementation % buf = read_16bit(filename, offset, numwords); else % use plain matlab, thanks to Philip van der Broek fp = fopen(filename,'r','ieee-le'); status = fseek(fp, offset, 'bof'); if status error(['failed seeking ' filename]); end [buf,num] = fread(fp,numwords,'bit24=>double'); fclose(fp); if (num<numwords) error(['failed opening ' filename]); return end end
github
lcnbeapp/beapp-master
read_ctf_ascii.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_ctf_ascii.m
3,157
utf_8
32e93975d6d654771bf27ed64dc95ca0
function [file] = read_ctf_ascii(filename) % READ_CTF_ASCII reads general data from an CTF configuration file % % The file should be formatted like % Group % { % item1 : value1a value1b value1c % item2 : value2a value2b value2c % item3 : value3a value3b value3c % item4 : value4a value4b value4c % } % % This fileformat structure is used in % params.avg % default.hdm % multiSphere.hdm % processing.cfg % and maybe for other files as well. % Copyright (C) 2003, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ fid = fopen(filename, 'r'); if fid==-1 error(sprintf('could not open file %s', filename)); end line = ''; while ischar(line) line = cleanline(fgetl(fid)); if isempty(line) || (length(line)==1 && all(line==-1)) continue end % the line is not empty, which means that we have encountered a chunck of information subline = cleanline(fgetl(fid)); % read the { subline = cleanline(fgetl(fid)); % read the first item while isempty(findstr(subline, '}')) if ~isempty(subline) [item, value] = strtok(subline, ':'); value(1) = ' '; % remove the : value = strtrim(value); item = strtrim(item); % turn warnings off ws = warning('off'); % the item name should be a real string, otherwise I cannot put it into the structure if strcmp(sprintf('%d', str2num(deblank(item))), deblank(item)) % add something to the start of the string to distinguish it from a number item = ['item_' item]; end % the value can be either a number or a string, and is put into the structure accordingly if isempty(str2num(value)) % the value appears to be a string eval(sprintf('file.%s.%s = [ ''%s'' ];', line, item, value)); else % the value appears to be a number or a list of numbers eval(sprintf('file.%s.%s = [ %s ];', line, item, value)); end % revert to previous warning state warning(ws); end subline = cleanline(fgetl(fid)); % read the first item end end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function line = cleanline(line) if isempty(line) || (length(line)==1 && all(line==-1)) return end comment = findstr(line, '//'); if ~isempty(comment) line(min(comment):end) = ' '; end line = strtrim(line);
github
lcnbeapp/beapp-master
read_mpi_dap.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_mpi_dap.m
7,026
utf_8
ca2c62870772cb3bfb71c4c7d8109a21
function [dap] = read_mpi_dap(filename) % READ_MPI_DAP read the analog channels from a DAP file % and returns the values in microvolt (uV) % % Use as % [dap] = read_mpi_dap(filename) % Copyright (C) 2005-2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ fid = fopen(filename, 'rb', 'ieee-le'); % read the file header filehdr = readheader(fid); analog = {}; analoghdr = {}; analogsweephdr = {}; spike = {}; spikehdr = {}; spikesweephdr = {}; W = filehdr.nexps; S = filehdr.nsweeps; for w=1:filehdr.nexps % read the experiment header exphdr{w} = readheader(fid); if filehdr.nanalog if filehdr.analogmode==-1 % record mode for s=1:filehdr.nsweeps % read the analogsweepheader analogsweephdr{s} = readheader(fid); for j=1:filehdr.nanalog % read the analog header analoghdr{w,s,j} = readheader(fid); % read the analog data analog{w,s,j} = fread(fid, analoghdr{w,s,j}.datasize, 'int16'); % calibrate the analog data analog{w,s,j} = analog{w,s,j} * 2.5/2048; end end % for s=1:S elseif filehdr.analogmode==0 % average mode s = 1; for j=1:filehdr.nanalog % read the analog header analoghdr{w,s,j} = readheader(fid); % read the analog data analog{w,s,j} = fread(fid, analoghdr{w,s,j}.datasize, 'int16'); % calibrate the analog data analog{w,s,j} = analog{w,s,j} * 2.5/2048; end else error('unknown analog mode'); end end if filehdr.nspike for s=1:filehdr.nsweeps spikesweephdr{s} = readheader(fid); for j=1:filehdr.nspike % read the spike header spikehdr{w,s,j} = readheader(fid); % read the spike data spike{w,s,j} = fread(fid, spikehdr{w,s,j}.datasize, 'int16'); end end % for s=1:S end end % for w=1:W dap.filehdr = filehdr; dap.exphdr = exphdr; dap.analogsweephdr = analogsweephdr; dap.analoghdr = analoghdr; dap.analog = analog; dap.spikesweephdr = spikesweephdr; dap.spikehdr = spikehdr; dap.spike = spike; fclose(fid); return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = readheader(fid) % determine the header type, header size and data size hdr.headertype = fread(fid, 1, 'uchar'); dummy = fread(fid, 1, 'uchar'); hdr.headersize = fread(fid, 1, 'int16') + 1; % expressed in words, not bytes hdr.datasize = fread(fid, 1, 'int16'); % expressed in words, not bytes % read the header details switch hdr.headertype case 1 % fileheader % fprintf('fileheader at %d\n' ,ftell(fid)-6); dummy = fread(fid, 1, 'uchar')'; % 6 hdr.nexps = fread(fid, 1, 'uchar')'; % 7 hdr.progname = fread(fid, 7, 'uchar')'; % 8-14 hdr.version = fread(fid, 1, 'uchar')'; % 15 hdr.progversion = fread(fid, 2, 'uchar')'; % 16-17 hdr.fileversion = fread(fid, 2, 'uchar')'; % 18-19 hdr.date = fread(fid, 1, 'int16'); % 20-21 hdr.time = fread(fid, 1, 'int16'); % 22-23 hdr.nanalog = fread(fid, 1, 'uint8'); % 24 hdr.nspike = fread(fid, 1, 'uint8'); % 25 hdr.nbins = fread(fid, 1, 'int16'); % 26-27 hdr.binwidth = fread(fid, 1, 'int16'); % 28-29 dummy = fread(fid, 1, 'int16'); % 30-31 hdr.nsweeps = fread(fid, 1, 'int16'); % 32-33 hdr.analogmode = fread(fid, 1, 'uchar')'; % 34 "0 for average, -1 for record" dummy = fread(fid, 1, 'uchar')'; % 35 dummy = fread(fid, 1, 'int16'); % 36-37 dummy = fread(fid, 1, 'int16'); % 38-39 dummy = fread(fid, 1, 'int16'); % 40-41 case 65 % expheader % fprintf('expheader at %d\n' ,ftell(fid)-6); hdr.time = fread(fid, 1, 'int16'); % 6-7 hdr.parallel = fread(fid, 1, 'int16'); % 8-9 hdr.id = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 129 % analogchannelheader % fprintf('analogchannelheader at %d\n' ,ftell(fid)-6); dummy = fread(fid, 1, 'int16'); % 6-7 hdr.channum = fread(fid, 1, 'uchar'); % 8 dummy = fread(fid, 1, 'uchar'); % 9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 161 % spikechannelheader % fprintf('spikechannelheader at %d\n' ,ftell(fid)-6); dummy = fread(fid, 1, 'int16'); % 6-7 hdr.channum = fread(fid, 1, 'uchar'); % 8 dummy = fread(fid, 1, 'uchar'); % 9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 137 % analogsweepheader % fprintf('analogsweepheader at %d\n' ,ftell(fid)-6); hdr.sweepnum = fread(fid, 1, 'int16'); % 6-7 hdr.parallel = fread(fid, 1, 'int16'); % 8-9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 169 % spikesweepheader % fprintf('spikesweepheader at %d\n' ,ftell(fid)-6); hdr.sweepnum = fread(fid, 1, 'int16'); % 6-7 hdr.parallel = fread(fid, 1, 'int16'); % 8-9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 otherwise error(sprintf('unsupported format for header (%d)', hdr.headertype)); end
github
lcnbeapp/beapp-master
read_neuralynx_bin.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_neuralynx_bin.m
6,640
utf_8
1448e3703a6b780a4d8fddd68e151fec
function [dat] = read_neuralynx_bin(filename, begsample, endsample) % READ_NEURALYNX_BIN % % Use as % hdr = read_neuralynx_bin(filename) % or % dat = read_neuralynx_bin(filename, begsample, endsample) % % This is not a formal Neuralynx file format, but at the % F.C. Donders Centre we use it in conjunction with Neuralynx, % SPIKESPLITTING and SPIKEDOWNSAMPLE. % % The first version of this file format contained in the first 8 bytes the % channel label as string. Subsequently it contained 32 bit integer values. % % The second version of this file format starts with 8 bytes describing (as % a space-padded string) the data type. The channel label is contained in % the filename as dataset.chanlabel.bin. % % The third version of this file format starts with 7 bytes describing (as % a zero-padded string) the data type, followed by the 8th byte which % describes the downscaling for the 8 and 16 bit integer representations. % The downscaling itself is represented as uint8 and should be interpreted as % the number of bits to shift. The channel label is contained in the % filename as dataset.chanlabel.bin. % Copyright (C) 2007-2008, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ needhdr = (nargin==1); needdat = (nargin>=2); % this is used for backward compatibility oldformat = false; % the first 8 bytes contain the header fid = fopen(filename, 'rb', 'ieee-le'); magic = fread(fid, 8, 'uint8=>char')'; % the header describes the format of the subsequent samples subtype = []; if strncmp(magic, 'uint8', length('uint8')) format = 'uint8'; samplesize = 1; elseif strncmp(magic, 'int8', length('int8')) format = 'int8'; samplesize = 1; elseif strncmp(magic, 'uint16', length('uint16')) format = 'uint16'; samplesize = 2; elseif strncmp(magic, 'int16', length('int16')) format = 'int16'; samplesize = 2; elseif strncmp(magic, 'uint32', length('uint32')) format = 'uint32'; samplesize = 4; elseif strncmp(magic, 'int32', length('int32')) format = 'int32'; samplesize = 4; elseif strncmp(magic, 'uint64', length('uint64')) format = 'uint64'; samplesize = 8; elseif strncmp(magic, 'int64', length('int64')) format = 'int64'; samplesize = 8; elseif strncmp(magic, 'float32', length('float32')) format = 'float32'; samplesize = 4; elseif strncmp(magic, 'float64', length('float64')) format = 'float64'; samplesize = 8; else warning('could not detect sample format, assuming file format subtype 1 with ''int32'''); subtype = 1; % the file format is version 1 format = 'int32'; samplesize = 4; end % determine whether the file format is version 2 or 3 if isempty(subtype) if all(magic((length(format)+1):end)==' ') subtype = 2; else subtype = 3; end end % determine the channel name switch subtype case 1 % the first 8 bytes of the file contain the channel label (padded with spaces) label = strtrim(magic); case {2, 3} % the filename is formatted like "dataset.chanlabel.bin" [p, f, x1] = fileparts(filename); [p, f, x2] = fileparts(f); if isempty(x2) warning('could not determine channel label'); label = 'unknown'; else label = x2(2:end); end clear p f x1 x2 otherwise error('unknown file format subtype'); end % determine the downscale factor, i.e. the number of bits that the integer representation has to be shifted back to the left switch subtype case 1 % these never contained a multiplication factor but always corresponded % to the lowest N bits of the original 32 bit integer downscale = 0; case 2 % these might contain a multiplication factor but that factor cannot be retrieved from the file warning('downscale factor is unknown for ''%s'', assuming that no downscaling was applied', filename); downscale = 0; case 3 downscale = double(magic(8)); otherwise error('unknown file format subtype'); end [p1, f1, x1] = fileparts(filename); [p2, f2, x2] = fileparts(f1); headerfile = fullfile(p1, [f2, '.txt']); if exist(headerfile, 'file') orig = neuralynx_getheader(headerfile); % construct the header from the accompanying text file hdr = []; hdr.Fs = orig.SamplingFrequency; hdr.nChans = 1; hdr.nSamples = (filesize(filename)-8)/samplesize; hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.label = {label}; else % construct the header from the hard-coded defaults hdr = []; hdr.Fs = 32556; hdr.nChans = 1; hdr.nSamples = (filesize(filename)-8)/samplesize; hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.label = {label}; end if ~needdat % also return the file details hdr.orig.subtype = subtype; hdr.orig.magic = magic; hdr.orig.format = format; hdr.orig.downscale = downscale; % return only the header details dat = hdr; else % read and return the data if begsample<1 begsample = 1; end if isinf(endsample) endsample = hdr.nSamples; end fseek(fid, 8+(begsample-1)*samplesize, 'bof'); % skip to the beginning of the interesting data format = sprintf('%s=>%s', format, format); dat = fread(fid, [1 endsample-begsample+1], format); if downscale>1 % the data was downscaled with 2^N, i.e. shifted N bits to the right in case of integer representations % now it should be upscaled again with the same amount dat = dat.*(2^downscale); end if length(dat)<(endsample-begsample+1) error('could not read the requested data'); end end % needdat fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the file size in bytes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [siz] = filesize(filename) l = dir(filename); if l.isdir error(sprintf('"%s" is not a file', filename)); end siz = l.bytes;
github
lcnbeapp/beapp-master
inifile.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/inifile.m
23,578
utf_8
f647125ffa71c22e44a119c27e73d460
function readsett = inifile(fileName,operation,keys,style) %readsett = INIFILE(fileName,operation,keys,style) % Creates, reads, or writes data from/to ini (ascii) file. % % - fileName: ini file name % - operation: can be one of the following: % 'new' (rewrites an existing or creates a new, empty file), % 'deletekeys'(deletes keys and their values - if they exist), % 'read' (reads values as strings), % 'write' (writes values given as strings), % - keys: cell array of STRINGS; max 5 columns, min % 3 columns. Each row has the same number of columns. The columns are: % 'section': section name string (the root is considered if empty or not given) % 'subsection': subsection name string (the root is considered if empty or not given) % 'key': name of the field to write/read from (given as a string). % 'value': (optional) string-value to write to the ini file in case of 'write' operation % 'defaultValue': (optional) value that is returned when the key is not found when reading ('read' operation) % - style: 'tabbed' writes sections, subsections and keys in a tabbed style % to get a more readable file. The 'plain' style is the % default style. This only affects the keys that will be written/rewritten. % % - readsett: read setting in the case of the 'read' operation. If % the keys are not found, the default values are returned % as strings (if given in the 5-th column). % % EXAMPLE: % Suppose we want a new ini file, test1.ini with 3 fields. % We can write them into the file using: % % inifile('test1.ini','new'); % writeKeys = {'measurement','person','name','Primoz Cermelj';... % 'measurement','protocol','id','1';... % 'application','','description','some...'}; % inifile('test1.ini','write',writeKeys,'plain'); % % Later, you can read them out. Additionally, if any of them won't % exist, a default value will be returned (if the 5-th column is given as below). % % readKeys = {'measurement','person','name','','John Doe';... % 'measurement','protocol','id','','0';... % 'application','','description','','none'}; % readSett = inifile('test1.ini','read',readKeys); % % % NOTES: When the operation is 'new', only the first 2 parameters are % required. If the operation is 'write' and the file is empty or does not exist, % a new file is created. When writing and if any of the section or subsection or key does not exist, % it creates (adds) a new one. % Everything but value is NOT case sensitive. Given keys and values % will be trimmed (leading and trailing spaces will be removed). % Any duplicates (section, subsection, and keys) are ignored. Empty section and/or % subsection can be given as an empty string, '', but NOT as an empty matrix, []. % % This function was tested on the win32 platform only but it should % also work on Unix/Linux platforms. Since some short-circuit operators % are used, at least Matlab 6.5 should be used. % % FREE SOFTWARE - please refer the source % Copyright (c) 2003 by Primoz Cermelj % First release on 29.01.2003 % Primoz Cermelj, Slovenia % Contact: [email protected] % Download location: http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=2976&objectType=file % % Version: 1.1.0 % Last revision: 04.02.2004 % % Bug reports, questions, etc. can be sent to the e-mail given above. % % This programme is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or any later version. % % This programme is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. %-------------------------------------------------------------------------- %---------------- % INIFILE history %---------------- % % [v.1.1.0] 04.02.2004 % - FIX: 'writetext' option removed (there was a bug previously) % % [v.1.01b] 19.12.2003 % - NEW: A new concept - multiple keys can now be read, written, or deleted % ALL AT ONCE which makes this function much faster. For example, to % write 1000 keys, using previous versions it took 157 seconds on a % 1.5 GHz machine, with this new version it took only 1.83 seconds. % In general, the speed improvement is greater when larger number of % read/written keys are considered. % - NEW: The format of the input parameters has changed. See above. % % [v.0.97] 19.11.2003 % - NEW: Additional m-function, strtrim, is no longer needed % % [v.0.96] 16.10.2003 % - FIX: Detects empty keys % % [v.0.95] 04.07.2003 % - NEW: 'deletekey' option/operation added % - FIX: A major file refinement to obtain a more compact utility -> additional operations can "easily" be implemented % % [v.0.91-0.94] % - FIX: Some minor refinements % % [v.0.90] 29.01.2003 % - NEW: First release of this tool % %---------------- global NL_CHAR; % Checks the input arguments if nargin < 2 error('Not enough input arguments'); end if (strcmpi(operation,'read')) | (strcmpi(operation,'deletekeys')) if nargin < 3 error('Not enough input arguments.'); end if ~exist(fileName) error(['File ' fileName ' does not exist.']); end [m,n] = size(keys); if n > 5 error('Keys argument has too many columns'); end for ii=1:m if isempty(keys(ii,3)) | ~ischar(keys{ii,3}) error('Empty or non-char keys are not allowed.'); end end elseif (strcmpi(operation,'write')) | (strcmpi(operation,'writetext')) if nargin < 3 error('Not enough input arguments'); end [m,n] = size(keys); for ii=1:m if isempty(keys(ii,3)) | ~ischar(keys{ii,3}) error('Empty or non-char keys are not allowed.'); end end elseif (~strcmpi(operation,'new')) error(['Unknown inifile operation: ''' operation '''']); end if nargin >= 3 for ii=1:m for jj=1:n if ~ischar(keys{ii,jj}) error('All cells from keys must be given as strings, even the empty ones.'); end end end end if nargin < 4 || isempty(style) style = 'plain'; else if ~(strcmpi(style,'plain') | strcmpi(style,'tabbed')) | ~ischar(style) error('Unsupported style given or style not given as a string'); end end % Sets new-line character (string) if ispc NL_CHAR = '\r\n'; else NL_CHAR = '\n'; end %---------------------------- % CREATES a new, empty file (rewrites an existing one) %---------------------------- if strcmpi(operation,'new') fh = fopen(fileName,'w'); if fh == -1 error(['File: ''' fileName ''' can not be (re)created']); end fclose(fh); return %---------------------------- % READS key-value pairs out %---------------------------- elseif (strcmpi(operation,'read')) if n < 5 defaultValues = cellstrings(m,1); else defaultValues = keys(:,5); end readsett = defaultValues; keysIn = keys(:,1:3); [secsExist,subsecsExist,keysExist,readValues,so,eo] = findkeys(fileName,keysIn); ind = find(keysExist); if ~isempty(ind) readsett(ind) = readValues(ind); end return %---------------------------- % WRITES key-value pairs to an existing or non-existing % file (file can even be empty) %---------------------------- elseif (strcmpi(operation,'write')) if m < 1 error('At least one key is needed when writing keys'); end if ~exist(fileName) inifile(fileName,'new'); end writekeys(fileName,keys,style); return %---------------------------- % DELETES key-value pairs out %---------------------------- elseif (strcmpi(operation,'deletekeys')) deletekeys(fileName,keys); else error('Unknown operation for INIFILE.'); end %-------------------------------------------------- %%%%%%%%%%%%% SUBFUNCTIONS SECTION %%%%%%%%%%%%%%%% %-------------------------------------------------- %------------------------------------ function [secsExist,subSecsExist,keysExist,values,startOffsets,endOffsets] = findkeys(fileName,keysIn) % This function parses ini file for keys as given by keysIn. keysIn is a cell % array of strings having 3 columns; section, subsection and key in each row. % section and/or subsection can be empty (root section or root subsection) % but the key can not be empty. The startOffsets and endOffsets are start and % end bytes that each key occuppies, respectively. If any of the keys doesn't exist, % startOffset and endOffset for this key are the same. A special case is % when the key that doesn't exist also corresponds to a non-existing % section and non-existing subsection. In such a case, the startOffset and % endOffset have values of -1. nKeys = size(keysIn,1); % number of keys nKeysLocated = 0; % number of keys located secsExist = zeros(nKeys,1); % if section exists (and is non-empty) subSecsExist = zeros(nKeys,1); % if subsection... keysExist = zeros(nKeys,1); % if key that we are looking for exists keysLocated = keysExist; % if the key's position (existing or non-existing) is LOCATED values = cellstrings(nKeys,1); % read values of keys (strings) startOffsets = -ones(nKeys,1); % start byte-position of the keys endOffsets = -ones(nKeys,1); % end byte-position of the keys keyInd = find(strcmpi(keysIn(:,1),'')); % key indices having [] section (root section) line = []; currSection = ''; currSubSection = ''; fh = fopen(fileName,'r'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try %--- Searching for the keys - their values and start and end locations in bytes while 1 pos1 = ftell(fh); line = fgetl(fh); if line == -1 % end of file, exit line = []; break end [status,readValue,readKey] = processiniline(line); if (status == 1) % (new) section found % Keys that were found as belonging to any previous section % are now assumed as located (because another % section is found here which could even be a repeated one) keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) ); if length(keyInd) keysLocated(keyInd) = 1; nKeysLocated = nKeysLocated + length(keyInd); end currSection = readValue; currSubSection = ''; % Indices to non-located keys belonging to current section keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) ); if ~isempty(keyInd) secsExist(keyInd) = 1; end pos2 = ftell(fh); startOffsets(keyInd) = pos2+1; endOffsets(keyInd) = pos2+1; elseif (status == 2) % (new) subsection found % Keys that were found as belonging to any PREVIOUS section % and/or subsection are now assumed as located (because another % subsection is found here which could even be a repeated one) keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) & ~keysLocated & strcmpi(keysIn(:,2),currSubSection)); if length(keyInd) keysLocated(keyInd) = 1; nKeysLocated = nKeysLocated + length(keyInd); end currSubSection = readValue; % Indices to non-located keys belonging to current section and subsection at the same time keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) & ~keysLocated & strcmpi(keysIn(:,2),currSubSection)); if ~isempty(keyInd) subSecsExist(keyInd) = 1; end pos2 = ftell(fh); startOffsets(keyInd) = pos2+1; endOffsets(keyInd) = pos2+1; elseif (status == 3) % key found if isempty(keyInd) continue % no keys from 'keys' - from section-subsection par currently in end currKey = readValue; pos2 = ftell(fh); % the last-byte position of the read key - the total sum of chars read so far for ii=1:length(keyInd) if strcmpi( keysIn(keyInd(ii),3),readKey ) & ~keysLocated(keyInd(ii)) keysExist(keyInd(ii)) = 1; startOffsets(keyInd(ii)) = pos1+1; endOffsets(keyInd(ii)) = pos2; values{keyInd(ii)} = currKey; keysLocated(keyInd(ii)) = 1; nKeysLocated = nKeysLocated + 1; else if ~keysLocated(keyInd(ii)) startOffsets(keyInd(ii)) = pos2+1; endOffsets(keyInd(ii)) = pos2+1; end end end if nKeysLocated >= nKeys % if all the keys are located break end else % general text found (even empty line(s)) end %--- End searching end fclose(fh); catch fclose(fh); error(['Error parsing the file for keys: ' fileName ': ' lasterr]); end %------------------------------------ %------------------------------------ function writekeys(fileName,keys,style) % Writes keys to the section and subsection pair % If any of the keys doesn't exist, a new key is added to % the end of the section-subsection pair otherwise the key is updated (changed). % Keys is a 4-column cell array of strings. global NL_CHAR; RETURN = sprintf('\r'); NEWLINE = sprintf('\n'); [m,n] = size(keys); if n < 4 error('Keys to be written are given in an invalid format.'); end % Get keys position first using findkeys keysIn = keys; [secsExist,subSecsExist,keysExist,readValues,so,eo] = findkeys(fileName,keys(:,1:3)); % Read the whole file's contents out fh = fopen(fileName,'r'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try dataout = fscanf(fh,'%c'); catch fclose(fh); error(lasterr); end fclose(fh); %--- Rewriting the file -> writing the refined contents fh = fopen(fileName,'w'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try tab1 = []; if strcmpi(style,'tabbed') tab1 = sprintf('\t'); end % Proper sorting of keys is cruical at this point in order to avoid % inproper key-writing. % Find keys with -1 offsets - keys with non-existing section AND % subsection - keys that will be added to the end of the file fs = length(dataout); % file size in bytes nAddedKeys = 0; ind = find(so==-1); if ~isempty(ind) so(ind) = (fs+10); % make sure these keys will come to the end when sorting eo(ind) = (fs+10); nAddedKeys = length(ind); end % Sort keys according to start- and end-offsets [dummy,ind] = sort(so,1); so = so(ind); eo = eo(ind); keysIn = keysIn(ind,:); keysExist = keysExist(ind); secsExist = secsExist(ind); subSecsExist = subSecsExist(ind); readValues = readValues(ind); values = keysIn(:,4); % Find keys with equal start offset (so) and additionally sort them % (locally). These are non-existing keys, including the ones whose % section and subsection will also be added. nKeys = size(so,1); fullInd = 1:nKeys; ii = 1; while ii < nKeys ind = find(so==so(ii)); if ~isempty(ind) && length(ind) > 1 n = length(ind); from = ind(1); to = ind(end); tmpKeys = keysIn( ind,: ); [tmpKeys,ind2] = sortrows( lower(tmpKeys) ); fullInd(from:to) = ind(ind2); ii = ii + n; else ii = ii + 1; end end % Final (re)sorting so = so(fullInd); eo = eo(fullInd); keysIn = keysIn(fullInd,:); keysExist = keysExist(fullInd); secsExist = secsExist(fullInd); subSecsExist = subSecsExist(fullInd); readValues = readValues(fullInd); values = keysIn(:,4); % Refined data - datain datain = []; for ii=1:nKeys % go through all the keys, existing and non-existing ones if ii==1 from = 1; % from byte-offset of original data (dataout) else from = eo(ii-1); if keysExist(ii-1) from = from + 1; end end to = min(so(ii)-1,fs); % to byte-offset of original data (dataout) if ~isempty(dataout) datain = [datain dataout(from:to)]; % the lines before the key end if length(datain) & (~(datain(end)==RETURN | datain(end)==NEWLINE)) datain = [datain, sprintf(NL_CHAR)]; end tab = []; if ~keysExist(ii) if ~secsExist(ii) && ~isempty(keysIn(ii,1)) if ~isempty(keysIn{ii,1}) datain = [datain sprintf(['%s' NL_CHAR],['[' keysIn{ii,1} ']'])]; end % Key-indices with the same section as this, ii-th key (even empty sections are considered) ind = find( strcmpi( keysIn(:,1), keysIn(ii,1)) ); % This section exists at all keys corresponding to the same section from know on (even the empty ones) secsExist(ind) = 1; end if ~subSecsExist(ii) && ~isempty(keysIn(ii,2)) if ~isempty( keysIn{ii,2}) if secsExist(ii); tab = tab1; end; datain = [datain sprintf(['%s' NL_CHAR],[tab '{' keysIn{ii,2} '}'])]; end % Key-indices with the same section AND subsection as this, ii-th key (even empty sections and subsections are considered) ind = find( strcmpi( keysIn(:,1), keysIn(ii,1)) & strcmpi( keysIn(:,2), keysIn(ii,2)) ); % This subsection exists at all keys corresponding to the same section and subsection from know on (even the empty ones) subSecsExist(ind) = 1; end end if secsExist(ii) & (~isempty(keysIn{ii,1})); tab = tab1; end; if subSecsExist(ii) & (~isempty(keysIn{ii,2})); tab = [tab tab1]; end; datain = [datain sprintf(['%s' NL_CHAR],[tab keysIn{ii,3} ' = ' values{ii}])]; end from = eo(ii); if keysExist(ii) from = from + 1; end to = length(dataout); if from < to datain = [datain dataout(from:to)]; end fprintf(fh,'%c',datain); catch fclose(fh); error(['Error writing keys to file: ''' fileName ''' : ' lasterr]); end fclose(fh); %------------------------------------ %------------------------------------ function deletekeys(fileName,keys) % Deletes keys and their values out; keys must have at least 3 columns: % section, subsection, and key [m,n] = size(keys); if n < 3 error('Keys to be deleted are given in an invalid format.'); end % Get keys position first keysIn = keys; [secsExist,subSecsExist,keysExist,readValues,so,eo] = findkeys(fileName,keys(:,1:3)); % Read the whole file's contents out fh = fopen(fileName,'r'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try dataout = fscanf(fh,'%c'); catch fclose(fh); error(lasterr); end fclose(fh); %--- Rewriting the file -> writing the refined contents fh = fopen(fileName,'w'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try ind = find(keysExist); nExistingKeys = length(ind); datain = dataout; if nExistingKeys % Filtering - retain only the existing keys... fs = length(dataout); % file size in bytes so = so(ind); eo = eo(ind); keysIn = keysIn(ind,:); % ...and sorting [so,ind] = sort(so); eo = eo(ind); keysIn = keysIn(ind,:); % Refined data - datain datain = []; for ii=1:nExistingKeys % go through all the existing keys if ii==1 from = 1; % from byte-offset of original data (dataout) else from = eo(ii-1)+1; end to = so(ii)-1; % to byte-offset of original data (dataout) if ~isempty(dataout) datain = [datain dataout(from:to)]; % the lines before the key end end from = eo(ii)+1; to = length(dataout); if from < to datain = [datain dataout(from:to)]; end end fprintf(fh,'%c',datain); catch fclose(fh); error(['Error deleting keys from file: ''' fileName ''' : ' lasterr]); end fclose(fh); %------------------------------------ %------------------------------------ function [status,value,key] = processiniline(line) % Processes a line read from the ini file and % returns the following values: % - status: 0 => empty line or unknown string % 1 => section found % 2 => subsection found % 3 => key-value pair found % - value: value-string of a key, section, or subsection % - key: key-string status = 0; value = []; key = []; line = strim(line); % removes any leading and trailing spaces if isempty(line) % empty line return end if (line(1) == '[') & (line(end) == ']')... % section found & (length(line) >= 3) value = lower(line(2:end-1)); status = 1; elseif (line(1) == '{') &... % subsection found (line(end) == '}') & (length(line) >= 3) value = lower(line(2:end-1)); status = 2; else pos = findstr(line,'='); if ~isempty(pos) % key-value pair found status = 3; key = lower(line(1:pos-1)); value = line(pos+1:end); key = strim(key); % removes any leading and trailing spaces value = strim(value); % removes any leading and trailing spaces if isempty(key) % empty keys are not allowed status = 0; key = []; value = []; end end end %------------------------------------ %------------------------------------ function outstr = strim(str) % Removes leading and trailing spaces (spaces, tabs, endlines,...) % from the str string. if isnumeric(str); outstr = str; return end ind = find( ~isspace(str) ); % indices of the non-space characters in the str if isempty(ind) outstr = []; else outstr = str( ind(1):ind(end) ); end %------------------------------------ function cs = cellstrings(m,n) % Creates a m x n cell array of empty strings - '' cs = cell(m,n); for ii=1:m for jj=1:n cs{ii,jj} = ''; end end
github
lcnbeapp/beapp-master
yokogawa2grad_new.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/yokogawa2grad_new.m
9,059
utf_8
9cbc5b3c41718d550ce5fc8fa204712f
function grad = yokogawa2grad_new(hdr) % YOKOGAWA2GRAD_NEW converts the position and weights of all coils that % compromise a gradiometer system into a structure that can be used % by FieldTrip. This implementation uses the new "yokogawa_meg_reader" % toolbox. % % See also FT_READ_HEADER, CTF2GRAD, BTI2GRAD, FIF2GRAD, YOKOGAWA2GRAD % Copyright (C) 2005-2012, Robert Oostenveld % Copyright (C) 2010, Tilmann Sander-Thoemmes % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % The following line is only a safety measure: No function of the toolbox % is actually called in this routine. if ~ft_hastoolbox('yokogawa_meg_reader') error('cannot determine whether Yokogawa toolbox is present'); end if isfield(hdr, 'label') label = hdr.label; % keep for later use end if isfield(hdr, 'orig') hdr = hdr.orig; % use the original header, not the FieldTrip header end % The "channel_info.channel(i)" structure contains, s. sepcifications in % Yokogawa MEG Reader Toolbox 1.4 specifications.pdf. % type, type of sensor % data.x (in m, inner coil) % data.y (in m, inner coil) % data.z (in m, inner coil) % data.size (in m, coil diameter) % for gradiometers % data.baseline (in m) % for axial gradiometers and magnetometers % data.zdir orientation of inner coil (theta in deg: angle to z-axis) % data.xdir orientation of inner coil (phi in deg: angle to x-axis) % for planar gradiometers % Note, that Yokogawa planar gradiometers contain two coils perpendicular to % the sphere, i.e. the planar gradiometers normal is the spheres tangential. % Therefore the definition of an inner coil makes sense here in contrast to % planar gradiometers from Neuromag, where the gradiometer normal is radial. % data.zdir1 orientation of inner coil (theta in deg: angle to z-axis) % data.xdir1 orientation of inner coil (phi in deg: angle to x-axis) % data.zdir2 baseline orientation from inner coil (theta in deg: angle to z-axis) % data.xdir2 baseline orientation from inner coil (phi in deg: angle to x-axis) % % The code below is not written for speed or elegance, but for readability. % % shorten names ch_info = hdr.channel_info.channel; type = [ch_info.type]; handles = definehandles; % get all axial grads, planar grads, and magnetometers. % reference channels without position information are excluded. grad_ind = [1:hdr.channel_count]; isgrad = (type==handles.AxialGradioMeter | type==handles.PlannerGradioMeter | ... type==handles.MagnetoMeter); isref = (type==handles.RefferenceAxialGradioMeter | type==handles.RefferencePlannerGradioMeter | ... type==handles.RefferenceMagnetoMeter); for i = 1: hdr.channel_count if isref(i) && sum( ch_info( i ).data.x^2 + ch_info( i ).data.y^2 + ch_info( i ).data.z^2 ) > 0.0, isgrad(i) = 1; end; end grad_ind = grad_ind(isgrad); grad_nr = size(grad_ind,2); grad = []; grad.coilpos = zeros(2*grad_nr,3); grad.coilori = zeros(2*grad_nr,3); % define gradiometer and magnetometer for i = 1:grad_nr ch_ind = grad_ind(i); grad.coilpos(i,1) = ch_info(ch_ind).data.x*100; % cm grad.coilpos(i,2) = ch_info(ch_ind).data.y*100; % cm grad.coilpos(i,3) = ch_info(ch_ind).data.z*100; % cm grad.chanpos = grad.coilpos(1:grad_nr,:); if ch_info(ch_ind).type==handles.AxialGradioMeter || ch_info(ch_ind).type==handles.RefferenceAxialGradioMeter baseline = ch_info(ch_ind).data.baseline; ori_1st = [ch_info(ch_ind).data.zdir ch_info(ch_ind).data.xdir ]; % polar to x,y,z coordinates ori_1st = ... [sin(ori_1st(:,1)/180*pi).*cos(ori_1st(:,2)/180*pi) ... sin(ori_1st(:,1)/180*pi).*sin(ori_1st(:,2)/180*pi) ... cos(ori_1st(:,1)/180*pi)]; grad.coilori(i,:) = ori_1st; grad.coilpos(i+grad_nr,:) = [grad.coilpos(i,:)+ori_1st*baseline*100]; grad.coilori(i+grad_nr,:) = -ori_1st; elseif ch_info(ch_ind).type==handles.PlannerGradioMeter || ch_info(ch_ind).type==handles.RefferencePlannerGradioMeter baseline = ch_info(ch_ind).data.baseline; ori_1st = [ch_info(ch_ind).data.zdir1 ch_info(ch_ind).data.xdir1 ]; % polar to x,y,z coordinates ori_1st = ... [sin(ori_1st(:,1)/180*pi).*cos(ori_1st(:,2)/180*pi) ... sin(ori_1st(:,1)/180*pi).*sin(ori_1st(:,2)/180*pi) ... cos(ori_1st(:,1)/180*pi)]; grad.coilori(i,:) = ori_1st; ori_1st_to_2nd = [ch_info(ch_ind).data.zdir2 ch_info(ch_ind).data.xdir2 ]; % polar to x,y,z coordinates ori_1st_to_2nd = ... [sin(ori_1st_to_2nd(:,1)/180*pi).*cos(ori_1st_to_2nd(:,2)/180*pi) ... sin(ori_1st_to_2nd(:,1)/180*pi).*sin(ori_1st_to_2nd(:,2)/180*pi) ... cos(ori_1st_to_2nd(:,1)/180*pi)]; grad.coilpos(i+grad_nr,:) = [grad.coilpos(i,:)+ori_1st_to_2nd*baseline*100]; grad.coilori(i+grad_nr,:) = -ori_1st; else % magnetometer ori_1st = [ch_info(ch_ind).data.zdir ch_info(ch_ind).data.xdir ]; % polar to x,y,z coordinates ori_1st = ... [sin(ori_1st(:,1)/180*pi).*cos(ori_1st(:,2)/180*pi) ... sin(ori_1st(:,1)/180*pi).*sin(ori_1st(:,2)/180*pi) ... cos(ori_1st(:,1)/180*pi)]; grad.coilori(i,:) = ori_1st; grad.coilpos(i+grad_nr,:) = [0 0 0]; grad.coilori(i+grad_nr,:) = [0 0 0]; end grad.chanori = grad.coilori(1:grad_nr,:); end % Define the pair of 1st and 2nd coils for each gradiometer grad.tra = repmat(diag(ones(1,grad_nr),0),1,2); % for mangetometers change tra as there is no second coil for i = 1:grad_nr ch_ind = grad_ind(i); if ch_info(ch_ind).type==handles.MagnetoMeter grad.tra(i,grad_nr+i) = 0; end end % the gradiometer labels should be consistent with the channel labels in % read_yokogawa_header, the predefined list of channel names in ft_senslabel % and with ft_channelselection: % but it is ONLY consistent with read_yokogawa_header as NO FIXED relation % between channel index and type of channel exists for Yokogawa systems. % Therefore all have individual label sequences: Support in ft_senslabel % is only partial. if ~isempty(label) grad.label = label(grad_ind)'; else % this is only backup, if something goes wrong above. label = cell(grad_nr,1); for i=1:length(label) label{i,1} = sprintf('AG%03d', i); end grad.label = label; end grad.unit = 'cm'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % ????4.0mm???????` handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % ???a15.5mm???~?? handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % ????12.0mm???????` handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
lcnbeapp/beapp-master
read_besa_avr.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_besa_avr.m
3,870
utf_8
f19ef935bf322fb2ccbcced4717efd61
function [avr] = read_besa_avr(filename) % READ_BESA_AVR reads average EEG data in BESA format % % Use as % [avr] = read_besa_avr(filename) % % This will return a structure with the header information in % avr.npnt % avr.tsb % avr.di % avr.sb % avr.sc % avr.Nchan (optional) % avr.label (optional) % and the ERP data is contained in the Nchan X Nsamples matrix % avr.data % Copyright (C) 2003-2006, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ fid = fopen(filename, 'rt'); % the first line contains header information headstr = fgetl(fid); ok = 0; if ~ok try buf = sscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f Nchan= %f SegmentName= %s\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); avr.Nchan = buf(6); avr.SegmentName = buf(7); ok = 1; catch ok = 0; end end if ~ok try buf = fscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f Nchan= %f\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); avr.Nchan = buf(6); ok = 1; catch ok = 0; end end if ~ok try buf = sscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); ok = 1; catch ok = 0; end end if ~ok error('Could not interpret the header information.'); end % rewind to the beginning of the file, skip the header line fseek(fid, 0, 'bof'); fgetl(fid); % the second line may contain channel names chanstr = fgetl(fid); chanstr = deblank(fliplr(deblank(fliplr(chanstr)))); if (chanstr(1)>='A' && chanstr(1)<='Z') || (chanstr(1)>='a' && chanstr(1)<='z') haschan = 1; avr.label = str2cell(strrep(deblank(chanstr), '''', ''))'; else [root, name] = fileparts(filename); haschan = 0; elpfile = fullfile(root, [name '.elp']); elafile = fullfile(root, [name '.ela']); if exist(elpfile, 'file') % read the channel names from the accompanying ELP file lbl = importdata(elpfile); avr.label = strrep(lbl.textdata(:,2) ,'''', ''); elseif exist(elafile, 'file') % read the channel names from the accompanying ELA file lbl = importdata(elafile); lbl = strrep(lbl ,'MEG ', ''); % remove the channel type lbl = strrep(lbl ,'EEG ', ''); % remove the channel type avr.label = lbl; else warning('Could not create channels labels.'); end end % seek to the beginning of the data fseek(fid, 0, 'bof'); fgetl(fid); % skip the header line if haschan fgetl(fid); % skip the channel name line end buf = fscanf(fid, '%f'); nchan = length(buf)/avr.npnt; avr.data = reshape(buf, avr.npnt, nchan)'; fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to cut a string into pieces at the spaces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function c = str2cell(s) c = {}; [t, r] = strtok(s, ' '); while ~isempty(t) c{end+1} = t; [t, r] = strtok(r, ' '); end
github
lcnbeapp/beapp-master
ft_datatype_source.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/ft_datatype_source.m
12,246
utf_8
ab7ac36100ef0e75b5989d6870ea0bbf
function [source] = ft_datatype_source(source, varargin) % FT_DATATYPE_SOURCE describes the FieldTrip MATLAB structure for data that is % represented at the source level. This is typically obtained with a beamformer of % minimum-norm source reconstruction using FT_SOURCEANALYSIS. % % An example of a source structure obtained after performing DICS (a frequency % domain beamformer scanning method) is shown here % % pos: [6732x3 double] positions at which the source activity could have been estimated % inside: [6732x1 logical] boolean vector that indicates at which positions the source activity was estimated % dim: [xdim ydim zdim] if the positions can be described as a 3D regular grid, this contains the % dimensionality of the 3D volume % cumtapcnt: [120x1 double] information about the number of tapers per original trial % time: 0.100 the latency at which the activity is estimated (in seconds) % freq: 30 the frequency at which the activity is estimated (in Hz) % pow: [6732x120 double] the estimated power at each source position % powdimord: 'pos_rpt' defines how the numeric data has to be interpreted, % in this case 6732 dipole positions x 120 repetitions (i.e. trials) % cfg: [1x1 struct] the configuration used by the function that generated this data structure % % Required fields: % - pos % % Optional fields: % - time, freq, pow, coh, eta, mom, ori, cumtapcnt, dim, transform, inside, cfg, dimord, other fields with a dimord % % Deprecated fields: % - method, outside % % Obsoleted fields: % - xgrid, ygrid, zgrid, transform, latency, frequency % % Historical fields: % - avg, cfg, cumtapcnt, df, dim, freq, frequency, inside, method, % outside, pos, time, trial, vol, see bug2513 % % Revision history: % % (2014) The subfields in the avg and trial fields are now present in the % main structure, e.g. source.avg.pow is now source.pow. Furthermore, the % inside is always represented as logical vector. % % (2011) The source representation should always be irregular, i.e. not % a 3-D volume, contain a "pos" field and not contain a "transform". % % (2010) The source structure should contain a general "dimord" or specific % dimords for each of the fields. The source reconstruction in the avg and % trial substructures has been moved to the toplevel. % % (2007) The xgrid/ygrid/zgrid fields have been removed, because they are % redundant. % % (2003) The initial version was defined % % See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_DIP, FT_DATATYPE_FREQ, % FT_DATATYPE_MVAR, FT_DATATYPE_RAW, FT_DATATYPE_SOURCE, FT_DATATYPE_SPIKE, % FT_DATATYPE_TIMELOCK, FT_DATATYPE_VOLUME % Copyright (C) 2013-2014, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % FIXME: I am not sure whether the removal of the xgrid/ygrid/zgrid fields % was really in 2007 % get the optional input arguments, which should be specified as key-value pairs version = ft_getopt(varargin, 'version', 'latest'); if strcmp(version, 'latest') || strcmp(version, 'upcoming') version = '2014'; end if isempty(source) return; end % old data structures may use latency/frequency instead of time/freq. It is % unclear when these were introduced and removed again, but they were never % used by any FieldTrip function itself if isfield(source, 'frequency'), source.freq = source.frequency; source = rmfield(source, 'frequency'); end if isfield(source, 'latency'), source.time = source.latency; source = rmfield(source, 'latency'); end switch version case '2014' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ensure that it has individual source positions source = fixpos(source); % ensure that it is always logical source = fixinside(source, 'logical'); % remove obsolete fields if isfield(source, 'method') source = rmfield(source, 'method'); end if isfield(source, 'transform') source = rmfield(source, 'transform'); end if isfield(source, 'xgrid') source = rmfield(source, 'xgrid'); end if isfield(source, 'ygrid') source = rmfield(source, 'ygrid'); end if isfield(source, 'zgrid') source = rmfield(source, 'zgrid'); end if isfield(source, 'avg') && isstruct(source.avg) && isfield(source, 'trial') && isstruct(source.trial) && ~isempty(intersect(fieldnames(source.avg), fieldnames(source.trial))) % it is not possible to convert both since they have the same field names ft_warning('removing ''avg'', keeping ''trial'''); source = rmfield(source, 'avg'); end if isfield(source, 'avg') && isstruct(source.avg) % move the average fields to the main structure fn = fieldnames(source.avg); for i=1:length(fn) dat = source.avg.(fn{i}); if isequal(size(dat), [1 size(source.pos,1)]) source.(fn{i}) = dat'; else source.(fn{i}) = dat; end clear dat end % j source = rmfield(source, 'avg'); end if isfield(source, 'inside') % the inside is by definition logically indexed probe = find(source.inside, 1, 'first'); else % just take the first source position probe = 1; end if isfield(source, 'trial') && isstruct(source.trial) npos = size(source.pos,1); % concatenate the fields for each trial and move them to the main structure fn = fieldnames(source.trial); for i=1:length(fn) % some fields are descriptive and hence identical over trials if strcmp(fn{i}, 'csdlabel') source.csdlabel = dat; continue end % start with the first trial dat = source.trial(1).(fn{i}); datsiz = getdimsiz(source, fn{i}); nrpt = datsiz(1); datsiz = datsiz(2:end); if iscell(dat) datsiz(1) = nrpt; % swap the size of pos with the size of rpt val = cell(npos,1); indx = find(source.inside); for k=1:length(indx) val{indx(k)} = nan(datsiz); val{indx(k)}(1,:,:,:) = dat{indx(k)}; end % concatenate all data as {pos}_rpt_etc for j=2:nrpt dat = source.trial(j).(fn{i}); for k=1:length(indx) val{indx(k)}(j,:,:,:) = dat{indx(k)}; end end % for all trials source.(fn{i}) = val; else % concatenate all data as pos_rpt_etc val = nan([datsiz(1) nrpt datsiz(2:end)]); val(:,1,:,:,:) = dat(:,:,:,:); for j=2:length(source.trial) dat = source.trial(j).(fn{i}); val(:,j,:,:,:) = dat(:,:,:,:); end % for all trials source.(fn{i}) = val; % else % siz = size(dat); % if prod(siz)==npos % siz = [npos nrpt]; % elseif siz(1)==npos % siz = [npos nrpt siz(2:end)]; % end % val = nan(siz); % % concatenate all data as pos_rpt_etc % val(:,1,:,:,:) = dat(:); % for j=2:length(source.trial) % dat = source.trial(j).(fn{i}); % val(:,j,:,:,:) = dat(:); % end % for all trials % source.(fn{i}) = val; end end % for each field source = rmfield(source, 'trial'); end % if trial % ensure that it has a dimord (or multiple for the different fields) source = fixdimord(source); % ensure that all data fields have the correct dimensions fn = getdatfield(source); for i=1:numel(fn) dimord = getdimord(source, fn{i}); dimtok = tokenize(dimord, '_'); dimsiz = getdimsiz(source, fn{i}); dimsiz(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions if numel(dimsiz)>=3 && strcmp(dimtok{1}, 'dim1') && strcmp(dimtok{2}, 'dim2') && strcmp(dimtok{3}, 'dim3') % convert it from voxel-based representation to position-based representation try source.(fn{i}) = reshape(source.(fn{i}), [prod(dimsiz(1:3)) dimsiz(4:end) 1]); catch warning('could not reshape %s to the expected dimensions', fn{i}); end end end case '2011' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ensure that it has individual source positions source = fixpos(source); % remove obsolete fields if isfield(source, 'xgrid') source = rmfield(source, 'xgrid'); end if isfield(source, 'ygrid') source = rmfield(source, 'ygrid'); end if isfield(source, 'zgrid') source = rmfield(source, 'zgrid'); end if isfield(source, 'transform') source = rmfield(source, 'transform'); end % ensure that it has a dimord (or multiple for the different fields) source = fixdimord(source); case '2010' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ensure that it has individual source positions source = fixpos(source); % remove obsolete fields if isfield(source, 'xgrid') source = rmfield(source, 'xgrid'); end if isfield(source, 'ygrid') source = rmfield(source, 'ygrid'); end if isfield(source, 'zgrid') source = rmfield(source, 'zgrid'); end % ensure that it has a dimord (or multiple for the different fields) source = fixdimord(source); case '2007' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ensure that it has individual source positions source = fixpos(source); % remove obsolete fields if isfield(source, 'dimord') source = rmfield(source, 'dimord'); end if isfield(source, 'xgrid') source = rmfield(source, 'xgrid'); end if isfield(source, 'ygrid') source = rmfield(source, 'ygrid'); end if isfield(source, 'zgrid') source = rmfield(source, 'zgrid'); end case '2003' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(source, 'dimord') source = rmfield(source, 'dimord'); end if ~isfield(source, 'xgrid') || ~isfield(source, 'ygrid') || ~isfield(source, 'zgrid') if isfield(source, 'dim') minx = min(source.pos(:,1)); maxx = max(source.pos(:,1)); miny = min(source.pos(:,2)); maxy = max(source.pos(:,2)); minz = min(source.pos(:,3)); maxz = max(source.pos(:,3)); source.xgrid = linspace(minx, maxx, source.dim(1)); source.ygrid = linspace(miny, maxy, source.dim(2)); source.zgrid = linspace(minz, maxz, source.dim(3)); end end otherwise %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% error('unsupported version "%s" for source datatype', version); end function pos = grid2pos(xgrid, ygrid, zgrid) [X, Y, Z] = ndgrid(xgrid, ygrid, zgrid); pos = [X(:) Y(:) Z(:)]; function pos = dim2pos(dim, transform) [X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3)); pos = [X(:) Y(:) Z(:)]; pos = ft_warp_apply(transform, pos, 'homogenous');
github
lcnbeapp/beapp-master
xml2struct.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/xml2struct.m
8,612
utf_8
3d883353ccb551f2dcd554835610a565
function [ s ] = xml2struct( file ) %Convert xml file into a MATLAB structure % [ s ] = xml2struct( file ) % % A file containing: % <XMLname attrib1="Some value"> % <Element>Some text</Element> % <DifferentElement attrib2="2">Some more text</DifferentElement> % <DifferentElement attrib3="2" attrib4="1">Even more text</DifferentElement> % </XMLname> % % Used to produce: % s.XMLname.Attributes.attrib1 = "Some value"; % s.XMLname.Element.Text = "Some text"; % s.XMLname.DifferentElement{1}.Attributes.attrib2 = "2"; % s.XMLname.DifferentElement{1}.Text = "Some more text"; % s.XMLname.DifferentElement{2}.Attributes.attrib3 = "2"; % s.XMLname.DifferentElement{2}.Attributes.attrib4 = "1"; % s.XMLname.DifferentElement{2}.Text = "Even more text"; % % Will produce (gp: to matche the output of xml2struct in XML4MAT, but note that Element(2) is empty): % Element: Some text % DifferentElement: % attrib2: 2 % DifferentElement: Some more text % attrib1: Some value % % Element: % DifferentElement: % attrib3: 2 % attrib4: 1 % DifferentElement: Even more text % attrib1: % % Note the characters : - and . are not supported in structure fieldnames and % are replaced by _ % % Written by W. Falkena, ASTI, TUDelft, 21-08-2010 % Attribute parsing speed increased by 40% by A. Wanner, 14-6-2011 % 2011/12/14 giopia: changes in the main function to make more similar to xml2struct of the XML4MAT toolbox, bc it's used by fieldtrip % 2012/04/04 roboos: added the original license clause, see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=645#c11 % 2012/04/04 roboos: don't print the filename that is being read %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Copyright (c) 2010, Wouter Falkena % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in % the documentation and/or other materials provided with the distribution % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE % ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE % LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS % INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE % POSSIBILITY OF SUCH DAMAGE. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if (nargin < 1) clc; help xml2struct return end %check for existance if (exist(file,'file') == 0) %Perhaps the xml extension was omitted from the file name. Add the %extension and try again. if (isempty(strfind(file,'.xml'))) file = [file '.xml']; end if (exist(file,'file') == 0) error(['The file ' file ' could not be found']); end end %fprintf('xml2struct reading %s\n', file); % gp 11/12/15 %read the xml file xDoc = xmlread(file); %parse xDoc into a MATLAB structure s = parseChildNodes(xDoc); fn = fieldnames(s); s = s.(fn{1}); % gp 11/12/15: output is compatible with xml2struct of xml2mat end % ----- Subfunction parseChildNodes ----- function [children,ptext] = parseChildNodes(theNode) % Recurse over node children. children = struct; ptext = []; if theNode.hasChildNodes childNodes = theNode.getChildNodes; numChildNodes = childNodes.getLength; for count = 1:numChildNodes theChild = childNodes.item(count-1); [text,name,attr,childs] = getNodeData(theChild); if (~strcmp(name,'#text') && ~strcmp(name,'#comment')) %XML allows the same elements to be defined multiple times, %put each in a different cell if (isfield(children,name)) % if 0 % numel(children) > 1 % gp 11/12/15: (~iscell(children.(name))) % %put existsing element into cell format % children.(name) = {children.(name)}; % end index = length(children)+1; % gp 11/12/15: index = length(children.(name))+1; else index = 1; % gp 11/12/15: new field end %add new element children(index).(name) = childs; if isempty(attr) if(~isempty(text)) children(index).(name) = text; end else fn = fieldnames(attr); for f = 1:numel(fn) children(index).(name)(1).(fn{f}) = attr.(fn{f}); % gp 11/12/15: children.(name){index}.('Attributes') = attr; end if(~isempty(text)) children(index).(name).(name) = text; % gp 11/12/15: children.(name){index}.('Text') = text; end end % else % gp 11/12/15: cleaner code, don't reuse the same code % %add previously unknown new element to the structure % children.(name) = childs; % if(~isempty(text)) % children.(name) = text; % gp 11/12/15: children.(name).('Text') = text; % end % if(~isempty(attr)) % children.('Attributes') = attr; % gp 11/12/15 children.(name).('Attributes') = attr; % end % end elseif (strcmp(name,'#text')) %this is the text in an element (i.e. the parentNode) if (~isempty(regexprep(text,'[\s]*',''))) if (isempty(ptext)) ptext = text; else %what to do when element data is as follows: %<element>Text <!--Comment--> More text</element> %put the text in different cells: % if (~iscell(ptext)) ptext = {ptext}; end % ptext{length(ptext)+1} = text; %just append the text ptext = [ptext text]; end end end end end end % ----- Subfunction getNodeData ----- function [text,name,attr,childs] = getNodeData(theNode) % Create structure of node info. %make sure name is allowed as structure name name = regexprep(char(theNode.getNodeName),'[-:.]','_'); attr = parseAttributes(theNode); if (isempty(fieldnames(attr))) attr = []; end %parse child nodes [childs,text] = parseChildNodes(theNode); if (isempty(fieldnames(childs))) %get the data of any childless nodes try %faster then if any(strcmp(methods(theNode), 'getData')) text = char(theNode.getData); catch %no data end end end % ----- Subfunction parseAttributes ----- function attributes = parseAttributes(theNode) % Create attributes structure. attributes = struct; if theNode.hasAttributes theAttributes = theNode.getAttributes; numAttributes = theAttributes.getLength; for count = 1:numAttributes %attrib = theAttributes.item(count-1); %attr_name = regexprep(char(attrib.getName),'[-:.]','_'); %attributes.(attr_name) = char(attrib.getValue); %Suggestion of Adrian Wanner str = theAttributes.item(count-1).toString.toCharArray()'; k = strfind(str,'='); attr_name = regexprep(str(1:(k(1)-1)),'[-:.]','_'); attributes.(attr_name) = str((k(1)+2):(end-1)); end end end
github
lcnbeapp/beapp-master
in_fread_manscan.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/in_fread_manscan.m
4,760
utf_8
474793281d7e666aeb2bff303bd62b5b
function F = in_fread_manscan(sFile, sfid, iEpoch, SamplesBounds) % IN_FREAD_MANSCAN: Read a block of recordings from a MANSCAN file % % USAGE: F = in_fread_manscan(sFile, sfid, iEpoch, SamplesBounds) : Read all channels % F = in_fread_manscan(sFile, sfid) : Read all channels, all the times % @============================================================================= % This software is part of the Brainstorm software: % http://neuroimage.usc.edu/brainstorm % % Copyright (c)2000-2013 Brainstorm by the University of Southern California % This software is distributed under the terms of the GNU General Public License % as published by the Free Software Foundation. Further details on the GPL % license can be found at http://www.gnu.org/copyleft/gpl.html. % % FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE % UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY % WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY % LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE. % % For more information type "brainstorm license" at command prompt. % =============================================================================@ % % Authors: Francois Tadel, 2012 if (nargin < 3) || isempty(iEpoch) iEpoch = 1; end if (nargin < 4) || isempty(SamplesBounds) if ~isempty(sFile.epochs) SamplesBounds = sFile.epochs(iEpoch).samples; else SamplesBounds = sFile.prop.samples; end end % Read data block nChannels = length(sFile.channelmat.Channel); nTimes = SamplesBounds(2) - SamplesBounds(1) + 1; % Epoch offset epochOffset = sFile.header.epoch(iEpoch).StartData1; % Time offset timeOffset = 2 * SamplesBounds(1) * nChannels; % Total offset totalOffset = epochOffset + timeOffset; % Set position in file fseek(sfid, totalOffset, 'bof'); % Read value F = fread(sfid, [nChannels,nTimes], 'int16'); % Apply gains F = bst_bsxfun(@rdivide, double(F), double(sFile.header.Gains)); function C = bst_bsxfun(fun, A, B) % BST_BSXFUN: Compatible version of bsxfun function. % % DESCRIPTION: % Matlab function bsxfun() is a useful, fast, and memory efficient % way to apply element-by-element operations on huge matrices. % The problem is that this function only exists in Matlab versions >= 7.4 % This function check Matlab version, and use bsxfun if possible, if not % it finds another way to perform the same operation. % @============================================================================= % This software is part of the Brainstorm software: % http://neuroimage.usc.edu/brainstorm % % Copyright (c)2000-2013 Brainstorm by the University of Southern California % This software is distributed under the terms of the GNU General Public License % as published by the Free Software Foundation. Further details on the GPL % license can be found at http://www.gnu.org/copyleft/gpl.html. % % FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE % UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY % WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY % LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE. % % For more information type "brainstorm license" at command prompt. % =============================================================================@ % % Authors: Francois Tadel, 2010 % Old Matlab version: do it old school if ~exist('bsxfun', 'builtin') sA = [size(A,1), size(A,2), size(A,3)]; sB = [size(B,1), size(B,2), size(B,3)]; % If arguments were not provided in the correct order if all(sA == [1 1 1]) || all(sB == [1 1 1]) C = fun(A, B); elseif all(sA == sB) C = fun(A, B); % Dim 1 elseif (sB(1) == 1) && (sA(2) == sB(2)) && (sA(3) == sB(3)) C = fun(A, repmat(B, [sA(1), 1, 1])); elseif (sA(1) == 1) && (sA(2) == sB(2)) && (sA(3) == sB(3)) C = fun(repmat(A, [sB(1), 1, 1]), B); % Dim 2 elseif (sA(1) == sB(1)) && (sB(2) == 1) && (sA(3) == sB(3)) C = fun(A, repmat(B, [1, sA(2), 1])); elseif (sA(1) == sB(1)) && (sA(2) == 1) && (sA(3) == sB(3)) C = fun(repmat(A, [1, sB(2), 1]), B); % Dim 3 elseif (sA(1) == sB(1)) && (sA(2) == sB(2)) && (sB(3) == 1) C = fun(A, repmat(B, [1, 1, sA(3)])); elseif (sA(1) == sB(1)) && (sA(2) == sB(2)) && (sA(3) == 1) C = fun(repmat(A, [1, 1, sB(3)]), B); else error('A and B must have enough common dimensions.'); end % New Matlab version: use bsxfun else C = bsxfun(fun, A, B); end
github
lcnbeapp/beapp-master
read_ply.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_ply.m
5,940
utf_8
b94bb1121711ea40234fe404e5e49681
function [vert, face] = read_ply(fn) % READ_PLY reads triangles, tetraheders or hexaheders from a Stanford *.ply file % % Use as % [vert, face, prop, face_prop] = read_ply(filename) % % Documentation is provided on % http://paulbourke.net/dataformats/ply/ % http://en.wikipedia.org/wiki/PLY_(file_format) % % See also WRITE_PLY, WRITE_VTK, READ_VTK % Copyright (C) 2013, Robert Oostenveld % % $Id$ fid = fopen(fn, 'r'); if fid~=-1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the file starts with an ascii header %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% line = readline(fid); if ~strcmp(line, 'ply') fclose(fid); error('unexpected header line'); end line = readline(fid); if ~strncmp(line, 'format', 6) fclose(fid); error('unexpected header line'); else format = line(8:end); end line = readline(fid); if ~strncmp(line, 'element vertex', 14) fclose(fid); error('unexpected header line'); else nvert = str2double(line(16:end)); end line = readline(fid); prop = []; while strncmp(line, 'property', 8) tok = tokenize(line); prop(end+1).format = tok{2}; prop(end ).name = tok{3}; line = readline(fid); end if ~strncmp(line, 'element face', 12) fclose(fid); error('unexpected header line'); else nface = str2double(line(14:end)); end line = readline(fid); if ~strcmp(line, 'property list uchar int vertex_index') && ~strcmp(line, 'property list uchar int vertex_indices') % the wikipedia documentation specifies vertex_index, but the OPTOCAT files % have vertex_indices % it would not be very difficult to enhance the reader here with another % representation of the faces, i.e. something else than "uchar int" fclose(fid); error('unexpected header line'); end line = readline(fid); while ~strcmp(line, 'end_header'); line = readline(fid); end offset = ftell(fid); fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the file continues with a section of data, which can be ascii or binary %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch format case 'ascii 1.0' fid = fopen(fn, 'rt'); fseek(fid, offset, 'cof'); dat = fscanf(fid,'%f',[numel(prop), nvert])'; for j=1:length(prop) vert.(prop(j).name) = dat(:,j); end face = zeros(nface,0); num = zeros(nface,1); for i=1:nface % each polygon can have a different number of elements num(i) = fscanf(fid,'%f',1); face(i,1:num(i)) = fscanf(fid,'%f',num(i)); end fclose(fid); case 'binary_little_endian 1.0' fid = fopen(fn, 'rb', 'l'); fseek(fid, offset, 'cof'); dat = zeros(nvert,length(prop)); for i=1:nvert for j=1:length(prop) dat(i,j) = fread(fid, 1, prop(j).format); end % for each property end % for each vertex for j=1:length(prop) switch prop(j).format % the format can be one of the following: char uchar short ushort int uint float double int8 uint8 int16 uint16 int32 uint32 float32 float64 case 'char' vert.(prop(j).name) = uint8(dat(:,j)); case 'uchar' vert.(prop(j).name) = uint8(dat(:,j)); case 'short' vert.(prop(j).name) = int16(dat(:,j)); case 'ushort' vert.(prop(j).name) = uint16(dat(:,j)); otherwise vert.(prop(j).name) = dat(:,j); end end clear dat; face = zeros(nface,0); num = zeros(nface,1); for i=1:nface % each polygon can have a different number of elements num(i) = fread(fid, 1, 'uint8'); face(i,1:num(i)) = fread(fid, num(i), 'int32'); end fclose(fid); case 'binary_big_endian 1.0' % this is exactly the same as the code above, except that the file is opened as big endian fid = fopen(fn, 'rb', 'b'); fseek(fid, offset, 'cof'); dat = zeros(nvert,length(prop)); for i=1:nvert for j=1:length(prop) dat(i,j) = fread(fid, 1, prop(j).format); end % for each property end % for each vertex for j=1:length(prop) switch prop(j).format % the format can be one of the following: char uchar short ushort int uint float double int8 uint8 int16 uint16 int32 uint32 float32 float64 case 'char' vert.(prop(j).name) = uint8(dat(:,j)); case 'uchar' vert.(prop(j).name) = uint8(dat(:,j)); case 'short' vert.(prop(j).name) = int16(dat(:,j)); case 'ushort' vert.(prop(j).name) = uint16(dat(:,j)); otherwise vert.(prop(j).name) = dat(:,j); end end clear dat; face = zeros(nface,0); num = zeros(nface,1); for i=1:nface % each polygon can have a different number of elements num(i) = fread(fid, 1, 'uint8'); face(i,1:num(i)) = fread(fid, num(i), 'int32'); end fclose(fid); otherwise error('unsupported format'); end % switch else error('unable to open file'); end % each polygon can have a different number of elements % mark all invalid entries with nan if any(num<size(face,2)) for i=1:nface face(i,(num(i)+1):end) = nan; end end % if if numel(face)>0 % MATLAB indexes start at 1, inside the file they start at 0 face = face+1; end end % function read_ply function line = readline(fid) % read the next line from the ascii header, skip all comment lines line = fgetl(fid); while strncmp(line, 'comment', 7); line = fgetl(fid); end end % function readline
github
lcnbeapp/beapp-master
read_eeglabdata.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_eeglabdata.m
3,192
utf_8
6350cca8d6035012007f36178fdbfde5
% read_eeglabdata() - import EEGLAB dataset files % % Usage: % >> dat = read_eeglabdata(filename); % % Inputs: % filename - [string] file name % % Optional inputs: % 'begtrial' - [integer] first trial to read % 'endtrial' - [integer] last trial to read % 'chanindx' - [integer] list with channel indices to read % 'header' - FILEIO structure header % % Outputs: % dat - data over the specified range % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2008- %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function dat = read_eeglabdata(filename, varargin) if nargin < 1 help read_eeglabdata; return; end; header = ft_getopt(varargin, 'header'); begsample = ft_getopt(varargin, 'begsample'); endsample = ft_getopt(varargin, 'endsample'); begtrial = ft_getopt(varargin, 'begtrial'); endtrial = ft_getopt(varargin, 'endtrial'); chanindx = ft_getopt(varargin, 'chanindx'); if isempty(header) header = read_eeglabheader(filename); end if ischar(header.orig.data) if strcmpi(header.orig.data(end-2:end), 'set'), header.ori = load('-mat', filename); else % assuming that the data file is in the current directory fid = fopen(header.orig.data); % assuming the .dat and .set files are located in the same directory if fid == -1 pathstr = fileparts(filename); fid = fopen(fullfile(pathstr, header.orig.data)); end if fid == -1 fid = fopen(fullfile(header.orig.filepath, header.orig.data)); % end if fid == -1, error(['Cannot not find data file: ' header.orig.data]); end; % only read the desired trials if strcmpi(header.orig.data(end-2:end), 'dat') dat = fread(fid,[header.nSamples*header.nTrials header.nChans],'float32')'; else dat = fread(fid,[header.nChans header.nSamples*header.nTrials],'float32'); end; dat = reshape(dat, header.nChans, header.nSamples, header.nTrials); fclose(fid); end; else dat = header.orig.data; dat = reshape(dat, header.nChans, header.nSamples, header.nTrials); end; if isempty(begtrial), begtrial = 1; end; if isempty(endtrial), endtrial = header.nTrials; end; if isempty(begsample), begsample = 1; end; if isempty(endsample), endsample = header.nSamples; end; dat = dat(:,begsample:endsample,begtrial:endtrial); if ~isempty(chanindx) % select the desired channels dat = dat(chanindx,:,:); end
github
lcnbeapp/beapp-master
readbdf.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/readbdf.m
3,632
utf_8
9c94d90dc0c8728b0b46e5276747e847
% readbdf() - Loads selected Records of an EDF or BDF File (European Data Format % for Biosignals) into MATLAB % Usage: % >> [DAT,signal] = readedf(EDF_Struct,Records,Mode); % Notes: % Records - List of Records for Loading % Mode - 0 Default % 1 No AutoCalib % 2 Concatenated (channels with lower sampling rate % if more than 1 record is loaded) % Output: % DAT - EDF data structure % signal - output signal % % Author: Alois Schloegl, 03.02.1998, updated T.S. Lorig Sept 6, 2002 for BDF read % % See also: openbdf(), sdfopen(), sdfread(), eeglab() % Version 2.11 % 03.02.1998 % Copyright (c) 1997,98 by Alois Schloegl % [email protected] % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This program has been modified from the original version for .EDF files % The modifications are to the number of bytes read on line 53 (from 2 to % 3) and to the type of data read - line 54 (from int16 to bit24). Finally the name % was changed from readedf to readbdf % T.S. Lorig Sept 6, 2002 % % Header modified for eeglab() compatibility - Arnaud Delorme 12/02 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [DAT,S]=readbdf(DAT,Records,Mode) if nargin<3 Mode=0; end; EDF=DAT.Head; RecLen=max(EDF.SPR); S=nan(RecLen,EDF.NS); DAT.Record=zeros(length(Records)*RecLen,EDF.NS); DAT.Valid=uint8(zeros(1,length(Records)*RecLen)); DAT.Idx=Records(:)'; for nrec=1:length(Records), NREC=(DAT.Idx(nrec)-1); if NREC<0 fprintf(2,'Warning READEDF: invalid Record Number %i \n',NREC);end; fseek(EDF.FILE.FID,(EDF.HeadLen+NREC*EDF.AS.spb*3),'bof'); [s, count]=fread(EDF.FILE.FID,EDF.AS.spb,'bit24'); try, S(EDF.AS.IDX2)=s; catch, error('File is incomplete (try reading begining of file)'); end; %%%%% Test on Over- (Under-) Flow % V=sum([(S'==EDF.DigMax(:,ones(RecLen,1))) + (S'==EDF.DigMin(:,ones(RecLen,1)))])==0; V=sum([(S(:,EDF.Chan_Select)'>=EDF.DigMax(EDF.Chan_Select,ones(RecLen,1))) + ... (S(:,EDF.Chan_Select)'<=EDF.DigMin(EDF.Chan_Select,ones(RecLen,1)))])==0; EDF.ERROR.DigMinMax_Warning(find(sum([(S'>EDF.DigMax(:,ones(RecLen,1))) + (S'<EDF.DigMin(:,ones(RecLen,1)))]')>0))=1; % invalid=[invalid; find(V==0)+l*k]; if floor(Mode/2)==1 for k=1:EDF.NS, DAT.Record(nrec*EDF.SPR(k)+(1-EDF.SPR(k):0),k)=S(1:EDF.SPR(k),k); end; else DAT.Record(nrec*RecLen+(1-RecLen:0),:)=S; end; DAT.Valid(nrec*RecLen+(1-RecLen:0))=V; end; if rem(Mode,2)==0 % Autocalib DAT.Record=[ones(RecLen*length(Records),1) DAT.Record]*EDF.Calib; end; DAT.Record=DAT.Record'; return;
github
lcnbeapp/beapp-master
ft_platform_supports.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/ft_platform_supports.m
9,557
utf_8
eb0e55d84d57e6873cce8df6cad90d96
function tf = ft_platform_supports(what,varargin) % FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform % supports a specific capability % % Usage: % tf = ft_platform_supports(what) % tf = ft_platform_supports('matlabversion', min_version, max_version) % % The following values are allowed for the 'what' parameter: % value means that the following is supported: % % 'which-all' which(...,'all') % 'exists-in-private-directory' exists(...) will look in the /private % subdirectory to see if a file exists % 'onCleanup' onCleanup(...) % 'alim' alim(...) % 'int32_logical_operations' bitand(a,b) with a, b of type int32 % 'graphics_objects' graphics sysem is object-oriented % 'libmx_c_interface' libmx is supported through mex in the % C-language (recent Matlab versions only % support C++) % 'stats' all statistical functions in % FieldTrip's external/stats directory % 'program_invocation_name' program_invocation_name() (GNU Octave) % 'singleCompThread' start Matlab with -singleCompThread % 'nosplash' -nosplash % 'nodisplay' -nodisplay % 'nojvm' -nojvm % 'no-gui' start GNU Octave with --no-gui % 'RandStream.setGlobalStream' RandStream.setGlobalStream(...) % 'RandStream.setDefaultStream' RandStream.setDefaultStream(...) % 'rng' rng(...) % 'rand-state' rand('state') % 'urlread-timeout' urlread(..., 'Timeout', t) % 'griddata-vector-input' griddata(...,...,...,a,b) with a and b % vectors % 'griddata-v4' griddata(...,...,...,...,...,'v4'), % that is v4 interpolation support % 'uimenu' uimenu(...) if ~ischar(what) error('first argument must be a string'); end switch what case 'matlabversion' tf = is_matlab() && matlabversion(varargin{:}); case 'exists-in-private-directory' tf = is_matlab(); case 'which-all' tf = is_matlab(); case 'onCleanup' tf = is_octave() || matlabversion(7.8, Inf); case 'alim' tf = is_matlab(); case 'int32_logical_operations' % earlier version of Matlab don't support bitand (and similar) % operations on int32 tf = is_octave() || ~matlabversion(-inf, '2012a'); case 'graphics_objects' % introduced in Matlab 2014b, graphics is handled through objects; % previous versions use numeric handles tf = is_matlab() && matlabversion('2014b', Inf); case 'libmx_c_interface' % removed after 2013b tf = matlabversion(-Inf, '2013b'); case 'stats' root_dir=fileparts(which('ft_defaults')); external_stats_dir=fullfile(root_dir,'external','stats'); % these files are only used by other functions in the external/stats % directory exclude_mfiles={'common_size.m',... 'iscomplex.m',... 'lgamma.m'}; tf = has_all_functions_in_dir(external_stats_dir,exclude_mfiles); case 'program_invocation_name' % Octave supports program_invocation_name, which returns the path % of the binary that was run to start Octave tf = is_octave(); case 'singleCompThread' tf = is_matlab() && matlabversion(7.8, inf); case {'nosplash','nodisplay','nojvm'} % Only on Matlab tf = is_matlab(); case 'no-gui' % Only on Octave tf = is_octave(); case 'RandStream.setDefaultStream' tf = is_matlab() && matlabversion('2008b', '2011b'); case 'RandStream.setGlobalStream' tf = is_matlab() && matlabversion('2012a', inf); case 'randomized_PRNG_on_startup' tf = is_octave() || ~matlabversion(-Inf,'7.3'); case 'rng' % recent Matlab versions tf = is_matlab() && matlabversion('7.12',Inf); case 'rand-state' % GNU Octave tf = is_octave(); case 'urlread-timeout' tf = is_matlab() && matlabversion('2012b',Inf); case 'griddata-vector-input' tf = is_matlab(); case 'griddata-v4' tf = is_matlab() && matlabversion('2009a',Inf); case 'uimenu' tf = is_matlab(); otherwise error('unsupported value for first argument: %s', what); end % switch end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_matlab() tf = ~is_octave(); end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_octave() persistent cached_tf; if isempty(cached_tf) cached_tf = logical(exist('OCTAVE_VERSION', 'builtin')); end tf = cached_tf; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = has_all_functions_in_dir(in_dir, exclude_mfiles) % returns true if all functions in in_dir are already provided by the % platform m_files=dir(fullfile(in_dir,'*.m')); n=numel(m_files); for k=1:n m_filename=m_files(k).name; if isempty(which(m_filename)) && ... isempty(strmatch(m_filename,exclude_mfiles)) tf=false; return; end end tf=true; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [inInterval] = matlabversion(min, max) % MATLABVERSION checks if the current MATLAB version is within the interval % specified by min and max. % % Use, e.g., as: % if matlabversion(7.0, 7.9) % % do something % end % % Both strings and numbers, as well as infinities, are supported, eg.: % matlabversion(7.1, 7.9) % is version between 7.1 and 7.9? % matlabversion(6, '7.10') % is version between 6 and 7.10? (note: '7.10', not 7.10) % matlabversion(-Inf, 7.6) % is version <= 7.6? % matlabversion('2009b') % exactly 2009b % matlabversion('2008b', '2010a') % between two versions % matlabversion('2008b', Inf) % from a version onwards % etc. % % See also VERSION, VER, VERLESSTHAN % Copyright (C) 2006, Robert Oostenveld % Copyright (C) 2010, Eelke Spaak % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this does not change over subsequent calls, making it persistent speeds it up persistent curVer if nargin<2 max = min; end if isempty(curVer) curVer = version(); end if ((ischar(min) && isempty(str2num(min))) || (ischar(max) && isempty(str2num(max)))) % perform comparison with respect to release string ind = strfind(curVer, '(R'); [year, ab] = parseMatlabRelease(curVer((ind + 2):(numel(curVer) - 1))); [minY, minAb] = parseMatlabRelease(min); [maxY, maxAb] = parseMatlabRelease(max); inInterval = orderedComparison(minY, minAb, maxY, maxAb, year, ab); else % perform comparison with respect to version number [major, minor] = parseMatlabVersion(curVer); [minMajor, minMinor] = parseMatlabVersion(min); [maxMajor, maxMinor] = parseMatlabVersion(max); inInterval = orderedComparison(minMajor, minMinor, maxMajor, maxMinor, major, minor); end end % function function [year, ab] = parseMatlabRelease(str) if (str == Inf) year = Inf; ab = Inf; elseif (str == -Inf) year = -Inf; ab = -Inf; else year = str2num(str(1:4)); ab = str(5); end end % function function [major, minor] = parseMatlabVersion(ver) if (ver == Inf) major = Inf; minor = Inf; elseif (ver == -Inf) major = -Inf; minor = -Inf; elseif (isnumeric(ver)) major = floor(ver); minor = int8((ver - floor(ver)) * 10); else % ver is string (e.g. '7.10'), parse accordingly [major, rest] = strtok(ver, '.'); major = str2num(major); minor = str2num(strtok(rest, '.')); end end % function % checks if testA is in interval (lowerA,upperA); if at edges, checks if testB is in interval (lowerB,upperB). function inInterval = orderedComparison(lowerA, lowerB, upperA, upperB, testA, testB) if (testA < lowerA || testA > upperA) inInterval = false; else inInterval = true; if (testA == lowerA) inInterval = inInterval && (testB >= lowerB); end if (testA == upperA) inInterval = inInterval && (testB <= upperB); end end end % function
github
lcnbeapp/beapp-master
ft_warning.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/ft_warning.m
7,789
utf_8
d832a7ad5e2f9bb42995e6e5d4caa198
function [ws, warned] = ft_warning(varargin) % FT_WARNING will throw a warning for every unique point in the % stacktrace only, e.g. in a for-loop a warning is thrown only once. % % Use as one of the following % ft_warning(string) % ft_warning(id, string) % Alternatively, you can use ft_warning using a timeout % ft_warning(string, timeout) % ft_warning(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. % % Use as ft_warning('-clear') to clear old warnings from the current % stack % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = ft_warning(...) % or as % ft_warning(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, ft_warning accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = ft_warning(...) % where w is a boolean that indicates whether a warning as been thrown or not. % % Please note that you can NOT use it like this % ft_warning('the value is %d', 10) % instead you should do % ft_warning(sprintf('the value is %d', 10)) % Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ global ft_default warned = false; ws = []; stack = dbstack; if any(strcmp({stack(2:end).file}, 'ft_warning.m')) % don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068 return; end if nargin < 1 error('You need to specify at least a warning message'); end if isstruct(varargin{1}) warning(varargin{1}); return; end if ~isfield(ft_default, 'warning') ft_default.warning = []; end if ~isfield(ft_default.warning, 'stopwatch') ft_default.warning.stopwatch = []; end if ~isfield(ft_default.warning, 'identifier') ft_default.warning.identifier = []; end if ~isfield(ft_default.warning, 'ignore') ft_default.warning.ignore = {}; end % put the arguments we will pass to warning() in this cell array warningArgs = {}; if nargin==3 % calling syntax (id, msg, timeout) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); msg = warningArgs{1}; timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && isequal(varargin{1}, 'off') ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && isequal(varargin{1}, 'on') ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = inf; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); msg = warningArgs{1}; timeout = inf; % default timeout in seconds fname = [warningArgs{1}]; end if ismember(msg, ft_default.warning.ignore) % do not show this warning return; end if isempty(timeout) error('Timeout ill-specified'); end if timeout ~= inf fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures line = []; else % here, we create the fieldname functionA.functionB.functionC... [tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier); if ~isempty(tmpfname), fname = tmpfname; clear tmpfname; end end if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1}) if strcmp(fname, '-clear') % reset all fields if called outside a function ft_default.warning.identifier = []; ft_default.warning.stopwatch = []; else if issubfield(ft_default.warning.identifier, fname) ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname); end end return; end % and add the line number to make this unique for the last function fname = horzcat(fname, line); if ~issubfield('ft_default.warning.stopwatch', fname) ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic); end now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call if ~issubfield(ft_default.warning.identifier, fname) || ... (issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout'])) % create or reset field ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []); % warning never given before or timed out ws = warning(warningArgs{:}); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg); warned = true; else % the warning has been issued before, but has not timed out yet ws = getsubfield(ft_default.warning.identifier, [fname '.ws']); end end % function ft_warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings) % stack(1) is this function, stack(2) is ft_warning stack = dbstack('-completenames'); if size(stack) < 3 fname = []; line = []; return; end i0 = 3; % ignore ft_preamble while strfind(stack(i0).name, 'ft_preamble') i0=i0+1; end fname = horzcat(fixname(stack(end).name)); if ~issubfield(ft_previous_warnings, fixname(stack(end).name)) ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields end for i=numel(stack)-1:-1:(i0) % skip postamble scripts if strncmp(stack(i).name, 'ft_postamble', 12) break; end fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields setsubfield(ft_previous_warnings, fname, []); end end % line of last function call line = ['.line', int2str(stack(i0).line)]; end % function outcome = issubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % outcome = isfield(strct, fname); % end % end % function strct = rmsubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % strct = rmfield(strct, fname); % end % end
github
lcnbeapp/beapp-master
ft_hastoolbox.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/ft_hastoolbox.m
24,831
utf_8
43bae19e25ce108f013f1c401e497630
function [status] = ft_hastoolbox(toolbox, autoadd, silent) % FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally % it will try to determine the path to the toolbox and install it % automatically. % % Use as % [status] = ft_hastoolbox(toolbox, autoadd, silent) % % autoadd = 0 means that it will not be added % autoadd = 1 means that give an error if it cannot be added % autoadd = 2 means that give a warning if it cannot be added % autoadd = 3 means that it remains silent if it cannot be added % % silent = 0 means that it will give some feedback about adding the toolbox % silent = 1 means that it will not give feedback % Copyright (C) 2005-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before % persistent previous previouspath % % if ~isequal(previouspath, path) % previous = []; % end % % if isempty(previous) % previous = struct; % elseif isfield(previous, fixname(toolbox)) % status = previous.(fixname(toolbox)); % return % end if isdeployed % it is not possible to check the presence of functions or change the path in a compiled application status = 1; return end % this points the user to the website where he/she can download the toolbox url = { 'AFNI' 'see http://afni.nimh.nih.gov' 'DSS' 'see http://www.cis.hut.fi/projects/dss' 'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab' 'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox' 'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM12' 'see http://www.fil.ion.ucl.ac.uk/spm' 'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd' 'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com' 'BIOSIG' 'see http://biosig.sourceforge.net' 'EEG' 'see http://eeg.sourceforge.net' 'EEGSF' 'see http://eeg.sourceforge.net' % alternative name 'MRI' 'see http://eeg.sourceforge.net' % alternative name 'NEUROSHARE' 'see http://www.neuroshare.org' 'BESA' 'see http://www.besa.de/downloads/matlab/ and get the "BESA MATLAB Readers"' 'MATLAB2BESA' 'see http://www.besa.de/downloads/matlab/ and get the "MATLAB to BESA Export functions"' 'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde' 'YOKOGAWA' 'this is deprecated, please use YOKOGAWA_MEG_READER instead' 'YOKOGAWA_MEG_READER' 'see http://www.yokogawa.com/me/me-login-en.htm' 'BEOWULF' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'MENTAT' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth' '4D-VERSION' 'contact Christian Wienbruch' 'COMM' 'see http://www.mathworks.com/products/communications' 'SIGNAL' 'see http://www.mathworks.com/products/signal' 'OPTIM' 'see http://www.mathworks.com/products/optim' 'IMAGE' 'see http://www.mathworks.com/products/image' % Mathworks refers to this as IMAGES 'SPLINES' 'see http://www.mathworks.com/products/splines' 'DISTCOMP' 'see http://www.mathworks.nl/products/parallel-computing/' 'COMPILER' 'see http://www.mathworks.com/products/compiler' 'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica' 'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm' 'FILEIO' 'see http://www.fieldtriptoolbox.org' 'PREPROC' 'see http://www.fieldtriptoolbox.org' 'FORWARD' 'see http://www.fieldtriptoolbox.org' 'INVERSE' 'see http://www.fieldtriptoolbox.org' 'SPECEST' 'see http://www.fieldtriptoolbox.org' 'REALTIME' 'see http://www.fieldtriptoolbox.org' 'PLOTTING' 'see http://www.fieldtriptoolbox.org' 'SPIKE' 'see http://www.fieldtriptoolbox.org' 'CONNECTIVITY' 'see http://www.fieldtriptoolbox.org' 'PEER' 'see http://www.fieldtriptoolbox.org' 'PLOTTING' 'see http://www.fieldtriptoolbox.org' 'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne' 'BCI2000' 'see http://bci2000.org' 'NLXNETCOM' 'see http://www.neuralynx.com' 'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external' 'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php' 'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydesaeter' 'BEMCP' 'contact Christophe Phillips' 'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435' 'PRTOOLS' 'see http://www.prtools.org' 'ITAB' 'contact Stefania Della Penna' 'BSMART' 'see http://www.brain-smart.org' 'PEER' 'see http://www.fieldtriptoolbox.org/development/peer' 'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki' 'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page' 'VGRID' 'see http://www.rheinahrcampus.de/~medsim/vgrid/manual.html' 'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS' 'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti' 'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0' 'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab' 'BCT' 'see http://www.brain-connectivity-toolbox.net/' 'CCA' 'see http://www.imt.liu.se/~magnus/cca or contact Magnus Borga' 'EGI_MFF' 'see http://www.egi.com/ or contact either Phan Luu or Colin Davey at EGI' 'TOOLBOX_GRAPH' 'see http://www.mathworks.com/matlabcentral/fileexchange/5355-toolbox-graph or contact Gabriel Peyre' 'NETCDF' 'see http://www.mathworks.com/matlabcentral/fileexchange/15177' 'MYSQL' 'see http://www.mathworks.com/matlabcentral/fileexchange/8663-mysql-database-connector' 'ISO2MESH' 'see http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?Home or contact Qianqian Fang' 'DATAHASH' 'see http://www.mathworks.com/matlabcentral/fileexchange/31272' 'IBTB' 'see http://www.ibtb.org' 'ICASSO' 'see http://www.cis.hut.fi/projects/ica/icasso' 'XUNIT' 'see http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework' 'PLEXON' 'available from http://www.plexon.com/assets/downloads/sdk/ReadingPLXandDDTfilesinMatlab-mexw.zip' 'MISC' 'various functions that were downloaded from http://www.mathworks.com/matlabcentral/fileexchange and elsewhere' '35625-INFORMATION-THEORY-TOOLBOX' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox' '29046-MUTUAL-INFORMATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox' '14888-MUTUAL-INFORMATION-COMPUTATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/14888-mutual-information-computation' 'PLOT2SVG' 'see http://www.mathworks.com/matlabcentral/fileexchange/7401-scalable-vector-graphics-svg-export-of-figures' 'BRAINSUITE' 'see http://brainsuite.bmap.ucla.edu/processing/additional-tools/' 'BRAINVISA' 'see http://brainvisa.info' 'FILEEXCHANGE' 'see http://www.mathworks.com/matlabcentral/fileexchange/' 'NEURALYNX_V6' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Neuralynx (windows only)' 'NEURALYNX_V3' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Ueli Rutishauser' 'NPMK' 'see https://github.com/BlackrockMicrosystems/NPMK' 'VIDEOMEG' 'see https://github.com/andreyzhd/VideoMEG' 'WAVEFRONT' 'see http://mathworks.com/matlabcentral/fileexchange/27982-wavefront-obj-toolbox' 'NEURONE' 'see http://www.megaemg.com/support/unrestricted-downloads' }; if nargin<2 % default is not to add the path automatically autoadd = 0; end if nargin<3 % default is not to be silent silent = 0; end % determine whether the toolbox is installed toolbox = upper(toolbox); % In case SPM8 or higher not available, allow to use fallback toolbox fallback_toolbox=''; switch toolbox case 'AFNI' dependency={'BrikLoad', 'BrikInfo'}; case 'DSS' dependency={'denss', 'dss_create_state'}; case 'EEGLAB' dependency = 'runica'; case 'NWAY' dependency = 'parafac'; case 'SPM' dependency = 'spm'; % any version of SPM is fine case 'SPM99' dependency = {'spm', get_spm_version()==99}; case 'SPM2' dependency = {'spm', get_spm_version()==2}; case 'SPM5' dependency = {'spm', get_spm_version()==5}; case 'SPM8' dependency = {'spm', get_spm_version()==8}; case 'SPM8UP' % version 8 or later, but not SPM 9X dependency = {'spm', get_spm_version()>=8, get_spm_version()<95}; %This is to avoid crashes when trying to add SPM to the path fallback_toolbox = 'SPM8'; case 'SPM12' dependency = {'spm', get_spm_version()==12}; case 'MEG-PD' dependency = {'rawdata', 'channames'}; case 'MEG-CALC' dependency = {'megmodel', 'megfield', 'megtrans'}; case 'BIOSIG' dependency = {'sopen', 'sread'}; case 'EEG' dependency = {'ctf_read_res4', 'ctf_read_meg4'}; case 'EEGSF' % alternative name dependency = {'ctf_read_res4', 'ctf_read_meg4'}; case 'MRI' % other functions in the mri section dependency = {'avw_hdr_read', 'avw_img_read'}; case 'NEUROSHARE' dependency = {'ns_OpenFile', 'ns_SetLibrary', ... 'ns_GetAnalogData'}; case 'ARTINIS' dependency = {'read_artinis_oxy3'}; case 'BESA' dependency = {'readBESAavr', 'readBESAelp', 'readBESAswf'}; case 'MATLAB2BESA' dependency = {'besa_save2Avr', 'besa_save2Elp', 'besa_save2Swf'}; case 'EEPROBE' dependency = {'read_eep_avr', 'read_eep_cnt'}; case 'YOKOGAWA' dependency = @()hasyokogawa('16bitBeta6'); case 'YOKOGAWA12BITBETA3' dependency = @()hasyokogawa('12bitBeta3'); case 'YOKOGAWA16BITBETA3' dependency = @()hasyokogawa('16bitBeta3'); case 'YOKOGAWA16BITBETA6' dependency = @()hasyokogawa('16bitBeta6'); case 'YOKOGAWA_MEG_READER' dependency = @()hasyokogawa('1.4'); case 'BEOWULF' dependency = {'evalwulf', 'evalwulf', 'evalwulf'}; case 'MENTAT' dependency = {'pcompile', 'pfor', 'peval'}; case 'SON2' dependency = {'SONFileHeader', 'SONChanList', 'SONGetChannel'}; case '4D-VERSION' dependency = {'read4d', 'read4dhdr'}; case {'STATS', 'STATISTICS'} dependency = has_license('statistics_toolbox'); % check the availability of a toolbox license case {'OPTIM', 'OPTIMIZATION'} dependency = has_license('optimization_toolbox'); % check the availability of a toolbox license case {'SPLINES', 'CURVE_FITTING'} dependency = has_license('curve_fitting_toolbox'); % check the availability of a toolbox license case 'COMM' dependency = {has_license('communication_toolbox'), 'de2bi'}; % also check the availability of a toolbox license case 'SIGNAL' dependency = {has_license('signal_toolbox'), 'window'}; % also check the availability of a toolbox license case 'IMAGE' dependency = has_license('image_toolbox'); % check the availability of a toolbox license case {'DCT', 'DISTCOMP'} dependency = has_license('distrib_computing_toolbox'); % check the availability of a toolbox license case 'COMPILER' dependency = has_license('compiler'); % check the availability of a toolbox license case 'FASTICA' dependency = 'fpica'; case 'BRAINSTORM' dependency = 'bem_xfer'; case 'DENOISE' dependency = {'tsr', 'sns'}; case 'CTF' dependency = {'getCTFBalanceCoefs', 'getCTFdata'}; case 'BCI2000' dependency = {'load_bcidat'}; case 'NLXNETCOM' dependency = {'MatlabNetComClient', 'NlxConnectToServer', ... 'NlxGetNewCSCData'}; case 'DIPOLI' dependency = {'dipoli.maci', 'file'}; case 'MNE' dependency = {'fiff_read_meas_info', 'fiff_setup_read_raw'}; case 'TCP_UDP_IP' dependency = {'pnet', 'pnet_getvar', 'pnet_putvar'}; case 'BEMCP' dependency = {'bem_Cij_cog', 'bem_Cij_lin', 'bem_Cij_cst'}; case 'OPENMEEG' dependency = {'om_save_tri'}; case 'PRTOOLS' dependency = {'prversion', 'dataset', 'svc'}; case 'ITAB' dependency = {'lcReadHeader', 'lcReadData'}; case 'BSMART' dependency = 'bsmart'; case 'FREESURFER' dependency = {'MRIread', 'vox2ras_0to1'}; case 'FNS' dependency = 'elecsfwd'; case 'SIMBIO' dependency = {'calc_stiff_matrix_val', 'sb_transfer'}; case 'VGRID' dependency = 'vgrid'; case 'GIFTI' dependency = 'gifti'; case 'XML4MAT' dependency = {'xml2struct', 'xml2whos'}; case 'SQDPROJECT' dependency = {'sqdread', 'sqdwrite'}; case 'BCT' dependency = {'macaque71.mat', 'motif4funct_wei'}; case 'CCA' dependency = {'ccabss'}; case 'EGI_MFF' dependency = {'mff_getObject', 'mff_getSummaryInfo'}; case 'TOOLBOX_GRAPH' dependency = 'toolbox_graph'; case 'NETCDF' dependency = {'netcdf'}; case 'MYSQL' % not sure if 'which' would work fine here, so use 'exist' dependency = has_mex('mysql'); % this only consists of a single mex file case 'ISO2MESH' dependency = {'vol2surf', 'qmeshcut'}; case 'QSUB' dependency = {'qsubfeval', 'qsubcellfun'}; case 'ENGINE' dependency = {'enginefeval', 'enginecellfun'}; case 'DATAHASH' dependency = {'DataHash'}; case 'IBTB' dependency = {'make_ibtb','binr'}; case 'ICASSO' dependency = {'icassoEst'}; case 'XUNIT' dependency = {'initTestSuite', 'runtests'}; case 'PLEXON' dependency = {'plx_adchan_gains', 'mexPlex'}; case '35625-INFORMATION-THEORY-TOOLBOX' dependency = {'conditionalEntropy', 'entropy', 'jointEntropy',... 'mutualInformation' 'nmi' 'nvi' 'relativeEntropy'}; case '29046-MUTUAL-INFORMATION' dependency = {'MI', 'license.txt'}; case '14888-MUTUAL-INFORMATION-COMPUTATION' dependency = {'condentropy', 'demo_mi', 'estcondentropy.cpp',... 'estjointentropy.cpp', 'estpa.cpp', ... 'findjointstateab.cpp', 'makeosmex.m',... 'mutualinfo.m', 'condmutualinfo.m',... 'entropy.m', 'estentropy.cpp',... 'estmutualinfo.cpp', 'estpab.cpp',... 'jointentropy.m' 'mergemultivariables.m' }; case 'PLOT2SVG' dependency = {'plot2svg.m', 'simulink2svg.m'}; case 'BRAINSUITE' dependency = {'readdfs.m', 'writedfc.m'}; case 'BRAINVISA' dependency = {'loadmesh.m', 'plotmesh.m', 'savemesh.m'}; case 'NEURALYNX_V6' dependency = has_mex('Nlx2MatCSC'); case 'NEURALYNX_V3' dependency = has_mex('Nlx2MatCSC_v3'); case 'NPMK' dependency = {'OpenNSx' 'OpenNEV'}; case 'VIDEOMEG' dependency = {'comp_tstamps' 'load_audio0123', 'load_video123'}; case 'WAVEFRONT' dependency = {'write_wobj' 'read_wobj'}; case 'NEURONE' dependency = {'readneurone' 'readneuronedata' 'readneuroneevents'}; % the following are FieldTrip modules/toolboxes case 'FILEIO' dependency = {'ft_read_header', 'ft_read_data', ... 'ft_read_event', 'ft_read_sens'}; case 'FORWARD' dependency = {'ft_compute_leadfield', 'ft_prepare_vol_sens'}; case 'PLOTTING' dependency = {'ft_plot_topo', 'ft_plot_mesh', 'ft_plot_matrix'}; case 'PEER' dependency = {'peerslave', 'peermaster'}; case 'CONNECTIVITY' dependency = {'ft_connectivity_corr', 'ft_connectivity_granger'}; case 'SPIKE' dependency = {'ft_spiketriggeredaverage', 'ft_spiketriggeredspectrum'}; case 'FILEEXCHANGE' dependency = is_subdir_in_fieldtrip_path('/external/fileexchange'); case {'INVERSE', 'REALTIME', 'SPECEST', 'PREPROC', ... 'COMPAT', 'STATFUN', 'TRIALFUN', 'UTILITIES/COMPAT', ... 'FILEIO/COMPAT', 'PREPROC/COMPAT', 'FORWARD/COMPAT', ... 'PLOTTING/COMPAT', 'TEMPLATE/LAYOUT', 'TEMPLATE/ANATOMY' ,... 'TEMPLATE/HEADMODEL', 'TEMPLATE/ELECTRODE', ... 'TEMPLATE/NEIGHBOURS', 'TEMPLATE/SOURCEMODEL'} dependency = is_subdir_in_fieldtrip_path(toolbox); otherwise if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end dependency = false; end status = is_present(dependency); if ~status && ~isempty(fallback_toolbox) % in case of SPM8UP toolbox = fallback_toolbox; end % try to determine the path of the requested toolbox if autoadd>0 && ~status % for core FieldTrip modules prefix = fileparts(which('ft_defaults')); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for external FieldTrip modules prefix = fullfile(fileparts(which('ft_defaults')), 'external'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for contributed FieldTrip extensions prefix = fullfile(fileparts(which('ft_defaults')), 'contrib'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for linux computers in the Donders Centre for Cognitive Neuroimaging prefix = '/home/common/matlab'; if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for windows computers in the Donders Centre for Cognitive Neuroimaging prefix = 'h:\common\matlab'; if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % use the MATLAB subdirectory in your homedirectory, this works on linux and mac prefix = fullfile(getenv('HOME'), 'matlab'); if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end if ~status % the toolbox is not on the path and cannot be added sel = find(strcmp(url(:,1), toolbox)); if ~isempty(sel) msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2}); else msg = sprintf('the %s toolbox is not installed', toolbox); end if autoadd==1 error(msg); elseif autoadd==2 ft_warning(msg); else % fail silently end end end % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before if status previous.(fixname(toolbox)) = status; end % remember the previous path, allows us to determine on the next call % whether the path has been modified outise of this function previouspath = path; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = myaddpath(toolbox, silent) if isdeployed warning('cannot change path settings for %s in a compiled application', toolbox); status = 1; elseif exist(toolbox, 'dir') if ~silent, ws = warning('backtrace', 'off'); warning('adding %s toolbox to your MATLAB path', toolbox); warning(ws); % return to the previous warning level end addpath(toolbox); status = 1; elseif (~isempty(regexp(toolbox, 'spm5$', 'once')) || ~isempty(regexp(toolbox, 'spm8$', 'once')) || ~isempty(regexp(toolbox, 'spm12$', 'once'))) && exist([toolbox 'b'], 'dir') status = myaddpath([toolbox 'b'], silent); else status = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function path = unixpath(path) %path(path=='\') = '/'; % replace backward slashes with forward slashes path = strrep(path,'\','/'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = hasfunction(funname, toolbox) try % call the function without any input arguments, which probably is inapropriate feval(funname); % it might be that the function without any input already works fine status = true; catch % either the function returned an error, or the function is not available % availability is influenced by the function being present and by having a % license for the function, i.e. in a concurrent licensing setting it might % be that all toolbox licenses are in use m = lasterror; if strcmp(m.identifier, 'MATLAB:license:checkouterror') if nargin>1 warning('the %s toolbox is available, but you don''t have a license for it', toolbox); else warning('the function ''%s'' is available, but you don''t have a license for it', funname); end status = false; elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction') status = false; else % the function seems to be available and it gave an unknown error, % which is to be expected with inappropriate input arguments status = true; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = is_subdir_in_fieldtrip_path(toolbox_name) fttrunkpath = unixpath(fileparts(which('ft_defaults'))); fttoolboxpath = fullfile(fttrunkpath, lower(toolbox_name)); needle=[pathsep fttoolboxpath pathsep]; haystack = [pathsep path() pathsep]; status = ~isempty(findstr(needle, haystack)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = has_mex(name) full_name=[name '.' mexext]; status = (exist(full_name, 'file')==3); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function v = get_spm_version() if ~is_present('spm') v=NaN; return end version_str = spm('ver'); token = regexp(version_str,'(\d*)','tokens'); v = str2num([token{:}{:}]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = has_license(toolbox_name) status = license('checkout', toolbox_name)==1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = is_present(dependency) if iscell(dependency) % use recursion status = all(cellfun(@is_present,dependency)); elseif islogical(dependency) % boolean status = all(dependency); elseif ischar(dependency) % name of a function status = is_function_present_in_search_path(dependency); elseif isa(dependency, 'function_handle') status = dependency(); else assert(false,'this should not happen'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = is_function_present_in_search_path(function_name) w = which(function_name); % must be in path and not a variable status = ~isempty(w) && ~isequal(w, 'variable');
github
lcnbeapp/beapp-master
read_yokogawa_data_new.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_yokogawa_data_new.m
5,623
utf_8
521f307689398a9963b8d12d779650dd
function [dat] = read_yokogawa_data_new(filename, hdr, begsample, endsample, chanindx) % READ_YOKAGAWA_DATA_NEW reads continuous, epoched or averaged MEG data % that has been generated by the Yokogawa MEG system and software % and allows that data to be used in combination with FieldTrip. % % Use as % [dat] = read_yokogawa_data_new(filename, hdr, begsample, endsample, chanindx) % % This is a wrapper function around the function % getYkgwData % % See also READ_YOKOGAWA_HEADER_NEW, READ_YOKOGAWA_EVENT % Copyright (C) 2005, Robert Oostenveld and 2010, Tilmann Sander-Thoemmes % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if ~ft_hastoolbox('yokogawa_meg_reader') error('cannot determine whether Yokogawa toolbox is present'); end % hdr = read_yokogawa_header(filename); hdr = hdr.orig; % use the original Yokogawa header, not the FieldTrip header % default is to select all channels if nargin<5 chanindx = 1:hdr.channel_count; end handles = definehandles; switch hdr.acq_type case handles.AcqTypeEvokedAve % dat is returned as double start_sample = begsample - 1; % samples start at 0 sample_length = endsample - begsample + 1; epoch_count = 1; start_epoch = 0; dat = getYkgwData(filename, start_sample, sample_length); case handles.AcqTypeContinuousRaw % dat is returned as double start_sample = begsample - 1; % samples start at 0 sample_length = endsample - begsample + 1; epoch_count = 1; start_epoch = 0; dat = getYkgwData(filename, start_sample, sample_length); case handles.AcqTypeEvokedRaw % dat is returned as double begtrial = ceil(begsample/hdr.sample_count); endtrial = ceil(endsample/hdr.sample_count); if begtrial<1 error('cannot read before the begin of the file'); elseif endtrial>hdr.actual_epoch_count error('cannot read beyond the end of the file'); end epoch_count = endtrial-begtrial+1; start_epoch = begtrial-1; % read all the neccessary trials that contain the desired samples dat = getYkgwData(filename, start_epoch, epoch_count); if size(dat,2)~=epoch_count*hdr.sample_count error('could not read all epochs'); end rawbegsample = begsample - (begtrial-1)*hdr.sample_count; rawendsample = endsample - (begtrial-1)*hdr.sample_count; sample_length = rawendsample - rawbegsample + 1; % select the desired samples from the complete trials dat = dat(:,rawbegsample:rawendsample); otherwise error('unknown data type'); end if size(dat,1)~=hdr.channel_count error('could not read all channels'); elseif size(dat,2)~=(endsample-begsample+1) error('could not read all samples'); end % select only the desired channels dat = dat(chanindx,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
lcnbeapp/beapp-master
read_plexon_nex.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_plexon_nex.m
7,574
utf_8
0034c1c75c81e41e90e48c678ed2ca9e
function [varargout] = read_plexon_nex(filename, varargin) % READ_PLEXON_NEX reads header or data from a Plexon *.nex file, which % is a file containing action-potential (spike) timestamps and waveforms % (spike channels), event timestamps (event channels), and continuous % variable data (continuous A/D channels). % % LFP and spike waveform data that is returned by this function is % expressed in microVolt. % % Use as % [hdr] = read_plexon_nex(filename) % [dat] = read_plexon_nex(filename, ...) % [dat1, dat2, dat3, hdr] = read_plexon_nex(filename, ...) % % Optional arguments should be specified in key-value pairs and can be % header structure with header information % feedback 0 or 1 % tsonly 0 or 1, read only the timestamps and not the waveforms % channel number, or list of numbers (that will result in multiple outputs) % begsample number (for continuous only) % endsample number (for continuous only) % % See also READ_PLEXON_PLX, READ_PLEXON_DDT % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % parse the optional input arguments hdr = ft_getopt(varargin, 'header'); channel = ft_getopt(varargin, 'channel'); feedback = ft_getopt(varargin, 'feedback', false); tsonly = ft_getopt(varargin, 'tsonly', false); begsample = ft_getopt(varargin, 'begsample', 1); endsample = ft_getopt(varargin, 'endsample', inf); % start with empty return values and empty data varargout = {}; % read header info from file, use Matlabs for automatic byte-ordering fid = fopen(filename, 'r', 'ieee-le'); fseek(fid, 0, 'eof'); siz = ftell(fid); fseek(fid, 0, 'bof'); if isempty(hdr) if feedback, fprintf('reading header from %s\n', filename); end % a NEX file consists of a file header, followed by a number of variable headers % sizeof(NexFileHeader) = 544 % sizeof(NexVarHeader) = 208 hdr.FileHeader = NexFileHeader(fid); if hdr.FileHeader.NumVars<1 error('no channels present in file'); end hdr.VarHeader = NexVarHeader(fid, hdr.FileHeader.NumVars); end for i=1:length(channel) chan = channel(i); vh = hdr.VarHeader(chan); clear buf fseek(fid, vh.DataOffset, 'bof'); switch vh.Type case 0 % Neurons, only timestamps buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); case 1 % Events, only timestamps buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); case 2 % Interval variables buf.begs = fread(fid, [1 vh.Count], 'int32=>int32'); buf.ends = fread(fid, [1 vh.Count], 'int32=>int32'); case 3 % Waveform variables buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); if ~tsonly buf.dat = fread(fid, [vh.NPointsWave vh.Count], 'int16'); % convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt buf.dat = buf.dat * (vh.ADtoMV * 1000); end case 4 % Population vector error('population vectors are not supported'); case 5 % Continuously recorded variables buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); buf.indx = fread(fid, [1 vh.Count], 'int32=>int32'); if vh.Count>1 && (begsample~=1 || endsample~=inf) error('reading selected samples from multiple AD segments is not supported'); end if ~tsonly numsample = min(endsample - begsample + 1, vh.NPointsWave); fseek(fid, (begsample-1)*2, 'cof'); buf.dat = fread(fid, [1 numsample], 'int16'); % convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt buf.dat = buf.dat * (vh.ADtoMV * 1000); end case 6 % Markers buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); for j=1:vh.NMarkers buf.MarkerNames{j,1} = fread(fid, [1 64], 'uint8=>char'); for k=1:vh.Count buf.MarkerValues{j,k} = fread(fid, [1 vh.MarkerLength], 'uint8=>char'); end end otherwise error('incorrect channel type'); end % switch channel type % return the data of this channel varargout{i} = buf; end % for channel % always return the header as last varargout{end+1} = hdr; fclose(fid); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = NexFileHeader(fid) hdr.NexFileHeader = fread(fid,4,'uint8=>char')'; % string NEX1 hdr.Version = fread(fid,1,'int32'); hdr.Comment = fread(fid,256,'uint8=>char')'; hdr.Frequency = fread(fid,1,'double'); % timestamped freq. - tics per second hdr.Beg = fread(fid,1,'int32'); % usually 0 hdr.End = fread(fid,1,'int32'); % maximum timestamp + 1 hdr.NumVars = fread(fid,1,'int32'); % number of variables in the first batch hdr.NextFileHeader = fread(fid,1,'int32'); % position of the next file header in the file, not implemented yet Padding = fread(fid,256,'uint8=>char')'; % future expansion %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = NexVarHeader(fid, numvar) for varlop=1:numvar hdr(varlop).Type = fread(fid,1,'int32'); % 0 - neuron, 1 event, 2- interval, 3 - waveform, 4 - pop. vector, 5 - continuously recorded hdr(varlop).Version = fread(fid,1,'int32'); % 100 hdr(varlop).Name = fread(fid,64,'uint8=>char')'; % variable name hdr(varlop).DataOffset = fread(fid,1,'int32'); % where the data array for this variable is located in the file hdr(varlop).Count = fread(fid,1,'int32'); % number of events, intervals, waveforms or weights hdr(varlop).WireNumber = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).UnitNumber = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).Gain = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).Filter = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).XPos = fread(fid,1,'double'); % neuron only, electrode position in (0,100) range, used in 3D hdr(varlop).YPos = fread(fid,1,'double'); % neuron only, electrode position in (0,100) range, used in 3D hdr(varlop).WFrequency = fread(fid,1,'double'); % waveform and continuous vars only, w/f sampling frequency hdr(varlop).ADtoMV = fread(fid,1,'double'); % waveform continuous vars only, coeff. to convert from A/D values to Millivolts hdr(varlop).NPointsWave = fread(fid,1,'int32'); % waveform only, number of points in each wave hdr(varlop).NMarkers = fread(fid,1,'int32'); % how many values are associated with each marker hdr(varlop).MarkerLength = fread(fid,1,'int32'); % how many characters are in each marker value Padding = fread(fid,68,'uint8=>char')'; end
github
lcnbeapp/beapp-master
read_bti_m4d.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_bti_m4d.m
5,780
utf_8
744eebbd1eba1a856943c7ce24600bc4
function [msi] = read_bti_m4d(filename) % READ_BTI_M4D % % Use as % msi = read_bti_m4d(filename) % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ [p, f, x] = fileparts(filename); if ~strcmp(x, '.m4d') % add the extension of the header filename = [filename '.m4d']; end fid = fopen(filename, 'r'); if fid==-1 error(sprintf('could not open file %s', filename)); end % start with an empty header structure msi = struct; % these header elements contain strings and should be converted in a cell-array strlist = { 'MSI.ChannelOrder' }; % these header elements contain numbers and should be converted in a numeric array % 'MSI.ChannelScale' % 'MSI.ChannelGain' % 'MSI.FileType' % 'MSI.TotalChannels' % 'MSI.TotalEpochs' % 'MSI.SamplePeriod' % 'MSI.SampleFrequency' % 'MSI.FirstLatency' % 'MSI.SlicesPerEpoch' % the conversion to numeric arrays is implemented in a general fashion % and all the fields above are automatically converted numlist = {}; line = ''; msi.grad.label = {}; msi.grad.coilpos = zeros(0,3); msi.grad.coilori = zeros(0,3); while ischar(line) line = cleanline(fgetl(fid)); if isempty(line) || (length(line)==1 && all(line==-1)) continue end sep = strfind(line, ':'); if length(sep)==1 key = line(1:(sep-1)); val = line((sep+1):end); elseif length(sep)>1 % assume that the first separator is the relevant one, and that the % next ones are part of the value string (e.g. a channel with a ':' in % its name sep = sep(1); key = line(1:(sep-1)); val = line((sep+1):end); elseif length(sep)<1 % this is not what I would expect error('unexpected content in m4d file'); end if ~isempty(strfind(line, 'Begin')) && (~isempty(strfind(line, 'Meg_Position_Information')) || ~isempty(strfind(line, 'Ref_Position_Information'))) % jansch added the second ~isempty() to accommodate for when the % block is about Eeg_Position_Information, which does not pertain to % gradiometers, and moreover can be empty (added: Aug 03, 2013) sep = strfind(key, '.'); sep = sep(end); key = key(1:(sep-1)); % if the key ends with begin and there is no value, then there is a block % of numbers following that relates to the magnetometer/gradiometer information. % All lines in that Begin-End block should be treated separately val = {}; lab = {}; num = {}; ind = 0; while isempty(strfind(line, 'End')) line = cleanline(fgetl(fid)); if isempty(line) || (length(line)==1 && all(line==-1)) || ~isempty(strfind(line, 'End')) continue end ind = ind+1; % remember the line itself, and also cut it into pieces val{ind} = line; % the line is tab-separated and looks like this % A68 0.0873437 -0.075789 0.0891512 0.471135 -0.815532 0.336098 sep = find(line==9); % the ascii value of a tab is 9 sep = sep(1); lab{ind} = line(1:(sep-1)); num{ind} = str2num(line((sep+1):end)); end % parsing Begin-End block val = val(:); lab = lab(:); num = num(:); num = cell2mat(num); % the following is FieldTrip specific if size(num,2)==6 msi.grad.label = [msi.grad.label; lab(:)]; % the numbers represent position and orientation of each magnetometer coil msi.grad.coilpos = [msi.grad.coilpos; num(:,1:3)]; msi.grad.coilori = [msi.grad.coilori; num(:,4:6)]; else error('unknown gradiometer design') end end % the key looks like 'MSI.fieldname.subfieldname' fieldname = key(5:end); % remove spaces from the begin and end of the string val = strtrim(val); % try to convert the value string into something more usefull if ~iscell(val) % the value can contain a variety of elements, only some of which are decoded here if ~isempty(strfind(key, 'Index')) || ~isempty(strfind(key, 'Count')) || any(strcmp(key, numlist)) % this contains a single number or a comma-separated list of numbers val = str2num(val); elseif ~isempty(strfind(key, 'Names')) || any(strcmp(key, strlist)) % this contains a comma-separated list of strings val = tokenize(val, ','); else tmp = str2num(val); if ~isempty(tmp) val = tmp; end end end % assign this header element to the structure msi = setsubfield(msi, fieldname, val); end % while ischar(line) % each coil weighs with a value of 1 into each channel msi.grad.tra = eye(size(msi.grad.coilpos,1)); msi.grad.unit = 'm'; fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to remove spaces from the begin and end % and to remove comments from the lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function line = cleanline(line) if isempty(line) || (length(line)==1 && all(line==-1)) return end comment = findstr(line, '//'); if ~isempty(comment) line(min(comment):end) = ' '; end line = strtrim(line);
github
lcnbeapp/beapp-master
read_asa.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_asa.m
3,803
utf_8
290f06e1b51f627f99d257a5f1b49465
function [val] = read_asa(filename, elem, format, number, token) % READ_ASA reads a specified element from an ASA file % % val = read_asa(filename, element, type, number) % % where the element is a string such as % NumberSlices % NumberPositions % Rows % Columns % etc. % % and format specifies the datatype according to % %d (integer value) % %f (floating point value) % %s (string) % % number is optional to specify how many lines of data should be read % The default is 1 for strings and Inf for numbers. % % token is optional to specifiy a character that separates the values from % anything not wanted. % Copyright (C) 2002-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ fid = fopen(filename, 'rt'); if fid==-1 error(sprintf('could not open file %s', filename)); end if nargin<4 if strcmp(format, '%s') number = 1; else number = Inf; end end if nargin<5 token = ''; end val = []; elem = strtrim(lower(elem)); while (1) line = fgetl(fid); if ~isempty(line) && isequal(line, -1) % prematurely reached end of file fclose(fid); return end line = strtrim(line); lower_line = lower(line); if strmatch(elem, lower_line) data = line((length(elem)+1):end); break end end while isempty(data) line = fgetl(fid); if isequal(line, -1) % prematurely reached end of file fclose(fid); return end data = strtrim(line); end if strcmp(format, '%s') if number==1 % interpret the data as a single string, create char-array val = detoken(strtrim(data), token); if val(1)=='=' val = val(2:end); % remove the trailing = end fclose(fid); return end % interpret the data as a single string, create cell-array val{1} = detoken(strtrim(data), token); count = 1; % read the remaining strings while count<number line = fgetl(fid); if ~isempty(line) && isequal(line, -1) fclose(fid); return end tmp = sscanf(line, format); if isempty(tmp) fclose(fid); return else count = count + 1; val{count} = detoken(strtrim(line), token); end end else % interpret the data as numeric, create numeric array count = 1; data = sscanf(detoken(data, token), format)'; if isempty(data), fclose(fid); return else val(count,:) = data; end % read remaining numeric data while count<number line = fgetl(fid); if ~isempty(line) && isequal(line, -1) fclose(fid); return end data = sscanf(detoken(line, token), format)'; if isempty(data) fclose(fid); return else count = count+1; val(count,:) = data; end end end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [out] = detoken(in, token) if isempty(token) out = in; return; end [tok rem] = strtok(in, token); if isempty(rem) out = in; return; else out = strtok(rem, token); return end
github
lcnbeapp/beapp-master
ft_checkdata.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/ft_checkdata.m
57,523
utf_8
361ae795581b786433b88af3f624763d
function [data] = ft_checkdata(data, varargin) % FT_CHECKDATA checks the input data of the main FieldTrip functions, e.g. whether % the type of data strucure corresponds with the required data. If neccessary % and possible, this function will adjust the data structure to the input % requirements (e.g. change dimord, average over trials, convert inside from % index into logical). % % If the input data does NOT correspond to the requirements, this function % is supposed to give a elaborate warning message and if applicable point % the user to external documentation (link to website). % % Use as % [data] = ft_checkdata(data, ...) % % Optional input arguments should be specified as key-value pairs and can include % feedback = yes, no % datatype = raw, freq, timelock, comp, spike, source, dip, volume, segmentation, parcellation % dimord = any combination of time, freq, chan, refchan, rpt, subj, chancmb, rpttap, pos % senstype = ctf151, ctf275, ctf151_planar, ctf275_planar, neuromag122, neuromag306, bti148, bti248, bti248_planar, magnetometer, electrode % inside = logical, index % ismeg = yes, no % isnirs = yes, no % hasunit = yes, no % hascoordsys = yes, no % hassampleinfo = yes, no, ifmakessense (only applies to raw data) % hascumtapcnt = yes, no (only applies to freq data) % hasdim = yes, no % hasdof = yes, no % cmbrepresentation = sparse, full (applies to covariance and cross-spectral density) % fsample = sampling frequency to use to go from SPIKE to RAW representation % segmentationstyle = indexed, probabilistic (only applies to segmentation) % parcellationstyle = indexed, probabilistic (only applies to parcellation) % hasbrain = yes, no (only applies to segmentation) % % For some options you can specify multiple values, e.g. % [data] = ft_checkdata(data, 'senstype', {'ctf151', 'ctf275'}), e.g. in megrealign % [data] = ft_checkdata(data, 'datatype', {'timelock', 'freq'}), e.g. in sourceanalysis % Copyright (C) 2007-2015, Robert Oostenveld % Copyright (C) 2010-2012, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % in case of an error this function could use dbstack for more detailled % user feedback % % this function should replace/encapsulate % fixdimord % fixinside % fixprecision % fixvolume % data2raw % raw2data % grid2transform % transform2grid % fourier2crsspctrm % freq2cumtapcnt % sensortype % time2offset % offset2time % fixsens -> this is kept a separate function because it should also be % called from other modules % % other potential uses for this function: % time -> offset in freqanalysis % average over trials % csd as matrix % FIXME the following is difficult, if not impossible, to support without knowing the parameter % FIXME it is presently (dec 2014) not being used anywhere in FT, so can be removed % hastrials = yes, no % get the optional input arguments feedback = ft_getopt(varargin, 'feedback', 'no'); dtype = ft_getopt(varargin, 'datatype'); % should not conflict with the ft_datatype function dimord = ft_getopt(varargin, 'dimord'); stype = ft_getopt(varargin, 'senstype'); % senstype is a function name which should not be masked ismeg = ft_getopt(varargin, 'ismeg'); isnirs = ft_getopt(varargin, 'isnirs'); inside = ft_getopt(varargin, 'inside'); % can be 'logical' or 'index' hastrials = ft_getopt(varargin, 'hastrials'); hasunit = ft_getopt(varargin, 'hasunit', 'no'); hascoordsys = ft_getopt(varargin, 'hascoordsys', 'no'); hassampleinfo = ft_getopt(varargin, 'hassampleinfo', 'ifmakessense'); hasdim = ft_getopt(varargin, 'hasdim'); hascumtapcnt = ft_getopt(varargin, 'hascumtapcnt'); hasdof = ft_getopt(varargin, 'hasdof'); cmbrepresentation = ft_getopt(varargin, 'cmbrepresentation'); channelcmb = ft_getopt(varargin, 'channelcmb'); fsample = ft_getopt(varargin, 'fsample'); segmentationstyle = ft_getopt(varargin, 'segmentationstyle'); % this will be passed on to the corresponding ft_datatype_xxx function parcellationstyle = ft_getopt(varargin, 'parcellationstyle'); % this will be passed on to the corresponding ft_datatype_xxx function hasbrain = ft_getopt(varargin, 'hasbrain'); % check whether people are using deprecated stuff depHastrialdef = ft_getopt(varargin, 'hastrialdef'); if (~isempty(depHastrialdef)) ft_warning('ft_checkdata option ''hastrialdef'' is deprecated; use ''hassampleinfo'' instead'); hassampleinfo = depHastrialdef; end % determine the type of input data % this can be raw, freq, timelock, comp, spike, source, volume, dip israw = ft_datatype(data, 'raw'); isfreq = ft_datatype(data, 'freq'); istimelock = ft_datatype(data, 'timelock'); iscomp = ft_datatype(data, 'comp'); isspike = ft_datatype(data, 'spike'); isvolume = ft_datatype(data, 'volume'); issegmentation = ft_datatype(data, 'segmentation'); isparcellation = ft_datatype(data, 'parcellation'); issource = ft_datatype(data, 'source'); isdip = ft_datatype(data, 'dip'); ismvar = ft_datatype(data, 'mvar'); isfreqmvar = ft_datatype(data, 'freqmvar'); ischan = ft_datatype(data, 'chan'); ismesh = ft_datatype(data, 'mesh'); % FIXME use the istrue function on ismeg and hasxxx options if ~isequal(feedback, 'no') if iscomp % it can be comp and raw/timelock/freq at the same time, therefore this has to go first nchan = size(data.topo,1); ncomp = size(data.topo,2); fprintf('the input is component data with %d components and %d original channels\n', ncomp, nchan); end if israw nchan = length(data.label); ntrial = length(data.trial); fprintf('the input is raw data with %d channels and %d trials\n', nchan, ntrial); elseif istimelock nchan = length(data.label); ntime = length(data.time); fprintf('the input is timelock data with %d channels and %d timebins\n', nchan, ntime); elseif isfreq if isfield(data, 'label') nchan = length(data.label); nfreq = length(data.freq); if isfield(data, 'time'), ntime = num2str(length(data.time)); else ntime = 'no'; end fprintf('the input is freq data with %d channels, %d frequencybins and %s timebins\n', nchan, nfreq, ntime); elseif isfield(data, 'labelcmb') nchan = length(data.labelcmb); nfreq = length(data.freq); if isfield(data, 'time'), ntime = num2str(length(data.time)); else ntime = 'no'; end fprintf('the input is freq data with %d channel combinations, %d frequencybins and %s timebins\n', nchan, nfreq, ntime); else error('cannot infer freq dimensions'); end elseif isspike nchan = length(data.label); fprintf('the input is spike data with %d channels\n', nchan); elseif isvolume if issegmentation subtype = 'segmented volume'; else subtype = 'volume'; end fprintf('the input is %s data with dimensions [%d %d %d]\n', subtype, data.dim(1), data.dim(2), data.dim(3)); clear subtype elseif issource data = fixpos(data); % ensure that positions are in pos, not in pnt nsource = size(data.pos, 1); if isparcellation subtype = 'parcellated source'; else subtype = 'source'; end if isfield(data, 'dim') fprintf('the input is %s data with %d brainordinates on a [%d %d %d] grid\n', subtype, nsource, data.dim(1), data.dim(2), data.dim(3)); elseif isfield(data, 'tri') fprintf('the input is %s data with %d vertex positions and %d triangles\n', subtype, nsource, size(data.tri, 1)); else fprintf('the input is %s data with %d brainordinates\n', subtype, nsource); end clear subtype elseif isdip fprintf('the input is dipole data\n'); elseif ismvar fprintf('the input is mvar data\n'); elseif isfreqmvar fprintf('the input is freqmvar data\n'); elseif ischan nchan = length(data.label); if isfield(data, 'brainordinate') fprintf('the input is parcellated data with %d parcels\n', nchan); else fprintf('the input is chan data with %d channels\n', nchan); end end elseif ismesh data = fixpos(data); if numel(data)==1 if isfield(data,'tri') fprintf('the input is mesh data with %d vertices and %d triangles\n', size(data.pos,1), size(data.tri,1)); elseif isfield(data,'hex') fprintf('the input is mesh data with %d vertices and %d hexahedrons\n', size(data.pos,1), size(data.hex,1)); elseif isfield(data,'tet') fprintf('the input is mesh data with %d vertices and %d tetrahedrons\n', size(data.pos,1), size(data.tet,1)); else fprintf('the input is mesh data with %d vertices', size(data.pos,1)); end else fprintf('the input is mesh data multiple surfaces\n'); end end % give feedback if issource && isvolume % it should be either one or the other: the choice here is to represent it as volume description since that is simpler to handle % the conversion is done by removing the grid positions data = rmfield(data, 'pos'); issource = false; end % the ft_datatype_XXX functions ensures the consistency of the XXX datatype % and provides a detailed description of the dataformat and its history if iscomp % this should go before israw/istimelock/isfreq data = ft_datatype_comp(data, 'hassampleinfo', hassampleinfo); elseif israw data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); elseif istimelock data = ft_datatype_timelock(data); elseif isfreq data = ft_datatype_freq(data); elseif isspike data = ft_datatype_spike(data); elseif issegmentation % this should go before isvolume data = ft_datatype_segmentation(data, 'segmentationstyle', segmentationstyle, 'hasbrain', hasbrain); elseif isvolume data = ft_datatype_volume(data); elseif isparcellation % this should go before issource data = ft_datatype_parcellation(data, 'parcellationstyle', parcellationstyle); elseif issource data = ft_datatype_source(data); elseif isdip data = ft_datatype_dip(data); elseif ismvar || isfreqmvar data = ft_datatype_mvar(data); end if ~isempty(dtype) if ~isa(dtype, 'cell') dtype = {dtype}; end okflag = 0; for i=1:length(dtype) % check that the data matches with one or more of the required ft_datatypes switch dtype{i} case 'raw+comp' okflag = okflag + (israw & iscomp); case 'freq+comp' okflag = okflag + (isfreq & iscomp); case 'timelock+comp' okflag = okflag + (istimelock & iscomp); case 'raw' okflag = okflag + (israw & ~iscomp); case 'freq' okflag = okflag + (isfreq & ~iscomp); case 'timelock' okflag = okflag + (istimelock & ~iscomp); case 'comp' okflag = okflag + (iscomp & ~(israw | istimelock | isfreq)); case 'spike' okflag = okflag + isspike; case 'volume' okflag = okflag + isvolume; case 'source' okflag = okflag + issource; case 'dip' okflag = okflag + isdip; case 'mvar' okflag = okflag + ismvar; case 'freqmvar' okflag = okflag + isfreqmvar; case 'chan' okflag = okflag + ischan; case 'segmentation' okflag = okflag + issegmentation; case 'parcellation' okflag = okflag + isparcellation; case 'mesh' okflag = okflag + ismesh; end % switch dtype end % for dtype % try to convert the data if needed for iCell = 1:length(dtype) if okflag % the requested datatype is specified in descending order of % preference (if there is a preference at all), so don't bother % checking the rest of the requested data types if we already % succeeded in converting break; end if isequal(dtype(iCell), {'parcellation'}) && issegmentation data = volume2source(data); % segmentation=volume, parcellation=source data = ft_datatype_parcellation(data); issegmentation = 0; isvolume = 0; isparcellation = 1; issource = 1; okflag = 1; elseif isequal(dtype(iCell), {'segmentation'}) && isparcellation data = source2volume(data); % segmentation=volume, parcellation=source data = ft_datatype_segmentation(data); isparcellation = 0; issource = 0; issegmentation = 1; isvolume = 1; okflag = 1; elseif isequal(dtype(iCell), {'source'}) && isvolume data = volume2source(data); data = ft_datatype_source(data); isvolume = 0; issource = 1; okflag = 1; elseif isequal(dtype(iCell), {'volume'}) && (ischan || istimelock || isfreq) data = parcellated2source(data); data = ft_datatype_volume(data); ischan = 0; isvolume = 1; okflag = 1; elseif isequal(dtype(iCell), {'source'}) && (ischan || istimelock || isfreq) data = parcellated2source(data); data = ft_datatype_source(data); ischan = 0; issource = 1; okflag = 1; elseif isequal(dtype(iCell), {'volume'}) && issource data = source2volume(data); data = ft_datatype_volume(data); isvolume = 1; issource = 0; okflag = 1; elseif isequal(dtype(iCell), {'raw+comp'}) && istimelock && iscomp data = timelock2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); istimelock = 0; iscomp = 1; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && issource data = source2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); issource = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && istimelock if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = timelock2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); istimelock = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'comp'}) && israw data = keepfields(data, {'label', 'topo', 'topolabel', 'unmixing', 'elec', 'grad', 'cfg'}); % these are the only relevant fields data = ft_datatype_comp(data); israw = 0; iscomp = 1; okflag = 1; elseif isequal(dtype(iCell), {'comp'}) && istimelock data = keepfields(data, {'label', 'topo', 'topolabel', 'unmixing', 'elec', 'grad', 'cfg'}); % these are the only relevant fields data = ft_datatype_comp(data); istimelock = 0; iscomp = 1; okflag = 1; elseif isequal(dtype(iCell), {'comp'}) && isfreq data = keepfields(data, {'label', 'topo', 'topolabel', 'unmixing', 'elec', 'grad', 'cfg'}); % these are the only relevant fields data = ft_datatype_comp(data); isfreq = 0; iscomp = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && israw if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = ft_datatype_raw(data); okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && istimelock if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = ft_datatype_timelock(data); okflag = 1; elseif isequal(dtype(iCell), {'freq'}) && isfreq if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = ft_datatype_freq(data); okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && israw if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = raw2timelock(data); data = ft_datatype_timelock(data); israw = 0; istimelock = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && isfreq if iscomp data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired iscomp = 0; end data = freq2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); isfreq = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && ischan data = chan2timelock(data); data = timelock2raw(data); data = ft_datatype_raw(data); ischan = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && ischan data = chan2timelock(data); data = ft_datatype_timelock(data); ischan = 0; istimelock = 1; okflag = 1; elseif isequal(dtype(iCell), {'freq'}) && ischan data = chan2freq(data); data = ft_datatype_freq(data); ischan = 0; isfreq = 1; okflag = 1; elseif isequal(dtype(iCell), {'spike'}) && israw data = raw2spike(data); data = ft_datatype_spike(data); israw = 0; isspike = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && isspike data = spike2raw(data,fsample); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); isspike = 0; israw = 1; okflag = 1; end end % for iCell if ~okflag % construct an error message if length(dtype)>1 str = sprintf('%s, ', dtype{1:(end-2)}); str = sprintf('%s%s or %s', str, dtype{end-1}, dtype{end}); else str = dtype{1}; end error('This function requires %s data as input.', str); end % if okflag end if ~isempty(dimord) if ~isa(dimord, 'cell') dimord = {dimord}; end if isfield(data, 'dimord') okflag = any(strcmp(data.dimord, dimord)); else okflag = 0; end if ~okflag % construct an error message if length(dimord)>1 str = sprintf('%s, ', dimord{1:(end-2)}); str = sprintf('%s%s or %s', str, dimord{end-1}, dimord{end}); else str = dimord{1}; end error('This function requires data with a dimord of %s.', str); end % if okflag end if ~isempty(stype) if ~isa(stype, 'cell') stype = {stype}; end if isfield(data, 'grad') || isfield(data, 'elec') || isfield(data, 'opto') if any(strcmp(ft_senstype(data), stype)) okflag = 1; elseif any(cellfun(@ft_senstype, repmat({data}, size(stype)), stype)) % this is required to detect more general types, such as "meg" or "ctf" rather than "ctf275" okflag = 1; else okflag = 0; end end if ~okflag % construct an error message if length(stype)>1 str = sprintf('%s, ', stype{1:(end-2)}); str = sprintf('%s%s or %s', str, stype{end-1}, stype{end}); else str = stype{1}; end error('This function requires %s data as input, but you are giving %s data.', str, ft_senstype(data)); end % if okflag end if ~isempty(ismeg) if isequal(ismeg, 'yes') okflag = isfield(data, 'grad'); elseif isequal(ismeg, 'no') okflag = ~isfield(data, 'grad'); end if ~okflag && isequal(ismeg, 'yes') error('This function requires MEG data with a ''grad'' field'); elseif ~okflag && isequal(ismeg, 'no') error('This function should not be given MEG data with a ''grad'' field'); end % if okflag end if ~isempty(isnirs) if isequal(isnirs, 'yes') okflag = isfield(data, 'opto'); elseif isequal(isnirs, 'no') okflag = ~isfield(data, 'opto'); end if ~okflag && isequal(isnirs, 'yes') error('This function requires NIRS data with an ''opto'' field'); elseif ~okflag && isequal(isnirs, 'no') error('This function should not be given NIRS data with an ''opto'' field'); end % if okflag end if ~isempty(inside) if strcmp(inside, 'index') warning('the indexed representation of inside/outside source locations is deprecated'); end % TODO absorb the fixinside function into this code data = fixinside(data, inside); okflag = isfield(data, 'inside'); if ~okflag % construct an error message error('This function requires data with an ''inside'' field.'); end % if okflag end if istrue(hasunit) && ~isfield(data, 'unit') % calling convert_units with only the input data adds the units without converting data = ft_convert_units(data); end % if hasunit if istrue(hascoordsys) && ~isfield(data, 'coordsys') data = ft_determine_coordsys(data); end % if hascoordsys if isequal(hastrials, 'yes') okflag = isfield(data, 'trial'); if ~okflag && isfield(data, 'dimord') % instead look in the dimord for rpt or subj okflag = ~isempty(strfind(data.dimord, 'rpt')) || ... ~isempty(strfind(data.dimord, 'rpttap')) || ... ~isempty(strfind(data.dimord, 'subj')); end if ~okflag error('This function requires data with a ''trial'' field'); end % if okflag end if strcmp(hasdim, 'yes') && ~isfield(data, 'dim') data.dim = pos2dim(data.pos); elseif strcmp(hasdim, 'no') && isfield(data, 'dim') data = rmfield(data, 'dim'); end % if hasdim if strcmp(hascumtapcnt, 'yes') && ~isfield(data, 'cumtapcnt') error('This function requires data with a ''cumtapcnt'' field'); elseif strcmp(hascumtapcnt, 'no') && isfield(data, 'cumtapcnt') data = rmfield(data, 'cumtapcnt'); end % if hascumtapcnt if strcmp(hasdof, 'yes') && ~isfield(data, 'dof') error('This function requires data with a ''dof'' field'); elseif strcmp(hasdof, 'no') && isfield(data, 'dof') data = rmfield(data, 'dof'); end % if hasdof if ~isempty(cmbrepresentation) if istimelock data = fixcov(data, cmbrepresentation); elseif isfreq data = fixcsd(data, cmbrepresentation, channelcmb); elseif isfreqmvar data = fixcsd(data, cmbrepresentation, channelcmb); else error('This function requires data with a covariance, coherence or cross-spectrum'); end end % cmbrepresentation if isfield(data, 'grad') % ensure that the gradiometer structure is up to date data.grad = ft_datatype_sens(data.grad); end if isfield(data, 'elec') % ensure that the electrode structure is up to date data.elec = ft_datatype_sens(data.elec); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % represent the covariance matrix in a particular manner %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = fixcov(data, desired) if any(isfield(data, {'cov', 'corr'})) if ~isfield(data, 'labelcmb') current = 'full'; else current = 'sparse'; end else error('Could not determine the current representation of the covariance matrix'); end if isequal(current, desired) % nothing to do elseif strcmp(current, 'full') && strcmp(desired, 'sparse') % FIXME should be implemented error('not yet implemented'); elseif strcmp(current, 'sparse') && strcmp(desired, 'full') % FIXME should be implemented error('not yet implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % represent the cross-spectral density matrix in a particular manner %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = fixcsd(data, desired, channelcmb) % FIXCSD converts univariate frequency domain data (fourierspctrm) into a bivariate % representation (crsspctrm), or changes the representation of bivariate frequency % domain data (sparse/full/sparsewithpow, sparsewithpow only works for crsspctrm or % fourierspctrm) % Copyright (C) 2010, Jan-Mathijs Schoffelen, Robert Oostenveld if isfield(data, 'crsspctrm') && isfield(data, 'powspctrm') current = 'sparsewithpow'; elseif isfield(data, 'powspctrm') current = 'sparsewithpow'; elseif isfield(data, 'fourierspctrm') && ~isfield(data, 'labelcmb') current = 'fourier'; elseif ~isfield(data, 'labelcmb') current = 'full'; elseif isfield(data, 'labelcmb') current = 'sparse'; else error('Could not determine the current representation of the %s matrix', param); end % first go from univariate fourier to the required bivariate representation if isequal(current, desired) % nothing to do elseif strcmp(current, 'fourier') && strcmp(desired, 'sparsewithpow') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt,1); flag = 0; else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1)); flag = nrpt==1; % needed to truncate the singleton dimension upfront %create auto-spectra nchan = length(data.label); if fastflag % all trials have the same amount of tapers powspctrm = zeros(nrpt,nchan,nfrq,ntim); ntap = data.cumtapcnt(1); for p = 1:ntap powspctrm = powspctrm + abs(data.fourierspctrm(p:ntap:end,:,:,:,:)).^2; end powspctrm = powspctrm./ntap; else % different amount of tapers powspctrm = zeros(nrpt,nchan,nfrq,ntim)+i.*zeros(nrpt,nchan,nfrq,ntim); sumtapcnt = [0;cumsum(data.cumtapcnt(:))]; for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat = data.fourierspctrm(indx,:,:,:); powspctrm(p,:,:,:) = (sum(tmpdat.*conj(tmpdat),1))./data.cumtapcnt(p); end end %create cross-spectra if ~isempty(channelcmb), ncmb = size(channelcmb,1); cmbindx = zeros(ncmb,2); labelcmb = cell(ncmb,2); for k = 1:ncmb ch1 = find(strcmp(data.label, channelcmb(k,1))); ch2 = find(strcmp(data.label, channelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(k,:) = [ch1 ch2]; labelcmb(k,:) = data.label([ch1 ch2])'; end end crsspctrm = zeros(nrpt,ncmb,nfrq,ntim)+i.*zeros(nrpt,ncmb,nfrq,ntim); if fastflag for p = 1:ntap tmpdat1 = data.fourierspctrm(p:ntap:end,cmbindx(:,1),:,:,:); tmpdat2 = data.fourierspctrm(p:ntap:end,cmbindx(:,2),:,:,:); crsspctrm = crsspctrm + tmpdat1.*conj(tmpdat2); end crsspctrm = crsspctrm./ntap; else for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:); tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:); crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p); end end data.crsspctrm = crsspctrm; data.labelcmb = labelcmb; end data.powspctrm = powspctrm; data = rmfield(data, 'fourierspctrm'); if ntim>1, data.dimord = 'chan_freq_time'; else data.dimord = 'chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end if flag, siz = size(data.powspctrm); data.powspctrm = reshape(data.powspctrm, [siz(2:end) 1]); if isfield(data, 'crsspctrm') siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, [siz(2:end) 1]); end end elseif strcmp(current, 'fourier') && strcmp(desired, 'sparse') if isempty(channelcmb), error('no channel combinations are specified'); end dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt,1); flag = 0; else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end flag = nrpt==1; % flag needed to squeeze first dimension if singleton ncmb = size(channelcmb,1); cmbindx = zeros(ncmb,2); labelcmb = cell(ncmb,2); for k = 1:ncmb ch1 = find(strcmp(data.label, channelcmb(k,1))); ch2 = find(strcmp(data.label, channelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(k,:) = [ch1 ch2]; labelcmb(k,:) = data.label([ch1 ch2])'; end end sumtapcnt = [0;cumsum(data.cumtapcnt(:))]; fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1)); if fastflag && nrpt>1 ntap = data.cumtapcnt(1); % compute running sum across tapers siz = [size(data.fourierspctrm) 1]; for p = 1:ntap indx = p:ntap:nrpt*ntap; if p==1. tmpc = zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)) + ... 1i.*zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)); end for k = 1:size(cmbindx,1) tmpc(:,k,:,:) = data.fourierspctrm(indx,cmbindx(k,1),:,:).* ... conj(data.fourierspctrm(indx,cmbindx(k,2),:,:)); end if p==1 crsspctrm = tmpc; else crsspctrm = tmpc + crsspctrm; end end crsspctrm = crsspctrm./ntap; else crsspctrm = zeros(nrpt, ncmb, nfrq, ntim); for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:); tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:); crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p); end end data.crsspctrm = crsspctrm; data.labelcmb = labelcmb; data = rmfield(data, 'fourierspctrm'); data = rmfield(data, 'label'); if ntim>1, data.dimord = 'chancmb_freq_time'; else data.dimord = 'chancmb_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end if flag, % deal with the singleton 'rpt', i.e. remove it siz = size(data.powspctrm); data.powspctrm = reshape(data.powspctrm, [siz(2:end) 1]); if isfield(data,'crsspctrm') % this conditional statement is needed in case there's a single channel siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, [siz(2:end) 1]); end end elseif strcmp(current, 'fourier') && strcmp(desired, 'full') % this is how it is currently and the desired functionality of prepare_freq_matrices dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt, 1); flag = 0; else nrpt = 1; flag = 1; end if ~isempty(strmatch('rpttap',dimtok)), nrpt=size(data.cumtapcnt, 1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end if any(data.cumtapcnt(1,:) ~= data.cumtapcnt(1,1)), error('this only works when all frequencies have the same number of tapers'); end nchan = length(data.label); crsspctrm = zeros(nrpt,nchan,nchan,nfrq,ntim); sumtapcnt = [0;cumsum(data.cumtapcnt(:,1))]; for k = 1:ntim for m = 1:nfrq for p = 1:nrpt %FIXME speed this up in the case that all trials have equal number of tapers indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat = transpose(data.fourierspctrm(indx,:,m,k)); crsspctrm(p,:,:,m,k) = (tmpdat*tmpdat')./data.cumtapcnt(p); clear tmpdat; end end end data.crsspctrm = crsspctrm; data = rmfield(data, 'fourierspctrm'); if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end % remove first singleton dimension if flag || nrpt==1, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end elseif strcmp(current, 'fourier') && strcmp(desired, 'fullfast'), dimtok = tokenize(data.dimord, '_'); nrpt = size(data.fourierspctrm, 1); nchn = numel(data.label); nfrq = numel(data.freq); if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end data.fourierspctrm = reshape(data.fourierspctrm, [nrpt nchn nfrq*ntim]); data.fourierspctrm(~isfinite(data.fourierspctrm)) = 0; crsspctrm = complex(zeros(nchn,nchn,nfrq*ntim)); for k = 1:nfrq*ntim tmp = transpose(data.fourierspctrm(:,:,k)); n = sum(tmp~=0,2); crsspctrm(:,:,k) = tmp*tmp'./n(1); end data = rmfield(data, 'fourierspctrm'); data.crsspctrm = reshape(crsspctrm, [nchn nchn nfrq ntim]); if isfield(data, 'time'), data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if isfield(data, 'trialinfo'), data = rmfield(data, 'trialinfo'); end; if isfield(data, 'sampleinfo'), data = rmfield(data, 'sampleinfo'); end; if isfield(data, 'cumsumcnt'), data = rmfield(data, 'cumsumcnt'); end; if isfield(data, 'cumtapcnt'), data = rmfield(data, 'cumtapcnt'); end; end % convert to the requested bivariate representation % from one bivariate representation to another if isequal(current, desired) % nothing to do elseif (strcmp(current, 'full') && strcmp(desired, 'fourier')) || ... (strcmp(current, 'sparse') && strcmp(desired, 'fourier')) || ... (strcmp(current, 'sparsewithpow') && strcmp(desired, 'fourier')) % this is not possible error('converting the cross-spectrum into a Fourier representation is not possible'); elseif strcmp(current, 'full') && strcmp(desired, 'sparsewithpow') error('not yet implemented'); elseif strcmp(current, 'sparse') && strcmp(desired, 'sparsewithpow') % convert back to crsspctrm/powspctrm representation: useful for plotting functions etc indx = labelcmb2indx(data.labelcmb); autoindx = indx(indx(:,1)==indx(:,2), 1); cmbindx = setdiff([1:size(indx,1)]', autoindx); if strcmp(data.dimord(1:3), 'rpt') data.powspctrm = data.crsspctrm(:, autoindx, :, :); data.crsspctrm = data.crsspctrm(:, cmbindx, :, :); else data.powspctrm = data.crsspctrm(autoindx, :, :); data.crsspctrm = data.crsspctrm(cmbindx, :, :); end data.label = data.labelcmb(autoindx,1); data.labelcmb = data.labelcmb(cmbindx, :); if isempty(cmbindx) data = rmfield(data, 'crsspctrm'); data = rmfield(data, 'labelcmb'); end elseif strcmp(current, 'full') && strcmp(desired, 'sparse') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end nchan = length(data.label); ncmb = nchan*nchan; labelcmb = cell(ncmb, 2); cmbindx = zeros(nchan, nchan); k = 1; for j=1:nchan for m=1:nchan labelcmb{k, 1} = data.label{m}; labelcmb{k, 2} = data.label{j}; cmbindx(m,j) = k; k = k+1; end end % reshape all possible fields fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt>1, data.(fn{ii}) = reshape(data.(fn{ii}), nrpt, ncmb, nfrq, ntim); else data.(fn{ii}) = reshape(data.(fn{ii}), ncmb, nfrq, ntim); end end end % remove obsolete fields data = rmfield(data, 'label'); try data = rmfield(data, 'dof'); end % replace updated fields data.labelcmb = labelcmb; if ntim>1, data.dimord = 'chancmb_freq_time'; else data.dimord = 'chancmb_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'sparse') % this representation for sparse data contains autospectra as e.g. {'A' 'A'} in labelcmb if isfield(data, 'crsspctrm'), dimtok = tokenize(data.dimord, '_'); catdim = match_str(dimtok, {'chan' 'chancmb'}); data.crsspctrm = cat(catdim, data.powspctrm, data.crsspctrm); data.labelcmb = [data.label(:) data.label(:); data.labelcmb]; data = rmfield(data, 'powspctrm'); data.dimord = strrep(data.dimord, 'chan_', 'chancmb_'); else data.crsspctrm = data.powspctrm; data.labelcmb = [data.label(:) data.label(:)]; data = rmfield(data, 'powspctrm'); data.dimord = strrep(data.dimord, 'chan_', 'chancmb_'); end data = rmfield(data, 'label'); elseif strcmp(current, 'sparse') && strcmp(desired, 'full') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end if ~isfield(data, 'label') % ensure that the bivariate spectral factorization results can be % processed. FIXME this is experimental and will not work if the user % did something weird before for k = 1:numel(data.labelcmb) tmp = tokenize(data.labelcmb{k}, '['); data.labelcmb{k} = tmp{1}; end data.label = unique(data.labelcmb(:)); end nchan = length(data.label); ncmb = size(data.labelcmb,1); cmbindx = zeros(nchan,nchan); for k = 1:size(data.labelcmb,1) ch1 = find(strcmp(data.label, data.labelcmb(k,1))); ch2 = find(strcmp(data.label, data.labelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(ch1,ch2) = k; end end complete = all(cmbindx(:)~=0); % remove obsolete fields try data = rmfield(data, 'powspctrm'); end try data = rmfield(data, 'labelcmb'); end try data = rmfield(data, 'dof'); end fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt==1, data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]); end tmpall = nan(nrpt,nchan,nchan,nfrq,ntim); for j = 1:nrpt for k = 1:ntim for m = 1:nfrq tmpdat = nan(nchan,nchan); indx = find(cmbindx); if ~complete % this realizes the missing combinations to be represented as the % conjugate of the corresponding combination across the diagonal tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]); tmpdat = ctranspose(tmpdat); end tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]); tmpall(j,:,:,m,k) = tmpdat; end % for m end % for k end % for j % replace the data in the old representation with the new representation if nrpt>1, data.(fn{ii}) = tmpall; else data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]); end end % if numel end % for ii if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end elseif strcmp(current, 'sparse') && strcmp(desired, 'fullfast') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end if ~isfield(data, 'label') data.label = unique(data.labelcmb(:)); end nchan = length(data.label); ncmb = size(data.labelcmb,1); cmbindx = zeros(nchan,nchan); for k = 1:size(data.labelcmb,1) ch1 = find(strcmp(data.label, data.labelcmb(k,1))); ch2 = find(strcmp(data.label, data.labelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(ch1,ch2) = k; end end complete = all(cmbindx(:)~=0); fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt==1, data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]); end tmpall = nan(nchan,nchan,nfrq,ntim); for k = 1:ntim for m = 1:nfrq tmpdat = nan(nchan,nchan); indx = find(cmbindx); if ~complete % this realizes the missing combinations to be represented as the % conjugate of the corresponding combination across the diagonal tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]); tmpdat = ctranspose(tmpdat); end tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]); tmpall(:,:,m,k) = tmpdat; end % for m end % for k % replace the data in the old representation with the new representation if nrpt>1, data.(fn{ii}) = tmpall; else data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]); end end % if numel end % for ii % remove obsolete fields try data = rmfield(data, 'powspctrm'); end try data = rmfield(data, 'labelcmb'); end try data = rmfield(data, 'dof'); end if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end elseif strcmp(current, 'sparsewithpow') && any(strcmp(desired, {'full', 'fullfast'})) % recursively call ft_checkdata, but ensure channel order to be the same % as the original input. origlabelorder = data.label; % keep track of the original order of the channels data = ft_checkdata(data, 'cmbrepresentation', 'sparse'); data.label = origlabelorder; % this avoids the labels to be alphabetized in the next call data = ft_checkdata(data, 'cmbrepresentation', 'full'); end % convert from one to another bivariate representation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [source] = parcellated2source(data) if ~isfield(data, 'brainordinate') error('projecting parcellated data onto the full brain model geometry requires the specification of brainordinates'); end % the main structure contains the functional data on the parcels % the brainordinate sub-structure contains the original geometrical model source = data.brainordinate; data = rmfield(data, 'brainordinate'); if isfield(data, 'cfg') source.cfg = data.cfg; end fn = fieldnames(data); fn = setdiff(fn, {'label', 'time', 'freq', 'hdr', 'cfg', 'grad', 'elec', 'dimord', 'unit'}); % remove irrelevant fields fn(~cellfun(@isempty, regexp(fn, 'dimord$'))) = []; % remove irrelevant (dimord) fields sel = false(size(fn)); for i=1:numel(fn) try sel(i) = ismember(getdimord(data, fn{i}), {'chan', 'chan_time', 'chan_freq', 'chan_freq_time', 'chan_chan'}); end end parameter = fn(sel); fn = fieldnames(source); sel = false(size(fn)); for i=1:numel(fn) tmp = source.(fn{i}); sel(i) = iscell(tmp) && isequal(tmp(:), data.label(:)); end parcelparam = fn(sel); if numel(parcelparam)~=1 error('cannot determine which parcellation to use'); else parcelparam = parcelparam{1}(1:(end-5)); % minus the 'label' end for i=1:numel(parameter) source.(parameter{i}) = unparcellate(data, source, parameter{i}, parcelparam); end % copy over fields (these are necessary for visualising the data in ft_sourceplot) source = copyfields(data, source, {'time', 'freq'}); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = volume2source(data) if isfield(data, 'dimord') % it is a modern source description else % it is an old-fashioned source description xgrid = 1:data.dim(1); ygrid = 1:data.dim(2); zgrid = 1:data.dim(3); [x y z] = ndgrid(xgrid, ygrid, zgrid); data.pos = ft_warp_apply(data.transform, [x(:) y(:) z(:)]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = source2volume(data) if isfield(data, 'dimord') % it is a modern source description %this part depends on the assumption that the list of positions is describing a full 3D volume in %an ordered way which allows for the extraction of a transformation matrix %i.e. slice by slice try if isfield(data, 'dim'), data.dim = pos2dim(data.pos, data.dim); else data.dim = pos2dim(data); end catch end end if isfield(data, 'dim') && length(data.dim)>=3, data.transform = pos2transform(data.pos, data.dim); end % remove the unwanted fields data = removefields(data, {'pos', 'xgrid', 'ygrid', 'zgrid', 'tri', 'tet', 'hex'}); % make inside a volume data = fixinside(data, 'logical'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = freq2raw(freq) if isfield(freq, 'powspctrm') param = 'powspctrm'; elseif isfield(freq, 'fourierspctrm') param = 'fourierspctrm'; else error('not supported for this data representation'); end if strcmp(freq.dimord, 'rpt_chan_freq_time') || strcmp(freq.dimord, 'rpttap_chan_freq_time') dat = freq.(param); elseif strcmp(freq.dimord, 'chan_freq_time') dat = freq.(param); dat = reshape(dat, [1 size(dat)]); % add a singleton dimension else error('not supported for dimord %s', freq.dimord); end nrpt = size(dat,1); nchan = size(dat,2); nfreq = size(dat,3); ntime = size(dat,4); data = []; % create the channel labels like "MLP11@12Hz"" k = 0; for i=1:nfreq for j=1:nchan k = k+1; data.label{k} = sprintf('%s@%dHz', freq.label{j}, freq.freq(i)); end end % reshape and copy the data as if it were timecourses only for i=1:nrpt data.time{i} = freq.time; data.trial{i} = reshape(dat(i,:,:,:), nchan*nfreq, ntime); if any(isnan(data.trial{i}(1,:))), tmp = data.trial{i}(1,:); begsmp = find(isfinite(tmp),1, 'first'); endsmp = find(isfinite(tmp),1, 'last' ); data.trial{i} = data.trial{i}(:, begsmp:endsmp); data.time{i} = data.time{i}(begsmp:endsmp); end end if isfield(freq, 'trialinfo'), data.trialinfo = freq.trialinfo; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = raw2timelock(data) nsmp = cellfun('size',data.time,2); data = ft_checkdata(data, 'hassampleinfo', 'yes'); ntrial = numel(data.trial); nchan = numel(data.label); if ntrial==1 data.time = data.time{1}; data.avg = data.trial{1}; data = rmfield(data, 'trial'); data.dimord = 'chan_time'; else % code below tries to construct a general time-axis where samples of all trials can fall on % find earliest beginning and latest ending begtime = min(cellfun(@min,data.time)); endtime = max(cellfun(@max,data.time)); % find 'common' sampling rate fsample = 1./mean(cellfun(@mean,cellfun(@diff,data.time,'uniformoutput',false))); % estimate number of samples nsmp = round((endtime-begtime)*fsample) + 1; % numerical round-off issues should be dealt with by this round, as they will/should never cause an extra sample to appear % construct general time-axis time = linspace(begtime,endtime,nsmp); % concatenate all trials tmptrial = nan(ntrial, nchan, length(time)); begsmp = nan(ntrial, 1); endsmp = nan(ntrial, 1); for i=1:ntrial begsmp(i) = nearest(time, data.time{i}(1)); endsmp(i) = nearest(time, data.time{i}(end)); tmptrial(i,:,begsmp(i):endsmp(i)) = data.trial{i}; end % update the sampleinfo begpad = begsmp - min(begsmp); endpad = max(endsmp) - endsmp; if isfield(data, 'sampleinfo') data.sampleinfo = data.sampleinfo + [-begpad(:) endpad(:)]; end % construct the output timelocked data % data.avg = reshape(nanmean(tmptrial, 1), nchan, length(tmptime)); % data.var = reshape(nanvar (tmptrial, [], 1), nchan, length(tmptime)) % data.dof = reshape(sum(~isnan(tmptrial), 1), nchan, length(tmptime)); data.trial = tmptrial; data.time = time; data.dimord = 'rpt_chan_time'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = timelock2raw(data) switch data.dimord case 'chan_time' data.trial{1} = data.avg; data.time = {data.time}; data = rmfield(data, 'avg'); case 'rpt_chan_time' tmptrial = {}; tmptime = {}; ntrial = size(data.trial,1); nchan = size(data.trial,2); ntime = size(data.trial,3); for i=1:ntrial tmptrial{i} = reshape(data.trial(i,:,:), [nchan, ntime]); tmptime{i} = data.time; end data = rmfield(data, 'trial'); data.trial = tmptrial; data.time = tmptime; case 'subj_chan_time' tmptrial = {}; tmptime = {}; ntrial = size(data.individual,1); nchan = size(data.individual,2); ntime = size(data.individual,3); for i=1:ntrial tmptrial{i} = reshape(data.individual(i,:,:), [nchan, ntime]); tmptime{i} = data.time; end data = rmfield(data, 'individual'); data.trial = tmptrial; data.time = tmptime; otherwise error('unsupported dimord'); end % remove the unwanted fields if isfield(data, 'avg'), data = rmfield(data, 'avg'); end if isfield(data, 'var'), data = rmfield(data, 'var'); end if isfield(data, 'cov'), data = rmfield(data, 'cov'); end if isfield(data, 'dimord'), data = rmfield(data, 'dimord'); end if isfield(data, 'numsamples'), data = rmfield(data, 'numsamples'); end if isfield(data, 'dof'), data = rmfield(data, 'dof'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = chan2freq(data) data.dimord = [data.dimord '_freq']; data.freq = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = chan2timelock(data) data.dimord = [data.dimord '_time']; data.time = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spike] = raw2spike(data) fprintf('converting raw data into spike data\n'); nTrials = length(data.trial); [spikelabel] = detectspikechan(data); spikesel = match_str(data.label, spikelabel); nUnits = length(spikesel); if nUnits==0 error('cannot convert raw data to spike format since the raw data structure does not contain spike channels'); end trialTimes = zeros(nTrials,2); for iUnit = 1:nUnits unitIndx = spikesel(iUnit); spikeTimes = []; % we dont know how large it will be, so use concatenation inside loop trialInds = []; for iTrial = 1:nTrials % read in the spike times [spikeTimesTrial] = getspiketimes(data, iTrial, unitIndx); nSpikes = length(spikeTimesTrial); spikeTimes = [spikeTimes; spikeTimesTrial(:)]; trialInds = [trialInds; ones(nSpikes,1)*iTrial]; % get the begs and ends of trials hasNum = find(~isnan(data.time{iTrial})); if iUnit==1, trialTimes(iTrial,:) = data.time{iTrial}([hasNum(1) hasNum(end)]); end end spike.label{iUnit} = data.label{unitIndx}; spike.waveform{iUnit} = []; spike.time{iUnit} = spikeTimes(:)'; spike.trial{iUnit} = trialInds(:)'; if iUnit==1, spike.trialtime = trialTimes; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = spike2raw(spike, fsample) if nargin<2 || isempty(fsample) timeDiff = abs(diff(sort([spike.time{:}]))); fsample = 1/min(timeDiff(timeDiff>0)); warning('Desired sampling rate for spike data not specified, automatically resampled to %f', fsample); end % get some sizes nUnits = length(spike.label); nTrials = size(spike.trialtime,1); % preallocate data.trial(1:nTrials) = {[]}; data.time(1:nTrials) = {[]}; for iTrial = 1:nTrials % make bins: note that the spike.time is already within spike.trialtime x = [spike.trialtime(iTrial,1):(1/fsample):spike.trialtime(iTrial,2)]; timeBins = [x x(end)+1/fsample] - (0.5/fsample); time = (spike.trialtime(iTrial,1):(1/fsample):spike.trialtime(iTrial,2)); % convert to continuous trialData = zeros(nUnits,length(time)); for iUnit = 1:nUnits % get the timestamps and only select those timestamps that are in the trial ts = spike.time{iUnit}; hasTrial = spike.trial{iUnit}==iTrial; ts = ts(hasTrial); N = histc(ts,timeBins); if isempty(N) N = zeros(1,length(timeBins)-1); else N(end) = []; end % store it in a matrix trialData(iUnit,:) = N; end data.trial{iTrial} = trialData; data.time{iTrial} = time; end % for all trials % create the associated labels and other aspects of data such as the header data.label = spike.label; data.fsample = fsample; if isfield(spike,'hdr'), data.hdr = spike.hdr; end if isfield(spike,'cfg'), data.cfg = spike.cfg; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = source2raw(source) fn = fieldnames(source); fn = setdiff(fn, {'pos', 'dim', 'transform', 'time', 'freq', 'cfg'}); for i=1:length(fn) dimord{i} = getdimord(source, fn{i}); end sel = strcmp(dimord, 'pos_time'); assert(sum(sel)>0, 'the source structure does not contain a suitable field to represent as raw channel-level data'); assert(sum(sel)<2, 'the source structure contains multiple fields that can be represented as raw channel-level data'); fn = fn{sel}; dimord = dimord{sel}; switch dimord case 'pos_time' % add fake raw channel data to the original data structure data.trial{1} = source.(fn); data.time{1} = source.time; % add fake channel labels data.label = {}; for i=1:size(source.pos,1) data.label{i} = sprintf('source%d', i); end data.label = data.label(:); data.cfg = source.cfg; otherwise % FIXME other formats could be implemented as well end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for detection of channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spikelabel, eeglabel] = detectspikechan(data) maxRate = 2000; % default on what we still consider a neuronal signal: this firing rate should never be exceeded % autodetect the spike channels ntrial = length(data.trial); nchans = length(data.label); spikechan = zeros(nchans,1); for i=1:ntrial for j=1:nchans hasAllInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:) == round(data.trial{i}(j,:))); hasAllPosInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:)>=0); T = nansum(diff(data.time{i}),2); % total time fr = nansum(data.trial{i}(j,:),2) ./ T; spikechan(j) = spikechan(j) + double(hasAllInts & hasAllPosInts & fr<=maxRate); end end spikechan = (spikechan==ntrial); spikelabel = data.label(spikechan); eeglabel = data.label(~spikechan); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spikeTimes] = getspiketimes(data, trial, unit) spikeIndx = logical(data.trial{trial}(unit,:)); spikeCount = data.trial{trial}(unit,spikeIndx); spikeTimes = data.time{trial}(spikeIndx); if isempty(spikeTimes), return; end multiSpikes = find(spikeCount>1); % get the additional samples and spike times, we need only loop through the bins [addSamples, addTimes] = deal([]); for iBin = multiSpikes(:)' % looping over row vector addTimes = [addTimes ones(1,spikeCount(iBin))*spikeTimes(iBin)]; addSamples = [addSamples ones(1,spikeCount(iBin))*spikeIndx(iBin)]; end % before adding these times, first remove the old ones spikeTimes(multiSpikes) = []; spikeTimes = sort([spikeTimes(:); addTimes(:)]);
github
lcnbeapp/beapp-master
read_yokogawa_data.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_yokogawa_data.m
10,974
utf_8
493fda2552516eab52e525c3387a7397
function [dat] = read_yokogawa_data(filename, hdr, begsample, endsample, chanindx) % READ_YOKAGAWA_DATA reads continuous, epoched or averaged MEG data % that has been generated by the Yokogawa MEG system and software % and allows that data to be used in combination with FieldTrip. % % Use as % [dat] = read_yokogawa_data(filename, hdr, begsample, endsample, chanindx) % % This is a wrapper function around the functions % GetMeg160ContinuousRawDataM % GetMeg160EvokedAverageDataM % GetMeg160EvokedRawDataM % % See also READ_YOKOGAWA_HEADER, READ_YOKOGAWA_EVENT % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if ~ft_hastoolbox('yokogawa') error('cannot determine whether Yokogawa toolbox is present'); end % hdr = read_yokogawa_header(filename); hdr = hdr.orig; % use the original Yokogawa header, not the FieldTrip header % default is to select all channels if nargin<5 chanindx = 1:hdr.channel_count; end handles = definehandles; fid = fopen(filename, 'rb', 'ieee-le'); switch hdr.acq_type case handles.AcqTypeEvokedAve % Data is returned by double. start_sample = begsample - 1; % samples start at 0 sample_length = endsample - begsample + 1; epoch_count = 1; start_epoch = 0; dat = double(GetMeg160EvokedAverageDataM( fid, start_sample, sample_length )); % the first extra sample is the channel number channum = dat(:,1); dat = dat(:,2:end); case handles.AcqTypeContinuousRaw % Data is returned by int16. start_sample = begsample - 1; % samples start at 0 sample_length = endsample - begsample + 1; epoch_count = 1; start_epoch = 0; dat = double(GetMeg160ContinuousRawDataM( fid, start_sample, sample_length )); % the first extra sample is the channel number channum = dat(:,1); dat = dat(:,2:end); case handles.AcqTypeEvokedRaw % Data is returned by int16. begtrial = ceil(begsample/hdr.sample_count); endtrial = ceil(endsample/hdr.sample_count); if begtrial<1 error('cannot read before the begin of the file'); elseif endtrial>hdr.actual_epoch_count error('cannot read beyond the end of the file'); end epoch_count = endtrial-begtrial+1; start_epoch = begtrial-1; % read all the neccessary trials that contain the desired samples dat = double(GetMeg160EvokedRawDataM( fid, start_epoch, epoch_count )); % the first extra sample is the channel number channum = dat(:,1); dat = dat(:,2:end); if size(dat,2)~=epoch_count*hdr.sample_count error('could not read all epochs'); end rawbegsample = begsample - (begtrial-1)*hdr.sample_count; rawendsample = endsample - (begtrial-1)*hdr.sample_count; sample_length = rawendsample - rawbegsample + 1; % select the desired samples from the complete trials dat = dat(:,rawbegsample:rawendsample); otherwise error('unknown data type'); end fclose(fid); if size(dat,1)~=hdr.channel_count error('could not read all channels'); elseif size(dat,2)~=(endsample-begsample+1) error('could not read all samples'); end % Count of AxialGradioMeter ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.AxialGradioMeter]); axialgradiometer_index_tmp = index; axialgradiometer_ch_count = length(index); % Count of PlannerGradioMeter ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.PlannerGradioMeter]); plannergradiometer_index_tmp = index; plannergradiometer_ch_count = length(index); % Count of EegChannel ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.EegChannel]); eegchannel_index_tmp = index; eegchannel_ch_count = length(index); % Count of NullChannel ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.NullChannel]); nullchannel_index_tmp = index; nullchannel_ch_count = length(index); %%% Pulling out AxialGradioMeter and value conversion to physical units. if ~isempty(axialgradiometer_index_tmp) % Acquisition of channel information axialgradiometer_index = axialgradiometer_index_tmp; ch_info = hdr.channel_info; axialgradiometer_ch_info = ch_info(axialgradiometer_index, :); % Value conversion % B = ( ADValue * VoltRange / ADRange - Offset ) * Sensitivity / FLLGain calib = hdr.calib_info; amp_gain = hdr.amp_gain(1); tmp_ch_no = channum(axialgradiometer_index, 1); tmp_data = dat(axialgradiometer_index, 1:sample_length); tmp_offset = calib(axialgradiometer_index, 3) * ones(1,sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = ( tmp_data * ad_range - tmp_offset ); clear tmp_offset; tmp_gain = calib(axialgradiometer_index, 2) * ones(1,sample_length); tmp_data = tmp_data .* tmp_gain / amp_gain; dat(axialgradiometer_index, 1:sample_length) = tmp_data; clear tmp_gain; % Deletion of Inf row index = find(axialgradiometer_ch_info(1,:) == Inf); axialgradiometer_ch_info(:,index) = []; % Deletion of channel_type row axialgradiometer_ch_info(:,2) = []; % Outputs to the global variable handles.sqd.axialgradiometer_ch_info = axialgradiometer_ch_info; handles.sqd.axialgradiometer_ch_no = tmp_ch_no; handles.sqd.axialgradiometer_data = [ tmp_ch_no tmp_data]; clear tmp_data; end %%% Pulling out PlannerGradioMeter and value conversion to physical units. if ~isempty(plannergradiometer_index_tmp) % Acquisition of channel information plannergradiometer_index = plannergradiometer_index_tmp; ch_info = hdr.channel_info; plannergradiometer_ch_info = ch_info(plannergradiometer_index, :); % Value conversion % B = ( ADValue * VoltRange / ADRange - Offset ) * Sensitivity / FLLGain calib = hdr.calib_info; amp_gain = hdr.amp_gain(1); tmp_ch_no = channum(plannergradiometer_index, 1); tmp_data = dat(plannergradiometer_index, 1:sample_length); tmp_offset = calib(plannergradiometer_index, 3) * ones(1,sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = ( tmp_data * ad_range - tmp_offset ); clear tmp_offset; tmp_gain = calib(plannergradiometer_index, 2) * ones(1,sample_length); tmp_data = tmp_data .* tmp_gain / amp_gain; dat(plannergradiometer_index, 1:sample_length) = tmp_data; clear tmp_gain; % Deletion of Inf row index = find(plannergradiometer_ch_info(1,:) == Inf); plannergradiometer_ch_info(:,index) = []; % Deletion of channel_type row plannergradiometer_ch_info(:,2) = []; % Outputs to the global variable handles.sqd.plannergradiometer_ch_info = plannergradiometer_ch_info; handles.sqd.plannergradiometer_ch_no = tmp_ch_no; handles.sqd.plannergradiometer_data = [ tmp_ch_no tmp_data]; clear tmp_data; end %%% Pulling out EegChannel Channel and value conversion to Volt units. if ~isempty(eegchannel_index_tmp) % Acquisition of channel information eegchannel_index = eegchannel_index_tmp; % Value conversion % B = ADValue * VoltRange / ADRange tmp_ch_no = channum(eegchannel_index, 1); tmp_data = dat(eegchannel_index, 1:sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = tmp_data * ad_range; dat(eegchannel_index, 1:sample_length) = tmp_data; % Outputs to the global variable handles.sqd.eegchannel_ch_no = tmp_ch_no; handles.sqd.eegchannel_data = [ tmp_ch_no tmp_data]; clear tmp_data; end %%% Pulling out Null Channel and value conversion to Volt units. if ~isempty(nullchannel_index_tmp) % Acquisition of channel information nullchannel_index = nullchannel_index_tmp; % Value conversion % B = ADValue * VoltRange / ADRange tmp_ch_no = channum(nullchannel_index, 1); tmp_data = dat(nullchannel_index, 1:sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = tmp_data * ad_range; dat(nullchannel_index, 1:sample_length) = tmp_data; % Outputs to the global variable handles.sqd.nullchannel_ch_no = tmp_ch_no; handles.sqd.nullchannel_data = [ tmp_ch_no tmp_data]; clear tmp_data; end % select only the desired channels dat = dat(chanindx,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
lcnbeapp/beapp-master
decode_fif.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/decode_fif.m
5,978
utf_8
d33206202f4aa5a18ba3ada03de48664
function [info] = decode_fif(orig) % DECODE_FIF is a helper function for real-time processing of Neuromag data. This % function is used to decode the content of the optional neuromag_fif chunk(s). % % See also DECODE_RES4, DECODE_NIFTI1, SAP2MATLAB % Copyright (C) 2013 Arjen Stolk & Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % check that the required low-level toolbox is available ft_hastoolbox('mne', 1); global FIFF if isempty(FIFF) FIFF = fiff_define_constants(); end if isfield(orig, 'neuromag_header') % The binary blob was created on the little-endian Intel Linux acquisition % computer, whereas the default for fiff files is that they are stored in % big-endian byte order. MATLAB is able to swap the bytes on the fly by specifying % 'le" or "be" to fopen. The normal MNE fiff_open function assumes that it is big % endian, hence here we have to open it as little endian. filename = tempname; % write the binary blob to disk, byte-by-byte to avoid any swapping between little and big-endian content F = fopen(filename, 'w'); fwrite(F, orig.neuromag_header, 'uint8'); fclose(F); % read the content of the file using the standard reading functions [info, meas] = read_header(filename); % clean up the temporary file delete(filename); end % Typically, at the end of acquisition, the isotrak and hpiresult information % is stored in the neuromag fiff container which can then (offline) be read by % fiff_read_meas_info. However, for the purpose of head position monitoring % (see Stolk et al., Neuroimage 2013) during acquisition, this crucial % information requires to be accessible online. read_isotrak and read_hpiresult % can extract information from the additionally chunked (neuromag2ft) files. if isfield(orig, 'neuromag_isotrak') filename = tempname; % write the binary blob to disk, byte-by-byte to avoid any swapping between little and big-endian content F = fopen(filename, 'w'); fwrite(F, orig.neuromag_isotrak, 'uint8'); fclose(F); % read the content of the file using the standard reading functions [info.dig] = read_isotrak(filename); % clean up the temporary file delete(filename); end if isfield(orig, 'neuromag_hpiresult') filename = tempname; % write the binary blob to disk, byte-by-byte to avoid any swapping between little and big-endian content F = fopen(filename, 'w'); fwrite(F, orig.neuromag_hpiresult, 'uint8'); fclose(F); % read the content of the file using the standard reading functions [info.dev_head_t, info.ctf_head_t] = read_hpiresult(filename); % clean up the temporary file delete(filename); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [info, meas] = read_header(filename) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % open and read the file as little endian [fid, tree] = fiff_open_le(filename); % open as little endian [info, meas] = fiff_read_meas_info(fid, tree); fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dig] = read_isotrak(filename) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% global FIFF % open the isotrak file (big endian) % (typically stored in meas_info dir during acquisition, no fif extension required) [fid, tree] = fiff_open(filename); % locate the Polhemus data isotrak = fiff_dir_tree_find(tree,FIFF.FIFFB_ISOTRAK); dig=struct('kind',{},'ident',{},'r',{},'coord_frame',{}); coord_frame = FIFF.FIFFV_COORD_HEAD; if length(isotrak) == 1 p = 0; for k = 1:isotrak.nent kind = isotrak.dir(k).kind; pos = isotrak.dir(k).pos; if kind == FIFF.FIFF_DIG_POINT p = p + 1; tag = fiff_read_tag(fid,pos); dig(p) = tag.data; else if kind == FIFF.FIFF_MNE_COORD_FRAME tag = fiff_read_tag(fid,pos); coord_frame = tag.data; elseif kind == FIFF.FIFF_COORD_TRANS tag = fiff_read_tag(fid,pos); dig_trans = tag.data; end end end end for k = 1:length(dig) dig(k).coord_frame = coord_frame; end if exist('dig_trans','var') if (dig_trans.from ~= coord_frame && dig_trans.to ~= coord_frame) clear('dig_trans'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dev_head_t, ctf_head_t] = read_hpiresult(filename) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% global FIFF % open the hpiresult file (big endian) % (typically stored in meas_info dir during acquisition, no fif extension required) [fid, tree] = fiff_open(filename); % locate the transformation matrix dev_head_t=[]; ctf_head_t=[]; hpi_result = fiff_dir_tree_find(tree,FIFF.FIFFB_HPI_RESULT); if length(hpi_result) == 1 for k = 1:hpi_result.nent kind = hpi_result.dir(k).kind; pos = hpi_result.dir(k).pos; if kind == FIFF.FIFF_COORD_TRANS tag = fiff_read_tag(fid,pos); cand = tag.data; if cand.from == FIFF.FIFFV_COORD_DEVICE && ... cand.to == FIFF.FIFFV_COORD_HEAD dev_head_t = cand; elseif cand.from == FIFF.FIFFV_MNE_COORD_CTF_HEAD && ... cand.to == FIFF.FIFFV_COORD_HEAD ctf_head_t = cand; end end end end
github
lcnbeapp/beapp-master
read_biff.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_biff.m
5,799
utf_8
78a82ce91f8383fd0f478b921280d6bb
function [this] = read_biff(filename, opt) % READ_BIFF reads data and header information from a BIFF file % % This is a attemt for a reference implementation to read the BIFF % file format as defined by the Clinical Neurophysiology department of % the University Medical Centre, Nijmegen. % % read all data and information % [data] = read_biff(filename) % or read a selected top-level chunk % [chunk] = read_biff(filename, chunkID) % % known top-level chunk id's are % data : measured data (matrix) % dati : information on data (struct) % expi : information on experiment (struct) % pati : information on patient (struct) % evnt : event markers (struct) % Copyright (C) 2000, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ define_biff; this = []; fid = fopen(filename, 'r'); fseek(fid,0,'eof'); eof = ftell(fid); fseek(fid,0,'bof'); [id, siz] = chunk_header(fid); switch id case 'SEMG' child = subtree(BIFF, id); this = read_biff_chunk(fid, id, siz, child); case 'LIST' fprintf('skipping unimplemented chunk id="%s" size=%4d\n', id, siz); case 'CAT ' fprintf('skipping unimplemented chunk id="%s" size=%4d\n', id, siz); otherwise fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz); fseek(fid, siz, 'cof'); end % switch fclose(fid); % close file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION read_biff_chunk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function this = read_biff_chunk(fid, id, siz, chunk) % start with empty structure this = []; if strcmp(id, 'null') % this is an empty chunk fprintf('skipping empty chunk id="%s" size=%4d\n', id, siz); assert(~feof(fid)); fseek(fid, siz, 'cof'); elseif isempty(chunk) % this is an unrecognized chunk fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz); assert(~feof(fid)); fseek(fid, siz, 'cof'); else eoc = ftell(fid) + siz; name = char(chunk.desc(2)); type = char(chunk.desc(3)); fprintf('reading chunk id= "%s" size=%4d name="%s"\n', id, siz, name); switch type case 'group' while ~feof(fid) & ftell(fid)<eoc % read all subchunks [id, siz] = chunk_header(fid); child = subtree(chunk, id); if ~isempty(child) % read data and add subchunk data to chunk structure name = char(child.desc(2)); val = read_biff_chunk(fid, id, siz, child); this = setfield(this, name, val); else fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz); fseek(fid, siz, 'cof'); end end % while case 'string' this = char(fread(fid, siz, 'uchar')'); case {'char', 'uchar', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'float32', 'float64'} this = fread(fid, 1, type); case {'char', 'uchar', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'float32', 'float64'} this = fread(fid, 1, type); case {'int8vec', 'int16vec', 'int32vec', 'int64vec', 'uint8vec', 'uint16vec', 'uint32vec', 'float32vec', 'float64vec'} ncol = fread(fid, 1, 'uint32'); this = fread(fid, ncol, type(1:(length(type)-3))); case {'int8mat', 'int16mat', 'int32mat', 'int64mat', 'uint8mat', 'uint16mat', 'uint32mat', 'float32mat', 'float64mat'} nrow = fread(fid, 1, 'uint32'); ncol = fread(fid, 1, 'uint32'); this = fread(fid, [nrow, ncol], type(1:(length(type)-3))); otherwise fseek(fid, siz, 'cof'); % skip this chunk sprintf('unimplemented data type "%s" in chunk "%s"', type, id); % warning(ans); end % switch chunk type end % else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION subtree %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function child = subtree(parent, id) blank = findstr(id, ' '); while ~isempty(blank) id(blank) = '_'; blank = findstr(id, ' '); end elem = fieldnames(parent); % list of all subitems num = find(strcmp(elem, id)); % number in parent tree if size(num) == [1,1] child = getfield(parent, char(elem(num))); % child subtree else child = []; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION chunk_header %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [id, siz] = chunk_header(fid) id = char(fread(fid, 4, 'uchar')'); % read chunk ID siz = fread(fid, 1, 'uint32'); % read chunk size if strcmp(id, 'GRP ') | strcmp(id, 'BIFF') id = char(fread(fid, 4, 'uchar')'); % read real chunk ID siz = siz - 4; % reduce size by 4 end
github
lcnbeapp/beapp-master
read_eeglabheader.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_eeglabheader.m
2,267
utf_8
f76d1bbb9aa657b05643502ef19fdb10
% read_eeglabheader() - import EEGLAB dataset files % % Usage: % >> header = read_eeglabheader(filename); % % Inputs: % filename - [string] file name % % Outputs: % header - FILEIO toolbox type structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2008- %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function header = read_eeglabheader(filename) if nargin < 1 help read_eeglabheader; return; end; if ~isstruct(filename) load('-mat', filename); else EEG = filename; end; header.Fs = EEG.srate; header.nChans = EEG.nbchan; header.nSamples = EEG.pnts; header.nSamplesPre = -EEG.xmin*EEG.srate; header.nTrials = EEG.trials; try header.label = { EEG.chanlocs.labels }'; catch warning('creating default channel names'); for i=1:header.nChans header.label{i} = sprintf('chan%03d', i); end end ind = 1; for i = 1:length( EEG.chanlocs ) if isfield(EEG.chanlocs(i), 'X') && ~isempty(EEG.chanlocs(i).X) header.elec.label{ind, 1} = EEG.chanlocs(i).labels; % this channel has a position header.elec.elecpos(ind,1) = EEG.chanlocs(i).X; header.elec.elecpos(ind,2) = EEG.chanlocs(i).Y; header.elec.elecpos(ind,3) = EEG.chanlocs(i).Z; ind = ind+1; end; end; % remove data % ----------- %if isfield(EEG, 'datfile') % if ~isempty(EEG.datfile) % EEG.data = EEG.datfile; % end; %else % EEG.data = 'in set file'; %end; EEG.icaact = []; header.orig = EEG;
github
lcnbeapp/beapp-master
read_ctf_svl.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_ctf_svl.m
3,812
utf_8
d3442d0a013cf5e0a8d4277d99e45206
% [data, hdr] = opensvl(filename) % % Reads a CTF SAM (.svl) file. function [data, hdr] = read_ctf_svl(filename) fid = fopen(filename, 'rb', 'ieee-be', 'ISO-8859-1'); if fid <= 0 error('Could not open SAM file: %s\n', filename); end % ---------------------------------------------------------------------- % Read header. hdr.identity = fread(fid, 8, '*char')'; % 'SAMIMAGE' hdr.version = fread(fid, 1, 'int32'); % SAM file version. hdr.setName = fread(fid, 256, '*char')'; % Dataset name. hdr.numChans = fread(fid, 1, 'int32'); hdr.numWeights = fread(fid, 1, 'int32'); % 0 for static image. if(hdr.numWeights ~= 0) warning('hdr.numWeights ~= 0'); end fread(fid,1,'int32'); % Padding to next 8 byte boundary. hdr.xmin = fread(fid, 1, 'double'); % Bounding box coordinates (m). hdr.xmax = fread(fid, 1, 'double'); hdr.ymin = fread(fid, 1, 'double'); hdr.ymax = fread(fid, 1, 'double'); hdr.zmin = fread(fid, 1, 'double'); hdr.zmax = fread(fid, 1, 'double'); hdr.stepSize = fread(fid, 1, 'double'); % m hdr.hpFreq = fread(fid, 1, 'double'); % High pass filtering frequency (Hz). hdr.lpFreq = fread(fid, 1, 'double'); % Low pass. hdr.bwFreq = fread(fid, 1, 'double'); % Bandwidth hdr.meanNoise = fread(fid, 1, 'double'); % Sensor noise (T). hdr.mriName = fread(fid, 256, '*char')'; hdr.fiducial.mri.nas = fread(fid, 3, 'int32'); % CTF MRI voxel coordinates? hdr.fiducial.mri.rpa = fread(fid, 3, 'int32'); hdr.fiducial.mri.lpa = fread(fid, 3, 'int32'); hdr.SAMType = fread(fid, 1, 'int32'); % 0: image, 1: weights array, 2: weights list. hdr.SAMUnit = fread(fid, 1, 'int32'); % Possible values: 0 coefficients Am/T, 1 moment Am, 2 power (Am)^2, 3 Z, % 4 F, 5 T, 6 probability, 7 MUSIC. fread(fid, 1, 'int32'); % Padding to next 8 byte boundary. if hdr.version > 1 % Version 2 has extra fields. hdr.fiducial.head.nas = fread(fid, 3, 'double'); % CTF head coordinates? hdr.fiducial.head.rpa = fread(fid, 3, 'double'); hdr.fiducial.head.lpa = fread(fid, 3, 'double'); hdr.SAMUnitName = fread(fid, 32, '*char')'; % Possible values: 'Am/T' SAM coefficients, 'Am' source strength, % '(Am)^2' source power, ('Z', 'F', 'T') statistics, 'P' probability. end % ---------------------------------------------------------------------- % Read image data. data = fread(fid, inf, 'double'); fclose(fid); % Raw image data is ordered as a C array with indices: [x][y][z], meaning % z changes fastest and x slowest. These x, y, z axes point to ALS % (anterior, left, superior) respectively in real world coordinates, % which means the voxels are in SLA order. % ---------------------------------------------------------------------- % Post processing. % Change from m to mm. hdr.xmin = hdr.xmin * 1000; hdr.ymin = hdr.ymin * 1000; hdr.zmin = hdr.zmin * 1000; hdr.xmax = hdr.xmax * 1000; hdr.ymax = hdr.ymax * 1000; hdr.zmax = hdr.zmax * 1000; hdr.stepSize = hdr.stepSize * 1000; % Number of voxels in each dimension. hdr.dim = [round((hdr.xmax - hdr.xmin)/hdr.stepSize) + 1, ... round((hdr.ymax - hdr.ymin)/hdr.stepSize) + 1, ... round((hdr.zmax - hdr.zmin)/hdr.stepSize) + 1]; data = reshape(data, hdr.dim([3, 2, 1])); % Build transformation matrix from raw voxel coordinates (indexed from 1) % to head coordinates in mm. Note that the bounding box is given in % these coordinates (in m, but converted above). % Apply scaling. hdr.transform = diag([hdr.stepSize * ones(1, 3), 1]); % Reorder directions. hdr.transform = hdr.transform(:, [3, 2, 1, 4]); % Apply translation. hdr.transform(1:3, 4) = [hdr.xmin; hdr.ymin; hdr.zmin] - hdr.stepSize; % -step is needed since voxels are indexed from 1. end
github
lcnbeapp/beapp-master
read_erplabevent.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_erplabevent.m
1,786
utf_8
40ece49ff6bd2afd6024b46f210e65fa
% read_erplabevent() - import ERPLAB dataset events % % Usage: % >> event = read_erplabevent(filename, ...); % % Inputs: % filename - [string] file name % % Optional inputs: % 'header' - FILEIO structure header % % Outputs: % event - FILEIO toolbox event structure % % Modified from read_eeglabevent %123456789012345678901234567890123456789012345678901234567890123456789012 % % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function event = read_erplabevent(filename, varargin) if nargin < 1 help read_erplabheader; return; end; hdr = ft_getopt(varargin, 'header'); if isempty(hdr) hdr = read_erplabheader(filename); end event = []; % these will be the output in FieldTrip format oldevent = hdr.orig.bindescr; % these are in ERPLAB format for index = 1:length(oldevent) event(end+1).type = 'trial'; event(end ).sample = (index-1)*hdr.nSamples + 1; event(end ).value = oldevent{index}; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; end;
github
lcnbeapp/beapp-master
read_yokogawa_header_new.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_yokogawa_header_new.m
8,887
utf_8
70f6185e29007e7790efc5a8cb91bf23
function hdr = read_yokogawa_header_new(filename) % READ_YOKOGAWA_HEADER_NEW reads the header information from continuous, % epoched or averaged MEG data that has been generated by the Yokogawa % MEG system and software and allows that data to be used in combination % with FieldTrip. % % Use as % [hdr] = read_yokogawa_header_new(filename) % % This is a wrapper function around the functions % getYkgwHdrSystem % getYkgwHdrChannel % getYkgwHdrAcqCond % getYkgwHdrCoregist % getYkgwHdrDigitize % getYkgwHdrSource % % See also READ_YOKOGAWA_DATA_NEW, READ_YOKOGAWA_EVENT % ** % Copyright (C) 2005, Robert Oostenveld and 2010, Tilmann Sander-Thoemmes % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % FIXED % txt -> m % fopen iee-le if ~ft_hastoolbox('yokogawa_meg_reader') error('cannot determine whether Yokogawa toolbox is present'); end handles = definehandles; sys_info = getYkgwHdrSystem(filename); id = sys_info.system_id; ver = sys_info.version; rev = sys_info.revision; sys_name = sys_info.system_name; model_name = sys_info.model_name; clear('sys_info'); % remove structure as local variables are collected in the end channel_info = getYkgwHdrChannel(filename); channel_count = channel_info.channel_count; acq_cond = getYkgwHdrAcqCond(filename); acq_type = acq_cond.acq_type; % these depend on the data type sample_rate = []; sample_count = []; pretrigger_length = []; averaged_count = []; actual_epoch_count = []; switch acq_type case handles.AcqTypeContinuousRaw sample_rate = acq_cond.sample_rate; sample_count = acq_cond.sample_count; if isempty(sample_rate) | isempty(sample_count) error('invalid sample rate or sample count in ', filename); return; end pretrigger_length = 0; averaged_count = 1; case handles.AcqTypeEvokedAve sample_rate = acq_cond.sample_rate; sample_count = acq_cond.frame_length; pretrigger_length = acq_cond.pretrigger_length; averaged_count = acq_cond.average_count; if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(averaged_count) error('invalid sample rate or sample count or pretrigger length or average count in ', filename); return; end if acq_cond.multi_trigger.enable error('multi trigger mode not supported for ', filename); return; end case handles.AcqTypeEvokedRaw sample_rate = acq_cond.sample_rate; sample_count = acq_cond.frame_length; pretrigger_length = acq_cond.pretrigger_length; actual_epoch_count = acq_cond.average_count; if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(actual_epoch_count) error('invalid sample rate or sample count or pretrigger length or epoch count in ', filename); return; end if acq_cond.multi_trigger.enable error('multi trigger mode not supported for ', filename); return; end otherwise error('unknown data type'); end clear('acq_cond'); % remove structure as local variables are collected in the end coregist = getYkgwHdrCoregist(filename); digitize = getYkgwHdrDigitize(filename); source = getYkgwHdrSource(filename); % put all local variables into a structure, this is a bit unusual matlab programming style tmp = whos; orig = []; for i=1:length(tmp) if isempty(strmatch(tmp(i).name, {'tmp', 'ans', 'handles'})) orig = setfield(orig, tmp(i).name, eval(tmp(i).name)); end end % convert the original header information into something that FieldTrip understands hdr = []; hdr.orig = orig; % also store the original full header information hdr.Fs = orig.sample_rate; % sampling frequency hdr.nChans = orig.channel_count; % number of channels hdr.nSamples = []; % number of samples per trial hdr.nSamplesPre = []; % number of pre-trigger samples in each trial hdr.nTrials = []; % number of trials switch orig.acq_type case handles.AcqTypeEvokedAve hdr.nSamples = orig.sample_count; hdr.nSamplesPre = orig.pretrigger_length; hdr.nTrials = 1; % only the average, which can be considered as a single trial case handles.AcqTypeContinuousRaw hdr.nSamples = orig.sample_count; hdr.nSamplesPre = 0; % there is no fixed relation between triggers and data hdr.nTrials = 1; % the continuous data can be considered as a single very long trial case handles.AcqTypeEvokedRaw hdr.nSamples = orig.sample_count; hdr.nSamplesPre = orig.pretrigger_length; hdr.nTrials = orig.actual_epoch_count; otherwise error('unknown acquisition type'); end % construct a cell-array with labels of each channel for i=1:hdr.nChans % this should be consistent with the predefined list in ft_senslabel, % with yokogawa2grad_new and with ft_channelselection if hdr.orig.channel_info.channel(i).type == handles.NullChannel prefix = ''; elseif hdr.orig.channel_info.channel(i).type == handles.MagnetoMeter prefix = 'M'; elseif hdr.orig.channel_info.channel(i).type == handles.AxialGradioMeter prefix = 'AG'; elseif hdr.orig.channel_info.channel(i).type == handles.PlannerGradioMeter prefix = 'PG'; elseif hdr.orig.channel_info.channel(i).type == handles.RefferenceMagnetoMeter prefix = 'RM'; elseif hdr.orig.channel_info.channel(i).type == handles.RefferenceAxialGradioMeter prefix = 'RAG'; elseif hdr.orig.channel_info.channel(i).type == handles.RefferencePlannerGradioMeter prefix = 'RPG'; elseif hdr.orig.channel_info.channel(i).type == handles.TriggerChannel prefix = 'TRIG'; elseif hdr.orig.channel_info.channel(i).type == handles.EegChannel prefix = 'EEG'; elseif hdr.orig.channel_info.channel(i).type == handles.EcgChannel prefix = 'ECG'; elseif hdr.orig.channel_info.channel(i).type == handles.EtcChannel prefix = 'ETC'; end hdr.label{i} = sprintf('%s%03d', prefix, i); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
lcnbeapp/beapp-master
ft_datatype_raw.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/ft_datatype_raw.m
11,070
utf_8
aff8ada66bf72bd5975e10ea4d2a3648
function [data] = ft_datatype_raw(data, varargin) % FT_DATATYPE_RAW describes the FieldTrip MATLAB structure for raw data % % The raw datatype represents sensor-level time-domain data typically % obtained after calling FT_DEFINETRIAL and FT_PREPROCESSING. It contains % one or multiple segments of data, each represented as Nchan X Ntime % arrays. % % An example of a raw data structure with 151 MEG channels is % % label: {151x1 cell} the channel labels (e.g. 'MRC13') % time: {1x266 cell} the timeaxis [1*Ntime double] per trial % trial: {1x266 cell} the numeric data [151*Ntime double] per trial % sampleinfo: [266x2 double] the begin and endsample of each trial relative to the recording on disk % trialinfo: [266x1 double] optional trigger or condition codes for each trial % hdr: [1x1 struct] the full header information of the original dataset on disk % grad: [1x1 struct] information about the sensor array (for EEG it is called elec) % cfg: [1x1 struct] the configuration used by the function that generated this data structure % % Required fields: % - time, trial, label % % Optional fields: % - sampleinfo, trialinfo, grad, elec, hdr, cfg % % Deprecated fields: % - fsample % % Obsoleted fields: % - offset % % Historical fields: % - cfg, elec, fsample, grad, hdr, label, offset, sampleinfo, time, % trial, trialdef, see bug2513 % % Revision history: % % (2011/latest) The description of the sensors has changed, see FT_DATATYPE_SENS % for further information. % % (2010v2) The trialdef field has been replaced by the sampleinfo and % trialinfo fields. The sampleinfo corresponds to trl(:,1:2), the trialinfo % to trl(4:end). % % (2010v1) In 2010/Q3 it shortly contained the trialdef field which was a copy % of the trial definition (trl) is generated by FT_DEFINETRIAL. % % (2007) It used to contain the offset field, which correcponds to trl(:,3). % Since the offset field is redundant with the time axis, the offset field is % from now on not present any more. It can be recreated if needed. % % (2003) The initial version was defined % % See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_TIMELOCK, FT_DATATYPE_FREQ, % FT_DATATYPE_SPIKE, FT_DATATYPE_SENS % Copyright (C) 2011, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % get the optional input arguments, which should be specified as key-value pairs version = ft_getopt(varargin, 'version', 'latest'); hassampleinfo = ft_getopt(varargin, 'hassampleinfo', 'ifmakessense'); % can be yes/no/ifmakessense hastrialinfo = ft_getopt(varargin, 'hastrialinfo', 'ifmakessense'); % can be yes/no/ifmakessense % do some sanity checks assert(isfield(data, 'trial') && isfield(data, 'time') && isfield(data, 'label'), 'inconsistent raw data structure, some field is missing'); assert(length(data.trial)==length(data.time), 'inconsistent number of trials in raw data structure'); for i=1:length(data.trial) assert(size(data.trial{i},2)==length(data.time{i}), 'inconsistent number of samples in trial %d', i); assert(size(data.trial{i},1)==length(data.label), 'inconsistent number of channels in trial %d', i); end if isequal(hassampleinfo, 'ifmakessense') hassampleinfo = 'no'; % default to not adding it if isfield(data, 'sampleinfo') && size(data.sampleinfo,1)~=numel(data.trial) % it does not make sense, so don't keep it hassampleinfo = 'no'; end if isfield(data, 'sampleinfo') hassampleinfo = 'yes'; % if it's already there, consider keeping it numsmp = data.sampleinfo(:,2)-data.sampleinfo(:,1)+1; for i=1:length(data.trial) if size(data.trial{i},2)~=numsmp(i); % it does not make sense, so don't keep it hassampleinfo = 'no'; % the actual removal will be done further down warning('removing inconsistent sampleinfo'); break; end end end end if isequal(hastrialinfo, 'ifmakessense') hastrialinfo = 'no'; if isfield(data, 'trialinfo') hastrialinfo = 'yes'; if size(data.trialinfo,1)~=numel(data.trial) % it does not make sense, so don't keep it hastrialinfo = 'no'; warning('removing inconsistent trialinfo'); end end end % convert it into true/false hassampleinfo = istrue(hassampleinfo); hastrialinfo = istrue(hastrialinfo); if strcmp(version, 'latest') version = '2011'; end if isempty(data) return; end switch version case '2011' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(data, 'grad') % ensure that the gradiometer structure is up to date data.grad = ft_datatype_sens(data.grad); end if isfield(data, 'elec') % ensure that the electrode structure is up to date data.elec = ft_datatype_sens(data.elec); end if ~isfield(data, 'fsample') for i=1:length(data.time) if length(data.time{i})>1 data.fsample = 1/mean(diff(data.time{i})); break else data.fsample = nan; end end if isnan(data.fsample) warning('cannot determine sampling frequency'); end end if isfield(data, 'offset') data = rmfield(data, 'offset'); end % the trialdef field should be renamed into sampleinfo if isfield(data, 'trialdef') data.sampleinfo = data.trialdef; data = rmfield(data, 'trialdef'); end if (hassampleinfo && ~isfield(data, 'sampleinfo')) || (hastrialinfo && ~isfield(data, 'trialinfo')) % try to reconstruct the sampleinfo and trialinfo data = fixsampleinfo(data); end if ~hassampleinfo && isfield(data, 'sampleinfo') data = rmfield(data, 'sampleinfo'); end if ~hastrialinfo && isfield(data, 'trialinfo') data = rmfield(data, 'trialinfo'); end case '2010v2' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(data, 'fsample') data.fsample = 1/mean(diff(data.time{1})); end if isfield(data, 'offset') data = rmfield(data, 'offset'); end % the trialdef field should be renamed into sampleinfo if isfield(data, 'trialdef') data.sampleinfo = data.trialdef; data = rmfield(data, 'trialdef'); end if (hassampleinfo && ~isfield(data, 'sampleinfo')) || (hastrialinfo && ~isfield(data, 'trialinfo')) % try to reconstruct the sampleinfo and trialinfo data = fixsampleinfo(data); end if ~hassampleinfo && isfield(data, 'sampleinfo') data = rmfield(data, 'sampleinfo'); end if ~hastrialinfo && isfield(data, 'trialinfo') data = rmfield(data, 'trialinfo'); end case {'2010v1' '2010'} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(data, 'fsample') data.fsample = 1/mean(diff(data.time{1})); end if isfield(data, 'offset') data = rmfield(data, 'offset'); end if ~isfield(data, 'trialdef') && hascfg % try to find it in the nested configuration history data.trialdef = ft_findcfg(data.cfg, 'trl'); end case '2007' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(data, 'fsample') data.fsample = 1/mean(diff(data.time{1})); end if isfield(data, 'offset') data = rmfield(data, 'offset'); end case '2003' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(data, 'fsample') data.fsample = 1/mean(diff(data.time{1})); end if ~isfield(data, 'offset') data.offset = zeros(length(data.time),1); for i=1:length(data.time); data.offset(i) = round(data.time{i}(1)*data.fsample); end end otherwise %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% error('unsupported version "%s" for raw datatype', version); end % Numerical inaccuracies in the binary representations of floating point % values may accumulate. The following code corrects for small inaccuracies % in the time axes of the trials. See http://bugzilla.fcdonders.nl/show_bug.cgi?id=1390 data = fixtimeaxes(data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = fixtimeaxes(data) if ~isfield(data, 'fsample') fsample = 1/mean(diff(data.time{1})); else fsample = data.fsample; end begtime = zeros(1, length(data.time)); endtime = zeros(1, length(data.time)); numsample = zeros(1, length(data.time)); for i=1:length(data.time) begtime(i) = data.time{i}(1); endtime(i) = data.time{i}(end); numsample(i) = length(data.time{i}); end % compute the differences over trials and the tolerance tolerance = 0.01*(1/fsample); begdifference = abs(begtime-begtime(1)); enddifference = abs(endtime-endtime(1)); % check whether begin and/or end are identical, or close to identical begidentical = all(begdifference==0); endidentical = all(enddifference==0); begsimilar = all(begdifference < tolerance); endsimilar = all(enddifference < tolerance); % Compute the offset of each trial relative to the first trial, and express % that in samples. Non-integer numbers indicate that there is a slight skew % in the time over trials. This works in case of variable length trials. offset = fsample * (begtime-begtime(1)); skew = abs(offset - round(offset)); % try to determine all cases where a correction is needed % note that this does not yet address all possible cases where a fix might be needed needfix = false; needfix = needfix || ~begidentical && begsimilar; needfix = needfix || ~endidentical && endsimilar; needfix = needfix || ~all(skew==0) && all(skew<0.01); % if the skew is less than 1% it will be corrected if needfix ft_warning('correcting numerical inaccuracy in the time axes'); for i=1:length(data.time) % reconstruct the time axis of each trial, using the begin latency of % the first trial and the integer offset in samples of each trial data.time{i} = begtime(1) + ((1:numsample(i)) - 1 + round(offset(i)))/fsample; end end
github
lcnbeapp/beapp-master
getdimsiz.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/getdimsiz.m
2,235
utf_8
340d495a654f2f6752aa1af7ac915390
function dimsiz = getdimsiz(data, field) % GETDIMSIZ % % Use as % dimsiz = getdimsiz(data, field) % % If the length of the vector that is returned is smaller than the % number of dimensions that you would expect from GETDIMORD, you % should assume that it has trailing singleton dimensions. % % Example use % dimord = getdimord(datastructure, fieldname); % dimtok = tokenize(dimord, '_'); % dimsiz = getdimsiz(datastructure, fieldname); % dimsiz(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions % % See also GETDIMORD, GETDATFIELD if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field) field = ['avg.' field]; elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field) field = ['trial.' field]; elseif ~isfield(data, field) error('field "%s" not present in data', field); end if strncmp(field, 'avg.', 4) prefix = []; field = field(5:end); % strip the avg data.(field) = data.avg.(field); % move the avg into the main structure data = rmfield(data, 'avg'); elseif strncmp(field, 'trial.', 6) prefix = numel(data.trial); field = field(7:end); % strip the trial data.(field) = data.trial(1).(field); % move the first trial into the main structure data = rmfield(data, 'trial'); else prefix = []; end dimsiz = cellmatsize(data.(field)); % add nrpt in case of source.trial dimsiz = [prefix dimsiz]; end % main function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the size of data representations like {pos}_ori_time % FIXME this will fail for {xxx_yyy}_zzz %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function siz = cellmatsize(x) if iscell(x) if isempty(x) siz = 0; return % nothing else to do elseif isvector(x) cellsize = numel(x); % the number of elements in the cell-array else cellsize = size(x); x = x(:); % convert to vector for further size detection end [dum, indx] = max(cellfun(@numel, x)); matsize = size(x{indx}); % the size of the content of the cell-array siz = [cellsize matsize]; % concatenate the two else siz = size(x); end end % function cellmatsize
github
lcnbeapp/beapp-master
read_yokogawa_header.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_yokogawa_header.m
8,273
utf_8
ce0d6dbecc09597da7bbb311519c6c84
function hdr = read_yokogawa_header(filename) % READ_YOKOGAWA_HEADER reads the header information from continuous, % epoched or averaged MEG data that has been generated by the Yokogawa % MEG system and software and allows that data to be used in combination % with FieldTrip. % % Use as % [hdr] = read_yokogawa_header(filename) % % This is a wrapper function around the functions % GetMeg160SystemInfoM % GetMeg160ChannelCountM % GetMeg160ChannelInfoM % GetMeg160CalibInfoM % GetMeg160AmpGainM % GetMeg160DataAcqTypeM % GetMeg160ContinuousAcqCondM % GetMeg160EvokedAcqCondM % % See also READ_YOKOGAWA_DATA, READ_YOKOGAWA_EVENT % this function also calls % GetMeg160MriInfoM % GetMeg160MatchingInfoM % GetMeg160SourceInfoM % but I don't know whether to use the information provided by those % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % FIXED % txt -> m % fopen iee-le if ~ft_hastoolbox('yokogawa') error('cannot determine whether Yokogawa toolbox is present'); end handles = definehandles; fid = fopen(filename, 'rb', 'ieee-le'); % these are always present [id ver rev sys_name] = GetMeg160SystemInfoM(fid); channel_count = GetMeg160ChannelCountM(fid); channel_info = GetMeg160ChannelInfoM(fid); calib_info = GetMeg160CalibInfoM(fid); amp_gain = GetMeg160AmpGainM(fid); acq_type = GetMeg160DataAcqTypeM(fid); ad_bit = GetMeg160ADbitInfoM(fid); % these depend on the data type sample_rate = []; sample_count = []; pretrigger_length = []; averaged_count = []; actual_epoch_count = []; switch acq_type case handles.AcqTypeContinuousRaw [sample_rate, sample_count] = GetMeg160ContinuousAcqCondM(fid); if isempty(sample_rate) | isempty(sample_count) fclose(fid); return; end pretrigger_length = 0; averaged_count = 1; case handles.AcqTypeEvokedAve [sample_rate, sample_count, pretrigger_length, averaged_count] = GetMeg160EvokedAcqCondM( fid ); if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(averaged_count) fclose(fid); return; end case handles.AcqTypeEvokedRaw [sample_rate, sample_count, pretrigger_length, actual_epoch_count] = GetMeg160EvokedAcqCondM( fid ); if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(actual_epoch_count) fclose(fid); return; end otherwise error('unknown data type'); end % these are always present mri_info = GetMeg160MriInfoM(fid); matching_info = GetMeg160MatchingInfoM(fid); source_info = GetMeg160SourceInfoM(fid); fclose(fid); % put all local variables into a structure, this is a bit unusual matlab programming style tmp = whos; orig = []; for i=1:length(tmp) if isempty(strmatch(tmp(i).name, {'tmp', 'fid', 'ans', 'handles'})) orig = setfield(orig, tmp(i).name, eval(tmp(i).name)); end end % convert the original header information into something that FieldTrip understands hdr = []; hdr.orig = orig; % also store the original full header information hdr.Fs = orig.sample_rate; % sampling frequency hdr.nChans = orig.channel_count; % number of channels hdr.nSamples = []; % number of samples per trial hdr.nSamplesPre = []; % number of pre-trigger samples in each trial hdr.nTrials = []; % number of trials switch orig.acq_type case handles.AcqTypeEvokedAve hdr.nSamples = orig.sample_count; hdr.nSamplesPre = orig.pretrigger_length; hdr.nTrials = 1; % only the average, which can be considered as a single trial case handles.AcqTypeContinuousRaw hdr.nSamples = orig.sample_count; hdr.nSamplesPre = 0; % there is no fixed relation between triggers and data hdr.nTrials = 1; % the continuous data can be considered as a single very long trial case handles.AcqTypeEvokedRaw hdr.nSamples = orig.sample_count; hdr.nSamplesPre = orig.pretrigger_length; hdr.nTrials = orig.actual_epoch_count; otherwise error('unknown acquisition type'); end % construct a cell-array with labels of each channel for i=1:hdr.nChans % this should be consistent with the predefined list in ft_senslabel, % with yokogawa2grad and with ft_channelselection if hdr.orig.channel_info(i, 2) == handles.NullChannel prefix = ''; elseif hdr.orig.channel_info(i, 2) == handles.MagnetoMeter prefix = 'M'; elseif hdr.orig.channel_info(i, 2) == handles.AxialGradioMeter prefix = 'AG'; elseif hdr.orig.channel_info(i, 2) == handles.PlannerGradioMeter prefix = 'PG'; elseif hdr.orig.channel_info(i, 2) == handles.RefferenceMagnetoMeter prefix = 'RM'; elseif hdr.orig.channel_info(i, 2) == handles.RefferenceAxialGradioMeter prefix = 'RAG'; elseif hdr.orig.channel_info(i, 2) == handles.RefferencePlannerGradioMeter prefix = 'RPG'; elseif hdr.orig.channel_info(i, 2) == handles.TriggerChannel prefix = 'TRIG'; elseif hdr.orig.channel_info(i, 2) == handles.EegChannel prefix = 'EEG'; elseif hdr.orig.channel_info(i, 2) == handles.EcgChannel prefix = 'ECG'; elseif hdr.orig.channel_info(i, 2) == handles.EtcChannel prefix = 'ETC'; end hdr.label{i} = sprintf('%s%03d', prefix, i); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
lcnbeapp/beapp-master
encode_nifti1.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/encode_nifti1.m
4,870
utf_8
9cf92a03587c511a5cec2c8c76a3c2c3
function blob = encode_nifti1(H) %function blob = encode_nifti1(H) % % Encodes a NIFTI-1 header (=> raw 348 bytes (uint8)) from a Matlab structure % that matches the C struct defined in nifti1.h. % % WARNING: This function currently ignores endianness !!! % (C) 2010 S.Klanke blob = uint8(zeros(1,348)); if ~isstruct(H) error 'Input must be a structure'; end % see nift1.h for information on structure sizeof_hdr = int32(348); blob(1:4) = typecast(sizeof_hdr, 'uint8'); blob = setString(blob, 5, 14, H, 'data_type'); blob = setString(blob, 15, 32, H, 'db_name'); blob = setInt32( blob, 33, 36, H, 'extents'); blob = setInt16( blob, 37, 38, H, 'session_error'); blob = setInt8( blob, 39, 39, H, 'regular'); blob = setInt8( blob, 40, 40, H, 'dim_info'); dim = int16(H.dim(:)'); ndim = numel(dim); if ndim<1 || ndim>7 error 'Field "dim" must have 1..7 elements'; end dim = [int16(ndim) dim]; blob(41:(42+2*ndim)) = typecast(dim,'uint8'); blob = setSingle(blob, 57, 60, H, 'intent_p1'); blob = setSingle(blob, 61, 64, H, 'intent_p2'); blob = setSingle(blob, 65, 68, H, 'intent_p3'); blob = setInt16( blob, 69, 70, H, 'intent_code'); blob = setInt16( blob, 71, 72, H, 'datatype'); blob = setInt16( blob, 73, 74, H, 'bitpix'); blob = setInt16( blob, 75, 76, H, 'slice_start'); blob = setSingle(blob, 77, 80, H, 'qfac'); if isfield(H,'pixdim') pixdim = single(H.pixdim(:)'); ndim = numel(pixdim); if ndim<1 || ndim>7 error 'Field "pixdim" must have 1..7 elements'; end blob(81:(80+4*ndim)) = typecast(pixdim,'uint8'); end blob = setSingle(blob, 109, 112, H, 'vox_offset'); blob = setSingle(blob, 113, 116, H, 'scl_scope'); blob = setSingle(blob, 117, 120, H, 'scl_inter'); blob = setInt16( blob, 121, 122, H, 'slice_end'); blob = setInt8( blob, 123, 123, H, 'slice_code'); blob = setInt8( blob, 124, 124, H, 'xyzt_units'); blob = setSingle(blob, 125, 128, H, 'cal_max'); blob = setSingle(blob, 129, 132, H, 'cal_min'); blob = setSingle(blob, 133, 136, H, 'slice_duration'); blob = setSingle(blob, 137, 140, H, 'toffset'); blob = setInt32( blob, 141, 144, H, 'glmax'); blob = setInt32( blob, 145, 148, H, 'glmin'); blob = setString(blob, 149, 228, H, 'descrip'); blob = setString(blob, 229, 252, H, 'aux_file'); blob = setInt16( blob, 253, 254, H, 'qform_code'); blob = setInt16( blob, 255, 256, H, 'sform_code'); blob = setSingle(blob, 257, 260, H, 'quatern_b'); blob = setSingle(blob, 261, 264, H, 'quatern_c'); blob = setSingle(blob, 265, 268, H, 'quatern_d'); blob = setSingle(blob, 269, 272, H, 'quatern_x'); blob = setSingle(blob, 273, 276, H, 'quatern_y'); blob = setSingle(blob, 277, 280, H, 'quatern_z'); blob = setSingle(blob, 281, 296, H, 'srow_x'); blob = setSingle(blob, 297, 312, H, 'srow_y'); blob = setSingle(blob, 313, 328, H, 'srow_z'); blob = setString(blob, 329, 344, H, 'intent_name'); if ~isfield(H,'magic') blob(345:347) = uint8('ni1'); else blob = setString(blob, 345, 347, H, 'magic'); end function blob = setString(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = getfield(H, fieldname); ne = numel(F); mx = endidx - begidx +1; if ne > 0 if ~ischar(F) || ne > mx errmsg = sprintf('Field "data_type" must be a string of maximally %i characters.', mx); error(errmsg); end blob(begidx:(begidx+ne-1)) = uint8(F(:)'); end % set 32-bit integers (check #elements) function blob = setInt32(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int32(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 4; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8'); % set 16-bit integers (check #elements) function blob = setInt16(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int16(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 2; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+2*ne-1)) = typecast(F(:)', 'uint8'); % just 8-bit integers (check #elements) function blob = setInt8(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int8(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1); if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+ne-1)) = typecast(F(:)', 'uint8'); % single precision floats function blob = setSingle(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = single(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 4; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8');
github
lcnbeapp/beapp-master
read_nervus_header.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_nervus_header.m
30,014
utf_8
a7e8259eae22c5af14fb48467f95f2b7
function output = read_nervus_header(filename) % read_nervus_header Returns header information from Nicolet file. % % FILENAME is the file name of a file in the Natus/Nicolet/Nervus(TM) % format (originally designed by Taugagreining HF in Iceland) % % Based on ieeg-portal/Nicolet-Reader % at https://github.com/ieeg-portal/Nicolet-Reader % % Copyright (C) 2016, Jan Brogger and Joost Wagenaar % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: $ %--Constants-- LABELSIZE = 32; TSLABELSIZE = 64; UNITSIZE = 16; ITEMNAMESIZE = 64; % ---------------- Opening File------------------ h = fopen(filename,'rb','ieee-le'); if h==-1 error('Can''t open Nervus EEG file') end nrvHdr = struct(); nrvHdr.filename = filename; nrvHdr.misc1 = fread(h,5, 'uint32'); nrvHdr.unknown = fread(h,1,'uint32'); nrvHdr.indexIdx = fread(h,1,'uint32'); [nrvHdr.NrStaticPackets, nrvHdr.StaticPackets] = read_nervus_header_staticpackets(h); nrvHdr.QIIndex = read_nervus_header_Qi(h, nrvHdr.NrStaticPackets); nrvHdr.QIIndex2 = read_nervus_header_Qi2(h, nrvHdr.QIIndex); nrvHdr.MainIndex = read_nervus_header_main(h, nrvHdr.indexIdx, nrvHdr.QIIndex.nrEntries); nrvHdr.allIndexIDs = [nrvHdr.MainIndex.sectionIdx]; nrvHdr.infoGuids = read_nervus_header_infoGuids(h, nrvHdr.StaticPackets, nrvHdr.MainIndex); nrvHdr.DynamicPackets = read_nervus_header_dynamicpackets(h, nrvHdr.StaticPackets, nrvHdr.MainIndex); nrvHdr.PatientInfo = read_nervus_header_patient(h, nrvHdr.StaticPackets, nrvHdr.MainIndex); nrvHdr.SigInfo = read_nervus_header_SignalInfo(h, nrvHdr.StaticPackets, nrvHdr.MainIndex, ITEMNAMESIZE, LABELSIZE, UNITSIZE); nrvHdr.ChannelInfo = read_nervus_header_ChannelInfo(h, nrvHdr.StaticPackets, nrvHdr.MainIndex, ITEMNAMESIZE, LABELSIZE); nrvHdr.TSInfo = read_nervus_header_TSInfo(h, nrvHdr.DynamicPackets, nrvHdr.MainIndex, ITEMNAMESIZE, TSLABELSIZE, LABELSIZE); nrvHdr.Segments = read_nervus_header_Segments(h, nrvHdr.StaticPackets, nrvHdr.MainIndex, nrvHdr.TSInfo); nrvHdr.Events = read_nervus_header_events(h, nrvHdr.StaticPackets, nrvHdr.MainIndex); nrvHdr.MontageInfo = read_nervus_header_montage(h, nrvHdr.StaticPackets, nrvHdr.MainIndex); reference = unique(nrvHdr.Segments(1).refName(cellfun(@length, [nrvHdr.Segments(1).refName])>0)); if strcmp(reference, 'REF') nrvHdr.reference = 'common'; else nrvHdr.reference = 'unknown'; end fclose(h); %Calculate sample count across segments % - some channels have lower sampling rates, so we for each segments we % choose the channel with the highest sampling rate totalNSamples = 0; for i=1:size(nrvHdr.Segments,2) totalNSamples = totalNSamples + max(nrvHdr.Segments(i).samplingRate*nrvHdr.Segments(i).duration); end output = struct(); output.Fs = max([nrvHdr.Segments.samplingRate]); output.nChans = size([nrvHdr.Segments(1).chName],2); output.label = nrvHdr.Segments(1).chName; output.nSamples = totalNSamples; output.nSamplesPre = 0; output.nTrials = 1; %size(nrvHdr.Segments,2); output.reference = nrvHdr.reference; output.filename = nrvHdr.filename; output.orig = nrvHdr; end function [NrStaticPackets, StaticPackets] = read_nervus_header_staticpackets(h) % Get StaticPackets structure and Channel IDS fseek(h, 172,'bof'); NrStaticPackets = fread(h,1, 'uint32'); StaticPackets = struct(); for i = 1:NrStaticPackets StaticPackets(i).tag = deblank(cast(fread(h, 40, 'uint16'),'char')'); StaticPackets(i).index = fread(h,1,'uint32'); switch StaticPackets(i).tag case 'ExtraDataStaticPackets' StaticPackets(i).IDStr = 'ExtraDataStaticPackets'; case 'SegmentStream' StaticPackets(i).IDStr = 'SegmentStream'; case 'DataStream' StaticPackets(i).IDStr = 'DataStream'; case 'InfoChangeStream' StaticPackets(i).IDStr = 'InfoChangeStream'; case 'InfoGuids' StaticPackets(i).IDStr = 'InfoGuids'; case '{A271CCCB-515D-4590-B6A1-DC170C8D6EE2}' StaticPackets(i).IDStr = 'TSGUID'; case '{8A19AA48-BEA0-40D5-B89F-667FC578D635}' StaticPackets(i).IDStr = 'DERIVATIONGUID'; case '{F824D60C-995E-4D94-9578-893C755ECB99}' StaticPackets(i).IDStr = 'FILTERGUID'; case '{02950361-35BB-4A22-9F0B-C78AAA5DB094}' StaticPackets(i).IDStr = 'DISPLAYGUID'; case '{8E9421-70F5-11D3-8F72-00105A9AFD56}' StaticPackets(i).IDStr = 'FILEINFOGUID'; case '{E4138BC0-7733-11D3-8685-0050044DAAB1}' StaticPackets(i).IDStr = 'SRINFOGUID'; case '{C728E565-E5A0-4419-93D2-F6CFC69F3B8F}' StaticPackets(i).IDStr = 'EVENTTYPEINFOGUID'; case '{D01B34A0-9DBD-11D3-93D3-00500400C148}' StaticPackets(i).IDStr = 'AUDIOINFOGUID'; case '{BF7C95EF-6C3B-4E70-9E11-779BFFF58EA7}' StaticPackets(i).IDStr = 'CHANNELGUID'; case '{2DEB82A1-D15F-4770-A4A4-CF03815F52DE}' StaticPackets(i).IDStr = 'INPUTGUID'; case '{5B036022-2EDC-465F-86EC-C0A4AB1A7A91}' StaticPackets(i).IDStr = 'INPUTSETTINGSGUID'; case '{99A636F2-51F7-4B9D-9569-C7D45058431A}' StaticPackets(i).IDStr = 'PHOTICGUID'; case '{55C5E044-5541-4594-9E35-5B3004EF7647}' StaticPackets(i).IDStr = 'ERRORGUID'; case '{223A3CA0-B5AC-43FB-B0A8-74CF8752BDBE}' StaticPackets(i).IDStr = 'VIDEOGUID'; case '{0623B545-38BE-4939-B9D0-55F5E241278D}' StaticPackets(i).IDStr = 'DETECTIONPARAMSGUID'; case '{CE06297D-D9D6-4E4B-8EAC-305EA1243EAB}' StaticPackets(i).IDStr = 'PAGEGUID'; case '{782B34E8-8E51-4BB9-9701-3227BB882A23}' StaticPackets(i).IDStr = 'ACCINFOGUID'; case '{3A6E8546-D144-4B55-A2C7-40DF579ED11E}' StaticPackets(i).IDStr = 'RECCTRLGUID'; case '{D046F2B0-5130-41B1-ABD7-38C12B32FAC3}' StaticPackets(i).IDStr = 'GUID TRENDINFOGUID'; case '{CBEBA8E6-1CDA-4509-B6C2-6AC2EA7DB8F8}' StaticPackets(i).IDStr = 'HWINFOGUID'; case '{E11C4CBA-0753-4655-A1E9-2B2309D1545B}' StaticPackets(i).IDStr = 'VIDEOSYNCGUID'; case '{B9344241-7AC1-42B5-BE9B-B7AFA16CBFA5}' StaticPackets(i).IDStr = 'SLEEPSCOREINFOGUID'; case '{15B41C32-0294-440E-ADFF-DD8B61C8B5AE}' StaticPackets(i).IDStr = 'FOURIERSETTINGSGUID'; case '{024FA81F-6A83-43C8-8C82-241A5501F0A1}' StaticPackets(i).IDStr = 'SPECTRUMGUID'; case '{8032E68A-EA3E-42E8-893E-6E93C59ED515}' StaticPackets(i).IDStr = 'SIGNALINFOGUID'; case '{30950D98-C39C-4352-AF3E-CB17D5B93DED}' StaticPackets(i).IDStr = 'SENSORINFOGUID'; case '{F5D39CD3-A340-4172-A1A3-78B2CDBCCB9F}' StaticPackets(i).IDStr = 'DERIVEDSIGNALINFOGUID'; case '{969FBB89-EE8E-4501-AD40-FB5A448BC4F9}' StaticPackets(i).IDStr = 'ARTIFACTINFOGUID'; case '{02948284-17EC-4538-A7FA-8E18BD65E167}' StaticPackets(i).IDStr = 'STUDYINFOGUID'; case '{D0B3FD0B-49D9-4BF0-8929-296DE5A55910}' StaticPackets(i).IDStr = 'PATIENTINFOGUID'; case '{7842FEF5-A686-459D-8196-769FC0AD99B3}' StaticPackets(i).IDStr = 'DOCUMENTINFOGUID'; case '{BCDAEE87-2496-4DF4-B07C-8B4E31E3C495}' StaticPackets(i).IDStr = 'USERSINFOGUID'; case '{B799F680-72A4-11D3-93D3-00500400C148}' StaticPackets(i).IDStr = 'EVENTGUID'; case '{AF2B3281-7FCE-11D2-B2DE-00104B6FC652}' StaticPackets(i).IDStr = 'SHORTSAMPLESGUID'; case '{89A091B3-972E-4DA2-9266-261B186302A9}' StaticPackets(i).IDStr = 'DELAYLINESAMPLESGUID'; case '{291E2381-B3B4-44D1-BB77-8CF5C24420D7}' StaticPackets(i).IDStr = 'GENERALSAMPLESGUID'; case '{5F11C628-FCCC-4FDD-B429-5EC94CB3AFEB}' StaticPackets(i).IDStr = 'FILTERSAMPLESGUID'; case '{728087F8-73E1-44D1-8882-C770976478A2}' StaticPackets(i).IDStr = 'DATEXDATAGUID'; case '{35F356D9-0F1C-4DFE-8286-D3DB3346FD75}' StaticPackets(i).IDStr = 'TESTINFOGUID'; otherwise if isstrprop(StaticPackets(i).tag, 'digit') StaticPackets(i).IDStr = num2str(StaticPackets(i).tag); else StaticPackets(i).IDStr = 'UNKNOWN'; end end end end function QIIndex = read_nervus_header_Qi(h, nrStaticPackets) %% QI index fseek(h, 172208,'bof'); QIIndex =struct(); QIIndex.nrEntries = fread(h,1,'uint32'); QIIndex.misc1 = fread(h,1,'uint32'); QIIndex.indexIdx = fread(h,1,'uint32'); QIIndex.misc3 = fread(h,1,'uint32'); QIIndex.LQi = fread(h,1,'uint64')'; QIIndex.firstIdx = fread(h,nrStaticPackets,'uint64'); end function QIIndex2 = read_nervus_header_Qi2(h, QIIndex) fseek(h, 188664,'bof'); QIIndex2 = struct(); for i = 1:QIIndex.LQi QIIndex2(i).ftel = ftell(h); QIIndex2(i).index = fread(h,2,'uint16')'; %4 QIIndex2(i).misc1 = fread(h,1,'uint32'); %8 QIIndex2(i).indexIdx = fread(h,1,'uint32'); %12 QIIndex2(i).misc2 = fread(h,3,'uint32')'; %24 QIIndex2(i).sectionIdx = fread(h,1,'uint32');%28 QIIndex2(i).misc3 = fread(h,1,'uint32'); %32 QIIndex2(i).offset = fread(h,1,'uint64'); % 40 QIIndex2(i).blockL = fread(h,1,'uint32');%44 QIIndex2(i).dataL = fread(h,1,'uint32')';%48 end end function MainIndex = read_nervus_header_main(h, indexIdx, nrEntries) %% Get Main Index: % Index consists of multiple blocks, after each block is the pointer % to the next block. Total number of entries is in obj.Qi.nrEntries MainIndex = struct(); curIdx = 0; nextIndexPointer = indexIdx; curIdx2 = 1; while curIdx < nrEntries fseek(h, nextIndexPointer, 'bof'); nrIdx = fread(h,1, 'uint64'); MainIndex(curIdx + nrIdx).sectionIdx = 0; % Preallocate next set of indices var = fread(h,3*nrIdx, 'uint64'); for i = 1: nrIdx MainIndex(curIdx + i).sectionIdx = var(3*(i-1)+1); MainIndex(curIdx + i).offset = var(3*(i-1)+2); MainIndex(curIdx + i).blockL = mod(var(3*(i-1)+3),2^32); MainIndex(curIdx + i).sectionL = round(var(3*(i-1)+3)/2^32); end nextIndexPointer = fread(h,1, 'uint64'); curIdx = curIdx + i; curIdx2=curIdx2+1; end end function infoGuids = read_nervus_header_infoGuids(h, StaticPackets, MainIndex) infoIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'InfoGuids'),1)).index; indexInstance = MainIndex(find([MainIndex.sectionIdx]==infoIdx,1)); nrInfoGuids = indexInstance.sectionL/16; infoGuids = struct(); fseek(h, indexInstance.offset,'bof'); for i = 1:nrInfoGuids guidmixed = fread(h,16, 'uint8')'; guidnonmixed = [guidmixed(04), guidmixed(03), guidmixed(02), guidmixed(01), ... guidmixed(06), guidmixed(05), guidmixed(08), guidmixed(07), ... guidmixed(09), guidmixed(10), guidmixed(11), guidmixed(12), ... guidmixed(13), guidmixed(15), guidmixed(15), guidmixed(16)]; infoGuids(i).guid = num2str(guidnonmixed,'%02X'); end end function dynamicPackets = read_nervus_header_dynamicpackets(h, StaticPackets, MainIndex) dynamicPackets = struct(); indexIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'InfoChangeStream'),1)).index; offset = MainIndex(indexIdx).offset; nrDynamicPackets = MainIndex(indexIdx).sectionL / 48; fseek(h, offset, 'bof'); %Read first only the dynamic packets structure without actual data for i = 1: nrDynamicPackets dynamicPackets(i).offset = offset+i*48; guidmixed = fread(h,16, 'uint8')'; guidnonmixed = [guidmixed(04), guidmixed(03), guidmixed(02), guidmixed(01), ... guidmixed(06), guidmixed(05), guidmixed(08), guidmixed(07), ... guidmixed(09), guidmixed(10), guidmixed(11), guidmixed(12), ... guidmixed(13), guidmixed(14), guidmixed(15), guidmixed(16)]; dynamicPackets(i).guid = num2str(guidnonmixed, '%02X'); dynamicPackets(i).guidAsStr = sprintf('{%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X}', guidnonmixed); dynamicPackets(i).date = datenum(1899,12,31) + fread(h,1,'double'); dynamicPackets(i).datefrac = fread(h,1,'double'); dynamicPackets(i).internalOffsetStart = fread(h,1, 'uint64')'; dynamicPackets(i).packetSize = fread(h,1, 'uint64')'; dynamicPackets(i).data = zeros(0, 1,'uint8'); switch dynamicPackets(i).guid case 'BF7C95EF6C3B4E709E11779BFFF58EA7' dynamicPackets(i).IDStr = 'CHANNELGUID'; case '8A19AA48BEA040D5B89F667FC578D635' dynamicPackets(i).IDStr = 'DERIVATIONGUID'; case 'F824D60C995E4D949578893C755ECB99' dynamicPackets(i).IDStr = 'FILTERGUID'; case '0295036135BB4A229F0BC78AAA5DB094' dynamicPackets(i).IDStr = 'DISPLAYGUID'; case '782B34E88E514BB997013227BB882A23' dynamicPackets(i).IDStr = 'ACCINFOGUID'; case 'A271CCCB515D4590B6A1DC170C8D6EE2' dynamicPackets(i).IDStr = 'TSGUID'; case 'D01B34A09DBD11D393D300500400C148' dynamicPackets(i).IDStr = 'AUDIOINFOGUID'; otherwise dynamicPackets(i).IDStr = 'UNKNOWN'; end end %Then read the actual data from the pointers above for i = 1: nrDynamicPackets %Look up the GUID of this dynamic packet in the static packets % to find the section index infoIdx = StaticPackets(find(strcmp({StaticPackets.tag},dynamicPackets(i).guidAsStr),1)).index; %Matching index segments indexInstances = MainIndex([MainIndex.sectionIdx] == infoIdx); %Then, treat all these sections as one contiguous memory block % and grab this packet across these instances internalOffset = 0; remainingDataToRead = dynamicPackets(i).packetSize; %disp(['Target packet ' dynamicPackets(i).IDStr ' : ' num2str(dynamicPackets(i).internalOffsetStart) ' to ' num2str(dynamicPackets(i).internalOffsetStart+dynamicPackets(i).packetSize) ' target read length ' num2str(remainingDataToRead)]); currentTargetStart = dynamicPackets(i).internalOffsetStart; for j = 1: size(indexInstances,2) currentInstance = indexInstances(j); %hitInThisSegment = ''; if (internalOffset <= currentTargetStart) && (internalOffset+currentInstance.sectionL) >= currentTargetStart startAt = currentTargetStart; stopAt = min(startAt+remainingDataToRead, internalOffset+currentInstance.sectionL); readLength = stopAt-startAt; filePosStart = currentInstance.offset+startAt-internalOffset; fseek(h,filePosStart, 'bof'); dataPart = fread(h,readLength,'uint8=>uint8'); dynamicPackets(i).data = cat(1, dynamicPackets(i).data, dataPart); %hitInThisSegment = ['HIT at ' num2str(startAt) ' to ' num2str(stopAt)]; %if (readLength < remainingDataToRead) % hitInThisSegment = [hitInThisSegment ' (partial ' num2str(readLength) ' )']; %else % hitInThisSegment = [hitInThisSegment ' (finished - this segment contributed ' num2str(readLength) ' )']; %end %hitInThisSegment = [hitInThisSegment ' abs file pos ' num2str(filePosStart) ' - ' num2str(filePosStart+readLength)]; remainingDataToRead = remainingDataToRead-readLength; currentTargetStart = currentTargetStart + readLength; end %disp([' Index ' num2str(j) ' Offset: ' num2str(internalOffset) ' to ' num2str(internalOffset+currentInstance.sectionL) ' ' num2str(hitInThisSegment)]); internalOffset = internalOffset + currentInstance.sectionL; end end end function PatientInfo = read_nervus_header_patient(h, StaticPackets, Index) %% Get PatientGUID PatientInfo = struct(); infoProps = { 'patientID', 'firstName','middleName','lastName',... 'altID','mothersMaidenName','DOB','DOD','street','sexID','phone',... 'notes','dominance','siteID','suffix','prefix','degree','apartment',... 'city','state','country','language','height','weight','race','religion',... 'maritalStatus'}; infoIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'PATIENTINFOGUID'),1)).index; indexInstance = Index(find([Index.sectionIdx]==infoIdx,1)); fseek(h, indexInstance.offset,'bof'); guid = fread(h, 16, 'uint8'); lSection = fread(h, 1, 'uint64'); % reserved = fread(h, 3, 'uint16'); nrValues = fread(h,1,'uint64'); nrBstr = fread(h,1,'uint64'); for i = 1:nrValues id = fread(h,1,'uint64'); switch id case {7,8} unix_time = (fread(h,1, 'double')*(3600*24)) - 2209161600;% 2208988800; %8 obj.segments(i).dateStr = datestr(unix_time/86400 + datenum(1970,1,1)); value = datevec( obj.segments(i).dateStr ); value = value([3 2 1]); case {23,24} value = fread(h,1,'double'); otherwise value = 0; end PatientInfo.(infoProps{id}) = value; end strSetup = fread(h,nrBstr*2,'uint64'); for i=1:2:(nrBstr*2) id = strSetup(i); value = deblank(cast(fread(h, strSetup(i+1) + 1, 'uint16'),'char')'); info.(infoProps{id}) = value; end end function sigInfo = read_nervus_header_SignalInfo(h, StaticPackets, Index, ITEMNAMESIZE, LABELSIZE, UNITSIZE) infoIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'InfoGuids'),1)).index; indexInstance = Index(find([Index.sectionIdx]==infoIdx,1)); fseek(h, indexInstance.offset,'bof'); sigInfo = struct(); SIG_struct = struct(); sensorIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'SIGNALINFOGUID'),1)).index; indexInstance = Index(find([Index.sectionIdx]==sensorIdx,1)); fseek(h, indexInstance.offset,'bof'); SIG_struct.guid = fread(h, 16, 'uint8'); SIG_struct.name = fread(h, ITEMNAMESIZE, '*char'); unkown = fread(h, 152, '*char'); %#ok<NASGU> fseek(h, 512, 'cof'); nrIdx = fread(h,1, 'uint16'); %783 misc1 = fread(h,3, 'uint16'); %#ok<NASGU> for i = 1: nrIdx sigInfo(i).sensorName = deblank(cast(fread(h, LABELSIZE, 'uint16'),'char')'); sigInfo(i).transducer = deblank(cast(fread(h, UNITSIZE, 'uint16'),'char')'); sigInfo(i).guid = fread(h, 16, '*uint8'); sigInfo(i).bBiPolar = logical(fread(h, 1 ,'uint32')); sigInfo(i).bAC = logical(fread(h, 1 ,'uint32')); sigInfo(i).bHighFilter = logical(fread(h, 1 ,'uint32')); sigInfo(i).color = fread(h, 1 ,'uint32'); reserved = fread(h, 256, '*char'); %#ok<NASGU> end end function channelInfo = read_nervus_header_ChannelInfo(h, StaticPackets, Index, ITEMNAMESIZE, LABELSIZE) %% Get CHANNELINFO (CHANNELGUID) CH_struct = struct(); sensorIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'CHANNELGUID'),1)).index; indexInstance = Index(find([Index.sectionIdx]==sensorIdx,1)); fseek(h, indexInstance.offset,'bof'); CH_struct.guid = fread(h, 16, 'uint8'); CH_struct.name = fread(h, ITEMNAMESIZE, '*char'); fseek(h, 152, 'cof'); CH_struct.reserved = fread(h, 16, 'uint8'); CH_struct.deviceID = fread(h, 16, 'uint8'); fseek(h, 488, 'cof'); nrIdx = fread(h,2, 'uint32'); %783 channelInfo = struct(); for i = 1: nrIdx(2) channelInfo(i).sensor = deblank(cast(fread(h, LABELSIZE, 'uint16'),'char')'); channelInfo(i).samplingRate = fread(h,1,'double'); channelInfo(i).bOn = logical(fread(h, 1 ,'uint32')); channelInfo(i).lInputID = fread(h, 1 ,'uint32'); channelInfo(i).lInputSettingID = fread(h,1,'uint32'); channelInfo(i).reserved = fread(h,4,'char'); fseek(h, 128, 'cof'); end curIdx = 0; for i = 1: length(channelInfo) if channelInfo(i).bOn channelInfo(i).indexID = curIdx; curIdx = curIdx+1; else channelInfo(i).indexID = -1; end end end function [TSInfo] = read_nervus_header_TSInfo(h, DynamicPackets, Index, ITEMNAMESIZE, TSLABELSIZE, LABELSIZE) tsPackets = DynamicPackets(strcmp({DynamicPackets.IDStr},'TSGUID')); if length(tsPackets) > 1 warning(['Multiple TSinfo packets detected; using first instance ' ... ' ac for all segments. See documentation for info.']); elseif isempty(tsPackets) warning(['No TSINFO found']); else tsPacket = tsPackets(1); TSInfo = struct(); elems = typecast(tsPacket.data(753:756),'uint32'); alloc = typecast(tsPacket.data(757:760),'uint32'); offset = 761; for i = 1:elems internalOffset = 0; TSInfo(i).label = deblank(char(typecast(tsPacket.data(offset:(offset+TSLABELSIZE-1))','uint16'))); internalOffset = internalOffset + TSLABELSIZE*2; TSInfo(i).activeSensor = deblank(char(typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+LABELSIZE))','uint16'))); internalOffset = internalOffset + TSLABELSIZE; TSInfo(i).refSensor = deblank(char(typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','uint16'))); internalOffset = internalOffset + 8; internalOffset = internalOffset + 56; TSInfo(i).lowcut = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','double'); internalOffset = internalOffset + 8; TSInfo(i).hiCut = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','double'); internalOffset = internalOffset + 8; TSInfo(i).samplingRate = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','double'); internalOffset = internalOffset + 8; TSInfo(i).resolution = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','double'); internalOffset = internalOffset + 8; TSInfo(i).specialMark = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+2))','uint16'); internalOffset = internalOffset + 2; TSInfo(i).notch = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+2))','uint16'); internalOffset = internalOffset + 2; TSInfo(i).eeg_offset = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','double'); offset = offset + 552; %disp([num2str(i) ' : ' TSInfo(i).label ' : ' TSInfo(i).activeSensor ' : ' TSInfo(i).refSensor ' : ' num2str(TSInfo(i).samplingRate)]); end end end function [segments] = read_nervus_header_Segments(h, StaticPackets, Index, TSInfo) %% Get Segment Start Times segmentIdx = StaticPackets(find(strcmp({StaticPackets.IDStr}, 'SegmentStream'),1)).index; indexIdx = find([Index.sectionIdx] == segmentIdx, 1); segmentInstance = Index(indexIdx); nrSegments = segmentInstance.sectionL/152; fseek(h, segmentInstance.offset,'bof'); segments = struct(); for i = 1: nrSegments dateOLE = fread(h,1, 'double'); segments(i).dateOLE = dateOLE; unix_time = (dateOLE*(3600*24)) - 2209161600;% 2208988800; %8 segments(i).dateStr = datestr(unix_time/86400 + datenum(1970,1,1)); datev = datevec( segments(i).dateStr ); segments(i).startDate = datev(1:3); segments(i).startTime = datev(4:6); fseek(h, 8 , 'cof'); %16 segments(i).duration = fread(h,1, 'double');%24 fseek(h, 128 , 'cof'); %152 end % Get nrValues per segment and channel for iSeg = 1:length(segments) % Add Channel Names to segments segments(iSeg).chName = {TSInfo.label}; segments(iSeg).refName = {TSInfo.refSensor}; segments(iSeg).samplingRate = [TSInfo.samplingRate]; segments(iSeg).scale = [TSInfo.resolution]; segments(iSeg).sampleCount = max(segments(iSeg).samplingRate*segments(iSeg).duration); end end function [eventMarkers] = read_nervus_header_events(h, StaticPackets, Index) %% Get events - Andrei Barborica, Dec 2015 % Find sequence of events, that are stored in the section tagged 'Events' eventsSection = strcmp({StaticPackets.tag}, 'Events'); idxSection = find(eventsSection); indexIdx = find([Index.sectionIdx] == StaticPackets(idxSection).index); offset = Index(indexIdx).offset; ePktLen = 272; % Event packet length, see EVENTPACKET definition eMrkLen = 240; % Event marker length, see EVENTMARKER definition evtPktGUID = hex2dec({'80', 'F6', '99', 'B7', 'A4', '72', 'D3', '11', '93', 'D3', '00', '50', '04', '00', 'C1', '48'}); % GUID for event packet header HCEVENT_ANNOTATION = '{A5A95612-A7F8-11CF-831A-0800091B5BDA}'; HCEVENT_SEIZURE = '{A5A95646-A7F8-11CF-831A-0800091B5BDA}'; HCEVENT_FORMATCHANGE = '{08784382-C765-11D3-90CE-00104B6F4F70}'; HCEVENT_PHOTIC = '{6FF394DA-D1B8-46DA-B78F-866C67CF02AF}'; HCEVENT_POSTHYPERVENT = '{481DFC97-013C-4BC5-A203-871B0375A519}'; HCEVENT_REVIEWPROGRESS = '{725798BF-CD1C-4909-B793-6C7864C27AB7}'; HCEVENT_EXAMSTART = '{96315D79-5C24-4A65-B334-E31A95088D55}'; HCEVENT_HYPERVENTILATION = '{A5A95608-A7F8-11CF-831A-0800091B5BDA}'; HCEVENT_IMPEDANCE = '{A5A95617-A7F8-11CF-831A-0800091B5BDA}'; DAYSECS = 86400.0; % From nrvdate.h fseek(h,offset,'bof'); pktGUID = fread(h,16,'uint8'); pktLen = fread(h,1,'uint64'); eventMarkers = struct(); i = 0; % Event counter while (pktGUID == evtPktGUID) i = i + 1; % Please refer to EVENTMARKER structure in the Nervus file documentation fseek(h,8,'cof'); % Skip eventID, not used evtDate = fread(h,1,'double'); evtDateFraction = fread(h,1,'double'); eventMarkers(i).dateOLE = evtDate; eventMarkers(i).dateFraction = evtDateFraction; evtPOSIXTime = evtDate*DAYSECS + evtDateFraction - 2209161600;% 2208988800; %8 eventMarkers(i).dateStr = datestr(evtPOSIXTime/DAYSECS + datenum(1970,1,1),'dd-mmmm-yyyy HH:MM:SS.FFF'); % Save fractions of seconds, as well eventMarkers(i).duration = fread(h,1,'double'); fseek(h,48,'cof'); evtUser = fread(h,12,'uint16'); eventMarkers(i).user = deblank(char(evtUser).'); evtTextLen = fread(h,1,'uint64'); evtGUID = fread(h,16,'uint8'); eventMarkers(i).GUID = sprintf('{%.2X%.2X%.2X%.2X-%.2X%.2X-%.2X%.2X-%.2X%.2X-%.2X%.2X%.2X%.2X%.2X%.2X}',evtGUID([4 3 2 1 6 5 8 7 9:16])); fseek(h,16,'cof'); % Skip Reserved4 array evtLabel = fread(h,32,'uint16'); % LABELSIZE = 32; evtLabel = deblank(char(evtLabel).'); % Not used eventMarkers(i).label = evtLabel; % Only a subset of all event types are dealt with switch eventMarkers(i).GUID case HCEVENT_SEIZURE eventMarkers(i).IDStr = 'Seizure'; %disp(' Seizure event'); case HCEVENT_ANNOTATION eventMarkers(i).IDStr = 'Annotation'; fseek(h,32,'cof'); % Skip Reserved5 array evtAnnotation = fread(h,evtTextLen,'uint16'); eventMarkers(i).annotation = deblank(char(evtAnnotation).'); %disp(sprintf(' Annotation:%s',evtAnnotation)); case HCEVENT_FORMATCHANGE eventMarkers(i).IDStr = 'Format change'; case HCEVENT_PHOTIC eventMarkers(i).IDStr = 'Photic'; case HCEVENT_POSTHYPERVENT eventMarkers(i).IDStr = 'Posthyperventilation'; case HCEVENT_REVIEWPROGRESS eventMarkers(i).IDStr = 'Review progress'; case HCEVENT_EXAMSTART eventMarkers(i).IDStr = 'Exam start'; case HCEVENT_HYPERVENTILATION eventMarkers(i).IDStr = 'Hyperventilation'; case HCEVENT_IMPEDANCE eventMarkers(i).IDStr = 'Impedance'; otherwise eventMarkers(i).IDStr = 'UNKNOWN'; end % Next packet offset = offset + pktLen; fseek(h,offset,'bof'); pktGUID = fread(h,16,'uint8'); pktLen = fread(h,1,'uint64'); end end function [montage] = read_nervus_header_montage(h, StaticPackets, Index) %% Get montage - Andrei Barborica, Dec 2015 % Derivation (montage) mtgIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'DERIVATIONGUID'),1)).index; indexIdx = find([Index.sectionIdx]==mtgIdx,1); fseek(h,Index(indexIdx(1)).offset + 40,'bof'); % Beginning of current montage name mtgName = deblank(char(fread(h,32,'uint16')).'); fseek(h,640,'cof'); % Number of traces in the montage numDerivations = fread(h,1,'uint32'); numDerivations2 = fread(h,1,'uint32'); montage = struct(); for i = 1:numDerivations montage(i).derivationName = deblank(char(fread(h,64,'uint16')).'); montage(i).signalName1 = deblank(char(fread(h,32,'uint16')).'); montage(i).signalName2 = deblank(char(fread(h,32,'uint16')).'); fseek(h,264,'cof'); % Skip additional info end % Display properties dispIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'DISPLAYGUID'),1)).index; indexIdx = find([Index.sectionIdx]==dispIdx,1); fseek(h,Index(indexIdx(1)).offset + 40,'bof'); % Beginning of current montage name displayName = deblank(char(fread(h,32,'uint16')).'); fseek(h,640,'cof'); % Number of traces in the montage numTraces = fread(h,1,'uint32'); numTraces2 = fread(h,1,'uint32'); if (numTraces == numDerivations) for i = 1:numTraces fseek(h,32,'cof'); montage(i).color = fread(h,1,'uint32'); % Use typecast(uint32(montage(i).color),'uint8') to convert to RGB array fseek(h,136-4,'cof'); end else disp('Could not match montage derivations with display color table'); end end
github
lcnbeapp/beapp-master
avw_hdr_read.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/avw_hdr_read.m
16,654
utf_8
f63f3dbd244a89c6108eff59453680c3
function [ avw, machine ] = avw_hdr_read(fileprefix, machine, verbose) % avw_hdr_read - read Analyze format data header (*.hdr) % % [ avw, machine ] = avw_hdr_read(fileprefix, [machine], [verbose]) % % fileprefix - string filename (without .hdr); the file name % can be given as a full path or relative to the % current directory. % % machine - a string, see machineformat in fread for details. % The default here is 'ieee-le' but the routine % will automatically switch between little and big % endian to read any such Analyze header. It % reports the appropriate machine format and can % return the machine value. % % avw.hdr - a struct, all fields returned from the header. % For details, find a good description on the web % or see the Analyze File Format pdf in the % mri_toolbox doc folder or read this .m file. % % verbose - the default is to output processing information to the command % window. If verbose = 0, this will not happen. % % This function is called by avw_img_read % % See also avw_hdr_write, avw_hdr_make, avw_view_hdr, avw_view % % $Revision$ $Date: 2009/01/14 09:24:45 $ % Licence: GNU GPL, no express or implied warranties % History: 05/2002, [email protected] % The Analyze format and c code below is copyright % (c) Copyright, 1986-1995 % Biomedical Imaging Resource, Mayo Foundation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('verbose','var'), verbose = 1; end if verbose, version = '[$Revision$]'; fprintf('\nAVW_HDR_READ [v%s]\n',version(12:16)); tic; end if ~exist('fileprefix','var'), msg = sprintf('...no input fileprefix - see help avw_hdr_read\n\n'); error(msg); end if ~exist('machine','var'), machine = 'ieee-le'; end if findstr('.hdr',fileprefix), % fprintf('...removing .hdr extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.hdr',''); end if findstr('.img',fileprefix), % fprintf('...removing .img extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.img',''); end file = sprintf('%s.hdr',fileprefix); if exist(file), if verbose, fprintf('...reading %s Analyze format',machine); end fid = fopen(file,'r',machine); avw.hdr = read_header(fid,verbose); avw.fileprefix = fileprefix; fclose(fid); if ~isequal(avw.hdr.hk.sizeof_hdr,348), if verbose, fprintf('...failed.\n'); end % first try reading the opposite endian to 'machine' switch machine, case 'ieee-le', machine = 'ieee-be'; case 'ieee-be', machine = 'ieee-le'; end if verbose, fprintf('...reading %s Analyze format',machine); end fid = fopen(file,'r',machine); avw.hdr = read_header(fid,verbose); avw.fileprefix = fileprefix; fclose(fid); end if ~isequal(avw.hdr.hk.sizeof_hdr,348), % Now throw an error if verbose, fprintf('...failed.\n'); end msg = sprintf('...size of header not equal to 348 bytes!\n\n'); error(msg); end else msg = sprintf('...cannot find file %s.hdr\n\n',file); error(msg); end if verbose, t=toc; fprintf('...done (%5.2f sec).\n',t); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ dsr ] = read_header(fid,verbose) % Original header structures - ANALYZE 7.5 %struct dsr % { % struct header_key hk; /* 0 + 40 */ % struct image_dimension dime; /* 40 + 108 */ % struct data_history hist; /* 148 + 200 */ % }; /* total= 348 bytes*/ dsr.hk = header_key(fid); dsr.dime = image_dimension(fid,verbose); dsr.hist = data_history(fid); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hk] = header_key(fid) % The required elements in the header_key substructure are: % % int sizeof_header Must indicate the byte size of the header file. % int extents Should be 16384, the image file is created as % contiguous with a minimum extent size. % char regular Must be 'r' to indicate that all images and % volumes are the same size. % Original header structures - ANALYZE 7.5 % struct header_key /* header key */ % { /* off + size */ % int sizeof_hdr /* 0 + 4 */ % char data_type[10]; /* 4 + 10 */ % char db_name[18]; /* 14 + 18 */ % int extents; /* 32 + 4 */ % short int session_error; /* 36 + 2 */ % char regular; /* 38 + 1 */ % char hkey_un0; /* 39 + 1 */ % }; /* total=40 bytes */ fseek(fid,0,'bof'); hk.sizeof_hdr = fread(fid, 1,'*int32'); % should be 348! hk.data_type = fread(fid,10,'*char')'; hk.db_name = fread(fid,18,'*char')'; hk.extents = fread(fid, 1,'*int32'); hk.session_error = fread(fid, 1,'*int16'); hk.regular = fread(fid, 1,'*char')'; % might be uint8 hk.hkey_un0 = fread(fid, 1,'*uint8')'; % check if this value was a char zero if hk.hkey_un0 == 48, hk.hkey_un0 = 0; end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ dime ] = image_dimension(fid,verbose) %struct image_dimension % { /* off + size */ % short int dim[8]; /* 0 + 16 */ % /* % dim[0] Number of dimensions in database; usually 4. % dim[1] Image X dimension; number of *pixels* in an image row. % dim[2] Image Y dimension; number of *pixel rows* in slice. % dim[3] Volume Z dimension; number of *slices* in a volume. % dim[4] Time points; number of volumes in database % */ % char vox_units[4]; /* 16 + 4 */ % char cal_units[8]; /* 20 + 8 */ % short int unused1; /* 28 + 2 */ % short int datatype; /* 30 + 2 */ % short int bitpix; /* 32 + 2 */ % short int dim_un0; /* 34 + 2 */ % float pixdim[8]; /* 36 + 32 */ % /* % pixdim[] specifies the voxel dimensions: % pixdim[1] - voxel width, mm % pixdim[2] - voxel height, mm % pixdim[3] - slice thickness, mm % pixdim[4] - volume timing, in msec % ..etc % */ % float vox_offset; /* 68 + 4 */ % float roi_scale; /* 72 + 4 */ % float funused1; /* 76 + 4 */ % float funused2; /* 80 + 4 */ % float cal_max; /* 84 + 4 */ % float cal_min; /* 88 + 4 */ % int compressed; /* 92 + 4 */ % int verified; /* 96 + 4 */ % int glmax; /* 100 + 4 */ % int glmin; /* 104 + 4 */ % }; /* total=108 bytes */ dime.dim = fread(fid,8,'*int16')'; dime.vox_units = fread(fid,4,'*char')'; dime.cal_units = fread(fid,8,'*char')'; dime.unused1 = fread(fid,1,'*int16'); dime.datatype = fread(fid,1,'*int16'); dime.bitpix = fread(fid,1,'*int16'); dime.dim_un0 = fread(fid,1,'*int16'); dime.pixdim = fread(fid,8,'*float')'; dime.vox_offset = fread(fid,1,'*float'); dime.roi_scale = fread(fid,1,'*float'); dime.funused1 = fread(fid,1,'*float'); dime.funused2 = fread(fid,1,'*float'); dime.cal_max = fread(fid,1,'*float'); dime.cal_min = fread(fid,1,'*float'); dime.compressed = fread(fid,1,'*int32'); dime.verified = fread(fid,1,'*int32'); dime.glmax = fread(fid,1,'*int32'); dime.glmin = fread(fid,1,'*int32'); if dime.dim(1) < 4, % Number of dimensions in database; usually 4. if verbose, fprintf('...ensuring 4 dimensions in avw.hdr.dime.dim\n'); end dime.dim(1) = int16(4); end if dime.dim(5) < 1, % Time points; number of volumes in database if verbose, fprintf('...ensuring at least 1 volume in avw.hdr.dime.dim(5)\n'); end dime.dim(5) = int16(1); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ hist ] = data_history(fid) % Original header structures - ANALYZE 7.5 %struct data_history % { /* off + size */ % char descrip[80]; /* 0 + 80 */ % char aux_file[24]; /* 80 + 24 */ % char orient; /* 104 + 1 */ % char originator[10]; /* 105 + 10 */ % char generated[10]; /* 115 + 10 */ % char scannum[10]; /* 125 + 10 */ % char patient_id[10]; /* 135 + 10 */ % char exp_date[10]; /* 145 + 10 */ % char exp_time[10]; /* 155 + 10 */ % char hist_un0[3]; /* 165 + 3 */ % int views /* 168 + 4 */ % int vols_added; /* 172 + 4 */ % int start_field; /* 176 + 4 */ % int field_skip; /* 180 + 4 */ % int omax; /* 184 + 4 */ % int omin; /* 188 + 4 */ % int smax; /* 192 + 4 */ % int smin; /* 196 + 4 */ % }; /* total=200 bytes */ hist.descrip = fread(fid,80,'*char')'; hist.aux_file = fread(fid,24,'*char')'; hist.orient = fread(fid, 1,'*uint8'); % see note below on char hist.originator = fread(fid,10,'*char')'; hist.generated = fread(fid,10,'*char')'; hist.scannum = fread(fid,10,'*char')'; hist.patient_id = fread(fid,10,'*char')'; hist.exp_date = fread(fid,10,'*char')'; hist.exp_time = fread(fid,10,'*char')'; hist.hist_un0 = fread(fid, 3,'*char')'; hist.views = fread(fid, 1,'*int32'); hist.vols_added = fread(fid, 1,'*int32'); hist.start_field = fread(fid, 1,'*int32'); hist.field_skip = fread(fid, 1,'*int32'); hist.omax = fread(fid, 1,'*int32'); hist.omin = fread(fid, 1,'*int32'); hist.smax = fread(fid, 1,'*int32'); hist.smin = fread(fid, 1,'*int32'); % check if hist.orient was saved as ascii char value switch hist.orient, case 48, hist.orient = uint8(0); case 49, hist.orient = uint8(1); case 50, hist.orient = uint8(2); case 51, hist.orient = uint8(3); case 52, hist.orient = uint8(4); case 53, hist.orient = uint8(5); end return % Note on using char: % The 'char orient' field in the header is intended to % hold simply an 8-bit unsigned integer value, not the ASCII representation % of the character for that value. A single 'char' byte is often used to % represent an integer value in Analyze if the known value range doesn't % go beyond 0-255 - saves a byte over a short int, which may not mean % much in today's computing environments, but given that this format % has been around since the early 1980's, saving bytes here and there on % older systems was important! In this case, 'char' simply provides the % byte of storage - not an indicator of the format for what is stored in % this byte. Generally speaking, anytime a single 'char' is used, it is % probably meant to hold an 8-bit integer value, whereas if this has % been dimensioned as an array, then it is intended to hold an ASCII % character string, even if that was only a single character. % Denny <[email protected]> % Comments % The header format is flexible and can be extended for new % user-defined data types. The essential structures of the header % are the header_key and the image_dimension. % % The required elements in the header_key substructure are: % % int sizeof_header Must indicate the byte size of the header file. % int extents Should be 16384, the image file is created as % contiguous with a minimum extent size. % char regular Must be 'r' to indicate that all images and % volumes are the same size. % % The image_dimension substructure describes the organization and % size of the images. These elements enable the database to reference % images by volume and slice number. Explanation of each element follows: % % short int dim[ ]; /* Array of the image dimensions */ % % dim[0] Number of dimensions in database; usually 4. % dim[1] Image X dimension; number of pixels in an image row. % dim[2] Image Y dimension; number of pixel rows in slice. % dim[3] Volume Z dimension; number of slices in a volume. % dim[4] Time points; number of volumes in database. % dim[5] Undocumented. % dim[6] Undocumented. % dim[7] Undocumented. % % char vox_units[4] Specifies the spatial units of measure for a voxel. % char cal_units[8] Specifies the name of the calibration unit. % short int unused1 /* Unused */ % short int datatype /* Datatype for this image set */ % /*Acceptable values for datatype are*/ % #define DT_NONE 0 % #define DT_UNKNOWN 0 /*Unknown data type*/ % #define DT_BINARY 1 /*Binary ( 1 bit per voxel)*/ % #define DT_UNSIGNED_CHAR 2 /*Unsigned character ( 8 bits per voxel)*/ % #define DT_SIGNED_SHORT 4 /*Signed short (16 bits per voxel)*/ % #define DT_SIGNED_INT 8 /*Signed integer (32 bits per voxel)*/ % #define DT_FLOAT 16 /*Floating point (32 bits per voxel)*/ % #define DT_COMPLEX 32 /*Complex (64 bits per voxel; 2 floating point numbers)/* % #define DT_DOUBLE 64 /*Double precision (64 bits per voxel)*/ % #define DT_RGB 128 /*A Red-Green-Blue datatype*/ % #define DT_ALL 255 /*Undocumented*/ % % short int bitpix; /* Number of bits per pixel; 1, 8, 16, 32, or 64. */ % short int dim_un0; /* Unused */ % % float pixdim[]; Parallel array to dim[], giving real world measurements in mm and ms. % pixdim[0]; Pixel dimensions? % pixdim[1]; Voxel width in mm. % pixdim[2]; Voxel height in mm. % pixdim[3]; Slice thickness in mm. % pixdim[4]; timeslice in ms (ie, TR in fMRI). % pixdim[5]; Undocumented. % pixdim[6]; Undocumented. % pixdim[7]; Undocumented. % % float vox_offset; Byte offset in the .img file at which voxels start. This value can be % negative to specify that the absolute value is applied for every image % in the file. % % float roi_scale; Specifies the Region Of Interest scale? % float funused1; Undocumented. % float funused2; Undocumented. % % float cal_max; Specifies the upper bound of the range of calibration values. % float cal_min; Specifies the lower bound of the range of calibration values. % % int compressed; Undocumented. % int verified; Undocumented. % % int glmax; The maximum pixel value for the entire database. % int glmin; The minimum pixel value for the entire database. % %
github
lcnbeapp/beapp-master
read_stl.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_stl.m
4,432
utf_8
6aec08043b6655fd9efe5194e20bf28f
function [pnt, tri, nrm] = read_stl(filename) % READ_STL reads a triangulation from an ascii or binary *.stl file, which % is a file format native to the stereolithography CAD software created by % 3D Systems. % % Use as % [pnt, tri, nrm] = read_stl(filename) % % The format is described at http://en.wikipedia.org/wiki/STL_(file_format) % % See also WRITE_STL % Copyright (C) 2006-2011, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ fid = fopen(filename, 'rt'); % read a small section to determine whether it is ascii or binary % a binary STL file has an 80 byte asci header, followed by non-printable characters section = fread(fid, 160, 'uint8'); fseek(fid, 0, 'bof'); if printableascii(section) % the first 160 characters are printable ascii, so assume it is an ascii format % solid testsphere % facet normal -0.13 -0.13 -0.98 % outer loop % vertex 1.50000 1.50000 0.00000 % vertex 1.50000 1.11177 0.05111 % vertex 1.11177 1.50000 0.05111 % endloop % endfacet % ... ntri = 0; while ~feof(fid) line = fgetl(fid); ntri = ntri + ~isempty(findstr('facet normal', line)); end fseek(fid, 0, 'bof'); tri = zeros(ntri,3); nrm = zeros(ntri,3); pnt = zeros(ntri*3,3); line = fgetl(fid); name = sscanf(line, 'solid %s'); for i=1:ntri line1 = fgetl(fid); line2 = fgetl(fid); % outer loop line3 = fgetl(fid); line4 = fgetl(fid); line5 = fgetl(fid); line6 = fgetl(fid); % endloop line7 = fgetl(fid); % endfacet i1 = (i-1)*3+1; i2 = (i-1)*3+2; i3 = (i-1)*3+3; tri(i,:) = [i1 i2 i3]; dum = sscanf(strtrim(line1), 'facet normal %f %f %f'); nrm(i,:) = dum(:)'; dum = sscanf(strtrim(line3), 'vertex %f %f %f'); pnt(i1,:) = dum(:)'; dum = sscanf(strtrim(line4), 'vertex %f %f %f'); pnt(i2,:) = dum(:)'; dum = sscanf(strtrim(line5), 'vertex %f %f %f'); pnt(i3,:) = dum(:)'; end else % reopen the file in binary mode, which does not make a difference on % UNIX but it does on windows fclose(fid); fid = fopen(filename, 'rb'); fseek(fid, 80, 'bof'); % skip the ascii header ntri = fread(fid, 1, 'uint32'); tri = reshape(1:(ntri*3),[3 ntri])'; tmp = fread(fid, [12 ntri], '12*float32', 2); % read 12 floats at a time, and skip 2 bytes. nrm = tmp(1:3,:)'; tmp = reshape(tmp(4:end,:),[3 3 ntri]); % position info tmp = permute(tmp,[2 3 1]); pnt = reshape(tmp, [], 3); % the above replaces the below, which is much slower, because it is using % a for loop across triangles % tri = zeros(ntri,3); % nrm = zeros(ntri,3); % pnt = zeros(ntri*3,3); % attr = zeros(ntri,1); % for i=1:ntri % i1 = (i-1)*3+1; % i2 = (i-1)*3+2; % i3 = (i-1)*3+3; % tri(i,:) = [i1 i2 i3]; % nrm(i,:) = fread(fid, 3, 'float32'); % pnt(i1,:) = fread(fid, 3, 'float32'); % pnt(i2,:) = fread(fid, 3, 'float32'); % pnt(i3,:) = fread(fid, 3, 'float32'); % attr(i) = fread(fid, 1, 'uint16'); % Attribute byte count, don't know what it is % end % for each triangle end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function retval = printableascii(num) % Codes 20hex (32dec) to 7Ehex (126dec), known as the printable characters, % represent letters, digits, punctuation marks, and a few miscellaneous % symbols. There are 95 printable characters in total. num = double(num); num(num==double(sprintf('\n'))) = double(sprintf(' ')); num(num==double(sprintf('\r'))) = double(sprintf(' ')); num(num==double(sprintf('\t'))) = double(sprintf(' ')); retval = all(num>=32 & num<=126);
github
lcnbeapp/beapp-master
read_itab_mhd.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_itab_mhd.m
12,518
utf_8
d0ebd0b4e1de627d76cb523010d16ec7
function mhd = read_itab_mhd(filename) fid = fopen(filename, 'rb'); % Name of structure mhd.stname = fread(fid, [1 10], 'uint8=>char'); % Header identifier (VP_BIOMAG) mhd.stver = fread(fid, [1 8], 'uint8=>char'); % Header version mhd.stendian = fread(fid, [1 4], 'uint8=>char'); % LE (little endian) or BE (big endian) format % Subject's INFOs mhd.first_name = fread(fid, [1 32], 'uint8=>char'); % Subject's first name mhd.last_name = fread(fid, [1 32], 'uint8=>char'); % Subject's family name mhd.id = fread(fid, [1 32], 'uint8=>char'); % Subject's id mhd.notes = fread(fid, [1 256], 'uint8=>char'); % Notes on measurement % Other subj infos mhd.subj_info.sex = fread(fid, [1 1], 'uint8=>char'); % Sex (M or F) pad = fread(fid, [1 5], 'uint8'); mhd.subj_info.notes = fread(fid, [1 256], 'uint8=>char'); % Notes on subject mhd.subj_info.height = fread(fid, [1 1], 'float'); % Height in cm mhd.subj_info.weight = fread(fid, [1 1], 'float'); % Weight in kg mhd.subj_info.birthday = fread(fid, [1 1], 'int32'); % Birtday (1-31) mhd.subj_info.birthmonth = fread(fid, [1 1], 'int32'); % Birthmonth (1-12) mhd.subj_info.birthyear = fread(fid, [1 1], 'int32'); % Birthyear (1900-2002) % Data acquisition INFOs mhd.time = fread(fid, [1 12], 'uint8=>char'); % time (ascii) mhd.date = fread(fid, [1 16], 'uint8=>char'); % date (ascii) mhd.nchan = fread(fid, [1 1], 'int32'); % total number of channels mhd.nelech = fread(fid, [1 1], 'int32'); % number of electric channels mhd.nelerefch = fread(fid, [1 1], 'int32'); % number of electric reference channels mhd.nmagch = fread(fid, [1 1], 'int32'); % number of magnetic channels mhd.nmagrefch = fread(fid, [1 1], 'int32'); % number of magnetic reference channels mhd.nauxch = fread(fid, [1 1], 'int32'); % number of auxiliary channels mhd.nparamch = fread(fid, [1 1], 'int32'); % number of parameter channels mhd.ndigitch = fread(fid, [1 1], 'int32'); % number of digit channels mhd.nflagch = fread(fid, [1 1], 'int32'); % number of flag channels mhd.data_type = fread(fid, [1 1], 'int32'); % 0 - BE_SHORT (HP-PA, big endian) % 1 - BE_LONG (HP-PA, big endian) % 2 - BE_FLOAT (HP-PA, big endian) % 3 - LE_SHORT (Intel, little endian) % 4 - LE_LONG (Intel, little endian) % 5 - LE_FLOAT (Intel, little endian) % 6 - RTE_A_SHORT (HP-A900, big endian) % 7 - RTE_A_FLOAT (HP-A900, big endian) % 8 - ASCII mhd.smpfq = fread(fid, [1 1], 'single'); % sampling frequency in Hz mhd.hw_low_fr = fread(fid, [1 1], 'single'); % hw data acquisition low pass filter mhd.hw_hig_fr = fread(fid, [1 1], 'single'); % hw data acquisition high pass filter mhd.hw_comb = fread(fid, [1 1], 'int32'); % hw data acquisition 50 Hz filter (1-TRUE) mhd.sw_hig_tc = fread(fid, [1 1], 'single'); % sw data acquisition high pass time constant mhd.compensation= fread(fid, [1 1], 'int32'); % 0 - no compensation 1 - compensation mhd.ntpdata = fread(fid, [1 1], 'int32'); % total number of time points in data mhd.no_segments = fread(fid, [1 1], 'int32'); % Number of segments described in the segment structure % INFOs on different segments for i=1:5 mhd.sgmt(i).start = fread(fid, [1 1], 'int32'); % Starting time point from beginning of data mhd.sgmt(i).ntptot = fread(fid, [1 1], 'int32'); % Total number of time points mhd.sgmt(i).type = fread(fid, [1 1], 'int32'); mhd.sgmt(i).no_samples = fread(fid, [1 1], 'int32'); mhd.sgmt(i).st_sample = fread(fid, [1 1], 'int32'); end mhd.nsmpl = fread(fid, [1 1], 'int32'); % Overall number of samples % INFOs on different samples for i=1:4096 mhd.smpl(i).start = fread(fid, [1 1], 'int32'); % Starting time point from beginning of data mhd.smpl(i).ntptot = fread(fid, [1 1], 'int32'); % Total number of time points mhd.smpl(i).ntppre = fread(fid, [1 1], 'int32'); % Number of points in pretrigger mhd.smpl(i).type = fread(fid, [1 1], 'int32'); mhd.smpl(i).quality = fread(fid, [1 1], 'int32'); end mhd.nrefchan = fread(fid, [1 1], 'int32'); % number of reference channels mhd.ref_ch = fread(fid, [1 640], 'int32'); % reference channel list mhd.ntpref = fread(fid, [1 1], 'int32'); % total number of time points in reference % Header INFOs mhd.raw_header_type = fread(fid, [1 1], 'int32'); % 0 - Unknown header % 2 - rawfile (A900) % 3 - GE runfile header % 31 - ATB runfile header version 1.0 % 41 - IFN runfile header version 1.0 % 51 - BMDSys runfile header version 1.0 mhd.header_type = fread(fid, [1 1], 'int32'); % 0 - Unknown header % 2 - rawfile (A900) % 3 - GE runfile header % 4 - old header % 10 - 256ch normal header % 11 - 256ch master header % 20 - 640ch normal header % 21 - 640ch master header % 31 - ATB runfile header version 1.0 % 41 - IFN runfile header version 1.0 % 51 - BMDSys runfile header version 1.0 mhd.conf_file = fread(fid, [1 64], 'uint8=>char'); % Filename used for data acquisition configuration mhd.header_size = fread(fid, [1 1], 'int32'); % sizeof(header) at the time of file creation mhd.start_reference = fread(fid, [1 1], 'int32'); % start reference mhd.start_data = fread(fid, [1 1], 'int32'); % start data mhd.rawfile = fread(fid, [1 1], 'int32'); % 0 - not a rawfile 1 - rawfile mhd.multiplexed_data = fread(fid, [1 1], 'int32'); % 0 - FALSE 1 - TRUE mhd.isns = fread(fid, [1 1], 'int32'); % sensor code 1 - Single channel % 28 - Original Rome 28 ch. % 29 - .............. % .. - .............. % 45 - Updated Rome 28 ch. (spring 2009) % .. - .............. % .. - .............. % 55 - Original Chieti 55 ch. flat % 153 - Original Chieti 153 ch. helmet % 154 - Chieti 153 ch. helmet from Jan 2002 % Channel's INFOs for i=1:640 mhd.ch(i).type = fread(fid, [1 1], 'uint8'); pad = fread(fid, [1 3], 'uint8'); % type 0 - unknown % 1 - ele % 2 - mag % 4 - ele ref % 8 - mag ref % 16 - aux % 32 - param % 64 - digit % 128 - flag mhd.ch(i).number = fread(fid, [1 1], 'int32'); % number mhd.ch(i).label = fixstr(fread(fid, [1 16], 'uint8=>char')); % label mhd.ch(i).flag = fread(fid, [1 1], 'uint8'); pad = fread(fid, [1 3], 'uint8'); % on/off flag 0 - working channel % 1 - noisy channel % 2 - very noisy channel % 3 - broken channel mhd.ch(i).amvbit = fread(fid, [1 1], 'float'); % calibration from LSB to mV mhd.ch(i).calib = fread(fid, [1 1], 'float'); % calibration from mV to unit mhd.ch(i).unit = fread(fid, [1 6], 'uint8=>char'); % unit label (fT, uV, ...) pad = fread(fid, [1 2], 'uint8'); mhd.ch(i).ncoils = fread(fid, [1 1], 'int32'); % number of coils building up one channel mhd.ch(i).wgt = fread(fid, [1 10], 'float'); % weight of coils % position and orientation of coils for j=1:10 mhd.ch(i).position(j).r_s = fread(fid, [1 3], 'float'); mhd.ch(i).position(j).u_s = fread(fid, [1 3], 'float'); end end % Sensor position INFOs mhd.r_center = fread(fid, [1 3], 'float'); % sensor position in convenient format mhd.u_center = fread(fid, [1 3], 'float'); mhd.th_center = fread(fid, [1 1], 'float'); % sensor orientation as from markers fit mhd.fi_center= fread(fid, [1 1], 'float'); mhd.rotation_angle= fread(fid, [1 1], 'float'); mhd.cosdir = fread(fid, [3 3], 'float'); % for compatibility only mhd.irefsys = fread(fid, [1 1], 'int32'); % reference system 0 - sensor reference system % 1 - Polhemus % 2 - head3 % 3 - MEG % Marker positions for MRI integration mhd.num_markers = fread(fid, [1 1], 'int32'); % Total number of markers mhd.i_coil = fread(fid, [1 64], 'int32'); % Markers to be used to find sensor position mhd.marker = fread(fid, [3 64], 'float'); % Position of all the markers - MODIFIED VP mhd.best_chi = fread(fid, [1 1], 'float'); % Best chi_square value obtained in finding sensor position mhd.cup_vertex_center = fread(fid, [1 1], 'float'); % dist anc sensor cente vertex (as entered % from keyboard) mhd.cup_fi_center = fread(fid, [1 1], 'float'); % fi angle of sensor center mhd.cup_rotation_angle = fread(fid, [1 1], 'float'); % rotation angle of sensor center axis mhd.dist_a1_a2 = fread(fid, [1 1], 'float'); % head informations % (used to find subject's head dimensions) mhd.dist_inion_nasion = fread(fid, [1 1], 'float'); mhd.max_circ = fread(fid, [1 1], 'float'); mhd.nasion_vertex_inion = fread(fid, [1 1], 'float'); % Data analysis INFOs mhd.security = fread(fid, [1 1], 'int32'); % security flag mhd.ave_alignement = fread(fid, [1 1], 'int32'); % average data alignement 0 - FALSE % 1 - TRUE mhd.itri = fread(fid, [1 1], 'int32'); % trigger channel number mhd.ntpch = fread(fid, [1 1], 'int32'); % no. of time points per channel mhd.ntppre = fread(fid, [1 1], 'int32'); % no. of time points of pretrigger mhd.navrg = fread(fid, [1 1], 'int32'); % no. of averages mhd.nover = fread(fid, [1 1], 'int32'); % no. of discarded averages mhd.nave_filt = fread(fid, [1 1], 'int32'); % no. of applied filters % Filters used before average for i=1:15 mhd.ave_filt(i).type = fread(fid, [1 1], 'int32'); % type 0 - no filter % 1 - bandpass - param[0]: highpass freq % - param[1]: lowpass freq % 2 - notch - param[0]: notch freq 1 % param[1]: notch freq 2 % param[2]: notch freq 3 % param[3]: notch freq 4 % param[4]: span % 3 - artifact - param[0]: True/False % 4 - adaptive - param[0]: True/False % 5 - rectifier - param[0]: True/False % 6 - heart - param[0]: True/False % 7 - evoked - param[0]: True/False % 8 - derivate - param[0]: True/False % 9 - polarity - param[0]: True/False mhd.ave_filt(i).param = fread(fid, [1 5], 'float'); % up to 5 filter parameters end mhd.stdev = fread(fid, [1 1], 'int32'); % 0 - not present mhd.bas_start = fread(fid, [1 1], 'int32'); % starting data points for baseline mhd.bas_end = fread(fid, [1 1], 'int32'); % ending data points for baseline mhd.source_files = fread(fid, [1 32], 'int32'); % Progressive number of files (if more than one) % template INFOs mhd.ichtpl = fread(fid, [1 1], 'int32'); mhd.ntptpl = fread(fid, [1 1], 'int32'); mhd.ifitpl = fread(fid, [1 1], 'int32'); mhd.corlim = fread(fid, [1 1], 'float'); % Filters used before template for i=1:15 mhd.tpl_filt(i).type = fread(fid, [1 1], 'int32'); % type 0 - no filter % 1 - bandpass - param[0]: highpass freq % - param[1]: lowpass freq % 2 - notch - param[0]: notch freq 1 % param[1]: notch freq 2 % param[2]: notch freq 3 % param[3]: notch freq 4 % param[4]: span % 3 - artifact - param[0]: True/False % 4 - adaptive - param[0]: True/False % 5 - rectifier - param[0]: True/False % 6 - heart - param[0]: True/False % 7 - evoked - param[0]: True/False % 8 - derivate - param[0]: True/False % 9 - polarity - param[0]: True/False mhd.tpl_filt(i).param = fread(fid, [1 5], 'float'); % up to 5 filter parameters end % Just in case info mhd.dummy = fread(fid, [1 64], 'int32'); % there seems to be more dummy data at the end... fclose(fid); function str = fixstr(str) sel = find(str==0, 1, 'first'); if ~isempty(sel) str = str(1:sel-1); end
github
lcnbeapp/beapp-master
read_plexon_plx.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_plexon_plx.m
20,283
utf_8
ec115cb91003e60359655fdd73fdfdb6
function [varargout] = read_plexon_plx(filename, varargin) % READ_PLEXON_PLX reads header or data from a Plexon *.plx file, which % is a file containing action-potential (spike) timestamps and waveforms % (spike channels), event timestamps (event channels), and continuous % variable data (continuous A/D channels). % % Use as % [hdr] = read_plexon_plx(filename) % [dat] = read_plexon_plx(filename, ...) % [dat1, dat2, dat3, hdr] = read_plexon_plx(filename, ...) % % Optional input arguments should be specified in key-value pairs % 'header' = structure with header information % 'memmap' = 0 or 1 % 'feedback' = 0 or 1 % 'ChannelIndex' = number, or list of numbers (that will result in multiple outputs) % 'SlowChannelIndex' = number, or list of numbers (that will result in multiple outputs) % 'EventIndex' = number, or list of numbers (that will result in multiple outputs) % Copyright (C) 2007-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % parse the optional input arguments hdr = ft_getopt(varargin, 'header'); memmap = ft_getopt(varargin, 'memmap', false); feedback = ft_getopt(varargin, 'feedback', true); ChannelIndex = ft_getopt(varargin, 'ChannelIndex'); % type 1 EventIndex = ft_getopt(varargin, 'EventIndex'); % type 4 SlowChannelIndex = ft_getopt(varargin, 'SlowChannelIndex'); % type 5 needhdr = isempty(hdr); % start with empty return values varargout = {}; % the datafile is little endian, hence it may be neccessary to swap bytes in % the memory mapped data stream depending on the CPU type of this computer if littleendian swapFcn = @(x) x; else swapFcn = @(x) swapbytes(x); end % read header info from file, use Matlabs for automatic byte-ordering fid = fopen(filename, 'r', 'ieee-le'); fseek(fid, 0, 'eof'); siz = ftell(fid); fseek(fid, 0, 'bof'); if needhdr if feedback, fprintf('reading header from %s\n', filename); end % a PLX file consists of a file header, channel headers, and data blocks hdr = PL_FileHeader(fid); for i=1:hdr.NumDSPChannels hdr.ChannelHeader(i) = PL_ChannelHeader(fid); end for i=1:hdr.NumEventChannels hdr.EventHeader(i) = PL_EventHeader(fid); end for i=1:hdr.NumSlowChannels hdr.SlowChannelHeader(i) = PL_SlowChannelHeader(fid); end hdr.DataOffset = ftell(fid); if memmap % open the file as meory mapped object, note that byte swapping may be needed mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16'); end dum = struct(... 'Type', [],... 'UpperByteOf5ByteTimestamp', [],... 'TimeStamp', [],... 'Channel', [],... 'Unit', [],... 'NumberOfWaveforms', [],... 'NumberOfWordsInWaveform', [] ... ); % read the header of each data block and remember its data offset in bytes Nblocks = 0; offset = hdr.DataOffset; % only used when reading from memmapped file hdr.DataBlockOffset = []; hdr.DataBlockHeader = dum; while offset<siz if Nblocks>=length(hdr.DataBlockOffset); % allocate another 1000 elements, this prevents continuous reallocation hdr.DataBlockOffset(Nblocks+10000) = 0; hdr.DataBlockHeader(Nblocks+10000) = dum; if feedback, fprintf('reading DataBlockHeader %4.1f%%\n', 100*(offset-hdr.DataOffset)/(siz-hdr.DataOffset)); end end Nblocks = Nblocks+1; if memmap % get the header information from the memory mapped file hdr.DataBlockOffset(Nblocks) = offset; hdr.DataBlockHeader(Nblocks) = PL_DataBlockHeader(mm, offset-hdr.DataOffset, swapFcn); % skip the header (16 bytes) and the data (int16 words) offset = offset + 16 + 2 * double(hdr.DataBlockHeader(Nblocks).NumberOfWordsInWaveform * hdr.DataBlockHeader(Nblocks).NumberOfWaveforms); else % read the header information from the file the traditional way hdr.DataBlockOffset(Nblocks) = offset; hdr.DataBlockHeader(Nblocks) = PL_DataBlockHeader(fid, [], swapFcn); fseek(fid, 2 * double(hdr.DataBlockHeader(Nblocks).NumberOfWordsInWaveform * hdr.DataBlockHeader(Nblocks).NumberOfWaveforms), 'cof'); % data consists of short integers offset = ftell(fid); end % if memmap end % this prints the final 100% if feedback, fprintf('reading DataBlockHeader %4.1f%%\n', 100*(offset-hdr.DataOffset)/(siz-hdr.DataOffset)); end % remove the allocated space that was not needed hdr.DataBlockOffset = hdr.DataBlockOffset(1:Nblocks); hdr.DataBlockHeader = hdr.DataBlockHeader(1:Nblocks); end % if needhdr %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the spike channel data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(ChannelIndex) if feedback, fprintf('reading spike data from %s\n', filename); end if memmap % open the file as meory mapped object, note that byte swapping may be needed mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16'); end type = [hdr.DataBlockHeader.Type]; chan = [hdr.DataBlockHeader.Channel]; ts = [hdr.DataBlockHeader.TimeStamp]; for i=1:length(ChannelIndex) % determine the data blocks with continuous data belonging to this channel sel = (type==1 & chan==hdr.ChannelHeader(ChannelIndex(i)).Channel); sel = find(sel); if isempty(sel) warning('spike channel %d contains no data', ChannelIndex(i)); varargin{end+1} = []; continue; end % the number of samples can potentially be different in each block num = double([hdr.DataBlockHeader(sel).NumberOfWordsInWaveform]) .* double([hdr.DataBlockHeader(sel).NumberOfWaveforms]); % check whether the number of samples per block makes sense if any(num~=num(1)) error('spike channel blocks with diffent number of samples'); end % allocate memory to hold the data buf = zeros(num(1), length(sel), 'int16'); if memmap % get the header information from the memory mapped file datbeg = double(hdr.DataBlockOffset(sel) - hdr.DataOffset)/2 + 8 + 1; % expressed in 2-byte words, minus the file header, skip the 16 byte block header datend = datbeg + num - 1; for j=1:length(sel) buf(:,j) = mm.Data(datbeg(j):datend(j)); end % optionally swap the bytes to correct for the endianness buf = swapFcn(buf); else % read the data from the file in the traditional way offset = double(hdr.DataBlockOffset(sel)) + 16; % expressed in bytes, skip the 16 byte block header for j=1:length(sel) fseek(fid, offset(j), 'bof'); buf(:,j) = fread(fid, num(j), 'int16'); end end % if memmap % remember the data for this channel varargout{i} = buf; end %for ChannelIndex end % if ChannelIndex %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the continuous channel data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(SlowChannelIndex) if feedback, fprintf('reading continuous data from %s\n', filename); end if memmap % open the file as meory mapped object, note that byte swapping may be needed mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16'); end type = [hdr.DataBlockHeader.Type]; chan = [hdr.DataBlockHeader.Channel]; ts = [hdr.DataBlockHeader.TimeStamp]; for i=1:length(SlowChannelIndex) % determine the data blocks with continuous data belonging to this channel sel = (type==5 & chan==hdr.SlowChannelHeader(SlowChannelIndex(i)).Channel); sel = find(sel); if isempty(sel) error(sprintf('Continuous channel %d contains no data', SlowChannelIndex(i))); % warning('Continuous channel %d contains no data', SlowChannelIndex(i)); % varargin{end+1} = []; % continue; end % the number of samples can be different in each block num = double([hdr.DataBlockHeader(sel).NumberOfWordsInWaveform]) .* double([hdr.DataBlockHeader(sel).NumberOfWaveforms]); cumnum = cumsum([0 num]); % allocate memory to hold the data buf = zeros(1, cumnum(end), 'int16'); if memmap % get the header information from the memory mapped file datbeg = double(hdr.DataBlockOffset(sel) - hdr.DataOffset)/2 + 8 + 1; % expressed in 2-byte words, minus the file header, skip the 16 byte block header datend = datbeg + num - 1; for j=1:length(sel) bufbeg = cumnum(j)+1; bufend = cumnum(j+1); % copy the data from the memory mapped file into the continuous buffer buf(bufbeg:bufend) = mm.Data(datbeg(j):datend(j)); end % optionally swap the bytes to correct for the endianness buf = swapFcn(buf); else % read the data from the file in the traditional way offset = double(hdr.DataBlockOffset(sel)) + 16; % expressed in bytes, skip the 16 byte block header for j=1:length(sel) bufbeg = cumnum(j)+1; bufend = cumnum(j+1); % copy the data from the file into the continuous buffer fseek(fid, offset(j), 'bof'); buf(bufbeg:bufend) = fread(fid, num(j), 'int16'); end end % if memmap % remember the data for this channel varargout{i} = buf; end %for SlowChannelIndex end % if SlowChannelIndex %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the event channel data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(EventIndex) if feedback, fprintf('reading events from %s\n', filename); end type = [hdr.DataBlockHeader.Type]; unit = [hdr.DataBlockHeader.Unit]; chan = [hdr.DataBlockHeader.Channel]; ts = [hdr.DataBlockHeader.TimeStamp]; for i=1:length(EventIndex) % determine the data blocks with continuous data belonging to this channel sel = (type==4 & chan==hdr.EventHeader(EventIndex(i)).Channel); sel = find(sel); % all information is already contained in the DataBlockHeader, i.e. there is nothing to read if isempty(sel) warning('event channel %d contains no data', EventIndex(i)); end event.TimeStamp = ts(sel); event.Channel = chan(sel); event.Unit = unit(sel); varargout{i} = event; end % for EventIndex end % if EventIndex fclose(fid); % always return the header as last varargout{end+1} = hdr; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS for reading the different header elements %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = PL_FileHeader(fid) hdr.MagicNumber = fread(fid, 1, 'uint32=>uint32'); % = 0x58454c50; hdr.Version = fread(fid, 1, 'int32' ); % Version of the data format; determines which data items are valid hdr.Comment = fread(fid, [1 128], 'uint8=>char' ); % User-supplied comment hdr.ADFrequency = fread(fid, 1, 'int32' ); % Timestamp frequency in hertz hdr.NumDSPChannels = fread(fid, 1, 'int32' ); % Number of DSP channel headers in the file hdr.NumEventChannels = fread(fid, 1, 'int32' ); % Number of Event channel headers in the file hdr.NumSlowChannels = fread(fid, 1, 'int32' ); % Number of A/D channel headers in the file hdr.NumPointsWave = fread(fid, 1, 'int32' ); % Number of data points in waveform hdr.NumPointsPreThr = fread(fid, 1, 'int32' ); % Number of data points before crossing the threshold hdr.Year = fread(fid, 1, 'int32' ); % Time/date when the data was acquired hdr.Month = fread(fid, 1, 'int32' ); hdr.Day = fread(fid, 1, 'int32' ); hdr.Hour = fread(fid, 1, 'int32' ); hdr.Minute = fread(fid, 1, 'int32' ); hdr.Second = fread(fid, 1, 'int32' ); hdr.FastRead = fread(fid, 1, 'int32' ); % reserved hdr.WaveformFreq = fread(fid, 1, 'int32' ); % waveform sampling rate; ADFrequency above is timestamp freq hdr.LastTimestamp = fread(fid, 1, 'double'); % duration of the experimental session, in ticks % The following 6 items are only valid if Version >= 103 hdr.Trodalness = fread(fid, 1, 'char' ); % 1 for single, 2 for stereotrode, 4 for tetrode hdr.DataTrodalness = fread(fid, 1, 'char' ); % trodalness of the data representation hdr.BitsPerSpikeSample = fread(fid, 1, 'char' ); % ADC resolution for spike waveforms in bits (usually 12) hdr.BitsPerSlowSample = fread(fid, 1, 'char' ); % ADC resolution for slow-channel data in bits (usually 12) hdr.SpikeMaxMagnitudeMV = fread(fid, 1, 'uint16'); % the zero-to-peak voltage in mV for spike waveform adc values (usually 3000) hdr.SlowMaxMagnitudeMV = fread(fid, 1, 'uint16'); % the zero-to-peak voltage in mV for slow-channel waveform adc values (usually 5000); Only valid if Version >= 105 (usually either 1000 or 500) % The following item is only valid if Version >= 105 hdr.SpikePreAmpGain = fread(fid, 1, 'uint16'); % so that this part of the header is 256 bytes hdr.Padding = fread(fid, 46, 'char' ); % so that this part of the header is 256 bytes % Counters for the number of timestamps and waveforms in each channel and unit. % Note that these only record the counts for the first 4 units in each channel. % channel numbers are 1-based - array entry at [0] is unused hdr.TSCounts = fread(fid, [5 130], 'int32' ); % number of timestamps[channel][unit] hdr.WFCounts = fread(fid, [5 130], 'int32' ); % number of waveforms[channel][unit] % Starting at index 300, the next array also records the number of samples for the % continuous channels. Note that since EVCounts has only 512 entries, continuous % channels above channel 211 do not have sample counts. hdr.EVCounts = fread(fid, 512, 'int32' ); % number of timestamps[event_number] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = PL_ChannelHeader(fid) hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % Name given to the DSP channel hdr.SIGName = fread(fid, [1 32], 'uint8=>char' ); % Name given to the corresponding SIG channel hdr.Channel = fread(fid, 1, 'int32' ); % DSP channel number, 1-based hdr.WFRate = fread(fid, 1, 'int32' ); % When MAP is doing waveform rate limiting, this is limit w/f per sec divided by 10 hdr.SIG = fread(fid, 1, 'int32' ); % SIG channel associated with this DSP channel 1 - based hdr.Ref = fread(fid, 1, 'int32' ); % SIG channel used as a Reference signal, 1- based hdr.Gain = fread(fid, 1, 'int32' ); % actual gain divided by SpikePreAmpGain. For pre version 105, actual gain divided by 1000. hdr.Filter = fread(fid, 1, 'int32' ); % 0 or 1 hdr.Threshold = fread(fid, 1, 'int32' ); % Threshold for spike detection in a/d values hdr.Method = fread(fid, 1, 'int32' ); % Method used for sorting units, 1 - boxes, 2 - templates hdr.NUnits = fread(fid, 1, 'int32' ); % number of sorted units hdr.Template = fread(fid, [64 5], 'int16' ); % Templates used for template sorting, in a/d values hdr.Fit = fread(fid, 5, 'int32' ); % Template fit hdr.SortWidth = fread(fid, 1, 'int32' ); % how many points to use in template sorting (template only) hdr.Boxes = reshape(fread(fid, 4*2*5, 'int16' ), [4 2 5]); % the boxes used in boxes sorting hdr.SortBeg = fread(fid, 1, 'int32' ); % beginning of the sorting window to use in template sorting (width defined by SortWidth) hdr.Comment = fread(fid, [1 128], 'uint8=>char' ); hdr.Padding = fread(fid, 11, 'int32' ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = PL_EventHeader(fid) hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % name given to this event hdr.Channel = fread(fid, 1, 'int32' ); % event number, 1-based hdr.Comment = fread(fid, [1 128], 'uint8=>char' ); hdr.Padding = fread(fid, 33, 'int32' ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = PL_SlowChannelHeader(fid) hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % name given to this channel hdr.Channel = fread(fid, 1, 'int32' ); % channel number, 0-based hdr.ADFreq = fread(fid, 1, 'int32' ); % digitization frequency hdr.Gain = fread(fid, 1, 'int32' ); % gain at the adc card hdr.Enabled = fread(fid, 1, 'int32' ); % whether this channel is enabled for taking data, 0 or 1 hdr.PreAmpGain = fread(fid, 1, 'int32' ); % gain at the preamp % As of Version 104, this indicates the spike channel (PL_ChannelHeader.Channel) of % a spike channel corresponding to this continuous data channel. % <=0 means no associated spike channel. hdr.SpikeChannel = fread(fid, 1, 'int32' ); hdr.Comment = fread(fid, [1 128], 'uint8=>char' ); hdr.Padding = fread(fid, 28, 'int32' ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = PL_DataBlockHeader(fid, offset, swapFcn) % % this is the conventional code, it has been replaced by code that works % % with both regular and memmapped files % hdr.Type = fread(fid, 1, 'int16=>int16' ); % Data type; 1=spike, 4=Event, 5=continuous % hdr.UpperByteOf5ByteTimestamp = fread(fid, 1, 'uint16=>uint16' ); % Upper 8 bits of the 40 bit timestamp % hdr.TimeStamp = fread(fid, 1, 'uint32=>uint32' ); % Lower 32 bits of the 40 bit timestamp % hdr.Channel = fread(fid, 1, 'int16=>int16' ); % Channel number % hdr.Unit = fread(fid, 1, 'int16=>int16' ); % Sorted unit number; 0=unsorted % hdr.NumberOfWaveforms = fread(fid, 1, 'int16=>int16' ); % Number of waveforms in the data to folow, usually 0 or 1 % hdr.NumberOfWordsInWaveform = fread(fid, 1, 'int16=>int16' ); % Number of samples per waveform in the data to follow if isa(fid, 'memmapfile') mm = fid; datbeg = offset/2 + 1; % the offset is in bytes (minus the file header), the memory mapped file is indexed in int16 words datend = offset/2 + 8; buf = mm.Data(datbeg:datend); else buf = fread(fid, 8, 'int16=>int16'); end hdr.Type = swapFcn(buf(1)); hdr.UpperByteOf5ByteTimestamp = swapFcn(uint16(buf(2))); hdr.TimeStamp = swapFcn(typecast(buf([3 4]), 'uint32')); hdr.Channel = swapFcn(buf(5)); hdr.Unit = swapFcn(buf(6)); hdr.NumberOfWaveforms = swapFcn(buf(7)); hdr.NumberOfWordsInWaveform = swapFcn(buf(8));
github
lcnbeapp/beapp-master
read_neurosim_evolution.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_neurosim_evolution.m
4,493
utf_8
611253a932a6acc90c0b61a442dc58a5
function [hdr, dat] = read_neurosim_evolution(filename, varargin) % READ_NEUROSIM_EVOLUTION reads the "evolution" file that is written % by Jan van der Eerden's NeuroSim software. When a directory is used % as input, the default filename 'evolution' is read. % % Use as % [hdr, dat] = read_neurosim_evolution(filename, ...) % where additional options should come in key-value pairs and can include % Vonly = 0 or 1, only give the membrane potentials as output % headerOnly = 0 or 1, only read the header information (skip the data), automatically set to 1 if nargout==1 % % See also FT_READ_HEADER, FT_READ_DATA % Copyright (C) 2012 Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if isdir(filename) filename = fullfile(filename, 'evolution'); end Vonly = ft_getopt(varargin, 'Vonly',0); headerOnly = ft_getopt(varargin, 'headerOnly',0); if nargout<2 % make sure that when only one output is requested the header is returned headerOnly=true; end label = {}; orig = {}; fid = fopen(filename, 'rb'); % read the header line = '#'; ishdr=1; while ishdr==1 % find temporal information if strfind(lower(line),'start time') dum= regexp(line, 'time\s+(\d+.\d+E[+-]\d+)', 'tokens'); hdr.FirstTimeStamp = str2double(dum{1}{1}); end if strfind(lower(line),'time bin') dum= regexp(line, 'bin\s+(\d+.\d+E[+-]\d+)', 'tokens'); dt=str2double(dum{1}{1}); hdr.Fs= 1e3/dt; hdr.TimeStampPerSample=dt; end if strfind(lower(line),'end time') dum= regexp(line, 'time\s+(\d+.\d+E[+-]\d+)', 'tokens'); hdr.LastTimeStamp = str2double(dum{1}{1}); hdr.nSamples=int64((hdr.LastTimeStamp-hdr.FirstTimeStamp)/dt+1); end % parse the content of the line, determine the label for each column colid = sscanf(line, '# column %d:', 1); if ~isempty(colid) label{colid} = [num2str(colid) rmspace(line(find(line==':'):end))]; end offset = ftell(fid); % remember the file pointer position line = fgetl(fid); % get the next line if ~isempty(line) && line(1)~='#' && ~isempty(str2num(line)) % the data starts here, rewind the last line fseek(fid, offset, 'bof'); line = []; ishdr=0; else orig{end+1} = line; end end timelab=find(~cellfun('isempty',regexp(lower(label), 'time', 'match'))); if ~headerOnly % read the complete data dat = fscanf(fid, '%f', [length(label), inf]); hdr.nSamples = length(dat(timelab, :)); %overwrites the value written in the header with the actual number of samples found hdr.LastTimeStamp = dat(1,end); end fclose(fid); % only extract V_membrane if wanted if Vonly matchLab=regexp(label,'V of (\S+) neuron','start'); idx=find(~cellfun(@isempty,matchLab)); if isempty(idx) % most likely a multi compartment simulation matchLab=regexp(label,'V\S+ of (\S+) neuron','start'); idx=find(~cellfun(@isempty,matchLab)); end if ~headerOnly dat=dat([timelab idx],:); end label=label([timelab idx]); for n=2:length(label) % renumbering of the labels label{n}=[num2str(n) label{n}(regexp(label{n},': V'):end)]; end end % convert the header into FieldTrip style hdr.label = label(:); hdr.nChans = length(label); hdr.nSamplesPre = 0; hdr.nTrials = 1; % also store the original ascii header details hdr.orig = orig(:); [hdr.chanunit hdr.chantype] = deal(cell(length(label),1)); hdr.chantype(:) = {'evolution (neurosim)'}; hdr.chanunit(:) = {'unknown'}; function y=rmspace(x) % remove double spaces from string % (c) Bart Gips 2012 y=strtrim(x); [sbeg send]=regexp(y,' \s+'); for n=1:length(sbeg) y(sbeg(n):send(n)-1)=[]; end
github
lcnbeapp/beapp-master
read_eeglabevent.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_eeglabevent.m
3,698
utf_8
d48c0efc8368b120e96562164a153a88
% read_eeglabevent() - import EEGLAB dataset events % % Usage: % >> event = read_eeglabevent(filename, ...); % % Inputs: % filename - [string] file name % % Optional inputs: % 'header' - FILEIO structure header % % Outputs: % event - FILEIO toolbox event structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2008- %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function event = read_eeglabevent(filename, varargin) if nargin < 1 help read_eeglabheader; return; end; hdr = ft_getopt(varargin, 'header'); if isempty(hdr) hdr = read_eeglabheader(filename); end event = []; % these will be the output in FieldTrip format oldevent = hdr.orig.event; % these are in EEGLAB format if ~isempty(oldevent) nameList=fieldnames(oldevent); else nameList=[]; end; nameList=setdiff(nameList,{'type','value','sample','offset','duration','latency'}); for index = 1:length(oldevent) if isfield(oldevent,'code') type = oldevent(index).code; elseif isfield(oldevent,'value') type = oldevent(index).value; else type = 'trigger'; end; % events can have a numeric or a string value if isfield(oldevent,'type') value = oldevent(index).type; else value = 'default'; end; % this is the sample number of the concatenated data to which the event corresponds sample = oldevent(index).latency; % a non-zero offset only applies to trial-events, i.e. in case the data is % segmented and each data segment needs to be represented as event. In % that case the offset corresponds to the baseline duration (times -1). offset = 0; if isfield(oldevent, 'duration') duration = oldevent(index).duration; else duration = 0; end; % add the current event in FieldTrip format event(index).type = type; % this is usually a string, e.g. 'trigger' or 'trial' event(index).value = value; % in case of a trigger, this is the value event(index).sample = sample; % this is the sample in the datafile at which the event happens event(index).offset = offset; % some events should be represented with a shifted time-axix, e.g. a trial with a baseline period event(index).duration = duration; % some events have a duration, such as a trial %add custom fields for iField=1:length(nameList) eval(['event(index).' nameList{iField} '=oldevent(index).' nameList{iField} ';']); end; end; if hdr.nTrials>1 % add the trials to the event structure for i=1:hdr.nTrials event(end+1).type = 'trial'; event(end ).sample = (i-1)*hdr.nSamples + 1; if isfield(oldevent,'setname') && (length(oldevent) == hdr.nTrials) event(end ).value = oldevent(i).setname; %accommodate Widmann's pop_grandaverage function else event(end ).value = []; end; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; end end
github
lcnbeapp/beapp-master
read_bti_ascii.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_bti_ascii.m
2,240
utf_8
560f3413b1fc96661f8ed42823efdc13
function [file] = read_bti_ascii(filename) % READ_BTI_ASCII reads general data from a BTI configuration file % % The file should be formatted like % Group: % item1 : value1a value1b value1c % item2 : value2a value2b value2c % item3 : value3a value3b value3c % item4 : value4a value4b value4c % % Copyright (C) 2004, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ fid = fopen(filename, 'r'); if fid==-1 error(sprintf('could not open file %s', filename)); end line = ''; while ischar(line) line = cleanline(fgetl(fid)) if isempty(line) | line==-1 | isempty(findstr(line, ':')) continue end % the line is not empty, which means that we have encountered a chunck of information if findstr(line, ':')~=length(line) [item, value] = strtok(line, ':'); value(1) = ' '; % remove the : value = strtrim(value); item = strtrim(item); item(findstr(item, '.')) = '_'; item(findstr(item, ' ')) = '_'; if ischar(item) eval(sprintf('file.%s = ''%s'';', item, value)); else eval(sprintf('file.%s = %s;', item, value)); end else subline = cleanline(fgetl(fid)); error, the rest has not been implemented (yet) end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function line = cleanline(line) if isempty(line) | line==-1 return end comment = findstr(line, '//'); if ~isempty(comment) line(min(comment):end) = ' '; end line = strtrim(line);
github
lcnbeapp/beapp-master
openbdf.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/openbdf.m
6,812
utf_8
cb49358a2a955b165a5c50127c25e3d8
% openbdf() - Opens an BDF File (European Data Format for Biosignals) in MATLAB (R) % % Usage: % >> EDF=openedf(FILENAME) % % Note: About EDF -> www.biosemi.com/faq/file_format.htm % % Author: Alois Schloegl, 5.Nov.1998 % % See also: readedf() % Copyright (C) 1997-1998 by Alois Schloegl % [email protected] % Ver 2.20 18.Aug.1998 % Ver 2.21 10.Oct.1998 % Ver 2.30 5.Nov.1998 % % For use under Octave define the following function % function s=upper(s); s=toupper(s); end; % V2.12 Warning for missing Header information % V2.20 EDF.AS.* changed % V2.30 EDF.T0 made Y2K compatible until Year 2090 % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % Name changed for bdf files Sept 6,2002 T.S. Lorig % Header updated for EEGLAB format (update web link too) - Arnaud Delorme 14 Oct 2002 function [DAT,H1]=openbdf(FILENAME) SLASH='/'; % defines Seperator for Subdirectories BSLASH=char(92); cname=computer; if cname(1:2)=='PC' SLASH=BSLASH; end; fid=fopen(FILENAME,'r','ieee-le'); if fid<0 fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']); return; end; EDF.FILE.FID=fid; EDF.FILE.OPEN = 1; EDF.FileName = FILENAME; PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]); SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]); EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME)); EDF.FILE.Name = FILENAME(SPos+1:PPos-1); if SPos==0 EDF.FILE.Path = pwd; else EDF.FILE.Path = FILENAME(1:SPos-1); end; EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext]; H1=char(fread(EDF.FILE.FID,256,'char')'); % EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer %if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end; EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification %EDF.H.StartDate = H1(169:176); % 8 Byte %EDF.H.StartTime = H1(177:184); % 8 Byte EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ]; % Y2K compatibility until year 2090 if EDF.VERSION(1)=='0' if EDF.T0(1) < 91 EDF.T0(1)=2000+EDF.T0(1); else EDF.T0(1)=1900+EDF.T0(1); end; else ; % in a future version, this is hopefully not needed end; EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header % reserved = H1(193:236); % 44 Byte EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals EDF.Label = char(fread(EDF.FILE.FID,[16,EDF.NS],'char')'); EDF.Transducer = char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); EDF.PhysDim = char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'); EDF.PhysMin= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.PhysMax= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMin = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); % EDF.DigMax = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); % % check validity of DigMin and DigMax if (length(EDF.DigMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n'); EDF.DigMin = -(2^15)*ones(EDF.NS,1); end if (length(EDF.DigMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n'); EDF.DigMax = (2^15-1)*ones(EDF.NS,1); end if (any(EDF.DigMin >= EDF.DigMax)) fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n'); end % check validity of PhysMin and PhysMax if (length(EDF.PhysMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n'); EDF.PhysMin = EDF.DigMin; end if (length(EDF.PhysMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n'); EDF.PhysMax = EDF.DigMax; end if (any(EDF.PhysMin >= EDF.PhysMax)) fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n'); EDF.PhysMin = EDF.DigMin; EDF.PhysMax = EDF.DigMax; end EDF.PreFilt= char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); % tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record EDF.SPR = str2num(char(tmp)); % samples per data record fseek(EDF.FILE.FID,32*EDF.NS,0); EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./ ... (EDF.DigMax-EDF.DigMin); EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin; tmp = find(EDF.Cal < 0); EDF.Cal(tmp) = ones(size(tmp)); EDF.Off(tmp) = zeros(size(tmp)); EDF.Calib=[EDF.Off';(diag(EDF.Cal))]; %EDF.Calib=sparse(diag([1; EDF.Cal])); %EDF.Calib(1,2:EDF.NS+1)=EDF.Off'; EDF.SampleRate = EDF.SPR / EDF.Dur; EDF.FILE.POS = ftell(EDF.FILE.FID); if EDF.NRec == -1 % unknown record size, determine correct NRec fseek(EDF.FILE.FID, 0, 'eof'); endpos = ftell(EDF.FILE.FID); EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2)); fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof'); H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records end; EDF.Chan_Select=(EDF.SPR==max(EDF.SPR)); for k=1:EDF.NS if EDF.Chan_Select(k) EDF.ChanTyp(k)='N'; else EDF.ChanTyp(k)=' '; end; if findstr(upper(EDF.Label(k,:)),'ECG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EKG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EEG') EDF.ChanTyp(k)='E'; elseif findstr(upper(EDF.Label(k,:)),'EOG') EDF.ChanTyp(k)='O'; elseif findstr(upper(EDF.Label(k,:)),'EMG') EDF.ChanTyp(k)='M'; end; end; EDF.AS.spb = sum(EDF.SPR); % Samples per Block bi=[0;cumsum(EDF.SPR)]; idx=[];idx2=[]; for k=1:EDF.NS, idx2=[idx2, (k-1)*max(EDF.SPR)+(1:EDF.SPR(k))]; end; maxspr=max(EDF.SPR); idx3=zeros(EDF.NS*maxspr,1); for k=1:EDF.NS, idx3(maxspr*(k-1)+(1:maxspr))=bi(k)+ceil((1:maxspr)'/maxspr*EDF.SPR(k));end; %EDF.AS.bi=bi; EDF.AS.IDX2=idx2; %EDF.AS.IDX3=idx3; DAT.Head=EDF; DAT.MX.ReRef=1; %DAT.MX=feval('loadxcm',EDF); return;
github
lcnbeapp/beapp-master
ft_trialfun_general.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/trialfun/ft_trialfun_general.m
13,804
utf_8
24b04b8f0e079fd37494db20f8d6a99a
function [trl, event] = ft_trialfun_general(cfg) % FT_TRIALFUN_GENERAL determines trials/segments in the data that are % interesting for analysis, using the general event structure returned % by read_event. This function is independent of the dataformat % % The trialdef structure can contain the following specifications % cfg.trialdef.eventtype = 'string' % cfg.trialdef.eventvalue = number, string or list with numbers or strings % cfg.trialdef.prestim = latency in seconds (optional) % cfg.trialdef.poststim = latency in seconds (optional) % % If you want to read all data from a continous file in segments, you can specify % cfg.trialdef.triallength = duration in seconds (can be Inf) % cfg.trialdef.ntrials = number of trials % % If you specify % cfg.trialdef.eventtype = '?' % a list with the events in your datafile will be displayed on screen. % % If you specify % cfg.trialdef.eventtype = 'gui' % a graphical user interface will allow you to select events of interest. % % See also FT_DEFINETRIAL, FT_PREPROCESSING % Copyright (C) 2005-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % some events do not require the specification a type, pre or poststim period % in that case it is more convenient not to have them, instead of making them empty if ~isfield(cfg, 'trialdef') cfg.trialdef = []; end if isfield(cfg.trialdef, 'eventvalue') && isempty(cfg.trialdef.eventvalue ), cfg.trialdef = rmfield(cfg.trialdef, 'eventvalue' ); end if isfield(cfg.trialdef, 'prestim') && isempty(cfg.trialdef.prestim ), cfg.trialdef = rmfield(cfg.trialdef, 'prestim' ); end if isfield(cfg.trialdef, 'poststim') && isempty(cfg.trialdef.poststim ), cfg.trialdef = rmfield(cfg.trialdef, 'poststim' ); end if isfield(cfg.trialdef, 'triallength') && isempty(cfg.trialdef.triallength ), cfg.trialdef = rmfield(cfg.trialdef, 'triallength'); end if isfield(cfg.trialdef, 'ntrials') && isempty(cfg.trialdef.ntrials ), cfg.trialdef = rmfield(cfg.trialdef, 'ntrials' ); end if isfield(cfg.trialdef, 'triallength') % reading all segments from a continuous file is incompatible with any other option try, cfg.trialdef = rmfield(cfg.trialdef, 'eventvalue'); end try, cfg.trialdef = rmfield(cfg.trialdef, 'prestim' ); end try, cfg.trialdef = rmfield(cfg.trialdef, 'poststim' ); end if ~isfield(cfg.trialdef, 'ntrials') if isinf(cfg.trialdef.triallength) cfg.trialdef.ntrials = 1; else cfg.trialdef.ntrials = inf; end end end % default rejection parameter if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % read the header, contains the sampling frequency hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat); % read the events if isfield(cfg, 'event') fprintf('using the events from the configuration structure\n'); event = cfg.event; else fprintf('reading the events from ''%s''\n', cfg.headerfile); event = ft_read_event(cfg.headerfile, 'headerformat', cfg.headerformat, 'eventformat', cfg.eventformat, 'dataformat', cfg.dataformat); end % for the following, the trials do not depend on the events in the data if isfield(cfg.trialdef, 'triallength') if isinf(cfg.trialdef.triallength) % make one long trial with the complete continuous data in it trl = [1 hdr.nSamples*hdr.nTrials 0]; elseif isinf(cfg.trialdef.ntrials) % cut the continous data into as many segments as possible nsamples = round(cfg.trialdef.triallength*hdr.Fs); trlbeg = 1:nsamples:(hdr.nSamples*hdr.nTrials - nsamples + 1); trlend = trlbeg + nsamples - 1; offset = zeros(size(trlbeg)); trl = [trlbeg(:) trlend(:) offset(:)]; else % make the pre-specified number of trials nsamples = round(cfg.trialdef.triallength*hdr.Fs); trlbeg = (0:(cfg.trialdef.ntrials-1))*nsamples + 1; trlend = trlbeg + nsamples - 1; offset = zeros(size(trlbeg)); trl = [trlbeg(:) trlend(:) offset(:)]; end return end trl = []; val = []; if isfield(cfg.trialdef, 'eventtype') if strcmp(cfg.trialdef.eventtype, '?') % no trials should be added, show event information using subfunction and exit show_event(event); return elseif strcmp(cfg.trialdef.eventtype, 'gui') || (isfield(cfg.trialdef, 'eventvalue') && length(cfg.trialdef.eventvalue)==1 && strcmp(cfg.trialdef.eventvalue, 'gui')) cfg.trialdef = select_event(event, cfg.trialdef); usegui = 1; else usegui = 0; end else usegui = 0; end % start by selecting all events sel = true(1, length(event)); % this should be a row vector % select all events of the specified type if isfield(cfg.trialdef, 'eventtype') && ~isempty(cfg.trialdef.eventtype) for i=1:numel(event) sel(i) = sel(i) && ismatch(event(i).type, cfg.trialdef.eventtype); end elseif ~isfield(cfg.trialdef, 'eventtype') || isempty(cfg.trialdef.eventtype) % search for trial events for i=1:numel(event) sel(i) = sel(i) && ismatch(event(i).type, 'trial'); end end % select all events with the specified value if isfield(cfg.trialdef, 'eventvalue') && ~isempty(cfg.trialdef.eventvalue) for i=1:numel(event) sel(i) = sel(i) && ismatch(event(i).value, cfg.trialdef.eventvalue); end end % convert from boolean vector into a list of indices sel = find(sel); if usegui % Checks whether offset and duration are defined for all the selected % events and/or prestim/poststim are defined in trialdef. if (any(cellfun('isempty', {event(sel).offset})) || ... any(cellfun('isempty', {event(sel).duration}))) && ... ~(isfield(cfg.trialdef, 'prestim') && isfield(cfg.trialdef, 'poststim')) % If at least some of offset/duration values and prestim/poststim % values are missing tries to ask the user for prestim/poststim answer = inputdlg({'Prestimulus latency (sec)','Poststimulus latency (sec)'}, 'Enter borders'); if isempty(answer) || any(cellfun('isempty', answer)) error('The information in the data and cfg is insufficient to define trials.'); else cfg.trialdef.prestim=str2double(answer{1}); cfg.trialdef.poststim=str2double(answer{2}); if isnan(cfg.trialdef.prestim) || isnan(cfg.trialdef.poststim) error('Illegal input for trial borders'); end end end % if specification is not complete end % if usegui for i=sel % catch empty fields in the event table and interpret them meaningfully if isempty(event(i).offset) % time axis has no offset relative to the event event(i).offset = 0; end if isempty(event(i).duration) % the event does not specify a duration event(i).duration = 0; end % determine where the trial starts with respect to the event if ~isfield(cfg.trialdef, 'prestim') trloff = event(i).offset; trlbeg = event(i).sample; else % override the offset of the event trloff = round(-cfg.trialdef.prestim*hdr.Fs); % also shift the begin sample with the specified amount trlbeg = event(i).sample + trloff; end % determine the number of samples that has to be read (excluding the begin sample) if ~isfield(cfg.trialdef, 'poststim') trldur = max(event(i).duration - 1, 0); else % this will not work if prestim was not defined, the code will then crash trldur = round((cfg.trialdef.poststim+cfg.trialdef.prestim)*hdr.Fs) - 1; end trlend = trlbeg + trldur; % add the beginsample, endsample and offset of this trial to the list % if all samples are in the dataset if trlbeg>0 && trlend<=hdr.nSamples*hdr.nTrials, trl = [trl; [trlbeg trlend trloff]]; if isnumeric(event(i).value), val = [val; event(i).value]; elseif ischar(event(i).value) && numel(event(i).value)>1 && (event(i).value(1)=='S'|| event(i).value(1)=='R') % on brainvision these are called 'S 1' for stimuli or 'R 1' for responses val = [val; str2double(event(i).value(2:end))]; else val = [val; nan]; end end end % append the vector with values if ~isempty(val) && ~all(isnan(val)) && size(trl,1)==size(val,1) trl = [trl val]; end if usegui && ~isempty(trl) % This complicated line just computes the trigger times in seconds and % converts them to a cell array of strings to use in the GUI eventstrings = cellfun(@num2str, mat2cell((trl(:, 1)- trl(:, 3))./hdr.Fs , ones(1, size(trl, 1))), 'UniformOutput', 0); % Let us start with handling at least the completely unsegmented case % semi-automatically. The more complicated cases are better left % to the user. if hdr.nTrials==1 selected = find(trl(:,1)>0 & trl(:,2)<=hdr.nSamples); else selected = find(trl(:,1)>0); end indx = select_channel_list(eventstrings, selected , 'Select events'); trl=trl(indx, :); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that shows event table %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function show_event(event) if isempty(event) fprintf('no events were found in the datafile\n'); return end eventtype = unique({event.type}); Neventtype = length(eventtype); if Neventtype==0 fprintf('no events were found in the datafile\n'); else fprintf('the following events were found in the datafile\n'); for i=1:Neventtype sel = find(strcmp(eventtype{i}, {event.type})); try eventvalue = unique({event(sel).value}); % cell-array with string value eventvalue = sprintf('''%s'' ', eventvalue{:}); % translate into a single string catch eventvalue = unique(cell2mat({event(sel).value})); % array with numeric values or empty eventvalue = num2str(eventvalue); % translate into a single string end fprintf('event type: ''%s'' ', eventtype{i}); fprintf('with event values: %s', eventvalue); fprintf('\n'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that allows the user to select an event using gui %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function trialdef = select_event(event, trialdef) if isempty(event) fprintf('no events were found in the datafile\n'); return end if strcmp(trialdef.eventtype, 'gui') eventtype = unique({event.type}); else eventtype ={trialdef.eventtype}; end Neventtype = length(eventtype); if Neventtype==0 fprintf('no events were found in the datafile\n'); else % Two lists are built in parallel settings={}; % The list of actual values to be used later strsettings={}; % The list of strings to show in the GUI for i=1:Neventtype sel = find(strcmp(eventtype{i}, {event.type})); emptyval = find(cellfun('isempty', {event(sel).value})); if all(cellfun(@isnumeric, {event(sel).value})) [event(sel(emptyval)).value]=deal(Inf); eventvalue = unique([event(sel).value]); else if ~isempty(find(strcmp('Inf', {event(sel).value}))) % It's a very unlikely scenario but ... warning('Event value''Inf'' cannot be handled by GUI selection. Mistakes are possible.') end [event(sel(emptyval)).value]=deal('Inf'); eventvalue = unique({event(sel).value}); if ~iscell(eventvalue) eventvalue = {eventvalue}; end end for j=1:length(eventvalue) if (isnumeric(eventvalue(j)) && eventvalue(j)~=Inf) || ... (iscell(eventvalue(j)) && ischar(eventvalue{j}) && ~strcmp(eventvalue{j}, 'Inf')) settings = [settings; [eventtype(i), eventvalue(j)]]; else settings = [settings; [eventtype(i), {[]}]]; end if isa(eventvalue, 'numeric') strsettings = [strsettings; {['Type: ' eventtype{i} ' ; Value: ' num2str(eventvalue(j))]}]; else strsettings = [strsettings; {['Type: ' eventtype{i} ' ; Value: ' eventvalue{j}]}]; end end end if isempty(strsettings) fprintf('no events of the selected type were found in the datafile\n'); return end [selection, ok] = listdlg('ListString',strsettings, 'SelectionMode', 'multiple', 'Name', 'Select event', 'ListSize', [300 300]); if ok trialdef.eventtype = settings(selection,1); trialdef.eventvalue = settings(selection,2); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION returns true if x is a member of array y, regardless of the class of x and y %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = ismatch(x, y) if isempty(x) || isempty(y) s = false; elseif ischar(x) && ischar(y) s = strcmp(x, y); elseif isnumeric(x) && isnumeric(y) s = ismember(x, y); elseif ischar(x) && iscell(y) y = y(strcmp(class(x), cellfun(@class, y, 'UniformOutput', false))); s = ismember(x, y); elseif isnumeric(x) && iscell(y) && all(cellfun(@isnumeric, y)) s = false; for i=1:numel(y) s = s || ismember(x, y{i}); end else s = false; end
github
lcnbeapp/beapp-master
ft_trialfun_realtime.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/trialfun/ft_trialfun_realtime.m
4,420
utf_8
d7133e3da082881a031513a257c0a2d9
function trl = ft_trialfun_realtime(cfg) % FT_TRIALFUN_REALTIME can be used to segment a continuous stream of % data in real-time. Trials are defined as [begsample endsample offset % condition] % % The configuration structure can contain the following specifications % cfg.minsample = the last sample number that was already considered (passed from rt_process) % cfg.blocksize = in seconds. In case of events, offset is % wrt the trigger. % cfg.offset = the offset wrt the 0 point. In case of no events, offset is wrt % prevSample. E.g., [-0.9 1] will read 1 second blocks with % 0.9 second overlap % cfg.bufferdata = {'first' 'last'}. If 'last' then only the last block of % interest is read. Otherwise, all well-defined blocks are read (default = 'first') % Copyright (C) 2009, Marcel van Gerven % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if ~isfield(cfg,'minsample'), cfg.minsample = 0; end if ~isfield(cfg,'blocksize'), cfg.blocksize = 0.1; end if ~isfield(cfg,'offset'), cfg.offset = 0; end if ~isfield(cfg,'bufferdata'), cfg.bufferdata = 'first'; end if ~isfield(cfg,'triggers'), cfg.triggers = []; end % blocksize and offset in terms of samples cfg.blocksize = round(cfg.blocksize * cfg.hdr.Fs); cfg.offset = round(cfg.offset * cfg.hdr.Fs); % retrieve trials of interest if isempty(cfg.event) % asynchronous mode trl = trialfun_asynchronous(cfg); else % synchronous mode trl = trialfun_synchronous(cfg); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function trl = trialfun_asynchronous(cfg) trl = []; prevSample = cfg.minsample; if strcmp(cfg.bufferdata, 'last') % only get last block % begsample starts blocksize samples before the end begsample = cfg.hdr.nSamples*cfg.hdr.nTrials - cfg.blocksize; % begsample should be offset samples away from the previous read if begsample >= (prevSample + cfg.offset) endsample = cfg.hdr.nSamples*cfg.hdr.nTrials; if begsample < endsample && begsample > 0 trl = [begsample endsample 0 nan]; end end else % get all blocks while true % see whether new samples are available newsamples = (cfg.hdr.nSamples*cfg.hdr.nTrials-prevSample); % if newsamples exceeds the offset plus length specified in blocksize if newsamples >= (cfg.offset+cfg.blocksize) % we do not consider samples < 1 begsample = max(1,prevSample+cfg.offset); endsample = max(1,prevSample+cfg.offset+cfg.blocksize); if begsample < endsample && endsample <= cfg.hdr.nSamples*cfg.hdr.nTrials trl = [trl; [begsample endsample 0 nan]]; end prevSample = endsample; else break; end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function trl = trialfun_synchronous(cfg) trl = []; % process all events for j=1:length(cfg.event) if isempty(cfg.triggers) curtrig = cfg.event(j).value; else [m1,curtrig] = ismember(cfg.event(j).value,cfg.triggers); end if isempty(curtrig), curtrig = nan; end if isempty(cfg.triggers) || (~isempty(m1) && m1) % catched a trigger of interest % we do not consider samples < 1 begsample = max(1,cfg.event(j).sample + cfg.offset); endsample = max(1,begsample + cfg.blocksize); trl = [trl; [begsample endsample cfg.offset curtrig]]; end end
github
lcnbeapp/beapp-master
select_channel_list.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/trialfun/private/select_channel_list.m
5,924
utf_8
94982b0a4829981930c1c446e459ca7c
function [select] = select_channel_list(label, select, titlestr) % SELECT_CHANNEL_LIST presents a dialog for selecting multiple elements % from a cell array with strings, such as the labels of EEG channels. % The dialog presents two columns with an add and remove mechanism. % % select = select_channel_list(label, initial, titlestr) % % with % initial indices of channels that are initially selected % label cell array with channel labels (strings) % titlestr title for dialog (optional) % and % select indices of selected channels % % If the user presses cancel, the initial selection will be returned. % Copyright (C) 2003, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin<3 titlestr = 'Select'; end pos = get(0,'DefaultFigurePosition'); pos(3:4) = [290 300]; dlg = dialog('Name', titlestr, 'Position', pos); set(gca, 'Visible', 'off'); % explicitly turn the axis off, as it sometimes appears select = select(:)'; % ensure that it is a row array userdata.label = label; userdata.select = select; userdata.unselect = setdiff(1:length(label), select); set(dlg, 'userdata', userdata); uicontrol(dlg, 'style', 'text', 'position', [ 10 240+20 80 20], 'string', 'unselected'); uicontrol(dlg, 'style', 'text', 'position', [200 240+20 80 20], 'string', 'selected '); uicontrol(dlg, 'style', 'listbox', 'position', [ 10 40+20 80 200], 'min', 0, 'max', 2, 'tag', 'lbunsel') uicontrol(dlg, 'style', 'listbox', 'position', [200 40+20 80 200], 'min', 0, 'max', 2, 'tag', 'lbsel') uicontrol(dlg, 'style', 'pushbutton', 'position', [105 175+20 80 20], 'string', 'add all >' , 'callback', @label_addall); uicontrol(dlg, 'style', 'pushbutton', 'position', [105 145+20 80 20], 'string', 'add >' , 'callback', @label_add); uicontrol(dlg, 'style', 'pushbutton', 'position', [105 115+20 80 20], 'string', '< remove' , 'callback', @label_remove); uicontrol(dlg, 'style', 'pushbutton', 'position', [105 85+20 80 20], 'string', '< remove all', 'callback', @label_removeall); uicontrol(dlg, 'style', 'pushbutton', 'position', [ 55 10 80 20], 'string', 'Cancel', 'callback', 'close'); uicontrol(dlg, 'style', 'pushbutton', 'position', [155 10 80 20], 'string', 'OK', 'callback', 'uiresume'); label_redraw(dlg); % wait untill the dialog is closed or the user presses OK/Cancel uiwait(dlg); if ishandle(dlg) % the user pressed OK, return the selection from the dialog userdata = get(dlg, 'userdata'); select = userdata.select; close(dlg); return else % the user pressed Cancel or closed the dialog, return the initial selection return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_redraw(h) userdata = get(h, 'userdata'); set(findobj(h, 'tag', 'lbsel' ), 'string', userdata.label(userdata.select)); set(findobj(h, 'tag', 'lbunsel'), 'string', userdata.label(userdata.unselect)); % set the active element in the select listbox, based on the previous active element tmp = min(get(findobj(h, 'tag', 'lbsel'), 'value')); tmp = min(tmp, length(get(findobj(h, 'tag', 'lbsel'), 'string'))); if isempty(tmp) | tmp==0 tmp = 1; end set(findobj(h, 'tag', 'lbsel' ), 'value', tmp); % set the active element in the unselect listbox, based on the previous active element tmp = min(get(findobj(h, 'tag', 'lbunsel'), 'value')); tmp = min(tmp, length(get(findobj(h, 'tag', 'lbunsel'), 'string'))); if isempty(tmp) | tmp==0 tmp = 1; end set(findobj(h, 'tag', 'lbunsel' ), 'value', tmp); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_addall(h, eventdata, handles, varargin) h = get(h, 'parent'); userdata = get(h, 'userdata'); userdata.select = 1:length(userdata.label); userdata.unselect = []; set(findobj(h, 'tag', 'lbunsel' ), 'value', 1); set(h, 'userdata', userdata); label_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_removeall(h, eventdata, handles, varargin) h = get(h, 'parent'); userdata = get(h, 'userdata'); userdata.unselect = 1:length(userdata.label); userdata.select = []; set(findobj(h, 'tag', 'lbsel' ), 'value', 1); set(h, 'userdata', userdata); label_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_add(h, eventdata, handles, varargin) h = get(h, 'parent'); userdata = get(h, 'userdata'); if ~isempty(userdata.unselect) add = userdata.unselect(get(findobj(h, 'tag', 'lbunsel' ), 'value')); userdata.select = sort([userdata.select add]); userdata.unselect = sort(setdiff(userdata.unselect, add)); set(h, 'userdata', userdata); label_redraw(h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_remove(h, eventdata, handles, varargin); h = get(h, 'parent'); userdata = get(h, 'userdata'); if ~isempty(userdata.select) remove = userdata.select(get(findobj(h, 'tag', 'lbsel' ), 'value')); userdata.select = sort(setdiff(userdata.select, remove)); userdata.unselect = sort([userdata.unselect remove]); set(h, 'userdata', userdata); label_redraw(h); end
github
lcnbeapp/beapp-master
ft_headmodel_fns.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/ft_headmodel_fns.m
5,517
utf_8
f2babb12e0dbf26d42ff2aa1a9791792
function headmodel = ft_headmodel_fns(seg, varargin) % FT_HEADMODEL_FNS creates the volume conduction structure to be used % in the FNS forward solver. % % Use as % headmodel = ft_headmodel_fns(seg, ...) % % Optional input arguments should be specified in key-value pairs and % can include % tissuecond = matrix C [9XN tissue types]; where N is the number of % tissues and a 3x3 tensor conductivity matrix is stored % in each column. % tissue = see fns_contable_write % tissueval = match tissues of segmentation input % transform = 4x4 transformation matrix (default eye(4)) % sens = sensor information (for which ft_datatype(sens,'sens')==1) % deepelec = used in the case of deep voxel solution % tolerance = scalar (default 1e-8) % % Standard default values for conductivity matrix C are derived from % Saleheen HI, Ng KT. New finite difference formulations for general % inhomogeneous anisotropic bioelectric problems. IEEE Trans Biomed Eng. % 1997 % % Additional documentation available at: % http://hunghienvn.nmsu.edu/wiki/index.php/FNS % % See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD % Copyright (C) 2011, Cristiano Micheli and Hung Dang % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ ft_hastoolbox('fns', 1); % get the optional arguments tissue = ft_getopt(varargin, 'tissue', []); tissueval = ft_getopt(varargin, 'tissueval', []); tissuecond = ft_getopt(varargin, 'tissuecond', []); transform = ft_getopt(varargin, 'transform', eye(4)); unit = ft_getopt(varargin, 'unit', 'mm'); sens = ft_getopt(varargin, 'sens', []); deepelec = ft_getopt(varargin, 'deepelec', []); % used in the case of deep voxel solution tolerance = ft_getopt(varargin, 'tolerance', 1e-8); if isempty(sens) error('A set of sensors is required') end if ispc error('FNS only works on Linux and OS X') end % check the consistency between tissue values and the segmentation vecval = ismember(tissueval,unique(seg(:))); if any(vecval)==0 warning('Some of the tissue values are not in the segmentation') end % create the files to be written try tmpfolder = pwd; cd(tempdir) [tmp,tname] = fileparts(tempname); segfile = [tname]; [tmp,tname] = fileparts(tempname); confile = [tname '.csv']; [tmp,tname] = fileparts(tempname); elecfile = [tname '.h5']; [tmp,tname] = fileparts(tempname); exefile = [tname '.sh']; [tmp,tname] = fileparts(tempname); datafile = [tname '.h5']; % this requires the fieldtrip/fileio toolbox ft_hastoolbox('fileio', 1); % create a fake mri structure and write the segmentation on disk disp('writing the segmentation file...') mri = []; mri.dim = size(seg); mri.transform = eye(4); mri.seg = uint8(seg); cfg = []; cfg.datatype = 'uint8'; cfg.coordsys = 'ctf'; cfg.parameter = 'seg'; cfg.filename = segfile; cfg.filetype = 'analyze'; ft_volumewrite(cfg, mri); % write the cond matrix on disk, load the default cond matrix in case not specified disp('writing the conductivity file...') condmatrix = fns_contable_write('tissue',tissue,'tissueval',tissueval,'tissuecond',tissuecond); csvwrite(confile,condmatrix); % write the positions of the electrodes on disk disp('writing the electrodes file...') pos = ft_warp_apply(inv(transform),sens.elecpos); % in voxel coordinates! % convert pos into int32 datatype. hdf5write(elecfile, '/electrodes/gridlocs', int32(pos)); % Exe file efid = fopen(exefile, 'w'); if ~ispc fprintf(efid,'#!/usr/bin/env bash\n'); fprintf(efid,['elecsfwd1 -img ' segfile ' -electrodes ./' elecfile ' -data ./', ... datafile ' -contable ./' confile ' -TOL ' num2str(tolerance) ' \n']);%2>&1 > /dev/null end fclose(efid); % run the shell instructions dos(sprintf('chmod +x %s', exefile)); dos(['./' exefile]); % FIXME: find a cleverer way to store the huge transfer matrix (vista?) [transfer,status] = fns_read_transfer(datafile); cleaner(segfile,confile,elecfile,exefile,datafile) catch ME disp('The transfer matrix was not written') cleaner(segfile,confile,elecfile,exefile,datafile) cd(tmpfolder) rethrow(ME) end % start with an empty volume conductor headmodel = []; headmodel.tissue = tissue; headmodel.tissueval = tissueval; headmodel.transform = transform; headmodel.unit = unit; headmodel.segdim = size(seg); headmodel.type = 'fns'; headmodel.transfer = transfer; if ~isempty(deepelec) headmodel.deepelec = deepelec; end function cleaner(segfile,confile,elecfile,exefile,datafile) delete([segfile '.hdr']); delete([segfile '.img']); delete(confile); delete(elecfile); delete(exefile); delete(datafile);
github
lcnbeapp/beapp-master
ft_convert_units.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/ft_convert_units.m
10,207
utf_8
d3c04f1222517baf2f069d68e3dd6abe
function [obj] = ft_convert_units(obj, target, varargin) % FT_CONVERT_UNITS changes the geometrical dimension to the specified SI unit. % The units of the input object is determined from the structure field % object.unit, or is estimated based on the spatial extend of the structure, % e.g. a volume conduction model of the head should be approximately 20 cm large. % % Use as % [object] = ft_convert_units(object, target) % % The following geometrical objects are supported as inputs % electrode or gradiometer array, see FT_DATATYPE_SENS % volume conductor, see FT_DATATYPE_HEADMODEL % anatomical mri, see FT_DATATYPE_VOLUME % segmented mri, see FT_DATATYPE_SEGMENTATION % dipole grid definition, see FT_DATATYPE_SOURCE % % Possible target units are 'm', 'dm', 'cm ' or 'mm'. If no target units % are specified, this function will only determine the native geometrical % units of the object. % % See also FT_ESTIMATE_UNITS, FT_READ_VOL, FT_READ_SENS % Copyright (C) 2005-2016, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % This function consists of three parts: % 1) determine the input units % 2) determine the requested scaling factor to obtain the output units % 3) try to apply the scaling to the known geometrical elements in the input object feedback = ft_getopt(varargin, 'feedback', false); if isstruct(obj) && numel(obj)>1 % deal with a structure array for i=1:numel(obj) if nargin>1 tmp(i) = ft_convert_units(obj(i), target, varargin{:}); else tmp(i) = ft_convert_units(obj(i)); end end obj = tmp; return elseif iscell(obj) && numel(obj)>1 % deal with a cell array % this might represent combined EEG, ECoG and/or MEG for i=1:numel(obj) obj{i} = ft_convert_units(obj{i}, target, varargin{:}); end return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % determine the unit-of-dimension of the input object %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(obj, 'unit') && ~isempty(obj.unit) % use the units specified in the object unit = obj.unit; elseif isfield(obj, 'bnd') && isfield(obj.bnd, 'unit') unit = unique({obj.bnd.unit}); if ~all(strcmp(unit, unit{1})) error('inconsistent units in the individual boundaries'); else unit = unit{1}; end % keep one representation of the units rather than keeping it with each boundary % the units will be reassigned further down obj.bnd = rmfield(obj.bnd, 'unit'); else % try to determine the units by looking at the size of the object if isfield(obj, 'chanpos') && ~isempty(obj.chanpos) siz = norm(idrange(obj.chanpos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'elecpos') && ~isempty(obj.elecpos) siz = norm(idrange(obj.elecpos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'coilpos') && ~isempty(obj.coilpos) siz = norm(idrange(obj.coilpos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'pnt') && ~isempty(obj.pnt) siz = norm(idrange(obj.pnt)); unit = ft_estimate_units(siz); elseif isfield(obj, 'pos') && ~isempty(obj.pos) siz = norm(idrange(obj.pos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'transform') && ~isempty(obj.transform) % construct the corner points of the volume in voxel and in head coordinates [pos_voxel, pos_head] = cornerpoints(obj.dim, obj.transform); siz = norm(idrange(pos_head)); unit = ft_estimate_units(siz); elseif isfield(obj, 'fid') && isfield(obj.fid, 'pnt') && ~isempty(obj.fid.pnt) siz = norm(idrange(obj.fid.pnt)); unit = ft_estimate_units(siz); elseif isfield(obj, 'fid') && isfield(obj.fid, 'pos') && ~isempty(obj.fid.pos) siz = norm(idrange(obj.fid.pos)); unit = ft_estimate_units(siz); elseif ft_voltype(obj, 'infinite') % this is an infinite medium volume conductor, which does not care about units unit = 'm'; elseif ft_voltype(obj,'singlesphere') siz = obj.r; unit = ft_estimate_units(siz); elseif ft_voltype(obj,'localspheres') siz = median(obj.r); unit = ft_estimate_units(siz); elseif ft_voltype(obj,'concentricspheres') siz = max(obj.r); unit = ft_estimate_units(siz); elseif isfield(obj, 'bnd') && isstruct(obj.bnd) && isfield(obj.bnd(1), 'pnt') && ~isempty(obj.bnd(1).pnt) siz = norm(idrange(obj.bnd(1).pnt)); unit = ft_estimate_units(siz); elseif isfield(obj, 'bnd') && isstruct(obj.bnd) && isfield(obj.bnd(1), 'pos') && ~isempty(obj.bnd(1).pos) siz = norm(idrange(obj.bnd(1).pos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'nas') && isfield(obj, 'lpa') && isfield(obj, 'rpa') pnt = [obj.nas; obj.lpa; obj.rpa]; siz = norm(idrange(pnt)); unit = ft_estimate_units(siz); else error('cannot determine geometrical units'); end % recognized type of volume conduction model or sensor array end % determine input units if nargin<2 || isempty(target) % just remember the units in the output and return obj.unit = unit; return elseif strcmp(unit, target) % no conversion is needed obj.unit = unit; return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the scaling factor from the input units to the desired ones %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% scale = ft_scalingfactor(unit, target); if istrue(feedback) % give some information about the conversion fprintf('converting units from ''%s'' to ''%s''\n', unit, target) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % apply the scaling factor %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % volume conductor model if isfield(obj, 'r'), obj.r = scale * obj.r; end if isfield(obj, 'o'), obj.o = scale * obj.o; end if isfield(obj, 'bnd') && isfield(obj.bnd, 'pnt') for i=1:length(obj.bnd) obj.bnd(i).pnt = scale * obj.bnd(i).pnt; end end if isfield(obj, 'bnd') && isfield(obj.bnd, 'pos') for i=1:length(obj.bnd) obj.bnd(i).pos = scale * obj.bnd(i).pos; end end % old-fashioned gradiometer array if isfield(obj, 'pnt1'), obj.pnt1 = scale * obj.pnt1; end if isfield(obj, 'pnt2'), obj.pnt2 = scale * obj.pnt2; end if isfield(obj, 'prj'), obj.prj = scale * obj.prj; end % gradiometer array, electrode array, head shape or dipole grid if isfield(obj, 'pnt'), obj.pnt = scale * obj.pnt; end if isfield(obj, 'pos'), obj.pos = scale * obj.pos; end if isfield(obj, 'chanpos'), obj.chanpos = scale * obj.chanpos; end if isfield(obj, 'chanposorg'), obj.chanposold = scale * obj.chanposorg; end % pre-2016 version if isfield(obj, 'chanposold'), obj.chanposold = scale * obj.chanposold; end % 2016 version and later if isfield(obj, 'coilpos'), obj.coilpos = scale * obj.coilpos; end if isfield(obj, 'elecpos'), obj.elecpos = scale * obj.elecpos; end % gradiometer array that combines multiple coils in one channel if isfield(obj, 'tra') && isfield(obj, 'chanunit') % find the gradiometer channels that are expressed as unit of field strength divided by unit of distance, e.g. T/cm for i=1:length(obj.chanunit) tok = tokenize(obj.chanunit{i}, '/'); if ~isempty(regexp(obj.chanunit{i}, 'm$', 'once')) % assume that it is T/m or so obj.tra(i,:) = obj.tra(i,:) / scale; obj.chanunit{i} = [tok{1} '/' target]; elseif ~isempty(regexp(obj.chanunit{i}, '[T|V]$', 'once')) % assume that it is T or V, don't do anything elseif strcmp(obj.chanunit{i}, 'unknown') % assume that it is T or V, don't do anything else error('unexpected units %s', obj.chanunit{i}); end end % for end % if % fiducials if isfield(obj, 'fid') && isfield(obj.fid, 'pnt'), obj.fid.pnt = scale * obj.fid.pnt; end if isfield(obj, 'fid') && isfield(obj.fid, 'pos'), obj.fid.pos = scale * obj.fid.pos; end % dipole grid if isfield(obj, 'resolution'), obj.resolution = scale * obj.resolution; end % x,y,zgrid can also be 'auto' if isfield(obj, 'xgrid') && ~ischar(obj.xgrid), obj.xgrid = scale * obj.xgrid; end if isfield(obj, 'ygrid') && ~ischar(obj.ygrid), obj.ygrid = scale * obj.ygrid; end if isfield(obj, 'zgrid') && ~ischar(obj.zgrid), obj.zgrid = scale * obj.zgrid; end % anatomical MRI or functional volume if isfield(obj, 'transform'), H = diag([scale scale scale 1]); obj.transform = H * obj.transform; end if isfield(obj, 'transformorig'), H = diag([scale scale scale 1]); obj.transformorig = H * obj.transformorig; end % sourcemodel obtained through mne also has a orig-field with the high % number of vertices if isfield(obj, 'orig') if isfield(obj.orig, 'pnt') obj.orig.pnt = scale * obj.orig.pnt; end if isfield(obj.orig, 'pos') obj.orig.pos = scale * obj.orig.pos; end end % remember the unit obj.unit = target; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % IDRANGE interdecile range for more robust range estimation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function r = idrange(x) keeprow=true(size(x,1),1); for l=1:size(x,2) keeprow = keeprow & isfinite(x(:,l)); end sx = sort(x(keeprow,:), 1); ii = round(interp1([0, 1], [1, size(x(keeprow,:), 1)], [.1, .9])); % indices for 10 & 90 percentile r = diff(sx(ii, :));
github
lcnbeapp/beapp-master
ft_apply_montage.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/ft_apply_montage.m
21,632
utf_8
44431986d20b2a03b833ec06858af91d
function [input] = ft_apply_montage(input, montage, varargin) % FT_APPLY_MONTAGE changes the montage of an electrode or gradiometer array. A % montage can be used for EEG rereferencing, MEG synthetic gradients, MEG % planar gradients or unmixing using ICA. This function applies the montage % to the input EEG or MEG sensor array, which can subsequently be used for % forward computation and source reconstruction of the data. % % Use as % [sens] = ft_apply_montage(sens, montage, ...) % [data] = ft_apply_montage(data, montage, ...) % [freq] = ft_apply_montage(freq, montage, ...) % [montage] = ft_apply_montage(montage1, montage2, ...) % % A montage is specified as a structure with the fields % montage.tra = MxN matrix % montage.labelold = Nx1 cell-array % montage.labelnew = Mx1 cell-array % % As an example, a bipolar montage could look like this % bipolar.labelold = {'1', '2', '3', '4'} % bipolar.labelnew = {'1-2', '2-3', '3-4'} % bipolar.tra = [ % +1 -1 0 0 % 0 +1 -1 0 % 0 0 +1 -1 % ]; % % The montage can optionally also specify the channel type and unit of the input % and output data with % montage.chantypeold = Nx1 cell-array % montage.chantypenew = Mx1 cell-array % montage.chanunitold = Nx1 cell-array % montage.chanunitnew = Mx1 cell-array % % Additional options should be specified in key-value pairs and can be % 'keepunused' string, 'yes' or 'no' (default = 'no') % 'inverse' string, 'yes' or 'no' (default = 'no') % 'balancename' string, name of the montage (default = '') % 'feedback' string, see FT_PROGRESS (default = 'text') % 'warning' boolean, whether to show warnings (default = true) % % If the first input is a montage, then the second input montage will be % applied to the first. In effect, the output montage will first do % montage1, then montage2. % % See also FT_READ_SENS, FT_TRANSFORM_SENS % Copyright (C) 2008-2016, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if iscell(input) && iscell(input) % this represents combined EEG, ECoG and/or MEG for i=1:numel(input) input{i} = ft_apply_montage(input{i}, montage, varargin{:}); end return end % use "old/new" instead of "org/new" montage = fixmontage(montage); input = fixmontage(input); % the input might also be a montage % get optional input arguments keepunused = ft_getopt(varargin, 'keepunused', 'no'); inverse = ft_getopt(varargin, 'inverse', 'no'); feedback = ft_getopt(varargin, 'feedback', 'text'); showwarning = ft_getopt(varargin, 'warning', true); bname = ft_getopt(varargin, 'balancename', ''); if istrue(showwarning) warningfun = @warning; else warningfun = @nowarning; end % these are optional, at the end we will clean up the output in case they did not exist haschantype = (isfield(input, 'chantype') || isfield(input, 'chantypenew')) && all(isfield(montage, {'chantypeold', 'chantypenew'})); haschanunit = (isfield(input, 'chanunit') || isfield(input, 'chanunitnew')) && all(isfield(montage, {'chanunitold', 'chanunitnew'})); % make sure they always exist to facilitate the remainder of the code if ~isfield(montage, 'chantypeold') montage.chantypeold = repmat({'unknown'}, size(montage.labelold)); if isfield(input, 'chantype') && ~istrue(inverse) warning('copying input chantype to montage'); [sel1, sel2] = match_str(montage.labelold, input.label); montage.chantypeold(sel1) = input.chantype(sel2); end end if ~isfield(montage, 'chantypenew') montage.chantypenew = repmat({'unknown'}, size(montage.labelnew)); if isfield(input, 'chantype') && istrue(inverse) warning('copying input chantype to montage'); [sel1, sel2] = match_str(montage.labelnew, input.label); montage.chantypenew(sel1) = input.chantype(sel2); end end if ~isfield(montage, 'chanunitold') montage.chanunitold = repmat({'unknown'}, size(montage.labelold)); if isfield(input, 'chanunit') && ~istrue(inverse) warning('copying input chanunit to montage'); [sel1, sel2] = match_str(montage.labelold, input.label); montage.chanunitold(sel1) = input.chanunit(sel2); end end if ~isfield(montage, 'chanunitnew') montage.chanunitnew = repmat({'unknown'}, size(montage.labelnew)); if isfield(input, 'chanunit') && istrue(inverse) warning('copying input chanunit to montage'); [sel1, sel2] = match_str(montage.labelnew, input.label); montage.chanunitnew(sel1) = input.chanunit(sel2); end end if ~isfield(input, 'label') && isfield(input, 'labelnew') % the input data structure is also a montage inputlabel = input.labelnew; if isfield(input, 'chantypenew') inputchantype = input.chantypenew; else inputchantype = repmat({'unknown'}, size(input.labelnew)); end if isfield(input, 'chanunitnew') inputchanunit = input.chanunitnew; else inputchanunit = repmat({'unknown'}, size(input.labelnew)); end else % the input should describe the channel labels, and optionally the type and unit inputlabel = input.label; if isfield(input, 'chantype') inputchantype = input.chantype; else inputchantype = repmat({'unknown'}, size(input.label)); end if isfield(input, 'chanunit') inputchanunit = input.chanunit; else inputchanunit = repmat({'unknown'}, size(input.label)); end end % check the consistency of the montage if ~iscell(montage.labelold) || ~iscell(montage.labelnew) error('montage labels need to be specified in cell-arrays'); end % check the consistency of the montage if ~all(isfield(montage, {'tra', 'labelold', 'labelnew'})) error('the second input argument does not correspond to a montage'); end % check the consistency of the montage if size(montage.tra,1)~=length(montage.labelnew) error('the number of channels in the montage is inconsistent'); elseif size(montage.tra,2)~=length(montage.labelold) error('the number of channels in the montage is inconsistent'); end % use a default unit transfer from sensors to channels if not otherwise specified if ~isfield(input, 'tra') && isfield(input, 'label') if isfield(input, 'elecpos') && length(input.label)==size(input.elecpos, 1) nchan = length(input.label); input.tra = eye(nchan); elseif isfield(input, 'coilpos') && length(input.label)==size(input.coilpos, 1) nchan = length(input.label); input.tra = eye(nchan); elseif isfield(input, 'chanpos') && length(input.label)==size(input.chanpos, 1) nchan = length(input.label); input.tra = eye(nchan); end end if istrue(inverse) % swap the role of the original and new channels tmp.labelnew = montage.labelold; tmp.labelold = montage.labelnew; tmp.chantypenew = montage.chantypeold; tmp.chantypeold = montage.chantypenew; tmp.chanunitnew = montage.chanunitold; tmp.chanunitold = montage.chanunitnew; % apply the inverse montage, this can be used to undo a previously % applied montage tmp.tra = full(montage.tra); if rank(tmp.tra) < length(tmp.tra) warningfun('the linear projection for the montage is not full-rank, the resulting data will have reduced dimensionality'); tmp.tra = pinv(tmp.tra); else tmp.tra = inv(tmp.tra); end montage = tmp; end % select and keep the columns that are non-empty, i.e. remove the empty columns selcol = find(~all(montage.tra==0, 1)); montage.tra = montage.tra(:,selcol); montage.labelold = montage.labelold(selcol); montage.chantypeold = montage.chantypeold(selcol); montage.chanunitold = montage.chanunitold(selcol); clear selcol % select and remove the columns corresponding to channels that are not present in the % original data remove = setdiff(montage.labelold, intersect(montage.labelold, inputlabel)); selcol = match_str(montage.labelold, remove); % we cannot just remove the colums, all rows that depend on it should also be removed selrow = false(length(montage.labelnew),1); for i=1:length(selcol) selrow = selrow & (montage.tra(:,selcol(i))~=0); end % convert from indices to logical vector selcol = indx2logical(selcol, length(montage.labelold)); % remove rows and columns montage.labelold = montage.labelold(~selcol); montage.labelnew = montage.labelnew(~selrow); montage.chantypeold = montage.chantypeold(~selcol); montage.chantypenew = montage.chantypenew(~selrow); montage.chanunitold = montage.chanunitold(~selcol); montage.chanunitnew = montage.chanunitnew(~selrow); montage.tra = montage.tra(~selrow, ~selcol); clear remove selcol selrow i % add columns for channels that are present in the input data but not specified in % the montage, stick to the original order in the data [dum, ix] = setdiff(inputlabel, montage.labelold); addlabel = inputlabel(sort(ix)); addchantype = inputchantype(sort(ix)); addchanunit = inputchanunit(sort(ix)); m = size(montage.tra,1); n = size(montage.tra,2); k = length(addlabel); % check for NaNs in unused channels; these will be mixed in with the rest % of the channels and result in NaNs in the output even when multiplied % with zeros or identity if k > 0 && isfield(input, 'trial') % check for raw data now only cfg = []; cfg.channel = addlabel; data_unused = ft_selectdata(cfg, input); % use an anonymous function to test for the presence of NaNs in the input data hasnan = @(x) any(isnan(x(:))); if any(cellfun(hasnan, data_unused.trial)) error('FieldTrip:NaNsinInputData', ['Your input data contains NaNs in channels that are unused '... 'in the supplied montage. This would result in undesired NaNs in the '... 'output data. Please remove these channels from the input data (using '... 'ft_selectdata) before attempting to apply the montage.']); end end if istrue(keepunused) % add the channels that are not rereferenced to the input and output of the % montage montage.tra((m+(1:k)),(n+(1:k))) = eye(k); montage.labelold = cat(1, montage.labelold(:), addlabel(:)); montage.labelnew = cat(1, montage.labelnew(:), addlabel(:)); montage.chantypeold = cat(1, montage.chantypeold(:), addchantype(:)); montage.chantypenew = cat(1, montage.chantypenew(:), addchantype(:)); montage.chanunitold = cat(1, montage.chanunitold(:), addchanunit(:)); montage.chanunitnew = cat(1, montage.chanunitnew(:), addchanunit(:)); else % add the channels that are not rereferenced to the input of the montage only montage.tra(:,(n+(1:k))) = zeros(m,k); montage.labelold = cat(1, montage.labelold(:), addlabel(:)); montage.chantypeold = cat(1, montage.chantypeold(:), addchantype(:)); montage.chanunitold = cat(1, montage.chanunitold(:), addchanunit(:)); end clear addlabel addchantype addchanunit m n k % determine whether all channels are unique m = size(montage.tra,1); n = size(montage.tra,2); if length(unique(montage.labelnew))~=m error('not all output channels of the montage are unique'); end if length(unique(montage.labelold))~=n error('not all input channels of the montage are unique'); end % determine whether all channels that have to be rereferenced are available if length(intersect(inputlabel, montage.labelold))~=length(montage.labelold) error('not all channels that are required in the montage are available in the data'); end % reorder the columns of the montage matrix [selinput, selmontage] = match_str(inputlabel, montage.labelold); montage.tra = montage.tra(:,selmontage); montage.labelold = montage.labelold(selmontage); montage.chantypeold = montage.chantypeold(selmontage); montage.chanunitold = montage.chanunitold(selmontage); % ensure that the montage is double precision montage.tra = double(montage.tra); % making the tra matrix sparse will speed up subsequent multiplications, but should % not result in a sparse matrix % note that this only makes sense for matrices with a lot of zero elements, for dense % matrices keeping it full will be much quicker if size(montage.tra,1)>1 && nnz(montage.tra)/numel(montage.tra) < 0.3 montage.tra = sparse(montage.tra); else montage.tra = full(montage.tra); end % update the channel scaling if the input has different units than the montage expects if isfield(input, 'chanunit') && ~isequal(input.chanunit, montage.chanunitold) scale = ft_scalingfactor(input.chanunit, montage.chanunitold); montage.tra = montage.tra * diag(scale); montage.chanunitold = input.chanunit; elseif isfield(input, 'chanunitnew') && ~isequal(input.chanunitnew, montage.chanunitold) scale = ft_scalingfactor(input.chanunitnew, montage.chanunitold); montage.tra = montage.tra * diag(scale); montage.chanunitold = input.chanunitnew; end if isfield(input, 'chantype') && ~isequal(input.chantype, montage.chantypeold) error('inconsistent chantype in data and montage'); elseif isfield(input, 'chantypenew') && ~isequal(input.chantypenew, montage.chantypeold) error('inconsistent chantype in data and montage'); end if isfield(input, 'labelold') && isfield(input, 'labelnew') inputtype = 'montage'; elseif isfield(input, 'tra') inputtype = 'sens'; elseif isfield(input, 'trial') inputtype = 'raw'; elseif isfield(input, 'fourierspctrm') inputtype = 'freq'; else inputtype = 'unknown'; end switch inputtype case 'montage' % apply the montage on top of the other montage if isa(input.tra, 'single') % sparse matrices and single precision do not match input.tra = full(montage.tra) * input.tra; else input.tra = montage.tra * input.tra; end input.labelnew = montage.labelnew; input.chantypenew = montage.chantypenew; input.chanunitnew = montage.chanunitnew; case 'sens' % apply the montage to an electrode or gradiometer description sens = input; clear input % apply the montage to the inputor array if isa(sens.tra, 'single') % sparse matrices and single precision do not match sens.tra = full(montage.tra) * sens.tra; else sens.tra = montage.tra * sens.tra; end % The montage operates on the coil weights in sens.tra, but the output channels % can be different. If possible, we want to keep the original channel positions % and orientations. [sel1, sel2] = match_str(montage.labelnew, inputlabel); keepchans = length(sel1)==length(montage.labelnew); if isfield(sens, 'chanpos') if keepchans sens.chanpos = sens.chanpos(sel2,:); else if ~isfield(sens, 'chanposold') % add a chanposold only if it is not there yet sens.chanposold = sens.chanpos; end sens.chanpos = nan(numel(montage.labelnew),3); end end if isfield(sens, 'chanori') if keepchans sens.chanori = sens.chanori(sel2,:); else if ~isfield(sens, 'chanoriold') sens.chanoriold = sens.chanori; end sens.chanori = nan(numel(montage.labelnew),3); end end sens.label = montage.labelnew; sens.chantype = montage.chantypenew; sens.chanunit = montage.chanunitnew; % keep the % original label, % type and unit % for reference if ~isfield(sens, 'labelold') sens.labelold = inputlabel; end if ~isfield(sens, 'chantypeold') sens.chantypeold = inputchantype; end if ~isfield(sens, 'chanunitold') sens.chanunitold = inputchanunit; end % keep track of the order of the balancing and which one is the current one if istrue(inverse) if isfield(sens, 'balance')% && isfield(sens.balance, 'previous') if isfield(sens.balance, 'previous') && numel(sens.balance.previous)>=1 sens.balance.current = sens.balance.previous{1}; sens.balance.previous = sens.balance.previous(2:end); elseif isfield(sens.balance, 'previous') sens.balance.current = 'none'; sens.balance = rmfield(sens.balance, 'previous'); else sens.balance.current = 'none'; end end elseif ~istrue(inverse) && ~isempty(bname) if isfield(sens, 'balance'), % check whether a balancing montage with name bname already exist, % and if so, how many mnt = fieldnames(sens.balance); sel = strmatch(bname, mnt); if numel(sel)==0, % bname can stay the same elseif numel(sel)==1 % the original should be renamed to 'bname1' and the new one should % be 'bname2' sens.balance.([bname, '1']) = sens.balance.(bname); sens.balance = rmfield(sens.balance, bname); if isfield(sens.balance, 'current') && strcmp(sens.balance.current, bname) sens.balance.current = [bname, '1']; end if isfield(sens.balance, 'previous') sel2 = strmatch(bname, sens.balance.previous); if ~isempty(sel2) sens.balance.previous{sel2} = [bname, '1']; end end bname = [bname, '2']; else bname = [bname, num2str(length(sel)+1)]; end end if isfield(sens, 'balance') && isfield(sens.balance, 'current') if ~isfield(sens.balance, 'previous') sens.balance.previous = {}; end sens.balance.previous = [{sens.balance.current} sens.balance.previous]; sens.balance.current = bname; sens.balance.(bname) = montage; end end % rename the output variable input = sens; clear sens case 'raw'; % apply the montage to the raw data that was preprocessed using fieldtrip data = input; clear input Ntrials = numel(data.trial); ft_progress('init', feedback, 'processing trials'); for i=1:Ntrials ft_progress(i/Ntrials, 'processing trial %d from %d\n', i, Ntrials); if isa(data.trial{i}, 'single') % sparse matrices and single % precision do not match data.trial{i} = full(montage.tra) * data.trial{i}; else data.trial{i} = montage.tra * data.trial{i}; end end ft_progress('close'); data.label = montage.labelnew; data.chantype = montage.chantypenew; data.chanunit = montage.chanunitnew; % rename the output variable input = data; clear data case 'freq' % apply the montage to the spectrally decomposed data freq = input; clear input if strcmp(freq.dimord, 'rpttap_chan_freq') siz = size(freq.fourierspctrm); nrpt = siz(1); nchan = siz(2); nfreq = siz(3); output = zeros(nrpt, size(montage.tra,1), nfreq); for foilop=1:nfreq output(:,:,foilop) = freq.fourierspctrm(:,:,foilop) * montage.tra'; end freq.fourierspctrm = output; % replace the original Fourier spectrum elseif strcmp(freq.dimord, 'rpttap_chan_freq_time') siz = size(freq.fourierspctrm); nrpt = siz(1); nchan = siz(2); nfreq = siz(3); ntime = siz(4); output = zeros(nrpt, size(montage.tra,1), nfreq, ntime); for foilop=1:nfreq for toilop = 1:ntime output(:,:,foilop,toilop) = freq.fourierspctrm(:,:,foilop,toilop) * montage.tra'; end end freq.fourierspctrm = output; % replace the original Fourier spectrum else error('unsupported dimord in frequency data (%s)', freq.dimord); end freq.label = montage.labelnew; freq.chantype = montage.chantypenew; freq.chanunit = montage.chanunitnew; % rename the output variable input = freq; clear freq otherwise error('unrecognized input'); end % switch inputtype % only retain the chantype and/or chanunit if they were present in the input if ~haschantype input = removefields(input, {'chantype', 'chantypeold', 'chantypenew'}); end if ~haschanunit input = removefields(input, {'chanunit', 'chanunitold', 'chanunitnew'}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = indx2logical(x, n) y = false(1,n); y(x) = true; function nowarning(varargin) return function s = removefields(s, fn) for i=1:length(fn) if isfield(s, fn{i}) s = rmfield(s, fn{i}); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION use "old/new" instead of "org/new" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function montage = fixmontage(montage) if isfield(montage, 'labelorg') montage.labelold = montage.labelorg; montage = rmfield(montage, 'labelorg'); end if isfield(montage, 'chantypeorg') montage.chantypeold = montage.chantypeorg; montage = rmfield(montage, 'chantypeorg'); end if isfield(montage, 'chanunitorg') montage.chanunitold = montage.chanunitorg; montage = rmfield(montage, 'chanunitorg'); end
github
lcnbeapp/beapp-master
ft_headmodel_slab.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/ft_headmodel_slab.m
3,563
utf_8
a25dc7acd56e431b9a85280512392362
function headmodel = ft_headmodel_slab(mesh1, mesh2, Pc, varargin) % FT_HEADMODEL_SLAB creates an EEG volume conduction model that % is described with an infinite conductive slab. You can think % of this as two parallel planes containing a mass of conductive % material (e.g. water) and externally to them a non-conductive material % (e.g. air). % % Use as % headmodel = ft_headmodel_slab(mesh1, mesh2, Pc, varargin) % where % mesh1.pos = Nx3 vector specifying N points through which the 'upper' plane is fitted % mesh2.pos = Nx3 vector specifying N points through which the 'lower' plane is fitted % Pc = 1x3 vector specifying the spatial position of a point lying in the conductive slab % (this determines the plane's normal's direction) % % Optional arguments should be specified in key-value pairs and can include % 'sourcemodel' = 'monopole' % 'conductivity' = number , conductivity value of the conductive halfspace (default = 1) % % See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD % Copyright (C) 2012, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ model = ft_getopt(varargin, 'sourcemodel', 'monopole'); cond = ft_getopt(varargin, 'conductivity'); if isempty(cond) warning('Conductivity was not specified, using 1'); cond = 1; end % the description of this volume conduction model consists of the % description of the plane, and a point in the void halfspace % replace pnt with pos mesh1 = fixpos(mesh1); mesh2 = fixpos(mesh2); if isstruct(mesh1) && isfield(mesh1,'pos') pos1 = mesh1.pos; pos2 = mesh2.pos; elseif size(mesh1,2)==3 pos1 = mesh1; pos2 = mesh2; else error('incorrect specification of the geometry'); end % fit a plane to the points [N1,P1] = fit_plane(pos1); [N2,P2] = fit_plane(pos2); % checks if Pc is in the conductive part. If not, flip incond = acos(dot(N1,(Pc-P1)./norm(Pc-P1))) > pi/2; if ~incond N1 = -N1; end incond = acos(dot(N2,(Pc-P2)./norm(Pc-P2))) > pi/2; if ~incond N2 = -N2; end headmodel = []; headmodel.cond = cond; headmodel.pos1 = P1(:)'; % a point that lies on the plane that separates the conductive tissue from the air headmodel.ori1 = N1(:)'; % a unit vector pointing towards the air headmodel.ori1 = headmodel.ori1/norm(headmodel.ori1); headmodel.pos2 = P2(:)'; headmodel.ori2 = N2(:)'; headmodel.ori2 = headmodel.ori2/norm(headmodel.ori2); if strcmpi(model,'monopole') headmodel.type = 'slab_monopole'; else error('unknow method') end function [N,P] = fit_plane(X) % Fits a plane through a number of points in 3D cartesian coordinates P = mean(X,1); % the plane is spanned by this point and by a normal vector X = bsxfun(@minus,X,P); [u, s, v] = svd(X, 0); N = v(:,3); % orientation of the plane, can be in either direction
github
lcnbeapp/beapp-master
ft_prepare_vol_sens.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/ft_prepare_vol_sens.m
26,259
utf_8
225596851f014058749908d3367e615b
function [headmodel, sens] = ft_prepare_vol_sens(headmodel, sens, varargin) % FT_PREPARE_VOL_SENS does some bookkeeping to ensure that the volume % conductor model and the sensor array are ready for subsequent forward % leadfield computations. It takes care of some pre-computations that can % be done efficiently prior to the leadfield calculations. % % Use as % [headmodel, sens] = ft_prepare_vol_sens(headmodel, sens, ...) % with input arguments % headmodel structure with volume conductor definition % sens structure with gradiometer or electrode definition % % The headmodel structure represents a volume conductor model of the head, % its contents depend on the type of model. The sens structure represents a % sensor array, i.e. EEG electrodes or MEG gradiometers. % % Additional options should be specified in key-value pairs and can be % 'channel' cell-array with strings (default = 'all') % 'order' number, for single shell "Nolte" model (default = 10) % % The detailed behaviour of this function depends on whether the input % consists of EEG or MEG and furthermoree depends on the type of volume % conductor model: % - in case of EEG single and concentric sphere models, the electrodes are % projected onto the skin surface. % - in case of EEG boundary element models, the electrodes are projected on % the surface and a blilinear interpoaltion matrix from vertices to % electrodes is computed. % - in case of MEG and a localspheres model, a local sphere is determined % for each coil in the gradiometer definition. % - in case of MEG with a singleshell Nolte model, the volume conduction % model is initialized % In any case channel selection and reordering will be done. The channel % order returned by this function corresponds to the order in the 'channel' % option, or if not specified, to the order in the input sensor array. % % See also FT_COMPUTE_LEADFIELD, FT_READ_VOL, FT_READ_SENS, FT_TRANSFORM_VOL, % FT_TRANSFORM_SENS % Copyright (C) 2004-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if iscell(headmodel) && iscell(sens) % this represents combined EEG, ECoG and/or MEG for i=1:numel(headmodel) [headmodel{i}, sens{i}] = ft_prepare_vol_sens(headmodel{i}, sens{i}, varargin{:}); end return end % get the optional input arguments % fileformat = ft_getopt(varargin, 'fileformat'); channel = ft_getopt(varargin, 'channel', sens.label); % cell-array with channel labels, default is all order = ft_getopt(varargin, 'order', 10); % order of expansion for Nolte method; 10 should be enough for real applications; in simulations it makes sense to go higher % ensure that the sensor description is up-to-date (Aug 2011) sens = ft_datatype_sens(sens); % this is to support volumes saved in mat-files, particularly interpolated if ischar(headmodel) vpath = fileparts(headmodel); % remember the path to the file headmodel = ft_read_vol(headmodel); % replace the filename with the content of the file end % ensure that the volume conduction description is up-to-date (Jul 2012) headmodel = ft_datatype_headmodel(headmodel); % determine whether the input contains EEG or MEG sensors iseeg = ft_senstype(sens, 'eeg'); ismeg = ft_senstype(sens, 'meg'); % determine the skin compartment if ~isfield(headmodel, 'skin_surface') if isfield(headmodel, 'bnd') headmodel.skin_surface = find_outermost_boundary(headmodel.bnd); elseif isfield(headmodel, 'r') && length(headmodel.r)<=4 [dum, headmodel.skin_surface] = max(headmodel.r); end end % determine the inner_skull_surface compartment if ~isfield(headmodel, 'inner_skull_surface') if isfield(headmodel, 'bnd') headmodel.inner_skull_surface = find_innermost_boundary(headmodel.bnd); elseif isfield(headmodel, 'r') && length(headmodel.r)<=4 [dum, headmodel.inner_skull_surface] = min(headmodel.r); end end % otherwise the voltype assignment to an empty struct below won't work if isempty(headmodel) headmodel = []; end % this makes them easier to recognise sens.type = ft_senstype(sens); headmodel.type = ft_voltype(headmodel); if isfield(headmodel, 'unit') && isfield(sens, 'unit') && ~strcmp(headmodel.unit, sens.unit) error('inconsistency in the units of the volume conductor and the sensor array'); end if ismeg && iseeg % this is something that could be implemented relatively easily error('simultaneous EEG and MEG not yet supported'); elseif ~ismeg && ~iseeg error('the input does not look like EEG, nor like MEG'); elseif ismeg % always ensure that there is a linear transfer matrix for combining the coils into gradiometers if ~isfield(sens, 'tra'); Nchans = length(sens.label); Ncoils = size(sens.coilpos,1); if Nchans~=Ncoils error('inconsistent number of channels and coils'); end sens.tra = eye(Nchans, Ncoils); end if ~ft_voltype(headmodel, 'localspheres') % select the desired channels from the gradiometer array [selchan, selsens] = match_str(channel, sens.label); % only keep the desired channels, order them according to the users specification try, sens.chantype = sens.chantype(selsens,:); end try, sens.chanunit = sens.chanunit(selsens,:); end try, sens.chanpos = sens.chanpos (selsens,:); end try, sens.chanori = sens.chanori (selsens,:); end sens.label = sens.label(selsens); sens.tra = sens.tra(selsens,:); else % for the localspheres model it is done further down end % remove the coils that do not contribute to any channel output selcoil = any(sens.tra~=0,1); sens.coilpos = sens.coilpos(selcoil,:); sens.coilori = sens.coilori(selcoil,:); sens.tra = sens.tra(:,selcoil); switch ft_voltype(headmodel) case {'infinite' 'infinite_monopole' 'infinite_currentdipole' 'infinite_magneticdipole'} % nothing to do case 'singlesphere' % nothing to do case 'concentricspheres' % nothing to do case 'neuromag' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if the forward model is computed using the external Neuromag toolbox, % we have to add a selection of the channels so that the channels % in the forward model correspond with those in the data. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [selchan, selsens] = match_str(channel, sens.label); headmodel.chansel = selsens; case 'localspheres' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If the volume conduction model consists of multiple spheres then we % have to match the channels in the gradiometer array and the volume % conduction model. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the initial localspheres volume conductor has a local sphere per % channel, whereas it should have a local sphere for each coil if size(headmodel.r,1)==size(sens.coilpos,1) && ~isfield(headmodel, 'label') % it appears that each coil already has a sphere, which suggests % that the volume conductor already has been prepared to match the % sensor array return elseif size(headmodel.r,1)==size(sens.coilpos,1) && isfield(headmodel, 'label') if ~isequal(headmodel.label(:), sens.label(:)) % if only the order is different, it would be possible to reorder them error('the coils in the volume conduction model do not correspond to the sensor array'); else % the coil-specific spheres in the volume conductor should not have a label % because the label is already specified for the coils in the % sensor array headmodel = rmfield(headmodel, 'label'); end return end % the CTF way of representing the headmodel is one-sphere-per-channel % whereas the FieldTrip way of doing the forward computation is one-sphere-per-coil Nchans = size(sens.tra,1); Ncoils = size(sens.tra,2); Nspheres = size(headmodel.label); if isfield(headmodel, 'orig') % these are present in a CTF *.hdm file singlesphere.o(1,1) = headmodel.orig.MEG_Sphere.ORIGIN_X; singlesphere.o(1,2) = headmodel.orig.MEG_Sphere.ORIGIN_Y; singlesphere.o(1,3) = headmodel.orig.MEG_Sphere.ORIGIN_Z; singlesphere.r = headmodel.orig.MEG_Sphere.RADIUS; % ensure consistent units singlesphere = ft_convert_units(singlesphere, headmodel.unit); % determine the channels that do not have a corresponding sphere % and use the globally fitted single sphere for those missing = setdiff(sens.label, headmodel.label); if ~isempty(missing) warning('using the global fitted single sphere for %d channels that do not have a local sphere', length(missing)); end for i=1:length(missing) headmodel.label(end+1) = missing(i); headmodel.r(end+1,:) = singlesphere.r; headmodel.o(end+1,:) = singlesphere.o; end end % make a new structure that only holds the local spheres, one per coil localspheres = []; localspheres.type = headmodel.type; localspheres.unit = headmodel.unit; % for each coil in the MEG helmet, determine the corresponding channel and from that the corresponding local sphere for i=1:Ncoils coilindex = find(sens.tra(:,i)~=0); % to which channel does this coil belong if length(coilindex)>1 % this indicates that there are multiple channels to which this coil contributes, % which happens if the sensor array represents a synthetic higher-order gradient. [dum, coilindex] = max(abs(sens.tra(:,i))); end coillabel = sens.label{coilindex}; % what is the label of this channel chanindex = find(strcmp(coillabel, headmodel.label)); % what is the index of this channel in the list of local spheres localspheres.r(i,:) = headmodel.r(chanindex); localspheres.o(i,:) = headmodel.o(chanindex,:); end headmodel = localspheres; % finally do the selection of channels and coils % order them according to the users specification [selchan, selsens] = match_str(channel, sens.label); % first only modify the linear combination of coils into channels try, sens.chantype = sens.chantype(selsens,:); end try, sens.chanunit = sens.chanunit(selsens,:); end try, sens.chanpos = sens.chanpos (selsens,:); end try, sens.chanori = sens.chanori (selsens,:); end sens.label = sens.label(selsens); sens.tra = sens.tra(selsens,:); % subsequently remove the coils that do not contribute to any sensor output selcoil = find(sum(sens.tra,1)~=0); sens.coilpos = sens.coilpos(selcoil,:); sens.coilori = sens.coilori(selcoil,:); sens.tra = sens.tra(:,selcoil); % make the same selection of coils in the localspheres model headmodel.r = headmodel.r(selcoil); headmodel.o = headmodel.o(selcoil,:); case 'singleshell' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if the forward model is computed using the code from Guido Nolte, we % have to initialize the volume model using the gradiometer coil % locations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the surface normals for each vertex point if ~isfield(headmodel.bnd, 'nrm') fprintf('computing surface normals\n'); headmodel.bnd.nrm = normals(headmodel.bnd.pos, headmodel.bnd.tri); end % estimate center and radius [center,radius] = fitsphere(headmodel.bnd.pos); % initialize the forward calculation (only if coils are available) if size(sens.coilpos,1)>0 && ~isfield(headmodel, 'forwpar') s = ft_scalingfactor(headmodel.unit, 'cm'); headmodel.forwpar = meg_ini([s*headmodel.bnd.pos headmodel.bnd.nrm], s*center', order, [s*sens.coilpos sens.coilori]); headmodel.forwpar.scale = s; end case 'openmeeg' if isfield(headmodel,'mat') & ~isempty(headmodel.mat) warning('MEG with openmeeg only supported with NEMO lab pipeline. Please omit the mat matrix from the headmodel structure.'); end case 'simbio' error('MEG not yet supported with simbio'); otherwise error('unsupported volume conductor model for MEG'); end elseif iseeg % the electrodes are used, the channel positions are not relevant any more % channel positinos need to be recomputed after projecting the electrodes on the skin if isfield(sens, 'chanpos'); sens = rmfield(sens, 'chanpos'); end % select the desired channels from the electrode array % order them according to the users specification [selchan, selsens] = match_str(channel, sens.label); Nchans = length(sens.label); sens.label = sens.label(selsens); try, sens.chantype = sens.chantype(selsens); end; try, sens.chanunit = sens.chanunit(selsens); end; if isfield(sens, 'tra') % first only modify the linear combination of electrodes into channels sens.tra = sens.tra(selsens,:); % subsequently remove the electrodes that do not contribute to any channel output selelec = any(sens.tra~=0,1); sens.elecpos = sens.elecpos(selelec,:); sens.tra = sens.tra(:,selelec); else % the electrodes and channels are identical sens.elecpos = sens.elecpos(selsens,:); end switch ft_voltype(headmodel) case {'infinite' 'infinite_monopole' 'infinite_currentdipole'} % nothing to do case {'halfspace', 'halfspace_monopole'} % electrodes' all-to-all distances numelec = size(sens.elecpos,1); ref_el = sens.elecpos(1,:); md = dist( (sens.elecpos-repmat(ref_el,[numelec 1]))' ); % take the min distance as reference md = min(md(1,2:end)); pos = sens.elecpos; % scan the electrodes and reposition the ones which are in the % wrong halfspace (projected on the plane)... if not too far away! for i=1:size(pos,1) P = pos(i,:); is_in_empty = acos(dot(headmodel.ori,(P-headmodel.pos)./norm(P-headmodel.pos))) < pi/2; if is_in_empty dPplane = abs(dot(headmodel.ori, headmodel.pos-P, 2)); if dPplane>md error('Some electrodes are too distant from the plane: consider repositioning them') else % project point on plane Ppr = pointproj(P,[headmodel.pos headmodel.ori]); pos(i,:) = Ppr; end end end sens.elecpos = pos; case {'slab_monopole'} % electrodes' all-to-all distances numelc = size(sens.elecpos,1); ref_elc = sens.elecpos(1,:); md = dist( (sens.elecpos-repmat(ref_elc,[numelc 1]))' ); % choose min distance between electrodes md = min(md(1,2:end)); pos = sens.elecpos; % looks for contacts outside the strip which are not too far away % and projects them on the nearest plane for i=1:size(pos,1) P = pos(i,:); instrip1 = acos(dot(headmodel.ori1,(P-headmodel.pos1)./norm(P-headmodel.pos1))) > pi/2; instrip2 = acos(dot(headmodel.ori2,(P-headmodel.pos2)./norm(P-headmodel.pos2))) > pi/2; is_in_empty = ~(instrip1&instrip2); if is_in_empty dPplane1 = abs(dot(headmodel.ori1, headmodel.pos1-P, 2)); dPplane2 = abs(dot(headmodel.ori2, headmodel.pos2-P, 2)); if dPplane1>md && dPplane2>md error('Some electrodes are too distant from the planes: consider repositioning them') elseif dPplane2>dPplane1 % project point on nearest plane Ppr = pointproj(P,[headmodel.pos1 headmodel.ori1]); pos(i,:) = Ppr; else % project point on nearest plane Ppr = pointproj(P,[headmodel.pos2 headmodel.ori2]); pos(i,:) = Ppr; end end end sens.elecpos = pos; case {'singlesphere', 'concentricspheres'} % ensure that the electrodes ly on the skin surface radius = max(headmodel.r); pos = sens.elecpos; if isfield(headmodel, 'o') % shift the the centre of the sphere to the origin pos(:,1) = pos(:,1) - headmodel.o(1); pos(:,2) = pos(:,2) - headmodel.o(2); pos(:,3) = pos(:,3) - headmodel.o(3); end distance = sqrt(sum(pos.^2,2)); % to the center of the sphere if any((abs(distance-radius)/radius)>0.005) warning('electrodes do not lie on skin surface -> using radial projection') end pos = pos * radius ./ [distance distance distance]; if isfield(headmodel, 'o') % shift the center back to the original location pos(:,1) = pos(:,1) + headmodel.o(1); pos(:,2) = pos(:,2) + headmodel.o(2); pos(:,3) = pos(:,3) + headmodel.o(3); end sens.elecpos = pos; case {'bem', 'dipoli', 'asa', 'bemcp', 'openmeeg'} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % do postprocessing of volume and electrodes in case of BEM model %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % project the electrodes on the skin and determine the bilinear interpolation matrix % HACK - use NEMO lab pipeline if mat field is absent for openmeeg (i.e. don't do anything) if ~isfield(headmodel, 'tra') && (isfield(headmodel, 'mat') && ~isempty(headmodel.mat)) % determine boundary corresponding with skin and inner_skull_surface if ~isfield(headmodel, 'skin_surface') headmodel.skin_surface = find_outermost_boundary(headmodel.bnd); fprintf('determining skin compartment (%d)\n', headmodel.skin_surface); end if ~isfield(headmodel, 'source') headmodel.source = find_innermost_boundary(headmodel.bnd); fprintf('determining source compartment (%d)\n', headmodel.source); end if size(headmodel.mat,1)~=size(headmodel.mat,2) && size(headmodel.mat,1)==length(sens.elecpos) fprintf('electrode transfer and system matrix were already combined\n'); else fprintf('projecting electrodes on skin surface\n'); % compute linear interpolation from triangle vertices towards electrodes [el, prj] = project_elec(sens.elecpos, headmodel.bnd(headmodel.skin_surface).pos, headmodel.bnd(headmodel.skin_surface).tri); tra = transfer_elec(headmodel.bnd(headmodel.skin_surface).pos, headmodel.bnd(headmodel.skin_surface).tri, el); % replace the original electrode positions by the projected positions sens.elecpos = prj; if size(headmodel.mat,1)==size(headmodel.bnd(headmodel.skin_surface).pos,1) % construct the transfer from only the skin vertices towards electrodes interp = tra; else % construct the transfer from all vertices (also inner_skull_surface/outer_skull_surface) towards electrodes interp = []; for i=1:length(headmodel.bnd) if i==headmodel.skin_surface interp = [interp, tra]; else interp = [interp, zeros(size(el,1), size(headmodel.bnd(i).pos,1))]; end end end % incorporate the linear interpolation matrix and the system matrix into one matrix % this speeds up the subsequent repeated leadfield computations fprintf('combining electrode transfer and system matrix\n'); if strcmp(ft_voltype(headmodel), 'openmeeg') % check that the external toolbox is present ft_hastoolbox('openmeeg', 1); nb_points_external_surface = size(headmodel.bnd(headmodel.skin_surface).pos,1); headmodel.mat = headmodel.mat((end-nb_points_external_surface+1):end,:); headmodel.mat = interp(:,1:nb_points_external_surface) * headmodel.mat; else % convert to sparse matrix to speed up the subsequent multiplication interp = sparse(interp); headmodel.mat = interp * headmodel.mat; % ensure that the model potential will be average referenced avg = mean(headmodel.mat, 1); headmodel.mat = headmodel.mat - repmat(avg, size(headmodel.mat,1), 1); end end end case 'fns' if isfield(headmodel,'bnd') [el, prj] = project_elec(sens.elecpos, headmodel.bnd.pos, headmodel.bnd.tri); sens.tra = transfer_elec(headmodel.bnd.pos, headmodel.bnd.tri, el); % replace the original electrode positions by the projected positions sens.elecpos = prj; end case 'simbio' % check that the external toolbox is present ft_hastoolbox('simbio', 1); % extract the outer surface bnd = mesh2edge(headmodel); for j=1:length(sens.label) d = bsxfun(@minus, bnd.pos, sens.elecpos(j,:)); [d, i] = min(sum(d.^2, 2)); % replace the position of each electrode by the closest vertex sens.elecpos(j,:) = bnd.pos(i,:); end headmodel.transfer = sb_transfer(headmodel,sens); case 'interpolate' % this is to allow moving leadfield files if ~exist(headmodel.filename{1}, 'file') for i = 1:length(headmodel.filename) [p, f, x] = fileparts(headmodel.filename{i}); headmodel.filename{i} = fullfile(vpath, [f x]); end end matchlab = isequal(sens.label, headmodel.sens.label); matchpos = isequal(sens.elecpos, headmodel.sens.elecpos); matchtra = (~isfield(sens, 'tra') && ~isfield(headmodel.sens, 'tra')) || isequal(sens.tra, headmodel.sens.tra); if matchlab && matchpos && matchtra % the input sensor array matches precisely with the forward model % no further interpolation is needed else % interpolate the channels in the forward model to the desired channels filename = tempname; headmodel = ft_headmodel_interpolate(filename, sens, headmodel); % update the sensor array with the one from the volume conductor sens = headmodel.sens; end % if recomputing interpolation % for the leadfield computations the @nifti object is used to map the image data into memory ft_hastoolbox('spm8up', 1); for i=1:length(headmodel.sens.label) % map each of the leadfield files into memory headmodel.chan{i} = nifti(headmodel.filename{i}); end otherwise error('unsupported volume conductor model for EEG'); end % FIXME this needs careful thought to ensure that the average referencing which is now done here and there, and that the linear interpolation in case of BEM are all dealt with consistently % % always ensure that there is a linear transfer matrix for % % rereferencing the EEG potential % if ~isfield(sens, 'tra'); % sens.tra = eye(length(sens.label)); % end % update the channel positions as the electrodes were projected to the skin surface [pos, ori, lab] = channelposition(sens); [selsens, selpos] = match_str(sens.label, lab); sens.chanpos = nan(length(sens.label),3); sens.chanpos(selsens,:) = pos(selpos,:); end % if iseeg or ismeg if isfield(sens, 'tra') if issparse(sens.tra) && size(sens.tra, 1)==1 % this multiplication would result in a sparse leadfield, which is not what we want % the effect can be demonstrated as sparse(1)*rand(1,10), see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1169#c7 sens.tra = full(sens.tra); elseif ~issparse(sens.tra) && size(sens.tra, 1)>1 % the multiplication of the "sensor" leadfield (electrode or coil) with the tra matrix to get the "channel" leadfield % is faster for most cases if the pre-multiplying weighting matrix is made sparse sens.tra = sparse(sens.tra); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Ppr = pointproj(P,plane) % projects a point on a plane % plane(1:3) is a point on the plane % plane(4:6) is the ori of the plane Ppr = []; ori = plane(4:6); line = [P ori]; % get indices of line and plane which are parallel par = abs(dot(plane(4:6), line(:,4:6), 2))<1e-14; % difference between origins of plane and line dp = plane(1:3) - line(:, 1:3); % Divide only for non parallel vectors (DL) t = dot(ori(~par,:), dp(~par,:), 2)./dot(ori(~par,:), line(~par,4:6), 2); % compute coord of intersection point Ppr(~par, :) = line(~par,1:3) + repmat(t,1,3).*line(~par,4:6); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This function serves as a replacement for the dist function in the Neural % Networks toolbox. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [d] = dist(x) n = size(x,2); d = zeros(n,n); for i=1:n for j=(i+1):n d(i,j) = sqrt(sum((x(:,i)-x(:,j)).^2)); d(j,i) = d(i,j); end end
github
lcnbeapp/beapp-master
ft_headmodel_halfspace.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/ft_headmodel_halfspace.m
3,238
utf_8
1c182d8deabdfeefe195129d7faa2b2d
function headmodel = ft_headmodel_halfspace(mesh, Pc, varargin) % FT_HEADMODEL_HALFSPACE creates an EEG volume conduction model that % is described with an infinite conductive halfspace. You can think % of this as a plane with on one side a infinite mass of conductive % material (e.g. water) and on the other side non-conductive material % (e.g. air). % % Use as % headmodel = ft_headmodel_halfspace(mesh, Pc, ...) % where % mesh.pos = Nx3 vector specifying N points through which a plane is fitted % Pc = 1x3 vector specifying the spatial position of a point lying in the conductive halfspace % (this determines the plane normal's direction) % % Additional optional arguments should be specified as key-value pairs and can include % 'sourcemodel' = string, 'monopole' or 'dipole' (default = 'dipole') % 'conductivity' = number, conductivity value of the conductive halfspace (default = 1) % % See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD % Copyright (C) 2012, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ model = ft_getopt(varargin, 'sourcemodel', 'dipole'); cond = ft_getopt(varargin, 'conductivity'); if isempty(cond) warning('Conductivity was not specified, using 1'); cond = 1; end % the description of this volume conduction model consists of the % description of the plane, and a point in the void halfspace if isstruct(mesh) && isfield(mesh,'pos') pos = mesh.pos; elseif size(mesh,2)==3 pos = mesh; else error('incorrect specification of the geometry'); end % fit a plane to the points [N,P] = fit_plane(pos); % checks if Pc is in the conductive part. If not, flip incond = acos(dot(N,(Pc-P)./norm(Pc-P))) > pi/2; if ~incond N = -N; end headmodel = []; headmodel.cond = cond; headmodel.pos = P(:)'; % a point that lies on the plane that separates the conductive tissue from the air headmodel.ori = N(:)'; % a unit vector pointing towards the air headmodel.ori = headmodel.ori/norm(headmodel.ori); if strcmpi(model,'dipole') headmodel.type = 'halfspace'; elseif strcmpi(model,'monopole') headmodel.type = 'halfspace_monopole'; else error('unknow method') end function [N,P] = fit_plane(X) % Fits a plane through a number of points in 3D cartesian coordinates P = mean(X,1); % the plane is spanned by this point and by a normal vector X = bsxfun(@minus,X,P); [u, s, v] = svd(X, 0); N = v(:,3); % orientation of the plane, can be in either direction
github
lcnbeapp/beapp-master
ft_headmodel_dipoli.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/ft_headmodel_dipoli.m
7,156
utf_8
aa51271ac3c67c39dcc78a6d6937d469
function headmodel = ft_headmodel_dipoli(mesh, varargin) % FT_HEADMODEL_DIPOLI creates a volume conduction model of the head % using the boundary element method (BEM) for EEG. This function takes % as input the triangulated surfaces that describe the boundaries and % returns as output a volume conduction model which can be used to % compute leadfields. % % This implements % Oostendorp TF, van Oosterom A. "Source parameter estimation in % inhomogeneous volume conductors of arbitrary shape." IEEE Trans % Biomed Eng. 1989 Mar;36(3):382-91. % % The implementation of this function uses an external command-line % executable with the name "dipoli" which is provided by Thom Oostendorp. % % Use as % headmodel = ft_headmodel_dipoli(mesh, ...) % % The mesh is given as a boundary or a struct-array of boundaries (surfaces) % % Optional input arguments should be specified in key-value pairs and can % include % isolatedsource = string, 'yes' or 'no' % conductivity = vector, conductivity of each compartment % % See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD % $Id$ ft_hastoolbox('dipoli', 1); % get the optional arguments isolatedsource = ft_getopt(varargin, 'isolatedsource'); conductivity = ft_getopt(varargin, 'conductivity'); if isfield(mesh, 'bnd') mesh = mesh.bnd; end % replace pnt with pos mesh = fixpos(mesh); % start with an empty volume conductor headmodel = []; headmodel.bnd = mesh; % determine the number of compartments numboundaries = numel(headmodel.bnd); % % The following checks can in principle be performed, but are too % % time-consuming. Instead the code here relies on the calling function to % % feed in the correct geometry. % % % % if ~all(surface_closed(headmodel.bnd)) % % error('...'); % % end % % if any(surface_intersection(headmodel.bnd)) % % error('...'); % % end % % if any(surface_selfintersection(headmodel.bnd)) % % error('...'); % % end % % % The following checks should always be done. % headmodel.bnd = surface_orientation(headmodel.bnd, 'outwards'); % might have to be inwards % % order = surface_nesting(headmodel.bnd, 'outsidefirst'); % might have to be insidefirst % headmodel.bnd = headmodel.bnd(order); % FIXME also the cond % if isempty(isolatedsource) if numboundaries>1 % the isolated source compartment is by default the most inner one isolatedsource = true; else isolatedsource = false; end else % convert into a boolean isolatedsource = istrue(isolatedsource); end if isolatedsource fprintf('using isolated source approach\n'); else fprintf('not using isolated source approach\n'); end % determine the desired nesting of the compartments order = surface_nesting(headmodel.bnd, 'outsidefirst'); % rearrange boundaries and conductivities if numel(headmodel.bnd)>1 fprintf('reordering the boundaries to: '); fprintf('%d ', order); fprintf('\n'); % update the order of the compartments headmodel.bnd = headmodel.bnd(order); end if isempty(conductivity) warning('No conductivity is declared, Assuming standard values\n') if numboundaries == 1 conductivity = 1; elseif numboundaries == 3 % skin/skull/brain conductivity = [1 1/80 1] * 0.33; elseif numboundaries == 4 %FIXME: check for better default values here % skin / outer skull / inner skull / brain conductivity = [1 1/80 1 1] * 0.33; else error('Conductivity values are required!') end headmodel.cond = conductivity; else if numel(conductivity)~=numboundaries error('a conductivity value should be specified for each compartment'); end headmodel.cond = conductivity(order); end headmodel.skin_surface = 1; headmodel.source = numboundaries; % this is now the last one if isolatedsource fprintf('using compartment %d for the isolated source approach\n', headmodel.source); else fprintf('not using the isolated source approach\n'); end % find the location of the dipoli binary str = which('dipoli.maci'); [p, f, x] = fileparts(str); dipoli = fullfile(p, f); % without the .m extension switch mexext case {'mexmaci' 'mexmaci64'} % apple computer dipoli = [dipoli '.maci']; case {'mexglnx86' 'mexa64'} % linux computer dipoli = [dipoli '.glnx86']; otherwise error('there is no dipoli executable for your platform'); end fprintf('using the executable "%s"\n', dipoli); % write the triangulations to file prefix = tempname; bndfile = cell(1,numboundaries); bnddip = headmodel.bnd; for i=1:numboundaries bndfile{i} = sprintf('%s_%d.tri', prefix, i); % checks if normals are inwards oriented otherwise flips them ok = checknormals(bnddip(i)); if ~ok fprintf('flipping normals'' direction\n') bnddip(i).tri = fliplr(bnddip(i).tri); end write_tri(bndfile{i}, bnddip(i).pos, bnddip(i).tri); end % these will hold the shell script and the inverted system matrix exefile = [tempname '.sh']; amafile = [tempname '.ama']; fid = fopen(exefile, 'w'); fprintf(fid, '#!/bin/sh\n'); fprintf(fid, '\n'); fprintf(fid, '%s -i %s << EOF\n', dipoli, amafile); for i=1:numboundaries if isolatedsource && headmodel.source==i % the isolated potential approach should be applied using this compartment fprintf(fid, '!%s\n', bndfile{i}); else fprintf(fid, '%s\n', bndfile{i}); end fprintf(fid, '%g\n', headmodel.cond(i)); end fprintf(fid, '\n'); fprintf(fid, '\n'); fprintf(fid, 'EOF\n'); fclose(fid); % ensure that the temporary shell script can be executed dos(sprintf('chmod +x %s', exefile)); try % execute dipoli and read the resulting file dos(exefile); ama = loadama(amafile); headmodel = ama2vol(ama); % This is to maintain the headmodel.bnd convention (outward oriented), whereas % in terms of further calculation it shuold not really matter. % The calculation fo the head model is done with inward normals % (sometimes flipped from the original input). This assures that the % outward oriented mesh is saved outward oriiented in the headmodel structure for i=1:numel(headmodel.bnd) isinw = checknormals(headmodel.bnd(i)); fprintf('flipping the normals outwards, after head matrix calculation\n') if isinw headmodel.bnd(i).tri = fliplr(headmodel.bnd(i).tri); end end catch error('an error ocurred while running the dipoli executable - please look at the screen output'); end % delete the temporary files for i=1:numboundaries delete(bndfile{i}) end delete(amafile); delete(exefile); % remember that it is a dipoli model headmodel.type = 'dipoli'; function ok = checknormals(bnd) % checks if the normals are inward oriented ok = 0; pos = bnd.pos; tri = bnd.tri; % translate to the center org = median(pos,1); pos(:,1) = pos(:,1) - org(1); pos(:,2) = pos(:,2) - org(2); pos(:,3) = pos(:,3) - org(3); w = sum(solid_angle(pos, tri)); if w<0 && (abs(w)-4*pi)<1000*eps % FIXME: this method is rigorous only for star shaped surfaces warning('your normals are outwards oriented\n') ok = 0; elseif w>0 && (abs(w)-4*pi)<1000*eps % warning('your normals are inwards oriented\n') ok = 1; else fprintf('attention: your surface probably is irregular!') ok = 1; end
github
lcnbeapp/beapp-master
ft_headmodel_openmeeg.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/ft_headmodel_openmeeg.m
6,801
utf_8
88866540a84637e828c25e8c1d20d1ed
function headmodel = ft_headmodel_openmeeg(mesh, varargin) % FT_HEADMODEL_OPENMEEG creates a volume conduction model of the % head using the boundary element method (BEM). This function takes % as input the triangulated surfaces that describe the boundaries and % returns as output a volume conduction model which can be used to % compute leadfields. % % This function implements % Gramfort et al. OpenMEEG: opensource software for quasistatic % bioelectromagnetics. Biomedical engineering online (2010) vol. 9 (1) pp. 45 % http://www.biomedical-engineering-online.com/content/9/1/45 % doi:10.1186/1475-925X-9-45 % and % Kybic et al. Generalized head models for MEG/EEG: boundary element method % beyond nested volumes. Phys. Med. Biol. (2006) vol. 51 pp. 1333-1346 % doi:10.1088/0031-9155/51/5/021 % % The implementation in this function is derived from the the OpenMEEG project % and uses external command-line executables. See http://gforge.inria.fr/projects/openmeeg % and http://gforge.inria.fr/frs/?group_id=435. % % Use as % headmodel = ft_headmodel_openmeeg(mesh, ...) % % Optional input arguments should be specified in key-value pairs and can % include % conductivity = vector, conductivity of each compartment % % See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD %$Id$ ft_hastoolbox('openmeeg', 1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the first part is largely shared with the dipoli and bemcp implementation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get the optional arguments conductivity = ft_getopt(varargin, 'conductivity'); % copy the boundaries from the mesh into the volume conduction model if isfield(mesh,'bnd') mesh = mesh.bnd; end % start with an empty volume conductor headmodel = []; headmodel.bnd = mesh; % determine the number of compartments numboundaries = length(headmodel.bnd); % determine the desired nesting of the compartments order = surface_nesting(headmodel.bnd, 'outsidefirst'); % rearrange boundaries and conductivities if numel(headmodel.bnd)>1 fprintf('reordering the boundaries to: '); fprintf('%d ', order); fprintf('\n'); % update the order of the compartments headmodel.bnd = headmodel.bnd(order); end if isempty(conductivity) warning('No conductivity is declared, Assuming standard values\n') if numboundaries == 1 conductivity = 1; elseif numboundaries == 3 % skin/skull/brain conductivity = [1 1/80 1] * 0.33; else error('Conductivity values are required for 2 shells. More than 3 shells not allowed') end headmodel.cond = conductivity; else if numel(conductivity)~=numboundaries error('a conductivity value should be specified for each compartment'); end % update the order of the compartments headmodel.cond = conductivity(order); end headmodel.skin_surface = 1; headmodel.source = numboundaries; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this uses an implementation that was contributed by INRIA Odyssee Team %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % show the license once % openmeeg_license % check that the binaries are ok om_checkombin; % store the current path and change folder to the temporary one tmpfolder = cd; bndom = headmodel.bnd; try cd(tempdir) % write the triangulations to file bndfile = {}; for ii=1:length(bndom) % check if vertices' normals are inward oriented ok = checknormals(bndom(ii)); if ~ok % Flip faces for openmeeg convention (inwards normals) fprintf('flipping normals'' direction\n') bndom(ii).tri = fliplr(bndom(ii).tri); end end for ii=1:length(headmodel.bnd) [junk,tname] = fileparts(tempname); bndfile{ii} = [tname '.tri']; om_save_tri(bndfile{ii}, bndom(ii).pos, bndom(ii).tri); end % these will hold the shell script and the inverted system matrix [tmp,tname] = fileparts(tempname); if ~ispc exefile = [tname '.sh']; else exefile = [tname '.bat']; end [tmp,tname] = fileparts(tempname); condfile = [tname '.cond']; [tmp,tname] = fileparts(tempname); geomfile = [tname '.mesh']; [tmp,tname] = fileparts(tempname); hmfile = [tname '.bin']; [tmp,tname] = fileparts(tempname); hminvfile = [tname '.bin']; % write conductivity and mesh files om_write_geom(geomfile,bndfile); om_write_cond(condfile,headmodel.cond); % Exe file efid = fopen(exefile, 'w'); omp_num_threads = feature('numCores'); if ~ispc fprintf(efid,'#!/usr/bin/env bash\n'); fprintf(efid,['export OMP_NUM_THREADS=',num2str(omp_num_threads),'\n']); fprintf(efid,['om_assemble -HM ./' geomfile ' ./' condfile ' ./' hmfile ' 2>&1 > /dev/null\n']); fprintf(efid,['om_minverser ./' hmfile ' ./' hminvfile ' 2>&1 > /dev/null\n']); else fprintf(efid,['om_assemble -HM ./' geomfile ' ./' condfile ' ./' hmfile '\n']); fprintf(efid,['om_minverser ./' hmfile ' ./' hminvfile '\n']); end fclose(efid); if ~ispc dos(sprintf('chmod +x %s', exefile)); end catch cd(tmpfolder) rethrow(lasterror) end try % execute OpenMEEG and read the resulting file if ispc dos([exefile]); else version = om_getgccversion; if version>3 dos(['./' exefile]); else error('non suitable GCC compiler version (must be superior to gcc3)'); end end headmodel.mat = om_load_sym(hminvfile,'binary'); cleaner(headmodel,bndfile,condfile,geomfile,hmfile,hminvfile,exefile) cd(tmpfolder) catch warning('an error ocurred while running OpenMEEG'); disp(lasterr); cleaner(headmodel,bndfile,condfile,geomfile,hmfile,hminvfile,exefile) cd(tmpfolder) end % remember the type of volume conduction model headmodel.type = 'openmeeg'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cleaner(headmodel,bndfile,condfile,geomfile,hmfile,hminvfile,exefile) % delete the temporary files for i=1:length(headmodel.bnd) delete(bndfile{i}) end delete(condfile); delete(geomfile); delete(hmfile); delete(hminvfile); delete(exefile); function ok = checknormals(bnd) % FIXME: this method is rigorous only for star shaped surfaces ok = 0; pos = bnd.pos; tri = bnd.tri; % translate to the center org = mean(pos,1); pos(:,1) = pos(:,1) - org(1); pos(:,2) = pos(:,2) - org(2); pos(:,3) = pos(:,3) - org(3); w = sum(solid_angle(pos, tri)); if w<0 && (abs(w)-4*pi)<1000*eps ok = 0; warning('your normals are outwards oriented\n') elseif w>0 && (abs(w)-4*pi)<1000*eps ok = 1; % warning('your normals are inwards oriented') else error('your surface probably is irregular\n') ok = 0; end
github
lcnbeapp/beapp-master
ft_datatype_sens.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/ft_datatype_sens.m
22,743
utf_8
fab01996ef9a98c643827fb2767fbaf3
function [sens] = ft_datatype_sens(sens, varargin) % FT_DATATYPE_SENS describes the FieldTrip structure that represents an EEG, ECoG, or % MEG sensor array. This structure is commonly called "elec" for EEG, "grad" for MEG, % "opto" for NIRS, or general "sens" for either one. % % For all sensor types a distinction should be made between the channel (i.e. the % output of the transducer that is A/D converted) and the sensor, which may have some % spatial extent. E.g. with EEG you can have a bipolar channel, where the position of % the channel can be represented as in between the position of the two electrodes. % % The structure for MEG gradiometers and/or magnetometers contains % sens.label = Mx1 cell-array with channel labels % sens.chanpos = Mx3 matrix with channel positions % sens.chanori = Mx3 matrix with channel orientations, used for synthetic planar gradient computation % sens.tra = MxN matrix to combine coils into channels % sens.coilpos = Nx3 matrix with coil positions % sens.coilori = Nx3 matrix with coil orientations % sens.balance = structure containing info about the balancing, See FT_APPLY_MONTAGE % and optionally % sens.chanposold = Mx3 matrix with original channel positions (in case % sens.chanpos has been updated to contain NaNs, e.g. % after ft_componentanalysis) % sens.chanoriold = Mx3 matrix with original channel orientations % sens.labelold = Mx1 cell-array with original channel labels % % The structure for EEG or ECoG channels contains % sens.label = Mx1 cell-array with channel labels % sens.elecpos = Nx3 matrix with electrode positions % sens.chanpos = Mx3 matrix with channel positions (often the same as electrode positions) % sens.tra = MxN matrix to combine electrodes into channels % In case sens.tra is not present in the EEG sensor array, the channels % are assumed to be average referenced. % % The structure for NIRS channels contains % sens.optopos = contains information about the position of the optodes % sens.optotype = contains information about the type of optode (receiver or transmitter) % sens.chanpos = contains information about the position of the channels (i.e. average of optopos) % sens.tra = NxC matrix, boolean, contains information about how receiver and transmitter form channels % sens.wavelength = 1xM vector of all wavelengths that were used % sens.transmits = NxM matrix, boolean, where N is the number of optodes and M the number of wavelengths per transmitter. Specifies what optode is transmitting at what wavelength (or nothing at all, which indicates that it is a receiver) % sens.laserstrength = 1xM vector of the strength of the emitted light of the lasers % % The following fields apply to MEG and EEG % sens.chantype = Mx1 cell-array with the type of the channel, see FT_CHANTYPE % sens.chanunit = Mx1 cell-array with the units of the channel signal, e.g. 'V', 'fT' or 'T/cm', see FT_CHANUNIT % % The following fields are optional % sens.type = string with the type of acquisition system, see FT_SENSTYPE % sens.fid = structure with fiducial information % % Historical fields: % pnt, pos, ori, pnt1, pnt2 % % Revision history: % (2016/latest) The chantype and chanunit have become required fields. % Original channel details are specified with the suffix "old" rather than "org". % All numeric values are represented in double precision. % It is possible to convert the amplitude and distance units (e.g. from T to fT and % from m to mm) and it is possible to express planar and axial gradiometer channels % either in units of amplitude or in units of amplitude/distance (i.e. proper % gradient). % % (2011v2) The chantype and chanunit have been added for MEG. % % (2011v1) To facilitate determining the position of channels (e.g. for plotting) % in case of balanced MEG or bipolar EEG, an explicit distinction has been made % between chanpos+chanori and coilpos+coilori (for MEG) and chanpos and elecpos % (for EEG). The pnt and ori fields are removed % % (2010) Added support for bipolar or otherwise more complex linear combinations % of EEG electrodes using sens.tra, similar to MEG. % % (2009) Noice reduction has been added for MEG systems in the balance field. % % (2006) The optional fields sens.type and sens.unit were added. % % (2003) The initial version was defined, which looked like this for EEG % sens.pnt = Mx3 matrix with electrode positions % sens.label = Mx1 cell-array with channel labels % and like this for MEG % sens.pnt = Nx3 matrix with coil positions % sens.ori = Nx3 matrix with coil orientations % sens.tra = MxN matrix to combine coils into channels % sens.label = Mx1 cell-array with channel labels % % See also FT_READ_SENS, FT_SENSTYPE, FT_CHANTYPE, FT_APPLY_MONTAGE, CTF2GRAD, FIF2GRAD, % BTI2GRAD, YOKOGAWA2GRAD, ITAB2GRAD % Copyright (C) 2011-2016, Robert Oostenveld & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % undocumented options for the 2016 format % amplitude = string, can be 'T' or 'fT' % distance = string, can be 'm', 'cm' or 'mm' % scaling = string, can be 'amplitude' or 'amplitude/distance' % these are for remembering the type on subsequent calls with the same input arguments persistent previous_argin previous_argout current_argin = [{sens} varargin]; if isequal(current_argin, previous_argin) % don't do the whole cheking again, but return the previous output from cache sens = previous_argout{1}; return end % get the optional input arguments, which should be specified as key-value pairs version = ft_getopt(varargin, 'version', 'latest'); amplitude = ft_getopt(varargin, 'amplitude'); % should be 'V' 'uV' 'T' 'mT' 'uT' 'nT' 'pT' 'fT' distance = ft_getopt(varargin, 'distance'); % should be 'm' 'dm' 'cm' 'mm' scaling = ft_getopt(varargin, 'scaling'); % should be 'amplitude' or 'amplitude/distance', the default depends on the senstype if ~isempty(amplitude) && ~any(strcmp(amplitude, {'V' 'uV' 'T' 'mT' 'uT' 'nT' 'pT' 'fT'})) error('unsupported unit of amplitude "%s"', amplitude); end if ~isempty(distance) && ~any(strcmp(distance, {'m' 'dm' 'cm' 'mm'})) error('unsupported unit of distance "%s"', distance); end if strcmp(version, 'latest') version = '2016'; end if isempty(sens) return; end % this is needed further down nchan = length(sens.label); % there are many cases which deal with either eeg or meg ismeg = ft_senstype(sens, 'meg'); switch version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case '2016' % update it to the previous standard version sens = ft_datatype_sens(sens, 'version', '2011v2'); % ensure that all numbers are represented in double precision sens = ft_struct2double(sens); % use "old/new" rather than "org/new" if isfield(sens, 'labelorg') sens.labelold = sens.labelorg; sens = rmfield(sens, 'labelorg'); end if isfield(sens, 'chantypeorg') sens.chantypeold = sens.chantypeorg; sens = rmfield(sens, 'chantypeorg'); end if isfield(sens, 'chanuniteorg') sens.chanunitold = sens.chanunitorg; sens = rmfield(sens, 'chanunitorg'); end if isfield(sens, 'chanposorg') sens.chanposold = sens.chanposorg; sens = rmfield(sens, 'chanposorg'); end if isfield(sens, 'chanoriorg') sens.chanoriold = sens.chanoriorg; sens = rmfield(sens, 'chanoriorg'); end % in version 2011v2 this was optional, now it is required if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown')) sens.chantype = ft_chantype(sens); end % in version 2011v2 this was optional, now it is required if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown')) sens.chanunit = ft_chanunit(sens); end if ~isempty(distance) % update the units of distance, this also updates the tra matrix sens = ft_convert_units(sens, distance); else % determine the default, this may be needed to set the scaling distance = sens.unit; end if ~isempty(amplitude) && isfield(sens, 'tra') % update the tra matrix for the units of amplitude, this ensures that % the leadfield values remain consistent with the units for i=1:nchan if ~isempty(regexp(sens.chanunit{i}, 'm$', 'once')) % this channel is expressed as amplitude per distance sens.tra(i,:) = sens.tra(i,:) * ft_scalingfactor(sens.chanunit{i}, [amplitude '/' distance]); sens.chanunit{i} = [amplitude '/' distance]; elseif ~isempty(regexp(sens.chanunit{i}, '[T|V]$', 'once')) % this channel is expressed as amplitude sens.tra(i,:) = sens.tra(i,:) * ft_scalingfactor(sens.chanunit{i}, amplitude); sens.chanunit{i} = amplitude; else error('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i); end end else % determine the default amplityde, this may be needed to set the scaling if any(~cellfun(@isempty, regexp(sens.chanunit, '^T'))) % one of the channel units starts with T amplitude = 'T'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^fT'))) % one of the channel units starts with fT amplitude = 'fT'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^V'))) % one of the channel units starts with V amplitude = 'V'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^uV'))) % one of the channel units starts with uV amplitude = 'uV'; else % this unknown amplitude will cause a problem if the scaling needs to be changed between amplitude and amplitude/distance amplitude = 'unknown'; end end % perform some sanity checks if ismeg sel_m = ~cellfun(@isempty, regexp(sens.chanunit, '/m$')); sel_dm = ~cellfun(@isempty, regexp(sens.chanunit, '/dm$')); sel_cm = ~cellfun(@isempty, regexp(sens.chanunit, '/cm$')); sel_mm = ~cellfun(@isempty, regexp(sens.chanunit, '/mm$')); if strcmp(sens.unit, 'm') && (any(sel_dm) || any(sel_cm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'dm') && (any(sel_m) || any(sel_cm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'cm') && (any(sel_m) || any(sel_dm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'mm') && (any(sel_m) || any(sel_dm) || any(sel_cm)) error('inconsistent units in input gradiometer'); end % the default should be amplitude/distance for neuromag and amplitude for all others if isempty(scaling) if ft_senstype(sens, 'neuromag') scaling = 'amplitude/distance'; elseif ft_senstype(sens, 'yokogawa440') warning('asuming that the default scaling should be amplitude rather than amplitude/distance'); scaling = 'amplitude'; else scaling = 'amplitude'; end end % update the gradiometer scaling if strcmp(scaling, 'amplitude') && isfield(sens, 'tra') for i=1:nchan if strcmp(sens.chanunit{i}, [amplitude '/' distance]) % this channel is expressed as amplitude per distance coil = find(abs(sens.tra(i,:))~=0); if length(coil)~=2 error('unexpected number of coils contributing to channel %d', i); end baseline = norm(sens.coilpos(coil(1),:) - sens.coilpos(coil(2),:)); sens.tra(i,:) = sens.tra(i,:)*baseline; % scale with the baseline distance sens.chanunit{i} = amplitude; elseif strcmp(sens.chanunit{i}, amplitude) % no conversion needed else % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3144 ft_warning(sprintf('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i)); end % if end % for elseif strcmp(scaling, 'amplitude/distance') && isfield(sens, 'tra') for i=1:nchan if strcmp(sens.chanunit{i}, amplitude) % this channel is expressed as amplitude coil = find(abs(sens.tra(i,:))~=0); if length(coil)==1 || strcmp(sens.chantype{i}, 'megmag') % this is a magnetometer channel, no conversion needed continue elseif length(coil)~=2 error('unexpected number of coils (%d) contributing to channel %s (%d)', length(coil), sens.label{i}, i); end baseline = norm(sens.coilpos(coil(1),:) - sens.coilpos(coil(2),:)); sens.tra(i,:) = sens.tra(i,:)/baseline; % scale with the baseline distance sens.chanunit{i} = [amplitude '/' distance]; elseif strcmp(sens.chanunit{i}, [amplitude '/' distance]) % no conversion needed else % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3144 ft_warning(sprintf('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i)); end % if end % for end % if strcmp scaling else sel_m = ~cellfun(@isempty, regexp(sens.chanunit, '/m$')); sel_dm = ~cellfun(@isempty, regexp(sens.chanunit, '/dm$')); sel_cm = ~cellfun(@isempty, regexp(sens.chanunit, '/cm$')); sel_mm = ~cellfun(@isempty, regexp(sens.chanunit, '/mm$')); if any(sel_m | sel_dm | sel_cm | sel_mm) error('scaling of amplitude/distance has not been considered yet for EEG'); end end % if iseeg or ismeg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case '2011v2' if ~isempty(amplitude) || ~isempty(distance) || ~isempty(scaling) warning('amplitude, distance and scaling are not supported for version "%s"', version); end % This speeds up subsequent calls to ft_senstype and channelposition. % However, if it is not more precise than MEG or EEG, don't keep it in % the output (see further down). if ~isfield(sens, 'type') sens.type = ft_senstype(sens); end if isfield(sens, 'pnt') if ismeg % sensor description is a MEG sensor-array, containing oriented coils sens.coilpos = sens.pnt; sens = rmfield(sens, 'pnt'); sens.coilori = sens.ori; sens = rmfield(sens, 'ori'); else % sensor description is something else, EEG/ECoG etc sens.elecpos = sens.pnt; sens = rmfield(sens, 'pnt'); end end if ~isfield(sens, 'chanpos') if ismeg % sensor description is a MEG sensor-array, containing oriented coils [chanpos, chanori, lab] = channelposition(sens); % the channel order can be different in the two representations [selsens, selpos] = match_str(sens.label, lab); sens.chanpos = nan(length(sens.label), 3); sens.chanori = nan(length(sens.label), 3); % insert the determined position/orientation on the appropriate rows sens.chanpos(selsens,:) = chanpos(selpos,:); sens.chanori(selsens,:) = chanori(selpos,:); if length(selsens)~=length(sens.label) warning('cannot determine the position and orientation for all channels'); end else % sensor description is something else, EEG/ECoG etc % note that chanori will be all NaNs [chanpos, chanori, lab] = channelposition(sens); % the channel order can be different in the two representations [selsens, selpos] = match_str(sens.label, lab); sens.chanpos = nan(length(sens.label), 3); % insert the determined position/orientation on the appropriate rows sens.chanpos(selsens,:) = chanpos(selpos,:); if length(selsens)~=length(sens.label) warning('cannot determine the position and orientation for all channels'); end end end if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown')) if ismeg sens.chantype = ft_chantype(sens); else % for EEG it is not required end end if ~isfield(sens, 'unit') % this should be done prior to calling ft_chanunit, since ft_chanunit uses this for planar neuromag channels sens = ft_convert_units(sens); end if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown')) if ismeg sens.chanunit = ft_chanunit(sens); else % for EEG it is not required end end if any(strcmp(sens.type, {'meg', 'eeg', 'magnetometer', 'electrode', 'unknown'})) % this is not sufficiently informative, so better remove it % see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1806 sens = rmfield(sens, 'type'); end if size(sens.chanpos,1)~=length(sens.label) || ... isfield(sens, 'tra') && size(sens.tra,1)~=length(sens.label) || ... isfield(sens, 'tra') && isfield(sens, 'elecpos') && size(sens.tra,2)~=size(sens.elecpos,1) || ... isfield(sens, 'tra') && isfield(sens, 'coilpos') && size(sens.tra,2)~=size(sens.coilpos,1) || ... isfield(sens, 'tra') && isfield(sens, 'coilori') && size(sens.tra,2)~=size(sens.coilori,1) || ... isfield(sens, 'chanpos') && size(sens.chanpos,1)~=length(sens.label) || ... isfield(sens, 'chanori') && size(sens.chanori,1)~=length(sens.label) error('inconsistent number of channels in sensor description'); end if ismeg % ensure that the magnetometer/gradiometer balancing is specified if ~isfield(sens, 'balance') || ~isfield(sens.balance, 'current') sens.balance.current = 'none'; end % try to add the chantype and chanunit to the CTF G1BR montage if isfield(sens, 'balance') && isfield(sens.balance, 'G1BR') && ~isfield(sens.balance.G1BR, 'chantype') sens.balance.G1BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G1BR.labelorg)); sens.balance.G1BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G1BR.labelorg)); sens.balance.G1BR.chantypenew = repmat({'unknown'}, size(sens.balance.G1BR.labelnew)); sens.balance.G1BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G1BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G1BR.labelorg, sens.label); sens.balance.G1BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G1BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G1BR.labelnew, sens.label); sens.balance.G1BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G1BR.chanunitnew(sel1) = sens.chanunit(sel2); end % idem for G2BR if isfield(sens, 'balance') && isfield(sens.balance, 'G2BR') && ~isfield(sens.balance.G2BR, 'chantype') sens.balance.G2BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G2BR.labelorg)); sens.balance.G2BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G2BR.labelorg)); sens.balance.G2BR.chantypenew = repmat({'unknown'}, size(sens.balance.G2BR.labelnew)); sens.balance.G2BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G2BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G2BR.labelorg, sens.label); sens.balance.G2BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G2BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G2BR.labelnew, sens.label); sens.balance.G2BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G2BR.chanunitnew(sel1) = sens.chanunit(sel2); end % idem for G3BR if isfield(sens, 'balance') && isfield(sens.balance, 'G3BR') && ~isfield(sens.balance.G3BR, 'chantype') sens.balance.G3BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G3BR.labelorg)); sens.balance.G3BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G3BR.labelorg)); sens.balance.G3BR.chantypenew = repmat({'unknown'}, size(sens.balance.G3BR.labelnew)); sens.balance.G3BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G3BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G3BR.labelorg, sens.label); sens.balance.G3BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G3BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G3BR.labelnew, sens.label); sens.balance.G3BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G3BR.chanunitnew(sel1) = sens.chanunit(sel2); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% otherwise error('converting to version %s is not supported', version); end % switch % this makes the display with the "disp" command look better sens = sortfieldnames(sens); % remember the current input and output arguments, so that they can be % reused on a subsequent call in case the same input argument is given current_argout = {sens}; previous_argin = current_argin; previous_argout = current_argout; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b = sortfieldnames(a) fn = sort(fieldnames(a)); for i=1:numel(fn) b.(fn{i}) = a.(fn{i}); end
github
lcnbeapp/beapp-master
pinvNx2.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/pinvNx2.m
1,116
utf_8
a10c4b3cf66f4a8756fdb95d62b5e04a
function y = pinvNx2(x) % PINVNX2 computes a pseudo-inverse of the slices of an Nx2xM real-valued matrix. % Output has dimensionality 2xNxM. This implementation is generally faster % than calling pinv in a for-loop, once M > 2 siz = [size(x) 1]; xtx = zeros([2,2,siz(3:end)]); xtx(1,1,:,:) = sum(x(:,1,:,:).^2,1); xtx(2,2,:,:) = sum(x(:,2,:,:).^2,1); tmp = sum(x(:,1,:,:).*x(:,2,:,:),1); xtx(1,2,:,:) = tmp; xtx(2,1,:,:) = tmp; ixtx = inv2x2(xtx); y = mtimes2xN(ixtx, permute(x, [2 1 3:ndims(x)])); function [d] = inv2x2(x) % INV2X2 computes inverse of matrix x, where x = 2x2xN, using explicit analytic definition adjx = [x(2,2,:,:) -x(1,2,:,:); -x(2,1,:,:) x(1,1,:,:)]; denom = x(1,1,:,:).*x(2,2,:,:) - x(1,2,:,:).*x(2,1,:,:); d = adjx./denom([1 1],[1 1],:,:); function [z] = mtimes2xN(x, y) % MTIMES2XN computes x*y where x = 2x2xM and y = 2xNxM % and output dimensionatity is 2xNxM siz = size(y); z = zeros(siz); for k = 1:siz(2) z(1,k,:,:) = x(1,1,:,:).*y(1,k,:,:) + x(1,2,:,:).*y(2,k,:,:); z(2,k,:,:) = x(2,1,:,:).*y(1,k,:,:) + x(2,2,:,:).*y(2,k,:,:); end
github
lcnbeapp/beapp-master
normals.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/normals.m
2,528
utf_8
96701c7ebda7e6efca8095b3adb6081c
function [nrm] = normals(pnt, tri, opt) % NORMALS compute the surface normals of a triangular mesh % for each triangle or for each vertex % % [nrm] = normals(pnt, tri, opt) % where opt is either 'vertex' or 'triangle' % Copyright (C) 2002-2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin<3 opt='vertex'; elseif (opt(1)=='v' | opt(1)=='V') opt='vertex'; elseif (opt(1)=='t' | opt(1)=='T') opt='triangle'; else error('invalid optional argument'); end npnt = size(pnt,1); ntri = size(tri,1); % shift to center pnt(:,1) = pnt(:,1)-mean(pnt(:,1),1); pnt(:,2) = pnt(:,2)-mean(pnt(:,2),1); pnt(:,3) = pnt(:,3)-mean(pnt(:,3),1); % compute triangle normals % nrm_tri = zeros(ntri, 3); % for i=1:ntri % v2 = pnt(tri(i,2),:) - pnt(tri(i,1),:); % v3 = pnt(tri(i,3),:) - pnt(tri(i,1),:); % nrm_tri(i,:) = cross(v2, v3); % end % vectorized version of the previous part v2 = pnt(tri(:,2),:) - pnt(tri(:,1),:); v3 = pnt(tri(:,3),:) - pnt(tri(:,1),:); nrm_tri = cross(v2, v3); if strcmp(opt, 'vertex') % compute vertex normals nrm_pnt = zeros(npnt, 3); for i=1:ntri nrm_pnt(tri(i,1),:) = nrm_pnt(tri(i,1),:) + nrm_tri(i,:); nrm_pnt(tri(i,2),:) = nrm_pnt(tri(i,2),:) + nrm_tri(i,:); nrm_pnt(tri(i,3),:) = nrm_pnt(tri(i,3),:) + nrm_tri(i,:); end % normalise the direction vectors to have length one nrm = nrm_pnt ./ (sqrt(sum(nrm_pnt.^2, 2)) * ones(1,3)); else % normalise the direction vectors to have length one nrm = nrm_tri ./ (sqrt(sum(nrm_tri.^2, 2)) * ones(1,3)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fast cross product to replace the MATLAB standard version function [c] = cross(a,b) c = [a(:,2).*b(:,3)-a(:,3).*b(:,2) a(:,3).*b(:,1)-a(:,1).*b(:,3) a(:,1).*b(:,2)-a(:,2).*b(:,1)];
github
lcnbeapp/beapp-master
meg_ini.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/meg_ini.m
5,362
utf_8
57aac4444f8347f1d9de9ff52daf0147
function forwpar=meg_ini(vc,center,order,sens,refs,gradlocs,weights) % initializes MEG-forward calculation % usage: forwpar=meg_ini(vc,center,order,sens,refs,gradlocs,weights) % % input: % vc: Nx6 matrix; N is the number of surface points % the first three numbers in each row are the location % and the second three are the orientation of the surface % normal % center: 3x1 vector denoting the center of volume the conductor % order: desired order of spherical spherical harmonics; % for 'real' realistic volume conductors order=10 is o.k % sens: Mx6 matrix containing sensor location and orientation, % format as for vc % refs: optional argument. If provided, refs contains the location and oriantion % (format as sens) of additional sensors which are subtracted from the original % ones. This makes a gradiometer. One can also do this with the % magnetometer version of this program und do the subtraction outside this program, % but the gradiometer version is faster. % gradlocs, weights: optional two arguments (they must come together!). % gradlocs are the location of additional channels (e.g. to calculate % a higher order gradiometer) and weights. The i.th row in weights contains % the weights to correct if the i.th cannel. These extra fields are added! % (has historical reasons). % % output: % forpwar: structure containing all parameters needed for forward calculation % % note: it is assumed that locations are in cm. % Copyright (C) 2003, Guido Nolte % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin==4 if order>0; coeff_sens=getcoeffs(sens,vc,center,order); forwpar=struct('device_sens',sens,'coeff_sens',coeff_sens,'center',center,'order',order); else forwpar=struct('device_sens',sens,'center',center,'order',order); end elseif nargin==5 if order>0; coeff_sens=getcoeffs(sens,vc,center,order); coeff_refs=getcoeffs(refs,vc,center,order); forwpar=struct('device_sens',sens,'device_ref',refs,'coeff_sens',coeff_sens,'coeff_ref',coeff_refs,'center',center,'order',order); else forwpar=struct('device_sens',sens,'device_ref',refs,'center',center,'order',order); end elseif nargin==7; if order>0; coeff_sens=getcoeffs(sens,vc,center,order); coeff_refs=getcoeffs(refs,vc,center,order); coeff_weights=getcoeffs(gradlocs,vc,center,order); forwpar=struct('device_sens',sens,'device_ref',refs,'coeff_sens',coeff_sens,'coeff_ref',coeff_refs,'center',center,'order',order,'device_weights',gradlocs,'coeff_weights',coeff_weights,'weights',weights); else forwpar=struct('device_sens',sens,'device_ref',refs,'center',center,'order',order,'device_weights',gradlocs,'weights',weights); end else error('you must provide 4,5 or 7 arguments'); end return % main function function coeffs=getcoeffs(device,vc,center,order) [ndip,ndum]=size(vc); [nchan,ndum]=size(device); x1=vc(:,1:3)-repmat(center',ndip,1); n1=vc(:,4:6); x2=device(:,1:3)-repmat(center',nchan,1); n2=device(:,4:6); scale=10; nbasis=(order+1)^2-1; [bas,gradbas]=legs(x1,n1,order,scale); bt=leadsphere_all(x1',x2',n2'); n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan); b=dotproduct(n1rep,bt); ctc=gradbas'*gradbas; warning('OFF', 'MATLAB:nearlySingularMatrix'); coeffs=inv(ctc)*gradbas'*b; warning('ON', 'MATLAB:nearlySingularMatrix'); return function field=getfield(source,device,coeffs,center,order) [ndip,ndum]=size(source); [nchan,ndum]=size(device); x1=source(:,1:3)-repmat(center',ndip,1); n1=source(:,4:6); x2=device(:,1:3)-repmat(center',nchan,1); n2=device(:,4:6); %spherical bt=leadsphere_all(x1',x2',n2'); n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan); b=dotproduct(n1rep,bt); field=b'; %correction if order>0 scale=10; [bas,gradbas]=legs(x1,n1,order,scale); nbasis=(order+1)^2-1; coeffs=coeffs(1:nbasis,:); fcorr=gradbas*coeffs; field=field-fcorr'; end return function out=crossproduct(x,y) % usage: out=testprog(x,y) % testprog calculates the cross-product of vector x and y [n,m,k]=size(x); out=zeros(3,m,k); out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:); out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:); out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:); return function out=dotproduct(x,y) % usage: out=dotproduct(x,y) % testprog calculates the dotproduct of vector x and y [n,m,k]=size(x); outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:); out=reshape(outb,m,k); return function result=norms(x) [n,m,k]=size(x); resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2); result=reshape(resultb,m,k); return
github
lcnbeapp/beapp-master
eeg_halfspace_monopole.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/eeg_halfspace_monopole.m
3,463
utf_8
20c31956ac04fd0bf5615016a9aec23e
function [lf] = eeg_halfspace_monopole(rd, elc, vol) % EEG_HALFSPACE_MONOPOLE calculate the halfspace medium leadfield % on positions pnt for a monopole at position rd and conductivity cond % The halfspace solution requires a plane dividing a conductive zone of % conductivity cond, from a non coductive zone (cond = 0) % % [lf] = eeg_halfspace_monopole(rd, elc, cond) % % Implemented from Malmivuo J, Plonsey R, Bioelectromagnetism (1993) % http://www.bem.fi/book/index.htm % Copyright (C) 2011, Cristiano Micheli % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ siz = size(rd); if any(siz==1) % positions are specified as a single vector Npoles = prod(siz)/3; rd = rd(:)'; % ensure that it is a row vector elseif siz(2)==3 % positions are specified as a Nx3 matrix -> reformat to a single vector Npoles = siz(1); rd = rd'; rd = rd(:)'; % ensure that it is a row vector else error('incorrect specification of dipole locations'); end Nelc = size(elc,1); lf = zeros(Nelc,Npoles); for i=1:Npoles % this is the position of dipole "i" pole1 = rd((1:3) + 3*(i-1)); % distances electrodes - corrent poles r1 = elc - ones(Nelc,1) * pole1; % Method of mirror charges: % Defines the position of mirror charge being symmetric to the plane pole2 = get_mirror_pos(pole1,vol); % distances electrodes - mirror charge r2 = elc - ones(Nelc,1) * pole2; % denominator R1 = (4*pi*vol.cond) * (sum(r1' .^2 ) )'; % denominator, mirror term R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) )'; % condition of poles falling in the non conductive halfspace invacuum = acos(dot(vol.ori,(pole1-vol.pnt)./norm(pole1-vol.pnt))) < pi/2; if invacuum warning('a pole lies on the vacuum side of the plane'); lf(:,i) = NaN(Nelc,1); elseif any(R1)==0 warning('a pole coincides with one of the electrodes'); lf(:,i) = NaN(Nelc,1); else lf(:,i) = (1 ./ R1) + (1 ./ R2); end end function P2 = get_mirror_pos(P1,vol) % calculates the position of a point symmetric to pnt with respect to a plane P2 = []; % define the plane pnt = vol.pnt; ori = vol.ori; % already normalized if abs(dot(P1-pnt,ori))<eps warning(sprintf ('point %f %f %f lies in the symmetry plane',P1(1),P1(2),P1(3))) P2 = P1; else % define the plane in parametric form % define a non colinear vector vc with respect to the plane normal vc = [1 0 0]; if abs(cross(ori, vc, 2))<eps vc = [0 1 0]; end % define plane's direction vectors v1 = cross(ori, vc, 2); v1 = v1/norm(v1); v2 = cross(pnt, ori, 2); v2 = v2/norm(v2); plane = [pnt v1 v2]; % distance plane-point P1 d = abs(dot(ori, plane(:,1:3)-P1(:,1:3), 2)); % symmetric point P2 = P1 + 2*d*ori; end
github
lcnbeapp/beapp-master
eeg_halfspace_medium_leadfield.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/eeg_halfspace_medium_leadfield.m
3,463
utf_8
b68f2792331216de0c239ced9734fe42
function [lf] = eeg_halfspace_medium_leadfield(rd, elc, vol) % HALFSPACE_MEDIUM_LEADFIELD calculate the halfspace medium leadfield % on positions pnt for a dipole at position rd and conductivity cond % The halfspace solution requires a plane dividing a conductive zone of % conductivity cond, from a non coductive zone (cond = 0) % % [lf] = halfspace_medium_leadfield(rd, elc, cond) % Copyright (C) 2011, Cristiano Micheli and Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ siz = size(rd); if any(siz==1) % positions are specified as a single vector Ndipoles = prod(siz)/3; rd = rd(:)'; % ensure that it is a row vector elseif siz(2)==3 % positions are specified as a Nx3 matrix -> reformat to a single vector Ndipoles = siz(1); rd = rd'; rd = rd(:)'; % ensure that it is a row vector else error('incorrect specification of dipole locations'); end Nelc = size(elc,1); lf = zeros(Nelc,3*Ndipoles); for i=1:Ndipoles % this is the position of dipole "i" dip1 = rd((1:3) + 3*(i-1)); % distances electrodes - dipole r1 = elc - ones(Nelc,1) * dip1; % Method of mirror dipoles: % Defines the position of mirror dipoles being symmetric to the plane dip2 = get_mirror_pos(dip1,vol); % distances electrodes - mirror dipole r2 = elc - ones(Nelc,1) * dip2; % denominator R1 = (4*pi*vol.cond) * (sum(r1' .^2 ) .^ 1.5)'; % denominator, mirror term R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) .^ 1.5)'; % condition of dipoles falling in the non conductive halfspace invacuum = acos(dot(vol.ori,(dip1-vol.pnt)./norm(dip1-vol.pnt))) < pi/2; if invacuum warning('dipole lies on the vacuum side of the plane'); lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3); elseif any(R1)==0 warning('dipole coincides with one of the electrodes'); lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3); else lf(:,(1:3) + 3*(i-1)) = (r1 ./ [R1 R1 R1]) + (r2 ./ [R2 R2 R2]); end end function P2 = get_mirror_pos(P1,vol) % calculates the position of a point symmetric to pnt with respect to a plane P2 = []; % define the plane pnt = vol.pnt; ori = vol.ori; % already normalized if abs(dot(P1-pnt,ori))<eps warning(sprintf ('point %f %f %f lies in the symmetry plane',P1(1),P1(2),P1(3))) P2 = P1; else % define the plane in parametric form % define a non colinear vector vc with respect to the plane normal vc = [1 0 0]; if abs(cross(ori, vc, 2))<eps vc = [0 1 0]; end % define plane's direction vectors v1 = cross(ori, vc, 2); v1 = v1/norm(v1); v2 = cross(pnt, ori, 2); v2 = v2/norm(v2); plane = [pnt v1 v2]; % distance plane-point P1 d = abs(dot(ori, plane(:,1:3)-P1(:,1:3), 2)); % symmetric point P2 = P1 + 2*d*ori; end
github
lcnbeapp/beapp-master
ft_warning.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/ft_warning.m
7,789
utf_8
d832a7ad5e2f9bb42995e6e5d4caa198
function [ws, warned] = ft_warning(varargin) % FT_WARNING will throw a warning for every unique point in the % stacktrace only, e.g. in a for-loop a warning is thrown only once. % % Use as one of the following % ft_warning(string) % ft_warning(id, string) % Alternatively, you can use ft_warning using a timeout % ft_warning(string, timeout) % ft_warning(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. % % Use as ft_warning('-clear') to clear old warnings from the current % stack % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = ft_warning(...) % or as % ft_warning(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, ft_warning accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = ft_warning(...) % where w is a boolean that indicates whether a warning as been thrown or not. % % Please note that you can NOT use it like this % ft_warning('the value is %d', 10) % instead you should do % ft_warning(sprintf('the value is %d', 10)) % Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ global ft_default warned = false; ws = []; stack = dbstack; if any(strcmp({stack(2:end).file}, 'ft_warning.m')) % don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068 return; end if nargin < 1 error('You need to specify at least a warning message'); end if isstruct(varargin{1}) warning(varargin{1}); return; end if ~isfield(ft_default, 'warning') ft_default.warning = []; end if ~isfield(ft_default.warning, 'stopwatch') ft_default.warning.stopwatch = []; end if ~isfield(ft_default.warning, 'identifier') ft_default.warning.identifier = []; end if ~isfield(ft_default.warning, 'ignore') ft_default.warning.ignore = {}; end % put the arguments we will pass to warning() in this cell array warningArgs = {}; if nargin==3 % calling syntax (id, msg, timeout) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); msg = warningArgs{1}; timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && isequal(varargin{1}, 'off') ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && isequal(varargin{1}, 'on') ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = inf; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); msg = warningArgs{1}; timeout = inf; % default timeout in seconds fname = [warningArgs{1}]; end if ismember(msg, ft_default.warning.ignore) % do not show this warning return; end if isempty(timeout) error('Timeout ill-specified'); end if timeout ~= inf fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures line = []; else % here, we create the fieldname functionA.functionB.functionC... [tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier); if ~isempty(tmpfname), fname = tmpfname; clear tmpfname; end end if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1}) if strcmp(fname, '-clear') % reset all fields if called outside a function ft_default.warning.identifier = []; ft_default.warning.stopwatch = []; else if issubfield(ft_default.warning.identifier, fname) ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname); end end return; end % and add the line number to make this unique for the last function fname = horzcat(fname, line); if ~issubfield('ft_default.warning.stopwatch', fname) ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic); end now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call if ~issubfield(ft_default.warning.identifier, fname) || ... (issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout'])) % create or reset field ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []); % warning never given before or timed out ws = warning(warningArgs{:}); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg); warned = true; else % the warning has been issued before, but has not timed out yet ws = getsubfield(ft_default.warning.identifier, [fname '.ws']); end end % function ft_warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings) % stack(1) is this function, stack(2) is ft_warning stack = dbstack('-completenames'); if size(stack) < 3 fname = []; line = []; return; end i0 = 3; % ignore ft_preamble while strfind(stack(i0).name, 'ft_preamble') i0=i0+1; end fname = horzcat(fixname(stack(end).name)); if ~issubfield(ft_previous_warnings, fixname(stack(end).name)) ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields end for i=numel(stack)-1:-1:(i0) % skip postamble scripts if strncmp(stack(i).name, 'ft_postamble', 12) break; end fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields setsubfield(ft_previous_warnings, fname, []); end end % line of last function call line = ['.line', int2str(stack(i0).line)]; end % function outcome = issubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % outcome = isfield(strct, fname); % end % end % function strct = rmsubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % strct = rmfield(strct, fname); % end % end
github
lcnbeapp/beapp-master
leadsphere_all.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/leadsphere_all.m
2,291
utf_8
3d513e7f5d8a9f4a12ced5392ee85220
function out=leadsphere_chans(xloc,sensorloc,sensorori) % usage: out=leadsphere_chans(xloc,sensorloc,sensorori) % Copyright (C) 2003, Guido Nolte % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ [n,nsens]=size(sensorloc); %n=3 m=? [n,ndip]=size(xloc); xlocrep=reshape(repmat(xloc,1,nsens),3,ndip,nsens); sensorlocrep=reshape(repmat(sensorloc,ndip,1),3,ndip,nsens); sensororirep=reshape(repmat(sensorori,ndip,1),3,ndip,nsens); r2=norms(sensorlocrep); veca=sensorlocrep-xlocrep; a=norms(veca); adotr2=dotproduct(veca,sensorlocrep); gradf1=scal2vec(1./r2.*(a.^2)+adotr2./a+2*a+2*r2); gradf2=scal2vec(a+2*r2+adotr2./a); gradf=gradf1.*sensorlocrep-gradf2.*xlocrep; F=a.*(r2.*a+adotr2); A1=scal2vec(1./F); A2=A1.^2; A3=crossproduct(xlocrep,sensororirep); A4=scal2vec(dotproduct(gradf,sensororirep)); A5=crossproduct(xlocrep,sensorlocrep); out=1e-7*(A3.*A1-(A4.*A2).*A5); %%GRB change return; function out=crossproduct(x,y) [n,m,k]=size(x); out=zeros(3,m,k); out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:); out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:); out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:); return; function out=dotproduct(x,y) [n,m,k]=size(x); outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:); out=reshape(outb,m,k); return; function result=norms(x) [n,m,k]=size(x); resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2); result=reshape(resultb,m,k); return; function result=scal2vec(x) [m,k]=size(x); % result=zeros(3,m,k); % for i=1:3 % result(i,:,:)=x; % end result=reshape(repmat(x(:)', [3 1]), [3 m k]); return
github
lcnbeapp/beapp-master
ft_hastoolbox.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/ft_hastoolbox.m
24,831
utf_8
43bae19e25ce108f013f1c401e497630
function [status] = ft_hastoolbox(toolbox, autoadd, silent) % FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally % it will try to determine the path to the toolbox and install it % automatically. % % Use as % [status] = ft_hastoolbox(toolbox, autoadd, silent) % % autoadd = 0 means that it will not be added % autoadd = 1 means that give an error if it cannot be added % autoadd = 2 means that give a warning if it cannot be added % autoadd = 3 means that it remains silent if it cannot be added % % silent = 0 means that it will give some feedback about adding the toolbox % silent = 1 means that it will not give feedback % Copyright (C) 2005-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before % persistent previous previouspath % % if ~isequal(previouspath, path) % previous = []; % end % % if isempty(previous) % previous = struct; % elseif isfield(previous, fixname(toolbox)) % status = previous.(fixname(toolbox)); % return % end if isdeployed % it is not possible to check the presence of functions or change the path in a compiled application status = 1; return end % this points the user to the website where he/she can download the toolbox url = { 'AFNI' 'see http://afni.nimh.nih.gov' 'DSS' 'see http://www.cis.hut.fi/projects/dss' 'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab' 'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox' 'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM12' 'see http://www.fil.ion.ucl.ac.uk/spm' 'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd' 'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com' 'BIOSIG' 'see http://biosig.sourceforge.net' 'EEG' 'see http://eeg.sourceforge.net' 'EEGSF' 'see http://eeg.sourceforge.net' % alternative name 'MRI' 'see http://eeg.sourceforge.net' % alternative name 'NEUROSHARE' 'see http://www.neuroshare.org' 'BESA' 'see http://www.besa.de/downloads/matlab/ and get the "BESA MATLAB Readers"' 'MATLAB2BESA' 'see http://www.besa.de/downloads/matlab/ and get the "MATLAB to BESA Export functions"' 'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde' 'YOKOGAWA' 'this is deprecated, please use YOKOGAWA_MEG_READER instead' 'YOKOGAWA_MEG_READER' 'see http://www.yokogawa.com/me/me-login-en.htm' 'BEOWULF' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'MENTAT' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth' '4D-VERSION' 'contact Christian Wienbruch' 'COMM' 'see http://www.mathworks.com/products/communications' 'SIGNAL' 'see http://www.mathworks.com/products/signal' 'OPTIM' 'see http://www.mathworks.com/products/optim' 'IMAGE' 'see http://www.mathworks.com/products/image' % Mathworks refers to this as IMAGES 'SPLINES' 'see http://www.mathworks.com/products/splines' 'DISTCOMP' 'see http://www.mathworks.nl/products/parallel-computing/' 'COMPILER' 'see http://www.mathworks.com/products/compiler' 'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica' 'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm' 'FILEIO' 'see http://www.fieldtriptoolbox.org' 'PREPROC' 'see http://www.fieldtriptoolbox.org' 'FORWARD' 'see http://www.fieldtriptoolbox.org' 'INVERSE' 'see http://www.fieldtriptoolbox.org' 'SPECEST' 'see http://www.fieldtriptoolbox.org' 'REALTIME' 'see http://www.fieldtriptoolbox.org' 'PLOTTING' 'see http://www.fieldtriptoolbox.org' 'SPIKE' 'see http://www.fieldtriptoolbox.org' 'CONNECTIVITY' 'see http://www.fieldtriptoolbox.org' 'PEER' 'see http://www.fieldtriptoolbox.org' 'PLOTTING' 'see http://www.fieldtriptoolbox.org' 'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne' 'BCI2000' 'see http://bci2000.org' 'NLXNETCOM' 'see http://www.neuralynx.com' 'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external' 'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php' 'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydesaeter' 'BEMCP' 'contact Christophe Phillips' 'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435' 'PRTOOLS' 'see http://www.prtools.org' 'ITAB' 'contact Stefania Della Penna' 'BSMART' 'see http://www.brain-smart.org' 'PEER' 'see http://www.fieldtriptoolbox.org/development/peer' 'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki' 'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page' 'VGRID' 'see http://www.rheinahrcampus.de/~medsim/vgrid/manual.html' 'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS' 'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti' 'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0' 'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab' 'BCT' 'see http://www.brain-connectivity-toolbox.net/' 'CCA' 'see http://www.imt.liu.se/~magnus/cca or contact Magnus Borga' 'EGI_MFF' 'see http://www.egi.com/ or contact either Phan Luu or Colin Davey at EGI' 'TOOLBOX_GRAPH' 'see http://www.mathworks.com/matlabcentral/fileexchange/5355-toolbox-graph or contact Gabriel Peyre' 'NETCDF' 'see http://www.mathworks.com/matlabcentral/fileexchange/15177' 'MYSQL' 'see http://www.mathworks.com/matlabcentral/fileexchange/8663-mysql-database-connector' 'ISO2MESH' 'see http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?Home or contact Qianqian Fang' 'DATAHASH' 'see http://www.mathworks.com/matlabcentral/fileexchange/31272' 'IBTB' 'see http://www.ibtb.org' 'ICASSO' 'see http://www.cis.hut.fi/projects/ica/icasso' 'XUNIT' 'see http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework' 'PLEXON' 'available from http://www.plexon.com/assets/downloads/sdk/ReadingPLXandDDTfilesinMatlab-mexw.zip' 'MISC' 'various functions that were downloaded from http://www.mathworks.com/matlabcentral/fileexchange and elsewhere' '35625-INFORMATION-THEORY-TOOLBOX' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox' '29046-MUTUAL-INFORMATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox' '14888-MUTUAL-INFORMATION-COMPUTATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/14888-mutual-information-computation' 'PLOT2SVG' 'see http://www.mathworks.com/matlabcentral/fileexchange/7401-scalable-vector-graphics-svg-export-of-figures' 'BRAINSUITE' 'see http://brainsuite.bmap.ucla.edu/processing/additional-tools/' 'BRAINVISA' 'see http://brainvisa.info' 'FILEEXCHANGE' 'see http://www.mathworks.com/matlabcentral/fileexchange/' 'NEURALYNX_V6' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Neuralynx (windows only)' 'NEURALYNX_V3' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Ueli Rutishauser' 'NPMK' 'see https://github.com/BlackrockMicrosystems/NPMK' 'VIDEOMEG' 'see https://github.com/andreyzhd/VideoMEG' 'WAVEFRONT' 'see http://mathworks.com/matlabcentral/fileexchange/27982-wavefront-obj-toolbox' 'NEURONE' 'see http://www.megaemg.com/support/unrestricted-downloads' }; if nargin<2 % default is not to add the path automatically autoadd = 0; end if nargin<3 % default is not to be silent silent = 0; end % determine whether the toolbox is installed toolbox = upper(toolbox); % In case SPM8 or higher not available, allow to use fallback toolbox fallback_toolbox=''; switch toolbox case 'AFNI' dependency={'BrikLoad', 'BrikInfo'}; case 'DSS' dependency={'denss', 'dss_create_state'}; case 'EEGLAB' dependency = 'runica'; case 'NWAY' dependency = 'parafac'; case 'SPM' dependency = 'spm'; % any version of SPM is fine case 'SPM99' dependency = {'spm', get_spm_version()==99}; case 'SPM2' dependency = {'spm', get_spm_version()==2}; case 'SPM5' dependency = {'spm', get_spm_version()==5}; case 'SPM8' dependency = {'spm', get_spm_version()==8}; case 'SPM8UP' % version 8 or later, but not SPM 9X dependency = {'spm', get_spm_version()>=8, get_spm_version()<95}; %This is to avoid crashes when trying to add SPM to the path fallback_toolbox = 'SPM8'; case 'SPM12' dependency = {'spm', get_spm_version()==12}; case 'MEG-PD' dependency = {'rawdata', 'channames'}; case 'MEG-CALC' dependency = {'megmodel', 'megfield', 'megtrans'}; case 'BIOSIG' dependency = {'sopen', 'sread'}; case 'EEG' dependency = {'ctf_read_res4', 'ctf_read_meg4'}; case 'EEGSF' % alternative name dependency = {'ctf_read_res4', 'ctf_read_meg4'}; case 'MRI' % other functions in the mri section dependency = {'avw_hdr_read', 'avw_img_read'}; case 'NEUROSHARE' dependency = {'ns_OpenFile', 'ns_SetLibrary', ... 'ns_GetAnalogData'}; case 'ARTINIS' dependency = {'read_artinis_oxy3'}; case 'BESA' dependency = {'readBESAavr', 'readBESAelp', 'readBESAswf'}; case 'MATLAB2BESA' dependency = {'besa_save2Avr', 'besa_save2Elp', 'besa_save2Swf'}; case 'EEPROBE' dependency = {'read_eep_avr', 'read_eep_cnt'}; case 'YOKOGAWA' dependency = @()hasyokogawa('16bitBeta6'); case 'YOKOGAWA12BITBETA3' dependency = @()hasyokogawa('12bitBeta3'); case 'YOKOGAWA16BITBETA3' dependency = @()hasyokogawa('16bitBeta3'); case 'YOKOGAWA16BITBETA6' dependency = @()hasyokogawa('16bitBeta6'); case 'YOKOGAWA_MEG_READER' dependency = @()hasyokogawa('1.4'); case 'BEOWULF' dependency = {'evalwulf', 'evalwulf', 'evalwulf'}; case 'MENTAT' dependency = {'pcompile', 'pfor', 'peval'}; case 'SON2' dependency = {'SONFileHeader', 'SONChanList', 'SONGetChannel'}; case '4D-VERSION' dependency = {'read4d', 'read4dhdr'}; case {'STATS', 'STATISTICS'} dependency = has_license('statistics_toolbox'); % check the availability of a toolbox license case {'OPTIM', 'OPTIMIZATION'} dependency = has_license('optimization_toolbox'); % check the availability of a toolbox license case {'SPLINES', 'CURVE_FITTING'} dependency = has_license('curve_fitting_toolbox'); % check the availability of a toolbox license case 'COMM' dependency = {has_license('communication_toolbox'), 'de2bi'}; % also check the availability of a toolbox license case 'SIGNAL' dependency = {has_license('signal_toolbox'), 'window'}; % also check the availability of a toolbox license case 'IMAGE' dependency = has_license('image_toolbox'); % check the availability of a toolbox license case {'DCT', 'DISTCOMP'} dependency = has_license('distrib_computing_toolbox'); % check the availability of a toolbox license case 'COMPILER' dependency = has_license('compiler'); % check the availability of a toolbox license case 'FASTICA' dependency = 'fpica'; case 'BRAINSTORM' dependency = 'bem_xfer'; case 'DENOISE' dependency = {'tsr', 'sns'}; case 'CTF' dependency = {'getCTFBalanceCoefs', 'getCTFdata'}; case 'BCI2000' dependency = {'load_bcidat'}; case 'NLXNETCOM' dependency = {'MatlabNetComClient', 'NlxConnectToServer', ... 'NlxGetNewCSCData'}; case 'DIPOLI' dependency = {'dipoli.maci', 'file'}; case 'MNE' dependency = {'fiff_read_meas_info', 'fiff_setup_read_raw'}; case 'TCP_UDP_IP' dependency = {'pnet', 'pnet_getvar', 'pnet_putvar'}; case 'BEMCP' dependency = {'bem_Cij_cog', 'bem_Cij_lin', 'bem_Cij_cst'}; case 'OPENMEEG' dependency = {'om_save_tri'}; case 'PRTOOLS' dependency = {'prversion', 'dataset', 'svc'}; case 'ITAB' dependency = {'lcReadHeader', 'lcReadData'}; case 'BSMART' dependency = 'bsmart'; case 'FREESURFER' dependency = {'MRIread', 'vox2ras_0to1'}; case 'FNS' dependency = 'elecsfwd'; case 'SIMBIO' dependency = {'calc_stiff_matrix_val', 'sb_transfer'}; case 'VGRID' dependency = 'vgrid'; case 'GIFTI' dependency = 'gifti'; case 'XML4MAT' dependency = {'xml2struct', 'xml2whos'}; case 'SQDPROJECT' dependency = {'sqdread', 'sqdwrite'}; case 'BCT' dependency = {'macaque71.mat', 'motif4funct_wei'}; case 'CCA' dependency = {'ccabss'}; case 'EGI_MFF' dependency = {'mff_getObject', 'mff_getSummaryInfo'}; case 'TOOLBOX_GRAPH' dependency = 'toolbox_graph'; case 'NETCDF' dependency = {'netcdf'}; case 'MYSQL' % not sure if 'which' would work fine here, so use 'exist' dependency = has_mex('mysql'); % this only consists of a single mex file case 'ISO2MESH' dependency = {'vol2surf', 'qmeshcut'}; case 'QSUB' dependency = {'qsubfeval', 'qsubcellfun'}; case 'ENGINE' dependency = {'enginefeval', 'enginecellfun'}; case 'DATAHASH' dependency = {'DataHash'}; case 'IBTB' dependency = {'make_ibtb','binr'}; case 'ICASSO' dependency = {'icassoEst'}; case 'XUNIT' dependency = {'initTestSuite', 'runtests'}; case 'PLEXON' dependency = {'plx_adchan_gains', 'mexPlex'}; case '35625-INFORMATION-THEORY-TOOLBOX' dependency = {'conditionalEntropy', 'entropy', 'jointEntropy',... 'mutualInformation' 'nmi' 'nvi' 'relativeEntropy'}; case '29046-MUTUAL-INFORMATION' dependency = {'MI', 'license.txt'}; case '14888-MUTUAL-INFORMATION-COMPUTATION' dependency = {'condentropy', 'demo_mi', 'estcondentropy.cpp',... 'estjointentropy.cpp', 'estpa.cpp', ... 'findjointstateab.cpp', 'makeosmex.m',... 'mutualinfo.m', 'condmutualinfo.m',... 'entropy.m', 'estentropy.cpp',... 'estmutualinfo.cpp', 'estpab.cpp',... 'jointentropy.m' 'mergemultivariables.m' }; case 'PLOT2SVG' dependency = {'plot2svg.m', 'simulink2svg.m'}; case 'BRAINSUITE' dependency = {'readdfs.m', 'writedfc.m'}; case 'BRAINVISA' dependency = {'loadmesh.m', 'plotmesh.m', 'savemesh.m'}; case 'NEURALYNX_V6' dependency = has_mex('Nlx2MatCSC'); case 'NEURALYNX_V3' dependency = has_mex('Nlx2MatCSC_v3'); case 'NPMK' dependency = {'OpenNSx' 'OpenNEV'}; case 'VIDEOMEG' dependency = {'comp_tstamps' 'load_audio0123', 'load_video123'}; case 'WAVEFRONT' dependency = {'write_wobj' 'read_wobj'}; case 'NEURONE' dependency = {'readneurone' 'readneuronedata' 'readneuroneevents'}; % the following are FieldTrip modules/toolboxes case 'FILEIO' dependency = {'ft_read_header', 'ft_read_data', ... 'ft_read_event', 'ft_read_sens'}; case 'FORWARD' dependency = {'ft_compute_leadfield', 'ft_prepare_vol_sens'}; case 'PLOTTING' dependency = {'ft_plot_topo', 'ft_plot_mesh', 'ft_plot_matrix'}; case 'PEER' dependency = {'peerslave', 'peermaster'}; case 'CONNECTIVITY' dependency = {'ft_connectivity_corr', 'ft_connectivity_granger'}; case 'SPIKE' dependency = {'ft_spiketriggeredaverage', 'ft_spiketriggeredspectrum'}; case 'FILEEXCHANGE' dependency = is_subdir_in_fieldtrip_path('/external/fileexchange'); case {'INVERSE', 'REALTIME', 'SPECEST', 'PREPROC', ... 'COMPAT', 'STATFUN', 'TRIALFUN', 'UTILITIES/COMPAT', ... 'FILEIO/COMPAT', 'PREPROC/COMPAT', 'FORWARD/COMPAT', ... 'PLOTTING/COMPAT', 'TEMPLATE/LAYOUT', 'TEMPLATE/ANATOMY' ,... 'TEMPLATE/HEADMODEL', 'TEMPLATE/ELECTRODE', ... 'TEMPLATE/NEIGHBOURS', 'TEMPLATE/SOURCEMODEL'} dependency = is_subdir_in_fieldtrip_path(toolbox); otherwise if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end dependency = false; end status = is_present(dependency); if ~status && ~isempty(fallback_toolbox) % in case of SPM8UP toolbox = fallback_toolbox; end % try to determine the path of the requested toolbox if autoadd>0 && ~status % for core FieldTrip modules prefix = fileparts(which('ft_defaults')); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for external FieldTrip modules prefix = fullfile(fileparts(which('ft_defaults')), 'external'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for contributed FieldTrip extensions prefix = fullfile(fileparts(which('ft_defaults')), 'contrib'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for linux computers in the Donders Centre for Cognitive Neuroimaging prefix = '/home/common/matlab'; if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for windows computers in the Donders Centre for Cognitive Neuroimaging prefix = 'h:\common\matlab'; if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % use the MATLAB subdirectory in your homedirectory, this works on linux and mac prefix = fullfile(getenv('HOME'), 'matlab'); if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end if ~status % the toolbox is not on the path and cannot be added sel = find(strcmp(url(:,1), toolbox)); if ~isempty(sel) msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2}); else msg = sprintf('the %s toolbox is not installed', toolbox); end if autoadd==1 error(msg); elseif autoadd==2 ft_warning(msg); else % fail silently end end end % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before if status previous.(fixname(toolbox)) = status; end % remember the previous path, allows us to determine on the next call % whether the path has been modified outise of this function previouspath = path; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = myaddpath(toolbox, silent) if isdeployed warning('cannot change path settings for %s in a compiled application', toolbox); status = 1; elseif exist(toolbox, 'dir') if ~silent, ws = warning('backtrace', 'off'); warning('adding %s toolbox to your MATLAB path', toolbox); warning(ws); % return to the previous warning level end addpath(toolbox); status = 1; elseif (~isempty(regexp(toolbox, 'spm5$', 'once')) || ~isempty(regexp(toolbox, 'spm8$', 'once')) || ~isempty(regexp(toolbox, 'spm12$', 'once'))) && exist([toolbox 'b'], 'dir') status = myaddpath([toolbox 'b'], silent); else status = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function path = unixpath(path) %path(path=='\') = '/'; % replace backward slashes with forward slashes path = strrep(path,'\','/'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = hasfunction(funname, toolbox) try % call the function without any input arguments, which probably is inapropriate feval(funname); % it might be that the function without any input already works fine status = true; catch % either the function returned an error, or the function is not available % availability is influenced by the function being present and by having a % license for the function, i.e. in a concurrent licensing setting it might % be that all toolbox licenses are in use m = lasterror; if strcmp(m.identifier, 'MATLAB:license:checkouterror') if nargin>1 warning('the %s toolbox is available, but you don''t have a license for it', toolbox); else warning('the function ''%s'' is available, but you don''t have a license for it', funname); end status = false; elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction') status = false; else % the function seems to be available and it gave an unknown error, % which is to be expected with inappropriate input arguments status = true; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = is_subdir_in_fieldtrip_path(toolbox_name) fttrunkpath = unixpath(fileparts(which('ft_defaults'))); fttoolboxpath = fullfile(fttrunkpath, lower(toolbox_name)); needle=[pathsep fttoolboxpath pathsep]; haystack = [pathsep path() pathsep]; status = ~isempty(findstr(needle, haystack)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = has_mex(name) full_name=[name '.' mexext]; status = (exist(full_name, 'file')==3); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function v = get_spm_version() if ~is_present('spm') v=NaN; return end version_str = spm('ver'); token = regexp(version_str,'(\d*)','tokens'); v = str2num([token{:}{:}]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = has_license(toolbox_name) status = license('checkout', toolbox_name)==1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = is_present(dependency) if iscell(dependency) % use recursion status = all(cellfun(@is_present,dependency)); elseif islogical(dependency) % boolean status = all(dependency); elseif ischar(dependency) % name of a function status = is_function_present_in_search_path(dependency); elseif isa(dependency, 'function_handle') status = dependency(); else assert(false,'this should not happen'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = is_function_present_in_search_path(function_name) w = which(function_name); % must be in path and not a variable status = ~isempty(w) && ~isequal(w, 'variable');
github
lcnbeapp/beapp-master
mesh2edge.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/mesh2edge.m
3,713
utf_8
410baaa2ca114acab82443de9a844a68
function [newbnd] = mesh2edge(bnd) % MESH2EDGE finds the edge lines from a triangulated mesh or the edge % surfaces from a tetrahedral or hexahedral mesh. An edge is defined as an % element that does not border any other element. This also implies that a % closed triangulated surface has no edges. % % Use as % [edge] = mesh2edge(mesh) % % See also POLY2TRI % Copyright (C) 2013-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if isfield(bnd, 'tri') % make a list of all edges edge1 = bnd.tri(:, [1 2]); edge2 = bnd.tri(:, [2 3]); edge3 = bnd.tri(:, [3 1]); edge = cat(1, edge1, edge2, edge3); elseif isfield(bnd, 'tet') % make a list of all triangles that form the tetraheder tri1 = bnd.tet(:, [1 2 3]); tri2 = bnd.tet(:, [2 3 4]); tri3 = bnd.tet(:, [3 4 1]); tri4 = bnd.tet(:, [4 1 2]); edge = cat(1, tri1, tri2, tri3, tri4); elseif isfield(bnd, 'hex') % make a list of all "squares" that form the cube/hexaheder % FIXME should be checked, this is impossible without a drawing square1 = bnd.hex(:, [1 2 3 4]); square2 = bnd.hex(:, [5 6 7 8]); square3 = bnd.hex(:, [1 2 6 5]); square4 = bnd.hex(:, [2 3 7 6]); square5 = bnd.hex(:, [3 4 8 7]); square6 = bnd.hex(:, [4 1 5 8]); edge = cat(1, square1, square2, square3, square4, square5, square6); end % isfield(bnd) % soort all polygons in the same direction % keep the original as "edge" and the sorted one as "sedge" sedge = sort(edge, 2); % % find the edges that are not shared -> count the number of occurences % n = size(sedge,1); % occurences = ones(n,1); % for i=1:n % for j=(i+1):n % if all(sedge(i,:)==sedge(j,:)) % occurences(i) = occurences(i)+1; % occurences(j) = occurences(j)+1; % end % end % end % % % make the selection in the original, not the sorted version of the edges % % otherwise the orientation of the edges might get flipped % edge = edge(occurences==1,:); % find the edges that are not shared indx = findsingleoccurringrows(sedge); edge = edge(indx, :); % replace pnt by pos bnd = fixpos(bnd); % the naming of the output edges depends on what they represent newbnd.pos = bnd.pos; if isfield(bnd, 'tri') % these have two vertices in each edge element newbnd.line = edge; elseif isfield(bnd, 'tet') % these have three vertices in each edge element newbnd.tri = edge; elseif isfield(bnd, 'hex') % these have four vertices in each edge element newbnd.poly = edge; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION, see http://bugzilla.fcdonders.nl/show_bug.cgi?id=1833#c12 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function indx = findsingleoccurringrows(X) [X, indx] = sortrows(X); sel = any(diff([X(1,:)-1; X],1),2) & any(diff([X; X(end,:)+1],1),2); indx = indx(sel); function indx = finduniquerows(X) [X, indx] = sortrows(X); sel = any(diff([X(1,:)-1; X],1),2); indx = indx(sel);
github
lcnbeapp/beapp-master
project_elec.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/project_elec.m
3,791
utf_8
61bc3f095e4ced1311048c06823bb037
function [el, prj] = project_elec(elc, pnt, tri) % PROJECT_ELEC projects electrodes on a triangulated surface % and returns triangle index, la/mu parameters and distance % % Use as % [el, prj] = project_elec(elc, pnt, tri) % which returns % el = Nx4 matrix with [tri, la, mu, dist] for each electrode % prj = Nx3 matrix with the projected electrode position % % See also TRANSFER_ELEC % Copyright (C) 1999-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ Nelc = size(elc,1); el = zeros(Nelc, 4); % this is a work-around for http://bugzilla.fcdonders.nl/show_bug.cgi?id=2369 elc = double(elc); pnt = double(pnt); tri = double(tri); for i=1:Nelc [proj,dist] = ptriprojn(pnt(tri(:,1),:), pnt(tri(:,2),:), pnt(tri(:,3),:), elc(i,:), 1); [mindist, minindx] = min(abs(dist)); [la, mu] = lmoutr(pnt(tri(minindx,1),:), pnt(tri(minindx,2),:), pnt(tri(minindx,3),:), proj(minindx,:)); smallest_dist = dist(minindx); smallest_tri = minindx; smallest_la = la; smallest_mu = mu; % the following can be done faster, because the smallest_dist can be % directly selected % Ntri = size(tri,1); % for j=1:Ntri % %[proj, dist] = ptriproj(pnt(tri(j,1),:), pnt(tri(j,2),:), pnt(tri(j,3),:), elc(i,:), 1); % if dist(j)<smallest_dist % % remember the triangle index, distance and la/mu % [la, mu] = lmoutr(pnt(tri(j,1),:), pnt(tri(j,2),:), pnt(tri(j,3),:), proj(j,:)); % smallest_dist = dist(j); % smallest_tri = j; % smallest_la = la; % smallest_mu = mu; % end % end % store the projection for this electrode el(i,:) = [smallest_tri smallest_la smallest_mu smallest_dist]; end if nargout>1 prj = zeros(size(elc)); for i=1:Nelc v1 = pnt(tri(el(i,1),1),:); v2 = pnt(tri(el(i,1),2),:); v3 = pnt(tri(el(i,1),3),:); la = el(i,2); mu = el(i,3); prj(i,:) = routlm(v1, v2, v3, la, mu); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION this is an alternative implementation that will also work for % polygons %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function prj = polyproj(elc,pnt) % projects a point on a plane, e.g. an electrode on a polygon % pnt is a Nx3 matrix with multiple vertices that span the plane % these vertices can be slightly off the plane center = mean(pnt,1); % shift the vertices to have zero mean pnt(:,1) = pnt(:,1) - center(1); pnt(:,2) = pnt(:,2) - center(2); pnt(:,3) = pnt(:,3) - center(3); elc(:,1) = elc(:,1) - center(1); elc(:,2) = elc(:,2) - center(2); elc(:,3) = elc(:,3) - center(3); pnt = pnt'; elc = elc'; [u, s, v] = svd(pnt); % The vertices are assumed to ly in plane, at least reasonably. That means % that from the three eigenvectors there is one which is very small, i.e. % the one orthogonal to the plane. Project the electrodes along that % direction. u(:,3) = 0; prj = u * u' * elc; prj = prj'; prj(:,1) = prj(:,1) + center(1); prj(:,2) = prj(:,2) + center(2); prj(:,3) = prj(:,3) + center(3);
github
lcnbeapp/beapp-master
eeg_slab_monopole.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/eeg_slab_monopole.m
4,375
utf_8
1ffef5225bbeaf47b2a91906c7df7b3a
function [lf] = eeg_slab_monopole(rd, elc, vol) % EEG_SLAB_MONOPOLE calculate the strip medium leadfield % on positions pnt for a monopole at position rd and conductivity cond % The halfspace solution requires a plane dividing a conductive zone of % conductivity cond, from a non coductive zone (cond = 0) % % [lf] = eeg_slab_monopole(rd, elc, cond) % % Implemented from Malmivuo J, Plonsey R, Bioelectromagnetism (1993) % http://www.bem.fi/book/index.htm % Copyright (C) 2011, Cristiano Micheli % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ siz = size(rd); if any(siz==1) % positions are specified as a single vector Npoles = prod(siz)/3; rd = rd(:)'; % ensure that it is a row vector elseif siz(2)==3 % positions are specified as a Nx3 matrix -> reformat to a single vector Npoles = siz(1); rd = rd'; rd = rd(:)'; % ensure that it is a row vector else error('incorrect specification of pole locations'); end Nelc = size(elc,1); lf = zeros(Nelc,Npoles); for i=1:Npoles % this is the position of dipole "i" pole1 = rd((1:3) + 3*(i-1)); % distances electrodes - corrent poles r1 = elc - ones(Nelc,1) * pole1; % Method of mirror charges: % Defines the position of mirror charge being symmetric to the plane [pole2,pole3,pole4] = get_mirror_pos(pole1,vol); % distances electrodes - mirror charge r2 = elc - ones(Nelc,1) * pole2; r3 = elc - ones(Nelc,1) * pole3; r4 = elc - ones(Nelc,1) * pole4; % denominator R1 = (4*pi*vol.cond) * sqrt(sum(r1' .^2 ) )'; % denominator, mirror term R2 = -(4*pi*vol.cond) * sqrt(sum(r2' .^2 ) )'; % denominator, mirror term of P1, plane 2 R3 = -(4*pi*vol.cond) * sqrt(sum(r3' .^2 ) )'; % denominator, mirror term of P2, plane 2 R4 = (4*pi*vol.cond) * sqrt(sum(r4' .^2 ) )'; % condition of poles falling in the non conductive halfspace instrip1 = acos(dot(vol.ori1,(pole1-vol.pnt1)./norm(pole1-vol.pnt1))) > pi/2; instrip2 = acos(dot(vol.ori2,(pole1-vol.pnt2)./norm(pole1-vol.pnt2))) > pi/2; invacuum = ~(instrip1&instrip2); if invacuum warning('a pole lies on the vacuum side of the plane'); lf(:,i) = NaN(Nelc,1); elseif any(R1)==0 warning('a pole coincides with one of the electrodes'); lf(:,i) = NaN(Nelc,1); else lf(:,i) = (1 ./ R1) + (1 ./ R2) + (1 ./ R3);% + (1 ./ R4); end end function [P2,P3,P4] = get_mirror_pos(P1,vol) % calculates the position of a point symmetric to the pole, with respect to plane1 % and two points symmetric to the last ones, with respect to plane2 P2 = []; P3 = []; P4 = []; % define the planes pnt1 = vol.pnt1; ori1 = vol.ori1; pnt2 = vol.pnt2; ori2 = vol.ori2; if abs(dot(P1-pnt1,ori1))<eps || abs(dot(P1-pnt2,ori2))<eps warning(sprintf ('point %f %f %f lies on the plane',P1(1),P1(2),P1(3))) P2 = P1; else % define the planes plane1 = def_plane(pnt1,ori1); plane2 = def_plane(pnt2,ori2); % distance plane1-point P1 d = abs(dot(ori1, plane1(:,1:3)-P1(:,1:3), 2)); % symmetric point P2 = P1 + 2*d*ori1; % distance plane2-point P1 d = abs(dot(ori2, plane2(:,1:3)-P1(:,1:3), 2)); % symmetric point P3 = P1 + 2*d*ori2; % distance plane2-point P2 d = abs(dot(ori2, plane2(:,1:3)-P2(:,1:3), 2)); % symmetric point P4 = P2 + 2*d*ori2; end function plane = def_plane(pnt,ori) % define the plane in parametric form % define a non colinear vector vc with respect to the plane normal vc = [1 0 0]; if abs(cross(ori, vc, 2))<eps vc = [0 1 0]; end % define plane's direction vectors v1 = cross(ori, vc, 2); v1 = v1/norm(v1); v2 = cross(pnt, ori, 2); v2 = v2/norm(v2); plane = [pnt v1 v2];
github
lcnbeapp/beapp-master
eeg_leadfield1.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/eeg_leadfield1.m
3,868
utf_8
84a91d4f1daf6dc32450398058ef4c3c
function lf = eeg_leadfield1(R, elc, vol) % EEG_LEADFIELD1 electric leadfield for a dipole in a single sphere % % [lf] = eeg_leadfield1(R, elc, vol) % % with input arguments % R position dipole (vector of length 3) % elc position electrodes % and vol being a structure with the elements % vol.r radius of sphere % vol.cond conductivity of sphere % % The center of the sphere should be at the origin. % % This implementation is adapted from % Luetkenhoener, Habilschrift '92 % The original reference is % R. Kavanagh, T. M. Darccey, D. Lehmann, and D. H. Fender. Evaluation of methods for three-dimensional localization of electric sources in the human brain. IEEE Trans Biomed Eng, 25:421-429, 1978. % Copyright (C) 2002, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ Nchans = size(elc, 1); lf = zeros(Nchans,3); % always take the outermost sphere, this makes comparison with the 4-sphere computation easier [vol.r, indx] = max(vol.r); vol.cond = vol.cond(indx); % check whether the electrode ly on the sphere, allowing 0.5% tolerance dist = sqrt(sum(elc.^2,2)); if any(abs(dist-vol.r)>vol.r*0.005) warning('electrodes do not ly on sphere surface -> using projection') end elc = vol.r * elc ./ [dist dist dist]; % check whether the dipole is inside the brain [disabled for EEGLAB] % if sqrt(sum(R.^2))>=vol.r % error('dipole is outside the brain compartment'); % end c0 = norm(R); c1 = vol.r; c2 = 4*pi*c0^2*vol.cond; if c0==0 % the dipole is in the origin, this can and should be handeled as an exception [phi, el] = cart2sph(elc(:,1), elc(:,2), elc(:,3)); theta = pi/2 - el; lf(:,1) = sin(theta).*cos(phi); lf(:,2) = sin(theta).*sin(phi); lf(:,3) = cos(theta); % the potential in a homogenous sphere is three times the infinite medium potential lf = 3/(c1^2*4*pi*vol.cond)*lf; else for i=1:Nchans % use another name for the electrode, in accordance with lutkenhoner1992 r = elc(i,:); c3 = r-R; c4 = norm(c3); c5 = c1^2 * c0^2 - dot(r,R)^2; % lutkenhoner A.11 c6 = c0^2*r - dot(r,R)*R; % lutkenhoner, just after A.17 % the original code reads (cf. lutkenhoner1992 equation A.17) % lf(i,:) = ((dot(R, r/norm(r) - (r-R)/norm(r-R))/(norm(cross(r,R))^2) + 2/(norm(r-R)^3)) * cross(R, cross(r, R)) + ((norm(r)^2-norm(R)^2)/(norm(r-R)^3) - 1/norm(r)) * R) / (4*pi*vol.cond(1)*norm(R)^2); % but more efficient execution of the code is achieved by some precomputations if c5<1000*eps % the dipole lies on a single line with the electrode lf(i,:) = (2/c4^3 * c6 + ((c1^2-c0^2)/c4^3 - 1/c1) * R) / c2; else % nothing wrong, do the complete computation lf(i,:) = ((dot(R, r/c1 - c3/c4)/c5 + 2/c4^3) * c6 + ((c1^2-c0^2)/c4^3 - 1/c1) * R) / c2; end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fast cross product function [c] = cross(a,b) c = [a(2)*b(3)-a(3)*b(2) a(3)*b(1)-a(1)*b(3) a(1)*b(2)-a(2)*b(1)]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fast dot product function [c] = dot(a,b) c = sum(a.*b);
github
lcnbeapp/beapp-master
meg_forward.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/meg_forward.m
3,954
utf_8
e674beba8b799e44fadd7b5e0ee82b9a
function field=meg_forward(dip_par,forwpar) % calculates the magnetic field of n dipoles % in a realistic volume conductor % usage: field=meg_forward(dip_par,forwpar) % % input: % dip_par nx6 matrix where each row contains location (first 3 numbers) % and moment (second 3 numbers) of a dipole % forwpar structure containing all information relevant for this % calculation; forwpar is calculated with meg_ini % You have here an option to include linear transformations in % the forward model by specifying forpwar.lintrafo=A % where A is an NxM matrix. Then field -> A field % You can use that, e.g., if you can write the forward model % with M magnetometer-channels plus a matrix multiplication % transforming this to a (eventually higher order) gradiometer. % % output: % field mxn matrix where the i.th column is the field in m channels % of the i.th dipole % % note: No assumptions about units are made (i.e. no scaling factors) % % Copyright (C) 2003, Guido Nolte % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ device_sens=forwpar.device_sens; field_sens_sphere=getfield_sphere(dip_par,forwpar.device_sens,forwpar.center); field=field_sens_sphere;clear field_sens_sphere; if isfield(forwpar,'device_ref') field=field-getfield_sphere(dip_par,forwpar.device_ref,forwpar.center); end if isfield(forwpar,'device_weights') field=field+forwpar.weights*getfield_sphere(dip_par,forwpar.device_weights,forwpar.center); end if forwpar.order>0 coeff=forwpar.coeff_sens; if isfield(forwpar,'device_ref') coeff=coeff-forwpar.coeff_ref; end if isfield(forwpar,'device_weights') coeff=coeff+forwpar.coeff_weights*forwpar.weights'; end field=field+getfield_corr(dip_par,coeff,forwpar.center,forwpar.order); end if isfield(forwpar,'lintrafo'); field=forwpar.lintrafo*field; end return % main function function field=getfield_sphere(source,device,center) [ndip,ndum]=size(source); [nchan,ndum]=size(device); x1=source(:,1:3)-repmat(center',ndip,1); n1=source(:,4:6); x2=device(:,1:3)-repmat(center',nchan,1); n2=device(:,4:6); %spherical bt=leadsphere_all(x1',x2',n2'); n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan); b=dotproduct(n1rep,bt); field=b'; return function field=getfield_corr(source,coeffs,center,order) [ndip,ndum]=size(source); x1=source(:,1:3)-repmat(center',ndip,1); n1=source(:,4:6); %correction if order>0 scale=10; [bas,gradbas]=legs(x1,n1,order,scale); nbasis=(order+1)^2-1; coeffs=coeffs(1:nbasis,:); field=-(gradbas*coeffs)'; end return function out=crossproduct(x,y) % usage: out=testprog(x,y) % testprog calculates the cross-product of vector x and y [n,m,k]=size(x); out=zeros(3,m,k); out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:); out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:); out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:); return function out=dotproduct(x,y) % usage: out=dotproduct(x,y) % testprog calculates the dotproduct of vector x and y [n,m,k]=size(x); outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:); out=reshape(outb,m,k); return function result=norms(x) [n,m,k]=size(x); resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2); result=reshape(resultb,m,k); return
github
lcnbeapp/beapp-master
leadfield_openmeeg.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/forward/private/leadfield_openmeeg.m
16,073
utf_8
59380282979799a30ccf58093f1bc3d8
function [lp, voxels_in] = leadfield_openmeeg ( voxels, vol, sens, varargin ) % FT_OM_COMPUTE_LEAD uses OpenMEEG to compute the lead fields / potentials % using the boundary element method (BEM). % The inputs are as follows: % voxels = an [Nx3] array of voxel locations. % vol = the volume structure containing bnd and cond fields. In % order to save the matrices computed by OpenMEEG, the % fields 'path' and 'basefile' should also be provided. % Matrices will be stored under the directory specified by % 'path' and 'basefile' will be used to generate the % filename. If FT_OM_COMPUTE_LEAD is run with the same % 'path' and 'basefile' parameters and detects the % corresponding files from the OpenMEEG process, it will % use those files for further processing rather than % creating/calculating them again. % sens = the sens structure (elec for EEG or grad for MEG) % % Additional parameters can be specified by setting the following vol % fields: % vol.ecog = "yes"/["no"] allows the computation of lead potentials % for ECoG grids. (sens must be an EEG elec structure) % vol.method = ["hminv"]/"adjoint" to use the adjoint method instead of % the inverse head matrix. % % By default, the BEM will be computed using the inverse head matrix % method. This is slower than the adjoint method, but more efficient if the % BEM needs to be computed multiple times when sensor positions have % moved relative to fixed head coordinates. To implement this type of % computation: % 1) vol.path and vol.basefile should be specified so that OpenMEEG % matrices will be saved. % 2) Once the first BEM is computed, copy the following files to a second % working directory: % - *_hm.bin % - *_hminv.bin % - *_dsm#.bin (where # is a number) % 3) vol.path should be changed to the second working directory and % vol.basefile should remain the same. % 4) Recompute the BEM with the new set of sensor positions and/or voxels. % % Copyright (C) 2013, Daniel D.E. Wong, Sarang S. Dalal % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % vol = fixpos(vol); % renames old subfield 'pnt' to 'pos', if necessary % Variable declarations CPU_LIM = feature('numCores'); VOXCHUNKSIZE = 30000; % if OpenMEEG uses too much memory for a given computer, try reducing VOXCHUNKSIZE om_format = 'binary'; % note that OpenMEEG's mat-file supported is limited in file size (2GB?) switch(om_format) case 'matlab' om_ext = '.mat'; case 'binary' om_ext = '.bin'; otherwise error('invalid OpenMEEG output type requested'); end OPENMEEG_PATH = []; % '/usr/local/bin/'; % In case OpenMEEG executables omitted from PATH variable persistent ldLibraryPath0; if ispc warning('Sorry, Windows is not yet tested'); elseif isunix setenv('OMP_NUM_THREADS',num2str(CPU_LIM)); if(~ismac) % MacOS doesn't use LD_LIBRARY_PATH; in case of problems, look into "DYLD_LIBRARY_PATH" if isempty(ldLibraryPath0) ldLibraryPath0 = getenv('LD_LIBRARY_PATH'); % We'll restore this at the end end UNIX_LDLIBRARYPATH = '/usr/lib:/usr/local/lib'; setenv('LD_LIBRARY_PATH',UNIX_LDLIBRARYPATH); % MATLAB changes the default LD_LIBRARY_PATH variable end end [om_status,om_errmsg] = system(fullfile(OPENMEEG_PATH,'om_assemble')); % returns 0 if om_assemble is not happy if(om_status ~= 0) error([om_errmsg 'Unable to properly execute OpenMEEG. Please configure variable declarations and paths in this file as needed.']); else clear om_status end % Extra options method = ft_getopt(vol,'method','hminv'); ecog = ft_getopt(vol,'ecog','no'); % Use basefile and basepath for saving files if isfield(vol,'basefile') basefile = vol.basefile; else basefile = tempname; end if isfield(vol,'path') path = vol.path; cleanup_flag = false; else path = fullfile(tempdir,'ft-om'); cleanup_flag = true; end mkdir(path); sensorFile = fullfile(path, [basefile '_sensorcoords.txt']); if exist(sensorFile,'file') disp('Sensor coordinate file already exists. Skipping...') else disp('Writing sensor coordinates...') fid = fopen(sensorFile,'w'); if ft_senstype(sens, 'eeg') for ii=1:size(sens.chanpos,1) fprintf(fid,'%s\t%.15f\t%.15f\t%.15f\n', sens.label{ii}, sens.chanpos(ii,:)); end else % MEG % Find channel labels for each coil -- non-trivial for MEG gradiometers! % Note that each coil in a gradiometer pair will receive the same label [chanlabel_idx,coilpos_idx]=find(abs(sens.tra)==1); newchanlabelmethod = true if(newchanlabelmethod) for ii=1:size(sens.coilpos,1) fprintf(fid,'%.15f\t%.15f\t%.15f\t%.15f\t%.15f\t%.15f\n',sens.coilpos(ii,:),sens.coilori(ii,:)); end else if(size(sens.tra,1) < max(chanlabel_idx) | size(sens.tra,2) ~= length(coilpos_idx) | length(coilpos_idx) ~= size(sens.coilpos,1)) % These dimensions should match; if not, some channels may have been % removed, or there's unexpected handling of MEG reference coils error('Mismatch between number of rows in sens.tra and number of channels... possibly some channels removed or unexpected MEG reference coil configuration'); end for ii=1:length(coilpos_idx) coilpair_idx = find(chanlabel_idx(ii) == chanlabel_idx); if(length(coilpair_idx)==2) whichcoil = find(ii == coilpair_idx); switch(whichcoil) case 1 labelsuffix = 'A'; case 2 labelsuffix = 'B'; end else labelsuffix = ''; end label = [sens.label{chanlabel_idx(ii)} labelsuffix]; fprintf(fid,'%s\t%.15f\t%.15f\t%.15f\t%.15f\t%.15f\t%.15f\n',label,sens.coilpos(ii,:),sens.coilori(ii,:)); end end end fclose(fid); end condFile = fullfile(path, [basefile '.cond']); if exist(condFile,'file') disp('Conductivity file already exists. Skipping...') else disp('Writing conductivity file...') write_cond(vol,condFile); end geomFile = fullfile(path, [basefile '.geom']); if exist(geomFile,'file') disp('Geometry descriptor file already exists. Skipping...') else disp('Writing geometry descriptor file...') write_geom(vol,geomFile,basefile); end disp('Writing OpenMEEG mesh files...') write_mesh(vol,path,basefile); disp('Validating mesh...') [om_status om_msg] = system([fullfile(OPENMEEG_PATH, 'om_check_geom'), ' -g ', geomFile]) if(om_status ~= 0) % status = 0 if successful error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']); end disp('Writing dipole file...') chunks = ceil(size(voxels,1)/VOXCHUNKSIZE); dipFile = cell(chunks,1); for ii = 1:chunks dipFile{ii} = fullfile(path, [basefile '_voxels' num2str(ii) om_ext]); if exist(dipFile{ii},'file') fprintf('\t%s already exists. Skipping...\n', dipFile{ii}); else voxidx = ((ii-1)*VOXCHUNKSIZE + 1) : (min((ii)*VOXCHUNKSIZE,size(voxels,1))); writevoxels = [kron(voxels(voxidx,:),ones(3,1)) , kron(ones(length(voxidx),1),eye(3))]; om_save_full(writevoxels,dipFile{ii},om_format); end end hmFile = fullfile(path, [basefile '_hm' om_ext]); if exist(hmFile,'file') disp('Head matrix already exists. Skipping...') else disp('Building head matrix') [om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_assemble'), ' -hm ', geomFile, ' ', condFile, ' ', hmFile]) if(om_status ~= 0) % status = 0 if successful error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']); end end if strcmp(method,'hminv') hminvFile = fullfile(path, [basefile '_hminv' om_ext]); if exist(hminvFile,'file') disp('Inverse head matrix already exists. Skipping...'); else disp('Computing inverse head matrix'); if(CPU_LIM >= 4) % Matlab's inverse function is multithreaded and performs faster with at least 4 cores om_save_sym(inv(om_load_sym(hmFile,om_format)),hminvFile,om_format); else [om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_minverser'), ' ', hmFile, ' ', hminvFile]) if(om_status ~= 0) % status = 0 if successful error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']); end end end end dsmFile = cell(chunks,1); for ii = 1:chunks dsmFile{ii} = fullfile(path, [basefile '_dsm' num2str(ii) om_ext]); if exist(dsmFile{ii},'file') fprintf('\t%s already exists. Skipping...\n', dsmFile{ii}); else disp('Assembling source matrix'); [om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_assemble'), ' -dsm ', geomFile, ' ', condFile, ' ', dipFile{ii}, ' ' dsmFile{ii}]) if(om_status ~= 0) % status = 0 if successful error([om_msg, 'Aborting OpenMEEG pipeline due to above error. If 4-layer BEM attempted, try 3-layer BEM (scalp, skull, brain).']); end end end disp('--------------------------------------') if ft_senstype(sens, 'eeg') if strcmp(ecog,'yes') ohmicFile = fullfile(path, [basefile '_h2ecogm']); cmd = '-h2ecogm'; else ohmicFile = fullfile(path, [basefile '_h2em' om_ext]); cmd = '-h2em'; end else ohmicFile = fullfile(path, [basefile '_h2mm' om_ext]); cmd = '-h2mm'; end if exist(ohmicFile,'file') disp('Ohmic current file already exists. Skipping...') else disp('Calculating Contribution of Ohmic Currents') [om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_assemble'), ' ', cmd, ' ', geomFile, ' ', condFile, ' ' , sensorFile, ' ' , ohmicFile]) if(om_status ~= 0) % status = 0 if successful error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']); end end if ft_senstype(sens, 'meg') disp('Contribution of all sources to the MEG sensors') scFile = cell(chunks,1); for ii = 1:chunks scFile{ii} = fullfile(path, [basefile '_ds2mm' num2str(ii) om_ext]); if exist(scFile{ii},'file') fprintf('\t%s already exists. Skipping...\n',scFile{ii}) else [om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_assemble'), ' -ds2mm ', dipFile{ii} ,' ', sensorFile, ' ' , scFile{ii}]) if(om_status ~= 0) % status = 0 if successful error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']); end end end end disp('Putting it all together.') bemFile = cell(chunks,1); for ii = 1:chunks if ft_senstype(sens, 'eeg') bemFile{ii} = fullfile(path, [basefile '_eeggain' num2str(ii) om_ext]); else bemFile{ii} = fullfile(path, [basefile '_meggain' num2str(ii) om_ext]); end if exist(bemFile{ii},'file') fprintf('/t%s already exists. Skipping...\n', bemFile{ii}); continue; end if strcmp(method,'hminv') if ft_senstype(sens, 'eeg') [om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_gain'), ' -EEG ', hminvFile, ' ', dsmFile{ii}, ' ', ohmicFile, ' ', bemFile{ii}]); else [om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_gain'), ' -MEG ', hminvFile, ' ', dsmFile{ii}, ' ', ohmicFile,' ', scFile{ii}, ' ',bemFile{ii}]); end else % Adjoint method if ft_senstype(sens, 'eeg') [om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_gain'), ' -EEGadjoint ', geomFile, ' ', condFile, ' ', dipFile{ii},' ', hmFile, ' ', ohmicFile, ' ', bemFile{ii}]); else [om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_gain'), ' -MEGadjoint ', geomFile, ' ', condFile, ' ', dipFile{ii},' ', hmFile, ' ', ohmicFile, ' ', scFile{ii}, ' ',bemFile{ii}]); end end if(om_status ~= 0) % status = 0 if successful error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']); end end % Import lead field/potential [g, voxels_in] = import_gain(path, basefile, ft_senstype(sens, 'eeg')); if (voxels_in ~= voxels) & (nargout == 1); warning('Imported voxels from OpenMEEG process not the same as function input.'); end; lp = sens.tra*g; % Mchannels x (3 orientations x Nvoxels) % Cleanup if cleanup_flag rmdir(basepath,'s') end if (isunix & ~ismac) setenv('LD_LIBRARY_PATH',ldLibraryPath0); end function write_cond(vol,filename) fid=fopen(filename,'w'); fprintf(fid,'# Properties Description 1.0 (Conductivities)\n'); tissues = {'Scalp\t%f\n'; 'Skull\t%f\n'; 'CSF\t%f\n'; 'Brain\t%f\n'}; if length(vol.cond)==3; tissues = tissues([1 2 4]); end; fprintf(fid,'Air\t0\n'); for ii=1:length(vol.cond) fprintf(fid,tissues{ii},vol.cond(ii)); end fclose(fid); function write_geom(vol,filename,basepathfile) fid=fopen(filename,'w'); fprintf(fid,'# Domain Description 1.0\n'); fprintf(fid,'Interfaces %i Mesh\n',length(vol.cond)); tissues={'_scalp.tri\n'; '_skull.tri\n'; '_csf.tri\n'; '_brain.tri\n'}; if length(vol.cond)==3; tissues = tissues([1 2 4]); end; for ii = 1:length(vol.cond) fprintf(fid,[basepathfile tissues{ii}]); end fprintf('\n'); fprintf(fid,'Domains %i\n',length(vol.cond)+1); domains={'Scalp'; 'Skull'; 'CSF'; 'Brain'}; if length(vol.cond)==3; domains = domains([1 2 4]); end; fprintf(fid,'Domain Air %i\n',1); for ii = 1:length(vol.cond) if ii < length(vol.cond) fprintf(fid,['Domain ' domains{ii} ' %i -%i\n'],ii+1,ii); else fprintf(fid,['Domain ' domains{ii} ' -%i\n'],ii); end end fclose(fid); function write_mesh(vol,path,basefile) tissues={'_scalp'; '_skull'; '_csf'; '_brain'}; if length(vol.cond)==3; tissues = tissues([1 2 4]); end; for ii = 1:length(vol.cond) meshFile = fullfile(path, [basefile tissues{ii} '.tri']); if exist(meshFile,'file') fprintf('\t%s already exists. Skipping...\n', meshFile); break; else om_save_tri(fullfile(path, [basefile tissues{ii} '.tri']),vol.bnd(ii).pos,vol.bnd(ii).tri); %savemesh([path basefile tissues{ii} '.mesh'],vol.bnd(ii).vertices/1000,vol.bnd(ii).faces-1,-vol.bnd(ii).normals); end end function [g, voxels] = import_gain(path, basefile, eegflag) om_format = 'binary'; switch(om_format) case 'matlab' om_ext = '.mat'; case 'binary' om_ext = '.bin'; otherwise error('invalid OpenMEEG output type requested'); end if eegflag omgainfiles = dir(fullfile(path, [basefile '_eeggain*' om_ext])); else omgainfiles = dir(fullfile(path, [basefile '_meggain*' om_ext])); end omvoxfiles = dir(fullfile(path, [basefile '_voxels*' om_ext])); g=[]; voxels=[]; % join gain/voxel files % [openmeeg calculation may have been split for memory reasons] for ii=1:length(omgainfiles) g = [g om_load_full(fullfile(path, omgainfiles(ii).name),om_format)]; voxels = [voxels;om_load_full(fullfile(path, omvoxfiles(ii).name),om_format)]; end voxels = voxels(1:3:end,1:3);
github
lcnbeapp/beapp-master
firwsord.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/preproc/private/firwsord.m
2,973
utf_8
a2d4fcfe22b1570834add343cd9b6bc0
% firwsord() - Estimate windowed sinc FIR filter order depending on % window type and requested transition band width % % Usage: % >> [m, dev] = firwsord(wtype, fs, df); % >> m = firwsord('kaiser', fs, df, dev); % % Inputs: % wtype - char array window type. 'rectangular', 'bartlett', 'hann', % 'hamming', 'blackman', or 'kaiser' % fs - scalar sampling frequency % df - scalar requested transition band width % dev - scalar maximum passband deviation/ripple (Kaiser window % only) % % Output: % m - scalar estimated filter order % dev - scalar maximum passband deviation/ripple % % References: % [1] Smith, S. W. (1999). The scientist and engineer's guide to % digital signal processing (2nd ed.). San Diego, CA: California % Technical Publishing. % [2] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal % Processing: Principles, Algorithms, and Applications (3rd ed.). % Englewood Cliffs, NJ: Prentice-Hall % [3] Ifeachor E. C., & Jervis B. W. (1993). Digital Signal % Processing: A Practical Approach. Wokingham, UK: Addison-Wesley % % Author: Andreas Widmann, University of Leipzig, 2005 % % See also: % firws, invfirwsord %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005-2014 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % $Id$ function [ m, dev ] = firwsord(wintype, fs, df, dev) winTypeArray = {'rectangular', 'bartlett', 'hann', 'hamming', 'blackman', 'kaiser'}; winDfArray = [0.9 2.9 3.1 3.3 5.5]; winDevArray = [0.089 0.056 0.0063 0.0022 0.0002]; % Check arguments if nargin < 3 || isempty(fs) || isempty(df) || isempty(wintype) error('Not enough input arguments.') end % Window type wintype = find(strcmp(wintype, winTypeArray)); if isempty(wintype) error('Unknown window type.') end df = df / fs; % Normalize transition band width if wintype == 6 % Kaiser window if nargin < 4 || isempty(dev) error('Not enough input arguments.') end devdb = -20 * log10(dev); m = 1 + (devdb - 8) / (2.285 * 2 * pi * df); else m = winDfArray(wintype) / df; dev = winDevArray(wintype); end m = ceil(m / 2) * 2; % Make filter order even (FIR type I) end
github
lcnbeapp/beapp-master
minphaserceps.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/preproc/private/minphaserceps.m
2,151
utf_8
57715581f54dbcadc7e0a0bda70ce5c9
% rcepsminphase() - Convert FIR filter coefficient to minimum phase % % Usage: % >> b = minphaserceps(b); % % Inputs: % b - FIR filter coefficients % % Outputs: % bMinPhase - minimum phase FIR filter coefficients % % Author: Andreas Widmann, University of Leipzig, 2013 % % References: % [1] Smith III, O. J. (2007). Introduction to Digital Filters with Audio % Applications. W3K Publishing. Retrieved Nov 11 2013, from % https://ccrma.stanford.edu/~jos/fp/Matlab_listing_mps_m.html % [2] Vetter, K. (2013, Nov 11). Long FIR filters with low latency. % Retrieved Nov 11 2013, from % http://www.katjaas.nl/minimumphase/minimumphase.html %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2013 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % $Id$ function [bMinPhase] = minphaserceps(b) % Line vector b = b(:)'; n = length(b); upsamplingFactor = 1e3; % Impulse response upsampling/zero padding to reduce time-aliasing nFFT = 2^ceil(log2(n * upsamplingFactor)); % Power of 2 clipThresh = 1e-8; % -160 dB % Spectrum s = abs(fft(b, nFFT)); s(s < clipThresh) = clipThresh; % Clip spectrum to reduce time-aliasing % Real cepstrum c = real(ifft(log(s))); % Fold c = [c(1) [c(2:nFFT / 2) 0] + conj(c(nFFT:-1:nFFT / 2 + 1)) zeros(1, nFFT / 2 - 1)]; % Minimum phase bMinPhase = real(ifft(exp(fft(c)))); % Remove zero-padding bMinPhase = bMinPhase(1:n); end
github
lcnbeapp/beapp-master
firws.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/preproc/private/firws.m
3,217
utf_8
c683c72e05eaadd0e53428ab481f880a
%firws() - Designs windowed sinc type I linear phase FIR filter % % Usage: % >> b = firws(m, f); % >> b = firws(m, f, w); % >> b = firws(m, f, t); % >> b = firws(m, f, t, w); % % Inputs: % m - filter order (mandatory even) % f - vector or scalar of cutoff frequency/ies (-6 dB; % pi rad / sample) % % Optional inputs: % w - vector of length m + 1 defining window {default blackman} % t - 'high' for highpass, 'stop' for bandstop filter {default low-/ % bandpass} % % Output: % b - filter coefficients % % Example: % fs = 500; cutoff = 0.5; df = 1; % m = firwsord('hamming', fs, df); % b = firws(m, cutoff / (fs / 2), 'high', windows('hamming', m + 1)); % % References: % Smith, S. W. (1999). The scientist and engineer's guide to digital % signal processing (2nd ed.). San Diego, CA: California Technical % Publishing. % % Author: Andreas Widmann, University of Leipzig, 2005 % % See also: % firwsord, invfirwsord, kaiserbeta, windows %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % $Id$ function [b, a] = firws(m, f, t, w) a = 1; if nargin < 2 error('Not enough input arguments'); end if length(m) > 1 || ~isnumeric(m) || ~isreal(m) || mod(m, 2) ~= 0 || m < 2 error('Filter order must be a real, even, positive integer.'); end f = f / 2; if any(f <= 0) || any(f >= 0.5) error('Frequencies must fall in range between 0 and 1.'); end if nargin < 3 || isempty(t) t = ''; end if nargin < 4 || isempty(w) if ~isempty(t) && ~ischar(t) w = t; t = ''; else w = windows('blackman', (m + 1)); end end w = w(:)'; % Make window row vector b = fkernel(m, f(1), w); if length(f) == 1 && strcmpi(t, 'high') b = fspecinv(b); end if length(f) == 2 b = b + fspecinv(fkernel(m, f(2), w)); if isempty(t) || ~strcmpi(t, 'stop') b = fspecinv(b); end end % Compute filter kernel function b = fkernel(m, f, w) m = -m / 2 : m / 2; b(m == 0) = 2 * pi * f; % No division by zero b(m ~= 0) = sin(2 * pi * f * m(m ~= 0)) ./ m(m ~= 0); % Sinc b = b .* w; % Window b = b / sum(b); % Normalization to unity gain at DC % Spectral inversion function b = fspecinv(b) b = -b; b(1, (length(b) - 1) / 2 + 1) = b(1, (length(b) - 1) / 2 + 1) + 1;
github
lcnbeapp/beapp-master
kaiserbeta.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/preproc/private/kaiserbeta.m
1,569
utf_8
18e3b152604b8dd8d1bb7052e720f3a6
% kaiserbeta() - Estimate Kaiser window beta % % Usage: % >> beta = pop_kaiserbeta(dev); % % Inputs: % dev - scalar maximum passband deviation/ripple % % Output: % beta - scalar Kaiser window beta % % References: % [1] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal % Processing: Principles, Algorithms, and Applications (3rd ed.). % Englewood Cliffs, NJ: Prentice-Hall % % Author: Andreas Widmann, University of Leipzig, 2005 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005-2014 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % $Id$ function [ beta ] = kaiserbeta(dev) devdb = -20 * log10(dev); if devdb > 50 beta = 0.1102 * (devdb - 8.7); elseif devdb >= 21 beta = 0.5842 * (devdb - 21)^0.4 + 0.07886 * (devdb - 21); else beta = 0; end end
github
lcnbeapp/beapp-master
invfirwsord.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/preproc/private/invfirwsord.m
2,900
utf_8
1ede4ed306eda03dcaa8daffa9426079
% invfirwsord() - Estimate windowed sinc FIR filter transition band width % depending on filter order and window type % % Usage: % >> [df, dev] = invfirwsord(wtype, fs, m); % >> df = invfirwsord('kaiser', fs, m, dev); % % Inputs: % wtype - char array window type. 'rectangular', 'bartlett', 'hann', % 'hamming', 'blackman', or 'kaiser' % fs - scalar sampling frequency} % m - scalar filter order % dev - scalar maximum passband deviation/ripple (Kaiser window % only) % % Output: % df - scalar estimated transition band width % dev - scalar maximum passband deviation/ripple % % References: % [1] Smith, S. W. (1999). The scientist and engineer's guide to % digital signal processing (2nd ed.). San Diego, CA: California % Technical Publishing. % [2] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal % Processing: Principles, Algorithms, and Applications (3rd ed.). % Englewood Cliffs, NJ: Prentice-Hall % [3] Ifeachor E. C., & Jervis B. W. (1993). Digital Signal % Processing: A Practical Approach. Wokingham, UK: Addison-Wesley % % Author: Andreas Widmann, University of Leipzig, 2005 % % See also: % firws, firwsord %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005-2014 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % $Id$ function [ df, dev ] = invfirwsord(wintype, fs, m, dev) winTypeArray = {'rectangular', 'bartlett', 'hann', 'hamming', 'blackman', 'kaiser'}; winDfArray = [0.9 2.9 3.1 3.3 5.5]; winDevArray = [0.089 0.056 0.0063 0.0022 0.0002]; % Check arguments if nargin < 3 || isempty(fs) || isempty(m) || isempty(wintype) error('Not enough input arguments.') end % Window type wintype = find(strcmp(wintype, winTypeArray)); if isempty(wintype) error('Unknown window type.') end if wintype == 6 % Kaiser window if nargin < 4 || isempty(dev) error('Not enough input arguments.') end devdb = -20 * log10(dev); df = (devdb - 8) / (2.285 * 2 * pi * (m - 1)); else df = winDfArray(wintype) / m; dev = winDevArray(wintype); end % df is normalized df = df * fs; end
github
lcnbeapp/beapp-master
windows.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/preproc/private/windows.m
3,152
utf_8
13d9e2d7d608f7550b77f84278c89184
% windows() - Symmetric window functions % % Usage: % >> h = windows(t, m); % >> h = windows(t, m, a); % % Inputs: % t - char array 'rectangular', 'bartlett', 'hann', 'hamming', % 'blackman', 'blackmanharris', 'kaiser', or 'tukey' % m - scalar window length % % Optional inputs: % a - scalar or vector with window parameter(s) % % Output: % w - column vector window % % Author: Andreas Widmann, University of Leipzig, 2014 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2014 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % $Id$ function w = windows(t, m, a) if nargin < 2 || isempty(t) || isempty(m) error('Not enough input arguments.'); end % Check window length if m ~= round(m) m = round(m); warning('firws:nonIntegerWindowLength', 'Non-integer window length. Rounding to integer.') end if m < 1 error('Invalid window length.') end % Length 1 if m == 1 w = 1; return; end % Even/odd? isOddLength = mod(m, 2); if isOddLength x = (0:(m - 1) / 2)' / (m - 1); else x = (0:m / 2 - 1)' / (m - 1); end switch t case 'rectangular' w = ones(length(x), 1); case 'bartlett' w = 2 * x; case 'hann' a = 0.5; w = a - (1 - a) * cos(2 * pi * x); case 'hamming' a = 0.54; w = a - (1 - a) * cos(2 * pi * x); case 'blackman' a = [0.42 0.5 0.08 0]; w = a(1) - a(2) * cos (2 * pi * x) + a(3) * cos(4 * pi * x) - a(4) * cos(6 * pi * x); case 'blackmanharris' a = [0.35875 0.48829 0.14128 0.01168]; w = a(1) - a(2) * cos (2 * pi * x) + a(3) * cos(4 * pi * x) - a(4) * cos(6 * pi * x); case 'kaiser' if nargin < 3 || isempty(a) a = 0.5; end w = besseli(0, a * sqrt(1 - (2 * x - 1).^2)) / besseli(0, a); case 'tukey' if nargin < 3 || isempty(a) a = 0.5; end if a <= 0 % Rectangular w = ones(length(x), 1); elseif a >= 1 % Hann w = 0.5 - (1 - 0.5) * cos(2 * pi * x); else mTaper = floor((m - 1) * a / 2) + 1; xTaper = 2 * (0:mTaper - 1)' / (a * (m - 1)) - 1; w = [0.5 * (1 + cos(pi * xTaper)); ones(length(x) - mTaper, 1)]; end otherwise error('Unkown window type') end % Make symmetric if isOddLength w = [w; w(end - 1:-1:1)]; else w = [w; w(end:-1:1)]; end end
github
lcnbeapp/beapp-master
ft_warning.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/preproc/private/ft_warning.m
7,789
utf_8
d832a7ad5e2f9bb42995e6e5d4caa198
function [ws, warned] = ft_warning(varargin) % FT_WARNING will throw a warning for every unique point in the % stacktrace only, e.g. in a for-loop a warning is thrown only once. % % Use as one of the following % ft_warning(string) % ft_warning(id, string) % Alternatively, you can use ft_warning using a timeout % ft_warning(string, timeout) % ft_warning(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. % % Use as ft_warning('-clear') to clear old warnings from the current % stack % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = ft_warning(...) % or as % ft_warning(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, ft_warning accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = ft_warning(...) % where w is a boolean that indicates whether a warning as been thrown or not. % % Please note that you can NOT use it like this % ft_warning('the value is %d', 10) % instead you should do % ft_warning(sprintf('the value is %d', 10)) % Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ global ft_default warned = false; ws = []; stack = dbstack; if any(strcmp({stack(2:end).file}, 'ft_warning.m')) % don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068 return; end if nargin < 1 error('You need to specify at least a warning message'); end if isstruct(varargin{1}) warning(varargin{1}); return; end if ~isfield(ft_default, 'warning') ft_default.warning = []; end if ~isfield(ft_default.warning, 'stopwatch') ft_default.warning.stopwatch = []; end if ~isfield(ft_default.warning, 'identifier') ft_default.warning.identifier = []; end if ~isfield(ft_default.warning, 'ignore') ft_default.warning.ignore = {}; end % put the arguments we will pass to warning() in this cell array warningArgs = {}; if nargin==3 % calling syntax (id, msg, timeout) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); msg = warningArgs{1}; timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && isequal(varargin{1}, 'off') ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && isequal(varargin{1}, 'on') ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = inf; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); msg = warningArgs{1}; timeout = inf; % default timeout in seconds fname = [warningArgs{1}]; end if ismember(msg, ft_default.warning.ignore) % do not show this warning return; end if isempty(timeout) error('Timeout ill-specified'); end if timeout ~= inf fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures line = []; else % here, we create the fieldname functionA.functionB.functionC... [tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier); if ~isempty(tmpfname), fname = tmpfname; clear tmpfname; end end if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1}) if strcmp(fname, '-clear') % reset all fields if called outside a function ft_default.warning.identifier = []; ft_default.warning.stopwatch = []; else if issubfield(ft_default.warning.identifier, fname) ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname); end end return; end % and add the line number to make this unique for the last function fname = horzcat(fname, line); if ~issubfield('ft_default.warning.stopwatch', fname) ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic); end now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call if ~issubfield(ft_default.warning.identifier, fname) || ... (issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout'])) % create or reset field ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []); % warning never given before or timed out ws = warning(warningArgs{:}); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg); warned = true; else % the warning has been issued before, but has not timed out yet ws = getsubfield(ft_default.warning.identifier, [fname '.ws']); end end % function ft_warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings) % stack(1) is this function, stack(2) is ft_warning stack = dbstack('-completenames'); if size(stack) < 3 fname = []; line = []; return; end i0 = 3; % ignore ft_preamble while strfind(stack(i0).name, 'ft_preamble') i0=i0+1; end fname = horzcat(fixname(stack(end).name)); if ~issubfield(ft_previous_warnings, fixname(stack(end).name)) ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields end for i=numel(stack)-1:-1:(i0) % skip postamble scripts if strncmp(stack(i).name, 'ft_postamble', 12) break; end fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields setsubfield(ft_previous_warnings, fname, []); end end % line of last function call line = ['.line', int2str(stack(i0).line)]; end % function outcome = issubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % outcome = isfield(strct, fname); % end % end % function strct = rmsubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % strct = rmfield(strct, fname); % end % end
github
lcnbeapp/beapp-master
fir_filterdcpadded.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/preproc/private/fir_filterdcpadded.m
2,934
utf_8
a5287ea8667b904280539687a04797ca
% fir_filterdcpadded() - Pad data with DC constant and filter % % Usage: % >> data = fir_filterdcpadded(b, a, data, causal); % % Inputs: % b - vector of filter coefficients % a - 1 % data - raw data (times x chans) % causal - boolean perform causal filtering {default 0} % usefftfilt - boolean use fftfilt instead of filter % % Outputs: % data - smoothed data % % Note: % firfiltdcpadded always operates (pads, filters) along first dimension. % Not memory optimized. % % Author: Andreas Widmann, University of Leipzig, 2014 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2013 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % $Id$ function [ data ] = fir_filterdcpadded(b, a, data, causal, usefftfilt) % Defaults if nargin < 4 || isempty(usefftfilt) usefftfilt = 0; end if nargin < 3 || isempty(causal) causal = 0; end % Check arguments if nargin < 2 error('Not enough input arguments.'); end % Is FIR? if ~isscalar(a) || a ~= 1 error('Not a FIR filter. onepass-zerophase and onepass-minphase filtering is available for FIR filters only.') end % Group delay if mod(length(b), 2) ~= 1 error('Filter order is not even.'); end groupDelay = (length(b) - 1) / 2; % Filter symmetry isSym = all(b(1:groupDelay) == b(end:-1:groupDelay + 2)); isAntisym = all([b(1:groupDelay) == -b(end:-1:groupDelay + 2) b(groupDelay + 1) == 0]); if causal == 0 && ~(isSym || isAntisym) error('Filter is not anti-/symmetric. For onepass-zerophase filtering the filter must be anti-/symmetric.') end % Padding if causal startPad = repmat(data(1, :), [2 * groupDelay 1]); endPad = []; else startPad = repmat(data(1, :), [groupDelay 1]); endPad = repmat(data(end, :), [groupDelay 1]); end % Filter data (with double precision) isSingle = isa(data, 'single'); if usefftfilt data = fftfilt(double(b), double([startPad; data; endPad])); else data = filter(double(b), 1, double([startPad; data; endPad])); % Pad and filter with double precision end % Convert to single if isSingle data = single(data); end % Remove padded data data = data(2 * groupDelay + 1:end, :); end
github
lcnbeapp/beapp-master
plotfresp.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/preproc/private/plotfresp.m
5,213
utf_8
02ff3bdc63f5c3410460734e2a7378fe
% plotfresp() - Plot a filter's impulse, step, magnitude, and phase response % % Usage: % >> plotfresp(b, a, nfft, fs, causal); % % Inputs: % b - vector numerator coefficients % % Optional inputs: % a - scalar or vector denominator coefficients (IIR support is % experimental!) {default 1} % nfft - scalar number of points {default 512} % fs - scalar sampling frequency {default 1} % dir - string filter direction {default 'onepass'} % % Author: Andreas Widmann, University of Leipzig, 2005 % % See also: % firws %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2005-2014 Andreas Widmann, University of Leipzig, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % $Id$ function plotfresp(b, a, nfft, fs, dir) if nargin < 5 || isempty(dir) dir = 'onepass'; end if nargin < 4 || isempty(fs) fs = 1; end if nargin < 3 || isempty(nfft) nfft = 512; end if nargin < 2 || isempty(a) a = 1; end if nargin < 1 error('Not enough input arguments.'); end % FIR? if isscalar(a) && a == 1 isFIR = true; else isFIR = false; end % Linear phase FIR if isFIR && all(b(:)' == fliplr(b(:)')) % TODO: antisymmetric isLinPhaseFir = true; else isLinPhaseFir = false; end % Twopass/zerophase? if strncmp('twopass', dir, 7) isTwopass = true; isZerophase = true; elseif strcmp('onepass-zerophase', dir) if ~isLinPhaseFir error('Onepass-zerophase filtering is only allowed for linear-phase FIR filters.') end isTwopass = false; isZerophase = true; else isTwopass = false; isZerophase = false; end % Impulse response if isFIR impresp = b(:)'; else if ~exist('impz', 'file') warning('Plotting IIR filter responses requires signal processing toolbox.') return end impresp = impz(b, a)'; end % Twopass if isTwopass impresp = conv(impresp, fliplr(impresp)); end n = length(impresp); % Zerophase if isZerophase groupdelay = (n - 1) / 2; x = -groupdelay:groupdelay; else x = 0:n - 1; end nfft = max([2^ceil(log2(n)) nfft]); % Do not truncate impulse response f = linspace(0, fs / 2, nfft / 2 + 1); z = fft(impresp, nfft); z = z(1:nfft / 2 + 1); % Find open figure window H = findobj('Tag', 'plotfiltresp', 'type', 'figure'); if ~isempty(H) figure(H); else H = figure; set(H, 'Tag', 'plotfiltresp'); posArray = get(H, 'Position'); posArray(3) = posArray(4) * 1.6; set(H, 'Position', posArray); end % Formatting titlePropArray = {'Fontweight', 'bold'}; axisPropArray = {'NextPlot', 'add', 'XGrid', 'on', 'YGrid', 'on', 'Box', 'on'}; % Impulse resonse ax(1) = subplot(2, 3, 1, axisPropArray{:}); stem(x, impresp, 'fill') title('Impulse response', titlePropArray{:}); ylabel('Amplitude'); % Step response ax(4) = subplot(2, 3, 4, axisPropArray{:}); stem(x, cumsum(impresp), 'fill'); title('Step response', titlePropArray{:}); ylimArray = ylim; if ylimArray(2) < -ylimArray(1) + 1; ylimArray(2) = -ylimArray(1) + 1; ylim(ylimArray); end xMin = []; xMax = []; childrenArray = get(ax(4), 'Children'); for iChild =1:length(childrenArray) xData = get(childrenArray(iChild), 'XData'); xMin = min([xMin min(xData)]); xMax = max([xMax max(xData)]); end set(ax([1 4]), 'XLim', [xMin xMax]); ylabel('Amplitude'); % Magnitude response ax(2) = subplot(2, 3, 2, axisPropArray{:}); plot(f, abs(z)); title('Magnitude response', titlePropArray{:}); ylabel('Magnitude (linear)'); ax(5) = subplot(2, 3, 5, axisPropArray{:}); plot(f, 20 * log10(abs(z))); title('Magnitude response', titlePropArray{:}); ylimArray = ylim; if ylimArray(1) < -200 ylimArray(1) = -200; ylim(ylimArray); end ylabel('Magnitude (dB)'); % Phase response ax(3) = subplot(2, 3, 3, axisPropArray{:}); phaseresp = unwrap(angle(z)); if isZerophase % Correct delay for zero-phase FIR filter? delay = -f / fs * groupdelay * 2 * pi; phaseresp = phaseresp - delay; phaseresp = mod(round(phaseresp / pi), 2) * pi; % Avoid rounding errors; linear-phase FIR only! end plot(f, phaseresp); title('Phase response', titlePropArray{:}); ylabel('Phase (rad)'); % Formatting xlabelArray = get(ax(1:5), 'XLabel'); if fs == 1 set([xlabelArray{[2 3 5]}], 'String', 'Normalized frequency (2 \pi rad / sample)'); else set([xlabelArray{[2 3 5]}], 'String', 'Frequency (Hz)'); end set([xlabelArray{[1 4]}], 'String', 'n (samples)'); set(ax([2 3 5]), 'XLim', [0 fs / 2]); set(ax(1:5), 'ColorOrder', circshift(get(ax(1), 'ColorOrder'), -1)); end
github
lcnbeapp/beapp-master
qsublist.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/qsub/qsublist.m
8,076
utf_8
d9f7d454a9f8d6bc5991aa409e239c11
function retval = qsublist(cmd, jobid, pbsid) % QSUBLIST is a helper function that is used to keep track of all the jobs in a % submitted batch. specifically, it is used to maintain the mapping between the % job identifier in the batch queueing system and MATLAB. % % Use as % qsublist('list') % qsublist('killall') % qsublist('kill', jobid) % qsublist('getjobid', pbsid) % qsublist('getpbsid', jobid) % % The jobid is the identifier that is used within MATLAB for the file names, % for example 'roboos_mentat242_p4376_b2_j453'. % % The pbsid is the identifier that is used within the batch queueing system, % for example '15260.torque'. % % The following commands can be used by the end-user. % 'list' display all jobs % 'kill' kill a specific job, based on the jobid % 'killall' kill all jobs % 'getjobid' return the mathing jobid, given the pbsid % 'getpbsid' return the mathing pbsid, given the jobid % % The following low-level commands are used by QSUBFEVAL and QSUBGET for job % maintenance and monitoring. % 'add' % 'del' % 'completed' % % See also QSUBCELLFUN, QSUBFEVAL, QSUBGET % ----------------------------------------------------------------------- % Copyright (C) 2011-2015, Robert Oostenveld % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/ % % $Id$ % ----------------------------------------------------------------------- persistent list_jobid list_pbsid % this function should stay in memory to keep the persistent variables for a long time % locking it ensures that it does not accidentally get cleared if the m-file on disk gets updated mlock if ~isempty(list_jobid) && isequal(list_jobid, list_pbsid) % it might also be system, but torque, sge, slurm and lsf will have other job identifiers backend = 'local'; else % use the environment variables to determine the backend backend = defaultbackend; end if nargin<1 cmd = 'list'; end if nargin<2 jobid = []; end if nargin<3 pbsid = []; end if isempty(jobid) && ~isempty(pbsid) % get it from the persistent list sel = find(strcmp(pbsid, list_pbsid)); if length(sel)==1 jobid = list_jobid{sel}; else warning('cannot determine the jobid that corresponds to pbsid %s', pbsid); end end if isempty(pbsid) && ~isempty(jobid) % get it from the persistent list sel = find(strcmp(jobid, list_jobid)); if length(sel)==1 pbsid = list_pbsid{sel}; else warning('cannot determine the pbsid that corresponds to jobid %s', jobid); end end switch cmd case 'add' % add it to the persistent lists list_jobid{end+1} = jobid; list_pbsid{end+1} = pbsid; case 'del' sel = strcmp(jobid, list_jobid); % remove the job from the persistent lists list_jobid(sel) = []; list_pbsid(sel) = []; case 'kill' sel = strcmp(jobid, list_jobid); if any(sel) % remove it from the batch queue switch backend case 'torque' system(sprintf('qdel %s', pbsid)); case 'sge' system(sprintf('qdel %s', pbsid)); case 'slurm' system(sprintf('scancel --name %s', jobid)); case 'lsf' system(sprintf('bkill %s', pbsid)); case 'local' % cleaning up of local jobs is not supported case 'system' % cleaning up of system jobs is not supported end % remove the corresponing files from the shared storage system(sprintf('rm -f %s*', jobid)); % remove it from the persistent lists list_jobid(sel) = []; list_pbsid(sel) = []; end case 'killall' if ~isempty(list_jobid) % give an explicit warning, because chances are that the user will see messages from qdel % about jobs that have just completed and hence cannot be deleted any more fprintf('cleaning up all scheduled and running jobs, don''t worry if you see warnings from "qdel"\n'); end % start at the end, work towards the begin of the list for i=length(list_jobid):-1:1 qsublist('kill', list_jobid{i}, list_pbsid{i}); end case 'completed' % cmd = 'completed' returns whether the job is completed as a boolean % % It first determines whether the output files exist. If so, it might be that the % batch queueing system is still writing to them, hence the next system-specific % check also polls the status of the job. First checking the files and then the % job status ensures that we don't saturate the torque server with job-status % requests. curPwd = getcustompwd(); outputfile = fullfile(curPwd, sprintf('%s_output.mat', jobid)); % if the job is aborted to a resource violation, there will not be an output file logout = fullfile(curPwd, sprintf('%s.o*', jobid)); % note the wildcard in the file name logerr = fullfile(curPwd, sprintf('%s.e*', jobid)); % note the wildcard in the file name % poll the job status to confirm that the job truely completed if isfile(logout) && isfile(logerr) && ~isempty(pbsid) % only perform the more expensive check once the log files exist switch backend case 'torque' [dum, jobstatus] = system(['qstat ' pbsid ' -f1 | grep job_state | grep -o "= [A-Z]" | grep -o "[A-Z]"']); if isempty(jobstatus) warning('cannot determine the status for pbsid %s', pbsid); retval = 1; else retval = strcmp(strtrim(jobstatus) ,'C'); end case 'lsf' [dum, jobstatus] = system(['bjobs ' pbsid ' | awk ''NR==2'' | awk ''{print $3}'' ']); retval = strcmp(strtrim(jobstatus), 'DONE'); case 'sge' [dum, jobstatus] = system(['qstat -s z | grep ' pbsid ' | awk ''{print $5}''']); retval = strcmp(strtrim(jobstatus), 'z') | strcmp(strtrim(jobstatus), 'qw'); case 'slurm' % only return the status based on the presence of the output files % FIXME it would be good to implement a proper check for slurm as well retval = 1; case {'local','system'} % only return the status based on the presence of the output files % there is no way polling the batch execution system retval = 1; end elseif isfile(logout) && isfile(logerr) && isempty(pbsid) % we cannot locate the job in the PBS/torque backend (weird, but it happens), hence we have to rely on the e and o files % note that the mat file still might be missing, e.g. when the job was killed due to a resource violation retval = 1; else retval = 0; end case 'list' for i=1:length(list_jobid) fprintf('%s %s\n', list_jobid{i}, list_pbsid{i}); end case 'getjobid' % return the mathing jobid, given the pbsid retval = jobid; case 'getpbsid' % return the mathing pbsid, given the jobid retval = pbsid; otherwise error('unsupported command (%s)', cmd); end % switch if length(list_jobid)~=length(list_pbsid) error('jobid and pbsid lists are inconsistent'); end if mislocked && isempty(list_jobid) && isempty(list_pbsid) % it is now safe to unload the function and persistent variables from memory munlock end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function that detects a file, even with a wildcard in the filename %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = isfile(name) tmp = dir(name); status = length(tmp)==1 && ~tmp.isdir;
github
lcnbeapp/beapp-master
qsubcellfun.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/qsub/qsubcellfun.m
19,264
utf_8
ed7719203341c9d8668d006d2ffc44bb
function varargout = qsubcellfun(fname, varargin) % QSUBCELLFUN applies a function to each element of a cell-array. The % function execution is done in parallel using the Torque, SGE, PBS or % SLURM batch queue system. % % Use as % argout = qsubcellfun(fname, x1, x2, ...) % % This function has a number of optional arguments that have to passed % as key-value pairs at the end of the list of input arguments. All other % input arguments (including other key-value pairs) will be passed to the % function to be evaluated. % UniformOutput = boolean (default = false) % StopOnError = boolean (default = true) % diary = string, can be 'always', 'never', 'warning', 'error' (default = 'error') % timreq = number, the time in seconds required to run a single job % timoverhead = number in seconds, how much time to allow MATLAB to start (default = 180 seconds) % memreq = number, the memory in bytes required to run a single job % memoverhead = number in bytes, how much memory to account for MATLAB itself (default = 1024^3, i.e. 1GB) % stack = number, stack multiple jobs in a single qsub job (default = 'auto') % backend = string, can be 'torque', 'sge', 'slurm', 'lsf', 'system', 'local' (default is automatic) % batchid = string, to identify the jobs in the queue (default is user_host_pid_batch) % compile = string, can be 'auto', 'yes', 'no' (default = 'no') % queue = string, which queue to submit the job in (default is empty) % options = string, additional options that will be passed to qsub/srun (default is empty) % matlabcmd = string, the Linux command line to start MATLAB on the compute nodes (default is automatic % display = 'yes' or 'no', whether the nodisplay option should be passed to MATLAB (default = 'no', meaning nodisplay) % jvm = 'yes' or 'no', whether the nojvm option should be passed to MATLAB (default = 'yes', meaning with jvm) % rerunable = 'yes' or 'no', whether the job can be restarted on a torque/maui/moab cluster (default = 'no') % % It is required to give an estimate of the time and memory requirements of % the individual jobs. The memory requirement of the MATLAB executable % itself will automatically be added, just as the time required to start % up a new MATLAB process. If you don't know what the memory and time % requirements of your job are, you can get an estimate for them using % TIC/TOC and MEMTIC/MEMTOC around a single execution of one of the jobs in % your interactive MATLAB session. You can also start with very large % estimates, e.g. 4*1024^3 bytes for the memory (which is 4GB) and 28800 % seconds for the time (which is 8 hours) and then run a single job through % qsubcellfun. When the job returns, it will print the memory and time it % required. % % Example % fname = 'power'; % x1 = {1, 2, 3, 4, 5}; % x2 = {2, 2, 2, 2, 2}; % y = qsubcellfun(fname, x1, x2, 'memreq', 1024^3, 'timreq', 300); % % Using the compile=yes or compile=auto option, you can compile your % function into a stand-alone executable that can be executed on the cluster % without requiring additional MATLAB licenses. You can also call the % QSUBCOMPILE function prior to calling QSUBCELLFUN. If you plan multiple % batches of the same function, compiling it prior to QSUBCELLFUN is more % efficient. In that case you will have to delete the compiled executable % yourself once you are done. % % In case you abort your call to qsubcellfun by pressing ctrl-c, % the already submitted jobs will be canceled. Some small temporary % files might remain in your working directory. % % To check the the status and healthy execution of the jobs on the Torque % batch queuing system, you can use % qstat % qstat -an1 % qstat -Q % comands on the linux command line. To delete jobs from the Torque batch % queue and to abort already running jobs, you can use % qdel <jobnumber> % qdel all % % See also QSUBCOMPILE, QSUBFEVAL, CELLFUN, PEERCELLFUN, FEVAL, DFEVAL, DFEVALASYNC % ----------------------------------------------------------------------- % Copyright (C) 2011-2015, Robert Oostenveld % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/ % % $Id$ % ----------------------------------------------------------------------- if ft_platform_supports('onCleanup') % switch to zombie when finished or when Ctrl-C gets pressed % the onCleanup function does not exist for older versions onCleanup(@cleanupfun); end % remove the persistent lists with job and pbs identifiers clear qsublist stopwatch = tic; % locate the begin of the optional key-value arguments optbeg = find(cellfun(@ischar, varargin)); optarg = varargin(optbeg:end); % get the optional input arguments UniformOutput = ft_getopt(optarg, 'UniformOutput', false ); StopOnError = ft_getopt(optarg, 'StopOnError', true ); diary = ft_getopt(optarg, 'diary', 'error' ); % 'always', 'never', 'warning', 'error' timreq = ft_getopt(optarg, 'timreq'); memreq = ft_getopt(optarg, 'memreq'); timoverhead = ft_getopt(optarg, 'timoverhead', 180); % allow some overhead to start up the MATLAB executable memoverhead = ft_getopt(optarg, 'memoverhead', 1024*1024*1024); % allow some overhead for the MATLAB executable in memory stack = ft_getopt(optarg, 'stack', 'auto'); % 'auto' or a number compile = ft_getopt(optarg, 'compile', 'no'); % can be 'auto', 'yes' or 'no' backend = ft_getopt(optarg, 'backend', []); % the default will be determined by qsubfeval queue = ft_getopt(optarg, 'queue', []); submitoptions = ft_getopt(optarg, 'options', []); batch = ft_getopt(optarg, 'batch', getbatch()); % this is a number that is automatically incremented batchid = ft_getopt(optarg, 'batchid', generatebatchid(batch)); % this is a string like user_host_pid_batch display = ft_getopt(optarg, 'display', 'no'); matlabcmd = ft_getopt(optarg, 'matlabcmd', []); jvm = ft_getopt(optarg, 'jvm', 'yes'); whichfunction = ft_getopt(optarg, 'whichfunction'); % the complete filename to the function, including path rerunable = ft_getopt(optarg, 'rerunable'); % the default is determined in qsubfeval % skip the optional key-value arguments if ~isempty(optbeg) varargin = varargin(1:(optbeg-1)); end if isstruct(fname) % the function has been compiled by qsubcompile fcomp = fname; % continue with the original function name fname = fcomp.fname; else fcomp = []; end % determine which function it is if isempty(whichfunction) if ischar(fname) whichfunction = which(fname); elseif isa(fname, 'function_handle') whichfunction = which(func2str(fname)); end end % if the first attempt failed, it might be due a function that is private to the calling function if isempty(whichfunction) s = dbstack('-completenames'); s = s(2); % qsubcellfun is the first, the calling function is the second if ischar(fname) whichfunction = which(fullfile(fileparts(s.file), 'private', fname)); elseif isa(fname, 'function_handle') whichfunction = which(fullfile(fileparts(s.file), 'private', func2str(fname))); end if ~isempty(whichfunction) warning('assuming %s as full function name', whichfunction); end clear s end % there are potentially errors to catch from the which() function if isempty(whichfunction) && ischar(fname) error('Not a valid M-file (%s).', fname); end % determine the number of input arguments and the number of jobs numargin = numel(varargin); numjob = numel(varargin{1}); % determine the number of MATLAB jobs to "stack" together into seperate qsub jobs if isequal(stack, 'auto') if ~isempty(timreq) stack = floor(180/timreq); else stack = 1; end end % ensure that the stacking is not higher than the number of jobs stack = min(stack, numjob); % give some feedback about the stacking if stack>1 fprintf('stacking %d MATLAB jobs in each qsub job\n', stack); end % prepare some arrays that are used for bookkeeping jobid = cell(1, numjob); puttime = nan(1, numjob); timused = nan(1, numjob); memused = nan(1, numjob); submitted = false(1, numjob); collected = false(1, numjob); submittime = inf(1, numjob); collecttime = inf(1, numjob); % it can be difficult to determine the number of output arguments try if isequal(fname, 'cellfun') || isequal(fname, @cellfun) if isa(varargin{1}{1}, 'char') || isa(varargin{1}{1}, 'function_handle') numargout = nargout(varargin{1}{1}); elseif isa(varargin{1}{1}, 'struct') % the function to be executed has been compiled fcomp = varargin{1}{1}; numargout = nargout(fcomp.fname); end else numargout = nargout(fname); end catch % the "catch me" syntax is broken on MATLAB74, this fixes it nargout_err = lasterror; if strcmp(nargout_err.identifier, 'MATLAB:narginout:doesNotApply') % e.g. in case of nargin('plus') numargout = 1; else rethrow(nargout_err); end end if numargout<0 % the nargout function returns -1 in case of a variable number of output arguments numargout = 1; elseif numargout>nargout % the number of output arguments is constrained by the users' call to this function numargout = nargout; elseif nargout>numargout error('Too many output arguments.'); end % running a compiled version in parallel takes no MATLAB licenses % auto compilation will be attempted if the total batch takes more than 30 minutes if (strcmp(compile, 'auto') && (numjob*timreq/3600)>0.5) || istrue(compile) try % try to compile into a stand-allone application fcomp = qsubcompile(fname, 'batch', batch, 'batchid', batchid); catch if istrue(compile) % the error that was caught is critical rethrow(lasterror); elseif strcmp(compile, 'auto') % compilation was only optional, the caught error is not critical warning(lasterr); end end % try-catch end % if compile if stack>1 % combine multiple jobs in one, the idea is to use recursion like this % a = {{@plus, @plus}, {{1}, {2}}, {{3}, {4}}} % b = cellfun(@cellfun, a{:}) % these options will be passed to the recursive call after being modified further down if ~any(strcmpi(optarg, 'timreq')) optarg{end+1} = 'timreq'; optarg{end+1} = timreq; end if ~any(strcmpi(optarg, 'stack')) optarg{end+1} = 'stack'; optarg{end+1} = stack; end if ~any(strcmpi(optarg, 'UniformOutput')) optarg{end+1} = 'UniformOutput'; optarg{end+1} = UniformOutput; end if ~any(strcmpi(optarg, 'whichfunction')) optarg{end+1} = 'whichfunction'; optarg{end+1} = whichfunction; end if ~any(strcmpi(optarg, 'compile')) optarg{end+1} = 'compile'; optarg{end+1} = compile; end % update these settings for the recursive call optarg{find(strcmpi(optarg, 'timreq'))+1} = timreq*stack; optarg{find(strcmpi(optarg, 'stack'))+1} = 1; optarg{find(strcmpi(optarg, 'UniformOutput'))+1} = false; optarg{find(strcmpi(optarg, 'compile'))+1} = false; % FIXME the partitioning can be further perfected partition = floor((0:numjob-1)/stack)+1; numpartition = partition(end); stackargin = cell(1,numargin+3); % include the fname, uniformoutput, false if istrue(compile) if ischar(fcomp.fname) % it should contain function handles, not strings stackargin{1} = repmat({str2func(fcomp.fname)}, 1, numpartition); else stackargin{1} = repmat({fcomp.fname}, 1, numpartition); end else if ischar(fname) % it should contain function handles, not strings stackargin{1} = repmat({str2func(fname)}, 1, numpartition); else stackargin{1} = repmat({fname}, 1, numpartition); end end stackargin{end-1} = repmat({'uniformoutput'},1,numpartition); % uniformoutput stackargin{end} = repmat({false},1,numpartition); % false % reorganize the original input into the stacked format for i=1:numargin tmp = cell(1,numpartition); for j=1:numpartition tmp{j} = {varargin{i}{partition==j}}; end stackargin{i+1} = tmp; % note that the first element is the fname clear tmp end stackargout = cell(1,numargout); [stackargout{:}] = qsubcellfun(@cellfun, stackargin{:}, optarg{:}); % reorganise the stacked output into the original format for i=1:numargout tmp = cell(size(varargin{1})); for j=1:numpartition tmp(partition==j) = stackargout{i}{j}; end varargout{i} = tmp; clear tmp end if numargout>0 && UniformOutput [varargout{:}] = makeuniform(varargout{:}); end return; end % check the input arguments for i=1:numargin if ~isa(varargin{i}, 'cell') error('input argument #%d should be a cell-array', i+1); end if numel(varargin{i})~=numjob error('inconsistent number of elements in input #%d', i+1); end end for submit=1:numjob % redistribute the input arguments argin = cell(1, numargin); for j=1:numargin argin{j} = varargin{j}{submit}; end % submit the job if ~isempty(fcomp) % use the compiled version [curjobid curputtime] = qsubfeval(fcomp, argin{:}, 'memreq', memreq, 'timreq', timreq, 'memoverhead', memoverhead, 'timoverhead', timoverhead, 'diary', diary, 'batch', batch, 'batchid', batchid, 'backend', backend, 'options', submitoptions, 'queue', queue, 'matlabcmd', matlabcmd, 'display', display, 'jvm', jvm, 'nargout', numargout, 'whichfunction', whichfunction, 'rerunable', rerunable); else % use the non-compiled version [curjobid curputtime] = qsubfeval(fname, argin{:}, 'memreq', memreq, 'timreq', timreq, 'memoverhead', memoverhead, 'timoverhead', timoverhead, 'diary', diary, 'batch', batch, 'batchid', batchid, 'backend', backend, 'options', submitoptions, 'queue', queue, 'matlabcmd', matlabcmd, 'display', display, 'jvm', jvm, 'nargout', numargout, 'whichfunction', whichfunction, 'rerunable', rerunable); end % fprintf('submitted job %d\n', submit); jobid{submit} = curjobid; puttime(submit) = curputtime; submitted(submit) = true; submittime(submit) = toc(stopwatch); clear curjobid curputtime end % for while (~all(collected)) % try to collect the jobs that have finished for collect=find(~collected) % this will return empty arguments if the job has not finished ws = warning('off', 'FieldTrip:qsub:jobNotAvailable'); [argout, options] = qsubget(jobid{collect}, 'output', 'cell', 'diary', diary, 'StopOnError', StopOnError); warning(ws); if ~isempty(argout) || ~isempty(options) % fprintf('collected job %d\n', collect); collected(collect) = true; collecttime(collect) = toc(stopwatch); if isempty(argout) && StopOnError==false % this happens if an error was detected in qsubget and StopOnError is false % replace the output of the failed jobs with [] argout = repmat({[]}, 1, numargout); end % redistribute the output arguments for j=1:numargout varargout{j}{collect} = argout{j}; end % gather the job statistics % these are empty in case an error happened during remote evaluation, therefore the default value of NaN is specified timused(collect) = ft_getopt(options, 'timused', nan); memused(collect) = ft_getopt(options, 'memused', nan); end % if end % for pausejava(0.1); end % while % ensure the output to have the same size/dimensions as the input for i=1:numargout varargout{i} = reshape(varargout{i}, size(varargin{1})); end if numargout>0 && UniformOutput [varargout{:}] = makeuniform(varargout{:}); end % clean up the remains of the compilation if (strcmp(compile, 'yes') || strcmp(compile, 'auto')) && ~isempty(fcomp) % the extension might be .app or .exe or none system(sprintf('rm -rf %s', fcomp.batchid)); % on Linux system(sprintf('rm -rf %s.app', fcomp.batchid)); % on Apple OS X system(sprintf('rm -rf %s.exe', fcomp.batchid)); % on Windows system(sprintf('rm -rf run_%s*.sh', fcomp.batchid)); end % compare the time used inside this function with the total execution time fprintf('computational time = %.1f sec, elapsed = %.1f sec, speedup %.1f x\n', nansum(timused), toc(stopwatch), nansum(timused)/toc(stopwatch)); if all(puttime>timused) warning('the job submission took more time than the actual execution'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function varargout = makeuniform(varargin) varargout = varargin; numargout = numel(varargin); % check whether the output can be converted to a uniform one for i=1:numel(varargout) for j=1:numel(varargout{i}) if numel(varargout{i}{j})~=1 % this error message is consistent with the one from cellfun error('Non-scalar in Uniform output, at index %d, output %d. Set ''UniformOutput'' to false.', j, i); end end end % convert the output to a uniform one for i=1:numargout varargout{i} = [varargout{i}{:}]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanmax(x) y = max(x(~isnan(x(:)))); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanmin(x) y = min(x(~isnan(x(:)))); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanmean(x) x = x(~isnan(x(:))); y = mean(x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanstd(x) x = x(~isnan(x(:))); y = std(x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nansum(x) x = x(~isnan(x(:))); y = sum(x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cleanupfun % the qsublist function maintains a persistent list with all jobs % request it to kill all the jobs and to cleanup all the files qsublist('killall');
github
lcnbeapp/beapp-master
qsublisten.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/qsub/qsublisten.m
4,326
utf_8
6ac189cba48025bdbd36f682f9b258cc
function num = qsublisten(callback, varargin) % QSUBLISTEN checks whether jobs, submitted by qsubfeval, have been % completed. Whenever a job returns, it executes the provided callback function % (should be a function handle), with the job ID as an input argument. Results % can then be retrieved by calling QSUBGET. If a cell array is provided as % a the 'filter' option (see below), the second input argument passed to the % callback function will be an index into this cell array (to facilitate % checking which job returned in the callback function). % % Note that this function is blocking; i.e., it only returns after a % certain criterion has been met. % % Arguments can be supplied with key-value pairs: % maxnum = maximum number of jobs to collect, function will return % after this is reached. Default = Inf; so it is highly % recommended you provide something here, since with % maxnum=Inf the function will never return. % filter = regular expression filter for job IDs to respond to. % The default tests for jobs generated from the current % MATLAB process. A cell array of strings can be % provided; in that case, exact match is required. % sleep = number of seconds to sleep between checks (default=0) % % This function returns the number of jobs that were collected and for % which the callback function was called. % Copyright (C) 2012, Eelke Spaak % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ maxnum = ft_getopt(varargin, 'maxnum', Inf); filter = ft_getopt(varargin, 'filter', [generatesessionid '.*']); sleep = ft_getopt(varargin, 'sleep', 0); if ischar(filter) regexpFilt = 1; elseif iscellstr(filter) regexpFilt = 0; else error('filter should either be a regexp string or cell array of exact-match strings'); end % keep track of which job IDs we have already recognized and fired the callback for foundJobs = []; curPwd = getcustompwd(); num = 0; while (num < maxnum) files = dir(); for k = 1:numel(files) % preliminary filter to get just the qsub-specific output files jobid = regexp(files(k).name, '^(.*)\.o.*$', 'tokens'); if ~isempty(jobid) && isempty(findstr(foundJobs, jobid{1}{1})) jobid = jobid{1}{1}; % wait until not only the stdout file exists, but also the stderr and % _output.mat. If we fire the callback before all three files are % present, a subsequent call to qsubget will fail outputfile = fullfile(curPwd, sprintf('%s_output.mat', jobid)); logerr = fullfile(curPwd, sprintf('%s.e*', jobid)); while ~exist(outputfile,'file') || ~isfile(logerr) pausejava(0.01); end if (regexpFilt && ~isempty(regexp(jobid, filter, 'once'))) || (~regexpFilt && ~isempty(find(strcmp(jobid, filter)))) if (~regexpFilt && nargin(callback)>1) % also provide an index into the filter array callback(jobid, find(strcmp(jobid, filter))); else callback(jobid); end num = num+1; foundJobs = [foundJobs '|' jobid]; end end end if (sleep > 0) pausejava(sleep); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function that detects a file, even with a wildcard in the filename %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = isfile(name) tmp = dir(name); status = length(tmp)==1 && ~tmp.isdir; end end
github
lcnbeapp/beapp-master
ft_platform_supports.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/qsub/private/ft_platform_supports.m
9,557
utf_8
eb0e55d84d57e6873cce8df6cad90d96
function tf = ft_platform_supports(what,varargin) % FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform % supports a specific capability % % Usage: % tf = ft_platform_supports(what) % tf = ft_platform_supports('matlabversion', min_version, max_version) % % The following values are allowed for the 'what' parameter: % value means that the following is supported: % % 'which-all' which(...,'all') % 'exists-in-private-directory' exists(...) will look in the /private % subdirectory to see if a file exists % 'onCleanup' onCleanup(...) % 'alim' alim(...) % 'int32_logical_operations' bitand(a,b) with a, b of type int32 % 'graphics_objects' graphics sysem is object-oriented % 'libmx_c_interface' libmx is supported through mex in the % C-language (recent Matlab versions only % support C++) % 'stats' all statistical functions in % FieldTrip's external/stats directory % 'program_invocation_name' program_invocation_name() (GNU Octave) % 'singleCompThread' start Matlab with -singleCompThread % 'nosplash' -nosplash % 'nodisplay' -nodisplay % 'nojvm' -nojvm % 'no-gui' start GNU Octave with --no-gui % 'RandStream.setGlobalStream' RandStream.setGlobalStream(...) % 'RandStream.setDefaultStream' RandStream.setDefaultStream(...) % 'rng' rng(...) % 'rand-state' rand('state') % 'urlread-timeout' urlread(..., 'Timeout', t) % 'griddata-vector-input' griddata(...,...,...,a,b) with a and b % vectors % 'griddata-v4' griddata(...,...,...,...,...,'v4'), % that is v4 interpolation support % 'uimenu' uimenu(...) if ~ischar(what) error('first argument must be a string'); end switch what case 'matlabversion' tf = is_matlab() && matlabversion(varargin{:}); case 'exists-in-private-directory' tf = is_matlab(); case 'which-all' tf = is_matlab(); case 'onCleanup' tf = is_octave() || matlabversion(7.8, Inf); case 'alim' tf = is_matlab(); case 'int32_logical_operations' % earlier version of Matlab don't support bitand (and similar) % operations on int32 tf = is_octave() || ~matlabversion(-inf, '2012a'); case 'graphics_objects' % introduced in Matlab 2014b, graphics is handled through objects; % previous versions use numeric handles tf = is_matlab() && matlabversion('2014b', Inf); case 'libmx_c_interface' % removed after 2013b tf = matlabversion(-Inf, '2013b'); case 'stats' root_dir=fileparts(which('ft_defaults')); external_stats_dir=fullfile(root_dir,'external','stats'); % these files are only used by other functions in the external/stats % directory exclude_mfiles={'common_size.m',... 'iscomplex.m',... 'lgamma.m'}; tf = has_all_functions_in_dir(external_stats_dir,exclude_mfiles); case 'program_invocation_name' % Octave supports program_invocation_name, which returns the path % of the binary that was run to start Octave tf = is_octave(); case 'singleCompThread' tf = is_matlab() && matlabversion(7.8, inf); case {'nosplash','nodisplay','nojvm'} % Only on Matlab tf = is_matlab(); case 'no-gui' % Only on Octave tf = is_octave(); case 'RandStream.setDefaultStream' tf = is_matlab() && matlabversion('2008b', '2011b'); case 'RandStream.setGlobalStream' tf = is_matlab() && matlabversion('2012a', inf); case 'randomized_PRNG_on_startup' tf = is_octave() || ~matlabversion(-Inf,'7.3'); case 'rng' % recent Matlab versions tf = is_matlab() && matlabversion('7.12',Inf); case 'rand-state' % GNU Octave tf = is_octave(); case 'urlread-timeout' tf = is_matlab() && matlabversion('2012b',Inf); case 'griddata-vector-input' tf = is_matlab(); case 'griddata-v4' tf = is_matlab() && matlabversion('2009a',Inf); case 'uimenu' tf = is_matlab(); otherwise error('unsupported value for first argument: %s', what); end % switch end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_matlab() tf = ~is_octave(); end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_octave() persistent cached_tf; if isempty(cached_tf) cached_tf = logical(exist('OCTAVE_VERSION', 'builtin')); end tf = cached_tf; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = has_all_functions_in_dir(in_dir, exclude_mfiles) % returns true if all functions in in_dir are already provided by the % platform m_files=dir(fullfile(in_dir,'*.m')); n=numel(m_files); for k=1:n m_filename=m_files(k).name; if isempty(which(m_filename)) && ... isempty(strmatch(m_filename,exclude_mfiles)) tf=false; return; end end tf=true; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [inInterval] = matlabversion(min, max) % MATLABVERSION checks if the current MATLAB version is within the interval % specified by min and max. % % Use, e.g., as: % if matlabversion(7.0, 7.9) % % do something % end % % Both strings and numbers, as well as infinities, are supported, eg.: % matlabversion(7.1, 7.9) % is version between 7.1 and 7.9? % matlabversion(6, '7.10') % is version between 6 and 7.10? (note: '7.10', not 7.10) % matlabversion(-Inf, 7.6) % is version <= 7.6? % matlabversion('2009b') % exactly 2009b % matlabversion('2008b', '2010a') % between two versions % matlabversion('2008b', Inf) % from a version onwards % etc. % % See also VERSION, VER, VERLESSTHAN % Copyright (C) 2006, Robert Oostenveld % Copyright (C) 2010, Eelke Spaak % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this does not change over subsequent calls, making it persistent speeds it up persistent curVer if nargin<2 max = min; end if isempty(curVer) curVer = version(); end if ((ischar(min) && isempty(str2num(min))) || (ischar(max) && isempty(str2num(max)))) % perform comparison with respect to release string ind = strfind(curVer, '(R'); [year, ab] = parseMatlabRelease(curVer((ind + 2):(numel(curVer) - 1))); [minY, minAb] = parseMatlabRelease(min); [maxY, maxAb] = parseMatlabRelease(max); inInterval = orderedComparison(minY, minAb, maxY, maxAb, year, ab); else % perform comparison with respect to version number [major, minor] = parseMatlabVersion(curVer); [minMajor, minMinor] = parseMatlabVersion(min); [maxMajor, maxMinor] = parseMatlabVersion(max); inInterval = orderedComparison(minMajor, minMinor, maxMajor, maxMinor, major, minor); end end % function function [year, ab] = parseMatlabRelease(str) if (str == Inf) year = Inf; ab = Inf; elseif (str == -Inf) year = -Inf; ab = -Inf; else year = str2num(str(1:4)); ab = str(5); end end % function function [major, minor] = parseMatlabVersion(ver) if (ver == Inf) major = Inf; minor = Inf; elseif (ver == -Inf) major = -Inf; minor = -Inf; elseif (isnumeric(ver)) major = floor(ver); minor = int8((ver - floor(ver)) * 10); else % ver is string (e.g. '7.10'), parse accordingly [major, rest] = strtok(ver, '.'); major = str2num(major); minor = str2num(strtok(rest, '.')); end end % function % checks if testA is in interval (lowerA,upperA); if at edges, checks if testB is in interval (lowerB,upperB). function inInterval = orderedComparison(lowerA, lowerB, upperA, upperB, testA, testB) if (testA < lowerA || testA > upperA) inInterval = false; else inInterval = true; if (testA == lowerA) inInterval = inInterval && (testB >= lowerB); end if (testA == upperA) inInterval = inInterval && (testB <= upperB); end end end % function
github
lcnbeapp/beapp-master
ft_warning.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/qsub/private/ft_warning.m
7,789
utf_8
d832a7ad5e2f9bb42995e6e5d4caa198
function [ws, warned] = ft_warning(varargin) % FT_WARNING will throw a warning for every unique point in the % stacktrace only, e.g. in a for-loop a warning is thrown only once. % % Use as one of the following % ft_warning(string) % ft_warning(id, string) % Alternatively, you can use ft_warning using a timeout % ft_warning(string, timeout) % ft_warning(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. % % Use as ft_warning('-clear') to clear old warnings from the current % stack % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = ft_warning(...) % or as % ft_warning(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, ft_warning accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = ft_warning(...) % where w is a boolean that indicates whether a warning as been thrown or not. % % Please note that you can NOT use it like this % ft_warning('the value is %d', 10) % instead you should do % ft_warning(sprintf('the value is %d', 10)) % Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ global ft_default warned = false; ws = []; stack = dbstack; if any(strcmp({stack(2:end).file}, 'ft_warning.m')) % don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068 return; end if nargin < 1 error('You need to specify at least a warning message'); end if isstruct(varargin{1}) warning(varargin{1}); return; end if ~isfield(ft_default, 'warning') ft_default.warning = []; end if ~isfield(ft_default.warning, 'stopwatch') ft_default.warning.stopwatch = []; end if ~isfield(ft_default.warning, 'identifier') ft_default.warning.identifier = []; end if ~isfield(ft_default.warning, 'ignore') ft_default.warning.ignore = {}; end % put the arguments we will pass to warning() in this cell array warningArgs = {}; if nargin==3 % calling syntax (id, msg, timeout) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); msg = warningArgs{1}; timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && isequal(varargin{1}, 'off') ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && isequal(varargin{1}, 'on') ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = inf; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); msg = warningArgs{1}; timeout = inf; % default timeout in seconds fname = [warningArgs{1}]; end if ismember(msg, ft_default.warning.ignore) % do not show this warning return; end if isempty(timeout) error('Timeout ill-specified'); end if timeout ~= inf fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures line = []; else % here, we create the fieldname functionA.functionB.functionC... [tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier); if ~isempty(tmpfname), fname = tmpfname; clear tmpfname; end end if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1}) if strcmp(fname, '-clear') % reset all fields if called outside a function ft_default.warning.identifier = []; ft_default.warning.stopwatch = []; else if issubfield(ft_default.warning.identifier, fname) ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname); end end return; end % and add the line number to make this unique for the last function fname = horzcat(fname, line); if ~issubfield('ft_default.warning.stopwatch', fname) ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic); end now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call if ~issubfield(ft_default.warning.identifier, fname) || ... (issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout'])) % create or reset field ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []); % warning never given before or timed out ws = warning(warningArgs{:}); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg); warned = true; else % the warning has been issued before, but has not timed out yet ws = getsubfield(ft_default.warning.identifier, [fname '.ws']); end end % function ft_warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings) % stack(1) is this function, stack(2) is ft_warning stack = dbstack('-completenames'); if size(stack) < 3 fname = []; line = []; return; end i0 = 3; % ignore ft_preamble while strfind(stack(i0).name, 'ft_preamble') i0=i0+1; end fname = horzcat(fixname(stack(end).name)); if ~issubfield(ft_previous_warnings, fixname(stack(end).name)) ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields end for i=numel(stack)-1:-1:(i0) % skip postamble scripts if strncmp(stack(i).name, 'ft_postamble', 12) break; end fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields setsubfield(ft_previous_warnings, fname, []); end end % line of last function call line = ['.line', int2str(stack(i0).line)]; end % function outcome = issubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % outcome = isfield(strct, fname); % end % end % function strct = rmsubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % strct = rmfield(strct, fname); % end % end
github
lcnbeapp/beapp-master
ft_checkopt.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/qsub/private/ft_checkopt.m
5,085
utf_8
c8bce4359cc4a8be5591788b5984166d
function opt = ft_checkopt(opt, key, allowedtype, allowedval) % FT_CHECKOPT does a validity test on the types and values of a configuration % structure or cell-array with key-value pairs. % % Use as % opt = ft_checkopt(opt, key) % opt = ft_checkopt(opt, key, allowedtype) % opt = ft_checkopt(opt, key, allowedtype, allowedval) % % For allowedtype you can specify a string or a cell-array with multiple % strings. All the default MATLAB types can be specified, such as % 'double' % 'logical' % 'char' % 'single' % 'float' % 'int16' % 'cell' % 'struct' % 'function_handle' % Furthermore, the following custom types can be specified % 'doublescalar' % 'doublevector' % 'doublebivector' i.e. [1 1] or [1 2] % 'ascendingdoublevector' i.e. [1 2 3 4 5], but not [1 3 2 4 5] % 'ascendingdoublebivector' i.e. [1 2], but not [2 1] % 'doublematrix' % 'numericscalar' % 'numericvector' % 'numericmatrix' % 'charcell' % % For allowedval you can specify a single value or a cell-array % with multiple values. % % This function will give an error or it returns the input configuration % structure or cell-array without modifications. A match on any of the % allowed types and any of the allowed values is sufficient to let this % function pass. % % See also FT_GETOPT, FT_SETOPT % Copyright (C) 2011-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin<3 allowedtype = {}; end if ~iscell(allowedtype) allowedtype = {allowedtype}; end if nargin<4 allowedval = {}; end if ~iscell(allowedval) allowedval = {allowedval}; end % get the value that belongs to this key val = ft_getopt(opt, key); % the default will be [] if isempty(val) && ~any(strcmp(allowedtype, 'empty')) if isnan(ft_getopt(opt, key, nan)) error('the option "%s" was not specified or was empty', key); end end % check that the type of the option is allowed ok = isempty(allowedtype); for i=1:length(allowedtype) switch allowedtype{i} case 'empty' ok = isempty(val); case 'charcell' ok = isa(val, 'cell') && all(cellfun(@ischar, val(:))); case 'doublescalar' ok = isa(val, 'double') && numel(val)==1; case 'doublevector' ok = isa(val, 'double') && sum(size(val)>1)==1; case 'ascendingdoublevector' ok = isa(val,'double') && issorted(val); case 'doublebivector' ok = isa(val,'double') && sum(size(val)>1)==1 && length(val)==2; case 'ascendingdoublebivector' ok = isa(val,'double') && sum(size(val)>1)==1 && length(val)==2 && val(2)>val(1); case 'doublematrix' ok = isa(val, 'double') && sum(size(val)>1)>1; case 'numericscalar' ok = isnumeric(val) && numel(val)==1; case 'numericvector' ok = isnumeric(val) && sum(size(val)>1)==1; case 'numericmatrix' ok = isnumeric(val) && sum(size(val)>1)>1; otherwise ok = isa(val, allowedtype{i}); end if ok % no reason to do additional checks break end end % for allowedtype % construct a string that describes the type of the input variable if isnumeric(val) && numel(val)==1 valtype = sprintf('%s scalar', class(val)); elseif isnumeric(val) && numel(val)==length(val) valtype = sprintf('%s vector', class(val)); elseif isnumeric(val) && length(size(val))==2 valtype = sprintf('%s matrix', class(val)); elseif isnumeric(val) valtype = sprintf('%s array', class(val)); else valtype = class(val); end if ~ok if length(allowedtype)==1 error('the type of the option "%s" is invalid, it should be "%s" instead of "%s"', key, allowedtype{1}, valtype); else error('the type of the option "%s" is invalid, it should be any of %s instead of "%s"', key, printcell(allowedtype), valtype); end end % check that the type of the option is allowed ok = isempty(allowedval); for i=1:length(allowedval) ok = isequal(val, allowedval{i}); if ok % no reason to do additional checks break end end % for allowedtype if ~ok error('the value of the option "%s" is invalid', key); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [s] = printcell(c) if ~isempty(c) s = sprintf('%s, ', c{:}); s = sprintf('{%s}', s(1:end-2)); else s = '{}'; end
github
lcnbeapp/beapp-master
ft_statfun_roc.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/statfun/ft_statfun_roc.m
5,415
utf_8
a8e88fc1a733545abfe4d0608e309d53
function [s, cfg] = ft_statfun_roc(cfg, dat, design) % FT_STATFUN_ROC computes the area under the curve (AUC) of the % Receiver Operator Characteristic (ROC). This is a measure of the % separability of the data divided over two conditions. The AUC can % be used to test statistical significance of being able to predict % on a single observation basis to which condition the observation % belongs. % % Use this function by calling one of the high-level statistics % functions as % [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) % [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) % [stat] = ft_sourcestatistics(cfg, source1, source2, ...) % with the following configuration option % cfg.statistic = 'ft_statfun_roc' % % Configuration options that are relevant for this function are % cfg.ivar = number, index into the design matrix with the independent variable % cfg.logtransform = 'yes' or 'no' (default = 'no') % % Note that this statfun performs a one sided test in which condition "1" % is assumed to be larger than condition "2". % A low-level example for this function is % a = randn(1,1000) + 1; % b = randn(1,1000); % design = [1*ones(1,1000) 2*ones(1,1000)]; % auc = ft_statfun_roc([], [a b], design); % Copyright (C) 2008, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if ~isfield(cfg, 'ivar'), cfg.ivar = 1; end if ~isfield(cfg, 'logtransform'), cfg.logtransform = 'no'; end if strcmp(cfg.logtransform, 'yes'), dat = log10(dat); end if isfield(cfg, 'numbins') % this function was completely reimplemented on 21 July 2008 by Robert Oostenveld % the old function had a positive bias in the AUC (i.e. the expected value was not 0.5) error('the option cfg.numbins is not supported any more'); end % start with a quick test to see whether there appear to be NaNs if any(isnan(dat(1,:))) % exclude trials that contain NaNs for all observed data points sel = all(isnan(dat),1); dat = dat(:,~sel); design = design(:,~sel); end % logical indexing is faster than using find(...) selA = (design(cfg.ivar,:)==1); selB = (design(cfg.ivar,:)==2); % select the data in the two classes datA = dat(:, selA); datB = dat(:, selB); nobs = size(dat,1); na = size(datA,2); nb = size(datB,2); auc = zeros(nobs, 1); for k = 1:nobs % compute the area under the curve for each channel/time/frequency a = datA(k,:); b = datB(k,:); % to speed up the AUC, the critical value is determined by the actual % values in class B, which also ensures a regular sampling of the False Alarms b = sort(b); ca = zeros(nb+1,1); ib = zeros(nb+1,1); % cb = zeros(nb+1,1); % ia = zeros(nb+1,1); for i=1:nb % for the first approach below, the critval could also be choosen based on e.g. linspace(min,max,n) critval = b(i); % for each of the two distributions, determine the number of correct and incorrect assignments given the critical value % ca(i) = sum(a>=critval); % ib(i) = sum(b>=critval); % cb(i) = sum(b<critval); % ia(i) = sum(a<critval); % this is a much faster approach, which works due to using the sorted values in b as the critical values ca(i) = sum(a>=critval); % correct assignments to class A ib(i) = nb-i+1; % incorrect assignments to class B end % add the end point ca(end) = 0; ib(end) = 0; % cb(end) = nb; % ia(end) = na; hits = ca/na; fa = ib/nb; % the numerical integration is faster if the points are sorted hits = fliplr(hits); fa = fliplr(fa); if false % this part is optional and should only be used when exploring the data figure plot(fa, hits, '.-') xlabel('false positive'); ylabel('true positive'); title('ROC-curve'); end % compute the area under the curve using numerical integration auc(k) = numint(fa, hits); end % return the area under the curve as the statistic of interest s = struct('auc', auc); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NUMINT computes a numerical integral of a set of sampled points using % linear interpolation. Alugh the algorithm works for irregularly sampled points % along the x-axis, it will perform best for regularly sampled points % % Use as % z = numint(x, y) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function z = numint(x, y) if ~all(diff(x)>=0) % ensure that the points are sorted along the x-axis [x, i] = sort(x); y = y(i); end n = length(x); z = 0; for i=1:(n-1) x0 = x(i); y0 = y(i); dx = x(i+1)-x(i); dy = y(i+1)-y(i); z = z + (y0 * dx) + (dy*dx/2); end
github
lcnbeapp/beapp-master
ft_warning.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/statfun/private/ft_warning.m
7,789
utf_8
d832a7ad5e2f9bb42995e6e5d4caa198
function [ws, warned] = ft_warning(varargin) % FT_WARNING will throw a warning for every unique point in the % stacktrace only, e.g. in a for-loop a warning is thrown only once. % % Use as one of the following % ft_warning(string) % ft_warning(id, string) % Alternatively, you can use ft_warning using a timeout % ft_warning(string, timeout) % ft_warning(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. % % Use as ft_warning('-clear') to clear old warnings from the current % stack % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = ft_warning(...) % or as % ft_warning(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, ft_warning accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = ft_warning(...) % where w is a boolean that indicates whether a warning as been thrown or not. % % Please note that you can NOT use it like this % ft_warning('the value is %d', 10) % instead you should do % ft_warning(sprintf('the value is %d', 10)) % Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ global ft_default warned = false; ws = []; stack = dbstack; if any(strcmp({stack(2:end).file}, 'ft_warning.m')) % don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068 return; end if nargin < 1 error('You need to specify at least a warning message'); end if isstruct(varargin{1}) warning(varargin{1}); return; end if ~isfield(ft_default, 'warning') ft_default.warning = []; end if ~isfield(ft_default.warning, 'stopwatch') ft_default.warning.stopwatch = []; end if ~isfield(ft_default.warning, 'identifier') ft_default.warning.identifier = []; end if ~isfield(ft_default.warning, 'ignore') ft_default.warning.ignore = {}; end % put the arguments we will pass to warning() in this cell array warningArgs = {}; if nargin==3 % calling syntax (id, msg, timeout) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); msg = warningArgs{1}; timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && isequal(varargin{1}, 'off') ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && isequal(varargin{1}, 'on') ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = inf; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); msg = warningArgs{1}; timeout = inf; % default timeout in seconds fname = [warningArgs{1}]; end if ismember(msg, ft_default.warning.ignore) % do not show this warning return; end if isempty(timeout) error('Timeout ill-specified'); end if timeout ~= inf fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures line = []; else % here, we create the fieldname functionA.functionB.functionC... [tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier); if ~isempty(tmpfname), fname = tmpfname; clear tmpfname; end end if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1}) if strcmp(fname, '-clear') % reset all fields if called outside a function ft_default.warning.identifier = []; ft_default.warning.stopwatch = []; else if issubfield(ft_default.warning.identifier, fname) ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname); end end return; end % and add the line number to make this unique for the last function fname = horzcat(fname, line); if ~issubfield('ft_default.warning.stopwatch', fname) ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic); end now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call if ~issubfield(ft_default.warning.identifier, fname) || ... (issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout'])) % create or reset field ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []); % warning never given before or timed out ws = warning(warningArgs{:}); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg); warned = true; else % the warning has been issued before, but has not timed out yet ws = getsubfield(ft_default.warning.identifier, [fname '.ws']); end end % function ft_warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings) % stack(1) is this function, stack(2) is ft_warning stack = dbstack('-completenames'); if size(stack) < 3 fname = []; line = []; return; end i0 = 3; % ignore ft_preamble while strfind(stack(i0).name, 'ft_preamble') i0=i0+1; end fname = horzcat(fixname(stack(end).name)); if ~issubfield(ft_previous_warnings, fixname(stack(end).name)) ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields end for i=numel(stack)-1:-1:(i0) % skip postamble scripts if strncmp(stack(i).name, 'ft_postamble', 12) break; end fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields setsubfield(ft_previous_warnings, fname, []); end end % line of last function call line = ['.line', int2str(stack(i0).line)]; end % function outcome = issubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % outcome = isfield(strct, fname); % end % end % function strct = rmsubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % strct = rmfield(strct, fname); % end % end
github
lcnbeapp/beapp-master
ft_realtime_ouunpod.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/realtime/online_eeg/ft_realtime_ouunpod.m
20,299
utf_8
e7df0f8c5ebb142a8a4f339bb345f448
function ft_realtime_ouunpod(cfg) % FT_REALTIME_OUUNPOD is an example realtime application for online power % estimation and visualisation. It is designed for use with the OuUnPod, an % OpenEEG based low cost EEG system with two channels, but in principle % should work for any EEG or MEG system. % % Use as % ft_realtime_ouunpod(cfg) % with the following configuration options % cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'all') % cfg.foilim = [Flow Fhigh] (default = [1 45]) % cfg.blocksize = number, size of the blocks/chuncks that are processed (default = 1 second) % cfg.bufferdata = whether to start on the 'first or 'last' data that is available (default = 'last') % % The source of the data is configured as % cfg.dataset = string % or alternatively to obtain more low-level control as % cfg.datafile = string % cfg.headerfile = string % cfg.eventfile = string % cfg.dataformat = string, default is determined automatic % cfg.headerformat = string, default is determined automatic % cfg.eventformat = string, default is determined automatic % % To stop the realtime function, you have to press Ctrl-C % % See also http://ouunpod.blogspot.com % Copyright (C) 2008-2012, Robert Oostenveld % Copyright (C) 2012-2014, Stephen Whitmarsh % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % set the default configuration options if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % default is detected automatically if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end % default is detected automatically if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end % default is detected automatically if ~isfield(cfg, 'blocksize'), cfg.blocksize = 0.05; end % stepsize, in seconds if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end if ~isfield(cfg, 'bufferdata'), cfg.bufferdata = 'last'; end % first or last if ~isfield(cfg, 'dataset'), cfg.dataset = 'buffer:\\localhost:1972'; end; if ~isfield(cfg, 'foilim'), cfg.foilim = [1 45]; end if ~isfield(cfg, 'windowsize'), cfg.windowsize = 2; end % length of sliding window, in seconds if ~isfield(cfg, 'scale'), cfg.scale = 1; end % can be used to fix the calibration if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end % use neurofeedback with MIDI, yes or no % translate dataset into datafile+headerfile cfg = ft_checkconfig(cfg, 'dataset2files', 'yes'); cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'}); if strcmp(cfg.feedback, 'yes') % setup MIDI, see http://en.wikipedia.org/wiki/General_MIDI beatdrum = true; m = midiOut; % Microsoft GS Wavetable Synth = device number 2 midiOut('O', 2); % o for output; 2 for device nr 2 midiOut('.', 1); % all off midiOut('.', 2); % all off % midiOut('P', 2, 20); organ midiOut('P', 1, 53); midiOut('P', 2, 53); midiOut('+', 1, [64 65], [127 127]); % command, channelnr, key, velocity midiOut('+', 2, [64 65 67], [127 127 127]); % command, channelnr, key, velocity midiOut(uint8([175+1, 7, 0])); % change volume midiOut(uint8([175+2, 7, 0])); end % if MIDI feedback % these are used by the GUI callbacks clear global vaxis hdr chanindx global vaxis hdr chanindx % this specifies the vertical axis for each of the 6 subplots vaxis = [ -300 300 -300 300 0 1000 0 1000 0 1000 0 1000 ]; b2clicked = false; % schemerlamp = Lamp('com9'); % ensure that the persistent variables related to caching are cleared clear ft_read_header % start by reading the header from the realtime buffer hdr = ft_read_header(cfg.headerfile, 'cache', true, 'retry', true); % define a subset of channels for reading cfg.channel = ft_channelselection(cfg.channel, hdr.label); chanindx = match_str(hdr.label, cfg.channel); nchan = length(chanindx); if nchan>2 chanindx = [1 2]; nchan = 2; warning('exactly two channels should be selected'); end if nchan<2 error('exactly two channels should be selected'); end nhistory = 100; % determine the size of blocks to process blocksize = round(cfg.blocksize * hdr.Fs); prevSample = 0; count = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this is the general BCI loop where realtime incoming data is handled %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% left_thresh_ampl = -100; left_thresh_time = nan; % [cfg.blockmem*blocksize-blocksize*4 cfg.blockmem*blocksize]; % FIXME these are hardcoded, but might be incompatible with the cfg and data settings right_freq = [40 45]; right_offset = 0.5; right_mult = 127/0.5; TFR = zeros(2, (cfg.foilim(2)-cfg.foilim(1)+1), 100); f1 = nan; % these are handles used in drawing u1=[]; u2=[]; u3=[]; u4=[]; u5=[]; u6=[]; p1=[]; p2=[]; p3=[]; p4=[]; p5=[]; p6=[]; c1=[]; c2=[]; b2=[]; while true if isempty(f1) || ~ishandle(f1) close all; f1 = figure; set(f1, 'resizeFcn', 'u1=[]; u2=[]; u3=[]; u4=[]; u5=[]; u6=[]; p1=[]; p2=[]; p3=[]; p4=[]; p5=[]; p6=[]; c1=[]; c2=[]; b2=[];'); u1=[]; u2=[]; u3=[]; u4=[]; u5=[]; u6=[]; p1=[]; p2=[]; p3=[]; p4=[]; p5=[]; p6=[]; c1=[]; c2=[]; b2=[]; end % determine number of samples available in buffer hdr = ft_read_header(cfg.headerfile, 'cache', true); % see whether new samples are available newsamples = (hdr.nSamples*hdr.nTrials-prevSample); if newsamples>=blocksize && (hdr.nSamples*hdr.nTrials/hdr.Fs)>cfg.windowsize % determine the samples to process if strcmp(cfg.bufferdata, 'last') begsample = hdr.nSamples*hdr.nTrials - round(cfg.windowsize*hdr.Fs) + 1; endsample = hdr.nSamples*hdr.nTrials; elseif strcmp(cfg.bufferdata, 'first') begsample = prevSample+1; endsample = prevSample+blocksize ; else error('unsupported value for cfg.bufferdata'); end % remember up to where the data was read prevSample = endsample; count = count + 1; fprintf('processing segment %d from sample %d to %d\n', count, begsample, endsample); % read the data segment from buffer dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false); dat = cfg.scale * dat; % construct a matching time axis time = ((begsample:endsample)-1)/hdr.Fs; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % from here onward it is specific to the power estimation from the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % apply some preprocessing to the data dat = ft_preproc_polyremoval(dat, 1); dat = ft_preproc_highpassfilter(dat, hdr.Fs, 3, 1, 'but', 'twopass'); dat = ft_preproc_lowpassfilter (dat, hdr.Fs, 35, 3, 'but', 'twopass'); if hdr.Fs<11025 % sampling range is low, assume it is EEG if hdr.Fs>110 % apply line noise filter dat = ft_preproc_bandstopfilter(dat, hdr.Fs, [45 55], 4, 'but', 'twopass'); end if hdr.Fs>230 % apply line noise filter dat = ft_preproc_bandstopfilter(dat, hdr.Fs, [95 115], 4, 'but', 'twopass'); end [spec, ntaper, freqoi] = ft_specest_mtmfft(dat, time, 'taper', 'dpss', 'tapsmofrq', 2, 'freqoi', cfg.foilim(1):cfg.foilim(2)); else % sampling range is high, assume it is audio [spec, ntaper, freqoi] = ft_specest_mtmfft(dat, time, 'taper', 'hanning', 'freqoi', cfg.foilim(1):cfg.foilim(2)); end pow = squeeze(mean(abs(spec.^2), 1)); % compute power, average over tapers if ~exist('TFR', 'var') TFR = nan(length(chanindx), length(freqoi), nhistory); end TFR(:,:,1:nhistory-1) = TFR(:,:,2:nhistory); TFR(:,:,end) = pow; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % translate channel 1 into a neurofeedback command %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(cfg.feedback, 'yes') % compute the average power in the specified frequency range fbeg = nearest(freqoi, cfg.feedback1.foilim(1)); fend = nearest(freqoi, cfg.feedback1.foilim(2)); value1 = mean(pow(1, fbeg:fend)); % scale the value between 0 and 1 historicalmean = mean(nanmean(TFR(1,fbeg:fend,:),3),2); historicalmin = min (nanmin (TFR(1,fbeg:fend,:),3),2); historicalmax = max (nanmax (TFR(1,fbeg:fend,:),3),2); % the value can be larger than expected from the history value1 = (value1 - historicalmin) ./ (historicalmax - historicalmin); controlfunction(cfg.feedback1, value1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % translate channel 2 into a neurofeedback command %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(cfg.feedback, 'yes') % if value2>threshold % controlfunction(cfg.feedback2); % end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % make the GUI elements %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% try if isempty(c1) || ~ishandle(c1) pos = [0.25 0.95 0.1 0.05]; c1 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_channel, 'BackgroundColor', 'white'); set(c1, 'position', pos); set(c1, 'string', chanindx(1)); set(c1, 'tag', 'c1'); end if isempty(c2) || ~ishandle(c2) pos = [0.70 0.95 0.1 0.05]; c2 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_channel, 'BackgroundColor', 'white'); set(c2, 'position', pos); set(c2, 'string', chanindx(2)); set(c2, 'tag', 'c2'); end if isempty(u1) || ~ishandle(u1) pos = get(p1, 'position'); % link the position to the subplot pos(1) = pos(1)-0.1; pos(2) = pos(2)-0.05; pos(3) = 0.1; pos(4) = 0.05; u1 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white'); set(u1, 'position', pos); set(u1, 'string', num2str(vaxis(1,2))); set(u1, 'tag', 'u1'); end if isempty(u2) || ~ishandle(u2) pos = get(p2, 'position'); % link the position to the subplot pos(1) = pos(1)-0.1; pos(2) = pos(2)-0.05; pos(3) = 0.1; pos(4) = 0.05; u2 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white'); set(u2, 'position', pos); set(u2, 'string', num2str(vaxis(2,2))); set(u2, 'tag', 'u2'); end if isempty(u3) || ~ishandle(u3) pos = get(p3, 'position'); % link the position to the subplot pos(1) = pos(1)-0.1; pos(2) = pos(2)-0.05; pos(3) = 0.1; pos(4) = 0.05; u3 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white'); set(u3, 'position', pos); set(u3, 'position', pos); set(u3, 'string', num2str(vaxis(3,2))); set(u3, 'tag', 'u3'); end if isempty(u4) || ~ishandle(u4) pos = get(p4, 'position'); % link the position to the subplot pos(1) = pos(1)-0.1; pos(2) = pos(2)-0.05; pos(3) = 0.1; pos(4) = 0.05; u4 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white'); set(u4, 'position', pos); set(u4, 'string', num2str(vaxis(4,2))); set(u4, 'tag', 'u4'); end if isempty(u5) || ~ishandle(u5) pos = get(p5, 'position'); % link the position to the subplot pos(1) = pos(1)-0.1; pos(2) = pos(2)-0.05; pos(3) = 0.1; pos(4) = 0.05; u5 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white'); set(u5, 'position', pos); set(u5, 'string', num2str(vaxis(5,2))); set(u5, 'tag', 'u5'); end if isempty(u6) || ~ishandle(u6) pos = get(p6, 'position'); % link the position to the subplot pos(1) = pos(1)-0.1; pos(2) = pos(2)-0.05; pos(3) = 0.1; pos(4) = 0.05; u6 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white'); set(u6, 'position', pos); set(u6, 'string', num2str(vaxis(6,2))); set(u6, 'tag', 'u6'); end if isempty(b2) || ~ishandle(b2) pos = [0.88 0.01 0.1 0.05]; b2 = uicontrol('style', 'pushbutton', 'units', 'normalized', 'callback', 'evalin(''caller'', ''b2clicked = true;'')'); set(b2, 'position', pos); set(b2, 'string', 'quit'); set(b2, 'tag', 'b2'); end end % try if b2clicked close all return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % visualize the data in 2*3 subplots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% try if isempty(p1) || ~ishandle(p1) p1 = subplot(3, 2, 1); else subplot(p1); h1 = plot(time, dat(1, :)); axis([min(time) max(time) vaxis(1, 1) vaxis(1, 2)]); set(p1, 'XTickLabel', []); ylabel('amplitude (uV)'); xlabel(sprintf('time: %d seconds', cfg.windowsize)); grid on if strcmp(cfg.feedback, 'yes') ax = axis; line([ax(1) ax(2)], [left_thresh_ampl left_thresh_ampl], 'color', 'red'); line([ax(1) + left_thresh_time(1)/hdr.Fs ax(1) + left_thresh_time(1)/hdr.Fs], [-300 300], 'color', 'green'); line([ax(1) + left_thresh_time(2)/hdr.Fs ax(1) + left_thresh_time(2)/hdr.Fs], [-300 300], 'color', 'green'); end end if isempty(p2) || ~ishandle(p2) p2 = subplot(3, 2, 2); else subplot(p2); h2 = plot(time, dat(2, :)); axis([min(time) max(time) vaxis(2, 1) vaxis(2, 2)]); set(p2, 'XTickLabel', []); ylabel('amplitude (uV)'); xlabel(sprintf('time: %d seconds', cfg.windowsize)); grid on end if isempty(p3) || ~ishandle(p3) p3 = subplot(3, 2, 3); else subplot(p3) h3 = bar(1:length(freqoi), pow(1, :), 0.5); % plot(pow(1).Frequencies, pow(1).Data); % bar(pow(1).Frequencies, pow(1).Data); axis([cfg.foilim(1) cfg.foilim(2) vaxis(3, 1) vaxis(3, 2)]); % str = sprintf('time = %d s\n', round(mean(time))); % title(str); xlabel('frequency (Hz)'); ylabel('power'); end if isempty(p4) || ~ishandle(p4) p4 = subplot(3, 2, 4); else subplot(p4) h4 = bar(1:length(freqoi), pow(2, :), 0.5); % plot(pow(2).Frequencies, pow(2).Data); % bar(pow(2).Frequencies, pow(2).Data); ax = axis; axis([cfg.foilim(1) cfg.foilim(2) vaxis(4, 1) vaxis(4, 2)]); if strcmp(cfg.feedback, 'yes') line([right_freq(1) right_freq(1)], [ax(3) ax(4)]); line([right_freq(2) right_freq(2)], [ax(3) ax(4)]); line([right_freq(1) right_freq(2)], [right_offset right_offset]); end xlabel('frequency (Hz)'); ylabel('power'); end if isempty(p5) || ~ishandle(p5) p5 = subplot(3, 2, 5); else subplot(p5) h5 = surf(squeeze(TFR(1, :, :))); axis([1 100 cfg.foilim(1) cfg.foilim(2) vaxis(5, 1) vaxis(5, 2)]); view(110, 45); xlabel(''); % this is the historical time ylabel('frequency (Hz)'); zlabel('power'); set(p5, 'XTickLabel', []); set(h5, 'EdgeColor', 'none'); shading interp box off end if isempty(p6) || ~ishandle(p6) p6 = subplot(3, 2, 6); else subplot(p6) h6 = surf(squeeze(TFR(2, :, :))); axis([1 100 cfg.foilim(1) cfg.foilim(2) vaxis(6, 1) vaxis(6, 2)]); view(110, 45); xlabel(''); % this is the historical time ylabel('frequency (Hz)'); zlabel('power'); set(p6, 'XTickLabel', []); set(h6, 'EdgeColor', 'none'); shading interp box off end end % try %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % present MIDI feedback if the data exceeds the specified limits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(cfg.feedback, 'yes') if left_thresh_ampl < 0 if min((dat(1, left_thresh_time(1):left_thresh_time(2)))) < left_thresh_ampl if beatdrum == true % midiOut('+', 10, 64, 127); beatdrum = false; else % midiOut('+', 10, 31, 127); beatdrum = true; end else midiOut('.', 1); end; elseif max((dat(left_thresh_time(1):left_thresh_time(2)))) > left_thresh_ampl if beatdrum == true % midiOut('+', 10, 64, 127); beatdrum = false; else % midiOut('+', 10, 31, 127); beatdrum = true; end else % midiOut('.', 1); end; % schemerlamp.setLevel(round(TFR(1, 60, end) / mean(TFR(1, 60, :)))*5); volume_right = round((mean(TFR(2, right_freq, end)) - right_offset) * right_mult); % midiOut(uint8([175+1, 7, volume_left])); % midiOut(uint8([16*14+1-1, 0, volume_left])); % ptich midiOut(uint8([175+2, 7, volume_right])); midiOut(uint8([16*14+2-1, 0, volume_right])); % ptich % schemerlamp.setLevel(9); end % if MIDI feedback % force an update of the figure drawnow end % if enough new samples end % while true %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function update_channel(h, varargin) global hdr chanindx val = abs(str2num(get(h, 'string'))); val = max(1, min(val, hdr.nChans)); if ~isempty(val) switch get(h, 'tag') case 'c1' chanindx(1) = val; set(h, 'string', num2str(val)); case 'c2' chanindx(2) = val; set(h, 'string', num2str(val)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function update_axis(h, varargin) global vaxis val = abs(str2num(get(h, 'string'))); if ~isempty(val) switch get(h, 'tag') case 'u1' vaxis(1,:) = [-val val]; case 'u2' vaxis(2,:) = [-val val]; case 'u3' vaxis(3,:) = [0 val]; case 'u4' vaxis(4,:) = [0 val]; case 'u5' vaxis(5,:) = [0 val]; case 'u6' vaxis(6,:) = [0 val]; end end
github
lcnbeapp/beapp-master
ft_realtime_oddball.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/realtime/online_eeg/ft_realtime_oddball.m
13,163
utf_8
d5a3400a1168a9e53bccbb79f889bebb
function ft_realtime_oddball(cfg) % FT_REALTIME_ODDBALL is an realtime application that computes an online % average for a standard and deviant condition. The ERPs/ERFs are plotted, % together with the difference as t-values. It should work both for EEG and % MEG, as long as there are two triggers present % % Use as % ft_realtime_oddball(cfg) % with the following configuration options % cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'all') % cfg.trialfun = string with the trial function % % The source of the data is configured as % cfg.dataset = string % or alternatively to obtain more low-level control as % cfg.datafile = string % cfg.headerfile = string % cfg.eventfile = string % cfg.dataformat = string, default is determined automatic % cfg.headerformat = string, default is determined automatic % cfg.eventformat = string, default is determined automatic % % To stop the realtime function, you have to press Ctrl-C % Copyright (C) 2008-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % set the default configuration options if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % default is detected automatically if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end % default is detected automatically if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end % default is detected automatically if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end if ~isfield(cfg, 'bufferdata'), cfg.bufferdata = 'last'; end % first or last if ~isfield(cfg, 'jumptoeof'), cfg.jumptoeof = 'no'; end % jump to end of file at initialization % translate dataset into datafile+headerfile cfg = ft_checkconfig(cfg, 'dataset2files', 'yes'); cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'}); % these are used by the GUI callbacks clear global chansel chanindx vaxis hdr global chansel chanindx vaxis hdr b1clicked = false; b2clicked = false; chansel = 1; % this is the subselection out of chanindx vaxis = [ -6 6 -3 3 ]; % ensure that the persistent variables related to caching are cleared clear ft_read_header % start by reading the header from the realtime buffer hdr = ft_read_header(cfg.headerfile, 'cache', true); % define a subset of channels for reading cfg.channel = ft_channelselection(cfg.channel, hdr.label); chanindx = match_str(hdr.label, cfg.channel); nchan = length(chanindx); if nchan==0 error('no channels were selected'); end if strcmp(cfg.jumptoeof, 'yes') prevSample = hdr.nSamples * hdr.nTrials; else prevSample = 0; end count = 0; f1 = nan; % initialize the timelock cell-array, each cell will hold the average in one condition timelock = {}; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this is the general BCI loop where realtime incoming data is handled %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% while true % determine latest header and event information event = ft_read_event(cfg.dataset, 'minsample', prevSample+1); % only consider events that are later than the data processed sofar hdr = ft_read_header(cfg.dataset, 'cache', true); % the trialfun might want to use this, but it is not required cfg.event = event; % store it in the configuration, so that it can be passed on to the trialfun cfg.hdr = hdr; % store it in the configuration, so that it can be passed on to the trialfun % evaluate the trialfun, note that the trialfun should not re-read the events and header fprintf('evaluating ''%s'' based on %d events\n', cfg.trialfun, length(event)); trl = feval(cfg.trialfun, cfg); % the code below assumes that the 4th column of the trl matrix contains the condition index % set the default condition to one if no condition index was given if size(trl,1)>0 && size(trl,2)<4 trl(:,4) = 1; end fprintf('processing %d trials\n', size(trl,1)); for trllop=1:size(trl,1) begsample = trl(trllop,1); endsample = trl(trllop,2); offset = trl(trllop,3); condition = trl(trllop,4); % it is important that the 4th column is returned with the condition number % remember up to where the data was read prevSample = endsample; count = count + 1; fprintf('processing segment %d from sample %d to %d, condition = %d\n', count, begsample, endsample, condition); while (hdr.nSamples*hdr.nTrials < endsample) % wait until all data up to the endsample has arrived hdr = ft_read_header(cfg.headerfile, 'cache', true); end % read the selected data segment from the buffer dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % from here onward it is specific to the processing of the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % apply some preprocessing options dat = ft_preproc_lowpassfilter(dat, hdr.Fs, 45); dat = ft_preproc_baselinecorrect(dat, 1, -offset); % put the data in a fieldtrip-like raw structure data.trial{1} = dat; data.time{1} = offset2time(offset, hdr.Fs, endsample-begsample+1); data.label = hdr.label(chanindx); data.hdr = hdr; data.fsample = hdr.Fs; if length(timelock)<condition || isempty(timelock{condition}) % this is the first occurence of this condition, initialize an empty timelock structure timelock{condition}.label = data.label; timelock{condition}.time = data.time{1}; timelock{condition}.avg = []; timelock{condition}.var = []; timelock{condition}.dimord = 'chan_time'; nchans = size(data.trial{1}, 1); nsamples = size(data.trial{1}, 2); % the following elements are for the cumulative computation timelock{condition}.n = 0; % number of trials timelock{condition}.s = zeros(nchans, nsamples); % sum timelock{condition}.ss = zeros(nchans, nsamples); % sum of squares end % add the new data to the accumulated data timelock{condition}.n = timelock{condition}.n + 1; timelock{condition}.s = timelock{condition}.s + data.trial{1}; timelock{condition}.ss = timelock{condition}.ss + data.trial{1}.^2; % compute the average and variance on the fly timelock{condition}.avg = timelock{condition}.s ./ timelock{condition}.n; timelock{condition}.var = (timelock{condition}.ss - (timelock{condition}.s.^2)./timelock{condition}.n) ./ (timelock{condition}.n-1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % from here onward the GUI is constructed %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% try if ~ishandle(f1) close all; f1 = figure; clear u1 u2 clear p1 p2 clear c1 set(f1, 'resizeFcn', 'clear u1 u2 p1 p2 c1 b1 b2') end if ~exist('p1') p1 = subplot(2,1,1); end if ~exist('p2') p2 = subplot(2,1,2); end if ~exist('c1') pos = [0.75 0.93 0.1 0.05]; c1 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_channel, 'BackgroundColor', 'white'); set(c1, 'position', pos); set(c1, 'string', chanindx(chansel)); set(c1, 'tag', 'c1'); end if ~exist('u1') pos = get(p1, 'position'); % link the position to the subplot pos(1) = pos(1)-0.1; pos(2) = pos(2)-0.05; pos(3) = 0.1; pos(4) = 0.05; u1 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white'); set(u1, 'position', pos); set(u1, 'string', num2str(vaxis(1,2))); set(u1, 'tag', 'u1'); end if ~exist('u2') pos = get(p2, 'position'); % link the position to the subplot pos(1) = pos(1)-0.1; pos(2) = pos(2)-0.05; pos(3) = 0.1; pos(4) = 0.05; u2 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white'); set(u2, 'position', pos); set(u2, 'string', num2str(vaxis(2,2))); set(u2, 'tag', 'u1'); end if ~exist('b1') pos = [0.75 0.01 0.1 0.05]; b1 = uicontrol('style', 'pushbutton', 'units', 'normalized', 'callback', 'evalin(''caller'', ''b1clicked = true'')'); set(b1, 'position', pos); set(b1, 'string', 'reset'); set(b1, 'tag', 'b1'); end if ~exist('b2') pos = [0.88 0.01 0.1 0.05]; b2 = uicontrol('style', 'pushbutton', 'units', 'normalized', 'callback', 'evalin(''caller'', ''b2clicked = true'')'); set(b2, 'position', pos); set(b2, 'string', 'quit'); set(b2, 'tag', 'b2'); end end % try if b1clicked timelock = {}; try, cla(p1); end try, cla(p2); end b1clicked = false; end if b2clicked return b2clicked = false; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % from here onward the data is plotted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% try if length(timelock)>1 sel = ~cellfun(@isempty, timelock); sel = find(sel, 2, 'first'); if length(sel)~=2 break end standard = timelock{sel(1)}; deviant = timelock{sel(2)}; tscore = (deviant.avg - standard.avg) ./ sqrt(standard.var./standard.n + deviant.var./deviant.n); time = standard.time; % deviant is the same if exist('p1') subplot(p1) cla hold on hs = plot(time, standard.avg(chansel,:), 'b-'); hd = plot(time, deviant.avg(chansel,:), 'r-'); set(hs, 'lineWidth', 1.5) set(hd, 'lineWidth', 1.5) grid on axis([time(1) time(end) vaxis(1,1) vaxis(1,2)]) legend(sprintf('standard (n=%d)', standard.n), sprintf('deviant (n=%d)', deviant.n)); xlabel('time (s)'); ylabel('amplitude (uV)'); title(sprintf('channel "%s"', hdr.label{chanindx(chansel)})); end if exist('p2') subplot(p2) cla hold on ht = plot(time, tscore(chansel,:), 'g-'); set(ht, 'lineWidth', 1.5) grid on axis([time(1) time(end) vaxis(2,1) vaxis(2,2)]) legend('difference'); xlabel('time (s)'); ylabel('t-score (a.u.)'); end end % two conditions are available end % try % force matlab to redraw the figure drawnow end % looping over new trials end % while true %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [time] = offset2time(offset, fsample, nsamples) offset = double(offset); nsamples = double(nsamples); time = (offset + (0:(nsamples-1)))/fsample; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function update_channel(h, varargin) global chansel chanindx hdr val = abs(str2num(get(h, 'string'))); val = max(1, min(val, length(chanindx))); if ~isempty(val) switch get(h, 'tag') case 'c1' chansel = val; set(h, 'string', num2str(val)); fprintf('switching to channel "%s"', hdr.label{chanindx(chansel)}); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function update_axis(h, varargin) global vaxis val = abs(str2num(get(h, 'string'))); if ~isempty(val) switch get(h, 'tag') case 'u1' vaxis(1,:) = [-val val]; case 'u2' vaxis(2,:) = [-val val]; end end
github
lcnbeapp/beapp-master
ft_omri_info_from_header.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/realtime/online_mri/ft_omri_info_from_header.m
4,361
utf_8
97589ff2ee8f9fa7ee376b4b628de647
function S = ft_omri_info_from_header(hdr) % function S = ft_omri_info_from_header(hdr) % % Convenience function to retrieve most important MR information % from a given header (H) as retrieved from a FieldTrip buffer. % Will look at both NIFTI-1 and SiemensAP fields, if present, and % give preference to SiemensAP info. % % Returns empty array if no information could be found. % Copyright (C) 2012, Stefan Klanke % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ SNif = []; SSap = []; if isfield(hdr,'nifti_1') try SNif = mri_info_from_nifti(hdr.nifti_1); catch warning('Errors occured while inspecting NIFTI-1 header.'); end end if isfield(hdr,'siemensap') try SSap = mri_info_from_sap(hdr.siemensap); catch warning('Errors occured while inspecting SiemensAP header.'); end end if ~isempty(SSap) S = SSap; if ~isempty(SNif) if ~isequal(SNif.voxels,SSap.voxels) warning('Conflicting information in NIFTI and SiemensAP - trusting SiemensAP...'); end S.mat0 = SNif.mat0; end else if ~isempty(SNif) S = SNif; else S = []; end end function S = mri_info_from_nifti(NH) S.vx = double(NH.dim(1)); S.vy = double(NH.dim(2)); S.vz = double(NH.dim(3)); S.voxels = [S.vx S.vy S.vz]; S.voxdim = double(NH.pixdim(1:3)); S.size = S.voxels .* S.voxdim; VoxToWorld = double([NH.srow_x; NH.srow_y; NH.srow_z]); M = VoxToWorld(1:3,1:3); P = VoxToWorld(1:3,4); % correct Mat0 in the same way SPM does (voxel index starts at 1) S.mat0 = [M (P-M*[1;1;1]); 0 0 0 1]; S.numEchos = 1; % can't detect this from NIFTI :-( switch NH.slice_code % Long-term TODO: look at slice_start and slice_end for padded slices case 1 % NIFTI_SLICE_SEQ_INC inds = 1:S.vz; case 2 % NIFTI_SLICE_SEQ_DEC inds = S.vz:-1:1; case 3 % NIFTI_SLICE_ALT_INC inds = [(1:2:S.vz) (2:2:S.vz)]; case 4 % NIFTI_SLICE_ALT_DEC inds = [(S.vz:-2:1) ((S.vz-1):-2:1)]; case 5 % NIFTI_SLICE_ALT_INC2 inds = [(2:2:S.vz) (1:2:S.vz)]; case 6 % NIFTI_SLICE_ALT_DEC2 inds = [((S.vz-1):-2:1) (S.vz:-2:1)]; otherwise warning('Unrecognized slice order - using default'); inds = 1:S.vz; end if NH.slice_duration > 0 S.TR = double(NH.slice_duration * S.vz); % first set up linear S.deltaT = (0:(S.vz-1))*double(NH.slice_duration) % then re-shuffle S.deltaT(inds) = S.deltaT; else % what can we do here? S.TR = 2; S.deltaT = (0:(S.vz-1))*S.TR/S.vz; S.deltaT(inds) = S.deltaT; end function S = mri_info_from_sap(SP) phaseFOV = SP.sSliceArray.asSlice{1}.dPhaseFOV; readoutFOV = SP.sSliceArray.asSlice{1}.dReadoutFOV; sliceThick = SP.sSliceArray.asSlice{1}.dThickness; distFactor = SP.sGroupArray.asGroup{1}.dDistFact; S.vx = double(SP.sKSpace.lBaseResolution); S.vy = S.vx * phaseFOV / readoutFOV; S.vz = double(SP.sSliceArray.lSize); S.voxels = [S.vx S.vy S.vz]; % this only takes care of the scaling, not the proper orientation sx = readoutFOV/S.vx; sy = phaseFOV/S.vy; % should always be == sx sz = sliceThick * (1.0 + distFactor); S.size = [readoutFOV phaseFOV S.vz*sz]; S.mat0 = [sx 0 0 0; 0 sy 0 0; 0 0 sz 0; 0 0 0 1]; S.voxdim = [sx sy sz]; S.numEchos = double(SP.lContrasts); S.TR = double(SP.alTR) * 1e-6; % originally in microseconds switch SP.sSliceArray.ucMode case 1 % == NIFTI_SLICE_SEQ_INC inds = 1:S.vz; case 2 % == NIFTI_SLICE_SEQ_DEC inds = S.vz:-1:1; case 4 % odd:ALT_INC or even:ALT_INC2 if mod(S.vz,2) == 1 inds = [(1:2:S.vz) (2:2:S.vz)]; else inds = [(2:2:S.vz) (1:2:S.vz)]; end otherwise warning('Unrecognized slice order - using default'); inds = 1:S.vz; end % first set up linear S.deltaT = (0:(S.vz-1))*S.TR/S.vz % then re-shuffle S.deltaT(inds) = S.deltaT;
github
lcnbeapp/beapp-master
encode_nifti1.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/realtime/online_mri/private/encode_nifti1.m
4,870
utf_8
9cf92a03587c511a5cec2c8c76a3c2c3
function blob = encode_nifti1(H) %function blob = encode_nifti1(H) % % Encodes a NIFTI-1 header (=> raw 348 bytes (uint8)) from a Matlab structure % that matches the C struct defined in nifti1.h. % % WARNING: This function currently ignores endianness !!! % (C) 2010 S.Klanke blob = uint8(zeros(1,348)); if ~isstruct(H) error 'Input must be a structure'; end % see nift1.h for information on structure sizeof_hdr = int32(348); blob(1:4) = typecast(sizeof_hdr, 'uint8'); blob = setString(blob, 5, 14, H, 'data_type'); blob = setString(blob, 15, 32, H, 'db_name'); blob = setInt32( blob, 33, 36, H, 'extents'); blob = setInt16( blob, 37, 38, H, 'session_error'); blob = setInt8( blob, 39, 39, H, 'regular'); blob = setInt8( blob, 40, 40, H, 'dim_info'); dim = int16(H.dim(:)'); ndim = numel(dim); if ndim<1 || ndim>7 error 'Field "dim" must have 1..7 elements'; end dim = [int16(ndim) dim]; blob(41:(42+2*ndim)) = typecast(dim,'uint8'); blob = setSingle(blob, 57, 60, H, 'intent_p1'); blob = setSingle(blob, 61, 64, H, 'intent_p2'); blob = setSingle(blob, 65, 68, H, 'intent_p3'); blob = setInt16( blob, 69, 70, H, 'intent_code'); blob = setInt16( blob, 71, 72, H, 'datatype'); blob = setInt16( blob, 73, 74, H, 'bitpix'); blob = setInt16( blob, 75, 76, H, 'slice_start'); blob = setSingle(blob, 77, 80, H, 'qfac'); if isfield(H,'pixdim') pixdim = single(H.pixdim(:)'); ndim = numel(pixdim); if ndim<1 || ndim>7 error 'Field "pixdim" must have 1..7 elements'; end blob(81:(80+4*ndim)) = typecast(pixdim,'uint8'); end blob = setSingle(blob, 109, 112, H, 'vox_offset'); blob = setSingle(blob, 113, 116, H, 'scl_scope'); blob = setSingle(blob, 117, 120, H, 'scl_inter'); blob = setInt16( blob, 121, 122, H, 'slice_end'); blob = setInt8( blob, 123, 123, H, 'slice_code'); blob = setInt8( blob, 124, 124, H, 'xyzt_units'); blob = setSingle(blob, 125, 128, H, 'cal_max'); blob = setSingle(blob, 129, 132, H, 'cal_min'); blob = setSingle(blob, 133, 136, H, 'slice_duration'); blob = setSingle(blob, 137, 140, H, 'toffset'); blob = setInt32( blob, 141, 144, H, 'glmax'); blob = setInt32( blob, 145, 148, H, 'glmin'); blob = setString(blob, 149, 228, H, 'descrip'); blob = setString(blob, 229, 252, H, 'aux_file'); blob = setInt16( blob, 253, 254, H, 'qform_code'); blob = setInt16( blob, 255, 256, H, 'sform_code'); blob = setSingle(blob, 257, 260, H, 'quatern_b'); blob = setSingle(blob, 261, 264, H, 'quatern_c'); blob = setSingle(blob, 265, 268, H, 'quatern_d'); blob = setSingle(blob, 269, 272, H, 'quatern_x'); blob = setSingle(blob, 273, 276, H, 'quatern_y'); blob = setSingle(blob, 277, 280, H, 'quatern_z'); blob = setSingle(blob, 281, 296, H, 'srow_x'); blob = setSingle(blob, 297, 312, H, 'srow_y'); blob = setSingle(blob, 313, 328, H, 'srow_z'); blob = setString(blob, 329, 344, H, 'intent_name'); if ~isfield(H,'magic') blob(345:347) = uint8('ni1'); else blob = setString(blob, 345, 347, H, 'magic'); end function blob = setString(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = getfield(H, fieldname); ne = numel(F); mx = endidx - begidx +1; if ne > 0 if ~ischar(F) || ne > mx errmsg = sprintf('Field "data_type" must be a string of maximally %i characters.', mx); error(errmsg); end blob(begidx:(begidx+ne-1)) = uint8(F(:)'); end % set 32-bit integers (check #elements) function blob = setInt32(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int32(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 4; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8'); % set 16-bit integers (check #elements) function blob = setInt16(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int16(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 2; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+2*ne-1)) = typecast(F(:)', 'uint8'); % just 8-bit integers (check #elements) function blob = setInt8(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int8(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1); if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+ne-1)) = typecast(F(:)', 'uint8'); % single precision floats function blob = setSingle(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = single(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 4; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8');