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
|
ZijingMao/baselineeegtest-master
|
read_erplabheader.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
write_plexon_nex.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/write_plexon_nex.m
| 9,546 |
utf_8
|
c3e00b18b8d0d194f3b0231301f3945f
|
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.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: write_plexon_nex.m 7123 2012-12-06 21:21:38Z roboos $
% 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: write_plexon_nex.m 7123 2012-12-06 21:21:38Z roboos $', 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
|
ZijingMao/baselineeegtest-master
|
ft_convert_units.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/ft_convert_units.m
| 9,048 |
utf_8
|
b0b47d21a2d75a5138e1d3499af2bf96
|
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 FT_ESTIMATE_UNITS, FT_READ_VOL, FT_READ_SENS
% Copyright (C) 2005-2013, Robert Oostenveld
%
% 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: ft_convert_units.m 10013 2014-12-03 09:14:21Z roboos $
% 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
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 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, '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 = 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'),
for i=1:length(obj.bnd)
obj.bnd(i).pnt = scale * obj.bnd(i).pnt;
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, 'chanpos'), obj.chanpos = scale * obj.chanpos; end
if isfield(obj, 'chanposorg'), obj.chanposorg = scale * obj.chanposorg; end
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
% dipole grid
if isfield(obj, 'pos'), obj.pos = scale * obj.pos; end
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
% 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
|
ZijingMao/baselineeegtest-master
|
ft_datatype.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/ft_datatype.m
| 9,441 |
utf_8
|
38c5cce959f40526c327578253ce1570
|
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.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: ft_datatype.m 10489 2015-06-27 06:22:20Z roboos $
if nargin<2
desired = [];
end
% determine the type of input data, this can be raw, freq, timelock, comp, spike, source, volume, dip, segmentation, parcellation
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, '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');
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');
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 issegmentation
% a segmentation data structure is a volume data structure, but in general not vice versa
% segmentation should conditionally go before volume, otherwise the returned ft_datatype will be volume
type = 'segmentation';
elseif isvolume
type = 'volume';
elseif isparcellation
% a parcellation data structure is a source data structure, but in general not vice versa
% parcellation should conditionally go before source, otherwise the returned ft_datatype will be source
type = 'parcellation';
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', 'segmentation'}));
case 'source'
type = any(strcmp(type, {'source', 'parcellation'}));
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')
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 ~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
|
ZijingMao/baselineeegtest-master
|
ft_apply_montage.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/ft_apply_montage.m
| 19,718 |
utf_8
|
82280137ae6d7db9e4e24fa895096d47
|
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 inputor array. The inputor array 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.labelorg = Nx1 cell-array
% montage.labelnew = Mx1 cell-array
%
% As an example, a bipolar montage could look like this
% bipolar.labelorg = {'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.chantypeorg = Nx1 cell-array
% montage.chantypenew = Mx1 cell-array
% montage.chanunitorg = 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')
%
% 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-2014, Robert Oostenveld
%
% 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: ft_apply_montage.m 10341 2015-04-17 14:10:18Z jorhor $
% 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', 'yes');
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, {'chantypeorg', 'chantypenew'}));
haschanunit = (isfield(input, 'chanunit') || isfield(input, 'chanunitnew')) && all(isfield(montage, {'chanunitorg', 'chanunitnew'}));
% make sure they always exist to facilitate the remainder of the code
if ~isfield(montage, 'chantypeorg')
montage.chantypeorg = repmat({'unknown'}, size(montage.labelorg));
if isfield(input, 'chantype') && ~istrue(inverse)
warning('copying input chantype to montage');
[sel1, sel2] = match_str(montage.labelorg, input.label);
montage.chantypeorg(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, 'chanunitorg')
montage.chanunitorg = repmat({'unknown'}, size(montage.labelorg));
if isfield(input, 'chanunit') && ~istrue(inverse)
warning('copying input chanunit to montage');
[sel1, sel2] = match_str(montage.labelorg, input.label);
montage.chanunitorg(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.labelorg) || ~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', 'labelorg', '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.labelorg)
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.labelorg;
tmp.labelorg = montage.labelnew;
tmp.chantypenew = montage.chantypeorg;
tmp.chantypeorg = montage.chantypenew;
tmp.chanunitnew = montage.chanunitorg;
tmp.chanunitorg = 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.labelorg = montage.labelorg(selcol);
montage.chantypeorg = montage.chantypeorg(selcol);
montage.chanunitorg = montage.chanunitorg(selcol);
clear selcol
% select and remove the columns corresponding to channels that are not present in the
% original data
remove = setdiff(montage.labelorg, intersect(montage.labelorg, inputlabel));
selcol = match_str(montage.labelorg, 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.labelorg));
% remove rows and columns
montage.labelorg = montage.labelorg(~selcol);
montage.labelnew = montage.labelnew(~selrow);
montage.chantypeorg = montage.chantypeorg(~selcol);
montage.chantypenew = montage.chantypenew(~selrow);
montage.chanunitorg = montage.chanunitorg(~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.labelorg);
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);
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.labelorg = cat(1, montage.labelorg(:), addlabel(:));
montage.labelnew = cat(1, montage.labelnew(:), addlabel(:));
montage.chantypeorg = cat(1, montage.chantypeorg(:), addchantype(:));
montage.chantypenew = cat(1, montage.chantypenew(:), addchantype(:));
montage.chanunitorg = cat(1, montage.chanunitorg(:), 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.labelorg = cat(1, montage.labelorg(:), addlabel(:));
montage.chantypeorg = cat(1, montage.chantypeorg(:), addchantype(:));
montage.chanunitorg = cat(1, montage.chanunitorg(:), 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.labelorg))~=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.labelorg))~=length(montage.labelorg)
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.labelorg);
montage.tra = montage.tra(:,selmontage);
montage.labelorg = montage.labelorg(selmontage);
montage.chantypeorg = montage.chantypeorg(selmontage);
montage.chanunitorg = montage.chanunitorg(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.chanunitorg)
scale = scalingfactor(input.chanunit, montage.chanunitorg);
montage.tra = montage.tra * diag(scale);
montage.chanunitorg = input.chanunit;
elseif isfield(input, 'chanunitnew') && ~isequal(input.chanunitnew, montage.chanunitorg)
scale = scalingfactor(input.chanunitnew, montage.chanunitorg);
montage.tra = montage.tra * diag(scale);
montage.chanunitorg = input.chanunitnew;
end
if isfield(input, 'chantype') && ~isequal(input.chantype, montage.chantypeorg)
error('inconsistent chantype in data and montage');
elseif isfield(input, 'chantypenew') && ~isequal(input.chantypenew, montage.chantypeorg)
error('inconsistent chantype in data and montage');
end
if isfield(input, 'labelorg') && 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, 'chanposorg')
% add a chanposorg only if it is not there yet
sens.chanposorg = 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, 'chanoriorg')
sens.chanoriorg = 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, 'labelorg')
sens.labelorg = inputlabel;
end
if ~isfield(sens, 'chantypeorg')
sens.chantypeorg = inputchantype;
end
if ~isfield(sens, 'chanunitorg')
sens.chanunitorg = 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', 'chantypeorg', 'chantypenew'});
end
if ~haschanunit
input = removefields(input, {'chanunit', 'chanunitorg', '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
|
github
|
ZijingMao/baselineeegtest-master
|
read_erplabdata.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_erplabdata.m
| 2,110 |
utf_8
|
60380c3ce12bbfd85b4dd554bdc0ae20
|
% 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
|
ZijingMao/baselineeegtest-master
|
in_fopen_manscan.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
read_biosemi_bdf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_biosemi_bdf.m
| 10,872 |
utf_8
|
51356ef9877faea1b6799cde11807eff
|
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.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: read_biosemi_bdf.m 8119 2013-05-09 12:35:07Z jansch $
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
|
ZijingMao/baselineeegtest-master
|
read_ctf_ascii.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_ctf_ascii.m
| 3,218 |
utf_8
|
ed3ebfd532e8ac61a7237dede21d739b
|
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.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: read_ctf_ascii.m 7123 2012-12-06 21:21:38Z roboos $
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
|
ZijingMao/baselineeegtest-master
|
read_mpi_dap.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_mpi_dap.m
| 7,085 |
utf_8
|
a51b5774d3dc46b048015b2b12e95e76
|
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.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: read_mpi_dap.m 7123 2012-12-06 21:21:38Z roboos $
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
|
ZijingMao/baselineeegtest-master
|
read_neuralynx_bin.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_neuralynx_bin.m
| 6,705 |
utf_8
|
1851b52bfcf664aadb50e417bd3ab74b
|
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.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: read_neuralynx_bin.m 7123 2012-12-06 21:21:38Z roboos $
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
|
ZijingMao/baselineeegtest-master
|
inifile.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
yokogawa2grad_new.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/yokogawa2grad_new.m
| 9,123 |
utf_8
|
a05c043b59134bedb201bba241ad57ef
|
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.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: yokogawa2grad_new.m 7123 2012-12-06 21:21:38Z roboos $
% 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
|
ZijingMao/baselineeegtest-master
|
read_besa_avr.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_besa_avr.m
| 3,929 |
utf_8
|
91f2ee59d1af564811511e0e7f201ba4
|
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.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: read_besa_avr.m 7123 2012-12-06 21:21:38Z roboos $
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
|
ZijingMao/baselineeegtest-master
|
ft_datatype_source.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/ft_datatype_source.m
| 11,599 |
utf_8
|
860bbf1db76786f373d55c7cd4a64746
|
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.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: ft_datatype_source.m 10266 2015-03-04 12:20:43Z jansch $
% 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)
% 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);
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 source = fixpos(source)
if ~isfield(source, 'pos')
if isfield(source, 'xgrid') && isfield(source, 'ygrid') && isfield(source, 'zgrid')
source.pos = grid2pos(source.xgrid, source.ygrid, source.zgrid);
elseif isfield(source, 'dim') && isfield(source, 'transform')
source.pos = dim2pos(source.dim, source.transform);
else
error('cannot reconstruct individual source positions');
end
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
|
ZijingMao/baselineeegtest-master
|
xml2struct.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
in_fread_manscan.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
read_ply.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_ply.m
| 5,986 |
utf_8
|
e7e4d22b778a98c951a9972c41d4dea3
|
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: read_ply.m 8776 2013-11-14 09:04:48Z roboos $
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
|
ZijingMao/baselineeegtest-master
|
read_eeglabdata.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_eeglabdata.m
| 3,193 |
utf_8
|
33c4ab48f49c3929347fee8295589fbc
|
% 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
|
ZijingMao/baselineeegtest-master
|
readbdf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
ft_platform_supports.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/ft_platform_supports.m
| 8,056 |
utf_8
|
ad60f22e6572bea34e03b9ffadfa0129
|
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(...)
% '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++)
% '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)
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 '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 '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 = matlabversion('2012b',Inf);
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 [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.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: ft_platform_supports.m 10466 2015-06-22 16:39:29Z roboos $
% 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
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 [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
% 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
end % function
|
github
|
ZijingMao/baselineeegtest-master
|
ft_warning.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/ft_warning.m
| 7,651 |
utf_8
|
883d92d69f8b72d44f2446b5ee2353cb
|
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, Robert Oostenveld
% Copyright (C) 2013, Robert Oostenveld, J?rn M. Horschig
%
% 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: ft_warning.m 10518 2015-07-04 13:07:46Z roboos $
global ft_default
if nargin < 1
error('You need to specify at least a warning message');
end
warned = false;
if isstruct(varargin{1})
warning(varargin{1});
return;
end
if ~isfield(ft_default, 'warning')
ft_default.warning.stopwatch = [];
ft_default.warning.identifier = [];
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 = decomma(fixname(fname)); % make a nice string that is allowed as structure fieldname
if length(fname) > 63 % MATLAB max name
fname = fname(1:63);
end
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 name = decomma(name)
name(name==',')=[];
end % function
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
|
ZijingMao/baselineeegtest-master
|
ft_hastoolbox.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/ft_hastoolbox.m
| 25,228 |
utf_8
|
0972697d520199424e9b41666dc33c04
|
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.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: ft_hastoolbox.m 10419 2015-05-22 10:19:44Z roboos $
% 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.megis.de, or contact Karsten Hoechstetter'
'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'
'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.ru.nl/neuroimaging/fieldtrip'
'PREPROC' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'FORWARD' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'INVERSE' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'SPECEST' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'REALTIME' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'SPIKE' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'CONNECTIVITY' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'PEER' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'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://fieldtrip.fcdonders.nl/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/'
};
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);
% set fieldtrip trunk path, used for determining ft-subdirs are on path
fttrunkpath = unixpath(fileparts(which('ft_defaults')));
switch toolbox
case 'AFNI'
status = (exist('BrikLoad', 'file') && exist('BrikInfo', 'file'));
case 'DSS'
status = exist('denss', 'file') && exist('dss_create_state', 'file');
case 'EEGLAB'
status = exist('runica', 'file');
case 'NWAY'
status = exist('parafac', 'file');
case 'SPM'
status = exist('spm.m', 'file'); % any version of SPM is fine
case 'SPM99'
status = exist('spm.m', 'file') && strcmp(spm('ver'),'SPM99');
case 'SPM2'
status = exist('spm.m', 'file') && strcmp(spm('ver'),'SPM2');
case 'SPM5'
status = exist('spm.m', 'file') && strcmp(spm('ver'),'SPM5');
case 'SPM8'
status = exist('spm.m', 'file') && strncmp(spm('ver'),'SPM8', 4);
case 'SPM8UP' % version 8 or later
status = 0;
if exist('spm.m', 'file')
v = spm('ver');
if str2num(v(isstrprop(v, 'digit')))>=8
status = 1;
end
end
%This is to avoid crashes when trying to add SPM to the path
if ~status
toolbox = 'SPM8';
end
case 'SPM12'
status = exist('spm.m', 'file') && strncmp(spm('ver'),'SPM12', 5);
case 'MEG-PD'
status = (exist('rawdata', 'file') && exist('channames', 'file'));
case 'MEG-CALC'
status = (exist('megmodel', 'file') && exist('megfield', 'file') && exist('megtrans', 'file'));
case 'BIOSIG'
status = (exist('sopen', 'file') && exist('sread', 'file'));
case 'EEG'
status = (exist('ctf_read_res4', 'file') && exist('ctf_read_meg4', 'file'));
case 'EEGSF' % alternative name
status = (exist('ctf_read_res4', 'file') && exist('ctf_read_meg4', 'file'));
case 'MRI' % other functions in the mri section
status = (exist('avw_hdr_read', 'file') && exist('avw_img_read', 'file'));
case 'NEUROSHARE'
status = (exist('ns_OpenFile', 'file') && exist('ns_SetLibrary', 'file') && exist('ns_GetAnalogData', 'file'));
case 'ARTINIS'
status = exist('read_artinis_oxy3', 'file');
case 'BESA'
status = (exist('readBESAtfc', 'file') && exist('readBESAswf', 'file'));
case 'EEPROBE'
status = (exist('read_eep_avr', 'file') && exist('read_eep_cnt', 'file'));
case 'YOKOGAWA'
status = hasyokogawa('16bitBeta6');
case 'YOKOGAWA12BITBETA3'
status = hasyokogawa('12bitBeta3');
case 'YOKOGAWA16BITBETA3'
status = hasyokogawa('16bitBeta3');
case 'YOKOGAWA16BITBETA6'
status = hasyokogawa('16bitBeta6');
case 'YOKOGAWA_MEG_READER'
status = hasyokogawa('1.4');
case 'BEOWULF'
status = (exist('evalwulf', 'file') && exist('evalwulf', 'file') && exist('evalwulf', 'file'));
case 'MENTAT'
status = (exist('pcompile', 'file') && exist('pfor', 'file') && exist('peval', 'file'));
case 'SON2'
status = (exist('SONFileHeader', 'file') && exist('SONChanList', 'file') && exist('SONGetChannel', 'file'));
case '4D-VERSION'
status = (exist('read4d', 'file') && exist('read4dhdr', 'file'));
case {'STATS', 'STATISTICS'}
status = license('checkout', 'statistics_toolbox'); % also check the availability of a toolbox license
case {'OPTIM', 'OPTIMIZATION'}
status = license('checkout', 'optimization_toolbox'); % also check the availability of a toolbox license
case {'SPLINES', 'CURVE_FITTING'}
status = license('checkout', 'curve_fitting_toolbox'); % also check the availability of a toolbox license
case 'SIGNAL'
status = license('checkout', 'signal_toolbox') && exist('window', 'file'); % also check the availability of a toolbox license
case 'IMAGE'
status = license('checkout', 'image_toolbox'); % also check the availability of a toolbox license
case {'DCT', 'DISTCOMP'}
status = license('checkout', 'distrib_computing_toolbox'); % also check the availability of a toolbox license
case 'COMPILER'
status = license('checkout', 'compiler'); % also check the availability of a toolbox license
case 'FASTICA'
status = exist('fpica', 'file');
case 'BRAINSTORM'
status = exist('bem_xfer', 'file');
case 'DENOISE'
status = (exist('tsr', 'file') && exist('sns', 'file'));
case 'CTF'
status = (exist('getCTFBalanceCoefs', 'file') && exist('getCTFdata', 'file'));
case 'BCI2000'
status = exist('load_bcidat', 'file');
case 'NLXNETCOM'
status = (exist('MatlabNetComClient', 'file') && exist('NlxConnectToServer', 'file') && exist('NlxGetNewCSCData', 'file'));
case 'DIPOLI'
status = exist('dipoli.maci', 'file');
case 'MNE'
status = (exist('fiff_read_meas_info', 'file') && exist('fiff_setup_read_raw', 'file'));
case 'TCP_UDP_IP'
status = (exist('pnet', 'file') && exist('pnet_getvar', 'file') && exist('pnet_putvar', 'file'));
case 'BEMCP'
status = (exist('bem_Cij_cog', 'file') && exist('bem_Cij_lin', 'file') && exist('bem_Cij_cst', 'file'));
case 'OPENMEEG'
status = exist('om_save_tri.m', 'file');
case 'PRTOOLS'
status = (exist('prversion', 'file') && exist('dataset', 'file') && exist('svc', 'file'));
case 'ITAB'
status = (exist('lcReadHeader', 'file') && exist('lcReadData', 'file'));
case 'BSMART'
status = exist('bsmart', 'file');
case 'FREESURFER'
status = exist('MRIread', 'file') && exist('vox2ras_0to1', 'file');
case 'FNS'
status = exist('elecsfwd', 'file');
case 'SIMBIO'
status = exist('calc_stiff_matrix_val', 'file') && exist('sb_transfer', 'file');
case 'VGRID'
status = exist('vgrid.m', 'file');
case 'GIFTI'
status = exist('gifti', 'file');
case 'XML4MAT'
status = exist('xml2struct.m', 'file') && exist('xml2whos.m', 'file');
case 'SQDPROJECT'
status = exist('sqdread.m', 'file') && exist('sqdwrite.m', 'file');
case 'BCT'
status = exist('macaque71.mat', 'file') && exist('motif4funct_wei.m', 'file');
case 'CCA'
status = exist('ccabss.m', 'file');
case 'EGI_MFF'
status = exist('mff_getObject.m', 'file') && exist('mff_getSummaryInfo.m', 'file');
case 'TOOLBOX_GRAPH'
status = exist('toolbox_graph', 'file');
case 'NETCDF'
status = exist('netcdf', 'file');
case 'MYSQL'
status = exist(['mysql.' mexext], 'file'); % this only consists of a single mex file
case 'ISO2MESH'
status = exist('vol2surf.m', 'file') && exist('qmeshcut.m', 'file');
case 'QSUB'
status = exist('qsubfeval.m', 'file') && exist('qsubcellfun.m', 'file');
case 'ENGINE'
status = exist('enginefeval.m', 'file') && exist('enginecellfun.m', 'file');
case 'DATAHASH'
status = exist('DataHash.m', 'file');
case 'IBTB'
status = exist('make_ibtb.m', 'file') && exist('binr.m', 'file');
case 'ICASSO'
status = exist('icassoEst.m', 'file');
case 'XUNIT'
status = exist('initTestSuite.m', 'file') && exist('runtests.m', 'file');
case 'PLEXON'
status = exist('plx_adchan_gains.m', 'file') && exist('mexPlex', 'file');
case '35625-INFORMATION-THEORY-TOOLBOX'
filelist = {'conditionalEntropy' 'entropy' 'jointEntropy' 'mutualInformation' 'nmi' 'nvi' 'relativeEntropy'};
status = all(cellfun(@exist, filelist, repmat({'file'}, size(filelist))));
case '29046-MUTUAL-INFORMATION'
filelist = {'MI.m' 'license.txt'};
status = all(cellfun(@exist, filelist, repmat({'file'}, size(filelist))));
case '14888-MUTUAL-INFORMATION-COMPUTATION'
filelist = {'condentropy.m' 'demo_mi.m' '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' };
status = all(cellfun(@exist, filelist, repmat({'file'}, size(filelist))));
case 'PLOT2SVG'
filelist = {'plot2svg.m' 'simulink2svg.m'};
status = all(cellfun(@exist, filelist, repmat({'file'}, size(filelist))));
case 'BRAINSUITE'
filelist = {'readdfs.m' 'writedfc.m'};
status = all(cellfun(@exist, filelist, repmat({'file'}, size(filelist))));
case 'BRAINVISA'
filelist = {'loadmesh.m' 'plotmesh.m' 'savemesh.m'};
status = all(cellfun(@exist, filelist, repmat({'file'}, size(filelist))));
% the following are fieldtrip modules/toolboxes
case 'FILEIO'
status = (exist('ft_read_header', 'file') && exist('ft_read_data', 'file') && exist('ft_read_event', 'file') && exist('ft_read_sens', 'file'));
case 'FORWARD'
status = (exist('ft_compute_leadfield', 'file') && exist('ft_prepare_vol_sens', 'file'));
case 'PLOTTING'
status = (exist('ft_plot_topo', 'file') && exist('ft_plot_mesh', 'file') && exist('ft_plot_matrix', 'file'));
case 'PEER'
status = exist('peerslave', 'file') && exist('peermaster', 'file');
case 'CONNECTIVITY'
status = exist('ft_connectivity_corr', 'file') && exist('ft_connectivity_granger', 'file');
case 'SPIKE'
status = exist('ft_spiketriggeredaverage.m', 'file') && exist('ft_spiketriggeredspectrum.m', 'file');
% these were missing, added them using the below style, see bug 1804 - roevdmei
case 'INVERSE'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/inverse'], 'once')); % INVERSE is not added above, consider doing it there -roevdmei
case 'REALTIME'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/realtime'], 'once')); % REALTIME is not added above, consider doing it there -roevdmei
case 'SPECEST'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/specest'], 'once')); % SPECEST is not added above, consider doing it there -roevdmei
case 'PREPROC'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/preproc'], 'once')); % PREPROC is not added above, consider doing it there -roevdmei
% the following are not proper toolboxes, but only subdirectories in the fieldtrip toolbox
% these are added in ft_defaults and are specified with unix-style forward slashes
case 'FILEEXCHANGE'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/external/fileexchange'], 'once'));
case 'COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/compat'], 'once'));
case 'STATFUN'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/statfun'], 'once'));
case 'TRIALFUN'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/trialfun'], 'once'));
case 'UTILITIES/COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/utilities/compat'], 'once'));
case 'FILEIO/COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/fileio/compat'], 'once'));
case 'PREPROC/COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/preproc/compat'], 'once'));
case 'FORWARD/COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/forward/compat'], 'once'));
case 'PLOTTING/COMPAT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/plotting/compat'], 'once'));
case 'TEMPLATE/LAYOUT'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/layout'], 'once'));
case 'TEMPLATE/ANATOMY'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/anatomy'], 'once'));
case 'TEMPLATE/HEADMODEL'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/headmodel'], 'once'));
case 'TEMPLATE/ELECTRODE'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/electrode'], 'once'));
case 'TEMPLATE/NEIGHBOURS'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/neighbours'], 'once'));
case 'TEMPLATE/SOURCEMODEL'
status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/sourcemodel'], 'once'));
otherwise
if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end
status = 0;
end
% it should be a boolean value
status = (status~=0);
% 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
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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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
|
github
|
ZijingMao/baselineeegtest-master
|
read_yokogawa_data_new.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_yokogawa_data_new.m
| 5,691 |
utf_8
|
0f379a92d07b29f6a231c357f4f02920
|
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.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: read_yokogawa_data_new.m 7123 2012-12-06 21:21:38Z roboos $
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
|
ZijingMao/baselineeegtest-master
|
read_plexon_nex.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_plexon_nex.m
| 7,637 |
utf_8
|
fa08ec3a9e740a63be5c6ee72ef0d1a0
|
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.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: read_plexon_nex.m 8429 2013-08-27 13:09:43Z roboos $
% 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
|
ZijingMao/baselineeegtest-master
|
read_bti_m4d.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_bti_m4d.m
| 5,838 |
utf_8
|
123c765eeecec5359bfdfc0af7c65fc0
|
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.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: read_bti_m4d.m 8770 2013-11-12 13:54:58Z roboos $
[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
|
ZijingMao/baselineeegtest-master
|
read_asa.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_asa.m
| 3,857 |
utf_8
|
bd6525da96c296723f6a29b027b2445e
|
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.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: read_asa.m 7123 2012-12-06 21:21:38Z roboos $
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
|
ZijingMao/baselineeegtest-master
|
ft_checkdata.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/ft_checkdata.m
| 77,665 |
utf_8
|
0c7aabcbe3ab11b70e71782914d5d60e
|
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
% 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.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: ft_checkdata.m 10497 2015-06-30 15:52:15Z jimher $
% 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');
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');
hasdimord = ft_getopt(varargin, 'hasdimord', 'no');
hasdim = ft_getopt(varargin, 'hasdim');
hascumtapcnt = ft_getopt(varargin, 'hascumtapcnt');
hasdof = ft_getopt(varargin, 'hasdof', 'no');
haspow = ft_getopt(varargin, 'haspow', 'no');
cmbrepresentation = ft_getopt(varargin, 'cmbrepresentation');
channelcmb = ft_getopt(varargin, 'channelcmb');
sourcedimord = ft_getopt(varargin, 'sourcedimord');
sourcerepresentation = ft_getopt(varargin, 'sourcerepresentation');
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
if (~isempty(ft_getopt(varargin, 'hasoffset')))
ft_warning('ft_checkdata option ''hasoffset'' has been removed and will be ignored');
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');
% 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
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
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;
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')
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(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 isvolume
% % ensure consistent dimensions of the volumetric data
% % reshape each of the volumes that is found into a 3D array
% param = parameterselection('all', data);
% dim = data.dim;
% for i=1:length(param)
% tmp = getsubfield(data, param{i});
% tmp = reshape(tmp, dim);
% data = setsubfield(data, param{i}, tmp);
% end
%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 istrue(hascoordsys) && ~isfield(data, 'coordsys')
data = ft_determine_coordsys(data);
end
if issource || isvolume,
% the following section is to make a dimord-consistent representation of
% volume and source data, taking trials, time and frequency into account
if isequal(hasdimord, 'yes') && (~isfield(data, 'dimord') || ~strcmp(data.dimord,sourcedimord))
% determine the size of the data
if isfield(data, 'dimord'),
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('time', dimtok)), Ntime = length(data.time); else Ntime = 1; end
if ~isempty(strmatch('freq', dimtok)), Nfreq = length(data.freq); else Nfreq = 1; end
else
Nfreq = 1;
Ntime = 1;
end
%convert old style source representation into new style
if isfield(data, 'avg') && isfield(data.avg, 'mom') && (isfield(data, 'freq') || isfield(data, 'frequency')) && strcmp(sourcedimord, 'rpt_pos'),
%frequency domain source representation convert to single trial power
Npos = size(data.pos,1);
Nrpt = size(data.cumtapcnt,1);
tmpmom = zeros(Npos, size(data.avg.mom{data.inside(1)},2));
tmpmom(data.inside,:) = cat(1,data.avg.mom{data.inside});
tmppow = zeros(Npos, Nrpt);
tapcnt = [0;cumsum(data.cumtapcnt)];
for k = 1:Nrpt
Ntap = tapcnt(k+1)-tapcnt(k);
tmppow(data.inside,k) = sum(abs(tmpmom(data.inside,(tapcnt(k)+1):tapcnt(k+1))).^2,2)./Ntap;
end
data.pow = tmppow';
data = rmfield(data, 'avg');
if strcmp(inside, 'logical'),
data = fixinside(data, 'logical');
data.inside = repmat(data.inside(:)',[Nrpt 1]);
end
elseif isfield(data, 'avg') && isfield(data.avg, 'mom') && (isfield(data, 'freq') || isfield(data, 'frequency')) && strcmp(sourcedimord, 'rpttap_pos'),
%frequency domain source representation convert to single taper fourier coefficients
Npos = size(data.pos,1);
Nrpt = sum(data.cumtapcnt);
data.fourierspctrm = complex(zeros(Nrpt, Npos), zeros(Nrpt, Npos));
data.fourierspctrm(:, data.inside) = transpose(cat(1, data.avg.mom{data.inside}));
data = rmfield(data, 'avg');
elseif isfield(data, 'avg') && isfield(data.avg, 'mom') && isfield(data, 'time') && strcmp(sourcedimord, 'pos_time'),
Npos = size(data.pos,1);
Nrpt = 1;
tmpmom = zeros(Npos, size(data.avg.mom{data.inside(1)},2));
tmpmom(data.inside,:) = cat(1,data.avg.mom{data.inside});
data.mom = tmpmom;
if isfield(data.avg, 'noise'),
tmpnoise = data.avg.noise(:);
data.noise = tmpnoise(:,ones(1,size(tmpmom,2)));
end
data = rmfield(data, 'avg');
Ntime = length(data.time);
elseif isfield(data, 'trial') && isfield(data.trial(1), 'mom') && isfield(data, 'time') && strcmp(sourcedimord, 'rpt_pos_time'),
Npos = size(data.pos,1);
Nrpt = length(data.trial);
Ntime = length(data.time);
tmpmom = zeros(Nrpt, Npos, Ntime);
for k = 1:Nrpt
tmpmom(k,data.inside,:) = cat(1,data.trial(k).mom{data.inside});
end
data = rmfield(data, 'trial');
data.mom = tmpmom;
elseif isfield(data, 'trial') && isstruct(data.trial)
Nrpt = length(data.trial);
else
Nrpt = 1;
end
% start with an initial specification of the dimord and dim
if (~isfield(data, 'dim') || ~isfield(data, 'dimord'))
if issource
% at least it should have a Nx3 pos
data.dim = size(data.pos, 1);
data.dimord = 'pos';
elseif isvolume
% at least it should have a 1x3 dim
data.dim = data.dim;
data.dimord = 'dim1_dim2_dim3';
end
end
% add the additional dimensions
if Nfreq>1
data.dimord = [data.dimord '_freq'];
data.dim = [data.dim Nfreq];
end
if Ntime>1
data.dimord = [data.dimord '_time'];
data.dim = [data.dim Ntime];
end
if Nrpt>1 && strcmp(sourcedimord, 'rpt_pos'),
data.dimord = ['rpt_' data.dimord];
data.dim = [Nrpt data.dim ];
elseif Nrpt>1 && strcmp(sourcedimord, 'rpttap_pos'),
data.dimord = ['rpttap_' data.dimord];
data.dim = [Nrpt data.dim ];
end
% the nested trial structure is not compatible with dimord
if isfield(data, 'trial') && isstruct(data.trial)
param = fieldnames(data.trial);
for i=1:length(param)
if isa(data.trial(1).(param{i}), 'cell')
concat = cell(data.dim(1), prod(data.dim(2:end)));
else
concat = zeros(data.dim(1), prod(data.dim(2:end)));
end
for j=1:length(data.trial)
tmp = data.trial(j).(param{i});
concat(j,:) = tmp(:);
end % for each trial
data.trial = rmfield(data.trial, param{i});
data.(param{i}) = reshape(concat, data.dim);
end % for each param
data = rmfield(data, 'trial');
end
end
% ensure consistent dimensions of the source reconstructed data
% reshape each of the source reconstructed parameters
if issource && isfield(data, 'dim') && prod(data.dim)==size(data.pos,1)
dim = [prod(data.dim) 1];
%elseif issource && any(~cellfun('isempty',strfind(fieldnames(data), 'dimord')))
% dim = [size(data.pos,1) 1]; %sparsely represented source structure new style
elseif isfield(data, 'dim'),
dim = [data.dim 1];
elseif issource && ~isfield(data, 'dimord')
dim = [size(data.pos,1) 1];
elseif isfield(data, 'dimord'),
%HACK
dimtok = tokenize(data.dimord, '_');
for i=1:length(dimtok)
if strcmp(dimtok(i), 'pos')
dim(1,i) = size(data.pos,1);
elseif strcmp(dimtok(i), '{pos}')
dim(1,i) = size(data.pos,1);
elseif issubfield(data,dimtok{i})
dim(1,i) = length(getsubfield(data,dimtok{i}));
else
dim(1,i) = nan; % this applies to rpt, ori
end
end
try
% the following only works for rpt, not for ori
i = find(isnan(dim));
if ~isempty(i)
n = fieldnames(data);
for ii=1:length(n)
numels(1,ii) = numel(getfield(data,n{ii}));
end
nrpt = numels./prod(dim(setdiff(1:length(dim),i)));
nrpt = nrpt(nrpt==round(nrpt));
dim(i) = max(nrpt);
end
end % try
if numel(dim)==1, dim(1,2) = 1; end;
end
% these fields should not be reshaped
exclude = {'cfg' 'fwhm' 'leadfield' 'q' 'rough' 'pos'};
if ~isempty(inside) && ~strcmp(inside, 'logical')
% also exclude the inside/outside from being reshaped
exclude = cat(2, exclude, {'inside' 'outside'});
end
param = setdiff(parameterselection('all', data), exclude);
for i=1:length(param)
if any(param{i}=='.')
% the parameter is nested in a substructure, which can have multiple elements (e.g. source.trial(1).pow, source.trial(2).pow, ...)
% loop over the substructure array and reshape for every element
tok = tokenize(param{i}, '.');
sub1 = tok{1}; % i.e. this would be 'trial'
sub2 = tok{2}; % i.e. this would be 'pow'
tmp1 = getfield(data, sub1);
for j=1:numel(tmp1)
tmp2 = getfield(tmp1(j), sub2);
if prod(dim)==numel(tmp2)
tmp2 = reshape(tmp2, dim);
end
tmp1(j) = setfield(tmp1(j), sub2, tmp2);
end
data = setfield(data, sub1, tmp1);
else
tmp = getfield(data, param{i});
if prod(dim)==numel(tmp)
tmp = reshape(tmp, dim);
end
data = setfield(data, param{i}, tmp);
end
end
end
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 isequal(hasdim, 'yes') && ~isfield(data, 'dim')
data.dim = pos2dim(data.pos);
elseif isequal(hasdim, 'no') && isfield(data, 'dim')
data = rmfield(data, 'dim');
end % if hasdim
if isequal(hascumtapcnt, 'yes') && ~isfield(data, 'cumtapcnt')
error('This function requires data with a ''cumtapcnt'' field');
elseif isequal(hascumtapcnt, 'no') && isfield(data, 'cumtapcnt')
data = rmfield(data, 'cumtapcnt');
end % if hascumtapcnt
if isequal(hasdof, 'yes') && ~isfield(data, 'hasdof')
error('This function requires data with a ''dof'' field');
elseif isequal(hasdof, 'no') && isfield(data, 'hasdof')
data = rmfield(data, 'cumtapcnt');
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.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, [siz(2:end) 1]); 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, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, [siz(2:end) 1]); 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');
else
data.crsspctrm = data.powspctrm;
data.labelcmb = [data.label(:) data.label(:)];
data = rmfield(data, 'powspctrm');
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'}))
% this is how is currently done in prepare_freq_matrices
data = ft_checkdata(data, 'cmbrepresentation', 'sparse');
data = ft_checkdata(data, 'cmbrepresentation', 'full');
end % convert from one to another bivariate representation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert to new source representation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [output] = fixsource(input, varargin)
% FIXME this should be merged into ft_datatype_source
% FIXSOURCE converts old style source structures into new style source structures and the
% other way around
%
% Use as:
% fixsource(input, type)
% where input is a source structure,
%
% Typically, old style source structures contain
% avg.XXX or trial.XXX fields
%
% The new style source structure contains:
% source.pos
% source.dim (optional, if the list of positions describes a 3D volume
% source.XXX the old style subfields in avg/trial
% source.XXXdimord string how to interpret the respective XXX field:
% e.g. source.leadfield = cell(1,Npos), source.leadfielddimord = '{pos}_chan_ori'
% source.mom = cell(1,Npos), source.momdimord = '{pos}_ori_rpttap'
type = ft_getopt(varargin, 'type');
haspow = ft_getopt(varargin, 'haspow');
if isempty(type), type = 'old'; end
if isempty(haspow), haspow = 'no'; end
fnames = fieldnames(input);
tmp = cell2mat(strfind(fnames, 'dimord')); % get dimord like fields
if isfield(input, 'inside') && islogical(input.inside)
% the following code expects an indexed representation
input = fixinside(input, 'index');
end
if any(tmp>1)
current = 'new';
elseif any(tmp==1)
% don't know what to do yet data is JM's own invention
current = 'old';
else
current = 'old';
end
if strcmp(current, type),
% do nothing
output = input;
% return
elseif strcmp(current, 'old') && strcmp(type, 'new'),
% go from old to new
if isfield(input, 'avg'),
stuff = getfield(input, 'avg');
output = rmfield(input, 'avg');
elseif isfield(input, 'trial'),
stuff = getfield(input, 'trial');
output = rmfield(input, 'trial');
else
% this could occur later in the pipeline, e.g. when doing group statistics using individual subject descriptive statistics
% warning('the input does not contain an avg or trial field');
stuff = struct; % empty structure
output = input;
end
%-------------------------------------------------
%remove and rename the specified fields if present
removefields = {'xgrid';'ygrid';'zgrid';'method'};
renamefields = {'frequency' 'freq'; 'csdlabel' 'orilabel'};
fnames = fieldnames(output);
for k = 1:numel(fnames)
ix = strmatch(fnames{k}, removefields);
if ~isempty(ix),
output = rmfield(output, fnames{k});
end
ix = find(strcmp(fnames{k}, renamefields(:,1)));
if ~isempty(ix),
output = setfield(output, renamefields{ix,2}, ...
getfield(output, renamefields{ix,1}));
output = rmfield(output, fnames{k});
end
end
%----------------------------------------------------------------------
%put the stuff originally in avg or trial one level up in the structure
fnames = fieldnames(stuff(1));
npos = size(input.pos,1);
nrpt = numel(stuff);
for k = 1:numel(fnames)
if nrpt>1,
%multiple trials
%(or subjects FIXME not yet implemented, nor tested)
tmp = getfield(stuff(1), fnames{k});
siz = size(tmp);
if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom')
%pcc based mom is orixrpttap
%tranpose to keep manageable
for kk = 1:numel(input.inside)
indx = input.inside(kk);
tmp{indx} = permute(tmp{indx}, [2 1 3]);
end
nrpttap = sum(input.cumtapcnt);
sizvox = [size(tmp{input.inside(1)}) 1];
sizvox = [nrpttap sizvox(2:end)];
elseif strcmp(fnames{k}, 'mom'),
%this is then probably not a frequency based mom
nrpttap = numel(stuff);
sizvox = [size(tmp{input.inside(1)}) 1];
sizvox = [nrpttap sizvox];
elseif iscell(tmp)
nrpttap = numel(stuff);
sizvox = [size(tmp{input.inside(1)}) 1];
sizvox = [nrpttap sizvox];
end
if siz(1) ~= npos && siz(2) ==npos,
tmp = transpose(tmp);
end
if iscell(tmp)
%allocate memory for cell-array
tmpall = cell(npos,1);
for n = 1:numel(input.inside)
tmpall{input.inside(n)} = zeros(sizvox);
end
else
%allocate memory for matrix
tmpall = zeros([npos nrpt siz(2:end)]);
end
cnt = 0;
for m = 1:nrpt
tmp = getfield(stuff(m), fnames{k});
siz = size(tmp);
if siz(1) ~= npos && siz(2) ==npos,
tmp = transpose(tmp);
end
if ~iscell(tmp),
tmpall(:,m,:,:,:) = tmp;
else
for n = 1:numel(input.inside)
indx = input.inside(n);
tmpdat = tmp{indx};
if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom'),
if n==1, siz1 = size(tmpdat,2); end
else
if n==1, siz1 = 1; end
end
tmpall{indx}(cnt+[1:siz1],:,:,:,:) = tmpdat;
if n==numel(input.inside), cnt = cnt + siz1; end
end
end
end
output = setfield(output, fnames{k}, tmpall);
newdimord = createdimord(output, fnames{k}, 1);
if ~isempty(newdimord)
output = setfield(output, [fnames{k},'dimord'], newdimord);
end
else
tmp = getfield(stuff, fnames{k});
siz = size(tmp);
if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom')
%pcc based mom is ori*rpttap
%tranpose to keep manageable
for kk = 1:numel(input.inside)
indx = input.inside(kk);
tmp{indx} = permute(tmp{indx}, [2 1 3]);
end
end
if siz(1) ~= npos && siz(2) ==npos,
tmp = transpose(tmp);
end
output = setfield(output, fnames{k}, tmp);
newdimord = createdimord(output, fnames{k});
if ~isempty(newdimord)
output = setfield(output, [fnames{k},'dimord'], newdimord);
end
end
end
if isfield(output, 'csdlabel')
output = setfield(output, 'orilabel', getfield(output, 'csdlabel'));
output = rmfield(output, 'csdlabel');
end
if isfield(output, 'leadfield')
% add dimord to leadfield as well. since the leadfield is not in
% the original .avg or .trial field it has not yet been taken care of
output.leadfielddimord = createdimord(output, 'leadfield');
end
if isfield(output, 'ori')
% convert cell-array ori into matrix
ori = nan(3,npos);
if ~islogical(output.inside)
try
ori(:,output.inside) = cat(2, output.ori{output.inside});
catch
%when oris are in wrong orientation (row rather than column)
for k = 1:numel(output.inside)
ori(:,output.inside(k)) = output.ori{output.inside(k)}';
end
end
else
try
ori(:,find(output.inside)) = cat(2, output.ori{find(output.inside)});
catch
tmpinside = find(output.inside);
for k = 1:numel(tmpinside)
ouri(:,tmpinside(k)) = output.ori{tmpinside(k)}';
end
end
end
output.ori = ori;
end
current = 'new';
elseif strcmp(current, 'new') && strcmp(type, 'old')
%go from new to old
error('not implemented yet');
end
if strcmp(current, 'new') && strcmp(haspow, 'yes'),
%----------------------------------------------
%convert mom into pow if requested and possible
convert = 0;
if isfield(output, 'mom') && size(output.mom{output.inside(1)},2)==1,
convert = 1;
else
warning('conversion from mom to pow is not possible, either because there is no mom in the data, or because the dimension of mom>1. in that case call ft_sourcedescriptives first with cfg.projectmom');
end
if isfield(output, 'cumtapcnt')
convert = 1 & convert;
else
warning('conversion from mom to pow will not be done, because cumtapcnt is missing');
end
if convert,
npos = size(output.pos,1);
nrpt = size(output.cumtapcnt,1);
tmpmom = cat(2,output.mom{output.inside});
tmppow = zeros(npos, nrpt);
tapcnt = [0;cumsum(output.cumtapcnt(:))];
for k = 1:nrpt
ntap = tapcnt(k+1)-tapcnt(k);
tmppow(output.inside,k) = sum(abs(tmpmom((tapcnt(k)+1):tapcnt(k+1),:)).^2,1)./ntap;
end
output.pow = tmppow;
output.powdimord = ['pos_rpt_freq'];
end
elseif strcmp(current, 'old') && strcmp(haspow, 'yes')
warning('construction of single trial power estimates is not implemented here using old style source representation');
end
%-------------------------------------------------------
function [dimord] = createdimord(output, fname, rptflag)
if nargin==2, rptflag = 0; end
tmp = output.(fname);
dimord = '';
dimnum = 1;
hasori = isfield(output, 'ori'); %if not, this is probably singleton and not relevant at the end
if iscell(tmp) && (size(output.pos,1)==size(tmp,dimnum) || size(output.pos,1)==size(tmp,2))
dimord = [dimord,'{pos}'];
dimnum = dimnum + 1;
elseif ~iscell(tmp) && size(output.pos,1)==size(tmp,dimnum)
dimord = [dimord,'pos'];
dimnum = dimnum + 1;
end
if isfield(output, 'inside')
if islogical(output.inside)
firstinside = find(output.inside, 1);
else
firstinside = output.inside(1);
end
end
switch fname
case 'cov'
if hasori, dimord = [dimord,'_ori_ori']; end;
case 'csd'
if hasori, dimord = [dimord,'_ori_ori']; end;
case 'csdlabel'
dimord = dimord;
case 'filter'
dimord = [dimord,'_ori_chan'];
case 'leadfield'
dimord = [dimord,'_chan_ori'];
case 'mom'
if isfield(output, 'cumtapcnt') && sum(output.cumtapcnt)==size(tmp{firstinside},1)
if hasori,
dimord = [dimord,'_rpttap_ori'];
else
dimord = [dimord,'_rpttap'];
end
elseif isfield(output, 'time') && numel(output.time)>1
if rptflag,
dimord = [dimord,'_rpt'];
dimnum = dimnum + 1;
end
if numel(output.time)==size(tmp{firstinside},dimnum)
dimord = [dimord,'_ori_time'];
end
end
if isfield(output, 'freq') && numel(output.freq)>1
dimord = [dimord,'_freq'];
end
case 'nai'
if isfield(output, 'freq') && numel(output.freq)==size(tmp,dimnum)
dimord = [dimord,'_freq'];
end
case 'noise'
if isfield(output, 'freq') && numel(output.freq)==size(tmp,dimnum)
dimord = [dimord,'_freq'];
end
case 'noisecsd'
dimord = [dimord,'_ori_ori'];
case 'noisecov'
dimord = [dimord,'_ori_ori'];
case 'ori'
dimord = '';
case {'pow' 'dspm'}
if isfield(output, 'cumtapcnt') && size(output.cumtapcnt,1)==size(tmp,dimnum)
dimord = [dimord,'_rpt'];
dimnum = dimnum + 1;
end
if isfield(output, 'freq') && numel(output.freq)>1 && numel(output.freq)==size(tmp,dimnum)
dimord = [dimord,'_freq'];
dimnum = dimnum+1;
end
if isfield(output, 'time') && numel(output.time)>1 && numel(output.time)==size(tmp,dimnum)
dimord = [dimord,'_time'];
dimnum = dimnum+1;
end
otherwise
warning('skipping unknown fieldname %s', fname);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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));
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 timelock = freq2timelock(freq)
% FREQ2TIMELOCK transform the frequency data into something
% on which the timelocked source reconstruction methods can
% perform their trick.
%
% After source reconstruction, you should use TIMELOCK2FREQ.
if isfield(freq, 'fourierspctrm')
fprintf('constructing real/imag data representation from single trial fourier representation\n');
% select the complex amplitude at the frequency of interest
cdim = find(strcmp(freq.dimord, 'chan')); % should be 2
fdim = find(strcmp(freq.dimord, 'freq')); % should be 3
fbin = nearest(freq.freq, cfg.frequency);
cfg.frequency = freq.freq(fbin);
if cdim==2 && fdim==3 && numel(freq.freq)==1
% other dimords are not supported, since they do not occur
spctrm = transpose(freq.fourierspctrm);
else
error('conversion of fourierspctrm failed');
end
% concatenate the real and imaginary part
avg = [real(spctrm) imag(spctrm)];
elseif isfield(freq, 'crsspctrm')
fprintf('constructing real/imag data representation from csd matrix\n');
% hmmm... I have no idea whether this is correct
tmpcfg.channel = freq.label;
tmpcfg.frequency = freq.freq;
% this subfunction also takes care of the channel selection
[Cf, Cr, Pr, Ntrials, dum] = prepare_freq_matrices(tmpcfg, freq);
if length(size(Cf))==3
% average the cross-spectrum over trials
Cf = squeeze(mean(Cf,1));
end
% reconstruct something that spans the same space as the fft of the data, hmmm...
[u, s, v] = svd(Cf);
spctrm = u * sqrt(s);
% concatenate the real and imaginary part
avg = [real(spctrm) imag(spctrm)];
else
error('unknown representation of frequency domain data');
end
timelock = [];
timelock.avg = avg;
timelock.label = cfg.channel;
timelock.time = 1:size(timelock.avg,2);
if isfield(freq, 'cfg'), timelock.cfg = freq.cfg; end
timelock.dimord = 'chan_time';
if isfield(freq, 'grad')
timelock.grad = freq.grad;
end
if isfield(freq, 'elec')
timelock.elec = freq.elec;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function timelock = comp2timelock(comp)
% COMP2TIMELOCK transform the independent components into something
% on which the timelocked source reconstruction methods can
% perform their trick.
% only convert, do not perform channel or component selection
timelock = [];
timelock.avg = comp.topo;
timelock.label = comp.topolabel;
timelock.time = 1:size(timelock.avg,2);
if isfield(comp, 'cfg'), timelock.cfg = comp.cfg; end
timelock.dimord = 'chan_time';
if isfield(comp, 'grad')
timelock.grad = comp.grad;
end
if isfield(comp, 'elec')
timelock.elec = comp.elec;
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(:)]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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
|
github
|
ZijingMao/baselineeegtest-master
|
read_yokogawa_data.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_yokogawa_data.m
| 11,038 |
utf_8
|
aa2c8a06c417ada7e9af353f2307443e
|
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.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: read_yokogawa_data.m 7123 2012-12-06 21:21:38Z roboos $
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
|
ZijingMao/baselineeegtest-master
|
decode_fif.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/decode_fif.m
| 6,033 |
utf_8
|
4edf09a0624e103cb761080e759c75ae
|
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.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: decode_fif.m 9030 2013-12-12 14:54:09Z roboos $
% 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
|
ZijingMao/baselineeegtest-master
|
read_biff.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_biff.m
| 5,857 |
utf_8
|
d71281c0e6be7868430597d71c166b5d
|
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.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: read_biff.m 7123 2012-12-06 21:21:38Z roboos $
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
|
ZijingMao/baselineeegtest-master
|
read_eeglabheader.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_eeglabheader.m
| 2,255 |
utf_8
|
fe4446f32b250441d57acff9ebe691a2
|
% 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.pnt(ind,1) = EEG.chanlocs(i).X;
header.elec.pnt(ind,2) = EEG.chanlocs(i).Y;
header.elec.pnt(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
|
ZijingMao/baselineeegtest-master
|
read_ctf_svl.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
read_erplabevent.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
read_yokogawa_header_new.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_yokogawa_header_new.m
| 8,959 |
utf_8
|
654f373c60405e9a27c40d65ab0147dd
|
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.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: read_yokogawa_header_new.m 7123 2012-12-06 21:21:38Z roboos $
% 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
|
ZijingMao/baselineeegtest-master
|
ft_datatype_raw.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/ft_datatype_raw.m
| 11,130 |
utf_8
|
ba366978335b30f2c90877f56f9b4519
|
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.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: ft_datatype_raw.m 10451 2015-06-10 22:00:07Z roboos $
% 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
|
ZijingMao/baselineeegtest-master
|
getdimsiz.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/getdimsiz.m
| 1,601 |
utf_8
|
bd44c3d3917f25521cd5c01d896ce113
|
function dimsiz = getdimsiz(data, field)
% GETDIMSIZ
%
% Use as
% dimsiz = getdimsiz(data, field)
%
% See also GETDIMORD
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)
cellsize = numel(x); % the number of elements in the cell-array
[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
|
ZijingMao/baselineeegtest-master
|
read_yokogawa_header.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_yokogawa_header.m
| 8,340 |
utf_8
|
c1392a52ad7bb86127e7a704c5abce9d
|
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.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: read_yokogawa_header.m 7123 2012-12-06 21:21:38Z roboos $
% 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
|
ZijingMao/baselineeegtest-master
|
encode_nifti1.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
avw_hdr_read.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/avw_hdr_read.m
| 16,668 |
utf_8
|
7cb599cd5b75177fed96189188822304
|
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: 7123 $ $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: 7123 $]';
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
|
ZijingMao/baselineeegtest-master
|
read_stl.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_stl.m
| 4,072 |
utf_8
|
f8ab163555c079a78445be6bc53cac39
|
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.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: read_stl.m 7123 2012-12-06 21:21:38Z roboos $
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 = 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
|
ZijingMao/baselineeegtest-master
|
read_itab_mhd.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
read_plexon_plx.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_plexon_plx.m
| 20,344 |
utf_8
|
dd04c6311c617f6001b0b3938dac087a
|
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.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: read_plexon_plx.m 8426 2013-08-26 09:48:07Z roboos $
% 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
|
ZijingMao/baselineeegtest-master
|
read_neurosim_evolution.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_neurosim_evolution.m
| 4,562 |
utf_8
|
e362fcc35f185715fe33ab48d889a0d9
|
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.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: read_neurosim_evolution.m 8776 2013-11-14 09:04:48Z roboos $
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
|
ZijingMao/baselineeegtest-master
|
read_eeglabevent.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_eeglabevent.m
| 3,698 |
utf_8
|
6acdf266f18a8591ec4ac4582b3ef28c
|
% 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
|
ZijingMao/baselineeegtest-master
|
read_bti_ascii.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_bti_ascii.m
| 2,300 |
utf_8
|
9144223206dfa96caa46025367ac07c8
|
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.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: read_bti_ascii.m 8313 2013-07-15 09:31:42Z jansch $
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
|
ZijingMao/baselineeegtest-master
|
openbdf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/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
|
ZijingMao/baselineeegtest-master
|
topoplot.m
|
.m
|
baselineeegtest-master/VisualizationFilters/External EEGLAB functions/topoplot.m
| 65,383 |
utf_8
|
0710c0959c950ba5e133559a71e28eb8
|
% topoplot() - plot a topographic map of a scalp data field in a 2-D circular view
% (looking down at the top of the head) using interpolation on a fine
% cartesian grid. Can also show specified channnel location(s), or return
% an interpolated value at an arbitrary scalp location (see 'noplot').
% By default, channel locations below head center (arc_length 0.5) are
% shown in a 'skirt' outside the cartoon head (see 'plotrad' and 'headrad'
% options below). Nose is at top of plot; left is left; right is right.
% Using option 'plotgrid', the plot may be one or more rectangular grids.
% Usage:
% >> topoplot(datavector, EEG.chanlocs); % plot a map using an EEG chanlocs structure
% >> topoplot(datavector, 'my_chan.locs'); % read a channel locations file and plot a map
% >> topoplot('example'); % give an example of an electrode location file
% >> [h grid_or_val plotrad_or_grid, xmesh, ymesh]= ...
% topoplot(datavector, chan_locs, 'Input1','Value1', ...);
% Required Inputs:
% datavector - single vector of channel values. Else, if a vector of selected subset
% (int) channel numbers -> mark their location(s) using 'style' 'blank'.
% chan_locs - name of an EEG electrode position file (>> topoplot example).
% Else, an EEG.chanlocs structure (>> help readlocs or >> topoplot example)
% Optional inputs:
% 'maplimits' - 'absmax' -> scale map colors to +/- the absolute-max (makes green 0);
% 'maxmin' -> scale colors to the data range (makes green mid-range);
% [lo.hi] -> use user-definined lo/hi limits
% {default: 'absmax'}
% 'style' - 'map' -> plot colored map only
% 'contour' -> plot contour lines only
% 'both' -> plot both colored map and contour lines
% 'fill' -> plot constant color between contour lines
% 'blank' -> plot electrode locations only {default: 'both'}
% 'electrodes' - 'on','off','labels','numbers','ptslabels','ptsnumbers'. To set the 'pts'
% marker,,see 'Plot detail options' below. {default: 'on' -> mark electrode
% locations with points ('.') unless more than 64 channels, then 'off'}.
% 'plotchans' - [vector] channel numbers (indices) to use in making the head plot.
% {default: [] -> plot all chans}
% 'chantype' - cell array of channel type(s) to plot. Will also accept a single quoted
% string type. Channel type for channel k is field EEG.chanlocs(k).type.
% If present, overrides 'plotchans' and also 'chaninfo' with field
% 'chantype'. Ex. 'EEG' or {'EEG','EOG'} {default: all, or 'plotchans' arg}
% 'plotgrid' - [channels] Plot channel data in one or more rectangular grids, as
% specified by [channels], a position matrix of channel numbers defining
% the topographic locations of the channels in the grid. Zero values are
% given the figure background color; negative integers, the color of the
% polarity-reversed channel values. Ex: >> figure; ...
% >> topoplot(values,'chanlocs','plotgrid',[11 12 0; 13 14 15]);
% % Plot a (2,3) grid of data values from channels 11-15 with one empty
% grid cell (top right) {default: no grid plot}
% 'nosedir' - ['+X'|'-X'|'+Y'|'-Y'] direction of nose {default: '+X'}
% 'chaninfo' - [struct] optional structure containing fields 'nosedir', 'plotrad'
% and/or 'chantype'. See these (separate) field definitions above, below.
% {default: nosedir +X, plotrad 0.5, all channels}
% 'plotrad' - [0.15<=float<=1.0] plotting radius = max channel arc_length to plot.
% See >> topoplot example. If plotrad > 0.5, chans with arc_length > 0.5
% (i.e. below ears-eyes) are plotted in a circular 'skirt' outside the
% cartoon head. See 'intrad' below. {default: max(max(chanlocs.radius),0.5);
% If the chanlocs structure includes a field chanlocs.plotrad, its value
% is used by default}.
% 'headrad' - [0.15<=float<=1.0] drawing radius (arc_length) for the cartoon head.
% NOTE: Only headrad = 0.5 is anatomically correct! 0 -> don't draw head;
% 'rim' -> show cartoon head at outer edge of the plot {default: 0.5}
% 'intrad' - [0.15<=float<=1.0] radius of the scalp map interpolation area (square or
% disk, see 'intsquare' below). Interpolate electrodes in this area and use
% this limit to define boundaries of the scalp map interpolated data matrix
% {default: max channel location radius}
% 'intsquare' - ['on'|'off'] 'on' -> Interpolate values at electrodes located in the whole
% square containing the (radius intrad) interpolation disk; 'off' -> Interpolate
% values from electrodes shown in the interpolation disk only {default: 'on'}.
% 'conv' - ['on'|'off'] Show map interpolation only out to the convext hull of
% the electrode locations to minimize extrapolation. {default: 'off'}
% 'noplot' - ['on'|'off'|[rad theta]] do not plot (but return interpolated data).
% Else, if [rad theta] are coordinates of a (possibly missing) channel,
% returns interpolated value for channel location. For more info,
% see >> topoplot 'example' {default: 'off'}
% 'verbose' - ['on'|'off'] comment on operations on command line {default: 'on'}.
%
% Plot detail options:
% 'drawaxis' - ['on'|'off'] draw axis on the top left corner.
% 'emarker' - Matlab marker char | {markerchar color size linewidth} char, else cell array
% specifying the electrode 'pts' marker. Ex: {'s','r',32,1} -> 32-point solid
% red square. {default: {'.','k',[],1} where marker size ([]) depends on the number
% of channels plotted}.
% 'emarker2' - {markchans}|{markchans marker color size linewidth} cell array specifying
% an alternate marker for specified 'plotchans'. Ex: {[3 17],'s','g'}
% {default: none, or if {markchans} only are specified, then {markchans,'o','r',10,1}}
% 'hcolor' - color of the cartoon head. Use 'hcolor','none' to plot no head. {default: 'k' = black}
% 'shading' - 'flat','interp' {default: 'flat'}
% 'numcontour' - number of contour lines {default: 6}
% 'contourvals' - values for contour {default: same as input values}
% 'pmask' - values for masking topoplot. Array of zeros and 1 of the same size as the input
% value array {default: []}
% 'color' - color of the contours {default: dark grey}
% 'whitebk ' - ('on'|'off') make the background color white (e.g., to print empty plotgrid channels)
% {default: 'off'}
% 'gridscale' - [int > 32] size (nrows) of interpolated scalp map data matrix {default: 67}
% 'colormap' - (n,3) any size colormap {default: existing colormap}
% 'circgrid' - [int > 100] number of elements (angles) in head and border circles {201}
%
% Dipole plotting options:
% 'dipole' - [xi yi xe ye ze] plot dipole on the top of the scalp map
% from coordinate (xi,yi) to coordinates (xe,ye,ze) (dipole head
% model has radius 1). If several rows, plot one dipole per row.
% Coordinates returned by dipplot() may be used. Can accept
% an EEG.dipfit.model structure (See >> help dipplot).
% Ex: ,'dipole',EEG.dipfit.model(17) % Plot dipole(s) for comp. 17.
% 'dipnorm' - ['on'|'off'] normalize dipole length {default: 'on'}.
% 'diporient' - [-1|1] invert dipole orientation {default: 1}.
% 'diplen' - [real] scale dipole length {default: 1}.
% 'dipscale' - [real] scale dipole size {default: 1}.
% 'dipsphere' - [real] size of the dipole sphere. {default: 85 mm}.
% 'dipcolor' - [color] dipole color as Matlab code code or [r g b] vector
% {default: 'k' = black}.
% Outputs:
% h - handle of the colored surface. If no surface is plotted,
% return "gca", the handle of the current plot.
% grid_or_val - [matrix] the interpolated data image (with off-head points = NaN).
% Else, single interpolated value at the specified 'noplot' arg channel
% location ([rad theta]), if any.
% plotrad_or_grid - IF grid image returned above, then the 'plotrad' radius of the grid.
% Else, the grid image
% xmesh, ymesh - x and y values of the returned grid (above)
%
% Chan_locs format:
% See >> topoplot 'example'
%
% Examples:
%
% To plot channel locations only:
% >> figure; topoplot([],EEG.chanlocs,'style','blank','electrodes','labelpoint','chaninfo',EEG.chaninfo);
%
% Notes: - To change the plot map masking ring to a new figure background color,
% >> set(findobj(gca,'type','patch'),'facecolor',get(gcf,'color'))
% - Topoplots may be rotated. From the commandline >> view([deg 90]) {default: [0 90])
%
% Authors: Andy Spydell, Colin Humphries, Arnaud Delorme & Scott Makeig
% CNL / Salk Institute, 8/1996-/10/2001; SCCN/INC/UCSD, Nov. 2001 -
%
% See also: timtopo(), envtopo()
% Deprecated options:
% 'shrink' - ['on'|'off'|'force'|factor] Deprecated. 'on' -> If max channel arc_length
% > 0.5, shrink electrode coordinates towards vertex to plot all channels
% by making max arc_length 0.5. 'force' -> Normalize arc_length
% so the channel max is 0.5. factor -> Apply a specified shrink
% factor (range (0,1) = shrink fraction). {default: 'off'}
% 'electcolor' {'k'} ... electrode marking details and their {defaults}.
% 'emarker' {'.'}|'emarkersize' {14}|'emarkersizemark' {40}|'efontsize' {var} -
% electrode marking details and their {defaults}.
% 'ecolor' - color of the electrode markers {default: 'k' = black}
% 'interplimits' - ['electrodes'|'head'] 'electrodes'-> interpolate the electrode grid;
% 'head'-> interpolate the whole disk {default: 'head'}.
% Unimplemented future options:
% Copyright (C) Colin Humphries & Scott Makeig, CNL / Salk Institute, Aug, 1996
%
% 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
% Topoplot Version 2.1
% Early development history:
% Begun by Andy Spydell and Scott Makeig, NHRC, 7-23-96
% 8-96 Revised by Colin Humphries, CNL / Salk Institute, La Jolla CA
% -changed surf command to imagesc (faster)
% -can now handle arbitrary scaling of electrode distances
% -can now handle non integer angles in chan_locs
% 4-4-97 Revised again by Colin Humphries, reformatted by SM
% -added parameters
% -changed chan_locs format
% 2-26-98 Revised by Colin
% -changed image back to surface command
% -added fill and blank styles
% -removed extra background colormap entry (now use any colormap)
% -added parameters for electrode colors and labels
% -now each topoplot axes use the caxis command again.
% -removed OUTPUT parameter
% 3-11-98 changed default emarkersize, improve help msg -sm
% 5-24-01 made default emarkersize vary with number of channels -sm
% 01-25-02 reformated help & license, added link -ad
% 03-15-02 added readlocs and the use of eloc input structure -ad
% 03-25-02 added 'labelpoint' options and allow Values=[] -ad &sm
% 03-25-02 added details to "Unknown parameter" warning -sm & ad
function [handle,Zi,grid,Xi,Yi] = topoplot(Values,loc_file,varargin)
%
%%%%%%%%%%%%%%%%%%%%%%%% Set defaults %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
icadefs % read defaults MAXTOPOPLOTCHANS and DEFAULT_ELOC and BACKCOLOR
if ~exist('BACKCOLOR') % if icadefs.m does not define BACKCOLOR
BACKCOLOR = [.93 .96 1]; % EEGLAB standard
end
whitebk = 'off'; % by default, make gridplot background color = EEGLAB screen background color
plotgrid = 'off';
plotchans = [];
noplot = 'off';
handle = [];
Zi = [];
chanval = NaN;
rmax = 0.5; % actual head radius - Don't change this!
INTERPLIMITS = 'head'; % head, electrodes
INTSQUARE = 'on'; % default, interpolate electrodes located though the whole square containing
% the plotting disk
default_intrad = 1; % indicator for (no) specified intrad
MAPLIMITS = 'absmax'; % absmax, maxmin, [values]
GRID_SCALE = 67; % plot map on a 67X67 grid
CIRCGRID = 201; % number of angles to use in drawing circles
AXHEADFAC = 1.3; % head to axes scaling factor
CONTOURNUM = 6; % number of contour levels to plot
STYLE = 'both'; % default 'style': both,straight,fill,contour,blank
HEADCOLOR = [0 0 0]; % default head color (black)
CCOLOR = [0.2 0.2 0.2]; % default contour color
ELECTRODES = []; % default 'electrodes': on|off|label - set below
MAXDEFAULTSHOWLOCS = 64;% if more channels than this, don't show electrode locations by default
EMARKER = '.'; % mark electrode locations with small disks
ECOLOR = [0 0 0]; % default electrode color = black
EMARKERSIZE = []; % default depends on number of electrodes, set in code
EMARKERLINEWIDTH = 1; % default edge linewidth for emarkers
EMARKERSIZE1CHAN = 20; % default selected channel location marker size
EMARKERCOLOR1CHAN = 'red'; % selected channel location marker color
EMARKER2CHANS = []; % mark subset of electrode locations with small disks
EMARKER2 = 'o'; % mark subset of electrode locations with small disks
EMARKER2COLOR = 'r'; % mark subset of electrode locations with small disks
EMARKERSIZE2 = 10; % default selected channel location marker size
EMARKER2LINEWIDTH = 1;
EFSIZE = get(0,'DefaultAxesFontSize'); % use current default fontsize for electrode labels
HLINEWIDTH = 1.7; % default linewidth for head, nose, ears
BLANKINGRINGWIDTH = .035;% width of the blanking ring
HEADRINGWIDTH = .007;% width of the cartoon head ring
SHADING = 'flat'; % default 'shading': flat|interp
shrinkfactor = []; % shrink mode (dprecated)
intrad = []; % default interpolation square is to outermost electrode (<=1.0)
plotrad = []; % plotting radius ([] = auto, based on outermost channel location)
headrad = []; % default plotting radius for cartoon head is 0.5
squeezefac = 1.0;
MINPLOTRAD = 0.15; % can't make a topoplot with smaller plotrad (contours fail)
VERBOSE = 'off';
MASKSURF = 'off';
CONVHULL = 'off'; % dont mask outside the electrodes convex hull
DRAWAXIS = 'off';
CHOOSECHANTYPE = 0;
ContourVals = Values;
PMASKFLAG = 0;
%%%%%% Dipole defaults %%%%%%%%%%%%
DIPOLE = [];
DIPNORM = 'on';
DIPSPHERE = 85;
DIPLEN = 1;
DIPSCALE = 1;
DIPORIENT = 1;
DIPCOLOR = [0 0 0];
NOSEDIR = '+X';
CHANINFO = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%%%%%%%%%%%%%%%%%%%%%%% Handle arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if nargin< 1
help topoplot;
return
end
% calling topoplot from Fieldtrip
% -------------------------------
fieldtrip = 0;
if nargin < 2, loc_file = []; end;
if isstruct(Values) | ~isstruct(loc_file), fieldtrip == 1; end;
if isstr(loc_file), if exist(loc_file) ~= 2, fieldtrip == 1; end; end;
if fieldtrip
disp('Calling topoplot from Fieldtrip');
dir1 = which('topoplot'); dir1 = fileparts(dir1);
dir2 = which('electrodenormalize'); dir2 = fileparts(dir2);
addpath(dir2);
try,
topoplot(Values, loc_file, varargin{:});
catch,
end;
addpath(dir1);
return;
end;
nargs = nargin;
if nargs == 1
if isstr(Values)
if any(strcmp(lower(Values),{'example','demo'}))
fprintf(['This is an example of an electrode location file,\n',...
'an ascii file consisting of the following four columns:\n',...
' channel_number degrees arc_length channel_name\n\n',...
'Example:\n',...
' 1 -18 .352 Fp1 \n',...
' 2 18 .352 Fp2 \n',...
' 5 -90 .181 C3 \n',...
' 6 90 .181 C4 \n',...
' 7 -90 .500 A1 \n',...
' 8 90 .500 A2 \n',...
' 9 -142 .231 P3 \n',...
'10 142 .231 P4 \n',...
'11 0 .181 Fz \n',...
'12 0 0 Cz \n',...
'13 180 .181 Pz \n\n',...
...
'In topoplot() coordinates, 0 deg. points to the nose, positive\n',...
'angles point to the right hemisphere, and negative to the left.\n',...
'The model head sphere has a circumference of 2; the vertex\n',...
'(Cz) has arc_length 0. Locations with arc_length > 0.5 are below\n',...
'head center and are plotted outside the head cartoon.\n',...
'Option plotrad controls how much of this lower-head "skirt" is shown.\n',...
'Option headrad controls if and where the cartoon head will be drawn.\n',...
'Option intrad controls how many channels will be included in the interpolation.\n',...
])
return
end
end
end
if nargs < 2
loc_file = DEFAULT_ELOC;
if ~exist(loc_file)
fprintf('default locations file "%s" not found - specify chan_locs in topoplot() call.\n',loc_file)
error(' ')
end
end
if isempty(loc_file)
loc_file = 0;
end
if isnumeric(loc_file) & loc_file == 0
loc_file = DEFAULT_ELOC;
end
if nargs > 2
if ~(round(nargs/2) == nargs/2)
error('Odd number of input arguments??')
end
for i = 1:2:length(varargin)
Param = varargin{i};
Value = varargin{i+1};
if ~isstr(Param)
error('Flag arguments must be strings')
end
Param = lower(Param);
switch Param
case 'conv'
CONVHULL = lower(Value);
if ~strcmp(CONVHULL,'on') & ~strcmp(CONVHULL,'off')
error('Value of ''conv'' must be ''on'' or ''off''.');
end
case 'colormap'
if size(Value,2)~=3
error('Colormap must be a n x 3 matrix')
end
colormap(Value)
case 'intsquare'
INTSQUARE = lower(Value);
if ~strcmp(INTSQUARE,'on') & ~strcmp(INTSQUARE,'off')
error('Value of ''intsquare'' must be ''on'' or ''off''.');
end
case {'interplimits','headlimits'}
if ~isstr(Value)
error('''interplimits'' value must be a string')
end
Value = lower(Value);
if ~strcmp(Value,'electrodes') & ~strcmp(Value,'head')
error('Incorrect value for interplimits')
end
INTERPLIMITS = Value;
case 'verbose'
VERBOSE = Value;
case 'nosedir'
NOSEDIR = Value;
if isempty(strmatch(lower(NOSEDIR), { '+x', '-x', '+y', '-y' }))
error('Invalid nose direction');
end;
case 'chaninfo'
CHANINFO = Value;
if isfield(CHANINFO, 'nosedir'), NOSEDIR = CHANINFO.nosedir; end;
if isfield(CHANINFO, 'shrink' ), shrinkfactor = CHANINFO.shrink; end;
if isfield(CHANINFO, 'plotrad') & isempty(plotrad), plotrad = CHANINFO.plotrad; end;
if isfield(CHANINFO, 'chantype')
chantype = CHANINFO.chantype;
if ischar(chantype), chantype = cellstr(chantype); end
CHOOSECHANTYPE = 1;
end
case 'chantype'
chantype = Value;
CHOOSECHANTYPE = 1;
if ischar(chantype), chantype = cellstr(chantype); end
if ~iscell(chantype), error('chantype must be cell array. e.g. {''EEG'', ''EOG''}'); end
case 'drawaxis'
DRAWAXIS = Value;
case 'maplimits'
MAPLIMITS = Value;
case 'masksurf'
MASKSURF = Value;
case 'circgrid'
CIRCGRID = Value;
if isstr(CIRCGRID) | CIRCGRID<100
error('''circgrid'' value must be an int > 100');
end
case 'style'
STYLE = lower(Value);
case 'numcontour'
CONTOURNUM = Value;
case 'electrodes'
ELECTRODES = lower(Value);
if strcmpi(ELECTRODES,'pointlabels') | strcmpi(ELECTRODES,'ptslabels') ...
| strcmpi(ELECTRODES,'labelspts') | strcmpi(ELECTRODES,'ptlabels') ...
| strcmpi(ELECTRODES,'labelpts')
ELECTRODES = 'labelpoint'; % backwards compatability
elseif strcmpi(ELECTRODES,'pointnumbers') | strcmpi(ELECTRODES,'ptsnumbers') ...
| strcmpi(ELECTRODES,'numberspts') | strcmpi(ELECTRODES,'ptnumbers') ...
| strcmpi(ELECTRODES,'numberpts') | strcmpi(ELECTRODES,'ptsnums') ...
| strcmpi(ELECTRODES,'numspts')
ELECTRODES = 'numpoint'; % backwards compatability
elseif strcmpi(ELECTRODES,'nums')
ELECTRODES = 'numbers'; % backwards compatability
elseif strcmpi(ELECTRODES,'pts')
ELECTRODES = 'on'; % backwards compatability
elseif ~strcmp(ELECTRODES,'off') ...
& ~strcmpi(ELECTRODES,'on') ...
& ~strcmp(ELECTRODES,'labels') ...
& ~strcmpi(ELECTRODES,'numbers') ...
& ~strcmpi(ELECTRODES,'labelpoint') ...
& ~strcmpi(ELECTRODES,'numpoint')
error('Unknown value for keyword ''electrodes''');
end
case 'dipole'
DIPOLE = Value;
case 'dipsphere'
DIPSPHERE = Value;
case 'dipnorm'
DIPNORM = Value;
case 'diplen'
DIPLEN = Value;
case 'dipscale'
DIPSCALE = Value;
case 'contourvals'
ContourVals = Value;
case 'pmask'
ContourVals = Value;
PMASKFLAG = 1;
case 'diporient'
DIPORIENT = Value;
case 'dipcolor'
DIPCOLOR = Value;
case 'emarker'
if ischar(Value)
EMARKER = Value;
elseif ~iscell(Value) | length(Value) > 4
error('''emarker'' argument must be a cell array {marker color size linewidth}')
else
EMARKER = Value{1};
end
if length(Value) > 1
ECOLOR = Value{2};
end
if length(Value) > 2
EMARKERSIZE2 = Value{3};
end
if length(Value) > 3
EMARKERLINEWIDTH = Value{4};
end
case 'emarker2'
if ~iscell(Value) | length(Value) > 5
error('''emarker2'' argument must be a cell array {chans marker color size linewidth}')
end
EMARKER2CHANS = abs(Value{1}); % ignore channels < 0
if length(Value) > 1
EMARKER2 = Value{2};
end
if length(Value) > 2
EMARKER2COLOR = Value{3};
end
if length(Value) > 3
EMARKERSIZE2 = Value{4};
end
if length(Value) > 4
EMARKER2LINEWIDTH = Value{5};
end
case 'shrink'
shrinkfactor = Value;
case 'intrad'
intrad = Value;
if isstr(intrad) | (intrad < MINPLOTRAD | intrad > 1)
error('intrad argument should be a number between 0.15 and 1.0');
end
case 'plotrad'
plotrad = Value;
if isstr(plotrad) | (plotrad < MINPLOTRAD | plotrad > 1)
error('plotrad argument should be a number between 0.15 and 1.0');
end
case 'headrad'
headrad = Value;
if isstr(headrad) & ( strcmpi(headrad,'off') | strcmpi(headrad,'none') )
headrad = 0; % undocumented 'no head' alternatives
end
if isempty(headrad) % [] -> none also
headrad = 0;
end
if ~isstr(headrad)
if ~(headrad==0) & (headrad < MINPLOTRAD | headrad>1)
error('bad value for headrad');
end
elseif ~strcmpi(headrad,'rim')
error('bad value for headrad');
end
case {'headcolor','hcolor'}
HEADCOLOR = Value;
case {'contourcolor','ccolor'}
CCOLOR = Value;
case {'electcolor','ecolor'}
ECOLOR = Value;
case {'emarkersize','emsize'}
EMARKERSIZE = Value;
case {'emarkersize1chan','emarkersizemark'}
EMARKERSIZE1CHAN= Value;
case {'efontsize','efsize'}
EFSIZE = Value;
case 'shading'
SHADING = lower(Value);
if ~any(strcmp(SHADING,{'flat','interp'}))
error('Invalid shading parameter')
end
case 'noplot'
noplot = Value;
if ~isstr(noplot)
if length(noplot) ~= 2
error('''noplot'' location should be [radius, angle]')
else
chanrad = noplot(1);
chantheta = noplot(2);
noplot = 'on';
end
end
case 'gridscale'
GRID_SCALE = Value;
if isstr(GRID_SCALE) | GRID_SCALE ~= round(GRID_SCALE) | GRID_SCALE < 32
error('''gridscale'' value must be integer > 32.');
end
case {'plotgrid','gridplot'}
plotgrid = 'on';
gridchans = Value;
case 'plotchans'
plotchans = Value(:);
if find(plotchans<=0)
error('''plotchans'' values must be > 0');
end
% if max(abs(plotchans))>max(Values) | max(abs(plotchans))>length(Values) -sm ???
case {'whitebk','whiteback','forprint'}
whitebk = Value;
otherwise
error(['Unknown input parameter ''' Param ''' ???'])
end
end
end
if strcmpi(whitebk, 'on')
BACKCOLOR = [ 1 1 1 ];
end;
cmap = colormap;
cmaplen = size(cmap,1);
if strcmp(STYLE,'blank') % else if Values holds numbers of channels to mark
if length(Values) < length(loc_file)
ContourVals = zeros(1,length(loc_file));
ContourVals(Values) = 1;
Values = ContourVals;
end;
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% test args for plotting an electrode grid %%%%%%%%%%%%%%%%%%%%%%
%
if strcmp(plotgrid,'on')
STYLE = 'grid';
gchans = sort(find(abs(gridchans(:))>0));
% if setdiff(gchans,unique(gchans))
% fprintf('topoplot() warning: ''plotgrid'' channel matrix has duplicate channels\n');
% end
if ~isempty(plotchans)
if intersect(gchans,abs(plotchans))
fprintf('topoplot() warning: ''plotgrid'' and ''plotchans'' have channels in common\n');
end
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% misc arg tests %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(ELECTRODES) % if electrode labeling not specified
if length(Values) > MAXDEFAULTSHOWLOCS % if more channels than default max
ELECTRODES = 'off'; % don't show electrodes
else % else if fewer chans,
ELECTRODES = 'on'; % do
end
end
if isempty(Values)
STYLE = 'blank';
end
[r,c] = size(Values);
if r>1 & c>1,
error('input data must be a single vector');
end
Values = Values(:); % make Values a column vector
ContourVals = ContourVals(:); % values for contour
if ~isempty(intrad) & ~isempty(plotrad) & intrad < plotrad
error('intrad must be >= plotrad');
end
if ~strcmpi(STYLE,'grid') % if not plot grid only
%
%%%%%%%%%%%%%%%%%%%% Read the channel location information %%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(loc_file)
[tmpeloc labels Th Rd indices] = readlocs( loc_file);
elseif isstruct(loc_file) % a locs struct
[tmpeloc labels Th Rd indices] = readlocs( loc_file );
% Note: Th and Rd correspond to indices channels-with-coordinates only
else
error('loc_file must be a EEG.locs struct or locs filename');
end
Th = pi/180*Th; % convert degrees to radians
allchansind = 1:length(Th);
if ~isempty(plotchans)
if max(plotchans) > length(Th)
error('''plotchans'' values must be <= max channel index');
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% channels to plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(plotchans)
plotchans = intersect(plotchans, indices);
end;
if ~isempty(Values) & ~strcmpi( STYLE, 'blank') & isempty(plotchans)
plotchans = indices;
end
if isempty(plotchans) & strcmpi( STYLE, 'blank')
plotchans = indices;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% filter for channel type(s), if specified %%%%%%%%%%%%%%%%%%%%%
%
if CHOOSECHANTYPE,
newplotchans = eeg_chantype(loc_file,chantype);
plotchans = intersect(newplotchans, plotchans);
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% filter channels used for components %%%%%%%%%%%%%%%%%%%%%
%
if isfield(CHANINFO, 'icachansind') & ~isempty(Values) & length(Values) ~= length(tmpeloc)
% test if ICA component
% ---------------------
if length(CHANINFO.icachansind) == length(Values)
% if only a subset of channels are to be plotted
% and ICA components also use a subject of channel
% we must find the new indices for these channels
plotchans = intersect(CHANINFO.icachansind, plotchans);
tmpvals = zeros(1, length(tmpeloc));
tmpvals(CHANINFO.icachansind) = Values;
Values = tmpvals;
tmpvals = zeros(1, length(tmpeloc));
tmpvals(CHANINFO.icachansind) = ContourVals;
ContourVals = tmpvals;
end;
end;
%
%%%%%%%%%%%%%%%%%%% last channel is reference? %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if length(tmpeloc) == length(Values) + 1 % remove last channel if necessary
% (common reference channel)
if plotchans(end) == length(tmpeloc)
plotchans(end) = [];
end;
end;
%
%%%%%%%%%%%%%%%%%%% remove infinite and NaN values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if length(Values) > 1
inds = union(find(isnan(Values)), find(isinf(Values))); % NaN and Inf values
plotchans = setdiff(plotchans, inds);
end;
if strcmp(plotgrid,'on')
plotchans = setxor(plotchans,gchans); % remove grid chans from head plotchans
end
[x,y] = pol2cart(Th,Rd); % transform electrode locations from polar to cartesian coordinates
plotchans = abs(plotchans); % reverse indicated channel polarities
allchansind = allchansind(plotchans);
Th = Th(plotchans);
Rd = Rd(plotchans);
x = x(plotchans);
y = y(plotchans);
labels = labels(plotchans); % remove labels for electrodes without locations
labels = strvcat(labels); % make a label string matrix
if ~isempty(Values) & length(Values) > 1
Values = Values(plotchans);
ContourVals = ContourVals(plotchans);
end;
%
%%%%%%%%%%%%%%%%%% Read plotting radius from chanlocs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(plotrad) & isfield(tmpeloc, 'plotrad'),
plotrad = tmpeloc(1).plotrad;
if isstr(plotrad) % plotrad shouldn't be a string
plotrad = str2num(plotrad) % just checking
end
if plotrad < MINPLOTRAD | plotrad > 1.0
fprintf('Bad value (%g) for plotrad.\n',plotrad);
error(' ');
end
if strcmpi(VERBOSE,'on') & ~isempty(plotrad)
fprintf('Plotting radius plotrad (%g) set from EEG.chanlocs.\n',plotrad);
end
end;
if isempty(plotrad)
plotrad = min(1.0,max(Rd)*1.02); % default: just outside the outermost electrode location
plotrad = max(plotrad,0.5); % default: plot out to the 0.5 head boundary
end % don't plot channels with Rd > 1 (below head)
if isempty(intrad)
default_intrad = 1; % indicator for (no) specified intrad
intrad = min(1.0,max(Rd)*1.02); % default: just outside the outermost electrode location
else
default_intrad = 0; % indicator for (no) specified intrad
if plotrad > intrad
plotrad = intrad;
end
end % don't interpolate channels with Rd > 1 (below head)
if isstr(plotrad) | plotrad < MINPLOTRAD | plotrad > 1.0
error('plotrad must be between 0.15 and 1.0');
end
%
%%%%%%%%%%%%%%%%%%%%%%% Set radius of head cartoon %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isempty(headrad) % never set -> defaults
if plotrad >= rmax
headrad = rmax; % (anatomically correct)
else % if plotrad < rmax
headrad = 0; % don't plot head
if strcmpi(VERBOSE, 'on')
fprintf('topoplot(): not plotting cartoon head since plotrad (%5.4g) < 0.5\n',...
plotrad);
end
end
elseif strcmpi(headrad,'rim') % force plotting at rim of map
headrad = plotrad;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Shrink mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(shrinkfactor) | isfield(tmpeloc, 'shrink'),
if isempty(shrinkfactor) & isfield(tmpeloc, 'shrink'),
shrinkfactor = tmpeloc(1).shrink;
if strcmpi(VERBOSE,'on')
if isstr(shrinkfactor)
fprintf('Automatically shrinking coordinates to lie above the head perimter.\n');
else
fprintf('Automatically shrinking coordinates by %3.2f\n', shrinkfactor);
end;
end
end;
if isstr(shrinkfactor)
if strcmpi(shrinkfactor, 'on') | strcmpi(shrinkfactor, 'force') | strcmpi(shrinkfactor, 'auto')
if abs(headrad-rmax) > 1e-2
fprintf(' NOTE -> the head cartoon will NOT accurately indicate the actual electrode locations\n');
end
if strcmpi(VERBOSE,'on')
fprintf(' Shrink flag -> plotting cartoon head at plotrad\n');
end
headrad = plotrad; % plot head around outer electrodes, no matter if 0.5 or not
end
else % apply shrinkfactor
plotrad = rmax/(1-shrinkfactor);
headrad = plotrad; % make deprecated 'shrink' mode plot
if strcmpi(VERBOSE,'on')
fprintf(' %g%% shrink applied.');
if abs(headrad-rmax) > 1e-2
fprintf(' Warning: With this "shrink" setting, the cartoon head will NOT be anatomically correct.\n');
else
fprintf('\n');
end
end
end
end; % if shrink
%
%%%%%%%%%%%%%%%%% Issue warning if headrad ~= rmax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if headrad ~= 0.5 & strcmpi(VERBOSE, 'on')
fprintf(' NB: Plotting map using ''plotrad'' %-4.3g,',plotrad);
fprintf( ' ''headrad'' %-4.3g\n',headrad);
fprintf('Warning: The plotting radius of the cartoon head is NOT anatomically correct (0.5).\n')
end
%
%%%%%%%%%%%%%%%%%%%%% Find plotting channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
pltchans = find(Rd <= plotrad); % plot channels inside plotting circle
if strcmpi(INTSQUARE,'on') % interpolate channels in the radius intrad square
intchans = find(x <= intrad & y <= intrad); % interpolate and plot channels inside interpolation square
else
intchans = find(Rd <= intrad); % interpolate channels in the radius intrad circle only
end
%
%%%%%%%%%%%%%%%%%%%%% Eliminate channels not plotted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
allx = x;
ally = y;
intchans; % interpolate using only the 'intchans' channels
pltchans; % plot using only indicated 'plotchans' channels
if length(pltchans) < length(Rd) & strcmpi(VERBOSE, 'on')
fprintf('Interpolating %d and plotting %d of the %d scalp electrodes.\n', ...
length(intchans),length(pltchans),length(Rd));
end;
% fprintf('topoplot(): plotting %d channels\n',length(pltchans));
if ~isempty(EMARKER2CHANS)
if strcmpi(STYLE,'blank')
error('emarker2 not defined for style ''blank'' - use marking channel numbers in place of data');
else % mark1chans and mark2chans are subsets of pltchans for markers 1 and 2
[tmp1 mark1chans tmp2] = setxor(pltchans,EMARKER2CHANS);
[tmp3 tmp4 mark2chans] = intersect(EMARKER2CHANS,pltchans);
end
end
if ~isempty(Values)
if length(Values) == length(Th) % if as many map Values as channel locs
intValues = Values(intchans);
intContourVals = ContourVals(intchans);
Values = Values(pltchans);
ContourVals = ContourVals(pltchans);
end;
end; % now channel parameters and values all refer to plotting channels only
allchansind = allchansind(pltchans);
intTh = Th(intchans); % eliminate channels outside the interpolation area
intRd = Rd(intchans);
intx = x(intchans);
inty = y(intchans);
Th = Th(pltchans); % eliminate channels outside the plotting area
Rd = Rd(pltchans);
x = x(pltchans);
y = y(pltchans);
labels= labels(pltchans,:);
%
%%%%%%%%%%%%%%% Squeeze channel locations to <= rmax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
squeezefac = rmax/plotrad;
intRd = intRd*squeezefac; % squeeze electrode arc_lengths towards the vertex
Rd = Rd*squeezefac; % squeeze electrode arc_lengths towards the vertex
% to plot all inside the head cartoon
intx = intx*squeezefac;
inty = inty*squeezefac;
x = x*squeezefac;
y = y*squeezefac;
allx = allx*squeezefac;
ally = ally*squeezefac;
% Note: Now outermost channel will be plotted just inside rmax
else % if strcmpi(STYLE,'grid')
intx = rmax; inty=rmax;
end % if ~strcmpi(STYLE,'grid')
%
%%%%%%%%%%%%%%%% rotate channels based on chaninfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(lower(NOSEDIR), '+x')
rotate = 0;
else
if strcmpi(lower(NOSEDIR), '+y')
rotate = 3*pi/2;
elseif strcmpi(lower(NOSEDIR), '-x')
rotate = pi;
else rotate = pi/2;
end;
allcoords = (inty + intx*sqrt(-1))*exp(sqrt(-1)*rotate);
intx = imag(allcoords);
inty = real(allcoords);
allcoords = (ally + allx*sqrt(-1))*exp(sqrt(-1)*rotate);
allx = imag(allcoords);
ally = real(allcoords);
allcoords = (y + x*sqrt(-1))*exp(sqrt(-1)*rotate);
x = imag(allcoords);
y = real(allcoords);
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Make the plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~strcmpi(STYLE,'blank') % if draw interpolated scalp map
if ~strcmpi(STYLE,'grid') % not a rectangular channel grid
%
%%%%%%%%%%%%%%%% Find limits for interpolation %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if default_intrad % if no specified intrad
if strcmpi(INTERPLIMITS,'head') % intrad is 'head'
xmin = min(-rmax,min(intx)); xmax = max(rmax,max(intx));
ymin = min(-rmax,min(inty)); ymax = max(rmax,max(inty));
else % INTERPLIMITS = rectangle containing electrodes -- DEPRECATED OPTION!
xmin = max(-rmax,min(intx)); xmax = min(rmax,max(intx));
ymin = max(-rmax,min(inty)); ymax = min(rmax,max(inty));
end
else % some other intrad specified
xmin = -intrad*squeezefac; xmax = intrad*squeezefac; % use the specified intrad value
ymin = -intrad*squeezefac; ymax = intrad*squeezefac;
end
%
%%%%%%%%%%%%%%%%%%%%%%% Interpolate scalp map data %%%%%%%%%%%%%%%%%%%%%%%%
%
xi = linspace(xmin,xmax,GRID_SCALE); % x-axis description (row vector)
yi = linspace(ymin,ymax,GRID_SCALE); % y-axis description (row vector)
try
[Xi,Yi,Zi] = griddata(inty,intx,intValues,yi',xi,'invdist'); % interpolate data
[Xi,Yi,ZiC] = griddata(inty,intx,intContourVals,yi',xi,'invdist'); % interpolate data
catch,
[Xi,Yi,Zi] = griddata(inty,intx,intValues',yi,xi'); % interpolate data (Octave)
[Xi,Yi,ZiC] = griddata(inty,intx,intContourVals',yi,xi'); % interpolate data
end;
%
%%%%%%%%%%%%%%%%%%%%%%% Mask out data outside the head %%%%%%%%%%%%%%%%%%%%%
%
mask = (sqrt(Xi.^2 + Yi.^2) <= rmax); % mask outside the plotting circle
ii = find(mask == 0);
Zi(ii) = NaN; % mask non-plotting voxels with NaNs
ZiC(ii) = NaN; % mask non-plotting voxels with NaNs
grid = plotrad; % unless 'noplot', then 3rd output arg is plotrad
%
%%%%%%%%%% Return interpolated value at designated scalp location %%%%%%%%%%
%
if exist('chanrad') % optional first argument to 'noplot'
chantheta = (chantheta/360)*2*pi;
chancoords = round(ceil(GRID_SCALE/2)+GRID_SCALE/2*2*chanrad*[cos(-chantheta),...
-sin(-chantheta)]);
if chancoords(1)<1 ...
| chancoords(1) > GRID_SCALE ...
| chancoords(2)<1 ...
| chancoords(2)>GRID_SCALE
error('designated ''noplot'' channel out of bounds')
else
chanval = Zi(chancoords(1),chancoords(2));
grid = Zi;
Zi = chanval; % return interpolated value instead of Zi
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Return interpolated image only %%%%%%%%%%%%%%%%%
%
if strcmpi(noplot, 'on')
if strcmpi(VERBOSE,'on')
fprintf('topoplot(): no plot requested.\n')
end
return;
end
%
%%%%%%%%%%%%%%%%%%%%%%% Calculate colormap limits %%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(MAPLIMITS)
if strcmp(MAPLIMITS,'absmax')
amax = max(max(abs(Zi)));
amin = -amax;
elseif strcmp(MAPLIMITS,'maxmin') | strcmp(MAPLIMITS,'minmax')
amin = min(min(Zi));
amax = max(max(Zi));
else
error('unknown ''maplimits'' value.');
end
elseif length(MAPLIMITS) == 2
amin = MAPLIMITS(1);
amax = MAPLIMITS(2);
else
error('unknown ''maplimits'' value');
end
delta = xi(2)-xi(1); % length of grid entry
end % if ~strcmpi(STYLE,'grid')
%
%%%%%%%%%%%%%%%%%%%%%%%%%% Scale the axes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%cla % clear current axis
hold on
h = gca; % uses current axes
% instead of default larger AXHEADFAC
if squeezefac<0.92 & plotrad-headrad > 0.05 % (size of head in axes)
AXHEADFAC = 1.05; % do not leave room for external ears if head cartoon
% shrunk enough by the 'skirt' option
end
set(gca,'Xlim',[-rmax rmax]*AXHEADFAC,'Ylim',[-rmax rmax]*AXHEADFAC);
% specify size of head axes in gca
unsh = (GRID_SCALE+1)/GRID_SCALE; % un-shrink the effects of 'interp' SHADING
%
%%%%%%%%%%%%%%%%%%%%%%%% Plot grid only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(STYLE,'grid') % plot grid only
%
% The goal below is to make the grid cells square - not yet achieved in all cases? -sm
%
g1 = size(gridchans,1);
g2 = size(gridchans,2);
gmax = max([g1 g2]);
Xi = linspace(-rmax*g2/gmax,rmax*g2/gmax,g1+1);
Xi = Xi+rmax/g1; Xi = Xi(1:end-1);
Yi = linspace(-rmax*g1/gmax,rmax*g1/gmax,g2+1);
Yi = Yi+rmax/g2; Yi = Yi(1:end-1); Yi = Yi(end:-1:1); % by trial and error!
%
%%%%%%%%%%% collect the gridchans values %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
gridvalues = zeros(size(gridchans));
for j=1:size(gridchans,1)
for k=1:size(gridchans,2)
gc = gridchans(j,k);
if gc > 0
gridvalues(j,k) = Values(gc);
elseif gc < 0
gridvalues(j,k) = -Values(gc);
else
gridvalues(j,k) = nan; % not-a-number = no value
end
end
end
%
%%%%%%%%%%% reset color limits for grid plot %%%%%%%%%%%%%%%%%%%%%%%%%
%
if isstr(MAPLIMITS)
if strcmp(MAPLIMITS,'maxmin') | strcmp(MAPLIMITS,'minmax')
amin = min(min(gridvalues(~isnan(gridvalues))));
amax = max(max(gridvalues(~isnan(gridvalues))));
elseif strcmp(MAPLIMITS,'absmax')
% 11/21/2005 Toby edit
% This should now work as specified. Before it only crashed (using
% "plotgrid" and "maplimits>absmax" options).
amax = max(max(abs(gridvalues(~isnan(gridvalues)))));
amin = -amax;
%amin = -max(max(abs([amin amax])));
%amax = max(max(abs([amin amax])));
else
error('unknown ''maplimits'' value');
end
elseif length(MAPLIMITS) == 2
amin = MAPLIMITS(1);
amax = MAPLIMITS(2);
else
error('unknown ''maplimits'' value');
end
%
%%%%%%%%%% explicitly compute grid colors, allowing BACKCOLOR %%%%%%
%
gridvalues = 1+floor(cmaplen*(gridvalues-amin)/(amax-amin));
gridvalues(find(gridvalues == cmaplen+1)) = cmaplen;
gridcolors = zeros([size(gridvalues),3]);
for j=1:size(gridchans,1)
for k=1:size(gridchans,2)
if ~isnan(gridvalues(j,k))
gridcolors(j,k,:) = cmap(gridvalues(j,k),:);
else
if strcmpi(whitebk,'off')
gridcolors(j,k,:) = BACKCOLOR; % gridchans == 0 -> background color
% This allows the plot to show 'space' between separate sub-grids or strips
else % 'on'
gridcolors(j,k,:) = [1 1 1]; BACKCOLOR; % gridchans == 0 -> white for printing
end
end
end
end
%
%%%%%%%%%% draw the gridplot image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
handle=imagesc(Xi,Yi,gridcolors); % plot grid with explicit colors
axis square
%
%%%%%%%%%%%%%%%%%%%%%%%% Plot map contours only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'contour') % plot surface contours only
[cls chs] = contour(Xi,Yi,ZiC,CONTOURNUM,'k');
% for h=chs, set(h,'color',CCOLOR); end
%
%%%%%%%%%%%%%%%%%%%%%%%% Else plot map and contours %%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'both') % plot interpolated surface and surface contours
if strcmp(SHADING,'interp')
tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi))-0.1,Zi,...
'EdgeColor','none','FaceColor',SHADING);
else % SHADING == 'flat'
tmph = surface(Xi-delta/2,Yi-delta/2,zeros(size(Zi))-0.1,Zi,...
'EdgeColor','none','FaceColor',SHADING);
end
if strcmpi(MASKSURF, 'on')
set(tmph, 'visible', 'off');
handle = tmph;
end;
warning off;
if ~PMASKFLAG
[cls chs] = contour(Xi,Yi,ZiC,CONTOURNUM,'k');
else
ZiC(find(ZiC > 0.5 )) = NaN;
[cls chs] = contourf(Xi,Yi,ZiC,0,'k');
subh = get(chs, 'children');
for indsubh = 1:length(subh)
numfaces = size(get(subh(indsubh), 'XData'),1);
set(subh(indsubh), 'FaceVertexCData', ones(numfaces,3), 'Cdatamapping', 'direct', 'facealpha', 0.5, 'linewidth', 2);
end;
end;
for h=chs, set(h,'color',CCOLOR); end
warning on;
%
%%%%%%%%%%%%%%%%%%%%%%%% Else plot map only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'straight') | strcmp(STYLE,'map') % 'straight' was former arg
if strcmp(SHADING,'interp') % 'interp' mode is shifted somehow... but how?
tmph = surface(Xi*unsh,Yi*unsh,zeros(size(Zi)),Zi,'EdgeColor','none',...
'FaceColor',SHADING);
else
tmph = surface(Xi-delta/2,Yi-delta/2,zeros(size(Zi)),Zi,'EdgeColor','none',...
'FaceColor',SHADING);
end
if strcmpi(MASKSURF, 'on')
set(tmph, 'visible', 'off');
handle = tmph;
end;
%
%%%%%%%%%%%%%%%%%% Else fill contours with uniform colors %%%%%%%%%%%%%%%%%%
%
elseif strcmp(STYLE,'fill')
[cls chs] = contourf(Xi,Yi,Zi,CONTOURNUM,'k');
% for h=chs, set(h,'color',CCOLOR); end
% <- 'not line objects.' Why does 'both' work above???
else
error('Invalid style')
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Set color axis %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
caxis([amin amax]); % set coloraxis
else % if STYLE 'blank'
%
%%%%%%%%%%%%%%%%%%%%%%% Draw blank head %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(noplot, 'on')
if strcmpi(VERBOSE,'on')
fprintf('topoplot(): no plot requested.\n')
end
return;
end
%cla
hold on
set(gca,'Xlim',[-rmax rmax]*AXHEADFAC,'Ylim',[-rmax rmax]*AXHEADFAC)
% pos = get(gca,'position');
% fprintf('Current axes size %g,%g\n',pos(3),pos(4));
if strcmp(ELECTRODES,'labelpoint') | strcmp(ELECTRODES,'numpoint')
text(-0.6,-0.6, ...
[ int2str(length(Rd)) ' of ' int2str(length(tmpeloc)) ' electrode locations shown']);
text(-0.6,-0.7, [ 'Click on electrodes to toggle name/number']);
tl = title('Channel locations');
set(tl, 'fontweight', 'bold');
end;
end % STYLE 'blank'
if exist('handle') ~= 1
handle = gca;
end;
if ~strcmpi(STYLE,'grid') % if not plot grid only
%
%%%%%%%%%%%%%%%%%%% Plot filled ring to mask jagged grid boundary %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
hwidth = HEADRINGWIDTH; % width of head ring
hin = squeezefac*headrad*(1- hwidth/2); % inner head ring radius
if strcmp(SHADING,'interp')
rwidth = BLANKINGRINGWIDTH*1.3; % width of blanking outer ring
else
rwidth = BLANKINGRINGWIDTH; % width of blanking outer ring
end
rin = rmax*(1-rwidth/2); % inner ring radius
if hin>rin
rin = hin; % dont blank inside the head ring
end
if strcmp(CONVHULL,'on') %%%%%%%%% mask outside the convex hull of the electrodes %%%%%%%%%
cnv = convhull(allx,ally);
cnvfac = round(CIRCGRID/length(cnv)); % spline interpolate the convex hull
if cnvfac < 1, cnvfac=1; end;
CIRCGRID = cnvfac*length(cnv);
startangle = atan2(allx(cnv(1)),ally(cnv(1)));
circ = linspace(0+startangle,2*pi+startangle,CIRCGRID);
rx = sin(circ);
ry = cos(circ);
allx = allx(:)'; % make x (elec locations; + to nose) a row vector
ally = ally(:)'; % make y (elec locations, + to r? ear) a row vector
erad = sqrt(allx(cnv).^2+ally(cnv).^2); % convert to polar coordinates
eang = atan2(allx(cnv),ally(cnv));
eang = unwrap(eang);
eradi =spline(linspace(0,1,3*length(cnv)), [erad erad erad], ...
linspace(0,1,3*length(cnv)*cnvfac));
eangi =spline(linspace(0,1,3*length(cnv)), [eang+2*pi eang eang-2*pi], ...
linspace(0,1,3*length(cnv)*cnvfac));
xx = eradi.*sin(eangi); % convert back to rect coordinates
yy = eradi.*cos(eangi);
yy = yy(CIRCGRID+1:2*CIRCGRID);
xx = xx(CIRCGRID+1:2*CIRCGRID);
eangi = eangi(CIRCGRID+1:2*CIRCGRID);
eradi = eradi(CIRCGRID+1:2*CIRCGRID);
xx = xx*1.02; yy = yy*1.02; % extend spline outside electrode marks
splrad = sqrt(xx.^2+yy.^2); % arc radius of spline points (yy,xx)
oob = find(splrad >= rin); % enforce an upper bound on xx,yy
xx(oob) = rin*xx(oob)./splrad(oob); % max radius = rin
yy(oob) = rin*yy(oob)./splrad(oob); % max radius = rin
splrad = sqrt(xx.^2+yy.^2); % arc radius of spline points (yy,xx)
oob = find(splrad < hin); % don't let splrad be inside the head cartoon
xx(oob) = hin*xx(oob)./splrad(oob); % min radius = hin
yy(oob) = hin*yy(oob)./splrad(oob); % min radius = hin
ringy = [[ry(:)' ry(1) ]*(rin+rwidth) yy yy(1)];
ringx = [[rx(:)' rx(1) ]*(rin+rwidth) xx xx(1)];
ringh2= patch(ringy,ringx,ones(size(ringy)),BACKCOLOR,'edgecolor','none'); hold on
% plot(ry*rmax,rx*rmax,'b') % debugging line
else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% mask the jagged border around rmax %%%%%%%%%%%%%%%5%%%%%%
circ = linspace(0,2*pi,CIRCGRID);
rx = sin(circ);
ry = cos(circ);
ringx = [[rx(:)' rx(1) ]*(rin+rwidth) [rx(:)' rx(1)]*rin];
ringy = [[ry(:)' ry(1) ]*(rin+rwidth) [ry(:)' ry(1)]*rin];
if ~strcmpi(STYLE,'blank')
ringh= patch(ringx,ringy,0.01*ones(size(ringx)),BACKCOLOR,'edgecolor','none'); hold on
end
% plot(ry*rmax,rx*rmax,'b') % debugging line
end
%f1= fill(rin*[rx rX],rin*[ry rY],BACKCOLOR,'edgecolor',BACKCOLOR); hold on
%f2= fill(rin*[rx rX*(1+rwidth)],rin*[ry rY*(1+rwidth)],BACKCOLOR,'edgecolor',BACKCOLOR);
% Former line-style border smoothing - width did not scale with plot
% brdr=plot(1.015*cos(circ).*rmax,1.015*sin(circ).*rmax,... % old line-based method
% 'color',HEADCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % plot skirt outline
% set(brdr,'color',BACKCOLOR,'linewidth',HLINEWIDTH + 4); % hide the disk edge jaggies
%
%%%%%%%%%%%%%%%%%%%%%%%%% Plot cartoon head, ears, nose %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if headrad > 0 % if cartoon head to be plotted
%
%%%%%%%%%%%%%%%%%%% Plot head outline %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
headx = [[rx(:)' rx(1) ]*(hin+hwidth) [rx(:)' rx(1)]*hin];
heady = [[ry(:)' ry(1) ]*(hin+hwidth) [ry(:)' ry(1)]*hin];
if ~isstr(HEADCOLOR) | ~strcmpi(HEADCOLOR,'none')
ringh= patch(headx,heady,ones(size(headx)),HEADCOLOR,'edgecolor',HEADCOLOR); hold on
end
% rx = sin(circ); rX = rx(end:-1:1);
% ry = cos(circ); rY = ry(end:-1:1);
% for k=2:2:CIRCGRID
% rx(k) = rx(k)*(1+hwidth);
% ry(k) = ry(k)*(1+hwidth);
% end
% f3= fill(hin*[rx rX],hin*[ry rY],HEADCOLOR,'edgecolor',HEADCOLOR); hold on
% f4= fill(hin*[rx rX*(1+hwidth)],hin*[ry rY*(1+hwidth)],HEADCOLOR,'edgecolor',HEADCOLOR);
% Former line-style head
% plot(cos(circ).*squeezefac*headrad,sin(circ).*squeezefac*headrad,...
% 'color',HEADCOLOR,'Linestyle','-','LineWidth',HLINEWIDTH); % plot head outline
%
%%%%%%%%%%%%%%%%%%% Plot ears and nose %%%%%%%%%%%%%%%%%%%%%%%%%%%
%
base = rmax-.0046;
basex = 0.18*rmax; % nose width
tip = 1.15*rmax;
tiphw = .04*rmax; % nose tip half width
tipr = .01*rmax; % nose tip rounding
q = .04; % ear lengthening
EarX = [.497-.005 .510 .518 .5299 .5419 .54 .547 .532 .510 .489-.005]; % rmax = 0.5
EarY = [q+.0555 q+.0775 q+.0783 q+.0746 q+.0555 -.0055 -.0932 -.1313 -.1384 -.1199];
sf = headrad/plotrad; % squeeze the model ears and nose
% by this factor
if ~isstr(HEADCOLOR) | ~strcmpi(HEADCOLOR,'none')
plot3([basex;tiphw;0;-tiphw;-basex]*sf,[base;tip-tipr;tip;tip-tipr;base]*sf,...
2*ones(size([basex;tiphw;0;-tiphw;-basex])),...
'Color',HEADCOLOR,'LineWidth',HLINEWIDTH); % plot nose
plot3(EarX*sf,EarY*sf,2*ones(size(EarX)),'color',HEADCOLOR,'LineWidth',HLINEWIDTH) % plot left ear
plot3(-EarX*sf,EarY*sf,2*ones(size(EarY)),'color',HEADCOLOR,'LineWidth',HLINEWIDTH) % plot right ear
end
end
%
% %%%%%%%%%%%%%%%%%%% Show electrode information %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
plotax = gca;
axis square % make plotax square
axis off
pos = get(gca,'position');
xlm = get(gca,'xlim');
ylm = get(gca,'ylim');
% textax = axes('position',pos,'xlim',xlm,'ylim',ylm); % make new axes so clicking numbers <-> labels
% will work inside head cartoon patch
% axes(textax);
axis square % make textax square
pos = get(gca,'position');
set(plotax,'position',pos);
xlm = get(gca,'xlim');
set(plotax,'xlim',xlm);
ylm = get(gca,'ylim');
set(plotax,'ylim',ylm); % copy position and axis limits again
axis equal;
set(gca, 'xlim', [-0.525 0.525]); set(plotax, 'xlim', [-0.525 0.525]);
set(gca, 'ylim', [-0.525 0.525]); set(plotax, 'ylim', [-0.525 0.525]);
%get(textax,'pos') % test if equal!
%get(plotax,'pos')
%get(textax,'xlim')
%get(plotax,'xlim')
%get(textax,'ylim')
%get(plotax,'ylim')
if isempty(EMARKERSIZE)
EMARKERSIZE = 10;
if length(y)>=160
EMARKERSIZE = 3;
elseif length(y)>=128
EMARKERSIZE = 3;
elseif length(y)>=100
EMARKERSIZE = 3;
elseif length(y)>=80
EMARKERSIZE = 4;
elseif length(y)>=64
EMARKERSIZE = 5;
elseif length(y)>=48
EMARKERSIZE = 6;
elseif length(y)>=32
EMARKERSIZE = 8;
end
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations only %%%%%%%%%%%%%%%%%%%%%%%%%%
%
ELECTRODE_HEIGHT = 2.1; % z value for plotting electrode information (above the surf)
if strcmp(ELECTRODES,'on') % plot electrodes as spots
if isempty(EMARKER2CHANS)
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
else % plot markers for normal chans and EMARKER2CHANS separately
hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Print electrode labels only %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'labels') % print electrode names (labels)
for i = 1:size(labels,1)
text(double(y(i)),double(x(i)),...
ELECTRODE_HEIGHT,labels(i,:),'HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',ECOLOR,...
'FontSize',EFSIZE)
end
%
%%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations plus labels %%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'labelpoint')
if isempty(EMARKER2CHANS)
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
else
hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
for i = 1:size(labels,1)
hh(i) = text(double(y(i)+0.01),double(x(i)),...
ELECTRODE_HEIGHT,labels(i,:),'HorizontalAlignment','left',...
'VerticalAlignment','middle','Color', ECOLOR,'userdata', num2str(allchansind(i)), ...
'FontSize',EFSIZE, 'buttondownfcn', ...
['tmpstr = get(gco, ''userdata'');'...
'set(gco, ''userdata'', get(gco, ''string''));' ...
'set(gco, ''string'', tmpstr); clear tmpstr;'] );
end
%
%%%%%%%%%%%%%%%%%%%%%%% Mark electrode locations plus numbers %%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'numpoint')
if isempty(EMARKER2CHANS)
hp2 = plot3(y,x,ones(size(x))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
else
hp2 = plot3(y(mark1chans),x(mark1chans),ones(size((mark1chans)))*ELECTRODE_HEIGHT,...
EMARKER,'Color',ECOLOR,'markersize',EMARKERSIZE,'linewidth',EMARKERLINEWIDTH);
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
for i = 1:size(labels,1)
hh(i) = text(double(y(i)+0.01),double(x(i)),...
ELECTRODE_HEIGHT,num2str(allchansind(i)),'HorizontalAlignment','left',...
'VerticalAlignment','middle','Color', ECOLOR,'userdata', labels(i,:) , ...
'FontSize',EFSIZE, 'buttondownfcn', ...
['tmpstr = get(gco, ''userdata'');'...
'set(gco, ''userdata'', get(gco, ''string''));' ...
'set(gco, ''string'', tmpstr); clear tmpstr;'] );
end
%
%%%%%%%%%%%%%%%%%%%%%% Print electrode numbers only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'numbers')
for i = 1:size(labels,1)
text(double(y(i)),double(x(i)),...
ELECTRODE_HEIGHT,int2str(allchansind(i)),'HorizontalAlignment','center',...
'VerticalAlignment','middle','Color',ECOLOR,...
'FontSize',EFSIZE)
end
%
%%%%%%%%%%%%%%%%%%%%%% Mark emarker2 electrodes only %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif strcmp(ELECTRODES,'off') & ~isempty(EMARKER2CHANS)
hp2b = plot3(y(mark2chans),x(mark2chans),ones(size((mark2chans)))*ELECTRODE_HEIGHT,...
EMARKER2,'Color',EMARKER2COLOR,'markerfacecolor',EMARKER2COLOR,'linewidth',EMARKER2LINEWIDTH,'markersize',EMARKERSIZE2);
end
%
%%%%%%%% Mark specified electrode locations with red filled disks %%%%%%%%%%%%%%%%%%%%%%
%
try,
if strcmpi(STYLE,'blank') % if mark-selected-channel-locations mode
for kk = 1:length(1:length(x))
if Values(kk) == 3
hp2 = plot3(y(kk),x(kk),ELECTRODE_HEIGHT,EMARKER,'Color', [0 0 0], 'markersize', EMARKERSIZE1CHAN);
elseif Values(kk) == 2
hp2 = plot3(y(kk),x(kk),ELECTRODE_HEIGHT,EMARKER,'Color', [0.5 0 0], 'markersize', EMARKERSIZE1CHAN);
elseif Values(kk) == 1
hp2 = plot3(y(kk),x(kk),ELECTRODE_HEIGHT,EMARKER,'Color', [1 0 0], 'markersize', EMARKERSIZE1CHAN);
elseif strcmpi(ELECTRODES,'on')
hp2 = plot3(y(kk),x(kk),ELECTRODE_HEIGHT,EMARKER,'Color', ECOLOR, 'markersize', EMARKERSIZE);
end
end
end
catch, end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%% Plot dipole(s) on the scalp map %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if ~isempty(DIPOLE)
hold on;
tmp = DIPOLE;
if isstruct(DIPOLE)
if ~isfield(tmp,'posxyz')
error('dipole structure is not an EEG.dipfit.model')
end
DIPOLE = []; % Note: invert x and y from dipplot usage
DIPOLE(:,1) = -tmp.posxyz(:,2)/DIPSPHERE; % -y -> x
DIPOLE(:,2) = tmp.posxyz(:,1)/DIPSPHERE; % x -> y
DIPOLE(:,3) = -tmp.momxyz(:,2);
DIPOLE(:,4) = tmp.momxyz(:,1);
else
DIPOLE(:,1) = -tmp(:,2); % same for vector input
DIPOLE(:,2) = tmp(:,1);
DIPOLE(:,3) = -tmp(:,4);
DIPOLE(:,4) = tmp(:,3);
end;
for index = 1:size(DIPOLE,1)
if ~any(DIPOLE(index,:))
DIPOLE(index,:) = [];
end
end;
DIPOLE(:,1:4) = DIPOLE(:,1:4)*rmax*(rmax/plotrad); % scale radius from 1 -> rmax (0.5)
DIPOLE(:,3:end) = (DIPOLE(:,3:end))*rmax/100000*(rmax/plotrad);
if strcmpi(DIPNORM, 'on')
for index = 1:size(DIPOLE,1)
DIPOLE(index,3:4) = DIPOLE(index,3:4)/norm(DIPOLE(index,3:end))*0.2;
end;
end;
DIPOLE(:, 3:4) = DIPORIENT*DIPOLE(:, 3:4)*DIPLEN;
PLOT_DIPOLE=1;
if sum(DIPOLE(1,3:4).^2) <= 0.00001
if strcmpi(VERBOSE,'on')
fprintf('Note: dipole is length 0 - not plotted\n')
end
PLOT_DIPOLE = 0;
end
if 0 % sum(DIPOLE(1,1:2).^2) > plotrad
if strcmpi(VERBOSE,'on')
fprintf('Note: dipole is outside plotting area - not plotted\n')
end
PLOT_DIPOLE = 0;
end
if PLOT_DIPOLE
for index = 1:size(DIPOLE,1)
hh = plot( DIPOLE(index, 1), DIPOLE(index, 2), '.');
set(hh, 'color', DIPCOLOR, 'markersize', DIPSCALE*30);
hh = line( [DIPOLE(index, 1) DIPOLE(index, 1)+DIPOLE(index, 3)]', ...
[DIPOLE(index, 2) DIPOLE(index, 2)+DIPOLE(index, 4)]',[10 10]);
set(hh, 'color', DIPCOLOR, 'linewidth', DIPSCALE*30/7);
end;
end;
end;
end % if ~ 'gridplot'
%
%%%%%%%%%%%%% Plot axis orientation %%%%%%%%%%%%%%%%%%%%
%
if strcmpi(DRAWAXIS, 'on')
axes('position', [0 0.85 0.08 0.1]);
axis off;
coordend1 = sqrt(-1)*3;
coordend2 = -3;
coordend1 = coordend1*exp(sqrt(-1)*rotate);
coordend2 = coordend2*exp(sqrt(-1)*rotate);
line([5 5+round(real(coordend1))]', [5 5+round(imag(coordend1))]', 'color', 'k');
line([5 5+round(real(coordend2))]', [5 5+round(imag(coordend2))]', 'color', 'k');
if round(real(coordend2))<0
text( 5+round(real(coordend2))*1.2, 5+round(imag(coordend2))*1.2-2, '+Y');
else text( 5+round(real(coordend2))*1.2, 5+round(imag(coordend2))*1.2, '+Y');
end;
if round(real(coordend1))<0
text( 5+round(real(coordend1))*1.2, 5+round(imag(coordend1))*1.2+1.5, '+X');
else text( 5+round(real(coordend1))*1.2, 5+round(imag(coordend1))*1.2, '+X');
end;
set(gca, 'xlim', [0 10], 'ylim', [0 10]);
end;
%
%%%%%%%%%%%%% Set EEGLAB background color to match head border %%%%%%%%%%%%%%%%%%%%%%%%
%
try,
icadefs;
set(gcf, 'color', BACKCOLOR);
catch,
end;
hold off
axis off
return
|
github
|
ZijingMao/baselineeegtest-master
|
readlocs.m
|
.m
|
baselineeegtest-master/VisualizationFilters/External EEGLAB functions/readlocs.m
| 33,743 |
utf_8
|
c376d1ca0e88b41512b698fc39b404fd
|
% readlocs() - read electrode location coordinates and other information from a file.
% Several standard file formats are supported. Users may also specify
% a custom column format. Defined format examples are given below
% (see File Formats).
% Usage:
% >> eloc = readlocs( filename );
% >> EEG.chanlocs = readlocs( filename, 'key', 'val', ... );
% >> [eloc, labels, theta, radius, indices] = ...
% readlocs( filename, 'key', 'val', ... );
% Inputs:
% filename - Name of the file containing the electrode locations
% {default: 2-D polar coordinates} (see >> help topoplot )
%
% Optional inputs:
% 'filetype' - ['loc'|'sph'|'sfp'|'xyz'|'asc'|'polhemus'|'besa'|'chanedit'|'custom']
% Type of the file to read. By default the file type is determined
% using the file extension (see below under File Formats),
% 'loc' an EEGLAB 2-D polar coordinates channel locations file
% Coordinates are theta and radius (see definitions below).
% 'sph' Matlab spherical coordinates (Note: spherical
% coordinates used by Matlab functions are different
% from spherical coordinates used by BESA - see below).
% 'sfp' EGI Cartesian coordinates (NOT Matlab Cartesian - see below).
% 'xyz' Matlab/EEGLAB Cartesian coordinates (NOT EGI Cartesian).
% z is toward nose; y is toward left ear; z is toward vertex
% 'asc' Neuroscan polar coordinates.
% 'polhemus' or 'polhemusx' - Polhemus electrode location file recorded
% with 'X' on sensor pointing to subject (see below and readelp()).
% 'polhemusy' - Polhemus electrode location file recorded with
% 'Y' on sensor pointing to subject (see below and readelp()).
% 'besa' BESA-'.elp' spherical coordinates. (Not MATLAB spherical -
% see below).
% 'chanedit' - EEGLAB channel location file created by pop_chanedit().
% 'custom' - Ascii file with columns in user-defined 'format' (see below).
% 'importmode' - ['eeglab'|'native'] for location files containing 3-D cartesian electrode
% coordinates, import either in EEGLAB format (nose pointing toward +X).
% This may not always be possible since EEGLAB might not be able to
% determine the nose direction for scanned electrode files. 'native' import
% original carthesian coordinates (user can then specify the position of
% the nose when calling the topoplot() function; in EEGLAB the position
% of the nose is stored in the EEG.chaninfo structure). {default 'eeglab'}
% 'format' - [cell array] Format of a 'custom' channel location file (see above).
% {default: if no file type is defined. The cell array contains
% labels defining the meaning of each column of the input file.
% 'channum' [positive integer] channel number.
% 'labels' [string] channel name (no spaces).
% 'theta' [real degrees] 2-D angle in polar coordinates.
% positive => rotating from nose (0) toward left ear
% 'radius' [real] radius for 2-D polar coords; 0.5 is the head
% disk radius and limit for topoplot() plotting).
% 'X' [real] Matlab-Cartesian X coordinate (to nose).
% 'Y' [real] Matlab-Cartesian Y coordinate (to left ear).
% 'Z' [real] Matlab-Cartesian Z coordinate (to vertex).
% '-X','-Y','-Z' Matlab-Cartesian coordinates pointing opposite
% to the above.
% 'sph_theta' [real degrees] Matlab spherical horizontal angle.
% positive => rotating from nose (0) toward left ear.
% 'sph_phi' [real degrees] Matlab spherical elevation angle.
% positive => rotating from horizontal (0) upwards.
% 'sph_radius' [real] distance from head center (unused).
% 'sph_phi_besa' [real degrees] BESA phi angle from vertical.
% positive => rotating from vertex (0) towards right ear.
% 'sph_theta_besa' [real degrees] BESA theta horiz/azimuthal angle.
% positive => rotating from right ear (0) toward nose.
% 'ignore' ignore column}.
% The input file may also contain other channel information fields.
% 'type' channel type: 'EEG', 'MEG', 'EMG', 'ECG', others ...
% 'calib' [real near 1.0] channel calibration value.
% 'gain' [real > 1] channel gain.
% 'custom1' custom field #1.
% 'custom2', 'custom3', 'custom4', etc. more custom fields
% 'skiplines' - [integer] Number of header lines to skip (in 'custom' file types only).
% Note: Characters on a line following '%' will be treated as comments.
% 'readchans' - [integer array] indices of electrodes to read. {default: all}
% 'center' - [(1,3) real array or 'auto'] center of xyz coordinates for conversion
% to spherical or polar, Specify the center of the sphere here, or 'auto'.
% This uses the center of the sphere that best fits all the electrode
% locations read. {default: [0 0 0]}
% Outputs:
% eloc - structure containing the channel names and locations (if present).
% It has three fields: 'eloc.labels', 'eloc.theta' and 'eloc.radius'
% identical in meaning to the EEGLAB struct 'EEG.chanlocs'.
% labels - cell array of strings giving the names of the electrodes. NOTE: Unlike the
% three outputs below, includes labels of channels *without* location info.
% theta - vector (in degrees) of polar angles of the electrode locations.
% radius - vector of polar-coordinate radii (arc_lengths) of the electrode locations
% indices - indices, k, of channels with non-empty 'locs(k).theta' coordinate
%
% File formats:
% If 'filetype' is unspecified, the file extension determines its type.
%
% '.loc' or '.locs' or '.eloc':
% polar coordinates. Notes: angles in degrees:
% right ear is 90; left ear -90; head disk radius is 0.5.
% Fields: N angle radius label
% Sample: 1 -18 .511 Fp1
% 2 18 .511 Fp2
% 3 -90 .256 C3
% 4 90 .256 C4
% ...
% Note: In previous releases, channel labels had to contain exactly
% four characters (spaces replaced by '.'). This format still works,
% though dots are no longer required.
% '.sph':
% Matlab spherical coordinates. Notes: theta is the azimuthal/horizontal angle
% in deg.: 0 is toward nose, 90 rotated to left ear. Following this, performs
% the elevation (phi). Angles in degrees.
% Fields: N theta phi label
% Sample: 1 18 -2 Fp1
% 2 -18 -2 Fp2
% 3 90 44 C3
% 4 -90 44 C4
% ...
% '.elc':
% Cartesian 3-D electrode coordinates scanned using the EETrak software.
% See readeetraklocs().
% '.elp':
% Polhemus-.'elp' Cartesian coordinates. By default, an .elp extension is read
% as PolhemusX-elp in which 'X' on the Polhemus sensor is pointed toward the
% subject. Polhemus files are not in columnar format (see readelp()).
% '.elp':
% BESA-'.elp' spherical coordinates: Need to specify 'filetype','besa'.
% The elevation angle (phi) is measured from the vertical axis. Positive
% rotation is toward right ear. Next, perform azimuthal/horizontal rotation
% (theta): 0 is toward right ear; 90 is toward nose, -90 toward occiput.
% Angles are in degrees. If labels are absent or weights are given in
% a last column, readlocs() adjusts for this. Default labels are E1, E2, ...
% Fields: label phi theta
% Sample: Fp1 -92 -72
% Fp2 92 72
% C3 -46 0
% C4 46 0
% ...
% '.xyz':
% Matlab/EEGLAB Cartesian coordinates. Here. x is towards the nose,
% y is towards the left ear, and z towards the vertex. Note that the first
% column (x) is -Y in a Matlab 3-D plot, the second column (y) is X in a
% matlab 3-D plot, and the third column (z) is Z.
% Fields: channum x y z label
% Sample: 1 .950 .308 -.035 Fp1
% 2 .950 -.308 -.035 Fp2
% 3 0 .719 .695 C3
% 4 0 -.719 .695 C4
% ...
% '.asc', '.dat':
% Neuroscan-.'asc' or '.dat' Cartesian polar coordinates text file.
% '.sfp':
% BESA/EGI-xyz Cartesian coordinates. Notes: For EGI, x is toward right ear,
% y is toward the nose, z is toward the vertex. EEGLAB converts EGI
% Cartesian coordinates to Matlab/EEGLAB xyz coordinates.
% Fields: label x y z
% Sample: Fp1 -.308 .950 -.035
% Fp2 .308 .950 -.035
% C3 -.719 0 .695
% C4 .719 0 .695
% ...
% '.ced':
% ASCII file saved by pop_chanedit(). Contains multiple MATLAB/EEGLAB formats.
% Cartesian coordinates are as in the 'xyz' format (above).
% Fields: channum label theta radius x y z sph_theta sph_phi ...
% Sample: 1 Fp1 -18 .511 .950 .308 -.035 18 -2 ...
% 2 Fp2 18 .511 .950 -.308 -.035 -18 -2 ...
% 3 C3 -90 .256 0 .719 .695 90 44 ...
% 4 C4 90 .256 0 -.719 .695 -90 44 ...
% ...
% The last columns of the file may contain any other defined fields (gain,
% calib, type, custom).
%
% Fieldtrip structure:
% If a Fieltrip structure is given as input, an EEGLAB
% chanlocs structure is returned
%
% Author: Arnaud Delorme, Salk Institute, 8 Dec 2002
%
% See also: readelp(), writelocs(), topo2sph(), sph2topo(), sph2cart()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 28 Feb 2002
%
% 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 [eloc, labels, theta, radius, indices] = readlocs( filename, varargin );
if nargin < 1
help readlocs;
return;
end;
% NOTE: To add a new channel format:
% ----------------------------------
% 1) Add a new element to the structure 'chanformat' (see 'ADD NEW FORMATS HERE' below):
% 2) Enter a format 'type' for the new file format,
% 3) Enter a (short) 'typestring' description of the format
% 4) Enter a longer format 'description' (possibly multiline, see ex. (1) below)
% 5) Enter format file column labels in the 'importformat' field (see ex. (2) below)
% 6) Enter the number of header lines to skip (if any) in the 'skipline' field
% 7) Document the new channel format in the help message above.
% 8) After testing, please send the new version of readloca.m to us
% at [email protected] with a sample locs file.
% The 'chanformat' structure is also used (automatically) by the writelocs()
% and pop_readlocs() functions. You do not need to edit these functions.
chanformat(1).type = 'polhemus';
chanformat(1).typestring = 'Polhemus native .elp file';
chanformat(1).description = [ 'Polhemus native coordinate file containing scanned electrode positions. ' ...
'User must select the direction ' ...
'for the nose after importing the data file.' ];
chanformat(1).importformat = 'readelp() function';
% ---------------------------------------------------------------------------------------------------
chanformat(2).type = 'besa';
chanformat(2).typestring = 'BESA spherical .elp file';
chanformat(2).description = [ 'BESA spherical coordinate file. Note that BESA spherical coordinates ' ...
'are different from Matlab spherical coordinates' ];
chanformat(2).skipline = 0; % some BESA files do not have headers
chanformat(2).importformat = { 'type' 'labels' 'sph_theta_besa' 'sph_phi_besa' 'sph_radius' };
% ---------------------------------------------------------------------------------------------------
chanformat(3).type = 'xyz';
chanformat(3).typestring = 'Matlab .xyz file';
chanformat(3).description = [ 'Standard 3-D cartesian coordinate files with electrode labels in ' ...
'the first column and X, Y, and Z coordinates in columns 2, 3, and 4' ];
chanformat(3).importformat = { 'channum' '-Y' 'X' 'Z' 'labels'};
% ---------------------------------------------------------------------------------------------------
chanformat(4).type = 'sfp';
chanformat(4).typestring = 'BESA or EGI 3-D cartesian .sfp file';
chanformat(4).description = [ 'Standard BESA 3-D cartesian coordinate files with electrode labels in ' ...
'the first column and X, Y, and Z coordinates in columns 2, 3, and 4.' ...
'Coordinates are re-oriented to fit the EEGLAB standard of having the ' ...
'nose along the +X axis.' ];
chanformat(4).importformat = { 'labels' '-Y' 'X' 'Z' };
chanformat(4).skipline = 0;
% ---------------------------------------------------------------------------------------------------
chanformat(5).type = 'loc';
chanformat(5).typestring = 'EEGLAB polar .loc file';
chanformat(5).description = [ 'EEGLAB polar .loc file' ];
chanformat(5).importformat = { 'channum' 'theta' 'radius' 'labels' };
% ---------------------------------------------------------------------------------------------------
chanformat(6).type = 'sph';
chanformat(6).typestring = 'Matlab .sph spherical file';
chanformat(6).description = [ 'Standard 3-D spherical coordinate files in Matlab format' ];
chanformat(6).importformat = { 'channum' 'sph_theta' 'sph_phi' 'labels' };
% ---------------------------------------------------------------------------------------------------
chanformat(7).type = 'asc';
chanformat(7).typestring = 'Neuroscan polar .asc file';
chanformat(7).description = [ 'Neuroscan polar .asc file, automatically recentered to fit EEGLAB standard' ...
'of having ''Cz'' at (0,0).' ];
chanformat(7).importformat = 'readneurolocs';
% ---------------------------------------------------------------------------------------------------
chanformat(8).type = 'dat';
chanformat(8).typestring = 'Neuroscan 3-D .dat file';
chanformat(8).description = [ 'Neuroscan 3-D cartesian .dat file. Coordinates are re-oriented to fit ' ...
'the EEGLAB standard of having the nose along the +X axis.' ];
chanformat(8).importformat = 'readneurolocs';
% ---------------------------------------------------------------------------------------------------
chanformat(9).type = 'elc';
chanformat(9).typestring = 'ASA .elc 3-D file';
chanformat(9).description = [ 'ASA .elc 3-D coordinate file containing scanned electrode positions. ' ...
'User must select the direction ' ...
'for the nose after importing the data file.' ];
chanformat(9).importformat = 'readeetraklocs';
% ---------------------------------------------------------------------------------------------------
chanformat(10).type = 'chanedit';
chanformat(10).typestring = 'EEGLAB complete 3-D file';
chanformat(10).description = [ 'EEGLAB file containing polar, cartesian 3-D, and spherical 3-D ' ...
'electrode locations.' ];
chanformat(10).importformat = { 'channum' 'labels' 'theta' 'radius' 'X' 'Y' 'Z' 'sph_theta' 'sph_phi' ...
'sph_radius' 'type' };
chanformat(10).skipline = 1;
% ---------------------------------------------------------------------------------------------------
chanformat(11).type = 'custom';
chanformat(11).typestring = 'Custom file format';
chanformat(11).description = 'Custom ASCII file format where user can define content for each file columns.';
chanformat(11).importformat = '';
% ---------------------------------------------------------------------------------------------------
% ----- ADD MORE FORMATS HERE -----------------------------------------------------------------------
% ---------------------------------------------------------------------------------------------------
listcolformat = { 'labels' 'channum' 'theta' 'radius' 'sph_theta' 'sph_phi' ...
'sph_radius' 'sph_theta_besa' 'sph_phi_besa' 'gain' 'calib' 'type' ...
'X' 'Y' 'Z' '-X' '-Y' '-Z' 'custom1' 'custom2' 'custom3' 'custom4' 'ignore' 'not def' };
% ----------------------------------
% special mode for getting the info
% ----------------------------------
if isstr(filename) & strcmp(filename, 'getinfos')
eloc = chanformat;
labels = listcolformat;
return;
end;
g = finputcheck( varargin, ...
{ 'filetype' 'string' {} '';
'importmode' 'string' { 'eeglab','native' } 'eeglab';
'defaultelp' 'string' { 'besa','polhemus' } 'polhemus';
'skiplines' 'integer' [0 Inf] [];
'elecind' 'integer' [1 Inf] [];
'format' 'cell' [] {} }, 'readlocs');
if isstr(g), error(g); end;
if isstr(filename)
% format auto detection
% --------------------
if strcmpi(g.filetype, 'autodetect'), g.filetype = ''; end;
g.filetype = strtok(g.filetype);
periods = find(filename == '.');
fileextension = filename(periods(end)+1:end);
g.filetype = lower(g.filetype);
if isempty(g.filetype)
switch lower(fileextension),
case {'loc' 'locs' }, g.filetype = 'loc';
case 'xyz', g.filetype = 'xyz';
fprintf( [ 'WARNING: Matlab Cartesian coord. file extension (".xyz") detected.\n' ...
'If importing EGI Cartesian coords, force type "sfp" instead.\n'] );
case 'sph', g.filetype = 'sph';
case 'ced', g.filetype = 'chanedit';
case 'elp', g.filetype = g.defaultelp;
case 'asc', g.filetype = 'asc';
case 'dat', g.filetype = 'dat';
case 'elc', g.filetype = 'elc';
case 'eps', g.filetype = 'besa';
case 'sfp', g.filetype = 'sfp';
otherwise, g.filetype = '';
end;
fprintf('readlocs(): ''%s'' format assumed from file extension\n', g.filetype);
else
if strcmpi(g.filetype, 'locs'), g.filetype = 'loc'; end
if strcmpi(g.filetype, 'eloc'), g.filetype = 'loc'; end
end;
% assign format from filetype
% ---------------------------
if ~isempty(g.filetype) & ~strcmpi(g.filetype, 'custom') ...
& ~strcmpi(g.filetype, 'asc') & ~strcmpi(g.filetype, 'elc') & ~strcmpi(g.filetype, 'dat')
indexformat = strmatch(lower(g.filetype), { chanformat.type }, 'exact');
g.format = chanformat(indexformat).importformat;
if isempty(g.skiplines)
g.skiplines = chanformat(indexformat).skipline;
end;
if isempty(g.filetype)
error( ['readlocs() error: The filetype cannot be detected from the \n' ...
' file extension, and custom format not specified']);
end;
end;
% import file
% -----------
if strcmp(g.filetype, 'asc') | strcmp(g.filetype, 'dat')
eloc = readneurolocs( filename );
eloc = rmfield(eloc, 'sph_theta'); % for the conversion below
eloc = rmfield(eloc, 'sph_theta_besa'); % for the conversion below
if isfield(eloc, 'type')
for index = 1:length(eloc)
type = eloc(index).type;
if type == 69, eloc(index).type = 'EEG';
elseif type == 88, eloc(index).type = 'REF';
elseif type >= 76 & type <= 82, eloc(index).type = 'FID';
else eloc(index).type = num2str(eloc(index).type);
end;
end;
end;
elseif strcmp(g.filetype, 'elc')
eloc = readeetraklocs( filename );
%eloc = read_asa_elc( filename ); % from fieldtrip
%eloc = struct('labels', eloc.label, 'X', mattocell(eloc.pnt(:,1)'), 'Y', ...
% mattocell(eloc.pnt(:,2)'), 'Z', mattocell(eloc.pnt(:,3)'));
eloc = convertlocs(eloc, 'cart2all');
eloc = rmfield(eloc, 'sph_theta'); % for the conversion below
eloc = rmfield(eloc, 'sph_theta_besa'); % for the conversion below
elseif strcmp(lower(g.filetype(1:end-1)), 'polhemus') | ...
strcmp(g.filetype, 'polhemus')
try,
[eloc labels X Y Z]= readelp( filename );
if strcmp(g.filetype, 'polhemusy')
tmp = X; X = Y; Y = tmp;
end;
for index = 1:length( eloc )
eloc(index).X = X(index);
eloc(index).Y = Y(index);
eloc(index).Z = Z(index);
end;
catch,
disp('readlocs(): Could not read Polhemus coords. Trying to read BESA .elp file.');
[eloc, labels, theta, radius, indices] = readlocs( filename, 'defaultelp', 'besa', varargin{:} );
end;
else
% importing file
% --------------
if isempty(g.skiplines), g.skiplines = 0; end;
if strcmpi(g.filetype, 'chanedit')
array = loadtxt( filename, 'delim', 9, 'skipline', g.skiplines, 'blankcell', 'off');
else
array = load_file_or_array( filename, g.skiplines);
end;
if size(array,2) < length(g.format)
fprintf(['readlocs() warning: Fewer columns in the input than expected.\n' ...
' See >> help readlocs\n']);
elseif size(array,2) > length(g.format)
fprintf(['readlocs() warning: More columns in the input than expected.\n' ...
' See >> help readlocs\n']);
end;
% removing lines BESA
% -------------------
if isempty(array{1,2})
disp('BESA header detected, skipping three lines...');
array = load_file_or_array( filename, g.skiplines-1);
if isempty(array{1,2})
array = load_file_or_array( filename, g.skiplines-1);
end;
end;
% xyz format, is the first col absent
% -----------------------------------
if strcmp(g.filetype, 'xyz')
if size(array, 2) == 4
array(:, 2:5) = array(:, 1:4);
end;
end;
% removing comments and empty lines
% ---------------------------------
indexbeg = 1;
while isempty(array{indexbeg,1}) | ...
(isstr(array{indexbeg,1}) & array{indexbeg,1}(1) == '%' )
indexbeg = indexbeg+1;
end;
array = array(indexbeg:end,:);
% converting file
% ---------------
for indexcol = 1:min(size(array,2), length(g.format))
[str mult] = checkformat(g.format{indexcol});
for indexrow = 1:size( array, 1)
if mult ~= 1
eval ( [ 'eloc(indexrow).' str '= -array{indexrow, indexcol};' ]);
else
eval ( [ 'eloc(indexrow).' str '= array{indexrow, indexcol};' ]);
end;
end;
end;
end;
% handling BESA coordinates
% -------------------------
if isfield(eloc, 'sph_theta_besa')
if isfield(eloc, 'type')
if isnumeric(eloc(1).type)
disp('BESA format detected ( Theta | Phi )');
for index = 1:length(eloc)
eloc(index).sph_phi_besa = eloc(index).labels;
eloc(index).sph_theta_besa = eloc(index).type;
eloc(index).labels = '';
eloc(index).type = '';
end;
eloc = rmfield(eloc, 'labels');
end;
end;
if isfield(eloc, 'labels')
if isnumeric(eloc(1).labels)
disp('BESA format detected ( Elec | Theta | Phi )');
for index = 1:length(eloc)
eloc(index).sph_phi_besa = eloc(index).sph_theta_besa;
eloc(index).sph_theta_besa = eloc(index).labels;
eloc(index).labels = eloc(index).type;
eloc(index).type = '';
eloc(index).radius = 1;
end;
end;
end;
try
eloc = convertlocs(eloc, 'sphbesa2all');
eloc = convertlocs(eloc, 'topo2all'); % problem with some EGI files (not BESA files)
catch, disp('Warning: coordinate conversion failed'); end;
fprintf('Readlocs: BESA spherical coords. converted, now deleting BESA fields\n');
fprintf(' to avoid confusion (these fields can be exported, though)\n');
eloc = rmfield(eloc, 'sph_phi_besa');
eloc = rmfield(eloc, 'sph_theta_besa');
% converting XYZ coordinates to polar
% -----------------------------------
elseif isfield(eloc, 'sph_theta')
try
eloc = convertlocs(eloc, 'sph2all');
catch, disp('Warning: coordinate conversion failed'); end;
elseif isfield(eloc, 'X')
try
eloc = convertlocs(eloc, 'cart2all');
catch, disp('Warning: coordinate conversion failed'); end;
else
try
eloc = convertlocs(eloc, 'topo2all');
catch, disp('Warning: coordinate conversion failed'); end;
end;
% inserting labels if no labels
% -----------------------------
if ~isfield(eloc, 'labels')
fprintf('readlocs(): Inserting electrode labels automatically.\n');
for index = 1:length(eloc)
eloc(index).labels = [ 'E' int2str(index) ];
end;
else
% remove trailing '.'
for index = 1:length(eloc)
if isstr(eloc(index).labels)
tmpdots = find( eloc(index).labels == '.' );
eloc(index).labels(tmpdots) = [];
end;
end;
end;
% resorting electrodes if number not-sorted
% -----------------------------------------
if isfield(eloc, 'channum')
if ~isnumeric(eloc(1).channum)
error('Channel numbers must be numeric');
end;
allchannum = [ eloc.channum ];
if any( sort(allchannum) ~= allchannum )
fprintf('readlocs(): Re-sorting channel numbers based on ''channum'' column indices\n');
[tmp newindices] = sort(allchannum);
eloc = eloc(newindices);
end;
eloc = rmfield(eloc, 'channum');
end;
else
if isstruct(filename)
% detect Fieldtrip structure and convert it
% -----------------------------------------
if isfield(filename, 'pnt')
neweloc = [];
for index = 1:length(filename.label)
neweloc(index).labels = filename.label{index};
neweloc(index).X = filename.pnt(index,1);
neweloc(index).Y = filename.pnt(index,2);
neweloc(index).Z = filename.pnt(index,3);
end;
eloc = neweloc;
eloc = convertlocs(eloc, 'cart2all');
else
eloc = filename;
end;
else
disp('readlocs(): input variable must be a string or a structure');
end;
end;
if ~isempty(g.elecind)
eloc = eloc(g.elecind);
end;
if nargout > 2
if isfield(eloc, 'theta')
tmptheta = { eloc.theta }; % check which channels have (polar) coordinates set
else tmptheta = cell(1,length(eloc));
end;
if isfield(eloc, 'theta')
tmpx = { eloc.X }; % check which channels have (polar) coordinates set
else tmpx = cell(1,length(eloc));
end;
indices = find(~cellfun('isempty', tmptheta));
indices = intersect(find(~cellfun('isempty', tmpx)), indices);
indices = sort(indices);
indbad = setdiff(1:length(eloc), indices);
tmptheta(indbad) = { NaN };
theta = [ tmptheta{:} ];
end;
if nargout > 3
if isfield(eloc, 'theta')
tmprad = { eloc.radius }; % check which channels have (polar) coordinates set
else tmprad = cell(1,length(eloc));
end;
tmprad(indbad) = { NaN };
radius = [ tmprad{:} ];
end;
%tmpnum = find(~cellfun('isclass', { eloc.labels }, 'char'));
%disp('Converting channel labels to string');
for index = 1:length(eloc)
if ~isstr(eloc(index).labels)
eloc(index).labels = int2str(eloc(index).labels);
end;
end;
labels = { eloc.labels };
if isfield(eloc, 'ignore')
eloc = rmfield(eloc, 'ignore');
end;
% process fiducials if any
% ------------------------
fidnames = { 'nz' 'lpa' 'rpa' 'nasion' 'left' 'right' 'nazion' 'fidnz' 'fidt9' 'fidt10' 'cms' 'drl' };
for index = 1:length(fidnames)
ind = strmatch(fidnames{index}, lower(labels), 'exact');
if ~isempty(ind), eloc(ind).type = 'FID'; end;
end;
return;
% interpret the variable name
% ---------------------------
function array = load_file_or_array( varname, skiplines );
if isempty(skiplines),
skiplines = 0;
end;
if exist( varname ) == 2
array = loadtxt(varname,'verbose','off','skipline',skiplines,'blankcell','off');
else % variable in the global workspace
% --------------------------
try, array = evalin('base', varname);
catch, error('readlocs(): cannot find the named file or variable, check syntax');
end;
end;
return;
% check field format
% ------------------
function [str, mult] = checkformat(str)
mult = 1;
if strcmpi(str, 'labels'), str = lower(str); return; end;
if strcmpi(str, 'channum'), str = lower(str); return; end;
if strcmpi(str, 'theta'), str = lower(str); return; end;
if strcmpi(str, 'radius'), str = lower(str); return; end;
if strcmpi(str, 'ignore'), str = lower(str); return; end;
if strcmpi(str, 'sph_theta'), str = lower(str); return; end;
if strcmpi(str, 'sph_phi'), str = lower(str); return; end;
if strcmpi(str, 'sph_radius'), str = lower(str); return; end;
if strcmpi(str, 'sph_theta_besa'), str = lower(str); return; end;
if strcmpi(str, 'sph_phi_besa'), str = lower(str); return; end;
if strcmpi(str, 'gain'), str = lower(str); return; end;
if strcmpi(str, 'calib'), str = lower(str); return; end;
if strcmpi(str, 'type') , str = lower(str); return; end;
if strcmpi(str, 'X'), str = upper(str); return; end;
if strcmpi(str, 'Y'), str = upper(str); return; end;
if strcmpi(str, 'Z'), str = upper(str); return; end;
if strcmpi(str, '-X'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, '-Y'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, '-Z'), str = upper(str(2:end)); mult = -1; return; end;
if strcmpi(str, 'custom1'), return; end;
if strcmpi(str, 'custom2'), return; end;
if strcmpi(str, 'custom3'), return; end;
if strcmpi(str, 'custom4'), return; end;
error(['readlocs(): undefined field ''' str '''']);
|
github
|
ZijingMao/baselineeegtest-master
|
finputcheck.m
|
.m
|
baselineeegtest-master/VisualizationFilters/External EEGLAB functions/finputcheck.m
| 8,676 |
utf_8
|
98c5e52d4a9cd0c05a41cee29d409e4b
|
% finputcheck() - check Matlab function {'key','value'} input argument pairs
%
% Usage: >> result = finputcheck( varargin, fieldlist );
% >> [result varargin] = finputcheck( varargin, fieldlist, ...
% callingfunc, mode, verbose );
% Input:
% varargin - Cell array 'varargin' argument from a function call using 'key',
% 'value' argument pairs. See Matlab function 'varargin'
% fieldlist - A 4-column cell array, one row per 'key'. The first
% column contains the key string, the second its type(s),
% the third the accepted value range, and the fourth the
% default value. Allowed types are 'boolean', 'integer',
% 'real', 'string', 'cell' or 'struct'. For example,
% {'key1' 'string' { 'string1' 'string2' } 'defaultval_key1'}
% {'key2' {'real' 'integer'} { minint maxint } 'defaultval_key2'}
% callingfunc - Calling function name for error messages. {default: none}.
% mode - ['ignore'|'error'] ignore keywords that are either not specified
% in the fieldlist cell array or generate an error.
% {default: 'error'}.
% verbose - ['verbose', 'quiet'] print information. Default: 'verbose'.
%
% Outputs:
% result - If no error, structure with 'key' as fields and 'value' as
% content. If error this output contain the string error.
% varargin - residual varagin containing unrecognized input arguments.
% Requires mode 'ignore' above.
%
% Note: In case of error, a string is returned containing the error message
% instead of a structure.
%
% Example (insert the following at the beginning of your function):
% result = finputcheck(varargin, ...
% { 'title' 'string' [] ''; ...
% 'percent' 'real' [0 1] 1 ; ...
% 'elecamp' 'integer' [1:10] [] });
% if isstr(result)
% error(result);
% end
%
% Note:
% The 'title' argument should be a string. {no default value}
% The 'percent' argument should be a real number between 0 and 1. {default: 1}
% The 'elecamp' argument should be an integer between 1 and 10 (inclusive).
%
% Now 'g.title' will contain the title arg (if any, else the default ''), etc.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 10 July 2002
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 10 July 2002, [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 [g, varargnew] = finputcheck( vararg, fieldlist, callfunc, mode, verbose )
if nargin < 2
help finputcheck;
return;
end;
if nargin < 3
callfunc = '';
else
callfunc = [callfunc ' ' ];
end;
if nargin < 4
mode = 'do not ignore';
end;
if nargin < 5
verbose = 'verbose';
end;
NAME = 1;
TYPE = 2;
VALS = 3;
DEF = 4;
SIZE = 5;
varargnew = {};
% create structure
% ----------------
if ~isempty(vararg)
for index=1:length(vararg)
if iscell(vararg{index})
vararg{index} = {vararg{index}};
end;
end;
try
g = struct(vararg{:});
catch
vararg = removedup(vararg, verbose);
try
g = struct(vararg{:});
catch
g = [ callfunc 'error: bad ''key'', ''val'' sequence' ]; return;
end;
end;
else
g = [];
end;
for index = 1:size(fieldlist,NAME)
% check if present
% ----------------
if ~isfield(g, fieldlist{index, NAME})
g = setfield( g, fieldlist{index, NAME}, fieldlist{index, DEF});
end;
tmpval = getfield( g, {1}, fieldlist{index, NAME});
% check type
% ----------
if ~iscell( fieldlist{index, TYPE} )
res = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}, ...
fieldlist{index, VALS}, tmpval, callfunc );
if isstr(res), g = res; return; end;
else
testres = 0;
tmplist = fieldlist;
for it = 1:length( fieldlist{index, TYPE} )
if ~iscell(fieldlist{index, VALS})
res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ...
fieldlist{index, VALS}, tmpval, callfunc );
else res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ...
fieldlist{index, VALS}{it}, tmpval, callfunc );
end;
if ~isstr(res{it}), testres = 1; end;
end;
if testres == 0,
g = res{1};
for tmpi = 2:length(res)
g = [ g 10 'or ' res{tmpi} ];
end;
return;
end;
end;
end;
% check if fields are defined
% ---------------------------
allfields = fieldnames(g);
for index=1:length(allfields)
if isempty(strmatch(allfields{index}, fieldlist(:, 1)', 'exact'))
if ~strcmpi(mode, 'ignore')
g = [ callfunc 'error: undefined argument ''' allfields{index} '''']; return;
end;
varargnew{end+1} = allfields{index};
varargnew{end+1} = getfield(g, {1}, allfields{index});
end;
end;
function g = fieldtest( fieldname, fieldtype, fieldval, tmpval, callfunc );
NAME = 1;
TYPE = 2;
VALS = 3;
DEF = 4;
SIZE = 5;
g = [];
switch fieldtype
case { 'integer' 'real' 'boolean' 'float' },
if ~isnumeric(tmpval) && ~islogical(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be numeric' ]; return;
end;
if strcmpi(fieldtype, 'boolean')
if tmpval ~=0 && tmpval ~= 1
g = [ callfunc 'error: argument ''' fieldname ''' must be 0 or 1' ]; return;
end;
else
if strcmpi(fieldtype, 'integer')
if ~isempty(fieldval)
if (any(isnan(tmpval(:))) && ~any(isnan(fieldval))) ...
&& (~ismember(tmpval, fieldval))
g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return;
end;
end;
else % real or float
if ~isempty(fieldval) && ~isempty(tmpval)
if any(tmpval < fieldval(1)) || any(tmpval > fieldval(2))
g = [ callfunc 'error: value out of range for argument ''' fieldname '''' ]; return;
end;
end;
end;
end;
case 'string'
if ~isstr(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a string' ]; return;
end;
if ~isempty(fieldval)
if isempty(strmatch(lower(tmpval), lower(fieldval), 'exact'))
g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return;
end;
end;
case 'cell'
if ~iscell(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a cell array' ]; return;
end;
case 'struct'
if ~isstruct(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a structure' ]; return;
end;
case '';
otherwise, error([ 'finputcheck error: unrecognized type ''' fieldname '''' ]);
end;
% remove duplicates in the list of parameters
% -------------------------------------------
function cella = removedup(cella, verbose)
% make sure if all the values passed to unique() are strings, if not, exist
%try
[tmp indices] = unique(cella(1:2:end));
if length(tmp) ~= length(cella)/2
myfprintf(verbose,'Note: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n');
end;
cella = cella(sort(union(indices*2-1, indices*2)));
%catch
% some elements of cella were not string
% error('some ''key'' values are not string.');
%end;
function myfprintf(verbose, varargin)
if strcmpi(verbose, 'verbose')
fprintf(varargin{:});
end;
|
github
|
ZijingMao/baselineeegtest-master
|
meshReduce.m
|
.m
|
baselineeegtest-master/VisualizationFilters/geom3d/meshes3d/meshReduce.m
| 9,863 |
utf_8
|
fe0668cc856377deaeeb38dfce52916d
|
function varargout = meshReduce(nodes, varargin)
%MESHREDUCE Merge coplanar faces of a polyhedral mesh
%
% Note: deprecated, should use "mergeCoplanarFaces" instead
%
% [NODES FACES] = meshReduce(NODES, FACES)
% [NODES EDGES FACES] = meshReduce(NODES, EDGES, FACES)
% NODES is a set of 3D points (as a Nn-by-3 array),
% and FACES is one of:
% - a Nf-by-X array containing vertex indices of each face, with each
% face having the same number of vertices,
% - a Nf-by 1 cell array, each cell containing indices of a face.
% The function groups faces which are coplanar and contiguous, resulting
% in a "lighter" mesh. This can be useful for visualizing binary 3D
% images for example.
%
% FACES = meshReduce(..., PRECISION)
% Adjust the threshold for deciding if two faces are coplanar or
% parallel. Default value is 1e-14.
%
% Example
% [n e f] = createCube;
% figure; drawMesh(n, f); view(3); axis equal;
% f2 = meshReduce(n, f);
% figure; drawMesh(n, f2); view(3); axis equal;
%
% See also
% meshes3d, mergeCoplanarFaces
%
% ------
% Author: David Legland
% e-mail: [email protected]
% Created: 2006-07-05
% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).
% 20/07/2006 add tolerance for coplanarity test
% 21/08/2006 fix small bug due to difference of methods to test
% coplanaritity, sometimes resulting in 3 points of a face not coplanar !
% Also add control on precision
% 14/08/2007 rename minConvexHull->meshReduce, and extend to non convex
% shapes
% 2011-01-14 code clean up
% 2013-02-22 deprecate and rename to mergeCoplanarFaces
warning('MatGeom:meshes3d:deprecated', ...
'Function ''meshReduce'' is deprecated, should use ''mergeCoplanarFaces'' instead');
%% Process input arguments
% set up precision
acc = 1e-14;
if ~isempty(varargin)
var = varargin{end};
if length(var)==1
acc = var;
varargin(end) = [];
end
end
% extract faces and edges
if length(varargin)==1
faces = varargin{1};
else
faces = varargin{2};
end
%% Initialisations
% number of faces
Nn = size(nodes, 1);
Nf = size(faces, 1);
% compute number of vertices of each face
Fn = ones(Nf, 1)*size(faces, 2);
% compute normal of each faces
normals = faceNormal(nodes, faces);
% initialize empty faces and edges
faces2 = cell(0, 1);
edges2 = zeros(0, 2);
% Processing flag for each face
% 1: face to process, 0: already processed
% in the beginning, every triangle face need to be processed
flag = ones(Nf, 1);
%% Main iteration
% iterate on each face
for f = 1:Nf
% check if face was already performed
if ~flag(f)
continue;
end
% indices of faces with same normal
ind = find(abs(vectorNorm3d(cross(repmat(normals(f, :), [Nf 1]), normals)))<acc);
%ind = ind(ind~=i);
% keep only coplanar faces (test coplanarity of points in both face)
ind2 = false(size(ind));
for j = 1:length(ind)
ind2(j) = isCoplanar(nodes([faces(f,:) faces(ind(j),:)], :), acc);
end
ind2 = ind(ind2);
% compute edges of all faces in the plane
planeEdges = zeros(sum(Fn(ind2)), 2);
pos = 1;
for i=1:length(ind2)
face = faces(ind2(i), :);
faceEdges = sort([face' face([2:end 1])'], 2);
planeEdges(pos:sum(Fn(ind2(1:i))), :) = faceEdges;
pos = sum(Fn(ind2(1:i)))+1;
end
planeEdges = unique(planeEdges, 'rows');
% relabel plane edges, and find connected components
[planeNodes, I, J] = unique(planeEdges(:)); %#ok<ASGLU>
planeEdges2 = reshape(J, size(planeEdges));
component = grLabel(nodes(planeNodes, :), planeEdges2);
% compute degree (number of adjacent faces) of each edge.
Npe = size(planeEdges, 1);
edgesDegree = zeros(Npe, 1);
for i = 1:length(ind2)
face = faces(ind2(i), :);
faceEdges = sort([face' face([2:end 1])'], 2);
for j = 1:size(faceEdges, 1)
indEdge = find(sum(ismember(planeEdges, faceEdges(j,:)),2)==2);
edgesDegree(indEdge) = edgesDegree(indEdge)+1;
end
end
% extract unique edges and nodes of the plane
planeEdges = planeEdges(edgesDegree==1, :);
planeEdges2 = planeEdges2(edgesDegree==1, :);
% find connected component of each edge
planeEdgesComp = zeros(size(planeEdges, 1), 1);
for e = 1:size(planeEdges, 1)
planeEdgesComp(e) = component(planeEdges2(e, 1));
end
% iterate on connected faces
for c=1:max(component)
% convert to chains of nodes
loops = graph2Contours(nodes, planeEdges(planeEdgesComp==c, :));
% add a simple Polygon for each loop
facePolygon = loops{1};
for l = 2:length(loops)
facePolygon = [facePolygon, NaN, loops{l}]; %#ok<AGROW>
end
faces2{length(faces2)+1, 1} = facePolygon;
% also add news edges
edges2 = unique([edges2; planeEdges], 'rows');
end
% mark processed faces
flag(ind2) = 0;
end
%% Additional processing on nodes
% select only nodes which appear in at least one edge
indNodes = unique(edges2(:));
% for each node, compute index of corresponding new node (or 0 if dropped)
refNodes = zeros(Nn, 1);
for i=1:length(indNodes)
refNodes(indNodes(i)) = i;
end
% changes indices of nodes in edges2 array
for i=1:length(edges2(:))
edges2(i) = refNodes(edges2(i));
end
% changes indices of nodes in faces2 array
for f=1:length(faces2)
face = faces2{f};
for i=1:length(face)
if ~isnan(face(i))
face(i) = refNodes(face(i));
end
end
faces2{f} = face;
end
% keep only boundary nodes
nodes2 = nodes(indNodes, :);
%% Process output arguments
if nargout == 1
varargout{1} = faces2;
elseif nargout == 2
varargout{1} = nodes2;
varargout{2} = faces2;
elseif nargout==3
varargout{1} = nodes2;
varargout{2} = edges2;
varargout{3} = faces2;
end
function labels = grLabel(nodes, edges)
%GRLABEL associate a label to each connected component of the graph
% LABELS = grLabel(NODES, EDGES)
% Returns an array with as many rows as the array NODES, containing index
% number of each connected component of the graph. If the graph is
% totally connected, returns an array of 1.
%
% Example
% nodes = rand(6, 2);
% edges = [1 2;1 3;4 6];
% labels = grLabel(nodes, edges);
% labels =
% 1
% 1
% 1
% 2
% 3
% 2
%
% See also
% getNeighbourNodes
%
%
% ------
% Author: David Legland
% e-mail: [email protected]
% Created: 2007-08-14, using Matlab 7.4.0.287 (R2007a)
% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.
% init
Nn = size(nodes, 1);
labels = (1:Nn)';
% iteration
modif = true;
while modif
modif = false;
for i=1:Nn
neigh = getNeighbourNodes(i, edges);
neighLabels = labels([i;neigh]);
% check for a modification
if length(unique(neighLabels))>1
modif = true;
end
% put new labels
labels(ismember(labels, neighLabels)) = min(neighLabels);
end
end
% change to have fewer labels
labels2 = unique(labels);
for i=1:length(labels2)
labels(labels==labels2(i)) = i;
end
function nodes2 = getNeighbourNodes(node, edges)
%GETNEIGHBOURNODES find nodes adjacent to a given node
%
% NEIGHS = getNeighbourNodes(NODE, EDGES)
% NODE: index of the node
% EDGES: the complete edges list
% NEIGHS: the nodes adjacent to the given node.
%
% NODE can also be a vector of node indices, in this case the result is
% the set of neighbors of any input node.
%
%
% -----
%
% author : David Legland
% INRA - TPV URPOI - BIA IMASTE
% created the 16/08/2004.
%
% HISTORY
% 10/02/2004 documentation
% 13/07/2004 faster algorithm
% 03/10/2007 can specify several input nodes
[i, j] = find(ismember(edges, node));
nodes2 = edges(i,1:2);
nodes2 = unique(nodes2(:));
nodes2 = sort(nodes2(~ismember(nodes2, node)));
function curves = graph2Contours(nodes, edges)
%GRAPH2CONTOURS convert a graph to a set of contour curves
%
% CONTOURS = GRAPH2CONTOURS(NODES, EDGES)
% NODES, EDGES is a graph representation (type "help graph" for details)
% The algorithm assume every node has degree 2, and the set of edges
% forms only closed loops. The result is a list of indices arrays, each
% array containing consecutive point indices of a contour.
%
% To transform contours into drawable curves, please use :
% CURVES{i} = NODES(CONTOURS{i}, :);
%
%
% NOTE : contours are not oriented. To manage contour orientation, edges
% also need to be oriented. So we must precise generation of edges.
%
% -----
%
% author : David Legland
% INRA - TPV URPOI - BIA IMASTE
% created the 05/08/2004.
%
curves = {};
c = 0;
while size(edges,1)>0
% find first point of the curve
n0 = edges(1,1);
curve = n0;
% second point of the curve
n = edges(1,2);
e = 1;
while true
% add current point to the curve
curve = [curve n];
% remove current edge from the list
edges = edges((1:size(edges,1))~=e,:);
% find index of edge containing reference to current node
e = find(edges(:,1)==n | edges(:,2)==n);
e = e(1);
% get index of next current node
% (this is the other node of the current edge)
if edges(e,1)==n
n = edges(e,2);
else
n = edges(e,1);
end
% if node is same as start node, loop is closed, and we stop
% node iteration.
if n==n0
break;
end
end
% remove the last edge of the curve from edge list.
edges = edges((1:size(edges,1))~=e,:);
% add the current curve to the list, and start a new curve
c = c+1;
curves{c} = curve;
end
|
github
|
ZijingMao/baselineeegtest-master
|
meshSurfaceArea.m
|
.m
|
baselineeegtest-master/VisualizationFilters/geom3d/meshes3d/meshSurfaceArea.m
| 1,883 |
utf_8
|
abe62e53f393c56a2782e20e4e788092
|
function area = meshSurfaceArea(vertices, edges, faces)
%MESHSURFACEAREA Surface area of a polyhedral mesh
%
% S = meshSurfaceArea(V, F)
% S = meshSurfaceArea(V, E, F)
% Computes the surface area of the mesh specified by vertex array V and
% face array F. Vertex array is a NV-by-3 array of coordinates.
% Face array can be a NF-by-3 or NF-by-4 numeric array, or a Nf-by-1 cell
% array, containing vertex indices of each face.
%
% This functions iterates on faces, extract vertices of the current face,
% and computes the sum of face areas.
%
% This function assumes faces are coplanar and convex. If faces are all
% triangular, the function "trimeshSurfaceArea" should be more efficient.
%
%
% Example
% % compute the surface of a unit cube (should be equal to 6)
% [v f] = createCube;
% meshSurfaceArea(v, f)
% ans =
% 6
%
% See also
% meshes3d, trimeshSurfaceArea, meshVolume, meshFacePolygons,
% polygonArea3d
%
% ------
% Author: David Legland
% e-mail: [email protected]
% Created: 2010-10-13, using Matlab 7.9.0.529 (R2009b)
% Copyright 2010 INRA - Cepia Software Platform.
% check input number
if nargin == 2
faces = edges;
end
% pre-compute normals
normals = normalizeVector3d(faceNormal(vertices, faces));
% init accumulator
area = 0;
if isnumeric(faces)
% iterate on faces in a numeric array
for i = 1:size(faces, 1)
poly = vertices(faces(i, :), :);
area = area + polyArea3d(poly, normals(i,:));
end
else
% iterate on faces in a cell array
for i = 1:length(faces)
poly = vertices(faces{i}, :);
area = area + polyArea3d(poly, normals(i,:));
end
end
function a = polyArea3d(v, normal)
nv = size(v, 1);
v0 = repmat(v(1,:), nv, 1);
products = sum(cross(v-v0, v([2:end 1], :)-v0, 2), 1);
a = abs(dot(products, normal, 2))/2;
|
github
|
ZijingMao/baselineeegtest-master
|
mergeCoplanarFaces.m
|
.m
|
baselineeegtest-master/VisualizationFilters/geom3d/meshes3d/mergeCoplanarFaces.m
| 10,111 |
utf_8
|
28a4d5c9c038ed1d5250c1babe495a14
|
function varargout = mergeCoplanarFaces(nodes, varargin)
%MERGECOPLANARFACES Merge coplanar faces of a polyhedral mesh
%
% [NODES FACES] = mergeCoplanarFaces(NODES, FACES)
% [NODES EDGES FACES] = mergeCoplanarFaces(NODES, EDGES, FACES)
% NODES is a set of 3D points (as a nNodes-by-3 array),
% and FACES is one of:
% - a nFaces-by-X array containing vertex indices of each face, with each
% face having the same number of vertices,
% - a nFaces-by-1 cell array, each cell containing indices of a face.
% The function groups faces which are coplanar and contiguous, resulting
% in a "lighter" mesh. This can be useful for visualizing binary 3D
% images for example.
%
% FACES = mergeCoplanarFaces(..., PRECISION)
% Adjust the threshold for deciding if two faces are coplanar or
% parallel. Default value is 1e-5.
%
% Example
% [v e iFace] = createCube;
% figure; drawMesh(v, iFace); view(3); axis equal;
% [v2 f2] = mergeCoplanarFaces(v, iFace);
% figure; drawMesh(v, f2);
% view(3); axis equal; view(3);
%
% See also
% meshes3d, drawMesh, minConvexHull, triangulateFaces
%
% ------
% Author: David Legland
% e-mail: [email protected]
% Created: 2006-07-05
% Copyright 2006 INRA - CEPIA Nantes - MIAJ (Jouy-en-Josas).
% 20/07/2006 add tolerance for coplanarity test
% 21/08/2006 fix small bug due to difference of methods to test
% coplanaritity, sometimes resulting in 3 points of a face not coplanar !
% Also add control on precision
% 14/08/2007 rename minConvexHull->meshReduce, and extend to non convex
% shapes
% 2011-01-14 code clean up
% 2013-02-22 rename from meshReduce to mergeCoplanarFaces
%% Process input arguments
% set up precision
acc = 1e-5;
if ~isempty(varargin)
var = varargin{end};
if length(var) == 1
acc = var;
varargin(end) = [];
end
end
% extract faces and edges
if length(varargin) == 1
faces = varargin{1};
else
faces = varargin{2};
end
%% Initialisations
% number of faces
nNodes = size(nodes, 1);
nFaces = size(faces, 1);
% compute number of vertices of each face
Fn = ones(nFaces, 1) * size(faces, 2);
% compute normal of each faces
normals = faceNormal(nodes, faces);
% initialize empty faces and edges
faces2 = cell(0, 1);
edges2 = zeros(0, 2);
% Processing flag for each face
% 1: face to process, 0: already processed
% in the beginning, every triangle face need to be processed
flag = ones(nFaces, 1);
%% Main iteration
% iterate on each face
for iFace = 1:nFaces
% check if face was already performed
if ~flag(iFace)
continue;
end
% indices of faces with same normal
% ind = find(abs(vectorNorm3d(cross(repmat(normals(iFace, :), [nFaces 1]), normals)))<acc);
ind = find(vectorNorm3d(vectorCross3d(normals(iFace, :), normals)) < acc);
% keep only coplanar faces (test coplanarity of points in both face)
ind2 = false(size(ind));
for j = 1:length(ind)
ind2(j) = isCoplanar(nodes([faces(iFace,:) faces(ind(j),:)], :), acc);
end
ind2 = ind(ind2);
% compute edges of all faces in the plane
planeEdges = zeros(sum(Fn(ind2)), 2);
pos = 1;
for i = 1:length(ind2)
face = faces(ind2(i), :);
faceEdges = sort([face' face([2:end 1])'], 2);
planeEdges(pos:sum(Fn(ind2(1:i))), :) = faceEdges;
pos = sum(Fn(ind2(1:i)))+1;
end
planeEdges = unique(planeEdges, 'rows');
% relabel plane edges
[planeNodes, I, J] = unique(planeEdges(:)); %#ok<ASGLU>
planeEdges2 = reshape(J, size(planeEdges));
% The set of coplanar faces may not necessarily form a single connected
% component. The following computes label of each connected component.
component = grLabel(nodes(planeNodes, :), planeEdges2);
% compute degree (number of adjacent faces) of each edge.
Npe = size(planeEdges, 1);
edgeDegrees = zeros(Npe, 1);
for i = 1:length(ind2)
face = faces(ind2(i), :);
faceEdges = sort([face' face([2:end 1])'], 2);
for j = 1:size(faceEdges, 1)
indEdge = find(sum(ismember(planeEdges, faceEdges(j,:)),2)==2);
edgeDegrees(indEdge) = edgeDegrees(indEdge)+1;
end
end
% extract unique edges and nodes of the plane
planeEdges = planeEdges(edgeDegrees==1, :);
planeEdges2 = planeEdges2(edgeDegrees==1, :);
% find connected component of each edge
planeEdgesComp = zeros(size(planeEdges, 1), 1);
for iEdge = 1:size(planeEdges, 1)
planeEdgesComp(iEdge) = component(planeEdges2(iEdge, 1));
end
% iterate on connected faces
for c = 1:max(component)
% convert to chains of nodes
loops = graph2Contours(nodes, planeEdges(planeEdgesComp==c, :));
% add a simple Polygon for each loop
facePolygon = loops{1};
for l = 2:length(loops)
facePolygon = [facePolygon, NaN, loops{l}]; %#ok<AGROW>
end
faces2{length(faces2)+1, 1} = facePolygon;
% also add news edges
edges2 = unique([edges2; planeEdges], 'rows');
end
% mark processed faces
flag(ind2) = 0;
end
%% Additional processing on nodes
% select only nodes which appear in at least one edge
indNodes = unique(edges2(:));
% for each node, compute index of corresponding new node (or 0 if dropped)
refNodes = zeros(nNodes, 1);
for i = 1:length(indNodes)
refNodes(indNodes(i)) = i;
end
% changes indices of nodes in edges2 array
for i = 1:length(edges2(:))
edges2(i) = refNodes(edges2(i));
end
% changes indices of nodes in faces2 array
for iFace = 1:length(faces2)
face = faces2{iFace};
for i = 1:length(face)
if ~isnan(face(i))
face(i) = refNodes(face(i));
end
end
faces2{iFace} = face;
end
% keep only boundary nodes
nodes2 = nodes(indNodes, :);
%% Process output arguments
if nargout == 1
varargout{1} = faces2;
elseif nargout == 2
varargout{1} = nodes2;
varargout{2} = faces2;
elseif nargout == 3
varargout{1} = nodes2;
varargout{2} = edges2;
varargout{3} = faces2;
end
function labels = grLabel(nodes, edges)
%GRLABEL associate a label to each connected component of the graph
% LABELS = grLabel(NODES, EDGES)
% Returns an array with as many rows as the array NODES, containing index
% number of each connected component of the graph. If the graph is
% totally connected, returns an array of 1.
%
% Example
% nodes = rand(6, 2);
% edges = [1 2;1 3;4 6];
% labels = grLabel(nodes, edges);
% labels =
% 1
% 1
% 1
% 2
% 3
% 2
%
% See also
% getNeighbourNodes
%
%
% ------
% Author: David Legland
% e-mail: [email protected]
% Created: 2007-08-14, using Matlab 7.4.0.287 (R2007a)
% Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas.
% init
nNodes = size(nodes, 1);
labels = (1:nNodes)';
% iteration
modif = true;
while modif
modif = false;
for i=1:nNodes
neigh = getNeighbourNodes(i, edges);
neighLabels = labels([i;neigh]);
% check for a modification
if length(unique(neighLabels))>1
modif = true;
end
% put new labels
labels(ismember(labels, neighLabels)) = min(neighLabels);
end
end
% change to have fewer labels
labels2 = unique(labels);
for i = 1:length(labels2)
labels(labels==labels2(i)) = i;
end
function nodes2 = getNeighbourNodes(node, edges)
%GETNEIGHBOURNODES find nodes adjacent to a given node
%
% NEIGHS = getNeighbourNodes(NODE, EDGES)
% NODE: index of the node
% EDGES: the complete edges list
% NEIGHS: the nodes adjacent to the given node.
%
% NODE can also be a vector of node indices, in this case the result is
% the set of neighbors of any input node.
%
%
% -----
%
% author : David Legland
% INRA - TPV URPOI - BIA IMASTE
% created the 16/08/2004.
%
% HISTORY
% 10/02/2004 documentation
% 13/07/2004 faster algorithm
% 03/10/2007 can specify several input nodes
[i, j] = find(ismember(edges, node)); %#ok<NASGU>
nodes2 = edges(i,1:2);
nodes2 = unique(nodes2(:));
nodes2 = sort(nodes2(~ismember(nodes2, node)));
function curves = graph2Contours(nodes, edges) %#ok<INUSL>
%GRAPH2CONTOURS convert a graph to a set of contour curves
%
% CONTOURS = GRAPH2CONTOURS(NODES, EDGES)
% NODES, EDGES is a graph representation (type "help graph" for details)
% The algorithm assume every node has degree 2, and the set of edges
% forms only closed loops. The result is a list of indices arrays, each
% array containing consecutive point indices of a contour.
%
% To transform contours into drawable curves, please use :
% CURVES{i} = NODES(CONTOURS{i}, :);
%
%
% NOTE : contours are not oriented. To manage contour orientation, edges
% also need to be oriented. So we must precise generation of edges.
%
% -----
%
% author : David Legland
% INRA - TPV URPOI - BIA IMASTE
% created the 05/08/2004.
%
curves = {};
c = 0;
while size(edges,1)>0
% find first point of the curve
n0 = edges(1,1);
curve = n0;
% second point of the curve
n = edges(1,2);
e = 1;
while true
% add current point to the curve
curve = [curve n]; %#ok<AGROW>
% remove current edge from the list
edges = edges((1:size(edges,1))~=e,:);
% find index of edge containing reference to current node
e = find(edges(:,1)==n | edges(:,2)==n);
e = e(1);
% get index of next current node
% (this is the other node of the current edge)
if edges(e,1)==n
n = edges(e,2);
else
n = edges(e,1);
end
% if node is same as start node, loop is closed, and we stop
% node iteration.
if n==n0
break;
end
end
% remove the last edge of the curve from edge list.
edges = edges((1:size(edges,1))~=e,:);
% add the current curve to the list, and start a new curve
c = c+1;
curves{c} = curve; %#ok<AGROW>
end
|
github
|
ZijingMao/baselineeegtest-master
|
rocarea.m
|
.m
|
baselineeegtest-master/BaselineTest/XDBLDAUtility/Utilities/rocarea.m
| 2,034 |
utf_8
|
c5ed1630baa8d2de141052ed2c13dab4
|
% rocarea() - computes the area under the ROC curve
% If no output arguments are specified
% it will display an ROC curve with the
% Az and approximate fraction correct.
%
% Usage:
% >> [Az,tp,fp,fc]=rocarea(p,label);
%
% Inputs:
% p - classification output
% label - truth labels {0,1}
%
% Outputs:
% Az - Area under ROC curve
% tp - true positive rate
% fp - false positive rate
% fc - fraction correct
%
% Authors: Lucas Parra ([email protected], 2004)
% with Adam Gerson (reformatted for EEGLAB)
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2004 Lucas Parra
%
% 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 [Az,tp,fp,fc]=rocarea(p,label)
[tmp,indx]=sort(-p);
label = label>0;
Np=sum(label==1);
Nn=sum(label==0);
tp=0; pinc=1/Np;
fp=0; finc=1/Nn;
Az=0;
N=Np+Nn;
tp=zeros(N+1,1);
fp=zeros(N+1,1);
for i=1:N
tp(i+1)=tp(i)+label(indx(i))/Np;
fp(i+1)=fp(i)+(~label(indx(i)))/Nn;
Az = Az + (~label(indx(i)))*tp(i+1)/Nn;
end;
[m,i]=min(fp-tp);
fc = 1-mean([fp(i), 1-tp(i)]);
if nargout==0
plot(fp,tp); axis([0 1 0 1]); hold on
plot([0 1],[1 0],':'); hold off
xlabel('false positive rate')
ylabel('true positive rate')
title('ROC Curve'); axis([0 1 0 1]);
text(0.4,0.2,sprintf('Az = %.2f',Az))
text(0.4,0.1,sprintf('fc = %.2f',fc))
axis square
end
|
github
|
ZijingMao/baselineeegtest-master
|
logist.m
|
.m
|
baselineeegtest-master/BaselineTest/XDBLDAUtility/Utilities/logist.m
| 9,603 |
utf_8
|
e175ee099b786fea664b3f83b907a2f7
|
% logist() - Iterative recursive least squares algorithm for linear
% logistic model
%
% Usage:
% >> [v] = logist(x,y,vinit,show,regularize,lambda,lambdasearch,eigvalratio);
%
% Inputs:
% x - N input samples [N,D]
% y - N binary labels [N,1] {0,1}
%
% Optional parameters:
% vinit - initialization for faster convergence
% show - if>0 will show first two dimensions
% regularize - [1|0] -> [yes|no]
% lambda - regularization constant for weight decay. Makes
% logistic regression into a support vector machine
% for large lambda (cf. Clay Spence). Defaults to 10^-6.
% lambdasearch- [1|0] -> search for optimal regularization constant lambda
% eigvalratio - if the data does not fill D-dimensional space,
% i.e. rank(x)<D, you should specify a minimum
% eigenvalue ratio relative to the largest eigenvalue
% of the SVD. All dimensions with smaller eigenvalues
% will be eliminated prior to the discrimination.
%
% Outputs:
% v - v(1:D) normal to separating hyperplane. v(D+1) slope
%
% Compute probability of new samples with p = bernoull(1,[x 1]*v);
%
% References:
%
% @article{gerson2005,
% author = {Adam D. Gerson and Lucas C. Parra and Paul Sajda},
% title = {Cortical Origins of Response Time Variability
% During Rapid Discrimination of Visual Objects},
% journal = {{NeuroImage}},
% year = {in revision}}
%
% @article{parra2005,
% author = {Lucas C. Parra and Clay D. Spence and Paul Sajda},
% title = {Recipes for the Linear Analysis of {EEG}},
% journal = {{NeuroImage}},
% year = {in revision}}
%
% Authors: Adam Gerson ([email protected], 2004),
% with Lucas Parra ([email protected], 2004)
% and Paul Sajda (ps629@columbia,edu 2004)
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda
%
% 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 [v] = logist(x,y,v,show,regularize,lambda,lambdasearch,eigvalratio)
printoutput=0;
[N,D]=size(x);
iter=0; showcount=0;
if nargin<3 | isempty(v),
v=zeros(D,1);
vth=0;
else vth=v(D+1);
v=v(1:D);
end;
if nargin<4 | isempty(show);
show=0;
end;
if nargin<5 | isempty(regularize);
regularize=0;
end
if nargin<6 | isempty(lambda);
lambda=eps;
end;
if nargin<7 | isempty(lambdasearch),
lambdasearch=0;
end
if nargin<8 | isempty(eigvalratio);
eigvalratio=0;
end;
if regularize,
lambda=1e-6;
end
% subspace reduction if requested - electrodes might be linked
if eigvalratio
[U,S,V] = svd(x,0); % subspace analysis
V = V(:,find(diag(S)/S(1,1)>eigvalratio)); % keep significant subspace
x = x*V; % map the data to that subspace
v = V'*v; % reduce initialization to the subspace
[N,D]=size(x); % less dimensions now
end
% combine threshold computation with weight vector.
x = [x ones(N,1)];
v = [v; vth];
vold=ones(size(v));
if regularize,
lambda = [0.5*lambda*ones(1,D) 0]';
end
% clear warning as we will use it to catch conditioning problems
lastwarn('');
% If lambda increases, the maximum number of iterations is increased from
% maxiter to maxiterlambda
maxiter=100;
maxiterlambda=1000;
singularwarning=0;
lambdawarning=0; % Initialize warning flags
if show,
figure;
end
% IRLS for binary classification of experts (bernoulli distr.)
while ((subspace(vold,v)>1e-7)&(iter<=maxiter)& ...
(~singularwarning)&(~lambdawarning))|iter==0,
vold=v;
% this computes step 1. In the Parra paper referenced above, mu is what Parra called "p".
% mu is the estimate of y with the current weights v.
% p <- f(wT * X)
mu = bernoull(1,x*v); % recompute weights
% w and e values are used in the calculations in steps 2 and 3. In the
% Parra paper, w is what Parra called (p .* (1-p)). e is what Parra
% calls (d-p) -- this the error between the actual y and the estimate
% of y based on the current weights.
w = mu.*(1-mu);
e = (y - mu);
% this computes Step 2 (Gradient)
% g <- X * (d-p) - lambda * v
grad = x'*e; % - lambda .* v;
if regularize,
grad=grad - lambda .* v;
end
%inc = inv(x'*diag(w)*x+eps*eye(D+1)) * grad;
% this computes step 3 and the incremental part of 4. inc is equivalent
% to inv(H) * g in the Parra paper. This value is essentially the
% Newton Direction or Newton Step. Adding this to the vector of weights
% moves the weights towards minimizing the error of the fit.
% H <- X * diag(p.* (1-p)) * XT + lambda * I
% H^-1 * g
inc = inv(x' * (repmat(w,1,D+1).*x) + diag(lambda) * eye(D+1)) * grad;
if strncmp(lastwarn,'Matrix is close to singular or badly scaled.',44)
warning('Bad conditioning. Suggest reducing subspace.')
singularwarning=1;
end
if (norm(inc)>=1000)®ularize,
if ~lambdasearch, ...
warning('Data may be perfectly separable. Suggest increasing regularization constant lambda');
end
lambdawarning = 1;
end;
% avoid funny outliers that happen with inv
if (norm(inc) >= 1000)®ularize&lambdasearch,
% Increase regularization constant lambda
lambda = sign(lambda).*abs(lambda.^(1/1.02));
lambdawarning = 0;
if printoutput,
fprintf('Bad conditioning. Data may be perfectly separable. Increasing lambda to: %6.2f\n',lambda(1));
end
maxiter=maxiterlambda;
elseif (~singularwarning)&(~lambdawarning),
% update -- this completes step 4 in the Parra paper.
% w <- w + inv(H) * g;
v = v + inc;
if show
showcount=showcount+1;
subplot(1,2,1)
ax = [min(x(:,1)), max(x(:,1)), min(x(:,2)), max(x(:,2))];
hold off;
h(1)=plot(x(y>0,1),x(y>0,2),'bo');
hold on;
h(2)=plot(x(y<1,1),x(y<1,2),'r+');
xlabel('First Dimension','FontSize',14);
ylabel('Second Dimension','FontSize',14);
title('Discrimination Boundary','FontSize',14);
legend(h,'Dataset 1','Dataset 2');
axis square;
if norm(v)>0,
tmean=mean(x);
tmp = tmean;
tmp(1)=0;
t1=tmp;
t1(2)=ax(3);
t2=tmp;
t2(2)=ax(4);
xmin=median([ax(1), -(t1*v)/v(1), -(t2*v)/v(1)]);
xmax=median([ax(2), -(t1*v)/v(1), -(t2*v)/v(1)]);
tmp = tmean;
tmp(2)=0;
t1=tmp;
t1(1)=ax(1);
t2=tmp;
t2(1)=ax(2);
ymin=median([ax(3), -(t1*v)/v(2), -(t2*v)/v(2)]);
ymax=median([ax(4), -(t1*v)/v(2), -(t2*v)/v(2)]);
if v(1)*v(2)>0,
tmp=xmax;
xmax=xmin;
xmin=tmp;
end;
if ~(xmin<ax(1)|xmax > ax(2)|ymin < ax(3)|ymax > ax(4)),
h = plot([xmin xmax],[ymin ymax],'k','LineWidth',2);
end;
end;
subplot(1,2,2);
vnorm(showcount) = subspace(vold,v);
if vnorm(showcount) == 0,
vnorm(showcount)=nan;
end
plot(log(vnorm)/log(10));
title('Subspace between v(t) and v(t+1)','FontSize',14);
xlabel('Iteration','FontSize',14);
ylabel('Subspace','FontSize',14);
axis square;
drawnow;
end;
% exit if converged
if subspace(vold,v)<1e-7,
if printoutput,
disp(['Converged... ']);
disp(['Iterations: ' num2str(iter)]);
disp(['Subspace: ' num2str(subspace(vold,v))]);
disp(['Lambda: ' num2str(lambda(1))]);
end
end;
end
% exit if taking too long
iter=iter+1;
if iter>maxiter,
if printoutput,
disp(['Not converging after ' num2str(maxiter)' iterations.']);
disp(['Iterations: ' num2str(iter-1)]);
disp(['Subspace: ' num2str(subspace(vold,v))]);
disp(['Lambda: ' num2str(lambda(1))]);
end
end;
end;
if eigvalratio
v = [V*v(1:D);v(D+1)]; % the result should be in the original space
end
function [p]=bernoull(x,eta);
% bernoull() - Computes Bernoulli distribution of x
% for "natural parameter" eta.
%
% Usage:
% >> [p] = bernoull(x,eta)
%
% The mean m of a Bernoulli distributions relates to eta as,
% m = exp(eta)/(1+exp(eta));
p = exp(eta.*x - log(1+exp(eta)));
|
github
|
ZijingMao/baselineeegtest-master
|
LDAsimple.m
|
.m
|
baselineeegtest-master/BaselineTest/XDBLDAUtility/blda/LDAsimple.m
| 2,300 |
utf_8
|
b58ee004f29558ff0e923ce17fbe6102
|
% LDA - MATLAB subroutine to perform linear discriminant analysis
% by Will Dwinnell and Deniz Sevis
%
% Use:
% W = LDA(Input,Target,Priors)
%
% W = discovered linear coefficients (first column is the constants)
% Input = predictor data (variables in columns, observations in rows)
% Target = target variable (class labels)
% Priors = vector of prior probabilities (optional)
%
% Note: discriminant coefficients are stored in W in the order of unique(Target)
%
% Example:
%
% % Generate example data: 2 groups, of 10 and 15, respectively
% X = [randn(10,2); randn(15,2) + 1.5]; Y = [zeros(10,1); ones(15,1)];
%
% % Calculate linear discriminant coefficients
% W = LDA(X,Y);
%
% % Calulcate linear scores for training data
% L = [ones(25,1) X] * W';
%
% % Calculate class probabilities
% P = exp(L) ./ repmat(sum(exp(L),2),[1 2]);
%
%
% Last modified: Dec-11-2010
function W = LDAsimple(Input,Target,Priors)
% Determine size of input data
[n m] = size(Input);
% Discover and count unique class labels
ClassLabel = unique(Target);
k = length(ClassLabel);
% Initialize
nGroup = NaN(k,1); % Group counts
GroupMean = NaN(k,m); % Group sample means
PooledCov = zeros(m,m); % Pooled covariance
W = NaN(k,m+1); % model coefficients
if (nargin >= 3) PriorProb = Priors; end
% Loop over classes to perform intermediate calculations
for i = 1:k,
% Establish location and size of each class
Group = (Target == ClassLabel(i));
nGroup(i) = sum(double(Group));
% Calculate group mean vectors
GroupMean(i,:) = mean(Input(Group,:));
% Accumulate pooled covariance information
PooledCov = PooledCov + ((nGroup(i) - 1) / (n - k) ).* cov(Input(Group,:));
end
% Assign prior probabilities
if (nargin >= 3)
% Use the user-supplied priors
PriorProb = Priors;
else
% Use the sample probabilities
PriorProb = nGroup / n;
end
% Loop over classes to calculate linear discriminant coefficients
for i = 1:k,
% Intermediate calculation for efficiency
% This replaces: GroupMean(g,:) * inv(PooledCov)
Temp = GroupMean(i,:) / PooledCov;
% Constant
W(i,1) = -0.5 * Temp * GroupMean(i,:)' + log(PriorProb(i));
% Linear
W(i,2:end) = Temp;
end
% Housekeeping
clear Temp
end
% EOF
|
github
|
ZijingMao/baselineeegtest-master
|
mylasso.m
|
.m
|
baselineeegtest-master/Deconvolution/mylasso.m
| 57,431 |
utf_8
|
7247888eb5e7c928a60c6911143d2a0b
|
function [B,stats] = mylasso(x,y,distr,varargin)
%LASSOGLM Perform lasso or elastic net regularization for a generalized linear model.
% [B,STATS] = LASSOGLM(X,Y,DISTR,...) Performs L1-penalized maximum likelihood
% fits (lasso) relating the predictors in X to the responses in Y, or
% fits subject to joint L1- and L2 constraints (elastic net).
% The default is a lasso-style fit, that is, a maximum likelihood fit
% subject to a constraint on the L1-norm of the coefficients B.
%
% LASSOGLM accepts all the command line parameters of the LASSO function
% and it accepts command line parameters of the GLMFIT function, with
% the following exceptions. LASSOGLM also accepts the arguments 'Link'
% and 'Offset' of GLMFIT (they can also be lower case 'link' or 'offset').
% LASSOGLM It does not accept the argument 'estdisp' of GLMFIT, or the
% argument 'constant'. LASSOGLM does not calculate standard errors
% or covariances among the coefficients, as GLMFIT does.
% LASSOGLM always calculates an Intercept term.
%
% Positional parameters:
%
% X A numeric matrix (dimension, say, NxP)
% Y A numeric vector of length N. If DISTR is
% 'binomial', Y may be a binary vector indicating
% success/failure, and the total number of trials is
% taken to be 1 for all observations. If DISTR is
% 'binomial', Y may also be a two column matrix, the
% first column containing the number of successes for
% each observation, and the second column containing
% the total number of trials.
% DISTR The distributional family for the non-systematic
% variation in the responses. Acceptable values for DISTR are
% 'normal', 'binomial', 'poisson', 'gamma', and 'inverse gaussian'.
% By default, the distribution is fit using the canonical link
% corresponding to DISTR. Other link functions may be
% specified using the optional parameter 'link'.
%
% Optional input parameters:
%
% 'Weights' Observation weights. Must be a vector of non-negative
% values, of the same length as columns of X. At least
% two values must be positive. (default ones(N,1) or
% equivalently (1/N)*ones(N,1)).
% 'Alpha' Elastic net mixing value, or the relative balance
% between L2 and L1 penalty (default 1, range (0,1]).
% Alpha=1 ==> lasso, otherwise elastic net.
% Alpha near zero ==> nearly ridge regression.
% 'NumLambda' The number of lambda values to use, if the parameter
% 'Lambda' is not supplied (default 100). Ignored
% if 'Lambda' is supplied. LASSOGLM may return fewer
% fits than specified by 'NumLambda' if the deviance
% of the fits drops below a threshold percentage of
% the null deviance (deviance of the fit without
% any predictors X).
% 'LambdaRatio' Ratio between the minimum value and maximum value of
% lambda to generate, if the parameter "Lambda" is not
% supplied. Legal range is [0,1). Default is 0.0001.
% If 'LambdaRatio' is zero, LASSOGLM will generate its
% default sequence of lambda values but replace the
% smallest value in this sequence with the value zero.
% 'LambdaRatio' is ignored if 'Lambda' is supplied.
% 'Lambda' Lambda values. Will be returned in return argument
% STATS in ascending order. The default is to have
% LASSOGLM generate a sequence of lambda values, based
% on 'NumLambda' and 'LambdaRatio'. LASSOGLM will generate
% a sequence, based on the values in X and Y, such that
% the largest Lambda value is estimated to be just
% sufficient to produce all zero coefficients B.
% You may supply a vector of real, non-negative values
% of lambda for LASSOGLM to use, in place of its default
% sequence. If you supply a value for 'Lambda',
% 'NumLambda' and 'LambdaRatio' are ignored.
% 'DFmax' Maximum number of non-zero coefficients in the model.
% Can be useful with large numbers of predictors.
% Results only for lambda values that satisfy this
% degree of sparseness will be returned.
% 'Standardize' Whether to scale X prior to fitting the model
% sequence.
% 'RelTol' Convergence threshold for coordinate descent algorithm.
% The coordinate descent iterations will terminate
% when the relative change in the size of the
% estimated coefficients B drops below this threshold.
% Default: 1e-4. Legal range is (0,1).
% 'CV' If present, indicates the method used to compute Deviance.
% When 'CV' is a positive integer K, LASSOGLM uses K-fold
% cross-validation. Set 'CV' to a cross-validation
% partition, created using CVPARTITION, to use other
% forms of cross-validation. You cannot use a
% 'Leaveout' partition with LASSOGLM.
% When 'CV' is 'resubstitution', LASSOGLM uses X and Y
% both to fit the model and to estimate the deviance
% of the fitted model, without cross-validation.
% The default is 'resubstitution'.
% 'MCReps' A positive integer indicating the number of Monte-Carlo
% repetitions for cross-validation. The default value is 1.
% If 'CV' is 'resubstitution' or a cvpartition of type
% 'resubstitution', 'MCReps' must be 1. If 'CV' is a
% cvpartition of type 'holdout', then 'MCReps' must be
% greater than one.
% 'PredictorNames' A cell array of names for the predictor variables,
% in the order in which they appear in X.
% Default: {}
% 'Options' A structure that contains options specifying whether to
% conduct cross-validation evaluations in parallel, and
% options specifying how to use random numbers when computing
% cross validation partitions. This argument can be created
% by a call to STATSET. CROSSVAL uses the following fields:
% 'UseParallel'
% 'UseSubstreams'
% 'Streams'
% For information on these fields see PARALLELSTATS.
% NOTE: If supplied, 'Streams' must be of length one.
% 'Link' The link function to use in place of the canonical link.
% The link function defines the relationship f(mu) = x*b
% between the mean response mu and the linear combination of
% predictors x*b. Specify the link parameter value as one of
% - the text strings 'identity', 'log', 'logit', 'probit',
% 'comploglog', 'reciprocal', 'loglog', or
% - an exponent P defining the power link, mu = (x*b)^P
% for x*b > 0, or
% - a cell array of the form {FL FD FI}, containing three
% function handles, created using @, that define the link (FL),
% the derivative of the link (FD), and the inverse link (FI).
% 'Offset' A vector to use as an additional predictor variable, but
% with a coefficient value fixed at 1.0.
%
% Return values:
% B The fitted coefficients for each model.
% B will have dimension PxL, where
% P = size(X,2) is the number of predictors, and
% L = length(STATS.Lambda).
% STATS STATS is a struct that contains information about the
% sequence of model fits corresponding to the columns
% of B. STATS contains the following fields:
%
% 'Intercept' The intercept term for each model. Dimension 1xL.
% 'Lambda' The sequence of lambda penalties used, in ascending order.
% Dimension 1xL.
% 'Alpha' The elastic net mixing value that was used.
% 'DF' The number of nonzero coefficients in B for each
% value of lambda. Dimension 1xL.
% 'Deviance' The deviance of the fitted model for each value of
% lambda. If cross-validation was performed, the values
% for 'Deviance' represent the estimated expected
% deviance of the model applied to new data, as
% calculated by cross-validation. Otherwise,
% 'Deviance' is the deviance of the fitted model
% applied to the data used to perform the fit.
% Dimension 1xL.
%
% If cross-validation was performed, STATS also includes the following
% fields:
%
% 'SE' The standard error of 'Deviance' for each lambda, as
% calculated during cross-validation. Dimension 1xL.
% 'LambdaMinDeviance' The lambda value with minimum expected deviance, as
% calculated during cross-validation. Scalar.
% 'Lambda1SE' The largest lambda such that 'Deviance' is within
% one standard error of the minimum. Scalar.
% 'IndexMinDeviance' The index of Lambda with value LambdaMinMSE. Scalar.
% 'Index1SE' The index of Lambda with value Lambda1SE. Scalar.
%
% See also lassoPlot, lasso, ridge, parallelstats, glmfit.
% References:
% [1] Tibshirani, R. (1996) Regression shrinkage and selection
% via the lasso. Journal of the Royal Statistical Society,
% Series B, Vol 58, No. 1, pp. 267-288.
% [2] Zou, H. and T. Hastie. (2005) Regularization and variable
% selection via the elastic net. Journal of the Royal Statistical
% Society, Series B, Vol. 67, No. 2, pp. 301-320.
% [3] Friedman, J., R. Tibshirani, and T. Hastie. (2010) Regularization
% paths for generalized linear models via coordinate descent.
% Journal of Statistical Software, Vol 33, No. 1,
% http://www.jstatsoft.org/v33/i01.
% [4] Hastie, T., R. Tibshirani, and J. Friedman. (2008) The Elements
% of Statistical Learning, 2nd edition, Springer, New York.
% [5] Dobson, A.J. (2002) An Introduction to Generalized Linear
% Models, 2nd edition, Chapman&Hall/CRC Press.
% [6] McCullagh, P., and J.A. Nelder (1989) Generalized Linear
% Models, 2nd edition, Chapman&Hall/CRC Press.
% [7] Collett, D. (2003) Modelling Binary Data, 2nd edition,
% Chapman&Hall/CRC Press.
% Copyright 2011-2012 The MathWorks, Inc.
if nargin < 2
error(message('stats:lassoGlm:TooFewInputs'));
end
if nargin < 3 || isempty(distr), distr = 'normal'; end
paramNames = { 'link' 'offset' 'weights'};
paramDflts = {'canonical' [] []};
[link,offset,pwts,~,varargin] = ...
internal.stats.parseArgs(paramNames, paramDflts, varargin{:});
% Read in the optional parameters pertinent to regularization (eg, lasso)
LRdefault = 1e-4;
pnames = { 'alpha' 'numlambda' 'lambdaratio' 'lambda' ...
'dfmax' 'standardize' 'reltol' 'cv' 'mcreps' ...
'predictornames' 'options' };
dflts = { 1 100 LRdefault [] ...
[] true 1e-4 'resubstitution' 1 ...
{} []};
[alpha, nLambda, lambdaRatio, lambda, ...
dfmax, standardize, reltol, cvp, mcreps, predictorNames, parallelOptions] ...
= internal.stats.parseArgs(pnames, dflts, varargin{:});
if ~isempty(lambda)
userSuppliedLambda = true;
else
userSuppliedLambda = false;
end
% X a real 2D matrix
if ~ismatrix(x) || length(size(x)) ~= 2 || ~isreal(x)
error(message('stats:lassoGlm:XnotaReal2DMatrix'));
end
% We need at least two observations.
if isempty(x) || size(x,1) < 2
error(message('stats:lassoGlm:TooFewObservations'));
end
% Number of Predictors
P = size(x,2);
% Head off potential cruft in the command window.
wsIllConditioned2 = warning('off','stats:glmfit:IllConditioned');
cleanupIllConditioned2 = onCleanup(@() warning(wsIllConditioned2));
% Sanity checking on predictors, responses, weights and offset parameter,
% and removal of NaNs and Infs from same. Also, conversion of the
% two-column form of binomial response to a proportion.
[X, Y, offset, pwts, dataClass, nTrials, binomialTwoColumn] = ...
glmProcessData(x, y, distr, 'off', offset, pwts);
[~,sqrtvarFun,devFun,linkFun,dlinkFun,ilinkFun,link,mu,eta,muLims,isCanonical,dlinkFunCanonical] = ...
glmProcessDistrAndLink(Y,distr,link,'off',nTrials,dataClass);
[X,Y,pwts,nLambda,lambda,dfmax,cvp,mcreps,predictorNames,ever_active] = ...
processLassoParameters(X,Y,pwts,alpha,nLambda,lambdaRatio,lambda,dfmax, ...
standardize,reltol,cvp,mcreps,predictorNames);
% Compute the amount of penalty at which all coefficients shrink to zero.
[lambdaMax, nullDev, nullIntercept] = computeLambdaMax(X, Y, pwts, alpha, standardize, ...
distr, link, dlinkFun, offset, isCanonical, dlinkFunCanonical, devFun);
% If the command line did not provide a sequence of penalty terms,
% generate a sequence.
if isempty(lambda)
lambda = computeLambdaSequence(lambdaMax, nLambda, lambdaRatio, LRdefault);
end
% Also, to help control saturated fits with binomial outcomes,
% also alter the glmfit values for muLims
if strcmp(distr,'binomial')
muLims = [1.0e-5 1.0-1.0e-5];
end
% Will convert from lambda penalty matched to average log-likelihood
% per observation (which is what lasso uses) to an equivalent
% penalty for total log-likelihood (which is what glmIRLS uses.)
if isempty(pwts) && isscalar(nTrials)
totalWeight = size(X,1);
elseif ~isempty(pwts) && isscalar(nTrials)
totalWeight = sum(pwts);
elseif isempty(pwts) && ~isscalar(nTrials)
totalWeight = sum(nTrials);
else
totalWeight = sum(pwts .* nTrials);
end
% Convert lambda penalty to match total log-likelihood
lambda = lambda * totalWeight;
penalizedFitPartition = @(x,y,offset,pwts,n,wlsfit,b,active,mu,eta,sqrtvarFun) ...
glmIRLSwrapper(x,y,distr,offset,pwts,dataClass,n, ...
sqrtvarFun,linkFun,dlinkFun,ilinkFun,devFun,b,active,mu,muLims,wlsfit,nullDev,reltol);
penalizedFit = @(x,y,wlsfit,b,active,mu,eta) ...
penalizedFitPartition(x,y,offset,pwts',nTrials,wlsfit,b,active,mu,eta,sqrtvarFun);
[B,Intercept,lambda,deviance] = ...
lassoFit(X,Y,pwts,lambda,alpha,dfmax,standardize,reltol,lambdaMax*totalWeight,ever_active, ...
penalizedFit,mu,eta,dataClass,userSuppliedLambda,nullDev,nullIntercept);
% Store the number of non-zero coefficients for each lambda.
df = sum(B~=0,1);
% The struct 'stats' will comprise the second return argument.
% Put place holders for ever-present fields to avoid undefined references
% and to secure the order we want in the struct.
stats = struct();
stats.Intercept = [];
stats.Lambda = [];
stats.Alpha = alpha;
stats.DF = [];
stats.Deviance = [];
stats.PredictorNames = predictorNames;
% ---------------------------------------------------------
% If requested, use cross-validation to calculate
% Prediction Mean Squared Error for each lambda.
% ---------------------------------------------------------
if ~isequal(cvp,'resubstitution')
% Replace dfmax with P, the number of predictors supplied at the
% command line. dfmax might cause one fold to return empty values,
% because no lambda satisfies the dfmax criteria, while other folds
% return a numeric value. The lambda sequence has already been
% pruned by dfmax, if appropriate, in the call to lassoFit above.
cvfun = @(Xtrain,Ytrain,Xtest,Ytest) lassoFitAndPredict( ...
Xtrain,Ytrain,Xtest,Ytest, ...
lambda,alpha,P,standardize,reltol,ever_active, ...
penalizedFitPartition,distr,link,linkFun,dlinkFun,sqrtvarFun, ...
isCanonical, dlinkFunCanonical,devFun,dataClass);
weights = pwts;
if isempty(weights)
weights = nan(size(X,1),1);
end
if isempty(offset) || isequal(offset,0)
offset = nan(size(X,1),1);
end
if binomialTwoColumn
response = [nTrials Y];
else
response = Y;
end
cvDeviance = crossval(cvfun,[weights(:) offset(:) X],response, ...
'Partition',cvp,'Mcreps',mcreps,'Options',parallelOptions);
% Scale single-fold deviances up to estimate whole data set deviance
cvDeviance = bsxfun(@times,cvDeviance,repmat((size(X,1) ./ cvp.TestSize)', mcreps, 1));
deviance = mean(cvDeviance);
se = std(cvDeviance) / sqrt(size(cvDeviance,1));
minDeviance = min(deviance);
minIx = find(deviance == minDeviance,1);
lambdaMin = lambda(minIx);
minplus1 = deviance(minIx) + se(minIx);
seIx = find((deviance(1:minIx) <= minplus1),1,'first');
if isempty(seIx)
lambdaSE = [];
else
lambdaSE = lambda(seIx);
end
% Deposit cross-validation results in struct for return value.
stats.SE = se;
stats.LambdaMinDeviance = lambdaMin;
stats.Lambda1SE = lambdaSE;
stats.IndexMinDeviance = minIx;
stats.Index1SE = seIx;
% Convert key lambda values determined by cross-validation
% back to match average log-likelihood per observation.
stats.LambdaMinDeviance = stats.LambdaMinDeviance / totalWeight;
stats.Lambda1SE = stats.Lambda1SE / totalWeight;
end
% ------------------------------------------
% Order results by ascending lambda
% ------------------------------------------
nLambda = length(lambda);
reverseIndices = nLambda:-1:1;
lambda = lambda(reverseIndices);
lambda = reshape(lambda,1,nLambda);
B = B(:,reverseIndices);
Intercept = Intercept(reverseIndices);
df = df(reverseIndices);
deviance = deviance(reverseIndices);
if ~isequal(cvp,'resubstitution')
stats.SE = stats.SE(reverseIndices);
stats.IndexMinDeviance = nLambda - stats.IndexMinDeviance + 1;
stats.Index1SE = nLambda - stats.Index1SE + 1;
end
stats.Intercept = Intercept;
stats.Lambda = lambda;
stats.DF = df;
stats.Deviance = deviance;
% Convert lambda penalty back to match average deviance per observation.
stats.Lambda = stats.Lambda / totalWeight;
end %-main block
% ------------------------------------------
% SUBFUNCTIONS
% ------------------------------------------
% ===================================================
% startingVals()
% ===================================================
function mu = startingVals(distr,y,N)
% Find a starting value for the mean, avoiding boundary values
switch distr
case 'poisson'
mu = y + 0.25;
case 'binomial'
mu = (N .* y + 0.5) ./ (N + 1);
case {'gamma' 'inverse gaussian'}
mu = max(y, eps(class(y))); % somewhat arbitrary
otherwise
mu = y;
end
end %-startingVals
% ===================================================
% diagnoseSeparation()
% ===================================================
function diagnoseSeparation(eta,y,N)
% Compute sample proportions, sorted by increasing fitted value
[x,idx] = sort(eta);
if ~isscalar(N)
N = N(idx);
end
p = y(idx);
if all(p==p(1)) % all sample proportions are the same
return
end
if x(1)==x(end) % all fitted probabilities are the same
return
end
noFront = 0<p(1) && p(1)<1; % no "front" section as defined below
noEnd = 0<p(end) && p(end)<1; % no "end" section as defined below
if p(1)==p(end) || (noFront && noEnd)
% No potential for perfect separation if the ends match or neither
% end is perfect
return
end
% There is at least one observation potentially taking probability 0 or
% 1 at one end or the other with the data sorted by eta. We want to see
% if the data, sorted by eta (x) value, have this form:
% x(1)<=...<=x(A) < x(A+1)=...=x(B-1) < x(B)<=...<=x(n)
% with p(1)=...=p(A)=0 p(B)=...=p(n)=1
% or p(1)=...=p(A)=1 p(B)=...=p(n)=0
%
% This includes the possibilities:
% A+1=B - no middle section
% A=0 - no perfect fit at the front
% B=n+1 - no perfect fit at the end
dx = 100*max(eps(x(1)),eps(x(end)));
n = length(p);
if noFront
A = 0;
else
A = find(p~=p(1),1,'first')-1;
cutoff = x(A+1)-dx;
A = sum(x(1:A)<cutoff);
end
if noEnd
B = n+1;
else
B = find(p~=p(end),1,'last')+1;
cutoff = x(B-1)+dx;
B = (n+1) - sum(x(B:end)>cutoff);
end
if A+1<B-1
% There is a middle region with >1 point, see if x varies there
if x(B-1)-x(A+1)>dx
return
end
end
% We have perfect separation that can be defined by some middle point
if A+1==B
xmid = x(A) + 0.5*(x(B)-x(A));
else
xmid = x(A+1);
if isscalar(N)
pmid = mean(p(A+1:B-1));
else
pmid = sum(p(A+1:B-1).*N(A+1:B-1)) / sum(N(A+1:B-1));
end
end
% Create explanation part for the lower region, if any
if A>=1
explanation = sprintf('\n XB<%g: P=%g',xmid,p(1));
else
explanation = '';
end
% Add explanation part for the middle region, if any
if A+1<B
explanation = sprintf('%s\n XB=%g: P=%g',explanation,xmid,pmid);
end
% Add explanation part for the upper region, if any
if B<=n
explanation = sprintf('%s\n XB>%g: P=%g',explanation,xmid,p(end));
end
warning(message('stats:lassoGlm:PerfectSeparation', explanation));
end %-diagnoseSeparation()
% ===============================================
% glmProcessData()
% ===============================================
function [x, y, offset, pwts, dataClass, N, binomialTwoColumn] = ...
glmProcessData(x, y, distr, const, offset, pwts)
N = []; % needed only for binomial
binomialTwoColumn = false;
% Convert the two-column form of 'y', if supplied ('binomial' only).
if strcmp(distr,'binomial')
if size(y,2) == 1
% N will get set to 1 below
if any(y < 0 | y > 1)
error(message('stats:lassoGlm:BadDataBinomialFormat'));
end
elseif size(y,2) == 2
binomialTwoColumn = true;
y(y(:,2)==0,2) = NaN;
N = y(:,2);
y = y(:,1) ./ N;
if any(y < 0 | y > 1)
error(message('stats:lassoGlm:BadDataBinomialRange'));
end
else
error(message('stats:lassoGlm:MatrixOrBernoulliRequired'));
end
end
[anybad,~,y,x,offset,pwts,N] = dfswitchyard('statremovenan',y,x,offset,pwts,N);
if anybad > 0
switch anybad
case 2
error(message('stats:lassoGlm:InputSizeMismatchX'))
case 3
error(message('stats:lassoGlm:InputSizeMismatchOffset'))
case 4
error(message('stats:lassoGlm:InputSizeMismatchPWTS'))
end
end
% Extra screening for lassoglm (Infs and zero weights)
okrows = all(isfinite(x),2) & all(isfinite(y),2) & all(isfinite(offset));
if ~isempty(pwts)
% This screen works on weights prior to stripping NaNs and Infs.
if ~isvector(pwts) || ~isreal(pwts) || size(x,1) ~= length(pwts) || ...
~all(isfinite(pwts)) || any(pwts<0)
error(message('stats:lassoGlm:InvalidObservationWeights'));
end
okrows = okrows & pwts(:)>0;
pwts = pwts(okrows);
end
% We need at least two observations after stripping NaNs and Infs and zero weights.
if sum(okrows)<2
error(message('stats:lassoGlm:TooFewObservationsAfterNaNs'));
end
% Remove observations with Infs in the predictor or response
% or with zero observation weight. NaNs were already gone.
x = x(okrows,:);
y = y(okrows);
if ~isempty(N) && ~isscalar(N)
N = N(okrows);
end
if ~isempty(offset)
offset = offset(okrows);
end
if isequal(const,'on')
x = [ones(size(x,1),1) x];
end
dataClass = superiorfloat(x,y);
x = cast(x,dataClass);
y = cast(y,dataClass);
if isempty(offset), offset = 0; end
if isempty(N), N = 1; end
end %-glmProcessData()
% ===================================================
% processLassoParameters()
% ===================================================
function [X,Y,weights,nLambda,lambda,dfmax,cvp,mcreps,predictorNames,ever_active] = ...
processLassoParameters(X,Y,weights, alpha, nLambda, lambdaRatio, lambda, dfmax, ...
standardize, reltol, cvp, mcreps, predictorNames)
% === 'Weights' parameter ===
if ~isempty(weights)
% Computations expect that weights is a row vector.
weights = weights(:)';
end
[~,P] = size(X);
% If X has any constant columns, we want to exclude them from the
% coordinate descent calculations. The corresponding coefficients
% will be returned as zero.
constantPredictors = (range(X)==0);
ever_active = ~constantPredictors;
% === 'Alpha' parameter ===
% Require 0 < alpha <= 1.
% "0" would correspond to ridge, "1" is lasso.
if ~isscalar(alpha) || ~isreal(alpha) || ~isfinite(alpha) || ...
alpha <= 0 || alpha > 1
error(message('stats:lassoGlm:InvalidAlpha'))
end
% === 'Standardize' option ===
% Require a logical value.
if ~isscalar(standardize) || (~islogical(standardize) && standardize~=0 && standardize~=1)
error(message('stats:lassoGlm:InvalidStandardize'))
end
% === 'Lambda' sequence or 'NumLambda' and 'lambdaRatio' ===
if ~isempty(lambda)
% Sanity check on user-supplied lambda sequence. Should be non-neg real.
if ~isreal(lambda) || any(lambda < 0)
error(message('stats:lassoGlm:NegativeLambda'));
end
lambda = sort(lambda(:),1,'descend');
else
% Sanity-check of 'NumLambda', should be positive integer.
if ~isreal(nLambda) || ~isfinite(nLambda) || nLambda < 1
error(message('stats:lassoGlm:InvalidNumLambda'));
else
nLambda = floor(nLambda);
end
% Sanity-checking of LambdaRatio, should be in [0,1).
if ~isreal(lambdaRatio) || lambdaRatio <0 || lambdaRatio >= 1
error(message('stats:lassoGlm:InvalidLambdaRatio'));
end
end
% === 'RelTol' parameter ===
%
if ~isscalar(reltol) || ~isreal(reltol) || ~isfinite(reltol) || reltol <= 0 || reltol >= 1
error(message('stats:lassoGlm:InvalidRelTol'));
end
% === 'DFmax' parameter ===
%
% DFmax is #non-zero coefficients
% DFmax should map to an integer in [1,P] but we truncate if .gt. P
%
if isempty(dfmax)
dfmax = P;
else
if ~isscalar(dfmax)
error(message('stats:lassoGlm:DFmaxBadType'));
end
try
dfmax = uint32(dfmax);
catch ME
mm = message('stats:lassoGlm:DFmaxBadType');
throwAsCaller(MException(mm.Identifier,'%s',getString(mm)));
end
if dfmax < 1
error(message('stats:lassoGlm:DFmaxNotAnIndex'));
else
dfmax = min(dfmax,P);
end
end
% === 'Mcreps' parameter ===
%
if ~isscalar(mcreps) || ~isreal(mcreps) || ~isfinite(mcreps) || mcreps < 1
error(message('stats:lassoGlm:MCRepsBadType'));
end
mcreps = fix(mcreps);
% === 'CV' parameter ===
%
if isnumeric(cvp) && isscalar(cvp) && (cvp==round(cvp)) && (0<cvp)
% cvp is a kfold value. It will be passed as such to crossval.
if (cvp>size(X,1))
error(message('stats:lassoGlm:InvalidCVforX'));
end
cvp = cvpartition(size(X,1),'Kfold',cvp);
elseif isa(cvp,'cvpartition')
if strcmpi(cvp.Type,'resubstitution')
cvp = 'resubstitution';
elseif strcmpi(cvp.Type,'leaveout')
error(message('stats:lassoGlm:InvalidCVtype'));
elseif strcmpi(cvp.Type,'holdout') && mcreps<=1
error(message('stats:lassoGlm:InvalidMCReps'));
end
elseif strncmpi(cvp,'resubstitution',length(cvp))
% This may have been set as the default, or may have been
% provided at the command line. In case it's the latter, we
% expand abbreviations.
cvp = 'resubstitution';
else
error(message('stats:lassoGlm:InvalidCVtype'));
end
if strcmp(cvp,'resubstitution') && mcreps ~= 1
error(message('stats:lassoGlm:InvalidMCReps'));
end
if isa(cvp,'cvpartition')
if (cvp.N ~= size(X,1)) || (min(cvp.TrainSize) < 2)
% We need partitions that match the total number of observations
% (after stripping NaNs and Infs and zero observation weights), and
% we need training sets with at least 2 usable observations.
error(message('stats:lassoGlm:TooFewObservationsForCrossval'));
end
end
% === 'PredictorNames' parameter ===
%
% If PredictorNames is not supplied or is supplied as empty, we just
% leave it that way. Otherwise, confirm that it is a cell array of strings.
%
if ~isempty(predictorNames)
if ~iscellstr(predictorNames) || length(predictorNames(:)) ~= size(X,2)
error(message('stats:lassoGlm:InvalidPredictorNames'));
else
predictorNames = predictorNames(:)';
end
end
end %-processLassoParameters()
% ===================================================
% glmProcessDistrAndLink()
% ===================================================
function [estdisp,sqrtvarFun,devFun,linkFun,dlinkFun,ilinkFun,link,mu,eta,muLims,...
isCanonical,dlinkFunCanonical] = ...
glmProcessDistrAndLink(y,distr,link,estdisp,N,dataClass)
switch distr
case 'normal'
canonicalLink = 'identity';
case 'binomial'
canonicalLink = 'logit';
case 'poisson'
canonicalLink = 'log';
case 'gamma'
canonicalLink = 'reciprocal';
case 'inverse gaussian'
canonicalLink = -2;
end
if isequal(link, 'canonical'), link = canonicalLink; end
switch distr
case 'normal'
sqrtvarFun = @(mu) ones(size(mu));
devFun = @(mu,y) (y - mu).^2;
estdisp = 'on';
case 'binomial'
sqrtN = sqrt(N);
sqrtvarFun = @(mu) sqrt(mu).*sqrt(1-mu) ./ sqrtN;
devFun = @(mu,y) 2*N.*(y.*log((y+(y==0))./mu) + (1-y).*log((1-y+(y==1))./(1-mu)));
case 'poisson'
if any(y < 0)
error(message('stats:lassoGlm:BadDataPoisson'));
end
sqrtvarFun = @(mu) sqrt(mu);
devFun = @(mu,y) 2*(y .* (log((y+(y==0)) ./ mu)) - (y - mu));
case 'gamma'
if any(y <= 0)
error(message('stats:lassoGlm:BadDataGamma'));
end
sqrtvarFun = @(mu) mu;
devFun = @(mu,y) 2*(-log(y ./ mu) + (y - mu) ./ mu);
estdisp = 'on';
case 'inverse gaussian'
if any(y <= 0)
error(message('stats:lassoGlm:BadDataInvGamma'));
end
sqrtvarFun = @(mu) mu.^(3/2);
devFun = @(mu,y) ((y - mu)./mu).^2 ./ y;
estdisp = 'on';
otherwise
error(message('stats:lassoGlm:BadDistribution'));
end
% Instantiate functions for one of the canned links, or validate a
% user-defined link specification.
[linkFun,dlinkFun,ilinkFun] = dfswitchyard('stattestlink',link,dataClass);
% Initialize mu and eta from y.
mu = startingVals(distr,y,N);
eta = linkFun(mu);
% Enforce limits on mu to guard against an inverse link that doesn't map into
% the support of the distribution.
switch distr
case 'binomial'
% mu is a probability, so order one is the natural scale, and eps is a
% reasonable lower limit on that scale (plus it's symmetric).
muLims = [eps(dataClass) 1-eps(dataClass)];
case {'poisson' 'gamma' 'inverse gaussian'}
% Here we don't know the natural scale for mu, so make the lower limit
% small. This choice keeps mu^4 from underflowing. No upper limit.
muLims = realmin(dataClass).^.25;
otherwise
muLims = [];
end
% These two quantities (isCanonical, dlinkFunCanonical) are not used by
% glmfit but they are needed for calculation of lambdaMax in lassoglm.
isCanonical = isequal(link, canonicalLink);
[~, dlinkFunCanonical] = dfswitchyard('stattestlink', canonicalLink, dataClass);
end %-glmProcessDistrAndLink()
% ===================================================
% glmIRLS()
% ===================================================
function [b,mu,eta,varargout] = glmIRLS(x,y,distr,offset,pwts,dataClass,N, ...
sqrtvarFun,linkFun,dlinkFun,ilinkFun,b,active,mu,muLims, ...
wlsfit,nullDev,devFun,reltol)
wsIterationLimit = warning('off','stats:lassoGlm:IterationLimit');
wsPerfectSeparation = warning('off','stats:lassoGlm:PerfectSeparation');
wsBadScaling = warning('off','stats:lassoGlm:BadScaling');
cleanupIterationLimit = onCleanup(@() warning(wsIterationLimit));
cleanupPerfectSeparation = onCleanup(@() warning(wsPerfectSeparation));
cleanupBadScaling = onCleanup(@() warning(wsBadScaling));
if isempty(pwts)
pwts = 1;
end
% Set up for iterations
iter = 0;
iterLim = 100;
warned = false;
seps = sqrt(eps);
% Match the convergence tolerance for the IRLS algorithm to the
% command line parameter 'RelTol'.
convcrit = max(1e-6,2*reltol);
eta = linkFun(mu);
while iter <= iterLim
iter = iter+1;
% Compute adjusted dependent variable for least squares fit
deta = dlinkFun(mu);
z = eta + (y - mu) .* deta;
% Compute IRLS weights the inverse of the variance function
sqrtw = sqrt(pwts) ./ (abs(deta) .* sqrtvarFun(mu));
% If the weights have an enormous range, we won't be able to do IRLS very
% well. The prior weights may be bad, or the fitted mu's may have too
% wide a range, which is probably because the data do as well, or because
% the link function is trying to go outside the distribution's support.
wtol = max(sqrtw)*eps(dataClass)^(2/3);
t = (sqrtw < wtol);
if any(t)
t = t & (sqrtw ~= 0);
if any(t)
sqrtw(t) = wtol;
if ~warned
warning(message('stats:lassoGlm:BadScaling'));
end
warned = true;
end
end
b_old = b;
[b,active] = wlsfit(z - offset, x, sqrtw.^2, b, active);
% Form current linear predictor, including offset
eta = offset + x * b;
% Compute predicted mean using inverse link function
mu = ilinkFun(eta);
% Force mean in bounds, in case the link function is a wacky choice
switch distr
case 'binomial'
if any(mu < muLims(1) | muLims(2) < mu)
mu = max(min(mu,muLims(2)),muLims(1));
end
case {'poisson' 'gamma' 'inverse gaussian'}
if any(mu < muLims(1))
mu = max(mu,muLims(1));
end
end
% Check stopping conditions
% Convergence of the coefficients
if (~any(abs(b-b_old) > convcrit * max(seps, abs(b_old))))
break;
end
% Proportion of explained deviance explained
if sum(devFun(mu,y)) < (1.0e-3 * nullDev)
break;
end
end
if iter > iterLim
warning(message('stats:lassoGlm:IterationLimit'));
end
if iter>iterLim && isequal(distr,'binomial')
diagnoseSeparation(eta,y,N);
end
varargout{1} = active;
end %-glmIRLS
% ===================================================
% glmIRLSwrapper()
% ===================================================
function [B,active,varargout] = glmIRLSwrapper(X,Y,distr,offset,pwts,dataClass,N, ...
sqrtvarFun,linkFun,dlinkFun,ilinkFun,devFun,b,active,mu,muLims, ...
wlsfit,nullDev,reltol)
% glmIRLSwrapper is a utility function for regularized GLM. It is called by
% the regularization framework (lassoFit()), and adapts to the conventions
% and expectations of the IRLS implementation for GLM.
%
% Lasso always returns an intercept, but lassoFit passes in the predictor
% matrix 'X' without a column of ones. Unlike OLS, GLM cannot calve off
% estimation of the predictor variable coefficients and calculate the
% intercept externally, post-fit. This is because each IRLS step
% computes a local linear predictor (eta), and this requires an
% intercept contribution. Therefore, prepend a column of ones before
% passing to glmIRLS. The variable B returned by glmIRLS will include
% the intercept term as the first element of B.
X = [ones(size(X,1),1) X];
% glmIRLS assumes pwts=1 if no observation weights were supplied,
% rather than empty, which is what lassoFit will feed in.
if isempty(pwts), pwts=1; end
[B,mu,eta,active] = glmIRLS(X,Y,distr,offset,pwts,dataClass,N, ...
sqrtvarFun,linkFun,dlinkFun,ilinkFun,b,active,mu,muLims, ...
wlsfit,nullDev,devFun,reltol);
deviance = sum(pwts.* devFun(mu,Y));
% Pull the intercept estimate out of B and return separately.
Intercept = B(1);
B = B(2:end);
extras.Intercept = Intercept;
extras.Deviance = deviance;
varargout{1} = extras;
varargout{2} = mu;
varargout{3} = eta;
end %-glmIRLSwrapper
% ===================================================
% lassoFitAndPredict()
% ===================================================
function dev = lassoFitAndPredict(Xtrain,Ytrain,Xtest,Ytest, ...
lambda,alpha,dfmax,standardize,reltol,ever_active, ...
penalizedFitPartition,distr,link,linkFun,dlinkFun,sqrtvarFun, ...
isCanonical, dlinkFunCanonical,devFun,dataClass)
%
% This function sets up the conditions for lasso fit and prediction from
% within crossvalidation. It defines quantities as necessary for the
% current fold.
trainWeights = Xtrain(:,1);
% To conform with crossval syntax, weights are prepended to the predictor
% matrix. Empty weights are temporarily converted to a vector of NaNs.
% This clause restores them to empty. Same occurs below for test weights.
if any(isnan(trainWeights))
trainWeights = [];
end
trainOffset = Xtrain(:,2);
if any(isnan(trainOffset))
trainOffset = 0;
end
Xtrain = Xtrain(:,3:end);
if size(Ytrain,2) == 2
trainN = Ytrain(:,1);
Ytrain = Ytrain(:,2);
else
trainN = 1;
end
% These quantities depend on the particular set of responses used for the fit.
% Within crossval, we work with a subset of the original data. Therefore,
% these quantities must be redefined on each invocation.
mu = startingVals(distr,Ytrain,trainN);
eta = linkFun(mu);
if isequal(distr,'binomial')
sqrtvarFun = @(mu) sqrt(mu).*sqrt(1-mu) ./ sqrt(trainN);
devFun = @(mu,y) 2*trainN.*(y.*log((y+(y==0))./mu) + (1-y).*log((1-y+(y==1))./(1-mu)));
end
penalizedFit = @(x,y,wlsfit,b,active,mu,eta) penalizedFitPartition(x,y, ...
trainOffset,trainWeights,trainN,wlsfit,b,active,mu,eta,sqrtvarFun);
[lambdaMax, nullDev, nullIntercept] = computeLambdaMax(Xtrain, Ytrain, trainWeights, ...
alpha, standardize, distr, link, dlinkFun, trainOffset, isCanonical, dlinkFunCanonical, devFun);
% Will convert from lambda penalty matched to average log-likelihood
% per observation (which is what lasso uses) to an equivalent
% penalty for total log-likelihood (which is what glmIRLS uses.)
if isempty(trainWeights) && isscalar(trainN)
totalWeight = size(Xtrain,1);
elseif ~isempty(trainWeights) && isscalar(trainN)
totalWeight = sum(trainWeights);
elseif isempty(trainWeights) && ~isscalar(trainN)
totalWeight = sum(trainN);
else
totalWeight = sum(trainWeights .* trainN);
end
lambdaMax = lambdaMax * totalWeight;
[B,Intercept] = lassoFit(Xtrain,Ytrain, ...
trainWeights,lambda,alpha,dfmax,standardize,reltol, ...
lambdaMax,ever_active,penalizedFit,mu,eta,dataClass,true,nullDev,nullIntercept);
Bplus = [Intercept; B];
testWeights = Xtest(:,1);
if any(isnan(testWeights))
testWeights = ones(size(Xtest,1),1);
end
testOffset = Xtest(:,2);
if any(isnan(testOffset))
testOffset = 0;
end
Xtest = Xtest(:,3:end);
if size(Ytest,2) == 2
testN = Ytest(:,1);
Ytest = Ytest(:,2);
else
testN = 1;
end
% For binomial with two-column form of response, the deviance function
% depends on the number of trials for each observation, which is provided
% in testN. Within crossval, the test set is a subset of the original data.
% Therefore, the deviance function needs to be redefined for each test set.
if isequal(distr,'binomial')
devFun = @(mu,y) 2*testN.*(y.*log((y+(y==0))./mu) + (1-y).*log((1-y+(y==1))./(1-mu)));
end
numFits = size(Bplus,2);
dev = zeros(1,numFits);
for i=1:numFits
if ~isequal(testOffset,0)
mu = glmval(Bplus(:,i), Xtest, link, 'Offset',testOffset);
else
mu = glmval(Bplus(:,i), Xtest, link);
end
di = devFun(mu,Ytest);
dev(i) = sum(testWeights' * di);
end
end %-lassoFitAndPredict
% ===================================================
% lassoFit()
% ===================================================
function [B,Intercept,lambda,varargout] = ...
lassoFit(X,Y,weights,lambda,alpha,dfmax,standardize,reltol, ...
lambdaMax,ever_active,penalizedFit,mu,eta,dataClass,userSuppliedLambda,nullDev,nullIntercept)
%
% ------------------------------------------------------
% Perform model fit for each lambda and the given alpha
% ------------------------------------------------------
regressionType = 'GLM';
[~,P] = size(X);
nLambda = length(lambda);
% If X has any constant columns, we want to exclude them from the
% coordinate descent calculations. The corresponding coefficients
% will be returned as zero.
constantPredictors = (range(X)==0);
ever_active = ever_active & ~constantPredictors;
% === weights and standardization ===
%
observationWeights = ~isempty(weights);
if ~isempty(weights)
observationWeights = true;
weights = weights(:)';
% Normalize weights up front.
weights = weights / sum(weights);
end
if standardize
if ~observationWeights
% Center and scale
[X0,muX,sigmaX] = zscore(X);
% Avoid divide by zero with constant predictors
sigmaX(constantPredictors) = 1;
else
% Weighted center and scale
muX = weights*X;
X0 = bsxfun(@minus,X,muX);
sigmaX = sqrt( weights*(X0.^2) );
% Avoid divide by zero with constant predictors
sigmaX(constantPredictors) = 1;
X0 = bsxfun(@rdivide, X0, sigmaX);
end
else
switch regressionType
case 'OLS'
if ~observationWeights
% Center
muX = mean(X,1);
X0 = bsxfun(@minus,X,muX);
sigmaX = 1;
else
% Weighted center
muX = weights*X;
X0 = bsxfun(@minus,X,muX);
sigmaX = 1;
end
case 'GLM'
X0 = X;
% For GLM don't center until we get inside the IRLS
sigmaX = 1;
muX = zeros(1,size(X,2));
end
end
% For OLS, Y is centered, for GLM it is not.
switch regressionType
case 'OLS'
if ~observationWeights
muY = mean(Y);
else
muY = weights*Y;
end
Y0 = bsxfun(@minus,Y,muY);
case 'GLM'
Y0 = Y;
end
% Preallocate the returned matrix of coefficients, B,
% and other variables sized to nLambda.
B = zeros(P,nLambda);
b = zeros(P,1,dataClass);
if nLambda > 0
Extras(nLambda) = struct('Intercept', nullIntercept, 'Deviance', nullDev);
for i=1:nLambda-1, Extras(i) = Extras(nLambda); end
intercept = nullIntercept;
end
active = false(1,P);
for i = 1:nLambda
lam = lambda(i);
if lam >= lambdaMax
continue;
end
% This anonymous function adapts the conventions of the IRLS algorithm
% for glm fit to the coordinate descent algorithm for penalized WLS,
% which is used within the IRLS algorithm.
wlsfit = @(x,y,weights,b,active) glmPenalizedWlsWrapper(y,x,b,active,weights,lam, ...
alpha,reltol,ever_active);
[b,active,extras,mu,eta] = penalizedFit(X0,Y0,wlsfit,[intercept;b],active,mu,eta);
B(:,i) = b;
Extras(i) = extras;
% Halt if maximum model size ('DFmax') has been met or exceeded.
if sum(active) > dfmax
% truncate B and lambda output arguments
lambda = lambda(1:(i-1));
B = B(:,1:(i-1));
Extras = Extras(:,1:(i-1));
break
end
% Halt if we have exceeded a threshold on the percent of
% null deviance left unexplained.
if ~(userSuppliedLambda || isempty(nullDev))
if extras.Deviance < 1.0e-3 * nullDev
lambda = lambda(1:i);
B = B(:,1:i);
Extras = Extras(:,1:i);
break
end
end
end % of lambda sequence
% ------------------------------------------
% Unwind the centering and scaling (if any)
% ------------------------------------------
B = bsxfun(@rdivide, B, sigmaX');
B(~ever_active,:) = 0;
switch regressionType
case 'OLS'
Intercept = muY-muX*B;
case 'GLM'
Intercept = zeros(1,length(lambda));
for i=1:length(lambda)
Intercept(i) = Extras(i).Intercept;
end
if isempty(lambda)
Intercept = [];
else
Intercept = Intercept - muX*B;
end
end
% ------------------------------------------
% Calculate Mean Prediction Squared Error (or other GoF)
% ------------------------------------------
switch regressionType
case 'OLS'
Intercept = muY-muX*B;
BwithI = [Intercept; B];
fits = [ones(size(X,1),1) X]*BwithI;
residuals = bsxfun(@minus, Y, fits);
if ~observationWeights
mspe = mean(residuals.^2);
else
% This line relies on the weights having been normalized.
mspe = weights * (residuals.^2);
end
varargout{1} = mspe;
case 'GLM'
deviance = zeros(1,length(lambda));
for i=1:length(lambda)
deviance(i) = Extras(i).Deviance;
end
if isempty(lambda)
deviance = [];
end
varargout{1} = deviance;
end
end %-lassoFit
% ===================================================
% thresholdScreen()
% ===================================================
function potentially_active = thresholdScreen(X0, wX0, Y0, ...
b, active, threshold)
r = Y0 - X0(:,active)*b(active,:);
% We don't need the (b.*wX2)' term that one might expect, because it
% is zero for the inactive predictors.
potentially_active = abs(r' *wX0) > threshold;
end %-thresholdScreen
% ===================================================
% cdescentCycleNewCandidates()
% ===================================================
function [b,active,wX2,wX2calculated,shrinkFactor] = ...
cdescentCycleNewCandidates(X0, weights, wX0, wX2, wX2calculated, Y0, ...
b, active, shrinkFactor, threshold, candidates)
%
r = Y0 - X0(:,active)*b(active,:);
bold = b;
for j=find(candidates);
% Regress j-th partial residuals on j-th predictor
bj = wX0(:,j)' * r;
margin = abs(bj) - threshold;
% Soft thresholding
if margin > 0
if ~wX2calculated(j)
wX2(j) = weights * X0(:,j).^2;
wX2calculated(j) = true;
shrinkFactor(j) = wX2(j) + shrinkFactor(j);
end
b(j) = sign(bj) .* margin ./ shrinkFactor(j);
active(j) = true;
end
r = r - X0(:,j)*(b(j)-bold(j));
end
end %-cdescentCycleNewCandidates
% ===================================================
% cdescentCycleNoRecalc()
% ===================================================
function [b,active] = ...
cdescentCycleNoRecalc(X0, wX0, wX2, Y0, b, active, shrinkFactor, threshold)
%
r = Y0 - X0(:,active)*b(active,:);
bwX2 = b.*wX2;
bold = b;
for j=find(active);
% Regress j-th partial residuals on j-th predictor
bj = wX0(:,j)' * r + bwX2(j);
margin = abs(bj) - threshold;
% Soft thresholding
if margin > 0
b(j) = sign(bj) .* margin ./ shrinkFactor(j);
else
b(j) = 0;
active(j) = false;
end
r = r - X0(:,j)*(b(j)-bold(j));
end
end %-cdescentCycleNoRecalc
% ===================================================
% penalizedWls()
% ===================================================
function [b,varargout] = ...
penalizedWls(X,Y,b,active,weights,lambda,alpha,reltol)
weights = weights(:)';
[~,P] = size(X);
wX = bsxfun(@times,X,weights');
wX2 = zeros(P,1);
wX2(active) = (weights * X(:,active).^2)';
wX2calculated = active;
threshold = lambda * alpha;
shrinkFactor = wX2 + lambda * (1-alpha);
% Iterative coordinate descent until converged
while true
bold = b;
old_active = active;
[b,active] = cdescentCycleNoRecalc(X,wX,wX2,Y, b,active,shrinkFactor,threshold);
if ~any( abs(b(old_active) - bold(old_active)) > reltol * max(1.0,abs(bold(old_active))) )
% Cycling over the active set converged.
% Do one full pass through the predictors.
% If there is no predictor added to the active set, we're done.
% Otherwise, resume the coordinate descent iterations.
bold = b;
potentially_active = thresholdScreen(X,wX,Y,b,active,threshold);
new_candidates = potentially_active & ~active;
if any(new_candidates)
[b,new_active,wX2,wX2calculated,shrinkFactor] = ...
cdescentCycleNewCandidates(X,weights,wX,wX2,wX2calculated,Y, ...
b,active,shrinkFactor,threshold,new_candidates);
else
new_active = active;
end
if isequal(new_active, active)
break
else
super_active = active | new_active;
if ~any( abs(b(super_active) - bold(super_active)) > reltol * max(1.0,abs(bold(super_active))) )
% We didn't change the coefficients enough by the full pass
% through the predictors to warrant continuing the iterations.
% The active coefficients after this pass and the
% active coefficients prior to this pass differ.
% This implies that a coefficient changed between zero
% and a small numeric value. There is no "fit-wise" reason
% to prefer the before and after coefficients, so we
% choose the more parsimonious alternative.
if sum(new_active) > sum(active)
b = bold;
else
active = new_active;
end
break
else
active = new_active;
end
end
end
end
varargout{1} = active;
end %-penalizedWls()
% ===================================================
% glmPenalizedWlsWrapper()
% ===================================================
function [b,varargout] = glmPenalizedWlsWrapper(X,Y,b,active,weights, ...
lambda,alpha,reltol,ever_active)
% The coordinate descent in penalizedWls() assumes centered X and Y,
% and it assumes X does NOT have a column of ones.
X0 = X(:,2:end);
weights = weights(:)';
normedWeights = weights / sum(weights);
% Center X
muX = normedWeights * X0;
X0 = bsxfun(@minus,X0,muX);
% Center Y.
muY = normedWeights * Y;
Y = Y - muY;
[bPredictors,varargout{1}] = penalizedWls(X0, Y, b(2:end), ...
active,weights,lambda,alpha,reltol);
bPredictors(~ever_active,:) = 0;
% Since X and Y were centered for the WLS we can calculate the intercept
% after the fact.
Intercept = muY-muX*bPredictors;
b = [Intercept; bPredictors];
end %-glmPenalizedWlsWrapper()
function [lambdaMax, nullDev, nullIntercept] = computeLambdaMax(X, Y, weights, alpha, standardize, ...
distr, link, dlinkFun, offset, isCanonical, dlinkFunCanonical, devFun)
% lambdaMax is the penalty term (lambda) beyond which coefficients
% are guaranteed to be all zero: there is no benefit to calculating
% penalized fits with lambda > lambdaMax.
%
% nullDev is the deviance of the fit using just a constant term.
%
% The input parameter 'devFun' is used only as a sanity check to see if glmfit
% gets a plausible fit with intercept term only.
% Head off potential cruft in the command window.
wsIllConditioned2 = warning('off','stats:glmfit:IllConditioned');
wsIterationLimit = warning('off','stats:glmfit:IterationLimit');
wsPerfectSeparation = warning('off','stats:glmfit:PerfectSeparation');
wsBadScaling = warning('off','stats:glmfit:BadScaling');
cleanupIllConditioned2 = onCleanup(@() warning(wsIllConditioned2));
cleanupIterationLimit = onCleanup(@() warning(wsIterationLimit));
cleanupPerfectSeparation = onCleanup(@() warning(wsPerfectSeparation));
cleanupBadScaling = onCleanup(@() warning(wsBadScaling));
if ~isempty(weights)
observationWeights = true;
weights = weights(:)';
% Normalized weights are used for standardization and calculating lambdaMax.
normalizedweights = weights / sum(weights);
else
observationWeights = false;
end
[N,~] = size(X);
% If we were asked to standardize the predictors, do so here because
% the calculation of lambdaMax needs the predictors as we will use
% them to perform fits.
if standardize
% If X has any constant columns, we want to protect against
% divide-by-zero in normalizing variances.
constantPredictors = (range(X)==0);
if ~observationWeights
% Center and scale
%[X0,~,~] = zscore(X,1);
[X0,~,~] = zscore(X);
else
% Weighted center and scale
muX = normalizedweights * X;
X0 = bsxfun(@minus,X,muX);
sigmaX = sqrt( normalizedweights * (X0.^2) );
% Avoid divide by zero with constant predictors
sigmaX(constantPredictors) = 1;
X0 = bsxfun(@rdivide, X0, sigmaX);
end
else
if ~observationWeights
% Center
muX = mean(X,1);
X0 = bsxfun(@minus,X,muX);
else
% Weighted center
muX = normalizedweights(:)' * X;
X0 = bsxfun(@minus,X,muX);
end
end
constantTerm = ones(length(Y),1);
if isscalar(offset)
[coeffs,nullDev] = glmfit(constantTerm,Y,distr,'constant','off', ...
'link',link, 'weights',weights);
predictedMu = glmval(coeffs,constantTerm,link,'constant','off');
else
[coeffs,nullDev] = glmfit(constantTerm,Y,distr,'constant','off', ...
'link',link,'weights',weights,'offset',offset);
predictedMu = glmval(coeffs,constantTerm,link,'constant','off','offset',offset);
end
nullIntercept = coeffs;
% Sanity check. With badly matched link / distr / data, glmfit may not
% have been able to converge to a reasonble estimate. If so, the inputs
% to lassoglm may constitute a difficult problem formulation with
% unsatisfactory maximum likelihood solution. Poor formulations
% have been observed with mismatched links (ie, 'reciprocal' link with
% the Poisson distribution, in place of canonical 'log'). As a screen for
% this contingency, calculate the deviance we would get using the scalar
% unmodeled mean for the response data. Call this quantity "muDev".
% The value of muDev should be no better than the nullDev calculated
% by glmfit above (albeit it might be equal or nearly equal).
% If the value is better, warn that the computations are of uncertain validity.
if observationWeights
muDev = weights * devFun(mean(Y)*ones(length(Y),1), Y);
else
muDev = sum(devFun(mean(Y)*ones(length(Y),1), Y));
end
if (muDev - nullDev) / max([1.0 muDev nullDev]) < - 1.0e-4
[~, lastid] = lastwarn;
if strcmp(lastid,'stats:glmfit:BadScaling')
% This reassignment of predicted values is not guaranteed to
% improve matters, but is an attempt to generate a workable
% sequence of lambda values. Note: Since it is a constant
% value for all observations, observation weights are a wash.
predictedMu = mean(Y)*ones(length(Y),1);
warning(message('stats:lassoGlm:DifficultLikelihood'));
end
end
if ~isCanonical
X0 = bsxfun( @times, X0, dlinkFunCanonical(predictedMu) ./ dlinkFun(predictedMu) );
end
if ~observationWeights
dotp = abs(X0' * (Y - predictedMu));
lambdaMax = max(dotp) / (N*alpha);
else
wX0 = bsxfun(@times, X0, normalizedweights');
dotp = abs(sum(bsxfun(@times, wX0, (Y - predictedMu))));
lambdaMax = max(dotp) / alpha;
end
end %-computeLambdaMax()
function lambda = computeLambdaSequence(lambdaMax, nLambda, lambdaRatio, LRdefault)
% Fill in the log-spaced sequence of lambda values.
if nLambda==1
lambda = lambdaMax;
else
% Fill in a number "nLambda" of smaller values, on a log scale.
if lambdaRatio==0
lambdaRatio = LRdefault;
addZeroLambda = true;
else
addZeroLambda = false;
end
lambdaMin = lambdaMax * lambdaRatio;
loghi = log(lambdaMax);
loglo = log(lambdaMin);
logrange = loghi - loglo;
interval = -logrange/(nLambda-1);
lambda = exp(loghi:interval:loglo)';
if addZeroLambda
lambda(end) = 0;
else
lambda(end) = lambdaMin;
end
end
end %-computeLambdaSequence
|
github
|
ZijingMao/baselineeegtest-master
|
extractfields.m
|
.m
|
baselineeegtest-master/DLResultAnalysis/extractfields.m
| 2,885 |
utf_8
|
749c4e2f71a16853b1cfdb07ec28f1e9
|
function A = extractfields(S, name)
%EXTRACTFIELD Field values from structure array
%
% A = EXTRACTFIELD(S, NAME) returns the field values specified by the
% fieldname NAME in the 1-by-N output array A. N is the total number
% of elements in the field NAME of structure S:
%
% N = numel([S(:).(name)]).
%
% NAME is a case-sensitive string defining the field name of the
% structure S. A will be a cell array if any field values in the
% fieldname contain a string or if the field values are not uniform in
% type; otherwise A will be the same type as the field values. The shape
% of the input field is not preserved in A.
%
% Examples
% --------
% % Plot X, Y coordinates from a geographic data structure
% roads = shaperead('concord_roads.shp');
% plot(extractfield(roads,'X'),extractfield(roads,'Y'));
%
% % Extract feature names from a geographic data structure
% roads = shaperead('concord_roads.shp');
% names = extractfield(roads,'STREETNAME');
%
% % Extract a mixed-type field into a cell array
% S(1).Type = 0;
% S(2).Type = logical(0);
% mixedType = extractfield(S,'Type');
%
% See also STRUCT, SHAPEREAD.
% Copyright 1996-2010 The MathWorks, Inc.
% Validate inputs
error(nargchk(2,2,nargin,'struct'))
fcnname = mfilename;
validateattributes(S, {'struct'}, {'vector'}, fcnname, 'S', 1)
validateattributes(name, {'char'}, {'row'}, fcnname, 'NAME', 2)
if isfield(S,name)
% Determine if need to return a cell array
if cellType(S,name)
% The elements in the field are strings or mixed type
A = {S(:).(name)};
return;
end
try
% The field is numeric.
% This will error if the fieldname's shape is neither row vector
% nor uniform.
A = [S(:).(name)];
% Do not preserve the shape
if size(A,1) ~= 1
A = reshape(A, [1 numel(A)]);
end
catch
% The elements in the field are mixed size
% Reshape into a row vector and append
A = reshape(S(1).(name),[ 1 numel(S(1).(name)) ]);
for i=2:length(S)
values = reshape(S(i).(name),[ 1 numel(S(i).(name)) ]);
A = [A values];
end
end
else
error('map:extractfield:invalidFieldname', ...
'Fieldname ''%s'' does not exist.', name)
end
%----------------------------------------------------------------
function returnCell = cellType(S, name)
%CELLTYPE Return true if field values of NAME are mixed type, or
% non-numeric.
% Determine if the field is non-numeric or mixed type
classType = class(S(1).(name));
for i=1:length(S)
if issparse(S(i).(name))
error('map:extractfield:expectedNonSparse', ...
'Sparse storage class is not supported.');
end
if ~isnumeric(S(i).(name)) || ...
~isequal(class(S(i).(name)), classType)
returnCell = true;
return;
end
end
returnCell = false;
|
github
|
ZijingMao/baselineeegtest-master
|
datestr8601.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/datestr8601.m
| 17,551 |
utf_8
|
1b3b9a5bdd75dbc154c6dc8f3c241d7b
|
function varargout = datestr8601(DVN,varargin)
% Convert a Date Vector or Serial Date Number to an ISO 8601 formatted Date String (timestamp).
%
% (c) 2014 Stephen Cobeldick
%
% ### Function ###
%
% Syntax:
% Str = datestr8601
% Str = datestr8601(DVN)
% Str = datestr8601(DVN,Tok)
% [Str1,Str2,...] = datestr8601(DVN,Tok1,Tok2,...)
%
% Easy conversion of a Date Vector or Serial Date Number to a Date String
% whose style is controlled by (optional) input token/s. The string may
% be an ISO 8601 timestamp or a single date/time value: multiple tokens may
% be used to output multiple strings (faster than multiple function calls).
%
% By default the function uses the current time and returns the basic
% ISO 8601 calendar notation timestamp: this is very useful for naming
% files that can be sorted alphabetically into chronological order!
%
% The ISO 8601 timestamp style options are:
% - Date in calendar, ordinal or week-numbering notation.
% - Basic or extended format.
% - Choice of date-time separator character ( @T_).
% - Full or lower precision (trailing units omitted)
% - Decimal fraction of the trailing unit.
% These style options are illustrated in the tables below.
%
% Note 1: Calls undocumented MATLAB functions "datevecmx" and "datenummx".
% Note 2: Some Date Strings use the ISO 8601 week-numbering year, where the first
% week of the year includes the first Thursday of the year: please double check!
% Note 3: Out-of-range values are permitted in the input Date Vector.
%
% See also DATENUM8601 DATEROUND CLOCK NOW DATESTR DATENUM DATEVEC
%
% ### Examples ###
%
% Examples use the date+time described by the vector [1999,1,3,15,6,48.0568].
%
% datestr8601
% ans = '19990103T150648'
%
% datestr8601([],'yn_HM')
% ans = '1999003_1506'
%
% datestr8601(now-1,'DDDD')
% ans = 'Saturday'
%
% datestr8601(clock,'*ymdHMS')
% ans = '1999-01-03T15:06:48'
%
% [A,B,C,D] = datestr8601(clock,'ddd','mmmm','yyyy','*YWD')
% sprintf('The %s of %s %s has the ISO week-date "%s".',A,B,C,D)
% ans = 'The 3rd of January 1999 has the ISO week-date "1998-W53-7".'
%
% ### Single Value Tokens ###
%
% For date values the case of the token determines the output Date String's
% year-type: lowercase = calendar year, UPPERCASE = week-numbering year.
%
% 'W' = the standard ISO 8601 week number (this is probably what you want).
% 'w' = the weeks (rows) shown on an actual printed calendar (very esoteric).
%
% 'Q' = each quarter is 13 weeks (the last may be 14). Uses week-numbering year.
% 'q' = each quarter is three months long: Jan-Mar, Apr-Jun, Jul-Sep, Oct-Dec.
%
% 'N'+'R' = 7*52 or 7*53 (year dependent).
% 'n'+'r' = 365 (or 366 if a leap year).
%
% Input | Output | Output
% <Tok>:| <Str> Date/Time Representation: | <Str> Example:
% ------|---------------------------------------------|--------------------
% # Calendar year # |
% 'yyyy'| year, four digit |'1999'
% 'n' | day of the year, variable digits |'3'
% 'nn' | day of the year, three digit, zero padded |'003'
% 'nnn' | day of the year, ordinal and suffix |'3rd'
% 'r' | days remaining in year, variable digits |'362'
% 'rr' | days remaining in year, three digit, padded |'362'
% 'rrr' | days remaining in year, ordinal and suffix |'362nd'
% 'q' | year quarter, 3-month |'1'
% 'qq' | year quarter, 3-month, abbreviation |'Q1'
% 'qqq' | year quarter, 3-month, ordinal and suffix |'1st'
% 'w' | week of the year, one or two digit |'1'
% 'ww' | week of the year, two digit, zero padded |'01'
% 'www' | week of the year, ordinal and suffix |'1st'
% 'm' | month of the year, one or two digit |'1'
% 'mm' | month of the year, two digit, zero padded |'01'
% 'mmm' | month name, three letter abbreviation |'Jan'
% 'mmmm'| month name, in full |'January'
% 'd' | day of the month, one or two digit |'3'
% 'dd' | day of the month, two digit, zero padded |'03'
% 'ddd' | day of the month, ordinal and suffix |'3rd'
% ------|---------------------------------------------|---------
% # Week-numbering year # |
% 'YYYY'| year, four digit, |'1998'
% 'N' | day of the year, variable digits |'371'
% 'NN' | day of the year, three digit, zero padded |'371'
% 'NNN' | day of the year, ordinal and suffix |'371st'
% 'R' | days remaining in year, variable digits |'0'
% 'RR' | days remaining in year, three digit, padded |'000'
% 'RRR' | days remaining in year, ordinal and suffix |'0th'
% 'Q' | year quarter, 13-week |'4'
% 'QQ' | year quarter, 13-week, abbreviation |'Q4'
% 'QQQ' | year quarter, 13-week, ordinal and suffix |'4th'
% 'W' | week of the year, one or two digit |'53'
% 'WW' | week of the year, two digit, zero padded |'53'
% 'WWW' | week of the year, ordinal and suffix |'53rd'
% ------|---------------------------------------------|---------
% # Weekday # |
% 'D' | weekday number (Monday=1) |'7'
% 'DD' | weekday name, two letter abbreviation |'Su'
% 'DDD' | weekday name, three letter abbreviation |'Sun'
% 'DDDD'| weekday name, in full |'Sunday'
% ------|---------------------------------------------|---------
% # Time of day # |
% 'H' | hour of the day, one or two digit |'15'
% 'HH' | hour of the day, two digit, zero padded |'15'
% 'M' | minute of the hour, one or two digit |'6'
% 'MM' | minute of the hour, two digit, zero padded |'06'
% 'S' | second of the minute, one or two digit |'48'
% 'SS' | second of the minute, two digit, zero padded|'48'
% 'F' | deci-second of the second, zero padded |'0'
% 'FF' | centisecond of the second, zero padded |'05'
% 'FFF' | millisecond of the second, zero padded |'056'
% ------|---------------------------------------------|---------
% 'MANP'| Midnight/AM/Noon/PM (+-0.0005s) |'PM'
% ------|---------------------------------------------|---------
%
% ### ISO 8601 Timestamps ###
%
% The token consists of one letter for each of the consecutive date/time
% units in the timestamp, thus it defines the date notation (calendar,
% ordinal or week-date) and selects either basic or extended format:
%
% Output | Basic Format | Extended Format (token prefix '*')
% Date | Input | Output Timestamp| Input | Output Timestamp
% Notation:| <Tok>: | <Str> Example: | <Tok>: | <Str> Example:
% ---------|--------|-----------------|---------|--------------------------
% Calendar |'ymdHMS'|'19990103T150648'|'*ymdHMS'|'1999-01-03T15:06:48'
% ---------|--------|-----------------|---------|--------------------------
% Ordinal |'ynHMS' |'1999003T150648' |'*ynHMS' |'1999-003T15:06:48'
% ---------|--------|-----------------|---------|--------------------------
% Week |'YWDHMS'|'1998W537T150648'|'*YWDHMS'|'1998-W53-7T15:06:48'
% ---------|--------|-----------------|---------|--------------------------
%
% Options for reduced precision timestamps, non-standard date-time separator
% character, and the addition of a decimal fraction of the trailing unit:
%
% # Omit leading and/or trailing units (reduced precision), eg:
% ---------|--------|-----------------|---------|--------------------------
% |'DHMS' |'7T150648' |'*DHMS' |'7T15:06:48'
% ---------|--------|-----------------|---------|--------------------------
% |'mdH' |'0103T15' |'*mdH' |'01-03T15'
% ---------|--------|-----------------|---------|--------------------------
% # Select the date-time separator character (one of ' ','@','T','_'), eg:
% ---------|--------|-----------------|---------|--------------------------
% |'n_HMS' |'003_150648' |'*n_HMS' |'003_15:06:48'
% ---------|--------|-----------------|---------|--------------------------
% |'YWD@H' |'1998W537@15' |'*YWD@H' |'1998-W53-7@15'
% ---------|--------|-----------------|---------|--------------------------
% # Decimal fraction of the trailing date/time value, eg:
% ---------|--------|-----------------|---------|--------------------------
% |'HMS4' |'150648.0568' |'*HMS4' |'15:06:48.0568'
% ---------|--------|-----------------|---------|--------------------------
% |'YW7' |'1998W53.9471032'|'*YW7' |'1998-W53.9471032'
% ---------|--------|-----------------|---------|--------------------------
% |'y10' |'1999.0072047202'|'*y10' |'1999.0072047202'
% ---------|--------|-----------------|---------|--------------------------
%
% Note 4: Token parsing matches Single Value tokens before ISO 8601 tokens.
% Note 5: This function does not check for ISO 8601 compliance: user beware!
% Note 6: Date-time separator character must be one of ' ','@','T','_'.
% Note 7: Date notations cannot be combined: note upper/lower case characters.
%
% ### Input & Output Arguments ###
%
% Inputs:
% DVN = Date Vector, [year,month,day,hour,minute,second.millisecond].
% = Serial Date Number, where 1 = start of 1st January of the year 0000.
% = []*, uses current time (default).
% Tok = String token, chosen from the above tables (default is 'ymdHMS').
%
% Outputs:
% Str = Date String, whose representation is controlled by argument <Tok>.
%
% [Str1,Str2,...] = datestr8601(DVN,Tok1,Tok2,...)
DfAr = {'ymdHMS'}; % {Tok1}
DfAr(1:numel(varargin)) = varargin;
%
% Calculate date-vector:
if nargin==0||isempty(DVN) % Default = now
DtV = clock;
elseif isscalar(DVN) % Serial Date Number
DtV = datevecmx(DVN);
elseif isrow(DVN) % Date Vector
DtV = datevecmx(datenummx(DVN));
else
error('First input <DVN> must be a single Date Vector or Date Number.');
end
% Calculate Serial Date Number:
DtN = datenummx(DtV);
% Weekday index (Mon=0):
DtD = mod(floor(DtN(1))-3,7);
% Adjust date to suit week-numbering:
DtN(2,1) = DtN(1)+3-DtD;
DtV(2,:) = datevecmx(floor(DtN(2)));
DtV(2,4:6) = DtV(1,4:6);
% Separate fraction of seconds from seconds:
DtV(:,7) = round(rem(DtV(1,6),1)*10000);
DtV(:,6) = floor(DtV(1,6));
% Date at the end of the year [last,this]:
DtE(1,:) = datenummx([DtV(1)-1,12,31;DtV(1),12,31]);
DtE(2,:) = datenummx([DtV(2)-1,12,31;DtV(2),12,31]);
DtO = 3-mod(DtE(2,:)+1,7);
DtE(2,:) = DtE(2,:)+DtO;
%
varargout = DfAr;
%
APC = {'Midnight','AM','Noon','PM'};
ChO = ['00000000001111111111222222222233333333334444444444555555555566666';...
'01234567890123456789012345678901234567890123456789012345678901234';...
'tsnrtttttttttttttttttsnrtttttttsnrtttttttsnrtttttttsnrtttttttsnrt';...
'htddhhhhhhhhhhhhhhhhhtddhhhhhhhtddhhhhhhhtddhhhhhhhtddhhhhhhhtddh'].';
Err = '%.0f%s input (token) is not recognized: ''%s''';
%
for m = 1:numel(DfAr)
% Ordinal suffix of input:
OrS = ChO(1+rem(m+1,10)+10*any(rem(m+1,100)==11:13),3:4); % (also day of the year)
% Input token:
Tok = DfAr{m};
assert(ischar(Tok)&&isrow(Tok),'%.0f%s input must be a string token.',m+1,OrS)
TkL = numel(Tok);
TkU = strcmp(upper(Tok),Tok);
switch Tok
case {'S','SS','M','MM','H','HH','d','dd','ddd','m','mm'}
% seconds, minutes, hours, day of the month, month of the year
Val = DtV(1,strfind('ymdHMS',Tok(1)));
varargout{m} = ChO(1+Val,1+(TkL~=2&&Val<10):max(2,2*(TkL-1))); % (also week)
case {'D','DD','DDD','DDDD'}
% weekday
varargout{m} = ds8601Day(TkL,DtD);
case {'mmm','mmmm'}
% month of the year
varargout{m} = ds8601Mon(TkL,DtV(1,2));
case {'F','FF','FFF'}
% deci/centi/milliseconds
Tok = sprintf('%04.0f',DtV(1,7));
varargout{m} = Tok(1:TkL);
case {'n','nn','nnn','r','rr','rrr','N','NN','NNN','R','RR','RRR'}
% day of the year, days remaining in the year
varargout{m} = ds8601DoY(TkL,ChO,...
abs(floor(DtN(1))-DtE(1+TkU,1+strncmpi('r',Tok,1))));
case {'y','yyyy','Y','YYYY'}
% year
varargout{m} = sprintf('%04.0f',DtV(1+TkU));
case {'w','ww','www','W','WW','WWW'}
% week of the year
Val = floor(max(0,(DtN(1+TkU)-DtE(1+TkU)+DtO(1)*~TkU))/7);
varargout{m} = ChO(2+Val,1+(TkL~=2&&Val<10):max(2,2*(TkL-1))); % (also S/M/H/d/m)
case {'q','qq','qqq','Q','QQ','QQQ'}
% year quarter
Val = [ceil(DtV(1,2)/3),min(4,1+floor((DtN(2)-DtE(2))/91))];
varargout{m} = ds8601Qtr(TkL,Val(1+TkU));
case 'MANP'
% midnight/am/noon/pm
Val = 2+2*(DtV(1,4)>=12)-(all(DtV(1,5:7)==0)&&any(DtV(1,4)==[0,12]));
varargout{m} = APC{Val};
otherwise % ISO 8601 timestamp
% Identify format, date, separator, time and digit characters:
TkU = regexp(Tok,'(^\*?)([ymdnYWD]*)([ @T_]?)([HMS]*)(\d*$)','tokens','once');
assert(~isempty(TkU),Err,m+1,OrS,Tok)
TkL = [TkU{2},TkU{4}];
% Identify timestamp:
Val = strfind('ymdHMSynHMSYWDHMS',TkL);
assert(~isempty(Val),Err,m+1,OrS,Tok)
BeR = [1,2,3,4,5,6,1,3,4,5,6,1,2,3,4,5,6];
BeN = [1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3];
BeR = BeR(Val(1)-1+(1:numel(TkL)));
assert(all(diff(BeR)>0),Err,m+1,OrS,Tok)
% Create date string:
varargout{m} = ds8601ISO(DtV,DtN,DtE,DtD,ChO,BeR,...%Bas,Dgt,Ntn,Sep)
isempty(TkU{1}),sscanf(TkU{5},'%d'),BeN(Val(1)),TkU{3});
end
end
%
end
%----------------------------------------------------------------------END:datestr8601
function DtS = ds8601Day(TkL,Val)
% weekday
%
if TkL==1
StT = '1234567';
DtS = StT(1+Val);
else
StT = ['Monday ';'Tuesday ';'Wednesday';...
'Thursday ';'Friday ';'Saturday ';'Sunday '];
StE = [6,7,9,8,6,8,6]; % Weekday name lengths
DtS = StT(1+Val,1:max(TkL,StE(1+Val)*(TkL-3))); % (also month)
end
%
end
%----------------------------------------------------------------------END:ds8601Day
function DtS = ds8601Mon(TkL,Val)
% month
%
StT = ['January ';'February ';'March ';'April ';...
'May ';'June ';'July ';'August ';...
'September';'October ';'November ';'December '];
StE = [7,8,5,5,3,4,4,6,9,7,8,8]; % Month name lengths
DtS = StT(Val,1:max(TkL,StE(Val)*(TkL-3))); % (also weekday)
%
end
%----------------------------------------------------------------------END:ds8601Mon
function DtS = ds8601DoY(TkL,ChO,Val)
% day of the year, days remaining in the year
%
if TkL<3
DtS = sprintf('%0*.0f',2*TkL-1,Val);
else
DtS = sprintf('%.0f%s',Val,ChO(1+rem(Val,10)+10*any(rem(Val,100)==11:13),3:4)); % (also OrS)
end
%
end
%----------------------------------------------------------------------END:ds8601DoY
function DtS = ds8601Qtr(TkL,Val)
% year quarter
%
QT = ['Q1st';'Q2nd';'Q3rd';'Q4th'];
QI = 1+abs(TkL-2):max(2,2*(TkL-1));
DtS = QT(Val,QI);
%
end
%----------------------------------------------------------------------END:ds8601Qtr
function DtS = ds8601ISO(DtV,DtN,DtE,DtD,ChO,BeR,Bas,Dgt,Ntn,Sep)
% ISO 8601 timestamp
%
% For calculating decimal fraction of date/time values:
BeE = BeR(end);
DtK = 1;
DtW = DtV(1,:);
DtZ = [1,1,1,0,0,0,0];
%
if isempty(Sep)
Sep = 'T';
end
if Bas % Basic-format
DtC = {'', '', '',Sep, '', '';'','','','','',''};
else
% Extended-format
DtC = {'','-','-',Sep,':',':';'','','','','',''};
end
%
% hours, minutes, seconds:
for m = 4:max(BeR)
DtC{2,m} = ChO(1+DtW(m),1:2);
end
%
switch Ntn
case 1 % Calendar.
% month, day of the month:
for m = max(2,min(BeR)):3
DtC{2,m} = ChO(1+DtW(m),1:2);
end
case 2 % Ordinal.
% day of the year:
DtC{2,3} = sprintf('%03.0f',floor(DtN(1))-DtE(1));
case 3 % Week-numbering
DtW = DtV(2,:);
% Decimal fraction of weeks, not days:
if BeR(end)==2
BeE = 3;
DtK = 7;
DtZ(3) = DtW(3)-DtD;
end
% weekday:
if any(BeR==3)
DtC{2,3} = ChO(2+DtD,2);
end
% week of the year:
if any(BeR==2)
DtC{2,2} = ['W',ChO(2+floor((DtN(2)-DtE(2))/7),1:2)];
end
end
%
if BeR(1)==1
% year:
DtC{2,1} = sprintf('%04.0f',DtW(1));
end
%
% Concatenate separator and value strings:
BeN = [BeR*2-1;BeR*2];
DtS = [DtC{BeN(2:end)}];
%
% Decimal fraction of trailing unit (decimal places):
if 0<Dgt
DcP = 0;
if BeR(end)==6
% second
DcP = 4;
Str = sprintf('%0*.0f',DcP,DtW(7));
elseif BeR(end)==3
% day
DcP = 10;
Str = sprintf('%.*f',DcP,rem(DtN(1),1));
Str(1:2) = [];
elseif any(DtW(BeR(end)+1:7)>DtZ(BeR(end)+1:7));
% year/month/week/hour/minute
DcP = 16;
% Floor all trailing units:
DtW(7) = [];
DtW(BeR(end)+1:6) = DtZ(BeR(end)+1:6);
DtF = datenummx(DtW);
% Increment the chosen unit:
DtW(BeE) = DtW(BeE)+DtK;
% Decimal fraction of the chosen unit:
dcf = (DtN(1+(Ntn==3))-DtF)/(datenummx(DtW)-DtF);
Str = sprintf('%.*f',DcP,dcf);
Str(1:2) = [];
end
Str(1+DcP:Dgt) = '0';
DtS = [DtS,'.',Str(1:Dgt)];
end
%
end
%----------------------------------------------------------------------END:ds8601ISO
|
github
|
ZijingMao/baselineeegtest-master
|
parseXML.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/parseXML.m
| 2,009 |
utf_8
|
41322e38af16d5d7496a794c7b9ea2c8
|
function theStruct = parseXML(filename)
% PARSEXML Convert XML file to a MATLAB structure.
try
tree = xmlread(filename);
catch
error('Failed to read XML file %s.',filename);
end
% Recurse over child nodes. This could run into problems
% with very deeply nested trees.
try
theStruct = parseChildNodes(tree);
catch
error('Unable to parse XML file %s.',filename);
end
% ----- Subfunction PARSECHILDNODES -----
function children = parseChildNodes(theNode)
% Recurse over node children.
children = [];
if theNode.hasChildNodes
childNodes = theNode.getChildNodes;
numChildNodes = childNodes.getLength;
allocCell = cell(1, numChildNodes);
children = struct( ...
'Name', allocCell, 'Attributes', allocCell, ...
'Data', allocCell, 'Children', allocCell);
for count = 1:numChildNodes
theChild = childNodes.item(count-1);
children(count) = makeStructFromNode(theChild);
end
end
% ----- Subfunction MAKESTRUCTFROMNODE -----
function nodeStruct = makeStructFromNode(theNode)
% Create structure of node info.
nodeStruct = struct( ...
'Name', char(theNode.getNodeName), ...
'Attributes', parseAttributes(theNode), ...
'Data', '', ...
'Children', parseChildNodes(theNode));
if any(strcmp(methods(theNode), 'getData'))
nodeStruct.Data = char(theNode.getData);
else
nodeStruct.Data = '';
end
% ----- Subfunction PARSEATTRIBUTES -----
function attributes = parseAttributes(theNode)
% Create attributes structure.
attributes = [];
if theNode.hasAttributes
theAttributes = theNode.getAttributes;
numAttributes = theAttributes.getLength;
allocCell = cell(1, numAttributes);
attributes = struct('Name', allocCell, 'Value', ...
allocCell);
for count = 1:numAttributes
attrib = theAttributes.item(count-1);
attributes(count).Name = char(attrib.getName);
attributes(count).Value = char(attrib.getValue);
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
xml_write.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/xml_write.m
| 14,648 |
utf_8
|
22c16c351430ff67bb44dd116db74334
|
function DOMnode = xml_write(filename, tree, RootName, Pref)
%XML_WRITE Writes Matlab data structures to XML file
%
% DESCRIPTION
% xml_write( filename, tree) Converts Matlab data structure 'tree' containing
% cells, structs, numbers and strings to Document Object Model (DOM) node
% tree, then saves it to XML file 'filename' using Matlab's xmlwrite
% function. Optionally one can also use alternative version of xmlwrite
% function which directly calls JAVA functions for XML writing without
% MATLAB middleware. This function is provided as a patch to existing
% bugs in xmlwrite (in R2006b).
%
% xml_write(filename, tree, RootName, Pref) allows you to specify
% additional preferences about file format
%
% DOMnode = xml_write([], tree) same as above except that DOM node is
% not saved to the file but returned.
%
% INPUT
% filename file name
% tree Matlab structure tree to store in xml file.
% RootName String with XML tag name used for root (top level) node
% Optionally it can be a string cell array storing: Name of
% root node, document "Processing Instructions" data and
% document "comment" string
% Pref Other preferences:
% Pref.ItemName - default 'item' - name of a special tag used to
% itemize cell arrays
% Pref.XmlEngine - let you choose the XML engine. Currently default is
% 'Xerces', which is using directly the apache xerces java file.
% Other option is 'Matlab' which uses MATLAB's xmlwrite and its
% XMLUtils java file. Both options create identical results except in
% case of CDATA sections where xmlwrite fails.
% Pref.CellItem - default 'true' - allow cell arrays to use 'item'
% notation. See below.
% Pref.RootOnly - default true - output variable 'tree' corresponds to
% xml file root element, otherwise it correspond to the whole file.
% Pref.StructItem - default 'true' - allow arrays of structs to use
% 'item' notation. For example "Pref.StructItem = true" gives:
% <a>
% <b>
% <item> ... <\item>
% <item> ... <\item>
% <\b>
% <\a>
% while "Pref.StructItem = false" gives:
% <a>
% <b> ... <\b>
% <b> ... <\b>
% <\a>
%
%
% Several special xml node types can be created if special tags are used
% for field names of 'tree' nodes:
% - node.CONTENT - stores data section of the node if other fields
% (usually ATTRIBUTE are present. Usually data section is stored
% directly in 'node'.
% - node.ATTRIBUTE.name - stores node's attribute called 'name'.
% - node.COMMENT - create comment child node from the string. For global
% comments see "RootName" input variable.
% - node.PROCESSING_INSTRUCTIONS - create "processing instruction" child
% node from the string. For global "processing instructions" see
% "RootName" input variable.
% - node.CDATA_SECTION - stores node's CDATA section (string). Only works
% if Pref.XmlEngine='Xerces'. For more info, see comments of F_xmlwrite.
% - other special node types like: document fragment nodes, document type
% nodes, entity nodes and notation nodes are not being handled by
% 'xml_write' at the moment.
%
% OUTPUT
% DOMnode Document Object Model (DOM) node tree in the format
% required as input to xmlwrite. (optional)
%
% EXAMPLES:
% MyTree=[];
% MyTree.MyNumber = 13;
% MyTree.MyString = 'Hello World';
% xml_write('test.xml', MyTree);
% type('test.xml')
% %See also xml_tutorial.m
%
% See also
% xml_read, xmlread, xmlwrite
%
% Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com
%% Check Matlab Version
v = ver('MATLAB');
if length(v) > 1
v = v(1); % added by Nima
end;
v = str2double(regexp(v.Version, '\d.\d','match','once'));
if (v<7)
error('Your MATLAB version is too old. You need version 7.0 or newer.');
end
%% default preferences
DPref.ItemName = 'item'; % name of a special tag used to itemize cell arrays
DPref.StructItem = true; % allow arrays of structs to use 'item' notation
DPref.CellItem = true; % allow cell arrays to use 'item' notation
DPref.XmlEngine = 'Matlab'; % use matlab provided XMLUtils
%DPref.XmlEngine = 'Xerces'; % use Xerces xml generator directly
RootOnly = true; % Input is root node only
GlobalProcInst = [];
GlobalComment = [];
GlobalDocType = [];
%% read user preferences
if (nargin>3)
if (isfield(Pref, 'ItemName' )), DPref.ItemName = Pref.ItemName; end
if (isfield(Pref, 'StructItem')), DPref.StructItem = Pref.StructItem; end
if (isfield(Pref, 'CellItem' )), DPref.CellItem = Pref.CellItem; end
if (isfield(Pref, 'XmlEngine' )), DPref.XmlEngine = Pref.XmlEngine; end
if (isfield(Pref, 'RootOnly' )), RootOnly = Pref.RootOnly; end
end
if (nargin<3 || isempty(RootName)), RootName=inputname(2); end
if (isempty(RootName)), RootName='ROOT'; end
if (iscell(RootName)) % RootName also stores global text node data
rName = RootName;
RootName = char(rName{1});
if (length(rName)>1), GlobalProcInst = char(rName{2}); end
if (length(rName)>2), GlobalComment = char(rName{3}); end
if (length(rName)>3), GlobalDocType = char(rName{4}); end
end
if(~RootOnly && isstruct(tree)) % if struct than deal with each field separatly
fields = fieldnames(tree);
for i=1:length(fields)
field = fields{i};
x = tree(1).(field);
if (strcmp(field, 'COMMENT'))
GlobalComment = x;
elseif (strcmp(field, 'PROCESSING_INSTRUCTION'))
GlobalProcInst = x;
elseif (strcmp(field, 'DOCUMENT_TYPE'))
GlobalDocType = x;
else
RootName = field;
t = x;
end
end
tree = t;
end
%% Initialize jave object that will store xml data structure
RootName = varName2str(RootName);
if (~isempty(GlobalDocType))
% n = strfind(GlobalDocType, ' ');
% if (~isempty(n))
% dtype = com.mathworks.xml.XMLUtils.createDocumentType(GlobalDocType);
% end
% DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName, dtype);
warning('xml_io_tools:write:docType', ...
'DOCUMENT_TYPE node was encountered which is not supported yet. Ignoring.');
end
DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName);
%% Use recursive function to convert matlab data structure to XML
root = DOMnode.getDocumentElement;
struct2DOMnode(DOMnode, root, tree, DPref.ItemName, DPref);
%% Remove the only child of the root node
root = DOMnode.getDocumentElement;
Child = root.getChildNodes; % create array of children nodes
nChild = Child.getLength; % number of children
if (nChild==1)
node = root.removeChild(root.getFirstChild);
while(node.hasChildNodes)
root.appendChild(node.removeChild(node.getFirstChild));
end
while(node.hasAttributes) % copy all attributes
root.setAttributeNode(node.removeAttributeNode(node.getAttributes.item(0)));
end
end
%% Save exotic Global nodes
if (~isempty(GlobalComment))
DOMnode.insertBefore(DOMnode.createComment(GlobalComment), DOMnode.getFirstChild());
end
if (~isempty(GlobalProcInst))
n = strfind(GlobalProcInst, ' ');
if (~isempty(n))
proc = DOMnode.createProcessingInstruction(GlobalProcInst(1:(n(1)-1)),...
GlobalProcInst((n(1)+1):end));
DOMnode.insertBefore(proc, DOMnode.getFirstChild());
end
end
% if (~isempty(GlobalDocType))
% n = strfind(GlobalDocType, ' ');
% if (~isempty(n))
% dtype = DOMnode.createDocumentType(GlobalDocType);
% DOMnode.insertBefore(dtype, DOMnode.getFirstChild());
% end
% end
%% save java DOM tree to XML file
if (~isempty(filename))
if (strcmpi(DPref.XmlEngine, 'Xerces'))
xmlwrite_xerces(filename, DOMnode);
else
xmlwrite(filename, DOMnode);
end
end
%% =======================================================================
% === struct2DOMnode Function ===========================================
% =======================================================================
function [] = struct2DOMnode(xml, parent, s, name, Pref)
% struct2DOMnode is a recursive function that converts matlab's structs to
% DOM nodes.
% INPUTS:
% xml - jave object that will store xml data structure
% parent - parent DOM Element
% s - Matlab data structure to save
% name - name to be used in xml tags describing 's'
% Pref - preferenced
name = varName2str(name);
ItemName = Pref.ItemName;
if (ischar(s) && min(size(s))>1) % if 2D array of characters
s=cellstr(s); % than convert to cell array
end
while (iscell(s) && length(s)==1), s = s{1}; end
nItem = length(s);
if (iscell(s)) % if this is a cell array
if (nItem==1 || strcmp(name, 'CONTENT') || ~Pref.CellItem)
if (strcmp(name, 'CONTENT')), CellName = ItemName; % use 'item' notation <item> ... <\item>
else CellName = name; end % don't use 'item' notation <a> ... <\a>
for iItem=1:nItem % save each cell separatly
struct2DOMnode(xml, parent, s{iItem}, CellName, Pref); % recursive call
end
else % use 'item' notation <a> <item> ... <\item> <\a>
node = xml.createElement(name);
for iItem=1:nItem % save each cell separatly
struct2DOMnode(xml, node, s{iItem}, ItemName , Pref); % recursive call
end
parent.appendChild(node);
end
elseif (isstruct(s)) % if struct than deal with each field separatly
fields = fieldnames(s);
% if array of structs with no attributes than use 'items' notation
if (nItem>1 && Pref.StructItem && ~isfield(s,'ATTRIBUTE') )
node = xml.createElement(name);
for iItem=1:nItem
struct2DOMnode(xml, node, s(iItem), ItemName, Pref ); % recursive call
end
parent.appendChild(node);
else % otherwise save each struct separatelly
for j=1:nItem
node = xml.createElement(name);
for i=1:length(fields)
field = fields{i};
x = s(j).(field);
%if (isempty(x)), continue; end
if (iscell(x) && (strcmp(field, 'COMMENT') || ...
strcmp(field, 'CDATA_SECTION') || ...
strcmp(field, 'PROCESSING_INSTRUCTION')))
for k=1:length(x) % if nodes that should have strings have cellstrings
struct2DOMnode(xml, node, x{k}, field, Pref ); % recursive call will modify 'node'
end
elseif (strcmp(field, 'ATTRIBUTE')) % set attributes of the node
if (isempty(x)), continue; end
if (~isstruct(x))
warning('xml_io_tools:write:badAttribute', ...
'Struct field named ATTRIBUTE encountered which was not a struct. Ignoring.');
continue;
end
attName = fieldnames(x); % get names of all the attributes
for k=1:length(attName) % attach them to the node
att = xml.createAttribute(varName2str(attName(k)));
att.setValue(var2str(x.(attName{k})));
node.setAttributeNode(att);
end
else % set children of the node
struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node'
end
end % end for i=1:nFields
parent.appendChild(node);
end % end for j=1:nItem
end
else % if not a struct and not a cell than it is a leaf node
if (strcmp(name, 'CONTENT'))
txt = xml.createTextNode(var2str(s)); % ... than it can be converted to text
parent.appendChild(txt);
elseif (strcmp(name, 'COMMENT')) % create comment node
if (ischar(s))
com = xml.createComment(s);
parent.appendChild(com);
else
warning('xml_io_tools:write:badComment', ...
'Struct field named COMMENT encountered which was not a string. Ignoring.');
end
elseif (strcmp(name, 'CDATA_SECTION')) % create CDATA Section
if (ischar(s))
cdt = xml.createCDATASection(s);
parent.appendChild(cdt);
else
warning('xml_io_tools:write:badCData', ...
'Struct field named CDATA_SECTION encountered which was not a string. Ignoring.');
end
elseif (strcmp(name, 'PROCESSING_INSTRUCTION')) % set attributes of the node
OK = false;
if (ischar(s))
n = strfind(s, ' ');
if (~isempty(n))
proc = xml.createProcessingInstruction(s(1:(n(1)-1)),s((n(1)+1):end));
parent.insertBefore(proc, parent.getFirstChild());
OK = true;
end
end
if (~OK)
warning('xml_io_tools:write:badProcInst', ...
['Struct field named PROCESSING_INSTRUCTION need to be',...
' a string, for example: xml-stylesheet type="text/css" ', ...
'href="myStyleSheet.css". Ignoring.']);
end
else % I guess it is a regular text leaf node
txt = xml.createTextNode(var2str(s));
node = xml.createElement(name);
node.appendChild(txt);
parent.appendChild(node);
end
end
%% =======================================================================
% === var2str Function ==================================================
% =======================================================================
function str = var2str(s)
% convert matlab variables to a sting
if (isnumeric(s) || islogical(s))
dim = size(s);
if (min(dim)<1 || length(dim)>2) % if 1D or 3D array
s=s(:); s=s.'; % convert to 1D array
str=num2str(s); % convert array of numbers to string
else % if a 2D array
s=mat2str(s); % convert matrix to a string
str=regexprep(s,';',';\n');
end
elseif iscell(s)
str = char(s{1});
for i=2:length(s)
str = [str, ' ', char(s{i})];
end
else
str = char(s);
end
str=str(:); str=str.'; % make sure this is a row vector of char's
if (length(str)>1)
str(str<32|str==127)=' '; % convert no-printable characters to spaces
str = strtrim(str); % remove spaces from begining and the end
str = regexprep(str,'\s+',' '); % remove multiple spaces
end
%% =======================================================================
% === var2Namestr Function ==============================================
% =======================================================================
function str = varName2str(str)
% convert matlab variable names to a sting
str = char(str);
p = strfind(str,'0x');
if (~isempty(p))
for i=1:length(p)
before = str( p(i)+(0:3) ); % string to replace
after = char(hex2dec(before(3:4))); % string to replace with
str = regexprep(str,before,after, 'once', 'ignorecase');
p=p-3; % since 4 characters were replaced with one - compensate
end
end
str = regexprep(str,'_COLON_',':', 'once', 'ignorecase');
str = regexprep(str,'_DASH_' ,'-', 'once', 'ignorecase');
|
github
|
ZijingMao/baselineeegtest-master
|
datenum8601.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/datenum8601.m
| 9,816 |
utf_8
|
a85d0376153e989173a5fb941cea7489
|
function [DtN,Spl,TkC] = datenum8601(Str,Tok)
% Convert an ISO 8601 formatted Date String (timestamp) to a Serial Date Number.
%
% (c) 2014 Stephen Cobeldick
%
% ### Function ###
%
% Syntax:
% DtN = datenum8601(Str)
% DtN = datenum8601(Str,Tok)
% [DtN,Spl,TkC] = datenum8601(...)
%
% By default the function automatically detects all ISO 8601 timestamp/s in
% the string, or use a token to restrict detection to only one particular style.
%
% The ISO 8601 timestamp style options are:
% - Date in calendar, ordinal or week-numbering notation.
% - Basic or extended format.
% - Choice of date-time separator character ( @T_).
% - Full or lower precision (trailing units omitted)
% - Decimal fraction of the trailing unit.
% These style options are illustrated in the tables below.
%
% The function returns the Serial Date Numbers of the date and time given
% by the ISO 8601 style timestamp/s, the input string parts that are split
% by the detected timestamps (i.e. the substrings not part of any ISO 8601
% timestamp), and string token/s that define the detected timestamp style/s.
%
% Note 1: Calls undocumented MATLAB function "datenummx".
% Note 2: Unspecified month/date/week/day timestamp values default to one (1).
% Note 3: Unspecified hour/minute/second timestamp values default to zero (0).
% Note 4: Auto-detection mode also parses mixed basic/extended timestamps.
%
% See also DATESTR8601 DATEROUND CLOCK NOW DATENUM DATEVEC DATESTR
%
% ### Examples ###
%
% Examples use the date+time described by the vector [1999,1,3,15,6,48.0568].
%
% datenum8601('1999-01-03 15:06:48.0568')
% ans = 730123.62972287962
%
% datenum8601('1999003T150648.0568')
% ans = 730123.62972287962
%
% datenum8601('1998W537_150648.0568')
% ans = 730123.62972287962
%
% [DtN,Spl,Tok] = datenum8601('A19990103B1999-003C1998-W53-7D')
% DtN = [730123,730123,730123]
% Spl = {'A','B','C','D'}
% Tok = {'ymd','*yn','*YWD'}
%
% [DtN,Spl,Tok] = datenum8601('1999-003T15')
% DtN = 730123.6250
% Spl = {'',''}
% Tok = {'*ynTH'}
%
% [DtN,Spl,Tok] = datenum8601('1999-01-03T15','*ymd')
% DtN = 730123.0000
% Spl = {'','T15'}
% Tok = {'*ymd'}
%
% ### ISO 8601 Timestamps ###
%
% The token consists of one letter for each of the consecutive date/time
% units in the timestamp, thus it defines the date notation (calendar,
% ordinal or week-date) and selects either basic or extended format:
%
% Input | Basic Format | Extended Format (token prefix '*')
% Date | In/Out | Input Timestamp | In/Out | Input Timestamp
% Notation:| <Tok>: | <Str> Example: | <Tok>: | <Str> Example:
% ---------|--------|-----------------|---------|---------------------------
% Calendar |'ymdHMS'|'19990103T150648'|'*ymdHMS'|'1999-01-03T15:06:48'
% ---------|--------|-----------------|---------|---------------------------
% Ordinal |'ynHMS' |'1999003T150648' |'*ynHMS' |'1999-003T15:06:48'
% ---------|--------|-----------------|---------|---------------------------
% Week |'YWDHMS'|'1998W537T150648'|'*YWDHMS'|'1998-W53-7T15:06:48'
% ---------|--------|-----------------|---------|---------------------------
%
% Options for reduced precision timestamps, non-standard date-time separator
% character, and the addition of a decimal fraction of the trailing unit:
%
% # Omit trailing units (reduced precision), eg: | Output->Vector:
% ---------|--------|-----------------|---------|-----------------|---------------------
% |'Y' |'1999W' |'*Y' |'1999-W' |[1999,1,4,0,0,0]
% ---------|--------|-----------------|---------|-----------------|---------------------
% |'ymdH' |'19990103T15' |'*ymdH' |'1999-01-03T15' |[1999,1,3,15,0,0]
% ---------|--------|-----------------|---------|-----------------|---------------------
% # Select the date-time separator character (one of ' ','@','T','_'), eg:
% ---------|--------|-----------------|---------|-----------------|---------------------
% |'yn_HM' |'1999003_1506' |'*yn_HM' |'1999-003_15:06' |[1999,1,3,15,6,0]
% ---------|--------|-----------------|---------|-----------------|---------------------
% |'YWD@H' |'1998W537@15' |'*YWD@H' |'1998-W53-7@15' |[1999,1,3,15,0,0]
% ---------|--------|-----------------|---------|-----------------|---------------------
% # Decimal fraction of trailing date/time value, eg:
% ---------|--------|-----------------|---------|-----------------|---------------------
% |'ynH3' |'1999003T15.113' |'*ynH3' |'1999-003T15.113'|[1999,1,3,15,6,46.80]
% ---------|--------|-----------------|---------|-----------------|---------------------
% |'YWD4' |'1998W537.6297' |'*YWD4' |'1998-W53-7.6297'|[1999,1,3,15,6,46.08]
% ---------|--------|-----------------|---------|-----------------|---------------------
% |'y10' |'1999.0072047202'|'*y10' |'1999.0072047202'|[1999,1,3,15,6,48.06]
% ---------|--------|-----------------|---------|-----------------|---------------------
%
% Note 5: This function does not check for ISO 8601 compliance: user beware!
% Note 6: Date-time separator character must be one of ' ','@','T','_'.
% Note 7: Date notations cannot be combined: note upper/lower case characters.
%
% ### Input & Output Arguments ###
%
% Inputs (*default):
% Str = Date String, possibly containing one or more ISO 8601 dates/timestamps.
% Tok = String token, to select the required date notation and format (*[]=any).
%
% Outputs:
% DtN = Numeric Vector of Serial Date Numbers, one from each timestamp in input <Str>.
% Spl = Cell of Strings, the strings before, between and after the detected timestamps.
% TkC = Cell of Strings, tokens of each timestamp notation and format (see tables).
%
% [DtN,Spl,TkC] = datenum8601(Str,Tok*)
% Define "regexp" match string:
if nargin<2 || isempty(Tok)
% Automagically detect timestamp style.
MtE = [...
'(\d{4})',... % year
'((-(?=(\d{2,3}|W)))?)',... % -
'(W?)',... % W
'(?(3)(\d{2})?|(\d{2}$|\d{2}(?=(\D|\d{2})))?)',... % week/month
'(?(4)(-(?=(?(3)\d|\d{2})))?)',... % -
'(?(4)(?(3)\d|\d{2})?|(\d{3})?)',... % day of week/month/year
'(?(6)([ @T_](?=\d{2}))?)',... % date-time separator character
'(?(7)(\d{2})?)',... % hour
'(?(8)(:(?=\d{2}))?)',... % :
'(?(8)(\d{2})?)',... % minute
'(?(10)(:(?=\d{2}))?)',... % :
'(?(10)(\d{2})?)',... % second
'((\.\d+)?)']; % trailing unit decimal fraction
% (Note: allows a mix of basic/extended formats)
else
% User requests a specific timestamp style.
assert(ischar(Tok)&&isrow(Tok),'Second input <Tok> must be a string.')
TkU = regexp(Tok,'(^\*?)([ymdnYWD]*)([ @T_]?)([HMS]*)(\d*$)','tokens','once');
assert(~isempty(TkU),'Second input <Tok> is not recognized: ''%s''',Tok)
MtE = [TkU{2},TkU{4}];
TkL = numel(MtE);
Ntn = find(strncmp(MtE,{'ymdHMS','ynHMS','YWDHMS'},TkL),1,'first');
assert(~isempty(Ntn),'Second input <Tok> is not recognized: ''%s''',Tok)
MtE = dn8601Usr(TkU,TkL,Ntn);
end
%
assert(ischar(Str)&&size(Str,1)<2,'First input <Str> must be a string.')
%
% Extract timestamp tokens, return split strings:
[TkC,Spl] = regexp(Str,MtE,'tokens','split');
%
[DtN,TkC] = cellfun(@dn8601Main,TkC);
%
end
%----------------------------------------------------------------------END:datenum8601
function [DtN,Tok] = dn8601Main(TkC)
% Convert detected substrings into serial date number, create string token.
%
% Lengths of matched tokens:
TkL = cellfun('length',TkC);
% Preallocate Date Vector:
DtV = [1,1,1,0,0,0];
%
% Create token:
Ext = '*';
Sep = [TkC{7},'HMS'];
TkX = {['ymd',Sep],['y*n',Sep],['YWD',Sep]};
Ntn = 1+(TkL(6)==3)+2*TkL(3);
Tok = [Ext(1:+any(TkL([2,5,9,11])==1)),TkX{Ntn}(0<TkL([1,4,6,7,8,10,12]))];
%
% Convert date and time values to numeric:
Idx = [1,4,6,8,10,12];
for m = find(TkL(Idx));
DtV(m) = sscanf(TkC{Idx(m)},'%f');
end
% Add decimal fraction of trailing unit:
if TkL(13)>1
if Ntn==2&&m==2 % Month (special case not converted by "datenummx"):
DtV(3) = 1+sscanf(TkC{13},'%f')*(datenummx(DtV+[0,1,0,0,0,0])-datenummx(DtV));
else % All other date or time values (are converted by "datenummx"):
DtV(m) = DtV(m)+sscanf(TkC{13},'%f');
end
Tok = {[Tok,sprintf('%.0f',TkL(13)-1)]};
else
Tok = {Tok};
end
%
% Week-numbering vector to ordinal vector:
if Ntn==3
DtV(3) = DtV(3)+7*DtV(2)-4-mod(datenummx([DtV(1),1,1]),7);
DtV(2) = 1;
end
% Convert out-of-range Date Vector to Serial Date Number:
DtN = datenummx(DtV) - 31*(0==DtV(2));
% (Month zero is a special case not converted by "datenummx")
%
end
%----------------------------------------------------------------------END:dn8601Main
function MtE = dn8601Usr(TkU,TkL,Ntn)
% Create "regexp" <match> string from user input token.
%
% Decimal fraction:
if isempty(TkU{5})
MtE{13} = '()';
else
MtE{13} = ['(\.\d{',TkU{5},'})'];
end
% Date-time separator character:
if isempty(TkU{3})
MtE{7} = '(T)';
else
MtE{7} = ['(',TkU{3},')'];
end
% Year and time tokens (year, hour, minute, second):
MtE([1,8,10,12]) = {'(\d{4})','(\d{2})','(\d{2})','(\d{2})'};
% Format tokens:
if isempty(TkU{1}) % Basic
MtE([2,5,9,11]) = {'()','()','()','()'};
else % Extended
MtE([2,5,9,11]) = {'(-)','(-)','(:)','(:)'};
end
% Date tokens:
switch Ntn
case 1 % Calendar
Idx = [2,5,7,9,11,13];
MtE([3,4,6]) = {'()', '(\d{2})','(\d{2})'};
case 2 % Ordinal
Idx = [2,7,9,11,13];
MtE([3,4,5,6]) = {'()','()','()','(\d{3})'};
case 3 % Week
Idx = [2,5,7,9,11,13];
MtE([3,4,6]) = {'(W)','(\d{2})','(\d{1})'};
end
%
% Concatenate tokens into "regexp" match token:
MtE(Idx(TkL):12) = {'()'};
MtE = [MtE{:}];
%
end
%----------------------------------------------------------------------END:dn8601Usr
|
github
|
ZijingMao/baselineeegtest-master
|
xml2struct.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/xml2struct.m
| 6,773 |
utf_8
|
0194599f7bac6b67c42391f372b5ff91
|
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</Element>
% <DifferentElement attrib3="2" attrib4="1">Even more text</DifferentElement>
% </XMLname>
%
% Will 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";
%
% Please note that the following characters are substituted
% '-' by '_dash_', ':' by '_colon_' and '.' by '_dot_'
%
% Written by W. Falkena, ASTI, TUDelft, 21-08-2010
% Attribute parsing speed increased by 40% by A. Wanner, 14-6-2011
% Added CDATA support by I. Smirnov, 20-3-2012
%
% Modified by X. Mo, University of Wisconsin, 12-5-2012
if (nargin < 1)
clc;
help xml2struct
return
end
if isa(file, 'org.apache.xerces.dom.DeferredDocumentImpl') || isa(file, 'org.apache.xerces.dom.DeferredElementImpl')
% input is a java xml object
xDoc = file;
else
%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
%read the xml file
xDoc = xmlread(file);
end
%parse xDoc into a MATLAB structure
s = parseChildNodes(xDoc);
end
% ----- Subfunction parseChildNodes -----
function [children,ptext,textflag] = parseChildNodes(theNode)
% Recurse over node children.
children = struct;
ptext = struct; textflag = 'Text';
if hasChildNodes(theNode)
childNodes = getChildNodes(theNode);
numChildNodes = getLength(childNodes);
for count = 1:numChildNodes
theChild = item(childNodes,count-1);
[text,name,attr,childs,textflag] = getNodeData(theChild);
if (~strcmp(name,'#text') && ~strcmp(name,'#comment') && ~strcmp(name,'#cdata_dash_section'))
%XML allows the same elements to be defined multiple times,
%put each in a different cell
if (isfield(children,name))
if (~iscell(children.(name)))
%put existsing element into cell format
children.(name) = {children.(name)};
end
index = length(children.(name))+1;
%add new element
children.(name){index} = childs;
if(~isempty(fieldnames(text)))
children.(name){index} = text;
end
if(~isempty(attr))
children.(name){index}.('Attributes') = attr;
end
else
%add previously unknown (new) element to the structure
children.(name) = childs;
if(~isempty(text) && ~isempty(fieldnames(text)))
children.(name) = text;
end
if(~isempty(attr))
children.(name).('Attributes') = attr;
end
end
else
ptextflag = 'Text';
if (strcmp(name, '#cdata_dash_section'))
ptextflag = 'CDATA';
elseif (strcmp(name, '#comment'))
ptextflag = 'Comment';
end
%this is the text in an element (i.e., the parentNode)
if (~isempty(regexprep(text.(textflag),'[\s]*','')))
if (~isfield(ptext,ptextflag) || isempty(ptext.(ptextflag)))
ptext.(ptextflag) = text.(textflag);
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.(ptextflag) = [ptext.(ptextflag) text.(textflag)];
end
end
end
end
end
end
% ----- Subfunction getNodeData -----
function [text,name,attr,childs,textflag] = getNodeData(theNode)
% Create structure of node info.
%make sure name is allowed as structure name
name = toCharArray(getNodeName(theNode))';
name = strrep(name, '-', '_dash_');
name = strrep(name, ':', '_colon_');
name = strrep(name, '.', '_dot_');
attr = parseAttributes(theNode);
if (isempty(fieldnames(attr)))
attr = [];
end
%parse child nodes
[childs,text,textflag] = parseChildNodes(theNode);
if (isempty(fieldnames(childs)) && isempty(fieldnames(text)))
%get the data of any childless nodes
% faster than if any(strcmp(methods(theNode), 'getData'))
% no need to try-catch (?)
% faster than text = char(getData(theNode));
text.(textflag) = toCharArray(getTextContent(theNode))';
end
end
% ----- Subfunction parseAttributes -----
function attributes = parseAttributes(theNode)
% Create attributes structure.
attributes = struct;
if hasAttributes(theNode)
theAttributes = getAttributes(theNode);
numAttributes = getLength(theAttributes);
for count = 1:numAttributes
%attrib = item(theAttributes,count-1);
%attr_name = regexprep(char(getName(attrib)),'[-:.]','_');
%attributes.(attr_name) = char(getValue(attrib));
%Suggestion of Adrian Wanner
str = toCharArray(toString(item(theAttributes,count-1)))';
k = strfind(str,'=');
attr_name = str(1:(k(1)-1));
attr_name = strrep(attr_name, '-', '_dash_');
attr_name = strrep(attr_name, ':', '_colon_');
attr_name = strrep(attr_name, '.', '_dot_');
attributes.(attr_name) = str((k(1)+2):(end-1));
end
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
progress.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/progress.m
| 5,835 |
utf_8
|
931aef4557497a7657c39bb4e0508084
|
function n = progress(rate,title)
%PROGRESS Text progress bar
% Similar to waitbar but without the figure display.
%
% Start:
% PROGRESS('init'); initializes the progress bar with title 'Please wait...'
% PROGRESS('init',TITLE); initializes the progress bar with title TITLE
% PROGRESS(RATE); sets the length of the bar to RATE (between 0 and 1)
% PROGRESS(RATE,TITLE); sets the RATE and the TITLE
% PROGRESS('close'); (optionnal) closes the bar
%
% Faster version for high number of loops:
% The function returns a integer indicating the length of the bar.
% This can be use to speed up the computation by avoiding unnecessary
% refresh of the display
% N = PROGRESS('init'); or N = PROGRESS('init',TITLE);
% N = PROGRESS(RATE,N); changes the length of the bar only if different
% from the previous one
% N = PROGRESS(RATE,TITLE); changes the RATE and the TITLE
% PROGRESS('close'); (optionnal) closes the bar
%
% The previous state could be kept in a global variable, but it is a bit
% slower and doesn't allows nested waitbars (see examples)
%
% Known bug: Calling progress('close') shortly afer another call of the
% function may cause strange errors. I guess it is because of the
% backspace char. You can add a pause(0.01) before to avoid this.
%
% Examples:
% progress('init');
% for i=1:100
% progress(i/100, sprintf('loop %d/100',i));
%
% % computing something ...
% pause(.1)
% end
% progress('close'); % optionnal
%
%
% % Inside a script you may use:
% n = progress('init','wait for ... whatever');
% for i=1:100
% n = progress(i/100,n);
%
% % computing something ...
% pause(.1)
% end
% progress('close');
%
%
% % Add a time estimation:
% progress('init','Processing...');
% tic % only if not already called
% t0 = toc; % or toc if tic has already been called
% tm = t0;
% L = 100;
% for i=1:L
% tt = ceil((toc-t0)*(L-i)/i);
% progress(i/L,sprintf('Processing... (estimated time: %ds)',tt));
%
% % computing something ...
% pause(.1)
% end
% progress('close');
%
%
% % Add a faster time estimation:
% n = progress('init','Processing...');
% tic % only if not already called
% t0 = toc; % or toc if tic has already been called
% tm = t0;
% L = 100;
% for i=1:L
% if tm+1 < toc % refresh time every 1s only
% tm = toc;
% tt = ceil((toc-t0)*(L-i)/i);
% n = progress(i/L,sprintf('Processing... (estimated time: %ds)',tt));
% else
% n = progress(i/L,n);
% end
%
% % computing something ...
% pause(.1)
% end
% progress('close');
%
% % Nested loops:
% % One loop...
% n1 = progress('init','Main loop');
% for i=0:7
% n1 = progress(i/7,n1);
%
% % ... and another, inside the first one.
% n2 = progress('init','Inside loop');
% for j=0:50
% n2 = progress(j/50,n2);
%
% % computing something ...
% pause(.01)
% end
% progress('close');
% end
% pause(.01)
% progress('close');
% 31-08-2007
% By Joseph martinot-Lagarde
% [email protected]
% Adapted from:
% MMA 31-8-2005, [email protected]
% Department of Physics
% University of Aveiro, Portugal
%% The simplest way to bypass it...
% n = 0; return
%% Width of the bar
%If changes are made here, change also the default title
lmax=70; % TM: changed from lmax=50;
%% Erasing the bar if necessary
% not needed, but one could find it prettier
if isequal(rate,'close')
% there were 3 '\n' added plus the title and the bar itself
fprintf(rep('\b',2*lmax+3))
return
end
%% The init
if isequal(rate,'init') % If in init stage
cont = 0; % we don't continue a previous bar
back = '\n'; % add a blank line at the begining
rate = 0; % start from 0
else
cont = 1; % we continue a previous bar
end
%% No need to update the view if not necessary
% optional, but saves a LOT of time
% length of the displayer bar in number of char
% double([0,1]) to int([0,lmax-1])
n = min(max( ceil(rate*(lmax-2)) ,0),lmax-2);
% If the 2nd arg is numeric, assumed to be the previous bar length
if nargin >=2 && isnumeric(title)
if n == title % If no change, do nothing
return
else % otherwise continue
n_ = title;
clear title
end
else % draw the whole bar
n_ = -1;
end
%% The title
% If a new title is given, display it
if exist('title','var')
Ltitle = length(title);
if Ltitle > lmax % If too long, cut it
title = [title(1:lmax) '\n']
else % otherwise center it
title = [rep(' ',floor((lmax-Ltitle)/2)) title rep(' ',ceil((lmax-Ltitle)/2)) '\n'];
end
if cont % If not in init stage, erase the '\n' and the previous title
back = rep('\b',lmax+1);
end
else
if cont % If not in init stage, give a void title
title = '';
back = ''; % has to be set
else % else set a default title
title = ' Please wait... \n';
end
end
%% The bar
% '\f' should draw a small square (at least in Windows XP, Matlab 7.3.0 R2006b)
% If not, change to any desired single character, like '*' or '#'
if ~cont || n_ == -1 % at the begining disp the whole bar
str = ['[' rep('*',n) rep(' ',lmax-n-2) ']\n'];
if cont % If not in init stage, erase the previous bar
back = [back, rep('\b',lmax+1)];
end
else % draw only the part that changed
str = [rep('*',n-n_) rep(' ',lmax-n-2) ']\n'];
back = [back, rep('\b',lmax-n_)];
end
%% The print
% Actually make the change
fprintf([back title str]);
return
%% Function to repeat a char n times
function cout = rep(cin,n)
if n==0
cout = [];
return
elseif length(cin)==1
cout = cin(ones(1,n));
return
else
d = [1; 2];
d = d(:,ones(1,n));
cout = cin(reshape(d,1,2*n));
return
end
|
github
|
ZijingMao/baselineeegtest-master
|
strjoin_adjoiner_first.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/strjoin_adjoiner_first.m
| 993 |
utf_8
|
0b68faa60355ed75dc3a7916aa8293cc
|
% Concatenates a cell array of strings.
%
% Input arguments:
% adjoiner:
% string separating each neighboring element
% strings:
% a cell array of strings to join
%
% See also: strsplit, cell2mat
% Copyright 2008-2009 Levente Hunyadi
function string = strjoin(adjoiner, strings)
if isempty(strings)
string = '';
return;
end;
validateattributes(adjoiner, {'char'}, {'vector'});
validateattributes(strings, {'cell'}, {'vector'});
assert(iscellstr(strings), ...
'strjoin:ArgumentTypeMismatch', ...
'The elements to join should be stored in a cell vector of strings (character arrays).');
if isempty(strings)
string = '';
return;
end
% arrange substrings into cell array of strings
concat = cell(1, 2 * numel(strings) - 1); % must be row vector
j = 1;
concat{j} = strings{1};
for i = 2 : length(strings)
j = j + 1;
concat{j} = adjoiner;
j = j + 1;
concat{j} = strings{i};
end
% concatenate substrings preserving spaces
string = cell2mat(concat);
|
github
|
ZijingMao/baselineeegtest-master
|
env_load_dependencies.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/environment/env_load_dependencies.m
| 10,994 |
utf_8
|
2e237b15a1d3f2144f496fe00181882c
|
function env_load_dependencies(dependency_dir,autocompile)
% Execute dependency loaders in the given directory tree.
% env_load_dependencies(Directory)
%
% This function recognizes 3 types of dependency loader scripts in the dependencies (sub-)folders.
% 1. Scripts called env_exec.m. Each such script is executed by env_load_dependencies.
%
% 2. Scripts called env_add.m. Each such function is executed, and if the 'ans' variable is true
% after executing the script (it is set to true before running the script), and no exception
% had occured, the containing directory is added using addpath.
%
% 3. Scripts called env_compile.m. The presence of such a function indicates to the loader function
% that any mex or Java source files in the given directory should be automatically compiled.
% Additional compiler inputs (such as defines, libraries and include directories), if any, may
% be declared as Name=value; statements in the file itself; These will be passed as named arguments
% to hlp_trycompile (examples can be found throughout the existing dependencies).
% A special parameter is Skip, which can be set to false on platforms on which the compilation
% shall be skipped (perhaps because it is known to fail).
%
% In:
% Directory : directory tree with dependencies to be loaded; by default, searches for a directory
% named 'dependencies', relative to the current path or the path of this file.
%
% Compile : whether to act on env_compile.m files (default: true)
%
% Example:
% % load the dependencies in the C:\mydependencies folder.
% env_load_dependencies('C:\mydependencies')
%
% Notes:
% If you intend to compile your toolbox, you cannot use empty .m files. Therefore, your marker files
% must contain at least a space character to satisfy the compiler.
%
% See also:
% env_startup
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2011-03-06
if ~exist('dependency_dir','var')
% other possible directories where the dependencies could be located:
possible_dirs = {pwd,fileparts(mfilename('fullpath'))};
while ~exist('dependency_dir','var')
% for each of the possible directories...
for d=1:length(possible_dirs)
% check whether it contains a 'dependencies' directory
curdir = possible_dirs{d};
if exist([curdir filesep 'dependencies'],'dir')
dependency_dir = [curdir filesep 'dependencies'];
break;
end
% otherwise peel off the last directory
fsp = find(curdir==filesep,1,'last');
if ~isempty(fsp)
possible_dirs{d} = curdir(1:fsp-1); end
end
if cellfun('isempty',possible_dirs)
error('Did not find a directory called ''dependencies''. Please specify it.'); end
end
end
if ~exist('autocompile','var')
autocompile = true; end
if autocompile
% check if compilation is suppressed on this platform
try
fname = [hlp_homedir filesep '.bcilab' filesep 'bcilab-dont-compile'];
fid = fopen(fname,'r');
platforms = fgetl(fid);
fclose(fid);
if strfind(platforms,[hlp_hostname ';'])
autocompile = false; end
catch
end
end
load_dependencies(genpath(dependency_dir),autocompile);
% now, make sure that the build-* directories are included after their ancestor directories...
if ~isdeployed
% get current path order
added_paths = strsplit(path,pathsep)';
added_paths = added_paths(cellfun(@(s)strncmp(dependency_dir,s,length(dependency_dir)),added_paths));
super_dirs = {}; % this is a cell array of super directories with build dirs that may have to be moved
sub_dirs = []; % this is an array of indices (into added_paths) of sub-directories that need
% to be moved in front of the respective super dirs (indexed the same)
% we start from the end so that we don't have to change indices
for p=length(added_paths):-1:1
try
cur = added_paths{p};
k = strfind(cur,[filesep 'build-']);
if ~isempty(k)
% if this is a build directory, add to the potential-move list
super_dirs{end+1} = cur(1:k(end)-1);
sub_dirs(end+1) = p;
end
% check if this is one of the super dirs
match = strcmp(cur,super_dirs);
if any(match)
% move all the respective sub-dirs to right before this position
indices = sub_dirs(match);
added_paths = vertcat(added_paths(1:p-1),added_paths(indices),added_paths(setdiff(p:end,indices)));
super_dirs = super_dirs(~match);
sub_dirs = sub_dirs(~match);
end
catch
warning('bcilab:dependency_glitch','Glitch during mex/build path reordering.');
super_dirs = {};
sub_dirs = [];
end
end
% rebuild path
rmpath(added_paths{:});
addpath(added_paths{:});
end
% from the given path list, add all paths that contain an active env_add.m
% file (active: either empty or runs without exceptions and ans is not being
% set to false), and execute all env_exec.m files
function load_dependencies(pathlist,autocompile)
compile_problems = {};
paths = strsplit(pathlist,pathsep);
for px = paths(end:-1:1)
p = px{1};
if exist([p filesep 'env_add.m'],'file')
% env_add file: check if "active"
[dummy,isactive] = evalc('runscript([p filesep ''env_add.m''])'); %#ok<ASGLU>
% immediately add all java .jar packages
dirinfos = dir([p filesep '*.jar']);
for m={dirinfos.name}
if isdeployed
warning off MATLAB:javaclasspath:jarAlreadySpecified; end
evalc('javaaddpath([p filesep m{1}]);');
end
else
isactive = false;
end
% env_exec file: run it
if exist([p filesep 'env_exec.m'],'file')
runscript([p filesep 'env_exec.m']); end
% env_compile file: invoke compilation, if necessary
if autocompile && exist([p filesep 'env_compile.m'],'file')
settings = get_settings([p filesep 'env_compile.m']);
% the Skip field determines whether the current platform should be skipped
if isfield(settings,'Skip')
docompile = ~settings.Skip;
else
docompile = true;
end
if ~isequal(settings,false) && docompile
if ~hlp_trycompile('Directory',p, 'Style','eager', settings);
compile_problems{end+1} = p; end
end
end
if isactive
% finally add to MATLAB & Java path
if ~isdeployed
addpath(p); end
% also add java files here (note: this may clear global variables)
if ~isempty(dir([p filesep '*.class']))
if isdeployed
warning off MATLAB:javaclasspath:jarAlreadySpecified; end
javaaddpath(p);
end
end
end
% handle compilation errors gracefully
if ~isempty(compile_problems) && ~isdeployed
disp('There were compiling problems for the dependencies in:');
for k=1:length(compile_problems)
disp([' ' compile_problems{k}]); end
fprintf('\n');
disp('This means that the affected features of BCILAB will be disabled.');
if ispc
disp('These issues are usually resolved by installing a (free) Microsoft Visual Studio Express version that is between five years to a half year older than your MATLAB release.');
disp('If you install a new compiler, you might have to type "mex -setup" in the MATLAB command line, before MATLAB recognizes it.');
elseif ismac
disp('These issues are usually resolved by installing the Xcode application that comes with your OS (with all install options to include gcc compiler support).');
elseif isunix
disp('These issues are usually resolved by a installing a version of the gcc compiler package that is between three years to a half year older than your MATLAB release.');
end
yn = lower(input('Should BCILAB try to recompile in the future (or skip recompilation if not)? [y/n]','s'));
if any(strcmp(yn,{'y','n','yes','no'}))
if yn(1) == 'n'
if ~exist([hlp_homedir filesep '.bcilab'],'dir')
if ~mkdir(hlp_homedir,'.bcilab');
disp('Cannot create directory .bcilab in your home folder.'); end
end
fname = [hlp_homedir filesep '.bcilab' filesep 'bcilab-dont-compile'];
disp(['BCILAB will add/update a file called ' fname ' which contains the names of computers on which you chose to disable compilation.']);
fid = fopen(fname,'a');
if fid ~= -1
try
fwrite(fid,[hlp_hostname ';']);
fclose(fid);
catch
try fclose(fid); catch,end
disp('There were permission problems while accessing this file. Did not update it.');
end
else
disp('The file name appears to be invalid on your platform; did not update it.');
end
end
else
disp('Please type ''y'' or ''n'' next time.');
end
fprintf('\n');
end
% run the given script (in its own scope...)
% and return the result of the last line
function ans = runscript(filename__)
try
ans = 1; %#ok<NOANS>
fprintf('Loading %s...\n',fileparts(filename__));
run_script(filename__); % Note: This function is equivalent to run(), but works in deployed mode,
% too. If the code fails here, you probably don't have this
% function in your path. You may retrieve it (it's in the 'misc'
% directory of BCILAB), or replace it here by run().
catch e
disp(['Error running dependency loader ' filename__ '; reason: ' e.message]);
disp('The dependency will likely not be fully operational.');
ans = 0; %#ok<NOANS>
end
% run the given settings script (in its own scope...)
% and return the collected defined variables (or false)
function settings = get_settings(filename__)
try
evalc('run_script(filename__)');
infos = whos();
settings = struct();
for n = {infos.name}
settings.(n{1}) = eval(n{1}); end
catch
disp(['The settings script ' filename__ ' contains an error.']);
settings = false;
end
% Split a string according to some delimiter(s). Not as fast as hlp_split (and doesn't fuse
% delimiters), but doesn't need bsxfun().
function strings = strsplit(string, splitter)
ix = strfind(string, splitter);
strings = cell(1,numel(ix)+1);
ix = [0 ix numel(string)+1];
for k = 2 : numel(ix)
strings{k-1} = string(ix(k-1)+1:ix(k)-1); end
strings = strings(~cellfun('isempty',strings));
|
github
|
ZijingMao/baselineeegtest-master
|
env_clear_classes.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/environment/env_clear_classes.m
| 1,399 |
utf_8
|
9aea4fb7a3c591fd3b2dbf3bbb2857e9
|
function env_clear_classes
% Clear instances of BCI paradigm (and other) classes.
%
% This function is mainly useful when editing the code of BCI paradigms in BCILAB. Whenever after an
% edit a warning along the lines of "Cannot apply change to the class Paradigm*** because some
% instances of the old version still exist" comes up, this function may be called to clear all such
% stray instances without erasing the remaining state of BCILAB.
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2011-12-29
global tracking;
% clear all micro-caches
hlp_microcache('clear');
% also clear all other stray class instances
try
% make a backup of the tracking struct
persistent backup; %#ok<TLEV>
backup = tracking;
% clear the classes, but keep this file (and the backup) locked
mlock;
now_clear;
munlock;
% restore the tracking variable from the backup
restore_tracking(backup);
catch
disp('Error while trying to clear classes from memory.');
end
function now_clear
% this needs to run in a different scope, otherwise the persistent variable ref would get lost
clear classes;
function restore_tracking(backup)
% this must be in a different scope, as we cannot have 2 global statements for the same variable
% in env_clear_memcaches()
global tracking;
tracking = backup;
|
github
|
ZijingMao/baselineeegtest-master
|
env_showmenu.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/environment/env_showmenu.m
| 16,493 |
utf_8
|
159e1459c66a23bf0aa2650e6dd1b8a3
|
function env_showmenu(varargin)
% Links the BCILAB menu into another menu, or creates a new root menu if necessary.
% env_showmenu(Options...)
%
% In:
% Options... : optional name-value pairs; names are:
% 'parent': parent menu to link into
%
% 'shortcuts': whether to enable keyboard shortcuts
%
% 'forcenew': whether to force creation of a new menu
%
% Example:
% % bring up the BCILAB main menu if it had been closed
% env_showmenu;
%
% See also:
% env_startup
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-10-29
% parse options...
hlp_varargin2struct(varargin,'parent',[], 'shortcuts',true,'forcenew',false);
% check if we're an EEGLAB plugin
folders = hlp_split(fileparts(mfilename('fullpath')),filesep);
within_eeglab = length(folders) >= 5 && strcmp(folders{end-3},'plugins') && ~isempty(strfind(folders{end-4},'eeglab'));
% highlight the menu if already there
f = findobj('Tag','bcilab_menu');
if ~isempty(f) && ~forcenew
close(get(f,'Parent')); end
if isempty(parent) %#ok<NODEF>
if within_eeglab && ~forcenew
% try to link into the EEGLAB main menu
try
toolsmenu = findobj(0,'tag','tools');
if ~isempty(toolsmenu)
parent = uimenu(toolsmenu, 'Label','BCILAB');
set(toolsmenu,'Enable','on');
end
catch
disp('Unable to link BCILAB menu into EEGLAB menu.');
end
end
if isempty(parent)
% create new root menu, if no parent
from_left = 100;
from_top = 150;
width = 500;
height = 1;
% determine position on primary monitor
import java.awt.GraphicsEnvironment
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gd = ge.getDefaultScreenDevice();
scrheight = gd.getDisplayMode().getHeight();
pos = [from_left, scrheight-from_top, width, height];
% create figure
figtitle = ['BCILAB ' env_version ' (on ' hlp_hostname ')'];
parent = figure('DockControls','off','NumberTitle','off','Name',figtitle,'Resize','off','MenuBar','none','Position',pos,'Tag','bcilab_toolwnd');
end
end
% Data Source menu
source = uimenu(parent, 'Label','Data Source','Tag','bcilab_menu');
uimenu(source,'Label','Load recording(s)...','Accelerator',char(shortcuts*'l'),'Callback','gui_loadset');
wspace = uimenu(source,'Label','Workspace','Separator','on');
uimenu(wspace,'Label','Load...','Callback','io_loadworkspace');
uimenu(wspace,'Label','Save...','Callback','io_saveworkspace');
uimenu(wspace,'Label','Clear...','Callback','clear');
uimenu(source,'Label','Run script...','Separator','on','Callback',@invoke_script);
if isdeployed
uimenu(source,'Label','Quit','Separator','on','Callback','exit'); end
% Offline Analysis menu
offline = uimenu(parent, 'Label','Offline Analysis');
uimenu(offline,'Label','New approach...','Accelerator',char(shortcuts*'n'),'Callback','gui_newapproach');
uimenu(offline,'Label','Modify approach...','Accelerator',char(shortcuts*'m'),'Callback','gui_configapproach([],true);');
uimenu(offline,'Label','Review/edit approach...','Accelerator',char(shortcuts*'r'),'Callback','gui_reviewapproach([],true);');
uimenu(offline,'Label','Save approach...','Accelerator',char(shortcuts*'s'),'Callback','gui_saveapproach');
uimenu(offline,'Label','Train new model...','Accelerator',char(shortcuts*'t'),'Callback','gui_calibratemodel','Separator','on');
uimenu(offline,'Label','Apply model to data...','Accelerator',char(shortcuts*'a'),'Callback','gui_applymodel');
uimenu(offline,'Label','Visualize model...','Accelerator',char(shortcuts*'v'),'Callback','gui_visualizemodel');
uimenu(offline,'Label','Run batch analysis...','Accelerator',char(shortcuts*'b'),'Callback','gui_batchanalysis','Separator','on');
uimenu(offline,'Label','Review results...','Accelerator',char(shortcuts*'i'),'Callback','gui_selectresults','Separator','on');
% Online Analysis menu
online = uimenu(parent,'Label','Online Analysis');
pipe = uimenu(online,'Label','Process data within...');
read = uimenu(online,'Label','Read input from...');
write = uimenu(online,'Label','Write output to...');
cm_read = uicontextmenu('Tag','bcilab_cm_read');
cm_write = uicontextmenu('Tag','bcilab_cm_write');
% for each plugin sub-directory...
dirs = dir(env_translatepath('functions:/online_plugins'));
for d={dirs(3:end).name}
% find all files, their names, identifiers, and function handles
files = dir(env_translatepath(['functions:/online_plugins/' d{1} '/run_*.m']));
names = {files.name};
idents = cellfun(@(n)n(1:end-2),names,'UniformOutput',false);
% for each entry...
for f=1:length(idents)
try
if ~exist(idents{f},'file') && ~isdeployed
addpath(env_translatepath(['functions:/online_plugins/' d{1}])); end
% get properties...
props = arg_report('properties',str2func(idents{f}));
% get category
if strncmp(idents{f},'run_read',8);
cats = [read,cm_read];
elseif strncmp(idents{f},'run_write',9);
cats = [write,cm_write];
elseif strncmp(idents{f},'run_pipe',8);
cats = pipe;
end
if isfield(props,'name')
% add menu entry
for cat=cats
uimenu(cat,'Label',[props.name '...'],'Callback',['arg_guidialog(@' idents{f} ');'],'Enable','on'); end
else
warning('env_showmenu:missing_guiname','The online plugin %s does not declare a GUI name; ignoring...',idents{f});
end
catch
disp(['Could not integrate the online plugin ' idents{f} '.']);
end
end
end
uimenu(online,'Label','Clear all online processing','Callback','onl_clear','Separator','on');
% Settings menu
settings = uimenu(parent, 'Label','Settings');
uimenu(settings,'Label','Directory settings...','Callback','gui_configpaths');
uimenu(settings,'Label','Cache settings...','Callback','gui_configcache');
uimenu(settings,'Label','Cluster settings...','Callback','gui_configcluster');
uimenu(settings,'Label','Clear memory cache','Callback','env_clear_memcaches','Separator','on');
% Help menu
helping = uimenu(parent,'Label','Help');
uimenu(helping,'Label','BCI Paradigms...','Callback','env_doc code/paradigms');
uimenu(helping,'Label','Filters...','Callback','env_doc code/filters');
uimenu(helping,'Label','Machine Learning...','Callback','env_doc code/machine_learning');
scripting = uimenu(helping,'Label','Scripting');
uimenu(scripting,'Label','File input/output...','Callback','env_doc code/io');
uimenu(scripting,'Label','Dataset editing...','Callback','env_doc code/dataset_editing');
uimenu(scripting,'Label','Offline scripting...','Callback','env_doc code/offline_analysis');
uimenu(scripting,'Label','Online scripting...','Callback','env_doc code/online_analysis');
uimenu(scripting,'Label','BCILAB environment...','Callback','env_doc code/environment');
uimenu(scripting,'Label','Cluster handling...','Callback','env_doc code/parallel');
uimenu(scripting,'Label','Keywords...','Separator','on','Callback','env_doc code/keywords');
uimenu(scripting,'Label','Helpers...','Callback','env_doc code/helpers');
uimenu(scripting,'Label','Internals...','Callback','env_doc code/utils');
authoring = uimenu(helping,'Label','Plugin authoring');
uimenu(authoring,'Label','Argument declaration...','Callback','env_doc code/arguments');
uimenu(authoring,'Label','Expression functions...','Callback','env_doc code/expressions');
uimenu(authoring,'Label','Online processing...','Callback','env_doc code/online_analysis');
uimenu(helping,'Label','About...','Separator','on','Callback',@about);
uimenu(helping,'Label','Save bug report...','Separator','on','Callback','io_saveworkspace([],true)');
uimenu(helping,'Label','File bug report...','Callback','arg_guidialog(@env_bugreport);');
% toolbar (if not linked into the EEGLAB menu)
if ~(within_eeglab && ~forcenew)
global tracking;
cluster_requested = isfield(tracking,'cluster_requested') && ~isempty(tracking.cluster_requested);
cluster_requested = hlp_rewrite(cluster_requested,false,'off',true,'on');
ht = uitoolbar(parent,'HandleVisibility','callback');
uipushtool(ht,'TooltipString','Load recording(s)',...
'CData',load_icon('bcilab:/resources/icons/file_open.png'),...
'HandleVisibility','callback','ClickedCallback','gui_loadset');
uipushtool(ht,'TooltipString','New approach',...
'CData',load_icon('bcilab:/resources/icons/approach_new.png'),...
'HandleVisibility','callback','ClickedCallback','gui_newapproach','Separator','on');
uipushtool(ht,'TooltipString','Load Approach',...
'CData',load_icon('bcilab:/resources/icons/approach_load.png'),...
'HandleVisibility','callback','ClickedCallback',@load_approach);
uipushtool(ht,'TooltipString','Save approach',...
'CData',load_icon('bcilab:/resources/icons/approach_save.png'),...
'HandleVisibility','callback','ClickedCallback','gui_saveapproach');
uipushtool(ht,'TooltipString','Modify approach',...
'CData',load_icon('bcilab:/resources/icons/approach_edit.png'),...
'HandleVisibility','callback','ClickedCallback','gui_configapproach([],true);');
uipushtool(ht,'TooltipString','Review/edit approach',...
'CData',load_icon('bcilab:/resources/icons/approach_review.png'),...
'HandleVisibility','callback','ClickedCallback','gui_reviewapproach([],true);');
uipushtool(ht,'TooltipString','Train new model',...
'CData',load_icon('bcilab:/resources/icons/model_new.png'),...
'HandleVisibility','callback','ClickedCallback','gui_calibratemodel','Separator','on');
uipushtool(ht,'TooltipString','Load Model',...
'CData',load_icon('bcilab:/resources/icons/model_load.png'),...
'HandleVisibility','callback','ClickedCallback',@load_model);
uipushtool(ht,'TooltipString','Save Model',...
'CData',load_icon('bcilab:/resources/icons/model_save.png'),...
'HandleVisibility','callback','ClickedCallback','gui_savemodel');
uipushtool(ht,'TooltipString','Apply model to data',...
'CData',load_icon('bcilab:/resources/icons/model_apply.png'),...
'HandleVisibility','callback','ClickedCallback','gui_applymodel');
uipushtool(ht,'TooltipString','Visualize model',...
'CData',load_icon('bcilab:/resources/icons/model_visualize.png'),...
'HandleVisibility','callback','ClickedCallback','gui_visualizemodel');
uipushtool(ht,'TooltipString','Run batch analysis',...
'CData',load_icon('bcilab:/resources/icons/batch_analysis.png'),...
'HandleVisibility','callback','ClickedCallback','gui_batchanalysis');
uipushtool(ht,'TooltipString','Read input from (online)',...
'CData',load_icon('bcilab:/resources/icons/online_in.png'),...
'HandleVisibility','callback','Separator','on','ClickedCallback',@click_read);
uipushtool(ht,'TooltipString','Write output to (online)',...
'CData',load_icon('bcilab:/resources/icons/online_out.png'),...
'HandleVisibility','callback','ClickedCallback',@click_write);
uipushtool(ht,'TooltipString','Clear online processing',...
'CData',load_icon('bcilab:/resources/icons/online_clear.png'),...
'HandleVisibility','callback','ClickedCallback','onl_clear');
uitoggletool(ht,'TooltipString','Request cluster availability',...
'CData',load_icon('bcilab:/resources/icons/acquire_cluster.png'),'HandleVisibility','callback','Separator','on','State',cluster_requested,'OnCallback','env_acquire_cluster','OffCallback','env_release_cluster');
uipushtool(ht,'TooltipString','About BCILAB',...
'CData',load_icon('bcilab:/resources/icons/help.png'),'HandleVisibility','callback','Separator','on','ClickedCallback',@about);
end
if within_eeglab && forcenew
mainmenu = findobj('Tag','EEGLAB');
% make the EEGLAB menu current again
if ~isempty(mainmenu)
figure(mainmenu); end
end
function about(varargin)
infotext = strvcat(...
'BCILAB is an open-source toolbox for Brain-Computer Interfacing research.', ...
'It is being developed by Christian Kothe at the Swartz Center for Computational Neuroscience,',...
'Institute for Neural Computation (University of California San Diego).', ...
' ',...
'Development of this software was supported by the Army Research Laboratories under', ...
'Cooperative Agreement Number W911NF-10-2-0022, as well as by a gift from the Swartz Foundation.', ...
' ',...
'The design was inspired by the preceding PhyPA toolbox, written by C. Kothe and T. Zander', ...
'at the Berlin Institute of Technology, Chair Human-Machine Systems.', ...
' ',...
'BCILAB connects to the following toolboxes/libraries:', ...
'* AWS SDK (Amazon)', ...
'* Amica (SCCN/UCSD)', ...
'* Chronux (Mitra Lab, Cold Spring Harbor)', ...
'* CVX (Stanford)', ...
'* DAL (U. Tokyo)', ...
'* DataSuite (SCCN/UCSD)', ...
'* EEGLAB (SCCN/UCSD)', ...
'* BCI2000import (www.bci2000.org)', ...
'* Logreg (Jan Drugowitsch)', ...
'* FastICA (Helsinki UT)', ...
'* glm-ie (Max Planck Institute for Biological Cybernetics, Tuebingen)', ...
'* glmnet (Stanford)', ...
'* GMMBayes (Helsinki UT)', ...
'* HKL (Francis Bach, INRIA)', ...
'* KernelICA (Francis Bach, Berkeley)', ...
'* LIBLINEAR (National Taiwan University)', ...
'* matlabcontrol (Joshua Kaplan)', ...
'* mlUnit (Thomas Dohmke)', ...
'* NESTA (Caltech)', ...
'* OSC (Andy Schmeder) and LibLO (Steve Harris)', ...
'* PROPACK (Stanford)', ...
'* PropertyGrid (Levente Hunyadi)', ...
'* SparseBayes (Vector Anomaly)', ...
'* SVMlight (Thorsten Joachims)', ...
'* SVMperf (Thorsten Joachims)', ...
'* Talairach (UTHSCSA)', ...
'* Time-frequency toolbox (CRNS / Rice University)', ...
'* t-SNE (TU Delft)', ...
'* UnLocBox (Nathanael Perraudin et al.)', ...
'* VDPGM (Kenichi Kurihara)'); %#ok<REMFF1>
warndlg2(infotext,'About');
function click_read(varargin)
% pop up a menu when clicking the "read input from" toolbar button
tw = findobj('tag','bcilab_toolwnd');
cm = findobj('tag','bcilab_cm_read');
tpos = get(tw,'Position');
ppos = get(0,'PointerLocation');
set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on');
set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on');
function click_write(varargin)
% pop up a menu when clicking the "write output to" toolbar button
tw = findobj('tag','bcilab_toolwnd');
cm = findobj('tag','bcilab_cm_write');
tpos = get(tw,'Position');
ppos = get(0,'PointerLocation');
set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on');
set(cm,'Position',ppos - tpos(1:2), 'Visible', 'on');
% run a script
function invoke_script(varargin)
[filename,filepath] = uigetfile({'*.m', 'MATLAB file'},'Select script to run',env_translatepath('bcilab:/'));
if ~isnumeric(filename)
run_script([filepath filename],true); end
% load a toolbar icon
function cols = load_icon(filename)
[cols,palette,alpha] = imread(env_translatepath(filename));
if ~isempty(palette)
error('This function does not handle palettized icons.'); end
cls = class(cols);
cols = double(cols);
cols = cols/double(intmax(cls));
cols([alpha,alpha,alpha]==0) = NaN;
% load a BCI model from disk
function load_model(varargin)
[filename,filepath] = uigetfile({'*.mdl', 'BCI Model'},'Select BCI model to load',env_translatepath('home:/.bcilab/models'));
if ~isnumeric(filename)
contents = io_load([filepath filename],'-mat');
for fld=fieldnames(contents)'
tmp = contents.(fld{1});
if isstruct(tmp) && isfield(tmp,'timestamp')
tmp.timestamp = now;
assignin('base',fld{1},tmp);
end
end
end
% load a BCI approach from disk
function load_approach(varargin)
[filename,filepath] = uigetfile({'*.apr', 'BCI Approach'},'Select BCI approach to load',env_translatepath('home:/.bcilab/approaches'));
if ~isnumeric(filename)
contents = io_load([filepath filename],'-mat');
for fld=fieldnames(contents)'
tmp = contents.(fld{1});
if isstruct(tmp) && isfield(tmp,'paradigm')
tmp.timestamp = now;
assignin('base',fld{1},tmp);
end
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
env_buildslave.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/environment/env_buildslave.m
| 8,548 |
utf_8
|
aa1e4148f6acf22b11f24d8df947e0e6
|
function env_buildslave(varargin)
% Run as a build slave: recompile the toolbox whenever it has changed.
%
% In:
% ScanInterval : the interval at which the toolbox is scanned for changes, in seconds
% (default: 30)
%
% WaitPeriod : the period that must have passed between the last change and a rebuild
% (default: 120)
%
% ScanDirectories : the directories and files to scan for changes
% (default: {'bcilab:/code', 'bcilab:/*.m'})
%
% ProjectName : name/location of the project to monitor
% (default: 'bcilab:/build')
%
% SpinInterval : interval at which the function is querying whether the build has
% finished (default: 5)
%
% LogFile : name/location of the logfile, if any
% (default: 'bcilab:/build/buildslave.log')
%
% IssueBuild : function to be called to issue a new build (default: 'env_compile_bcilab')
%
% PostBuild : function to be called after a successful build (default: [])
% (called with the name of the binary)
%
% WaitPreCompile : time to wait until we expect that the compilation has ramped up
% (default: 30)
%
% WaitPostCompile : time to wait until we expect that the compilation has completed (after mcc's have finished)
% (default: 30)
%
% WaitPostConflict : time to wait after we have had a failed build (e.g. due to concurrent editing)
% (default: 120)
%
% Notes:
% This function will likely not run on Win64, as it requires a process monitoring command to work.
%
% See also:
% env_compile_bcilab, deploytool
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2011-03-13
% read options
o = hlp_varargin2struct(varargin, ...
{'scan_interval','ScanInterval'},15, ...
{'wait_period','WaitPeriod'},120, ...
{'scan_dirs','ScanDirectories'},{'bcilab:/code','bcilab:/*.m'}, ...
{'project_name','ProjectName'},'bcilab:/build', ...
{'spin_interval','SpinInterval'},5, ...
{'log','LogFile'},'home:/.bcilab/logs/buildslave.log', ...
{'issue_build','IssueBuild'},@env_compile_bcilab, ...
{'post_build','PostBuild'},[], ...
{'wait_precompile','WaitPreCompile'},30, ...
{'wait_postcompile','WaitPostCompile'},30, ...
{'wait_postconflict','WaitPostConflict'},120);
% sanitize inputs
if ischar(o.scan_dirs)
o.scan_dirs = {o.scan_dirs}; end
for d=1:length(o.scan_dirs)
o.scan_dirs{d} = env_translatepath(o.scan_dirs{d}); end
o.log = env_translatepath(o.log);
if ischar(o.issue_build)
o.issue_build = str2func(o.issue_build); end
if ischar(o.post_build)
o.post_build = str2func(o.post_build); end
% name and location of the project file
o.project_name = env_translatepath(o.project_name);
[proj_dir,proj_tag] = fileparts(o.project_name); proj_dir(end+1) = filesep;
% name and location of the binary
binary_dir = [proj_dir proj_tag filesep 'distrib' filesep];
binary_name = proj_tag;
if ispc
binary_ext = '.exe';
else
binary_ext = '';
end
binary_path = [binary_dir binary_name binary_ext];
% names of marker files
mrk_notsynched = [o.project_name filesep 'not_synched'];
mrk_synching = [o.project_name filesep 'synching'];
mrk_synched = [o.project_name filesep 'synched'];
% check for status of the process monitoring tool...
if ~is_process_running('matlab')
error('Process monitoring does not work on your platform.'); end
% turn off a few warnings
if ispc
warning off MATLAB:FILEATTRIB:SyntaxWarning; end
warning off MATLAB:DELETE:FileNotFound;
% run...
quicklog(o.log,'===== Now running as build slave =====');
cleaner = onCleanup(@cleanup);
while 1
% get the date of the binary
bindate = timestamp(binary_path);
% get the most recent date of scanned directories
codedate = max(cellfun(@timestamp,o.scan_dirs));
% check if we are still sync'ed
if codedate > bindate
quicklog(o.log,'out of sync');
rmfile(mrk_synched);
makefile(mrk_notsynched);
rmfile(mrk_synching);
end
% check if wait period expired and there is no other compilation running...
if (codedate - bindate)*24*60*60 > o.wait_period && ~is_process_running('mcc')
% issue a recompilation...
quicklog(o.log,'recompiling...');
makefile(mrk_synching);
rmfile(mrk_notsynched);
rmfile(mrk_synched);
% rename the binary...
try
ds = datestr(clock); ds(ds == ':' | ds == ' ') = '-';
if exist(binary_path,'file')
movefile(binary_path,[binary_dir binary_name '-old-' ds binary_ext]); end
catch
quicklog(o.log,'cannot move binary %s',binary_path);
end
% issue a rebuild
try
clear functions;
o.issue_build();
% wait until mcc has ramped up
pause(o.wait_precompile);
catch e
quicklog(o.log,evalc('env_handleerror(e)'));
rethrow(e);
end
% wait until mcc's are done ...
while is_process_running('mcc')
pause(o.spin_interval); end
% wait until the packaging has finished...
pause(o.wait_postcompile);
quicklog(o.log,'finished.');
% check whether the code has been edited during the build
newdate = max(cellfun(@timestamp,o.scan_dirs));
if (newdate > codedate) && codedate
quicklog(o.log,'code has been edited concurrently.');
try
% if so, delete the binary
delete(binary_path);
catch
quicklog(o.log,'Cannot delete failed binary. This is a serious condition; exiting...');
return;
end
end
if exist(binary_path,'file')
% binary present
quicklog(o.log,'last compilation successful.');
if ~isempty(o.post_build)
% run the postbuild step
try
quicklog(o.log,'running post-build step...');
o.post_build(binary_path);
quicklog(o.log,'post-build step completed successfully...');
catch e
quicklog(o.log,evalc('env_handleerror(e)'));
rethrow(e);
end
end
makefile(mrk_synched);
rmfile(mrk_notsynched);
rmfile(mrk_synching);
else
% compilation must have been unsucessful...
quicklog(o.log,'last compilation failed...');
makefile(mrk_notsynched);
rmfile(mrk_synched);
rmfile(mrk_synching);
% wait for a moment to let the dust settle
pause(o.wait_postconflict);
end
else
if codedate > bindate
quicklog(o.log,'waiting for edits to finish...'); end
pause(o.scan_interval);
end
end
% calc the most recent time stamp of a given file system location
function ts = timestamp(loc)
if any(loc=='*') || ~exist(loc,'dir')
% assume that it's a file mask / reference
infos = dir(loc);
else
% assume that it's a directory reference
infos = cellfun(@dir,hlp_split(genpath(loc),pathsep),'UniformOutput',false);
infos = vertcat(infos{:});
end
if ~isempty(infos)
% take the maximum time stamp
if ~isfield(infos,'datenum')
[infos.datenum] = celldeal(cellfun(@datenum,{infos.date},'UniformOutput',false)); end
ts = max([infos.datenum]);
else
% no file: set to the beginning of time...
ts = 0;
end
% create a status marker file...
function makefile(name)
try
fid = fopen(name,'w+');
fclose(fid);
fileattrib(name,'+w','a');
catch
if fid ~= -1
try fclose(fid); catch,end
end
end
% remove a status marker file...
function rmfile(name)
try
delete(name);
catch
end
% check if a process is running using OS APIs
function tf = is_process_running(name)
if ispc
cmd = 'wmic process get description';
else
cmd = 'ps -A';
end
[errcode,content] = system(cmd);
if errcode
error('Process monitoring non-operational on your platform. This means you''ll need to compile manually using env_compile_bcilab.'); end
tf = ~isempty(strfind(lower(content),lower(name)));
% clean up any stray MCC tasks
function cleanup(varargin)
if ispc
system('taskkill /F /IM mcc.exe');
else
system('killall mcc');
end
|
github
|
ZijingMao/baselineeegtest-master
|
env_testslave.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/environment/env_testslave.m
| 5,607 |
utf_8
|
b279aa0a6ed3d730783ff07014023600
|
function env_testslave(varargin)
% Run as a test slave: run tests for the toolbox whenever it has changed.
%
% In:
% ScanInterval : the interval at which the toolbox is scanned for changes, in seconds
% (default: 30)
%
% WaitPeriod : the period that must have passed between the last change and a re-test
% (default: 120)
%
% ScanDirectories : the directories and files to scan for changes until re-tests are triggered
% (default: {'bcilab:/code', 'bcilab:/*.m'})
%
% TestDirectory : the directory where the test cases are located
% (default: 'bcilab:/resources/testcases')
%
% IssueTest : function to be called to issue a test run (default: @env_test_bcilab)
% (assumed to return data related to the test summary)
%
% PostTest : function to be called after a test run (default: [])
% (called with the results of IssueTest)
%
% LogFile : name/location of the logfile, if any
% (default: 'bcilab:/build/buildslave.log')
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2011-03-17
% read options
o = hlp_varargin2struct(varargin, ...
{'scan_interval','ScanInterval'},15, ...
{'wait_period','WaitPeriod'},120, ...
{'scan_dirs','ScanDirectories'},{'bcilab:/code','bcilab:/*.m'}, ...
{'issue_test','IssueTest'},@env_test_bcilab, ...
{'post_test','PostTest'},[], ...
{'log','LogFile'},sprintf('bcilab:/resources/testcases/log_%s.log',hlp_hostname), ...
{'report','ReportFile'},'bcilab:/resources/testcases/report_%s-%s.log');
% sanitize inputs
if ischar(o.scan_dirs)
o.scan_dirs = {o.scan_dirs}; end
for d=1:length(o.scan_dirs)
o.scan_dirs{d} = env_translatepath(o.scan_dirs{d}); end
o.log = env_translatepath(o.log);
o.report = env_translatepath(o.report);
if ischar(o.post_build)
o.post_build = str2func(o.post_build); end
% names of marker files
mrk_untested = [proj_dir 'untested'];
mrk_testing = [proj_dir 'testing'];
mrk_tested = [proj_dir 'tested'];
% turn off a few warnings
if ispc
warning off MATLAB:FILEATTRIB:SyntaxWarning; end
warning off MATLAB:DELETE:FileNotFound;
% run...
quicklog(o.log,'===== Now running as test slave =====');
while 1
% get the date of the last test (if any)
testdate = timestamp(mrk_tested);
% get the most recent date of scanned directories
codedate = max(cellfun(@timestamp,o.scan_dirs));
% check if we are still up-to-date
if codedate > testdate
quicklog(o.log,'out of sync');
rmfile(mrk_tested);
makefile(mrk_untested);
rmfile(mrk_testing);
end
% check if wait period expired ...
if (codedate - testdate)*24*60*60 > o.wait_period
% issue a re-test...
quicklog(o.log,'re-testing...');
makefile(mrk_testing);
rmfile(mrk_untested);
rmfile(mrk_tested);
% issue a re-test
try
results = o.issue_test();
catch e
quicklog(o.log,evalc('env_handleerror(e)'));
rethrow(e);
end
quicklog(o.log,'finished.');
% check whether the code has been edited during the build
newdate = max(cellfun(@timestamp,o.scan_dirs));
if (newdate > codedate) && codedate
quicklog(o.log,'code has been edited concurrently.');
% if so, revert to untested
makefile(mrk_untested);
rmfile(mrk_tested);
rmfile(mrk_testing);
else
quicklog(o.log,'testing completed.');
if ~isempty(o.post_test)
% run the post-testing step
try
quicklog(o.log,'running post-testing step...');
o.post_test(results);
quicklog(o.log,'post-testing step completed successfully...');
catch e
quicklog(o.log,evalc('env_handleerror(e)'));
rethrow(e);
end
end
% test completed successfully
makefile(mrk_tested);
rmfile(mrk_untested);
rmfile(mrk_testing);
% write/update report, if applicable
ds = datestr(clock); ds(ds == ':' | ds == ' ') = '-';
if ischar(results)
quicklog(sprintf(o.report,hlp_hostname,ds),results); end
end
else
if codedate > testdate
quicklog(o.log,'waiting for edits to finish...'); end
pause(o.scan_interval);
end
end
% calc the most recent time stamp of a given file system location
function ts = timestamp(loc)
if any(loc=='*') || ~exist(loc,'dir')
% assume that it's a file mask / reference
infos = dir(loc);
else
% assume that it's a directory reference
infos = cellfun(@dir,hlp_split(genpath(loc),pathsep),'UniformOutput',false);
infos = vertcat(infos{:});
end
if ~isempty(infos)
% take the maximum time stamp
if ~isfield(infos,'datenum')
[infos.datenum] = celldeal(cellfun(@datenum,{infos.date},'UniformOutput',false)); end
ts = max([infos.datenum]);
else
% no file: set to the beginning of time...
ts = 0;
end
% create a status marker file...
function makefile(name)
try
fid = fopen(name,'w+');
fclose(fid);
fileattrib(name,'+w','a');
catch
if fid ~= -1
try fclose(fid); catch,end
end
end
% remove a status marker file...
function rmfile(name)
try
delete(name);
catch
end
|
github
|
ZijingMao/baselineeegtest-master
|
env_startup.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/environment/env_startup.m
| 23,183 |
utf_8
|
00cabe6e6e1273c1d7b52a22c679bbc9
|
function env_startup(varargin)
% Start the BCILAB toolbox, i.e. set up global data structures and load dependency toolboxes.
% env_startup(Options...)
%
% Does all steps necessary for loading the toolbox -- the functions bcilab.m and eegplugin_bcilab.m
% are wrappers around this function which provide a higher level of convenience (configuration files
% in particular). Directly calling this function is not recommended.
%
% In:
% Options... : optional name-value pairs; allowed names are:
%
% --- directory settings ---
%
% 'data': Path where data sets are stored, used by data loading/saving routines.
% (default: path/to/bcilab/userdata)
% Note: this may also be a cell array of directories, in which case references
% to data:/ are looked up in all of the specified directories, and the
% best match is taken.
%
% 'store': Path in which data shall be stored. Write permissions necessary (by default
% identical to the data path)
%
% 'temp': temp directory (for misc outputs, e.g., AMICA models and dipole fits)
% (default: path/to/bcilab-temp, or path/to/cache/bcilab_temp if a cache
% directory was specified)
%
% --- caching settings ---
%
% 'cache': Path where intermediate data sets are cached. Should be located on a fast
% (local) drive with sufficient free capacity.
% * if this is left unspecified or empty, the cache is disabled
% * if this is a directory, it is used as the default cache location
% * a fine-grained cache setup can be defined by specifying a cell array of
% cache locations, where each cache location is a cell array of name-value
% pairs, with possible names:
% 'dir': directory of the cache location (e.g. '/tmp/bcilab_tmp/'), mandatory
% 'time': only computations taking more than this many seconds may be stored
% in this location, but if a computation takes so long that another
% cache location with a higher time applies, that other location is
% preferred. For example, the /tmp directory may take computations
% that take at least a minute, the home directory may take
% computations that take at least an hour, the shared /data/results
% location of the lab may take computations that take at least 12
% hours (default: 30 seconds)
% 'free': minimum amount of space to keep free on the given location, in GiB,
% or, if smaller than 1, free is taken as the fraction of total
% space to keep free. (default: 80)
% 'tag': arbitrary identifier for the cache location (default: 'location_i',
% for the i'th location) must be a valid MATLAB struct field name,
% only for display purposes
%
% 'mem_capacity': capacity of the memory cache (default: 2)
% if this is smaller than 1, it is taken as a fraction of the total
% free physical memory at startup time, otherwise it is in GB
%
% 'data_reuses' : estimated number of reuses of a data set being computed (default: 3)
% ... depending on disk access speeds, this determines whether it makes
% sense to cache the data set
%
% --- parallel computing settings ---
%
% 'parallel' : parallelization options; cell array of name-value pairs, with names:
% 'engine': parallelization engine to use, can be 'local',
% 'ParallelComputingToolbox', or 'BLS' (BCILAB Scheduler)
% (default: 'local')
% 'pool': node pool, cell array of 'host:port' strings; necessary for the
% BLS scheduler (default: {'localhost:23547','localhost:23548',
% ..., 'localhost:23554'})
% 'policy': scheduling policy function; necessary for the BLS scheduler
% (default: 'par_reschedule_policy')
%
% note: Parallel processing has so far received only relatively little
% testing. Please use this facility at your own risk and report
% any issues (e.g., starving jobs) that you may encounter.
%
% 'aquire_options' : Cell array of arguments as expected by par_getworkers_ssh
% (with bcilab-specific defaults for unspecified arguments)
% (default: {})
%
% 'worker' : whether this toolbox instance is started as a worker process or not; if
% false, diary logging and GUI menus and popups are enabled. If given as a
% cell array, the cell contents are passed on to the function par_worker,
% which lets the toolbox act as a commandline-less worker (waiting to
% receive jobs over the network) (default: false)
%
% --- misc settings ---
%
% 'menu' : create a menu bar (default: true) -- if this is set to 'separate', the BCILAB
% menu will be detached from the EEGLAB menu, even if run as a plugin.
%
% 'autocompile' : whether to try to auto-compile mex/java files (default: true)
%
% 'show_experimental' : whether to show methods and options marked 'experimental' in
% the GUIs (default: false)
%
% 'show_guru' : whether to show methods and options marked 'guru' in the GUIs
% (default: false)
%
% Examples:
% Note that env_startup is usually not being called directly; instead the bcilab.m function in the
% bcilab root directory forwards its arguments (and variables declared in a config script) to this
% function.
%
% % start BCILAB with a custom data directory, and a custom cache directory
% env_startup('data','C:\Data', 'cache','C:\Data\Temp');
%
% % as before, but specify multiple data paths that are being fused into a common directory view
% % where possible (in case of ambiguities, the earlier directories take precedence)
% env_startup('data',{'C:\Data','F:\Data2'}, 'cache','C:\Data\Temp');
%
% % start BCILAB with a custom data and storage directory, and specify a cache location with some
% % additional meta-data (namely: only cache there if a computation takes at least 60 seconds, and
% % reserve 15GB free space
% env_startup('data','/media/data', 'store','/media/data/results', 'cache',{{'dir','/tmp/tracking','time',60,'free',15}});
%
% % as before, but make sure that the free space does not fall below 20% of the disk
% env_startup('data','/media/data', 'store','/media/data/results', 'cache',{{'dir','/tmp/tracking','time',60,'free',0.2}});
%
% % start BCILAB and set up a very big in-memory cache for working with large data sets (of 16GB)
% env_startup('mem_capacity',16)
%
% % start BCILAB but prevent the main menu from popping up
% env_startup('menu',false)
%
% % start BCILAB and specify which parallel computation resources to use; this assumes that the
% % respective hostnames are reachable from this computer, and are running MATLAB sessions which
% % execute a command similar to: cd /your/path/to/bcilab; bcilab('worker',true); par_worker;
% env_startup('parallel',{'engine','BLS', 'pool',{'computer1','computer2','computer3'}}
%
%
% % start the toolbox as a worker
% env_startup('worker',true)
%
% % start the toolbox as worker, and pass some arguments to par_worker (making it listen on port
% % 15456, using a portrange of 0, and using some custom update-checking arguments
% env_startup('worker',{15456,0,'update_check',{'/data/bcilab-0.9-beta2b/build/bcilab','/mnt/remote/bcilab-build/bcilab'}})
%
% See also:
% env_load_dependencies, env_translatepath
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-03-28
% determine the BCILAB core directories
if ~isdeployed
tmpdir = path_normalize(fileparts(mfilename('fullpath')));
delims = strfind(tmpdir,filesep);
base_dir = tmpdir(1:delims(end-1));
else
% in deployed mode, we walk up until we find the BCILAB base directory
tmpdir = pwd;
delims = strfind(tmpdir,filesep);
disp(['Launching from directory ' tmpdir ' ...']);
for k=length(delims):-1:1
base_dir = tmpdir(1:delims(k));
if exist([base_dir filesep 'code'],'dir')
success = true; %#ok<NASGU>
break;
end
end
if ~exist('success','var')
error('Could not find the ''code'' directory; make sure that the binary is in a sub-directory of a full BCILAB distribution.'); end
end
function_dir = [base_dir 'code'];
dependency_dir = [base_dir 'dependencies'];
resource_dir = [base_dir 'resources'];
script_dir = [base_dir 'userscripts'];
build_dir = [base_dir 'build'];
% add them all to the MATLAB path (except for dependencies, which are loaded separately)
if ~isdeployed
% remove existing BCILAB path references
ea = which('env_add');
if ~isempty(ea)
% get the bcilab root directory that's currently in the path
bad_path = ea(1:strfind(ea,'dependencies')-2);
% remove all references
paths = strsplit(path,pathsep);
retain = cellfun('isempty',strfind(paths,bad_path));
path(sprintf(['%s' pathsep],paths{retain}));
if ~all(retain)
disp(' BCILAB sub-directories have been detected in the MATLAB path, removing them.'); end
end
% add core function paths
addpath(genpath(function_dir));
if exist(build_dir,'dir')
addpath(build_dir); end
evalc('addpath(genpath(script_dir))');
evalc('addpath([base_dir ''userdata''])');
% remove existing eeglab path references, if BCILAB is not itself contained as a plugin in this
% EEGLAB distribution
ep = which('eeglab');
if ~isempty(ep) && isempty(strfind(mfilename('fullpath'),fileparts(which('eeglab'))))
paths = strsplit(path,pathsep);
ep = strsplit(ep,filesep);
retain = cellfun('isempty',strfind(paths,ep{end-1}));
path(sprintf(['%s' pathsep],paths{retain}));
if ~all(retain)
disp(' The previously loaded EEGLAB path has been replaced.'); end
end
end
if hlp_matlab_version < 706
disp('Note: Your version of MATLAB is not supported by BCILAB any more. You may try BCILAB version 0.9, which supports old MATLAB''s back to version 2006a.'); end
% get options
opts = hlp_varargin2struct(varargin,'data',[],'store',[],'cache',[],'temp',[],'mem_capacity',2,'data_reuses',3, ...
'parallel',{'use','local'}, 'menu',true, 'configscript','', 'worker',false, 'autocompile',true, 'acquire_options',{}, ...
'show_experimental',false,'show_guru',false);
% load all dependencies, recursively...
disp('Loading BCILAB dependencies...');
env_load_dependencies(dependency_dir,opts.autocompile);
if ischar(opts.worker)
try
disp(['Evaluating worker argument: ' opts.worker]);
opts.worker = eval(opts.worker);
catch
disp('Failed to evaluate worker; setting it to false.');
opts.worker = false;
end
elseif ~isequal(opts.worker,false)
fprintf('Worker was given as a %s with value %s\n',class(opts.worker),hlp_tostring(opts.worker));
end
if ischar(opts.parallel)
try
disp(['Evaluating parallel argument: ' opts.parallel]);
opts.parallel = eval(opts.parallel);
catch
disp('Failed to evaluate worker; setting it to empty.');
opts.parallel = {};
end
end
% process data directories
if isempty(opts.data)
opts.data = {}; end
if ~iscell(opts.data)
opts.data = {opts.data}; end
for d = 1:length(opts.data)
opts.data{d} = path_normalize(opts.data{d}); end
if isempty(opts.data) || ~any(cellfun(@exist,opts.data))
opts.data = {[base_dir 'userdata']}; end
% process store directory
if isempty(opts.store)
opts.store = opts.data{1}; end
opts.store = path_normalize(opts.store);
% process cache directories
if isempty(opts.cache)
opts.cache = {}; end
if ischar(opts.cache)
opts.cache = {{'dir',opts.cache}}; end
if iscell(opts.cache) && ~isempty(opts.cache) && ~iscell(opts.cache{1})
opts.cache = {opts.cache}; end
for d=1:length(opts.cache)
opts.cache{d} = hlp_varargin2struct(opts.cache{d},'dir','','tag',['location_' num2str(d)],'time',30,'free',80); end
% remove entries with empty dir
opts.cache = opts.cache(cellfun(@(e)~isempty(e.dir),opts.cache));
for d=1:length(opts.cache)
% make sure that the BCILAB cache is in its own proper sub-directory
opts.cache{d}.dir = [path_normalize(opts.cache{d}.dir) filesep 'bcilab_cache'];
% create the directory if necessary
if ~isempty(opts.cache{d}.dir) && ~exist(opts.cache{d}.dir,'dir')
try
io_mkdirs([opts.cache{d}.dir filesep],{'+w','a'});
catch
disp(['cache directory ' opts.cache{d}.dir ' does not exist and could not be created']);
end
end
end
% process temp directory
if isempty(opts.temp)
if ~isempty(opts.cache)
opts.temp = [fileparts(opts.cache{1}.dir) filesep 'bcilab_temp'];
else
opts.temp = [base_dir(1:end-1) '-temp'];
end
end
opts.temp = path_normalize(opts.temp);
try
io_mkdirs([opts.temp filesep],{'+w','a'});
catch
disp(['temp directory ' opts.temp ' does not exist and could not be created.']);
end
% set global variables
global tracking
tracking.paths = struct('bcilab_path',{base_dir(1:end-1)}, 'function_path',{function_dir}, 'data_paths',{opts.data}, 'store_path',{opts.store}, 'dependency_path',{dependency_dir},'resource_path',{resource_dir},'temp_path',{opts.temp});
for d=1:length(opts.cache)
location = rmfield(opts.cache{d},'tag');
% convert GiB to bytes
if location.free >= 1
location.free = location.free*1024*1024*1024; end
try
warning off MATLAB:DELETE:Permission;
% probe the cache locations...
import java.io.*;
% try to add a free space checker (Java File object), which we use to check the quota, etc.
location.space_checker = File(opts.cache{d}.dir);
filename = [opts.cache{d}.dir filesep '__probe_cache_ ' num2str(round(rand*2^32)) '__.mat'];
if exist(filename,'file')
delete(filename); end
oldvalue = location.space_checker.getFreeSpace;
testdata = double(rand(1024)); %#ok<NASGU>
objinfo = whos('testdata');
% do a quick read/write test
t0=tic; save(filename,'testdata'); location.writestats = struct('size',{0 objinfo.bytes},'time',{0 toc(t0)});
t0=tic; load(filename); location.readstats = struct('size',{0 objinfo.bytes},'time',{0 toc(t0)});
newvalue = location.space_checker.getFreeSpace;
if exist(filename,'file')
delete(filename); end
% test if the space checker works, and also get some quick measurements of disk read/write speeds
if newvalue >= oldvalue
location = rmfield(location,'space_checker'); end
% and turn the free space ratio into an absolute value
if location.free < 1
location.free = location.free*location.space_checker.getTotalSpace; end
catch e
disp(['Could not probe cache file system speed; reason: ' e.message]);
end
tracking.cache.disk_paths.(opts.cache{d}.tag) = location;
end
if opts.mem_capacity < 1
free_mem = hlp_memavail();
tracking.cache.capacity = round(opts.mem_capacity * free_mem);
if free_mem < 1024*1024*1024
sprintf('Warning: You have less than 1 GB of free memory (reserving %.0f%% = %.0fMB for data caches).\n',100*opts.mem_capacity,tracking.cache.capacity/(1024*1024));
sprintf(' This will severely impact the offline processing speed of BCILAB.\n');
sprintf(' You may force a fixed amount of cache cacpacity by assinging a value greater than 1 (in GB) to the ''mem_capacity'' variable in your bcilab_config.m.');
end
else
tracking.cache.capacity = opts.mem_capacity*1024*1024*1024;
end
tracking.cache.reuses = opts.data_reuses;
tracking.cache.data = struct();
tracking.cache.sizes = struct();
tracking.cache.times = struct();
if ~isfield(tracking.cache,'disk_paths')
tracking.cache.disk_paths = struct(); end
% initialize stack mechanisms
tracking.stack.base = struct('disable_expressions',false);
% set parallelization settings
tracking.parallel = hlp_varargin2struct(opts.parallel, ...
'engine','local', ...
'pool',{'localhost:23547','localhost:23548','localhost:23549','localhost:23550','localhost:23551','localhost:23552','localhost:23553','localhost:23554'}, ...
'policy','par_reschedule_policy');
tracking.acquire_options = opts.acquire_options;
tracking.configscript = opts.configscript;
% set GUI settings
tracking.gui.show_experimental = opts.show_experimental;
tracking.gui.show_guru = opts.show_guru;
try
cd(script_dir);
catch
end
% set up some microcache domain properties
hlp_microcache('arg','lambda_equality','proper');
hlp_microcache('spec','group_size',5);
hlp_microcache('findfunction','lambda_equality','fast','group_size',5);
hlp_microcache('verybig','max_key_size',2^30,'max_result_size',2^30);
% set up some fine-grained disk-cache locations
hlp_diskcache('filterdesign','folder',opts.temp,'subdir','filterdesign','exactmatch_cutoff',0);
hlp_diskcache('icaweights','folder',opts.temp,'subdir','icaweights','exactmatch_cutoff',0);
hlp_diskcache('dipfits','folder',opts.temp,'subdir','dipfits','exactmatch_cutoff',0);
hlp_diskcache('featuremodels','folder',opts.temp,'subdir','featuremodels','exactmatch_cutoff',0);
hlp_diskcache('predictivemodels','folder',opts.temp,'subdir','predictivemodels','exactmatch_cutoff',0);
hlp_diskcache('statistics','folder',opts.temp,'subdir','statistics','exactmatch_cutoff',0);
hlp_diskcache('general','folder',opts.temp,'subdir','general');
hlp_diskcache('finegrained','folder',opts.temp,'subdir','finegrained');
hlp_diskcache('temporary','folder',opts.temp,'subdir','temporary');
% show toolbox status
fprintf('\n');
disp(['code is in ' function_dir]);
datalocs = [];
for d = opts.data
datalocs = [datalocs d{1} ', ']; end %#ok<AGROW>
disp(['data is in ' datalocs(1:end-2)]);
disp(['results are in ' opts.store]);
if ~isempty(opts.cache)
fnames = fieldnames(tracking.cache.disk_paths);
for f = 1:length(fnames)
if f == 1
disp(['cache is in ' tracking.cache.disk_paths.(fnames{f}).dir ' (' fnames{f} ')']);
else
disp([' ' tracking.cache.disk_paths.(fnames{f}).dir ' (' fnames{f} ')']);
end
end
else
disp('cache is disabled');
end
disp(['temp is in ' opts.temp]);
fprintf('\n');
% turn off a few nasty warnings
warning off MATLAB:log:logOfZero
warning off MATLAB:divideByZero %#ok<RMWRN>
warning off MATLAB:RandStream:ReadingInactiveLegacyGeneratorState % for GMMs....
if isequal(opts.worker,false) || isequal(opts.worker,0)
% --- regular mode ---
% set up logfile
if ~exist([hlp_homedir filesep '.bcilab'],'dir')
if ~mkdir(hlp_homedir,'.bcilab');
disp('Cannot create directory .bcilab in your home folder.'); end
end
tracking.logfile = env_translatepath('home:/.bcilab/logs/bcilab_console.log');
try
if ~exist([hlp_homedir filesep '.bcilab' filesep 'logs'],'dir')
mkdir([hlp_homedir filesep '.bcilab' filesep 'logs']); end
if exist(tracking.logfile,'file')
warning off MATLAB:DELETE:Permission
delete(tracking.logfile);
warning on MATLAB:DELETE:Permission
end
catch,end
try diary(tracking.logfile); catch,end
if ~exist([hlp_homedir filesep '.bcilab' filesep 'models'],'dir')
mkdir([hlp_homedir filesep '.bcilab' filesep 'models']); end
if ~exist([hlp_homedir filesep '.bcilab' filesep 'approaches'],'dir')
mkdir([hlp_homedir filesep '.bcilab' filesep 'approaches']); end
% create a menu
if ~(isequal(opts.menu,false) || isequal(opts.menu,0))
try
env_showmenu('forcenew',strcmp(opts.menu,'separate'));
catch e
disp('Could not open the BCILAB menu; traceback: ');
env_handleerror(e);
end
end
% display a version reminder
bpath = hlp_split(env_translatepath('bcilab:/'),filesep);
if ~isempty(strfind(bpath{end},'-stable'))
if isdeployed
disp(' This is the stable version.');
else
disp(' This is the stable version - please keep this in mind when editing.');
end
elseif ~isempty(strfind(bpath{end},'-devel'))
if isdeployed
disp(' This is the DEVELOPER version.');
else
try
cprintf([0 0.4 1],'This is the DEVELOPER version.\n');
catch
disp(' This is the DEVELOPER version.');
end
end
end
disp([' Welcome to the BCILAB toolbox on ' hlp_hostname '!'])
fprintf('\n');
else
disp('Now entering worker mode...');
% -- worker mode ---
if ~isdeployed
% disable standard dialogs in the workers
addpath(env_translatepath('dependencies:/disabled_dialogs')); end
% close EEGLAB main menu
mainmenu = findobj('Tag','EEGLAB');
if ~isempty(mainmenu)
close(mainmenu); end
drawnow;
% translate the options
if isequal(opts.worker,true)
opts.worker = {}; end
if ~iscell(opts.worker)
opts.worker = {opts.worker}; end
% start!
par_worker(opts.worker{:});
end
try
% pretend to invoke the dependency list so that the compiler finds it...
dependency_list;
catch
end
% normalize a directory path
function dir = path_normalize(dir)
dir = strrep(strrep(dir,'\',filesep),'/',filesep);
if dir(end) == filesep
dir = dir(1:end-1); end
% Split a string according to some delimiter(s). % Not as fast as hlp_split (and doesn't fuse
% delimiters), but works without bsxfun.
function strings = strsplit(string, splitter)
ix = strfind(string, splitter);
strings = cell(1,numel(ix)+1);
ix = [0 ix numel(string)+1];
for k = 2 : numel(ix)
strings{k-1} = string(ix(k-1)+1:ix(k)-1); end
|
github
|
ZijingMao/baselineeegtest-master
|
env_acquire_cluster.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/environment/env_acquire_cluster.m
| 3,786 |
utf_8
|
7ae4a6c911fe57c69049246902a82526
|
function env_acquire_cluster
% Acquire a cluster using the currently configured acquire options.
%
% The behavior of this function is governed by the configuration variable acquire_options that can
% be set either in the config file or in the "Cluster Settings" GUI dialog. Generally, this function
% will (if supported by the OS), check which of the desired cluster resources are already up, and
% start what still needs to be started. There is no guarantee that the cluster resources actually
% start successfully (and don't crash, etc), the function just tries its best. After that, the
% function will start a "heartbeat" timer that periodically tells the cluster resources that it is
% still interested in keeping them alive. Depending on how the cluster was configured, it may shut
% down the resources after they are no longer needed (e.g., for cost reasons).
%
% The heartbeat signal can be disabled by calling env_release_cluster or pressing the "request
% cluster availability" button in the GUI toolbar for a second time.
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2012-04-12
global tracking;
import java.io.*
import java.net.*
import java.lang.*
% interpret as cell array of arguments to par_getworkers_ssh
arguments = tracking.acquire_options;
if isempty(arguments)
disp('No settings for acquiring the cluster have been specified, no startup command will be issued.');
elseif ~iscell(arguments)
disp('The acquire_options parameter should be a cell array of name-value pairs which form arguments to par_getworkers_ssh.');
elseif isunix
% invoke, but also impose default arguments (if unspecified)
% by default, workers do not recruit (but only list) other workers, preventing a cascading effect
try
par_getworkers_ssh(arguments{:});
catch e
disp('Could not acquire worker machines; traceback: ');
env_handleerror(e);
end
else
disp('Cannot automatically acquire hosts from a non-UNIX system.');
end
% start the heartbeat timer
if ~isempty(tracking.parallel.pool)
fprintf('Initiating heartbeat signal... ');
tracking.cluster_requested = {};
% for each endpoint in the pool...
for p=1:length(tracking.parallel.pool)
% make a new socket
sock = DatagramSocket();
% and "connect" it to the worker endpoint (its heartbeat server)
endpoint = hlp_split(tracking.parallel.pool{p},':');
sock.connect(InetSocketAddress(endpoint{1}, str2num(endpoint{2})));
tracking.cluster_requested{p} = sock;
end
% start a timer that sends the heartbeat (every 30 seconds)
start(timer('ExecutionMode','fixedRate', 'Name','heartbeat_timer', 'Period',15, ...
'TimerFcn',@(timer_handle,varargin)send_heartbeat(timer_handle)));
disp('success.');
else
tracking.cluster_requested = true;
end
% called periodically to send heartbeat messages over the network
function send_heartbeat(timer_handle)
import java.io.*
import java.net.*
import java.lang.*
global tracking;
try
if ~isfield(tracking,'cluster_requested') || isempty(tracking.cluster_requested) || ~iscell(tracking.cluster_requested)
error('ouch!'); end
% for each socket in the list of heartbeat sockets...
for p=1:length(tracking.cluster_requested)
try
% send the message
tmp = DatagramPacket(uint8('dsfjk45djf'),10);
tracking.cluster_requested{p}.send(tmp);
catch e
% some socket problem: ignored.
end
end
catch e
% issue (most likely the request has been cancelled) stop & sdelete the heartbeat timer
stop(timer_handle);
delete(timer_handle);
disp('Heartbeat signal stopped.');
end
|
github
|
ZijingMao/baselineeegtest-master
|
loadjson.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/jsonlab/loadjson.m
| 16,145 |
ibm852
|
7582071c5bd7f5e5f74806ce191a9078
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id$
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'^\s*(?:\[.+\])|(?:\{.+\})\s*$','once'))
string=fname;
elseif(exist(fname,'file'))
try
string = fileread(fname);
catch
try
string = urlread(['file://',fname]);
catch
string = urlread(['file://',fullfile(pwd,fname)]);
end
end
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
object.(valid_field(str))=val;
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
if(isstruct(object))
object=struct2jdata(object);
end
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=-1;
if(isfield(varargin{1},'progressbar_'))
pbar=varargin{1}.progressbar_;
end
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
pos=skip_whitespace(pos,inStr,len);
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function newpos=skip_whitespace(pos,inStr,len)
newpos=pos;
while newpos <= len && isspace(inStr(newpos))
newpos = newpos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str);
switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos);
keyboard;
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr isoct
currstr=inStr(pos:min(pos+30,end));
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
if(isfield(varargin{1},'progressbar_'))
waitbar(pos/len,varargin{1}.progressbar_,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
return;
end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos))
return;
end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r))
e1r=bpos(pos);
end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l))
e1l=bpos(pos);
end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
ZijingMao/baselineeegtest-master
|
loadubjson.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/jsonlab/loadubjson.m
| 13,300 |
utf_8
|
b15e959f758c5c2efa2711aa79c443fc
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id$
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
% opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or
% earlier versions (JSONLab 1.0 final or earlier),
% the "name" tag is treated as a string. To load
% these UBJSON data, you need to manually set this
% flag to 1.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
if(jsonopt('NameIsString',0,varargin{:}))
str = parseStr(varargin{:});
else
str = parse_name(varargin{:});
end
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
object.(valid_field(str))=val;
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
if(isstruct(object))
object=struct2jdata(object);
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data, adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object, adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object, adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parse_name(varargin)
global pos inStr
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of name');
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
return;
end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos))
return;
end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r))
e1r=bpos(pos);
end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l))
e1l=bpos(pos);
end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
ZijingMao/baselineeegtest-master
|
savejson_for_ess.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/jsonlab/savejson_for_ess.m
| 19,319 |
utf_8
|
1299e4f40b734fe1fd182b132979005c
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% edited by Nima bigdely-Shamlo and added forceArray___ directive.
%
% $Id$
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array,
% class instance).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.SingletArray [0|1]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.SingletCell [1|0]: if 1, always enclose a cell with "[]"
% even it has only one element; if 0, brackets
% are ignored when a cell has only 1 element.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.emptyString the string to use instead of null for empty values;
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('filename',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
if(isfield(opt,'norowbracket'))
warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)');
if(~isfield(opt,'singletarray'))
opt.singletarray=not(opt.norowbracket);
end
end
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ...
iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
filename=jsonopt('FileName','',opt);
if(~isempty(filename))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(filename, 'wb');
fwrite(fid,json);
else
fid = fopen(filename, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
elseif(isobject(item))
txt=matlabobject2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt={};
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
bracketlevel=~jsonopt('singletcell',1,varargin{:});
if(len>bracketlevel)
if(~isempty(name))
txt={padding0, '"', checkname(name,varargin{:}),'": [', nl}; name='';
else
txt={padding0, '[', nl};
end
elseif(len==0)
if(~isempty(name))
txt={padding0, '"' checkname(name,varargin{:}) '": []'}; name='';
else
txt={padding0, '[]'};
end
end
for i=1:dim(1)
if(dim(1)>1)
txt(end+1:end+3)={padding2,'[',nl};
end
for j=1:dim(2)
txt{end+1}=obj2json(name,item{i,j},level+(dim(1)>1)+(len>bracketlevel),varargin{:});
if(j<dim(2))
txt(end+1:end+2)={',' nl};
end
end
if(dim(1)>1)
txt(end+1:end+3)={nl,padding2,']'};
end
if(i<dim(1))
txt(end+1:end+2)={',' nl};
end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>bracketlevel)
txt(end+1:end+3)={nl,padding0,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt={};
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0));
if isfield(item, 'forceArray_____'); % by Nima to allow focing to be an array
forcearray = true;
item = rmfield(item, 'forceArray_____');
end;
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+forcearray);
nl=ws.newline;
if(isempty(item))
if(~isempty(name))
txt={padding0, '"', checkname(name,varargin{:}),'": []'};
else
txt={padding0, '[]'};
end
return;
end
if(~isempty(name))
if(forcearray)
txt={padding0, '"', checkname(name,varargin{:}),'": [', nl};
end
else
if(forcearray)
txt={padding0, '[', nl};
end
end
for j=1:dim(2)
if(dim(1)>1)
txt(end+1:end+3)={padding2,'[',nl};
end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1 && ~forcearray)
txt(end+1:end+5)={padding1, '"', checkname(name,varargin{:}),'": {', nl};
else
txt(end+1:end+3)={padding1, '{', nl};
end
if(~isempty(names))
for e=1:length(names)
txt{end+1}=obj2json(names{e},item(i,j).(names{e}),...
level+(dim(1)>1)+1+forcearray,varargin{:});
if(e<length(names))
txt{end+1}=',';
end
txt{end+1}=nl;
end
end
txt(end+1:end+2)={padding1,'}'};
if(i<dim(1))
txt(end+1:end+2)={',' nl};
end
end
if(dim(1)>1)
txt(end+1:end+3)={nl,padding2,']'};
end
if(j<dim(2))
txt(end+1:end+2)={',' nl};
end
end
if(forcearray)
txt(end+1:end+3)={nl,padding0,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt={};
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1)
txt={padding1, '"', checkname(name,varargin{:}),'": [', nl};
end
else
if(len>1)
txt={padding1, '[', nl};
end
end
for e=1:len
val=escapejsonstring(item(e,:));
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name))
obj=['"',val,'"'];
end
txt(end+1:end+2)={padding1, obj};
else
txt(end+1:end+4)={padding0,'"',val,'"'};
end
if(e==len)
sep='';
end
txt{end+1}=sep;
end
if(len>1)
txt(end+1:end+3)={nl,padding1,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
(isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matlabobject2json(name,item,level,varargin)
if numel(item) == 0 %empty object
st = struct();
else
% "st = struct(item);" would produce an inmutable warning, because it
% make the protected and private properties visible. Instead we get the
% visible properties
propertynames = properties(item);
for p = 1:numel(propertynames)
for o = numel(item):-1:1 % aray of objects
st(o).(propertynames{p}) = item(o).(propertynames{p});
end
end
end
txt=struct2json(name,st,level,varargin{:});
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt=jsonopt('emptyString','null',varargin{:});
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos))
return;
end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8)
isoct=0;
end
end
if(isoct)
escapechars={'\\','\"','\/','\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\$1');
else
escapechars={'\\','\"','\/','\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\\$1');
end
|
github
|
ZijingMao/baselineeegtest-master
|
saveubjson.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/jsonlab/saveubjson.m
| 17,723 |
utf_8
|
3414421172c05225dfbd4a9c8c76e6b3
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id$
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array,
% class instance)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.SingletArray [0|1]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.SingletCell [1|0]: if 1, always enclose a cell with "[]"
% even it has only one element; if 0, brackets
% are ignored when a cell has only 1 element.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('filename',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
if(isfield(opt,'norowbracket'))
warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)');
if(~isfield(opt,'singletarray'))
opt.singletarray=not(opt.norowbracket);
end
end
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ...
iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
filename=jsonopt('FileName','',opt);
if(~isempty(filename))
fid = fopen(filename, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
elseif(isobject(item))
txt=matlabobject2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
bracketlevel=~jsonopt('singletcell',1,varargin{:});
len=numel(item); % let's handle 1D cell first
if(len>bracketlevel)
if(~isempty(name))
txt=[N_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[N_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1)
txt=[txt '['];
end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>bracketlevel),varargin{:})];
end
if(dim(1)>1)
txt=[txt ']'];
end
end
if(len>bracketlevel)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0));
if(~isempty(name))
if(forcearray)
txt=[N_(checkname(name,varargin{:})) '['];
end
else
if(forcearray)
txt='[';
end
end
for j=1:dim(2)
if(dim(1)>1)
txt=[txt '['];
end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1 && ~forcearray)
txt=[txt N_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},item(i,j).(names{e}),...
level+(dim(1)>1)+1+forcearray,varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1)
txt=[txt ']'];
end
end
if(forcearray)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1)
txt=[N_(checkname(name,varargin{:})) '['];
end
else
if(len>1)
txt='[';
end
end
for e=1:len
val=item(e,:);
if(len==1)
obj=[N_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name))
obj=['',S_(val),''];
end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
(isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[N_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[N_(checkname(name,varargin{:})),'{',N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[N_(checkname(name,varargin{:})) numtxt];
else
txt=[N_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,N_('_ArrayIsComplex_'),'T'];
end
txt=[txt,N_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,N_('_ArrayIsComplex_'),'T'];
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matlabobject2ubjson(name,item,level,varargin)
if numel(item) == 0 %empty object
st = struct();
else
% "st = struct(item);" would produce an inmutable warning, because it
% make the protected and private properties visible. Instead we get the
% visible properties
propertynames = properties(item);
for p = 1:numel(propertynames)
for o = numel(item):-1:1 % aray of objects
st(o).(propertynames{p}) = item(o).(propertynames{p});
end
end
end
txt=struct2ubjson(name,st,level,varargin{:});
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(id~=0))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(id~=0);
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos))
return;
end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=N_(str)
val=[I_(int32(length(str))) str];
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
ZijingMao/baselineeegtest-master
|
xml_write.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/xml_io/xml_write.m
| 18,325 |
utf_8
|
24bd3dc683e5a0a0ad4080deaa6a93a5
|
function DOMnode = xml_write(filename, tree, RootName, Pref)
%XML_WRITE Writes Matlab data structures to XML file
%
% DESCRIPTION
% xml_write( filename, tree) Converts Matlab data structure 'tree' containing
% cells, structs, numbers and strings to Document Object Model (DOM) node
% tree, then saves it to XML file 'filename' using Matlab's xmlwrite
% function. Optionally one can also use alternative version of xmlwrite
% function which directly calls JAVA functions for XML writing without
% MATLAB middleware. This function is provided as a patch to existing
% bugs in xmlwrite (in R2006b).
%
% xml_write(filename, tree, RootName, Pref) allows you to specify
% additional preferences about file format
%
% DOMnode = xml_write([], tree) same as above except that DOM node is
% not saved to the file but returned.
%
% INPUT
% filename file name
% tree Matlab structure tree to store in xml file.
% RootName String with XML tag name used for root (top level) node
% Optionally it can be a string cell array storing: Name of
% root node, document "Processing Instructions" data and
% document "comment" string
% Pref Other preferences:
% Pref.ItemName - default 'item' - name of a special tag used to
% itemize cell or struct arrays
% Pref.XmlEngine - let you choose the XML engine. Currently default is
% 'Xerces', which is using directly the apache xerces java file.
% Other option is 'Matlab' which uses MATLAB's xmlwrite and its
% XMLUtils java file. Both options create identical results except in
% case of CDATA sections where xmlwrite fails.
% Pref.CellItem - default 'true' - allow cell arrays to use 'item'
% notation. See below.
% Pref.RootOnly - default true - output variable 'tree' corresponds to
% xml file root element, otherwise it correspond to the whole file.
% Pref.StructItem - default 'true' - allow arrays of structs to use
% 'item' notation. For example "Pref.StructItem = true" gives:
% <a>
% <b>
% <item> ... <\item>
% <item> ... <\item>
% <\b>
% <\a>
% while "Pref.StructItem = false" gives:
% <a>
% <b> ... <\b>
% <b> ... <\b>
% <\a>
%
%
% Several special xml node types can be created if special tags are used
% for field names of 'tree' nodes:
% - node.CONTENT - stores data section of the node if other fields
% (usually ATTRIBUTE are present. Usually data section is stored
% directly in 'node'.
% - node.ATTRIBUTE.name - stores node's attribute called 'name'.
% - node.COMMENT - create comment child node from the string. For global
% comments see "RootName" input variable.
% - node.PROCESSING_INSTRUCTIONS - create "processing instruction" child
% node from the string. For global "processing instructions" see
% "RootName" input variable.
% - node.CDATA_SECTION - stores node's CDATA section (string). Only works
% if Pref.XmlEngine='Xerces'. For more info, see comments of F_xmlwrite.
% - other special node types like: document fragment nodes, document type
% nodes, entity nodes and notation nodes are not being handled by
% 'xml_write' at the moment.
%
% OUTPUT
% DOMnode Document Object Model (DOM) node tree in the format
% required as input to xmlwrite. (optional)
%
% EXAMPLES:
% MyTree=[];
% MyTree.MyNumber = 13;
% MyTree.MyString = 'Hello World';
% xml_write('test.xml', MyTree);
% type('test.xml')
% %See also xml_tutorial.m
%
% See also
% xml_read, xmlread, xmlwrite
%
% Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com
%% Check Matlab Version
v = ver('MATLAB');
v = str2double(regexp(v.Version, '\d.\d','match','once'));
if (v<7)
error('Your MATLAB version is too old. You need version 7.0 or newer.');
end
%% default preferences
DPref.TableName = {'tr','td'}; % name of a special tags used to itemize 2D cell arrays
DPref.ItemName = 'item'; % name of a special tag used to itemize 1D cell arrays
DPref.StructItem = true; % allow arrays of structs to use 'item' notation
DPref.CellItem = true; % allow cell arrays to use 'item' notation
DPref.StructTable= 'Html';
DPref.CellTable = 'Html';
DPref.XmlEngine = 'Matlab'; % use matlab provided XMLUtils
%DPref.XmlEngine = 'Xerces'; % use Xerces xml generator directly
DPref.PreserveSpace = false; % Preserve or delete spaces at the beggining and the end of stings?
RootOnly = true; % Input is root node only
GlobalProcInst = [];
GlobalComment = [];
GlobalDocType = [];
%% read user preferences
if (nargin>3)
if (isfield(Pref, 'TableName' )), DPref.TableName = Pref.TableName; end
if (isfield(Pref, 'ItemName' )), DPref.ItemName = Pref.ItemName; end
if (isfield(Pref, 'StructItem')), DPref.StructItem = Pref.StructItem; end
if (isfield(Pref, 'CellItem' )), DPref.CellItem = Pref.CellItem; end
if (isfield(Pref, 'CellTable')), DPref.CellTable = Pref.CellTable; end
if (isfield(Pref, 'StructTable')), DPref.StructTable= Pref.StructTable; end
if (isfield(Pref, 'XmlEngine' )), DPref.XmlEngine = Pref.XmlEngine; end
if (isfield(Pref, 'RootOnly' )), RootOnly = Pref.RootOnly; end
if (isfield(Pref, 'PreserveSpace')), DPref.PreserveSpace = Pref.PreserveSpace; end
end
if (nargin<3 || isempty(RootName)), RootName=inputname(2); end
if (isempty(RootName)), RootName='ROOT'; end
if (iscell(RootName)) % RootName also stores global text node data
rName = RootName;
RootName = char(rName{1});
if (length(rName)>1), GlobalProcInst = char(rName{2}); end
if (length(rName)>2), GlobalComment = char(rName{3}); end
if (length(rName)>3), GlobalDocType = char(rName{4}); end
end
if(~RootOnly && isstruct(tree)) % if struct than deal with each field separatly
fields = fieldnames(tree);
for i=1:length(fields)
field = fields{i};
x = tree(1).(field);
if (strcmp(field, 'COMMENT'))
GlobalComment = x;
elseif (strcmp(field, 'PROCESSING_INSTRUCTION'))
GlobalProcInst = x;
elseif (strcmp(field, 'DOCUMENT_TYPE'))
GlobalDocType = x;
else
RootName = field;
t = x;
end
end
tree = t;
end
%% Initialize jave object that will store xml data structure
RootName = varName2str(RootName);
if (~isempty(GlobalDocType))
% n = strfind(GlobalDocType, ' ');
% if (~isempty(n))
% dtype = com.mathworks.xml.XMLUtils.createDocumentType(GlobalDocType);
% end
% DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName, dtype);
warning('xml_io_tools:write:docType', ...
'DOCUMENT_TYPE node was encountered which is not supported yet. Ignoring.');
end
DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName);
%% Use recursive function to convert matlab data structure to XML
root = DOMnode.getDocumentElement;
struct2DOMnode(DOMnode, root, tree, DPref.ItemName, DPref);
%% Remove the only child of the root node
root = DOMnode.getDocumentElement;
Child = root.getChildNodes; % create array of children nodes
nChild = Child.getLength; % number of children
if (nChild==1)
node = root.removeChild(root.getFirstChild);
while(node.hasChildNodes)
root.appendChild(node.removeChild(node.getFirstChild));
end
while(node.hasAttributes) % copy all attributes
root.setAttributeNode(node.removeAttributeNode(node.getAttributes.item(0)));
end
end
%% Save exotic Global nodes
if (~isempty(GlobalComment))
DOMnode.insertBefore(DOMnode.createComment(GlobalComment), DOMnode.getFirstChild());
end
if (~isempty(GlobalProcInst))
n = strfind(GlobalProcInst, ' ');
if (~isempty(n))
proc = DOMnode.createProcessingInstruction(GlobalProcInst(1:(n(1)-1)),...
GlobalProcInst((n(1)+1):end));
DOMnode.insertBefore(proc, DOMnode.getFirstChild());
end
end
% Not supported yet as the code below does not work
% if (~isempty(GlobalDocType))
% n = strfind(GlobalDocType, ' ');
% if (~isempty(n))
% dtype = DOMnode.createDocumentType(GlobalDocType);
% DOMnode.insertBefore(dtype, DOMnode.getFirstChild());
% end
% end
%% save java DOM tree to XML file
if (~isempty(filename))
if (strcmpi(DPref.XmlEngine, 'Xerces'))
xmlwrite_xerces(filename, DOMnode);
else
xmlwrite(filename, DOMnode);
end
end
%% =======================================================================
% === struct2DOMnode Function ===========================================
% =======================================================================
function [] = struct2DOMnode(xml, parent, s, TagName, Pref)
% struct2DOMnode is a recursive function that converts matlab's structs to
% DOM nodes.
% INPUTS:
% xml - jave object that will store xml data structure
% parent - parent DOM Element
% s - Matlab data structure to save
% TagName - name to be used in xml tags describing 's'
% Pref - preferenced
% OUTPUT:
% parent - modified 'parent'
% perform some conversions
if (ischar(s) && min(size(s))>1) % if 2D array of characters
s=cellstr(s); % than convert to cell array
end
% if (strcmp(TagName, 'CONTENT'))
% while (iscell(s) && length(s)==1), s = s{1}; end % unwrap cell arrays of length 1
% end
TagName = varName2str(TagName);
%% == node is a 2D cell array ==
% convert to some other format prior to further processing
nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc?
if (iscell(s) && nDim==2 && strcmpi(Pref.CellTable, 'Matlab'))
s = var2str(s, Pref.PreserveSpace);
end
if (nDim==2 && (iscell (s) && strcmpi(Pref.CellTable, 'Vector')) || ...
(isstruct(s) && strcmpi(Pref.StructTable, 'Vector')))
s = s(:);
end
if (nDim>2), s = s(:); end % can not handle this case well
nItem = numel(s);
nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc?
%% == node is a cell ==
if (iscell(s)) % if this is a cell or cell array
if ((nDim==2 && strcmpi(Pref.CellTable,'Html')) || (nDim< 2 && Pref.CellItem))
% if 2D array of cells than can use HTML-like notation or if 1D array
% than can use item notation
if (strcmp(TagName, 'CONTENT')) % CONTENT nodes already have <TagName> ... </TagName>
array2DOMnode(xml, parent, s, Pref.ItemName, Pref ); % recursive call
else
node = xml.createElement(TagName); % <TagName> ... </TagName>
array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call
parent.appendChild(node);
end
else % use <TagName>...<\TagName> <TagName>...<\TagName> notation
array2DOMnode(xml, parent, s, TagName, Pref ); % recursive call
end
%% == node is a struct ==
elseif (isstruct(s)) % if struct than deal with each field separatly
if ((nDim==2 && strcmpi(Pref.StructTable,'Html')) || (nItem>1 && Pref.StructItem))
% if 2D array of structs than can use HTML-like notation or
% if 1D array of structs than can use 'items' notation
node = xml.createElement(TagName);
array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call
parent.appendChild(node);
elseif (nItem>1) % use <TagName>...<\TagName> <TagName>...<\TagName> notation
array2DOMnode(xml, parent, s, TagName, Pref ); % recursive call
else % otherwise save each struct separatelly
fields = fieldnames(s);
node = xml.createElement(TagName);
for i=1:length(fields) % add field by field to the node
field = fields{i};
x = s.(field);
switch field
case {'COMMENT', 'CDATA_SECTION', 'PROCESSING_INSTRUCTION'}
if iscellstr(x) % cell array of strings -> add them one by one
array2DOMnode(xml, node, x(:), field, Pref ); % recursive call will modify 'node'
elseif ischar(x) % single string -> add it
struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node'
else % not a string - Ignore
warning('xml_io_tools:write:badSpecialNode', ...
['Struct field named ',field,' encountered which was not a string. Ignoring.']);
end
case 'ATTRIBUTE' % set attributes of the node
if (isempty(x)), continue; end
if (isstruct(x))
attName = fieldnames(x); % get names of all the attributes
for k=1:length(attName) % attach them to the node
att = xml.createAttribute(varName2str(attName(k)));
att.setValue(var2str(x.(attName{k}),Pref.PreserveSpace));
node.setAttributeNode(att);
end
else
warning('xml_io_tools:write:badAttribute', ...
'Struct field named ATTRIBUTE encountered which was not a struct. Ignoring.');
end
otherwise % set children of the node
struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node'
end
end % end for i=1:nFields
parent.appendChild(node);
end
%% == node is a leaf node ==
else % if not a struct and not a cell than it is a leaf node
switch TagName % different processing depending on desired type of the node
case 'COMMENT' % create comment node
com = xml.createComment(s);
parent.appendChild(com);
case 'CDATA_SECTION' % create CDATA Section
cdt = xml.createCDATASection(s);
parent.appendChild(cdt);
case 'PROCESSING_INSTRUCTION' % set attributes of the node
OK = false;
if (ischar(s))
n = strfind(s, ' ');
if (~isempty(n))
proc = xml.createProcessingInstruction(s(1:(n(1)-1)),s((n(1)+1):end));
parent.insertBefore(proc, parent.getFirstChild());
OK = true;
end
end
if (~OK)
warning('xml_io_tools:write:badProcInst', ...
['Struct field named PROCESSING_INSTRUCTION need to be',...
' a string, for example: xml-stylesheet type="text/css" ', ...
'href="myStyleSheet.css". Ignoring.']);
end
case 'CONTENT' % this is text part of already existing node
txt = xml.createTextNode(var2str(s, Pref.PreserveSpace)); % convert to text
parent.appendChild(txt);
otherwise % I guess it is a regular text leaf node
txt = xml.createTextNode(var2str(s, Pref.PreserveSpace));
node = xml.createElement(TagName);
node.appendChild(txt);
parent.appendChild(node);
end
end % of struct2DOMnode function
%% =======================================================================
% === array2DOMnode Function ============================================
% =======================================================================
function [] = array2DOMnode(xml, parent, s, TagName, Pref)
% Deal with 1D and 2D arrays of cell or struct. Will modify 'parent'.
nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc?
switch nDim
case 2 % 2D array
for r=1:size(s,1)
subnode = xml.createElement(Pref.TableName{1});
for c=1:size(s,2)
v = s(r,c);
if iscell(v), v = v{1}; end
struct2DOMnode(xml, subnode, v, Pref.TableName{2}, Pref ); % recursive call
end
parent.appendChild(subnode);
end
case 1 %1D array
for iItem=1:numel(s)
v = s(iItem);
if iscell(v), v = v{1}; end
struct2DOMnode(xml, parent, v, TagName, Pref ); % recursive call
end
case 0 % scalar -> this case should never be called
if ~isempty(s)
if iscell(s), s = s{1}; end
struct2DOMnode(xml, parent, s, TagName, Pref );
end
end
%% =======================================================================
% === var2str Function ==================================================
% =======================================================================
function str = var2str(object, PreserveSpace)
% convert matlab variables to a string
switch (1)
case isempty(object)
str = '';
case (isnumeric(object) || islogical(object))
if ndims(object)>2, object=object(:); end % can't handle arrays with dimention > 2
str=mat2str(object); % convert matrix to a string
% mark logical scalars with [] (logical arrays already have them) so the xml_read
% recognizes them as MATLAB objects instead of strings. Same with sparse
% matrices
if ((islogical(object) && isscalar(object)) || issparse(object)),
str = ['[' str ']'];
end
if (isinteger(object)),
str = ['[', class(object), '(', str ')]'];
end
case iscell(object)
if ndims(object)>2, object=object(:); end % can't handle cell arrays with dimention > 2
[nr nc] = size(object);
obj2 = object;
for i=1:length(object(:))
str = var2str(object{i}, PreserveSpace);
if (ischar(object{i})), object{i} = ['''' object{i} '''']; else object{i}=str; end
obj2{i} = [object{i} ','];
end
for r = 1:nr, obj2{r,nc} = [object{r,nc} ';']; end
obj2 = obj2.';
str = ['{' obj2{:} '}'];
case isstruct(object)
str='';
warning('xml_io_tools:write:var2str', ...
'Struct was encountered where string was expected. Ignoring.');
case isa(object, 'function_handle')
str = ['[@' char(object) ']'];
case ischar(object)
str = object;
otherwise
str = char(object);
end
%% string clean-up
str=str(:); str=str.'; % make sure this is a row vector of char's
if (~isempty(str))
str(str<32|str==127)=' '; % convert no-printable characters to spaces
if (~PreserveSpace)
str = strtrim(str); % remove spaces from begining and the end
str = regexprep(str,'\s+',' '); % remove multiple spaces
end
end
%% =======================================================================
% === var2Namestr Function ==============================================
% =======================================================================
function str = varName2str(str)
% convert matlab variable names to a sting
str = char(str);
p = strfind(str,'0x');
if (~isempty(p))
for i=1:length(p)
before = str( p(i)+(0:3) ); % string to replace
after = char(hex2dec(before(3:4))); % string to replace with
str = regexprep(str,before,after, 'once', 'ignorecase');
p=p-3; % since 4 characters were replaced with one - compensate
end
end
str = regexprep(str,'_COLON_',':', 'once', 'ignorecase');
str = regexprep(str,'_DASH_' ,'-', 'once', 'ignorecase');
|
github
|
ZijingMao/baselineeegtest-master
|
xml_read.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/xml_io/xml_read.m
| 23,875 |
utf_8
|
46289b67fb9eefddf374ceaa34ea8ae8
|
function [tree, RootName, DOMnode] = xml_read(xmlfile, Pref)
%XML_READ reads xml files and converts them into Matlab's struct tree.
%
% DESCRIPTION
% tree = xml_read(xmlfile) reads 'xmlfile' into data structure 'tree'
%
% tree = xml_read(xmlfile, Pref) reads 'xmlfile' into data structure 'tree'
% according to your preferences
%
% [tree, RootName, DOMnode] = xml_read(xmlfile) get additional information
% about XML file
%
% INPUT:
% xmlfile URL or filename of xml file to read
% Pref Preferences:
% Pref.ItemName - default 'item' - name of a special tag used to itemize
% cell arrays
% Pref.ReadAttr - default true - allow reading attributes
% Pref.ReadSpec - default true - allow reading special nodes
% Pref.Str2Num - default 'smart' - convert strings that look like numbers
% to numbers. Options: "always", "never", and "smart"
% Pref.KeepNS - default true - keep or strip namespace info
% Pref.NoCells - default true - force output to have no cell arrays
% Pref.Debug - default false - show mode specific error messages
% Pref.NumLevels- default infinity - how many recursive levels are
% allowed. Can be used to speed up the function by prunning the tree.
% Pref.RootOnly - default true - output variable 'tree' corresponds to
% xml file root element, otherwise it correspond to the whole file.
% Pref.CellItem - default 'true' - leave 'item' nodes in cell notation.
% OUTPUT:
% tree tree of structs and/or cell arrays corresponding to xml file
% RootName XML tag name used for root (top level) node.
% Optionally it can be a string cell array storing: Name of
% root node, document "Processing Instructions" data and
% document "comment" string
% DOMnode output of xmlread
%
% DETAILS:
% Function xml_read first calls MATLAB's xmlread function and than
% converts its output ('Document Object Model' tree of Java objects)
% to tree of MATLAB struct's. The output is in format of nested structs
% and cells. In the output data structure field names are based on
% XML tags, except in cases when tags produce illegal variable names.
%
% Several special xml node types result in special tags for fields of
% 'tree' nodes:
% - node.CONTENT - stores data section of the node if other fields are
% present. Usually data section is stored directly in 'node'.
% - node.ATTRIBUTE.name - stores node's attribute called 'name'.
% - node.COMMENT - stores node's comment section (string). For global
% comments see "RootName" output variable.
% - node.CDATA_SECTION - stores node's CDATA section (string).
% - node.PROCESSING_INSTRUCTIONS - stores "processing instruction" child
% node. For global "processing instructions" see "RootName" output variable.
% - other special node types like: document fragment nodes, document type
% nodes, entity nodes, notation nodes and processing instruction nodes
% will be treated like regular nodes
%
% EXAMPLES:
% MyTree=[];
% MyTree.MyNumber = 13;
% MyTree.MyString = 'Hello World';
% xml_write('test.xml', MyTree);
% [tree treeName] = xml_read ('test.xml');
% disp(treeName)
% gen_object_display()
% % See also xml_examples.m
%
% See also:
% xml_write, xmlread, xmlwrite
%
% Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com
% References:
% - Function inspired by Example 3 found in xmlread function.
% - Output data structures inspired by xml_toolbox structures.
%% default preferences
DPref.TableName = {'tr','td'}; % name of a special tags used to itemize 2D cell arrays
DPref.ItemName = 'item'; % name of a special tag used to itemize 1D cell arrays
DPref.CellItem = false; % leave 'item' nodes in cell notation
DPref.ReadAttr = true; % allow reading attributes
DPref.ReadSpec = true; % allow reading special nodes: comments, CData, etc.
DPref.KeepNS = true; % Keep or strip namespace info
DPref.Str2Num = 'smart';% convert strings that look like numbers to numbers
DPref.NoCells = true; % force output to have no cell arrays
DPref.NumLevels = 1e10; % number of recurence levels
DPref.PreserveSpace = false; % Preserve or delete spaces at the beggining and the end of stings?
RootOnly = true; % return root node with no top level special nodes
Debug = false; % show specific errors (true) or general (false)?
tree = [];
RootName = [];
%% Check Matlab Version
v = ver('MATLAB');
try
version = str2double(regexp(v.Version, '\d.\d','match','once'));
if (version<7.1)
error('Your MATLAB version is too old. You need version 7.1 or newer.');
end
catch e
end;
%% read user preferences
if (nargin>1)
if (isfield(Pref, 'TableName')), DPref.TableName = Pref.TableName; end
if (isfield(Pref, 'ItemName' )), DPref.ItemName = Pref.ItemName; end
if (isfield(Pref, 'CellItem' )), DPref.CellItem = Pref.CellItem; end
if (isfield(Pref, 'Str2Num' )), DPref.Str2Num = Pref.Str2Num ; end
if (isfield(Pref, 'NoCells' )), DPref.NoCells = Pref.NoCells ; end
if (isfield(Pref, 'NumLevels')), DPref.NumLevels = Pref.NumLevels; end
if (isfield(Pref, 'ReadAttr' )), DPref.ReadAttr = Pref.ReadAttr; end
if (isfield(Pref, 'ReadSpec' )), DPref.ReadSpec = Pref.ReadSpec; end
if (isfield(Pref, 'KeepNS' )), DPref.KeepNS = Pref.KeepNS; end
if (isfield(Pref, 'RootOnly' )), RootOnly = Pref.RootOnly; end
if (isfield(Pref, 'Debug' )), Debug = Pref.Debug ; end
if (isfield(Pref, 'PreserveSpace')), DPref.PreserveSpace = Pref.PreserveSpace; end
end
if ischar(DPref.Str2Num), % convert from character description to numbers
DPref.Str2Num = find(strcmpi(DPref.Str2Num, {'never', 'smart', 'always'}))-1;
if isempty(DPref.Str2Num), DPref.Str2Num=1; end % 1-smart by default
end
%% read xml file using Matlab function
if isa(xmlfile, 'org.apache.xerces.dom.DeferredDocumentImpl');
% if xmlfile is a DOMnode than skip the call to xmlread
try
try
DOMnode = xmlfile;
catch ME
error('Invalid DOM node: \n%s.', getReport(ME));
end
catch %#ok<CTCH> catch for mablab versions prior to 7.5
error('Invalid DOM node. \n');
end
else % we assume xmlfile is a filename
if (Debug) % in debuging mode crashes are allowed
DOMnode = xmlread(xmlfile);
else % in normal mode crashes are not allowed
try
try
DOMnode = xmlread(xmlfile);
catch ME
error('Failed to read XML file %s: \n%s',xmlfile, getReport(ME));
end
catch %#ok<CTCH> catch for mablab versions prior to 7.5
error('Failed to read XML file %s\n',xmlfile);
end
end
end
Node = DOMnode.getFirstChild;
%% Find the Root node. Also store data from Global Comment and Processing
% Instruction nodes, if any.
GlobalTextNodes = cell(1,3);
GlobalProcInst = [];
GlobalComment = [];
GlobalDocType = [];
while (~isempty(Node))
if (Node.getNodeType==Node.ELEMENT_NODE)
RootNode=Node;
elseif (Node.getNodeType==Node.PROCESSING_INSTRUCTION_NODE)
data = strtrim(char(Node.getData));
target = strtrim(char(Node.getTarget));
GlobalProcInst = [target, ' ', data];
GlobalTextNodes{2} = GlobalProcInst;
elseif (Node.getNodeType==Node.COMMENT_NODE)
GlobalComment = strtrim(char(Node.getData));
GlobalTextNodes{3} = GlobalComment;
% elseif (Node.getNodeType==Node.DOCUMENT_TYPE_NODE)
% GlobalTextNodes{4} = GlobalDocType;
end
Node = Node.getNextSibling;
end
%% parse xml file through calls to recursive DOMnode2struct function
if (Debug) % in debuging mode crashes are allowed
[tree RootName] = DOMnode2struct(RootNode, DPref, 1);
else % in normal mode crashes are not allowed
try
try
[tree RootName] = DOMnode2struct(RootNode, DPref, 1);
catch ME
error('Unable to parse XML file %s: \n %s.',xmlfile, getReport(ME));
end
catch %#ok<CTCH> catch for mablab versions prior to 7.5
error('Unable to parse XML file %s.',xmlfile);
end
end
%% If there were any Global Text nodes than return them
if (~RootOnly)
if (~isempty(GlobalProcInst) && DPref.ReadSpec)
t.PROCESSING_INSTRUCTION = GlobalProcInst;
end
if (~isempty(GlobalComment) && DPref.ReadSpec)
t.COMMENT = GlobalComment;
end
if (~isempty(GlobalDocType) && DPref.ReadSpec)
t.DOCUMENT_TYPE = GlobalDocType;
end
t.(RootName) = tree;
tree=t;
end
if (~isempty(GlobalTextNodes))
GlobalTextNodes{1} = RootName;
RootName = GlobalTextNodes;
end
%% =======================================================================
% === DOMnode2struct Function ===========================================
% =======================================================================
function [s TagName LeafNode] = DOMnode2struct(node, Pref, level)
%% === Step 1: Get node name and check if it is a leaf node ==============
[TagName LeafNode] = NodeName(node, Pref.KeepNS);
s = []; % initialize output structure
%% === Step 2: Process Leaf Nodes (nodes with no children) ===============
if (LeafNode)
if (LeafNode>1 && ~Pref.ReadSpec), LeafNode=-1; end % tags only so ignore special nodes
if (LeafNode>0) % supported leaf node types
try
try % use try-catch: errors here are often due to VERY large fields (like images) that overflow java memory
s = char(node.getData);
if (isempty(s)), s = ' '; end % make it a string
% for some reason current xmlread 'creates' a lot of empty text
% fields with first chatacter=10 - those will be deleted.
if (~Pref.PreserveSpace || s(1)==10)
if (isspace(s(1)) || isspace(s(end))), s = strtrim(s); end % trim speces is any
end
if (LeafNode==1), s=str2var(s, Pref.Str2Num, 0); end % convert to number(s) if needed
catch ME % catch for mablab versions 7.5 and higher
warning('xml_io_tools:read:LeafRead', ...
'This leaf node could not be read and was ignored. ');
getReport(ME)
end
catch %#ok<CTCH> catch for mablab versions prior to 7.5
warning('xml_io_tools:read:LeafRead', ...
'This leaf node could not be read and was ignored. ');
end
end
if (LeafNode==3) % ProcessingInstructions need special treatment
target = strtrim(char(node.getTarget));
s = [target, ' ', s];
end
return % We are done the rest of the function deals with nodes with children
end
if (level>Pref.NumLevels+1), return; end % if Pref.NumLevels is reached than we are done
%% === Step 3: Process nodes with children ===============================
if (node.hasChildNodes) % children present
Child = node.getChildNodes; % create array of children nodes
nChild = Child.getLength; % number of children
% --- pass 1: how many children with each name -----------------------
f = [];
for iChild = 1:nChild % read in each child
[cname cLeaf] = NodeName(Child.item(iChild-1), Pref.KeepNS);
if (cLeaf<0), continue; end % unsupported leaf node types
if (~isfield(f,cname)),
f.(cname)=0; % initialize first time I see this name
end
f.(cname) = f.(cname)+1; % add to the counter
end % end for iChild
% text_nodes become CONTENT & for some reason current xmlread 'creates' a
% lot of empty text fields so f.CONTENT value should not be trusted
if (isfield(f,'CONTENT') && f.CONTENT>2), f.CONTENT=2; end
% --- pass 2: store all the children as struct of cell arrays ----------
for iChild = 1:nChild % read in each child
[c cname cLeaf] = DOMnode2struct(Child.item(iChild-1), Pref, level+1);
if (cLeaf && isempty(c)) % if empty leaf node than skip
continue; % usually empty text node or one of unhandled node types
elseif (nChild==1 && cLeaf==1)
s=c; % shortcut for a common case
else % if normal node
if (level>Pref.NumLevels), continue; end
n = f.(cname); % how many of them in the array so far?
if (~isfield(s,cname)) % encountered this name for the first time
if (n==1) % if there will be only one of them ...
s.(cname) = c; % than save it in format it came in
else % if there will be many of them ...
s.(cname) = cell(1,n);
s.(cname){1} = c; % than save as cell array
end
f.(cname) = 1; % initialize the counter
else % already have seen this name
s.(cname){n+1} = c; % add to the array
f.(cname) = n+1; % add to the array counter
end
end
end % for iChild
end % end if (node.hasChildNodes)
%% === Step 4: Post-process struct's created for nodes with children =====
if (isstruct(s))
fields = fieldnames(s);
nField = length(fields);
% Detect structure that looks like Html table and store it in cell Matrix
if (nField==1 && strcmpi(fields{1},Pref.TableName{1}))
tr = s.(Pref.TableName{1});
fields2 = fieldnames(tr{1});
if (length(fields2)==1 && strcmpi(fields2{1},Pref.TableName{2}))
% This seems to be a special structure such that for
% Pref.TableName = {'tr','td'} 's' corresponds to
% <tr> <td>M11</td> <td>M12</td> </tr>
% <tr> <td>M12</td> <td>M22</td> </tr>
% Recognize it as encoding for 2D struct
nr = length(tr);
for r = 1:nr
row = tr{r}.(Pref.TableName{2});
Table(r,1:length(row)) = row; %#ok<AGROW>
end
s = Table;
end
end
% --- Post-processing: convert 'struct of cell-arrays' to 'array of structs'
% Example: let say s has 3 fields s.a, s.b & s.c and each field is an
% cell-array with more than one cell-element and all 3 have the same length.
% Then change it to array of structs, each with single cell.
% This way element s.a{1} will be now accessed through s(1).a
vec = zeros(size(fields));
for i=1:nField, vec(i) = f.(fields{i}); end
if (numel(vec)>1 && vec(1)>1 && var(vec)==0) % convert from struct of
s = cell2struct(struct2cell(s), fields, 1); % arrays to array of struct
end % if anyone knows better way to do above conversion please let me know.
end
%% === Step 5: Process nodes with attributes =============================
if (node.hasAttributes && Pref.ReadAttr)
if (~isstruct(s)), % make into struct if is not already
ss.CONTENT=s;
s=ss;
end
Attr = node.getAttributes; % list of all attributes
for iAttr = 1:Attr.getLength % for each attribute
name = char(Attr.item(iAttr-1).getName); % attribute name
name = str2varName(name, Pref.KeepNS); % fix name if needed
value = char(Attr.item(iAttr-1).getValue); % attribute value
value = str2var(value, Pref.Str2Num, 1); % convert to number if possible
s.ATTRIBUTE.(name) = value; % save again
end % end iAttr loop
end % done with attributes
if (~isstruct(s)), return; end %The rest of the code deals with struct's
%% === Post-processing: fields of "s"
% convert 'cell-array of structs' to 'arrays of structs'
fields = fieldnames(s); % get field names
nField = length(fields);
for iItem=1:length(s) % for each struct in the array - usually one
for iField=1:length(fields)
field = fields{iField}; % get field name
% if this is an 'item' field and user want to leave those as cells
% than skip this one
if (strcmpi(field, Pref.ItemName) && Pref.CellItem), continue; end
x = s(iItem).(field);
if (iscell(x) && all(cellfun(@isstruct,x(:))) && numel(x)>1) % it's cell-array of structs
% numel(x)>1 check is to keep 1 cell-arrays created when Pref.CellItem=1
try % this operation fails sometimes
% example: change s(1).a{1}.b='jack'; s(1).a{2}.b='john'; to
% more convinient s(1).a(1).b='jack'; s(1).a(2).b='john';
s(iItem).(field) = [x{:}]'; %#ok<AGROW> % converted to arrays of structs
catch %#ok<CTCH>
% above operation will fail if s(1).a{1} and s(1).a{2} have
% different fields. If desired, function forceCell2Struct can force
% them to the same field structure by adding empty fields.
if (Pref.NoCells)
s(iItem).(field) = forceCell2Struct(x); %#ok<AGROW>
end
end % end catch
end
end
end
%% === Step 4: Post-process struct's created for nodes with children =====
% --- Post-processing: remove special 'item' tags ---------------------
% many xml writes (including xml_write) use a special keyword to mark
% arrays of nodes (see xml_write for examples). The code below converts
% s.item to s.CONTENT
ItemContent = false;
if (isfield(s,Pref.ItemName))
s.CONTENT = s.(Pref.ItemName);
s = rmfield(s,Pref.ItemName);
ItemContent = Pref.CellItem; % if CellItem than keep s.CONTENT as cells
end
% --- Post-processing: clean up CONTENT tags ---------------------
% if s.CONTENT is a cell-array with empty elements at the end than trim
% the length of this cell-array. Also if s.CONTENT is the only field than
% remove .CONTENT part and store it as s.
if (isfield(s,'CONTENT'))
if (iscell(s.CONTENT) && isvector(s.CONTENT))
x = s.CONTENT;
for i=numel(x):-1:1, if ~isempty(x{i}), break; end; end
if (i==1 && ~ItemContent)
s.CONTENT = x{1}; % delete cell structure
else
s.CONTENT = x(1:i); % delete empty cells
end
end
if (nField==1)
if (ItemContent)
ss = s.CONTENT; % only child: remove a level but ensure output is a cell-array
s=[]; s{1}=ss;
else
s = s.CONTENT; % only child: remove a level
end
end
end
%% =======================================================================
% === forceCell2Struct Function =========================================
% =======================================================================
function s = forceCell2Struct(x)
% Convert cell-array of structs, where not all of structs have the same
% fields, to a single array of structs
%% Convert 1D cell array of structs to 2D cell array, where each row
% represents item in original array and each column corresponds to a unique
% field name. Array "AllFields" store fieldnames for each column
AllFields = fieldnames(x{1}); % get field names of the first struct
CellMat = cell(length(x), length(AllFields));
for iItem=1:length(x)
fields = fieldnames(x{iItem}); % get field names of the next struct
for iField=1:length(fields) % inspect all fieldnames and find those
field = fields{iField}; % get field name
col = find(strcmp(field,AllFields),1);
if isempty(col) % no column for such fieldname yet
AllFields = [AllFields; field]; %#ok<AGROW>
col = length(AllFields); % create a new column for it
end
CellMat{iItem,col} = x{iItem}.(field); % store rearanged data
end
end
%% Convert 2D cell array to array of structs
s = cell2struct(CellMat, AllFields, 2);
%% =======================================================================
% === str2var Function ==================================================
% =======================================================================
function val=str2var(str, option, attribute)
% Can this string 'str' be converted to a number? if so than do it.
val = str;
len = numel(str);
if (len==0 || option==0), return; end % Str2Num="never" of empty string -> do not do enything
if (len>10000 && option==1), return; end % Str2Num="smart" and string is very long -> probably base64 encoded binary
digits = '(Inf)|(NaN)|(pi)|[\t\n\d\+\-\*\.ei EI\[\]\;\,]';
s = regexprep(str, digits, ''); % remove all the digits and other allowed characters
if (~all(~isempty(s))) % if nothing left than this is probably a number
if (~isempty(strfind(str, ' '))), option=2; end %if str has white-spaces assume by default that it is not a date string
if (~isempty(strfind(str, '['))), option=2; end % same with brackets
str(strfind(str, '\n')) = ';';% parse data tables into 2D arrays, if any
if (option==1) % the 'smart' option
try % try to convert to a date, like 2007-12-05
datenum(str); % if successful than leave it as string
catch %#ok<CTCH> % if this is not a date than ...
option=2; % ... try converting to a number
end
end
if (option==2)
if (attribute)
num = str2double(str); % try converting to a single number using sscanf function
if isnan(num), return; end % So, it wasn't really a number after all
else
num = str2num(str); %#ok<ST2NM> % try converting to a single number or array using eval function
end
if(isnumeric(num) && numel(num)>0), val=num; end % if convertion to a single was succesful than save
end
elseif ((str(1)=='[' && str(end)==']') || (str(1)=='{' && str(end)=='}')) % this looks like a (cell) array encoded as a string
try
val = eval(str);
catch %#ok<CTCH>
val = str;
end
elseif (~attribute) % see if it is a boolean array with no [] brackets
str1 = lower(str);
str1 = strrep(str1, 'false', '0');
str1 = strrep(str1, 'true' , '1');
s = regexprep(str1, '[01 \;\,]', ''); % remove all 0/1, spaces, commas and semicolons
if (~all(~isempty(s))) % if nothing left than this is probably a boolean array
num = str2num(str1); %#ok<ST2NM>
if(isnumeric(num) && numel(num)>0), val = (num>0); end % if convertion was succesful than save as logical
end
end
%% =======================================================================
% === str2varName Function ==============================================
% =======================================================================
function str = str2varName(str, KeepNS)
% convert a sting to a valid matlab variable name
if(KeepNS)
str = regexprep(str,':','_COLON_', 'once', 'ignorecase');
else
k = strfind(str,':');
if (~isempty(k))
str = str(k+1:end);
end
end
str = regexprep(str,'-','_DASH_' ,'once', 'ignorecase');
if (~isvarname(str)) && (~iskeyword(str))
str = genvarname(str);
end
%% =======================================================================
% === NodeName Function =================================================
% =======================================================================
function [Name LeafNode] = NodeName(node, KeepNS)
% get node name and make sure it is a valid variable name in Matlab.
% also get node type:
% LeafNode=0 - normal element node,
% LeafNode=1 - text node
% LeafNode=2 - supported non-text leaf node,
% LeafNode=3 - supported processing instructions leaf node,
% LeafNode=-1 - unsupported non-text leaf node
switch (node.getNodeType)
case node.ELEMENT_NODE
Name = char(node.getNodeName);% capture name of the node
Name = str2varName(Name, KeepNS); % if Name is not a good variable name - fix it
LeafNode = 0;
case node.TEXT_NODE
Name = 'CONTENT';
LeafNode = 1;
case node.COMMENT_NODE
Name = 'COMMENT';
LeafNode = 2;
case node.CDATA_SECTION_NODE
Name = 'CDATA_SECTION';
LeafNode = 2;
case node.DOCUMENT_TYPE_NODE
Name = 'DOCUMENT_TYPE';
LeafNode = 2;
case node.PROCESSING_INSTRUCTION_NODE
Name = 'PROCESSING_INSTRUCTION';
LeafNode = 3;
otherwise
NodeType = {'ELEMENT','ATTRIBUTE','TEXT','CDATA_SECTION', ...
'ENTITY_REFERENCE', 'ENTITY', 'PROCESSING_INSTRUCTION', 'COMMENT',...
'DOCUMENT', 'DOCUMENT_TYPE', 'DOCUMENT_FRAGMENT', 'NOTATION'};
Name = char(node.getNodeName);% capture name of the node
warning('xml_io_tools:read:unkNode', ...
'Unknown node type encountered: %s_NODE (%s)', NodeType{node.getNodeType}, Name);
LeafNode = -1;
end
|
github
|
ZijingMao/baselineeegtest-master
|
DataHash.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/data_hash/DataHash.m
| 15,429 |
utf_8
|
e725a80cb9180de1eb03e47b850a95dc
|
function Hash = DataHash(Data, Opt)
% DATAHASH - Checksum for Matlab array of any type
% This function creates a hash value for an input of any type. The type and
% dimensions of the input are considered as default, such that UINT8([0,0]) and
% UINT16(0) have different hash values. Nested STRUCTs and CELLs are parsed
% recursively.
%
% Hash = DataHash(Data, Opt)
% INPUT:
% Data: Array of these built-in types:
% (U)INT8/16/32/64, SINGLE, DOUBLE, (real or complex)
% CHAR, LOGICAL, CELL (nested), STRUCT (scalar or array, nested),
% function_handle.
% Opt: Struct to specify the hashing algorithm and the output format.
% Opt and all its fields are optional.
% Opt.Method: String, known methods for Java 1.6 (Matlab 2009a):
% 'SHA-1', 'SHA-256', 'SHA-384', 'SHA-512', 'MD2', 'MD5'.
% Known methods for Java 1.3 (Matlab 6.5):
% 'MD5', 'SHA-1'.
% Default: 'MD5'.
% Opt.Format: String specifying the output format:
% 'hex', 'HEX': Lower/uppercase hexadecimal string.
% 'double', 'uint8': Numerical vector.
% 'base64': Base64 encoded string, only printable
% ASCII characters, 33% shorter than 'hex'.
% Default: 'hex'.
% Opt.Input: Type of the input as string, not case-sensitive:
% 'array': The contents, type and size of the input [Data] are
% considered for the creation of the hash. Nested CELLs
% and STRUCT arrays are parsed recursively. Empty arrays of
% different type reply different hashs.
% 'file': [Data] is treated as file name and the hash is calculated
% for the files contents.
% 'bin': [Data] is a numerical, LOGICAL or CHAR array. Only the
% binary contents of the array is considered, such that
% e.g. empty arrays of different type reply the same hash.
% Default: 'array'.
%
% OUTPUT:
% Hash: String, DOUBLE or UINT8 vector. The length depends on the hashing
% method.
%
% EXAMPLES:
% % Default: MD5, hex:
% DataHash([]) % 7de5637fd217d0e44e0082f4d79b3e73
% % MD5, Base64:
% Opt.Format = 'base64';
% Opt.Method = 'MD5';
% DataHash(int32(1:10), Opt) % bKdecqzUpOrL4oxzk+cfyg
% % SHA-1, Base64:
% S.a = uint8([]);
% S.b = {{1:10}, struct('q', uint64(415))};
% Opt.Method = 'SHA-1';
% DataHash(S, Opt) % ZMe4eUAp0G9TDrvSW0/Qc0gQ9/A
% % SHA-1 of binary values:
% Opt.Method = 'SHA-1';
% Opt.Input = 'bin';
% DataHash(1:8, Opt) % 826cf9d3a5d74bbe415e97d4cecf03f445f69225
%
% NOTE:
% Function handles and user-defined objects cannot be converted uniquely:
% - The subfunction ConvertFuncHandle uses the built-in function FUNCTIONS,
% but the replied struct can depend on the Matlab version.
% - It is tried to convert objects to UINT8 streams in the subfunction
% ConvertObject. A conversion by STRUCT() might be more appropriate.
% Adjust these subfunctions on demand.
%
% MATLAB CHARs have 16 bits! In consequence the string 'hello' is treated as
% UINT16('hello') for the binary input method.
%
% DataHash uses James Tursa's smart and fast TYPECASTX, if it is installed:
% http://www.mathworks.com/matlabcentral/fileexchange/17476
% As fallback the built-in TYPECAST is used automatically, but for large
% inputs this can be more than 100 times slower.
% For Matlab 6.5 installing typecastx is obligatory to run DataHash.
%
% Tested: Matlab 6.5, 7.7, 7.8, 7.13, WinXP/32, Win7/64
% Author: Jan Simon, Heidelberg, (C) 2011-2012 matlab.THISYEAR(a)nMINUSsimon.de
%
% See also: TYPECAST, CAST.
% FEX:
% Michael Kleder, "Compute Hash", no structs and cells:
% http://www.mathworks.com/matlabcentral/fileexchange/8944
% Tim, "Serialize/Deserialize", converts structs and cells to a byte stream:
% http://www.mathworks.com/matlabcentral/fileexchange/29457
% Jan Simon, "CalcMD5", MD5 only, faster C-mex, no structs and cells:
% http://www.mathworks.com/matlabcentral/fileexchange/25921
% $JRev: R-k V:011 Sum:kZG25iszfKbg Date:28-May-2012 12:48:06 $
% $License: BSD (use/copy/change/redistribute on own risk, mention the author) $
% $File: Tools\GLFile\DataHash.m $
% History:
% 001: 01-May-2011 21:52, First version.
% 007: 10-Jun-2011 10:38, [Opt.Input], binary data, complex values considered.
% 011: 26-May-2012 15:57, Fails for binary input and empty data.
% Main function: ===============================================================
% Java is needed:
if ~usejava('jvm')
error(['JSimon:', mfilename, ':NoJava'], ...
'*** %s: Java is required.', mfilename);
end
% typecastx creates a shared data copy instead of the deep copy as Matlab's
% TYPECAST - for a [1000x1000] DOUBLE array this is 100 times faster!
persistent usetypecastx
if isempty(usetypecastx)
usetypecastx = ~isempty(which('typecastx')); % Run the slow WHICH once only
end
% Default options: -------------------------------------------------------------
Method = 'MD5';
OutFormat = 'hex';
isFile = false;
isBin = false;
% Check number and type of inputs: ---------------------------------------------
nArg = nargin;
if nArg == 2
if isa(Opt, 'struct') == 0 % Bad type of 2nd input:
error(['JSimon:', mfilename, ':BadInput2'], ...
'*** %s: 2nd input [Opt] must be a struct.', mfilename);
end
% Specify hash algorithm:
if isfield(Opt, 'Method')
Method = upper(Opt.Method);
end
% Specify output format:
if isfield(Opt, 'Format')
OutFormat = Opt.Format;
end
% Check if the Input type is specified - default: 'array':
if isfield(Opt, 'Input')
if strcmpi(Opt.Input, 'File')
isFile = true;
if ischar(Data) == 0
error(['JSimon:', mfilename, ':CannotOpen'], ...
'*** %s: 1st input is not a file name', mfilename);
end
if exist(Data, 'file') ~= 2
error(['JSimon:', mfilename, ':FileNotFound'], ...
'*** %s: File not found: %s.', mfilename, Data);
end
elseif strncmpi(Opt.Input, 'bin', 3) % Accept 'binary'
isBin = true;
if (isnumeric(Data) || ischar(Data) || islogical(Data)) == 0
error(['JSimon:', mfilename, ':BadDataType'], ...
'*** %s: 1st input is not numeric, CHAR or LOGICAL.', mfilename);
end
end
end
elseif nArg ~= 1 % Bad number of arguments:
error(['JSimon:', mfilename, ':BadNInput'], ...
'*** %s: 1 or 2 inputs required.', mfilename);
end
% Create the engine: -----------------------------------------------------------
try
Engine = java.security.MessageDigest.getInstance(Method);
catch
error(['JSimon:', mfilename, ':BadInput2'], ...
'*** %s: Invalid algorithm: [%s].', mfilename, Method);
end
% Create the hash value: -------------------------------------------------------
if isFile
% Read the file and calculate the hash:
FID = fopen(Data, 'r');
if FID < 0
error(['JSimon:', mfilename, ':CannotOpen'], ...
'*** %s: Cannot open file: %s.', mfilename, Data);
end
Data = fread(FID, Inf, '*uint8');
fclose(FID);
Engine.update(Data);
if usetypecastx
Hash = typecastx(Engine.digest, 'uint8');
else
Hash = typecast(Engine.digest, 'uint8');
end
elseif isBin % Contents of an elementary array:
if isempty(Data) % Nothing to do, Engine.update fails for empty input!
Hash = typecastx(Engine.digest, 'uint8');
elseif usetypecastx % Faster typecastx:
if isreal(Data)
Engine.update(typecastx(Data(:), 'uint8'));
else
Engine.update(typecastx(real(Data(:)), 'uint8'));
Engine.update(typecastx(imag(Data(:)), 'uint8'));
end
Hash = typecastx(Engine.digest, 'uint8');
else % Matlab's TYPECAST is less elegant:
if isnumeric(Data)
if isreal(Data)
Engine.update(typecast(Data(:), 'uint8'));
else
Engine.update(typecast(real(Data(:)), 'uint8'));
Engine.update(typecast(imag(Data(:)), 'uint8'));
end
elseif islogical(Data) % TYPECAST cannot handle LOGICAL
Engine.update(typecast(uint8(Data(:)), 'uint8'));
elseif ischar(Data) % TYPECAST cannot handle CHAR
Engine.update(typecast(uint16(Data(:)), 'uint8'));
Engine.update(typecast(Data(:), 'uint8'));
end
Hash = typecast(Engine.digest, 'uint8');
end
elseif usetypecastx % Faster typecastx:
Engine = CoreHash_(Data, Engine);
Hash = typecastx(Engine.digest, 'uint8');
else % Slower built-in TYPECAST:
Engine = CoreHash(Data, Engine);
Hash = typecast(Engine.digest, 'uint8');
end
% Convert hash specific output format: -----------------------------------------
switch OutFormat
case 'hex'
Hash = sprintf('%.2x', double(Hash));
case 'HEX'
Hash = sprintf('%.2X', double(Hash));
case 'double'
Hash = double(reshape(Hash, 1, []));
case 'uint8'
Hash = reshape(Hash, 1, []);
case 'base64'
Hash = fBase64_enc(double(Hash));
otherwise
error(['JSimon:', mfilename, ':BadOutFormat'], ...
'*** %s: [Opt.Format] must be: HEX, hex, uint8, double, base64.', ...
mfilename);
end
% return;
% ******************************************************************************
function Engine = CoreHash_(Data, Engine)
% This mothod uses the faster typecastx version.
% Consider the type and dimensions of the array to distinguish arrays with the
% same data, but different shape: [0 x 0] and [0 x 1], [1,2] and [1;2],
% DOUBLE(0) and SINGLE([0,0]):
Engine.update([uint8(class(Data)), typecastx(size(Data), 'uint8')]);
if isstruct(Data) % Hash for all array elements and fields:
F = sort(fieldnames(Data)); % Ignore order of fields
Engine = CoreHash_(F, Engine); % Catch the fieldnames
for iS = 1:numel(Data) % Loop over elements of struct array
for iField = 1:length(F) % Loop over fields
Engine = CoreHash_(Data(iS).(F{iField}), Engine);
end
end
elseif iscell(Data) % Get hash for all cell elements:
for iS = 1:numel(Data)
Engine = CoreHash_(Data{iS}, Engine);
end
elseif isnumeric(Data) || islogical(Data) || ischar(Data)
if isempty(Data) == 0
if isreal(Data) % TRUE for LOGICAL and CHAR also:
Engine.update(typecastx(Data(:), 'uint8'));
else % typecastx accepts complex input:
Engine.update(typecastx(real(Data(:)), 'uint8'));
Engine.update(typecastx(imag(Data(:)), 'uint8'));
end
end
elseif isa(Data, 'function_handle')
Engine = CoreHash(ConvertFuncHandle(Data), Engine);
else % Most likely this is a user-defined object:
try
Engine = CoreHash(ConvertObject(Data), Engine);
catch
warning(['JSimon:', mfilename, ':BadDataType'], ...
['Type of variable not considered: ', class(Data)]);
end
end
% return;
% ******************************************************************************
function Engine = CoreHash(Data, Engine)
% This methods uses the slower TYPECAST of Matlab
% See CoreHash_ for comments.
Engine.update([uint8(class(Data)), typecast(size(Data), 'uint8')]);
if isstruct(Data) % Hash for all array elements and fields:
F = sort(fieldnames(Data)); % Ignore order of fields
Engine = CoreHash(F, Engine); % Catch the fieldnames
for iS = 1:numel(Data) % Loop over elements of struct array
for iField = 1:length(F) % Loop over fields
Engine = CoreHash(Data(iS).(F{iField}), Engine);
end
end
elseif iscell(Data) % Get hash for all cell elements:
for iS = 1:numel(Data)
Engine = CoreHash(Data{iS}, Engine);
end
elseif isempty(Data)
elseif isnumeric(Data)
if isreal(Data)
Engine.update(typecast(Data(:), 'uint8'));
else
Engine.update(typecast(real(Data(:)), 'uint8'));
Engine.update(typecast(imag(Data(:)), 'uint8'));
end
elseif islogical(Data) % TYPECAST cannot handle LOGICAL
Engine.update(typecast(uint8(Data(:)), 'uint8'));
elseif ischar(Data) % TYPECAST cannot handle CHAR
Engine.update(typecast(uint16(Data(:)), 'uint8'));
elseif isa(Data, 'function_handle')
Engine = CoreHash(ConvertFuncHandle(Data), Engine);
else % Most likely a user-defined object:
try
Engine = CoreHash(ConvertObject(Data), Engine);
catch
warning(['JSimon:', mfilename, ':BadDataType'], ...
['Type of variable not considered: ', class(Data)]);
end
end
% return;
% ******************************************************************************
function FuncKey = ConvertFuncHandle(FuncH)
% The subfunction ConvertFuncHandle converts function_handles to a struct
% using the Matlab function FUNCTIONS. The output of this function changes
% with the Matlab version, such that DataHash(@sin) replies different hashes
% under Matlab 6.5 and 2009a.
% An alternative is using the function name and name of the file for
% function_handles, but this is not unique for nested or anonymous functions.
% If the MATLABROOT is removed from the file's path, at least the hash of
% Matlab's toolbox functions is (usually!) not influenced by the version.
% Finally I'm in doubt if there is a unique method to hash function handles.
% Please adjust the subfunction ConvertFuncHandles to your needs.
% The Matlab version influences the conversion by FUNCTIONS:
% 1. The format of the struct replied FUNCTIONS is not fixed,
% 2. The full paths of toolbox function e.g. for @mean differ.
FuncKey = functions(FuncH);
% ALTERNATIVE: Use name and path. The <matlabroot> part of the toolbox functions
% is replaced such that the hash for @mean does not depend on the Matlab
% version.
% Drawbacks: Anonymous functions, nested functions...
% funcStruct = functions(FuncH);
% funcfile = strrep(funcStruct.file, matlabroot, '<MATLAB>');
% FuncKey = uint8([funcStruct.function, ' ', funcfile]);
% Finally I'm afraid there is no unique method to get a hash for a function
% handle. Please adjust this conversion to your needs.
% return;
% ******************************************************************************
function DataBin = ConvertObject(DataObj)
% Convert a user-defined object to a binary stream. There cannot be a unique
% solution, so this part is left for the user...
% Perhaps a direct conversion is implemented:
DataBin = uint8(DataObj);
% Or perhaps this is better:
% DataBin = struct(DataObj);
% return;
% ******************************************************************************
function Out = fBase64_enc(In)
% Encode numeric vector of UINT8 values to base64 string.
Pool = [65:90, 97:122, 48:57, 43, 47]; % [0:9, a:z, A:Z, +, /]
v8 = [128; 64; 32; 16; 8; 4; 2; 1];
v6 = [32, 16, 8, 4, 2, 1];
In = reshape(In, 1, []);
X = rem(floor(In(ones(8, 1), :) ./ v8(:, ones(length(In), 1))), 2);
Y = reshape([X(:); zeros(6 - rem(numel(X), 6), 1)], 6, []);
Out = char(Pool(1 + v6 * Y));
% return;
|
github
|
ZijingMao/baselineeegtest-master
|
strsetmatch.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/strsetmatch.m
| 928 |
utf_8
|
73f5541ad337bbbc7179cf71004b7062
|
% Indicator of which elements of a universal set are in a particular set.
%
% Input arguments:
% strset:
% the particular set as a cell array of strings
% struniversal:
% the universal set as a cell array of strings, all elements in the
% particular set are expected to be in the universal set
%
% Output arguments:
% ind:
% a logical vector of which elements of the universal set are found in
% the particular set
% Copyright 2010 Levente Hunyadi
function ind = strsetmatch(strset, struniversal)
assert(iscellstr(strset), 'strsetmatch:ArgumentTypeMismatch', ...
'The particular set is expected to be a cell array of strings.');
assert(iscellstr(struniversal), 'strsetmatch:ArgumentTypeMismatch', ...
'The particular set is expected to be a cell array of strings.');
ind = false(size(struniversal));
for k = 1 : numel(struniversal)
ind(k) = ~isempty(strmatch(struniversal{k}, strset, 'exact'));
end
|
github
|
ZijingMao/baselineeegtest-master
|
helptext.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/helptext.m
| 1,593 |
utf_8
|
bd49205fc50aeae5a909c8b58a47be6d
|
% Help text associated with a function, class, property or method.
% Spaces are removed as necessary.
%
% See also: helpdialog
% Copyright 2008-2010 Levente Hunyadi
function text = helptext(obj)
if ischar(obj)
text = gethelptext(obj);
else
text = gethelptext(class(obj));
end
text = texttrim(text);
function text = gethelptext(key)
persistent dict;
if isempty(dict) && usejava('jvm')
dict = java.util.Properties();
end
if ~isempty(dict)
text = char(dict.getProperty(key)); % look up key in cache
if ~isempty(text) % help text found in cache
return;
end
text = help(key);
if ~isempty(text) % help text returned by help call, save it into cache
dict.setProperty(key, text);
end
else
text = help(key);
end
function lines = texttrim(text)
% Trims leading and trailing whitespace characters from lines of text.
% The number of leading whitespace characters to trim is determined by
% inspecting all lines of text.
loc = strfind(text, sprintf('\n'));
n = numel(loc);
loc = [ 0 loc ];
lines = cell(n,1);
if ~isempty(loc)
for k = 1 : n
lines{k} = text(loc(k)+1 : loc(k+1));
end
end
lines = deblank(lines);
% determine maximum leading whitespace count
f = ~cellfun(@isempty, lines); % filter for non-empty lines
firstchar = cellfun(@(line) find(~isspace(line), 1), lines(f)); % index of first non-whitespace character
if isempty(firstchar)
indent = 1;
else
indent = min(firstchar);
end
% trim leading whitespace
lines(f) = cellfun(@(line) line(min(indent,numel(line)):end), lines(f), 'UniformOutput', false);
|
github
|
ZijingMao/baselineeegtest-master
|
javaclass.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/javaclass.m
| 3,635 |
utf_8
|
7165e1fd27bd4f5898132023dc04662b
|
% Return java.lang.Class instance for MatLab type.
%
% Input arguments:
% mtype:
% the MatLab name of the type for which to return the java.lang.Class
% instance
% ndims:
% the number of dimensions of the MatLab data type
%
% See also: class
% Copyright 2009-2010 Levente Hunyadi
function jclass = javaclass(mtype, ndims)
validateattributes(mtype, {'char'}, {'nonempty','row'});
if nargin < 2
ndims = 0;
else
validateattributes(ndims, {'numeric'}, {'nonnegative','integer','scalar'});
end
if ndims == 1 && strcmp(mtype, 'char'); % a character vector converts into a string
jclassname = 'java.lang.String';
elseif ndims > 0
jclassname = javaarrayclass(mtype, ndims);
else
% The static property .class applied to a Java type returns a string in
% MatLab rather than an instance of java.lang.Class. For this reason,
% use a string and java.lang.Class.forName to instantiate a
% java.lang.Class object; the syntax java.lang.Boolean.class will not
% do so.
switch mtype
case 'logical' % logical vaule (true or false)
jclassname = 'java.lang.Boolean';
case 'char' % a singe character
jclassname = 'java.lang.Character';
case {'int8','uint8'} % 8-bit signed and unsigned integer
jclassname = 'java.lang.Byte';
case {'int16','uint16'} % 16-bit signed and unsigned integer
jclassname = 'java.lang.Short';
case {'int32','uint32'} % 32-bit signed and unsigned integer
jclassname = 'java.lang.Integer';
case {'int64','uint64'} % 64-bit signed and unsigned integer
jclassname = 'java.lang.Long';
case 'single' % single-precision floating-point number
jclassname = 'java.lang.Float';
case 'double' % double-precision floating-point number
jclassname = 'java.lang.Double';
case 'cellstr' % a single cell or a character array
jclassname = 'java.lang.String';
otherwise
error('java:javaclass:InvalidArgumentValue', ...
'MatLab type "%s" is not recognized or supported in Java.', mtype);
end
end
% Note: When querying a java.lang.Class object by name with the method
% jclass = java.lang.Class.forName(jclassname);
% MatLab generates an error. For the Class.forName method to work, MatLab
% requires class loader to be specified explicitly.
jclass = java.lang.Class.forName(jclassname, true, java.lang.Thread.currentThread().getContextClassLoader());
function jclassname = javaarrayclass(mtype, ndims)
% Returns the type qualifier for a multidimensional Java array.
switch mtype
case 'logical' % logical array of true and false values
jclassid = 'Z';
case 'char' % character array
jclassid = 'C';
case {'int8','uint8'} % 8-bit signed and unsigned integer array
jclassid = 'B';
case {'int16','uint16'} % 16-bit signed and unsigned integer array
jclassid = 'S';
case {'int32','uint32'} % 32-bit signed and unsigned integer array
jclassid = 'I';
case {'int64','uint64'} % 64-bit signed and unsigned integer array
jclassid = 'J';
case 'single' % single-precision floating-point number array
jclassid = 'F';
case 'double' % double-precision floating-point number array
jclassid = 'D';
case 'cellstr' % cell array of strings
jclassid = 'Ljava.lang.String;';
otherwise
error('java:javaclass:InvalidArgumentValue', ...
'MatLab type "%s" is not recognized or supported in Java.', mtype);
end
jclassname = [repmat('[',1,ndims), jclassid];
|
github
|
ZijingMao/baselineeegtest-master
|
helpdialog.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/helpdialog.m
| 3,397 |
utf_8
|
f16f23c1b608a247bc5298f5ebc6d321
|
% Displays a dialog to give help information on an object.
%
% Examples:
% helpdialog char
% gives information of character arrays
% helpdialog plot
% gives help on the plot command
% helpdialog(obj)
% gives help on the MatLab object obj
%
% See also: helptext, msgbox
% Copyright 2008-2010 Levente Hunyadi
function helpdialog(obj)
if nargin < 1
obj = 'helpdialog';
end
if ischar(obj)
key = obj;
else
key = class(obj);
end
title = [key ' - Quick help'];
text = helptext(key);
if isempty(text)
text = {'No help available.'};
end
if 0 % standard MatLab message dialog box
createmode = struct( ...
'WindowStyle', 'replace', ...
'Interpreter', 'none');
msgbox(text, title, 'help', createmode);
else
fig = figure( ...
'MenuBar', 'none', ...
'Name', title, ...
'NumberTitle', 'off', ...
'Position', [0 0 480 160], ...
'Toolbar', 'none', ...
'Visible', 'off', ...
'ResizeFcn', @helpdialog_resize);
% information icon
icons = load('dialogicons.mat');
icons.helpIconMap(256,:) = get(fig, 'Color');
iconaxes = axes( ...
'Parent', fig, ...
'Units', 'pixels', ...
'Tag', 'IconAxes');
try
iconimg = image('CData', icons.helpIconData, 'Parent', iconaxes);
set(fig, 'Colormap', icons.helpIconMap);
catch me
delete(fig);
rethrow(me)
end
if ~isempty(get(iconimg,'XData')) && ~isempty(get(iconimg,'YData'))
set(iconaxes, ...
'XLim', get(iconimg,'XData')+[-0.5 0.5], ...
'YLim', get(iconimg,'YData')+[-0.5 0.5]);
end
set(iconaxes, ...
'Visible', 'off', ...
'YDir', 'reverse');
% help text
rgb = get(fig, 'Color');
text = cellfun(@(line) helpdialog_html(line), text, 'UniformOutput', false);
html = ['<html>' strjoin(sprintf('\n'), text) '</html>'];
jtext = javax.swing.JLabel(html);
jcolor = java.awt.Color(rgb(1), rgb(2), rgb(3));
jtext.setBackground(jcolor);
jtext.setVerticalAlignment(1);
jscrollpane = javax.swing.JScrollPane(jtext, javax.swing.JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jscrollpane.getViewport().setBackground(jcolor);
jscrollpane.setBorder(javax.swing.border.EmptyBorder(0,0,0,0));
[jcontrol,jcontainer] = javacomponent(jscrollpane, [0 0 100 100]);
set(jcontainer, 'Tag', 'HelpText');
movegui(fig, 'center'); % center figure on screen
set(fig, 'Visible', 'on');
end
function helpdialog_resize(fig, event) %#ok<INUSD>
position = getpixelposition(fig);
width = position(3);
height = position(4);
iconaxes = findobj(fig, 'Tag', 'IconAxes');
helptext = findobj(fig, 'Tag', 'HelpText');
bottom = 7*height/12;
set(iconaxes, 'Position', [12 bottom 51 51]);
set(helptext, 'Position', [75 12 width-75-12 height-24]);
function html = helpdialog_html(line)
preline = deblank(line); % trailing spaces removed
line = strtrim(preline); % leading spaces removed
leadingspace = repmat(' ', 1, numel(preline)-numel(line)); % add leading spaces as non-breaking space
ix = strfind(line, 'See also');
if ~isempty(ix)
ix = ix(1) + numel('See also');
line = [ line(1:ix-1) regexprep(line(ix:end), '(\w[\d\w]+)', '<a href="matlab:helpdialog $1">$1</a>') ];
end
html = ['<p>' leadingspace line '</p>'];
|
github
|
ZijingMao/baselineeegtest-master
|
getdependentproperties.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/getdependentproperties.m
| 907 |
utf_8
|
5f87bb7115d9bcacd8556d89a4492c44
|
% Publicly accessible dependent properties of an object.
%
% See also: meta.property
% Copyright 2010 Levente Hunyadi
function dependent = getdependentproperties(obj)
dependent = {};
if isstruct(obj) % structures have no dependent properties
return;
end
try
clazz = metaclass(obj);
catch %#ok<CTCH>
return; % old-style class (i.e. not defined with the classdef keyword) have no dependent properties
end
k = 0; % number of dependent properties found
n = numel(clazz.Properties); % maximum number of properties
dependent = cell(n, 1);
for i = 1 : n
property = clazz.Properties{i};
if property.Abstract || property.Hidden || ~strcmp(property.GetAccess, 'public') || ~property.Dependent
continue; % skip abstract, hidden, inaccessible and independent properties
end
k = k + 1;
dependent{k} = property.Name;
end
dependent(k+1:end) = []; % drop unused cells
|
github
|
ZijingMao/baselineeegtest-master
|
example_matrixeditor.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/example_matrixeditor.m
| 471 |
utf_8
|
637b619421d215e7270f8502574e4ff7
|
% Demonstrates how to use the matrix editor.
%
% See also: MatrixEditor
% Copyright 2010 Levente Hunyadi
function example_matrixeditor
fig = figure( ...
'MenuBar', 'none', ...
'Name', 'Matrix editor demo - Copyright 2010 Levente Hunyadi', ...
'NumberTitle', 'off', ...
'Toolbar', 'none');
editor = MatrixEditor(fig, ...
'Item', [1,2,3,4;5,6,7,8;9,10,11,12], ...
'Type', PropertyType('denserealdouble','matrix'));
uiwait(fig);
disp(editor.Item);
|
github
|
ZijingMao/baselineeegtest-master
|
example_propertyeditor.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/example_propertyeditor.m
| 473 |
utf_8
|
49faa2989b2f9c32c26f366e77eaf0b2
|
% Demonstrates how to use the property editor.
%
% See also: PropertyEditor
% Copyright 2010 Levente Hunyadi
function example_propertyeditor
% create figure
f = figure( ...
'MenuBar', 'none', ...
'Name', 'Property editor demo - Copyright 2010 Levente Hunyadi', ...
'NumberTitle', 'off', ...
'Toolbar', 'none');
items = { SampleObject SampleObject };
editor = PropertyEditor(f, 'Items', items);
editor.AddItem(SampleNestedObject, 1);
editor.RemoveItem(1);
|
github
|
ZijingMao/baselineeegtest-master
|
nestedfetch.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/nestedfetch.m
| 1,000 |
utf_8
|
1f3b58597c8ee6879bc2650defb0799d
|
% Fetches the value of the named property of an object or structure.
% This function can deal with nested properties.
%
% Input arguments:
% obj:
% the handle or value object the value should be assigned to
% name:
% a property name with dot (.) separating property names at
% different hierarchy levels
% value:
% the value to assign to the property at the deepest hierarchy
% level
%
% Example:
% obj = struct('surface', struct('nested', 23));
% value = nestedfetch(obj, 'surface.nested');
% disp(value); % prints 23
%
% See also: nestedassign
% Copyright 2010 Levente Hunyadi
function value = nestedfetch(obj, name)
if ~iscell(name)
nameparts = strsplit(name, '.');
else
nameparts = name;
end
value = nestedfetch_recurse(obj, nameparts);
end
function value = nestedfetch_recurse(obj, name)
if numel(name) > 1
value = nestedfetch_recurse(obj.(name{1}), name(2:end));
else
value = obj.(name{1});
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
findobjuser.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/findobjuser.m
| 1,391 |
utf_8
|
3275be54ee6c453c85fd950bb6ac56b5
|
% Find handle graphics object with user data check.
% Retrieves those handle graphics objects (HGOs) that have the specified
% Tag property and whose UserData property satisfies the given predicate.
%
% Input arguments:
% fcn:
% a predicate (a function that returns a logical value) to test against
% the HGO's UserData property
% tag (optional):
% a string tag to restrict the set of controls to investigate
%
% See also: findobj
% Copyright 2010 Levente Hunyadi
function h = findobjuser(fcn, tag)
validateattributes(fcn, {'function_handle'}, {'scalar'});
if nargin < 2 || isempty(tag)
tag = '';
else
validateattributes(tag, {'char'}, {'row'});
end
%hh = get(0, 'ShowHiddenHandles');
%cleanup = onCleanup(@() set(0, 'ShowHiddenHandles', hh)); % restore visibility on exit or exception
if ~isempty(tag)
% look among all handles (incl. hidden handles) to help findobj locate the object it seeks
h = findobj(findall(0), '-property', 'UserData', '-and', 'Tag', tag); % more results if multiple matching HGOs exist
else
h = findobj(findall(0), '-property', 'UserData');
end
h = unique(h);
try
for k=1:length(h)
pred = fcn(get(h(k), 'UserData'));
if isempty(pred)
pred = false; end
f(k) = pred;
end
%f = arrayfun(@(handle) fcn(get(handle, 'UserData')), h, 'UniformOutput',false);
catch
1
end
h = h(f);
|
github
|
ZijingMao/baselineeegtest-master
|
javaStringArray.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/javaStringArray.m
| 628 |
utf_8
|
fe0389e3b0d1933d49c1a78c416a279c
|
% Converts a MatLab cell array of strings into a java.lang.String array.
%
% Input arguments:
% str:
% a cell array of strings (i.e. a cell array of char row vectors)
%
% Output arguments:
% arr:
% a java.lang.String array instance (i.e. java.lang.String[])
%
% See also: javaArray
% Copyright 2009-2010 Levente Hunyadi
function arr = javaStringArray(str)
assert(iscellstr(str) && isvector(str), ...
'java:StringArray:InvalidArgumentType', ...
'Cell row or column vector of strings expected.');
arr = javaArray('java.lang.String', length(str));
for k = 1 : numel(str);
arr(k) = java.lang.String(str{k});
end
|
github
|
ZijingMao/baselineeegtest-master
|
var2str.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/var2str.m
| 441 |
utf_8
|
5588acb0d18dcfac8183caf10a3b5675
|
% Textual representation of any MatLab value.
% Copyright 2009 Levente Hunyadi
function s = var2str(value)
if islogical(value) || isnumeric(value)
s = num2str(value);
elseif ischar(value) && isvector(value)
s = reshape(value, 1, numel(value));
elseif isjava(value)
s = char(value); % calls java.lang.Object.toString()
else
try
s = char(value);
catch %#ok<CTCH>
s = '[no preview available]';
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
getclassfield.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/getclassfield.m
| 376 |
utf_8
|
e3b87866af8da4dd40243e750a7e53f6
|
% Field value of each object in an array or cell array.
%
% See also: getfield
% Copyright 2010 Levente Hunyadi
function values = getclassfield(objects, field)
values = cell(size(objects));
if iscell(objects)
for k = 1 : numel(values)
values{k} = objects{k}.(field);
end
else
for k = 1 : numel(values)
values{k} = objects(k).(field);
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
arrayfilter.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/arrayfilter.m
| 488 |
utf_8
|
a2649b876169e3d850372917e57a8b68
|
% Filter elements of array that meet a condition.
% Copyright 2010 Levente Hunyadi
function array = arrayfilter(fun, array)
validateattributes(fun, {'function_handle'}, {'scalar'});
if isobject(array)
filter = false(size(array));
for k = 1 : numel(filter)
filter(k) = fun(array(k));
end
else
filter = arrayfun(fun, array); % logical indicator array of elements that satisfy condition
end
array = array(filter); % array of elements that meet condition
|
github
|
ZijingMao/baselineeegtest-master
|
example_propertygrid.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/example_propertygrid.m
| 4,929 |
utf_8
|
f1e5d6dc7fc518cdb070956ff714353c
|
% Demonstrates how to use the property pane.
%
% See also: PropertyGrid
% Copyright 2010 Levente Hunyadi
function example_propertygrid
properties = [ ...
PropertyGridField('double', pi, ...
'Category', 'Primitive types', ...
'DisplayName', 'real double', ...
'Description', 'Standard MatLab type.') ...
PropertyGridField('single', pi, ...
'Category', 'Primitive types', ...
'DisplayName', 'real single', ...
'Description', 'Single-precision floating point number.') ...
PropertyGridField('integer', int32(23), ...
'Category', 'Primitive types', ...
'DisplayName', 'int32', ...
'Description', 'A 32-bit integer value.') ...
PropertyGridField('interval', int32(2), ...
'Type', PropertyType('int32', 'scalar', [0 6]), ...
'Category', 'Primitive types', ...
'DisplayName', 'int32', ...
'Description', 'A 32-bit integer value with an interval domain.') ...
PropertyGridField('enumerated', int32(-1), ...
'Type', PropertyType('int32', 'scalar', {int32(-1), int32(0), int32(1)}), ...
'Category', 'Primitive types', ...
'DisplayName', 'int32', ...
'Description', 'A 32-bit integer value with an enumerated domain.') ...
PropertyGridField('logical', true, ...
'Category', 'Primitive types', ...
'DisplayName', 'logical', ...
'Description', 'A Boolean value that takes either true or false.') ...
PropertyGridField('doublematrix', [], ...
'Type', PropertyType('denserealdouble', 'matrix'), ...
'Category', 'Compound types', ...
'DisplayName', 'real double matrix', ...
'Description', 'Matrix of standard MatLab type with empty initial value.') ...
PropertyGridField('string', 'a sample string', ...
'Category', 'Compound types', ...
'DisplayName', 'string', ...
'Description', 'A row vector of characters.') ...
PropertyGridField('rowcellstr', {'a sample string','spanning multiple','lines'}, ...
'Category', 'Compound types', ...
'DisplayName', 'cell row of strings', ...
'Description', 'A row cell array whose every element is a string (char array).') ...
PropertyGridField('colcellstr', {'a sample string';'spanning multiple';'lines'}, ...
'Category', 'Compound types', ...
'DisplayName', 'cell column of strings', ...
'Description', 'A column cell array whose every element is a string (char array).') ...
PropertyGridField('season', 'spring', ...
'Type', PropertyType('char', 'row', {'spring','summer','fall','winter'}), ...
'Category', 'Compound types', ...
'DisplayName', 'string', ...
'Description', 'A row vector of characters that can take any of the predefined set of values.') ...
PropertyGridField('set', [true false true], ...
'Type', PropertyType('logical', 'row', {'A','B','C'}), ...
'Category', 'Compound types', ...
'DisplayName', 'set', ...
'Description', 'A logical vector that serves an indicator of which elements from a universe are included in the set.') ...
PropertyGridField('root', [], ... % [] (and no type explicitly set) indicates that value is not editable
'Category', 'Compound types', ...
'DisplayName', 'root node') ...
PropertyGridField('root.parent', int32(23), ...
'Category', 'Compound types', ...
'DisplayName', 'parent node') ...
PropertyGridField('root.parent.child', int32(2007), ...
'Category', 'Compound types', ...
'DisplayName', 'child node') ...
];
% arrange flat list into a hierarchy based on qualified names
properties = properties.GetHierarchy();
% create figure
f = figure( ...
'MenuBar', 'none', ...
'Name', 'Property grid demo - Copyright 2010 Levente Hunyadi', ...
'NumberTitle', 'off', ...
'Toolbar', 'none');
% procedural usage
g = PropertyGrid(f, ... % add property pane to figure
'Properties', properties, ... % set properties explicitly
'Position', [0 0 0.5 1]);
h = PropertyGrid(f, ...
'Position', [0.5 0 0.5 1]);
% declarative usage, bind object to grid
obj = SampleObject; % a value object
h.Item = obj; % bind object, discards any previously set properties
% update the type of a property assigned with type autodiscovery
userproperties = PropertyGridField.GenerateFrom(obj);
userproperties.FindByName('IntegerMatrix').Type = PropertyType('denserealdouble', 'matrix');
disp(userproperties.FindByName('IntegerMatrix').Type);
h.Bind(obj, userproperties);
% wait for figure to close
uiwait(f);
% display all properties and their values on screen
disp('Left-hand property grid');
disp(g.GetPropertyValues());
disp('Right-hand property grid');
disp(h.GetPropertyValues());
disp('SampleObject (modified)');
disp(h.Item);
disp('SampleNestedObject (modified)');
disp(h.Item.NestedObject);
|
github
|
ZijingMao/baselineeegtest-master
|
constructor.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/constructor.m
| 2,078 |
utf_8
|
c67e647ec8055710896666c9e83b45e0
|
% Sets public properties of a MatLab object using a name-value list.
% Properties are traversed in the order they occur in the class definition.
% Copyright 2008-2009 Levente Hunyadi
function obj = constructor(obj, varargin)
assert(isobject(obj), ...
'Function operates on MatLab new-style objects only.');
if nargin <= 1
return;
end
if isa(obj, 'hgsetget')
set(obj, varargin{:});
return;
end
assert(is_name_value_list(varargin), ...
'constructor:ArgumentTypeMismatch', ...
'A list of property name--value pairs is expected.');
% instantiate input parser object
parser = inputParser;
% query class properties using meta-class facility
metaobj = metaclass(obj);
properties = metaobj.Properties;
for i = 1 : numel(properties)
property = properties{i};
if is_public_property(property)
parser.addParamValue(property.Name, obj.(property.Name));
end
end
% set property values according to name-value list
parser.parse(varargin{:});
for i = 1 : numel(properties)
property = properties{i};
if is_public_property(property) && ~is_string_in_vector(property.Name, parser.UsingDefaults) % do not set defaults
obj.(property.Name) = parser.Results.(property.Name);
end
end
function tf = is_name_value_list(list)
% True if the specified list is a name-value list.
%
% Input arguments:
% list:
% a name-value list as a cell array.
validateattributes(list, {'cell'}, {'vector'});
n = numel(list);
if mod(n, 2) ~= 0
% a name-value list has an even number of elements
tf = false;
else
for i = 1 : 2 : n
if ~ischar(list{i})
% each odd element in a name-value list must be a char array
tf = false;
return;
end
end
tf = true;
end
function tf = is_string_in_vector(str, vector)
tf = any(strcmp(str, vector));
function tf = is_public_property(property)
% True if the property designates a public, accessible property.
tf = ~property.Abstract && ~property.Hidden && strcmp(property.GetAccess, 'public') && strcmp(property.SetAccess, 'public');
|
github
|
ZijingMao/baselineeegtest-master
|
nestedassign.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/nestedassign.m
| 1,457 |
utf_8
|
12d661bb4df3c64a0707a06f7e3e6afc
|
% Assigns the given value to the named property of an object or structure.
% This function can deal with nested properties.
%
% Input arguments:
% obj:
% the structure, handle or value object the value should be assigned to
% name:
% a property name with dot (.) separating property names at
% different hierarchy levels
% value:
% the value to assign to the property at the deepest hierarchy
% level
%
% Output arguments:
% obj:
% the updated object or structure, optional for handle objects
%
% Example:
% obj = struct('surface', struct('nested', 10));
% obj = nestedassign(obj, 'surface.nested', 23);
% disp(obj.surface.nested); % prints 23
%
% See also: nestedfetch
% Copyright 2010 Levente Hunyadi
function obj = nestedassign(obj, name, value)
if ~iscell(name)
nameparts = strsplit(name, '.');
else
nameparts = name;
end
obj = nestedassign_recurse(obj, nameparts, value);
end
function obj = nestedassign_recurse(obj, name, value)
% Assigns the given value to the named property of an object.
%
% Input arguments:
% obj:
% the handle or value object the value should be assigned to
% name:
% a cell array of the composite property name
% value:
% the value to assign to the property at the deepest hierarchy
% level
if numel(name) > 1
obj.(name{1}) = nestedassign_recurse(obj.(name{1}), name(2:end), value);
else
obj.(name{1}) = value;
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
javaArrayList.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/javaArrayList.m
| 740 |
utf_8
|
cb4ad03c4e0fc536bc1ae024bfb8920a
|
% Converts a MatLab array into a java.util.ArrayList.
%
% Input arguments:
% array:
% a MatLab row or column vector (with elements of any type)
%
% Output arguments:
% list:
% a java.util.ArrayList instance
%
% See also: javaArray
% Copyright 2010 Levente Hunyadi
function list = javaArrayList(array)
list = java.util.ArrayList;
if ~isempty(array)
assert(isvector(array), 'javaArrayList:DimensionMismatch', ...
'Row or column vector expected.');
if iscell(array) % convert cell array into ArrayList
for k = 1 : numel(array)
list.add(array{k});
end
else % convert (numeric) array into ArrayList
for k = 1 : numel(array)
list.add(array(k));
end
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
strjoin.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/private/strjoin.m
| 938 |
utf_8
|
63425068d4fd2fd0543aa9e5b46eca84
|
% Concatenates a cell array of strings.
%
% Input arguments:
% adjoiner:
% string separating each neighboring element
% strings:
% a cell array of strings to join
%
% See also: strsplit, cell2mat
% Copyright 2008-2009 Levente Hunyadi
function string = strjoin(adjoiner, strings)
validateattributes(adjoiner, {'char'}, {'vector'});
validateattributes(strings, {'cell'}, {'vector'});
assert(iscellstr(strings), ...
'strjoin:ArgumentTypeMismatch', ...
'The elements to join should be stored in a cell vector of strings (character arrays).');
if isempty(strings)
string = '';
return;
end
% arrange substrings into cell array of strings
concat = cell(1, 2 * numel(strings) - 1); % must be row vector
j = 1;
concat{j} = strings{1};
for i = 2 : length(strings)
j = j + 1;
concat{j} = adjoiner;
j = j + 1;
concat{j} = strings{i};
end
% concatenate substrings preserving spaces
string = cell2mat(concat);
|
github
|
ZijingMao/baselineeegtest-master
|
strsplit.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/PropertyGrid-2010-09-16-mod/private/strsplit.m
| 553 |
utf_8
|
81fa1c544a57b6a796400f39aedf3d44
|
% Splits a string into a cell array of strings.
%
% Input arguments:
% string:
% a string to split into a cell array
% adjoiner:
% string separating each neighboring element
%
% See also: strjoin
% Copyright 2008-2009 Levente Hunyadi
function strings = strsplit(string, adjoiner)
if nargin < 2
adjoiner = sprintf('\n');
end
ix = strfind(string, adjoiner);
strings = cell(numel(ix)+1, 1);
ix = [0 ix numel(string)+1]; % place implicit adjoiners before and after string
for k = 2 : numel(ix)
strings{k-1} = string(ix(k-1)+1:ix(k)-1);
end
|
github
|
ZijingMao/baselineeegtest-master
|
hlp_scope.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_scope.m
| 4,133 |
utf_8
|
fa953a173bee2b8cdcaacdbde3865192
|
function varargout = hlp_scope(assignments, f, varargin)
% Execute a function within a dynamic scope of values assigned to symbols.
% Results... = hlp_scope(Assignments, Function, Arguments...)
%
% This is the only completely reliable way in MATLAB to ensure that symbols that should be assigned
% while a function is running get cleared after the function returns orderly, crashes, segfaults,
% the user slams Ctrl+C, and so on. Symbols can be looked up via hlp_resolve().
%
% In:
% Assignments : Cell array of name-value pairs or a struct. Values are associated with symbols of
% the given names. The names should be valid MATLAB identifiers. These assigments
% form a dynamic scope for the execution of the function; scopes can also be
% nested, and assignments in inner scopes override those of outer scopes.
%
% Function : a function handle to invoke
%
% Arguments... : arguments to pass to the function
%
% Out:
% Results... : return value(s) of the function
%
% See also:
% hlp_resolve
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-05-03
% Copyright (C) Christian Kothe, SCCN, 2010, [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
% add a new stack frame with the evaluated assignments & get its unique id
id = make_stackframe(assignments);
% also take care that it gets reclaimed after we're done
reclaimer = onCleanup(@()return_stackframe(id));
% make a function that is tagged by id
func = make_func(id);
% evaluate the function with the id introduced into MATLAB's own stack
[varargout{1:nargout}] = func(f,varargin);
function func = make_func(id)
persistent funccache; % (cached, since the eval() below is a bit slow)
try
func = funccache.(id);
catch
func = eval(['@(f,a,frame__' id ')feval(f,a{:})']);
funccache.(id) = func;
end
function id = make_stackframe(assignments)
% put the assignments into a struct
if iscell(assignments)
assignments = cell2struct(assignments(2:2:end),assignments(1:2:end),2); end
% get a fresh frame id
global tracking;
try
id = tracking.stack.frameids.removeLast();
catch
if ~isfield(tracking,'stack') || ~isfield(tracking.stack,'frameids')
% need to create the id repository first
tracking.stack.frameids = java.util.concurrent.LinkedBlockingDeque();
for k=50000:-1:1
tracking.stack.frameids.addLast(sprintf('f%d',k)); end
else
if tracking.stack.frameids.size() == 0
% if this happens then either you have 10.000s of parallel executions of hlp_scope(),
% or you have a very deep recursion level (the MATLAB default is 500), or your function
% has crashed 10.000s of times in a way that keeps onCleanup from doing its job, or you have
% substituted onCleanup by a dummy class or function that doesn't actually work (e.g. on
% pre-2008a systems).
error('We ran out of stack frame ids. This should not happen under normal conditions. Please make sure that your onCleanup implementation is not consistently failing to execute.');
end
end
id = tracking.stack.frameids.removeLast();
end
% and store the assignments under it
tracking.stack.frames.(id) = assignments;
function return_stackframe(id)
% finally return the frame id again...
global tracking;
tracking.stack.frameids.addLast(id);
|
github
|
ZijingMao/baselineeegtest-master
|
hlp_fingerprint.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_fingerprint.m
| 7,989 |
utf_8
|
6c791e0e23e57c2a9b97a43096c2269f
|
function fp = hlp_fingerprint(data)
% Make a fingerprint (hash) of the given data structure.
% Fingerprint = hlp_fingerprint(Data)
%
% This includes all contents; however, large arrays (such as EEG.data) are only spot-checked. For
% thorough checking, use hlp_cryptohash.
%
% In:
% Data : some data structure
%
% Out:
% Fingerprint : an integer that identifies the data
%
% Notes:
% The fingerprint is not unique and identifies the data set only with a certain (albeit high)
% probability.
%
% On MATLAB versions prior to 2008b, hlp_fingerprint cannot be used concurrently from timers,
% and also may alter the random generator's state if cancelled via Ctrl+C.
%
% Examples:
% % calculate the hash of a large data structure
% hash = hlp_fingerprint(data);
%
% See also:
% hlp_cryptohash
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-02
% Copyright (C) Christian Kothe, SCCN, 2010, [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
warning off MATLAB:structOnObject
if hlp_matlab_version >= 707
fp = fingerprint(data,RandStream('swb2712','Seed',5183));
else
try
% save & override random state
randstate = rand('state'); %#ok<*RAND>
rand('state',5183);
% make the fingerprint
fp = fingerprint(data,0);
% restore random state
rand('state',randstate);
catch e
% restore random state in case of an error...
rand('state',randstate);
rethrow(e);
end
end
% make a fingerprint of the given data structure
function fp = fingerprint(data,rs)
% convert data into a string representation
data = summarize(data,rs);
% make sure that it does not contain 0's
data(data==0) = 'x';
% obtain a hash code via Java (MATLAB does not support proper integer arithmetic...)
str = java.lang.String(data);
fp = str.hashCode()+2^31;
% get a recursive string summary of arbitrary data
function x = summarize(x,rs)
if isnumeric(x)
% numeric array
if ~isreal(x)
x = [real(x) imag(x)]; end
if issparse(x)
x = [find(x) nonzeros(x)]; end
if numel(x) <= 4096
% small matrices are hashed completely
try
x = ['n' typecast([size(x) x(:)'],'uint8')];
catch
if hlp_matlab_version <= 702
x = ['n' typecast([size(x) double(x(:))'],'uint8')]; end
end
else
% large matrices are spot-checked
ne = numel(x);
count = floor(256 + (ne-256)/1000);
if hlp_matlab_version < 707
indices = 1+floor((ne-1)*rand(1,count));
else
indices = 1+floor((ne-1)*rand(rs,1,count));
end
if size(x,2) == 1
% x is a column vector: reindexed expression needs to be transposed
x = ['n' typecast([size(x) x(indices)'],'uint8')];
else
% x is a matrix or row vector: shape follows that of indices
x = ['n' typecast([size(x) x(indices)],'uint8')];
end
end
elseif iscell(x)
% cell array
sizeprod = cellfun('prodofsize',x(:));
if all(sizeprod <= 1) && any(sizeprod)
% all scalar elements (some empty, but not all)
if all(cellfun('isclass',x(:),'double')) || all(cellfun('isclass',x(:),'single'))
% standard floating-point scalars
if cellfun('isreal',x)
% all real
x = ['cdr' typecast([size(x) x{:}],'uint8')];
else
% some complex
x = ['cdc' typecast([size(x) real([x{:}]) imag([x{:}])],'uint8')];
end
elseif cellfun('isclass',x(:),'logical')
% all logical
x = ['cl' typecast(uint32(size(x)),'uint8') uint8([x{:}])];
elseif cellfun('isclass',x(:),'char')
% all single chars
x = ['ccs' typecast(uint32(size(x)),'uint8') x{:}];
else
% generic types (structs, cells, integers, handles, ...)
tmp = cellfun(@summarize,x,repmat({rs},size(x)),'UniformOutput',false);
x = ['cg' typecast(uint32(size(x)),'uint8') tmp{:}];
end
elseif isempty(x)
% empty cell array
x = ['ce' typecast(uint32(size(x)),'uint8')];
else
% some non-scalar elements
dims = cellfun('ndims',x(:));
size1 = cellfun('size',x(:),1);
size2 = cellfun('size',x(:),2);
if all((size1+size2 == 0) & (dims == 2))
% all empty and nondegenerate elements
if all(cellfun('isclass',x(:),'double'))
% []'s
x = ['ced' typecast(uint32(size(x)),'uint8')];
elseif all(cellfun('isclass',x(:),'cell'))
% {}'s
x = ['cec' typecast(uint32(size(x)),'uint8')];
elseif all(cellfun('isclass',x(:),'struct'))
% struct()'s
x = ['ces' typecast(uint32(size(x)),'uint8')];
elseif length(unique(cellfun(@class,x(:),'UniformOutput',false))) == 1
% same class
x = ['cex' class(x{1}) typecast(uint32(size(x)),'uint8')];
else
% arbitrary class...
tmp = cellfun(@summarize,x,repmat({rs},size(x)),'UniformOutput',false);
x = ['cg' typecast(uint32(size(x)),'uint8') tmp{:}];
end
elseif all((cellfun('isclass',x(:),'char') & size1 <= 1) | (sizeprod==0 & cellfun('isclass',x(:),'double')))
% all horizontal strings or proper empty strings, possibly some []'s
x = ['cch' [x{:}] typecast(uint32(size2'),'uint8')];
else
% arbitrary sizes...
if all(cellfun('isclass',x(:),'double')) || all(cellfun('isclass',x(:),'single'))
% all standard floating-point types...
tmp = cellfun(@vectorize,x,'UniformOutput',false);
% treat as a big vector...
x = ['cn' typecast(uint32(size(x)),'uint8') summarize([tmp{:}],rs)];
else
tmp = cellfun(@summarize,x,repmat({rs},size(x)),'UniformOutput',false);
x = ['cg' typecast(uint32(size(x)),'uint8') tmp{:}];
end
end
end
elseif ischar(x)
% char array
x = ['c' x(:)'];
elseif isstruct(x)
% struct
fn = fieldnames(x)';
if numel(x) > length(fn)
% summarize over struct fields to expose homogeneity
x = cellfun(@(f)summarize({x.(f)},rs),fn,'UniformOutput',false);
x = ['s' [fn{:}] ':' [x{:}]];
else
% summarize over struct elements
x = ['s' [fn{:}] ':' summarize(struct2cell(x),rs)];
end
elseif islogical(x)
% logical array
x = ['l' typecast(uint32(size(x)),'uint8') uint8(x(:)')];
elseif isa(x,'function_handle')
if strncmp(char(x),'@(',2)
f = functions(x);
x = ['f' f.function summarize(f.workspace{1},rs)];
else
x = ['f ' char(x)];
end
elseif isobject(x)
x = ['o' class(x) ':' summarize(struct(x),rs)];
else
try
x = ['u' class(x) ':' summarize(struct(x),rs)];
catch
warning('BCILAB:hlp_fingerprint:unsupported_type','Unsupported type: %s',class(x));
error; %#ok<LTARG>
end
end
function x = vectorize(x)
x = x(:)';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.