plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
lcnbeapp/beapp-master
om_normals.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/openmeeg/om_normals.m
1,572
utf_8
ca0342ba8f9473f946c7df879e4a82c8
function [nrm] = normals(pos, tri, opt) % NORMALS compute the surface normals of a triangular mesh % for each triangle or for each vertex % % Use as % nrm = normals(pos, tri, opt) % where opt is either 'vertex' or 'triangle' % Copyright (C) 2002-2007, Robert Oostenveld if nargin<3 opt='vertex'; elseif (opt(1)=='v' | opt(1)=='V') opt='vertex'; elseif (opt(1)=='t' | opt(1)=='T') opt='triangle'; else error('invalid optional argument'); end npos = size(pos,1); ntri = size(tri,1); % shift to center pos(:,1) = pos(:,1)-mean(pos(:,1),1); pos(:,2) = pos(:,2)-mean(pos(:,2),1); pos(:,3) = pos(:,3)-mean(pos(:,3),1); % compute triangle normals nrm_tri = zeros(ntri, 3); for i=1:ntri v2 = pos(tri(i,2),:) - pos(tri(i,1),:); v3 = pos(tri(i,3),:) - pos(tri(i,1),:); nrm_tri(i,:) = cross(v2, v3); end if strcmp(opt, 'vertex') % compute vertex normals nrm_pos = zeros(npos, 3); for i=1:ntri nrm_pos(tri(i,1),:) = nrm_pos(tri(i,1),:) + nrm_tri(i,:); nrm_pos(tri(i,2),:) = nrm_pos(tri(i,2),:) + nrm_tri(i,:); nrm_pos(tri(i,3),:) = nrm_pos(tri(i,3),:) + nrm_tri(i,:); end % normalise the direction vectors to have length one nrm = nrm_pos ./ (sqrt(sum(nrm_pos.^2, 2)) * ones(1,3)); else % normalise the direction vectors to have length one nrm = nrm_tri ./ (sqrt(sum(nrm_tri.^2, 2)) * ones(1,3)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fast cross product to replace the Matlab standard version function [c] = cross(a,b) c = [a(2)*b(3)-a(3)*b(2) a(3)*b(1)-a(1)*b(3) a(1)*b(2)-a(2)*b(1)];
github
lcnbeapp/beapp-master
normals.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/openmeeg/private/normals.m
2,346
utf_8
fc0a8ff8ded57a42b7f5436338ed6788
function [nrm] = normals(pnt, tri, opt); % NORMALS compute the surface normals of a triangular mesh % for each triangle or for each vertex % % [nrm] = normals(pnt, tri, opt) % where opt is either 'vertex' or 'triangle' % Copyright (C) 2002-2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.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$ if nargin<3 opt='vertex'; elseif (opt(1)=='v' | opt(1)=='V') opt='vertex'; elseif (opt(1)=='t' | opt(1)=='T') opt='triangle'; else error('invalid optional argument'); end npnt = size(pnt,1); ntri = size(tri,1); % shift to center pnt(:,1) = pnt(:,1)-mean(pnt(:,1),1); pnt(:,2) = pnt(:,2)-mean(pnt(:,2),1); pnt(:,3) = pnt(:,3)-mean(pnt(:,3),1); % compute triangle normals nrm_tri = zeros(ntri, 3); for i=1:ntri v2 = pnt(tri(i,2),:) - pnt(tri(i,1),:); v3 = pnt(tri(i,3),:) - pnt(tri(i,1),:); nrm_tri(i,:) = cross(v2, v3); end if strcmp(opt, 'vertex') % compute vertex normals nrm_pnt = zeros(npnt, 3); for i=1:ntri nrm_pnt(tri(i,1),:) = nrm_pnt(tri(i,1),:) + nrm_tri(i,:); nrm_pnt(tri(i,2),:) = nrm_pnt(tri(i,2),:) + nrm_tri(i,:); nrm_pnt(tri(i,3),:) = nrm_pnt(tri(i,3),:) + nrm_tri(i,:); end % normalise the direction vectors to have length one nrm = nrm_pnt ./ (sqrt(sum(nrm_pnt.^2, 2)) * ones(1,3)); else % normalise the direction vectors to have length one nrm = nrm_tri ./ (sqrt(sum(nrm_tri.^2, 2)) * ones(1,3)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fast cross product to replace the Matlab standard version function [c] = cross(a,b) c = [a(2)*b(3)-a(3)*b(2) a(3)*b(1)-a(1)*b(3) a(1)*b(2)-a(2)*b(1)];
github
lcnbeapp/beapp-master
dipoli.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/dipoli/dipoli.m
4,457
utf_8
f2e2fe3dbd61e25b90d68adb9202f375
function [vol] = dipoli(vol, isolated) % DIPOLI computes a BEM system matrix % % Use as % [vol] = dipoli(vol, isolated) % Copyright (C) 2005-2008, Robert Oostenveld % % $Log: dipoli.m,v $ % Revision 1.3 2008/12/24 10:25:41 roboos % cleaned up the dipoli wrapper, replaced the binary by a better one and added a copy of the helper functions (from fileio) % % Revision 1.2 2008/12/24 09:20:11 roboos % added subfunctions etc as dipoli_xxx and modified dipoli main function accordingly % % Revision 1.1.1.1 2008/12/24 08:52:28 roboos % created new module that will hold the dipoli specific stuff for prepare_bemmodel % % Revision 1.2 2006/01/20 09:48:36 roboos % fill remaining elements of matrix with zeros % changed reshape and transpose % %$Id$ warning('DIPOLI is deprecated, please use FT_PREPARE_HEADMODEL with cfg.method = ''dipoli'' instead.') % find the location of the binary str = which('dipoli.m'); [p, f, x] = fileparts(str); dipoli = fullfile(p, f); % without the .m extension dipoli = checkplatformbinary(dipoli); if ~isempty(dipoli) skin = find_outermost_boundary(vol.bnd); source = find_innermost_boundary(vol.bnd); % the first compartment should be the skin, the last the source if skin==1 && source==length(vol.bnd) vol.skin = 1; vol.source = length(vol.bnd); elseif skin==length(vol.bnd) && source==1 % flip the order of the compartments vol.bnd = fliplr(vol.bnd(:)'); vol.skin = 1; vol.source = length(vol.bnd); else error('the first compartment should be the skin, the last the source'); end if isolated fprintf('using the isolated source approach\n'); else fprintf('not using isolated source approach\n'); end % write the triangulations to file bnddip = vol.bnd; bndfile = {}; for i=1:length(bnddip) bndfile{i} = [tempname '.tri']; % make sure that normals on the vertices point outwards ok = checknormals(bnddip(i)); if ~ok, bnddip(i).tri = fliplr(bnddip(i).tri);end write_tri(bndfile{i}, bnddip(i).pnt, bnddip(i).tri); end % these will hold the shell script and the inverted system matrix exefile = [tempname '.sh']; amafile = [tempname '.ama']; fid = fopen(exefile, 'w'); fprintf(fid, '#!/bin/sh\n'); fprintf(fid, '\n'); fprintf(fid, '%s -i %s << EOF\n', dipoli, amafile); for i=1:length(vol.bnd) if isolated && vol.source==i % the isolated potential approach should be applied using this compartment fprintf(fid, '!%s\n', bndfile{i}); else fprintf(fid, '%s\n', bndfile{i}); end fprintf(fid, '%g\n', vol.cond(i)); end fprintf(fid, '\n'); fprintf(fid, '\n'); fprintf(fid, 'EOF\n'); fclose(fid); dos(sprintf('chmod +x %s', exefile)); try % execute dipoli and read the resulting file dos(exefile); ama = loadama(amafile); vol = ama2vol(ama); catch warning('an error ocurred while running dipoli'); disp(lasterr); end % delete the temporary files for i=1:length(vol.bnd) delete(bndfile{i}) end delete(amafile); delete(exefile); else error('Binary file not found or not implemented for this platform!') end function binname = checkplatformbinary(pathname) binname = []; % check for the appropriate platform dependent filename c = computer; is64 = ismember(lower(c),{'maci64' 'glnxa64' 'sol64' 'pcwin64'}); is32 = ismember(lower(c),{'maci' 'mac' 'pcwin'}); if ispc binname = [pathname '.exe']; elseif ismac if is64 allowedbinnames = {[pathname '.maci64'] [pathname '.maci'] [pathname '.mac']}; else allowedbinnames = {[pathname '.maci'] [pathname '.mac']}; end elseif isunix if is64 allowedbinnames = {[pathname '.glnxa64'] [pathname '.glnx86']}; else allowedbinnames = [pathname '.glnx86']; end else [pathname '.sol64']; end for i = 1:length(allowedbinnames) if exist(allowedbinnames{i}) binname = allowedbinnames{i}; return end end function ok = checknormals(bnd) ok = 0; pnt = bnd.pnt; tri = bnd.tri; % translate to the center org = mean(pnt,1); pnt(:,1) = pnt(:,1) - org(1); pnt(:,2) = pnt(:,2) - org(2); pnt(:,3) = pnt(:,3) - org(3); w = sum(solid_angle(pnt, tri)); if w<0 && (abs(w)-4*pi)<1000*eps % FIXME: this method is rigorous only for star shaped surfaces warning('your normals are not oriented correctly') ok = 0; elseif w>0 && abs(w-4*pi)<1000*eps ok = 1; else error('your surface probably is irregular') ok = 0; end
github
lcnbeapp/beapp-master
scpopen.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/biosig/private/scpopen.m
57,392
utf_8
efe5be2dea8235810f4b98539abfdbd1
function [HDR]=scpopen(arg1,CHAN,arg4,arg5,arg6) % SCPOPEN reads and writes SCP-ECG files % % SCPOPEN is an auxillary function to SOPEN for % opening of SCP-ECG files for reading ECG waveform data % % Use SOPEN instead of SCPOPEN % % See also: fopen, SOPEN, % $Id$ % (C) 2004,2006,2007,2008 by Alois Schloegl <[email protected]> % This is part of the BioSig-toolbox http://biosig.sf.net/ % % BioSig 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. if nargin<2, CHAN=0; end; if isstruct(arg1) HDR=arg1; FILENAME=HDR.FileName; elseif ischar(arg1); HDR.FileName=arg1; fprintf(2,'Warning SCPOPEN: the use of SCPOPEN is discouraged; please use SOPEN instead.\n'); end; VER = version; fid = fopen(HDR.FileName,HDR.FILE.PERMISSION,'ieee-le'); HDR.FILE.FID = fid; if ~isempty(findstr(HDR.FILE.PERMISSION,'r')), %%%%% READ tmpbytes = fread(fid,inf,'uchar'); tmpcrc = crc16eval(tmpbytes(3:end)); fseek(fid, 0, 'bof'); HDR.FILE.CRC = fread(fid,1,'uint16'); if (HDR.FILE.CRC ~= tmpcrc); fprintf(HDR.FILE.stderr,'Warning: CRC check failed (%x vs %x)\n',tmpcrc,HDR.FILE.CRC); end; HDR.FILE.Length = fread(fid,1,'uint32'); if HDR.FILE.Length~=HDR.FILE.size, fprintf(HDR.FILE.stderr,'Warning SCPOPEN: header information contains incorrect file size %i %i \n',HDR.FILE.Length,HDR.FILE.size); end; HDR.data = []; DHT = [0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9;0,1,5,3,11,7,23,15,47,31,95,63,191,127,383,255,767,511,1023]'; prefix = [1,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,10,10]; PrefixLength = prefix; %PREFIX = [0,4,5,12,13,28,29,60,61,124,125,252,253,508,509,1020,1021,1022,1023]; PREFIX = [0,4,5,12,13,28,29,60,61,124,125,252,253,508,509,1020,1021,1022,1023]'.*2.^[32-prefix]'; codelength = [1,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,18,26]; mask = [1,7,7,15,15,31,31,63,63,127,127,255,255,511,511,1023,1023,1023,1023]'.*2.^[32-prefix]'; %MASK = dec2bin(mask); %mask = [1,7,7,15,15,31,31,63,63,127,127,255,255,511,511,1023,1023,1023,1023]'; mask2 = [1,7,7,15,15,31,31,63,63,127,127,255,255,511,511,1023,1023,1023,1023]'; PREFIX2 = DHT(:,2); HT19999 = [prefix',codelength',ones(length(prefix),1),DHT]; HT = [prefix',codelength',ones(length(prefix),1),DHT]; dd = [0:255]'; ACC = zeros(size(dd)); c = 0; for k2 = 1:8, ACC = ACC + (dd>127).*(2^c); dd = mod(dd*2, 256); c = c + 1; end; section.CRC = fread(fid,1,'uint16'); section.ID = fread(fid,1,'uint16'); section.Length = fread(fid,1,'uint32'); section.Version = fread(fid,[1,2],'uint8'); section.tmp = fread(fid,[1,6],'uint8'); NSections = min(11,(section.Length-16)/10); for k = 1:NSections, HDR.Block(k).id = k; HDR.Block(k).length = 0; HDR.Block(k).startpos = -1; end; for K = 1:NSections, k = fread(fid,1,'uint16'); len = fread(fid,1,'uint32'); pos = fread(fid,1,'uint32'); if ((k > 0) && (k < NSections)) HDR.Block(k).id = k; HDR.Block(k).length = len; HDR.Block(k).startpos = pos-1; %% [HDR.Block(k).id ,length(tmpbytes), HDR.Block(k).length, HDR.Block(k).length+HDR.Block(k).startpos] %% FIXME: instead of min(...,FileSize) a warning or error message should be reported tmpcrc = crc16eval(tmpbytes(HDR.Block(k).startpos+3:min(HDR.Block(k).startpos+HDR.Block(k).length,HDR.FILE.size))); if (HDR.Block(k).length>0) if (tmpcrc~=(tmpbytes(HDR.Block(k).startpos+(1:2))'*[1;256])) fprintf(HDR.FILE.stderr,'Warning SCPOPEN: faulty CRC %04x in section %i\n',tmpcrc,k-1); end; end; end; end; %%[[HDR.Block.id];[HDR.Block.length];[HDR.Block.startpos]]' % default values - in case Section 6 is missing HDR.NS = 0; HDR.SPR = 0; HDR.NRec = 0; HDR.Calib = zeros(1,0); secList = find([HDR.Block.length]); for K = secList(1:end), if fseek(fid,HDR.Block(K).startpos,'bof'); fprintf(HDR.FILE.stderr,'Warning SCPOPEN: section %i not available, although it is listed in Section 0\n',secList(K+1)); end; section.CRC = fread(fid,1,'uint16'); section.ID = fread(fid,1,'uint16'); section.Length = fread(fid,1,'uint32'); section.Version = fread(fid,[1,2],'uint8'); section.tmp = fread(fid,[1,6],'uint8'); HDR.SCP.Section{find(K==secList)} = section; if (section.Length==0), elseif section.ID==0, NSections = (section.Length-16)/10; for k = 1:NSections, HDR.Block(k).id = fread(fid,1,'uint16'); HDR.Block(k).length = fread(fid,1,'uint32'); HDR.Block(k).startpos = fread(fid,1,'uint32')-1; end; elseif section.ID==1, tag = 0; k1 = 0; Sect1Len = section.Length-16; ListOfRequiredTags = [2,14,25,26]; ListOfRecommendedTags = [0,1,5,8,15,34]; while (tag~=255) & (Sect1Len>2), tag = fread(fid,1,'uint8'); len = fread(fid,1,'uint16'); Sect1Len = Sect1Len - 3 - len; %% [tag,len,Sect1Len], %% DEBUGGING information field = fread(fid,[1,len],'uchar'); if tag == 0, ListOfRecommendedTags(ListOfRecommendedTags==tag)=[]; HDR.Patient.Name = char(field); %% LastName elseif tag == 1, ListOfRecommendedTags(ListOfRecommendedTags==tag)=[]; HDR.Patient.FirstName = char(field); elseif tag == 2, ListOfRequiredTags(find(ListOfRequiredTags==2))=[]; HDR.Patient.Id = char(field); elseif tag == 3, HDR.Patient.LastName2 = char(field); elseif tag == 4, HDR.Patient.Age = field(1:2)*[1;256]; tmp = field(3); if tmp==1, HDR.Patient.Age = HDR.Patient.Age; % unit='Y'; elseif tmp==2, HDR.Patient.Age = HDR.Patient.Age/12; % unit='M'; elseif tmp==3, HDR.Patient.Age = HDR.Patient.Age/52; % unit='W'; elseif tmp==4, HDR.Patient.Age = HDR.Patient.Age/365.25; % unit='d'; elseif tmp==5, HDR.Patient.Age = HDR.Patient.Age/(365.25*24); %unit='h'; else warning('units of age not specified'); end; elseif (tag == 5) ListOfRecommendedTags(ListOfRecommendedTags==tag)=[]; if any(field(1:4)~=0) HDR.Patient.Birthday = [field(1:2)*[1;256],field(3:4),12,0,0]; end; elseif (tag == 6) if any(field(1:3)), HDR.Patient.Height = field(1:2)*[1;256]; tmp = field(3); if tmp==1, % unit='cm'; elseif tmp==2, HDR.Patient.Height = HDR.Patient.Height*2.54; %unit='inches'; elseif tmp==3, HDR.Patient.Height = HDR.Patient.Height*0.1; %unit='mm'; else warning('units of height not specified'); end; end; elseif (tag == 7) if any(field(1:3)), HDR.Patient.Weight = field(1:2)*[1;256]; tmp = field(3); if tmp==1, % unit='kg'; elseif tmp==2, HDR.Patient.Weight = HDR.Patient.Weight/1000; %unit='g'; elseif tmp==3, HDR.Patient.Weight = HDR.Patient.Weight/2.2; %unit='pound'; elseif tmp==4, HDR.Patient.Weight = HDR.Patient.Weight*0.0284; %unit='ounce'; else warning('units of weight not specified'); end; end; elseif tag == 8, ListOfRecommendedTags(ListOfRecommendedTags==tag)=[]; HDR.Patient.Sex = field; elseif tag == 9, HDR.Patient.Race = field; elseif tag == 10, if (field(1)~=0) HDR.Patient.Medication = field; else HDR.Patient.Medication.Code = field(2:3); HDR.Patient.Medication = field(4:end); end; elseif tag == 11, HDR.Patient.BloodPressure.Systolic = field*[1;256]; elseif tag == 12, HDR.Patient.BloodPressure.Diastolic = field*[1;256]; elseif tag == 13, HDR.Patient.Diagnosis = char(field); elseif tag == 14, ListOfRequiredTags(ListOfRequiredTags==tag)=[]; HDR.SCP1.AcquiringDeviceID = char(field); HDR.VERSION = field(15)/10; elseif tag == 15, ListOfRecommendedTags(ListOfRecommendedTags==tag)=[]; HDR.SCP1.AnalyisingDeviceID = char(field); elseif tag == 16, HDR.SCP1.AcquiringInstitution = char(field); elseif tag == 17, HDR.SCP1.AnalyzingInstitution = char(field); elseif tag == 18, HDR.SCP1.AcquiringDepartment = char(field); elseif tag == 19, HDR.SCP1.AnalyisingDepartment = char(field); elseif tag == 20, HDR.SCP1.Physician = char(field); elseif tag == 21, HDR.SCP1.LatestComfirmingPhysician = char(field); elseif tag == 22, HDR.SCP1.Technician = char(field); elseif tag == 23, HDR.SCP1.Room = char(field); elseif tag == 24, HDR.SCP1.Emergency = field; elseif tag == 25, ListOfRequiredTags(ListOfRequiredTags==tag)=[]; HDR.T0(1,1:3) = [field(1:2)*[1;256],field(3:4)]; elseif tag == 26, ListOfRequiredTags(ListOfRequiredTags==tag)=[]; HDR.T0(1,4:6) = field(1:3); elseif tag == 27, HDR.Filter.HighPass = field(1:2)*[1;256]/100; elseif tag == 28, HDR.Filter.LowPass = field(1:2)*[1;256]/100; elseif tag == 29, if (field==0) HDR.FILTER.Notch = NaN; elseif bitand(field,1) HDR.FILTER.Notch = 60; % 60Hz Notch elseif bitand(field,2) HDR.FILTER.Notch = 50; % 50Hz Notch elseif bitand(field,3)==0 HDR.FILTER.Notch = -1; % Notch Off end; HDR.SCP1.Filter.BitMap = field; elseif tag == 30, HDR.SCP1.FreeText = char(field); elseif tag == 31, HDR.SCP1.ECGSequenceNumber = char(field); elseif tag == 32, HDR.SCP1.MedicalHistoryCodes = char(field); elseif tag == 33, HDR.SCP1.ElectrodeConfigurationCodes = field; elseif tag == 34, ListOfRecommendedTags(ListOfRecommendedTags==tag)=[]; HDR.SCP1.Timezone = field; elseif tag == 35, HDR.SCP1.MedicalHistory = char(field); elseif tag == 255, % section terminator elseif tag >= 200, % manufacturer specific - not standardized else fprintf(HDR.FILE.stderr,'Warning SCOPEN: unknown tag %i (section 1)\n',tag); end; end; if ~isempty(ListOfRequiredTags) fprintf(HDR.FILE.stderr,'Warning SCPOPEN: the following tags are required but missing in file %s\n',HDR.FileName); disp(ListOfRequiredTags); end; if ~isempty(ListOfRecommendedTags) fprintf(HDR.FILE.stderr,'Warning SCPOPEN: the following tags are recommended but missing in file %s\n',HDR.FileName); disp(ListOfRecommendedTags); end; elseif section.ID==2, % Huffman tables HDR.SCP2.NHT = fread(fid,1,'uint16'); HDR.SCP2.NCT = fread(fid,1,'uint16'); if HDR.SCP2.NHT~=19999, NHT = HDR.SCP2.NHT; else NHT = 0; end; k3 = 0; for k1 = 1:NHT, HT1 = zeros(HDR.SCP2.NCT,5); for k2 = 1:HDR.SCP2.NCT, tmp = fread(fid,3,'uint8') ; HDR.SCP2.prefix = tmp(1); % PrefixLength HDR.SCP2.codelength = tmp(2); % CodeLength HDR.SCP2.TableModeSwitch = tmp(3); tmp(4) = fread(fid,1,'int16'); % BaseValue tmp(5) = fread(fid,1,'uint32'); % BaseCode k3 = k3 + 1; HT (k3,:) = [tmp']; HT1(k2,:) = [tmp']; end; HDR.SCP2.HTree{k1} = makeTree(HT1); HDR.SCP2.HTs{k1} = HT1; end; if HDR.SCP2.NHT~=19999, HDR.SCP2.HT = HT; else tmp = size(HT19999,1); HDR.SCP2.HT = [ones(tmp,1),[1:tmp]',HT19999]; HDR.SCP2.HTree{1} = makeTree(HT19999); HDR.SCP2.HTs{1} = HT19999; end; elseif section.ID==3, HDR.NS = fread(fid,1,'uint8'); HDR.FLAG.Byte = fread(fid,1,'uint8'); if ~bitand(HDR.FLAG.Byte,4) fprintf(HDR.FILE.stdout,'Warning SCPOPEN: not all leads simultaneously recorded - this mode is not supported.\n'); end; HDR.FLAG.ReferenceBeat = mod(HDR.FLAG.Byte,2); %HDR.NS = floor(mod(HDR.FLAG.Byte,128)/8); for k = 1:HDR.NS, HDR.LeadPos(k,1:2) = fread(fid,[1,2],'uint32'); HDR.LeadIdCode(k,1) = fread(fid,1,'uint8'); end; HDR.N = max(HDR.LeadPos(:))-min(HDR.LeadPos(:))+1; HDR.AS.SPR = HDR.LeadPos(:,2)-HDR.LeadPos(:,1)+1; HDR.SPR = HDR.AS.SPR(1); for k = 2:HDR.NS HDR.SPR = lcm(HDR.SPR,HDR.AS.SPR(k)); end; HDR = leadidcodexyz(HDR); for k = 1:HDR.NS, if 0, elseif (HDR.LeadIdCode(k)==0), HDR.Label{k} = 'unspecified lead'; elseif (HDR.VERSION <= 1.3) & (HDR.LeadIdCode(k) < 86), % HDR.Label{k} = H.Label(H.LeadIdCode==HDR.LeadIdCode(k)); elseif (HDR.VERSION <= 1.3) & (HDR.LeadIdCode(k) > 99), HDR.Label{k} = 'manufacturer specific'; elseif (HDR.VERSION >= 2.0) & (HDR.LeadIdCode(k) < 151), % HDR.Label{k} = H.Label(H.LeadIdCode==HDR.LeadIdCode(k)); elseif (HDR.VERSION >= 2.0) & (HDR.LeadIdCode(k) > 199), HDR.Label{k} = 'manufacturer specific'; else HDR.Label{k} = 'reserved'; end; end; HDR.Label = strvcat(HDR.Label); elseif section.ID==4, HDR.SCP4.L = fread(fid,1,'int16'); HDR.SCP4.fc0 = fread(fid,1,'int16'); HDR.SCP4.N = fread(fid,1,'int16'); HDR.SCP4.type = fread(fid,[7,HDR.SCP4.N],'uint16')'*[1,0,0,0; 0,1,0,0;0,2^16,0,0; 0,0,1,0;0,0,2^16,0; 0,0,0,1;0,0,0,2^16]; tmp = fread(fid,[2*HDR.SCP4.N],'uint32'); HDR.SCP4.PA = reshape(tmp,2,HDR.SCP4.N)'; HDR.SCP4.pa = [0;tmp;HDR.N]; elseif any(section.ID==[5,6]), SCP = []; SCP.Cal = fread(fid,1,'int16')/1e6; % quant in nV, converted into mV SCP.PhysDim = 'mV'; SCP.Dur = fread(fid,1,'int16'); SCP.SampleRate = 1e6/SCP.Dur; SCP.FLAG.DIFF = fread(fid,1,'uint8'); SCP.FLAG.bimodal_compression = fread(fid,1,'uint8'); if isnan(HDR.NS), HDR.ERROR.status = -1; HDR.ERROR.message = sprintf('Error SCPOPEN: could not read %s\n',HDR.FileName); fprintf(HDR.FILE.stderr,'Error SCPOPEN: could not read %s\n',HDR.FileName); return; end; if CHAN==0, CHAN = 1:HDR.NS; end; SCP.SPR = fread(fid,HDR.NS,'uint16'); HDR.InChanSelect = CHAN; if section.ID==6, HDR.HeadLen = ftell(fid); HDR.FLAG.DIFF = SCP.FLAG.DIFF; HDR.FLAG.bimodal_compression = SCP.FLAG.bimodal_compression; HDR.data = []; outlen = HDR.SPR; HDR.Calib = sparse(2:HDR.NS+1, 1:HDR.NS, SCP.Cal); elseif isfield(HDR,'SCP4') %% HACK: do no know whether it is correct outlen = floor(1000*HDR.SCP4.L/SCP.Dur); else outlen = inf; end; if ~isfield(HDR,'SCP2'), if any(SCP.SPR(1)~=SCP.SPR), error('SCPOPEN: SPR do not fit'); else S2 = fread(fid,[SCP.SPR(1)/2,HDR.NS],'int16'); end; %S2 = S2(:,CHAN); elseif (HDR.SCP2.NHT==1) && (HDR.SCP2.NCT==1) && (HDR.SCP2.prefix==0), codelength = HDR.SCP2.HT(1,4); if (codelength==16) S2 = fread(fid,[HDR.N,HDR.NS],'int16'); elseif (codelength==8) S2 = fread(fid,[HDR.N,HDR.NS],'int8'); else fprintf(HDR.FILE.stderr,'Warning SCPOPEN: codelength %i is not supported yet.',codelength); fprintf(HDR.FILE.stderr,' Contact <[email protected]>\n'); return; end; %S2 = S2(:,CHAN); elseif 1, HDR.SCP2.NHT~=19999; %% User specific Huffman table %% a more elegant Huffman decoder is used here %% for k = 1:HDR.NS, SCP.data{k} = fread(fid,SCP.SPR(k),'uint8'); end; % S2 = repmat(NaN,outlen,length(HDR.InChanSelect)); clear S2; sz = inf; for k3 = 1:length(HDR.InChanSelect), k = HDR.InChanSelect(k3); %HDR.NS, outdata{k3} = DecodeHuffman(HDR.SCP2.HTree,HDR.SCP2.HTs,SCP.data{k},outlen); sz = min(sz,length(outdata{k3})); end; for k3 = 1:length(HDR.InChanSelect), k = HDR.InChanSelect(k3); %HDR.NS, S2(:,k) = outdata{k3}(1:sz); end; accu=0; elseif HDR.SCP2.NHT==19999, HuffTab = DHT; for k = 1:HDR.NS, SCP.data{k} = fread(fid,SCP.SPR(k),'uint8'); end; %for k = 1:HDR.NS, for k3 = 1:length(HDR.InChanSelect), k = HDR.InChanSelect(k3); %HDR.NS, %for k = CHAN(:)', s2 = SCP.data{k}; s2 = [s2; repmat(0,ceil(max(HDR.SCP2.HT(:,4))/8),1)]; k1 = 0; l2 = 0; accu = 0; c = 0; x = []; HT = HDR.SCP2.HT(find(HDR.SCP2.HT(:,1)==1),3:7); while (l2 < HDR.LeadPos(k,2)), while ((c < max(HT(:,2))) & (k1<length(s2)-1)); k1 = k1 + 1; dd = s2(k1); accu = accu + ACC(dd+1)*(2^c); c = c + 8; if 0, %for k2 = 1:8, accu = accu + (dd>127)*(2^c); dd = mod(dd*2,256); c = c + 1; end; end; ixx = 1; %acc = mod(accu,2^32); % bitand returns NaN if accu >= 2^32 acc = accu - 2^32*fix(accu*(2^(-32))); % bitand returns NaN if accu >= 2^32 while (bitand(acc,2^HT(ixx,1)-1) ~= HT(ixx,5)), ixx = ixx + 1; end; dd = HT(ixx,2) - HT(ixx,1); if HT(ixx,3)==0, HT = HDR.SCP2.HT(find(HDR.SCP2.HT(:,1)==HT(ixx,5)),3:7); fprintf(HDR.FILE.stderr,'Warning SCPOPEN: Switching Huffman Tables is not tested yet.\n'); elseif (dd==0), l2 = l2 + 1; x(l2) = HT(ixx,4); else %if (HT(ixx,3)>0), l2 = l2 + 1; %acc2 = fix(accu*(2^(-HT(ixx,1)))); %tmp = mod(fix(accu*(2^(-HT(ixx,1)))),2^dd); tmp = fix(accu*(2^(-HT(ixx,1)))); % bitshift(accu,-HT(ixx,1)) tmp = tmp - (2^dd)*fix(tmp*(2^(-dd))); % bitand(...,2^dd) %tmp = bitand(accu,(2^dd-1)*(2^HT(ixx,1)))*(2^-HT(ixx,1)); % reverse bit-pattern if dd==8, tmp = ACC(tmp+1); else tmp = dec2bin(tmp); tmp = [char(repmat('0',1,dd-length(tmp))),tmp]; tmp = bin2dec(tmp(length(tmp):-1:1)); end x(l2) = tmp-(tmp>=(2^(dd-1)))*(2^dd); end; accu = fix(accu*2^(-HT(ixx,2))); c = c - HT(ixx,2); end; x = x(:); if k3==1, S2=x(:,ones(1,k)); elseif size(x,1)==size(S2,1), S2(:,k) = x; else fprintf(HDR.FILE.stderr,'Error SCPOPEN: Huffman decoding failed (%i) \n',size(x,1)); HDR.data = S2; return; end; end; elseif (HDR.SCP2.NHT==19999), % alternative decoding algorithm. warning('this branch is experimental - it might be broken') HuffTab = DHT; for k = 1:HDR.NS, SCP.data{k} = fread(fid,SCP.SPR(k),'uint8'); end; %for k = 1:HDR.NS, for k3 = 1:length(HDR.InChanSelect), k = HDR.InChanSelect(k3); %HDR.NS, %for k = CHAN(:)', tmp = SCP.data{k}; accu = [tmp(4)+256*tmp(3)+65536*tmp(2)+2^24*tmp(1)]; %accu = bitshift(accu,HDR.SCP2.prefix,32); c = 0; %HDR.SCP2.prefix; l = 4; l2 = 0; clear x; Ntmp = length(tmp); tmp = [tmp; zeros(4,1)]; while c <= 32, %1:HDR.SPR(k), ixx = 1; while (bitand(accu,mask(ixx)) ~= PREFIX(ixx)), ixx = ixx + 1; end; if ixx < 18, c = c + prefix(ixx); %accu = bitshift(accu, prefix(ixx),32); accu = mod(accu.*(2^prefix(ixx)),2^32); l2 = l2 + 1; x(l2) = HuffTab(ixx,1); elseif ixx == 18, c = c + prefix(ixx) + 8; %accu = bitshift(accu, prefix(ixx),32); accu = mod(accu.*(2^prefix(ixx)),2^32); l2 = l2 + 1; acc1 = mod(floor(accu*2^(-24)),256); %accu = bitshift(accu, 8, 32); accu = mod(accu*256, 2^32); x(l2) = acc1-(acc1>=2^7)*2^8; acc2 = 0; for kk = 1:8, acc2 = acc2*2 + mod(acc1,2); acc1 = floor(acc1/2); end; elseif ixx == 19, c = c + prefix(ixx); %accu = bitshift(accu, prefix(ixx),32); accu = mod(accu.*(2^prefix(ixx)),2^32); l2 = l2 + 1; while (c > 7) & (l < Ntmp), l = l+1; c = c-8; accu = accu + tmp(l)*2^c; end; acc1 = mod(floor(accu*2^(-16)),2^16); %accu = bitshift(accu, 16, 32); accu = mod(accu.*(2^16), 2^32); x(l2) = acc1-(acc1>=2^15)*2^16; acc2 = 0; for kk=1:16, acc2 = acc2*2+mod(acc1,2); acc1 = floor(acc1/2); end; %x(l2) = acc2; c = c + 16; end; while (c > 7) & (l < Ntmp), l = l+1; c = c-8; accu = accu + tmp(l)*(2^c); end; end; x = x(1:end-1)'; if k3==1, S2=x(:,ones(1,k)); elseif size(x,1)==size(S2,1), S2(:,k) = x; elseif 1, fprintf(HDR.FILE.stderr,'Error SCPOPEN: length=%i of channel %i different to length=%i of channel 1 \n',size(x,1),k,size(S2,1)); return; else fprintf(HDR.FILE.stderr,'Error SCPOPEN: Huffman decoding failed (%i) \n',size(x,1)); HDR.data=S2; return; end; end; elseif HDR.SCP2.NHT~=19999, %% OBSOLETE %% fprintf(HDR.FILE.stderr,'Error SOPEN SCP-ECG: user specified Huffman Table not supported\n'); HDR.SCP = SCP; return; else HDR.SCP2, end; % Decoding of Difference encoding if SCP.FLAG.DIFF==2, for k1 = 3:size(S2,1); S2(k1,:) = S2(k1,:) + [2,-1] * S2(k1-(1:2),:); end; elseif SCP.FLAG.DIFF==1, S2 = cumsum(S2); end; if section.ID==5, HDR.SCP5 = SCP; HDR.SCP5.data = S2; HDR.SampleRate = SCP.SampleRate; elseif section.ID==6, HDR.SCP6 = SCP; HDR.SampleRate = SCP.SampleRate; HDR.PhysDim = repmat({HDR.SCP6.PhysDim},HDR.NS,1); HDR.data = S2; if HDR.FLAG.bimodal_compression, %% FIXME: THIS IS A HACK - DO NOT KNOW WHETHER IT IS CORRECT. % HDR.FLAG.bimodal_compression = isfield(HDR,'SCP5') & isfield(HDR,'SCP4'); HDR.FLAG.bimodal_compression = isfield(HDR,'SCP4'); end; if HDR.FLAG.bimodal_compression, if isfield(HDR,'SCP5') F = HDR.SCP5.SampleRate/HDR.SCP6.SampleRate; HDR.SampleRate = HDR.SCP5.SampleRate; HDR.FLAG.F = F; else HDR.FLAG.F = 1; end; tmp=[HDR.SCP4.PA(:,1);HDR.LeadPos(1,2)]-[1;HDR.SCP4.PA(:,2)+1]; if ~all(tmp==floor(tmp)) tmp, end; t = (1:HDR.N) / HDR.SampleRate; S1 = zeros(HDR.N, HDR.NS); p = 1; k2 = 1; pa = [HDR.SCP4.PA;NaN,NaN]; flag = 1; %% FIXME: accu undefined ## accu = 0; for k1 = 1:HDR.N, if k1 == pa(p,2)+1, flag = 1; p = p+1; accu = S2(k2,:); elseif k1 == pa(p,1), flag = 0; k2 = ceil(k2); end; if flag, S1(k1,:) = ((F-1)*accu + S2(fix(k2),:)) / F; k2 = k2 + 1/F; else S1(k1,:) = S2(k2,:); k2 = k2 + 1; end; end; HDR.SCP.S2 = S2; HDR.SCP.S1 = S1; S2 = S1; end; if HDR.FLAG.ReferenceBeat & ~isfield(HDR,'SCP5') fprintf(HDR.FILE.stderr,'Warning SOPEN SCP-ECG: Flag ReferenceBeat set, but no section 5 (containing the reference beat) is available\n'); elseif HDR.FLAG.ReferenceBeat, tmp_data = HDR.SCP5.data*(HDR.SCP5.Cal/HDR.SCP6.Cal); for k = find(~HDR.SCP4.type(:,1)'), t1 = (HDR.SCP4.type(k,2):HDR.SCP4.type(k,4)); t0 = t1 - HDR.SCP4.type(k,3) + HDR.SCP4.fc0; S2(t1,:) = S2(t1,:) + tmp_data(t0,:); end; end; HDR.data = S2; end; elseif section.ID==7, HDR.SCP7.byte1 = fread(fid,1,'uint8'); HDR.SCP7.Nspikes = fread(fid,1,'uint8'); HDR.SCP7.meanPPI = fread(fid,1,'uint16'); HDR.SCP7.avePPI = fread(fid,1,'uint16'); for k=1:HDR.SCP7.byte1, HDR.SCP7.RefBeat{k} = fread(fid,16,'uint8'); %HDR.SCP7.RefBeat1 = fread(fid,16,'uint8'); end; for k=1:HDR.SCP7.Nspikes, tmp = fread(fid,16,'uint16'); tmp(1,2) = fread(fid,16,'int16'); tmp(1,3) = fread(fid,16,'uint16'); tmp(1,4) = fread(fid,16,'int16'); HDR.SCP7.ST(k,:) = tmp; end; for k=1:HDR.SCP7.Nspikes, tmp = fread(fid,6,'uint8'); HDR.SCP7.ST2(k,:) = tmp; end; HDR.SCP7.Nqrs = fread(fid,1,'uint16'); HDR.SCP7.beattype = fread(fid,HDR.SCP7.Nqrs,'uint8'); HDR.SCP7.VentricularRate = fread(fid,1,'uint16'); HDR.SCP7.AterialRate = fread(fid,1,'uint16'); HDR.SCP7.QTcorrected = fread(fid,1,'uint16'); HDR.SCP7.TypeHRcorr = fread(fid,1,'uint8'); len = fread(fid,1,'uint16'); tag = 255*(len==0); k1 = 0; while tag~=255, tag = fread(fid,1,'uchar'); len = fread(fid,1,'uint16'); field = fread(fid,[1,len],'uchar'); if tag == 0, HDR.Patient.LastName = char(field); elseif tag == 1, end; end; HDR.SCP7.P_onset = fread(fid,1,'uint16'); HDR.SCP7.P_offset = fread(fid,1,'uint16'); HDR.SCP7.QRS_onset = fread(fid,1,'uint16'); HDR.SCP7.QRS_offset = fread(fid,1,'uint16'); HDR.SCP7.T_offset = fread(fid,1,'uint16'); HDR.SCP7.P_axis = fread(fid,1,'uint16'); HDR.SCP7.QRS_axis = fread(fid,1,'uint16'); HDR.SCP7.T_axis = fread(fid,1,'uint16'); elseif section.ID==8, tmp = fread(fid,9,'uint8'); HDR.SCP8.Report = tmp(1); HDR.SCP8.Time = [[1,256]*tmp(2:3),tmp(4:8)']; HDR.SCP8.N = tmp(9); for k = 1:HDR.SCP8.N, ix = fread(fid,1,'uint8'); len = fread(fid,1,'uint16'); tmp = fread(fid,[1,len],'uchar'); HDR.SCP8.Statement{k,1} = char(tmp); end %elseif section.ID==9, % HDR.SCP9.byte1 = fread(fid,1,'uint8'); elseif section.ID==10, tmp = fread(fid,2,'uint16'); HDR.SCP10.NumberOfLeads = tmp(1); HDR.SCP10.ManufacturerCode = tmp(2); for k = []; 1:HDR.SCP10.NumberOfLeads, tmp = fread(fid,2,'uint16') LeadId = tmp(1); LeadLen = tmp(2); tmp = fread(fid,LeadLen/2,'uint16'); HDR.SCP10.LeadId(k)=LeadId; HDR.SCP10.LeadLen(k)=LeadLen; HDR.SCP10.Measurements{k}=tmp; end; elseif section.ID==11, bytes = fread(fid,11,'uint8'); HDR.SCP11.T0 = [bytes(2)*256+bytes(3), bytes(4:8)]; HDR.SCP11.Confirmed = bytes(1); HDR.SCP11.NumberOfStatements = bytes(9); for k = 1:HDR.SCP11.NumberOfStatements, SeqNo = fread(fid,1,'uint8'); len11 = fread(fid,1,'uint16'); typeID = fread(fid,1,'uint8'); Statement = fread(fid,len11-1,'uint8'); HDR.SCP11.Statement.SeqNo(k) = SeqNo; HDR.SCP11.Statement.len11(k) = len11; HDR.SCP11.Statement.typeID(k) = typeID; HDR.SCP11.Statement.Statement{k} = Statement; end; end; if ~section.Length, HDR.ERROR.status = -1; HDR.ERROR.message = 'Error SCPOPEN: \n'; return; end; end; HDR.SPR = size(HDR.data,1); HDR.NRec = 1; HDR.AS.endpos = HDR.SPR; HDR.FILE.OPEN = 0; HDR.FILE.POS = 0; HDR.TYPE = 'native'; fclose(HDR.FILE.FID); else % writing SCP file NSections = 12; SectIdHdr = zeros(1,16); VERSION = round(HDR.VERSION*10); if ~any(VERSION==[10,13,20]) fprintf(HDR.FILE.stderr,'Warning SCPOPEN(WRITE): unknown Version number %4.2f\n',HDR.VERSION); VERSION = 20; end; SectIdHdr(9:10) = VERSION; % Section and Protocol version number POS = 6; B = zeros(1,POS); for K = 0:NSections-1; b = []; if K==0, % SECTION 0 b = [SectIdHdr(1:10),'SCPECG', zeros(1,NSections*10)]; b(16+(7:10)) = s4b(POS+1); elseif K==1, % SECTION 1 b = SectIdHdr; % tag(1),len(1:2),field(1:len) if isfield(HDR.Patient,'Name'), b = [b, 0, s2b(length(HDR.Patient.Name)), HDR.Patient.Name]; end; if isfield(HDR.Patient,'Id'), b = [b, 2, s2b(length(HDR.Patient.Id)), HDR.Patient.Id]; end; if isfield(HDR.Patient,'Age'), %b = [b, 4, s2b(3), s2b(HDR.Patient.Age),1]; %% use birthday instead end; if isfield(HDR.Patient,'Birthday'), b = [b, 5, s2b(4), s2b(HDR.Patient.Birthday(1)),HDR.Patient.Birthday(2:3)]; end; if isfield(HDR.Patient,'Height'), if ~isnan(HDR.Patient.Height), b = [b, 6, s2b(3), s2b(HDR.Patient.Height),1]; end; end; if isfield(HDR.Patient,'Weight'), if ~isnan(HDR.Patient.Weight), b = [b, 7, s2b(3), s2b(HDR.Patient.Weight),1]; end; end; if isfield(HDR.Patient,'Sex'), if ~isempty(HDR.Patient.Sex) sex = HDR.Patient.Sex; if 0, elseif isnumeric(sex), sex = sex(1); elseif strncmpi(sex,'male',1); sex = 1; elseif strncmpi(sex,'female',1); sex = 2; else sex = 9; % unspecified end; b = [b, 8, s2b(1), sex]; end; end; if isfield(HDR.Patient,'Race'), b = [b, 9, s2b(1), HDR.Patient.Race(1)]; end; if isfield(HDR.Patient,'BloodPressure'), b = [b, 11, s2b(2), s2b(HDR.Patient.BloodPressure.Systolic)]; b = [b, 12, s2b(2), s2b(HDR.Patient.BloodPressure.Diastolic)]; end; %% Tag 14 tag14.AnalyzingProgramRevisionNumber = ['',char(0)]; tag14.SerialNumberAcqDevice = ['',char(0)]; tag14.AcqDeviceSystemSoftware = ['',char(0)]; tag14.SCPImplementationSoftware = ['BioSig4OctMat v 1.76+',char(0)]; tag14.ManufactureAcqDevice = ['',char(0)]; t14 = [zeros(1,35), length(tag14.AnalyzingProgramRevisionNumber),tag14.AnalyzingProgramRevisionNumber,tag14.SerialNumberAcqDevice,tag14.AcqDeviceSystemSoftware,tag14.SCPImplementationSoftware,tag14.ManufactureAcqDevice]; t14(8) = 255; % Manufacturer %%% ### FIXME ### t14(9:14) = % cardiograph model t14(15) = VERSION; % Version t14(16) = hex2dec('A0'); % Demographics and ECG rhythm data" (if we had also the reference beats we should change it in 0xC0). t14(18) = hex2dec('D0'); % Capabilities of the ECG Device: 0xD0 (acquire, print and store). b = [b, 14, s2b(length(t14)), t14]; b = [b, 25, s2b(4), s2b(HDR.T0(1)),HDR.T0(2:3)]; b = [b, 26, s2b(3), HDR.T0(4:6)]; if ~any(isnan(HDR.Filter.HighPass)) b = [b, 27, s2b(2), s2b(round(HDR.Filter.HighPass(1)*100))]; end; if ~any(isnan(HDR.Filter.LowPass)) b = [b, 28, s2b(2), s2b(round(HDR.Filter.LowPass(1)))]; end; b = [b, 255, 0, 0]; % terminator b = b + (b<0)*256; elseif K==3, % SECTION 3 b = [SectIdHdr,HDR.NS,4+HDR.NS*8]; if ~isfield(HDR,'LeadIdCode'), HDR.LeadIdCode = zeros(1,HDR.NS); end; if (numel(HDR.LeadIdCode)~=HDR.NS); warning('HDR.LeadIdCode does not have HDR.NS elements'); end; if any(HDR.LeadIdCode>255), warning('invalid LeadIdCode'); end; for k = 1:HDR.NS, b = [b, s4b(1), s4b(HDR.SPR*HDR.NRec), mod(HDR.LeadIdCode(k),256)]; end; elseif K==6, % SECTION 6 Cal = full(HDR.Calib(2:end,:)); Cal = Cal - diag(diag(Cal)); if any(Cal(:)) fprintf(HDR.FILE.stderr,'Calibration is not a diagonal matrix.\n\tThis can result in incorrect scalings.\n'); end; Cal = full(diag(HDR.Calib(2:end,:))); if any(Cal~=Cal(1)), fprintf(HDR.FILE.stderr,'scaling information is not equal for all channels; \n\tThis is not supported by SCP and can result in incorrect scalings.\n'); end; [tmp,scale1] = physicalunits(HDR.PhysDim{1}); [tmp,scale2] = physicalunits('nV'); b = [SectIdHdr, s2b(round(Cal(1)*scale1/scale2)), s2b(round(1e6/HDR.SampleRate)), 0, 0]; for k = 1:HDR.NS, b = [b, s2b(HDR.SPR*HDR.NRec*2)]; end; data = HDR.data(:); data = data + (data<0)*2^16; tmp = s2b(round(data))'; b = [b,tmp(:)']; else b = []; end; if (length(b)>0) if mod(length(b),2), % align to multiple of 2-byte blocks b = [b,0]; end; if (length(b)<16), fprintf(HDR.FILE.stderr,'section header %i less then 16 bytes %i', K,length(b)); end; b(3:4) = s2b(K); b(5:8) = s4b(length(b)); %b(1:2)= s4b(crc); b(1:2) = s2b(crc16eval(b(3:end))); % section 0: startpos in pointer field B(22+K*10+(7:10)) = s4b(POS+1); end; B = [B(1:POS),b]; % section 0 pointer field B(22+K*10+(1:2)) = s2b(K); B(22+K*10+(3:6)) = s4b(length(b)); % length POS = POS + length(b); end B(3:6) = s4b(POS); % length of file B(7:8) = s2b(crc16eval(B(9:22+NSections*10))); % CRC of Section 0 B(1:2) = s2b(crc16eval(B(3:end))); % fwrite(fid,crc,'int16'); count = fwrite(fid,B,'uchar'); fclose(fid); end end %% scpopen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Auxillary functions % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b2 = s2b(i) % converts 16bit into 2 bytes b2 = [bitand(i,255),bitand(bitshift(i,-8),255)]; return; end %%%%% s2b %%%%% function b4 = s4b(i) % converts 32 bit into 4 bytes b4 = [s2b(bitand(i,2^16-1)),s2b(bitand(bitshift(i,-16),2^16-1)) ]; return; end %%%%% s4b %%%%% function T = makeSubTree(T,bc,len,val) if (len==0) T.idxTable = val; return end; if 1, b = bitand(bc,1)+1; if ~isfield(T,'branch') T.branch = {[],[]}; end; T.branch{b} = makeSubTree(T.branch{b},bitshift(bc,-1),len-1,val); else if bitand(bc,1) if ~isfield(T,'node1'),T.node1 = []; end; T.node1 = makeSubTree(T.node1,bitshift(bc,-1),len-1,val); else if ~isfield(T,'node0'),T.node0 = []; end; T.node0 = makeSubTree(T.node0,bitshift(bc,-1),len-1,val); end; end, return; end %%%%% makeSubTree %%%%% function T = makeTree(HT) T = []; for k1 = 1:size(HT,1) for k2 = 1:HT(k1,1) % CodeLength T = makeSubTree(T,HT(k1,5),HT(k1,1),k1); end; end; %save matlab T,pause return; end %%%%% makeTree %%%%% function outdata = DecodeHuffman(HTrees,HTs,indata,outlen) ActualTable = 1; k1 = 1; r=0; k2 = 0; if ((outlen>0) && isfinite(outlen)) outdata = repmat(NaN,outlen,1); else outdata = [0;0]; %% make it a column vector end; Node = HTrees{ActualTable}; while ((k1*8+r <= 8*length(indata)) && (k2<outlen)) if ~isfield(Node,'idxTable') r = r+1; if (r>8), k1=k1+1; r=1; end; if 1, b = bitand(bitshift(indata(k1),r-8),1)+1; if ~isempty(Node.branch{b}) Node = Node.branch{b}; else fprintf(2,'Warning SCPOPEN: empty node in Huffman table\n'); end; else if bitand(bitshift(indata(k1),r-8),1) if isfield(Node,'node1') Node = Node.node1; else fprintf(2,'Warning SCPOPEN: empty node in Huffman table\n'); end; else if isfield(Node,'node0') Node = Node.node0; else fprintf(2,'Warning SCPOPEN: empty node in Huffman table\n'); end; end; end; end; if isfield(Node,'idxTable') TableEntry = HTs{ActualTable}(Node.idxTable,:); dlen = TableEntry(2)-TableEntry(1); if (~TableEntry(3)) ActualTable = TableEntry(4); elseif (dlen~=0) acc = 0; for k3 = 1:dlen, r = r+1; if (r>8), k1=k1+1; r=1; end; acc = 2*acc + bitand(bitshift(indata(k1),r-8), 1); end; if (acc>=bitshift(1,dlen-1)) acc = acc - bitshift(1,dlen); end; k2 = k2+1; outdata(k2) = acc; else k2 = k2+1; outdata(k2)=TableEntry(4); end; Node = HTrees{ActualTable}; end; end; return; end %%%%%%%% DecodeHuffman %%%%%%%%% function crc16 = crc16eval(D) % CRC16EVAL cyclic redundancy check with the polynomiaL x^16+x^12+x^5+1 % i.e. CRC-CCITT http://en.wikipedia.org/wiki/Crc16 D = uint16(D); crchi = 255; crclo = 255; t = '00102030405060708191a1b1c1d1e1f112023222524272629383b3a3d3c3f3e32434041464744454a5b58595e5f5c5d53626160676665646b7a79787f7e7d7c74858687808182838c9d9e9f98999a9b95a4a7a6a1a0a3a2adbcbfbeb9b8bbbab6c7c4c5c2c3c0c1cedfdcdddadbd8d9d7e6e5e4e3e2e1e0effefdfcfbfaf9f8f9181b1a1d1c1f1e110003020504070608393a3b3c3d3e3f30212223242526272b5a59585f5e5d5c53424140474645444a7b78797e7f7c7d72636061666764656d9c9f9e99989b9a95848786818083828cbdbebfb8b9babbb4a5a6a7a0a1a2a3afdedddcdbdad9d8d7c6c5c4c3c2c1c0cefffcfdfafbf8f9f6e7e4e5e2e3e0e1e'; crc16htab = hex2dec(reshape(t,2,length(t)/2)'); t = '0021426384a5c6e708294a6b8cadceef31107352b594f7d639187b5abd9cffde62432001e6c7a4856a4b2809eecfac8d53721130d7f695b45b7a1938dffe9dbcc4e586a740610223cced8eaf48690a2bf5d4b79671503312fddcbf9e79583b1aa687e4c522036041ae8feccd2a0b684997b6d5f4133251709fbeddfc1b3a597888a9caeb0c2d4e6f80a1c2e304254667b998fbda3d1c7f5eb190f3d235147756eacba8896e4f2c0de2c3a08166472405dbfa99b85f7e1d3cd3f291b0577615344c6d0e2fc8e98aab44650627c0e182a37d5c3f1ef9d8bb9a75543716f1d0b3922e0f6c4daa8be8c926076445a283e0c11f3e5d7c9bbad9f81736557493b2d1f0'; crc16ltab = hex2dec(reshape(t,2,length(t)/2)'); for k = 1:length(D), ix = double(bitxor(crchi,D(k)))+1; crchi = bitxor(crclo,crc16htab(ix)); crclo = crc16ltab(ix); end; crc16 = crchi*256+crclo; end %%%%% crc16eval %%%%%
github
lcnbeapp/beapp-master
openxml.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/biosig/private/openxml.m
13,850
utf_8
a2522f85226716568c1d40ee7e6666f6
function [HDR]=openxml(arg1,CHAN,arg4,arg5,arg6) % OPENXML reads XML files and tries to extract biosignal data % % This is an auxilary function to SOPEN. % Use SOPEN instead of OPENXML. % % % HDR = openxml(HDR); % % HDR contains the Headerinformation and internal data % % see also: SOPEN, SREAD, SSEEK, STELL, SCLOSE, SWRITE, SEOF % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 3 % of the License, or (at your option) any later version. % $Id$ % Copyright 2006,2007,2008 by Alois Schloegl <[email protected]> % This is part of the BIOSIG-toolbox http://biosig.sf.net/ if ischar(arg1); HDR.FileName = arg1; HDR.FILE.PERMISSION = 'r'; else HDR = arg1; end; %if strncmp(HDR.TYPE,'XML',3), % if any(HDR.FILE.PERMISSION=='r'), fid = fopen(HDR.FileName,HDR.FILE.PERMISSION,'ieee-le'); s = char(fread(fid,[1,1024],'char')); if all(s(1:2)==[255,254]) & all(s(4:2:end)==0) HDR.TYPE='XML-UTF16'; elseif ~isempty(findstr(char(s),'?xml version')) HDR.TYPE='XML-UTF8'; end; fseek(fid,0,'bof'); if strcmp(HDR.TYPE,'XML-UTF16'), magic = char(fread(fid,1,'uint16')); HDR.XML = char(fread(fid,[1,inf],'uint16')); elseif strcmp(HDR.TYPE,'XML-UTF8'), HDR.XML = char(fread(fid,[1,inf],'uint8')); end; fclose(fid); HDR.FILE.FID = fid; if 0, ~exist('xmlstruct') warning('XML toolbox missing') end; if 1, HDR.XMLstruct = xmlstruct(HDR.XML,'sub'); HDR.XMLlist = xmlstruct(HDR.XML); end; try XML = xmltree(HDR.XML); XML = convert(XML); HDR.XML = XML; HDR.TYPE = 'XML'; catch fprintf(HDR.FILE.stderr,'ERROR SOPEN (XML): XML-toolbox missing or invalid XML file.\n'); return; end; tmp = fieldnames(HDR.XML); if any(strmatch('PatientDemographics',tmp)) & any(strmatch('TestDemographics',tmp)) & any(strmatch('RestingECGMeasurements',tmp)) & any(strmatch('Diagnosis',tmp)) & any(strmatch('Waveform',tmp)), % GE-Marquette FDA-XML MAC5000 HDR.Patient.ID = HDR.XML.PatientDemographics.PatientID; tmp = HDR.XML.PatientDemographics.Gender; HDR.Patient.Sex = 2*(upper(tmp(1))=='F') + (upper(tmp(1))=='M'); HDR.Patient.Name = [HDR.XML.PatientDemographics.PatientLastName,', ',HDR.XML.PatientDemographics.PatientFirstName]; tmp = HDR.XML.TestDemographics.AcquisitionDate; tmp(tmp=='-') = ' '; HDR.T0([3,2,1])=str2double(tmp); tmp = HDR.XML.TestDemographics.AcquisitionTime; tmp(tmp==':') = ' '; HDR.T0(4:6) = str2double(tmp); HDR.NS = str2double(HDR.XML.Waveform.NumberofLeads); HDR.SampleRate = str2double(HDR.XML.Waveform.SampleBase); HDR.Filter.LowPass = str2double(HDR.XML.Waveform.LowPassFilter)*ones(1,HDR.NS); HDR.Filter.HighPass = str2double(HDR.XML.Waveform.HighPassFilter)*ones(1,HDR.NS); HDR.Filter.Notch = str2double(HDR.XML.Waveform.ACFilter)*ones(1,HDR.NS); HDR.NRec = 1; HDR.SPR = 1; for k = 1:HDR.NS, CH = HDR.XML.Waveform.LeadData{k}; HDR.AS.SPR(k) = str2double(CH.LeadSampleCountTotal); HDR.SPR = lcm(HDR.SPR,HDR.AS.SPR(k)); HDR.Cal(k) = str2double(CH.LeadAmplitudeUnitsPerBit); HDR.PhysDim{k} = CH.LeadAmplitudeUnits; HDR.Label{k} = CH.LeadID; t = radix64d(CH.WaveFormData); t = 256*t(2:2:end) + t(1:2:end); t = t - (t>=(2^15))*(2^16); HDR.data(:,k) = t(:); end; HDR.TYPE = 'native'; elseif any(strmatch('component',tmp)) % FDA-XML Format tmp = HDR.XML.component.series.derivation; if isfield(tmp,'Series'); tmp = tmp.Series.component.sequenceSet.component; else % Dovermed.CO.IL version of format tmp = tmp.derivedSeries.component.sequenceSet.component; end; HDR.NS = length(tmp)-1; HDR.NRec = 1; HDR.Cal = 1; HDR.PhysDim = {' '}; HDR.SampleRate = 1; HDR.TYPE = 'XML-FDA'; % that's an FDA XML file elseif any(strmatch('dataacquisition',tmp)) & any(strmatch('reportinfo',tmp)) & any(strmatch('patient',tmp)) & any(strmatch('documentinfo',tmp)), % SierraECG 1.03 *.open.xml from PHILIPS HDR.SampleRate = str2double(HDR.XML.dataacquisition.signalcharacteristics.samplingrate); HDR.NS = str2double(HDR.XML.dataacquisition.signalcharacteristics.numberchannelsvalid); HDR.Cal = str2double(HDR.XML.reportinfo.reportgain.amplitudegain.overallgain); HDR.PhysDim = {'uV'}; HDR.Filter.HighPass = str2double(HDR.XML.reportinfo.reportbandwidth.highpassfiltersetting); HDR.Filter.LowPass = str2double(HDR.XML.reportinfo.reportbandwidth.lowpassfiltersetting); HDR.Filter.Notch = str2double(HDR.XML.reportinfo.reportbandwidth.notchfiltersetting); t = HDR.XML.reportinfo.reportformat.waveformformat.mainwaveformformat; k = 0; HDR.Label={}; while ~isempty(t), [s,t] = strtok(t,' '); k = k+1; HDR.Label{k, 1} = [s,' ']; end; HDR.Patient.Id = str2double(HDR.XML.patient.generalpatientdata.patientid); tmp = HDR.XML.patient.generalpatientdata.age; if isfield(tmp,'years'), HDR.Patient.Age = str2double(tmp.years); end if isfield(tmp,'dateofbirth') tmp = tmp.dateofbirth; tmp(tmp=='-')=' '; HDR.Patient.Birthday([6,5,4]) = str2double(tmp); end; tmp = HDR.XML.patient.generalpatientdata.sex; HDR.Patient.Sex = strncmpi(tmp,'Male',1) + strncmpi(tmp,'Female',1)*2; HDR.Patient.Weight = str2double(HDR.XML.patient.generalpatientdata.weight.kg); HDR.Patient.Height = str2double(HDR.XML.patient.generalpatientdata.height.cm); HDR.VERSION = HDR.XML.documentinfo.documentversion; HDR.TYPE = HDR.XML.documentinfo.documenttype; elseif any(strmatch('component',tmp)) & any(strmatch('reportinfo',tmp)) & any(strmatch('patient',tmp)) & any(strmatch('documentinfo',tmp)), % FDA-XML Format tmp = HDR.XML.component.series.derivation; if isfield(tmp,'Series'); tmp = tmp.Series.component.sequenceSet.component; else % Dovermed.CO.IL version of format tmp = tmp.derivedSeries.component.sequenceSet.component; end; HDR.NS = length(tmp)-1; HDR.NRec = 1; HDR.Cal = 1; HDR.PhysDim = {' '}; HDR.SampleRate = 1; HDR.TYPE = 'XML-FDA'; % that's an FDA XML file elseif any(strmatch('StripData',tmp)) & any(strmatch('ClinicalInfo',tmp)) & any(strmatch('PatientInfo',tmp)) & any(strmatch('ArrhythmiaData',tmp)), % GE Case8000 stress ECG HDR.SampleRate = str2double(HDR.XML.StripData.SampleRate); tmp = HDR.XML.ClinicalInfo.ObservationDateTime; HDR.T0 = [str2double(tmp.Year), str2double(tmp.Month), str2double(tmp.Day), str2double(tmp.Hour), str2double(tmp.Minute), str2double(tmp.Second)]; HDR.Patient.Id = HDR.XML.PatientInfo.PID; HDR.Patient.Name = 'X'; % [HDR.XML.PatientInfo.Name, ', ', HDR.XML.PatientInfo.GivenName]; HDR.Patient.Age = str2double(HDR.XML.PatientInfo.Age); tmp = HDR.XML.PatientInfo.Gender; HDR.Patient.Sex = any(tmp(1)=='Mm') + any(tmp(1)=='Ff')*2; HDR.Patient.Height = str2double(HDR.XML.PatientInfo.Height); HDR.Patient.Weight = str2double(HDR.XML.PatientInfo.Weight); tmp = HDR.XML.PatientInfo.BirthDateTime; HDR.Patient.Birthday = [str2double(tmp.Year), str2double(tmp.Month), str2double(tmp.Day),0,0,0]; tmp = HDR.XML.StripData.Strip; HDR.NS = length(tmp{1}.WaveformData); tmax = str2double(tmp{end}.Time.Minute)*60 + str2double(tmp{end}.Time.Second)+10; data = repmat(NaN,tmax*HDR.SampleRate,HDR.NS); for k = 1:length(tmp); t = HDR.SampleRate*(str2double(tmp{k}.Time.Minute)*60 + str2double(tmp{k}.Time.Second)); for k2 = 1:HDR.NS, x = str2double(tmp{k}.WaveformData{k2}); data(t+1:t+length(x),k2)=x(:); end; end; tmp = HDR.XML.ArrhythmiaData.Strip; for k = 1:length(tmp); t = HDR.SampleRate*(str2double(tmp{k}.Time.Minute)*60 + str2double(tmp{k}.Time.Second)); for k2 = 1:HDR.NS, x = str2double(tmp{k}.WaveformData{k2}); data(t+1:t+length(x),k2)=x(:); end; end; HDR.data = data - 2^12*(data>2^11); HDR.TYPE = 'native'; HDR.NRec = 1; HDR.SPR = size(HDR.data,1); HDR.Calib = sparse(2:HDR.NS,1:HDR.NS,1); HDR.FLAG.UCAL = 1; else fprintf(HDR.FILE.stderr,'Warning SOPEN (XML): File %s is not supported.\n',HDR.FileName); return; end try tmp=HDR.XML.componentOf.timepointEvent.componentOf.subjectAssignment.subject.trialSubject.subjectDemographicPerson.name; HDR.Patient.Name = sprintf('%s, %s',tmp.family, tmp.given); catch end; HDR.Calib = sparse(2:HDR.NS+1,1:HDR.NS,HDR.Cal); HDR.FILE.OPEN = 1; HDR.FILE.POS = 0; % end; %end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Auxillary functions % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = radix64d(x); % RADIX64D - decoding of radix64 encoded sequence % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % $Id$ % (C) 2006 by Alois Schloegl <[email protected]> % This is part of the BIOSIG-toolbox http://biosig.sf.net/ global BIOSIG_GLOBAL if ~isfield(BIOSIG_GLOBAL,'R64E'); BIOSIG_GLOBAL.R64E = ['A':'Z','a':'z','0':'9','+','/']; BIOSIG_GLOBAL.R64D = zeros(256,1)-1; for k = 1:length(BIOSIG_GLOBAL.R64E), BIOSIG_GLOBAL.R64D(BIOSIG_GLOBAL.R64E(k)) = k-1; end; end; % http://www.faqs.org/rfcs/rfc2440.html t = BIOSIG_GLOBAL.R64D(x); t = [t(t>=0); zeros(3,1)]; N = floor(length(t)/4); t = reshape(bitand(t(1:N*4),2^6-1),4,N); y(1,:) = bitshift(t(1,:),2) + bitshift(t(2,:),-4); y(2,:) = bitshift(mod(t(2,:),16),4) + bitshift(t(3,:),-2); y(3,:) = bitshift(mod(t(3,:),4),6) + t(4,:); y = y(:)'; y = y(1:end-sum(x=='=')); % remove possible pad characters
github
lcnbeapp/beapp-master
matread.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/biosig/private/matread.m
10,217
utf_8
0c42f4955d1ed526f04022f79b06fd87
function [HDR,data,t]=matread(HDR,arg2,idxlist) % MATRREAD Loads (parts of) data stored in Matlab-format % % [HDR,data,timeindex]=matread(HDR,block_number, [startidx, endidx]) % This is the recommended use for Matlab-files generated from ADICHT data % Before using MATREAD, HDR=MATOPEN(filename, 'ADI', ...) must be applied. % % [HDR,data,timeindex]=matread(HDR,Variable_Name, [startidx, endidx]) % can be used for other Matlab4 files. % Variable name is a string which identifies a Matlab Variable. % Before using MATREAD, HDR=MATOPEN(filename, 'r', ...) must be applied. % % see also: EEGREAD, FREAD, EEGOPEN, EEGCLOSE % $Revision$ % $Id$ % Copyright (c) 1997-2003 by Alois Schloegl % [email protected] % This library is free software; you can redistribute it and/or % modify it under the terms of the GNU Library General Public % License as published by the Free Software Foundation; either % Version 2 of the License, or (at your option) any later version. % % This library 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 % Library General Public License for more details. % % You should have received a copy of the GNU Library General Public % License along with this library; if not, write to the % Free Software Foundation, Inc., 59 Temple Place - Suite 330, % Boston, MA 02111-1307, USA. CHt=[]; if ~ischar(arg2) if strcmp(HDR.TYPE,'ADI'); %HDR.ADI.Mode, BlockNo=abs(arg2); if isempty(BlockNo), BlockNo=1:length(HDR.ADI.DB); end; if (isinf(BlockNo) | (length(BlockNo)~=1)) if nargout<3, fprintf(2,'Warning MATREAD: missing output argument, time information cannot be returned\n'); end; CHd=HDR.ADI.DB(BlockNo); CHt=HDR.ADI.TB(BlockNo); elseif ((BlockNo<1) | BlockNo>length(HDR.ADI.DB)), fprintf(2,'Warning MATREAD: tried to read block %i, but only %i blocks in file %s\n',BlockNo,length(HDR.ADI.DB),HDR.FileName); CHd=[];CHt=[]; else CHd=HDR.ADI.DB(BlockNo); CHt=HDR.ADI.TB(BlockNo); end; else CHd=arg2; fprintf(2,'Warning MATREAD: Variable identified by number\n'); end; else %if ischar(arg2) CHd=find(strcmp(arg2,{HDR.Var.Name})); if isempty(CHd) %HDR.ErrNo=-1; fprintf(2,'Warning MATREAD: Variable %s not found\n',arg2); data=[]; return; end; end; if length(CHd)>1 fprintf(2,'Warning MATREAD: Only one block/variable can be read\n'); CHd=CHd(1); end; if nargin<4, end; if nargin<3, idxlist=[1,HDR.Var(CHd).Size(2)]; else if ~all(isfinite(idxlist)), idxlist=[1,HDR.Var(CHd).Size(2)]; end; end % if length(idxlist)<2,idxlist=idxlist*[1 1]; end; if (idxlist(1)<1) %| (idxlist(length(idxlist))>HDR.Var(CHd).Size(2))), fprintf(2,'Warning MATREAD #%i: Invalid File Position %f-%f\n',CHd,[idxlist(1)-1,idxlist(length(idxlist))]); idxlist(1)=1; %return; end; if idxlist(length(idxlist))>HDR.Var(CHd).Size(2), fprintf(2,'Warning MATREAD #%i: endidx exceeds block length %f-%f\n',CHd,[HDR.Var(CHd).Size(2),idxlist(length(idxlist))]); idxlist=[idxlist(1),HDR.Var(CHd).Size(2)]; %return; end; if 0; %((idxlist(1)<1) | (idxlist(length(idxlist))>HDR.Var(CHd).Size(2))), fprintf(2,'ERROR MATREAD #%i: Invalid File Position %f-%f\n',CHd,[idxlist(1)-1,idxlist(length(idxlist))]); return; end; Pos = (idxlist(1)-1) * HDR.Var(CHd).Size(1) * HDR.Var(CHd).SizeOfType; Len = min(idxlist(length(idxlist)), HDR.Var(CHd).Size(2)) - idxlist(1) + 1; fseek(HDR.FILE.FID, round(HDR.Var(CHd).Pos + Pos), -1); % round must be explicite, otherwise fseek does incorrect rounding [msg,errno] = ferror(HDR.FILE.FID); if errno, fprintf(2,'ERROR MATREAD: FSEEK does not work Pos=%f\n%s',HDR.Var(CHd).Pos+Pos,msg); return; end; count = 0; if ~any(CHd==HDR.ADI.DB), % for non-data blocks data=repmat(nan,HDR.Var(CHd).Size(1),Len); while (count<Len), cc = min(2^12,Len-count); % [CHd,idxlist(1),idxlist(length(idxlist)),Len,HDR.Var(CHd).Size(2)] [dta,c] = readnextblock4(HDR.FILE.FID,HDR.Var(CHd),cc); data(:,count+(1:size(dta,2))) = dta; count = count + cc; end; else BLOCKSIZE=64*3*25*4; % 2^12; % You can change this for optimizing on your platform %HDR=mat_setfilter(HDR,BlockNo);% set filters for this block for k=1:max(HDR.SIE.InChanSelect), if k <= HDR.NS, if HDR.SIE.FILT==1; [tmp,HDR.Filter.Z(:,k)] = filter(HDR.Filter.B,HDR.Filter.A,zeros(length(HDR.Filter.B),1)); HDR.FilterOVG.Z = HDR.Filter.Z; end; end; end; if isfield(HDR,'iFs') & (HDR.iFs>0) & (HDR.iFs<inf), Fs=HDR.SampleRate(find(CHd==HDR.ADI.DB))/HDR.iFs; data = repmat(nan,ceil(Len*size(HDR.SIE.T,2)/size(HDR.SIE.T,1)/Fs),length(HDR.SIE.ChanSelect)); else Fs=1; data = repmat(nan,ceil(Len*size(HDR.SIE.T,2)/size(HDR.SIE.T,1)),length(HDR.SIE.ChanSelect)); end; count=0; count2=0; while (count2<Len), cc = min(BLOCKSIZE,Len-count2); % [Len, count2, count, Fs, (Len-count2)*Fs, cc] % [CHd,idxlist(1),idxlist(length(idxlist)),Len,HDR.Var(CHd).Size(2)] [dta,c] = readnextblock4(HDR.FILE.FID,HDR.Var(CHd),cc); % ferror(HDR.FILE.FID) % [Len,cc,count,BLOCKSIZE,HDR.FILE.Pos,ftell(HDR.FILE.FID)], [nc,cc] = size(dta); % if any postprocessing, resample to internal Sampling rate iFs=1000Hz) if Fs~=1, dta=rs(dta',Fs,1)'; %**************************************************************************************1 end; if nc~=HDR.NS, % reorganizing of channels dta=sparse(find(HDR.ADI.index{arg2}),1:sum(HDR.ADI.index{arg2}>0),1)*dta; dta(find(~HDR.ADI.index{arg2}),:)=nan; end; for k = sort(HDR.SIE.InChanSelect), %1:size(data,2); %k=HDR.SIE.chanselect(K), if k<=HDR.NS, if HDR.SIE.FILT, [dta(k,:),HDR.Filter.Z(:,k)]=filter(HDR.Filter.B,HDR.Filter.A,dta(k,:),HDR.Filter.Z(:,k)); end; end; end; if HDR.SIE.RS, dta = rs(dta(HDR.SIE.ChanSelect,:)',HDR.SIE.T); %RS% ***********************************************2 else dta = dta(HDR.SIE.ChanSelect,:)'; end; data(count+(1:size(dta,1)),:) = dta; count = count + size(dta,1); count2 = count2 + cc; end; %%%%% Overflow Detection %%%%% if HDR.SIE.TH, for k=1:find(~isnan(sum(HDR.SIE.THRESHOLD,2))), ch = phrchan(HDR.FILE.Name); tmp = (data(:,k)<HDR.SIE.THRESHOLD(1,k)) | (data(:,ch)>HDR.SIE.THRESHOLD(2,k)); data(tmp,k) = NaN; end; end; % load time vector if nargout>2, if ~isempty(CHt), fseek(HDR.FILE.FID, round(HDR.Var(CHt).Pos + (idxlist(1)-1)*HDR.Var(CHt).SizeOfType),-1); [t,c]=readnextblock4(HDR.FILE.FID,HDR.Var(CHt),idxlist(length(idxlist))-min(idxlist)+1); if length(t)>1, tmp=diff(t); if any(abs(tmp-tmp(length(tmp)))>1000*eps) fprintf(2,'Warning %s: Sampling is not equally spaced in %s [%i,%i]\n',mfilename,HDR.FileName,idxlist(1),idxlist(length(idxlist))); end; end; %%%%% Delay of Filtering if HDR.SIE.FILT, t = t' + HDR.Filter.Delay; else t = t'; end; % if any postprocessing, resample to internal Sampling rate iFs=1000Hz) if isfield(HDR,'iFs') & (HDR.iFs>0) & (HDR.iFs<inf), Fs=HDR.SampleRate(find(CHd==HDR.ADI.DB))/HDR.iFs; if Fs~=1, t=rs(t,Fs,1); %*********************************************************************3 end; end; %%%%% Resampling of the time if HDR.SIE.RS, t=rs(t,HDR.SIE.T); %RS% %******************************************************************4 end; else fprintf(2,'Warning %s: timeindex is not available \n',mfilename); end; end; end; function [data,c]=readnextblock4(fid,VarInfo,Len), dt=VarInfo.Type(3); if dt==0, type = 'float64'; elseif dt==6, type = 'uint8'; elseif dt==4, type = 'uint16'; elseif dt==3, type = 'int16'; elseif dt==2, type = 'int32'; elseif dt==1, type = 'float32'; else fprintf(2,'Error %s: unknown data type\n',mfilename); return; end; [data,c]=fread(fid,[VarInfo.Size(1),Len],type); if VarInfo.Type(5); %HDR.ErrNo=-1; fprintf(2,'Warning %s: imaginary data not test\n',mfilename); [di,c]=fread(fid,[VarInfo.Size(1),Len],type); data=data+i*di; end; if VarInfo.Type(4)==1,data=char(data); end;
github
lcnbeapp/beapp-master
GE_createSPMmat.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/GE_createSPMmat.m
1,480
utf_8
9da4628d724922838247f14727e25722
%%%%%%%%%%%%%%%%%%%%%%%% % % % Write SPM mat file % % % %%%%%%%%%%%%%%%%%%%%%%%% function M = GE_createSPMmat(im_hdr, scandir) % % Put the appropriate translations and rotations to the M matrix % given the information in the image header and the direction of % acquisition % % S. Inati % Dartmouth College % Apr. 2001 % % The conversion from pixels to mm Dims = diag( [im_hdr.pixsize_X, ... im_hdr.pixsize_Y, ... im_hdr.slthick + im_hdr.scanspacing ]); % Compute the coordinate system in the image plane tlhc = [ im_hdr.tlhc_R; im_hdr.tlhc_A; im_hdr.tlhc_S ]; % Top Left Hand Corner of Image trhc = [ im_hdr.trhc_R; im_hdr.trhc_A; im_hdr.trhc_S ]; % Top Right Hand Corner of Image brhc = [ im_hdr.brhc_R; im_hdr.brhc_A; im_hdr.brhc_S ]; % Bottom Right Hand Corner of Image x = trhc - tlhc; x = x./sqrt(x'*x); % xhat y = trhc - brhc; y = y./sqrt(y'*y); % yhat % The normal to the plane norm = [ im_hdr.norm_R; im_hdr.norm_A; im_hdr.norm_S ]; % The directional normal z = scandir * norm; % zhat % Build the M matrix for SPM % M takes a voxel from the image and gives it a coordinate in mm % On the scanner the voxels start in the top left hand corner of the % first image. In SPM they start in the bottom left hand corner, % so flip y and set the origin to tlhc. % NB: The voxel (1,1,1) should have position tlhc Rot = [x, -y, z]; M = eye(4); M(1:3,1:3) = Rot * Dims; M(1:3,4) = tlhc - Rot*Dims*[1;1;1]; return
github
lcnbeapp/beapp-master
NewCs.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/NewCs.m
20,018
utf_8
02f4f3b94b14be6adab8ee52224b2dc3
function [cs] = NewCs(Name, win, p1, p2, p3, p4, p5) % % [cs] = NewCs (Name, Con, P1, P2) % %Purpose: % Create a command structure for passing to TellAfni % % %Input Parameters: % Name: Name of command, see AFNI's README.driver for all possibilities % Example: SET_THRESHOLD % To see a list of commands, try the function TellAfni_Commands % To start AFNI, use the special Name: 'start_afni' % Con : Index of controller where command is applied. % Choose from 'A' to 'J'. Default if win = '' is controller 'A' % P1 : First parameter passed to command. This can include the % controller index in the form A. See AFNI's README.driver % for information and Test_TellAfni for examples. % P2 : All other parameters to pass to command. This would include % any second parameters plus options. %Output Parameters: % cs : Returned structure to feed to AFNI with TellAfni % .err: Error flag % .w : AFNI controller % .c : AFNI command (Name) % .v : AFNI command value % % %More Info : % TellAfni % TellAfni_Commands % Test_TellAfni % AFNI's README.driver % % Author : Ziad Saad % Date : Tue Dec 6 12:05:09 EST 2005 % SSCC/NIMH/ National Institutes of Health, Bethesda Maryland %Define the function name for easy referencing FuncName = 'NewCs'; %Debug Flag DBG = 1; %initailize return variables cs.err = 1; cs.c = ''; cs.v = ''; cs.w = ''; np = nargin - 2; %number of p parameters if (np == -1), win = ''; end if (np == 0), p1 = ''; p2 = ''; p3 = ''; p4 = ''; p5 = ''; end if (np == 1), p2 = ''; p3 = ''; p4 = ''; p5 = ''; end if (np == 2), p3 = ''; p4 = ''; p5 = ''; end if (np == 3), p4 = ''; p5 = ''; end if (np == 4), p5 = ''; end if (~isempty(win)), win = upper(win); uwin = win; else win = 'A'; uwin = ''; end if (length(win) ~= 1 | win < 'A' | win > 'J'), fprintf(2,'Bad window specifer %s\n', win); return; end Name = upper(Name); switch (Name), case 'START_AFNI', cs.c = sprintf('%s', Name); if (~isempty(p1)), if (NewCs_CheckFnames(p1) > 0), cs.v = p1; else fprintf(2,'Command <%s> requires an existing directory or files for the first parameter\nSomething in %s not found\n', Name, p1) end end cs.v = sprintf('%s %s', cs.v, p2);; case 'ADD_OVERLAY_COLOR', if (np ~= 2 | isnumeric(p1) | isnumeric(p2)), fprintf(2,'Command <%s> requires two string parameters.\nHave %d in %s\n',... Name, np); return; end cs.c = Name; cs.w = win; cs.v = sprintf('%s %s', p1, p2); case 'SET_THRESHOLD', if (np < 1 | np > 2), fprintf(2,'Command <%s> needs 1 or 2 parameters.\nHave %d\n', Name, np); return; end if (~isnumeric(p1)), if (upper(p1(1)) >= 'A' & upper(p1(1)) <= 'J'), win = p1(1); p1 = p1(2:length(p1)); end p1 = str2double(p1); end if (p1 < 0 | p1 >= 1.0), fprintf(2,'Command <%s> has a bad value for threshold (%s).\nThreshold must be between 0 and 1\n',... Name, p1); return; end if (np == 2), if (p2 < 0 | p2 > 4), fprintf(2,'Command <%s> has a bad value for decimal (%f).\nDecimal must be between 0 and 4\n',... cs.c, p2); end return; end cs.v = sprintf('%c.%d %d', win, p1*10000, p2); cs.w = win; cs.c = Name; case 'SET_THRESHNEW', val = p1; isp = ''; if (np == 1), dec = ''; elseif (np==2), if (~isempty(find(p2 == '*'))), dec = '*'; else dec = ''; end if (~isempty(find(p2 == 'p'))), isp = 'p'; if (val < 0.0 | val > 1.0), fprintf(2,'Command <%s> requires pvalues between 0 and 1.0\n',... Name); end else isp = ''; end end cs.w = win; cs.c = Name; cs.v = sprintf('%c %.14f %c%c', cs.w, val, dec, isp); case 'SET_PBAR_NUMBER', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end if (~isnumeric(p1)), if (upper(p1(1)) >= 'A' & upper(p1(1)) <= 'J'), win = p1(1); p1 = p1(2:length(p1)); end p1 = str2double(p1); end if (p1 < 2 | p1 > 20), fprintf(2,'Command <%s> requires a number between 2 and 20\nHave %f', Name, p1); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%d', cs.w, p1); case 'SET_PBAR_SIGN', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); if (p1(1) ~= '+' & p1(1) ~= '-'), fprintf(2,'parameter must be either + or -\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s', win, p1); case 'SET_PBAR_ALL', if (np ~= 2), fprintf(2,'Command <%s> requires 2 parameters\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); ps = p1(1); p1 = p1(2:length(p1)); if (ps ~= '+' & ps ~= '-'), fprintf(2,'Missing sign for pbar\n', Name); return; end ncol = str2num(p1); if (ncol < 1 | ncol > 99), fprintf(2,'Command <%s> needs num between 1 and 99\n', Name); return; end if (ncol < 99), %find out how many colors are specified in p2 if (WordCount(p2) ~= ncol), fprintf(2,'Command <%s>: Mismatch between num (%d) and number of val=color strings (%d)\n', Name, ncol, WordCount(p2)); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%c%d %s', win, ps, ncol, p2); else %check on the topval np2 = WordCount(p2); if (np2 < 2 ), fprintf(2,'Command <%s> needs 2 parameters in second string (topval colorscale_name)\n', Name); return; end [err, topval] = GetWord(p2,1,' '); topval = str2num(topval); if (topval <= 0), fprintf(2,'Command <%s> needs a positive topval\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%c99 %s', win, ps, p2); end case 'PBAR_ROTATE', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); if (p1(1) ~= '+' & p1(1) ~= '-'), fprintf(2,'parameter must be either + or -\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s', win, p1); case 'DEFINE_COLORSCALE', if (np ~= 2), fprintf(2,'Command <%s> requires 2 parametera\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s %s', p1, p2); case 'SET_FUNC_AUTORANGE', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); if (p1(1) ~= '+' & p1(1) ~= '-'), fprintf(2,'parameter must be either + or -\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s', win, p1); case 'SET_FUNC_RANGE', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); if (p1n < 0.0), fprintf(2,'Command <%s> requires a positive parameter\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%f', win, p1n); case { 'SET_FUNC_VISIBLE', 'SEE_OVERLAY', 'SEE_FUNCTION'}, if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); if (p1(1) ~= '+' & p1(1) ~= '-'), fprintf(2,'parameter must be either + or -\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s', win, p1); case 'SET_FUNC_RESAM', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); [err,l1] = GetWord(p1,1,'.'); if (isempty(l1)), fprintf(2,'Command <%s> has empty parameter\n', Name); return; end err = NewCs_OKresam(l1); if (err), fprintf(2,'Function resampling mode %s not recognized.\nChoose from:\n%s\n',... l1, NewCs_OKresam()); return; end [err, l2] = GetWord(p1,2,'.'); if (~isempty(l2)), err = NewCs_OKresam(l2); if (err), fprintf(2,'Resampling mode %s not recognized.\nChoose from:\n%s\n',... l2, NewCs_OKresam()); return; end end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s.%s', win, l1, l2); case 'OPEN_PANEL', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); err = NewCs_OKpanel(p1); if (err), fprintf(2,'Panel %s not recognized.\nChoose from:\n%s\n',... p1, NewCs_OKpanel()); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s',win,p1); case 'SYSTEM', if (np < 1), fprintf(2,'Command <%s> requires at least 1 parameter\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s %s', p1, p2); case 'CHDIR', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s', p1); case 'RESCAN_THIS', if (np > 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end if (np), if (p1(1) < 'A' | p1(1) > 'J'), fprintf(2,'Command <%s> requires 1 parameter between A and J\n', Name); return; end win = p1(1); end cs.w = win; cs.c = Name; cs.v = sprintf('%c', win); case {'SET_SESSION', 'SWITCH_SESSION', 'SWITCH_DIRECTORY'}, if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s',win,p1); case {'SET_SUBBRICKS','SET_SUB_BRICKS'}, if (np < 1), fprintf(2,'Command <%s> requires at least 1 parameter\n', Name); return; end if (np == 2), win = p1; p1 = p2; end val = str2num(p1); if (length(val) ~= 3), fprintf(2,'Second string must contain 3 values.\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c %d %d %d', win, val(1), val(2), val(3)); case {'SET_ANATOMY', 'SWITCH_ANATOMY', 'SWITCH_UNDERLAY'}, if (np < 1), fprintf(2,'Command <%s> requires at least 1 parameter\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); if (np == 2), sb = str2num(p2); if (length(sb) ~= 1), fprintf(2,'Command <%s> requires one integer in the second parameter'); return; end end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s %s', win, p1, p2); case {'SET_FUNCTION', 'SWITCH_FUNCTION', 'SWITCH_OVERLAY'}, if (np < 1), fprintf(2,'Command <%s> requires at least 1 parameter\n', Name); return; end if (np == 2), sb = str2num(p2); if (length(sb) ~= 1 & length(sb) ~= 2), fprintf(2,'Command <%s> requires one or two integers in the second parameter'); return; end end [win, p1, p1n] = NewCs_GetWin(p1, uwin); cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s %s', win, p1, p2); case 'OPEN_WINDOW', if (np < 1), fprintf(2,'Command <%s> requires 1 parameter at least\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); err = NewCs_OKwindowname(p1); if (err), fprintf(2,'Window name %s not recognized.\nChoose from:\n%s\n',... p1, NewCs_OKwindowname()); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s %s', win, p1, p2); case 'CLOSE_WINDOW', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter \n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); err = NewCs_OKwindowname(p1); if (err), fprintf(2,'Window name %s not recognized.\nChoose from:\n%s\n',... p1, NewCs_OKwindowname()); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s', win, p1); case 'SAVE_JPEG', if (np ~= 2), fprintf(2,'Command <%s> requires 2 parameters\n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); err = NewCs_OKwindowname(p1); if (err), fprintf(2,'Window name %s not recognized.\nChoose from:\n%s\n',... p1, NewCs_OKwindowname()); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s %s', win, p1, p2); case { 'SET_DICOM_XYZ', 'SET_SPM_XYZ', 'SET_IJK'}, if (np < 1), fprintf(2,'Command <%s> requires at least 1 parameter\n', Name); return; end if (np == 2), win = p1; p1 = p2; end val = str2num(p1); if (length(val) ~= 3), fprintf(2,'Second string must contain 3 coordinates.\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c %f %f %f', win, val(1), val(2), val(3)); case 'SET_XHAIRS', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter \n', Name); return; end [win, p1, p1n] = NewCs_GetWin(p1, uwin); err = NewCs_OKxhaircode(p1); if (err), fprintf(2,'Xhair code %s not recognized.\nChoose from:\n%s\n',... p1, NewCs_OKxhaircode()); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%c.%s', win, p1); case 'PURGE_MEMORY', cs.w = win; cs.c = Name; cs.v = sprintf('%s', p1); case 'QUIT', cs.w = win; cs.c = Name; cs.v = ''; case 'SETENV', cs.w = win; cs.c = Name; cs.v = sprintf('%s %s', p1, p2); case 'REDISPLAY', cs.w = win; cs.c = Name; cs.v = ''; case 'SLEEP', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter \n', Name); return; end if (~isnumeric(p1)), fprintf(2,'Command <%s> requires at 1 numeric value\n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%f', p1); case 'OPEN_GRAPH_XY', if (np ~= 2), fprintf(2,'Command <%s> requires 2 parameters \n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s %s', p1, p2); case 'CLOSE_GRAPH_XY', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter \n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s', p1); case 'CLEAR_GRAPH_XY', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter \n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s', p1); case 'ADDTO_GRAPH_XY', if (np ~= 2), fprintf(2,'Command <%s> requires 2 parameters \n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s %s', p1, p2); case 'OPEN_GRAPH_1D', if (np ~= 2), fprintf(2,'Command <%s> requires 2 parameters \n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s %s', p1, p2); case 'CLOSE_GRAPH_1D', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter \n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s', p1); case 'CLEAR_GRAPH_1D', if (np ~= 1), fprintf(2,'Command <%s> requires 1 parameter \n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s', p1); case 'ADDTO_GRAPH_1D', if (np ~= 2), fprintf(2,'Command <%s> requires 2 parameters \n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s %s', p1, p2); case 'SET_GRAPH_GEOM', if (np ~= 2), fprintf(2,'Command <%s> requires 2 parameters \n', Name); return; end cs.w = win; cs.c = Name; cs.v = sprintf('%s %s', p1, p2); case 'MADMAG', fprintf(2,'Command <%s> not implemented yet.\n', Name); return; otherwise, fprintf(2,'Command <%s> not understood.\nTry function TellAfni_Commands for available commands.\n', Name); return; end cs.err = 0; return; %%%%% Supporting functions below %%%%%%%%%%%%%%%%% %figure out the window deal function [win,p1,p1n] = NewCs_GetWin(p1, uwin) win = uwin; p1n = 0.0; if (~isnumeric(p1)), if (length(p1) > 1), if ((p1(1)) >= 'A' & (p1(1)) <= 'J' & p1(2) == '.'), win = p1(1); if (~isempty(uwin) & uwin ~= win), fprintf(2,... 'Warning: Conflict in window specification (%c vs %c).\nChoosing one in parameter (%c).\n',... uwin, win, win); end p1 = p1(3:length(p1)); end end p1n = str2double(p1); else p1n = p1; end if (isempty(win)) win = 'A'; end return %check on windowname function [err] = NewCs_OKwindowname(p1) lcool = {'axialimage', 'sagittalimage', 'coronalimage',... 'axialgraph', 'sagittalgraph', 'coronalgraph'}; if (nargin == 1), switch (p1), case lcool, err = 0; return; otherwise, err = 1; return; end else err = ''; for (i=1:1:length(lcool)), err = sprintf('%s %s\n', err, char(lcool(i))); end return; end return %Check on xhaircode function [err] = NewCs_OKxhaircode(p1) lcool = {'OFF', 'SINGLE', 'MULTI',... 'LR_AP', 'LR_IS', 'AP_IS', 'LR', 'AP', 'IS'}; if (nargin == 1), switch (p1), case lcool, err = 0; return; otherwise, err = 1; return; end else err = ''; for (i=1:1:length(lcool)), err = sprintf('%s %s\n', err, char(lcool(i))); end return; end return %Check on resample function [err] = NewCs_OKresam(p1) lcool = {'NN', 'Li', 'Cu',... 'Bk'}; if (nargin == 1), switch (p1), case lcool, err = 0; return; otherwise, err = 1; return; end else err = ''; for (i=1:1:length(lcool)), err = sprintf('%s %s\n', err, char(lcool(i))); end return; end return %Check on panel function [err] = NewCs_OKpanel(p1) lcool = {'Define_Overlay', 'Define_Datamode', 'Define_Markers'}; if (nargin == 1), switch (p1), case lcool, err = 0; return; otherwise, err = 1; return; end else err = ''; for (i=1:1:length(lcool)), err = sprintf('%s %s\n', err, char(lcool(i))); end return; end return %check on input file names function [k] = NewCs_CheckFnames(s) [si, s] = strtok(s,' '); k = 0; if (exist(si,'dir') == 7 || filexist(si)), k = k + 1; else k = -1; end return
github
lcnbeapp/beapp-master
New_HEAD.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/New_HEAD.m
8,432
utf_8
3213a4c8b09f49855cafdf9925e5b3d3
function [err,Info, opt] = New_HEAD (opt) % % [err,Info, Opt] = New_HEAD (Opt) % %Purpose: % A function for the likes of Greg Detre. % It makes the creation of an AFNI dataset % from a 3 or 4 dimensional matrix in matlab a breeze. % % % %Input Parameters: % opt is an options structure with the following fields: % .prefix: A string containg the AFNI dataset's prefix % .prefix and one of .dimen or .master must % be used. % .dimen: A string or array containing the dimensions of % the dataset (at least 3 dimensions need be present). % The following four options are from 3dUndump. See 3dUndump -help % .view: '+orig' (default) or '+acpc' or '+tlrc' % If you choose +tlrc, the resultant volume % will fit the Talairach box. % .master: Name of an existing AFNI dataset that would % provide the needed matrix size, orientation etc. % Do not mix .master with .dimen % .datum: 'byte', 'short' (default), or 'float' % .orient: Orientation of data in matrix. Default in 'RAI' % % .tr: a float specifying the TR in seconds. % The presence of such a field necessitates a 4 dimensional % .scale: 0/1 This is only meaningful with 'short' data where it % defaults to 1. It defaults to 0 for other types. It is % used when storing float data as shorts to minimize disk % use while preserving numeric percision. % .Overwrite: y/[n] allow header to be created even if one with % similar name is found on disk %Output Parameters: % err : 0 No Problem % : 1 Problems % Info: The header structure, given the options specified % Opt: A modified version of the input Opt. It will be passed % along with the data array to WriteBrik for writing the % dataset to disk. (See Examples below) % %Examples: % Run New_HEAD('test') or see Test_New_HEAD.m for examples. % %More Info : % AFNI programs 3drefit and 3dAttribute are your friends % BrikLoad, BrikInfo, WriteBrik % README.attributes % % The function makes heavy use of 3dUndump % %This function requires AFNI binaries postdating Feb. 12 2007 % % % Author : Ziad Saad [email protected] % Date : Fri Feb 9 16:29:51 EST 2007 % SSCC/NIMH/ National Institutes of Health, Bethesda Maryland %Define the function name for easy referencing FuncName = 'New_HEAD'; %Debug Flag DBG = 1; %initailize return variables err = 1; Info = []; %check on return parameters if (nargout == 2), fprintf(1, 'Notice %s:\nYou are not specifying a return argument for Opt.\n', FuncName); fprintf(1, ' Be aware that some fields in Opt might have been modified inside\n'); fprintf(1, ' %s but these changes are not reflected in the Opt structure you\n', FuncName); fprintf(1, ' will be passing to WriteBrik.\n'); fprintf(1, ' If this makes no sense to you, just use:\n'); fprintf(1, ' [err, Info, Opt] = New_HEAD(Opt);\n'); end %work options if (ischar(opt)), %perhaps test mode Test_New_HEAD; return; end %standardize input if (isfield(opt,'dimen')), if (ischar(opt.dimen)), v = str2num(opt.dimen); rmfield(opt, 'dimen'); opt.dimen = v; end end %create command for -master option or non-tlrc views if (~isfield(opt,'view') | ~strcmp(opt.view,'+tlrc') | isfield(opt,'master')), tmp_suf = '___NeW_hEaD_'; sopt = '3dUndump -head_only'; if (isfield(opt,'dimen')), sopt = sprintf('%s -dimen %s', sopt, num2str(opt.dimen(1:3))); end if (isfield(opt,'orient')), sopt = sprintf('%s -orient %s', sopt, opt.orient); end if (isfield(opt,'master')), [Status, mPrefix, mView] = PrefixStatus (opt.master); sopt = sprintf('%s -master %s', sopt, opt.master); else mView = '+orig'; end if (~isfield(opt,'datum')), opt.datum = 'short'; end if (isfield(opt,'datum')), if (~strcmp(opt.datum,'short') & ~strcmp(opt.datum, 'byte') & ~strcmp(opt.datum,'float')), fprintf(1,'Error %s:\ndatum option must be one of ''byte'', ''short'', ''float''\nI have %s\n', FuncName, opt.datum); return; end sopt = sprintf('%s -datum %s', sopt, opt.datum); end if (~isfield(opt,'view')), opt.view = '+orig'; end if (isfield(opt,'prefix')), [Status, Prefix, View] = PrefixStatus (opt.prefix); if (Status < 1 & strcmp(View,opt.view)), if (isfield(opt,'overwrite') & ~strcmp(opt.overwrite,'y')), fprintf(1,'Error %s:\nLooks like %s exists already.\n',... FuncName, opt.prefix); return; end end opt.prefix = Prefix; ohead = sprintf('%s%s', tmp_suf, opt.prefix); sopt = sprintf('%s -prefix %s%s', sopt, ohead); else fprintf(1,'Error %s:\nNeed a .prefix option.\n', FuncName); return; end [e,w] = unix(sopt); if (e), fprintf(1,'Error %s:\nHeader creating command %s failed.\nSee this function''s help and 3dUndump -help\n3dUndump''s output was:\n%s\n', ... FuncName, sopt, w); New_HEAD_CLEAN(tmp_suf); return; end [err,Info] = BrikInfo(sprintf('%s%s', ohead,mView)); New_HEAD_CLEAN(tmp_suf); else %have +tlrc and no master mView = '+tlrc'; [e,d] = unix('which afni'); if (e), fprintf(1,'Error %s:\nFailed to find afni!\n', FuncName); return; end [e,pt] = GetPath(d); templ = sprintf('%s/TT_N27+tlrc.HEAD', pt); [e,Info] = BrikInfo(templ); if (e), fprintf(1,'Error %s:\nFailed to get header of %s!\n', FuncName, templ); return; end %recalculate the origin (res. of template is 1x1x1mm) oOrig = Info.ORIGIN; oDelta = Info.DELTA; oDimen = Info.DATASET_DIMENSIONS; %Calculate dimension ratio and adjust so that volume fits in box. rat = oDimen(1:3)./opt.dimen(1:3); Info.DELTA = Info.DELTA .* rat; Info.DATASET_DIMENSIONS(1:3) = opt.dimen(1:3); %Now shift the origin so that the final volume still fits in the same box (edge to edge) of TLRC box dOrig = 1./2*(Info.DELTA-oDelta); Info.ORIGIN = Info.ORIGIN+dOrig; %Have to deal with datum if (isfield(opt,'datum')), if (strcmp(opt.datum,'byte')), Info.BRICK_TYPES(1) = 0; elseif (strcmp(opt.datum,'short')), Info.BRICK_TYPES(1) = 1; elseif (strcmp(opt.datum,'float')), Info.BRICK_TYPES(1) = 3; else fprintf(1,'Error %s: Bad data type %s\n', FuncName, opt.datum); return; end else opt.datum = 'short' Info.BRICK_TYPES(1) = 1; end end %the scaling option if (isfield(opt,'scale')), if (opt.scale & ~strcmp(opt.datum,'short')), fprintf(1,'Warning %s:\n .scale option is only for ''short'' type data.\n Resetting it to 0.\n', FuncName); opt.scale = 0; end else if (strcmp(opt.datum,'short')), opt.scale = 1; else opt.scale = 0; end end %take care of prefix business Info.RootName = sprintf('%s%s', opt.prefix, opt.view); %take care of view if (strcmp(mView, opt.view) == 0), %different if (strcmp(opt.view,'+orig')) Info.SCENE_DATA(1) = 0; elseif (strcmp(opt.view,'+acpc')) Info.SCENE_DATA(1) = 1; elseif (strcmp(opt.view,'+tlrc')) Info.SCENE_DATA(1) = 2; else fprintf(1,'Error %s:\nBad view %s\n', FuncName, opt.view); return; end end %take care of 4th dimen if (isfield(opt,'dimen')), if (length(opt.dimen) > 3), Info.DATASET_RANK(2) = opt.dimen(4); Info.BRICK_TYPES = Info.BRICK_TYPES(1).*ones(1,opt.dimen(4)); Info.BRICK_FLOAT_FACS = Info.BRICK_FLOAT_FACS(1) .*ones(1, opt.dimen(4)); end end %take care of TR if (isfield(opt,'tr')), Info.TAXIS_NUMS(1) = Info.DATASET_RANK(2); Info.TAXIS_NUMS(2) = 0; %no time offset for slices at the moment Info.TAXIS_NUMS(3) = 77002; %units in seconds for tr (below) Info.TAXIS_FLOATS(1) = 0; %time origin 0 Info.TAXIS_FLOATS(2) = opt.tr; %TR in units of Info.TAXIS_NUMS(3) Info.TAXIS_FLOATS(3) = 0; %duration of acquisition Info.TAXIS_FLOATS(4) = 0; %no time offset please Info.TAXIS_FLOATS(5) = 0; %no time offset please Info.TAXIS_OFFSETS = zeros(1,Info.TAXIS_NUMS(1)); %no bloody time offset end err = 0; return; function New_HEAD_CLEAN(sss) unix(sprintf('rm -f %s*.HEAD >& /dev/null', sss)); return;
github
lcnbeapp/beapp-master
PeakFinder.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/PeakFinder.m
13,081
utf_8
2f79a40d4194ae7e9ad3a34c87589a80
function [R, e] = PeakFinder(vvec, Opt) %Example: PeakFinder('Resp*.1D'); % or PeakFinder(v) where v is a column vector % if v is a matrix, each column is processed separately. % %clear all but vvec (useful if I run this function as as script) keep('vvec', 'Opt'); e = 0; R = struct([]); if (nargin < 2) Opt = struct(); end if (~isfield(Opt,'PhysFS') | isempty(Opt.PhysFS)), Opt.PhysFS= 1/0.025; %sampling frequency end if (~isfield(Opt,'zerophaseoffset') | isempty(Opt.zerophaseoffset) ), Opt.zerophaseoffset = 0.5; %Fraction of the period that corresponds %to a phase of 0 %0.5 means the middle of the period, 0 means the 1st peak end if (~isfield(Opt,'Quiet') | isempty(Opt.Quiet)), Opt.Quiet = 0; end if (~isfield(Opt,'ResampFS') | isempty(Opt.ResampFS)), Opt.ResampFS = Opt.PhysFS; end if (~isfield(Opt,'fcutoff') | isempty(Opt.fcutoff)), Opt.fcutoff = 10; end if (~isfield(Opt,'FIROrder') | isempty(Opt.FIROrder)), Opt.FIROrder = 80; end if (~isfield(Opt,'ResamKernel') | isempty(Opt.ResamKernel)), Opt.ResamKernel = 'linear'; end if (~isfield(Opt,'Demo') | isempty(Opt.Demo)), Opt.Demo = 0; end if (~isfield(Opt,'as_windwidth') | isempty(Opt.as_windwidth)), Opt.as_windwidth = 0; end if (~isfield(Opt,'as_percover') | isempty(Opt.as_percover)), Opt.as_percover = 0; end if (~isfield(Opt,'as_fftwin') | isempty(Opt.as_fftwin)), Opt.as_fftwin = 0; end if (Opt.Demo), Opt.Quiet = 0; else pause off end %some filtering fnyq = Opt.PhysFS./2; %w(1) = 0.1/fnyq; %cut frequencies below 0.1Hz %w(2) = Opt.fcutoff/fnyq; % upper cut off frequency normalized %b = fir1(Opt.FIROrder, w, 'bandpass'); %FIR filter of order 40 w = Opt.fcutoff/fnyq; % upper cut off frequency normalized b = fir1(Opt.FIROrder, w, 'low'); %FIR filter of order 40 NoDups = 1; % remove duplicates that might come up when improving peak location if (ischar(vvec)), l = zglobb(vvec); nl = length(l); if (isnumeric(l)), fprintf(2,'File (%s) not found\n', vvec); e = 1; return; end else l = []; nl = size(vvec,2); if (nl < 1), fprintf(2,'No vectors\n', nl); e = 1; return; end end clear R; %must clear it. Or next line fails R(nl) = struct( 'vname', '',... 't', [], ... 'X', [],... 'iz', [],... %zero crossing (peak) locations 'ptrace', [], 'tptrace', [],... 'ntrace', [], 'tntrace', [],... 'prd', [], 'tmidprd', [], 'ptracemidprd', [],... 'phz', [],... 'RV', [], 'RVT', [] ... ); for (icol = 1:1:nl), if (~isempty(l) && ~l(icol).isdir), R(icol).vname = sprintf('%s%s', l(icol).path, l(icol).name); v = Read_1D(R(icol).vname); else, R(icol).vname = sprintf('vector input col %d', icol); v = vvec(:,icol); end windwidth = 0.2; %window for adjusting peak location in seconds %remove the mean v = (v - mean(v)); R(icol).v = v; %store it for debugging %filter both ways to cancel phase shift v = filter(b,1,v); v = flipud(v); v = filter(b,1,v); v = flipud(v); %get the analytic signal R(icol).X = analytic_signal(v, Opt.as_windwidth.*Opt.PhysFS,... Opt.as_percover, Opt.as_fftwin); %using local version to illustrate, can use hilbert %Doing ffts over smaller windows can improve peak detection %in the few instances that go undetected but what value to use %is not clear and there seems to be at times more errors introduced %in the lower envelope . nt = length(R(icol).X); R(icol).t = [0:1/Opt.PhysFS:(nt-1)/Opt.PhysFS]; % FIX FIX FIX iz = find( imag(R(icol).X(1:nt-1)).*imag(R(icol).X(2:nt)) <= 0); polall = -sign(imag(R(icol).X(1:nt-1)) - imag(R(icol).X(2:nt))); pk = real(R(icol).X(iz)); pol = polall(iz); tiz = R(icol).t(iz); ppp = find(pol>0); ptrace = pk(ppp); tptrace = tiz(ppp); ppp = find(pol<0); ntrace = pk(ppp); tntrace = tiz(ppp); if (~Opt.Quiet), fprintf(2,[ '--> Load signal\n',... '--> Smooth signal\n',... '--> Calculate analytic signal Z\n',... '--> Find zero crossing of imag(Z)\n',... '\n']); figure(1); clf subplot(211); plot (R(icol).t, real(R(icol).X),'g'); hold on %plot (R(icol).t, imag(R(icol).X),'g'); plot (tptrace, ptrace, 'ro'); plot (tntrace, ntrace, 'bo'); %plot (R(icol).t, abs(R(icol).X),'k'); subplot (413); vn = real(R(icol).X)./(abs(R(icol).X)+eps); plot (R(icol).t, vn, 'g'); hold on ppp = find(pol>0); plot (tiz(ppp), vn(iz(ppp)), 'ro'); ppp = find(pol<0); plot (tiz(ppp), vn(iz(ppp)), 'bo'); drawnow ; if (Opt.Demo), uiwait(msgbox('Press button to resume', 'Pausing', 'modal')); end end %Some polishing if (1), nww = ceil(windwidth/2 * Opt.PhysFS); pkp = pk; R(icol).iz = iz; for (i=1:1:length(iz)), n0 = max(2,iz(i)-nww); n1 = min(nt,iz(i)+nww); if (pol(i) > 0), [xx, ixx] = max((real(R(icol).X(n0:n1)))); else, [xx, ixx] = min((real(R(icol).X(n0:n1)))); end R(icol).iz(i) = n0+ixx-2; pkp(i) = xx; end tizp = R(icol).t(R(icol).iz); ppp = find(pol>0); R(icol).ptrace = pkp(ppp); R(icol).tptrace = tizp(ppp); ppp = find(pol<0); R(icol).ntrace = pkp(ppp); R(icol).tntrace = tizp(ppp); if (NoDups), %remove duplicates if (Opt.SepDups), fprintf(2,'YOU SHOULD NOT BE USING THIS.\n'); fprintf(2,' left here for the record\n'); [R(icol).tptrace, R(icol).ptrace] = ... remove_duplicates(R(icol).tptrace, R(icol).ptrace, Opt); [R(icol).tntrace, R(icol).ntrace] = ... remove_duplicates(R(icol).tntrace, R(icol).ntrace, Opt); else, [R(icol).tptrace, R(icol).ptrace,... R(icol).tntrace, R(icol).ntrace] = ... remove_PNduplicates(R(icol).tptrace, R(icol).ptrace,... R(icol).tntrace, R(icol).ntrace, Opt); end if (length(R(icol).ptrace) ~= length(R(icol).ntrace)), fprintf(1,'Bad news in tennis shoes. I''m outa here.\n'); e = 1; return; end end if (~Opt.Quiet), fprintf(2,[ '--> Improved peak location\n',... '--> Removed duplicates \n',... '\n']); subplot(211); plot( R(icol).tptrace, R(icol).ptrace,'r+',... R(icol).tptrace, R(icol).ptrace,'r'); plot( R(icol).tntrace, R(icol).ntrace,'b+',... R(icol).tntrace, R(icol).ntrace,'b'); drawnow ; if (Opt.Demo), uiwait(msgbox('Press button to resume', 'Pausing', 'modal')); end end else tizp = tiz; R(icol).iz = iz; pkp = pk; R(icol).ptrace = ptrace; nR(icol).ptrace = nptrace; end %Calculate the period nptrc = length(R(icol).tptrace); R(icol).prd = (R(icol).tptrace(2:nptrc) - R(icol).tptrace(1:nptrc-1) ); R(icol).ptracemidprd = ( R(icol).ptrace(2:nptrc) ... + R(icol).ptrace(1:nptrc-1) ) ./2.0; R(icol).tmidprd = ( R(icol).tptrace(2:nptrc) ... + R(icol).tptrace(1:nptrc-1)) ./2.0; if (~Opt.Quiet), fprintf(2,[ '--> Calculated the period (from beat to beat)\n',... '\n']); plot (R(icol).tmidprd, R(icol).ptracemidprd,'kx'); for (i=1:1:length(R(icol).prd)), text( R(icol).tmidprd(i), R(icol).ptracemidprd(i),... sprintf('%.2f', R(icol).prd(i))); end drawnow ; if (Opt.Demo), uiwait(msgbox('Press button to resume', 'Pausing', 'modal')); end end if (~isempty(Opt.ResamKernel)), %interpolate to slice sampling time grid: R(icol).tR = [0:1./Opt.ResampFS:max(R(icol).t)]; R(icol).ptraceR = interp1( R(icol).tptrace', R(icol).ptrace, ... R(icol).tR,Opt.ResamKernel); R(icol).ntraceR = interp1( R(icol).tntrace', R(icol).ntrace, ... R(icol).tR,Opt.ResamKernel); R(icol).prdR = interp1(R(icol).tmidprd, R(icol).prd, ... R(icol).tR,Opt.ResamKernel); %you get NaN when tR exceeds original signal time, so set those %to the last interpolated value R(icol).ptraceR = clean_resamp(R(icol).ptraceR); R(icol).ntraceR = clean_resamp(R(icol).ntraceR); R(icol).prdR = clean_resamp(R(icol).prdR); end if (icol ~= nl), input ('Hit enter to proceed...','s'); end end if (~Opt.Quiet), plotsign2(1); end return; function v = clean_resamp(v) inan = find(isnan(v)); %the bad igood = find(isfinite(v)); %the good for(i=1:1:length(inan)), if (inan(i) < igood(1)), v(inan(i))= v(igood(1)); elseif (inan(i) > igood(length(igood))), v(inan(i))= v(igood(length(igood))); else fprintf(2,'Error: Unexpected NaN case\n'); v(inan(i))= 0; end end return; function [t,v] = remove_duplicates(t,v, Opt) j = 1; for (i=2:1:length(t)), if ( t(i) ~= t(i-1) & ... t(i) - t(i-1) > 0.3), %minimum time %before next beat j = j + 1; t(j) = t(i); v(j) = v(i); else, if (~Opt.Quiet), fprintf(2,'Dropped peak at %g sec\n', t(i)); end end end t = t(1:j); v = v(1:j); return; function [tp,vp, tn, vn] = remove_PNduplicates(tp,vp, tn,vn, Opt) ok=zeros(1,length(tp)); ok(1) = 1; j = 1; for (i=2:1:min(length(tp), length(tn))), if ( tp(i) ~= tp(i-1) & ... tp(i) - tp(i-1) > 0.3), %minimum time %before next beat j = j + 1; ok(j) = i; else, if (~Opt.Quiet), fprintf(2,'Dropped peak at %g sec\n', tp(i)); end end end ok = ok(1:j); tp = tp(ok); vp = vp(ok); tn = tn(ok); vn = vn(ok); return; function h = analytic_signal(vi, windwidth, percover, win), nvi = length(vi); h = zeros(size(vi)); [bli, ble, num] = fftsegs (windwidth, percover, nvi); for (ii=1:1:length(bli)), v = vi(bli(ii):ble(ii)); nv = length(v); if (win == 1), fv = fft(v.*hamming(nv)); else, fv = fft(v); end wind = zeros(size(v)); %zero negative frequencies, double positive frequencies if (iseven(nv)), wind([1 nv/2+1]) = 1; %keep DC wind([2:nv/2]) = 2; %double pos. freq else wind([1]) = 1; wind([2:(nv+1)/2]) = 2; end h(bli(ii):ble(ii)) = h(bli(ii):ble(ii)) + ifft(fv.*wind); end h = h./num; return function [bli, ble, num] = fftsegs (ww, po, nv) % Returns the segements that are to be used for fft % calculations. % ww: Segment width (in number of samples) % po: Percent segment overlap % nv: Total number of samples in original symbol % Returns: % bli, ble: Two Nblck x 1 vectors defining the segments' % starting and ending indices % num: An nv x 1 vector containing the number of segments % each sample belongs to %example % [bli, ble, num] = fftsegs (100, 70, 1000); if (ww==0), po = 0; ww = nv; elseif (ww < 32 | ww > nv), fprintf(2,'Error fftsegs: Bad value for window width of %d\n', ww); return; end out = 0; while (out == 0), clear bli ble %How many blocks? jmp = floor((100-po)*ww/100); %jump from block to block nblck = nv./jmp; %number of jumps ib = 1; cnt = 0; while (cnt < 1 | ble(cnt)< nv), cnt = cnt + 1; bli(cnt) = ib; ble(cnt) = min(ib+ww-1, nv); ib = ib + jmp; end %if the last block is too small, spread the love if (ble(cnt) - bli(cnt) < 0.1.*ww), % too small a last block, merge ble(cnt-1) = ble(cnt); % into previous cnt = cnt -1; ble = ble(1:cnt); bli = bli(1:cnt); out = 1; elseif (ble(cnt) - bli(cnt) < 0.75.*ww), % too large to merge, spread it ww = ww+floor((ble(cnt)-bli(cnt))./nblck); out = 0; else %last block big enough, proceed out = 1; end %ble - bli + 1 %out end %bli %ble %ble - bli + 1 %now figure out the number of estimates each point of the time series gets num = zeros(nv,1); cnt = 1; while (cnt <= length(ble)), num(bli(cnt):ble(cnt)) = num(bli(cnt):ble(cnt))+ ones(ble(cnt)-bli(cnt)+1,1); cnt = cnt + 1; end
github
lcnbeapp/beapp-master
rgbdectohex.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/rgbdectohex.m
6,032
utf_8
fca22486bef72eb78e71977479b7940b
function [Cs] = rgbdectohex (Mrgb,strg) % % Mode 1: % [Cs] = rgbdectohex (Mrgb,[string]) % Mode 2: % rgbdectohex % % Mode 1: %This function takes as an input the rgb matrix Mrgb (size is Nx3) % where each row represents the rgb gun values of a color. % gun values should be integers between 0 and 255 % %the optional 'string' is placed before the #hex representation %in a way VERY suitable for afni's .Xdefaults file stuff ... % % remember the magic command : xrdb -merge <colors filename> % % the function cyclmat helps you fix your color maps, check it out... % %The hex values are all padded to two characters, looks nice. % % The function first displays the map, then gives you the option of % writing out the results: % to an ascii file that can be (if you specified the right strg parameter) used % directly in .Xdefaults % to an ascii file that contains RGB values % to an ascii file containing the definition of the colormap in a C- % syntax that can be added to pbar.c and added with PBAR_define_bigmap( char *mapcmd ); % %the result is written to stdout in a format used %by .Xdefault files, to make importing them to %.Xdefaults easy, just cut and paste. % %example: >> load hues_rygbr20 (this file is an ascii list of 3 integers per line specifying rgb colours) % >> Mcyc = cyclmat (hues_rygbr20,-1,13); (changes the order of the loaded color file..) % >> rgbdectohex (Mcyc,'AFNI*ovdef'); this displays the colour map, and asks if you want the results written out to a file % % If you sqaved the results to a file called junkmap % from command line do : xrdb -merge junkmap and the colormap is set for afni to read. % % If you use the return parameters [Cs, sall] then you'll get a command structure vector % that tells AFNI (TellAfni(Cs)) to load the newly created colorscale and switch to it. % The colorscale is named string if one is supplied. % % Mode 2: % Interactive mode for showing RGB colors. Enter RGB values to see color. % % see also MakeColorMap, TellAfni, ROIcmap % % Ziad Saad Nov 26 97/ Dec 4 97/ Jan 06 if (nargout), Cs = []; sall = ''; end if (nargin == 2), son = 1; else son = 0; strg = ''; end if (nargin == 0), while (1), strgb = input ('Enter rgb values (nothing to exit):','s'); if (isempty(strgb)) return; end Mrgb = str2num(strgb); ShowRGBcol(Mrgb); fprintf(1,' Color: %s\n', RGBtoXhex(Mrgb, 0, '')); end end if (size (Mrgb,2) ~= 3) fprintf(2,'rgbdectohex : Wrong Mrgb matrix size') Mhex = -1; return; end if (max(abs(round(Mrgb(:))-Mrgb(:))) > 0.0001), fprintf(2,'rgbdectohex : RGB values are not integers.\n'); Mhex = -1; return; end if (max(Mrgb(:)) < 1.1), fprintf(2,'rgbdectohex : Maximum RGB value < 1.1. Suspecting RGB to be between 0 and 1\nBe sure that color values are integers that can range between 0 and 255.') input ('Hit enter to continue','s'); end if (min(Mrgb(:)) < 0 | max(Mrgb(:)) > 255), fprintf(2,'rgbdectohex : RGB value must range between 0 and 255.'); return; end ShowRGBcol(Mrgb); for (i=1:1:size(Mrgb,1)), fprintf(1,'%s\n',RGBtoXhex(Mrgb(i,:), son, strg)); end %i chc = input ('Wanna write this to disk ? (y/n)','s'); if (chc == 'y'), chc2 = input ('Write rgb version of map too ? (y/n)','s'); chc3 = input ('Write C-friendly version of map to include in AFNI''c code ? (y/n)','s'); rep = 1; strout = strg; while (rep == 1), %strout = input ('Enter filename :','s'); rep = filexist (strout); if (rep == 1), fprintf (2,'rgdtodec : file %s exists, enter another name\n\a', strout); end end strout2 = sprintf ('%s.rgb',strout); strout3 = sprintf ('%s.love.c',strout); fid = fopen (strout,'wt'); if (chc2 == 'y'), fid2 = fopen (strout2,'wt'); end if (chc3 == 'y'), fid3 = fopen (strout3,'wt'); end if (fid == -1 | (chc2 == 'y' & fid2 == -1) | (chc3 == 'y' & fid3 == -1)), fprintf (2,'rgdtodec : Could not open %s or %s %s file for write operation\n',strout,strout2, strout3); end if (chc3 == 'y'), fprintf (fid3,'static char %s_CMD[] = { \n "%s "\n "', upper(strg), strg); end for (i=1:1:size(Mrgb,1)), s1 = pad_strn (lower(dec2hex(Mrgb(i,1))),'0',2,1); s2 = pad_strn (lower(dec2hex(Mrgb(i,2))),'0',2,1); s3 = pad_strn (lower(dec2hex(Mrgb(i,3))),'0',2,1); if (son == 1), cst = sprintf ('%g',i); cpd = pad_strn (cst,'0',2,1); fprintf (fid,'%s%s:\t#%s%s%s\n',strg,cpd,s1,s2,s3); else fprintf (fid,'#%s%s%s\n',s1,s2,s3); end if (chc2 == 'y'), fprintf (fid2,'%g %g %g\n',Mrgb(i,1),Mrgb(i,2),Mrgb(i,3)); end if (chc3 == 'y'), if (rem(i, 5)==1 & i > 1), fprintf (fid3,'"\n "'); end fprintf (fid3,'#%s%s%s ',s1,s2,s3); end end %i fclose (fid); if (chc2 == 'y'), fclose (fid2); end if (chc3 == 'y'), fprintf (fid3,'"\n};'); fclose (fid3); end end if (nargout), sall = ''; for (i=1:1:size(Mrgb,1)), s1 = pad_strn (lower(dec2hex(Mrgb(i,1))),'0',2,1); s2 = pad_strn (lower(dec2hex(Mrgb(i,2))),'0',2,1); s3 = pad_strn (lower(dec2hex(Mrgb(i,3))),'0',2,1); sall = sprintf('%s#%s%s%s ',sall, s1,s2,s3); end if (son == 0), strg = 'rgbdectohex'; end Cs = NewCs('DEFINE_COLORSCALE', '', strg, sall); Cs(2) = NewCs('SET_PBAR_ALL', '' , '+99', sprintf('1.0 %s', strg)); end return; function ShowRGBcol(Mrgb) figure (1); colormap (Mrgb./255); subplot 211; image ([1:1:length(Mrgb(:,1))]); title(sprintf('X11 Color in Hex: %s', RGBtoXhex(Mrgb, 0, ''))); %subplot 212; %pie (ones(1,length(Mrgb(:,1)))); return; function sret = RGBtoXhex(rgb, son, strg), s1 = pad_strn (lower(dec2hex(rgb(1))),'0',2,1); s2 = pad_strn (lower(dec2hex(rgb(2))),'0',2,1); s3 = pad_strn (lower(dec2hex(rgb(3))),'0',2,1); if (son == 1), cst = sprintf ('%g',i); cpd = pad_strn (cst,'0',2,1); sret = sprintf ('%s%s:\t#%s%s%s',strg,cpd,s1,s2,s3); else sret = sprintf ('#%s%s%s',s1,s2,s3); end return;
github
lcnbeapp/beapp-master
afni_niml_writesimple.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/afni_niml_writesimple.m
4,503
utf_8
231807f9346f2bfcc56fa5f3eda8ff00
function D=afni_niml_writesimple(S,fn) % writes surface data in a 'simple' struct in NIML format to a file. % % D=AFNI_NIML_WRITESIMPLE(fn,S) writes surface data S to the file FN. % S should be a struct with a field S.data, and optionally S.stats, % S.labels, S.history, S.types, and S.node_indices. % This function returns the more complicated NIML-struct D that is % written by afni_niml_write % % S.data a PxN struct for P nodes and N datapoints per node. % S.node_indices (optional) a Nx1 vector with indices in base 0. If % omitted, then it is assumed that all nodes have data. % S.stats } Either a string (with ';'-separated elements for % S.labels } S.stats and .labels: , or a cell with strings. % S.history } In the latter case, if the number of elements in the % cell is less than P, then elements are taken in cycles. % % Example: % S=struct() % S.data=randn(100002,4); % S.labels={'A-mean','A-Tscore','B-mean','B-Tscore'}; % S.stats={'none','Ttest(15)'}; % each stat descriptor will be used twice % afni_niml_writesimple('test.niml.dset',S) % % NNO Feb 2010 <[email protected]> if isnumeric(S) T=struct(); T.data=S; S=T; clear T; end if ischar(S) && isstruct(fn) % swap struct and filename T=fn; fn=S; S=T; clear T; end if ~(isstruct(S) && isfield(S,'data')) error('Illegal input: expected struct S with field S.data\n'); end % main header D=struct(); if isfield(S,'dset_type') D.dset_type=S.dset_type; else D.dset_type='Node_Bucket'; % this is the default end % make new self_idcode, to keep SUMA happy rand('twister',sum(100*clock)); D.self_idcode=['XYZ_' char(rand(1,24)*26+65)]; [path,f,ext]=fileparts(fn); D.filename=[f ext]; D.label=D.filename; D.name='AFNI_dataset'; D.ni_form='ni_group'; nodes=cell(7,1); %data nd=struct(); nd.data_type='Node_Bucket_data'; nd.name='SPARSE_DATA'; nd.data=S.data; [nverts,ncols]=size(S.data); nodes{1}=nd; % node indices nd=struct(); nd.data_type='Node_Bucket_node_indices'; if isfield(S,'node_indices') idxs=S.node_indices; else idxs=0:(nverts-1); end if issorted(idxs) nd.sorted_node_def='Yes'; else nd.sorted_node_def='No'; end if size(idxs,1)==1 idxs=idxs'; end if numel(idxs) ~= nverts error('The number of node indices (%d) does not match the number of rows (%d) in the data.',nverts,numel(idxs)); end nd.data=idxs; nd.COLMS_RANGE=data2range(idxs,0); nd.COLMS_LABS='Node Indices'; nd.COLMS_TYPE='Node_Index'; nd.name='INDEX_LIST'; nodes{2}=nd; % colum range nd=struct(); nd.atr_name='COLMS_RANGE'; nd.name='AFNI_atr'; nd.data=data2range(S.data); nodes{3}=nd; % default labels for columns defaultlabels=cell(1,ncols); for k=1:ncols defaultlabels{k}=sprintf('col_%d',k-1); end % default value for history; make call stack st=dbstack(); stc=cell(numel(st)); for j=1:numel(st) stc{j}=sprintf('%s (%d)',st(j).name,st(j).line); end defaulthistory=sprintf('Written %s using: %s',datestr(clock),unsplit_string(stc,' <- ')); if isfield(S,'history') S.history=[S.history ';' defaulthistory]; end nodes{4}=make_str_element('COLMS_LABS',S,'labels',defaultlabels,ncols); nodes{5}=make_str_element('COLMS_TYPE',S,'types',{'Generic_Float'},ncols); nodes{6}=make_str_element('COLMS_STATSYM',S,'stats',{'none'},ncols); nodes{7}=make_str_element('HISTORY_NOTE',S,'history',defaulthistory,ncols); D.nodes=nodes; afni_niml_write(D,fn); function elem=make_str_element(Nodefieldname,S,Sfieldname,default,ncols) elem=struct(); elem.atr_name=Nodefieldname; elem.name='AFNI_atr'; if isfield(S,Sfieldname) vals=S.(Sfieldname); else vals=default; end if iscell(vals); valcount=numel(vals); v=cell(1,ncols); for k=1:ncols v{k}=vals{mod(k-1,valcount)+1}; %cyclically take elements end vals=unsplit_string(v,';'); elseif ~ischar(vals) error('Unrecognized data type for field %s (%s)', Nodefieldname, Sfieldname); end elem.data=vals; function r=data2range(data,precision) % returns a string that defines the range of the data, and nodes where this % range is found. [rows,cols]=size(data); rs=cell(cols,1); for k=1:cols datak=data(:,k); [minv,mini]=min(datak); [maxv,maxi]=max(datak); if nargin<2 precision=get_required_precision(data(:,k)); end pat=sprintf('%%.%df %%.%df %%d %%d', precision, precision); rs{k}=sprintf(pat, minv, maxv, mini-1, maxi-1); end r=unsplit_string(rs,';');
github
lcnbeapp/beapp-master
zglobb.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/zglobb.m
3,946
utf_8
508195b45ee39c7296447826b75515f4
function [err,ErrMessage, NameList] = zglobb (Identifiers, Opt) % % [err, ErrMessage, List] = zglobb (Identifiers, [Opt]) %or % [List] = zglobb (Identifiers, [Opt]) %Purpose: % returns the list of files specified in Identifiers % % %Input Parameters: % Identifiers is a cellstr identifying which briks to use % Identifiers = {'ADzst2r*ir.alnd2AAzs+orig.HEAD' , 'AFzst2r*ir.alnd2AAzs+orig.HEAD'} % Opt is an optional Options structure % .LsType : type of output List % 'l' --> (default) Create a Nx1 structure vector with fields identical to those returned by dir % '|' --> Create a | delimited string with al the filenames in it % .NoExt : (default is '') a string containing a | delimited list of filename extensions to remove % example '.HEAD|.BRIK' % %Output Parameters: % err : 0 No Problem % : 1 Mucho Problems % ErrMessage : Any error or warning messages % List is the list of files with a format depending on Opt.LsType % %Key Terms: % %More Info : % ? as a wildcard now works on unix/OSX machines % % % % Author : Ziad Saad % Date : Fri Feb 09 09:55:01 EST 2001 % LBC/NIMH/ National Institutes of Health, Bethesda Maryland %Define the function name for easy referencing FuncName = 'zglobb'; %Debug Flag DBG = 1; %initailize return variables err = 1; ErrMessage = 'Undetermined'; NameList = []; if (nargin == 1), Opt.LsType = 'l'; Opt.NoExt = ''; else if (~isfield (Opt, 'LsType') | isempty(Opt.LsType)), Opt.LsType = 'l'; end if (~isfield (Opt, 'NoExt') | isempty(Opt.NoExt)), Opt.NoExt = ''; end end switch Opt.LsType, case 'l', NameList = []; case '|', NameList = ''; otherwise, ErrMessage = sprintf('%s is an unknown Opt.LsType value', Opt.LsType); err = 1; return; end if (ischar(Identifiers)), Identifiers = cellstr(Identifiers); end %get the names of the BRIKS identified in Identifiers N_ID = length(Identifiers); cnt = 0; i=1; while (i<=length(Identifiers)), % grab the path if it is there [eee, ppp] = GetPath(char(Identifiers(i))); if (ppp(length(ppp)) ~= filesep), ppp = [ppp filesep]; end if (~isempty (find(char(Identifiers(i)) == '?'))), %have to go via ls! com = sprintf('\\ls %s', char(Identifiers(i))); [ee,ll] = unix(com); if (ee), i = i + 1; continue; end cl = zstr2cell(ll); if (length(Identifiers)>=i+1), Identifiers = [ Identifiers(1:i-1) ... cl ... Identifiers(i+1:length(Identifiers))]; else Identifiers = [ Identifiers(1:i-1) ... cl ]; end end sd = dir (char(Identifiers(i))); ns = length(sd); for (j=1:1:ns) if (~strcmp(sd(j).name, '.') & ~strcmp(sd(j).name, '..')) cnt = cnt + 1; if (~isempty(Opt.NoExt)), sd(j).name = RemoveExtension (sd(j).name, Opt.NoExt); end switch Opt.LsType, case 'l', NameList(cnt).name = sd(j).name; NameList(cnt).date = sd(j).date; NameList(cnt).bytes = sd(j).bytes; NameList(cnt).isdir = sd(j).isdir; NameList(cnt).path = ppp; case '|' if (strcmp(ppp,'.') || strcmp(ppp,'./')), NameList = sprintf('%s|%s',NameList,sd(j).name); else NameList = sprintf('%s|%s%s', ... NameList,ppp,sd(j).name); end end end end i = i + 1; end if (Opt.LsType == '|'), NameList = NameList(2:length(NameList)); %get rid of first | end if (cnt == 0), ErrMessage = 'No match'; return; end if (nargout <= 1), err = NameList; else, err = 0; ErrMessage = ''; end return; function cl = zstr2cell(ll) sp = find(isspace(ll)); strt = 1; cl = cellstr(''); for(i=1:1:length(sp)), cl(i) = cellstr(ll(strt:sp(i)-1)); strt = sp(i)+1; end return;
github
lcnbeapp/beapp-master
afni_niml_parse.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/afni_niml_parse.m
4,013
utf_8
928c1d463779f609cd8549cfec5a0a37
function niml = afni_niml_parse(s) % Simple parsing routine for AFNI NIML datasets % % N=AFNI_NIML_PARSE(S) parses the niml string S and returns a parsed % structure P. % % P can either be an niml element, or a group of niml elements. In the % formder case, P contains a field .data; in the latter, a cell .nodes. % % If S contains multiple niml datasets that are not in a group, then N will % be a cell with the parsed datasets. % % This function is more or less the inverse of AFNI_NIML_PRINT. % % Many thanks to Ziad Saad, who wrote afni_niml_read and other routines % that formed the basis of this function. % % Please note that this function is *VERY EXPERIMENTAL* % % NNO Dec 2009 <[email protected]> % if the input is a string (i.e. not called recursively), parse header and % body and put them in a struct s. if ischar(s) s=afni_nel_parseheaderbody(s); end % make sure we only have the fieldnames we expect if ~isempty(setxor(fieldnames(s),{'headername','headertext','body'})) error('Illegal struct s, expected s.headername, s.headertext, s.body'); end % if more than 1 element, parse each of them seperately and put them in a % cell. scount=numel(s); if scount>1 niml=cell(scount,1); for k=1:scount niml{k}=afni_niml_parse(s(k)); end return end % parse the header part niml=afni_nel_parsekeyvalue(s.headertext); niml.name=s.headername; if isfield(niml,'ni_form') && strcmp(niml.ni_form,'ni_group') % this is a group of elements. parse each of the elements in the group % and put the results in a field .nodes nds=afni_niml_parse(s.body); % for consistency, ensure that .nodes is always a cell if iscell(nds) niml.nodes=nds; else niml.nodes{1}=nds; end else % this is a single element % set a few fields niml.vec_typ = afni_nel_getvectype(niml.ni_type); niml.vec_len = str2num(niml.ni_dimen); niml.vec_num = length(niml.vec_typ); % parse only if (~afni_ni_is_numeric_type(niml.vec_typ)), %fprintf(2,'Data not all numeric, will not parse it'); niml.data = afni_nel_parse_nonnumeric(niml, s.body); else niml.data = afni_nel_parse_data(niml, s.body); end end function p=afni_nel_parsekeyvalue(s) % parses a string of the form "K1=V1 K2=V2 ... expr='\s*(?<lhs>\w+)\s*=\s*"(?<rhs>[^"]+)"'; hh=regexp(s,expr,'names'); p = cell2struct({hh(:).rhs}, {hh(:).lhs},2); clear hh; function p=afni_nel_parseheaderbody(s) % parses a header and body % in the form <HEADERNAME HEADERTEXT>BODY</HEADERNAME> expr = '<(?<headername>\w+)(?<headertext>.*?)>(?<body>.*?)</\1>'; p = regexp(s, expr,'names'); function vec_typ=afni_nel_getvectype(tt) % gets the vector type for a data element vec_typ=zeros(1,1000); nn=0; while (~isempty(tt)), [ttt,tt] = strtok(tt, ','); %look for the N*type syntax N = 1; [tttt,ttt] = strtok(ttt,'*'); Ntttt = str2double(tttt); if (~isnan(Ntttt)), %have a number, get the type N = Ntttt; tttt = strtok(ttt,'*'); end vec_typ(nn+1:1:nn+N) = afni_ni_rowtype_name_to_code(tttt); nn = nn + N; end vec_typ=vec_typ(1:nn)-1; % convert to base0, as in the niml.h. % % This is a point of concern as the % afni_ni_rowtype_name_to_code function % seems to prefer base1 % % (if only matlab used base0 indexing...) function p = afni_nel_parse_data(nel, data) d=sscanf(data,'%f'); p = reshape(d, nel.vec_num, nel.vec_len)'; function p =afni_nel_parse_nonnumeric(nel,data) if strcmp(nel.ni_type,'String') p=strtrim(data); if strcmp(p([1 end]),'""') p=p(2:(end-1)); % remove surrounding quotes end else p=data; %do nothing end
github
lcnbeapp/beapp-master
afni_fig_interface.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/afni_fig_interface.m
3,035
utf_8
a6e27aaa75a4fe2aebabe4db5d20acfb
function afni_fig_interface(src, evnt) cf = gcf; figure(src); % evnt ud = get(src,'UserData'); if (isempty(ud) | ~isfield(ud,'axes_lock')), ud = default_ud(); set(src,'UserData',ud); end if ( lower(evnt.Character) == 'l' ), ud.axes_lock = ~ud.axes_lock; set (src,'UserData',ud); if ud.axes_lock, set (src,'Name','L'); else set (src,'Name',''); end elseif ( lower(evnt.Character) == 'a' ), if (ud.axes_lock), reset_axis(evnt.Character, get_all_axes(src)); else reset_axis(evnt.Character,gca); %can send arrays for characters and axes end elseif ( lower(evnt.Character) == 'x' |... lower(evnt.Character) == 'y' |... lower(evnt.Character) == 'z' ), if (ud.axes_lock), zoom_axis(evnt.Character, get_all_axes(src)); else zoom_axis(evnt.Character,gca); %can send arrays for characters and axes end elseif ( strcmp(evnt.Key , 'leftarrow') |... strcmp(evnt.Key , 'rightarrow') |... strcmp(evnt.Key , 'uparrow') |... strcmp(evnt.Key , 'downarrow')), if (ud.axes_lock), shift_axis(evnt, get_all_axes(src)); else shift_axis(evnt, gca); end end figure(cf); return; function reset_axis(a,h) ca = gca; for (ih=1:1:length(h)), axes(h(ih)); axis auto; end axes(ca); return function zoom_axis(a,h) ca = gca; for (ia=1:1:length(a)), for (ih=1:1:length(h)), axes(h(ih)); dv = 4; if ( ~(a(ia) - lower(a(ia))) ), dv = 1; end if (~(lower(a(ia)) - 'x')), se = [1 2]; elseif (~(lower(a(ia)) - 'y')), se = [3 4]; elseif (~(lower(a(ia)) - 'z')), se = [5 6]; else return; end v = axis; if (length(v) < max(se)), return; end vc = (v(se(1))+v(se(2)))/2; vd = v(se(2))-v(se(1)); v(se(1)) = vc-vd/dv; v(se(2)) = vc+vd/dv; axis(v); end end axes(gca); return; function shift_axis(e,h) ca = gca; for (ie=1:1:length(e)), for (ih=1:1:length(h)), axes(h(ih)); if (strcmp(e(ie).Key , 'leftarrow')), se = [1 2]; dv = +0.1; elseif (strcmp(e(ie).Key , 'rightarrow')), se = [1 2]; dv = -0.1; elseif (strcmp(e(ie).Key , 'downarrow')), se = [3 4]; dv = -0.1; elseif (strcmp(e(ie).Key , 'uparrow')), se = [3 4]; dv = 0.1; else return; end v = axis vd = v(se(2))-v(se(1)); v(se(1)) = v(se(1))+vd*dv; v(se(2)) = v(se(2))+vd*dv; axis(v); end end axes(gca); return; function v = get_all_axes(f) l = get(f, 'Children'); v = []; for (i=1:1:length(l)), if (strcmp(get(l(i),'Type'),'axes')), v = [v l(i)]; end end return function ud = default_ud() ud = struct('axes_lock', 0); return
github
lcnbeapp/beapp-master
TellAfni.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/TellAfni.m
5,472
utf_8
77dce5f5339989af26f3e100da6bcfc3
function [err] = TellAfni (cs, opt) % % [err] = TellAfni (cs, opt) % %Purpose: % Drive AFNI % % %Input Parameters: % cs: An Nx1 vector of communication command structures % It is obtained using NewCs structure % opt: An optional options structure % .QuitOnErr (0/[1]): Return from function if any of cs(i) is malformed % .Verbose (0/[1]/2): 0 = mute, 1 = Yak, Yak (default), 2 = YAK YAK %Output Parameters: % err : 0 No Problem % : N N Problems % % %More Info : % % NewCs % TellAfni_Commands % Test_TellAfni % AFNI's README.driver file and the program plugout_drive % % Author : Ziad Saad % Date : Tue Dec 6 10:38:23 EST 2005 % SSCC/NIMH/ National Institutes of Health, Bethesda Maryland %Define the function name for easy referencing FuncName = 'TellAfni'; %Debug Flag DBG = 1; %initailize return variables err = 1; LogFile = '.TellAfni.log'; if (nargin == 1) opt.QuitOnErr = []; end if (~isfield(opt, 'QuitOnErr') | isempty(opt.QuitOnErr)) opt.QuitOnErr = 1; end if (~isfield(opt, 'Verbose') | isempty(opt.Verbose)) opt.Verbose = 1; end ncs = length(cs); if (ncs == 0) err = 0; return; end if (isempty(LogFile) | LogFile(1) ~= '.'), fprintf(2,'Bad LogFile, whas happening?'); return; end com = ''; ComLast = ''; ncom = 0; for (i=1:1:ncs), if (cs(i).err), fprintf(2,'Error in command structure %d (%s).\n', i,cs(i).c); if (opt.QuitOnErr), fprintf(2,'Quitting.\n'); return; else fprintf(2,'Ignoring command.\n'); cs(i).c = ''; end end if (cs(i).c), switch (cs(i).c), case 'START_AFNI', if (exist(LogFile) == 2), fprintf(2,'\nError: Log file %s found.\n', LogFile); fprintf(2,'Make sure no other AFNI is running AND listening for plugouts.\n'); fprintf(2,'rm the logfile with:\n!rm -f %s \n', LogFile); fprintf(2,'Then try your command again.\n\n'); return; end scom = sprintf('afni -yesplugouts %s |& tee %s &', cs(i).v, LogFile); [s,w] = unix(scom); if (opt.Verbose & ~isempty(w)), fprintf(1,'Command output:\n%s\n', w); end if (s), fprintf(2,'Error launching afni\n'); return; end %check on errors regarding connections iserr = 1; Tel = 0; while (Tel < 10 & iserr), if ( (rem(Tel,1) < 0.0001) ) fprintf(2,'Checking on communication (%.1f/10)\n', Tel); end iserr = TellAfni_CheckLog(LogFile, (rem(Tel,1)<0.0001)); pause (0.2); % wait to be sure AFNI launched Tel = Tel+0.2; end if (iserr), fprintf(2,'\nLaunched a new AFNI but failed to communicate.\n'); fprintf(2,'Close the failed AFNI and any other AFNI sessions\n'); fprintf(2,'that are listening to plugouts.\n\n'); scom = sprintf('rm -f %s >& /dev/null', LogFile); unix(scom); return; end case 'QUIT', if (~isempty(LogFile)), ComLast = sprintf('rm -f %s >& /dev/null', LogFile); end com = sprintf('%s -com ''%s %s''', com, cs(i).c, cs(i).v); ncom = ncom+1; otherwise, com = sprintf('%s -com ''%s %s''', com, cs(i).c, cs(i).v); ncom = ncom+1; end end end b = 0; if (~isempty(com)), scom = sprintf('plugout_drive -v %s -quit', com); if (opt.Verbose > 1), fprintf(1, 'making call:\n%s\n', scom); end [s,w] = unix(scom); if (isempty(strfind(scom,'QUIT'))), %Do not check in cases of QUIT [err, g, b] = TellAfniCheck(w); if (ncom ~= err + g + b ), fprintf(2,'Warning: Unexpected parsing trouble (ncom=%d, err+g+b=%d).\n', ncom, err+g+b); end if (err), fprintf(2,'Warning: Failed in parsing plugout_drive output.\nCannot confirm how %d out of %d commands executed\n', err, ncom); end if (g & opt.Verbose), fprintf(1,'%d out of %d commands OK\n', g, ncom); end if (b), fprintf(2,'Warning: %d out of %d commands failed in AFNI.\n', b, ncom); end end if (opt.Verbose > 1), fprintf(1,'Command output:\n%s\n', w); end if (s), fprintf(2,'Error telling afni\n'); return; end end if (~isempty(ComLast)), [s,w] = unix(ComLast); end err = b; return; function err = TellAfni_CheckLog(LogFile, verb) err = 1; if (exist(LogFile) ~= 2), %no log file! return; end fid = fopen(LogFile,'r'); if (fid < 0) return, end c = fscanf(fid, '%c'); l = strfind(c,'Can''t bind? tcp_listen[bind]: Address already in use'); fclose(fid); if (~isempty(l)), if (verb) fprintf(2,'Warning: Can''t listen. You probably have another AFNI listening.\nCommunication might fail.\nOnly one AFNI can communicate via plugouts\n'); end return; end l = strfind(c,'Plugouts'); if (~isempty(l)), l = strfind(c,'= listening for connections'); if (isempty(l)), if (verb) fprintf(2,'Warning: pugouts not enabled. Communication might fail.\n'); end return; end else %not there yet return; end err = 0; return;
github
lcnbeapp/beapp-master
zinputdlg.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/zinputdlg.m
16,591
utf_8
63dc0806876466dc33fef8fbdfeb45c5
function Answer=zinputdlg(Prompt, Title, NumLines, DefAns, Resize) % A copy of inputdlg.m , modified to have better looking font settings %ZINPUTDLG Input dialog box. % ANSWER = ZINPUTDLG(PROMPT) creates a modal dialog box that returns user % input for multiple prompts in the cell array ANSWER. PROMPT is a cell % array containing the PROMPT strings. % % ZINPUTDLG uses UIWAIT to suspend execution until the user responds. % % ANSWER = ZINPUTDLG(PROMPT,NAME) specifies the title for the dialog. % % ANSWER = ZINPUTDLG(PROMPT,NAME,NUMLINES) specifies the number of lines for % each answer in NUMLINES. NUMLINES may be a constant value or a column % vector having one element per PROMPT that specifies how many lines per % input field. NUMLINES may also be a matrix where the first column % specifies how many rows for the input field and the second column % specifies how many columns wide the input field should be. % % ANSWER = ZINPUTDLG(PROMPT,NAME,NUMLINES,DEFAULTANSWER) specifies the % default answer to display for each PROMPT. DEFAULTANSWER must contain % the same number of elements as PROMPT and must be a cell array of % strings. % % ANSWER = ZINPUTDLG(PROMPT,NAME,NUMLINES,DEFAULTANSWER,OPTIONS) specifies % additional options. If OPTIONS is the string 'on', the dialog is made % resizable. If OPTIONS is a structure, the fields Resize, WindowStyle, and % Interpreter are recognized. Resize can be either 'on' or % 'off'. WindowStyle can be either 'normal' or 'modal'. Interpreter can be % either 'none' or 'tex'. If Interpreter is 'tex', the prompt strings are % rendered using LaTeX. % % Examples: % % prompt={'Enter the matrix size for x^2:','Enter the colormap name:'}; % name='Input for Peaks function'; % numlines=1; % defaultanswer={'20','hsv'}; % % answer=zinputdlg(prompt,name,numlines,defaultanswer); % % options.Resize='on'; % options.WindowStyle='normal'; % options.Interpreter='tex'; % % answer=zinputdlg(prompt,name,numlines,defaultanswer,options); % % See also DIALOG, ERRORDLG, HELPDLG, LISTDLG, MSGBOX, % QUESTDLG, TEXTWRAP, UIWAIT, WARNDLG . % Copyright 1994-2007 The MathWorks, Inc. % $Revision$ %%%%%%%%%%%%%%%%%%%% %%% Nargin Check %%% %%%%%%%%%%%%%%%%%%%% error(nargchk(0,5,nargin)); error(nargoutchk(0,1,nargout)); %%%%%%%%%%%%%%%%%%%%%%%%% %%% Handle Input Args %%% %%%%%%%%%%%%%%%%%%%%%%%%% if nargin<1 Prompt='Input:'; end if ~iscell(Prompt) Prompt={Prompt}; end NumQuest=numel(Prompt); if nargin<2, Title=' '; end if nargin<3 NumLines=1; end if nargin<4 DefAns=cell(NumQuest,1); for lp=1:NumQuest DefAns{lp}=''; end end if nargin<5 Resize = 'off'; end WindowStyle='modal'; Interpreter='none'; Options = struct([]); %#ok if nargin==5 && isstruct(Resize) Options = Resize; Resize = 'off'; if isfield(Options,'Resize'), Resize=Options.Resize; end if isfield(Options,'WindowStyle'), WindowStyle=Options.WindowStyle; end if isfield(Options,'Interpreter'), Interpreter=Options.Interpreter; end end [rw,cl]=size(NumLines); OneVect = ones(NumQuest,1); if (rw == 1 & cl == 2) %#ok Handle [] NumLines=NumLines(OneVect,:); elseif (rw == 1 & cl == 1) %#ok NumLines=NumLines(OneVect); elseif (rw == 1 & cl == NumQuest) %#ok NumLines = NumLines'; elseif (rw ~= NumQuest | cl > 2) %#ok error('MATLAB:inputdlg:IncorrectSize', 'NumLines size is incorrect.') end if ~iscell(DefAns), error('MATLAB:inputdlg:InvalidDefaultAnswer', 'Default Answer must be a cell array of strings.'); end %%%%%%%%%%%%%%%%%%%%%%% %%% Create InputFig %%% %%%%%%%%%%%%%%%%%%%%%%% FigWidth=175; FigHeight=100; FigPos(3:4)=[FigWidth FigHeight]; %#ok FigColor=get(0,'DefaultUicontrolBackgroundcolor'); InputFig=dialog( ... 'Visible' ,'off' , ... 'KeyPressFcn' ,@doFigureKeyPress, ... 'Name' ,Title , ... 'Pointer' ,'arrow' , ... 'Units' ,'pixels' , ... 'UserData' ,'Cancel' , ... 'Tag' ,Title , ... 'HandleVisibility' ,'callback' , ... 'Color' ,FigColor , ... 'NextPlot' ,'add' , ... 'WindowStyle' ,WindowStyle, ... 'DoubleBuffer' ,'on' , ... 'Resize' ,Resize ... ); %%%%%%%%%%%%%%%%%%%%% %%% Set Positions %%% %%%%%%%%%%%%%%%%%%%%% DefOffset = 5; DefBtnWidth = 53; DefBtnHeight = 23; TextInfo.Units = 'pixels' ; TextInfo.FontSize = get(0,'FactoryUIControlFontSize'); TextInfo.FontWeight = get(InputFig,'DefaultTextFontWeight'); TextInfo.HorizontalAlignment= 'left' ; TextInfo.HandleVisibility = 'callback' ; StInfo=TextInfo; StInfo.Style = 'text' ; StInfo.BackgroundColor = FigColor; EdInfo=StInfo; EdInfo.FontWeight = get(InputFig,'DefaultUicontrolFontWeight'); EdInfo.Style = 'edit'; EdInfo.BackgroundColor = 'white'; BtnInfo=StInfo; BtnInfo.FontWeight = get(InputFig,'DefaultUicontrolFontWeight'); BtnInfo.Style = 'pushbutton'; BtnInfo.HorizontalAlignment = 'center'; % Add VerticalAlignment here as it is not applicable to the above. TextInfo.VerticalAlignment = 'bottom'; TextInfo.Color = get(0,'FactoryUIControlForegroundColor'); % adjust button height and width btnMargin=1.4; ExtControl=uicontrol(InputFig ,BtnInfo , ... 'String' ,'OK' , ... 'Visible' ,'off' ... ); % BtnYOffset = DefOffset; BtnExtent = get(ExtControl,'Extent'); BtnWidth = max(DefBtnWidth,BtnExtent(3)+8); BtnHeight = max(DefBtnHeight,BtnExtent(4)*btnMargin); delete(ExtControl); % Determine # of lines for all Prompts TxtWidth=FigWidth-2*DefOffset; ExtControl=uicontrol(InputFig ,StInfo , ... 'String' ,'' , ... 'Position' ,[ DefOffset DefOffset 0.96*TxtWidth BtnHeight ] , ... 'Visible' ,'off' ... ); WrapQuest=cell(NumQuest,1); QuestPos=zeros(NumQuest,4); for ExtLp=1:NumQuest if size(NumLines,2)==2 [WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ... textwrap(ExtControl,Prompt(ExtLp),NumLines(ExtLp,2)); else [WrapQuest{ExtLp},QuestPos(ExtLp,1:4)]= ... textwrap(ExtControl,Prompt(ExtLp),80); end end % for ExtLp delete(ExtControl); QuestWidth =QuestPos(:,3); QuestHeight=QuestPos(:,4); TxtHeight=QuestHeight(1)/size(WrapQuest{1,1},1)+10; EditHeight=TxtHeight*NumLines(:,1); EditHeight(NumLines(:,1)==1)=EditHeight(NumLines(:,1)==1)+4; FigHeight=(NumQuest+2)*DefOffset + ... BtnHeight+sum(EditHeight) + ... sum(QuestHeight); TxtXOffset=DefOffset; QuestYOffset=zeros(NumQuest,1); EditYOffset=zeros(NumQuest,1); QuestYOffset(1)=FigHeight-DefOffset-QuestHeight(1); EditYOffset(1)=QuestYOffset(1)-EditHeight(1); for YOffLp=2:NumQuest, QuestYOffset(YOffLp)=EditYOffset(YOffLp-1)-QuestHeight(YOffLp)-DefOffset; EditYOffset(YOffLp)=QuestYOffset(YOffLp)-EditHeight(YOffLp); end % for YOffLp QuestHandle=[]; %#ok EditHandle=[]; AxesHandle=axes('Parent',InputFig,'Position',[0 0 1 1],'Visible','off'); inputWidthSpecified = false; for lp=1:NumQuest, if ~ischar(DefAns{lp}), delete(InputFig); error('MATLAB:inputdlg:InvalidInput', 'Default Answer must be a cell array of strings.'); end EditHandle(lp)=uicontrol(InputFig , ... EdInfo , ... 'Max' ,NumLines(lp,1) , ... 'Position' ,[ TxtXOffset EditYOffset(lp) TxtWidth EditHeight(lp) ], ... 'String' ,DefAns{lp} , ... 'Tag' ,'Edit' ... ); %force the damned thing to respond on 'enter' too if (NumLines(lp,1) == 1), %set (EditHandle(lp), 'KeyPressFcn',@doEditKeyPress); set (EditHandle(lp), 'Callback', @doCallback); end QuestHandle(lp)=text('Parent' ,AxesHandle, ... TextInfo , ... 'Position' ,[ TxtXOffset QuestYOffset(lp)], ... 'String' ,WrapQuest{lp} , ... 'Interpreter',Interpreter , ... 'Tag' ,'Quest' ... ); MinWidth = max(QuestWidth(:)); if (size(NumLines,2) == 2) % input field width has been specified. inputWidthSpecified = true; EditWidth = setcolumnwidth(EditHandle(lp), NumLines(lp,1), NumLines(lp,2)); MinWidth = max(MinWidth, EditWidth); end FigWidth=max(FigWidth, MinWidth+2*DefOffset); end % for lp % fig width may have changed, update the edit fields if they dont have user specified widths. if ~inputWidthSpecified TxtWidth=FigWidth-2*DefOffset; for lp=1:NumQuest set(EditHandle(lp), 'Position', [TxtXOffset EditYOffset(lp) TxtWidth EditHeight(lp)]); end end FigPos=get(InputFig,'Position'); FigWidth=max(FigWidth,2*(BtnWidth+DefOffset)+DefOffset); FigPos(1)=0; FigPos(2)=0; FigPos(3)=FigWidth; FigPos(4)=FigHeight; set(InputFig,'Position',zgetnicedialoglocation(FigPos,get(InputFig,'Units'))); OKHandle=uicontrol(InputFig , ... BtnInfo , ... 'Position' ,[ FigWidth-2*BtnWidth-2*DefOffset DefOffset BtnWidth BtnHeight ] , ... 'KeyPressFcn',@doControlKeyPress , ... 'String' ,'OK' , ... 'Callback' ,@doCallback , ... 'Tag' ,'OK' , ... 'UserData' ,'OK' ... ); zsetdefaultbutton(InputFig, OKHandle); CancelHandle=uicontrol(InputFig , ... BtnInfo , ... 'Position' ,[ FigWidth-BtnWidth-DefOffset DefOffset BtnWidth BtnHeight ] , ... 'KeyPressFcn',@doControlKeyPress , ... 'String' ,'Cancel' , ... 'Callback' ,@doCallback , ... 'Tag' ,'Cancel' , ... 'UserData' ,'Cancel' ... ); %#ok handles = guihandles(InputFig); handles.MinFigWidth = FigWidth; handles.FigHeight = FigHeight; handles.TextMargin = 2*DefOffset; guidata(InputFig,handles); set(InputFig,'ResizeFcn', {@doResize, inputWidthSpecified}); % make sure we are on screen movegui(InputFig) % if there is a figure out there and it's modal, we need to be modal too if ~isempty(gcbf) && strcmp(get(gcbf,'WindowStyle'),'modal') set(InputFig,'WindowStyle','modal'); end set(InputFig,'Visible','on'); drawnow; if ~isempty(EditHandle) uicontrol(EditHandle(1)); end if ishandle(InputFig) % Go into uiwait if the figure handle is still valid. % This is mostly the case during regular use. uiwait(InputFig); end % Check handle validity again since we may be out of uiwait because the % figure was deleted. if ishandle(InputFig) Answer={}; if strcmp(get(InputFig,'UserData'),'OK'), Answer=cell(NumQuest,1); for lp=1:NumQuest, Answer(lp)=get(EditHandle(lp),{'String'}); end end delete(InputFig); else Answer={}; end function doFigureKeyPress(obj, evd) %#ok switch(evd.Key) case {'return','space'} set(gcbf,'UserData','OK'); uiresume(gcbf); case {'escape'} delete(gcbf); end function doEditKeyPress(obj, evd) %#ok switch(evd.Key) case {'return'} set(gcbf,'UserData','OK'); uiresume(gcbf); case 'escape' delete(gcbf) end function doControlKeyPress(obj, evd) %#ok switch(evd.Key) case {'return'} if ~strcmp(get(obj,'UserData'),'Cancel') set(gcbf,'UserData','OK'); uiresume(gcbf); else delete(gcbf) end case 'escape' delete(gcbf) end function doCallback(obj, evd) %#ok if ~strcmp(get(obj,'UserData'),'Cancel') set(gcbf,'UserData','OK'); uiresume(gcbf); else delete(gcbf) end function doResize(FigHandle, evd, multicolumn) %#ok % TBD: Check difference in behavior w/ R13. May need to implement % additional resize behavior/clean up. Data=guidata(FigHandle); resetPos = false; FigPos = get(FigHandle,'Position'); FigWidth = FigPos(3); FigHeight = FigPos(4); if FigWidth < Data.MinFigWidth FigWidth = Data.MinFigWidth; FigPos(3) = Data.MinFigWidth; resetPos = true; end % make sure edit fields use all available space if % number of columns is not specified in dialog creation. if ~multicolumn for lp = 1:length(Data.Edit) EditPos = get(Data.Edit(lp),'Position'); EditPos(3) = FigWidth - Data.TextMargin; set(Data.Edit(lp),'Position',EditPos); end end if FigHeight ~= Data.FigHeight FigPos(4) = Data.FigHeight; resetPos = true; end if resetPos set(FigHandle,'Position',FigPos); end % set pixel width given the number of columns function EditWidth = setcolumnwidth(object, rows, cols) % Save current Units and String. old_units = get(object, 'Units'); old_string = get(object, 'String'); old_position = get(object, 'Position'); set(object, 'Units', 'pixels') set(object, 'String', char(ones(1,cols)*'x')); new_extent = get(object,'Extent'); if (rows > 1) % For multiple rows, allow space for the scrollbar new_extent = new_extent + 19; % Width of the scrollbar end new_position = old_position; new_position(3) = new_extent(3) + 1; set(object, 'Position', new_position); % reset string and units set(object, 'String', old_string, 'Units', old_units); EditWidth = new_extent(3); % A local version of matlab's getnicedialoglocation function figure_size = zgetnicedialoglocation(figure_size, figure_units) % adjust the specified figure position to fig nicely over GCBF % or into the upper 3rd of the screen % Copyright 1999-2006 The MathWorks, Inc. % $Revision$ %%%%%% PLEASE NOTE %%%%%%%%% %%%%%% This file has also been copied into: %%%%%% matlab/toolbox/ident/idguis %%%%%% If this functionality is changed, please %%%%%% change it also in idguis. %%%%%% PLEASE NOTE %%%%%%%%% parentHandle = gcbf; propName = 'Position'; if isempty(parentHandle) parentHandle = 0; propName = 'ScreenSize'; end old_u = get(parentHandle,'Units'); set(parentHandle,'Units',figure_units); container_size=get(parentHandle,propName); set(parentHandle,'Units',old_u); figure_size(1) = container_size(1) + 1/2*(container_size(3) - figure_size(3)); figure_size(2) = container_size(2) + 2/3*(container_size(4) - figure_size(4)); % A local version of matlab's setdefaultbutton function zsetdefaultbutton(figHandle, btnHandle) % WARNING: This feature is not supported in MATLAB and the API and % functionality may change in a future release. %SETDEFAULTBUTTON Set default button for a figure. % SETDEFAULTBUTTON(BTNHANDLE) sets the button passed in to be the default button % (the button and callback used when the user hits "enter" or "return" % when in a dialog box. % % This function is used by inputdlg.m, msgbox.m, questdlg.m and % uigetpref.m. % % Example: % % f = figure; % b1 = uicontrol('style', 'pushbutton', 'string', 'first', ... % 'position', [100 100 50 20]); % b2 = uicontrol('style', 'pushbutton', 'string', 'second', ... % 'position', [200 100 50 20]); % b3 = uicontrol('style', 'pushbutton', 'string', 'third', ... % 'position', [300 100 50 20]); % setdefaultbutton(b2); % % Copyright 2005-2007 The MathWorks, Inc. %--------------------------------------- NOTE ------------------------------------------ % This file was copied into matlab/toolbox/local/private. % These two files should be kept in sync - when editing please make sure % that *both* files are modified. % Nargin Check if nargin<1, error('MATLAB:setdefaultbutton:InvalidNumberOfArguments','Too few arguments for setdefaultbutton'); end if nargin>2, error('MATLAB:setdefaultbutton:InvalidNumberOfArguments','Too many arguments for setdefaultbutton'); end if (usejava('awt') == 1) % We are running with Java Figures useJavaDefaultButton(figHandle, btnHandle) else % We are running with Native Figures useHGDefaultButton(figHandle, btnHandle); end function useJavaDefaultButton(figH, btnH) % Get a UDD handle for the figure. fh = handle(figH); % Call the setDefaultButton method on the figure handle fh.setDefaultButton(btnH); function useHGDefaultButton(figHandle, btnHandle) % First get the position of the button. btnPos = getpixelposition(btnHandle); % Next calculate offsets. leftOffset = btnPos(1) - 1; bottomOffset = btnPos(2) - 2; widthOffset = btnPos(3) + 3; heightOffset = btnPos(4) + 3; % Create the default button look with a uipanel. % Use black border color even on Mac or Windows-XP (XP scheme) since % this is in natve figures which uses the Win2K style buttons on Windows % and Motif buttons on the Mac. h1 = uipanel(get(btnHandle, 'Parent'), 'HighlightColor', 'black', ... 'BorderType', 'etchedout', 'units', 'pixels', ... 'Position', [leftOffset bottomOffset widthOffset heightOffset]); % Make sure it is stacked on the bottom. uistack(h1, 'bottom');
github
lcnbeapp/beapp-master
afni_niml_read.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/afni_niml_read.m
2,791
utf_8
3da5cff1cf07ffd470bd42539f8078b9
function [p,s]=afni_niml_read(fn) % simple function to read niml files % % P=AFNI_NIML_READ(FN) reads a file FN and returns a NIML structure P. % [P,S]=AFNI_NIML_READ(FN) also returns the file contents S % % If FN refers to a file in another format than ASCII NIML, an attempt is % made to convert the file to this format with AFNI's ConvertDset % % NNO Dec 2009 <[email protected]> s=simpleread(fn); [b1, ext]=is_non_niml_ascii(fn); % if the extension suggests that it is not ASCII NIML if b1 || is_non_niml_ascii(s); % ... or the file contents suggest this % then we try to convert the file warning('Input file seems to be not a NIML ASCII file, will try to convert it to ascii'); s=binaryToASCII(s,ext); end p=afni_niml_parse(s); function s=simpleread(fn) fprintf('Reading %s\n', fn); fid=fopen(fn); if fid==-1 error('Error reading from file %s\n', fn); end s=fread(fid,inf,'char=>char'); fclose(fid); s=s'; function sa=binaryToASCII(sb,ext) % converts a non-ASCII NIML file to an ASCII NIML file % ext is the extension of the input file % keep looking for a temporary file name that does not exist yet rand('twister',sum(100*clock)); % initialize random number generator while true idx=floor(rand()*1e6); prefix=sprintf('__TMP_%d',idx); tmpfn1=sprintf('%s_in%s',prefix,ext); % input tmpfn2=sprintf('%s_out%s',prefix,'.niml.dset'); % output if ~exist(tmpfn1,'file') && ~exist(tmpfn2,'file') break; end end fid=fopen(tmpfn1,'w'); if fid<0 error('Could not open temporary file for writing'); end fwrite(fid,sb); fclose(fid); cmd=sprintf('ConvertDset -input %s -o_niml_asc -prefix %s', tmpfn1, tmpfn2); fprintf('Running command: %s\n', cmd); [a,w]=unix(cmd); if a ~= 0 fprintf(w) error('Error when trying to convert binary to ascii'); end fprintf('Conversion was successful\n'); % read the output file sa=simpleread(tmpfn2); % clean up delete(tmpfn1); delete(tmpfn2); function [b,ext]=is_non_niml_ascii(s) % tries to determine whether the file is niml ascii or not % - input argument can either be a filename or the contents of the file % - ouput contains whether it's a NIML ASCII file, and the extension [ffff,fn,ext1]=fileparts(s); if exist(s,'file') % s is a filename exts={'.gii','1D'}; b=~isempty(strmatch(lower(ext1),exts)); [ffff,fffff,ext2]=fileparts(fn); ext=[ext2 ext1]; % in case there is a double extension such as .niml.dset else % s contains the file contents expr='<(?<h>\w+).*ni_form\s*=\s*"(?<rhs>[^"]+)".*</\1>'; hh=regexp(s,expr,'names'); b=false; for k=1:numel(hh) b=~isempty(findstr(hh(k).rhs,'binary.')); if b return end end ext=NaN; %unknown end
github
lcnbeapp/beapp-master
afni_nel_parse.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/afni_nel_parse.m
1,763
utf_8
62fbd076a3c4430f06f6385abc18b2d8
function [nel] = afni_nel_parse(nellcell) %should really check that this is nel and not ngr ... %assuming we have nel %get the header part cnel = char(nellcell); clear nellcell; ncnel = length(cnel); %break up into head and data expr = '(?<head><(\w+).*?>)(?<data>.*)<'; %using expr = '(?<head><(\w+).*?>)(?<data>.*<.*>)'; %would get all of the data chunk including its closing tag %but then I'd have to strip it... [pp] = regexp(cnel,expr,'names'); %Now get the header fields into structs hh = regexp(pp.head, '(?<lhs>\w*)="(?<rhs>\S*)"','names'); nel = cell2struct({hh(:).rhs}, {hh(:).lhs},2); clear hh; tt = nel.ni_type; nel.vec_typ=zeros(1,1000); nn=0; while (~isempty(tt)), [ttt,tt] = strtok(tt, ','); %look for the N*type syntax N = 1; [tttt,ttt] = strtok(ttt,'*'); Ntttt = str2double(tttt); if (~isnan(Ntttt)), %have a number, get the type N = Ntttt; tttt = strtok(ttt,'*'); end nel.vec_typ(nn+1:1:nn+N) = afni_ni_rowtype_name_to_code(tttt); nn = nn + N; end %interpret some things nel.name = char(strtok(regexp(pp.head,'<\w+', 'match'),'<')); nel.vec_typ = nel.vec_typ(1:nn); nel.vec_len = str2num(nel.ni_dimen); nel.vec_num = length(nel.vec_typ); %Now parse the data if (~afni_ni_is_numeric_type(nel.vec_typ)), fprintf(2,'Data not all numeric, will not parse it'); nel.data = pp.data; else nel = afni_nel_parse_data(nel, pp.data); end clear pp return; function [nel] = afni_nel_parse_data(nel, data) nel.data = reshape(sscanf(data,'%f'), nel.vec_num, nel.vec_len)'; return;
github
lcnbeapp/beapp-master
afni_niml_print.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/afni_niml_print.m
5,521
utf_8
9dbc69da949e82e64071c668290ac2da
function s=afni_niml_print(p) % takes a NIML data structure and converts it to string representation % % S=AFNI_NIML_PRINT(P) takes an NIML datastructure P and returns a string % representation S. % % This function is more or less the inverse of AFNI_NIML_PARSE. % % The current implementation will take any struct that has the required % NIML fields; it does not check for any data consisentence. % % Please note that this function is *VERY EXPERIMENTAL*. % % NNO Dec 2009 <[email protected]> if iscell(p) ss=cell(1,numel(p)); % simple recursion for k=1:numel(p) ss{k}=afni_niml_print(p{k}); end s=[ss{:}]; % concatenate else headername=p.name; p=rmfield(p,'name'); % we don't want this as a field if isfield(p,'nodes') % is a group, do recursion sbody=afni_niml_print(p.nodes); p=rmfield(p,'nodes'); % 'nodes' is not a standard NIML field elseif isfield(p,'data') if ~isfield(p,'vec_typ') % in case the type is not specified, we try % to derive it based on the type of p.data ps=derive_vec_type(p.data); % set field names if not set fns=fieldnames(ps); for k=1:numel(fns) if ~isfield(p,fns{k}) p.(fns{k})=ps.(fns{k}); end end elseif p.vec_typ<0; error('vec_typ=%d not supported (yet)', p.vec_typ); end sbody=afni_niml_print_body(p); % some fields are not standard NIML (I think), we remove these removefields=strvcat('vec_typ','vec_len','vec_num','name','data'); fns=fieldnames(p); for k=1:numel(fns) fn=fns{k}; if ~isempty(strmatch(fn,removefields,'exact')) p=rmfield(p,fn); end end else disp(p) error('Do not understand this struct'); end headertext=afni_niml_print_header(p); s=sprintf('<%s\n%s >\n%s</%s>\n',headername,headertext,sbody,headername); end function s=afni_niml_print_body(p) format=get_print_format(p.vec_typ,p.data); if strcmp(format,'%s') around='"'; %surround by quotes if it is a string - CHECKME is that according to the standard? else around=''; p.data=p.data'; %transpose to fix major row vs. major column order end s=sprintf([format '\n'],p.data); s=[around s(1:(end-1)) around]; % remove last newline function s=afni_niml_print_header(p) pre=' '; % a bit of indendationn post=sprintf('\n'); % every header gets a new line fns=fieldnames(p); n=numel(fns); ss=cell(1,n); for k=1:n fn=fns{k}; val=strtrim(p.(fn)); if isnumeric(val) warning('Converting numeric to string for field %s\n', fn); val=num2str(val); end % surround by quotes, if that's not the case yet if val(1) ~= '"' && val(end) ~= '"' val=['"' val '"']; end if k==n post=''; %no new line at the very end end ss{k}=sprintf('%s%s=%s%s',pre,fn,val,post); end s=[ss{:}]; % concatenate results function p=derive_vec_type(data) % sets the vector type, in case this is not given. % % data should be either a string or numeric % TODO: support structs and cells, and mixed data types % TODO: allow other fields missing (maybe use the whole struct rather than % just the data so that we can be 'smart' and use converging % evidence? nidefs=afni_ni_defs(); if islogical(data) data=single(data); % convert to numeric end if isnumeric(data) if isequal(round(data),data) tp=nidefs.NI_INT; else tp=nidefs.NI_FLOAT; end [ln,nm]=size(data); elseif ischar(data) tp=nidefs.NI_STRING; ln=1; nm=1; else disp(data) error('Unknown data type'); end if nm>1 prefix=sprintf('%d*',nm); else prefix=''; end tps=strtrim(nidefs.type_name(tp+1,:)); % tricky base0 vs base1 p.ni_type=[prefix tps]; p.ni_dimen=sprintf('%d',ln); %NNO Jan 2010 fix p.vec_typ=repmat(tp,1,nm); % tricky base0 vs base1 % Jan 2010: removed 'tp+1' p.vec_len=ln; p.vec_num=nm; function f=get_print_format(vec_typ,data,nidefs) % use vec_typ to create a format string for printf % data is used in case we print floats; we use the least possible number of % floating point positions if nargin<3 nidefs=afni_ni_defs(); end n=numel(vec_typ); if n>1 if size(data,2) ~= n error('Mismatch between data and vec_typ: %d ~= %d', n, size(data,2)); end fs=cell(1,n); for k=1:n if k<n addend=' '; % spacing between elements ... else addend=''; % ... except for the last element end % recursion fs{k}=[get_print_format(vec_typ(k),data(:,k),nidefs) addend]; end f=[fs{:}]; % concatenate result else vec_str=strtrim(nidefs.type_name(vec_typ+1,:)); %tricky again, base0 vs base1 switch vec_str case 'String' f='%s'; case {'byte','short','int'} % CHECKME don't know if this is ok for bytes and shorts... f='%d'; otherwise precision=get_required_precision(data); f=sprintf('%%.%df',precision); end end
github
lcnbeapp/beapp-master
CA_EZ_Prep.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/CA_EZ_Prep.m
14,358
utf_8
af87e1ccd31dc096f0a411e877de8dd9
function [MapMPM, MapML, aur] = CA_EZ_Prep() % A function to process a new Eickhoff, Amunts and Zilles CA toolbox % The function creates new versions of AFNI's source files % thd_ttatlas_CA_EZ.c and thd_ttatlas_CA_EZ.h . % The new files created are called thd_ttatlas_CA_EZ-auto.c and thd_ttatlas_CA_EZ-auto.h % must be inspected then moved and renamed into afni's src directory. % % See SUMA/Readme_Modify.log for info on sequence of execution % search for: + How you install a new Zilles, Amunts, Eickhoff SPM toolbox:% % % See also scripts: % @Prep_New_CA_EZ % @Compare_CA_EZ % @Create_suma_tlrc.tgz % @Create_ca_ez_tlrc.tgz % @DistArchives % ZSS SSCC Feb 06 FuncName = 'CA_EZ_Prep'; MapMPM = []; MapML = []; toolbox_dir = '/Volumes/afni/home4/users/ziad/Programs/matlab/spm2/toolbox/Anatomy'; if (exist(toolbox_dir) ~= 7), fprintf(2,'Toolbox directory %s not found\nPick a new one:', toolbox_dir); toolbox = uigetdir(sprintf('.%c', filesep), 'Standard toobox dir not found. Pick a new one:'); if (exist(toolbox_dir) ~= 7), fprintf(2,'Toolbox directory %s not found.', toolbox_dir); return; end else %get around the symbolic linc so that reference is to actual directory ... curdir = pwd; cd (toolbox_dir); toolbox_dir = pwd; cd (curdir); [err,pt] = GetPath(toolbox_dir); [err,sout] = unix(sprintf('ls -l %s', pt)); c = input(sprintf('Found toolbox here: %s\nDirectory Listing:\n%s\nEnter "y" to use it, anything else to quit.\n', toolbox_dir, sout),'s'); if (isempty(c) || ( c(1) ~= 'y' && c(1) ~= 'Y' ) ), return; end end fprintf(1,'Using toolbox directoy %s...\n', toolbox_dir); %First get the MPM info prf = sprintf('%s%cAllAreas*MPM.mat', toolbox_dir, filesep); [err, ErrMessage, MPM_file] = zglobb ({prf}); if (size(MPM_file,1) ~= 1), fprintf(2,'Could not find unique MPM map list\n', toolbox_dir); for (i=1:1:size(MPM_file,1)), MPM_file(i), end return; end %load the MPM map structure MapMPM = load(MPM_file(1).name); MapMPM = MapMPM.MAP; %checks if (~isstruct(MapMPM)), fprintf(2,'MapMPM is not a struct\n'); return; end fld = 'name'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'GV'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'ref'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'smoothed'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'VOL'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'MaxMap'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'XYZ'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'XYZmm'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'orient'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'Z'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'LR'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'allXYZ'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'allZ'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end fld = 'allLR'; if (~isfield (MapMPM, fld)), fprintf(2,'%s field is not in MapMPM\n', fld); return; end %Now the MacroLabels prf = sprintf('%s%cMacro.mat', toolbox_dir, filesep); [err, ErrMessage, ML_file] = zglobb ({prf}); if (size(ML_file,1) ~= 1), fprintf(2,'Could not find unique ML map list\n', toolbox_dir); for (i=1:1:size(ML_file,1)), ML_file(i), end return; end %load the MacroLabels MapML = load(ML_file(1).name); MapML = MapML.Labels; if (~iscellstr(MapML)), fprintf(2,'MacroLabels variable not the expected cellstr\n'); return; end for (i=1:1:length(MapML)), MapML(i) = cellstr(fix_string(char(MapML(i)))); end MapML = char(MapML); %Output files cname = 'thd_ttatlas_CA_EZ-auto.c'; hname = 'thd_ttatlas_CA_EZ-auto.h'; rname = 'thd_ttatlas_CA_EZ-ref.h'; %Do the references % a horrible mess of an if block below. One hopes for a better solution someday if (~isempty(which('se_note'))), fprintf(1,'\nNow trying to get at references using se_note\n'); se_note; k = 0; vers = ''; if (exist('fg')), h = get(fg, 'Children'); cs = []; nref = 0; l = 1; for (i=1:1:length(h)), tmp = get(h(i),'String') if (~isempty(tmp)), k = k + 1; cs(k).s = tmp; if (iscellstr(cs(k).s) && length(cs(k).s) > 1), if (length(cs(k).s) > 5), %papers nref = nref + 1; ref(nref) = k; cs(k).typ = 1; else cs(k).typ = -1; %the authors's info au = cellstr(cs(k).s); end else cs(k).typ = 0; %other strings ot(l) = cellstr(cs(k).s); if (~isempty(strfind(char(ot(l)), 'Version'))), vers = zdeblank(char(ot(l))); end l = l + 1; end end end if (isempty(vers)), fprintf(2,'Version string not found!\n'); return; else fprintf(2,'Version set to %s\n', vers); end % find the corresponding references ti = char(cs(ref(1)).s); ar = char(cs(ref(2)).s); if (nref ~= 2 || (size(ar,1) ~= size(ti,1))), fprintf(2,'Warning:\nUnexpected number of ref strings or some mismatch (%d, %d, %d)\nYou have to edit thd_ttat', nref, size(ar,1), size(ti,1)); sdecl = sprintf('char CA_EZ_REF_STR[128][256]'); sdecl2 = sprintf('char CA_EZ_VERSION_STR[128]'); %return; else k = 1; l = 1; ar_tmp = ''; ti_tmp = ''; while (k<=size(ar,1)), if (sum(isspace(ar(k))) == size(k,2) && ~isempty(ar_tmp)), % all space, combine ca(l) = cellstr([ar_tmp '-x->' ti_tmp]); ar_tmp = ''; ti_tmp = ''; l = l + 1; else %catenate ar_tmp = [ar_tmp ' ' deblank(ar(k,:))]; ti_tmp = [ti_tmp ' ' deblank(ti(k,:))]; end k = k + 1; end %Now fix up the looks of the list DO NOT CHANGE USAGE OF '-----> ' for padding, C function PrettyRef depends on them imx = 0; for (l=1:1:length(ca)), isep = strfind(char(ca(l)), '-x->'); imx = max(isep, imx); end for (l=1:1:length(ca)), isep = strfind(char(ca(l)), '-x->'); ca_tmp = char(ca(l)); c1 = pad_strn(ca_tmp(1:isep), '-', imx, -1); c2 = ca_tmp(isep+4:length(ca_tmp)); ca(l) = cellstr([c1 '>' c2]); end aur = char(au); iout = find (aur < 32 | aur > 127); %replace characters outside of basci ascii text aur(iout) = '-'; %dunno what to do yet.... otr = flipud(char(ot)); car = char(ca); sdecl = sprintf('char CA_EZ_REF_STR[%d][%d]', size(otr,1)+size(aur,1)+size(car,1)+10, max([size(otr,2)+15, size(aur,2)+15,size(car,2)+15])); sdecl2 = sprintf('char CA_EZ_VERSION_STR[%d]',length(vers)+3); %do someting nice fida = fopen(rname,'w'); fprintf(fida, '%s = {\n',sdecl); fprintf(fida, '"%s",\n"%s",\n"%s",\n',otr(1,:), otr(2,:), otr(3,:)); for (i=1:1:size(aur,1)), fprintf(fida, '" %s",\n', aur(i,:)); end fprintf(fida, '"%s",\n', otr(4,:)); for (i=1:1:size(car,1)), fprintf(fida, '" %s",\n', car(i,:)); end fprintf(fida, '"%s",\n', otr(5,:)); fprintf(fida, '" ",\n" ",\n"AFNI adaptation by",\n" Ziad S. Saad ([email protected], SSCC/NIMH/NIH)",\n'); fprintf(fida, '" Info automatically created with CA_EZ_Prep.m based on se_note.m",\n'); fprintf(fida, '""};/* Must be the only empty string in the array*/\n'); %Must be the only empty string in the array fprintf(fida, '%s = { "%s" };\n', sdecl2, vers); fclose(fida); end end else fprintf(2,'Failed to locate se_note.m\nNo new reference string created'); return; end %Prep C output files fidc = fopen (cname,'w'); if (fidc < 0), fprintf(2,'Failed to open output .c file\n'); return; end fidh = fopen (hname,'w'); if (fidh < 0), fprintf(2,'Failed to open output .h file\n'); return; end str = sprintf('/*! Data for atlases from Eickhoff''s SPM toolbox.\nAutomatically compiled from: %s\n located at: %s\n by function %s\nDate: %s*/\n\n',... MPM_file(1).name, toolbox_dir, which(FuncName), date); fprintf(fidh,'%s', str); fprintf(fidc,'%s', str); %Add the references string file fprintf(fidc,'/*! Leave the reference string in a separate file\nfor easy script parsing.*/\n#include "%s"\n\n', rname); %Now do specifics to .h file NLbl_ML = size(MapML,1); MaxLbl_ML = size(MapML,2)+3; NLbl_MPM = length(MapMPM); MaxLbl_MPM = 0; for (i=1:1:NLbl_MPM), if (MaxLbl_MPM < length(MapMPM(i).name)), MaxLbl_MPM = length(MapMPM(i).name); end end MaxLbl_MPM = MaxLbl_MPM+3; if (MaxLbl_MPM > 64), fprintf(2,'Error: Labels longer than ATLAS_CMAX defined in AFNI src code.\nIncrease limit here and in thd_ttaltas_query.h\n'); return; end fprintf(fidh,'/* ----------- Macro Labels --------------------- */\n'); fprintf(fidh,'/* ----------- Based on: %s -------------*/\n', ML_file(1).name); fprintf(fidh,'#define ML_EZ_COUNT %d\n\n', NLbl_ML); fprintf(fidh,'extern ATLAS_point ML_EZ_list[ML_EZ_COUNT] ;\nextern char * ML_EZ_labels[ML_EZ_COUNT] ;\n'); fprintf(fidh,'extern int ML_EZ_labeled ;\nextern int ML_EZ_current ;\n'); fprintf(fidh,'/* ----------- Left Right --------------------- */\n'); fprintf(fidh,'/* ---- Based on my understanding -------------- */\n'); fprintf(fidh,'#define LR_EZ_COUNT 3\n\n'); fprintf(fidh,'extern ATLAS_point LR_EZ_list[LR_EZ_COUNT] ;\nextern char * LR_EZ_labels[LR_EZ_COUNT] ;\n'); fprintf(fidh,'extern int LR_EZ_labeled ;\nextern int LR_EZ_current ;\n\n'); fprintf(fidh,'/* ----------- MPM --------------------- */\n'); fprintf(fidh,'/* ----------- Based on: %s --------------*/\n', MPM_file(1).name); fprintf(fidh,'#define CA_EZ_COUNT %d\n', NLbl_MPM); fprintf(fidh,'#define CA_EZ_MPM_MIN 100 /*!< minimum meaningful value in MPM atlas */\n'); fprintf(fidh,'extern ATLAS_point CA_EZ_list[CA_EZ_COUNT] ;\nextern char * CA_EZ_labels[CA_EZ_COUNT] ;\n'); fprintf(fidh,'extern int CA_EZ_labeled ;\nextern int CA_EZ_current ;\n\n'); fprintf(fidh,'/* ----------- Refs --------------------- */\n'); fprintf(fidh,'/* ----------- Based on se_note.m --------------*/\n'); fprintf(fidh,'extern %s;\n', sdecl); fprintf(fidh,'extern %s;\n', sdecl2); %first create ML structure fprintf(fidc,'/* ----------- Macro Labels --------------------- */\n'); fprintf(fidc,'/* ----------- Based on: %s -------------*/\n', ML_file(1).name); fprintf(fidc,'ATLAS_point ML_EZ_list[ML_EZ_COUNT] = {\n'); for (i=1:1:size(MapML,1)), %pad string by dots fprintf(fidc,' { %-3d , "%s", 0, 0, 0, 0, ""}', i, pad_with_dot(MapML(i,:), 50)); if (i<size(MapML,1)) fprintf(fidc,',\n'); else fprintf(fidc,'\n'); end end fprintf(fidc,'};\n\n'); %Now create MPM structure fprintf(fidc,'/* ----------- MPM --------------------- */\n'); fprintf(fidc,'/* ----------- Based on: %s --------------*/\n', MPM_file(1).name); fprintf(fidc,'ATLAS_point CA_EZ_list[CA_EZ_COUNT] = { \n'); for (i=1:1:NLbl_MPM), [err,PathString,FileString] = GetPath (MapMPM(i).ref, 1); fprintf(fidc,' { %-3d, "%s", 0, 0, 0, 0, "%s" }', ... MapMPM(i).GV, pad_with_dot(MapMPM(i).name,40), pad_with_dot(RemoveExtension(FileString,'.img|.mnc|.hdr'), 27)); if (i<NLbl_MPM) fprintf(fidc,',\n'); else fprintf(fidc,'\n'); end end fprintf(fidc,'};\n\n'); %Now create LR structure fprintf(fidc,'/* ----------- Left Right --------------------- */\n'); fprintf(fidc,'/* ---- Based on my understanding -------------- */\n'); fprintf(fidc,'ATLAS_point LR_EZ_list[LR_EZ_COUNT] = {\n'); Lst = ['Non-Brain...'; 'Right Brain.'; 'Left Brain..']; for (i=1:1:3), fprintf(fidc,' { %-3d, "%s", 0, 0, 0, 0, "" }', ... i-1, Lst(i, :)); if (i<3) fprintf(fidc,',\n'); else fprintf(fidc,'\n'); end end fprintf(fidc,'};\n\n'); fclose(fidh); fclose(fidc); if (exist(rname) == 2), lst = sprintf('%s, %s and %s', cname, hname, rname); else lst = sprintf('%s and %s (%s was not created!)', cname, hname, rname); end fprintf(1,'\nThe files:\n %s\n in %s\nare meant to replace\n thd_ttatlas_CA_EZ.c, thd_ttatlas_CA_EZ.h and %s\nin AFNI''s src code.\n',... lst, pwd, rname) ; return; function str = fix_string(stri) str = stri; n_str = length(str); %are you missing a ) ? i = n_str; broken = 0; closed = 0; while (i > 1 && ~broken), if (str(i) == ')'), closed = closed + 1; elseif (str(i) == '('), if (closed == 0), broken = 1; end end i = i - 1; end if (broken), i = n_str; fixed = 0; while (i > 1 && ~fixed), if (~isspace(str(i))), if (i==n_str), str = [str,')']; else str(i+1) = ')'; end fixed = 1; end i = i - 1; end end return; function str = pad_with_dot(stri, ntot) if (nargin == 2), str = pad_strn(stri, ' ', ntot, -1); else str = stri; end n_str = length(str); i = n_str; while (i > 1 && isspace(str(i))), str(i) = '.'; i = i - 1; end return;
github
lcnbeapp/beapp-master
ROIcmap.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/afni/ROIcmap.m
3,688
utf_8
93376acea9697c3dce4c73aea3838d9b
function [M] = ROIcmap(nc,opt) % [M] = ROIcmap([nc],[opt]); % creates a colormap with % no color too close to grayscale, % no two consecutive colors too close % no colors exeedingly close to another in the map % no colors too close to a background color (optional) % nc: number of colors in map. Default is 64 % opt: optional options structure % .show: Figure handle in which to show the map % Default is 1. Set to 0 for no show. % In show mode, you get to pick colors with mouse % and read in their values. Hit enter to exit from % this mode. % .state: State of the random number generator. % Default is 0. % .write: Name of file to write colormap into % Default is '', no writing. Use something like % ROI64s0.1D.cmap, for a 64 cols, seed 0 colormap. % .avoid: Color to avoid getting close to. % .verb: verbosioty. 1 is default. 0 is for quiet % returns % M: The colormap. % %see also readXcol, rgbdectohex, and ScaleToMap % Ziad S. Saad SSCC/NIMH/NIH, [email protected] if (nargin == 0), nc = 64; opt.show = 1; elseif (nargin == 1), opt.show = 1; end if (isempty(nc)), nc = 64; end if (~isfield(opt,'show') | isempty(opt.show)), opt.show = 1; end if (~isfield(opt,'state') | isempty(opt.state)), opt.state = 0; end if (~isfield(opt,'write') | isempty(opt.write)), opt.write = ''; end if (~isfield(opt,'verb') | isempty(opt.verb)), opt.verb = 1; end if (~isfield(opt,'avoid') | isempty(opt.avoid)), opt.avoid = []; end %initialize rng rand('state',opt.state); M = zeros(nc,3); alldiff_lim = 0.5; %between 0 and 1, controls how different all colors in map are. %The first few colors can be quite different, high alldiff_lim %The difference is adjusted as more colors are demanded. g_lim = 0.2; %limit for too gray (0-1) d_lim = 0.40; %limit for too dim (0-3) b_lim = 2.2; %limit for too bright (0-3) for (i=1:1:nc), M(i,:) = rand(1,3); cnt = 0; %reject if too gray or too close to previous color while (toogray(M(i,:), g_lim, d_lim, b_lim) | tooclose(M,i, 0.6, alldiff_lim) | (~isempty(opt.avoid) & (sum(abs(M(i,:)-opt.avoid)) < 0.6))), M(i,:) = rand(1,3); cnt = cnt + 1; if (cnt > 2000), % too tight, relax alldiff_lim = max([0.95.*alldiff_lim 0.1]) ; d_lim = max([0.95.*d_lim 0.05]); b_lim = min([b_lim*1.05, 3.0]); if (opt.verb) fprintf(1,'Reduced alldiff_lim to %g, d_lim to %g, b_lim to %g\n', alldiff_lim, d_lim, b_lim); end cnt = 0; end end if (opt.verb) fprintf(1,'Color %d OK\n', i); end end if (opt.verb) fprintf(1,'alldiff_lim final was %g, d_lim final was %g, b_lim final was %g\n', alldiff_lim, d_lim, b_lim); end if (~isempty(opt.write)), optw.OverWrite = 'p'; wryte3(M, opt.write, optw); end if (opt.show), ShowCmap(M, opt.show); end return; function [a] = toogray(c, g_lim, d_lim, b_lim) a = 0; dc = abs(c - mean(c)); cs = sum(c); if (dc(1) < g_lim & dc(2) < g_lim & dc(3) < g_lim), a = 1; return; end if (cs < d_lim | cs > b_lim), a = 1; return; end return; function [a] = tooclose(M,i,prev_lim, alldiff_lim) if (i==1), a = 0; return; end a = 1; %too close to previous ? dc = abs(M(i,:)-M(i-1,:)); if (sum(dc) < prev_lim), return; end %too close to one before? if (i > 2), for (j=1:1:i-2), dc = abs(M(i,:)-M(j,:)); if (dc(1) < alldiff_lim & dc(2) < alldiff_lim & dc(3) < alldiff_lim), return; end end end %OK if you get here a = 0; return;
github
lcnbeapp/beapp-master
bemcp_example.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/bemcp/bemcp_example.m
21,663
utf_8
ee954ecd4779bb13a017d139b7a6acb1
function bemcp_example % Simple function to test/demonstrate how the Boundary element functions are % used in combination with Fildtrip/Forwinv routines. % % 1. A model is created as 3 concentric meshed spheres (using FT's % icosahedron routines), % 2. then random electrodes are placed on the upper part of the outer % sphere. % 3. the model is then "prepared" with 'ft_prepare_bemmodel', this bits % takes most time as it requires LOTS of calculation. % 4. sensors and volumes are plugged together by 'forwinv_prepare_vol_sens' % 5. Finally the leadfiled for 3 orthogonal sources placed at one location % is calculated with 'forwinv_compute_leadfield.m' % 6. Display the 3 leadfields % % NOTE: % this bit of code needs access to low level fieldtrip/forwinv routines % which have been copy/pasted here under. % Be aware that this way of programming is generally NOT advisable! % I used it only to ensure a quick & dirty check of the BEM module... % Christophe Phillips % $Id$ % create volume conductor starting from unit sphere [pnt, tri] = icosahedron162; vol = []; vol.cond = [1 1/80 1]; vol.source = 1; % index of source compartment vol.skin_surface = 3; % index of skin surface % inner_skull_surface vol.bnd(1).pnt = pnt*88; vol.bnd(1).tri = tri; % outer_skull_surface vol.bnd(2).pnt = pnt*92; vol.bnd(2).tri = tri; % skin_surface vol.bnd(3).pnt = pnt*100; vol.bnd(3).tri = tri; % create the BEM system matrix cfg = []; cfg.method = 'bemcp'; vol1 = ft_prepare_bemmodel(cfg, vol); % create some random electrodes pnt = randn(200,3); pnt = pnt(pnt(:,3)>0, :); % only those on the upper half sens = []; for i=1:size(pnt,1) sens.pnt(i,:) = pnt(i,:) / norm(pnt(i,:)); % scale towards the skin surface sens.label{i} = sprintf('%02d', i); end % prepare the sensor array and volume conduction, i.e. set up the linear % interpolation from vertices to electrodes [vol2, sens] = forwinv_prepare_vol_sens(vol1, sens); lf = forwinv_compute_leadfield([0 0 50], sens, vol2); figure; triplot(sens.pnt, [], lf(:,1)); colorbar figure; triplot(sens.pnt, [], lf(:,2)); colorbar figure; triplot(sens.pnt, [], lf(:,3)); colorbar return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Subfunctions from FieldTrip function [pnt, tri] = icosahedron162 % ICOSAHEDRON162 creates a 2-fold refined icosahedron % Copyright (C) 2003, Robert Oostenveld % % $Log: icosahedron162.m,v $ % Revision 1.3 2003/11/28 09:40:12 roberto % added a single help line % % Revision 1.2 2003/03/04 21:46:18 roberto % added CVS log entry and synchronized all copyright labels % [pnt, tri] = icosahedron; [pnt, tri] = refine(pnt, tri); [pnt, tri] = refine(pnt, tri); pnt = pnt ./ repmat(sqrt(sum(pnt.^2,2)), 1,3); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [pnt, tri] = icosahedron % ICOSAHEDRON creates an icosahedron % % [pnt, tri] = icosahedron % creates an icosahedron with 12 vertices and 20 triangles % % See also OCTAHEDRON, ICOSAHEDRON42, ICOSAHEDRON162, ICOSAHEDRON642, ICOSAHEDRON2562 % Copyright (C) 2002, Robert Oostenveld % % $Log: icosahedron.m,v $ % Revision 1.4 2006/07/26 11:03:38 roboos % added "see also octahedron" % % Revision 1.3 2003/03/11 15:35:20 roberto % converted all files from DOS to UNIX % % Revision 1.2 2003/03/04 21:46:18 roberto % added CVS log entry and synchronized all copyright labels % tri = [ 1 2 3 1 3 4 1 4 5 1 5 6 1 6 2 2 8 3 3 9 4 4 10 5 5 11 6 6 7 2 7 8 2 8 9 3 9 10 4 10 11 5 11 7 6 12 8 7 12 9 8 12 10 9 12 11 10 12 7 11 ]; pnt = zeros(12, 3); rho=0.4*sqrt(5); phi=2*pi*(0:4)/5; pnt( 1, :) = [0 0 1]; % top point pnt(2:6, 1) = rho*cos(phi)'; pnt(2:6, 2) = rho*sin(phi)'; pnt(2:6, 3) = rho/2; pnt(7:11, 1) = rho*cos(phi - pi/5)'; pnt(7:11, 2) = rho*sin(phi - pi/5)'; pnt(7:11, 3) = -rho/2; pnt(12, :) = [0 0 -1]; % bottom point return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [pntr, tri] = refine(pnt, tri, method, varargin) % REFINE a 3D surface that is described by a triangulation % % Use as % [pnt, tri] = refine(pnt, tri) % [pnt, tri] = refine(pnt, tri, 'updown', numtri) % % The default method is to refine the mesh globally by inserting a vertex at % each edge according to the algorithm described in Banks, 1983. % % The alternative 'updown' method refines the mesh a couple of times % using Banks' algorithm, followed by a downsampling using the REDUCEPATCH % function. % The Banks method is a memory efficient implementation which remembers % the previously inserted vertices. The refinement algorithm executes in % linear time with the number of triangles. % Copyright (C) 2002-2005, Robert Oostenveld % % $Log: refine.m,v $ % Revision 1.4 2005/05/06 08:54:31 roboos % added 'updown method, using matlab reducepatch function % % Revision 1.3 2003/03/11 15:35:20 roberto % converted all files from DOS to UNIX % % Revision 1.2 2003/03/04 21:46:19 roberto % added CVS log entry and synchronized all copyright labels % if nargin<3 method = 'banks'; end switch lower(method) case 'banks' npnt = size(pnt,1); ntri = size(tri,1); insert = spalloc(3*npnt,3*npnt,3*ntri); tri = zeros(4*ntri,3); % allocate memory for the new triangles pntr = zeros(npnt+3*ntri,3); % allocate memory for the maximum number of new vertices pntr(1:npnt,:) = pnt; % insert the original vertices current = npnt; for i=1:ntri if ~insert(tri(i,1),tri(i,2)) current = current + 1; pntr(current,:) = (pnt(tri(i,1),:) + pnt(tri(i,2),:))/2; insert(tri(i,1),tri(i,2)) = current; insert(tri(i,2),tri(i,1)) = current; v12 = current; else v12 = insert(tri(i,1),tri(i,2)); end if ~insert(tri(i,2),tri(i,3)) current = current + 1; pntr(current,:) = (pnt(tri(i,2),:) + pnt(tri(i,3),:))/2; insert(tri(i,2),tri(i,3)) = current; insert(tri(i,3),tri(i,2)) = current; v23 = current; else v23 = insert(tri(i,2),tri(i,3)); end if ~insert(tri(i,3),tri(i,1)) current = current + 1; pntr(current,:) = (pnt(tri(i,3),:) + pnt(tri(i,1),:))/2; insert(tri(i,3),tri(i,1)) = current; insert(tri(i,1),tri(i,3)) = current; v31 = current; else v31 = insert(tri(i,3),tri(i,1)); end % add the 4 new triangles with the correct indices tri(4*(i-1)+1, :) = [tri(i,1) v12 v31]; tri(4*(i-1)+2, :) = [tri(i,2) v23 v12]; tri(4*(i-1)+3, :) = [tri(i,3) v31 v23]; tri(4*(i-1)+4, :) = [v12 v23 v31]; end % remove the space for the vertices that was not used pntr = pntr(1:current, :); case 'updown' ntri = size(tri,1); while ntri<varargin{1} % increase the number of triangles by a factor of 4 [pnt, tri] = refine(pnt, tri, 'banks'); ntri = size(tri,1); end % reduce number of triangles using Matlab function [tri, pntr] = reducepatch(tri, pnt, varargin{1}); otherwise error(['unsupported method: ' method]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hs, hc, contour] = triplot(pnt, tri, val, mode, levels) % TRIPLOT make 2D or 3D plot of triangulated surface and interpolated values % The surface can be displayed with linear interpolated values or with % linear interpolated contours of a potential distribution. % % Use as % triplot(pnt, tri, value) % triplot(pnt, tri, value, mode) % triplot(pnt, tri, value, mode, levels) % This will make a plot of value on the surface described by triangles % tri with vertices pnt. The matrix tri can be [], in which case a % it will be computed using a delaunay triangulation. % % The visualization mode can be % 'surface' make interpolated plot of value on surface (default) % 'faces' plot white triangles only (value can be []) % 'faces_red' plot red triangles only (value can be []) % 'faces_blue' plot blue triangles only (value can be []) % 'faces_skin' plot skin-colored triangles only (value can be []) % 'face_index' plot index of each triangle (value can be []) % 'nodes' plot black vertices only (value can be []) % 'node_index' plot index of each vertex (value can be []) % 'node_label' plot label of each vertex (value should be cell array) % 'edges' plot black edges only (value can be []) % 'contour' make interpolated contour plot of value on surface % 'contour_bw' make interpolated black-white contour plot % 'contour_rb' make interpolated contour plot with red-blue % % With the optional levels, you can specify the levels at which contours will % be plotted % % See also PATCH, COLORMAP, VIEW (general Matlab commands) % updated on Mon Jul 23 12:41:44 MET DST 2001 % updated on Fri Jan 31 11:47:28 CET 2003 % Copyright (C) 2001=2006, Robert Oostenveld % % $Log: triplot.m,v $ % Revision 1.7 2008/06/24 13:37:51 roboos % added option faces_blue % always return handle to objects that were plotted % % Revision 1.6 2007/01/03 17:00:35 roboos % updated documentation, changed layout of code and comments % % Revision 1.5 2006/09/19 16:11:35 roboos % added support for line segments, removed "axis equal" at end % % Revision 1.4 2006/05/02 19:15:28 roboos % added 'faces_red' style % % Revision 1.3 2004/06/28 07:51:39 roberto % improved documentation, added faces_skin % % Revision 1.2 2003/03/17 10:37:29 roberto % improved general help comments and added copyrights % % start with empty return values hs = []; hc = []; contour = []; % everything is added to the current figure holdflag = ishold; hold on % check the input variables if ~isempty(val) val = val(:); end if nargin<4 mode = 'surface'; end if isempty(tri) & ~strcmp(mode, 'nodes') % no triangulation was specified but a triangulation is needed if size(pnt,2)==2 % make a 2d triangulation of the points using delaunay tri = delaunay(pnt(:,1), pnt(:,2)); else % make a 2d triangulation of the projected points using delaunay prj = elproj(pnt); tri = delaunay(prj(:,1), prj(:,2)); end end if size(tri,2)==2 % lines are specified instead of triangles, convert to triangles tri(:,3) = tri(:,2); end if nargin<3 warning('only displaying triangle edges') mode='edges'; val = []; elseif nargin<4 % warning('default displaying surface') mode='surface'; elseif nargin<5 % determine contour levels if ~isempty(val) & ~iscell(val) absmax = max(abs([min(val) max(val)])); levels = linspace(-absmax,absmax,21); else levels = []; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute contours for 2D or 3D triangulation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(mode, 'contour') || strcmp(mode, 'contour_bw') || strcmp(mode, 'contour_rb') triangle_val = val(tri); triangle_min = min(triangle_val, [], 2); triangle_max = max(triangle_val, [], 2); for cnt_indx=1:length(levels) cnt = levels(cnt_indx); use = cnt>=triangle_min & cnt<=triangle_max; counter = 0; intersect1 = []; intersect2 = []; for tri_indx=find(use)' pos = pnt(tri(tri_indx,:), :); v(1) = triangle_val(tri_indx,1); v(2) = triangle_val(tri_indx,2); v(3) = triangle_val(tri_indx,3); la(1) = (cnt-v(1)) / (v(2)-v(1)); % abcissa between vertex 1 and 2 la(2) = (cnt-v(2)) / (v(3)-v(2)); % abcissa between vertex 2 and 3 la(3) = (cnt-v(3)) / (v(1)-v(3)); % abcissa between vertex 1 and 2 abc(1,:) = pos(1,:) + la(1) * (pos(2,:) - pos(1,:)); abc(2,:) = pos(2,:) + la(2) * (pos(3,:) - pos(2,:)); abc(3,:) = pos(3,:) + la(3) * (pos(1,:) - pos(3,:)); counter = counter + 1; sel = find(la>=0 & la<=1); intersect1(counter, :) = abc(sel(1),:); intersect2(counter, :) = abc(sel(2),:); end % remember the details for external reference contour(cnt_indx).level = cnt; contour(cnt_indx).n = counter; contour(cnt_indx).intersect1 = intersect1; contour(cnt_indx).intersect2 = intersect2; end % collect all different contourlevels for plotting intersect1 = []; intersect2 = []; cntlevel = []; for cnt_indx=1:length(levels) intersect1 = [intersect1; contour(cnt_indx).intersect1]; intersect2 = [intersect2; contour(cnt_indx).intersect2]; cntlevel = [cntlevel; ones(contour(cnt_indx).n,1) * levels(cnt_indx)]; end X = [intersect1(:,1) intersect2(:,1)]'; Y = [intersect1(:,2) intersect2(:,2)]'; C = [cntlevel(:) cntlevel(:)]'; if size(pnt,2)>2 Z = [intersect1(:,3) intersect2(:,3)]'; else Z = zeros(2, length(cntlevel)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % plot the desired detail %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch lower(mode) case 'faces' % plot the faces of the 2D or 3D triangulation hs = patch('Vertices', pnt, 'Faces', tri); set(hs, 'FaceColor', 'white'); set(hs, 'EdgeColor', 'none'); case 'faces_skin' % plot the faces of the 2D or 3D triangulation skin_surface = [255 213 119]/255; inner_skull_surface = [202 100 100]/255; cortex = [255 213 119]/255; hs = patch('Vertices', pnt, 'Faces', tri); set(hs, 'FaceColor', skin_surface); set(hs, 'EdgeColor', 'none'); lighting gouraud material shiny camlight case 'faces_red' % plot the faces of the 2D or 3D triangulation hs = patch('Vertices', pnt, 'Faces', tri); set(hs, 'FaceColor', [1 0 0]); set(hs, 'EdgeColor', 'none'); lighting gouraud material shiny camlight case 'faces_blue' % plot the faces of the 2D or 3D triangulation hs = patch('Vertices', pnt, 'Faces', tri); set(hs, 'FaceColor', [0 0 1]); set(hs, 'EdgeColor', 'none'); lighting gouraud material shiny camlight case 'face_index' % plot the triangle indices (numbers) at each face for face_indx=1:size(tri,1) str = sprintf('%d', face_indx); tri_x = (pnt(tri(face_indx,1), 1) + pnt(tri(face_indx,2), 1) + pnt(tri(face_indx,3), 1))/3; tri_y = (pnt(tri(face_indx,1), 2) + pnt(tri(face_indx,2), 2) + pnt(tri(face_indx,3), 2))/3; tri_z = (pnt(tri(face_indx,1), 3) + pnt(tri(face_indx,2), 3) + pnt(tri(face_indx,3), 3))/3; h = text(tri_x, tri_y, tri_z, str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle'); hs = [hs; h]; end case 'edges' % plot the edges of the 2D or 3D triangulation hs = patch('Vertices', pnt, 'Faces', tri); set(hs, 'FaceColor', 'none'); set(hs, 'EdgeColor', 'black'); case 'nodes' % plot the nodes (vertices) only as points if size(pnt, 2)==2 hs = plot(pnt(:,1), pnt(:,2), 'k.'); else hs = plot3(pnt(:,1), pnt(:,2), pnt(:,3), 'k.'); end case 'nodes_blue' % plot the nodes (vertices) only as points if size(pnt, 2)==2 hs = plot(pnt(:,1), pnt(:,2), 'b.', 'MarkerSize', 20); else hs = plot3(pnt(:,1), pnt(:,2), pnt(:,3), 'b.', 'MarkerSize', 20); end case 'nodes_red' % plot the nodes (vertices) only as points if size(pnt, 2)==2 hs = plot(pnt(:,1), pnt(:,2), 'r.', 'MarkerSize', 20); else hs = plot3(pnt(:,1), pnt(:,2), pnt(:,3), 'r.', 'MarkerSize', 20); end case 'node_index' % plot the vertex indices (numbers) at each node for node_indx=1:size(pnt,1) str = sprintf('%d', node_indx); if size(pnt, 2)==2 h = text(pnt(node_indx, 1), pnt(node_indx, 2), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle'); else h = text(pnt(node_indx, 1), pnt(node_indx, 2), pnt(node_indx, 3), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle'); end hs = [hs; h]; end case 'node_label' % plot the vertex indices (numbers) at each node for node_indx=1:size(pnt,1) str = val{node_indx}; if ~isempty(str) if size(pnt, 2)==2 h = text(pnt(node_indx, 1), pnt(node_indx, 2), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle'); else h = text(pnt(node_indx, 1), pnt(node_indx, 2), pnt(node_indx, 3), str, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle'); end else h = -1; end hs = [hs; h]; end case 'surface' % plot a 2D or 3D triangulated surface with linear interpolation if length(val)==size(pnt,1) hs = patch('Vertices', pnt, 'Faces', tri, 'FaceVertexCData', val, 'FaceColor', 'interp'); else hs = patch('Vertices', pnt, 'Faces', tri, 'CData', val, 'FaceColor', 'flat'); end set(hs, 'EdgeColor', 'none'); case 'contour_bw' % make black-white contours hc = []; for i=1:length(cntlevel) if cntlevel(i)>0 linestyle = '-'; linewidth = 1; elseif cntlevel(i)<0 linestyle = '--'; linewidth = 1; else linestyle = '-'; linewidth = 2; end h1 = patch('XData', X(:,i), 'Ydata', Y(:,i), ... 'ZData', Z(:,i), 'CData', C(:,i), ... 'facecolor','none','edgecolor','black', ... 'linestyle', linestyle, 'linewidth', linewidth, ... 'userdata',cntlevel(i)); hc = [hc; h1]; end case 'contour_rb' % make red-blue contours hc = []; for i=1:length(cntlevel) if cntlevel(i)>0 edgecolor = 'red'; elseif cntlevel(i)<0 edgecolor = 'blue'; else edgecolor = 'black'; end h1 = patch('XData', X(:,i), 'Ydata', Y(:,i), ... 'ZData', Z(:,i), 'CData', C(:,i), ... 'facecolor','none','edgecolor',edgecolor, ... 'linestyle', '-', 'linewidth', 3, ... 'userdata',cntlevel(i)); hc = [hc; h1]; end case 'contour' % make full-color contours hc = []; for i=1:length(cntlevel) h1 = patch('XData', X(:,i), 'Ydata', Y(:,i), ... 'ZData', Z(:,i), 'CData', C(:,i), ... 'facecolor','none','edgecolor','flat',... 'userdata',cntlevel(i)); hc = [hc; h1]; end end % switch axis off axis vis3d axis equal if nargout==0 clear contour hc hs end if ~holdflag hold off end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [proj] = elproj(pos, method); % ELPROJ makes a azimuthal projection of a 3D electrode cloud % on a plane tangent to the sphere fitted through the electrodes % the projection is along the z-axis % % [proj] = elproj([x, y, z], 'method'); % % Method should be one of these: % 'gnomic' % 'stereographic' % 'ortographic' % 'inverse' % 'polar' % % Imagine a plane being placed against (tangent to) a globe. If % a light source inside the globe projects the graticule onto % the plane the result would be a planar, or azimuthal, map % projection. If the imaginary light is inside the globe a Gnomonic % projection results, if the light is antipodal a Sterographic, % and if at infinity, an Orthographic. % % The default projection is a polar projection (BESA like). % An inverse projection is the opposite of the default polar projection. % Copyright (C) 2000-2008, Robert Oostenveld % % $Log: elproj.m,v $ % Revision 1.4 2008/05/15 10:54:24 roboos % updated documentation % % Revision 1.3 2007/03/20 10:29:35 roboos % renamed method 'default' into 'polar' % % Revision 1.2 2003/03/17 10:37:28 roberto % improved general help comments and added copyrights % x = pos(:,1); y = pos(:,2); if size(pos, 2)==3 z = pos(:,3); end if nargin<2 method='polar'; end if nargin<3 secant=1; end if strcmp(method, 'orthographic') % this method compresses the lowest electrodes very much % electrodes on the bottom half of the sphere are folded inwards xp = x; yp = y; num = length(find(z<0)); str = sprintf('%d electrodes may be folded inwards in orthographic projection\n', num); if num warning(str); end proj = [xp yp]; elseif strcmp(method, 'gnomic') % the lightsource is in the middle of the sphere % electrodes on the equator are projected at infinity % electrodes below the equator are not projected at all rad = mean(sqrt(x.^2 + y.^2 + z.^2)); phi = cart2pol(x, y); th = atan(sqrt(x.^2 + y.^2) ./ z); xp = cos(phi) .* tan(th) .* rad; yp = sin(phi) .* tan(th) .* rad; num = length(find(th==pi/2 | z<0)); str = sprintf('removing %d electrodes from gnomic projection\n', num); if num warning(str); end xp(find(th==pi/2 | z<0)) = NaN; yp(find(th==pi/2 | z<0)) = NaN; proj = [xp yp]; elseif strcmp(method, 'stereographic') % the lightsource is antipodal (on the south-pole) rad = mean(sqrt(x.^2 + y.^2 + z.^2)); z = z + rad; phi = cart2pol(x, y); th = atan(sqrt(x.^2 + y.^2) ./ z); xp = cos(phi) .* tan(th) .* rad * 2; yp = sin(phi) .* tan(th) .* rad * 2; num = length(find(th==pi/2 | z<0)); str = sprintf('removing %d electrodes from stereographic projection\n', num); if num warning(str); end xp(find(th==pi/2 | z<0)) = NaN; yp(find(th==pi/2 | z<0)) = NaN; proj = [xp yp]; elseif strcmp(method, 'inverse') % compute the inverse projection of the default angular projection [th, r] = cart2pol(x, y); [xi, yi, zi] = sph2cart(th, pi/2 - r, 1); proj = [xi, yi, zi]; else % use default angular projection [az, el, r] = cart2sph(x, y, z); [x, y] = pol2cart(az, pi/2 - el); proj = [x, y]; end
github
lcnbeapp/beapp-master
hcluster.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/icasso/hcluster.m
3,513
utf_8
4f1454878c289ef16d6355f9b24353ce
function [P,Z,order]=hcluster(D,link) %function [P,Z,order] = hcluster(D,link) % %PURPOSE % %To perform a hierarchical agglomerative clustering on a distance %matrix. Returns partition vectors for each level of the clustering %hierarchy and information for visualizing the clustering hierarchy %as a dendrogram. % %INPUT % % D (MxM matrix) distance matrix % link (string) agglomeration strategy, (linkage) % 'al' or 'average' (group average link.) % 'sl' or 'single', (nearest neighbor link.) % 'cl' or 'complete' (furthest neighbor link.) %OUTPUT % % P (NxN matrix) contains the partitions on each level of the % dendrogram (partition vectors) % Z,order arguments returned by som_linkage. Needed for % drawing dendrogram with function % som_dendrogram. See also som_linkage. % %DETAILS % %A partition vector p represents division of objects into clusters, %p(i) is the number of cluster that object i belongs to. Cluster %numbers must be integers 1,2,...,k where k is the number of clusters. % %Function hcluster clusters hierarchically N objects according to an NxN %dissimilarity matrix D. D(i,j) is the distance between objects i %and j. The function applies a hierarchical agglomerative %clustering (single, complete, or group average linkage). It %returns matrix P (of size NxN) where each row is a partition %vector. The partition vectors present the clustering of the %objects on each level L=1,...,N of the dendrogram. Let c=P(L,i); %Now, c is the cluster that object i belongs to at level L. On each %row P(L,:), cluster labels are integers 1,2,...,L. % %Note, that the cluster labels cannot be compared over %partitions. The same cluster may appear at different level(s) but %it does not necessarily have the same label in every partition %vector P(L,:). % %SEE ALSO % som_linkage % som_dendrogram % icassoCluster %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.21 johan 040305 switch lower(link), case 'al' link='average'; % Change Icasso name to SOM Toolbox name case 'cl' link='complete';% Change Icasso name to SOM Toolbox name case 'sl' link='single'; % Change Icasso name to SOM Toolbox name end N=size(D,1); [Z,order]=som_linkage(ones(N,1),'linkage',link,'dist',D); P=Z2partition(Z); function partition=Z2partition(Z) % % function partition=Z2partition(Z) % % Recode SOM Toolbox presentation for hierachical clustering (Z) % into partition vectors(s) N=size(Z,1)+1; C=zeros(N); C(1,:)=1:N; for i=2:N, C(i,:)=C(i-1,:); C(i,(Z(i-1,1)==C(i,:))|(Z(i-1,2)==C(i,:)))=N-1+i; end for i=1:size(C,1), [u,tmp,newindex]=unique(C(i,:)); C(i,:)=newindex(:)'; end partition=C(end:-1:1,:);
github
lcnbeapp/beapp-master
cca.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/icasso/cca.m
8,088
utf_8
b5659dc842e6c1fde35175caed2d8ea2
function [P] = cca(D, P, epochs, Mdist, alpha0, lambda0) %CCA Projects data vectors using Curvilinear Component Analysis. % % P = cca(D, P, epochs, [Dist], [alpha0], [lambda0]) % % P = cca(D,2,10); % projects the given data to a plane % P = cca(D,pcaproj(D,2),5); % same, but with PCA initialization % P = cca(D, 2, 10, Dist); % same, but the given distance matrix is used % % Input and output arguments ([]'s are optional): % D (matrix) the data matrix, size dlen x dim % (struct) data or map struct % P (scalar) output dimension % (matrix) size dlen x odim, the initial projection % epochs (scalar) training length % [Dist] (matrix) pairwise distance matrix, size dlen x dlen. % If the distances in the input space should % be calculated otherwise than as euclidian % distances, the distance from each vector % to each other vector can be given here, % size dlen x dlen. For example PDIST % function can be used to calculate the % distances: Dist = squareform(pdist(D,'mahal')); % [alpha0] (scalar) initial step size, 0.5 by default % [lambda0] (scalar) initial radius of influence, 3*max(std(D)) by default % % P (matrix) size dlen x odim, the projections % % Unknown values (NaN's) in the data: projections of vectors with % unknown components tend to drift towards the center of the % projection distribution. Projections of totally unknown vectors are % set to unknown (NaN). % % See also SAMMON, PCAPROJ. % Reference: Demartines, P., Herault, J., "Curvilinear Component % Analysis: a Self-Organizing Neural Network for Nonlinear % Mapping of Data Sets", IEEE Transactions on Neural Networks, % vol 8, no 1, 1997, pp. 148-154. % Contributed to SOM Toolbox 2.0, February 2nd, 2000 by Juha Vesanto % Copyright (c) by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % juuso 171297 040100 % johan 170305: cca used error as a variable name which caused a % warning, changed to error_ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Check arguments error(nargchk(3, 6, nargin)); % check the number of input arguments % input data if isstruct(D), if strcmp(D.type,'som_map'), D = D.codebook; else D = D.data; end end [noc dim] = size(D); noc_x_1 = ones(noc, 1); % used frequently me = zeros(1,dim); st = zeros(1,dim); for i=1:dim, me(i) = mean(D(find(isfinite(D(:,i))),i)); st(i) = std(D(find(isfinite(D(:,i))),i)); end % initial projection if prod(size(P))==1, P = (2*rand(noc,P)-1).*st(noc_x_1,1:P) + me(noc_x_1,1:P); else % replace unknown projections with known values inds = find(isnan(P)); P(inds) = rand(size(inds)); end [dummy odim] = size(P); odim_x_1 = ones(odim, 1); % this is used frequently % training length train_len = epochs*noc; % random sample order rand('state',sum(100*clock)); sample_inds = ceil(noc*rand(train_len,1)); % mutual distances if nargin<4 | isempty(Mdist) | all(isnan(Mdist(:))), fprintf(2, 'computing mutual distances\r'); dim_x_1 = ones(dim,1); for i = 1:noc, x = D(i,:); Diff = D - x(noc_x_1,:); N = isnan(Diff); Diff(find(N)) = 0; Mdist(:,i) = sqrt((Diff.^2)*dim_x_1); N = find(sum(N')==dim); %mutual distance unknown if ~isempty(N), Mdist(N,i) = NaN; end end else % if the distance matrix is output from PDIST function if size(Mdist,1)==1, Mdist = squareform(Mdist); end if size(Mdist,1)~=noc, error('Mutual distance matrix size and data set size do not match'); end end % alpha and lambda if nargin<5 | isempty(alpha0) | isnan(alpha0), alpha0 = 0.5; end alpha = potency_curve(alpha0,alpha0/100,train_len); if nargin<6 | isempty(lambda0) | isnan(lambda0), lambda0 = max(st)*3; end lambda = potency_curve(lambda0,0.01,train_len); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Action k=0; fprintf(2, 'iterating: %d / %d epochs\r',k,epochs); for i=1:train_len, ind = sample_inds(i); % sample index dx = Mdist(:,ind); % mutual distances in input space known = find(~isnan(dx)); % known distances if ~isempty(known), % sample vector's projection y = P(ind,:); % distances in output space Dy = P(known,:) - y(noc_x_1(known),:); dy = sqrt((Dy.^2)*odim_x_1); % relative effect dy(find(dy==0)) = 1; % to get rid of div-by-zero's fy = exp(-dy/lambda(i)) .* (dx(known) ./ dy - 1); % Note that the function F here is e^(-dy/lambda)) % instead of the bubble function 1(lambda-dy) used in the % paper. % Note that here a simplification has been made: the derivatives of the % F function have been ignored in calculating the gradient of error % function w.r.t. to changes in dy. % update P(known,:) = P(known,:) + alpha(i)*fy(:,odim_x_1).*Dy; end % track if rem(i,noc)==0, k=k+1; fprintf(2, 'iterating: %d / %d epochs\r',k,epochs); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% clear up % calculate error error_ = cca_error(P,Mdist,lambda(train_len)); fprintf(2,'%d iterations, error %f \n', epochs, error_); % set projections of totally unknown vectors as unknown unknown = find(sum(isnan(D)')==dim); P(unknown,:) = NaN; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% tips % to plot the results, use the code below %subplot(2,1,1), %switch(odim), % case 1, plot(P(:,1),ones(dlen,1),'x') % case 2, plot(P(:,1),P(:,2),'x'); % otherwise, plot3(P(:,1),P(:,2),P(:,3),'x'); rotate3d on %end %subplot(2,1,2), dydxplot(P,Mdist); % to a project a new point x in the input space to the output space % do the following: % Diff = D - x(noc_x_1,:); Diff(find(isnan(Diff))) = 0; % dx = sqrt((Diff.^2)*dim_x_1); % p = project_point(P,x,dx); % this function can be found from below % tlen = size(p,1); % plot(P(:,1),P(:,2),'bx',p(tlen,1),p(tlen,2),'ro',p(:,1),p(:,2),'r-') % similar trick can be made to the other direction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function vals = potency_curve(v0,vn,l) % curve that decreases from v0 to vn with a rate that is % somewhere between linear and 1/t vals = v0 * (vn/v0).^([0:(l-1)]/(l-1)); function error_ = cca_error(P,Mdist,lambda) [noc odim] = size(P); noc_x_1 = ones(noc,1); odim_x_1 = ones(odim,1); error_ = 0; for i=1:noc, known = find(~isnan(Mdist(:,i))); if ~isempty(known), y = P(i,:); Dy = P(known,:) - y(noc_x_1(known),:); dy = sqrt((Dy.^2)*odim_x_1); fy = exp(-dy/lambda); error_ = error_ + sum(((Mdist(known,i) - dy).^2).*fy); end end error_ = error_/2; function [] = dydxplot(P,Mdist) [noc odim] = size(P); noc_x_1 = ones(noc,1); odim_x_1 = ones(odim,1); Pdist = zeros(noc,noc); for i=1:noc, y = P(i,:); Dy = P - y(noc_x_1,:); Pdist(:,i) = sqrt((Dy.^2)*odim_x_1); end Pdist = tril(Pdist,-1); inds = find(Pdist > 0); n = length(inds); plot(Pdist(inds),Mdist(inds),'.'); xlabel('dy'), ylabel('dx') function p = project_point(P,x,dx) [noc odim] = size(P); noc_x_1 = ones(noc,1); odim_x_1 = ones(odim,1); % initial projection [dummy,i] = min(dx); y = P(i,:)+rand(1,odim)*norm(P(i,:))/20; % lambda lambda = norm(std(P)); % termination eps = 1e-3; i_max = noc*10; i=1; p(i,:) = y; ready = 0; while ~ready, % mutual distances Dy = P - y(noc_x_1,:); % differences in output space dy = sqrt((Dy.^2)*odim_x_1); % distances in output space f = exp(-dy/lambda); fprintf(2,'iteration %d, error %g \r',i,sum(((dx - dy).^2).*f)); % all the other vectors push the projected one fy = f .* (dx ./ dy - 1) / sum(f); % update step = - sum(fy(:,odim_x_1).*Dy); y = y + step; i=i+1; p(i,:) = y; ready = (norm(step)/norm(y) < eps | i > i_max); end fprintf(2,'\n');
github
lcnbeapp/beapp-master
icassoEst.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/icasso/icassoEst.m
8,817
utf_8
adb9102f63b02f7a42b3da5bdcf803ae
function sR=icassoEst(mode,X,M,varargin) %function sR=icassoEst(mode,X,M,['FastICAparamName1',value1,'FastICAparamName2',value2,...]) % %PURPOSE % %To compute randomized ICA estimates M times from data X. Output of %this function (sR) is called 'Icasso result structure' (see %icassoStruct). sR keeps the on all the methods, parameters, and %results in the Icasso procedure. % %EXAMPLES OF BASIC USAGE % % sR=icassoEst('randinit', X, 30); % %estimates ICA for 30 times on data matrix X using Icasso %default parameters for FastICA: symmetrical approach, kurtosis as %contrast function. In maximum 100 iterations are used for %estimating ICA in each round. Randomizes only initial conditions. % % sR=icassoEst('both', X, 30, 'g', 'tanh', 'approach', 'defl'); % %estimates ICA for 15 times on data matrix X using 'tanh' as the %contrast function and the deflatory approach in FastICA. Applies %both bootstrapping the data and randomizing initial conditions. % %INPUT % % mode (string) 'randinit' | 'bootstrap | 'both' % X (dxN matrix) data where d=dimension, N=number of vectors % M (scalar) number of randomizations (estimation cycles) % %Optional input arguments are given as argument identifier - value %pairs: 'identifier1', value1, 'identifier2', value2,... %(case insensitive) % %FastICA parameters apply here (see function fastica) %Default: 'approach', 'symm', 'g', 'pow3', 'maxNumIterations', 100 % %OUTPUTS % % sR (struct) Icasso result data structure % %DETAILS % %Meaning of different choices for input arg. 'mode' % 'randinit': different random initial condition each time. % 'bootstrap': the same initial cond. each time, but data is % bootstrapped. The initial condition can be explicitly % specified using FastICA parameter 'initGuess'. % 'both': use both data bootstrapping and randomization of % initial condition. % %FASTICA PARAMETERS See function 'fastica' in FastICA toolbox for %more information. Note that the following FastICA parameters %cannot be used: % % In all modes ('randinit','bootstrap','both'): % using 'interactivePCA','sampleSize', 'displayMode', 'displayInterval', % and 'only' are not allowed for obvious reasons. In addition, % in modes 'randinit' and 'both': % using 'initGuess' is not allowed since initial guess is % randomized, and % in modes 'bootstrap' and 'both': % using 'whiteMat', 'dewhiteMat', and 'whiteSig' are not allowed % since they need to be computed for each bootstrap sample % individually. % %ESTIMATE INDEXING CONVENTION: when function icassoEst is run %each estimate gets a unique, integer label in order of %appearance. The same order and indexing is used throughout the %Icasso software. In many functions, one can pick a subset of %estimates sR by giving vector whose elements refers to this unique %label. % %SEE ALSO % icasso % fastica % icassoStruct % icassoExp % icassoGet % icassoShow % icassoResult % %When icassoEst is accomplished, use icassoExp to obtain clustering %results and to store them in sR After this, the results can be %examined visually using icassoShow. Results and other information %an be finally retrieved also by functions icassoResult and icassoGet. %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.1 johan 210704 % Set the Icasso struct sR=icassoStruct(X); % Check compulsatory input arguments if nargin<3, error('At least three input args. required'); end %% Check mode. mode=lower(mode); switch mode case {'randinit','bootstrap','both'} ; otherwise error(['Randomization mode must be ''randinit'', ''bootstrap'' or' ... ' ''both''.']); end sR.mode=mode; %% Set some values num_of_args=length(varargin); whitening='not done'; %% Default values for some FastICA options fasticaoptions={'g','pow3','approach','symm',... 'maxNumIterations',100}; %% flag: initial conditions given (default: not given) isInitGuess=0; %% flag: elements for whitening given (default: not given) isWhitesig=0; isWhitemat=0; isDewhitemat=0; %% Check varargin & set defaults fasticaoptions=processvarargin(varargin,fasticaoptions); num_of_args=length(fasticaoptions); %% Check fasticaoptions: i=1; while i<num_of_args, switch fasticaoptions{i} case {'approach','firstEig','lastEig','numOfIC','finetune','mu','g','a1','a2',... 'stabilization','epsilon','maxNumIterations','maxFinetune','verbose',... 'pcaE','pcaD'} ; % these are ok %% Get explicit whitening if given & update flags; note that the %% arguments are dropped away from fasticaoptions to avoid %% duplicate storage in Icasso result struct & in FastICA input case 'whiteSig' w=fasticaoptions{i+1}; isWhitesig=1; fasticaoptions(i:i+1)=[]; i=i-2; num_of_args=num_of_args-2; case 'whiteMat' White=fasticaoptions{i+1}; isWhitemat=1; fasticaoptions(i:i+1)=[]; i=i-2; num_of_args=num_of_args-2; case 'dewhiteMat' deWhite=fasticaoptions{i+1}; isDewhitemat=1; fasticaoptions(i:i+1)=[]; i=i-2; num_of_args=num_of_args-2; case {'sampleSize','displayMode','displayInterval','only','interactivePCA'} error(['You are not allowed to set FastICA option ''' fasticaoptions{i} ''' in Icasso.']); % initGuess depends on mode case 'initGuess' switch mode case {'randinit','both'} error(['FastICA option ''initGuess'' cannot be used in sampling mode ''' ... mode '''.']); case 'bootstrap' isInitGuess=1; otherwise error('Internal error!?'); end otherwise error(['Doesn''t recognize FastICA option ''' fasticaoptions{i} '''.']); end % add counter i=i+2; end %% Whitening: %% Check if some of whitening arguments have been given: if (isWhitesig | isWhitemat | isDewhitemat), %% both/bootstrap use each time different whitening... better to %% give error if (strcmp(mode,'bootstrap') | strcmp(mode,'both')), error(['FastICA options ''whiteSig'',''whiteMat'',''dewhiteMat'' cannot be' ... ' used in modes ''bootstrap'' and ''both''.']); end %% FastICA expects that all of the three arguments are given (see %help fastica): if not, error if isWhitesig & isWhitemat & isDewhitemat, disp('Using user specified whitening.'); else error(['To prewhiten, each of ''whiteSig'',''whiteMat'',''dewhiteMat'' have to' ... ' be given (see help fastica)']); end else % compute whitening for original data [w,White,deWhite]=fastica(X,'only','white',fasticaoptions{:}); end % store whitening for original data: sR.whiteningMatrix=White; sR.dewhiteningMatrix=deWhite; % Icasso uses the same random initial condition for every sample in % 'bootstrap'. It has to be computed if not given!! if strcmp(mode,'bootstrap') & ~isInitGuess, warning(sprintf('\n\n%s\n\n',['Initial guess not given for mode ''bootstrap'': I will' ... ' set a (fixed) random initial condition'])); % Randomize init conditions and add to fastica options: this % keeps it fixed in every estimation round. fasticaoptions{end+1}='initGuess'; fasticaoptions{end+1}=rand(size(White'))-.5; end % store options (except whitening which is % stored separately) sR.fasticaoptions=fasticaoptions; %% Compute N times FastICA k=0; index=[]; for i=1:M, %clc; fprintf('\n\n%s\n\n',['Randomization using FastICA: Round ' num2str(i) '/' ... num2str(M)]); switch mode case 'randinit' % data is fixed; X_=X; case {'bootstrap','both'} % Bootstrap and compute whitening for _bootstrapped_ data X_=bootstrap(X); [w,White,deWhite]=fastica(X_,'only','white',fasticaoptions{:}); otherwise error('Internal error?!'); end % Estimate FastICA set displayMode off [dummy,A_,W_]=fastica(X_,fasticaoptions{:},... 'whiteMat',White,'dewhiteMat',deWhite,'whiteSig',w,... 'sampleSize',1,'displayMode','off'); % Store results if any n=size(A_,2); if n>0, k=k+1; sR.index(end+1:end+n,:)=[repmat(k,n,1), [1:n]']; sR.A{k}=A_; sR.W{k}=W_; end end function X=bootstrap(X) N=size(X,2); index=round(rand(N,1)*N+.5); X=X(:,index);
github
lcnbeapp/beapp-master
icassoStruct.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/icasso/icassoStruct.m
8,190
utf_8
d80e7670415d1867f114b16bebb620f6
function sR=icassoStruct(X) %function sR=icassoStruct([X]) % %PURPOSE % %To initiate an Icasso result data structure which is meant for %storing and keeping organized all data, parameters and results %when performing the Icasso procedure. % %EXAMPLE OF BASIC USAGE % % S=icassoStruct(X); % %creates an Icasso result structure in workspace variable S. Its %fields are initially empty except field .signal that contains %matrix X. % %INPUT % %[An argument in brackets is optional. If it isn't given or it's % an empty matrix/string, the function will use a default value.] % %[X] (dxN matrix) the original data (signals) consisting of N % d-dimensional vectors. Icasso centers the data (removes the % sample mean from it) and stores it in field .signal. % If the input argument is not given, or it is empty, % the field is left empty. % %OUTPUT % % sR (struct) Icasso result structure that contains fields % % .mode (string) % .signal (matrix) % .index (matrix) % .fasticaoptions (cell array) % .A (cell array) % .W (cell array) % .whiteningMatrix (matrix) % .dewhiteningMatrix (matrix) % .cluster (struct) % .projection (struct) % %DETAILS % %The following table presents the fields of Icasso result %structure. Icasso is a sequential procedure that is split into %several phases (functions). The table shows the order in which %the fields are computed, the function that is used to change the %parameters/results in the field, and lastly the phases that %the result depends on. % %P=parameter that may be a explicit user input or a default parameter %set by Icasso % %Phase Field Function depends on field(s) % %(1) .mode icassoEst P %(1) .signal icassoEst P %(1) .index icassoEst (ICA results) %(1) .fasticaoptions icassoEst P %(1) .A icassoEst (ICA results) %(1a) .W icassoEst (ICA results) %(1) .whiteningMatrix icassoEst (ICA results) %(1b) .dewhiteningMatrix icassoEst (ICA results) % %(2a) .cluster.simfcn icassoCluster P %(2b) .cluster.similarity icassoCluster 1a,1b,2a %(2c) .cluster.s2d icassoCluster P %(2d) .cluster.strategy icassoCluster P %(2e) .cluster.partition icassoCluster 2b-d %(2f) .cluster.dendrogram icassoCluster 2b-d %(2g) .cluster.index.R icassoCluster 2b,2c,2e % %(3a) .projection.method icassoProjection P %(3b) .projection.parameters icassoProjection P %(3c) .projection.coordinates icassoProjection 2b,3a-b % %icasso performs the whole process with default parameters %icassoEst performs phase 1 %icassoExp performs phases 2-3 with default parameters. % %(1) Data, ICA parameters, and estimation results % % .mode (string) % type of randomization ('bootstrap'|'randinit'|'both') % % .signal (dxN matrix) % the original data (signal) X (centered) where N is % the number of samples and d the dimension % % .index (Mx2 matrix) % the left column is the number of the estimation cycle, the % right one is the number of the estimate on that cycle. % See also function: icassoGet % %The following fields contain parameters and results of the ICA %estimation using FastICA toolbox. More information can be found, %e.g., from of function fastica in FastICA toolbox. % % .fasticaoptions (cell array) % contains the options that FastICA uses in estimation. % % .A (cell array of matrices) % contains mixing matrices from each estimation cycle % % .W (cell array of matrices) % contains demixing matrices from each estimation cycle % % .whiteningMatrix (matrix) % whitening matrix for original data (sR.signal) % % .dewhiteningMatrix (matrix) % dewhitening matrix for original data (sR.signal). % %(2) Mutual similarities and clustering % %Parameters and results of % -computing similarities S between the estimates, and % -clustering the estimates %are stored in field .cluster which has the following subfields: % % .cluster.simfcn (string) % a string option for function icassoCluster % (icassoSimilarity); it tells how the mutual similarities % between estimates are computed. % % .cluster.similarity (MxM matrix) % mutual similarities between estimates. % % .cluster.s2d (string) % before clustering and computing the clustering validity index % the similarity matrix S stored in .cluster.similarity is % transformed into a dissimilarity matrix. This string is the % name of the subfunction that makes the transformation: there % is a function call % D=feval(sR.cluster.s2d,sR.cluster.similarity); % inside icassoCluster. Note that the dissimilarity matrix % is not stored in the Icasso result data struct. % % .cluster.strategy (string) % strategy that was used for hierarchical clustering which is % done on dissimilarities D % .cluster.partition (MxM matrix) % stores the partitions resulting clustering. Each row % partition(i,:), represents a division of M objects into K(i) % clusters (classes). On each row, clusters must be labeled % with integers 1,2,...,K(i), where K(i) is the number of % clusters that may be different on each row Example: % partition=[[1 2 3 4];[1 1 1 1];[1 1 2 2]] gives three % different partitions where partition(1,:) means every object % being in its own clusters; partition(2,:) means all objects % being in a single cluster, and in partition(3,:) objects 1&2 % belong to cluster 1 and 3&4 to cluster 2. % % .cluster.dendrogram.Z and .cluster.dendrogram.order % stores information needed for drawing dendrogram and % similarity matrix visualizations. More details in function % som_linkage % %The following subfields of .cluster contain heuristic validity %scores for the partitions in .cluster.partition. If the score is %NaN it means that the validity has not been (or can't be) %computed. % % .cluster.index.R (Mx1 vector) % computed by subfunction rindex % %(3) Projection for visualization % %Parameters for performing the visualization projection are results %of the projection can be found in field .projection. % % .projection has the following subfields: % % .projection.method (string) % projection method used in icassoProjection % % .projection.parameters (cell array) % contains parameters used in icassoProjection % % .coordinates (Mx2 matrix) % contains the coordinates of the projected estimates % %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.2 johan 100105 if nargin<1|isempty(X), X=[]; else X=remmean(X); end sR.mode=[]; sR.signal=X; sR.index=[]; sR.fasticaoptions=[]; sR.A=[]; sR.W=[]; sR.whiteningMatrix=[]; sR.dewhiteningMatrix=[]; sR.cluster=initClusterStruct; sR.projection=initProjectionStruct; function cluster=initClusterStruct cluster.simfcn=[]; cluster.similarity=[]; cluster.s2d=[]; cluster.strategy=[]; cluster.partition=[]; cluster.dendrogram.Z=[]; cluster.dendrogram.order=[]; cluster.index.R=[]; function projection=initProjectionStruct projection.method=[]; projection.parameters=[]; projection.coordinates=[];
github
lcnbeapp/beapp-master
som_dendrogram.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/icasso/som_dendrogram.m
9,039
utf_8
43f32770e95d19d4a12855bd8bfb91f3
function [h,Coord,Color,height] = som_dendrogram(Z,varargin) %SOM_DENDROGRAM Visualize a dendrogram. % % [h,Coord,Color,height] = som_dendrogram(Z, [[argID,] value, ...]) % % Z = som_linkage(sM); % som_dendrogram(Z); % som_dendrogram(Z,sM); % som_dendrogram(Z,'coord',co); % % Input and output arguments ([]'s are optional): % h (vector) handle to the arc lines % Z (matrix) size n-1 x 1, the hierarchical cluster matrix % returned by functions like LINKAGE and SOM_LINKAGE % n is the number of original data samples. % [argID, (string) See below. The values which are unambiguous can % value] (varies) be given without the preceeding argID. % Coord (matrix) size 2*n-1 x {1,2}, the coordinates of the % original data samples and cluster nodes used % in the visualization % Color (matrix) size 2*n-1 x 3, the colors of ... % height (vector) size 2*n-1 x 1, the heights of ... % % Here are the valid argument IDs and corresponding values. The values % which are unambiguous (marked with '*') can be given without the % preceeding argID. % 'data' *(struct) map or data struct: many other optional % arguments require this % (matrix) data matrix % 'coord' (matrix) size n x 1 or n x 2, the coordinates of % the original data samples either in 1D or 2D % (matrix) size 2*n-1 x {1,2}, the coordinates of both % original data samples and each cluster % *(string) 'SOM', 'pca#', 'sammon#', or 'cca#': the coordinates % are calculated using the given data and the % required projection algorithm. The '#' at the % end of projection algorithms refers to the % desired output dimension and can be either 1 or 2 % (2 by default). In case of 'SOM', the unit % coordinates (given by SOM_VIS_COORDS) are used. % 'color' (matrix) size n x 3, the color of the original data samples % (matrix) size 2*n-1 x 3, the colors of both original % data samples and each cluster % (string) color specification, e.g. 'r.', used for each node % 'height' (vector) size n-1 x 1, the heights used for each cluster % (vector) size 2*n-1 x 1, the heights used for both original % data samples and each cluster % *(string) 'order', the order of combination determines height % 'depth', the depth at which the combination % happens determines height % 'linecolor' (string) color specification for the arc color, 'k' by default % (vector) size 1 x 3 % % See also SOM_LINKAGE, DENDROGRAM. % Copyright (c) 2000 by Juha Vesanto % Contributed to SOM Toolbox on June 16th, 2000 by Juha Vesanto % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta juuso 160600 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% read the arguments % Z nd = size(Z,1)+1; nc = size(Z,1); % varargin Coordtype = 'natural'; Coord = []; codim = 1; Colortype = 'none'; Color = []; height = [zeros(nd,1); Z(:,3)]; M = []; linecol = 'k'; i=1; while i<=length(varargin), argok = 1; if ischar(varargin{i}), switch varargin{i}, case 'data', i = i + 1; M = varargin{i}; case 'coord', i=i+1; if isnumeric(varargin{i}), Coord = varargin{i}; Coordtype = 'given'; else if strcmp(varargin{i},'SOM'), Coordtype = 'SOM'; else Coordtype = 'projection'; Coord = varargin{i}; end end case 'color', i=i+1; if isempty(varargin{i}), Colortype = 'none'; elseif ischar(varargin{i}), Colortype = 'colorspec'; Color = varargin{i}; else Colortype = 'given'; Color = varargin{i}; end case 'height', i=i+1; height = varargin{i}; case 'linecolor', i=i+1; linecol = varargin{i}; case 'SOM', Coordtype = 'SOM'; case {'pca','pca1','pca2','sammon','sammon1','sammon2','cca','cca1','cca2'}, Coordtype = 'projection'; Coord = varargin{i}; case {'order','depth'}, height = varargin{i}; end elseif isstruct(varargin{i}), M = varargin{i}; else argok = 0; end if ~argok, disp(['(som_dendrogram) Ignoring invalid argument #' num2str(i+1)]); end i = i+1; end switch Coordtype, case 'SOM', if isempty(M) | ~any(strcmp(M.type,{'som_map','som_topol'})) , error('Cannot determine SOM coordinates without a SOM.'); end if strcmp(M.type,'som_map'), M = M.topol; end case 'projection', if isempty(M), error('Cannot do projection without the data.'); end if isstruct(M), if strcmp(M.type,'som_data'), M = M.data; elseif strcmp(M.type,'som_map'), M = M.codebook; end end if size(M,1) ~= nd, error('Given data must be equal in length to the number of original data samples.') end case 'given', if size(Coord,1) ~= nd & size(Coord,1) ~= nd+nc, error('Size of given coordinate matrix does not match the cluster hierarchy.'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% initialization % Coordinates switch Coordtype, case 'natural', o = leavesorder(Z)'; [dummy,Coord] = sort(o); codim = 1; case 'SOM', Coord = som_vis_coords(M.lattice,M.msize); codim = 2; case 'projection', switch Coord, case {'pca','pca2'}, Coord = pcaproj(M,2); codim = 2; case 'pca1', Coord = pcaproj(M,1); codim = 1; case {'cca','cca2'}, Coord = cca(M,2,20); codim = 2; case 'cca1', Coord = cca(M,1,20); codim = 1; case {'sammon','sammon2'}, Coord = sammon(M,2,50); codim = 2; case 'sammon1', Coord = sammon(M,1,50); codim = 1; end case 'given', codim = min(size(Coord,2),2); % nill end if size(Coord,1) == nd, Coord = [Coord; zeros(nc,size(Coord,2))]; for i=(nd+1):(nd+nc), leaves = leafnodes(Z,i,nd); if any(leaves), Coord(i,:) = mean(Coord(leaves,:),1); else Coord(i,:) = Inf; end end end % Colors switch Colortype, case 'colorspec', % nill case 'none', Color = ''; case 'given', if size(Color,1) == nd, Color = [Color; zeros(nc,3)]; for i=(nd+1):(nd+nc), leaves = leafnodes(Z,i,nd); if any(leaves), Color(i,:) = mean(Color(leaves,:),1); else Color(i,:) = 0.8; end end end end % height if ischar(height), switch height, case 'order', height = [zeros(nd,1); [1:nc]']; case 'depth', height = nodedepth(Z); height = max(height) - height; end else if length(height)==nc, height = [zeros(nd,1); height]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% draw % the arcs lfrom = []; lto = []; for i=1:nd+nc, if i<=nd, ch = []; elseif ~isfinite(Z(i-nd,3)), ch = []; else ch = Z(i-nd,1:2)'; end if any(ch), lfrom = [lfrom; i*ones(length(ch),1)]; lto = [lto; ch]; end end % the coordinates of the arcs if codim == 1, Lx = [Coord(lfrom), Coord(lto), Coord(lto)]; Ly = [height(lfrom), height(lfrom), height(lto)]; Lz = []; else Lx = [Coord(lfrom,1), Coord(lto,1), Coord(lto,1)]; Ly = [Coord(lfrom,2), Coord(lto,2), Coord(lto,2)]; Lz = [height(lfrom), height(lfrom), height(lto)]; end washold = ishold; if ~washold, cla; end % plot the lines if isempty(Lz), h = line(Lx',Ly','color',linecol); else h = line(Lx',Ly',Lz','color',linecol); if ~washold, view(3); end rotate3d on end % plot the nodes hold on switch Colortype, case 'none', % nill case 'colorspec', if codim == 1, plot(Coord,height,Color); else plot3(Coord(:,1), Coord(:,2), height, Color); end case 'given', som_grid('rect',[nd+nc 1],'line','none','Coord',[Coord, height],... 'Markersize',10,'Markercolor',Color); end if ~washold, hold off, end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% subfunctions function depth = nodedepth(Z) nd = size(Z,1)+1; nc = size(Z,1); depth = zeros(nd+nc,1); ch = nc+nd-1; while any(ch), c = ch(1); ch = ch(2:end); if c>nd & isfinite(Z(c-nd,3)), chc = Z(c-nd,1:2); depth(chc) = depth(c) + 1; ch = [ch, chc]; end end return; function inds = leafnodes(Z,i,nd) inds = []; ch = i; while any(ch), c = ch(1); ch = ch(2:end); if c>nd & isfinite(Z(c-nd,3)), ch = [ch, Z(c-nd,1:2)]; end if c<=nd, inds(end+1) = c; end end return; function order = leavesorder(Z) nd = size(Z,1)+1; order = 2*nd-1; nonleaves = 1; while any(nonleaves), j = nonleaves(1); ch = Z(order(j)-nd,1:2); if j==1, oleft = []; else oleft = order(1:(j-1)); end if j==length(order), oright = []; else oright = order((j+1):length(order)); end order = [oleft, ch, oright]; nonleaves = find(order>nd); end return;
github
lcnbeapp/beapp-master
corrw.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/icasso/corrw.m
1,654
utf_8
b24c05ddd84adfca75a0870878a9c0f7
function R=corrw(W,D) %function R=corrw(W,D) % %PURPOSE % %To compute mutual linear correlation coefficients between M %independent component estimates using the demixing matrix W and %the dewhitening matrix D of the original data. % % R=W*D*D'*W'; % %INPUT % % W (field W in Icasso struct: demixing matrices) % D (field dewhiteningMatrix in Icasso struct) the dewhitening % matrix of the data % %OUTPUT % % R (MxM matrix) of correlation coefficients % %SEE ALSO % icassoSimilarity % The normalization (rownorm) is a security measure: in some % versions the FastICA has not normalized W properly if iteration % stops prematurely %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.2 100105 B=rownorm(W*D); R=B*B'; function X=rownorm(X) % normalize rows to unit length. s=abs(sqrt(sum(X.^2,2))); if any(s==0), warning('Contains zero vectors: can''t normalize them!'); end X=X./repmat(s,1,size(X,2));
github
lcnbeapp/beapp-master
reducesim.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/icasso/reducesim.m
3,056
utf_8
d2d2a37c6d316586dbfc3da7760af840
function S=reducesim(S,minLimit,partition,scatter,scatterLimit) %function S=reducesim(S,minLimit) % or %function S=reducesim(S,minLimit,partition,scatter,scatterLimit) % %PURPOSE % %To reduce the number of lines that are drawn when the similarity %matrix is visualized. That is, to set similarities below certain %threshold to zero, and optionally, also within-cluster %similarities above certain threshold to zero. % %INPUT % % Two input arguments: % % S (matrix) NxN similarity matrix % minLimit (scalar) all values below this threshold in S are set to % zero % % Five input arguments: % % S (matrix) NxN similarity matrix % minLimit (scalar) all values below this threshold in S are set to % zero % partition (vector) Nx1 partition vector into K clusters (see % explanation for 'partition vector' in function hcluster) % scatter (vector) Kx1 vector that contains within-scatter for % each cluster i=1,2,...,K implied by vector partition % scatterLimit (scalar) threshold for within-cluster scatter. % % %OUTPUT % % S (matrix) NxN similarity matrix with some entries cut to zero. % %SEE ALSO % clusterstat % icassoShow %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.2 100105 johan if nargin==2|nargin==5, ; else error('You must specify 2 or 5 input arguments!'); end %%% Maximum number of lines MAX_NLINES=5000; %%% Set within-cluster similarities above certain threshold to zero if nargin==5, Ncluster=max(partition); for i=1:Ncluster, index=partition==i; if scatter(i)>scatterLimit; S(index,index)=0; end end end %%% We assume symmetric matrix and don't care about %self-similarities upper diagonal is enough S=tril(S); S(eye(size(S))==1)=0; %% Number of lines to draw Nlines=sum(sum(S>minLimit)); %%% If too many lines, try to set better minLimit if Nlines>MAX_NLINES, warning('Creates overwhelming number of lines'); warning('Tries to change the limit...'); minLimit=reduce(S,MAX_NLINES); warning(['New limit =' num2str(minLimit)]); end %%% Set values below minLimit to zero S(S<minLimit)=0; function climit=reduce(c,N) c(c==0)=[]; c=c(:); if N==0, warning('N=0 not allowed; setting N=1'); end if N>length(c), N=length(c); end climit=sort(-c); climit=-climit; climit=climit(N);
github
lcnbeapp/beapp-master
clusterhull.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/icasso/clusterhull.m
5,149
utf_8
49c19208dafd1008be107e012aa6f36e
function [h_marker,txtcoord]=clusterhull(mode,coord,partition,color) %function [h_marker,txtcoord]=clusterhull(mode,coord,partition,[color]) % %PURPOSE % %To draw a cluster visualization where the objects (represented by %points) belonging to the same cluster are presented by "cluster hulls", %polygons where the edge of the polygon is the convex hull of the %points that belong to the same cluster. % %INPUT % %%[An argument in brackets is optional. If it isn't given or it's % an empty matrix/string, the function will use a default value.] % %mode (string) 'edge' | 'fill' %coord (Mx2 matrix) coordinates of points (objects) %partition (Mx1 vector) partition vector of objects (see % explanation for 'partition vector' in function hcluster) %[color] (Kx3 matrix) each line is a 1x3 RGB vector that defines % color for each cluster. Default color is red for all % clusters color(i,:)=[NaN NaN NaN] means that cluster(i) % is not drawn at all. % %OUTPUT % % h_marker (vector) graphic handles to all clusters. h_marker(i)=NaN if % color(i,:)=[NaN NaN NaN] % txtcoord (Kx2 matrix) suggested coordinates for text labels. % txtcoord(i,:)=[NaN NaN] if cluster i is not drawn. % Meaningful only in mode 'edge', returns always a % matrix of NaNs in mode 'fill'. % %DETAILS % %In mode 'edge' each cluster is represented by a convex hull if %there are more than two points in the cluster. A two point cluster is %represented by a line segment and a one point cluster by a small %cross. The face of the convex hull is invisible. % %In mode 'fill' the cluster hulls are filled with the specified %color. Clusters having less than three members are ignored. % %NOTE The function always adds to a plot (turns 'hold on' temporarily). % %USED IN % icassoGraph %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.2 100105 johan holdStat=ishold; hold on; Ncluster=max(partition); if nargin<4|isempty(color), color=repmat([1 0 0],Ncluster,1); end switch mode case 'edge' [h_marker,txtcoord]=clusteredge(coord,partition,color); case 'fill' h_marker=clusterfill(coord,partition,color); txtcoord=repmat(NaN,Ncluster,1); otherwise error('Unknown operation mode.'); end % Some graphic settings set(gca,'xtick',[],'ytick',[]); axis equal; if ~holdStat, hold off; end function [h_marker,txtcoord]=clusteredge(coord,partition,color); %% Number of clusters Ncluster=max(partition); %% Line width and +-sign size LINEWIDTH=2; MARKERSIZE=6; for cluster=1:Ncluster, hullCoord=[]; index=partition==cluster; Npoints=sum(index); coord_=coord(index,:); isVisible=all(isfinite(color(cluster,:))); if isVisible, if Npoints>=3, I=convhull(coord_(:,1),coord_(:,2)); hullCoord=enlargehull([coord_(I,1) coord_(I,2)]); h_marker(cluster,1)=patch(hullCoord(:,1),hullCoord(:,2),0); set(h_marker(cluster,1),'edgecolor',color(cluster,:),'facecolor','none', ... 'linewidth',LINEWIDTH); elseif size(coord_,1)==2, hullCoord(:,1)=[coord_(1,1) coord_(2,1)]'; hullCoord(:,2)=[coord_(1,2) coord_(2,2)]'; h_marker(cluster,1)=plot(hullCoord(:,1)',hullCoord(:,2)','-'); set(h_marker(cluster,1),'color',color(cluster,:),'linewidth',LINEWIDTH); else hullCoord(:,1)=coord_(1,1); hullCoord(:,2)=coord_(1,2); h_marker(cluster,1)=plot(coord_(1,1),coord_(1,2),'+'); set(h_marker(cluster),'color',color(cluster,:),'markersize',MARKERSIZE); end txtcoord(cluster,:)=gettextcoord(hullCoord); else txtcoord(cluster,1:2)=NaN; h_marker(cluster,1)=NaN; end end function h_marker=clusterfill(coord,partition,color) Ncluster=max(partition); k=0; for cluster=1:Ncluster, hullCoord=[]; index=cluster==partition; Npoints=sum(index); coord_=coord(index,:); isVisible=all(isfinite(color(cluster,:))); if Npoints>=3 & isVisible, I=convhull(coord_(:,1),coord_(:,2)); hullCoord=enlargehull([coord_(I,1) coord_(I,2)]); h_marker(cluster,1)=patch(hullCoord(:,1),hullCoord(:,2),0); set(h_marker(cluster),'edgecolor','none','facecolor',color(cluster,:)); else h_marker(cluster,1)=NaN; end end function c=gettextcoord(coord) [tmp,i]=min(coord(:,1)); c=coord(i,:); function coord=enlargehull(coord) S=1.1; m=repmat(mean(coord(1:end-1,:),1),size(coord,1),1); coord_=coord-m; coord_=coord_.*S; coord=coord_+m;
github
lcnbeapp/beapp-master
vis_valuetype.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/icasso/vis_valuetype.m
7,502
utf_8
cb7a373fcda9120d69231b2748371740
function flag=vis_valuetype(value, valid, str); % VIS_VALUETYPE Used for type checks in SOM Toolbox visualization routines % % flag = vis_valuetype(value, valid, str) % % Input and output arguments: % value (varies) variable to be checked % valid (cell array) size 1xN, cells are strings or vectors (see below) % str (string) 'all' or 'any' (default), determines whether % all or just any of the types listed in argument 'valid' % should be true for 'value' % % flag (scalar) 1 or 0 (true or false) % % This is an internal function of SOM Toolbox visualization. It makes % various type checks. For example: % % % Return 1 if X is a numeric scalar otherwise 0: % f=vis_valuetype(X,{'1x1'}); % % % Return 1 if X is a ColorSpec, that is, a 1x3 vector presenting an RGB % % value or any of strings 'red','blue','green','yellow','magenta','cyan', % % 'white' or 'black' or their shortenings 'r','g','b','y','m','c','w','k': % f=vis_valueype(X,{'1x3rgb','colorstyle'}) % % % Return 1 if X is _both_ 10x3 size numeric matrix and has RGB values as rows % f=vis_valuetype(X,{'nx3rgb',[10 3]},'all') % % Strings that may be used in argument valid: % id is true if value is % % [n1 n2 ... nn] any n1 x n2 x ... x nn sized numeric matrix % '1x1' scalar (numeric) % '1x2' 1x2 vector (numeric) % 'nx1' any nx1 numeric vector % 'nx2' nx2 % 'nx3' nx3 % 'nxn' any numeric square matrix % 'nxn[0,1]' numeric square matrix with values in interval [0,1] % 'nxm' any numeric matrix % '1xn' any 1xn numeric vector % '1x3rgb' 1x3 vector v for which all(v>=0 & v<=1), e.g., a RGB code % 'nx3rgb' nx3 numeric matrix that contains n RGB values as rows % 'nx3dimrgb' nx3xdim numeric matrix that contains RGB values % 'nxnx3rgb' nxnx3 numeric matrix of nxn RGB triples % 'none' string 'none' % 'xor' string 'xor' % 'indexed' string 'indexed' % 'colorstyle' strings 'red','blue','green','yellow','magenta','cyan','white' % or 'black', or 'r','g','b','y','m','c','w','k' % 'markerstyle' any of Matlab's marker chars '.','o','x','+','*','s','d','v', % '^','<','>','p'or 'h' % 'linestyle' any or Matlab's line style strings '-',':','--', or '-.' % 'cellcolumn' a nx1 cell array % 'topol_cell' {lattice, msize, shape} % 'topol_cell_no_shape' {lattice, msize} % 'string' any string (1xn array of char) % 'chararray' any MxN char array % Copyright (c) 1999-2000 by the SOM toolbox programming team. % http://www.cis.hut.fi/projects/somtoolbox/ % Version 2.0beta Johan 201099 juuso 280800 if nargin == 2 str='any'; end flag=0; sz=size(value); dims=ndims(value); % isnumeric numeric=isnumeric(value); character=ischar(value); % main loop: go through all types in arg. 'valid' for i=1:length(valid), if isnumeric(valid{i}), % numeric size for double matrix if numeric & length(valid{i}) == dims, flag(i)=all(sz == valid{i}); else flag(i)=0; % not numeric or wrong dimension end else msg=''; % for a error message inside try try switch valid{i} % scalar case '1x1' flag(i)=numeric & dims == 2 & sz(1)==1 & sz(2) ==1; % 1x2 numeric vector case '1x2' flag(i)=numeric & dims == 2 & sz(1)==1 & sz(2) == 2; % 1xn numeric vector case '1xn' flag(i)=numeric & dims == 2 & sz(1) == 1; % any numeric matrix case 'nxm' flag(i)=numeric & dims == 2; % nx3 numeric matrix case 'nx3' flag(i)=numeric & dims == 2 & sz(2) == 3; % nx2 numeric matrix case 'nx2' flag(i)=numeric & dims == 2 & sz(2) == 2; % nx1 numeric vector case 'nx1' flag(i)=numeric & dims == 2 & sz(2) == 1; % nx1xm numric matrix case 'nx1xm' flag(i)=numeric & dims == 3 & sz(2) == 1; % nx3 matrix of RGB triples case 'nx3rgb' flag(i)=numeric & dims == 2 & sz(2) == 3 & in0_1(value); % RGB triple (ColorSpec vector) case '1x3rgb' flag(i) = numeric & dims == 2 & sz(1)==1 & sz(2) == 3 & in0_1(value); % any square matrix case 'nxn' flag(i)=numeric & dims == 2 & sz(1) == sz(2); % nx3xdim array of nxdim RGB triples case 'nx3xdimrgb' flag(i)=numeric & dims == 3 & sz(2) == 3 & in0_1(value); % nxnx3 array of nxn RGB triples case 'nxnx3rgb' flag(i)= numeric & dims == 3 & sz(1) == sz(2) & sz(3) == 3 ... & in0_1(value); % nxn matrix of values between [0,1] case 'nxn[0,1]' flag(i)=numeric & dims == 2 & sz(1) == sz(2) & in0_1(value); % string 'indexed' case 'indexed' flag(i) = ischar(value) & strcmp(value,'indexed'); % string 'none' case 'none' flag(i) = character & strcmp(value,'none'); % string 'xor' case 'xor' flag(i) = character & strcmp(value,'xor'); % any string (1xn char array) case 'string' flag(i) = character & dims == 2 & sz(1)<=1; % any char array case 'chararray' flag(i) = character & dims == 2 & sz(1)>0; % ColorSpec string case 'colorstyle' flag(i)=(character & sz(1) == 1 & sz(2) == 1 & ... any(ismember('ymcrgbwk',value))) | ... (ischar(value) & any(strcmp(value,{'none','yellow','magenta',... 'cyan','red','green','blue','white','black'}))); % any valid Matlab's Marker case 'markerstyle' flag(i)=character & sz(1) == 1 & sz(2) == 1 & ... any(ismember('.ox+*sdv^<>ph',value)); % any valid Matlab's LineStyle case 'linestyle' str=strrep(strrep(strrep(value,'z','1'),'--','z'),'-.','z'); flag(i)=character & any(ismember(str,'z-:')) & sz(1)==1 & (sz(2)==1 | sz(2)==2); % any struct case 'struct' flag(i)=isstruct(value); % nx1 cell array of strings case 'cellcolumn_of_char' flag(i)=iscell(value) & dims == 2 & sz(2)==1; try, char(value); catch, flag(i)=0; end % mxn cell array of strings case '2Dcellarray_of_char' flag(i)=iscell(value) & dims == 2; try, char(cat(2,value{:})); catch, flag(i)=0; end % valid {lattice, msize} case 'topol_cell_no_shape' flag(i)=1; if ~iscell(value) | length(size(value)) ~= 2 | size(value,2)~=2 flag(i)=0; else if vis_valuetype(value{1},{'string'}), switch value{1} case { 'hexa','rect'} ; otherwise flag(i)=0; end end if ~vis_valuetype(value{2},{'1xn'}), flag(i)=0; end end % valid {lattice, msize, shape} case 'topol_cell' flag(i)=1; if ~iscell(value) | length(size(value)) ~= 2 | size(value,2) ~= 3, flag(i)=0; else if vis_valuetype(value{1},{'string'}), switch value{1} case { 'hexa','rect'} ; otherwise flag(i)=0; end end if ~vis_valuetype(value{2},{'1xn'}) flag(i)=0; end if ~vis_valuetype(value{3},{'string'}) flag(i)=0; else switch value{3} case { 'sheet','cyl', 'toroid'} ; otherwise flag(i)=0; end end end otherwise msg='Unknown valuetype!'; end catch % error during type check is due to wrong type of value: % lets set flag(i) to 0 flag(i)=0; end % Unknown indetifier? error(msg); end % set flag according to 3rd parameter (all ~ AND, any ~ OR) if strcmp(str,'all'); flag=all(flag); else flag=any(flag); end end function f=in0_1(value) f=all(value(:) >= 0 & value(:)<=1);
github
lcnbeapp/beapp-master
icassoGet.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/icasso/icassoGet.m
5,635
utf_8
9a56d24c879fa67d054651240e964543
function out=icassoGet(sR,field,index) %function out=icassoGet(sR,field,[index]) % %PURPOSE % %Auxiliary function for obtaining various information from the %Icasso result data structure. Using icassoGet, you can return %information related to original data, e.g.: data matrix, %(de)whitening matrix, total number of estimates, number of %estimates on each round. You can also return specified estimated %independent components (sources), and rows of demixing matrices %from. (However, it is easier to use function icassoResult to return %the final estimation results from the complete Icasso procedure.) % %EXAMPLES OF BASIC USAGE % % M=icassoGet(sR,'m'); % %returns total number of estimates. % % nic=icassoGet(sR,'numOfIC') % %returns number of estimated IC components on each round in an Nx1 %vector (The number may differ in deflatory estimation mode due to %convergence problems.) % % r=icassoGet(sR,'round',[25 17 126]); % %workspace variable r contains now a 3x2 matrix where the first %column shows the number of estimation cycle. The second column %is the order of appearance of the estimate within the cycle: %e.g. 2 5 : estimate 25 was 5th estimate in cycle 2 % 1 17 : 17 1st 1 % 7 6 : 126 6th 7 % % W=icassoGet(sR,'demixingmatrix',[25 17 126]); % %returns the demixing matrix rows for estimates 25, 17, and 126. % % s=icassoGet(sR,'source'); % %returns _all_ M estimated independent components (sources), i.e., %estimates from all resampling cycles. % %INPUT % %[An argument in brackets is optional. If it isn't given or it's % an empty matrix/string, the function will use a default value.] % % sR (struct) Icasso result data structure (from icassoEst). % field (string) (case insensitive) determines what is returned: % 'data' the original data centered % 'N' the number of estimation cycles % 'M' the total number of estimates available; % equal to sum(icassoGet(sR,'numofic')); % 'numofic' number of ICs extracted on each cycle (Nx1 % vector) % 'odim' original data dimension % 'rdim' reduced data dimension (after PCA) % 'round' output is an Mx2 matrix that identifies from % which estimation round each estimate % originates: % out(i,1) is the estimation round for % estimate i, % out(i,2) is the ordinal number of the % estimate within the round. % 'source' estimated source signals % 'dewhitemat' dewhitening matrix for the original data % 'whitemat' dewhitening matrix for the original data % 'demixingmatrix' demixing matrix rows ('W' works as well) % % [index] (vector of integers) specifies which estimates to return % Applies only for 'demixingmatrix', and 'source' % Default: leaving this argument out corresponds to % selecting all estimates, i.e., giving [1:M] as index % vector. % %OUTPUT % % out (type and meaning vary according to input argument 'field') % %SEE ALSO % icassoResult %COPYRIGHT NOTICE %This function is a part of Icasso software library %Copyright (C) 2003-2005 Johan Himberg % %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 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. % ver 1.2 100105 M=size(sR.index,1); if nargin<3, index=1:M; end switch lower(field) case 'm' out=size(sR.index,1); case 'n' out=length(sR.A); case 'odim' out=size(sR.whiteningMatrix,2); case 'rdim' out=size(sR.whiteningMatrix,1); case 'numofic' for i=1:length(sR.A), out(i,1)=size(sR.A{i},2); end case {'w','demixingmatrix'} out=getDeMixing(sR,index); case 'data' out=sR.signal; case {'dewhitemat'} out=sR.dewhiteningMatrix; case {'whitemat'} out=sR.whiteningMatrix; case 'source' out=getSource(sR,index); case 'round' out=sR.index(index,:) otherwise error('Unknown operation.'); end %function A=getMixing(sR,index); % %function A=getMixing(sR,index); % % reindex %index2=sR.index(index,:); %N=size(index2,1); A=[]; %for i=1:N, % A(:,i)=sR.A{index2(i,1)}(:,index2(i,2)); %end function W=getDeMixing(sR,index); % %function W=getDeMixing(sR,index); % % reindex index2=sR.index(index,:); N=size(index2,1); W=[]; for i=1:N, W(i,:)=sR.W{index2(i,1)}(index2(i,2),:); end function S=getSource(sR,index) %function S=getSource(sR,index) % X=sR.signal; W=getDeMixing(sR,index); S=W*X; %% Old stuff %function dWh=getDeWhitening(sR,index); % %function dWh=getDeWhitening(sR,index); % % %index=sR.index(index,:); %Nindex=size(index,1); W=[]; %for i=1:Nindex, % dWh(:,i)=sR.dewhiteningMatrix{1}(:,index(i,2)); %end %function W=getWhitening(sR,index); % %function W=getWhitening(sR,index); % % %index=sR.index(index,:); %Nindex=size(index,1); W=[]; %for i=1:Nindex, % W(:,i)=sR.whiteningMatrix{index(i,1)}(:,index(i,2)); %end
github
lcnbeapp/beapp-master
spm_input.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_input.m
89,257
utf_8
74a73562f0562998a037c0c5d7a512c7
function varargout = spm_input(varargin) % Comprehensive graphical and command line input function % FORMATs (given in Programmers Help) %_______________________________________________________________________ % % spm_input handles most forms of interactive user input for SPM. % (File selection is handled by spm_select.m) % % There are five types of input: String, Evaluated, Conditions, Buttons % and Menus: These prompt for string input; string input which is % evaluated to give a numerical result; selection of one item from a % set of buttons; selection of an item from a menu. % % - STRING, EVALUATED & CONDITION input - % For STRING, EVALUATED and CONDITION input types, a prompt is % displayed adjacent to an editable text entry widget (with a lilac % background!). Clicking in the entry widget allows editing, pressing % <RETURN> or <ENTER> enters the result. You must enter something, % empty answers are not accepted. A default response may be pre-specified % in the entry widget, which will then be outlined. Clicking the border % accepts the default value. % % Basic editing of the entry widget is supported *without* clicking in % the widget, provided no other graphics widget has the focus. (If a % widget has the focus, it is shown highlighted with a thin coloured % line. Clicking on the window background returns the focus to the % window, enabling keyboard accelerators.). This enables you to type % responses to a sequence of questions without having to repeatedly % click the mouse in the text widgets. Supported are BackSpace and % Delete, line kill (^U). Other standard ASCII characters are appended % to the text in the entry widget. Press <RETURN> or <ENTER> to submit % your response. % % A ContextMenu is provided (in the figure background) giving access to % relevant utilities including the facility to load input from a file % (see spm_load.m and examples given below): Click the right button on % the figure background. % % For EVALUATED input, the string submitted is evaluated in the base % MatLab workspace (see MatLab's `eval` command) to give a numerical % value. This permits the entry of numerics, matrices, expressions, % functions or workspace variables. I.e.: % i) - a number, vector or matrix e.g. "[1 2 3 4]" % "[1:4]" % "1:4" % ii) - an expression e.g. "pi^2" % "exp(-[1:36]/5.321)" % iii) - a function (that will be invoked) e.g. "spm_load('tmp.dat')" % (function must be on MATLABPATH) "input_cov(36,5.321)" % iv) - a variable from the base workspace % e.g. "tmp" % % The last three options provide a great deal of power: spm_load will % load a matrix from an ASCII data file and return the results. When % called without an argument, spm_load will pop up a file selection % dialog. Alternatively, this facility can be gained from the % ContextMenu. The second example assummes a custom funcion called % input_cov has been written which expects two arguments, for example % the following file saved as input_cov.m somewhere on the MATLABPATH % (~/matlab, the matlab subdirectory of your home area, and the current % directory, are on the MATLABPATH by default): % % function [x] = input_cov(n,decay) % % data input routine - mono-exponential covariate % % FORMAT [x] = input_cov(n,decay) % % n - number of time points % % decay - decay constant % x = exp(-[1:n]/decay); % % Although this example is trivial, specifying large vectors of % empirical data (e.g. reaction times for 72 scans) is efficient and % reliable using this device. In the last option, a variable called tmp % is picked up from the base workspace. To use this method, set the % variables in the MatLab base workspace before starting an SPM % procedure (but after starting the SPM interface). E.g. % >> tmp=exp(-[1:36]/5.321) % % Occasionally a vector of a specific length will be required: This % will be indicated in the prompt, which will start with "[#]", where % # is the length of vector(s) required. (If a matrix is entered then % at least one dimension should equal #.) % % Occasionally a specific type of number will be required. This should % be obvious from the context. If you enter a number of the wrong type, % you'll be alerted and asked to re-specify. The types are i) Real % numbers; ii) Integers; iii) Whole numbers [0,1,2,3,...] & iv) Natural % numbers [1,2,3,...] % % CONDITIONS type input is for getting indicator vectors. The features % of evaluated input described above are complimented as follows: % v) - a compressed list of digits 0-9 e.g. "12121212" % ii) - a list of indicator characters e.g. "abababab" % a-z mapped to 1-26 in alphabetical order, *except* r ("rest") % which is mapped to zero (case insensitive, [A:Z,a:z] only) % ...in addition the response is checked to ensure integer condition indices. % Occasionally a specific number of conditions will be required: This % will be indicated in the prompt, which will end with (#), where # is % the number of conditions required. % % CONTRAST type input is for getting contrast weight vectors. Enter % contrasts as row-vectors. Contrast weight vectors will be padded with % zeros to the correct length, and checked for validity. (Valid % contrasts are estimable, which are those whose weights vector is in % the row-space of the design matrix.) % % Errors in string evaluation for EVALUATED & CONDITION types are % handled gracefully, the user notified, and prompted to re-enter. % % - BUTTON input - % For Button input, the prompt is displayed adjacent to a small row of % buttons. Press the approprate button. The default button (if % available) has a dark outline. Keyboard accelerators are available % (provided no graphics widget has the focus): <RETURN> or <ENTER> % selects the default button (if available). Typing the first character % of the button label (case insensitive) "presses" that button. (If % these Keys are not unique, then the integer keys 1,2,... "press" the % appropriate button.) % % The CommandLine variant presents a simple menu of buttons and prompts % for a selection. Any default response is indicated, and accepted if % an empty line is input. % % % - MENU input - % For Menu input, the prompt is displayed in a pull down menu widget. % Using the mouse, a selection is made by pulling down the widget and % releasing the mouse on the appropriate response. The default response % (if set) is marked with an asterisk. Keyboard accelerators are % available (provided no graphic widget has the focus) as follows: 'f', % 'n' or 'd' move forward to next response down; 'b', 'p' or 'u' move % backwards to the previous response up the list; the number keys jump % to the appropriate response number; <RETURN> or <ENTER> slelects the % currently displayed response. If a default is available, then % pressing <RETURN> or <ENTER> when the prompt is displayed jumps to % the default response. % % The CommandLine variant presents a simple menu and prompts for a selection. % Any default response is indicated, and accepted if an empty line is % input. % % % - Combination BUTTON/EDIT input - % In this usage, you will be presented with a set of buttons and an % editable text widget. Click one of the buttons to choose that option, % or type your response in the edit widget. Any default response will % be shown in the edit widget. The edit widget behaves in the same way % as with the STRING/EVALUATED input, and expects a single number. % Keypresses edit the text widget (rather than "press" the buttons) % (provided no other graphics widget has the focus). A default response % can be selected with the mouse by clicking the thick border of the % edit widget. % % % - Comand line - % If YPos is 0 or global CMDLINE is true, then the command line is used. % Negative YPos overrides CMDLINE, ensuring the GUI is used, at % YPos=abs(YPos). Similarly relative YPos beginning with '!' % (E.g.YPos='!+1') ensures the GUI is used. % % spm_input uses the SPM 'Interactive' window, which is 'Tag'ged % 'Interactive'. If there is no such window, then the current figure is % used, or an 'Interactive' window created if no windows are open. % %----------------------------------------------------------------------- % Programers help is contained in the main body of spm_input.m %----------------------------------------------------------------------- % See : input.m (MatLab Reference Guide) % See also : spm_select.m (SPM file selector dialog) % : spm_input.m (Input wrapper function - handles batch mode) %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Andrew Holmes % $Id$ %======================================================================= % - FORMAT specifications for programers %======================================================================= % generic - [p,YPos] = spm_input(Prompt,YPos,Type,...) % string - [p,YPos] = spm_input(Prompt,YPos,'s',DefStr) % string+ - [p,YPos] = spm_input(Prompt,YPos,'s+',DefStr) % evaluated - [p,YPos] = spm_input(Prompt,YPos,'e',DefStr,n) % - natural - [p,YPos] = spm_input(Prompt,YPos,'n',DefStr,n,mx) % - whole - [p,YPos] = spm_input(Prompt,YPos,'w',DefStr,n,mx) % - integer - [p,YPos] = spm_input(Prompt,YPos,'i',DefStr,n) % - real - [p,YPos] = spm_input(Prompt,YPos,'r',DefStr,n,mm) % condition - [p,YPos] = spm_input(Prompt,YPos,'c',DefStr,n,m) % contrast - [p,YPos] = spm_input(Prompt,YPos,'x',DefStr,n,X) % permutation- [p,YPos] = spm_input(Prompt,YPos,'p',DefStr,P,n) % button - [p,YPos] = spm_input(Prompt,YPos,'b',Labels,Values,DefItem) % button/edit combo's (edit for string or typed scalar evaluated input) % [p,YPos] = spm_input(Prompt,YPos,'b?1',Labels,Values,DefStr,mx) % ...where ? in b?1 specifies edit widget type as with string & eval'd input % - [p,YPos] = spm_input(Prompt,YPos,'n1',DefStr,mx) % - [p,YPos] = spm_input(Prompt,YPos,'w1',DefStr,mx) % button dialog % - [p,YPos] = spm_input(Prompt,YPos,'bd',... % Labels,Values,DefItem,Title) % menu - [p,YPos] = spm_input(Prompt,YPos,'m',Labels,Values,DefItem) % display - spm_input(Message,YPos,'d',Label) % display - (GUI only) spm_input(Alert,YPos,'d!',Label) % % yes/no - [p,YPos] = spm_input(Prompt,YPos,'y/n',Values,DefItem) % buttons (shortcut) where Labels is a bar delimited string % - [p,YPos] = spm_input(Prompt,YPos,Labels,Values,DefItem) % % NB: Natural numbers are [1:Inf), Whole numbers are [0:Inf) % % -- Parameters (input) -- % % Prompt - prompt string % - Defaults (missing or empty) to 'Enter an expression' % % YPos - (numeric) vertical position {1 - 12} % - overriden by global CMDLINE % - 0 for command line % - negative to force GUI % - (string) relative vertical position E.g. '+1' % - relative to last position used % - overriden by global CMDLINE % - YPos(1)=='!' forces GUI E.g. '!+1' % - '_' is a shortcut for the lowest GUI position % - Defaults (missing or empty) to '+1' % % Type - type of interrogation % - 's'tring % - 's+' multi-line string % - p returned as cellstr (nx1 cell array of strings) % - DefStr can be a cellstr or string matrix % - 'e'valuated string % - 'n'atural numbers % - 'w'hole numbers % - 'i'ntegers % - 'r'eals % - 'c'ondition indicator vector % - 'x' - contrast entry % - If n(2) or design matrix X is specified, then % contrast matrices are padded with zeros to have % correct length. % - if design matrix X is specified, then contrasts are % checked for validity (i.e. in the row-space of X) % (checking handled by spm_SpUtil) % - 'b'uttons % - 'bd' - button dialog: Uses MatLab's questdlg % - For up to three buttons % - Prompt can be a cellstr with a long multiline message % - CmdLine support as with 'b' type % - button/edit combo's: 'be1','bn1','bw1','bi1','br1' % - second letter of b?1 specifies type for edit widget % - 'n1' - single natural number (buttons 1,2,... & edit) % - 'w1' - single whole number (buttons 0,1,... & edit) % - 'm'enu pulldown % - 'y/n' : Yes or No buttons % (See shortcuts below) % - bar delimited string : buttons with these labels % (See shortcuts below) % - Defaults (missing or empty) to 'e' % % DefStr - Default string to be placed in entry widget for string and % evaluated types % - Defaults to '' % % n ('e', 'c' & 'p' types) % - Size of matrix requred % - NaN for 'e' type implies no checking - returns input as evaluated % - length of n(:) specifies dimension - elements specify size % - Inf implies no restriction % - Scalar n expanded to [n,1] (i.e. a column vector) % (except 'x' contrast type when it's [n,np] for np % - E.g: [n,1] & [1,n] (scalar n) prompt for an n-vector, % returned as column or row vector respectively % [1,Inf] & [Inf,1] prompt for a single vector, % returned as column or row vector respectively % [n,Inf] & [Inf,n] prompts for any number of n-vectors, % returned with row/column dimension n respectively. % [a,b] prompts for an 2D matrix with row dimension a and % column dimension b % [a,Inf,b] prompt for a 3D matrix with row dimension a, % page dimension b, and any column dimension. % - 'c' type can only deal with single vectors % - NaN for 'c' type treated as Inf % - Defaults (missing or empty) to NaN % % n ('x'type) % - Number of contrasts required by 'x' type (n(1)) % ( n(2) can be used specify length of contrast vectors if ) % ( a design matrix isn't passed ) % - Defaults (missing or empty) to 1 - vector contrast % % mx ('n', 'w', 'n1', 'w1', 'bn1' & 'bw1' types) % - Maximum value (inclusive) % % mm ('r' type) % - Maximum and minimum values (inclusive) % % m - Number of unique conditions required by 'c' type % - Inf implies no restriction % - Defaults (missing or empty) to Inf - no restriction % % P - set (vector) of numbers of which a permutation is required % % X - Design matrix for contrast checking in 'x' type % - Can be either a straight matrix or a space structure (see spm_sp) % - Column dimension of design matrix specifies length of contrast % vectors (overriding n(2) is specified). % % Title - Title for questdlg in 'bd' type % % Labels - Labels for button and menu types. % - string matrix, one label per row % - bar delimited string % E.g. 'AnCova|Scaling|None' % % Values - Return values corresponding to Labels for button and menu types % - j-th row is returned if button / menu item j is selected % (row vectors are transposed) % - Defaults (missing or empty) to - (button) Labels % - ( menu ) menu item numbers % % DefItem - Default item number, for button and menu types. % % -- Parameters (output) -- % p - results % YPos - Optional second output argument returns GUI position just used % %----------------------------------------------------------------------- % WINDOWS: % % spm_input uses the SPM 'Interactive' 'Tag'ged window. If this isn't % available and no figures are open, an 'Interactive' SPM window is % created (`spm('CreateIntWin')`). If figures are available, then the % current figure is used *unless* it is 'Tag'ged. % %----------------------------------------------------------------------- % SHORTCUTS: % % Buttons SHORTCUT - If the Type parameter is a bar delimited string, then % the Type is taken as 'b' with the specified labels, and the next parameter % (if specified) is taken for the Values. % % Yes/No question shortcut - p = spm_input(Prompt,YPos,'y/n') expands % to p = spm_input(Prompt,YPos,'b','yes|no',...), enabling easy use of % spm_input for yes/no dialogue. Values defaults to 'yn', so 'y' or 'n' % is returned as appropriate. % %----------------------------------------------------------------------- % EXAMPLES: % ( Specified YPos is overriden if global CMDLINE is ) % ( true, when the command line versions are used. ) % % p = spm_input % Command line input of an evaluated string, default prompt. % p = spm_input('Enter a value',1) % Evaluated string input, prompted by 'Enter a value', in % position 1 of the dialog figure. % p = spm_input(str,'+1','e',0.001) % Evaluated string input, prompted by contents of string str, % in next position of the dialog figure. % Default value of 0.001 offered. % p = spm_input(str,2,'e',[],5) % Evaluated string input, prompted by contents of string str, % in second position of the dialog figure. % Vector of length 5 required - returned as column vector % p = spm_input(str,2,'e',[],[Inf,5]) % ...as above, but can enter multiple 5-vectors in a matrix, % returned with 5-vectors in rows % p = spm_input(str,0,'c','ababab') % Condition string input, prompted by contents of string str % Uses command line interface. % Default string of 'ababab' offered. % p = spm_input(str,0,'c','010101') % As above, but default string of '010101' offered. % [p,YPos] = spm_input(str,'0','s','Image') % String input, same position as last used, prompted by str, % default of 'Image' offered. YPos returns GUI position used. % p = spm_input(str,'-1','y/n') % Yes/No buttons for question with prompt str, in position one % before the last used Returns 'y' or 'n'. % p = spm_input(str,'-1','y/n',[1,0],2) % As above, but returns 1 for yes response, 0 for no, % with 'no' as the default response % p = spm_input(str,4,'AnCova|Scaling') % Presents two buttons labelled 'AnCova' & 'Scaling', with % prompt str, in position 4 of the dialog figure. Returns the % string on the depresed button, where buttons can be pressed % with the mouse or by the respective keyboard accelerators % 'a' & 's' (or 'A' & 'S'). % p = spm_input(str,-4,'b','AnCova|Scaling',[],2) % As above, but makes "Scaling" the default response, and % overrides global CMDLINE % p = spm_input(str,0,'b','AnCova|Scaling|None',[1,2,3]) % Prompts for [A]ncova / [S]caling / [N]one in MatLab command % window, returns 1, 2, or 3 according to the first character % of the entered string as one of 'a', 's', or 'n' (case % insensitive). % p = spm_input(str,1,'b','AnCova',1) % Since there's only one button, this just displays the response % in GUI position 1 (or on the command line if global CMDLINE % is true), and returns 1. % p = spm_input(str,'+0','br1','None|Mask',[-Inf,NaN],0.8) % Presents two buttons labelled "None" & "Mask" (which return % -Inf & NaN if clicked), together with an editable text widget % for entry of a single real number. The default of 0.8 is % initially presented in the edit window, and can be selected by % pressing return. % Uses the previous GUI position, unless global CMDLINE is true, % in which case a command-line equivalent is used. % p = spm_input(str,'+0','w1') % Prompts for a single whole number using a combination of % buttons and edit widget, using the previous GUI position, % or the command line if global CMDLINE is true. % p = spm_input(str,'!0','m','Single Subject|Multi Subject|Multi Study') % Prints the prompt str in a pull down menu containing items % 'Single Subject', 'Multi Subject' & 'Multi Study'. When OK is % clicked p is returned as the index of the choice, 1,2, or 3 % respectively. Uses last used position in GUI, irrespective of % global CMDLINE % p = spm_input(str,5,'m',... % 'Single Subject|Multi Subject|Multi Study',... % ['SS';'MS';'SP'],2) % As above, but returns strings 'SS', 'MS', or 'SP' according to % the respective choice, with 'MS; as the default response. % p = spm_input(str,0,'m',... % 'Single Subject|Multi Subject|Multi Study',... % ['SS';'MS';'SP'],2) % As above, but the menu is presented in the command window % as a numbered list. % spm_input('AnCova, GrandMean scaling',0,'d') % Displays message in a box in the MatLab command window % [null,YPos]=spm_input('Session 1','+1','d!','fMRI') % Displays 'fMRI: Session 1' in next GUI position of the % 'Interactive' window. If CMDLINE is 1, then nothing is done. % Position used is returned in YPos. % %----------------------------------------------------------------------- % FORMAT h = spm_input(Prompt,YPos,'m!',Labels,cb,UD,XCB); % GUI PullDown menu utility - creates a pulldown menu in the Interactive window % FORMAT H = spm_input(Prompt,YPos,'b!',Labels,cb,UD,XCB); % GUI Buttons utility - creates GUI buttons in the Interactive window % % Prompt, YPos, Labels - as with 'm'enu/'b'utton types % cb - CallBack string % UD - UserData % XCB - Extended CallBack handling - allows different CallBack for each item, % and use of UD in CallBack strings. [Defaults to 1 for PullDown type % when multiple CallBacks specified, 0 o/w.] % H - Handle of 'PullDown' uicontrol / 'Button's % % In "normal" mode (when XCB is false), this is essentially a utility % to create a PullDown menu widget or set of buttons in the SPM % 'Interactive' figure, using positioning and Label definition % conveniences of the spm_input 'm'enu & 'b'utton types. If Prompt is % not empty, then the PullDown/Buttons appears on the right, with the % Prompt on the left, otherwise the PullDown/Buttons use the whole % width of the Interactive figure. The PopUp's CallBack string is % specified in cb, and [optional] UserData may be passed as UD. % % For buttons, a separate callback can be specified for each button, by % passing the callbacks corresponding to the Labels as rows of a % cellstr or string matrix. % % This "different CallBacks" facility can also be extended to the % PullDown type, using the "extended callback" mode (when XCB is % true). % In addition, in "extended callback", you can use UD to % refer to the UserData argument in the CallBack strings. (What happens % is this: The cb & UD are stored as fields in the PopUp's UserData % structure, and the PopUp's callback is set to spm_input('!m_cb'), % which reads UD into the functions workspace and eval's the % appropriate CallBack string. Note that this means that base % workspace variables are inaccessible (put what you need in UD), and % that any return arguments from CallBack functions are not passed back % to the base workspace). % % %----------------------------------------------------------------------- % UTILITY FUNCTIONS: % % FORMAT colour = spm_input('!Colour') % Returns colour for input widgets, as specified in COLOUR parameter at % start of code. % colour - [r,g,b] colour triple % % FORMAT [iCond,msg] = spm_input('!iCond',str,n,m) % Parser for special 'c'ondition type: Handles digit strings and % strings of indicator chars. % str - input string % n - length of condition vector required [defaut Inf - no restriction] % m - number of conditions required [default Inf - no restrictions] % iCond - Integer condition indicator vector % msg - status message % % FORMAT hM = spm_input('!InptConMen',Finter,H) % Sets a basic Input ContextMenu for the figure % Finter - figure to set menu in % H - handles of objects to delete on "crash out" option % hM - handle of UIContextMenu % % FORMAT [CmdLine,YPos] = spm_input('!CmdLine',YPos) % Sorts out whether to use CmdLine or not & canonicalises YPos % CmdLine - Binary flag % YPos - Position index % % FORMAT Finter = spm_input('!GetWin',F) % Locates (or creates) figure to work in % F - Interactive Figure, defaults to 'Interactive' % Finter - Handle of figure to use % % FORMAT [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp) % Raise window & jump pointer over question % RRec - Response rectangle of current question % F - Interactive Figure, Defaults to 'Interactive' % XDisp - X-displacement of cursor relative to RRec % PLoc - Pointer location before jumping % cF - Current figure before making F current. % % FORMAT [PLoc,cF] = spm_input('!PointerJumpBack',PLoc,cF) % Replace pointer and reset CurrentFigure back % PLoc - Pointer location before jumping % cF - Previous current figure % % FORMAT spm_input('!PrntPrmpt',Prompt,TipStr,Title) % Print prompt for CmdLine questioning % Prompt - prompt string, callstr, or string matrix % TipStr - tip string % Title - title string % % FORMAT [Frec,QRec,PRec,RRec] = spm_input('!InputRects',YPos,rec,F) % Returns rectangles (pixels) used in GUI % YPos - Position index % rec - Rectangle specifier: String, one of 'Frec','QRec','PRec','RRec' % Defaults to '', which returns them all. % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % FRec - Position of interactive window % QRec - Position of entire question % PRec - Position of prompt % RRec - Position of response % % FORMAT spm_input('!DeleteInputObj',F) % Deltes input objects (only) from figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % % FORMAT [CPos,hCPos] = spm_input('!CurrentPos',F) % Returns currently used GUI question positions & their handles % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % CPos - Vector of position indices % hCPos - (n x CPos) matrix of object handles % % FORMAT h = spm_input('!FindInputObj',F) % Returns handles of input GUI objects in figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % h - vector of object handles % % FORMAT [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine) % Returns next position index, specified by YPos % YPos - Absolute (integer) or relative (string) position index % Defaults to '+1' % F - Interactive Figure, defaults to spm_figure('FindWin','Interactive') % CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos) % NPos - Next position index % CPos & hCPos - as for !CurrentPos % % FORMAT NPos = spm_input('!SetNextPos',YPos,F,CmdLine) % Sets up for input at next position index, specified by YPos. This utility % function can be used stand-alone to implicitly set the next position % by clearing positions NPos and greater. % YPos - Absolute (integer) or relative (string) position index % Defaults to '+1' % F - Interactive Figure, defaults to spm_figure('FindWin','Interactive') % CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos) % NPos - Next position index % % FORMAT MPos = spm_input('!MaxPos',F,FRec3) % Returns maximum position index for figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % Not required if FRec3 is specified % FRec3 - Length of interactive figure in pixels % % FORMAT spm_input('!EditableKeyPressFcn',h,ch) % KeyPress callback for GUI string / eval input % % FORMAT spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch) % KeyPress callback for GUI buttons % % FORMAT spm_input('!PullDownKeyPressFcn',h,ch,DefItem) % KeyPress callback for GUI pulldown menus % % FORMAT spm_input('!m_cb') % Extended CallBack handler for 'p' PullDown utility type % % FORMAT spm_input('!dScroll',h,str) % Scroll text string in object h % h - handle of text object % Prompt - Text to scroll (Defaults to 'UserData' of h) % %----------------------------------------------------------------------- % SUBFUNCTIONS: % % FORMAT [Keys,Labs] = sf_labkeys(Labels) % Make unique character keys for the Labels, ignoring case. % Used with 'b'utton types. % % FORMAT [p,msg] = sf_eEval(str,Type,n,m) % Common code for evaluating various input types. % % FORMAT str = sf_SzStr(n,l) % Common code to construct prompt strings for pre-specified vector/matrix sizes % % FORMAT [p,msg] = sf_SzChk(p,n,msg) % Common code to check (& canonicalise) sizes of input vectors/matrices % %_______________________________________________________________________ % @(#)spm_input.m 2.8 Andrew Holmes 03/03/04 %-Parameters %======================================================================= PJump = 1; %-Jumping of pointer to question? TTips = 1; %-Use ToolTipStrings? (which can be annoying!) ConCrash = 1; %-Add "crash out" option to 'Interactive'fig.ContextMenu %-Condition arguments %======================================================================= if nargin<1|isempty(varargin{1}), Prompt=''; else, Prompt=varargin{1}; end if ~isempty(Prompt) & ischar(Prompt) & Prompt(1)=='!' %-Utility functions have Prompt string starting with '!' Type = Prompt; else %-Should be an input request: get Type & YPos if nargin<3|isempty(varargin{3}), Type='e'; else, Type=varargin{3}; end if any(Type=='|'), Type='b|'; end if nargin<2|isempty(varargin{2}), YPos='+1'; else, YPos=varargin{2}; end [CmdLine,YPos] = spm_input('!CmdLine',YPos); if ~CmdLine %-Setup for GUI use %-Locate (or create) figure to work in Finter = spm_input('!GetWin'); COLOUR = get(Finter,'Color'); %-Find out which Y-position to use, setup for use YPos = spm_input('!SetNextPos',YPos,Finter,CmdLine); %-Determine position of objects [FRec,QRec,PRec,RRec]=spm_input('!InputRects',YPos,'',Finter); end end switch lower(Type) case {'s','s+','e','n','w','i','r','c','x','p'} %-String and evaluated input %======================================================================= %-Condition arguments if nargin<6|isempty(varargin{6}), m=[]; else, m=varargin{6}; end if nargin<5|isempty(varargin{5}), n=[]; else, n=varargin{5}; end if nargin<4, DefStr=''; else, DefStr=varargin{4}; end if strcmp(lower(Type),'s+') %-DefStr should be a cellstr for 's+' type. if isempty(DefStr), DefStr = {}; else, DefStr = cellstr(DefStr); end DefStr = DefStr(:); else %-DefStr needs to be a string if ~ischar(DefStr), DefStr=num2str(DefStr); end DefStr = DefStr(:)'; end strM=''; switch lower(Type) %-Type specific defaults/setup case 's', TTstr='enter string'; case 's+',TTstr='enter string - multi-line'; case 'e', TTstr='enter expression to evaluate'; case 'n', TTstr='enter expression - natural number(s)'; if ~isempty(m), strM=sprintf(' (in [1,%d])',m); TTstr=[TTstr,strM]; end case 'w', TTstr='enter expression - whole number(s)'; if ~isempty(m), strM=sprintf(' (in [0,%d])',m); TTstr=[TTstr,strM]; end case 'i', TTstr='enter expression - integer(s)'; case 'r', TTstr='enter expression - real number(s)'; if ~isempty(m), TTstr=[TTstr,sprintf(' in [%g,%g]',min(m),max(m))]; end case 'c', TTstr='enter indicator vector e.g. 0101... or abab...'; if ~isempty(m) & isfinite(m), strM=sprintf(' (%d)',m); end case 'x', TTstr='enter contrast matrix'; case 'p', if isempty(n), error('permutation of what?'), else, P=n(:)'; end if isempty(m), n = [1,length(P)]; end m = P; if ~length(setxor(m,[1:max(m)])) TTstr=['enter permutation of [1:',num2str(max(m)),']']; else TTstr=['enter permutation of [',num2str(m),']']; end otherwise, TTstr='enter expression'; end strN = sf_SzStr(n); if CmdLine %-Use CmdLine to get answer %----------------------------------------------------------------------- spm_input('!PrntPrmpt',[Prompt,strN,strM],TTstr) %-Do Eval Types in Base workspace, catch errors switch lower(Type), case 's' if ~isempty(DefStr) Prompt=[Prompt,' (Default: ',DefStr,' )']; end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end while isempty(str) spm('Beep') fprintf('! %s : enter something!\n',mfilename) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end end p = str; msg = ''; case 's+' fprintf(['Multi-line input: Type ''.'' on a line',... ' of its own to terminate input.\n']) if ~isempty(DefStr) fprintf('Default : (press return to accept)\n') fprintf(' : %s\n',DefStr{:}) end fprintf('\n') str = input('l001 : ','s'); while (isempty(str) | strcmp(str,'.')) & isempty(DefStr) spm('Beep') fprintf('! %s : enter something!\n',mfilename) str = input('l001 : ','s'); end if isempty(str) %-Accept default p = DefStr; else %-Got some input, allow entry of additional lines p = {str}; str = input(sprintf('l%03u : ',length(p)+1),'s'); while ~strcmp(str,'.') p = [p;{str}]; str = input(sprintf('l%03u : ',length(p)+1),'s'); end end msg = ''; otherwise if ~isempty(DefStr) Prompt=[Prompt,' (Default: ',DefStr,' )']; end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type,n,m); while ischar(p) spm('Beep'), fprintf('! %s : %s\n',mfilename,msg) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type,n,m); end end if ~isempty(msg), fprintf('\t%s\n',msg), end else %-Use GUI to get answer %----------------------------------------------------------------------- %-Create text and edit control objects %--------------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',[strN,Prompt,strM],... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData','',... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); %-Default button surrounding edit widget (if a DefStr given) %-Callback sets hPrmpt UserData, and EditWidget string, to DefStr % (Buttons UserData holds handles [hPrmpt,hEditWidget], set later) cb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',... 'get(gcbo,''String'')),',... 'set(get(gcbo,''UserData'')*[0;1],''String'',',... 'get(gcbo,''String''))']; if ~isempty(DefStr) if iscellstr(DefStr), str=[DefStr{1},'...']; else, str=DefStr; end hDef = uicontrol(Finter,'Style','PushButton',... 'String',DefStr,... 'ToolTipString',... ['Click on border to accept default: ' str],... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',[],... 'BackgroundColor',COLOUR,... 'CallBack',cb,... 'Position',RRec+[-2,-2,+4,+4]); else hDef = []; end %-Edit widget: Callback puts string into hPrompts UserData cb = 'set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))'; h = uicontrol(Finter,'Style','Edit',... 'String',DefStr,... 'Max',strcmp(lower(Type),'s+')+1,... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',hPrmpt,... 'CallBack',cb,... 'Horizontalalignment','Left',... 'BackgroundColor','w',... 'Position',RRec); set(hDef,'UserData',[hPrmpt,h]) uifocus(h); if TTips, set(h,'ToolTipString',TTstr), end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,hDef,h]); cb = [ 'set(get(gcbo,''UserData''),''String'',',... '[''spm_load('''''',spm_select(1),'''''')'']), ',... 'set(get(get(gcbo,''UserData''),''UserData''),''UserData'',',... 'get(get(gcbo,''UserData''),''String''))']; uimenu(hM,'Label','load from text file','Separator','on',... 'CallBack',cb,'UserData',h) %-Bring window to fore & jump pointer to edit widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); %-Setup FigureKeyPressFcn for editing of entry widget without clicking set(Finter,'KeyPressFcn',[... 'spm_input(''!EditableKeyPressFcn'',',... 'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',... '''Style'',''edit''),',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for edit, do eval Types in Base workspace, catch errors %--------------------------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input window cleared whilst waiting ',... 'for response: Bailing out!']), end str = get(hPrmpt,'UserData'); switch lower(Type), case 's' p = str; msg = ''; case 's+' p = cellstr(str); msg = ''; otherwise [p,msg] = sf_eEval(str,Type,n,m); while ischar(p) set(h,'Style','Text',... 'String',msg,'HorizontalAlignment','Center',... 'ForegroundColor','r') spm('Beep'), pause(2) set(h,'Style','Edit',... 'String',str,... 'HorizontalAlignment','Left',... 'ForegroundColor','k') %set(hPrmpt,'UserData',''); waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input window cleared ',... 'whilst waiting for response: Bailing out!']),end str = get(hPrmpt,'UserData'); [p,msg] = sf_eEval(str,Type,n,m); end end %-Fix edit window, clean up, reposition pointer, set CurrentFig back delete([hM,hDef]), set(Finter,'KeyPressFcn','') set(h,'Style','Text','HorizontalAlignment','Center',... 'ToolTipString',msg,... 'BackgroundColor',COLOUR) spm_input('!PointerJumpBack',PLoc,cF) drawnow end % (if CmdLine) %-Return response %----------------------------------------------------------------------- varargout = {p,YPos}; case {'b','bd','b|','y/n','be1','bn1','bw1','bi1','br1',... '-n1','n1','-w1','w1','m'} %-'b'utton & 'm'enu Types %======================================================================= %-Condition arguments switch lower(Type), case {'b','be1','bi1','br1','m'} m = []; Title = ''; if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=''; else, Labels =varargin{4}; end case 'bd' if nargin<7, Title=''; else, Title =varargin{7}; end if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=''; else, Labels =varargin{4}; end case 'y/n' Title = ''; if nargin<5, DefItem=[]; else, DefItem=varargin{5}; end if nargin<4, Values=[]; else, Values =varargin{4}; end if isempty(Values), Values='yn'; end Labels = {'yes','no'}; case 'b|' Title = ''; if nargin<5, DefItem=[]; else, DefItem=varargin{5}; end if nargin<4, Values=[]; else, Values =varargin{4}; end Labels = varargin{3}; case 'bn1' if nargin<7, m=[]; else, m=varargin{7}; end if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=[1:5]'; Values=[1:5]; Type='-n1'; else, Labels=varargin{4}; end case 'bw1' if nargin<7, m=[]; else, m=varargin{7}; end if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=[0:4]'; Values=[0:4]; Type='-w1'; else, Labels=varargin{4}; end case {'-n1','n1','-w1','w1'} if nargin<5, m=[]; else, m=varargin{5}; end if nargin<4, DefItem=[]; else, DefItem=varargin{4}; end switch lower(Type) case {'n1','-n1'}, Labels=[1:min([5,m])]'; Values=Labels'; Type='-n1'; case {'w1','-w1'}, Labels=[0:min([4,m])]'; Values=Labels'; Type='-w1'; end end %-Check some labels were specified if isempty(Labels), error('No Labels specified'), end if iscellstr(Labels), Labels=char(Labels); end %-Convert Labels "option" string to string matrix if required if ischar(Labels) & any(Labels=='|') OptStr=Labels; BarPos=find([OptStr=='|',1]); Labels=OptStr(1:BarPos(1)-1); for Bar = 2:sum(OptStr=='|')+1 Labels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1)); end end %-Set default Values for the Labels if isempty(Values) if strcmp(lower(Type),'m') Values=[1:size(Labels,1)]'; else Values=Labels; end else %-Make sure Values are in rows if size(Labels,1)>1 & size(Values,1)==1, Values = Values'; end %-Check numbers of Labels and Values match if (size(Labels,1)~=size(Values,1)) error('Labels & Values incompatible sizes'), end end %-Numeric Labels to strings if isnumeric(Labels) tmp = Labels; Labels = cell(size(tmp,1),1); for i=1:prod(size(tmp)), Labels{i}=num2str(tmp(i,:)); end Labels=char(Labels); end switch lower(Type), case {'b','bd','b|','y/n'} %-Process button types %======================================================================= %-Make unique character keys for the Labels, sort DefItem %--------------------------------------------------------------- nLabels = size(Labels,1); [Keys,Labs] = sf_labkeys(Labels); if ~isempty(DefItem) & any(DefItem==[1:nLabels]) DefKey = Keys(DefItem); else DefItem = 0; DefKey = ''; end if CmdLine %-Display question prompt spm_input('!PrntPrmpt',Prompt,'',Title) %-Build prompt %------------------------------------------------------- if ~isempty(Labs) Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' ']; for i = 2:nLabels Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' ']; end else Prmpt = ['[',Keys(1),'] ']; for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end end if DefItem Prmpt = [Prmpt,... ' (Default: ',deblank(Labels(DefItem,:)),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('%s: %s\t(only option)',Prmpt,Labels) else str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end while isempty(str) | ~any(lower(Keys)==lower(str(1))) if ~isempty(str),fprintf('%c\t!Out of range\n',7),end str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end end k = find(lower(Keys)==lower(str(1))); end fprintf('\n') p = Values(k,:); if ischar(p), p=deblank(p); end elseif strcmp(lower(Type),'bd') if nLabels>3, error('at most 3 labels for GUI ''db'' type'), end tmp = cellstr(Labels); if DefItem tmp = [tmp; tmp(DefItem)]; Prompt = cellstr(Prompt); Prompt=Prompt(:); Prompt = [Prompt;{' '};... {['[default: ',tmp{DefItem},']']}]; else tmp = [tmp; tmp(1)]; end k = min(find(strcmp(tmp,... questdlg(Prompt,sprintf('%s%s: %s...',spm('ver'),... spm('GetUser',' (%s)'),Title),tmp{:})))); p = Values(k,:); if ischar(p), p=deblank(p); end else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets %-Create text and edit control objects %-'UserData' of prompt contains answer %------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',Prompt,... 'Tag',Tag,... 'UserData',[],... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); if nLabels==1 %-Only one choice - auto-pick k = 1; else %-Draw buttons and process response dX = RRec(3)/nLabels; if TTips, str = ['select with mouse or use kbd: ',... sprintf('%c/',Keys(1:end-1)),Keys(end)]; else, str=''; end %-Store button # in buttons 'UserData' property %-Store handle of prompt string in buttons 'Max' property %-Button callback sets UserData of prompt string to % number of pressed button cb = ['set(get(gcbo,''Max''),''UserData'',',... 'get(gcbo,''UserData''))']; H = []; XDisp = []; for i=1:nLabels if i==DefItem %-Default button, outline it h = uicontrol(Finter,'Style','Frame',... 'BackGroundColor','k',... 'ForeGroundColor','k',... 'Tag',Tag,... 'Position',... [RRec(1)+(i-1)*dX ... RRec(2)-1 dX RRec(4)+2]); XDisp = (i-1/3)*dX; H = [H,h]; end h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'ToolTipString',str,... 'Tag',Tag,... 'Max',hPrmpt,... 'UserData',i,... 'BackgroundColor',COLOUR,... 'Callback',cb,... 'Position',[RRec(1)+(i-1)*dX+1 ... RRec(2) dX-2 RRec(4)]); if i == DefItem, uifocus(h); end H = [H,h]; end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,H]); %-Bring window to fore & jump pointer to default button [PLoc,cF]=spm_input('!PointerJump',RRec,Finter,XDisp); %-Callback for KeyPress, to store valid button # in % UserData of Prompt, DefItem if (DefItem~=0) % & return (ASCII-13) is pressed set(Finter,'KeyPressFcn',... ['spm_input(''!ButtonKeyPressFcn'',',... 'findobj(gcf,''Tag'',''',Tag,''',',... '''Style'',''text''),',... '''',lower(Keys),''',',num2str(DefItem),',',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for button press, process results %----------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt) error(['Input objects cleared whilst ',... 'waiting for response: Bailing out!']) end k = get(hPrmpt,'UserData'); %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') spm_input('!PointerJumpBack',PLoc,cF) end %-Display answer uicontrol(Finter,'Style','Text',... 'String',deblank(Labels(k,:)),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',RRec); drawnow p = Values(k,:); if ischar(p), p=deblank(p); end end case {'be1','bn1','bw1','bi1','br1','-n1','-w1'} %-Process button/entry combo types %======================================================================= if ischar(DefItem), DefStr=DefItem; else, DefStr=num2str(DefItem); end if isempty(m), strM=''; else, strM=sprintf(' (<=%d)',m); end if CmdLine %-Process default item %--------------------------------------------------------------- if ~isempty(DefItem) [DefVal,msg] = sf_eEval(DefStr,Type(2),1); if ischar(DefVal), error(['Invalid DefItem: ',msg]), end Labels = strvcat(Labels,DefStr); Values = [Values;DefVal]; DefItem = size(Labels,1); end %-Add option to specify... Labels = strvcat(Labels,'specify...'); %-Process options nLabels = size(Labels,1); [Keys,Labs] = sf_labkeys(Labels); if ~isempty(DefItem), DefKey = Keys(DefItem); else, DefKey = ''; end %-Print banner prompt %--------------------------------------------------------------- spm_input('!PrntPrmpt',Prompt) %-Display question prompt if Type(1)=='-' %-No special buttons - go straight to input k = size(Labels,1); else %-Offer buttons, default or "specify..." %-Build prompt %------------------------------------------------------- if ~isempty(Labs) Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' ']; for i = 2:nLabels Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' ']; end else Prmpt = ['[',Keys(1),'] ']; for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end end if DefItem, Prmpt = [Prmpt,... ' (Default: ',deblank(Labels(DefItem,:)),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('%s: %s\t(only option)',Prmpt,Labels) else str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end while isempty(str) | ~any(lower(Keys)==lower(str(1))) if ~isempty(str),fprintf('%c\t!Invalid response\n',7),end str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end end k = find(lower(Keys)==lower(str(1))); end fprintf('\n') end %-Process response: prompt for value if "specify..." option chosen %=============================================================== if k<size(Labels,1) p = Values(k,:); if ischar(p), p=deblank(p); end else %-"specify option chosen: ask user to specify %------------------------------------------------------- switch lower(Type(2)) case 's', tstr=' string'; case 'e', tstr='n expression'; case 'n', tstr=' natural number';case 'w', tstr=' whole number'; case 'i', tstr='n integer'; case 'r', tstr=' real number'; otherwise, tstr=''; end Prompt = sprintf('%s (a%s%s)',Prompt,tstr,strM); if ~isempty(DefStr) Prompt=sprintf('%s\b, default %s)',Prompt,DefStr); end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end %-Eval in Base workspace, catch errors [p,msg] = sf_eEval(str,Type(2),1,m); while ischar(p) spm('Beep'), fprintf('! %s : %s\n',mfilename,msg) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type(2),1,m); end end else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets nLabels = size(Labels,1); %-#buttons %-Create text and edit control objects %-'UserData' of prompt contains answer %--------------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',[Prompt,strM],... 'Tag',Tag,... 'UserData',[],... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); %-Draw buttons & entry widget, & process response dX = RRec(3)*(2/3)/nLabels; %-Store button # in buttons 'UserData' %-Store handle of prompt string in buttons 'Max' property %-Callback sets UserData of prompt string to button number. cb = ['set(get(gcbo,''Max''),''UserData'',get(gcbo,''UserData''))']; if TTips, str=sprintf('select by mouse or enter value in text widget'); else, str=''; end H = []; for i=1:nLabels h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'Max',hPrmpt,... 'ToolTipString',str,... 'Tag',Tag,... 'UserData',i,... 'BackgroundColor',COLOUR,... 'Callback',cb,... 'Position',[RRec(1)+(i-1)*dX+1 RRec(2) dX-2 RRec(4)]); H = [H,h]; end %-Default button surrounding edit widget (if a DefStr given) %-Callback sets hPrmpt UserData, and EditWidget string, to DefStr % (Buttons UserData holds handles [hPrmpt,hEditWidget], set later) cb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',... 'get(gcbo,''String'')),',... 'set(get(gcbo,''UserData'')*[0;1],''String'',',... 'get(gcbo,''String''))']; if ~isempty(DefStr) hDef = uicontrol(Finter,'Style','PushButton',... 'String',DefStr,... 'ToolTipString',['Click on border to accept ',... 'default: ' DefStr],... 'Tag',Tag,... 'UserData',[],... 'CallBack',cb,... 'BackgroundColor',COLOUR,... 'Position',... [RRec(1)+RRec(3)*(2/3) RRec(2)-2 RRec(3)/3+2 RRec(4)+4]); H = [H,hDef]; else hDef = []; end %-Edit widget: Callback puts string into hPrompts UserData cb = ['set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))']; h = uicontrol(Finter,'Style','Edit',... 'String',DefStr,... 'ToolTipString',str,... 'Tag',Tag,... 'UserData',hPrmpt,... 'CallBack',cb,... 'Horizontalalignment','Center',... 'BackgroundColor','w',... 'Position',... [RRec(1)+RRec(3)*(2/3)+2 RRec(2) RRec(3)/3-2 RRec(4)]); set(hDef,'UserData',[hPrmpt,h]) uifocus(h); H = [H,h]; %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,H]); %-Bring window to fore & jump pointer to default button [PLoc,cF] = spm_input('!PointerJump',RRec,Finter,RRec(3)*0.95); %-Setup FigureKeyPressFcn for editing of entry widget without clicking set(Finter,'KeyPressFcn',[... 'spm_input(''!EditableKeyPressFcn'',',... 'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',... '''Style'',''edit''),',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for button press, process results %--------------------------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input objects cleared whilst waiting ',... 'for response: Bailing out!']), end p = get(hPrmpt,'UserData'); if ~ischar(p) k = p; p = Values(k,:); if ischar(p), p=deblank(p); end else Labels = strvcat(Labels,'specify...'); k = size(Labels,1); [p,msg] = sf_eEval(p,Type(2),1,m); while ischar(p) set(H,'Visible','off') h = uicontrol('Style','Text','String',msg,... 'Horizontalalignment','Center',... 'ForegroundColor','r',... 'BackgroundColor',COLOUR,... 'Tag',Tag,'Position',RRec); spm('Beep') pause(2), delete(h), set(H,'Visible','on') set(hPrmpt,'UserData','') waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input objects cleared ',... 'whilst waiting for response: Bailing out!']),end p = get(hPrmpt,'UserData'); if ischar(p), [p,msg] = sf_eEval(p,Type(2),1,m); end end end %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') spm_input('!PointerJumpBack',PLoc,cF) %-Display answer uicontrol(Finter,'Style','Text',... 'String',num2str(p),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',RRec); drawnow end % (if CmdLine) case 'm' %-Process menu type %======================================================================= nLabels = size(Labels,1); if ~isempty(DefItem) & ~any(DefItem==[1:nLabels]), DefItem=[]; end %-Process pull down menu type if CmdLine spm_input('!PrntPrmpt',Prompt) nLabels = size(Labels,1); for i = 1:nLabels, fprintf('\t%2d : %s\n',i,Labels(i,:)), end Prmpt = ['Menu choice (1-',int2str(nLabels),')']; if DefItem Prmpt=[Prmpt,' (Default: ',num2str(DefItem),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('Menu choice: 1 - %s\t(only option)',Labels) else k = input([Prmpt,' ? ']); if DefItem & isempty(k), k=DefItem; end while isempty(k) | ~any([1:nLabels]==k) if ~isempty(k),fprintf('%c\t!Out of range\n',7),end k = input([Prmpt,' ? ']); if DefItem & isempty(k), k=DefItem; end end end fprintf('\n') else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets if nLabels==1 %-Only one choice - auto-pick k = 1; else Labs=[repmat(' ',nLabels,2),Labels]; if DefItem Labs(DefItem,1)='*'; H = uicontrol(Finter,'Style','Frame',... 'BackGroundColor','k',... 'ForeGroundColor','k',... 'Position',QRec+[-1,-1,+2,+2]); else H = []; end cb = ['if (get(gcbo,''Value'')>1),',... 'set(gcbo,''UserData'',''Selected''), end']; hPopUp = uicontrol(Finter,'Style','PopUp',... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'String',strvcat([Prompt,'...'],Labs),... 'Tag',Tag,... 'UserData',DefItem,... 'CallBack',cb,... 'Position',QRec); if TTips, set(hPopUp,'ToolTipString',['select with ',... 'mouse or type option number (1-',... num2str(nLabels),') & press return']), end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPopUp,H]); %-Bring window to fore & jump pointer to menu widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); %-Callback for KeyPresses cb=['spm_input(''!PullDownKeyPressFcn'',',... 'findobj(gcf,''Tag'',''',Tag,'''),',... 'get(gcf,''CurrentCharacter''))']; set(Finter,'KeyPressFcn',cb) %-Wait for menu selection %----------------------------------------------- waitfor(hPopUp,'UserData') if ~ishandle(hPopUp), error(['Input object cleared ',... 'whilst waiting for response: Bailing out!']),end k = get(hPopUp,'Value')-1; %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') set(hPopUp,'Style','Text',... 'Horizontalalignment','Center',... 'String',deblank(Labels(k,:)),... 'BackgroundColor',COLOUR) spm_input('!PointerJumpBack',PLoc,cF) end %-Display answer uicontrol(Finter,'Style','Text',... 'String',deblank(Labels(k,:)),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',QRec); drawnow end p = Values(k,:); if ischar(p), p=deblank(p); end otherwise, error('unrecognised type') end % (switch lower(Type) within case {'b','b|','y/n'}) %-Return response %----------------------------------------------------------------------- varargout = {p,YPos}; case {'m!','b!'} %-GUI PullDown/Buttons utility %======================================================================= % H = spm_input(Prompt,YPos,'p',Labels,cb,UD,XCB) %-Condition arguments if nargin<7, XCB = 0; else, XCB = varargin{7}; end if nargin<6, UD = []; else, UD = varargin{6}; end if nargin<5, cb = ''; else, cb = varargin{5}; end if nargin<4, Labels = []; else, Labels = varargin{4}; end if CmdLine, error('Can''t do CmdLine GUI utilities!'), end if isempty(cb), cb = 'disp(''(CallBack not set)'')'; end if ischar(cb), cb = cellstr(cb); end if length(cb)>1 & strcmp(lower(Type),'m!'), XCB=1; end if iscellstr(Labels), Labels=char(Labels); end %-Convert Labels "option" string to string matrix if required if any(Labels=='|') OptStr=Labels; BarPos=find([OptStr=='|',1]); Labels=OptStr(1:BarPos(1)-1); for Bar = 2:sum(OptStr=='|')+1 Labels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1)); end end %-Check #CallBacks if ~( length(cb)==1 | (length(cb)==size(Labels,1)) ) error('Labels & Callbacks size mismatch'), end %-Draw Prompt %----------------------------------------------------------------------- Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets if ~isempty(Prompt) uicontrol(Finter,'Style','Text',... 'String',Prompt,... 'Tag',Tag,... 'HorizontalAlignment','Right',... 'BackgroundColor',COLOUR,... 'Position',PRec) Rec = RRec; else Rec = QRec; end %-Sort out UserData for extended callbacks (handled by spm_input('!m_cb') %----------------------------------------------------------------------- if XCB, if iscell(UD), UD={UD}; end, UD = struct('UD',UD,'cb',{cb}); end %-Draw PullDown or Buttons %----------------------------------------------------------------------- switch lower(Type), case 'm!' if XCB, UD.cb=cb; cb = {'spm_input(''!m_cb'')'}; end H = uicontrol(Finter,'Style','PopUp',... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'String',Labels,... 'Tag',Tag,... 'UserData',UD,... 'CallBack',char(cb),... 'Position',Rec); case 'b!' nLabels = size(Labels,1); dX = Rec(3)/nLabels; H = []; for i=1:nLabels if length(cb)>1, tcb=cb(i); else, tcb=cb; end if XCB, UD.cb=tcb; tcb = {'spm_input(''!m_cb'')'}; end h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'ToolTipString','',... 'Tag',Tag,... 'UserData',UD,... 'BackgroundColor',COLOUR,... 'Callback',char(tcb),... 'Position',[Rec(1)+(i-1)*dX+1 ... Rec(2) dX-2 Rec(4)]); H = [H,h]; end end %-Bring window to fore & jump pointer to menu widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); varargout = {H}; case {'d','d!'} %-Display message %======================================================================= %-Condition arguments if nargin<4, Label=''; else, Label=varargin{4}; end if CmdLine & strcmp(lower(Type),'d') fprintf('\n +-%s%s+',Label,repmat('-',1,57-length(Label))) Prompt = [Prompt,' ']; while length(Prompt)>0 tmp = length(Prompt); if tmp>56, tmp=min([max(find(Prompt(1:56)==' ')),56]); end fprintf('\n | %s%s |',Prompt(1:tmp),repmat(' ',1,56-tmp)) Prompt(1:tmp)=[]; end fprintf('\n +-%s+\n',repmat('-',1,57)) elseif ~CmdLine if ~isempty(Label), Prompt = [Label,': ',Prompt]; end figure(Finter) %-Create text axes and edit control objects %--------------------------------------------------------------- h = uicontrol(Finter,'Style','Text',... 'String',Prompt(1:min(length(Prompt),56)),... 'FontWeight','bold',... 'Tag',['GUIinput_',int2str(YPos)],... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'UserData',Prompt,... 'Position',QRec); if length(Prompt)>56 pause(1) set(h,'ToolTipString',Prompt) spm_input('!dScroll',h) uicontrol(Finter,'Style','PushButton','String','>',... 'ToolTipString','press to scroll message',... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',h,... 'CallBack',[... 'set(gcbo,''Visible'',''off''),',... 'spm_input(''!dScroll'',get(gcbo,''UserData'')),',... 'set(gcbo,''Visible'',''on'')'],... 'BackgroundColor',COLOUR,... 'Position',[QRec(1)+QRec(3)-10,QRec(2),15,QRec(4)]); end end if nargout>0, varargout={[],YPos}; end %======================================================================= % U T I L I T Y F U N C T I O N S %======================================================================= case '!colour' %======================================================================= % colour = spm_input('!Colour') varargout = {COLOUR}; case '!icond' %======================================================================= % [iCond,msg] = spm_input('!iCond',str,n,m) % Parse condition indicator spec strings: % '2 3 2 3', '0 1 0 1', '2323', '0101', 'abab', 'R A R A' if nargin<4, m=Inf; else, m=varargin{4}; end if nargin<3, n=NaN; else, n=varargin{3}; end if any(isnan(n(:))) n=Inf; elseif (length(n(:))==2 & ~any(n==1)) | length(n(:))>2 error('condition input can only do vectors') end if nargin<2, i=''; else, i=varargin{2}; end if isempty(i), varargout={[],'empty input'}; return, end msg = ''; i=i(:)'; if ischar(i) if i(1)=='0' & all(ismember(unique(i(:)),char(abs('0'):abs('9')))) %-Leading zeros in a digit list msg = sprintf('%s expanded',i); z = min(find([diff(i=='0'),1])); i = [zeros(1,z), spm_input('!iCond',i(z+1:end))']; else %-Try an eval, for functions & string #s i = evalin('base',['[',i,']'],'i'); end end if ischar(i) %-Evaluation error from above: see if it's an 'abab' or 'a b a b' type: [c,null,i] = unique(lower(i(~isspace(i)))); if all(ismember(c,char(abs('a'):abs('z')))) %-Map characters a-z to 1-26, but let 'r' be zero (rest) tmp = c-'a'+1; tmp(tmp=='r'-'a'+1)=0; i = tmp(i); msg = [sprintf('[%s] mapped to [',c),... sprintf('%d,',tmp(1:end-1)),... sprintf('%d',tmp(end)),']']; else i = '!'; msg = 'evaluation error'; end elseif ~all(floor(i(:))==i(:)) i = '!'; msg = 'must be integers'; elseif length(i)==1 & prod(n)>1 msg = sprintf('%d expanded',i); i = floor(i./10.^[floor(log10(i)+eps):-1:0]); i = i-[0,10*i(1:end-1)]; end %-Check size of i & #conditions if ~ischar(i), [i,msg] = sf_SzChk(i,n,msg); end if ~ischar(i) & isfinite(m) & length(unique(i))~=m i = '!'; msg = sprintf('%d conditions required',m); end varargout = {i,msg}; case '!inptconmen' %======================================================================= % hM = spm_input('!InptConMen',Finter,H) if nargin<3, H=[]; else, H=varargin{3}; end if nargin<2, varargout={[]}; else, Finter=varargin{2}; end hM = uicontextmenu('Parent',Finter); uimenu(hM,'Label','help on spm_input',... 'CallBack','spm_help(''spm_input.m'')') if ConCrash uimenu(hM,'Label','crash out','Separator','on',... 'CallBack','delete(get(gcbo,''UserData''))',... 'UserData',[hM,H]) end set(Finter,'UIContextMenu',hM) varargout={hM}; case '!cmdline' %======================================================================= % [CmdLine,YPos] = spm_input('!CmdLine',YPos) %-Sorts out whether to use CmdLine or not & canonicalises YPos if nargin<2, YPos=''; else, YPos=varargin{2}; end if isempty(YPos), YPos='+1'; end CmdLine = []; %-Special YPos specifications if ischar(YPos) if(YPos(1)=='!'), CmdLine=0; YPos(1)=[]; end elseif YPos==0 CmdLine=1; elseif YPos<0 CmdLine=0; YPos=-YPos; end CmdLine = spm('CmdLine',CmdLine); if CmdLine, YPos=0; end varargout = {CmdLine,YPos}; case '!getwin' %======================================================================= % Finter = spm_input('!GetWin',F) %-Locate (or create) figure to work in (Don't use 'Tag'ged figs) if nargin<2, F='Interactive'; else, F=varargin{2}; end Finter = spm_figure('FindWin',F); if isempty(Finter) if any(get(0,'Children')) if isempty(get(gcf,'Tag')), Finter = gcf; else, Finter = spm('CreateIntWin'); end else, Finter = spm('CreateIntWin'); end end varargout = {Finter}; case '!pointerjump' %======================================================================= % [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp) %-Raise window & jump pointer over question if nargin<4, XDisp=[]; else, XDisp=varargin{4}; end if nargin<3, F='Interactive'; else, F=varargin{3}; end if nargin<2, error('Insufficient arguments'), else, RRec=varargin{2}; end F = spm_figure('FindWin',F); PLoc = get(0,'PointerLocation'); cF = get(0,'CurrentFigure'); if ~isempty(F) figure(F) FRec = get(F,'Position'); if isempty(XDisp), XDisp=RRec(3)*4/5; end if PJump, set(0,'PointerLocation',... floor([(FRec(1)+RRec(1)+XDisp), (FRec(2)+RRec(2)+RRec(4)/3)])); end end varargout = {PLoc,cF}; case '!pointerjumpback' %======================================================================= % spm_input('!PointerJumpBack',PLoc,cF) %-Replace pointer and reset CurrentFigure back if nargin<4, cF=[]; else, F=varargin{3}; end if nargin<2, error('Insufficient arguments'), else, PLoc=varargin{2}; end if PJump, set(0,'PointerLocation',PLoc), end cF = spm_figure('FindWin',cF); if ~isempty(cF), set(0,'CurrentFigure',cF); end case '!prntprmpt' %======================================================================= % spm_input('!PrntPrmpt',Prompt,TipStr,Title) %-Print prompt for CmdLine questioning if nargin<4, Title = ''; else, Title = varargin{4}; end if nargin<3, TipStr = ''; else, TipStr = varargin{3}; end if nargin<2, Prompt = ''; else, Prompt = varargin{2}; end if isempty(Prompt), Prompt='Enter an expression'; end Prompt = cellstr(Prompt); if ~isempty(TipStr) tmp = 8 + length(Prompt{end}) + length(TipStr); if tmp < 62 TipStr = sprintf('%s(%s)',repmat(' ',1,70-tmp),TipStr); else TipStr = sprintf('\n%s(%s)',repmat(' ',1,max(0,70-length(TipStr))),TipStr); end end if isempty(Title) fprintf('\n%s\n',repmat('~',1,72)) else fprintf('\n= %s %s\n',Title,repmat('~',1,72-length(Title)-3)) end fprintf('\t%s',Prompt{1}) for i=2:prod(size(Prompt)), fprintf('\n\t%s',Prompt{i}), end fprintf('%s\n%s\n',TipStr,repmat('~',1,72)) case '!inputrects' %======================================================================= % [Frec,QRec,PRec,RRec,Sz,Se] = spm_input('!InputRects',YPos,rec,F) if nargin<4, F='Interactive'; else, F=varargin{4}; end if nargin<3, rec=''; else, rec=varargin{3}; end if nargin<2, YPos=1; else, YPos=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), error('Figure not found'), end Units = get(F,'Units'); set(F,'Units','pixels') FRec = get(F,'Position'); set(F,'Units',Units); Xdim = FRec(3); Ydim = FRec(4); WS = spm('WinScale'); Sz = round(22*min(WS)); %-Height Pd = Sz/2; %-Pad Se = 2*round(25*min(WS)/2); %-Seperation Yo = round(2*min(WS)); %-Y offset for responses a = 5.5/10; y = Ydim - Se*YPos; QRec = [Pd y Xdim-2*Pd Sz]; %-Question PRec = [Pd y floor(a*Xdim)-2*Pd Sz]; %-Prompt RRec = [ceil(a*Xdim) y+Yo floor((1-a)*Xdim)-Pd Sz]; %-Response % MRec = [010 y Xdim-50 Sz]; %-Menu PullDown % BRec = MRec + [Xdim-50+1, 0+1, 50-Xdim+30, 0]; %-Menu PullDown OK butt if ~isempty(rec) varargout = {eval(rec)}; else varargout = {FRec,QRec,PRec,RRec,Sz,Se}; end case '!deleteinputobj' %======================================================================= % spm_input('!DeleteInputObj',F) if nargin<2, F='Interactive'; else, F=varargin{2}; end h = spm_input('!FindInputObj',F); delete(h(h>0)) case {'!currentpos','!findinputobj'} %======================================================================= % [CPos,hCPos] = spm_input('!CurrentPos',F) % h = spm_input('!FindInputObj',F) % hPos contains handles: Columns contain handles corresponding to Pos if nargin<2, F='Interactive'; else, F=varargin{2}; end F = spm_figure('FindWin',F); %-Find tags and YPos positions of 'GUIinput_' 'Tag'ged objects H = []; YPos = []; for h = get(F,'Children')' tmp = get(h,'Tag'); if ~isempty(tmp) if strcmp(tmp(1:min(length(tmp),9)),'GUIinput_') H = [H, h]; YPos = [YPos, eval(tmp(10:end))]; end end end switch lower(Type), case '!findinputobj' varargout = {H}; case '!currentpos' if nargout<2 varargout = {max(YPos),[]}; elseif isempty(H) varargout = {[],[]}; else %-Sort out tmp = sort(YPos); CPos = tmp(find([1,diff(tmp)])); nPos = length(CPos); nPerPos = diff(find([1,diff(tmp),1])); hCPos = zeros(max(nPerPos),nPos); for i = 1:nPos hCPos(1:nPerPos(i),i) = H(YPos==CPos(i))'; end varargout = {CPos,hCPos}; end end case '!nextpos' %======================================================================= % [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine) %-Return next position to use if nargin<3, F='Interactive'; else, F=varargin{3}; end if nargin<2, YPos='+1'; else, YPos=varargin{2}; end if nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos); else, CmdLine=varargin{4}; end F = spm_figure('FindWin',F); %-Get current positions if nargout<3 CPos = spm_input('!CurrentPos',F); hCPos = []; else [CPos,hCPos] = spm_input('!CurrentPos',F); end if CmdLine NPos = 0; else MPos = spm_input('!MaxPos',F); if ischar(YPos) %-Relative YPos %-Strip any '!' prefix from YPos if(YPos(1)=='!'), YPos(1)=[]; end if strncmp(YPos,'_',1) %-YPos='_' means bottom YPos=eval(['MPos+',YPos(2:end)],'MPos'); else YPos = max([0,CPos])+eval(YPos); end else %-Absolute YPos YPos=abs(YPos); end NPos = min(max(1,YPos),MPos); end varargout = {NPos,CPos,hCPos}; case '!setnextpos' %======================================================================= % NPos = spm_input('!SetNextPos',YPos,F,CmdLine) %-Set next position to use if nargin<3, F='Interactive'; else, F=varargin{3}; end if nargin<2, YPos='+1'; else, YPos=varargin{2}; end if nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos); else, CmdLine=varargin{4}; end %-Find out which Y-position to use [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine); %-Delete any previous inputs using positions NPos and after if any(CPos>=NPos), h=hCPos(:,CPos>=NPos); delete(h(h>0)), end varargout = {NPos}; case '!maxpos' %======================================================================= % MPos = spm_input('!MaxPos',F,FRec3) % if nargin<3 if nargin<2, F='Interactive'; else, F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F) FRec3=spm('WinSize','Interactive')*[0;0;0;1]; else %-Get figure size Units = get(F,'Units'); set(F,'Units','pixels') FRec3 = get(F,'Position')*[0;0;0;1]; set(F,'Units',Units); end end Se = round(25*min(spm('WinScale'))); MPos = floor((FRec3-5)/Se); varargout = {MPos}; case '!editablekeypressfcn' %======================================================================= % spm_input('!EditableKeyPressFcn',h,ch,hPrmpt) if nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end if isempty(h), set(gcbf,'KeyPressFcn','','UserData',[]), return, end if nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else, ch=varargin{3};end if nargin<4, hPrmpt=get(h,'UserData'); else, hPrmpt=varargin{4}; end tmp = get(h,'String'); if isempty(tmp), tmp=''; end if iscellstr(tmp) & length(tmp)==1; tmp=tmp{:}; end if isempty(ch) %- shift / control / &c. pressed return elseif any(abs(ch)==[32:126]) %-Character if iscellstr(tmp), return, end tmp = [tmp, ch]; elseif abs(ch)==21 %- ^U - kill tmp = ''; elseif any(abs(ch)==[8,127]) %-BackSpace or Delete if iscellstr(tmp), return, end if length(tmp), tmp(length(tmp))=''; end elseif abs(ch)==13 %-Return pressed if ~isempty(tmp) set(hPrmpt,'UserData',get(h,'String')) end return else %-Illegal character return end set(h,'String',tmp) case '!buttonkeypressfcn' %======================================================================= % spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch) %-Callback for KeyPress, to store valid button # in UserData of Prompt, % DefItem if (DefItem~=0) & return (ASCII-13) is pressed %-Condition arguments if nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end if isempty(h), set(gcf,'KeyPressFcn','','UserData',[]), return, end if nargin<3, error('Insufficient arguments'); else, Keys=varargin{3}; end if nargin<4, DefItem=0; else, DefItem=varargin{4}; end if nargin<5, ch=get(gcf,'CurrentCharacter'); else, ch=varargin{5}; end if isempty(ch) %- shift / control / &c. pressed return elseif (DefItem & ch==13) But = DefItem; else But = find(lower(ch)==lower(Keys)); end if ~isempty(But), set(h,'UserData',But), end case '!pulldownkeypressfcn' %======================================================================= % spm_input('!PullDownKeyPressFcn',h,ch,DefItem) if nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end if isempty(h), set(gcf,'KeyPressFcn',''), return, end if nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else, ch=varargin{3};end if nargin<4, DefItem=get(h,'UserData'); else, ch=varargin{4}; end Pmax = get(h,'Max'); Pval = get(h,'Value'); if Pmax==1, return, end if isempty(ch) %- shift / control / &c. pressed return elseif abs(ch)==13 if Pval==1 if DefItem, set(h,'Value',max(2,min(DefItem+1,Pmax))), end else set(h,'UserData','Selected') end elseif any(ch=='bpu') %-Move "b"ack "u"p to "p"revious entry set(h,'Value',max(2,Pval-1)) elseif any(ch=='fnd') %-Move "f"orward "d"own to "n"ext entry set(h,'Value',min(Pval+1,Pmax)) elseif any(ch=='123456789') %-Move to entry n set(h,'Value',max(2,min(eval(ch)+1,Pmax))) else %-Illegal character end case '!m_cb' %-CallBack handler for extended CallBack 'p'ullDown type %======================================================================= % spm_input('!m_cb') %-Get PopUp handle and value h = gcbo; n = get(h,'Value'); %-Get PopUp's UserData, check cb and UD fields exist, extract cb & UD tmp = get(h,'UserData'); if ~(isfield(tmp,'cb') & isfield(tmp,'UD')) error('Invalid UserData structure for spm_input extended callback') end cb = tmp.cb; UD = tmp.UD; %-Evaluate appropriate CallBack string (ignoring any return arguments) % NB: Using varargout={eval(cb{n})}; gives an error if the CallBack % has no return arguments! if length(cb)==1, eval(char(cb)); else, eval(cb{n}); end case '!dscroll' %======================================================================= % spm_input('!dScroll',h,Prompt) %-Scroll text in object h if nargin<2, return, else, h=varargin{2}; end if nargin<3, Prompt = get(h,'UserData'); else, Prompt=varargin{3}; end tmp = Prompt; if length(Prompt)>56 while length(tmp)>56 tic, while(toc<0.1), pause(0.05), end tmp(1)=[]; set(h,'String',tmp(1:min(length(tmp),56))) end pause(1) set(h,'String',Prompt(1:min(length(Prompt),56))) end otherwise %======================================================================= error(['Invalid type/action: ',Type]) %======================================================================= end % (case lower(Type)) %======================================================================= %- S U B - F U N C T I O N S %======================================================================= function [Keys,Labs] = sf_labkeys(Labels) %======================================================================= %-Make unique character keys for the Labels, ignoring case if nargin<1, error('insufficient arguments'), end if iscellstr(Labels), Labels = char(Labels); end if isempty(Labels), Keys=''; Labs=''; return, end Keys=Labels(:,1)'; nLabels = size(Labels,1); if any(~diff(abs(sort(lower(Keys))))) if nLabels<10 Keys = sprintf('%d',[1:nLabels]); elseif nLabels<=26 Keys = sprintf('%c',abs('a')+[0:nLabels-1]); else error('Too many buttons!') end Labs = Labels; else Labs = Labels(:,2:end); end function [p,msg] = sf_eEval(str,Type,n,m) %======================================================================= %-Evaluation and error trapping of typed input if nargin<4, m=[]; end if nargin<3, n=[]; end if nargin<2, Type='e'; end if nargin<1, str=''; end if isempty(str), p='!'; msg='empty input'; return, end switch lower(Type) case 's' p = str; msg = ''; case 'e' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; else [p,msg] = sf_SzChk(p,n); end case 'n' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:)|p(:)<1)|~isreal(p) p='!'; msg='natural number(s) required'; elseif ~isempty(m) & any(p(:)>m) p='!'; msg=['max value is ',num2str(m)]; else [p,msg] = sf_SzChk(p,n); end case 'w' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:)|p(:)<0)|~isreal(p) p='!'; msg='whole number(s) required'; elseif ~isempty(m) & any(p(:)>m) p='!'; msg=['max value is ',num2str(m)]; else [p,msg] = sf_SzChk(p,n); end case 'i' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:))|~isreal(p) p='!'; msg='integer(s) required'; else [p,msg] = sf_SzChk(p,n); end case 'p' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif length(setxor(p(:)',m)) p='!'; msg='invalid permutation'; else [p,msg] = sf_SzChk(p,n); end case 'r' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif ~isreal(p) p='!'; msg='real number(s) required'; elseif ~isempty(m) & ( max(p)>max(m) | min(p)<min(m) ) p='!'; msg=sprintf('real(s) in [%g,%g] required',min(m),max(m)); else [p,msg] = sf_SzChk(p,n); end case 'c' if isempty(m), m=Inf; end [p,msg] = spm_input('!iCond',str,n,m); case 'x' X = m; %-Design matrix/space-structure if isempty(n), n=1; end %-Sort out contrast matrix dimensions (contrast vectors in rows) if length(n)==1, n=[n,Inf]; else, n=reshape(n(1:2),1,2); end if ~isempty(X) % - override n(2) w/ design column dimension n(2) = spm_SpUtil('size',X,2); end p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; else if isfinite(n(2)) & size(p,2)<n(2) tmp = n(2) -size(p,2); p = [p, zeros(size(p,1),tmp)]; if size(p,1)>1, str=' columns'; else, str='s'; end msg = sprintf('right padded with %d zero%s',tmp,str); else msg = ''; end if size(p,2)>n(2) p='!'; msg=sprintf('too long - only %d prams',n(2)); elseif isfinite(n(1)) & size(p,1)~=n(1) p='!'; if n(1)==1, msg='vector required'; else, msg=sprintf('%d contrasts required',n(1)); end elseif ~isempty(X) & ~spm_SpUtil('allCon',X,p') p='!'; msg='invalid contrast'; end end otherwise error('unrecognised type'); end function str = sf_SzStr(n,l) %======================================================================= %-Size info string constuction if nargin<2, l=0; else, l=1; end if nargin<1, error('insufficient arguments'), end if isempty(n), n=NaN; end n=n(:); if length(n)==1, n=[n,1]; end, dn=length(n); if any(isnan(n)) | (prod(n)==1 & dn<=2) | (dn==2 & min(n)==1 & isinf(max(n))) str = ''; lstr = ''; elseif dn==2 & min(n)==1 str = sprintf('[%d]',max(n)); lstr = [str,'-vector']; elseif dn==2 & sum(isinf(n))==1 str = sprintf('[%d]',min(n)); lstr = [str,'-vector(s)']; else str=''; for i = 1:dn if isfinite(n(i)), str = sprintf('%s,%d',str,n(i)); else, str = sprintf('%s,*',str); end end str = ['[',str(2:end),']']; lstr = [str,'-matrix']; end if l, str=sprintf('\t%s',lstr); else, str=[str,' ']; end function [p,msg] = sf_SzChk(p,n,msg) %======================================================================= %-Size checking if nargin<3, msg=''; end if nargin<2, n=[]; end, if isempty(n), n=NaN; else, n=n(:)'; end if nargin<1, error('insufficient arguments'), end if ischar(p) | any(isnan(n(:))), return, end if length(n)==1, n=[n,1]; end dn = length(n); sp = size(p); dp = ndims(p); if dn==2 & min(n)==1 %-[1,1], [1,n], [n,1], [1,Inf], [Inf,1] - vector - allow transpose %--------------------------------------------------------------- i = min(find(n==max(n))); if n(i)==1 & max(sp)>1 p='!'; msg='scalar required'; elseif ndims(p)~=2 | ~any(sp==1) | ( isfinite(n(i)) & max(sp)~=n(i) ) %-error: Not2D | not vector | not right length if isfinite(n(i)), str=sprintf('%d-',n(i)); else, str=''; end p='!'; msg=[str,'vector required']; elseif sp(i)==1 & n(i)~=1 p=p'; msg=[msg,' (input transposed)']; end elseif dn==2 & sum(isinf(n))==1 %-[n,Inf], [Inf,n] - n vector(s) required - allow transposing %--------------------------------------------------------------- i = find(isfinite(n)); if ndims(p)~=2 | ~any(sp==n(i)) p='!'; msg=sprintf('%d-vector(s) required',min(n)); elseif sp(i)~=n p=p'; msg=[msg,' (input transposed)']; end else %-multi-dimensional matrix required - check dimensions %--------------------------------------------------------------- if ndims(p)~=dn | ~all( size(p)==n | isinf(n) ) p = '!'; msg=''; for i = 1:dn if isfinite(n(i)), msg = sprintf('%s,%d',msg,n(i)); else, msg = sprintf('%s,*',msg); end end msg = ['[',msg(2:end),']-matrix required']; end end %========================================================================== function uifocus(h) try if strcmpi(get(h, 'Style'), 'PushButton') == 1 uicontrol(gcbo); else uicontrol(h); end end
github
lcnbeapp/beapp-master
spm_write_sn.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_write_sn.m
20,195
utf_8
5bb2c4d938b07e035b1552465111fcf7
function VO = spm_write_sn(V,prm,flags,extras) % Write Out Warped Images. % FORMAT VO = spm_write_sn(V,matname,flags,msk) % V - Images to transform (filenames or volume structure). % matname - Transformation information (filename or structure). % flags - flags structure, with fields... % interp - interpolation method (0-7) % wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences) % vox - voxel sizes (3 element vector - in mm) % Non-finite values mean use template vox. % bb - bounding box (2x3 matrix - in mm) % Non-finite values mean use template bb. % preserve - either 0 or 1. A value of 1 will "modulate" % the spatially normalised images so that total % units are preserved, rather than just % concentrations. % prefix - Prefix for normalised images. Defaults to 'w'. % msk - An optional cell array for masking the spatially % normalised images (see below). % % Warped images are written prefixed by "w". % % Non-finite vox or bounding box suggests that values should be derived % from the template image. % % Don't use interpolation methods greater than one for data containing % NaNs. % _______________________________________________________________________ % % FORMAT msk = spm_write_sn(V,matname,flags,'mask') % V - Images to transform (filenames or volume structure). % matname - Transformation information (filename or structure). % flags - flags structure, with fields... % wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences) % vox - voxel sizes (3 element vector - in mm) % Non-finite values mean use template vox. % bb - bounding box (2x3 matrix - in mm) % Non-finite values mean use template bb. % msk - a cell array for masking a series of spatially normalised % images. % % % _______________________________________________________________________ % % FORMAT VO = spm_write_sn(V,prm,'modulate') % V - Spatially normalised images to modulate (filenames or % volume structure). % prm - Transformation information (filename or structure). % % After nonlinear spatial normalization, the relative volumes of some % brain structures will have decreased, whereas others will increase. % The resampling of the images preserves the concentration of pixel % units in the images, so the total counts from structures that have % reduced volumes after spatial normalization will be reduced by an % amount proportional to the volume reduction. % % This routine rescales images after spatial normalization, so that % the total counts from any structure are preserved. It was written % as an optional step in performing voxel based morphometry. % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ if isempty(V), return; end; if ischar(prm), prm = load(prm); end; if ischar(V), V = spm_vol(V); end; if nargin==3 && ischar(flags) && strcmpi(flags,'modulate'), if nargout==0, modulate(V,prm); else VO = modulate(V,prm); end; return; end; def_flags = struct('interp',1,'vox',NaN,'bb',NaN,'wrap',[0 0 0],'preserve',0,... 'prefix','w'); if nargin < 3, flags = def_flags; else fnms = fieldnames(def_flags); for i=1:length(fnms), if ~isfield(flags,fnms{i}), flags.(fnms{i}) = def_flags.(fnms{i}); end; end; end; [x,y,z,mat] = get_xyzmat(prm,flags.bb,flags.vox); if nargin==4, if ischar(extras) && strcmpi(extras,'mask'), VO = get_snmask(V,prm,x,y,z,flags.wrap); return; end; if iscell(extras), msk = extras; end; end; if nargout>0 && length(V)>8, error('Too many images to save in memory'); end; if ~exist('msk','var') msk = get_snmask(V,prm,x,y,z,flags.wrap); end; if nargout==0, if isempty(prm.Tr), affine_transform(V,prm,x,y,z,mat,flags,msk); else nonlin_transform(V,prm,x,y,z,mat,flags,msk); end; else if isempty(prm.Tr), VO = affine_transform(V,prm,x,y,z,mat,flags,msk); else VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = affine_transform(V,prm,x,y,z,mat,flags,msk) [X,Y] = ndgrid(x,y); d = [flags.interp*[1 1 1]' flags.wrap(:)]; spm_progress_bar('Init',numel(V),'Resampling','volumes/slices completed'); for i=1:numel(V), VO = make_hdr_struct(V(i),x,y,z,mat, flags.prefix); if flags.preserve VO.fname = prepend(VO.fname,'m'); end detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); if flags.preserve, VO.pinfo(1:2,:) = VO.pinfo(1:2,:)/detAff; end; %Dat= zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; C = spm_bsplinc(V(i),d); for j=1:length(z), % Cycle over planes [X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF(1).mat*prm.Affine); dat = spm_bsplins(C,X2,Y2,Z2,d); if flags.preserve, dat = dat*detAff; end; dat(msk{j}) = NaN; Dat(:,:,j) = single(dat); if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; if nargout~=0, VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; else spm_write_vol(VO, Dat); end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk) [X,Y] = ndgrid(x,y); Tr = prm.Tr; BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); if flags.preserve, DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff'); DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff'); DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff'); end; d = [flags.interp*[1 1 1]' flags.wrap(:)]; spm_progress_bar('Init',numel(V),'Resampling','volumes completed'); for i=1:numel(V), VO = make_hdr_struct(V(i),x,y,z,mat, flags.prefix); if flags.preserve VO.fname = prepend(VO.fname,'m'); end detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); % Accumulate data %Dat= zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; C = spm_bsplinc(V(i),d); for j=1:length(z), % Cycle over planes % Nonlinear deformations %---------------------------------------------------------------------------- tx = get_2Dtrans(Tr(:,:,:,1),BZ,j); ty = get_2Dtrans(Tr(:,:,:,2),BZ,j); tz = get_2Dtrans(Tr(:,:,:,3),BZ,j); X1 = X + BX*tx*BY'; Y1 = Y + BX*ty*BY'; Z1 = z(j) + BX*tz*BY'; [X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF(1).mat*prm.Affine); dat = spm_bsplins(C,X2,Y2,Z2,d); dat(msk{j}) = NaN; if ~flags.preserve, Dat(:,:,j) = single(dat); else j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY'; j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY'; j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1; % The determinant of the Jacobian reflects relative volume changes. %------------------------------------------------------------------ dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff; Dat(:,:,j) = single(dat); end; if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; if nargout==0, if flags.preserve, VO = rmfield(VO,'pinfo'); end VO = spm_write_vol(VO,Dat); else VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = modulate(V,prm) spm_progress_bar('Init',numel(V),'Modulating','volumes completed'); for i=1:numel(V), VO = V(i); VO = rmfield(VO,'pinfo'); VO.fname = prepend(VO.fname,'m'); detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); %Dat = zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; [x,y,z,mat] = get_xyzmat(prm,NaN,NaN,VO); if sum((mat(:)-VO.mat(:)).^2)>1e-7, error('Orientations not compatible'); end; Tr = prm.Tr; if isempty(Tr), for j=1:length(z), % Cycle over planes dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0); Dat(:,:,j) = single(dat); if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; else BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff'); DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff'); DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff'); for j=1:length(z), % Cycle over planes tx = get_2Dtrans(Tr(:,:,:,1),BZ,j); ty = get_2Dtrans(Tr(:,:,:,2),BZ,j); tz = get_2Dtrans(Tr(:,:,:,3),BZ,j); j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY'; j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY'; j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1; % The determinant of the Jacobian reflects relative volume changes. %------------------------------------------------------------------ dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0); dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff; Dat(:,:,j) = single(dat); if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; end; if nargout==0, VO = spm_write_vol(VO,Dat); else VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = make_hdr_struct(V,x,y,z,mat,prefix) VO = V; VO.fname = prepend(V.fname,prefix); VO.mat = mat; VO.dim(1:3) = [length(x) length(y) length(z)]; VO.pinfo = V.pinfo; VO.descrip = 'spm - 3D normalized'; return; %_______________________________________________________________________ %_______________________________________________________________________ function T2 = get_2Dtrans(T3,B,j) d = [size(T3) 1 1 1]; tmp = reshape(T3,d(1)*d(2),d(3)); T2 = reshape(tmp*B(j,:)',d(1),d(2)); return; %_______________________________________________________________________ %_______________________________________________________________________ function PO = prepend(PI,pre) [pth,nm,xt,vr] = spm_fileparts(deblank(PI)); PO = fullfile(pth,[pre nm xt vr]); return; %_______________________________________________________________________ %_______________________________________________________________________ function Mask = getmask(X,Y,Z,dim,wrp) % Find range of slice tiny = 5e-2; Mask = true(size(X)); if ~wrp(1), Mask = Mask & (X >= (1-tiny) & X <= (dim(1)+tiny)); end; if ~wrp(2), Mask = Mask & (Y >= (1-tiny) & Y <= (dim(2)+tiny)); end; if ~wrp(3), Mask = Mask & (Z >= (1-tiny) & Z <= (dim(3)+tiny)); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [X2,Y2,Z2] = mmult(X1,Y1,Z1,Mult) if length(Z1) == 1, X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + (Mult(1,3)*Z1 + Mult(1,4)); Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + (Mult(2,3)*Z1 + Mult(2,4)); Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + (Mult(3,3)*Z1 + Mult(3,4)); else X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4); Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4); Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function msk = get_snmask(V,prm,x,y,z,wrap) % Generate a mask for where there is data for all images %----------------------------------------------------------------------- msk = cell(length(z),1); t1 = cat(3,V.mat); t2 = cat(1,V.dim); t = [reshape(t1,[16 length(V)])' t2(:,1:3)]; Tr = prm.Tr; [X,Y] = ndgrid(x,y); BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); if numel(V)>1 && any(any(diff(t,1,1))), spm_progress_bar('Init',length(z),'Computing available voxels','planes completed'); for j=1:length(z), % Cycle over planes Count = zeros(length(x),length(y)); if isempty(Tr), % Generate a mask for where there is data for all images %---------------------------------------------------------------------------- for i=1:numel(V), [X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF(1).mat*prm.Affine); Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap); end; else % Nonlinear deformations %---------------------------------------------------------------------------- X1 = X + BX*get_2Dtrans(Tr(:,:,:,1),BZ,j)*BY'; Y1 = Y + BX*get_2Dtrans(Tr(:,:,:,2),BZ,j)*BY'; Z1 = z(j) + BX*get_2Dtrans(Tr(:,:,:,3),BZ,j)*BY'; % Generate a mask for where there is data for all images %---------------------------------------------------------------------------- for i=1:numel(V), [X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF(1).mat*prm.Affine); Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap); end; end; msk{j} = uint32(find(Count ~= numel(V))); spm_progress_bar('Set',j); end; spm_progress_bar('Clear'); else for j=1:length(z), msk{j} = uint32([]); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [x,y,z,mat] = get_xyzmat(prm,bb,vox,VG) % The old voxel size and origin notation is used here. % This requires that the position and orientation % of the template is transverse. It would not be % straitforward to account for templates that are % in different orientations because the basis functions % would no longer be seperable. The seperable basis % functions mean that computing the deformation field % from the parameters is much faster. % bb = sort(bb); % vox = abs(vox); if nargin<4, VG = prm.VG(1); if all(~isfinite(bb(:))) && all(~isfinite(vox(:))), x = 1:VG.dim(1); y = 1:VG.dim(2); z = 1:VG.dim(3); mat = VG.mat; return; end end [bb0,vox0] = bbvox_from_V(VG); if ~all(isfinite(vox(:))), vox = vox0; end; if ~all(isfinite(bb(:))), bb = bb0; end; msk = find(vox<0); bb = sort(bb); bb(:,msk) = flipud(bb(:,msk)); % Adjust bounding box slightly - so it rounds to closest voxel. % Comment out if not needed. %bb(:,1) = round(bb(:,1)/vox(1))*vox(1); %bb(:,2) = round(bb(:,2)/vox(2))*vox(2); %bb(:,3) = round(bb(:,3)/vox(3))*vox(3); M = prm.VG(1).mat; vxg = sqrt(sum(M(1:3,1:3).^2)); if det(M(1:3,1:3))<0, vxg(1) = -vxg(1); end; ogn = M\[0 0 0 1]'; ogn = ogn(1:3)'; % Convert range into range of voxels within template image x = (bb(1,1):vox(1):bb(2,1))/vxg(1) + ogn(1); y = (bb(1,2):vox(2):bb(2,2))/vxg(2) + ogn(2); z = (bb(1,3):vox(3):bb(2,3))/vxg(3) + ogn(3); og = -vxg.*ogn; % Again, chose whether to round to closest voxel. %of = -vox.*(round(-bb(1,:)./vox)+1); of = bb(1,:)-vox; M1 = [vxg(1) 0 0 og(1) ; 0 vxg(2) 0 og(2) ; 0 0 vxg(3) og(3) ; 0 0 0 1]; M2 = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1]; mat = prm.VG(1).mat*inv(M1)*M2; LEFTHANDED = true; if (LEFTHANDED && det(mat(1:3,1:3))>0) || (~LEFTHANDED && det(mat(1:3,1:3))<0), Flp = [-1 0 0 (length(x)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1]; mat = mat*Flp; x = flipud(x(:))'; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [bb,vx] = bbvox_from_V(V) vx = sqrt(sum(V.mat(1:3,1:3).^2)); if det(V.mat(1:3,1:3))<0, vx(1) = -vx(1); end; o = V.mat\[0 0 0 1]'; o = o(1:3)'; bb = [-vx.*(o-1) ; vx.*(V.dim(1:3)-o)]; return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = write_dets(P,bb,vox) if nargin==1, job = P; P = job.P; bb = job.bb; vox = job.vox; end; spm_progress_bar('Init',numel(P),'Writing','volumes completed'); for i=1:numel(V), prm = load(deblank(P{i})); [x,y,z,mat] = get_xyzmat(prm,bb,vox); Tr = prm.Tr; BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff'); DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff'); DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff'); [pth,nam,ext,nm] = spm_fileparts(P{i}); VO = struct('fname',fullfile(pth,['jy_' nam ext nm]),... 'dim',[numel(x),numel(y),numel(z)],... 'dt',[spm_type('float32') spm_platform('bigend')],... 'pinfo',[1 0 0]',... 'mat',mat,... 'n',1,... 'descrip','Jacobian determinants'); VO = spm_create_vol(VO); detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; for j=1:length(z), % Cycle over planes % Nonlinear deformations tx = get_2Dtrans(Tr(:,:,:,1),BZ,j); ty = get_2Dtrans(Tr(:,:,:,2),BZ,j); tz = get_2Dtrans(Tr(:,:,:,3),BZ,j); %---------------------------------------------------------------------------- j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY'; j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY'; j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1; % The determinant of the Jacobian reflects relative volume changes. %------------------------------------------------------------------ dat = (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff; Dat(:,:,j) = single(dat); if numel(P)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; VO = spm_write_vol(VO,Dat); spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________
github
lcnbeapp/beapp-master
spm_imatrix.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_imatrix.m
1,499
utf_8
295b97abf7200bfd1af63c3e32aae6fd
function P = spm_imatrix(M) % returns the parameters for creating an affine transformation % FORMAT P = spm_imatrix(M) % M - Affine transformation matrix % P - Parameters (see spm_matrix for definitions) %___________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner & Stefan Kiebel % $Id$ % Translations and zooms %----------------------------------------------------------------------- R = M(1:3,1:3); C = chol(R'*R); P = [M(1:3,4)' 0 0 0 diag(C)' 0 0 0]; if det(R)<0, P(7)=-P(7);end % Fix for -ve determinants % Shears %----------------------------------------------------------------------- C = diag(diag(C))\C; P(10:12) = C([4 7 8]); R0 = spm_matrix([0 0 0 0 0 0 P(7:12)]); R0 = R0(1:3,1:3); R1 = R/R0; % This just leaves rotations in matrix R1 %----------------------------------------------------------------------- %[ c5*c6, c5*s6, s5] %[-s4*s5*c6-c4*s6, -s4*s5*s6+c4*c6, s4*c5] %[-c4*s5*c6+s4*s6, -c4*s5*s6-s4*c6, c4*c5] P(5) = asin(rang(R1(1,3))); if (abs(P(5))-pi/2)^2 < 1e-9, P(4) = 0; P(6) = atan2(-rang(R1(2,1)), rang(-R1(3,1)/R1(1,3))); else c = cos(P(5)); P(4) = atan2(rang(R1(2,3)/c), rang(R1(3,3)/c)); P(6) = atan2(rang(R1(1,2)/c), rang(R1(1,1)/c)); end; return; % There may be slight rounding errors making b>1 or b<-1. function a = rang(b) a = min(max(b, -1), 1); return;
github
lcnbeapp/beapp-master
spm_affreg.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_affreg.m
20,248
utf_8
431e3807877742bdec89d07ce61e87f8
function [M,scal] = spm_affreg(VG,VF,flags,M,scal) % Affine registration using least squares. % FORMAT [M,scal] = spm_affreg(VG,VF,flags,M0,scal0) % % VG - Vector of template volumes. % VF - Source volume. % flags - a structure containing various options. The fields are: % WG - Weighting volume for template image(s). % WF - Weighting volume for source image % Default to []. % sep - Approximate spacing between sampled points (mm). % Defaults to 5. % regtype - regularisation type. Options are: % 'none' - no regularisation % 'rigid' - almost rigid body % 'subj' - inter-subject registration (default). % 'mni' - registration to ICBM templates % globnorm - Global normalisation flag (1) % M0 - (optional) starting estimate. Defaults to eye(4). % scal0 - (optional) starting estimate. % % M - affine transform, such that voxels in VF map to those in % VG by VG.mat\M*VF.mat % scal - scaling factors for VG % % When only one template is used, then the cost function is approximately % symmetric, although a linear combination of templates can be used. % Regularisation is based on assuming a multi-normal distribution for the % elements of the Henckey Tensor. See: % "Non-linear Elastic Deformations". R. W. Ogden (Dover), 1984. % Weighting for the regularisation is determined approximately according % to: % "Incorporating Prior Knowledge into Image Registration" % J. Ashburner, P. Neelin, D. L. Collins, A. C. Evans & K. J. Friston. % NeuroImage 6:344-352 (1997). % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ if nargin<5, scal = ones(length(VG),1); end; if nargin<4, M = eye(4); end; def_flags = struct('sep',5, 'regtype','subj','WG',[],'WF',[],'globnorm',1,'debug',0); if nargin < 2 || ~isstruct(flags), flags = def_flags; else fnms = fieldnames(def_flags); for i=1:length(fnms), if ~isfield(flags,fnms{i}), flags.(fnms{i}) = def_flags.(fnms{i}); end; end; end; % Check to ensure inputs are valid... % --------------------------------------------------------------- if length(VF)>1, error('Can not use more than one source image'); end; if ~isempty(flags.WF), if length(flags.WF)>1, error('Can only use one source weighting image'); end; if any(any((VF.mat-flags.WF.mat).^2>1e-8)), error('Source and its weighting image must have same orientation'); end; if any(any(VF.dim(1:3)-flags.WF.dim(1:3))), error('Source and its weighting image must have same dimensions'); end; end; if ~isempty(flags.WG), if length(flags.WG)>1, error('Can only use one template weighting image'); end; tmp = reshape(cat(3,VG(:).mat,flags.WG.mat),16,length(VG)+length(flags.WG)); else tmp = reshape(cat(3,VG(:).mat),16,length(VG)); end; if any(any(diff(tmp,1,2).^2>1e-8)), error('Reference images must all have the same orientation'); end; if ~isempty(flags.WG), tmp = cat(1,VG(:).dim,flags.WG.dim); else tmp = cat(1,VG(:).dim); end; if any(any(diff(tmp(:,1:3),1,1))), error('Reference images must all have the same dimensions'); end; % --------------------------------------------------------------- % Generate points to sample from, adding some jitter in order to % make the cost function smoother. % --------------------------------------------------------------- rand('state',0); % want the results to be consistant. dg = VG(1).dim(1:3); df = VF(1).dim(1:3); if length(VG)==1, skip = sqrt(sum(VG(1).mat(1:3,1:3).^2)).^(-1)*flags.sep; [x1,x2,x3]=ndgrid(1:skip(1):dg(1)-.5, 1:skip(2):dg(2)-.5, 1:skip(3):dg(3)-.5); x1 = x1 + rand(size(x1))*0.5; x1 = x1(:); x2 = x2 + rand(size(x2))*0.5; x2 = x2(:); x3 = x3 + rand(size(x3))*0.5; x3 = x3(:); end; skip = sqrt(sum(VF(1).mat(1:3,1:3).^2)).^(-1)*flags.sep; [y1,y2,y3]=ndgrid(1:skip(1):df(1)-.5, 1:skip(2):df(2)-.5, 1:skip(3):df(3)-.5); y1 = y1 + rand(size(y1))*0.5; y1 = y1(:); y2 = y2 + rand(size(y2))*0.5; y2 = y2(:); y3 = y3 + rand(size(y3))*0.5; y3 = y3(:); % --------------------------------------------------------------- if flags.globnorm, % Scale all images approximately equally % --------------------------------------------------------------- for i=1:length(VG), VG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i)); end; VF(1).pinfo(1:2,:) = VF(1).pinfo(1:2,:)/spm_global(VF(1)); end; % --------------------------------------------------------------- if length(VG)==1, [G,dG1,dG2,dG3] = spm_sample_vol(VG(1),x1,x2,x3,1); if ~isempty(flags.WG), WG = abs(spm_sample_vol(flags.WG,x1,x2,x3,1))+eps; WG(~isfinite(WG)) = 1; end; end; [F,dF1,dF2,dF3] = spm_sample_vol(VF(1),y1,y2,y3,1); if ~isempty(flags.WF), WF = abs(spm_sample_vol(flags.WF,y1,y2,y3,1))+eps; WF(~isfinite(WF)) = 1; end; % --------------------------------------------------------------- n_main_its = 0; ss = Inf; W = [Inf Inf Inf]; est_smo = 1; % --------------------------------------------------------------- for iter=1:256, pss = ss; p0 = [0 0 0 0 0 0 1 1 1 0 0 0]; % Initialise the cost function and its 1st and second derivatives % --------------------------------------------------------------- n = 0; ss = 0; Beta = zeros(12+length(VG),1); Alpha = zeros(12+length(VG)); if length(VG)==1, % Make the cost function symmetric % --------------------------------------------------------------- % Build a matrix to rotate the derivatives by, converting from % derivatives w.r.t. changes in the overall affine transformation % matrix, to derivatives w.r.t. the parameters p. % --------------------------------------------------------------- dt = 0.0001; R = eye(13); MM0 = inv(VG.mat)*inv(spm_matrix(p0))*VG.mat; for i1=1:12, p1 = p0; p1(i1) = p1(i1)+dt; MM1 = (inv(VG.mat)*inv(spm_matrix(p1))*(VG.mat)); R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1); end; % --------------------------------------------------------------- [t1,t2,t3] = coords((M*VF(1).mat)\VG(1).mat,x1,x2,x3); msk = find((t1>=1 & t1<=df(1) & t2>=1 & t2<=df(2) & t3>=1 & t3<=df(3))); if length(msk)<32, error_message; end; t1 = t1(msk); t2 = t2(msk); t3 = t3(msk); t = spm_sample_vol(VF(1), t1,t2,t3,1); % Get weights % --------------------------------------------------------------- if ~isempty(flags.WF) || ~isempty(flags.WG), if isempty(flags.WF), wt = WG(msk); else wt = spm_sample_vol(flags.WF(1), t1,t2,t3,1)+eps; wt(~isfinite(wt)) = 1; if ~isempty(flags.WG), wt = 1./(1./wt + 1./WG(msk)); end; end; wt = sparse(1:length(wt),1:length(wt),wt); else % wt = speye(length(msk)); wt = []; end; % --------------------------------------------------------------- clear t1 t2 t3 % Update the cost function and its 1st and second derivatives. % --------------------------------------------------------------- [AA,Ab,ss1,n1] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,scal^(-2)*t,G(msk)-(1/scal)*t,wt); Alpha = Alpha + R'*AA*R; Beta = Beta + R'*Ab; ss = ss + ss1; n = n + n1; % t = G(msk) - (1/scal)*t; end; if 1, % Build a matrix to rotate the derivatives by, converting from % derivatives w.r.t. changes in the overall affine transformation % matrix, to derivatives w.r.t. the parameters p. % --------------------------------------------------------------- dt = 0.0001; R = eye(12+length(VG)); MM0 = inv(M*VF.mat)*spm_matrix(p0)*M*VF.mat; for i1=1:12, p1 = p0; p1(i1) = p1(i1)+dt; MM1 = (inv(M*VF.mat)*spm_matrix(p1)*M*VF.mat); R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1); end; % --------------------------------------------------------------- [t1,t2,t3] = coords(VG(1).mat\M*VF(1).mat,y1,y2,y3); msk = find((t1>=1 & t1<=dg(1) & t2>=1 & t2<=dg(2) & t3>=1 & t3<=dg(3))); if length(msk)<32, error_message; end; if length(msk)<32, error_message; end; t1 = t1(msk); t2 = t2(msk); t3 = t3(msk); t = zeros(length(t1),length(VG)); % Get weights % --------------------------------------------------------------- if ~isempty(flags.WF) || ~isempty(flags.WG), if isempty(flags.WG), wt = WF(msk); else wt = spm_sample_vol(flags.WG(1), t1,t2,t3,1)+eps; wt(~isfinite(wt)) = 1; if ~isempty(flags.WF), wt = 1./(1./wt + 1./WF(msk)); end; end; wt = sparse(1:length(wt),1:length(wt),wt); else wt = speye(length(msk)); end; % --------------------------------------------------------------- if est_smo, % Compute derivatives of residuals in the space of F % --------------------------------------------------------------- [ds1,ds2,ds3] = transform_derivs(VG(1).mat\M*VF(1).mat,dF1(msk),dF2(msk),dF3(msk)); for i=1:length(VG), [t(:,i),dt1,dt2,dt3] = spm_sample_vol(VG(i), t1,t2,t3,1); ds1 = ds1 - dt1*scal(i); clear dt1 ds2 = ds2 - dt2*scal(i); clear dt2 ds3 = ds3 - dt3*scal(i); clear dt3 end; dss = [ds1'*wt*ds1 ds2'*wt*ds2 ds3'*wt*ds3]; clear ds1 ds2 ds3 else for i=1:length(VG), t(:,i)= spm_sample_vol(VG(i), t1,t2,t3,1); end; end; clear t1 t2 t3 % Update the cost function and its 1st and second derivatives. % --------------------------------------------------------------- [AA,Ab,ss2,n2] = costfun(y1,y2,y3,dF1,dF2,dF3,msk,-t,F(msk)-t*scal,wt); Alpha = Alpha + R'*AA*R; Beta = Beta + R'*Ab; ss = ss + ss2; n = n + n2; end; if est_smo, % Compute a smoothness correction from the residuals and their % derivatives. This is analagous to the one used in: % "Analysis of fMRI Time Series Revisited" % Friston KJ, Holmes AP, Poline JB, Grasby PJ, Williams SCR, % Frackowiak RSJ, Turner R. Neuroimage 2:45-53 (1995). % --------------------------------------------------------------- vx = sqrt(sum(VG(1).mat(1:3,1:3).^2)); pW = W; W = (2*dss/ss2).^(-.5).*vx; W = min(pW,W); if flags.debug, fprintf('\nSmoothness FWHM: %.3g x %.3g x %.3g mm\n', W*sqrt(8*log(2))); end; if length(VG)==1, dens=2; else dens=1; end; smo = prod(min(dens*flags.sep/sqrt(2*pi)./W,[1 1 1])); est_smo=0; n_main_its = n_main_its + 1; end; % Update the parameter estimates % --------------------------------------------------------------- nu = n*smo; sig2 = ss/nu; [d1,d2] = reg(M,12+length(VG),flags.regtype); soln = (Alpha/sig2+d2)\(Beta/sig2-d1); scal = scal - soln(13:end); M = spm_matrix(p0 + soln(1:12)')*M; if flags.debug, fprintf('%d\t%g\n', iter, ss/n); piccies(VF,VG,M,scal) end; % If cost function stops decreasing, then re-estimate smoothness % and try again. Repeat a few times. % --------------------------------------------------------------- ss = ss/n; if iter>1, spm_chi2_plot('Set',ss); end; if (pss-ss)/pss < 1e-6, est_smo = 1; end; if n_main_its>3, break; end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [X1,Y1,Z1] = transform_derivs(Mat,X,Y,Z) % Given the derivatives of a scalar function, return those of the % affine transformed function %_______________________________________________________________________ t1 = Mat(1:3,1:3); t2 = eye(3); if sum((t1(:)-t2(:)).^2) < 1e-12, X1 = X;Y1 = Y; Z1 = Z; else X1 = Mat(1,1)*X + Mat(1,2)*Y + Mat(1,3)*Z; Y1 = Mat(2,1)*X + Mat(2,2)*Y + Mat(2,3)*Z; Z1 = Mat(3,1)*X + Mat(3,2)*Y + Mat(3,3)*Z; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [d1,d2] = reg(M,n,typ) % Analytically compute the first and second derivatives of a penalty % function w.r.t. changes in parameters. if nargin<3, typ = 'subj'; end; if nargin<2, n = 13; end; [mu,isig] = priors(typ); ds = 0.000001; d1 = zeros(n,1); d2 = zeros(n); p0 = [0 0 0 0 0 0 1 1 1 0 0 0]; h0 = penalty(p0,M,mu,isig); for i=7:12, % derivatives are zero w.r.t. rotations and translations p1 = p0; p1(i) = p1(i)+ds; h1 = penalty(p1,M,mu,isig); d1(i) = (h1-h0)/ds; % First derivative for j=7:12, p2 = p0; p2(j) = p2(j)+ds; h2 = penalty(p2,M,mu,isig); p3 = p1; p3(j) = p3(j)+ds; h3 = penalty(p3,M,mu,isig); d2(i,j) = ((h3-h2)/ds-(h1-h0)/ds)/ds; % Second derivative end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function h = penalty(p,M,mu,isig) % Return a penalty based on the elements of an affine transformation, % which is given by: % spm_matrix(p)*M % % The penalty is based on the 6 unique elements of the Hencky tensor % elements being multinormally distributed. %_______________________________________________________________________ % Unique elements of symmetric 3x3 matrix. els = [1 2 3 5 6 9]; T = spm_matrix(p)*M; T = T(1:3,1:3); T = 0.5*logm(T'*T); T = T(els)' - mu; h = T'*isig*T; return; %_______________________________________________________________________ %_______________________________________________________________________ function [mu,isig] = priors(typ) % The parameters for this distribution were derived empirically from 227 % scans, that were matched to the ICBM space. %_______________________________________________________________________ mu = zeros(6,1); isig = zeros(6); switch deblank(lower(typ)), case 'mni', % For registering with MNI templates... mu = [0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]'; isig = 1e4 * [ 0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163 -0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116 -0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060 -0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440 -0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062 -0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144]; case 'rigid', % Constrained to be almost rigid... mu = zeros(6,1); isig = eye(6)*1e9; case 'isochoric', % Volume preserving... error('Not implemented'); case 'isotropic', % Isotropic zoom in all directions... error('Not implemented'); case 'subj', % For inter-subject registration... mu = zeros(6,1); isig = 1e3 * [ 0.8876 0.0784 0.0784 -0.1749 0.0784 -0.1749 0.0784 5.3894 0.2655 0.0784 0.2655 0.0784 0.0784 0.2655 5.3894 0.0784 0.2655 0.0784 -0.1749 0.0784 0.0784 0.8876 0.0784 -0.1749 0.0784 0.2655 0.2655 0.0784 5.3894 0.0784 -0.1749 0.0784 0.0784 -0.1749 0.0784 0.8876]; case 'none', % No regularisation... mu = zeros(6,1); isig = zeros(6); otherwise, error(['"' typ '" not recognised as type of regularisation.']); end; return; %_______________________________________________________________________ function [y1,y2,y3]=coords(M,x1,x2,x3) % Affine transformation of a set of coordinates. %_______________________________________________________________________ y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4); y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4); y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4); return; %_______________________________________________________________________ %_______________________________________________________________________ function A = make_A(x1,x2,x3,dG1,dG2,dG3,t) % Generate part of a design matrix using the chain rule... % df/dm = df/dy * dy/dm % where % df/dm is the rate of change of intensity w.r.t. affine parameters % df/dy is the gradient of the image f % dy/dm crange of position w.r.t. change of parameters %_______________________________________________________________________ A = [x1.*dG1 x1.*dG2 x1.*dG3 ... x2.*dG1 x2.*dG2 x2.*dG3 ... x3.*dG1 x3.*dG2 x3.*dG3 ... dG1 dG2 dG3 t]; return; %_______________________________________________________________________ %_______________________________________________________________________ function [AA,Ab,ss,n] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,lastcols,b,wt) chunk = 10240; lm = length(msk); AA = zeros(12+size(lastcols,2)); Ab = zeros(12+size(lastcols,2),1); ss = 0; n = 0; for i=1:ceil(lm/chunk), ind = (((i-1)*chunk+1):min(i*chunk,lm))'; msk1 = msk(ind); A1 = make_A(x1(msk1),x2(msk1),x3(msk1),dG1(msk1),dG2(msk1),dG3(msk1),lastcols(ind,:)); b1 = b(ind); if ~isempty(wt), wt1 = wt(ind,ind); AA = AA + A1'*wt1*A1; %Ab = Ab + A1'*wt1*b1; Ab = Ab + (b1'*wt1*A1)'; ss = ss + b1'*wt1*b1; n = n + trace(wt1); clear wt1 else AA = AA + A1'*A1; %Ab = Ab + A1'*b1; Ab = Ab + (b1'*A1)'; ss = ss + b1'*b1; n = n + length(msk1); end; clear A1 b1 msk1 ind end; return; %_______________________________________________________________________ %_______________________________________________________________________ function error_message % Display an error message for when things go wrong. str = { 'There is not enough overlap in the images',... 'to obtain a solution.',... ' ',... 'Please check that your header information is OK.',... 'The Check Reg utility will show you the initial',... 'alignment between the images, which must be',... 'within about 4cm and about 15 degrees in order',... 'for SPM to find the optimal solution.'}; spm('alert*',str,mfilename,sqrt(-1)); error('insufficient image overlap') %_______________________________________________________________________ %_______________________________________________________________________ function piccies(VF,VG,M,scal) % This is for debugging purposes. % It shows the linear combination of template images, the affine % transformed source image, the residual image and a histogram of the % residuals. %_______________________________________________________________________ figure(2); Mt = spm_matrix([0 0 (VG(1).dim(3)+1)/2]); M = (M*VF(1).mat)\VG(1).mat; t = zeros(VG(1).dim(1:2)); for i=1:length(VG); t = t + spm_slice_vol(VG(i), Mt,VG(1).dim(1:2),1)*scal(i); end; u = spm_slice_vol(VF(1),M*Mt,VG(1).dim(1:2),1); subplot(2,2,1);imagesc(t');axis image xy off subplot(2,2,2);imagesc(u');axis image xy off subplot(2,2,3);imagesc(u'-t');axis image xy off %subplot(2,2,4);hist(b,50); % Entropy of residuals may be a nice cost function? drawnow; return; %_______________________________________________________________________
github
lcnbeapp/beapp-master
spm_vol.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_vol.m
5,475
utf_8
41a73601c2e44259fb8f1f4f3e870558
function V = spm_vol(P) % Get header information etc for images. % FORMAT V = spm_vol(P) % P - a matrix of filenames. % V - a vector of structures containing image volume information. % The elements of the structures are: % V.fname - the filename of the image. % V.dim - the x, y and z dimensions of the volume % V.dt - A 1x2 array. First element is datatype (see spm_type). % The second is 1 or 0 depending on the endian-ness. % V.mat - a 4x4 affine transformation matrix mapping from % voxel coordinates to real world coordinates. % V.pinfo - plane info for each plane of the volume. % V.pinfo(1,:) - scale for each plane % V.pinfo(2,:) - offset for each plane % The true voxel intensities of the jth image are given % by: val*V.pinfo(1,j) + V.pinfo(2,j) % V.pinfo(3,:) - offset into image (in bytes). % If the size of pinfo is 3x1, then the volume is assumed % to be contiguous and each plane has the same scalefactor % and offset. %__________________________________________________________________________ % % The fields listed above are essential for the mex routines, but other % fields can also be incorporated into the structure. % % The images are not memory mapped at this step, but are mapped when % the mex routines using the volume information are called. % % Note that spm_vol can also be applied to the filename(s) of 4-dim % volumes. In that case, the elements of V will point to a series of 3-dim % images. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ if nargin==0, V = struct('fname', {},... 'dim', {},... 'dt', {},... 'pinfo', {},... 'mat', {},... 'n', {},... 'descrip', {},... 'private',{}); return; end; % If is already a vol structure then just return; if isstruct(P), V = P; return; end; V = subfunc2(P); return; %_______________________________________________________________________ %_______________________________________________________________________ function V = subfunc2(P) if iscell(P), V = cell(size(P)); for j=1:numel(P), if iscell(P{j}), V{j} = subfunc2(P{j}); else V{j} = subfunc1(P{j}); end; end; else V = subfunc1(P); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function V = subfunc1(P) if isempty(P), V = []; return; end; counter = 0; for i=1:size(P,1), v = subfunc(P(i,:)); [V(counter+1:counter+size(v, 2),1).fname] = deal(''); [V(counter+1:counter+size(v, 2),1).mat] = deal([0 0 0 0]); [V(counter+1:counter+size(v, 2),1).mat] = deal(eye(4)); [V(counter+1:counter+size(v, 2),1).mat] = deal([1 0 0]'); if isempty(v), hread_error_message(P(i,:)); error(['Can''t get volume information for ''' P(i,:) '''']); end f = fieldnames(v); for j=1:size(f,1) eval(['[V(counter+1:counter+size(v,2),1).' f{j} '] = deal(v.' f{j} ');']); end counter = counter + size(v,2); end return; %_______________________________________________________________________ %_______________________________________________________________________ function V = subfunc(p) [pth,nam,ext,n1] = spm_fileparts(deblank(p)); p = fullfile(pth,[nam ext]); n = str2num(n1); if ~spm_existfile(p), %existance_error_message(p); error('File "%s" does not exist.', p); end switch ext, case {'.nii','.NII'}, % Do nothing case {'.img','.IMG'}, if ~spm_existfile(fullfile(pth,[nam '.hdr'])) && ~spm_existfile(fullfile(pth,[nam '.HDR'])), %existance_error_message(fullfile(pth,[nam '.hdr'])), error('File "%s" does not exist.', fullfile(pth,[nam '.hdr'])); end case {'.hdr','.HDR'}, ext = '.img'; p = fullfile(pth,[nam ext]); if ~spm_existfile(p), %existance_error_message(p), error('File "%s" does not exist.', p); end otherwise, error('File "%s" is not of a recognised type.', p); end if isempty(n), V = spm_vol_nifti(p); else V = spm_vol_nifti(p,n); end; if isempty(n) && length(V.private.dat.dim) > 3 V0(1) = V; for i = 2:V.private.dat.dim(4) V0(i) = spm_vol_nifti(p, i); end V = V0; end if ~isempty(V), return; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function hread_error_message(q) str = {... 'Error reading information on:',... [' ',spm_str_manip(q,'k40d')],... ' ',... 'Please check that it is in the correct format.'}; spm('alert*',str,mfilename,sqrt(-1)); return; %_______________________________________________________________________ %_______________________________________________________________________ function existance_error_message(q) str = {... 'Unable to find file:',... [' ',spm_str_manip(q,'k40d')],... ' ',... 'Please check that it exists.'}; spm('alert*',str,mfilename,sqrt(-1)); return;
github
lcnbeapp/beapp-master
spm_jobman.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_jobman.m
21,324
utf_8
970b3aa24a514dea929b79722697efdc
function varargout = spm_jobman(varargin) % Main interface for SPM Batch System % This function provides a compatibility layer between SPM and matlabbatch. % It translates spm_jobman callbacks into matlabbatch callbacks and allows % to edit and run SPM5 style batch jobs. % % FORMAT job_id = spm_jobman % job_id = spm_jobman('interactive') % job_id = spm_jobman('interactive',job) % job_id = spm_jobman('interactive',job,node) % job_id = spm_jobman('interactive','',node) % Runs the user interface in interactive mode. The job_id can be used to % manipulate this job in cfg_util. Note that changes to the job in cfg_util % will not show up in cfg_ui unless 'Update View' is called. % % FORMAT output_list = spm_jobman('serial') % output_list = spm_jobman('serial',job[,'', input1,...inputN]) % output_list = spm_jobman('serial',job ,node[,input1,...inputN]) % output_list = spm_jobman('serial','' ,node[,input1,...inputN]) % Runs the user interface in serial mode. I job is not empty, then node % is silently ignored. Inputs can be a list of arguments. These are % passed on to the open inputs of the specified job/node. Each input should % be suitable to be assigned to item.val{1}. For cfg_repeat/cfg_choice % items, input should be a cell list of indices input{1}...input{k} into % item.value. See cfg_util('filljob',...) for details. % % FORMAT output_list = spm_jobman('run',job) % output_list = spm_jobman('run_nogui',job) % Runs a job without X11 (as long as there is no graphics output from the % job itself). The matlabbatch system does not need graphics output to run % a job. % % node - indicates which part of the configuration is to be used. % For example, it could be 'jobs.spatial.coreg'. % % job - can be the name of a jobfile (as a .m, .mat or a .xml), a % cellstr of filenames, a 'jobs'/'matlabbatch' variable or a % cell of 'jobs'/'matlabbatch' variables loaded from a jobfile. % % Output_list is a cell array and contains the output arguments from each % module in the job. The format and contents of these outputs is defined in % the configuration of each module (.prog and .vout callbacks). % % FORMAT spm_jobman('initcfg') % Initialise cfg_util configuration and set path accordingly. % % FORMAT jobs = spm_jobman('spm5tospm8',jobs) % Takes a cell list of SPM5 job structures and returns SPM8 compatible versions. % % FORMAT job = spm_jobman('spm5tospm8bulk',jobfiles) % Takes a cell string with SPM5 job filenames and saves them in SPM8 % compatible format. The new job files will be MATLAB .m files. Their % filenames will be derived from the input filenames. To make sure they are % valid MATLAB script names they will be processed with % genvarname(filename) and have a '_spm8' string appended to their % filename. % % FORMAT spm_jobman('help',node) % spm_jobman('help',node,width) % Creates a cell array containing help information. This is justified % to be 'width' characters wide. e.g. % h = spm_jobman('help','jobs.spatial.coreg.estimate'); % for i=1:numel(h),fprintf('%s\n',h{i}); end; % % not implemented: FORMAT spm_jobman('defaults') % Runs the interactive defaults editor. % % FORMAT [tag, job] = spm_jobman('harvest', job_id|cfg_item|cfg_struct) % Take the job with id job_id in cfg_util and extract what is % needed to save it as a batch job (for experts only). If the argument is a % cfg_item or cfg_struct tree, it will be harvested outside cfg_util. % tag - tag of the root node of the current job/cfg_item tree % job - harvested data from the current job/cfg_item tree % % FORMAT spm_jobman('pulldown') % Creates a pulldown 'TASKS' menu in the Graphics window. % % not implemented: FORMAT spm_jobman('jobhelp') % Creates a cell array containing help information specific for a certain % job. Help is only printed for items where job specific help is % present. This can be used together with spm_jobman('help') to create a % job specific manual. This feature is available only on MATLAB R14SP2 % and higher. % % not implemented: FORMAT spm_jobman('chmod') % Changes the modality for the TASKS pulldown. % % This code is based on earlier versions by John Ashburner, Philippe % Ciuciu and Guillaume Flandin. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Copyright (C) 2008 Freiburg Brain Imaging % Volkmar Glauche % $Id$ if nargin==0 h = cfg_ui; if nargout > 0, varargout = {h}; end else cmd = lower(varargin{1}); if any(strcmp(cmd, {'serial','interactive','run','run_nogui'})) if nargin > 1 % sort out job/node arguments for interactive, serial, run cmds if nargin>=2 && ~isempty(varargin{2}) % do not consider node if job is given if ischar(varargin{2}) || iscellstr(varargin{2}) jobs = load_jobs(varargin{2}); elseif iscell(varargin{2}) if iscell(varargin{2}{1}) % assume varargin{2} is a cell of jobs jobs = varargin{2}; else % assume varargin{2} is a single job jobs{1} = varargin{2}; end; end; [mljob comp] = canonicalise_job(jobs); elseif any(strcmp(cmd, {'interactive','serial'})) && nargin>=3 && isempty(varargin{2}) % Node spec only allowed for 'interactive', 'serial' arg3 = regexprep(varargin{3},'^spmjobs\.','spm.'); mod_cfg_id = cfg_util('tag2mod_cfg_id',arg3); else error('spm:spm_jobman:WrongUI', ... 'Don''t know how to handle this ''%s'' call.', lower(varargin{1})); end; end end; switch cmd case 'help' if (nargin < 2) || isempty(varargin{2}) node = 'spm'; else node = regexprep(varargin{2},'^spmjobs\.','spm.'); end; if nargin < 3 width = 60; else width = varargin{3}; end; varargout{1} = cfg_util('showdocwidth', width, node); case 'initcfg' if ~isdeployed addpath(fullfile(spm('Dir'),'matlabbatch')); addpath(fullfile(spm('Dir'),'config')); end cfg_get_defaults('cfg_util.genscript_run', @genscript_run); cfg_util('initcfg'); % This must be the first call to cfg_util if ~spm('cmdline') f = cfg_ui('Visible','off'); % Create invisible batch ui f0 = findobj(f, 'Tag','MenuFile'); % Add entries to file menu f2 = uimenu(f0,'Label','Load SPM5 job', 'Callback',@load_job, ... 'HandleVisibility','off', 'tag','jobs', ... 'Separator','on'); f3 = uimenu(f0,'Label','Bulk Convert SPM5 job(s)', ... 'Callback',@conv_jobs, ... 'HandleVisibility','off', 'tag','jobs'); end case 'interactive', if exist('mljob', 'var') cjob = cfg_util('initjob', mljob); elseif exist('mod_cfg_id', 'var') if isempty(mod_cfg_id) arg3 = regexprep(varargin{3},'^spmjobs\.','spm.'); warning('spm:spm_jobman:NodeNotFound', ... ['Can not find executable node ''%s'' - running '... 'matlabbatch without default node.'], arg3); cjob = cfg_util('initjob'); else cjob = cfg_util('initjob'); mod_job_id = cfg_util('addtojob', cjob, mod_cfg_id); cfg_util('harvest', cjob, mod_job_id); end; else cjob = cfg_util('initjob'); end; cfg_ui('local_showjob', findobj(0,'tag','cfg_ui'), cjob); if nargout > 0 varargout{1} = cjob; end; case 'serial', if exist('mljob', 'var') cjob = cfg_util('initjob', mljob); else cjob = cfg_util('initjob'); if nargin > 2 arg3 = regexprep(varargin{3},'^spmjobs\.','spm.'); [mod_cfg_id, item_mod_id] = cfg_util('tag2cfg_id', lower(arg3)); cfg_util('addtojob', cjob, mod_cfg_id); end; end; sts = cfg_util('filljobui', cjob, @serial_ui, varargin{4:end}); if sts cfg_util('run', cjob); if nargout > 0 varargout{1} = cfg_util('getalloutputs', cjob); end end; cfg_util('deljob', cjob); case {'run','run_nogui'} cjob = cfg_util('initjob', mljob); cfg_util('run', cjob); if nargout > 0 varargout{1} = cfg_util('getalloutputs', cjob); end cfg_util('deljob', cjob); case {'spm5tospm8'} varargout{1} = canonicalise_job(varargin{2}); case {'spm5tospm8bulk'} conv_jobs(varargin{2}); case {'defaults'}, warning('spm:spm_jobman:NotImplemented', 'Not yet implemented.'); case {'pulldown'} pulldown; case {'chmod'} warning('spm:spm_jobman:NotImplemented', 'Callback ''%s'' not implemented.', varargin{1}); case {'help'} warning('spm:spm_jobman:NotImplemented', 'Not yet implemented.'); case {'jobhelp'} warning('spm:spm_jobman:NotImplemented', 'Callback ''%s'' not implemented.', varargin{1}); case {'harvest'} if nargin == 1 error('spm:spm_jobman:CantHarvest', ... ['Can not harvest job without job_id. Please use ' ... 'spm_jobman(''harvest'', job_id).']); elseif cfg_util('isjob_id', varargin{2}) [tag job] = cfg_util('harvest', varargin{2}); elseif isa(varargin{2}, 'cfg_item') [tag job] = harvest(varargin{2}, varargin{2}, false, false); elseif isstruct(varargin{2}) % try to convert into class before harvesting c = cfg_struct2cfg(varargin{2}); [tag job] = harvest(c,c,false,false); else error('spm:spm_jobman:CantHarvestThis', ['Can not harvest ' ... 'this argument.']); end; varargout{1} = tag; varargout{2} = job; otherwise error(['"' varargin{1} '" - unknown option']); end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [mljob, comp] = canonicalise_job(job) % job: a cell list of job data structures. % Check whether job is a SPM5 or matlabbatch job. In the first case, all % items in job{:} should have a fieldname of either 'temporal', 'spatial', % 'stats', 'tools' or 'util'. If this is the case, then job will be % assigned to mljob{1}.spm, which is the tag of the SPM root % configuration item. comp = true(size(job)); mljob = cell(size(job)); for cj = 1:numel(job) for k = 1:numel(job{cj}) comp(cj) = comp(cj) && any(strcmp(fieldnames(job{cj}{k}), ... {'temporal', 'spatial', 'stats', 'tools', 'util'})); if ~comp(cj) break; end; end; if comp(cj) tmp = convert_jobs(job{cj}); for i=1:numel(tmp), mljob{cj}{i}.spm = tmp{i}; end else mljob{cj} = job{cj}; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function conv_jobs(varargin) % Select a list of jobs, canonicalise each of it and save as a .m file % using gencode. spm('pointer','watch'); if nargin == 0 || ~iscellstr(varargin{1}) [fname sts] = spm_select([1 Inf], 'batch', 'Select job file(s)'); fname = cellstr(fname); if ~sts, return; end; else fname = varargin{1}; end; joblist = load_jobs(fname); for k = 1:numel(fname) if ~isempty(joblist{k}) [p n e v] = spm_fileparts(fname{k}); % Save new job as genvarname(*_spm8).m newfname = fullfile(p, sprintf('%s.m', ... genvarname(sprintf('%s_spm8', n)))); fprintf('SPM5 job: %s\nSPM8 job: %s\n', fname{k}, newfname); cjob = cfg_util('initjob', canonicalise_job(joblist(k))); cfg_util('savejob', cjob, newfname); cfg_util('deljob', cjob); end; end; spm('pointer','arrow'); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function load_job(varargin) % Select a single job file, canonicalise it and display it in GUI [fname sts] = spm_select([1 Inf], 'batch', 'Select job file'); if ~sts, return; end; spm('pointer','watch'); joblist = load_jobs(fname); if ~isempty(joblist{1}) spm_jobman('interactive',joblist{1}); end; spm('pointer','arrow'); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function newjobs = load_jobs(job) % Load a list of possible job files, return a cell list of jobs. Jobs can % be either SPM5 (i.e. containing a 'jobs' variable) or SPM8/matlabbatch % jobs. If a job file failed to load, an empty cell is returned in the % list. if ischar(job) filenames = cellstr(job); else filenames = job; end; newjobs = {}; for cf = 1:numel(filenames) [p,nam,ext] = fileparts(filenames{cf}); switch ext case '.xml', spm('Pointer','Watch'); try loadxml(filenames{cf},'jobs'); catch try loadxml(filenames{cf},'matlabbatch'); catch warning('spm:spm_jobman:LoadFailed','LoadXML failed: ''%s''',filenames{cf}); end; end; spm('Pointer'); case '.mat' try S=load(filenames{cf}); if isfield(S,'matlabbatch') matlabbatch = S.matlabbatch; elseif isfield(S,'jobs') jobs = S.jobs; else warning('spm:spm_jobman:JobNotFound','No SPM5/SPM8 job found in ''%s''', filenames{cf}); end catch warning('spm:spm_jobman:LoadFailed','Load failed: ''%s''',filenames{cf}); end; case '.m' try fid = fopen(filenames{cf},'rt'); str = fread(fid,'*char'); fclose(fid); eval(str); catch warning('spm:spm_jobman:LoadFailed','Load failed: ''%s''',filenames{cf}); end; if ~(exist('jobs','var') || exist('matlabbatch','var')) warning('spm:spm_jobman:JobNotFound','No SPM5/SPM8 job found in ''%s''', filenames{cf}); end; otherwise warning('Unknown extension: ''%s''', filenames{cf}); end; if exist('jobs','var') newjobs = [newjobs(:); {jobs}]; clear jobs; elseif exist('matlabbatch','var') newjobs = [newjobs(:); {matlabbatch}]; clear matlabbatch; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function njobs = convert_jobs(jobs) decel = struct('spatial',struct('realign',[],'coreg',[],'normalise',[]),... 'temporal',[],... 'stats',[],... 'meeg',[],... 'util',[],... 'tools',struct('dartel',[])); njobs = {}; for i0 = 1:numel(jobs), tmp0 = fieldnames(jobs{i0}); tmp0 = tmp0{1}; if any(strcmp(tmp0,fieldnames(decel))), for i1=1:numel(jobs{i0}.(tmp0)), tmp1 = fieldnames(jobs{i0}.(tmp0){i1}); tmp1 = tmp1{1}; if ~isempty(decel.(tmp0)), if any(strcmp(tmp1,fieldnames(decel.(tmp0)))), for i2=1:numel(jobs{i0}.(tmp0){i1}.(tmp1)), njobs{end+1} = struct(tmp0,struct(tmp1,jobs{i0}.(tmp0){i1}.(tmp1){i2})); end else njobs{end+1} = struct(tmp0,jobs{i0}.(tmp0){i1}); end else njobs{end+1} = struct(tmp0,jobs{i0}.(tmp0){i1}); end end else njobs{end+1} = jobs{i0}; end end %------------------------------------------------------------------------ %------------------------------------------------------------------------ function pulldown fg = spm_figure('findwin','Graphics'); if isempty(fg), return; end; set(0,'ShowHiddenHandles','on'); delete(findobj(fg,'tag','jobs')); set(0,'ShowHiddenHandles','off'); f0 = uimenu(fg,'Label','TASKS', ... 'HandleVisibility','off', 'tag','jobs'); f1 = uimenu(f0,'Label','BATCH', 'Callback',@cfg_ui, ... 'HandleVisibility','off', 'tag','jobs'); f4 = uimenu(f0,'Label','SPM (interactive)', ... 'HandleVisibility','off', 'tag','jobs', 'Separator','on'); cfg_ui('local_setmenu', f4, cfg_util('tag2cfg_id', 'spm'), ... @local_init_interactive, false); f5 = uimenu(f0,'Label','SPM (serial)', ... 'HandleVisibility','off', 'tag','jobs'); cfg_ui('local_setmenu', f5, cfg_util('tag2cfg_id', 'spm'), ... @local_init_serial, false); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function local_init_interactive(varargin) cjob = cfg_util('initjob'); mod_cfg_id = get(gcbo,'userdata'); cfg_util('addtojob', cjob, mod_cfg_id); cfg_ui('local_showjob', findobj(0,'tag','cfg_ui'), cjob); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function local_init_serial(varargin) mod_cfg_id = get(gcbo,'userdata'); cjob = cfg_util('initjob'); cfg_util('addtojob', cjob, mod_cfg_id); sts = cfg_util('filljobui', cjob, @serial_ui); if sts cfg_util('run', cjob); end; cfg_util('deljob', cjob); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [val sts] = serial_ui(item) % wrapper function to translate cfg_util('filljobui'... input requests into % spm_input/cfg_select calls. sts = true; switch class(item), case 'cfg_choice', labels = cell(size(item.values)); values = cell(size(item.values)); for k = 1:numel(item.values) labels{k} = item.values{k}.name; values{k} = k; end; val = spm_input(item.name, 1, 'm', labels, values); case 'cfg_menu', val = spm_input(item.name, 1, 'm', item.labels, item.values); val = val{1}; case 'cfg_repeat', labels = cell(size(item.values)); values = cell(size(item.values)); for k = 1:numel(item.values) labels{k} = item.values{k}.name; values{k} = k; end; % enter at least item.num(1) values for k = 1:item.num(1) val(k) = spm_input(sprintf('%s(%d)', item.name, k), 1, 'm', ... labels, values); end; % enter more (up to varargin{3}(2) values labels = {labels{:} 'Done'}; % values is a cell list of natural numbers, use -1 for Done values = {values{:} -1}; while numel(val) < item.num(2) val1 = spm_input(sprintf('%s(%d)', item.name, numel(val)+1), 1, ... 'm', labels, values); if val1{1} == -1 break; else val(end+1) = val1; end; end; case 'cfg_entry', val = spm_input(item.name, 1, item.strtype, '', item.num, ... item.extras); case 'cfg_files', [t,sts] = cfg_getfile(item.num, item.filter, item.name, '', ... item.dir, item.ufilter); if sts val = cellstr(t); else val = {}; error('File selector was closed.'); end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [code cont] = genscript_run % Return code snippet to initialise SPM defaults and run a job generated by % cfg_util('genscript',...) through spm_jobman. modality = spm('CheckModality'); code{1} = sprintf('spm(''defaults'', ''%s'');', modality); code{2} = 'spm_jobman(''serial'', jobs, '''', inputs{:});'; cont = false;
github
lcnbeapp/beapp-master
spm_eeg_inv_vbecd_disp.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_eeg_inv_vbecd_disp.m
22,913
UNKNOWN
d298cddd05dcda0aab1c23b6a9f98906
function spm_eeg_inv_vbecd_disp(action,varargin) % Display the dipoles as obtained from VB-ECD % % FORMAT spm_eeg_inv_vbecd_disp('Init',D) % Display the latest VB-ECD solution saved in the .inv{} field of the % data structure D. % % FORMAT spm_eeg_inv_vbecd_disp('Init',D, ind) % Display the ind^th .inv{} cell element, if it is actually a VB-ECD % solution. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Christophe Phillips % $Id$ % Note: % unfortunately I cannot see how to ensure that when zooming in the image % the dipole location stays in place... global st Fig = spm_figure('GetWin','Graphics'); colors = {'y','b','g','r','c','m'}; % 6 possible colors marker = {'o','x','+','*','s','d','v','p','h'}; % 9 possible markers Ncolors = length(colors); Nmarker = length(marker); if nargin == 0, action = 'Init'; end; switch lower(action), %========================================================================== case 'init' %========================================================================== % FORMAT spm_eeg_inv_vbecd_disp('init',D,ind) % Initialise the variables with GUI %-------------------------------------------------------------------------- if nargin<2 D = spm_eeg_load; else D = varargin{1}; end if nargin<3 % find the latest inverse produced with vbecd Ninv = length(D.inv); lind = []; for ii=1:Ninv if isfield(D.inv{ii},'method') && ... strcmp(D.inv{ii}.method,'vbecd') lind = [lind ii]; end end ind = max(lind); if ~ind, spm('alert*','No VB-ECD solution found with this data file!',... 'VB-ECD display') return end else ind = varargin{3}; end % Stash dipole(s) information in sdip structure sdip = D.inv{ind}.inverse; % if the exit flag is not in the structure, assume everything went ok. if ~isfield(sdip,'exitflag') sdip.exitflag = ones(1,sdip.n_seeds); end try Pimg = spm_vol(D.inv{ind}.mesh.sMRI); catch Pimg = spm_vol(fullfile(spm('dir'), 'canonical', 'single_subj_T1.nii')); end spm_orthviews('Reset'); spm_orthviews('Image', Pimg, [0.0 0.45 1 0.55]); spm_orthviews('MaxBB'); spm_orthviews('AddContext') st.callback = 'spm_image(''shopos'');'; % remove clicking in image for ii=1:3, set(st.vols{1}.ax{ii}.ax,'ButtonDownFcn',';'); end WS = spm('WinScale'); % Build GUI %========================================================================== % Location: %-------------------------------------------------------------------------- uicontrol(Fig,'Style','Frame','Position',[60 25 200 325].*WS, ... 'DeleteFcn','spm_image(''reset'');'); uicontrol(Fig,'Style','Frame','Position',[70 250 180 90].*WS); uicontrol(Fig,'Style','Text', 'Position',[75 320 170 016].*WS, ... 'String','Current Position'); uicontrol(Fig,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:'); uicontrol(Fig,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:'); uicontrol(Fig,'Style','Text', 'Position',[75 255 75 020].*WS,'String','Img Intens.:'); st.mp = uicontrol(Fig,'Style','Text', 'Position',[110 295 135 020].*WS,'String',''); st.vp = uicontrol(Fig,'Style','Text', 'Position',[110 275 135 020].*WS,'String',''); st.in = uicontrol(Fig,'Style','Text', 'Position',[150 255 85 020].*WS,'String',''); c = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;'; uicontrol(Fig,'Style','togglebutton','Position',[95 220 125 20].*WS,... 'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs'); % Dipoles/seeds selection: %-------------------------------------------------------------------------- uicontrol(Fig,'Style','Frame','Position',[300 25 180 325].*WS); sdip.hdl.hcl = uicontrol(Fig,'Style','pushbutton','Position',[310 320 100 20].*WS, ... 'String','Clear all','CallBack','spm_eeg_inv_vbecd_disp(''ClearAll'')'); sdip.hdl.hseed=zeros(sdip.n_seeds,1); for ii=1:sdip.n_seeds if sdip.exitflag(ii)==1 sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','togglebutton','String',num2str(ii),... 'Position',[310+rem(ii-1,8)*20 295-fix((ii-1)/8)*20 20 20].*WS,... 'CallBack','spm_eeg_inv_vbecd_disp(''ChgSeed'')'); else sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','Text','String',num2str(ii), ... 'Position',[310+rem(ii-1,8)*20 293-fix((ii-1)/8)*20 20 20].*WS) ; end end uicontrol(Fig,'Style','text','String','Select dipole # :', ... 'Position',[310 255-fix((sdip.n_seeds-1)/8)*20 110 20].*WS); txt_box = cell(sdip.n_dip,1); for ii=1:sdip.n_dip, txt_box{ii} = num2str(ii); end txt_box{sdip.n_dip+1} = 'all'; sdip.hdl.hdip = uicontrol(Fig,'Style','popup','String',txt_box, ... 'Position',[420 258-fix((sdip.n_seeds-1)/8)*20 40 20].*WS, ... 'Callback','spm_eeg_inv_vbecd_disp(''ChgDip'')'); % Dipoles orientation and strength: %-------------------------------------------------------------------------- uicontrol(Fig,'Style','Frame','Position',[70 120 180 90].*WS); uicontrol(Fig,'Style','Text', 'Position',[75 190 170 016].*WS, ... 'String','Dipole orientation & strength'); uicontrol(Fig,'Style','Text', 'Position',[75 165 65 020].*WS, ... 'String','x-y-z or.:'); uicontrol(Fig,'Style','Text', 'Position',[75 145 75 020].*WS, ... 'String','theta-phi or.:'); uicontrol(Fig,'Style','Text', 'Position',[75 125 75 020].*WS, ... 'String','Dip. intens.:'); sdip.hdl.hor1 = uicontrol(Fig,'Style','Text', 'Position', ... [140 165 105 020].*WS,'String','a'); sdip.hdl.hor2 = uicontrol(Fig,'Style','Text', 'Position', ... [150 145 85 020].*WS,'String','b'); sdip.hdl.int = uicontrol(Fig,'Style','Text', 'Position', ... [150 125 85 020].*WS,'String','c'); st.vols{1}.sdip = sdip; % First plot = all the seeds that converged ! l_conv = find(sdip.exitflag==1); if isempty(l_conv) error('No seed converged towards a stable solution, nothing to be displayed !') else spm_eeg_inv_vbecd_disp('DrawDip',l_conv,1) set(sdip.hdl.hseed(l_conv),'Value',1); % toggle all buttons end %========================================================================== case 'drawdip' %========================================================================== % FORMAT spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip,sdip) % e.g. spm_eeg_inv_vbecd_disp('DrawDip',1,1,sdip) % e.g. spm_eeg_inv_vbecd_disp('DrawDip',[1:5],1,sdip) %-------------------------------------------------------------------------- if nargin < 2 i_seed = 1; else i_seed = varargin{1}; end if nargin<3 i_dip = 1; else i_dip = varargin{2}; end if nargin<4 if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else error('I can''t find sdip structure'); end else sdip = varargin{3}; st.vols{1}.sdip = sdip; end if any(i_seed>sdip.n_seeds) || i_dip>(sdip.n_dip+1) error('Wrong i_seed or i_dip index in spm_eeg_inv_vbecd_disp'); end % Note if i_dip==(sdip.n_dip+1) all dipoles are displayed simultaneously, % The 3D cut will then be at the mean location of all sources !!! if i_dip == (sdip.n_dip+1) i_dip = 1:sdip.n_dip; end % if seed indexes passed is wrong (no convergence) remove the wrong ones i_seed(sdip.exitflag(i_seed)~=1) = []; if isempty(i_seed) error('You passed the wrong seed indexes...') end if size(i_seed,2)==1, i_seed=i_seed'; end % Display business %-------------------------------------------------------------------------- loc_mm = sdip.loc{i_seed(1)}(:,i_dip); if length(i_seed)>1 % unit = ones(1,sdip.n_dip); for ii = i_seed(2:end) loc_mm = loc_mm + sdip.loc{ii}(:,i_dip); end loc_mm = loc_mm/length(i_seed); end if length(i_dip)>1 loc_mm = mean(loc_mm,2); end % Place the underlying image at right cuts spm_orthviews('Reposition',loc_mm); if length(i_dip)>1 tabl_seed_dip = [kron(ones(length(i_dip),1),i_seed') ... kron(i_dip',ones(length(i_seed),1))]; else tabl_seed_dip = [i_seed' ones(length(i_seed),1)*i_dip]; end % Scaling, according to all dipoles in the selected seed sets. % The time displayed is the one corresponding to the maximum EEG power ! Mn_j = -1; l3 = -2:0; for ii = 1:length(i_seed) for jj = 1:sdip.n_dip Mn_j = max([Mn_j sqrt(sum(sdip.j{ii}(jj*3+l3,sdip.Mtb).^2))]); end end st.vols{1}.sdip.tabl_seed_dip = tabl_seed_dip; % Display all dipoles, the 1st one + the ones close enough. % Run through the 6 colors and 9 markers to differentiate the dipoles. % NOTA: 2 dipoles coming from the same set will have same colour/marker ind = 1 ; dip_h = zeros(9,size(tabl_seed_dip,1),1); % each dipole displayed has 9 handles: % 3 per view (2*3): for the line, for the circle & for the error js_m = zeros(3,1); % Deal with case of multiple i_seed and i_dip displayed. % make sure dipole from same i_seed have same colour but different marker. pi_dip = find(diff(tabl_seed_dip(:,2))); if isempty(pi_dip) % i.e. only one dip displayed per seed, use old fashion for ii=1:size(tabl_seed_dip,1) if ii>1 if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1) ind = ind+1; end end ic = mod(ind-1,Ncolors)+1; im = fix(ind/Ncolors)+1; loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,tabl_seed_dip(ii,2)); js = sdip.j{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,sdip.Mtb); vloc = sdip.cov_loc{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,tabl_seed_dip(ii,2)*3+l3); dip_h(:,ii) = add1dip(loc_pl,js/Mn_j*20,vloc, ... marker{im},colors{ic},st.vols{1}.ax,Fig,st.bb); js_m = js_m+js; end else for ii=1:pi_dip(1) if ii>1 if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1) ind = ind+1; end end ic = mod(ind-1,Ncolors)+1; for jj=1:sdip.n_dip im = mod(jj-1,Nmarker)+1; loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,jj); js = sdip.j{tabl_seed_dip(ii,1)}(jj*3+l3,sdip.Mtb); vloc = sdip.cov_loc{tabl_seed_dip(ii,1)}(jj*3+l3,jj*3+l3); js_m = js_m+js; dip_h(:,ii+(jj-1)*pi_dip(1)) = ... add1dip(loc_pl,js/Mn_j*20,vloc, ... marker{im},colors{ic},st.vols{1}.ax,Fig,st.bb); end end end st.vols{1}.sdip.ax = dip_h; % Display dipoles orientation and strength js_m = js_m/size(tabl_seed_dip,1); [th,phi,Ijs_m] = cart2sph(js_m(1),js_m(2),js_m(3)); Njs_m = round(js_m'/Ijs_m*100)/100; Angle = round([th phi]*1800/pi)/10; set(sdip.hdl.hor1,'String',[num2str(Njs_m(1)),' ',num2str(Njs_m(2)), ... ' ',num2str(Njs_m(3))]); set(sdip.hdl.hor2,'String',[num2str(Angle(1)),'� ',num2str(Angle(2)),'�']); set(sdip.hdl.int,'String',Ijs_m); % Change the colour of toggle button of dipoles actually displayed for ii=tabl_seed_dip(:,1) set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 1 .7]); end %========================================================================== case 'clearall' %========================================================================== % Clears all dipoles, and reset the toggle buttons %-------------------------------------------------------------------------- if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else error('I can''t find sdip structure'); end disp('Clears all dipoles') spm_eeg_inv_vbecd_disp('ClearDip'); for ii=1:st.vols{1}.sdip.n_seeds if sdip.exitflag(ii)==1 set(st.vols{1}.sdip.hdl.hseed(ii),'Value',0); end end set(st.vols{1}.sdip.hdl.hdip,'Value',1); %========================================================================== case 'chgseed' %========================================================================== % Changes the seeds displayed %-------------------------------------------------------------------------- % disp('Change seed') sdip = st.vols{1}.sdip; if isfield(sdip,'tabl_seed_dip') prev_seeds = p_seed(sdip.tabl_seed_dip); else prev_seeds = []; end l_seed = zeros(sdip.n_seeds,1); for ii=1:sdip.n_seeds if sdip.exitflag(ii)==1 l_seed(ii) = get(sdip.hdl.hseed(ii),'Value'); end end l_seed = find(l_seed); % Modify the list of seeds displayed if isempty(l_seed) % Nothing left displayed i_seed=[]; elseif isempty(prev_seeds) % Just one dipole added, nothing before i_seed=l_seed; elseif length(prev_seeds)>length(l_seed) % One seed removed i_seed = prev_seeds; for ii=1:length(l_seed) p = find(prev_seeds==l_seed(ii)); if ~isempty(p) prev_seeds(p) = []; end % prev_seeds is left with the index of the one removed end i_seed(i_seed==prev_seeds) = []; % Remove the dipole & change the button colour spm_eeg_inv_vbecd_disp('ClearDip',prev_seeds); set(sdip.hdl.hseed(prev_seeds),'BackgroundColor',[.7 .7 .7]); else % One dipole added i_seed = prev_seeds; for ii=1:length(prev_seeds) p = find(prev_seeds(ii)==l_seed); if ~isempty(p) l_seed(p) = []; end % l_seed is left with the index of the one added end i_seed = [i_seed ; l_seed]; end i_dip = get(sdip.hdl.hdip,'Value'); spm_eeg_inv_vbecd_disp('ClearDip'); if ~isempty(i_seed) spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip); end %========================================================================== case 'chgdip' %========================================================================== % Changes the dipole index for the first seed displayed %-------------------------------------------------------------------------- disp('Change dipole') sdip = st.vols{1}.sdip; i_dip = get(sdip.hdl.hdip,'Value'); if isfield(sdip,'tabl_seed_dip') i_seed = p_seed(sdip.tabl_seed_dip); else i_seed = []; end if ~isempty(i_seed) spm_eeg_inv_vbecd_disp('ClearDip') spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip); end %========================================================================== case 'cleardip' %========================================================================== % FORMAT spm_eeg_inv_vbecd_disp('ClearDip',seed_i) % e.g. spm_eeg_inv_vbecd_disp('ClearDip') % clears all displayed dipoles % e.g. spm_eeg_inv_vbecd_disp('ClearDip',1) % clears the first dipole displayed %-------------------------------------------------------------------------- if nargin>2 seed_i = varargin{1}; else seed_i = 0; end if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else return; % I don't do anything, as I can't find sdip strucure end if isfield(sdip,'ax') Nax = size(sdip.ax,2); else return; % I don't do anything, as I can't find axes info end if seed_i==0 % removes everything for ii=1:Nax for jj=1:9 delete(sdip.ax(jj,ii)); end end for ii=sdip.tabl_seed_dip(:,1) set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 .7 .7]); end sdip = rmfield(sdip,'tabl_seed_dip'); sdip = rmfield(sdip,'ax'); elseif seed_i<=Nax % remove one seed only l_seed = find(sdip.tabl_seed_dip(:,1)==seed_i); for ii=l_seed for jj=1:9 delete(sdip.ax(jj,ii)); end end sdip.ax(:,l_seed) = []; sdip.tabl_seed_dip(l_seed,:) = []; else error('Trying to clear unspecified dipole'); end st.vols{1}.sdip = sdip; %========================================================================== case 'redrawdip' %========================================================================== % spm_eeg_inv_vbecd_disp('RedrawDip') % redraw everything, useful when zooming into image %-------------------------------------------------------------------------- % spm_eeg_inv_vbecd_disp('ClearDip') % spm_eeg_inv_vbecd_disp('ChgDip') % disp('Change dipole') sdip = st.vols{1}.sdip; i_dip = get(sdip.hdl.hdip,'Value'); if isfield(sdip,'tabl_seed_dip') i_seed = p_seed(sdip.tabl_seed_dip); else i_seed = []; end if ~isempty(i_seed) spm_eeg_inv_vbecd_disp('ClearDip') spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip); end %========================================================================== otherwise %========================================================================== warning('Unknown action string'); end % warning(sw); return %========================================================================== % dh = add1dip(loc,js,vloc,mark,col,ax,Fig,bb) %========================================================================== function dh = add1dip(loc,js,vloc,mark,col,ax,Fig,bb) % Plots the dipoles on the 3 views, with an error ellipse for location % Then returns the handle to the plots global st is = inv(st.Space); loc = is(1:3,1:3)*loc(:) + is(1:3,4); % taking into account the zooming/scaling only for the location % NOT for the dipole's amplitude. % Amplitude plotting is quite arbitrary anyway and up to some scaling % defined for better viewing... loc(1,:) = loc(1,:) - bb(1,1)+1; loc(2,:) = loc(2,:) - bb(1,2)+1; loc(3,:) = loc(3,:) - bb(1,3)+1; % +1 added to be like John's orthview code % prepare error ellipse vloc = is(1:3,1:3)*vloc*is(1:3,1:3); [V,E] = eig(vloc); VE = V*diag(sqrt(diag(E))); % use std % VE = V*E; % or use variance ??? dh = zeros(9,1); figure(Fig) % Transverse slice, # 1 %---------------------- set(Fig,'CurrentAxes',ax{1}.ax) set(ax{1}.ax,'NextPlot','add') dh(1) = plot(loc(1),loc(2),[mark,col],'LineWidth',1); dh(2) = plot(loc(1)+[0 js(1)],loc(2)+[0 js(2)],col,'LineWidth',2); % add error ellipse [uu,ss,vv] = svd(VE([1 2],:)); [phi] = cart2pol(uu(1,1),uu(2,1)); e = diag(ss); t = (-1:.02:1)*pi; x = e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi)+loc(1); y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(2); dh(3) = plot(x,y,[':',col],'LineWidth',.5); set(ax{1}.ax,'NextPlot','replace') % Coronal slice, # 2 %---------------------- set(Fig,'CurrentAxes',ax{2}.ax) set(ax{2}.ax,'NextPlot','add') dh(4) = plot(loc(1),loc(3),[mark,col],'LineWidth',1); dh(5) = plot(loc(1)+[0 js(1)],loc(3)+[0 js(3)],col,'LineWidth',2); % add error ellipse [uu,ss,vv] = svd(VE([1 3],:)); [phi] = cart2pol(uu(1,1),uu(2,1)); e = diag(ss); t = (-1:.02:1)*pi; x = e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi)+loc(1); y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(3); dh(6) = plot(x,y,[':',col],'LineWidth',.5); set(ax{2}.ax,'NextPlot','replace') % Sagital slice, # 3 %---------------------- set(Fig,'CurrentAxes',ax{3}.ax) set(ax{3}.ax,'NextPlot','add') % dh(5) = plot(dim(2)-loc(2),loc(3),[mark,col],'LineWidth',2); % dh(6) = plot(dim(2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2); dh(7) = plot(bb(2,2)-bb(1,2)-loc(2),loc(3),[mark,col],'LineWidth',1); dh(8) = plot(bb(2,2)-bb(1,2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2); % add error ellipse [uu,ss,vv] = svd(VE([2 3],:)); [phi] = cart2pol(uu(1,1),uu(2,1)); e = diag(ss); t = (-1:.02:1)*pi; x = -(e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi))+bb(2,2)-bb(1,2)-loc(2); y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(3); dh(9) = plot(x,y,[':',col],'LineWidth',.5); set(ax{3}.ax,'NextPlot','replace') return %========================================================================== % pr_seed = p_seed(tabl_seed_dip) %========================================================================== function pr_seed = p_seed(tabl_seed_dip) % Gets the list of seeds used in the previous display ls = sort(tabl_seed_dip(:,1)); if length(ls)==1 pr_seed = ls; else pr_seed = ls([find(diff(ls)) ; length(ls)]); end % % OLD STUFF %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Use it with arguments or not: % - spm_eeg_inv_vbecd_disp('Init') % The routine asks for the dipoles file and image to display % - spm_eeg_inv_vbecd_disp('Init',sdip) % The routine will use the avg152T1 canonical image % - spm_eeg_inv_vbecd_disp('Init',sdip,P) % The routines dispays the dipoles on image P. % % If multiple seeds have been used, you can select the seeds to display % by pressing their index. % Given that the sources could have different locations, the slices % displayed will be the 3D view at the *average* or *mean* locations of % selected sources. % If more than 1 dipole was fitted at a time, then selection of source 1 % to N is possible through the pull-down selector. % % The location of the source/cut is displayed in mm and voxel, as well as % the underlying image intensity at that location. % The cross hair position can be hidden by clicking on its button. % % Nota_1: If the cross hair is manually moved by clicking in the image or % changing its coordinates, the dipole displayed will NOT be at % the right displayed location. That's something that needs to be improved... % % Nota_2: Some seeds may have not converged within the limits fixed, % these dipoles are not displayed... % % Fields needed in sdip structure to plot on an image: % + n_seeds: nr of seeds set used, i.e. nr of solutions calculated % + n_dip: nr of fitted dipoles on the EEG time series % + loc: location of fitted dipoles, cell{1,n_seeds}(3 x n_dip) % remember that loc is fixed over the time window. % + j: sources amplitude over the time window, % cell{1,n_seeds}(3*n_dip x Ntimebins) % + Mtb: index of maximum power in EEG time series used % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % First point to consider % loc_mm = sdip.loc{i_seed(1)}(:,i_dip); % % % PLace the underlying image at right cuts % spm_orthviews('Reposition',loc_mm); % % spm_orthviews('Reposition',loc_vx); % % spm_orthviews('Xhairs','off') % % % if i_seed = set, Are there other dipoles close enough ? % tabl_seed_dip=[i_seed(1) i_dip]; % table summarising which set & dip to use. % if length(i_seed)>1 % unit = ones(1,sdip.n_dip); % for ii = i_seed(2:end)' % d2 = sqrt(sum((sdip.loc{ii}-loc_mm*unit).^2)); % l_cl = find(d2<=lim_cl); % if ~isempty(l_cl) % for jj=l_cl % tabl_seed_dip = [tabl_seed_dip ; [ii jj]]; % end % end % end % end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get(sdip.hdl.hseed(1),'Value') % for ii=1:sdip.n_seeds, delete(hseed(ii)); end % h1 = uicontrol(Fig,'Style','togglebutton','Position',[600 25 10 10].*WS) % h2 = uicontrol(Fig,'Style','togglebutton','Position',[620 100 20 20].*WS,'String','1') % h2 = uicontrol(Fig,'Style','checkbox','Position',[600 100 10 10].*WS) % h3 = uicontrol(Fig,'Style','radiobutton','Position',[600 150 20 20].*WS) % h4 = uicontrol(Fig,'Style','radiobutton','Position',[700 150 20 20].*WS) % delete(h2),delete(h3),delete(h4), % delete(hdip)
github
lcnbeapp/beapp-master
spm_figure.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_figure.m
32,150
utf_8
8f4bd924a038c03f7d509cc9e37b8395
function varargout=spm_figure(varargin) % Setup and callback functions for Graphics window % FORMAT varargout=spm_figure(varargin) % - An embedded callback, multi-function function % - For detailed programmers comments, see format specifications % in main body of code %_______________________________________________________________________ % % spm_figure creates and manages the 'Graphics' window. This window and % these facilities may be used independently of SPM, and any number of % Graphics windows my be used within the same MATLAB session. (Though % only one SPM 'Graphics' 'Tag'ed window is permitted. % % The Graphics window is provided with a menu bar at the top that % facilitates editing and printing of the current graphic display, % enabling interactive editing of graphic output prior to printing % (e.g. selection of color maps, deleting, moving and editing graphics % objects or adding text). (This menu is also provided as a figure % background "ContextMenu" - right-clicking on the figure background % should bring up the menu.) % % Print: Graphics windows with multi-page axes are printed page by page. % % Clear: Clears the Graphics window. If in SPM usage (figure 'Tag'ed as % 'Graphics') then all SPM windows are cleared and reset. % % Colormap options: % * gray, hot, pink: Sets the colormap to its default values and loads % either a grayscale, 'hot metal' or color map. % * gray-hot, etc: Creates a 'split' colormap {128 x 3 matrix}. % The lower half is a gray scale and the upper half % is 'hot metal' or 'pink'. This color map is used for % viewing 'rendered' SPMs on a PET, MRI or other background images % % Colormap effects: % * Invert: Inverts (flips) the current color map. % * Brighten and Darken: Brighten and Darken the current colourmap % using the MATLAB BRIGHTEN command, with beta's of +0.2 and -0.2 % respectively. % % Editing: Right button ('alt' button) cancels operations % * Cut : Deletes the graphics object next selected (if deletable) % Select with middle mouse button to delete blocks of text, % or to delete individual elements from a plot. % * Move : To re-position a text, uicontrol or axis object using a % 'drag and drop' implementation (i.e. depress - move - release) % Using the middle 'extend' mouse button on a text object moves % the axes containing the text - i.e. blocks of text. % * Size : Re-sizes the text, uicontrol or axis object next selected % {left button - decrease, middle button - increase} by a factor % of 1.24 (or increase/decrease FontSize by 2 dpi) % * Text : Creates an editable text widget that produces a text object as % its CallBack. % The text object is provided with a ContextMenu, obtained by % right-clicking ('alt') on the text, allowing text attributes % to be changed. Alternatively, the edit facilities on the window % menu bar or ContextMenu can be used. % * Edit : To edit text, select a text object with the circle cursor, % and edit the text in the editable text widget that appears. % A middle 'extend' mouse click places a context menu on the text % object, facilitating easy modification of text atributes. % % For SPM usage, the figure should be 'Tag'ed as 'Graphics'. % % For SPM power users, and programmers, spm_figure provides utility % routines for using the SPM graphics interface. Of particular use are % the GetWin, FindWin and Clear functions See the embedded callback % reference in the main body of spm_figure, below the help text. % % See also: spm_print, spm_clf % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Andrew Holmes % $Id$ %======================================================================= % - FORMAT specifications for embedded CallBack functions %======================================================================= %( This is a multi function function, the first argument is an action ) %( string, specifying the particular action function to take. Recall ) %( MATLAB's command-function duality: `spm_figure Create` is ) %( equivalent to `spm_figure('Create')`. ) % % FORMAT F = spm_figure % [ShortCut] Defaults to Action 'Create' % % FORMAT F = spm_figure(F) - numeric F % [ShortCut] Defaults to spm_figure('CreateBar',F) % % FORMAT F = spm_figure('Create',Tag,Name,Visible) % Create a full length WhiteBg figure 'Tag'ed Tag (if specified), % with a ToolBar and background context menu. % Equivalent to spm_figure('CreateWin','Tag') and spm_figure('CreateBar') % Tag - 'Tag' string for figure. % Name - Name for window % Visible - 'on' or 'off' % F - Figure used % % FORMAT F = spm_figure('FindWin',F) % Finds window with 'Tag' or figure numnber F - returns empty F if not found % F - (Input) Figure to use [Optional] - 'Tag' string or figure number. % - Defaults to 'Graphics' % F - (Output) Figure number (if found) or empty (if not). % % FORMAT F = spm_figure('GetWin',Tag) % Like spm_figure('FindWin',Tag), except that if no such 'Tag'ged figure % is found and 'Tag' is recognized, one is created. Further, the "got" % window is made current. % Tag - Figure 'Tag' to get, defaults to 'Graphics' % F - Figure number (if found/created) or empty (if not). % % FORMAT F = spm_figure('ParentFig',h) % Finds window containing the object whose handle is specified % h - Handle of object whose parent figure is required % - If a vector, then first object handle is used % F - Number or parent figure % % FORMAT spm_figure('Clear',F,Tags) % Clears figure, leaving ToolBar (& other objects with invisible handles) % Optional third argument specifies 'Tag's of objects to delete. % If figure F is 'Tag'ged 'Interactive' (SPM usage), then the window % name and pointer are reset. % F - 'Tag' string or figure number of figure to clear, defaults to gcf % Tags - 'Tag's (string matrix or cell array of strings) of objects to delete % *regardless* of 'HandleVisibility'. Only these objects are deleted. % '!all' denotes all objects % % % FORMAT spm_figure('Print',F) % F - [Optional] Figure to print. ('Tag' or figure number) % Defaults to figure 'Tag'ed as 'Graphics'. % If none found, uses CurrentFigure if avaliable. % If objects 'Tag'ed 'NextPage' and 'PrevPage' are found, then the % pages are shown and printed in order. In breif, pages are held as % seperate axes, with ony one 'Visible' at any one time. The handles of % the "page" axes are stored in the 'UserData' of the 'NextPage' % object, while the 'PrevPage' object holds the current page number. % See spm_help('!Disp') for details on setting up paging axes. % % FORMAT [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',hPage) % SPM pagination function: Makes objects with handles hPage paginated % Creates pagination buttons if necessary. % hPage - Handles of objects to stick to this page % hNextPage, hPrevPage, hPageNo - Handles of pagination controls % % FORMAT spm_figure('TurnPage',move,F) % SPM pagination function: Turn to specified page % % FORMAT spm_figure('DeletePageControls',F) % SPM pagination function: Deletes page controls % F - [Optional] Figure in which to attempt to turn the page % Defaults to 'Graphics' 'Tag'ged window % % FORMAT n = spm_figure('#page') % Returns the current number of pages. % % FORMAT n = spm_figure('CurrentPage'); % Return the current page number. % % FORMAT spm_figure('WaterMark',F,str,Tag,Angle,Perm) % Adds watermark to figure windows. % F - Figure for watermark. Defaults to gcf % str - Watermark string. Defaults (missing or empty) to SPM % Tag - Tag for watermark axes. Defaults to '' % Angle - Angle for watermark. Defaults to -45 % Perm - If specified, then watermark is permanent (HandleVisibility 'off') % % FORMAT F = spm_figure('CreateWin',Tag,Name,Visible) % Creates a full length WhiteBg figure 'Tag'ged Tag (if specified). % F - Figure created % Tag - Tag for window % Name - Name for window % Visible - 'on' or 'off' % % FORMAT WS = spm_figure('GetWinScale') % Returns ratios of current display dimensions to that of a 1152 x 900 % Sun display. WS=[Xratio,Yratio,Xratio,Yratio]. Used for scaling other % GUI elements. % (Function duplicated in spm.m, repeated to reduce inter-dependencies.) % % FORMAT FS = spm_figure('FontSizes',FS) % Returns fontsizes FS scaled for the current display. % FS - (vector of) Font sizes to scale % [default [08,09,11,13,14,6:36]] % % FORMAT spm_figure('CreateBar',F) % Creates toolbar in figure F (defaults to gcf). F can be a 'Tag' % If the figure is 'Tag'ed as 'Graphics' (SPM usage), then the Print button % callback is set to attempt to clear an 'Interactive' figure too. % % FORMAT spm_figure('ColorMap') % Callback for "ColorMap" buttons % % FORMAT h = spm_figure('GraphicsHandle',F) % GUI choose object for handle identification. LeftMouse 'normal' returns % handle, MiddleMouse 'extend' returns parents handle, RightMouse 'alt' cancels. % F - figure to do a GUI "handle ID" in [Default gcbf] %_______________________________________________________________________ %-Condition arguments %----------------------------------------------------------------------- if (nargin==0), Action = 'Create'; else Action = varargin{1}; end switch lower(Action), case 'create' %======================================================================= % F = spm_figure('Create',Tag,Name,Visible) %-Condition arguments if nargin<4, Visible='on'; else Visible=varargin{4}; end if nargin<3, Name=''; else, Name=varargin{3}; end if nargin<2, Tag=''; else Tag=varargin{2}; end F = spm_figure('CreateWin',Tag,Name,Visible); spm_figure('CreateBar',F); spm_figure('FigContextMenu',F); varargout = {F}; case 'findwin' %======================================================================= % F=spm_figure('FindWin',F) % F=spm_figure('FindWin',Tag) %-Find window: Find window with FigureNumber# / 'Tag' attribute %-Returns empty if window cannot be found - deletes multiple tagged figs. if nargin<2, F='Graphics'; else F=varargin{2}; end shh = get(0,'showhiddenhandles'); set(0,'showhiddenhandles','on'); if isempty(F) % Leave F empty elseif ischar(F) % Finds Graphics window with 'Tag' string - delete multiples Tag=F; F = findobj(get(0,'Children'),'Flat','Tag',Tag); if length(F) > 1 % Multiple Graphics windows - close all but most recent close(F(2:end)) F = F(1); end else % F is supposed to be a figure number - check it if ~any(F==get(0,'Children')), F=[]; end end set(0,'showhiddenhandles',shh); varargout = {F}; case 'getwin' %======================================================================= % F=spm_figure('GetWin',Tag) if nargin<2, Tag='Graphics'; else Tag=varargin{2}; end F = spm_figure('FindWin',Tag); if isempty(F) if ischar(Tag) switch Tag case 'Graphics' F = spm_figure('Create','Graphics','Graphics'); case 'DEM' F = spm_figure('Create','DEM','Dynamic Expectation Maximisation'); case 'DFP' F = spm_figure('Create','DFP','Variational filtering'); case 'FMIN' F = spm_figure('Create','FMIN','Function minimisation'); case 'MFM' F = spm_figure('Create','MFM','Mean-field and neural mass models'); case 'MVB' F = spm_figure('Create','MVB','Multivariate Bayes'); case 'SI' F = spm_figure('Create','SI','System Identification'); case 'PPI' F = spm_figure('Create','PPI','Physio/Psycho-Physiologic Interaction'); case 'Interactive' F = spm('CreateIntWin'); otherwise F = spm_figure('Create',Tag,Tag); end end else set(0,'CurrentFigure',F); figure(F); end varargout = {F}; case 'parentfig' %======================================================================= % F=spm_figure('ParentFig',h) if nargin<2, error('No object specified'), else h=varargin{2}; end F = get(h(1),'Parent'); while ~strcmp(get(F,'Type'),'figure'), F=get(F,'Parent'); end varargout = {F}; case 'clear' %======================================================================= % spm_figure('Clear',F,Tags) %-Sort out arguments %----------------------------------------------------------------------- if nargin<3, Tags=[]; else Tags=varargin{3}; end if nargin<2, F=get(0,'CurrentFigure'); else F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), return, end %-Clear figure %----------------------------------------------------------------------- if isempty(Tags) %-Clear figure of objects with 'HandleVisibility' 'on' pos = get(F,'Position'); delete(findobj(get(F,'Children'),'flat','HandleVisibility','on')); drawnow set(F,'Position',pos); %-Reset figures callback functions zoom(F,'off'); rotate3d(F,'off'); set(F,'KeyPressFcn','',... 'WindowButtonDownFcn','',... 'WindowButtonMotionFcn','',... 'WindowButtonUpFcn','') %-If this is the 'Interactive' window, reset name & UserData if strcmp(get(F,'Tag'),'Interactive') set(F,'Name','','UserData',[]), end else %-Clear specified objects from figure cSHH = get(0,'ShowHiddenHandles'); set(0,'ShowHiddenHandles','on') if ischar(Tags); Tags=cellstr(Tags); end if any(strcmp(Tags(:),'!all')) delete(get(F,'Children')) else for tag = Tags(:)' delete(findobj(get(F,'Children'),'flat','Tag',tag{:})); end end set(0,'ShowHiddenHandles',cSHH) end set(F,'Pointer','Arrow') movegui(F); case 'print' %======================================================================= % spm_figure('Print',F,fname) %-Arguments & defaults if nargin<3, fname=''; else fname=varargin{3};end if nargin<2, F='Graphics'; else F=varargin{2}; end %-Find window to print, default to gcf if specified figure not found % Return if no figures if ~isempty(F), F = spm_figure('FindWin',F); end if isempty(F), F = get(0,'CurrentFigure'); end if isempty(F), return, end %-Note current figure, & switch to figure to print cF = get(0,'CurrentFigure'); set(0,'CurrentFigure',F) %-See if window has paging controls hNextPage = findobj(F,'Tag','NextPage'); hPrevPage = findobj(F,'Tag','PrevPage'); hPageNo = findobj(F,'Tag','PageNo'); iPaged = ~isempty(hNextPage); %-Construct print command %----------------------------------------------------------------------- %-Temporarily change all units to normalized prior to printing % (Fixes bizzarre problem with stuff jumping around!) %----------------------------------------------------------------------- H = findobj(get(F,'Children'),'flat','Type','axes'); if ~isempty(H), un = cellstr(get(H,'Units')); set(H,'Units','normalized') end; %-Print %----------------------------------------------------------------------- if ~iPaged spm_print(fname) else hPg = get(hNextPage,'UserData'); Cpage = get(hPageNo, 'UserData'); nPages = size(hPg,1); set([hNextPage,hPrevPage,hPageNo],'Visible','off') if Cpage~=1 set(hPg{Cpage,1},'Visible','off'), end for p = 1:nPages set(hPg{p,1},'Visible','on'); spm_print(fname); set(hPg{p,1},'Visible','off') end set(hPg{Cpage,1},'Visible','on') set([hNextPage,hPrevPage,hPageNo],'Visible','on') end if ~isempty(H), set(H,{'Units'},un); end; set(0,'CurrentFigure',cF) case 'printto' %======================================================================= %spm_figure('PrintTo',F) %-Arguments & defaults if nargin<2, F='Graphics'; else F=varargin{2}; end %-Find window to print, default to gcf if specified figure not found % Return if no figures F=spm_figure('FindWin',F); if isempty(F), F = get(0,'CurrentFigure'); end if isempty(F), return, end [fn pn] = uiputfile('*.ps', 'Print to File'); if fn == 0 return; end; psname = fullfile(pn, fn); spm_figure('Print',F,psname); case 'newpage' %======================================================================= % [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',h) if nargin<2 || isempty(varargin{2}) error('No handles to paginate') else h=varargin{2}(:)'; end %-Work out which figure we're in F = spm_figure('ParentFig',h(1)); hNextPage = findobj(F,'Tag','NextPage'); hPrevPage = findobj(F,'Tag','PrevPage'); hPageNo = findobj(F,'Tag','PageNo'); %-Create pagination widgets if required %----------------------------------------------------------------------- if isempty(hNextPage) WS = spm('WinScale'); FS = spm('FontSizes'); SatFig = findobj('Tag','Satellite'); if ~isempty(SatFig) SatFigPos = get(SatFig,'Position'); hNextPagePos = [SatFigPos(3)-25 15 15 15]; hPrevPagePos = [SatFigPos(3)-40 15 15 15]; hPageNo = [SatFigPos(3)-40 5 30 10]; else hNextPagePos = [580 022 015 015].*WS; hPrevPagePos = [565 022 015 015].*WS; hPageNo = [550 005 060 015].*WS; end hNextPage = uicontrol(F,'Style','Pushbutton',... 'HandleVisibility','on',... 'String','>','FontSize',FS(10),... 'ToolTipString','next page',... 'Callback','spm_figure(''TurnPage'',''+1'',gcbf)',... 'Position',hNextPagePos,... 'ForegroundColor',[0 0 0],... 'Tag','NextPage','UserData',[]); hPrevPage = uicontrol(F,'Style','Pushbutton',... 'HandleVisibility','on',... 'String','<','FontSize',FS(10),... 'ToolTipString','previous page',... 'Callback','spm_figure(''TurnPage'',''-1'',gcbf)',... 'Position',hPrevPagePos,... 'Visible','on',... 'Enable','off',... 'Tag','PrevPage'); hPageNo = uicontrol(F,'Style','Text',... 'HandleVisibility','on',... 'String','1',... 'FontSize',FS(6),... 'HorizontalAlignment','center',... 'BackgroundColor','w',... 'Position',hPageNo,... 'Visible','on',... 'UserData',1,... 'Tag','PageNo','UserData',1); end %-Add handles for this page to UserData of hNextPage %-Make handles for this page invisible if PageNo>1 %----------------------------------------------------------------------- mVis = strcmp('on',get(h,'Visible')); mHit = strcmp('on',get(h,'HitTest')); hPg = get(hNextPage,'UserData'); if isempty(hPg) hPg = {h(mVis), h(~mVis), h(mHit), h(~mHit)}; else hPg = [hPg; {h(mVis), h(~mVis), h(mHit), h(~mHit)}]; set(h(mVis),'Visible','off'); set(h(mHit),'HitTest','off'); end set(hNextPage,'UserData',hPg) %-Return handles to pagination controls if requested if nargout>0, varargout = {[hNextPage, hPrevPage, hPageNo]}; end case 'turnpage' %======================================================================= % spm_figure('TurnPage',move,F) if nargin<3, F='Graphics'; else F=varargin{3}; end if nargin<2, move=1; else move=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), error('No Graphics window'), end hNextPage = findobj(F,'Tag','NextPage'); hPrevPage = findobj(F,'Tag','PrevPage'); hPageNo = findobj(F,'Tag','PageNo'); if isempty(hNextPage), return, end hPg = get(hNextPage,'UserData'); Cpage = get(hPageNo, 'UserData'); nPages = size(hPg,1); %-Sort out new page number if ischar(move), Npage = Cpage+eval(move); else Npage = move; end Npage = max(min(Npage,nPages),1); %-Make current page invisible, new page visible, set page number string set(hPg{Cpage,1},'Visible','off'); set(hPg{Cpage,3},'HitTest','off'); set(hPg{Npage,1},'Visible','on'); set(hPg{Npage,3},'HitTest','on'); set(hPageNo,'UserData',Npage,'String',sprintf('%d / %d',Npage,nPages)) for k = 1:length(hPg{Npage,1}) % VG if strcmp(get(hPg{Npage,1}(k),'Type'),'axes') axes(hPg{Npage,1}(k)); end; end; %-Disable appropriate page turning control if on first/last page (for neatness) if Npage==1, set(hPrevPage,'Enable','off') else set(hPrevPage,'Enable','on'), end if Npage==nPages, set(hNextPage,'Enable','off') else set(hNextPage,'Enable','on'), end case 'deletepagecontrols' %======================================================================= % spm_figure('DeletePageControls',F) if nargin<2, F='Graphics'; else F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), error('No Graphics window'), end hNextPage = findobj(F,'Tag','NextPage'); hPrevPage = findobj(F,'Tag','PrevPage'); hPageNo = findobj(F,'Tag','PageNo'); delete([hNextPage hPrevPage hPageNo]) case '#page' %======================================================================= % n = spm_figure('#Page',F) if nargin<2, F='Graphics'; else F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), error('No Graphics window'), end hNextPage = findobj(F,'Tag','NextPage'); if isempty(hNextPage) n = 1; else n = size(get(hNextPage,'UserData'),1)+1; end varargout = {n}; case 'currentpage' %======================================================================= % n = spm_figure('CurrentPage', F) if nargin<2, F='Graphics'; else F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), error('No Graphics window'), end hPageNo = findobj(F,'Tag','PageNo'); Cpage = get(hPageNo, 'UserData'); varargout = {Cpage}; case 'watermark' %======================================================================= % spm_figure('WaterMark',F,str,Tag,Angle,Perm) if nargin<6, HVis='on'; else HVis='off'; end if nargin<5, Angle=-45; else Angle=varargin{5}; end if nargin<4 || isempty(varargin{4}), Tag = 'WaterMark'; else Tag=varargin{4}; end if nargin<3 || isempty(varargin{3}), str = 'SPM'; else str=varargin{3}; end if nargin<2, if any(get(0,'Children')), F=gcf; else F=''; end else F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), return, end %-Specify watermark color from background colour %----------------------------------------------------------------------- Colour = get(F,'Color'); %-Only mess with grayscale backgrounds if ~all(Colour==Colour(1)), return, end %-Work out colour - lighter unless grey value > 0.9 Colour = Colour+(2*(Colour(1)<0.9)-1)*0.02; cF = get(0,'CurrentFigure'); set(0,'CurrentFigure',F) Units=get(F,'Units'); set(F,'Units','normalized'); h = axes('Position',[0.45,0.5,0.1,0.1],... 'Units','normalized',... 'Visible','off',... 'Tag',Tag); set(F,'Units',Units) text(0.5,0.5,str,... 'FontSize',spm('FontSize',80),... 'FontWeight','Bold',... 'FontName',spm_platform('Font','times'),... 'Rotation',Angle,... 'HorizontalAlignment','Center',... 'VerticalAlignment','middle',... 'EraseMode','normal',... 'Color',Colour,... 'ButtonDownFcn',[... 'if strcmp(get(gcbf,''SelectionType''),''open''),',... 'delete(get(gcbo,''Parent'')),',... 'end']) set(h,'HandleVisibility',HVis) set(0,'CurrentFigure',cF) case 'createwin' %======================================================================= % F=spm_figure('CreateWin',Tag,Name,Visible) %-Condition arguments %----------------------------------------------------------------------- if nargin<4 || isempty(varargin{4}), Visible='on'; else Visible=varargin{4}; end if nargin<3, Name=''; else Name = varargin{3}; end if nargin<2, Tag=''; else Tag = varargin{2}; end WS = spm('WinScale'); %-Window scaling factors FS = spm('FontSizes'); %-Scaled font sizes PF = spm_platform('fonts'); %-Font names (for this platform) Rect = spm('WinSize','Graphics'); %-Graphics window rectangle S0 = spm('WinSize','0',1); %-Screen size (of the current monitor) F = figure(... 'Tag',Tag,... 'Position',[S0(1) S0(2) 0 0] + Rect,... 'Resize','off',... 'Color','w',... 'ColorMap',gray(64),... 'DefaultTextColor','k',... 'DefaultTextInterpreter','none',... 'DefaultTextFontName',PF.helvetica,... 'DefaultTextFontSize',FS(10),... 'DefaultAxesColor','w',... 'DefaultAxesXColor','k',... 'DefaultAxesYColor','k',... 'DefaultAxesZColor','k',... 'DefaultAxesFontName',PF.helvetica,... 'DefaultPatchFaceColor','k',... 'DefaultPatchEdgeColor','k',... 'DefaultSurfaceEdgeColor','k',... 'DefaultLineColor','k',... 'DefaultUicontrolFontName',PF.helvetica,... 'DefaultUicontrolFontSize',FS(10),... 'DefaultUicontrolInterruptible','on',... 'PaperType','A4',... 'PaperUnits','normalized',... 'PaperPosition',[.0726 .0644 .854 .870],... 'InvertHardcopy','off',... 'Renderer',spm_get_defaults('renderer'),... 'Visible','off',... 'Toolbar','none'); if ~isempty(Name) set(F,'Name',sprintf('%s%s: %s',spm('ver'),... spm('GetUser',' (%s)'),Name),'NumberTitle','off') end set(F,'Visible',Visible) varargout = {F}; case 'getwinscale' %======================================================================= % WS = spm_figure('GetWinScale') warning('spm_figure(''GetWinScale''... is Grandfathered: use spm(''WinScale''') varargout = {spm('WinScale')}; case 'fontsizes' %======================================================================= % FS = spm_figure('FontSizes',FS) warning('spm_figure(''FontSizes''... is Grandfathered: use spm(''FontSizes''') if nargin<2, FS=[08,09,11,13,14,6:36]; else FS=varargin{2}; end varargout = {round(FS*min(spm('WinScale')))}; %======================================================================= case 'createbar' %======================================================================= % spm_figure('CreateBar',F) if nargin<2, if any(get(0,'Children')), F=gcf; else F=''; end else F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), return, end cSHH = get(0,'ShowHiddenHandles'); set(0,'ShowHiddenHandles','on') t0 = findobj(get(F,'Children'),'Flat','Label','&Help'); if isempty(t0), t0 = uimenu( F,'Label','&Help'); end; set(findobj(t0,'Position',1),'Separator','on'); uimenu(t0,'Position',1,... 'Label','SPM web',... 'CallBack','web(''http://www.fil.ion.ucl.ac.uk/spm/'');'); uimenu(t0,'Position',1,... 'Label','SPM help','ForegroundColor',[0 1 0],... 'CallBack','spm_help'); t0=uimenu( F,'Label','Colours','HandleVisibility','off'); t1=uimenu(t0,'Label','ColorMap'); uimenu(t1,'Label','Gray', 'CallBack','spm_figure(''ColorMap'',''gray'')'); uimenu(t1,'Label','Hot', 'CallBack','spm_figure(''ColorMap'',''hot'')'); uimenu(t1,'Label','Pink', 'CallBack','spm_figure(''ColorMap'',''pink'')'); uimenu(t1,'Label','Jet','CallBack','spm_figure(''ColorMap'',''jet'')'); uimenu(t1,'Label','Gray-Hot', 'CallBack','spm_figure(''ColorMap'',''gray-hot'')'); uimenu(t1,'Label','Gray-Cool','CallBack','spm_figure(''ColorMap'',''gray-cool'')'); uimenu(t1,'Label','Gray-Pink','CallBack','spm_figure(''ColorMap'',''gray-pink'')'); uimenu(t1,'Label','Gray-Jet', 'CallBack','spm_figure(''ColorMap'',''gray-jet'')'); t1=uimenu(t0,'Label','Effects'); uimenu(t1,'Label','Invert','CallBack','spm_figure(''ColorMap'',''invert'')'); uimenu(t1,'Label','Brighten','CallBack','spm_figure(''ColorMap'',''brighten'')'); uimenu(t1,'Label','Darken','CallBack','spm_figure(''ColorMap'',''darken'')'); uimenu( F,'Label','Clear','HandleVisibility','off','CallBack','spm_figure(''Clear'',gcbf)'); t0=uimenu( F,'Label','SPM-Print','HandleVisibility','off'); %uimenu( F,'Label','SPM-Print','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)'); t1=uimenu(t0,'Label','default print file','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)'); t1=uimenu(t0,'Label','other print file','HandleVisibility','off','CallBack','spm_figure(''PrintTo'',spm_figure(''FindWin'',''Graphics''))'); % ### CODE FOR SATELLITE FIGURE ### % Code checks if there is a satellite window and if results are currently displayed % It assumes that if hReg is invalid then there are no results currently displayed % Modified by DRG to display a satellite figure 02/14/01. cb = ['global SatWindow,',... 'try,',... 'tmp = get(hReg);,',... 'ResFlag = 1;',... 'catch,',... 'ResFlag = 0;',... 'end,',... 'if SatWindow,',... 'figure(SatWindow),',... 'else,',... 'if ResFlag,',... 'spm_setup_satfig,',... 'end,',... 'end']; uimenu( F,'Label','Results-Fig','HandleVisibility','off','Callback',cb); % ### END NEW CODE ### set(0,'ShowHiddenHandles',cSHH) try spm_jobman('pulldown'); end %======================================================================= case 'figcontextmenu' %======================================================================= % h = spm_figure('FigContextMenu',F) if nargin<2 F = get(0,'CurrentFigure'); if isempty(F), error('no figure'), end else F = spm_figure('FindWin',varargin{2}); if isempty(F), error('no such figure'), end end h = uicontextmenu('Parent',F,'HandleVisibility','CallBack'); cSHH = get(0,'ShowHiddenHandles'); set(0,'ShowHiddenHandles','on') copy_menu(F,h); set(0,'ShowHiddenHandles',cSHH) set(F,'UIContextMenu',h) varargout = {h}; case 'colormap' %======================================================================= % spm_figure('ColorMap',ColAction,h) if nargin<3, h=[]; else h=varargin{3}; end if nargin<2, ColAction='gray'; else ColAction=varargin{2}; end switch lower(ColAction), case 'gray' colormap(gray(64)) case 'hot' colormap(hot(64)) case 'pink' colormap(pink(64)) case 'jet' colormap(jet(64)) case 'gray-hot' tmp = hot(64 + 16); tmp = tmp((1:64) + 16,:); colormap([gray(64); tmp]); case 'gray-cool' cool = [zeros(10,1) zeros(10,1) linspace(0.5,1,10)'; zeros(31,1) linspace(0,1,31)' ones(31,1); linspace(0,1,23)' ones(23,1) ones(23,1) ]; colormap([gray(64); cool]); case 'gray-pink' tmp = pink(64 + 16); tmp = tmp((1:64) + 16,:); colormap([gray(64); tmp]); case 'gray-jet' colormap([gray(64); jet(64)]); case 'invert' colormap(flipud(colormap)); case 'brighten' colormap(brighten(colormap, 0.2)); case 'darken' colormap(brighten(colormap, -0.2)); otherwise error('Illegal ColAction specification'); end case 'graphicshandle' %======================================================================= % h = spm_figure('GraphicsHandle',F) if nargin<2, F=gcbf; else F=spm_figure('FindWin',varargin{2}); end if isempty(F), return, end tmp = get(F,'Name'); set(F,'Name',... 'Handle: Select item to identify, MiddleMouse=parent, RightMouse=cancel...'); set(F,'Pointer','CrossHair') waitforbuttonpress; h = gco(F); hType = get(h,'Type'); SelnType = get(gcf,'SelectionType'); set(F,'Pointer','Arrow','Name',tmp) if ~strcmp(SelnType,'alt') && ~isempty(h) && gcf==F str = sprintf('Selected (%s) object',get(h,'Type')); if strcmp(SelnType,'normal') str = sprintf('%s: handle',str); else h = get(h,'Parent'); str = sprintf('%s: handle of parent (%s) object',str,get(h,'Type')); end if nargout==0 assignin('base','ans',h) fprintf('\n%s: \n',str) ans = h else varargout={h}; end else varargout={[]}; end otherwise %======================================================================= warning(['Illegal Action string: ',Action]) end return; %======================================================================= %======================================================================= function copy_menu(F,G) %======================================================================= handles = findobj(get(F,'Children'),'Flat','Type','uimenu','Visible','on'); if isempty(handles), return; end; for F1=handles', if ~strcmp(get(F1,'Label'),'&Window'), G1 = uimenu(G,'Label',get(F1,'Label'),... 'CallBack',get(F1,'CallBack'),... 'Position',get(F1,'Position'),... 'Separator',get(F1,'Separator')); copy_menu(F1,G1); end; end; return; %=======================================================================
github
lcnbeapp/beapp-master
spm_smooth.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_smooth.m
3,654
utf_8
0f00684dc1b7cb99c88cd50e6a64a20a
function spm_smooth(P,Q,s,dtype) % 3 dimensional convolution of an image % FORMAT spm_smooth(P,Q,S,dtype) % P - image to be smoothed % Q - filename for smoothed image % S - [sx sy sz] Gaussian filter width {FWHM} in mm % dtype - datatype [default: 0 == same datatype as P] %____________________________________________________________________________ % % spm_smooth is used to smooth or convolve images in a file (maybe). % % The sum of kernel coeficients are set to unity. Boundary % conditions assume data does not exist outside the image in z (i.e. % the kernel is truncated in z at the boundaries of the image space). S % can be a vector of 3 FWHM values that specifiy an anisotropic % smoothing. If S is a scalar isotropic smoothing is implemented. % % If Q is not a string, it is used as the destination of the smoothed % image. It must already be defined with the same number of elements % as the image. % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner & Tom Nichols % $Id$ %----------------------------------------------------------------------- if length(s) == 1; s = [s s s]; end if nargin<4, dtype = 0; end; if ischar(P), P = spm_vol(P); end; if isstruct(P), for i=1:numel(P), smooth1(P(i),Q,s,dtype); end else smooth1(P,Q,s,dtype); end %_______________________________________________________________________ %_______________________________________________________________________ function smooth1(P,Q,s,dtype) if isstruct(P), VOX = sqrt(sum(P.mat(1:3,1:3).^2)); else VOX = [1 1 1]; end; if ischar(Q) && isstruct(P), [pth,nam,ext,num] = spm_fileparts(Q); q = fullfile(pth,[nam,ext]); Q = P; Q.fname = q; if ~isempty(num), Q.n = str2num(num); end; if ~isfield(Q,'descrip'), Q.descrip = sprintf('SPM compatible'); end; Q.descrip = sprintf('%s - conv(%g,%g,%g)',Q.descrip, s); if dtype~=0, % Need to figure out some rescaling. Q.dt(1) = dtype; if ~isfinite(spm_type(Q.dt(1),'maxval')), Q.pinfo = [1 0 0]'; % float or double, so scalefactor of 1 else % Need to determine the range of intensities if isfinite(spm_type(P.dt(1),'maxval')), % Integer types have a defined maximum value maxv = spm_type(P.dt(1),'maxval')*P.pinfo(1) + P.pinfo(2); else % Need to find the max and min values in original image mx = -Inf; mn = Inf; for pl=1:P.dim(3), tmp = spm_slice_vol(P,spm_matrix([0 0 pl]),P.dim(1:2),0); tmp = tmp(isfinite(tmp)); mx = max(max(tmp),mx); mn = min(min(tmp),mn); end maxv = max(mx,-mn); end sf = maxv/spm_type(Q.dt(1),'maxval'); Q.pinfo = [sf 0 0]'; end end end % compute parameters for spm_conv_vol %----------------------------------------------------------------------- s = s./VOX; % voxel anisotropy s1 = s/sqrt(8*log(2)); % FWHM -> Gaussian parameter x = round(6*s1(1)); x = -x:x; x = spm_smoothkern(s(1),x,1); x = x/sum(x); y = round(6*s1(2)); y = -y:y; y = spm_smoothkern(s(2),y,1); y = y/sum(y); z = round(6*s1(3)); z = -z:z; z = spm_smoothkern(s(3),z,1); z = z/sum(z); i = (length(x) - 1)/2; j = (length(y) - 1)/2; k = (length(z) - 1)/2; if isstruct(Q), Q = spm_create_vol(Q); end; spm_conv_vol(P,Q,x,y,z,-[i,j,k]);
github
lcnbeapp/beapp-master
spm_smoothto8bit.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_smoothto8bit.m
2,377
utf_8
89653bff7e0591df6fa676885a830a16
function VO = spm_smoothto8bit(V,fwhm) % 3 dimensional convolution of an image to 8bit data in memory % FORMAT VO = spm_smoothto8bit(V,fwhm) % V - mapped image to be smoothed % fwhm - FWHM of Guassian filter width in mm % VO - smoothed volume in a form that can be used by the % spm_*_vol.mex* functions. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ if nargin>1 & fwhm>0, VO = smoothto8bit(V,fwhm); else, VO = V; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = smoothto8bit(V,fwhm) % 3 dimensional convolution of an image to 8bit data in memory % FORMAT VO = smoothto8bit(V,fwhm) % V - mapped image to be smoothed % fwhm - FWHM of Guassian filter width in mm % VO - smoothed volume in a form that can be used by the % spm_*_vol.mex* functions. %_______________________________________________________________________ vx = sqrt(sum(V.mat(1:3,1:3).^2)); s = (fwhm./vx./sqrt(8*log(2)) + eps).^2; r = cell(1,3); for i=1:3, r{i}.s = ceil(3.5*sqrt(s(i))); x = -r{i}.s:r{i}.s; r{i}.k = exp(-0.5 * (x.*x)/s(i))/sqrt(2*pi*s(i)); r{i}.k = r{i}.k/sum(r{i}.k); end; buff = zeros([V.dim(1:2) r{3}.s*2+1]); VO = V; VO.dt = [spm_type('uint8') spm_platform('bigend')]; V0.dat = uint8(0); V0.dat(VO.dim(1:3)) = uint8(0); VO.pinfo = []; for i=1:V.dim(3)+r{3}.s, if i<=V.dim(3), img = spm_slice_vol(V,spm_matrix([0 0 i]),V.dim(1:2),0); msk = find(~isfinite(img)); img(msk) = 0; buff(:,:,rem(i-1,r{3}.s*2+1)+1) = ... conv2(conv2(img,r{1}.k,'same'),r{2}.k','same'); else, buff(:,:,rem(i-1,r{3}.s*2+1)+1) = 0; end; if i>r{3}.s, kern = zeros(size(r{3}.k')); kern(rem((i:(i+r{3}.s*2))',r{3}.s*2+1)+1) = r{3}.k'; img = reshape(buff,[prod(V.dim(1:2)) r{3}.s*2+1])*kern; img = reshape(img,V.dim(1:2)); ii = i-r{3}.s; mx = max(img(:)); mn = min(img(:)); if mx==mn, mx=mn+eps; end; VO.pinfo(1:2,ii) = [(mx-mn)/255 mn]'; VO.dat(:,:,ii) = uint8(round((img-mn)*(255/(mx-mn)))); end; end;
github
lcnbeapp/beapp-master
spm_platform.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_platform.m
8,498
utf_8
9af699511e4e0bff6555d7a1e3fe0a23
function varargout=spm_platform(varargin) % Platform specific configuration parameters for SPM % % FORMAT ans = spm_platform(arg) % arg - optional string argument, can be % - 'bigend' - return whether this architecture is bigendian % - 0 - is little endian % - 1 - is big endian % - 'filesys' - type of filesystem % - 'unx' - UNIX % - 'win' - DOS % - 'sepchar' - returns directory separator % - 'user' - returns username % - 'host' - returns system's host name % - 'tempdir' - returns name of temp directory % - 'drives' - returns string containing valid drive letters % % FORMAT PlatFontNames = spm_platform('fonts') % Returns structure with fields named after the generic (UNIX) fonts, the % field containing the name of the platform specific font. % % FORMAT PlatFontName = spm_platform('font',GenFontName) % Maps generic (UNIX) FontNames to platform specific FontNames % % FORMAT PLATFORM = spm_platform('init',comp) % Initialises platform specific parameters in persistent PLATFORM % (External gateway to init_platform(comp) subfunction) % comp - computer to use [defaults to MATLAB's `computer`] % PLATFORM - copy of persistent PLATFORM % % FORMAT spm_platform % Initialises platform specific parameters in persistent PLATFORM % (External gateway to init_platform(computer) subfunction) % % ---------------- % SUBFUNCTIONS: % % FORMAT init_platform(comp) % Initialise platform specific parameters in persistent PLATFORM % comp - computer to use [defaults to MATLAB's `computer`] % %-------------------------------------------------------------------------- % % Since calls to spm_platform will be made frequently, most platform % specific parameters are stored as a structure in the persistent variable % PLATFORM. Subsequent calls use the information from this persistent % variable, if it exists. % % Platform specific definitions are contained in the data structures at % the beginning of the init_platform subfunction at the end of this % file. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Matthew Brett % $Id$ %-Initialise %-------------------------------------------------------------------------- persistent PLATFORM if isempty(PLATFORM), PLATFORM = init_platform; end if nargin==0, return, end switch lower(varargin{1}), case 'init' %-(re)initialise %========================================================================== init_platform(varargin{2:end}); varargout = {PLATFORM}; case 'bigend' %-Return endian for this architecture %========================================================================== varargout = {PLATFORM.bigend}; case 'filesys' %-Return file system %========================================================================== varargout = {PLATFORM.filesys}; case 'sepchar' %-Return file separator character %========================================================================== warning('use filesep instead (supported by MathWorks)') varargout = {PLATFORM.sepchar}; case 'rootlen' %-Return length in chars of root directory name %======================================================================= varargout = {PLATFORM.rootlen}; case 'user' %-Return user string %========================================================================== varargout = {PLATFORM.user}; case 'host' %-Return hostname %========================================================================== varargout = {PLATFORM.host}; case 'drives' %-Return drives %========================================================================== varargout = {PLATFORM.drives}; case 'tempdir' %-Return temporary directory %========================================================================== twd = getenv('SPMTMP'); if isempty(twd) twd = tempdir; end varargout = {twd}; case {'font','fonts'} %-Map default font names to platform font names %========================================================================== if nargin<2, varargout={PLATFORM.font}; return, end switch lower(varargin{2}) case 'times' varargout = {PLATFORM.font.times}; case 'courier' varargout = {PLATFORM.font.courier}; case 'helvetica' varargout = {PLATFORM.font.helvetica}; case 'symbol' varargout = {PLATFORM.font.symbol}; otherwise warning(['Unknown font ',varargin{2},', using default']) varargout = {PLATFORM.font.helvetica}; end otherwise %-Unknown Action string %========================================================================== error('Unknown Action string') %========================================================================== end %========================================================================== %- S U B - F U N C T I O N S %========================================================================== function PLATFORM = init_platform(comp) %-Initialise platform variables %========================================================================== if nargin<1, comp=computer; end %-Platform definitions %-------------------------------------------------------------------------- PDefs = {'PCWIN', 'win', 0;... 'PCWIN64', 'win', 0;... 'MAC', 'unx', 1;... 'MACI', 'unx', 0;... 'MACI64', 'unx', 0;... 'SOL2', 'unx', 1;... 'SOL64', 'unx', 1;... 'GLNX86', 'unx', 0;... 'GLNXA64', 'unx', 0}; PDefs = cell2struct(PDefs,{'computer','filesys','endian'},2); %-Which computer? %-------------------------------------------------------------------------- [issup, ci] = ismember(comp,{PDefs.computer}); if ~issup error([comp ' not supported architecture for ' spm('Ver')]); end %-Set byte ordering %-------------------------------------------------------------------------- PLATFORM.bigend = PDefs(ci).endian; %-Set filesystem type %-------------------------------------------------------------------------- PLATFORM.filesys = PDefs(ci).filesys; %-File separator character %-------------------------------------------------------------------------- PLATFORM.sepchar = filesep; %-Username %-------------------------------------------------------------------------- switch PLATFORM.filesys case 'unx' PLATFORM.user = getenv('USER'); case 'win' PLATFORM.user = getenv('USERNAME'); otherwise error(['Don''t know filesystem ',PLATFORM.filesys]) end if isempty(PLATFORM.user), PLATFORM.user = 'anonymous'; end %-Hostname %-------------------------------------------------------------------------- [sts, Host] = system('hostname'); if sts if strcmp(PLATFORM.filesys,'win') Host = getenv('COMPUTERNAME'); else Host = getenv('HOSTNAME'); end Host = regexp(Host,'(.*?)\.','tokens','once'); else Host = Host(1:end-1); end PLATFORM.host = Host; %-Drives %-------------------------------------------------------------------------- PLATFORM.drives = ''; if strcmp(PLATFORM.filesys,'win') driveLett = cellstr(char(('C':'Z')')); for i=1:numel(driveLett) if exist([driveLett{i} ':\'],'dir') PLATFORM.drives = [PLATFORM.drives driveLett{i}]; end end end %-Fonts %-------------------------------------------------------------------------- switch comp case {'MAC','MACI','MACI64'} PLATFORM.font.helvetica = 'TrebuchetMS'; PLATFORM.font.times = 'Times'; PLATFORM.font.courier = 'Courier'; PLATFORM.font.symbol = 'Symbol'; case {'SOL2','SOL64','GLNX86','GLNXA64'} PLATFORM.font.helvetica = 'Helvetica'; PLATFORM.font.times = 'Times'; PLATFORM.font.courier = 'Courier'; PLATFORM.font.symbol = 'Symbol'; case {'PCWIN','PCWIN64'} PLATFORM.font.helvetica = 'Arial Narrow'; PLATFORM.font.times = 'Times New Roman'; PLATFORM.font.courier = 'Courier New'; PLATFORM.font.symbol = 'Symbol'; end
github
lcnbeapp/beapp-master
spm_preproc.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_preproc.m
20,519
utf_8
c08f55c5a2eaeb3e30508750d366f52f
function results = spm_preproc(varargin) % Combined Segmentation and Spatial Normalisation % % FORMAT results = spm_preproc(V,opts) % V - image to work with % opts - options % opts.tpm - n tissue probability images for each class % opts.ngaus - number of Gaussians per class (n+1 classes) % opts.warpreg - warping regularisation % opts.warpco - cutoff distance for DCT basis functions % opts.biasreg - regularisation for bias correction % opts.biasfwhm - FWHM of Gausian form for bias regularisation % opts.regtype - regularisation for affine part % opts.fudge - a fudge factor % opts.msk - unused % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ [dir,nam,ext] = fileparts(which(mfilename)); opts0.tpm = char(... fullfile(dir,'tpm','grey.nii'),... fullfile(dir,'tpm','white.nii'),... fullfile(dir,'tpm','csf.nii')); opts0.ngaus = [2 2 2 4]; opts0.warpreg = 1; opts0.warpco = 25; opts0.biasreg = 0.0001; opts0.biasfwhm = 75; opts0.regtype = 'mni'; opts0.fudge = 5; opts0.samp = 3; opts0.msk = ''; if nargin==0 V = spm_select(1,'image'); else V = varargin{1}; end; if ischar(V), V = spm_vol(V); end; if nargin < 2 opts = opts0; else opts = varargin{2}; fnms = fieldnames(opts0); for i=1:length(fnms) if ~isfield(opts,fnms{i}), opts.(fnms{i}) = opts0.(fnms{i}); end; end; end; if length(opts.ngaus)~= size(opts.tpm,1)+1, error('Number of Gaussians per class is not compatible with number of classes'); end; K = sum(opts.ngaus); Kb = length(opts.ngaus); lkp = []; for k=1:Kb, lkp = [lkp ones(1,opts.ngaus(k))*k]; end; B = spm_vol(opts.tpm); b0 = spm_load_priors(B); d = V(1).dim(1:3); vx = sqrt(sum(V(1).mat(1:3,1:3).^2)); sk = max([1 1 1],round(opts.samp*[1 1 1]./vx)); [x0,y0,o] = ndgrid(1:sk(1):d(1),1:sk(2):d(2),1); z0 = 1:sk(3):d(3); tiny = eps; vx = sqrt(sum(V(1).mat(1:3,1:3).^2)); kron = inline('spm_krutil(a,b)','a','b'); % BENDING ENERGY REGULARIZATION for warping %----------------------------------------------------------------------- lam = 0.001; d2 = max(round((V(1).dim(1:3).*vx)/opts.warpco),[1 1 1]); kx = (pi*((1:d2(1))'-1)/d(1)/vx(1)).^2; ky = (pi*((1:d2(2))'-1)/d(2)/vx(2)).^2; kz = (pi*((1:d2(3))'-1)/d(3)/vx(3)).^2; Cwarp = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +... 1*kron(kz.^0,kron(ky.^2,kx.^0)) +... 1*kron(kz.^0,kron(ky.^0,kx.^2)) +... 2*kron(kz.^1,kron(ky.^1,kx.^0)) +... 2*kron(kz.^1,kron(ky.^0,kx.^1)) +... 2*kron(kz.^0,kron(ky.^1,kx.^1)) ); Cwarp = Cwarp*opts.warpreg; Cwarp = [Cwarp*vx(1)^4 ; Cwarp*vx(2)^4 ; Cwarp*vx(3)^4]; Cwarp = sparse(1:length(Cwarp),1:length(Cwarp),Cwarp,length(Cwarp),length(Cwarp)); B3warp = spm_dctmtx(d(3),d2(3),z0); B2warp = spm_dctmtx(d(2),d2(2),y0(1,:)'); B1warp = spm_dctmtx(d(1),d2(1),x0(:,1)); lmR = speye(size(Cwarp)); Twarp = zeros([d2 3]); % GAUSSIAN REGULARISATION for bias correction %----------------------------------------------------------------------- fwhm = opts.biasfwhm; sd = vx(1)*V(1).dim(1)/fwhm; d3(1) = ceil(sd*2); krn_x = exp(-(0:(d3(1)-1)).^2/sd.^2)/sqrt(vx(1)); sd = vx(2)*V(1).dim(2)/fwhm; d3(2) = ceil(sd*2); krn_y = exp(-(0:(d3(2)-1)).^2/sd.^2)/sqrt(vx(2)); sd = vx(3)*V(1).dim(3)/fwhm; d3(3) = ceil(sd*2); krn_z = exp(-(0:(d3(3)-1)).^2/sd.^2)/sqrt(vx(3)); Cbias = kron(krn_z,kron(krn_y,krn_x)).^(-2)*opts.biasreg; Cbias = sparse(1:length(Cbias),1:length(Cbias),Cbias,length(Cbias),length(Cbias)); B3bias = spm_dctmtx(d(3),d3(3),z0); B2bias = spm_dctmtx(d(2),d3(2),y0(1,:)'); B1bias = spm_dctmtx(d(1),d3(1),x0(:,1)); lmRb = speye(size(Cbias)); Tbias = zeros(d3); % Fudge Factor - to (approximately) account for % non-independence of voxels ff = opts.fudge; ff = max(1,ff^3/prod(sk)/abs(det(V.mat(1:3,1:3)))); Cwarp = Cwarp*ff; Cbias = Cbias*ff; ll = -Inf; llr = 0; llrb = 0; tol1 = 1e-4; % Stopping criterion. For more accuracy, use a smaller value d = [size(x0) length(z0)]; f = zeros(d); for z=1:length(z0), f(:,:,z) = spm_sample_vol(V,x0,y0,o*z0(z),0); end; [thresh,mx] = spm_minmax(f); mn = zeros(K,1); rand('state',0); % give same results each time for k1=1:Kb, kk = sum(lkp==k1); mn(lkp==k1) = rand(kk,1)*mx; end; vr = ones(K,1)*mx^2; mg = ones(K,1)/K; if ~isempty(opts.msk), VM = spm_vol(opts.msk); if sum(sum((VM.mat-V(1).mat).^2)) > 1e-6 || any(VM.dim(1:3) ~= V(1).dim(1:3)), error('Mask must have the same dimensions and orientation as the image.'); end; end; Affine = eye(4); if ~isempty(opts.regtype), Affine = spm_maff(V,{x0,y0,z0},b0,B(1).mat,Affine,opts.regtype,ff*100); Affine = spm_maff(V,{x0,y0,z0},b0,B(1).mat,Affine,opts.regtype,ff); end; M = B(1).mat\Affine*V(1).mat; nm = 0; for z=1:length(z0), x1 = M(1,1)*x0 + M(1,2)*y0 + (M(1,3)*z0(z) + M(1,4)); y1 = M(2,1)*x0 + M(2,2)*y0 + (M(2,3)*z0(z) + M(2,4)); z1 = M(3,1)*x0 + M(3,2)*y0 + (M(3,3)*z0(z) + M(3,4)); buf(z).msk = spm_sample_priors(b0{end},x1,y1,z1,1)<(1-1/512); fz = f(:,:,z); %buf(z).msk = fz>thresh; buf(z).msk = buf(z).msk & isfinite(fz) & (fz~=0); if ~isempty(opts.msk), msk = spm_sample_vol(VM,x0,y0,o*z0(z),0); buf(z).msk = buf(z).msk & msk; end; buf(z).nm = sum(buf(z).msk(:)); buf(z).f = fz(buf(z).msk); nm = nm + buf(z).nm; buf(z).bf(1:buf(z).nm,1) = single(1); buf(z).dat = single(0); if buf(z).nm, buf(z).dat(buf(z).nm,Kb) = single(0); end; end; clear f finalit = 0; spm_chi2_plot('Init','Processing','Log-likelihood','Iteration'); for iter=1:100, if finalit, % THIS CODE MAY BE USED IN FUTURE % Reload the data for the final iteration. This iteration % does not do any registration, so there is no need to % mask out the background voxels. %------------------------------------------------------------ llrb = -0.5*Tbias(:)'*Cbias*Tbias(:); for z=1:length(z0), fz = spm_sample_vol(V,x0,y0,o*z0(z),0); buf(z).msk = fz~=0; if ~isempty(opts.msk), msk = spm_sample_vol(VM,x0,y0,o*z0(z),0); buf(z).msk = buf(z).msk & msk; end; buf(z).nm = sum(buf(z).msk(:)); buf(z).f = fz(buf(z).msk); nm = nm + buf(z).nm; buf(z).bf(1:buf(z).nm,1) = single(1); buf(z).dat = single(0); if buf(z).nm, buf(z).dat(buf(z).nm,Kb) = single(0); end; if buf(z).nm, bf = transf(B1bias,B2bias,B3bias(z,:),Tbias); tmp = bf(buf(z).msk); llrb = llrb + sum(tmp); buf(z).bf = single(exp(tmp)); end; end; % The background won't fit well any more, so increase the % variances of these Gaussians in order to give it a chance vr(lkp(K)) = vr(lkp(K))*8; spm_chi2_plot('Init','Processing','Log-likelihood','Iteration'); end; % Load the warped prior probability images into the buffer %------------------------------------------------------------ for z=1:length(z0), if ~buf(z).nm, continue; end; [x1,y1,z1] = defs(Twarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk); for k1=1:Kb, tmp = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb); buf(z).dat(:,k1) = single(tmp); end; end; for iter1=1:10, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Estimate cluster parameters %------------------------------------------------------------ for subit=1:40, oll = ll; mom0 = zeros(K,1)+tiny; mom1 = zeros(K,1); mom2 = zeros(K,1); mgm = zeros(Kb,1); ll = llr+llrb; for z=1:length(z0), if ~buf(z).nm, continue; end; bf = double(buf(z).bf); cr = double(buf(z).f).*bf; q = zeros(buf(z).nm,K); b = zeros(buf(z).nm,Kb); s = zeros(buf(z).nm,1)+tiny; for k1=1:Kb, pr = double(buf(z).dat(:,k1)); b(:,k1) = pr; s = s + pr*sum(mg(lkp==k1)); end; for k1=1:Kb, b(:,k1) = b(:,k1)./s; end; mgm = mgm + sum(b,1)'; for k=1:K, q(:,k) = mg(k)*b(:,lkp(k)) .* exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)); end; sq = sum(q,2)+tiny; ll = ll + sum(log(sq)); for k=1:K, % Moments p1 = q(:,k)./sq; mom0(k) = mom0(k) + sum(p1(:)); p1 = p1.*cr; mom1(k) = mom1(k) + sum(p1(:)); p1 = p1.*cr; mom2(k) = mom2(k) + sum(p1(:)); end; end; % Mixing proportions, Means and Variances for k=1:K, mg(k) = (mom0(k)+eps)/(mgm(lkp(k))+eps); mn(k) = mom1(k)/(mom0(k)+eps); vr(k) =(mom2(k)-mom1(k)*mom1(k)/mom0(k)+1e6*eps)/(mom0(k)+eps); vr(k) = max(vr(k),eps); end; if subit>1 || (iter>1 && ~finalit), spm_chi2_plot('Set',ll); end; if finalit, fprintf('Mix: %g\n',ll); end; if subit == 1, ooll = ll; elseif (ll-oll)<tol1*nm, % Improvement is small, so go to next step break; end; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Estimate bias %------------------------------------------------------------ if prod(d3)>0, for subit=1:40, % Compute objective function and its 1st and second derivatives Alpha = zeros(prod(d3),prod(d3)); % Second derivatives Beta = zeros(prod(d3),1); % First derivatives ollrb = llrb; oll = ll; ll = llr+llrb; for z=1:length(z0), if ~buf(z).nm, continue; end; bf = double(buf(z).bf); cr = double(buf(z).f).*bf; q = zeros(buf(z).nm,K); for k=1:K, q(:,k) = double(buf(z).dat(:,lkp(k)))*mg(k); end; s = sum(q,2)+tiny; for k=1:K, q(:,k) = q(:,k)./s .* exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)); end; sq = sum(q,2)+tiny; ll = ll + sum(log(sq)); w1 = zeros(buf(z).nm,1); w2 = zeros(buf(z).nm,1); for k=1:K, tmp = q(:,k)./sq/vr(k); w1 = w1 + tmp.*(mn(k) - cr); w2 = w2 + tmp; end; wt1 = zeros(d(1:2)); wt1(buf(z).msk) = 1 + cr.*w1; wt2 = zeros(d(1:2)); wt2(buf(z).msk) = cr.*(cr.*w2 - w1); b3 = B3bias(z,:)'; Beta = Beta + kron(b3,spm_krutil(wt1,B1bias,B2bias,0)); Alpha = Alpha + kron(b3*b3',spm_krutil(wt2,B1bias,B2bias,1)); clear w1 w2 wt1 wt2 b3 end; if finalit, fprintf('Bia: %g\n',ll); end; if subit > 1 && ~(ll>oll), % Hasn't improved, so go back to previous solution Tbias = oTbias; llrb = ollrb; for z=1:length(z0), if ~buf(z).nm, continue; end; bf = transf(B1bias,B2bias,B3bias(z,:),Tbias); buf(z).bf = single(exp(bf(buf(z).msk))); end; break; else % Accept new solution spm_chi2_plot('Set',ll); oTbias = Tbias; if subit > 1 && ~((ll-oll)>tol1*nm), % Improvement is only small, so go to next step break; else % Use new solution and continue the Levenberg-Marquardt iterations Tbias = reshape((Alpha + Cbias + lmRb)\((Alpha+lmRb)*Tbias(:) + Beta),d3); llrb = -0.5*Tbias(:)'*Cbias*Tbias(:); for z=1:length(z0), if ~buf(z).nm, continue; end; bf = transf(B1bias,B2bias,B3bias(z,:),Tbias); tmp = bf(buf(z).msk); llrb = llrb + sum(tmp); buf(z).bf = single(exp(tmp)); end; end; end; end; if ~((ll-ooll)>tol1*nm), break; end; end; end; if finalit, break; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Estimate deformations %------------------------------------------------------------ mg1 = full(sparse(lkp,1,mg)); ll = llr+llrb; for z=1:length(z0), if ~buf(z).nm, continue; end; bf = double(buf(z).bf); cr = double(buf(z).f).*bf; q = zeros(buf(z).nm,Kb); tmp = zeros(buf(z).nm,1)+tiny; s = zeros(buf(z).nm,1)+tiny; for k1=1:Kb, s = s + mg1(k1)*double(buf(z).dat(:,k1)); end; for k1=1:Kb, kk = find(lkp==k1); pp = zeros(buf(z).nm,1); for k=kk, pp = pp + exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k))*mg(k); end; q(:,k1) = pp; tmp = tmp+pp.*double(buf(z).dat(:,k1))./s; end; ll = ll + sum(log(tmp)); for k1=1:Kb, buf(z).dat(:,k1) = single(q(:,k1)); end; end; for subit=1:20, oll = ll; A = cell(3,3); A{1,1} = zeros(prod(d2)); A{1,2} = zeros(prod(d2)); A{1,3} = zeros(prod(d2)); A{2,2} = zeros(prod(d2)); A{2,3} = zeros(prod(d2)); A{3,3} = zeros(prod(d2)); Beta = zeros(prod(d2)*3,1); for z=1:length(z0), if ~buf(z).nm, continue; end; [x1,y1,z1] = defs(Twarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk); b = zeros(buf(z).nm,Kb); db1 = zeros(buf(z).nm,Kb); db2 = zeros(buf(z).nm,Kb); db3 = zeros(buf(z).nm,Kb); s = zeros(buf(z).nm,1)+tiny; ds1 = zeros(buf(z).nm,1); ds2 = zeros(buf(z).nm,1); ds3 = zeros(buf(z).nm,1); p = zeros(buf(z).nm,1)+tiny; dp1 = zeros(buf(z).nm,1); dp2 = zeros(buf(z).nm,1); dp3 = zeros(buf(z).nm,1); for k1=1:Kb, [b(:,k1),db1(:,k1),db2(:,k1),db3(:,k1)] = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb); s = s + mg1(k1)* b(:,k1); ds1 = ds1 + mg1(k1)*db1(:,k1); ds2 = ds2 + mg1(k1)*db2(:,k1); ds3 = ds3 + mg1(k1)*db3(:,k1); end; for k1=1:Kb, b(:,k1) = b(:,k1)./s; db1(:,k1) = (db1(:,k1)-b(:,k1).*ds1)./s; db2(:,k1) = (db2(:,k1)-b(:,k1).*ds2)./s; db3(:,k1) = (db3(:,k1)-b(:,k1).*ds3)./s; pp = double(buf(z).dat(:,k1)); p = p + pp.*b(:,k1); dp1 = dp1 + pp.*(M(1,1)*db1(:,k1) + M(2,1)*db2(:,k1) + M(3,1)*db3(:,k1)); dp2 = dp2 + pp.*(M(1,2)*db1(:,k1) + M(2,2)*db2(:,k1) + M(3,2)*db3(:,k1)); dp3 = dp3 + pp.*(M(1,3)*db1(:,k1) + M(2,3)*db2(:,k1) + M(3,3)*db3(:,k1)); end; clear x1 y1 z1 b db1 db2 db3 s ds1 ds2 ds3 tmp = zeros(d(1:2)); tmp(buf(z).msk) = dp1./p; dp1 = tmp; tmp(buf(z).msk) = dp2./p; dp2 = tmp; tmp(buf(z).msk) = dp3./p; dp3 = tmp; b3 = B3warp(z,:)'; Beta = Beta - [... kron(b3,spm_krutil(dp1,B1warp,B2warp,0)) kron(b3,spm_krutil(dp2,B1warp,B2warp,0)) kron(b3,spm_krutil(dp3,B1warp,B2warp,0))]; b3b3 = b3*b3'; A{1,1} = A{1,1} + kron(b3b3,spm_krutil(dp1.*dp1,B1warp,B2warp,1)); A{1,2} = A{1,2} + kron(b3b3,spm_krutil(dp1.*dp2,B1warp,B2warp,1)); A{1,3} = A{1,3} + kron(b3b3,spm_krutil(dp1.*dp3,B1warp,B2warp,1)); A{2,2} = A{2,2} + kron(b3b3,spm_krutil(dp2.*dp2,B1warp,B2warp,1)); A{2,3} = A{2,3} + kron(b3b3,spm_krutil(dp2.*dp3,B1warp,B2warp,1)); A{3,3} = A{3,3} + kron(b3b3,spm_krutil(dp3.*dp3,B1warp,B2warp,1)); clear b3 b3b3 tmp p dp1 dp2 dp3 end; Alpha = [A{1,1} A{1,2} A{1,3} ; A{1,2} A{2,2} A{2,3}; A{1,3} A{2,3} A{3,3}]; clear A for subit1 = 1:3, if iter==1, nTwarp = (Alpha+lmR*lam + 10*Cwarp)\((Alpha+lmR*lam)*Twarp(:) - Beta); else nTwarp = (Alpha+lmR*lam + Cwarp)\((Alpha+lmR*lam)*Twarp(:) - Beta); end; nTwarp = reshape(nTwarp,[d2 3]); nllr = -0.5*nTwarp(:)'*Cwarp*nTwarp(:); nll = nllr+llrb; for z=1:length(z0), if ~buf(z).nm, continue; end; [x1,y1,z1] = defs(nTwarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk); sq = zeros(buf(z).nm,1) + tiny; b = zeros(buf(z).nm,Kb); s = zeros(buf(z).nm,1)+tiny; for k1=1:Kb, b(:,k1) = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb); s = s + mg1(k1)*b(:,k1); end; for k1=1:Kb, sq = sq + double(buf(z).dat(:,k1)).*b(:,k1)./s; end; clear b nll = nll + sum(log(sq)); clear sq x1 y1 z1 end; if nll<ll, % Worse solution, so use old solution and increase regularisation lam = lam*10; else % Accept new solution ll = nll; llr = nllr; Twarp = nTwarp; lam = lam*0.5; break; end; end; spm_chi2_plot('Set',ll); if (ll-oll)<tol1*nm, break; end; end; if ~((ll-ooll)>tol1*nm), finalit = 1; break; % This can be commented out. end; end; spm_chi2_plot('Clear'); results = opts; results.image = V; results.tpm = B; results.Affine = Affine; results.Twarp = Twarp; results.Tbias = Tbias; results.mg = mg; results.mn = mn; results.vr = vr; results.thresh = 0; %thresh; results.ll = ll; return; %======================================================================= %======================================================================= function t = transf(B1,B2,B3,T) if ~isempty(T), d2 = [size(T) 1]; t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2)); t = B1*t1*B2'; else t = zeros(size(B1,1),size(B2,1)); end; return; %======================================================================= %======================================================================= function [x1,y1,z1] = defs(Twarp,z,B1,B2,B3,x0,y0,z0,M,msk) x1a = x0 + transf(B1,B2,B3(z,:),Twarp(:,:,:,1)); y1a = y0 + transf(B1,B2,B3(z,:),Twarp(:,:,:,2)); z1a = z0(z) + transf(B1,B2,B3(z,:),Twarp(:,:,:,3)); if nargin>=10, x1a = x1a(msk); y1a = y1a(msk); z1a = z1a(msk); end; x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4); y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4); z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4); return; %=======================================================================
github
lcnbeapp/beapp-master
spm_preproc_write.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_preproc_write.m
8,906
utf_8
9312486f72c3a8971ab0c9e847c3a465
function spm_preproc_write(p,opts) % Write out VBM preprocessed data % FORMAT spm_preproc_write(p,opts) % p - results from spm_prep2sn % opts - writing options. A struct containing these fields: % biascor - write bias corrected image % GM - flags for which images should be written % WM - similar to GM % CSF - similar to GM %____________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ if nargin==1, opts = struct('biascor',0,'GM',[0 0 1],'WM',[0 0 1],'CSF',[0 0 0],'cleanup',0); end; if numel(p)>0, b0 = spm_load_priors(p(1).VG); end; for i=1:numel(p), preproc_apply(p(i),opts,b0); end; return; %======================================================================= %======================================================================= function preproc_apply(p,opts,b0) %sopts = [opts.GM ; opts.WM ; opts.CSF]; nclasses = size(fieldnames(opts),1) - 2 ; switch nclasses case 3 sopts = [opts.GM ; opts.WM ; opts.CSF]; case 4 sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1]; case 5 sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1 ; opts.EXTRA2]; otherwise error('######## unsupported number of classes....!!!') end [pth,nam,ext]=fileparts(p.VF.fname); T = p.flags.Twarp; bsol = p.flags.Tbias; d2 = [size(T) 1]; d = p.VF.dim(1:3); [x1,x2,o] = ndgrid(1:d(1),1:d(2),1); x3 = 1:d(3); d3 = [size(bsol) 1]; B1 = spm_dctmtx(d(1),d2(1)); B2 = spm_dctmtx(d(2),d2(2)); B3 = spm_dctmtx(d(3),d2(3)); bB3 = spm_dctmtx(d(3),d3(3),x3); bB2 = spm_dctmtx(d(2),d3(2),x2(1,:)'); bB1 = spm_dctmtx(d(1),d3(1),x1(:,1)); mg = p.flags.mg; mn = p.flags.mn; vr = p.flags.vr; K = length(p.flags.mg); Kb = length(p.flags.ngaus); for k1=1:size(sopts,1), %dat{k1} = zeros(d(1:3),'uint8'); dat{k1} = uint8(0); dat{k1}(d(1),d(2),d(3)) = 0; if sopts(k1,3), Vt = struct('fname', fullfile(pth,['c', num2str(k1), nam, ext]),... 'dim', p.VF.dim,... 'dt', [spm_type('uint8') spm_platform('bigend')],... 'pinfo', [1/255 0 0]',... 'mat', p.VF.mat,... 'n', [1 1],... 'descrip', ['Tissue class ' num2str(k1)]); Vt = spm_create_vol(Vt); VO(k1) = Vt; end; end; if opts.biascor, VB = struct('fname', fullfile(pth,['m', nam, ext]),... 'dim', p.VF.dim(1:3),... 'dt', [spm_type('float32') spm_platform('bigend')],... 'pinfo', [1 0 0]',... 'mat', p.VF.mat,... 'n', [1 1],... 'descrip', 'Bias Corrected'); VB = spm_create_vol(VB); end; lkp = []; for k=1:Kb, lkp = [lkp ones(1,p.flags.ngaus(k))*k]; end; spm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed'); M = p.VG(1).mat\p.flags.Affine*p.VF.mat; for z=1:length(x3), % Bias corrected image f = spm_sample_vol(p.VF,x1,x2,o*x3(z),0); cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f; if opts.biascor, % Write a plane of bias corrected data VB = spm_write_plane(VB,cr,z); end; if any(sopts(:)), msk = (f==0) | ~isfinite(f); [t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M); q = zeros([d(1:2) Kb]); bt = zeros([d(1:2) Kb]); for k1=1:Kb, bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb); end; b = zeros([d(1:2) K]); for k=1:K, b(:,:,k) = bt(:,:,lkp(k))*mg(k); end; s = sum(b,3); for k=1:K, p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps); q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s; end; sq = sum(q,3)+eps; sw = warning('off','MATLAB:divideByZero'); for k1=1:size(sopts,1), tmp = q(:,:,k1); tmp(msk) = 0; tmp = tmp./sq; dat{k1}(:,:,z) = uint8(round(255 * tmp)); end; warning(sw); end; spm_progress_bar('set',z); end; spm_progress_bar('clear'); if opts.cleanup > 0, [dat{1},dat{2},dat{3}] = clean_gwc(dat{1},dat{2},dat{3}, opts.cleanup); end; if any(sopts(:,3)), for z=1:length(x3), for k1=1:size(sopts,1), if sopts(k1,3), tmp = double(dat{k1}(:,:,z))/255; spm_write_plane(VO(k1),tmp,z); end; end; end; end; for k1=1:size(sopts,1), if any(sopts(k1,1:2)), so = struct('wrap',[0 0 0],'interp',1,'vox',[NaN NaN NaN],... 'bb',ones(2,3)*NaN,'preserve',0); ovx = abs(det(p.VG(1).mat(1:3,1:3)))^(1/3); fwhm = max(ovx./sqrt(sum(p.VF.mat(1:3,1:3).^2))-1,0.1); dat{k1} = decimate(dat{k1},fwhm); fn = fullfile(pth,['c', num2str(k1), nam, ext]); dim = [size(dat{k1}) 1]; VT = struct('fname',fn,'dim',dim(1:3),... 'dt', [spm_type('uint8') spm_platform('bigend')],... 'pinfo',[1/255 0]','mat',p.VF.mat,'dat',dat{k1}); if sopts(k1,2), spm_write_sn(VT,p,so); end; so.preserve = 1; if sopts(k1,1), VN = spm_write_sn(VT,p,so); VN.fname = fullfile(pth,['mwc', num2str(k1), nam, ext]); spm_write_vol(VN,VN.dat); end; end; end; return; %======================================================================= %======================================================================= function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M) x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1)); y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2)); z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3)); x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4); y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4); z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4); return; %======================================================================= %======================================================================= function t = transf(B1,B2,B3,T) if ~isempty(T) d2 = [size(T) 1]; t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2)); t = B1*t1*B2'; else t = zeros(size(B1,1),size(B2,1),size(B3,1)); end; return; %======================================================================= %======================================================================= function dat = decimate(dat,fwhm) % Convolve the volume in memory (fwhm in voxels). lim = ceil(2*fwhm); x = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x); y = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y); z = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z); i = (length(x) - 1)/2; j = (length(y) - 1)/2; k = (length(z) - 1)/2; spm_conv_vol(dat,dat,x,y,z,-[i j k]); return; %======================================================================= %======================================================================= function [g,w,c] = clean_gwc(g,w,c, level) if nargin<4, level = 1; end; b = w; b(1) = w(1); % Build a 3x3x3 seperable smoothing kernel %----------------------------------------------------------------------- kx=[0.75 1 0.75]; ky=[0.75 1 0.75]; kz=[0.75 1 0.75]; sm=sum(kron(kron(kz,ky),kx))^(1/3); kx=kx/sm; ky=ky/sm; kz=kz/sm; th1 = 0.15; if level==2, th1 = 0.2; end; % Erosions and conditional dilations %----------------------------------------------------------------------- niter = 32; spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed'); for j=1:niter, if j>2, th=th1; else th=0.6; end; % Dilate after two its of erosion. for i=1:size(b,3), gp = double(g(:,:,i)); wp = double(w(:,:,i)); bp = double(b(:,:,i))/255; bp = (bp>th).*(wp+gp); b(:,:,i) = uint8(round(bp)); end; spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]); spm_progress_bar('Set',j); end; th = 0.05; for i=1:size(b,3), gp = double(g(:,:,i))/255; wp = double(w(:,:,i))/255; cp = double(c(:,:,i))/255; bp = double(b(:,:,i))/255; bp = ((bp>th).*(wp+gp))>th; g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps))); w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps))); c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp)))); end; spm_progress_bar('Clear'); return; %======================================================================= %=======================================================================
github
lcnbeapp/beapp-master
spm.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm.m
44,832
utf_8
d2d75e50e191a0c29cf483d58a754d7f
function varargout=spm(varargin) % SPM: Statistical Parametric Mapping (startup function) %_______________________________________________________________________ % ___ ____ __ __ % / __)( _ \( \/ ) % \__ \ )___/ ) ( Statistical Parametric Mapping % (___/(__) (_/\/\_) SPM - http://www.fil.ion.ucl.ac.uk/spm/ %_______________________________________________________________________ % % SPM (Statistical Parametric Mapping) is a package for the analysis % functional brain mapping experiments. It is the in-house package of % the Wellcome Trust Centre for Neuroimaging, and is available to the % scientific community as copyright freeware under the terms of the % GNU General Public Licence. % % Theoretical, computational and other details of the package are % available in SPM's "Help" facility. This can be launched from the % main SPM Menu window using the "Help" button, or directly from the % command line using the command `spm_help`. % % Details of this release are available via the "About SPM" help topic % (file spm.man), accessible from the SPM splash screen. (Or type % `spm_help spm.man` in the MATLAB command window) % % This spm function initialises the default parameters, and displays a % splash screen with buttons leading to the PET, fMRI and M/EEG % modalities. Alternatively, `spm('pet')`, `spm('fmri')`, `spm('eeg')` % (equivalently `spm pet`, `spm fmri` and `spm eeg`) lead directly to % the respective modality interfaces. % % Once the modality is chosen, (and it can be toggled mid-session) the % SPM user interface is displayed. This provides a constant visual % environment in which data analysis is implemented. The layout has % been designed to be simple and at the same time show all the % facilities that are available. The interface consists of three % windows: A menu window with pushbuttons for the SPM routines (each % button has a 'CallBack' string which launches the appropriate % function/script); A blank panel used for interaction with the user; % And a graphics figure with various editing and print facilities (see % spm_figure.m). (These windows are 'Tag'ged 'Menu', 'Interactive', and % 'Graphics' respectively, and should be referred to by their tags % rather than their figure numbers.) % % Further interaction with the user is (mainly) via questioning in the % 'Interactive' window (managed by spm_input), and file selection % (managed by spm_select). See the help on spm_input.m and spm_select.m for % details on using these functions. % % If a "message of the day" file named spm_motd.man exists in the SPM % directory (alongside spm.m) then it is displayed in the Graphics % window on startup. % % Arguments to this routine (spm.m) lead to various setup facilities, % mainly of use to SPM power users and programmers. See programmers % FORMAT & help in the main body of spm.m % %_______________________________________________________________________ % SPM is developed by members and collaborators of the % Wellcome Trust Centre for Neuroimaging %-SVN ID and authorship of this program... %----------------------------------------------------------------------- % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Andrew Holmes % $Id$ %======================================================================= % - FORMAT specifications for embedded CallBack functions %======================================================================= %( This is a multi function function, the first argument is an action ) %( string, specifying the particular action function to take. Recall ) %( MATLAB's command-function duality: `spm Welcome` is equivalent to ) %( `spm('Welcome')`. ) % % FORMAT spm % Defaults to spm('Welcome') % % FORMAT spm('Welcome') % Clears command window, deletes all figures, prints welcome banner and % splash screen, sets window defaults. % % FORMAT spm('AsciiWelcome') % Prints ASCII welcome banner in MATLAB command window. % % FORMAT spm('PET') spm('FMRI') spm('EEG') % Closes all windows and draws new Menu, Interactive, and Graphics % windows for an SPM session. The buttons in the Menu window launch the % main analysis routines. % % FORMAT spm('ChMod',Modality) % Changes modality of SPM: Currently SPM supports PET & MRI modalities, % each of which have a slightly different Menu window and different % defaults. This function switches to the specified modality, setting % defaults and displaying the relevant buttons. % % FORMAT spm('defaults',Modality) % Sets default global variables for the specified modality. % % FORMAT [Modality,ModNum]=spm('CheckModality',Modality) % Checks the specified modality against those supported, returns % upper(Modality) and the Modality number, it's position in the list of % supported Modalities. % % FORMAT Fmenu = spm('CreateMenuWin',Vis) % Creates SPM menu window, 'Tag'ged 'Menu' % F - handle of figure created % Vis - Visibility, 'on' or 'off' % % Finter = FORMAT spm('CreateIntWin',Vis) % Creates an SPM Interactive window, 'Tag'ged 'Interactive' % F - handle of figure created % Vis - Visibility, 'on' or 'off' % % FORMAT [Finter,Fgraph,CmdLine] = spm('FnUIsetup',Iname,bGX,CmdLine) % Robust UIsetup procedure for functions: % Returns handles of 'Interactive' and 'Graphics' figures. % Creates 'Interactive' figure if ~CmdLine, creates 'Graphics' figure if bGX. % Iname - Name for 'Interactive' window % bGX - Need a Graphics window? [default 1] % CmdLine - CommandLine usage? [default spm('CmdLine')] % Finter - handle of 'Interactive' figure % Fgraph - handle of 'Graphics' figure % CmdLine - CommandLine usage? % % FORMAT WS=spm('WinScale') % Returns ratios of current display dimensions to that of a 1152 x 900 % Sun display. WS=[Xratio,Yratio,Xratio,Yratio]. Used for scaling other % GUI elements. % (Function duplicated in spm_figure.m, repeated to reduce inter-dependencies.) % % FORMAT [FS,sf] = spm('FontSize',FS) % FORMAT [FS,sf] = spm('FontSizes',FS) % Returns fontsizes FS scaled for the current display. % FORMAT sf = spm('FontScale') % Returns font scaling factor % FS - (vector of) Font sizes to scale [default [1:36]] % sf - font scaling factor (FS(out) = floor(FS(in)*sf) % % Rect = spm('WinSize',Win,raw) % Returns sizes and positions for SPM windows. % Win - 'Menu', 'Interactive', 'Graphics', or '0' % - Window whose position is required. Only first character is % examined. '0' returns size of root workspace. % raw - If specified, then positions are for a 1152 x 900 Sun display. % Otherwise the positions are scaled for the current display. % % FORMAT [c,cName] = spm('Colour') % Returns the RGB triple and a description for the current en-vogue SPM % colour, the background colour for the Menu and Help windows. % % FORMAT F = spm('FigName',Iname,F,CmdLine) % Set name of figure F to "SPMver (User): Iname" if ~CmdLine % Robust to absence of figure. % Iname - Name for figure % F (input) - Handle (or 'Tag') of figure to name [default 'Interactive'] % CmdLine - CommandLine usage? [default spm('CmdLine')] % F (output) - Handle of figure named % % FORMAT Fs = spm('Show') % Opens all SPM figure windows (with HandleVisibility) using `figure`. % Maintains current figure. % Fs - vector containing all HandleVisible figures (i.e. get(0,'Children')) % % FORMAT spm('Clear',Finter, Fgraph) % Clears and resets SPM-GUI, clears and timestamps MATLAB command window. % Finter - handle or 'Tag' of 'Interactive' figure [default 'Interactive'] % Fgraph - handle or 'Tag' of 'Graphics' figure [default 'Graphics'] % % FORMAT SPMid = spm('FnBanner', Fn,FnV) % Prints a function start banner, for version FnV of function Fn, & datestamps % FORMAT SPMid = spm('SFnBanner',Fn,FnV) % Prints a sub-function start banner % FORMAT SPMid = spm('SSFnBanner',Fn,FnV) % Prints a sub-sub-function start banner % Fn - Function name (string) % FnV - Function version (string) % SPMid - ID string: [SPMver: Fn (FnV)] % % FORMAT SPMdir = spm('Dir',Mfile) % Returns the directory containing the version of spm in use, % identified as the first in MATLABPATH containing the Mfile spm (this % file) (or Mfile if specified). % % FORMAT [v,r] = spm('Ver',Mfile,ReDo) % Returns the current version (v) and release (r) of file Mfile. This % corresponds to the Last changed Revision number extracted from the % Subversion Id tag. % If Mfile is absent or empty then it returns the current SPM version (v) % and release (r), extracted from the file Contents.m in the SPM directory % (these information are cached in a persistent variable to enable repeat % use without recomputation). % If Redo [default false] is true, then the cached current SPM information % are not used but recomputed (and recached). % % FORMAT v = spm('MLver') % Returns MATLAB version, truncated to major & minor revision numbers % % FORMAT xTB = spm('TBs') % Identifies installed SPM toolboxes: SPM toolboxes are defined as the % contents of sub-directories of fullfile(spm('Dir'),'toolbox') - the % SPM toolbox installation directory. For SPM to pick a toolbox up, % there must be a single mfile in the directory whose name ends with % the toolbox directory name. (I.e. A toolbox called "test" would be in % the "test" subdirectory of spm('Dir'), with a single file named % *test.m.) This M-file is regarded as the launch file for the % toolbox. % xTB - structure array containing toolbox definitions % xTB.name - name of toolbox (taken as toolbox directory name) % xTB.prog - launch program for toolbox % xTB.dir - toolbox directory % % FORMAT spm('TBlaunch',xTB,i) % Launch a toolbox, prepending TBdir to path if necessary % xTB - toolbox definition structure (i.e. from spm('TBs') % xTB.name - name of toolbox % xTB.prog - name of program to launch toolbox % xTB.dir - toolbox directory (prepended to path if not on path) % % FORMAT [v1,v2,...] = spm('GetGlobal',name1,name2,...) % Returns values of global variables (without declaring them global) % name1, name2,... - name strings of desired globals % a1, a2,... - corresponding values of global variables with given names % ([] is returned as value if global variable doesn't exist) % % FORMAT CmdLine = spm('CmdLine',CmdLine) % Command line SPM usage? % CmdLine (input) - CmdLine preference % [defaults (missing or empty) to global defaults.cmdline,] % [if it exists, or 0 (GUI) otherwise. ] % CmdLine (output) - true if global CmdLine if true, % or if on a terminal with no support for graphics windows. % % FORMAT spm('PopUpCB',h) % Callback handler for PopUp UI menus with multiple callbacks as cellstr UserData % % FORMAT str = spm('GetUser',fmt) % Returns current users login name, extracted from the hosting environment % fmt - format string: If USER is defined then sprintf(fmt,USER) is returned % % FORMAT spm('Beep') % Plays the keyboard beep! % % FORMAT spm('time') % Returns the current time and date as hh:mm dd/mm/yyyy % % FORMAT spm('Pointer',Pointer) % Changes pointer on all SPM (HandleVisible) windows to type Pointer % Pointer defaults to 'Arrow'. Robust to absence of windows % % FORMAT h = spm('alert',Message,Title,CmdLine,wait) % FORMAT h = spm('alert"',Message,Title,CmdLine,wait) % FORMAT h = spm('alert*',Message,Title,CmdLine,wait) % FORMAT h = spm('alert!',Message,Title,CmdLine,wait) % Displays an alert, either in a GUI msgbox, or as text in the command window. % ( 'alert"' uses the 'help' msgbox icon, 'alert*' the ) % ( 'error' icon, 'alert!' the 'warn' icon ) % Message - string (or cellstr) containing message to print % Title - title string for alert % CmdLine - CmdLine preference [default spm('CmdLine')] % - If CmdLine is complex, then a CmdLine alert is always used, % possibly in addition to a msgbox (the latter according % to spm('CmdLine').) % wait - if true, waits until user dismisses GUI / confirms text alert % [default 0] (if doing both GUI & text, waits on GUI alert) % h - handle of msgbox created, empty if CmdLine used % % FORMAT spm('GUI_FileDelete') % CallBack for GUI for file deletion, using spm_select and confirmation dialogs % % FORMAT spm('Clean') % Clear all variables, globals, functions, MEX links and class definitions. % % FORMAT spm('Help',varargin) % Merely a gateway to spm_help(varargin) - so you can type "spm help" % % FORMAT spm('Quit') % Quit SPM, delete all windows and clear the command window. % %_______________________________________________________________________ %-Parameters %----------------------------------------------------------------------- Modalities = {'PET','FMRI','EEG'}; %-Format arguments %----------------------------------------------------------------------- if nargin == 0, Action = 'Welcome'; else Action = varargin{1}; end %======================================================================= switch lower(Action), case 'welcome' %-Welcome splash screen %======================================================================= % spm('Welcome') spm_check_installation('basic'); defaults = spm('GetGlobal','defaults'); if isfield(defaults,'modality') spm(defaults.modality); return end %-Open startup window, set window defaults %----------------------------------------------------------------------- Fwelcome = openfig(fullfile(spm('Dir'),'spm_Welcome.fig'),'new','invisible'); set(Fwelcome,'name',sprintf('%s%s',spm('ver'),spm('GetUser',' (%s)'))); set(get(findobj(Fwelcome,'Type','axes'),'children'),'FontName',spm_platform('Font','Times')); set(findobj(Fwelcome,'Tag','SPM_VER'),'String',spm('Ver')); RectW = spm('WinSize','W',1); Rect0 = spm('WinSize','0',1); set(Fwelcome,'Units','pixels', 'Position',... [Rect0(1)+(Rect0(3)-RectW(3))/2, Rect0(2)+(Rect0(4)-RectW(4))/2, RectW(3), RectW(4)]); set(Fwelcome,'Visible','on'); %======================================================================= case 'asciiwelcome' %-ASCII SPM banner welcome %======================================================================= % spm('AsciiWelcome') disp( ' ___ ____ __ __ '); disp( '/ __)( _ \( \/ ) '); disp( '\__ \ )___/ ) ( Statistical Parametric Mapping '); disp(['(___/(__) (_/\/\_) ',spm('Ver'),' - http://www.fil.ion.ucl.ac.uk/spm/']); fprintf('\n'); %======================================================================= case lower(Modalities) %-Initialise SPM in PET, fMRI, EEG modality %======================================================================= % spm(Modality) spm_check_installation('basic'); try, feature('JavaFigures',0); end %-Initialisation and workspace canonicalisation %----------------------------------------------------------------------- local_clc; spm('AsciiWelcome'); fprintf('\n\nInitialising SPM'); Modality = upper(Action); fprintf('.'); delete(get(0,'Children')); fprintf('.'); %-Load startup global defaults %----------------------------------------------------------------------- spm_defaults; fprintf('.'); %-Setup for batch system %----------------------------------------------------------------------- spm_jobman('initcfg'); spm_select('prevdirs',[spm('Dir') filesep]); %-Draw SPM windows %----------------------------------------------------------------------- if ~spm('CmdLine') Fmenu = spm('CreateMenuWin','off'); fprintf('.'); Finter = spm('CreateIntWin','off'); fprintf('.'); else Fmenu = []; Finter = []; end Fgraph = spm_figure('Create','Graphics','Graphics','off'); fprintf('.'); spm_figure('WaterMark',Finter,spm('Ver'),'',45); fprintf('.'); Fmotd = fullfile(spm('Dir'),'spm_motd.man'); if exist(Fmotd,'file'), spm_help('!Disp',Fmotd,'',Fgraph,spm('Ver')); end fprintf('.'); %-Setup for current modality %----------------------------------------------------------------------- spm('ChMod',Modality); fprintf('.'); %-Reveal windows %----------------------------------------------------------------------- set([Fmenu,Finter,Fgraph],'Visible','on'); fprintf('done\n\n'); %-Print present working directory %----------------------------------------------------------------------- fprintf('SPM present working directory:\n\t%s\n',pwd) %======================================================================= case 'chmod' %-Change SPM modality PET<->fMRI<->EEG %======================================================================= % spm('ChMod',Modality) %----------------------------------------------------------------------- %-Sort out arguments %----------------------------------------------------------------------- if nargin<2, Modality = ''; else Modality = varargin{2}; end [Modality,ModNum] = spm('CheckModality',Modality); %-Sort out global defaults %----------------------------------------------------------------------- spm('defaults',Modality); %-Sort out visability of appropriate controls on Menu window %----------------------------------------------------------------------- Fmenu = spm_figure('FindWin','Menu'); if ~isempty(Fmenu) if strcmpi(Modality,'PET') set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'on' ); set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'on' ); elseif strcmpi(Modality,'FMRI') set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'on' ); set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'on' ); else set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'off'); set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'on' ); end set(findobj(Fmenu,'Tag','Modality'),'Value',ModNum,'UserData',ModNum); else warning('SPM Menu window not found'); end %======================================================================= case 'defaults' %-Set SPM defaults (as global variable) %======================================================================= % spm('defaults',Modality) %----------------------------------------------------------------------- if nargin<2, Modality=''; else Modality=varargin{2}; end Modality = spm('CheckModality',Modality); %-Re-initialise, load defaults (from spm_defaults.m) and store modality %----------------------------------------------------------------------- clear global defaults spm_get_defaults('modality',Modality); %-Addpath modality-specific toolboxes %----------------------------------------------------------------------- if strcmpi(Modality,'EEG') && ~isdeployed addpath(fullfile(spm('Dir'),'external','fieldtrip')); ft_defaults; addpath(fullfile(spm('Dir'),'external','bemcp')); addpath(fullfile(spm('Dir'),'external','ctf')); addpath(fullfile(spm('Dir'),'external','eeprobe')); addpath(fullfile(spm('Dir'),'toolbox', 'dcm_meeg')); addpath(fullfile(spm('Dir'),'toolbox', 'spectral')); addpath(fullfile(spm('Dir'),'toolbox', 'Neural_Models')); addpath(fullfile(spm('Dir'),'toolbox', 'Beamforming')); addpath(fullfile(spm('Dir'),'toolbox', 'MEEGtools')); end %-Return defaults variable if asked %----------------------------------------------------------------------- if nargout, varargout = {spm_get_defaults}; end %======================================================================= case 'checkmodality' %-Check & canonicalise modality string %======================================================================= % [Modality,ModNum] = spm('CheckModality',Modality) %----------------------------------------------------------------------- if nargin<2, Modality=''; else Modality=upper(varargin{2}); end if isempty(Modality) try Modality = spm_get_defaults('modality'); end end if ischar(Modality) ModNum = find(ismember(Modalities,Modality)); else if ~any(Modality == 1:length(Modalities)) Modality = 'ERROR'; ModNum = []; else ModNum = Modality; Modality = Modalities{ModNum}; end end if isempty(ModNum) if isempty(Modality) fprintf('Modality is not set: use spm(''defaults'',''MOD''); '); fprintf('where MOD is one of PET, FMRI, EEG.\n'); end error('Unknown Modality.'); end varargout = {upper(Modality),ModNum}; %======================================================================= case 'createmenuwin' %-Create SPM menu window %======================================================================= % Fmenu = spm('CreateMenuWin',Vis) %----------------------------------------------------------------------- if nargin<2, Vis='on'; else Vis=varargin{2}; end %-Close any existing 'Menu' 'Tag'ged windows %----------------------------------------------------------------------- delete(spm_figure('FindWin','Menu')) Fmenu = openfig(fullfile(spm('Dir'),'spm_Menu.fig'),'new','invisible'); set(Fmenu,'name',sprintf('%s%s: Menu',spm('ver'),spm('GetUser',' (%s)'))); S0 = spm('WinSize','0',1); SM = spm('WinSize','M'); set(Fmenu,'Units','pixels', 'Position',[S0(1) S0(2) 0 0] + SM); %-Set SPM colour %----------------------------------------------------------------------- set(findobj(Fmenu,'Tag', 'frame'),'backgroundColor',spm('colour')); try if ismac b = findobj(Fmenu,'Style','pushbutton'); set(b,'backgroundColor',get(b(1),'backgroundColor')+0.002); end end %-Set toolbox %----------------------------------------------------------------------- xTB = spm('tbs'); if ~isempty(xTB) set(findobj(Fmenu,'Tag', 'Toolbox'),'String',{'Toolbox:' xTB.name }); set(findobj(Fmenu,'Tag', 'Toolbox'),'UserData',xTB); else set(findobj(Fmenu,'Tag', 'Toolbox'),'Visible','off') end set(Fmenu,'Visible',Vis); varargout = {Fmenu}; %======================================================================= case 'createintwin' %-Create SPM interactive window %======================================================================= % Finter = spm('CreateIntWin',Vis) %----------------------------------------------------------------------- if nargin<2, Vis='on'; else Vis=varargin{2}; end %-Close any existing 'Interactive' 'Tag'ged windows %----------------------------------------------------------------------- delete(spm_figure('FindWin','Interactive')) Finter = openfig(fullfile(spm('Dir'),'spm_Interactive.fig'),'new','invisible'); set(Finter,'name',spm('Ver')); S0 = spm('WinSize','0',1); SI = spm('WinSize','I'); set(Finter,'Units','pixels', 'Position',[S0(1) S0(2) 0 0] + SI); set(Finter,'Visible',Vis); varargout = {Finter}; %======================================================================= case 'fnuisetup' %-Robust UI setup for main SPM functions %======================================================================= % [Finter,Fgraph,CmdLine] = spm('FnUIsetup',Iname,bGX,CmdLine) %----------------------------------------------------------------------- if nargin<4, CmdLine=spm('CmdLine'); else CmdLine=varargin{4}; end if nargin<3, bGX=1; else bGX=varargin{3}; end if nargin<2, Iname=''; else Iname=varargin{2}; end if CmdLine Finter = spm_figure('FindWin','Interactive'); if ~isempty(Finter), spm_figure('Clear',Finter), end %if ~isempty(Iname), fprintf('%s:\n',Iname), end else Finter = spm_figure('GetWin','Interactive'); spm_figure('Clear',Finter) if ~isempty(Iname) str = sprintf('%s (%s): %s',spm('ver'),spm('GetUser'),Iname); else str = ''; end set(Finter,'Name',str) end if bGX Fgraph = spm_figure('GetWin','Graphics'); spm_figure('Clear',Fgraph) else Fgraph = spm_figure('FindWin','Graphics'); end varargout = {Finter,Fgraph,CmdLine}; %======================================================================= case 'winscale' %-Window scale factors (to fit display) %======================================================================= % WS = spm('WinScale') %----------------------------------------------------------------------- S0 = spm('WinSize','0',1); if all(ismember(S0(:),[0 1])) varargout = {[1 1 1 1]}; return; end tmp = [S0(3)/1152 (S0(4)-50)/900]; varargout = {min(tmp)*[1 1 1 1]}; % Make sure that aspect ratio is about right - for funny shaped screens % varargout = {[S0(3)/1152 (S0(4)-50)/900 S0(3)/1152 (S0(4)-50)/900]}; %======================================================================= case {'fontsize','fontsizes','fontscale'} %-Font scaling %======================================================================= % [FS,sf] = spm('FontSize',FS) % [FS,sf] = spm('FontSizes',FS) % sf = spm('FontScale') %----------------------------------------------------------------------- if nargin<2, FS=1:36; else FS=varargin{2}; end offset = 1; %try, if ismac, offset = 1.4; end; end sf = offset + 0.85*(min(spm('WinScale'))-1); if strcmpi(Action,'fontscale') varargout = {sf}; else varargout = {ceil(FS*sf),sf}; end %======================================================================= case 'winsize' %-Standard SPM window locations and sizes %======================================================================= % Rect = spm('WinSize',Win,raw) %----------------------------------------------------------------------- if nargin<3, raw=0; else raw=1; end if nargin<2, Win=''; else Win=varargin{2}; end Rect = [[108 466 400 445];... [108 045 400 395];... [515 015 600 865];... [326 310 500 280]]; if isempty(Win) %-All windows elseif upper(Win(1))=='M' %-Menu window Rect = Rect(1,:); elseif upper(Win(1))=='I' %-Interactive window Rect = Rect(2,:); elseif upper(Win(1))=='G' %-Graphics window Rect = Rect(3,:); elseif upper(Win(1))=='W' %-Welcome window Rect = Rect(4,:); elseif Win(1)=='0' %-Root workspace Rect = get(0, 'MonitorPosition'); if all(ismember(Rect(:),[0 1])) warning('SPM:noDisplay','Unable to open display.'); end if size(Rect,1) > 1 % Multiple Monitors %-Use Monitor containing the Pointer pl = get(0,'PointerLocation'); Rect(:,[3 4]) = Rect(:,[3 4]) + Rect(:,[1 2]); w = find(pl(1)>=Rect(:,1) & pl(1)<=Rect(:,3) &... pl(2)>=Rect(:,2) & pl(2)<=Rect(:,4)); if numel(w)~=1, w = 1; end Rect = Rect(w,:); %-Make sure that the format is [x y width height] Rect(1,[3 4]) = Rect(1,[3 4]) - Rect(1,[1 2]) + 1; end else error('Unknown Win type'); end if ~raw WS = repmat(spm('WinScale'),size(Rect,1),1); Rect = Rect.*WS; end varargout = {Rect}; %======================================================================= case 'colour' %-SPM interface colour %======================================================================= % spm('Colour') %----------------------------------------------------------------------- %-Pre-developmental livery % varargout = {[1.0,0.2,0.3],'fightening red'}; %-Developmental livery % varargout = {[0.7,1.0,0.7],'flourescent green'}; %-Alpha release livery % varargout = {[0.9,0.9,0.5],'over-ripe banana'}; %-Beta release livery % varargout = {[0.9 0.8 0.9],'blackcurrant purple'}; %-Distribution livery varargout = {[0.8 0.8 1.0],'vile violet'}; try varargout = {spm_get_defaults('ui.colour'),'bluish'}; end %======================================================================= case 'figname' %-Robust SPM figure naming %======================================================================= % F = spm('FigName',Iname,F,CmdLine) %----------------------------------------------------------------------- if nargin<4, CmdLine=spm('CmdLine'); else CmdLine=varargin{4}; end if nargin<3, F='Interactive'; else F=varargin{3}; end if nargin<2, Iname=''; else Iname=varargin{2}; end %if ~isempty(Iname), fprintf('\t%s\n',Iname), end if CmdLine, varargout={[]}; return, end F = spm_figure('FindWin',F); if ~isempty(F) && ~isempty(Iname) set(F,'Name',sprintf('%s (%s): %s',spm('ver'),spm('GetUser'),Iname)) end varargout={F}; %======================================================================= case 'show' %-Bring visible MATLAB windows to the fore %======================================================================= % Fs = spm('Show') %----------------------------------------------------------------------- cF = get(0,'CurrentFigure'); Fs = get(0,'Children'); Fs = findobj(Fs,'flat','Visible','on'); for F=Fs', figure(F), end set(0,'CurrentFigure',cF) spm('FnBanner','GUI show'); varargout={Fs}; %======================================================================= case 'clear' %-Clear SPM GUI %======================================================================= % spm('Clear',Finter, Fgraph) %----------------------------------------------------------------------- if nargin<3, Fgraph='Graphics'; else Fgraph=varargin{3}; end if nargin<2, Finter='Interactive'; else Finter=varargin{2}; end spm_figure('Clear',Fgraph) spm_figure('Clear',Finter) spm('Pointer','Arrow') spm_conman('Initialise','reset'); local_clc; fprintf('\n'); %evalin('base','clear') %======================================================================= case {'fnbanner','sfnbanner','ssfnbanner'} %-Text banners for functions %======================================================================= % SPMid = spm('FnBanner', Fn,FnV) % SPMid = spm('SFnBanner',Fn,FnV) % SPMid = spm('SSFnBanner',Fn,FnV) %----------------------------------------------------------------------- time = spm('time'); str = spm('ver'); if nargin>=2, str = [str,': ',varargin{2}]; end if nargin>=3 v = regexp(varargin{3},'\$Rev: (\d*) \$','tokens','once'); if ~isempty(v) str = [str,' (v',v{1},')']; else str = [str,' (v',varargin{3},')']; end end switch lower(Action) case 'fnbanner' tab = ''; wid = 72; lch = '='; case 'sfnbanner' tab = sprintf('\t'); wid = 72-8; lch = '-'; case 'ssfnbanner' tab = sprintf('\t\t'); wid = 72-2*8; lch = '-'; end fprintf('\n%s%s',tab,str) fprintf('%c',repmat(' ',1,wid-length([str,time]))) fprintf('%s\n%s',time,tab) fprintf('%c',repmat(lch,1,wid)),fprintf('\n') varargout = {str}; %======================================================================= case 'dir' %-Identify specific (SPM) directory %======================================================================= % spm('Dir',Mfile) %----------------------------------------------------------------------- if nargin<2, Mfile='spm'; else Mfile=varargin{2}; end SPMdir = which(Mfile); if isempty(SPMdir) %-Not found or full pathname given if exist(Mfile,'file')==2 %-Full pathname SPMdir = Mfile; else error(['Can''t find ',Mfile,' on MATLABPATH']); end end SPMdir = fileparts(SPMdir); % if isdeployed % ind = findstr(SPMdir,'_mcr')-1; % if ~isempty(ind) % % MATLAB 2008a/2009a doesn't need this % SPMdir = fileparts(SPMdir(1:ind(1))); % end % end varargout = {SPMdir}; %======================================================================= case 'ver' %-SPM version %======================================================================= % [SPMver, SPMrel] = spm('Ver',Mfile,ReDo) %----------------------------------------------------------------------- if nargin > 3, warning('This usage of "spm ver" is now deprecated.'); end if nargin ~= 3, ReDo = false; else ReDo = logical(varargin{3}); end if nargin == 1 || (nargin > 1 && isempty(varargin{2})) Mfile = ''; else Mfile = which(varargin{2}); if isempty(Mfile) error('Can''t find %s on MATLABPATH.',varargin{2}); end end v = spm_version(ReDo); if isempty(Mfile) varargout = {v.Release v.Version}; else unknown = struct('file',Mfile,'id','???','date','','author',''); if ~isdeployed fp = fopen(Mfile,'rt'); if fp == -1, error('Can''t read %s.',Mfile); end str = fread(fp,Inf,'*uchar'); fclose(fp); str = char(str(:)'); r = regexp(str,['\$Id: (?<file>\S+) (?<id>[0-9]+) (?<date>\S+) ' ... '(\S+Z) (?<author>\S+) \$'],'names','once'); if isempty(r), r = unknown; end else r = unknown; end varargout = {r(1).id v.Release}; end %======================================================================= case 'mlver' %-MATLAB major & point version number %======================================================================= % v = spm('MLver') %----------------------------------------------------------------------- v = version; tmp = find(v=='.'); if length(tmp)>1, varargout={v(1:tmp(2)-1)}; end %======================================================================= case 'tbs' %-Identify installed toolboxes %======================================================================= % xTB = spm('TBs') %----------------------------------------------------------------------- % Toolbox directory %----------------------------------------------------------------------- Tdir = fullfile(spm('Dir'),'toolbox'); %-List of potential installed toolboxes directories %----------------------------------------------------------------------- if exist(Tdir,'dir') d = dir(Tdir); d = {d([d.isdir]).name}; d = {d{cellfun('isempty',regexp(d,'^\.'))}}; else d = {}; end %-Look for a "main" M-file in each potential directory %----------------------------------------------------------------------- xTB = []; for i = 1:length(d) tdir = fullfile(Tdir,d{i}); fn = cellstr(spm_select('List',tdir,['^.*' d{i} '\.m$'])); if ~isempty(fn{1}), xTB(end+1).name = strrep(d{i},'_',''); xTB(end).prog = spm_str_manip(fn{1},'r'); xTB(end).dir = tdir; end end varargout{1} = xTB; %======================================================================= case 'tblaunch' %-Launch an SPM toolbox %======================================================================= % xTB = spm('TBlaunch',xTB,i) %----------------------------------------------------------------------- if nargin < 3, i = 1; else i = varargin{3}; end if nargin < 2, xTB = spm('TBs'); else xTB = varargin{2}; end if i > 0 %-Addpath (& report) %------------------------------------------------------------------- if isempty(findstr(xTB(i).dir,path)) if ~isdeployed, addpath(xTB(i).dir,'-begin'); end spm('alert"',{'Toolbox directory prepended to Matlab path:',... xTB(i).dir},... [xTB(i).name,' toolbox'],1); end %-Launch %------------------------------------------------------------------- evalin('base',xTB(i).prog); end %======================================================================= case 'getglobal' %-Get global variable cleanly %======================================================================= % varargout = spm('GetGlobal',varargin) %----------------------------------------------------------------------- wg = who('global'); for i=1:nargin-1 if any(strcmp(wg,varargin{i+1})) eval(['global ',varargin{i+1},', tmp=',varargin{i+1},';']) varargout{i} = tmp; else varargout{i} = []; end end %======================================================================= case {'cmdline'} %-SPM command line mode? %======================================================================= % CmdLine = spm('CmdLine',CmdLine) %----------------------------------------------------------------------- if nargin<2, CmdLine=[]; else CmdLine=varargin{2}; end if isempty(CmdLine) defaults = spm('getglobal','defaults'); if isfield(defaults,'cmdline') CmdLine = defaults.cmdline; else CmdLine = 0; end end varargout = {CmdLine || (get(0,'ScreenDepth')==0)}; %======================================================================= case 'popupcb' %-Callback handling utility for PopUp menus %======================================================================= % spm('PopUpCB',h) %----------------------------------------------------------------------- if nargin<2, h=gcbo; else h=varargin{2}; end v = get(h,'Value'); if v==1, return, end set(h,'Value',1) CBs = get(h,'UserData'); evalin('base',CBs{v-1}) %======================================================================= case 'getuser' %-Get user name %======================================================================= % str = spm('GetUser',fmt) %----------------------------------------------------------------------- str = spm_platform('user'); if ~isempty(str) && nargin>1, str = sprintf(varargin{2},str); end varargout = {str}; %======================================================================= case 'beep' %-Produce beep sound %======================================================================= % spm('Beep') %----------------------------------------------------------------------- beep; %======================================================================= case 'time' %-Return formatted date/time string %======================================================================= % [timestr, date_vec] = spm('Time') %----------------------------------------------------------------------- tmp = clock; varargout = {sprintf('%02d:%02d:%02d - %02d/%02d/%4d',... tmp(4),tmp(5),floor(tmp(6)),tmp(3),tmp(2),tmp(1)), tmp}; %======================================================================= case 'memory' %======================================================================= % m = spm('Memory') %----------------------------------------------------------------------- maxmemdef = 200*1024*1024; m = maxmemdef; varargout = {m}; %======================================================================= case 'pointer' %-Set mouse pointer in all MATLAB windows %======================================================================= % spm('Pointer',Pointer) %----------------------------------------------------------------------- if nargin<2, Pointer='Arrow'; else Pointer=varargin{2}; end set(get(0,'Children'),'Pointer',Pointer) %======================================================================= case {'alert','alert"','alert*','alert!'} %-Alert dialogs %======================================================================= % h = spm('alert',Message,Title,CmdLine,wait) %----------------------------------------------------------------------- %- Globals %----------------------------------------------------------------------- if nargin<5, wait = 0; else wait = varargin{5}; end if nargin<4, CmdLine = []; else CmdLine = varargin{4}; end if nargin<3, Title = ''; else Title = varargin{3}; end if nargin<2, Message = ''; else Message = varargin{2}; end Message = cellstr(Message); if isreal(CmdLine) CmdLine = spm('CmdLine',CmdLine); CmdLine2 = 0; else CmdLine = spm('CmdLine'); CmdLine2 = 1; end timestr = spm('Time'); SPMv = spm('ver'); switch(lower(Action)) case 'alert', icon = 'none'; str = '--- '; case 'alert"', icon = 'help'; str = '~ - '; case 'alert*', icon = 'error'; str = '* - '; case 'alert!', icon = 'warn'; str = '! - '; end if CmdLine || CmdLine2 Message(strcmp(Message,'')) = {' '}; tmp = sprintf('%s: %s',SPMv,Title); fprintf('\n %s%s %s\n\n',str,tmp,repmat('-',1,62-length(tmp))) fprintf(' %s\n',Message{:}) fprintf('\n %s %s\n\n',repmat('-',1,62-length(timestr)),timestr) h = []; end if ~CmdLine tmp = max(size(char(Message),2),42) - length(SPMv) - length(timestr); str = sprintf('%s %s %s',SPMv,repmat(' ',1,tmp-4),timestr); h = msgbox([{''};Message(:);{''};{''};{str}],... sprintf('%s%s: %s',SPMv,spm('GetUser',' (%s)'),Title),... icon,'non-modal'); drawnow set(h,'windowstyle','modal'); end if wait if isempty(h) input(' press ENTER to continue...'); else uiwait(h) h = []; end end if nargout, varargout = {h}; end %======================================================================= case 'gui_filedelete' %-GUI file deletion %======================================================================= % spm('GUI_FileDelete') %----------------------------------------------------------------------- [P, sts] = spm_select(Inf,'.*','Select file(s) to delete'); if ~sts, return; end P = cellstr(P); n = numel(P); if n==0 || (n==1 && isempty(P{1})) spm('alert"','Nothing selected to delete!','file delete',0); return elseif n<4 str=[{' '};P]; elseif n<11 str=[{' '};P;{' ';sprintf('(%d files)',n)}]; else str=[{' '};P(1:min(n,10));{'...';' ';sprintf('(%d files)',n)}]; end if spm_input(str,-1,'bd','delete|cancel',[1,0],[],'confirm file delete') feval(@spm_unlink,P{:}); spm('alert"',P,'file delete',1); end %======================================================================= case 'clean' %-Clean MATLAB workspace %======================================================================= % spm('Clean') %----------------------------------------------------------------------- evalin('base','clear all'); evalc('clear classes'); %======================================================================= case 'help' %-Pass through for spm_help %======================================================================= % spm('Help',varargin) %----------------------------------------------------------------------- if nargin>1, spm_help(varargin{2:end}), else spm_help, end %======================================================================= case 'quit' %-Quit SPM and clean up %======================================================================= % spm('Quit') %----------------------------------------------------------------------- delete(get(0,'Children')); local_clc; fprintf('Bye for now...\n\n'); %======================================================================= otherwise %-Unknown action string %======================================================================= error('Unknown action string'); %======================================================================= end %======================================================================= function local_clc %-Clear command window %======================================================================= if ~isdeployed clc; end %======================================================================= function v = spm_version(ReDo) %-Retrieve SPM version %======================================================================= persistent SPM_VER; v = SPM_VER; if isempty(SPM_VER) || (nargin > 0 && ReDo) v = struct('Name','','Version','','Release','','Date',''); try fid = fopen(fullfile(spm('Dir'),'Contents.m'),'rt'); if fid == -1, error(str); end l1 = fgetl(fid); l2 = fgetl(fid); fclose(fid); l1 = strtrim(l1(2:end)); l2 = strtrim(l2(2:end)); t = textscan(l2,'%s','delimiter',' '); t = t{1}; v.Name = l1; v.Date = t{4}; v.Version = t{2}; v.Release = t{3}(2:end-1); catch if isdeployed % in deployed mode, M-files are encrypted % (but first two lines of Contents.m should be preserved) v.Name = 'Statistical Parametric Mapping'; v.Version = '8'; v.Release = 'SPM8'; v.Date = date; else error('Can''t obtain SPM Revision information.'); end end SPM_VER = v; end
github
lcnbeapp/beapp-master
spm_orthviews.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_orthviews.m
77,288
utf_8
8878b323c3d77a20da9a6c983c6cb96a
function varargout = spm_orthviews(action,varargin) % Display Orthogonal Views of a Normalized Image % FORMAT H = spm_orthviews('Image',filename[,position]) % filename - name of image to display % area - position of image % - area(1) - position x % - area(2) - position y % - area(3) - size x % - area(4) - size y % H - handle for ortho sections % FORMAT spm_orthviews('BB',bb) % bb - bounding box % [loX loY loZ % hiX hiY hiZ] % % FORMAT spm_orthviews('Redraw') % Redraws the images % % FORMAT spm_orthviews('Reposition',centre) % centre - X, Y & Z coordinates of centre voxel % % FORMAT spm_orthviews('Space'[,handle[,M,dim]]) % handle - the view to define the space by, optionally with extra % transformation matrix and dimensions (e.g. one of the blobs % of a view) % with no arguments - puts things into mm space % % FORMAT spm_orthviews('MaxBB') % sets the bounding box big enough display the whole of all images % % FORMAT spm_orthviews('Resolution',res) % res - resolution (mm) % % FORMAT spm_orthviews('Delete', handle) % handle - image number to delete % % FORMAT spm_orthviews('Reset') % clears the orthogonal views % % FORMAT spm_orthviews('Pos') % returns the co-ordinate of the crosshairs in millimetres in the % standard space. % % FORMAT spm_orthviews('Pos', i) % returns the voxel co-ordinate of the crosshairs in the image in the % ith orthogonal section. % % FORMAT spm_orthviews('Xhairs','off') OR spm_orthviews('Xhairs') % disables the cross-hairs on the display. % % FORMAT spm_orthviews('Xhairs','on') % enables the cross-hairs. % % FORMAT spm_orthviews('Interp',hld) % sets the hold value to hld (see spm_slice_vol). % % FORMAT spm_orthviews('AddBlobs',handle,XYZ,Z,mat) % Adds blobs from a pointlist to the image specified by the handle(s). % handle - image number to add blobs to % XYZ - blob voxel locations % Z - blob voxel intensities % mat - matrix from voxels to millimeters of blob. % name - a name for this blob % This method only adds one set of blobs, and displays them using a % split colour table. % % FORMAT spm_orthviews('AddColouredBlobs',handle,XYZ,Z,mat,colour,name) % Adds blobs from a pointlist to the image specified by the handle(s). % handle - image number to add blobs to % XYZ - blob voxel locations % Z - blob voxel intensities % mat - matrix from voxels to millimeters of blob. % colour - the 3 vector containing the colour that the blobs should be % name - a name for this blob % Several sets of blobs can be added in this way, and it uses full colour. % Although it may not be particularly attractive on the screen, the colour % blobs print well. % % FORMAT spm_orthviews('AddColourBar',handle,blobno) % Adds colourbar for a specified blob set % handle - image number % blobno - blob number % % FORMAT spm_orthviews('RemoveBlobs',handle) % Removes all blobs from the image specified by the handle(s). % % FORMAT spm_orthviews('Register',hReg) % hReg - Handle of HandleGraphics object to build registry in. % See spm_XYZreg for more information. % % spm_orthviews('AddContext',handle) % handle - image number to add context menu to % % spm_orthviews('RemoveContext',handle) % handle - image number to remove context menu from % % CONTEXT MENU % spm_orthviews offers many of its features in a context menu, which is % accessible via the right mouse button in each displayed image. % % PLUGINS % The display capabilities of spm_orthviews can be extended with % plugins. These are located in the spm_orthviews subdirectory of the SPM % distribution. Currently there are 3 plugins available: % quiver Add Quiver plots to a displayed image % quiver3d Add 3D Quiver plots to a displayed image % roi ROI creation and modification % The functionality of plugins can be accessed via calls to % spm_orthviews('plugin_name', plugin_arguments). For detailed descriptions % of each plugin see help spm_orthviews/spm_ov_'plugin_name'. % %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner, Matthew Brett, Tom Nichols and Volkmar Glauche % $Id$ % The basic fields of st are: % n - the number of images currently being displayed % vols - a cell array containing the data on each of the % displayed images. % Space - a mapping between the displayed images and the % mm space of each image. % bb - the bounding box of the displayed images. % centre - the current centre of the orthogonal views % callback - a callback to be evaluated on a button-click. % xhairs - crosshairs off/on % hld - the interpolation method % fig - the figure that everything is displayed in % mode - the position/orientation of the sagittal view. % - currently always 1 % % st.registry.hReg \_ See spm_XYZreg for documentation % st.registry.hMe / % % For each of the displayed images, there is a non-empty entry in the % vols cell array. Handles returned by "spm_orthviews('Image',.....)" % indicate the position in the cell array of the newly created ortho-view. % Operations on each ortho-view require the handle to be passed. % % When a new image is displayed, the cell entry contains the information % returned by spm_vol (type help spm_vol for more info). In addition, % there are a few other fields, some of which I will document here: % % premul - a matrix to premultiply the .mat field by. Useful % for re-orienting images. % window - either 'auto' or an intensity range to display the % image with. % mapping- Mapping of image intensities to grey values. Currently % one of 'linear', 'histeq', loghisteq', % 'quadhisteq'. Default is 'linear'. % Histogram equalisation depends on the image toolbox % and is only available if there is a license available % for it. % ax - a cell array containing an element for the three % views. The fields of each element are handles for % the axis, image and crosshairs. % % blobs - optional. Is there for using to superimpose blobs. % vol - 3D array of image data % mat - a mapping from vox-to-mm (see spm_vol, or % help on image formats). % max - maximum intensity for scaling to. If it % does not exist, then images are auto-scaled. % % There are two colouring modes: full colour, and split % colour. When using full colour, there should be a % 'colour' field for each cell element. When using % split colourscale, there is a handle for the colorbar % axis. % % colour - if it exists it contains the % red,green,blue that the blobs should be % displayed in. % cbar - handle for colorbar (for split colourscale). % % PLUGINS % The plugin concept has been developed to extend the display capabilities % of spm_orthviews without the need to rewrite parts of it. Interaction % between spm_orthviews and plugins takes place % a) at startup: The subfunction 'reset_st' looks for folders % 'spm_orthviews' in spm('Dir') and each toolbox % folder. Files with a name spm_ov_PLUGINNAME.m in any of % these folders will be treated as plugins. % For each such file, PLUGINNAME will be added to the list % st.plugins{:}. % The subfunction 'add_context' calls each plugin with % feval(['spm_ov_', st.plugins{k}], ... % 'context_menu', i, parent_menu) % Each plugin may add its own submenu to the context % menu. % b) at redraw: After images and blobs of st.vols{i} are drawn, the % struct st.vols{i} is checked for field names that occur in % the plugin list st.plugins{:}. For each matching entry, the % corresponding plugin is called with the command 'redraw': % feval(['spm_ov_', st.plugins{k}], ... % 'redraw', i, TM0, TD, CM0, CD, SM0, SD); % The values of TM0, TD, CM0, CD, SM0, SD are defined in the % same way as in the redraw subfunction of spm_orthviews. % It is up to the plugin to do all necessary redraw % operations for its display contents. Each displayed item % must have set its property 'HitTest' to 'off' to let events % go through to the underlying axis, which is responsible for % callback handling. The order in which plugins are called is % undefined. global st; if isempty(st), reset_st; end; spm('Pointer','watch'); if nargin == 0, action = ''; end; action = lower(action); switch lower(action), case 'image', H = specify_image(varargin{1}); if ~isempty(H) st.vols{H}.area = [0 0 1 1]; if numel(varargin)>=2, st.vols{H}.area = varargin{2}; end; if isempty(st.bb), st.bb = maxbb; end; bbox; cm_pos; end; varargout{1} = H; st.centre = mean(maxbb); redraw_all case 'bb', if ~isempty(varargin) && all(size(varargin{1})==[2 3]), st.bb = varargin{1}; end; bbox; redraw_all; case 'redraw', redraw_all; eval(st.callback); if isfield(st,'registry'), spm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe); end; case 'reposition', if isempty(varargin), tmp = findcent; else tmp = varargin{1}; end; if numel(tmp) == 3 h = valid_handles(st.snap); if ~isempty(h) tmp = st.vols{h(1)}.mat * ... round(st.vols{h(1)}.mat\[tmp(:); 1]); end st.centre = tmp(1:3); end redraw_all; eval(st.callback); if isfield(st,'registry'), spm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe); end cm_pos; case 'setcoords', st.centre = varargin{1}; st.centre = st.centre(:); redraw_all; eval(st.callback); cm_pos; case 'space', if numel(varargin)<1, st.Space = eye(4); st.bb = maxbb; bbox; redraw_all; else space(varargin{:}); bbox; redraw_all; end; case 'maxbb', st.bb = maxbb; bbox; redraw_all; case 'resolution', resolution(varargin{1}); bbox; redraw_all; case 'window', if numel(varargin)<2, win = 'auto'; elseif numel(varargin{2})==2, win = varargin{2}; end; for i=valid_handles(varargin{1}), st.vols{i}.window = win; end; redraw(varargin{1}); case 'delete', my_delete(varargin{1}); case 'move', move(varargin{1},varargin{2}); % redraw_all; case 'reset', my_reset; case 'pos', if isempty(varargin), H = st.centre(:); else H = pos(varargin{1}); end; varargout{1} = H; case 'interp', st.hld = varargin{1}; redraw_all; case 'xhairs', xhairs(varargin{1}); case 'register', register(varargin{1}); case 'addblobs', addblobs(varargin{:}); % redraw(varargin{1}); case 'addcolouredblobs', addcolouredblobs(varargin{:}); % redraw(varargin{1}); case 'addimage', addimage(varargin{1}, varargin{2}); % redraw(varargin{1}); case 'addcolouredimage', addcolouredimage(varargin{1}, varargin{2},varargin{3}); % redraw(varargin{1}); case 'addtruecolourimage', % spm_orthviews('Addtruecolourimage',handle,filename,colourmap,prop,mx,mn) % Adds blobs from an image in true colour % handle - image number to add blobs to [default 1] % filename of image containing blob data [default - request via GUI] % colourmap - colormap to display blobs in [GUI input] % prop - intensity proportion of activation cf grayscale [0.4] % mx - maximum intensity to scale to [maximum value in activation image] % mn - minimum intensity to scale to [minimum value in activation image] % if nargin < 2 varargin(1) = {1}; end if nargin < 3 varargin(2) = {spm_select(1, 'image', 'Image with activation signal')}; end if nargin < 4 actc = []; while isempty(actc) actc = getcmap(spm_input('Colourmap for activation image', '+1','s')); end varargin(3) = {actc}; end if nargin < 5 varargin(4) = {0.4}; end if nargin < 6 actv = spm_vol(varargin{2}); varargin(5) = {max([eps maxval(actv)])}; end if nargin < 7 varargin(6) = {min([0 minval(actv)])}; end addtruecolourimage(varargin{1}, varargin{2},varargin{3}, varargin{4}, ... varargin{5}, varargin{6}); % redraw(varargin{1}); case 'addcolourbar', addcolourbar(varargin{1}, varargin{2}); case 'rmblobs', rmblobs(varargin{1}); redraw(varargin{1}); case 'addcontext', if nargin == 1, handles = 1:24; else handles = varargin{1}; end; addcontexts(handles); case 'rmcontext', if nargin == 1, handles = 1:24; else handles = varargin{1}; end; rmcontexts(handles); case 'context_menu', c_menu(varargin{:}); case 'valid_handles', if nargin == 1 handles = 1:24; else handles = varargin{1}; end; varargout{1} = valid_handles(handles); otherwise, addonaction = strcmp(st.plugins,action); if any(addonaction) feval(['spm_ov_' st.plugins{addonaction}],varargin{:}); end; end; spm('Pointer'); return; %_______________________________________________________________________ %_______________________________________________________________________ function addblobs(handle, xyz, t, mat, name) global st if nargin < 5 name = ''; end; for i=valid_handles(handle), if ~isempty(xyz), rcp = round(xyz); dim = max(rcp,[],2)'; off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1)); vol = zeros(dim)+NaN; vol(off) = t; vol = reshape(vol,dim); st.vols{i}.blobs=cell(1,1); mx = max([eps max(t)]); mn = min([0 min(t)]); st.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'max',mx, 'min',mn,'name',name); addcolourbar(handle,1); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function addimage(handle, fname) global st for i=valid_handles(handle), if isstruct(fname), vol = fname(1); else vol = spm_vol(fname); end; mat = vol.mat; st.vols{i}.blobs=cell(1,1); mx = max([eps maxval(vol)]); mn = min([0 minval(vol)]); st.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'max',mx,'min',mn); addcolourbar(handle,1); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function addcolouredblobs(handle, xyz, t, mat, colour, name) if nargin < 6 name = ''; end; global st for i=valid_handles(handle), if ~isempty(xyz), rcp = round(xyz); dim = max(rcp,[],2)'; off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1)); vol = zeros(dim)+NaN; vol(off) = t; vol = reshape(vol,dim); if ~isfield(st.vols{i},'blobs'), st.vols{i}.blobs=cell(1,1); bset = 1; else bset = numel(st.vols{i}.blobs)+1; end; mx = max([eps maxval(vol)]); mn = min([0 minval(vol)]); st.vols{i}.blobs{bset} = struct('vol',vol, 'mat',mat, ... 'max',mx, 'min',mn, ... 'colour',colour, 'name',name); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function addcolouredimage(handle, fname,colour) global st for i=valid_handles(handle), if isstruct(fname), vol = fname(1); else vol = spm_vol(fname); end; mat = vol.mat; if ~isfield(st.vols{i},'blobs'), st.vols{i}.blobs=cell(1,1); bset = 1; else bset = numel(st.vols{i}.blobs)+1; end; mx = max([eps maxval(vol)]); mn = min([0 minval(vol)]); st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx,'min',mn,'colour',colour); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function addtruecolourimage(handle,fname,colourmap,prop,mx,mn) % adds true colour image to current displayed image global st for i=valid_handles(handle), if isstruct(fname), vol = fname(1); else vol = spm_vol(fname); end; mat = vol.mat; if ~isfield(st.vols{i},'blobs'), st.vols{i}.blobs=cell(1,1); bset = 1; else bset = numel(st.vols{i}.blobs)+1; end; c = struct('cmap', colourmap,'prop',prop); st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx, ... 'min',mn,'colour',c); addcolourbar(handle,bset); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function addcolourbar(vh,bh) global st if st.mode == 0, axpos = get(st.vols{vh}.ax{2}.ax,'Position'); else axpos = get(st.vols{vh}.ax{1}.ax,'Position'); end; st.vols{vh}.blobs{bh}.cbar = axes('Parent',st.fig,... 'Position',[(axpos(1)+axpos(3)+0.05+(bh-1)*.1) (axpos(2)+0.005) 0.05 (axpos(4)-0.01)],... 'Box','on', 'YDir','normal', 'XTickLabel',[], 'XTick',[]); if isfield(st.vols{vh}.blobs{bh},'name') ylabel(st.vols{vh}.blobs{bh}.name,'parent',st.vols{vh}.blobs{bh}.cbar); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function rmblobs(handle) global st for i=valid_handles(handle), if isfield(st.vols{i},'blobs'), for j=1:numel(st.vols{i}.blobs), if isfield(st.vols{i}.blobs{j},'cbar') && ishandle(st.vols{i}.blobs{j}.cbar), delete(st.vols{i}.blobs{j}.cbar); end; end; st.vols{i} = rmfield(st.vols{i},'blobs'); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function register(hreg) global st tmp = uicontrol('Position',[0 0 1 1],'Visible','off','Parent',st.fig); h = valid_handles(1:24); if ~isempty(h), tmp = st.vols{h(1)}.ax{1}.ax; st.registry = struct('hReg',hreg,'hMe', tmp); spm_XYZreg('Add2Reg',st.registry.hReg,st.registry.hMe, 'spm_orthviews'); else warning('Nothing to register with'); end; st.centre = spm_XYZreg('GetCoords',st.registry.hReg); st.centre = st.centre(:); return; %_______________________________________________________________________ %_______________________________________________________________________ function xhairs(arg1) global st st.xhairs = 0; opt = 'on'; if ~strcmp(arg1,'on'), opt = 'off'; else st.xhairs = 1; end; for i=valid_handles(1:24), for j=1:3, set(st.vols{i}.ax{j}.lx,'Visible',opt); set(st.vols{i}.ax{j}.ly,'Visible',opt); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function H = pos(arg1) global st H = []; for arg1=valid_handles(arg1), is = inv(st.vols{arg1}.premul*st.vols{arg1}.mat); H = is(1:3,1:3)*st.centre(:) + is(1:3,4); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function my_reset global st if ~isempty(st) && isfield(st,'registry') && ishandle(st.registry.hMe), delete(st.registry.hMe); st = rmfield(st,'registry'); end; my_delete(1:24); reset_st; return; %_______________________________________________________________________ %_______________________________________________________________________ function my_delete(arg1) global st % remove blobs (and colourbars, if any) rmblobs(arg1); % remove displayed axes for i=valid_handles(arg1), kids = get(st.fig,'Children'); for j=1:3, if any(kids == st.vols{i}.ax{j}.ax), set(get(st.vols{i}.ax{j}.ax,'Children'),'DeleteFcn',''); delete(st.vols{i}.ax{j}.ax); end; end; st.vols{i} = []; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function resolution(arg1) global st res = arg1/mean(svd(st.Space(1:3,1:3))); Mat = diag([res res res 1]); st.Space = st.Space*Mat; st.bb = st.bb/res; return; %_______________________________________________________________________ %_______________________________________________________________________ function move(handle,pos) global st for handle = valid_handles(handle), st.vols{handle}.area = pos; end; bbox; % redraw(valid_handles(handle)); return; %_______________________________________________________________________ %_______________________________________________________________________ function bb = maxbb global st mn = [Inf Inf Inf]; mx = -mn; for i=valid_handles(1:24), bb = [[1 1 1];st.vols{i}.dim(1:3)]; c = [ bb(1,1) bb(1,2) bb(1,3) 1 bb(1,1) bb(1,2) bb(2,3) 1 bb(1,1) bb(2,2) bb(1,3) 1 bb(1,1) bb(2,2) bb(2,3) 1 bb(2,1) bb(1,2) bb(1,3) 1 bb(2,1) bb(1,2) bb(2,3) 1 bb(2,1) bb(2,2) bb(1,3) 1 bb(2,1) bb(2,2) bb(2,3) 1]'; tc = st.Space\(st.vols{i}.premul*st.vols{i}.mat)*c; tc = tc(1:3,:)'; mx = max([tc ; mx]); mn = min([tc ; mn]); end; bb = [mn ; mx]; return; %_______________________________________________________________________ %_______________________________________________________________________ function space(arg1,M,dim) global st if ~isempty(st.vols{arg1}) num = arg1; if nargin < 2 M = st.vols{num}.mat; dim = st.vols{num}.dim(1:3); end; Mat = st.vols{num}.premul(1:3,1:3)*M(1:3,1:3); vox = sqrt(sum(Mat.^2)); if det(Mat(1:3,1:3))<0, vox(1) = -vox(1); end; Mat = diag([vox 1]); Space = (M)/Mat; bb = [1 1 1; dim]; bb = [bb [1;1]]; bb=bb*Mat'; bb=bb(:,1:3); bb=sort(bb); st.Space = Space; st.bb = bb; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function H = specify_image(arg1) global st H=[]; if isstruct(arg1), V = arg1(1); else try V = spm_vol(arg1); catch fprintf('Can not use image "%s"\n', arg1); return; end; end; ii = 1; while ~isempty(st.vols{ii}), ii = ii + 1; end; DeleteFcn = ['spm_orthviews(''Delete'',' num2str(ii) ');']; V.ax = cell(3,1); for i=1:3, ax = axes('Visible','off','DrawMode','fast','Parent',st.fig,'DeleteFcn',DeleteFcn,... 'YDir','normal','ButtonDownFcn',@repos_start); d = image(0,'Tag','Transverse','Parent',ax,... 'DeleteFcn',DeleteFcn); set(ax,'Ydir','normal','ButtonDownFcn',@repos_start); lx = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn); ly = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn); if ~st.xhairs, set(lx,'Visible','off'); set(ly,'Visible','off'); end; V.ax{i} = struct('ax',ax,'d',d,'lx',lx,'ly',ly); end; V.premul = eye(4); V.window = 'auto'; V.mapping = 'linear'; st.vols{ii} = V; H = ii; return; %_______________________________________________________________________ %_______________________________________________________________________ function repos_start(varargin) % don't use right mouse button to start reposition if ~strcmpi(get(gcbf,'SelectionType'),'alt') set(gcbf,'windowbuttonmotionfcn',@repos_move, 'windowbuttonupfcn',@repos_end); spm_orthviews('reposition'); end %_______________________________________________________________________ %_______________________________________________________________________ function repos_move(varargin) spm_orthviews('reposition'); %_______________________________________________________________________ %_______________________________________________________________________ function repos_end(varargin) set(gcbf,'windowbuttonmotionfcn','', 'windowbuttonupfcn',''); %_______________________________________________________________________ %_______________________________________________________________________ function addcontexts(handles) for ii = valid_handles(handles), addcontext(ii); end; spm_orthviews('reposition',spm_orthviews('pos')); return; %_______________________________________________________________________ %_______________________________________________________________________ function rmcontexts(handles) global st for ii = valid_handles(handles), for i=1:3, set(st.vols{ii}.ax{i}.ax,'UIcontextmenu',[]); st.vols{ii}.ax{i} = rmfield(st.vols{ii}.ax{i},'cm'); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function bbox global st Dims = diff(st.bb)'+1; TD = Dims([1 2])'; CD = Dims([1 3])'; if st.mode == 0, SD = Dims([3 2])'; else SD = Dims([2 3])'; end; un = get(st.fig,'Units');set(st.fig,'Units','Pixels'); sz = get(st.fig,'Position');set(st.fig,'Units',un); sz = sz(3:4); sz(2) = sz(2)-40; for i=valid_handles(1:24), area = st.vols{i}.area(:); area = [area(1)*sz(1) area(2)*sz(2) area(3)*sz(1) area(4)*sz(2)]; if st.mode == 0, sx = area(3)/(Dims(1)+Dims(3))/1.02; else sx = area(3)/(Dims(1)+Dims(2))/1.02; end; sy = area(4)/(Dims(2)+Dims(3))/1.02; s = min([sx sy]); offy = (area(4)-(Dims(2)+Dims(3))*1.02*s)/2 + area(2); sky = s*(Dims(2)+Dims(3))*0.02; if st.mode == 0, offx = (area(3)-(Dims(1)+Dims(3))*1.02*s)/2 + area(1); skx = s*(Dims(1)+Dims(3))*0.02; else offx = (area(3)-(Dims(1)+Dims(2))*1.02*s)/2 + area(1); skx = s*(Dims(1)+Dims(2))*0.02; end; % Transverse set(st.vols{i}.ax{1}.ax,'Units','pixels', ... 'Position',[offx offy s*Dims(1) s*Dims(2)],... 'Units','normalized','Xlim',[0 TD(1)]+0.5,'Ylim',[0 TD(2)]+0.5,... 'Visible','on','XTick',[],'YTick',[]); % Coronal set(st.vols{i}.ax{2}.ax,'Units','Pixels',... 'Position',[offx offy+s*Dims(2)+sky s*Dims(1) s*Dims(3)],... 'Units','normalized','Xlim',[0 CD(1)]+0.5,'Ylim',[0 CD(2)]+0.5,... 'Visible','on','XTick',[],'YTick',[]); % Sagittal if st.mode == 0, set(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',... 'Position',[offx+s*Dims(1)+skx offy s*Dims(3) s*Dims(2)],... 'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,... 'Visible','on','XTick',[],'YTick',[]); else set(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',... 'Position',[offx+s*Dims(1)+skx offy+s*Dims(2)+sky s*Dims(2) s*Dims(3)],... 'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,... 'Visible','on','XTick',[],'YTick',[]); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function redraw_all redraw(1:24); return; %_______________________________________________________________________ function mx = maxval(vol) if isstruct(vol), mx = -Inf; for i=1:vol.dim(3), tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0); imx = max(tmp(isfinite(tmp))); if ~isempty(imx),mx = max(mx,imx);end end; else mx = max(vol(isfinite(vol))); end; %_______________________________________________________________________ function mn = minval(vol) if isstruct(vol), mn = Inf; for i=1:vol.dim(3), tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0); imn = min(tmp(isfinite(tmp))); if ~isempty(imn),mn = min(mn,imn);end end; else mn = min(vol(isfinite(vol))); end; %_______________________________________________________________________ %_______________________________________________________________________ function redraw(arg1) global st bb = st.bb; Dims = round(diff(bb)'+1); is = inv(st.Space); cent = is(1:3,1:3)*st.centre(:) + is(1:3,4); for i = valid_handles(arg1), M = st.vols{i}.premul*st.vols{i}.mat; TM0 = [ 1 0 0 -bb(1,1)+1 0 1 0 -bb(1,2)+1 0 0 1 -cent(3) 0 0 0 1]; TM = inv(TM0*(st.Space\M)); TD = Dims([1 2]); CM0 = [ 1 0 0 -bb(1,1)+1 0 0 1 -bb(1,3)+1 0 1 0 -cent(2) 0 0 0 1]; CM = inv(CM0*(st.Space\M)); CD = Dims([1 3]); if st.mode ==0, SM0 = [ 0 0 1 -bb(1,3)+1 0 1 0 -bb(1,2)+1 1 0 0 -cent(1) 0 0 0 1]; SM = inv(SM0*(st.Space\M)); SD = Dims([3 2]); else SM0 = [ 0 -1 0 +bb(2,2)+1 0 0 1 -bb(1,3)+1 1 0 0 -cent(1) 0 0 0 1]; SM = inv(SM0*(st.Space\M)); SD = Dims([2 3]); end; try imgt = spm_slice_vol(st.vols{i},TM,TD,st.hld)'; imgc = spm_slice_vol(st.vols{i},CM,CD,st.hld)'; imgs = spm_slice_vol(st.vols{i},SM,SD,st.hld)'; ok = true; catch fprintf('Image "%s" can not be resampled\n', st.vols{i}.fname); ok = false; end if ok, % get min/max threshold if strcmp(st.vols{i}.window,'auto') mn = -Inf; mx = Inf; else mn = min(st.vols{i}.window); mx = max(st.vols{i}.window); end; % threshold images imgt = max(imgt,mn); imgt = min(imgt,mx); imgc = max(imgc,mn); imgc = min(imgc,mx); imgs = max(imgs,mn); imgs = min(imgs,mx); % compute intensity mapping, if histeq is available if license('test','image_toolbox') == 0 st.vols{i}.mapping = 'linear'; end; switch st.vols{i}.mapping, case 'linear', case 'histeq', % scale images to a range between 0 and 1 imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps); imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps); imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps); img = histeq([imgt1(:); imgc1(:); imgs1(:)],1024); imgt = reshape(img(1:numel(imgt1)),size(imgt1)); imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1)); imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1)); mn = 0; mx = 1; case 'quadhisteq', % scale images to a range between 0 and 1 imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps); imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps); imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps); img = histeq([imgt1(:).^2; imgc1(:).^2; imgs1(:).^2],1024); imgt = reshape(img(1:numel(imgt1)),size(imgt1)); imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1)); imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1)); mn = 0; mx = 1; case 'loghisteq', sw = warning('off','MATLAB:log:logOfZero'); imgt = log(imgt-min(imgt(:))); imgc = log(imgc-min(imgc(:))); imgs = log(imgs-min(imgs(:))); warning(sw); imgt(~isfinite(imgt)) = 0; imgc(~isfinite(imgc)) = 0; imgs(~isfinite(imgs)) = 0; % scale log images to a range between 0 and 1 imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps); imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps); imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps); img = histeq([imgt1(:); imgc1(:); imgs1(:)],1024); imgt = reshape(img(1:numel(imgt1)),size(imgt1)); imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1)); imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1)); mn = 0; mx = 1; end; % recompute min/max for display if strcmp(st.vols{i}.window,'auto') mx = -inf; mn = inf; end; if ~isempty(imgt), tmp = imgt(isfinite(imgt)); mx = max([mx max(max(tmp))]); mn = min([mn min(min(tmp))]); end; if ~isempty(imgc), tmp = imgc(isfinite(imgc)); mx = max([mx max(max(tmp))]); mn = min([mn min(min(tmp))]); end; if ~isempty(imgs), tmp = imgs(isfinite(imgs)); mx = max([mx max(max(tmp))]); mn = min([mn min(min(tmp))]); end; if mx==mn, mx=mn+eps; end; if isfield(st.vols{i},'blobs'), if ~isfield(st.vols{i}.blobs{1},'colour'), % Add blobs for display using the split colourmap scal = 64/(mx-mn); dcoff = -mn*scal; imgt = imgt*scal+dcoff; imgc = imgc*scal+dcoff; imgs = imgs*scal+dcoff; if isfield(st.vols{i}.blobs{1},'max'), mx = st.vols{i}.blobs{1}.max; else mx = max([eps maxval(st.vols{i}.blobs{1}.vol)]); st.vols{i}.blobs{1}.max = mx; end; if isfield(st.vols{i}.blobs{1},'min'), mn = st.vols{i}.blobs{1}.min; else mn = min([0 minval(st.vols{i}.blobs{1}.vol)]); st.vols{i}.blobs{1}.min = mn; end; vol = st.vols{i}.blobs{1}.vol; M = st.vols{i}.premul*st.vols{i}.blobs{1}.mat; tmpt = spm_slice_vol(vol,inv(TM0*(st.Space\M)),TD,[0 NaN])'; tmpc = spm_slice_vol(vol,inv(CM0*(st.Space\M)),CD,[0 NaN])'; tmps = spm_slice_vol(vol,inv(SM0*(st.Space\M)),SD,[0 NaN])'; %tmpt_z = find(tmpt==0);tmpt(tmpt_z) = NaN; %tmpc_z = find(tmpc==0);tmpc(tmpc_z) = NaN; %tmps_z = find(tmps==0);tmps(tmps_z) = NaN; sc = 64/(mx-mn); off = 65.51-mn*sc; msk = find(isfinite(tmpt)); imgt(msk) = off+tmpt(msk)*sc; msk = find(isfinite(tmpc)); imgc(msk) = off+tmpc(msk)*sc; msk = find(isfinite(tmps)); imgs(msk) = off+tmps(msk)*sc; cmap = get(st.fig,'Colormap'); if size(cmap,1)~=128 figure(st.fig) spm_figure('Colormap','gray-hot') end; redraw_colourbar(i,1,[mn mx],(1:64)'+64); elseif isstruct(st.vols{i}.blobs{1}.colour), % Add blobs for display using a defined % colourmap % colourmaps gryc = (0:63)'*ones(1,3)/63; actc = ... st.vols{1}.blobs{1}.colour.cmap; actp = ... st.vols{1}.blobs{1}.colour.prop; % scale grayscale image, not isfinite -> black imgt = scaletocmap(imgt,mn,mx,gryc,65); imgc = scaletocmap(imgc,mn,mx,gryc,65); imgs = scaletocmap(imgs,mn,mx,gryc,65); gryc = [gryc; 0 0 0]; % get max for blob image if isfield(st.vols{i}.blobs{1},'max'), cmx = st.vols{i}.blobs{1}.max; else cmx = max([eps maxval(st.vols{i}.blobs{1}.vol)]); end; if isfield(st.vols{i}.blobs{1},'min'), cmn = st.vols{i}.blobs{1}.min; else cmn = -cmx; end; % get blob data vol = st.vols{i}.blobs{1}.vol; M = st.vols{i}.premul*st.vols{i}.blobs{1}.mat; tmpt = spm_slice_vol(vol,inv(TM0*(st.Space\M)),TD,[0 NaN])'; tmpc = spm_slice_vol(vol,inv(CM0*(st.Space\M)),CD,[0 NaN])'; tmps = spm_slice_vol(vol,inv(SM0*(st.Space\M)),SD,[0 NaN])'; % actimg scaled round 0, black NaNs topc = size(actc,1)+1; tmpt = scaletocmap(tmpt,cmn,cmx,actc,topc); tmpc = scaletocmap(tmpc,cmn,cmx,actc,topc); tmps = scaletocmap(tmps,cmn,cmx,actc,topc); actc = [actc; 0 0 0]; % combine gray and blob data to % truecolour imgt = reshape(actc(tmpt(:),:)*actp+ ... gryc(imgt(:),:)*(1-actp), ... [size(imgt) 3]); imgc = reshape(actc(tmpc(:),:)*actp+ ... gryc(imgc(:),:)*(1-actp), ... [size(imgc) 3]); imgs = reshape(actc(tmps(:),:)*actp+ ... gryc(imgs(:),:)*(1-actp), ... [size(imgs) 3]); csz = size(st.vols{i}.blobs{1}.colour.cmap); cdata = reshape(st.vols{i}.blobs{1}.colour.cmap, [csz(1) 1 csz(2)]); redraw_colourbar(i,1,[cmn cmx],cdata); else % Add full colour blobs - several sets at once scal = 1/(mx-mn); dcoff = -mn*scal; wt = zeros(size(imgt)); wc = zeros(size(imgc)); ws = zeros(size(imgs)); imgt = repmat(imgt*scal+dcoff,[1,1,3]); imgc = repmat(imgc*scal+dcoff,[1,1,3]); imgs = repmat(imgs*scal+dcoff,[1,1,3]); cimgt = zeros(size(imgt)); cimgc = zeros(size(imgc)); cimgs = zeros(size(imgs)); colour = zeros(numel(st.vols{i}.blobs),3); for j=1:numel(st.vols{i}.blobs) % get colours of all images first if isfield(st.vols{i}.blobs{j},'colour'), colour(j,:) = reshape(st.vols{i}.blobs{j}.colour, [1 3]); else colour(j,:) = [1 0 0]; end; end; %colour = colour/max(sum(colour)); for j=1:numel(st.vols{i}.blobs), if isfield(st.vols{i}.blobs{j},'max'), mx = st.vols{i}.blobs{j}.max; else mx = max([eps max(st.vols{i}.blobs{j}.vol(:))]); st.vols{i}.blobs{j}.max = mx; end; if isfield(st.vols{i}.blobs{j},'min'), mn = st.vols{i}.blobs{j}.min; else mn = min([0 min(st.vols{i}.blobs{j}.vol(:))]); st.vols{i}.blobs{j}.min = mn; end; vol = st.vols{i}.blobs{j}.vol; M = st.Space\st.vols{i}.premul*st.vols{i}.blobs{j}.mat; tmpt = spm_slice_vol(vol,inv(TM0*M),TD,[0 NaN])'; tmpc = spm_slice_vol(vol,inv(CM0*M),CD,[0 NaN])'; tmps = spm_slice_vol(vol,inv(SM0*M),SD,[0 NaN])'; % check min/max of sampled image % against mn/mx as given in st tmpt(tmpt(:)<mn) = mn; tmpc(tmpc(:)<mn) = mn; tmps(tmps(:)<mn) = mn; tmpt(tmpt(:)>mx) = mx; tmpc(tmpc(:)>mx) = mx; tmps(tmps(:)>mx) = mx; tmpt = (tmpt-mn)/(mx-mn); tmpc = (tmpc-mn)/(mx-mn); tmps = (tmps-mn)/(mx-mn); tmpt(~isfinite(tmpt)) = 0; tmpc(~isfinite(tmpc)) = 0; tmps(~isfinite(tmps)) = 0; cimgt = cimgt + cat(3,tmpt*colour(j,1),tmpt*colour(j,2),tmpt*colour(j,3)); cimgc = cimgc + cat(3,tmpc*colour(j,1),tmpc*colour(j,2),tmpc*colour(j,3)); cimgs = cimgs + cat(3,tmps*colour(j,1),tmps*colour(j,2),tmps*colour(j,3)); wt = wt + tmpt; wc = wc + tmpc; ws = ws + tmps; cdata=permute(shiftdim((1/64:1/64:1)'* ... colour(j,:),-1),[2 1 3]); redraw_colourbar(i,j,[mn mx],cdata); end; imgt = repmat(1-wt,[1 1 3]).*imgt+cimgt; imgc = repmat(1-wc,[1 1 3]).*imgc+cimgc; imgs = repmat(1-ws,[1 1 3]).*imgs+cimgs; imgt(imgt<0)=0; imgt(imgt>1)=1; imgc(imgc<0)=0; imgc(imgc>1)=1; imgs(imgs<0)=0; imgs(imgs>1)=1; end; else scal = 64/(mx-mn); dcoff = -mn*scal; imgt = imgt*scal+dcoff; imgc = imgc*scal+dcoff; imgs = imgs*scal+dcoff; end; set(st.vols{i}.ax{1}.d,'HitTest','off', 'Cdata',imgt); set(st.vols{i}.ax{1}.lx,'HitTest','off',... 'Xdata',[0 TD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1)); set(st.vols{i}.ax{1}.ly,'HitTest','off',... 'Ydata',[0 TD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1)); set(st.vols{i}.ax{2}.d,'HitTest','off', 'Cdata',imgc); set(st.vols{i}.ax{2}.lx,'HitTest','off',... 'Xdata',[0 CD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1)); set(st.vols{i}.ax{2}.ly,'HitTest','off',... 'Ydata',[0 CD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1)); set(st.vols{i}.ax{3}.d,'HitTest','off','Cdata',imgs); if st.mode ==0, set(st.vols{i}.ax{3}.lx,'HitTest','off',... 'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1)); set(st.vols{i}.ax{3}.ly,'HitTest','off',... 'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(cent(3)-bb(1,3)+1)); else set(st.vols{i}.ax{3}.lx,'HitTest','off',... 'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1)); set(st.vols{i}.ax{3}.ly,'HitTest','off',... 'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(bb(2,2)+1-cent(2))); end; if ~isempty(st.plugins) % process any addons for k = 1:numel(st.plugins), if isfield(st.vols{i},st.plugins{k}), feval(['spm_ov_', st.plugins{k}], ... 'redraw', i, TM0, TD, CM0, CD, SM0, SD); end; end; end; end; end; drawnow; return; %_______________________________________________________________________ %_______________________________________________________________________ function redraw_colourbar(vh,bh,interval,cdata) global st if isfield(st.vols{vh}.blobs{bh},'cbar') if st.mode == 0, axpos = get(st.vols{vh}.ax{2}.ax,'Position'); else axpos = get(st.vols{vh}.ax{1}.ax,'Position'); end; % only scale cdata if we have out-of-range truecolour values if ndims(cdata)==3 && max(cdata(:))>1 cdata=cdata./max(cdata(:)); end; image([0 1],interval,cdata,'Parent',st.vols{vh}.blobs{bh}.cbar); set(st.vols{vh}.blobs{bh}.cbar, ... 'Position',[(axpos(1)+axpos(3)+0.05+(bh-1)*.1)... (axpos(2)+0.005) 0.05 (axpos(4)-0.01)],... 'YDir','normal','XTickLabel',[],'XTick',[]); if isfield(st.vols{vh}.blobs{bh},'name') ylabel(st.vols{vh}.blobs{bh}.name,'parent',st.vols{vh}.blobs{bh}.cbar); end; end; %_______________________________________________________________________ %_______________________________________________________________________ function centre = findcent global st obj = get(st.fig,'CurrentObject'); centre = []; cent = []; cp = []; for i=valid_handles(1:24), for j=1:3, if ~isempty(obj), if (st.vols{i}.ax{j}.ax == obj), cp = get(obj,'CurrentPoint'); end; end; if ~isempty(cp), cp = cp(1,1:2); is = inv(st.Space); cent = is(1:3,1:3)*st.centre(:) + is(1:3,4); switch j, case 1, cent([1 2])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,2)-1]; case 2, cent([1 3])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,3)-1]; case 3, if st.mode ==0, cent([3 2])=[cp(1)+st.bb(1,3)-1 cp(2)+st.bb(1,2)-1]; else cent([2 3])=[st.bb(2,2)+1-cp(1) cp(2)+st.bb(1,3)-1]; end; end; break; end; end; if ~isempty(cent), break; end; end; if ~isempty(cent), centre = st.Space(1:3,1:3)*cent(:) + st.Space(1:3,4); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function handles = valid_handles(handles) global st; if isempty(st) || ~isfield(st,'vols') handles = []; else handles = handles(:)'; handles = handles(handles<=24 & handles>=1 & ~rem(handles,1)); for h=handles, if isempty(st.vols{h}), handles(handles==h)=[]; end; end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function reset_st global st fig = spm_figure('FindWin','Graphics'); bb = []; %[ [-78 78]' [-112 76]' [-50 85]' ]; st = struct('n', 0, 'vols',[], 'bb',bb,'Space',eye(4),'centre',[0 0 0],'callback',';','xhairs',1,'hld',1,'fig',fig,'mode',1,'plugins',{{}},'snap',[]); st.vols = cell(24,1); xTB = spm('TBs'); if ~isempty(xTB) pluginbase = {spm('Dir') xTB.dir}; else pluginbase = {spm('Dir')}; end for k = 1:numel(pluginbase) pluginpath = fullfile(pluginbase{k},'spm_orthviews'); if isdir(pluginpath) pluginfiles = dir(fullfile(pluginpath,'spm_ov_*.m')); if ~isempty(pluginfiles) if ~isdeployed, addpath(pluginpath); end % fprintf('spm_orthviews: Using Plugins in %s\n', pluginpath); for l = 1:numel(pluginfiles) [p, pluginname, e, v] = spm_fileparts(pluginfiles(l).name); st.plugins{end+1} = strrep(pluginname, 'spm_ov_',''); % fprintf('%s\n',st.plugins{k}); end; end; end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function img = scaletocmap(inpimg,mn,mx,cmap,miscol) if nargin < 5, miscol=1;end cml = size(cmap,1); scf = (cml-1)/(mx-mn); img = round((inpimg-mn)*scf)+1; img(img<1) = 1; img(img>cml) = cml; img(~isfinite(img)) = miscol; return; %_______________________________________________________________________ %_______________________________________________________________________ function cmap = getcmap(acmapname) % get colormap of name acmapname if ~isempty(acmapname), cmap = evalin('base',acmapname,'[]'); if isempty(cmap), % not a matrix, is .mat file? [p, f, e] = fileparts(acmapname); acmat = fullfile(p, [f '.mat']); if exist(acmat, 'file'), s = struct2cell(load(acmat)); cmap = s{1}; end; end; end; if size(cmap, 2)~=3, warning('Colormap was not an N by 3 matrix') cmap = []; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function item_parent = addcontext(volhandle) global st; %create context menu fg = spm_figure('Findwin','Graphics');set(0,'CurrentFigure',fg); %contextmenu item_parent = uicontextmenu; %contextsubmenu 0 item00 = uimenu(item_parent, 'Label','unknown image', 'Separator','on'); spm_orthviews('context_menu','image_info',item00,volhandle); item0a = uimenu(item_parent, 'UserData','pos_mm', 'Callback','spm_orthviews(''context_menu'',''repos_mm'');','Separator','on'); item0b = uimenu(item_parent, 'UserData','pos_vx', 'Callback','spm_orthviews(''context_menu'',''repos_vx'');'); item0c = uimenu(item_parent, 'UserData','v_value'); %contextsubmenu 1 item1 = uimenu(item_parent,'Label','Zoom'); item1_1 = uimenu(item1, 'Label','Full Volume', 'Callback','spm_orthviews(''context_menu'',''zoom'',6);', 'Checked','on'); item1_2 = uimenu(item1, 'Label','160x160x160mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',5);'); item1_3 = uimenu(item1, 'Label','80x80x80mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',4);'); item1_4 = uimenu(item1, 'Label','40x40x40mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',3);'); item1_5 = uimenu(item1, 'Label','20x20x20mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',2);'); item1_6 = uimenu(item1, 'Label','10x10x10mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',1);'); %contextsubmenu 2 checked={'off','off'}; checked{st.xhairs+1} = 'on'; item2 = uimenu(item_parent,'Label','Crosshairs'); item2_1 = uimenu(item2, 'Label','on', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''on'');','Checked',checked{2}); item2_2 = uimenu(item2, 'Label','off', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''off'');','Checked',checked{1}); %contextsubmenu 3 if st.Space == eye(4) checked = {'off', 'on'}; else checked = {'on', 'off'}; end; item3 = uimenu(item_parent,'Label','Orientation'); item3_1 = uimenu(item3, 'Label','World space', 'Callback','spm_orthviews(''context_menu'',''orientation'',3);','Checked',checked{2}); item3_2 = uimenu(item3, 'Label','Voxel space (1st image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',2);','Checked',checked{1}); item3_3 = uimenu(item3, 'Label','Voxel space (this image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',1);','Checked','off'); %contextsubmenu 3 if isempty(st.snap) checked = {'off', 'on'}; else checked = {'on', 'off'}; end; item3 = uimenu(item_parent,'Label','Snap to Grid'); item3_1 = uimenu(item3, 'Label','Don''t snap', 'Callback','spm_orthviews(''context_menu'',''snap'',3);','Checked',checked{2}); item3_2 = uimenu(item3, 'Label','Snap to 1st image', 'Callback','spm_orthviews(''context_menu'',''snap'',2);','Checked',checked{1}); item3_3 = uimenu(item3, 'Label','Snap to this image', 'Callback','spm_orthviews(''context_menu'',''snap'',1);','Checked','off'); %contextsubmenu 4 if st.hld == 0, checked = {'off', 'off', 'on'}; elseif st.hld > 0, checked = {'off', 'on', 'off'}; else checked = {'on', 'off', 'off'}; end; item4 = uimenu(item_parent,'Label','Interpolation'); item4_1 = uimenu(item4, 'Label','NN', 'Callback','spm_orthviews(''context_menu'',''interpolation'',3);', 'Checked',checked{3}); item4_2 = uimenu(item4, 'Label','Bilin', 'Callback','spm_orthviews(''context_menu'',''interpolation'',2);','Checked',checked{2}); item4_3 = uimenu(item4, 'Label','Sinc', 'Callback','spm_orthviews(''context_menu'',''interpolation'',1);','Checked',checked{1}); %contextsubmenu 5 % item5 = uimenu(item_parent,'Label','Position', 'Callback','spm_orthviews(''context_menu'',''position'');'); %contextsubmenu 6 item6 = uimenu(item_parent,'Label','Image','Separator','on'); item6_1 = uimenu(item6, 'Label','Window'); item6_1_1 = uimenu(item6_1, 'Label','local'); item6_1_1_1 = uimenu(item6_1_1, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window'',2);'); item6_1_1_2 = uimenu(item6_1_1, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window'',1);'); item6_1_2 = uimenu(item6_1, 'Label','global'); item6_1_2_1 = uimenu(item6_1_2, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window_gl'',2);'); item6_1_2_2 = uimenu(item6_1_2, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window_gl'',1);'); if license('test','image_toolbox') == 1 offon = {'off', 'on'}; checked = offon(strcmp(st.vols{volhandle}.mapping, ... {'linear', 'histeq', 'loghisteq', 'quadhisteq'})+1); item6_2 = uimenu(item6, 'Label','Intensity mapping'); item6_2_1 = uimenu(item6_2, 'Label','local'); item6_2_1_1 = uimenu(item6_2_1, 'Label','Linear', 'Checked',checked{1}, ... 'Callback','spm_orthviews(''context_menu'',''mapping'',''linear'');'); item6_2_1_2 = uimenu(item6_2_1, 'Label','Equalised histogram', 'Checked',checked{2}, ... 'Callback','spm_orthviews(''context_menu'',''mapping'',''histeq'');'); item6_2_1_3 = uimenu(item6_2_1, 'Label','Equalised log-histogram', 'Checked',checked{3}, ... 'Callback','spm_orthviews(''context_menu'',''mapping'',''loghisteq'');'); item6_2_1_4 = uimenu(item6_2_1, 'Label','Equalised squared-histogram', 'Checked',checked{4}, ... 'Callback','spm_orthviews(''context_menu'',''mapping'',''quadhisteq'');'); item6_2_2 = uimenu(item6_2, 'Label','global'); item6_2_2_1 = uimenu(item6_2_2, 'Label','Linear', 'Checked',checked{1}, ... 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''linear'');'); item6_2_2_2 = uimenu(item6_2_2, 'Label','Equalised histogram', 'Checked',checked{2}, ... 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''histeq'');'); item6_2_2_3 = uimenu(item6_2_2, 'Label','Equalised log-histogram', 'Checked',checked{3}, ... 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''loghisteq'');'); item6_2_2_4 = uimenu(item6_2_2, 'Label','Equalised squared-histogram', 'Checked',checked{4}, ... 'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''quadhisteq'');'); end; %contextsubmenu 7 item7 = uimenu(item_parent,'Label','Blobs'); item7_1 = uimenu(item7, 'Label','Add blobs'); item7_1_1 = uimenu(item7_1, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',2);'); item7_1_2 = uimenu(item7_1, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',1);'); item7_2 = uimenu(item7, 'Label','Add image'); item7_2_1 = uimenu(item7_2, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_image'',2);'); item7_2_2 = uimenu(item7_2, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_image'',1);'); item7_3 = uimenu(item7, 'Label','Add colored blobs','Separator','on'); item7_3_1 = uimenu(item7_3, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',2);'); item7_3_2 = uimenu(item7_3, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',1);'); item7_4 = uimenu(item7, 'Label','Add colored image'); item7_4_1 = uimenu(item7_4, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',2);'); item7_4_2 = uimenu(item7_4, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',1);'); item7_5 = uimenu(item7, 'Label','Remove blobs', 'Visible','off','Separator','on'); item7_6 = uimenu(item7, 'Label','Remove colored blobs','Visible','off'); item7_6_1 = uimenu(item7_6, 'Label','local', 'Visible','on'); item7_6_2 = uimenu(item7_6, 'Label','global','Visible','on'); for i=1:3, set(st.vols{volhandle}.ax{i}.ax,'UIcontextmenu',item_parent); st.vols{volhandle}.ax{i}.cm = item_parent; end; if ~isempty(st.plugins) % process any plugins for k = 1:numel(st.plugins), feval(['spm_ov_', st.plugins{k}], ... 'context_menu', volhandle, item_parent); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function c_menu(varargin) global st switch lower(varargin{1}), case 'image_info', if nargin <3, current_handle = get_current_handle; else current_handle = varargin{3}; end; if isfield(st.vols{current_handle},'fname'), [p,n,e,v] = spm_fileparts(st.vols{current_handle}.fname); if isfield(st.vols{current_handle},'n') v = sprintf(',%d',st.vols{current_handle}.n); end; set(varargin{2}, 'Label',[n e v]); end; delete(get(varargin{2},'children')); if exist('p','var') item1 = uimenu(varargin{2}, 'Label', p); end; if isfield(st.vols{current_handle},'descrip'), item2 = uimenu(varargin{2}, 'Label',... st.vols{current_handle}.descrip); end; dt = st.vols{current_handle}.dt(1); item3 = uimenu(varargin{2}, 'Label', sprintf('Data type: %s', spm_type(dt))); str = 'Intensity: varied'; if size(st.vols{current_handle}.pinfo,2) == 1, if st.vols{current_handle}.pinfo(2), str = sprintf('Intensity: Y = %g X + %g',... st.vols{current_handle}.pinfo(1:2)'); else str = sprintf('Intensity: Y = %g X', st.vols{current_handle}.pinfo(1)'); end; end; item4 = uimenu(varargin{2}, 'Label',str); item5 = uimenu(varargin{2}, 'Label', 'Image dims', 'Separator','on'); item51 = uimenu(varargin{2}, 'Label',... sprintf('%dx%dx%d', st.vols{current_handle}.dim(1:3))); prms = spm_imatrix(st.vols{current_handle}.mat); item6 = uimenu(varargin{2}, 'Label','Voxel size', 'Separator','on'); item61 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', prms(7:9))); item7 = uimenu(varargin{2}, 'Label','Origin', 'Separator','on'); item71 = uimenu(varargin{2}, 'Label',... sprintf('%.2f %.2f %.2f', prms(1:3))); R = spm_matrix([0 0 0 prms(4:6)]); item8 = uimenu(varargin{2}, 'Label','Rotations', 'Separator','on'); item81 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(1,1:3))); item82 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(2,1:3))); item83 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(3,1:3))); item9 = uimenu(varargin{2},... 'Label','Specify other image...',... 'Callback','spm_orthviews(''context_menu'',''swap_img'');',... 'Separator','on'); case 'repos_mm', oldpos_mm = spm_orthviews('pos'); newpos_mm = spm_input('New Position (mm)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_mm),3); spm_orthviews('reposition',newpos_mm); case 'repos_vx' current_handle = get_current_handle; oldpos_vx = spm_orthviews('pos', current_handle); newpos_vx = spm_input('New Position (voxels)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_vx),3); newpos_mm = st.vols{current_handle}.mat*[newpos_vx;1]; spm_orthviews('reposition',newpos_mm(1:3)); case 'zoom' zoom_all(varargin{2}); bbox; redraw_all; case 'xhair', spm_orthviews('Xhairs',varargin{2}); cm_handles = get_cm_handles; for i = 1:numel(cm_handles), z_handle = get(findobj(cm_handles(i),'label','Crosshairs'),'Children'); set(z_handle,'Checked','off'); %reset check if strcmp(varargin{2},'off'), op = 1; else op = 2; end set(z_handle(op),'Checked','on'); end; case 'orientation', cm_handles = get_cm_handles; for i = 1:numel(cm_handles), z_handle = get(findobj(cm_handles(i),'label','Orientation'),'Children'); set(z_handle,'Checked','off'); end; if varargin{2} == 3, spm_orthviews('Space'); for i = 1:numel(cm_handles), z_handle = findobj(cm_handles(i),'label','World space'); set(z_handle,'Checked','on'); end; elseif varargin{2} == 2, spm_orthviews('Space',1); for i = 1:numel(cm_handles), z_handle = findobj(cm_handles(i),'label',... 'Voxel space (1st image)'); set(z_handle,'Checked','on'); end; else spm_orthviews('Space',get_current_handle); z_handle = findobj(st.vols{get_current_handle}.ax{1}.cm, ... 'label','Voxel space (this image)'); set(z_handle,'Checked','on'); return; end; case 'snap', cm_handles = get_cm_handles; for i = 1:numel(cm_handles), z_handle = get(findobj(cm_handles(i),'label','Snap to Grid'),'Children'); set(z_handle,'Checked','off'); end; if varargin{2} == 3, st.snap = []; elseif varargin{2} == 2, st.snap = 1; else st.snap = get_current_handle; z_handle = get(findobj(st.vols{get_current_handle}.ax{1}.cm,'label','Snap to Grid'),'Children'); set(z_handle(1),'Checked','on'); return; end; for i = 1:numel(cm_handles), z_handle = get(findobj(cm_handles(i),'label','Snap to Grid'),'Children'); set(z_handle(varargin{2}),'Checked','on'); end; case 'interpolation', tmp = [-4 1 0]; st.hld = tmp(varargin{2}); cm_handles = get_cm_handles; for i = 1:numel(cm_handles), z_handle = get(findobj(cm_handles(i),'label','Interpolation'),'Children'); set(z_handle,'Checked','off'); set(z_handle(varargin{2}),'Checked','on'); end; redraw_all; case 'window', current_handle = get_current_handle; if varargin{2} == 2, spm_orthviews('window',current_handle); else if isnumeric(st.vols{current_handle}.window) defstr = sprintf('%.2f %.2f', st.vols{current_handle}.window); else defstr = ''; end; [w yp] = spm_input('Range','+1','e',defstr,[1 inf]); while numel(w) < 1 || numel(w) > 2 uiwait(warndlg('Window must be one or two numbers','Wrong input size','modal')); [w yp] = spm_input('Range',yp,'e',defstr,[1 inf]); end if numel(w) == 1 w(2) = w(1)+eps; end spm_orthviews('window',current_handle,w); end; case 'window_gl', if varargin{2} == 2, for i = 1:numel(get_cm_handles), st.vols{i}.window = 'auto'; end; else current_handle = get_current_handle; if isnumeric(st.vols{current_handle}.window) defstr = sprintf('%d %d', st.vols{current_handle}.window); else defstr = ''; end; [w yp] = spm_input('Range','+1','e',defstr,[1 inf]); while numel(w) < 1 || numel(w) > 2 uiwait(warndlg('Window must be one or two numbers','Wrong input size','modal')); [w yp] = spm_input('Range',yp,'e',defstr,[1 inf]); end if numel(w) == 1 w(2) = w(1)+eps; end for i = 1:numel(get_cm_handles), st.vols{i}.window = w; end; end; redraw_all; case 'mapping', checked = strcmp(varargin{2}, ... {'linear', 'histeq', 'loghisteq', ... 'quadhisteq'}); checked = checked(end:-1:1); % Handles are stored in inverse order current_handle = get_current_handle; cm_handles = get_cm_handles; st.vols{current_handle}.mapping = varargin{2}; z_handle = get(findobj(cm_handles(current_handle), ... 'label','Intensity mapping'),'Children'); for k = 1:numel(z_handle) c_handle = get(z_handle(k), 'Children'); set(c_handle, 'checked', 'off'); set(c_handle(checked), 'checked', 'on'); end; redraw_all; case 'mapping_gl', checked = strcmp(varargin{2}, ... {'linear', 'histeq', 'loghisteq', 'quadhisteq'}); checked = checked(end:-1:1); % Handles are stored in inverse order cm_handles = get_cm_handles; for k = valid_handles(1:24), st.vols{k}.mapping = varargin{2}; z_handle = get(findobj(cm_handles(k), ... 'label','Intensity mapping'),'Children'); for l = 1:numel(z_handle) c_handle = get(z_handle(l), 'Children'); set(c_handle, 'checked', 'off'); set(c_handle(checked), 'checked', 'on'); end; end; redraw_all; case 'swap_img', current_handle = get_current_handle; newimg = spm_select(1,'image','select new image'); if ~isempty(newimg) new_info = spm_vol(newimg); fn = fieldnames(new_info); for k=1:numel(fn) st.vols{current_handle}.(fn{k}) = new_info.(fn{k}); end; spm_orthviews('context_menu','image_info',get(gcbo, 'parent')); redraw_all; end case 'add_blobs', % Add blobs to the image - in split colortable cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle; end; spm_figure('Clear','Interactive'); [SPM,VOL] = spm_getSPM; if ~isempty(SPM) for i = 1:numel(cm_handles), addblobs(cm_handles(i),VOL.XYZ,VOL.Z,VOL.M); c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs'); set(c_handle,'Visible','on'); delete(get(c_handle,'Children')); item7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);'); if varargin{2} == 1, item7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);'); end; end; redraw_all; end case 'remove_blobs', cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle; end; for i = 1:numel(cm_handles), rmblobs(cm_handles(i)); c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs'); delete(get(c_handle,'Children')); set(c_handle,'Visible','off'); end; redraw_all; case 'add_image', % Add blobs to the image - in split colortable cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle; end; spm_figure('Clear','Interactive'); fname = spm_select(1,'image','select image'); if ~isempty(fname) for i = 1:numel(cm_handles), addimage(cm_handles(i),fname); c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs'); set(c_handle,'Visible','on'); delete(get(c_handle,'Children')); item7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);'); if varargin{2} == 1, item7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);'); end; end; redraw_all; end case 'add_c_blobs', % Add blobs to the image - in full colour cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle; end; spm_figure('Clear','Interactive'); [SPM,VOL] = spm_getSPM; if ~isempty(SPM) c = spm_input('Colour','+1','m',... 'Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1); colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1]; c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'}; hlabel = sprintf('%s (%s)',VOL.title,c_names{c}); for i = 1:numel(cm_handles), addcolouredblobs(cm_handles(i),VOL.XYZ,VOL.Z,VOL.M,colours(c,:),VOL.title); addcolourbar(cm_handles(i),numel(st.vols{cm_handles(i)}.blobs)); c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs'); ch_c_handle = get(c_handle,'Children'); set(c_handle,'Visible','on'); %set(ch_c_handle,'Visible',on'); item7_4_1 = uimenu(ch_c_handle(2),'Label',hlabel,'ForegroundColor',colours(c,:),... 'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);',... 'UserData',c); if varargin{2} == 1, item7_4_2 = uimenu(ch_c_handle(1),'Label',hlabel,'ForegroundColor',colours(c,:),... 'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',... 'UserData',c); end; end; redraw_all; end case 'remove_c_blobs', cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle; end; colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1]; for i = 1:numel(cm_handles), if isfield(st.vols{cm_handles(i)},'blobs'), for j = 1:numel(st.vols{cm_handles(i)}.blobs), if all(st.vols{cm_handles(i)}.blobs{j}.colour == colours(varargin{3},:)); if isfield(st.vols{cm_handles(i)}.blobs{j},'cbar') delete(st.vols{cm_handles(i)}.blobs{j}.cbar); end st.vols{cm_handles(i)}.blobs(j) = []; break; end; end; rm_c_menu = findobj(st.vols{cm_handles(i)}.ax{1}.cm,'Label','Remove colored blobs'); delete(gcbo); if isempty(st.vols{cm_handles(i)}.blobs), st.vols{cm_handles(i)} = rmfield(st.vols{cm_handles(i)},'blobs'); set(rm_c_menu, 'Visible', 'off'); end; end; end; redraw_all; case 'add_c_image', % Add truecolored image cm_handles = valid_handles(1:24); if varargin{2} == 2, cm_handles = get_current_handle;end; spm_figure('Clear','Interactive'); fname = spm_select(1,'image','select image'); if ~isempty(fname) c = spm_input('Colour','+1','m','Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1); colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1]; c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'}; hlabel = sprintf('%s (%s)',fname,c_names{c}); for i = 1:numel(cm_handles), addcolouredimage(cm_handles(i),fname,colours(c,:)); addcolourbar(cm_handles(i),numel(st.vols{cm_handles(i)}.blobs)); c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs'); ch_c_handle = get(c_handle,'Children'); set(c_handle,'Visible','on'); %set(ch_c_handle,'Visible',on'); item7_4_1 = uimenu(ch_c_handle(2),'Label',hlabel,'ForegroundColor',colours(c,:),... 'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);','UserData',c); if varargin{2} == 1 item7_4_2 = uimenu(ch_c_handle(1),'Label',hlabel,'ForegroundColor',colours(c,:),... 'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',... 'UserData',c); end end redraw_all; end end; %_______________________________________________________________________ %_______________________________________________________________________ function current_handle = get_current_handle cm_handle = get(gca,'UIContextMenu'); cm_handles = get_cm_handles; current_handle = find(cm_handles==cm_handle); return; %_______________________________________________________________________ %_______________________________________________________________________ function cm_pos global st for i = 1:numel(valid_handles(1:24)), if isfield(st.vols{i}.ax{1},'cm') set(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_mm'),... 'Label',sprintf('mm: %.1f %.1f %.1f',spm_orthviews('pos'))); pos = spm_orthviews('pos',i); set(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_vx'),... 'Label',sprintf('vx: %.1f %.1f %.1f',pos)); set(findobj(st.vols{i}.ax{1}.cm,'UserData','v_value'),... 'Label',sprintf('Y = %g',spm_sample_vol(st.vols{i},pos(1),pos(2),pos(3),st.hld))); end end; return; %_______________________________________________________________________ %_______________________________________________________________________ function cm_handles = get_cm_handles global st cm_handles = []; for i=valid_handles(1:24), cm_handles = [cm_handles st.vols{i}.ax{1}.cm]; end return; %_______________________________________________________________________ %_______________________________________________________________________ function zoom_all(op) global st cm_handles = get_cm_handles; res = [.125 .125 .25 .5 1 1]; if op==6, st.bb = maxbb; else vx = sqrt(sum(st.Space(1:3,1:3).^2)); vx = vx.^(-1); pos = spm_orthviews('pos'); pos = st.Space\[pos ; 1]; pos = pos(1:3)'; if op == 5, st.bb = [pos-80*vx ; pos+80*vx] ; elseif op == 4, st.bb = [pos-40*vx ; pos+40*vx] ; elseif op == 3, st.bb = [pos-20*vx ; pos+20*vx] ; elseif op == 2, st.bb = [pos-10*vx ; pos+10*vx] ; elseif op == 1; st.bb = [pos- 5*vx ; pos+ 5*vx] ; else disp('no Zoom possible'); end; end resolution(res(op)); redraw_all; for i = 1:numel(cm_handles) z_handle = get(findobj(cm_handles(i),'label','Zoom'),'Children'); set(z_handle,'Checked','off'); set(z_handle(op),'Checked','on'); end if isfield(st.vols{1},'sdip') spm_eeg_inv_vbecd_disp('RedrawDip'); end return;
github
lcnbeapp/beapp-master
spm_maff.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_maff.m
11,287
utf_8
67d7a7a2de40e5f6a1c0c0e5e9f630f3
function [M,h] = spm_maff(varargin) % Affine registration to MNI space using mutual information % FORMAT M = spm_maff(P,samp,x,b0,MF,M,regtyp,ff) % P - filename or structure handle of image % x - cell array of {x1,x2,x3}, where x1 and x2 are % co-ordinates (from ndgrid), and x3 is a list of % slice numbers to use % b0 - a cell array of belonging probability images % (see spm_load_priors.m). % MF - voxel-to-world transform of belonging probability % images % M - starting estimates % regtype - regularisation type % 'mni' - registration of European brains with MNI space % 'eastern' - registration of East Asian brains with MNI space % 'rigid' - rigid(ish)-body registration % 'subj' - inter-subject registration % 'none' - no regularisation % ff - a fudge factor (derived from the one above) %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ [buf,MG] = loadbuf(varargin{1:2}); M = affreg(buf, MG, varargin{2:end}); return; %_______________________________________________________________________ %_______________________________________________________________________ function [buf,MG] = loadbuf(V,x) if ischar(V), V = spm_vol(V); end; x1 = x{1}; x2 = x{2}; x3 = x{3}; % Load the image V = spm_vol(V); d = V(1).dim(1:3); o = ones(size(x1)); d = [size(x1) length(x3)]; g = zeros(d); spm_progress_bar('Init',V.dim(3),'Loading volume','Planes loaded'); for i=1:d(3) g(:,:,i) = spm_sample_vol(V,x1,x2,o*x3(i),0); spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); % Convert the image to unsigned bytes [mn,mx] = spm_minmax(g); sw = warning('off','all'); for z=1:length(x3), gz = g(:,:,z); buf(z).msk = gz>mn & isfinite(gz); buf(z).nm = sum(buf(z).msk(:)); gz = double(gz(buf(z).msk)); buf(z).g = uint8(round(gz*(255/mx))); end; warning(sw); MG = V.mat; return; %_______________________________________________________________________ %_______________________________________________________________________ function [M,h0] = affreg(buf,MG,x,b0,MF,M,regtyp,ff) % Do the work x1 = x{1}; x2 = x{2}; x3 = x{3}; [mu,isig] = priors(regtyp); isig = isig*ff; Alpha0 = isig; Beta0 = -isig*mu; sol = M2P(M); sol1 = sol; ll = -Inf; nsmp = sum(cat(1,buf.nm)); pr = struct('b',[],'db1',[],'db2',[],'db3',[]); spm_chi2_plot('Init','Registering','Log-likelihood','Iteration'); for iter=1:200 penalty = (sol1-mu)'*isig*(sol1-mu); T = MF\P2M(sol1)*MG; R = derivs(MF,sol1,MG); y1a = T(1,1)*x1 + T(1,2)*x2 + T(1,4); y2a = T(2,1)*x1 + T(2,2)*x2 + T(2,4); y3a = T(3,1)*x1 + T(3,2)*x2 + T(3,4); h0 = zeros(256,length(b0)-1)+eps; for i=1:length(x3), if ~buf(i).nm, continue; end; y1 = y1a(buf(i).msk) + T(1,3)*x3(i); y2 = y2a(buf(i).msk) + T(2,3)*x3(i); y3 = y3a(buf(i).msk) + T(3,3)*x3(i); for k=1:size(h0,2), pr(k).b = spm_sample_priors(b0{k},y1,y2,y3,k==length(b0)); h0(:,k) = h0(:,k) + spm_hist(buf(i).g,pr(k).b); end; end; h1 = (h0+eps); ssh = sum(h1(:)); krn = spm_smoothkern(2,(-256:256)',0); h1 = conv2(h1,krn,'same'); h1 = h1/ssh; h2 = log2(h1./(sum(h1,2)*sum(h1,1))); ll1 = sum(sum(h0.*h2))/ssh - penalty/ssh; spm_chi2_plot('Set',ll1); if ll1-ll<1e-5, break; end; ll = ll1; sol = sol1; Alpha = zeros(12); Beta = zeros(12,1); for i=1:length(x3), nz = buf(i).nm; if ~nz, continue; end; msk = buf(i).msk; gi = double(buf(i).g)+1; y1 = y1a(msk) + T(1,3)*x3(i); y2 = y2a(msk) + T(2,3)*x3(i); y3 = y3a(msk) + T(3,3)*x3(i); dmi1 = zeros(nz,1); dmi2 = zeros(nz,1); dmi3 = zeros(nz,1); for k=1:size(h0,2), [pr(k).b, pr(k).db1, pr(k).db2, pr(k).db3] = spm_sample_priors(b0{k},y1,y2,y3,k==length(b0)); tmp = -h2(gi,k); dmi1 = dmi1 + tmp.*pr(k).db1; dmi2 = dmi2 + tmp.*pr(k).db2; dmi3 = dmi3 + tmp.*pr(k).db3; end; x1m = x1(msk); x2m = x2(msk); x3m = x3(i); A = [dmi1.*x1m dmi2.*x1m dmi3.*x1m... dmi1.*x2m dmi2.*x2m dmi3.*x2m... dmi1 *x3m dmi2 *x3m dmi3 *x3m... dmi1 dmi2 dmi3]; Alpha = Alpha + A'*A; Beta = Beta + sum(A,1)'; end; drawnow; Alpha = R'*Alpha*R; Beta = R'*Beta; % Gauss-Newton update sol1 = (Alpha+Alpha0)\(Alpha*sol - Beta - Beta0); end; spm_chi2_plot('Clear'); M = P2M(sol); return; %_______________________________________________________________________ %_______________________________________________________________________ function P = M2P(M) % Polar decomposition parameterisation of affine transform, % based on matrix logs J = M(1:3,1:3); V = sqrtm(J*J'); R = V\J; lV = logm(V); lR = -logm(R); if sum(sum(imag(lR).^2))>1e-6, error('Rotations by pi are still a problem.'); end; P = zeros(12,1); P(1:3) = M(1:3,4); P(4:6) = lR([2 3 6]); P(7:12) = lV([1 2 3 5 6 9]); return; %_______________________________________________________________________ %_______________________________________________________________________ function M = P2M(P) % Polar decomposition parameterisation of affine transform, % based on matrix logs % Translations D = P(1:3); D = D(:); % Rotation part ind = [2 3 6]; T = zeros(3); T(ind) = -P(4:6); R = expm(T-T'); % Symmetric part (zooms and shears) ind = [1 2 3 5 6 9]; T = zeros(3); T(ind) = P(7:12); V = expm(T+T'-diag(diag(T))); M = [V*R D ; 0 0 0 1]; return; %_______________________________________________________________________ %_______________________________________________________________________ function R = derivs(MF,P,MG) % Numerically compute derivatives of Affine transformation matrix w.r.t. % changes in the parameters. R = zeros(12,12); M0 = MF\P2M(P)*MG; M0 = M0(1:3,:); for i=1:12 dp = 0.000000001; P1 = P; P1(i) = P1(i) + dp; M1 = MF\P2M(P1)*MG; M1 = M1(1:3,:); R(:,i) = (M1(:)-M0(:))/dp; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [mu,isig] = priors(typ) % The parameters for this distribution were derived empirically from 227 % scans, that were matched to the ICBM space. %% Values can be derived by... %sn = spm_select(Inf,'.*seg_inv_sn.mat$'); %X = zeros(size(sn,1),12); %for i=1:size(sn,1), % p = load(deblank(sn(i,:))); % M = p.VF(1).mat*p.Affine/p.VG(1).mat; % J = M(1:3,1:3); % V = sqrtm(J*J'); % R = V\J; % lV = logm(V); % lR = -logm(R); % P = zeros(12,1); % P(1:3) = M(1:3,4); % P(4:6) = lR([2 3 6]); % P(7:12) = lV([1 2 3 5 6 9]); % X(i,:) = P'; %end; %mu = mean(X(:,7:12)); %XR = X(:,7:12) - repmat(mu,[size(X,1),1]); %isig = inv(XR'*XR/(size(X,1)-1)) mu = zeros(6,1); isig = zeros(6); switch deblank(lower(typ)) case 'mni', % For registering with MNI templates... mu = [0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]'; isig = 1e4 * [ 0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163 -0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116 -0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060 -0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440 -0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062 -0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144]; case 'imni', % For registering with MNI templates... mu = -[0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]'; isig = 1e4 * [ 0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163 -0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116 -0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060 -0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440 -0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062 -0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144]; case 'rigid', % Constrained to be almost rigid... mu = zeros(6,1); isig = eye(6)*1e8; case 'subj', % For inter-subject registration... mu = zeros(6,1); isig = 1e3 * [ 0.8876 0.0784 0.0784 -0.1749 0.0784 -0.1749 0.0784 5.3894 0.2655 0.0784 0.2655 0.0784 0.0784 0.2655 5.3894 0.0784 0.2655 0.0784 -0.1749 0.0784 0.0784 0.8876 0.0784 -0.1749 0.0784 0.2655 0.2655 0.0784 5.3894 0.0784 -0.1749 0.0784 0.0784 -0.1749 0.0784 0.8876]; case 'eastern', % For East Asian brains to MNI... mu = [0.0719 -0.0040 -0.0032 0.1416 0.0601 0.2578]'; isig = 1e4 * [ 0.0757 0.0220 -0.0224 -0.0049 0.0304 -0.0327 0.0220 0.3125 -0.1555 0.0280 -0.0012 -0.0284 -0.0224 -0.1555 1.9727 0.0196 -0.0019 0.0122 -0.0049 0.0280 0.0196 0.0576 -0.0282 -0.0200 0.0304 -0.0012 -0.0019 -0.0282 0.2128 -0.0275 -0.0327 -0.0284 0.0122 -0.0200 -0.0275 0.0511]; case 'none', % No regularisation... mu = zeros(6,1); isig = zeros(6); otherwise error(['"' typ '" not recognised as type of regularisation.']); end; mu = [zeros(6,1) ; mu]; isig = [zeros(6,12) ; zeros(6,6) isig]; return; %_______________________________________________________________________ %_______________________________________________________________________ function [h0,d1] = reg_unused(M) % Try to analytically compute the first and second derivatives of a % penalty function w.r.t. changes in parameters. It works for first % derivatives, but I couldn't make it work for the second derivs - so % I gave up and tried a new strategy. T = M(1:3,1:3); [U,S,V] = svd(T); s = diag(S); h0 = sum(log(s).^2); d1s = 2*log(s)./s; %d2s = 2./s.^2-2*log(s)./s.^2; d1 = zeros(12,1); for j=1:3 for i1=1:9 T1 = zeros(3,3); T1(i1) = 1; t1 = U(:,j)'*T1*V(:,j); d1(i1) = d1(i1) + d1s(j)*t1; end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function M = P2M_unused(P) % SVD parameterisation of affine transform, based on matrix-logs. % Translations D = P(1:3); D = D(:); % Rotation U ind = [2 3 6]; T = zeros(3); T(ind) = P(4:6); U = expm(T-T'); % Diagonal zooming matrix S = expm(diag(P(7:9))); % Rotation V' T(ind) = P(10:12); V = expm(T'-T); M = [U*S*V' D ; 0 0 0 1]; return; %_______________________________________________________________________ %_______________________________________________________________________
github
lcnbeapp/beapp-master
spm_normalise.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_normalise.m
13,235
utf_8
5dfafbc96b6282a48b19ee3433a77167
function params = spm_normalise(VG,VF,matname,VWG,VWF,flags) % Spatial (stereotactic) normalization % % FORMAT params = spm_normalise(VG,VF,matname,VWG,VWF,flags) % VG - template handle(s) % VF - handle of image to estimate params from % matname - name of file to store deformation definitions % VWG - template weighting image % VWF - source weighting image % flags - flags. If any field is not passed, then defaults are assumed. % smosrc - smoothing of source image (FWHM of Gaussian in mm). % Defaults to 8. % smoref - smoothing of template image (defaults to 0). % regtype - regularisation type for affine registration % See spm_affreg.m (default = 'mni'). % cutoff - Cutoff of the DCT bases. Lower values mean more % basis functions are used (default = 30mm). % nits - number of nonlinear iterations (default=16). % reg - amount of regularisation (default=0.1) % ___________________________________________________________________________ % % This module spatially (stereotactically) normalizes MRI, PET or SPECT % images into a standard space defined by some ideal model or template % image[s]. The template images supplied with SPM conform to the space % defined by the ICBM, NIH P-20 project, and approximate that of the % the space described in the atlas of Talairach and Tournoux (1988). % The transformation can also be applied to any other image that has % been coregistered with these scans. % % % Mechanism % Generally, the algorithms work by minimising the sum of squares % difference between the image which is to be normalised, and a linear % combination of one or more template images. For the least squares % registration to produce an unbiased estimate of the spatial % transformation, the image contrast in the templates (or linear % combination of templates) should be similar to that of the image from % which the spatial normalization is derived. The registration simply % searches for an optimum solution. If the starting estimates are not % good, then the optimum it finds may not find the global optimum. % % The first step of the normalization is to determine the optimum % 12-parameter affine transformation. Initially, the registration is % performed by matching the whole of the head (including the scalp) to % the template. Following this, the registration proceeded by only % matching the brains together, by appropriate weighting of the template % voxels. This is a completely automated procedure (that does not % require ``scalp editing'') that discounts the confounding effects of % skull and scalp differences. A Bayesian framework is used, such that % the registration searches for the solution that maximizes the a % posteriori probability of it being correct. i.e., it maximizes the % product of the likelihood function (derived from the residual squared % difference) and the prior function (which is based on the probability % of obtaining a particular set of zooms and shears). % % The affine registration is followed by estimating nonlinear deformations, % whereby the deformations are defined by a linear combination of three % dimensional discrete cosine transform (DCT) basis functions. % The parameters represent coefficients of the deformations in % three orthogonal directions. The matching involved simultaneously % minimizing the bending energies of the deformation fields and the % residual squared difference between the images and template(s). % % An option is provided for allowing weighting images (consisting of pixel % values between the range of zero to one) to be used for registering % abnormal or lesioned brains. These images should match the dimensions % of the image from which the parameters are estimated, and should contain % zeros corresponding to regions of abnormal tissue. % % % Uses % Primarily for stereotactic normalization to facilitate inter-subject % averaging and precise characterization of functional anatomy. It is % not necessary to spatially normalise the data (this is only a % pre-requisite for intersubject averaging or reporting in the % Talairach space). % % Inputs % The first input is the image which is to be normalised. This image % should be of the same modality (and MRI sequence etc) as the template % which is specified. The same spatial transformation can then be % applied to any other images of the same subject. These files should % conform to the SPM data format (See 'Data Format'). Many subjects can % be entered at once, and there is no restriction on image dimensions % or voxel size. % % Providing that the images have a correct ".mat" file associated with % them, which describes the spatial relationship between them, it is % possible to spatially normalise the images without having first % resliced them all into the same space. The ".mat" files are generated % by "spm_realign" or "spm_coregister". % % Default values of parameters pertaining to the extent and sampling of % the standard space can be changed, including the model or template % image[s]. % % % Outputs % All normalized *.img scans are written to the same subdirectory as % the original *.img, prefixed with a 'n' (i.e. n*.img). The details % of the transformations are displayed in the results window, and the % parameters are saved in the "*_sn.mat" file. % % %____________________________________________________________________________ % Refs: % K.J. Friston, J. Ashburner, C.D. Frith, J.-B. Poline, % J.D. Heather, and R.S.J. Frackowiak % Spatial Registration and Normalization of Images. % Human Brain Mapping 2:165-189(1995) % % J. Ashburner, P. Neelin, D.L. Collins, A.C. Evans and K. J. Friston % Incorporating Prior Knowledge into Image Registration. % NeuroImage 6:344-352 (1997) % % J. Ashburner and K. J. Friston % Nonlinear Spatial Normalization using Basis Functions. % Human Brain Mapping 7(4):in press (1999) %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ if nargin<2, error('Incorrect usage.'); end; if ischar(VF), VF = spm_vol(VF); end; if ischar(VG), VG = spm_vol(VG); end; if nargin<3, if nargout==0, [pth,nm,xt,vr] = spm_fileparts(deblank(VF(1).fname)); matname = fullfile(pth,[nm '_sn.mat']); else matname = ''; end; end; if nargin<4, VWG = ''; end; if nargin<5, VWF = ''; end; if ischar(VWG), VWG=spm_vol(VWG); end; if ischar(VWF), VWF=spm_vol(VWF); end; def_flags = struct('smosrc',8,'smoref',0,'regtype','mni',... 'cutoff',30,'nits',16,'reg',0.1,'graphics',1); if nargin < 6, flags = def_flags; else fnms = fieldnames(def_flags); for i=1:length(fnms), if ~isfield(flags,fnms{i}), flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i})); end; end; end; fprintf('Smoothing by %g & %gmm..\n', flags.smoref, flags.smosrc); VF1 = spm_smoothto8bit(VF,flags.smosrc); % Rescale images so that globals are better conditioned VF1.pinfo(1:2,:) = VF1.pinfo(1:2,:)/spm_global(VF1); for i=1:numel(VG), VG1(i) = spm_smoothto8bit(VG(i),flags.smoref); VG1(i).pinfo(1:2,:) = VG1(i).pinfo(1:2,:)/spm_global(VG(i)); end; % Affine Normalisation %----------------------------------------------------------------------- fprintf('Coarse Affine Registration..\n'); aflags = struct('sep',max(flags.smoref,flags.smosrc), 'regtype',flags.regtype,... 'WG',[],'WF',[],'globnorm',0); aflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2)))); aflags.sep = max(aflags.sep,max(sqrt(sum(VF(1).mat(1:3,1:3).^2)))); M = eye(4); %spm_matrix(prms'); spm_chi2_plot('Init','Affine Registration','Mean squared difference','Iteration'); [M,scal] = spm_affreg(VG1, VF1, aflags, M); fprintf('Fine Affine Registration..\n'); aflags.WG = VWG; aflags.WF = VWF; aflags.sep = aflags.sep/2; [M,scal] = spm_affreg(VG1, VF1, aflags, M,scal); Affine = inv(VG(1).mat\M*VF1(1).mat); spm_chi2_plot('Clear'); % Basis function Normalisation %----------------------------------------------------------------------- fov = VF1(1).dim(1:3).*sqrt(sum(VF1(1).mat(1:3,1:3).^2)); if any(fov<15*flags.smosrc/2 & VF1(1).dim(1:3)<15), fprintf('Field of view too small for nonlinear registration\n'); Tr = []; elseif isfinite(flags.cutoff) && flags.nits && ~isinf(flags.reg), fprintf('3D CT Norm...\n'); Tr = snbasis(VG1,VF1,VWG,VWF,Affine,... max(flags.smoref,flags.smosrc),flags.cutoff,flags.nits,flags.reg); else Tr = []; end; clear VF1 VG1 flags.version = 'spm_normalise.m 2.12 04/11/26'; flags.date = date; params = struct('Affine',Affine, 'Tr',Tr, 'VF',VF, 'VG',VG, 'flags',flags); if flags.graphics, spm_normalise_disp(params,VF); end; % Remove dat fields before saving %----------------------------------------------------------------------- if isfield(VF,'dat'), VF = rmfield(VF,'dat'); end; if isfield(VG,'dat'), VG = rmfield(VG,'dat'); end; if ~isempty(matname), fprintf('Saving Parameters..\n'); if spm_matlab_version_chk('7') >= 0, save(matname,'-V6','Affine','Tr','VF','VG','flags'); else save(matname,'Affine','Tr','VF','VG','flags'); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg) % 3D Basis Function Normalization % FORMAT Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg) % VG - Template volumes (see spm_vol). % VF - Volume to normalize. % VWG - weighting Volume - for template. % VWF - weighting Volume - for object. % Affine - A 4x4 transformation (in voxel space). % fwhm - smoothness of images. % cutoff - frequency cutoff of basis functions. % nits - number of iterations. % reg - regularisation. % Tr - Discrete cosine transform of the warps in X, Y & Z. % % snbasis performs a spatial normalization based upon a 3D % discrete cosine transform. % %______________________________________________________________________ fwhm = [fwhm 30]; % Number of basis functions for x, y & z %----------------------------------------------------------------------- tmp = sqrt(sum(VG(1).mat(1:3,1:3).^2)); k = max(round((VG(1).dim(1:3).*tmp)/cutoff),[1 1 1]); % Scaling is to improve stability. %----------------------------------------------------------------------- stabilise = 8; basX = spm_dctmtx(VG(1).dim(1),k(1))*stabilise; basY = spm_dctmtx(VG(1).dim(2),k(2))*stabilise; basZ = spm_dctmtx(VG(1).dim(3),k(3))*stabilise; dbasX = spm_dctmtx(VG(1).dim(1),k(1),'diff')*stabilise; dbasY = spm_dctmtx(VG(1).dim(2),k(2),'diff')*stabilise; dbasZ = spm_dctmtx(VG(1).dim(3),k(3),'diff')*stabilise; vx1 = sqrt(sum(VG(1).mat(1:3,1:3).^2)); vx2 = vx1; kx = (pi*((1:k(1))'-1)/VG(1).dim(1)/vx1(1)).^2; ox=ones(k(1),1); ky = (pi*((1:k(2))'-1)/VG(1).dim(2)/vx1(2)).^2; oy=ones(k(2),1); kz = (pi*((1:k(3))'-1)/VG(1).dim(3)/vx1(3)).^2; oz=ones(k(3),1); if 1, % BENDING ENERGY REGULARIZATION % Estimate a suitable sparse diagonal inverse covariance matrix for % the parameters (IC0). %----------------------------------------------------------------------- IC0 = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +... 1*kron(kz.^0,kron(ky.^2,kx.^0)) +... 1*kron(kz.^0,kron(ky.^0,kx.^2)) +... 2*kron(kz.^1,kron(ky.^1,kx.^0)) +... 2*kron(kz.^1,kron(ky.^0,kx.^1)) +... 2*kron(kz.^0,kron(ky.^1,kx.^1)) ); IC0 = reg*IC0*stabilise^6; IC0 = [IC0*vx2(1)^4 ; IC0*vx2(2)^4 ; IC0*vx2(3)^4 ; zeros(prod(size(VG))*4,1)]; IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0)); else % MEMBRANE ENERGY (LAPLACIAN) REGULARIZATION %----------------------------------------------------------------------- IC0 = kron(kron(oz,oy),kx) + kron(kron(oz,ky),ox) + kron(kron(kz,oy),ox); IC0 = reg*IC0*stabilise^6; IC0 = [IC0*vx2(1)^2 ; IC0*vx2(2)^2 ; IC0*vx2(3)^2 ; zeros(prod(size(VG))*4,1)]; IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0)); end; % Generate starting estimates. %----------------------------------------------------------------------- s1 = 3*prod(k); s2 = s1 + numel(VG)*4; T = zeros(s2,1); T(s1+(1:4:numel(VG)*4)) = 1; pVar = Inf; for iter=1:nits, fprintf(' iteration %2d: ', iter); [Alpha,Beta,Var,fw] = spm_brainwarp(VG,VF,Affine,basX,basY,basZ,dbasX,dbasY,dbasZ,T,fwhm,VWG, VWF); if Var>pVar, scal = pVar/Var ; Var = pVar; else scal = 1; end; pVar = Var; T = (Alpha + IC0*scal)\(Alpha*T + Beta); fwhm(2) = min([fw fwhm(2)]); fprintf(' FWHM = %6.4g Var = %g\n', fw,Var); end; % Values of the 3D-DCT - for some bizarre reason, this needs to be done % as two seperate statements in Matlab 6.5... %----------------------------------------------------------------------- Tr = reshape(T(1:s1),[k 3]); drawnow; Tr = Tr*stabilise.^3; return;
github
lcnbeapp/beapp-master
spm_minmax.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_minmax.m
3,705
utf_8
58192721e506d5814be863bb8a7e2acf
function [mnv,mxv] = spm_minmax(g) % Compute a suitable range of intensities for VBM preprocessing stuff % FORMAT [mnv,mxv] = spm_minmax(g) % g - array of data % mnv - minimum value % mxv - maximum value % % A MOG with two Gaussians is fitted to the intensities. The lower % Gaussian is assumed to represent background. The lower value is % where there is a 50% probability of being above background. The % upper value is one that encompases 99.5% of the values. %____________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ d = [size(g) 1]; mxv = double(max(g(:))); mnv = double(min(g(:))); h = zeros(256,1); spm_progress_bar('Init',d(3),'Initial histogram','Planes loaded'); sw = warning('off','all'); for i=1:d(3) h = h + spm_hist(uint8(round(g(:,:,i)*(255/mxv))),ones(d(1)*d(2),1)); spm_progress_bar('Set',i); end; warning(sw); spm_progress_bar('Clear'); % Occasional problems with partially masked data because the first Gaussian % just fits the big peak at zero. This will fix that one, but cause problems % for skull-stripped data. h(1) = 0; h(end) = 0; % Very crude heuristic to find a suitable lower limit. The large amount % of background really messes up mutual information registration. % Begin by modelling the intensity histogram with two Gaussians. One % for background, and the other for tissue. [mn,v,mg] = fithisto((0:255)',h,1000,[1 128],[32 128].^2,[1 1]); pr = distribution(mn,v,mg,(0:255)'); %fg = spm_figure('FindWin','Interactive'); %if ~isempty(fg) % figure(fg); % plot((0:255)',h/sum(h),'b', (0:255)',pr,'r'); % drawnow; %end; % Find the lowest intensity above the mean of the first Gaussian % where there is more than 50% probability of not being background mnd = find((pr(:,1)./(sum(pr,2)+eps) < 0.5) & (0:255)' >mn(1)); if isempty(mnd) || mnd(1)==1 || mn(1)>mn(2), mnd = 1; else mnd = mnd(1)-1; end mnv = mnd*mxv/255; % Upper limit should get 99.5% of the intensities of the % non-background region ch = cumsum(h(mnd:end))/sum(h(mnd:end)); ch = find(ch>0.995)+mnd; mxv = ch(1)/255*mxv; return; %_______________________________________________________________________ %_______________________________________________________________________ function [mn,v,mg,ll]=fithisto(x,h,maxit,n,v,mg) % Fit a mixture of Gaussians to a histogram h = h(:); x = x(:); sml = mean(diff(x))/1000; if nargin==4 mg = sum(h); mn = sum(x.*h)/mg; v = (x - mn); v = sum(v.*v.*h)/mg*ones(1,n); mn = (1:n)'/n*(max(x)-min(x))+min(x); mg = mg*ones(1,n)/n; elseif nargin==6 mn = n; n = length(mn); else error('Incorrect usage'); end; ll = Inf; for it=1:maxit prb = distribution(mn,v,mg,x); scal = sum(prb,2)+eps; oll = ll; ll = -sum(h.*log(scal)); if it>2 && oll-ll < length(x)/n*1e-9 break; end; for j=1:n p = h.*prb(:,j)./scal; mg(j) = sum(p); mn(j) = sum(x.*p)/mg(j); vr = x-mn(j); v(j) = sum(vr.*vr.*p)/mg(j)+sml; end; mg = mg + 1e-3; mg = mg/sum(mg); end; %_______________________________________________________________________ %_______________________________________________________________________ function y=distribution(m,v,g,x) % Gaussian probability density if nargin ~= 4 error('not enough input arguments'); end; x = x(:); m = m(:); v = v(:); g = g(:); if ~all(size(m) == size(v) & size(m) == size(g)) error('incompatible dimensions'); end; for i=1:size(m,1) d = x-m(i); amp = g(i)/sqrt(2*pi*v(i)); y(:,i) = amp*exp(-0.5 * (d.*d)/v(i)); end; return;
github
lcnbeapp/beapp-master
spm_create_vol.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_create_vol.m
4,914
utf_8
3d1ffa54c52618a0923d6642b8f5e471
function V = spm_create_vol(V,varargin) % Create a volume % FORMAT V = spm_create_vol(V) % V - image volume information (see spm_vol.m) %____________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ for i=1:numel(V), if nargin>1, v = create_vol(V(i),varargin{:}); else v = create_vol(V(i)); end; f = fieldnames(v); for j=1:size(f,1), V(i).(f{j}) = v.(f{j}); end; end; function V = create_vol(V,varargin) if ~isstruct(V), error('Not a structure.'); end; if ~isfield(V,'fname'), error('No "fname" field'); end; if ~isfield(V,'dim'), error('No "dim" field'); end; if ~all(size(V.dim)==[1 3]), error(['"dim" field is the wrong size (' num2str(size(V.dim)) ').']); end; if ~isfield(V,'n'), V.n = [1 1]; else V.n = [V.n(:)' 1 1]; V.n = V.n(1:2); end; if V.n(1)>1 && V.n(2)>1, error('Can only do up to 4D data (%s).',V.fname); end; if ~isfield(V,'dt'), V.dt = [spm_type('float64') spm_platform('bigend')]; end; dt{1} = spm_type(V.dt(1)); if strcmp(dt{1},'unknown'), error(['"' dt{1} '" is an unrecognised datatype (' num2str(V.dt(1)) ').']); end; if V.dt(2), dt{2} = 'BE'; else dt{2} = 'LE'; end; if ~isfield(V,'pinfo'), V.pinfo = [Inf Inf 0]'; end; if size(V.pinfo,1)==2, V.pinfo(3,:) = 0; end; V.fname = deblank(V.fname); [pth,nam,ext] = fileparts(V.fname); switch ext, case {'.img'} minoff = 0; case {'.nii'} minoff = 352; otherwise error(['"' ext '" is not a recognised extension.']); end; bits = spm_type(V.dt(1),'bits'); minoff = minoff + ceil(prod(V.dim(1:2))*bits/8)*V.dim(3)*(V.n(1)-1+V.n(2)-1); V.pinfo(3,1) = max(V.pinfo(3,:),minoff); if ~isfield(V,'descrip'), V.descrip = ''; end; if ~isfield(V,'private'), V.private = struct; end; dim = [V.dim(1:3) V.n]; dat = file_array(V.fname,dim,[dt{1} '-' dt{2}],0,V.pinfo(1),V.pinfo(2)); N = nifti; N.dat = dat; N.mat = V.mat; N.mat0 = V.mat; N.mat_intent = 'Aligned'; N.mat0_intent = 'Aligned'; N.descrip = V.descrip; try N0 = nifti(V.fname); % Just overwrite if both are single volume files. tmp = [N0.dat.dim ones(1,5)]; if prod(tmp(4:end))==1 && prod(dim(4:end))==1 N0 = []; end; catch N0 = []; end; if ~isempty(N0), % If the dimensions differ, then there is the potential for things to go badly wrong. tmp = [N0.dat.dim ones(1,5)]; if any(tmp(1:3) ~= dim(1:3)) warning(['Incompatible x,y,z dimensions in file "' V.fname '" [' num2str(tmp(1:3)) ']~=[' num2str(dim(1:3)) '].']); end; if dim(5) > tmp(5) && tmp(4) > 1, warning(['Incompatible 4th and 5th dimensions in file "' V.fname '" (' num2str([tmp(4:5) dim(4:5)]) ').']); end; N.dat.dim = [dim(1:3) max(dim(4:5),tmp(4:5))]; if ~strcmp(dat.dtype,N0.dat.dtype), warning(['Incompatible datatype in file "' V.fname '" ' N0.dat.dtype ' ~= ' dat.dtype '.']); end; if single(N.dat.scl_slope) ~= single(N0.dat.scl_slope) && (size(N0.dat,4)>1 || V.n(1)>1), warning(['Incompatible scalefactor in "' V.fname '" ' num2str(N0.dat.scl_slope) '~=' num2str(N.dat.scl_slope) '.']); end; if single(N.dat.scl_inter) ~= single(N0.dat.scl_inter), warning(['Incompatible intercept in "' V.fname '" ' num2str(N0.dat.scl_inter) '~=' num2str(N.dat.scl_inter) '.']); end; if single(N.dat.offset) ~= single(N0.dat.offset), warning(['Incompatible intercept in "' V.fname '" ' num2str(N0.dat.offset) '~=' num2str(N.dat.offset) '.']); end; if V.n(1)==1, % Ensure volumes 2..N have the original matrix nt = size(N.dat,4); if nt>1 && sum(sum((N0.mat-V.mat).^2))>1e-8, M0 = N0.mat; if ~isfield(N0.extras,'mat'), N0.extras.mat = zeros([4 4 nt]); else if size(N0.extras.mat,4)<nt, N0.extras.mat(:,:,nt) = zeros(4); end; end; for i=2:nt, if sum(sum(N0.extras.mat(:,:,i).^2))==0, N0.extras.mat(:,:,i) = M0; end; end; N.extras.mat = N0.extras.mat; end; N0.mat = V.mat; if strcmp(N0.mat0_intent,'Aligned'), N.mat0 = V.mat; end; if ~isempty(N.extras) && isstruct(N.extras) && isfield(N.extras,'mat') &&... size(N.extras.mat,3)>=1, N.extras.mat(:,:,V.n(1)) = V.mat; end; else N.extras.mat(:,:,V.n(1)) = V.mat; end; if ~isempty(N0.extras) && isstruct(N0.extras) && isfield(N0.extras,'mat'), N0.extras.mat(:,:,V.n(1)) = N.mat; N.extras = N0.extras; end; if sum((V.mat(:)-N0.mat(:)).^2) > 1e-4, N.extras.mat(:,:,V.n(1)) = V.mat; end; end; create(N); V.private = N;
github
lcnbeapp/beapp-master
spm_check_installation.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_check_installation.m
19,147
utf_8
5500b12cea8521a513b4ff3226dc8f4d
function spm_check_installation(action) % Check SPM installation % FORMAT spm_check_installation('basic') % Perform a superficial check of SPM installation [default]. % % FORMAT spm_check_installation('full') % Perform an in-depth diagnostic of SPM installation. % % FORMAT spm_check_installation('build') % Build signature of SPM distribution as used by previous option. % (for developers) %__________________________________________________________________________ % Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id$ if isdeployed, return; end %-Select action %-------------------------------------------------------------------------- if ~nargin, action = 'basic'; end switch action case 'basic' check_basic; case 'full' check_full; case 'build' build_signature; otherwise error('Unknown action to perform.'); end %========================================================================== % FUNCTION check_basic %========================================================================== function check_basic %-Minimal MATLAB version required %-------------------------------------------------------------------------- try v = spm_matlab_version_chk('7.1'); catch error('Where is spm_matlab_version_chk.m?'); end if v < 0 error([... 'SPM8 requires MATLAB 7.1 onwards in order to run.\n'... 'This MATLAB version is %s\n'], version); end %-Check installation %-------------------------------------------------------------------------- spm('Ver','',1); d = spm('Dir'); %-Check the search path %-------------------------------------------------------------------------- p = textscan(path,'%s','delimiter',pathsep); p = p{1}; if ~ismember(lower(d),lower(p)) error(sprintf([... 'You do not appear to have the MATLAB search path set up\n'... 'to include your SPM8 distribution. This means that you\n'... 'can start SPM in this directory, but if your change to\n'... 'another directory then MATLAB will be unable to find the\n'... 'SPM functions. You can use the editpath command in MATLAB\n'... 'to set it up.\n'... ' addpath %s\n'... 'For more information, try typing the following:\n'... ' help path\n help editpath'],d)); end %-Ensure that the original release - as well as the updates - was installed %-------------------------------------------------------------------------- if ~exist(fullfile(d,'spm_Npdf.m'),'file') % File that should not have changed if isunix error(sprintf([... 'There appears to be some problem with the installation.\n'... 'The original spm8.zip distribution should be installed\n'... 'and the updates installed on top of this. Unix commands\n'... 'to do this are:\n'... ' unzip spm8.zip\n'... ' unzip -o spm8_updates_r????.zip -d spm8\n'... 'You may need help from your local network administrator.'])); else error(sprintf([... 'There appears to be some problem with the installation.\n'... 'The original spm8.zip distribution should be installed\n'... 'and the updates installed on top of this. If in doubt,\n'... 'consult your local network administrator.'])); end end %-Ensure that the files were unpacked correctly %-------------------------------------------------------------------------- if ispc try t = load(fullfile(d,'Split.mat')); catch error(sprintf([... 'There appears to be some problem reading the MATLAB .mat\n'... 'files from the SPM distribution. This is probably\n'... 'something to do with the way that the distribution was\n'... 'unpacked. If you used WinZip, then ensure that\n'... 'TAR file smart CR/LF conversion is disabled\n'... '(under the Miscellaneous Configuration Options).'])); end if ~exist(fullfile(d,'toolbox','DARTEL','diffeo3d.c'),'file'), error(sprintf([... 'There appears to be some problem with the installation.\n'... 'This is probably something to do with the way that the\n'... 'distribution was unbundled from the original .zip files.\n'... 'Please ensure that the files are unpacked so that the\n'... 'directory structure is retained.'])); end end %-Check the MEX files %-------------------------------------------------------------------------- try feval(@spm_bsplinc,1,ones(1,6)); catch error([... 'SPM uses a number of MEX files, which are compiled functions.\n'... 'These need to be compiled for the various platforms on which SPM\n'... 'is run. At the FIL, where SPM is developed, the number of\n'... 'computer platforms is limited. It is therefore not possible to\n'... 'release a version of SPM that will run on all computers. See\n'... ' %s%csrc%cMakefile and\n'... ' http://en.wikibooks.org/wiki/SPM#Installation\n'... 'for information about how to compile mex files for %s\n'... 'in MATLAB %s.'],... d,filesep,filesep,computer,version); end %========================================================================== % FUNCTION check_full %========================================================================== function check_full %-Say Hello %-------------------------------------------------------------------------- disp( ' ___ ____ __ __ ' ); disp( '/ __)( _ \( \/ ) ' ); disp( '\__ \ )___/ ) ( Statistical Parametric Mapping ' ); disp(['(___/(__) (_/\/\_) SPM - http://www.fil.ion.ucl.ac.uk/spm/ ']); fprintf('\n'); %-Detect SPM directory %-------------------------------------------------------------------------- SPMdir = which('spm.m','-ALL'); if isempty(SPMdir) fprintf('SPM is not in your MATLAB path.\n'); return; elseif numel(SPMdir) > 1 fprintf('SPM seems to appear in several different folders:\n'); for i=1:numel(SPMdir) fprintf(' * %s\n',SPMdir{i}); end fprintf('Remove all but one with ''editpath'' or ''spm_rmpath''.\n'); return; else fprintf('SPM is installed in: %s\n',fileparts(SPMdir{1})); end SPMdir = fileparts(SPMdir{1}); %-Detect SPM version and revision number %-------------------------------------------------------------------------- v = struct('Name','','Version','','Release','','Date',''); try fid = fopen(fullfile(SPMdir,'Contents.m'),'rt'); if fid == -1 fprintf('Cannot open ''%s'' for reading.\n',fullfile(SPMdir,'Contents.m')); return; end l1 = fgetl(fid); l2 = fgetl(fid); fclose(fid); l1 = strtrim(l1(2:end)); l2 = strtrim(l2(2:end)); t = textscan(l2,'%s','delimiter',' '); t = t{1}; v.Name = l1; v.Date = t{4}; v.Version = t{2}; v.Release = t{3}(2:end-1); catch fprintf('Cannot obtain SPM version & revision number.\n'); return; end fprintf('SPM version is %s (%s, %s)\n', ... v.Release,v.Version,strrep(v.Date,'-',' ')); %-Detect SPM toolboxes %-------------------------------------------------------------------------- officials = {'Beamforming', 'DARTEL', 'dcm_meeg', 'DEM', 'FieldMap', ... 'HDW', 'MEEGtools', 'mixture', 'Neural_Models', 'Seg', 'spectral', ... 'SRender'}; dd = dir(fullfile(SPMdir,'toolbox')); dd = {dd([dd.isdir]).name}; dd(strmatch('.',dd)) = []; dd = setdiff(dd,officials); fprintf('SPM toolboxes:'); for i=1:length(dd) fprintf(' %s',dd{i}); end if isempty(dd), fprintf(' none'); end fprintf('\n'); %-Detect MATLAB & toolboxes %-------------------------------------------------------------------------- fprintf('MATLAB is installed in: %s\n',matlabroot); fprintf('MATLAB version is %s\n',version); fprintf('MATLAB toolboxes: '); hastbx = false; if license('test','signal_toolbox') && ~isempty(ver('signal')) vtbx = ver('signal'); hastbx = true; fprintf('signal (v%s) ',vtbx.Version); end if license('test','image_toolbox') && ~isempty(ver('images')) vtbx = ver('images'); hastbx = true; fprintf('images (v%s) ',vtbx.Version); end if license('test','statistics_toolbox') && ~isempty(ver('stats')) vtbx = ver('stats'); hastbx = true; fprintf('stats (v%s)',vtbx.Version); end if ~hastbx, fprintf('none.'); end fprintf('\n'); %-Detect Platform and Operating System %-------------------------------------------------------------------------- [C, maxsize] = computer; fprintf('Platform: %s (maxsize=%d)\n', C, maxsize); if ispc platform = [system_dependent('getos'),' ',system_dependent('getwinsys')]; elseif exist('ismac') && ismac [fail, input] = unix('sw_vers'); if ~fail platform = strrep(input, 'ProductName:', ''); platform = strrep(platform, sprintf('\t'), ''); platform = strrep(platform, sprintf('\n'), ' '); platform = strrep(platform, 'ProductVersion:', ' Version: '); platform = strrep(platform, 'BuildVersion:', 'Build: '); else platform = system_dependent('getos'); end else platform = system_dependent('getos'); end fprintf('OS: %s\n', platform); %-Detect Java %-------------------------------------------------------------------------- fprintf('%s\n', version('-java')); fprintf('Java support: '); level = {'jvm', 'awt', 'swing', 'desktop'}; for i=1:numel(level) if isempty(javachk(level{i})), fprintf('%s ',level{i}); end end fprintf('\n'); %-Detect Monitor(s) %-------------------------------------------------------------------------- M = get(0,'MonitorPositions'); fprintf('Monitor(s):'); for i=1:size(M,1) fprintf(' [%d %d %d %d]',M(i,:)); end fprintf(' (%dbit)\n', get(0,'ScreenDepth')); %-Detect OpenGL rendering %-------------------------------------------------------------------------- S = opengl('data'); fprintf('OpenGL version: %s',S.Version); if S.Software, fprintf('(Software)\n'); else fprintf('(Hardware)\n'); end fprintf('OpenGL renderer: %s (%s)\n',S.Vendor,S.Renderer); %-Detect MEX setup %-------------------------------------------------------------------------- fprintf('MEX extension: %s\n',mexext); try cc = mex.getCompilerConfigurations('C','Selected'); if ~isempty(cc) cc = cc(1); % can be C or C++ fprintf('C Compiler: %s (%s).\n', cc.Name, cc.Version); fprintf('C Compiler settings: %s (''%s'')\n', ... cc.Details.CompilerExecutable, cc.Details.OptimizationFlags); else fprintf('No C compiler is selected (see mex -setup)\n'); end end try [sts, m] = fileattrib(fullfile(SPMdir,'src')); m = [m.UserRead m.UserWrite m.UserExecute ... m.GroupRead m.GroupWrite m.GroupExecute ... m.OtherRead m.OtherWrite m.OtherExecute]; r = 'rwxrwxrwx'; r(~m) = '-'; fprintf('C Source code permissions: dir %s, ', r); [sts, m] = fileattrib(fullfile(SPMdir,'src','spm_resels_vol.c')); m = [m.UserRead m.UserWrite m.UserExecute ... m.GroupRead m.GroupWrite m.GroupExecute ... m.OtherRead m.OtherWrite m.OtherExecute]; r = 'rwxrwxrwx'; r(~m) = '-'; fprintf('file %s\n',r); end %-Get file details for local SPM installation %-------------------------------------------------------------------------- fprintf('%s\n',repmat('-',1,70)); l = generate_listing(SPMdir); fprintf('%s %40s\n','Parsing local installation...','...done'); %-Get file details for most recent public version %-------------------------------------------------------------------------- fprintf('Downloading SPM information...'); url = sprintf('http://www.fil.ion.ucl.ac.uk/spm/software/%s/%s.xml',... lower(v.Release),lower(v.Release)); try p = [tempname '.xml']; urlwrite(url,p); catch fprintf('\nCannot access URL %s\n',url); return; end fprintf('%40s\n','...done'); %-Parse it into a Matlab structure %-------------------------------------------------------------------------- fprintf('Parsing SPM information...'); tree = xmlread(p); delete(p); r = struct([]); ind = 1; if tree.hasChildNodes for i=0:tree.getChildNodes.getLength-1 m = tree.getChildNodes.item(i); if strcmp(m.getNodeName,'signature') m = m.getChildNodes; for j=0:m.getLength-1 if strcmp(m.item(j).getNodeName,'file') n = m.item(j).getChildNodes; for k=0:n.getLength-1 o = n.item(k); if ~strcmp(o.getNodeName,'#text') try s = char(o.getChildNodes.item(0).getData); catch s = ''; end switch char(o.getNodeName) case 'name' r(ind).file = s; case 'id' r(ind).id = str2num(s); otherwise r(ind).(char(o.getNodeName)) = s; end end end ind = ind + 1; end end end end end fprintf('%44s\n','...done'); %-Compare local and public versions %-------------------------------------------------------------------------- fprintf('%s\n',repmat('-',1,70)); compare_versions(l,r); fprintf('%s\n',repmat('-',1,70)); %========================================================================== % FUNCTION compare_versions %========================================================================== function compare_versions(l,r) %-Uniformise file names %-------------------------------------------------------------------------- a = {r.file}; a = strrep(a,'\','/'); [r.file] = a{:}; a = {l.file}; a = strrep(a,'\','/'); [l.file] = a{:}; %-Look for missing or unknown files %-------------------------------------------------------------------------- [x,ir,il] = setxor({r.file},{l.file}); if isempty([ir il]) fprintf('No missing or unknown files\n'); else if ~isempty(ir) fprintf('File(s) missing in your installation:\n'); end for i=1:length(ir) fprintf(' * %s\n', r(ir(i)).file); end if ~isempty(ir) && ~isempty(il), fprintf('%s\n',repmat('-',1,70)); end if ~isempty(il) fprintf('File(s) not part of the current version of SPM:\n'); end for i=1:length(il) fprintf(' * %s\n', l(il(i)).file); end end fprintf('%s\n',repmat('-',1,70)); %-Look for local changes or out-of-date files %-------------------------------------------------------------------------- [tf, ir] = ismember({r.file},{l.file}); dispc = true; for i=1:numel(r) if tf(i) if ~isempty(r(i).id) && (isempty(l(ir(i)).id) || (r(i).id ~= l(ir(i)).id)) dispc = false; fprintf('File %s is not up to date (r%d vs r%d)\n', ... r(i).file, r(i).id, l(ir(i)).id); end if ~isempty(r(i).md5) && ~isempty(l(ir(i)).md5) && ~strcmp(r(i).md5,l(ir(i)).md5) dispc = false; fprintf('File %s has been edited (checksum mismatch)\n', r(i).file); end end end if dispc fprintf('No local change or out-of-date files\n'); end %========================================================================== % FUNCTION build_signature %========================================================================== function build_signature [v,r] = spm('Ver','',1); d = spm('Dir'); l = generate_listing(d); fprintf('Saving %s signature in %s\n',... v, fullfile(pwd,sprintf('%s_signature.xml',v))); fid = fopen(fullfile(pwd,sprintf('%s_signature.xml',v)),'wt'); fprintf(fid,'<?xml version="1.0"?>\n'); fprintf(fid,'<!-- Signature for %s r%s -->\n',v,r); fprintf(fid,'<signature>\n'); for i=1:numel(l) fprintf(fid,' <file>\n'); fprintf(fid,' <name>%s</name>\n',l(i).file); fprintf(fid,' <id>%d</id>\n',l(i).id); fprintf(fid,' <date>%s</date>\n',l(i).date); fprintf(fid,' <md5>%s</md5>\n',l(i).md5); fprintf(fid,' </file>\n'); end fprintf(fid,'</signature>\n'); fclose(fid); %========================================================================== % FUNCTION generate_listing %========================================================================== function l = generate_listing(d,r,l) if nargin < 2 r = ''; end if nargin < 3 l = struct([]); end %-List content of folder %-------------------------------------------------------------------------- ccd = fullfile(d,r); fprintf('%-10s: %58s','Directory',ccd(max(1,length(ccd)-57):end)); dd = dir(ccd); f = {dd(~[dd.isdir]).name}; dispw = false; for i=1:length(f) [p,name,ext] = fileparts(f{i}); info = struct('file','', 'id',[], 'date','', 'md5',''); if ismember(ext,{'.m','.man','.txt','.xml','.c','.h',''}) info = extract_info(fullfile(ccd,f{i})); end info.file = fullfile(r,f{i}); try try info.md5 = md5sum(fullfile(ccd,f{i})); catch %[s, info.md5] = system(['md5sum "' fullfile(ccd,f{i}) '"']); %info.md5 = strtok(info.md5); end end if isempty(l), l = info; else l(end+1) = info; end if isempty(r) && strcmp(ext,'.m') w = which(f{i},'-ALL'); if numel(w) > 1 && ~strcmpi(f{i},'Contents.m') if ~dispw, fprintf('\n'); end dispw = true; fprintf('File %s appears %d times in your MATLAB path:\n',f{i},numel(w)); for j=1:numel(w) if j==1 && isempty(strmatch(d,w{1})) fprintf(' %s (SHADOWING)\n',w{1}); else fprintf(' %s\n',w{j}); end end end end end if ~dispw, fprintf('%s',repmat(sprintf('\b'),1,70)); end %-Recursively extract subdirectories %-------------------------------------------------------------------------- dd = {dd([dd.isdir]).name}; dd(strmatch('.',dd)) = []; for i=1:length(dd) l = generate_listing(d,fullfile(r,dd{i}),l); end %========================================================================== % FUNCTION extract_info %========================================================================== function svnprops = extract_info(f) %Extract Subversion properties ($Id$ tag) svnprops = struct('file',f, 'id',[], 'date','', 'md5',''); fp = fopen(f,'rt'); str = fread(fp,Inf,'*uchar'); fclose(fp); str = char(str(:)'); r = regexp(str,['\$Id: (?<file>\S+) (?<id>[0-9]+) (?<date>\S+) ' ... '(\S+Z) (?<author>\S+) \$'],'names'); if isempty(r) %fprintf('\n%s has no SVN Id.\n',f); else svnprops.file = r(1).file; svnprops.id = str2num(r(1).id); svnprops.date = r(1).date; [p,name,ext] = fileparts(f); if ~strmatch(svnprops.file,[name ext],'exact') warning('SVN Id for %s does not match filename.',f); end end if numel(r) > 1 %fprintf('\n%s has several SVN Ids.\n',f); end
github
lcnbeapp/beapp-master
spm_prep2sn.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/spm_prep2sn.m
7,345
utf_8
41b5744c0289cc48a8070de4648e82da
function [po,pin] = spm_prep2sn(p) % Convert the output from spm_preproc into an sn.mat % FORMAT [po,pin] = spm_prep2sn(p) % p - the results of spm_preproc % po - the output in a form that can be used by % spm_write_sn. % pin - the inverse transform in a form that can be % used by spm_write_sn. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id$ if ischar(p), p = load(p); end; VG = p.tpm; VF = p.image; [Y1,Y2,Y3] = create_def(p.Twarp,VF,VG(1),p.Affine); [Y1,Y2,Y3] = spm_invdef(Y1,Y2,Y3,VG(1).dim(1:3),eye(4),eye(4)); MT = procrustes(Y1,Y2,Y3,VG(1),VF.mat); d = size(p.Twarp); [Affine,Tr] = reparameterise(Y1,Y2,Y3,VG(1),VF.mat,MT,max(d(1:3)+2,[8 8 8])); flags = struct(... 'ngaus', p.ngaus,... 'mg', p.mg,... 'mn', p.mn,... 'vr', p.vr,... 'warpreg', p.warpreg,... 'warpco', p.warpco,... 'biasreg', p.biasreg,... 'biasfwhm', p.biasfwhm,... 'regtype', p.regtype,... 'fudge', p.fudge,... 'samp', p.samp,... 'msk', p.msk,... 'Affine', p.Affine,... 'Twarp', p.Twarp,... 'Tbias', p.Tbias,... 'thresh', p.thresh); if nargout==0, [pth,nam,ext] = fileparts(VF.fname); fnam = fullfile(pth,[nam '_seg_sn.mat']); if spm_matlab_version_chk('7') >= 0, save(fnam,'-V6','VG','VF','Tr','Affine','flags'); else save(fnam,'VG','VF','Tr','Affine','flags'); end; else po = struct(... 'VG', VG,... 'VF', VF,... 'Tr', Tr,... 'Affine', Affine,... 'flags', flags); end; if nargout>=2, % Parameterisation for the inverse pin = struct(... 'VG', p.image,... 'VF', p.tpm(1),... 'Tr', p.Twarp,... 'Affine', p.tpm(1).mat\p.Affine*p.image.mat,... 'flags', flags); % VG = p.image; % VF = p.tpm(1); % Tr = p.Twarp; % Affine = p.tpm(1).mat\p.Affine*p.image.mat; % save('junk_sn.mat','VG','VF','Tr','Affine'); end; return; %======================================================================= %======================================================================= function [Affine,Tr] = reparameterise(Y1,Y2,Y3,B,M2,MT,d2) % Take a deformation field and reparameterise in the same form % as used by the spatial normalisation routines of SPM d = [size(Y1) 1]; [x1,x2,o] = ndgrid(1:d(1),1:d(2),1); x3 = 1:d(3); Affine = M2\MT*B(1).mat; A = inv(Affine); B1 = spm_dctmtx(d(1),d2(1)); B2 = spm_dctmtx(d(2),d2(2)); B3 = spm_dctmtx(d(3),d2(3)); pd = prod(d2(1:3)); AA = eye(pd)*0.01; Ab = zeros(pd,3); spm_progress_bar('init',length(x3),['Reparameterising'],'Planes completed'); mx = [0 0 0]; for z=1:length(x3), y1 = double(Y1(:,:,z)); y2 = double(Y2(:,:,z)); y3 = double(Y3(:,:,z)); msk = isfinite(y1); w = double(msk); y1(~msk) = 0; y2(~msk) = 0; y3(~msk) = 0; z1 = A(1,1)*y1+A(1,2)*y2+A(1,3)*y3 + w.*(A(1,4) - x1); z2 = A(2,1)*y1+A(2,2)*y2+A(2,3)*y3 + w.*(A(2,4) - x2); z3 = A(3,1)*y1+A(3,2)*y2+A(3,3)*y3 + w *(A(3,4) - z ); b3 = B3(z,:)'; Ab(:,1) = Ab(:,1) + kron(b3,spm_krutil(z1,B1,B2,0)); Ab(:,2) = Ab(:,2) + kron(b3,spm_krutil(z2,B1,B2,0)); Ab(:,3) = Ab(:,3) + kron(b3,spm_krutil(z3,B1,B2,0)); AA = AA + kron(b3*b3',spm_krutil(w, B1,B2,1)); spm_progress_bar('set',z); end; spm_progress_bar('clear'); Tr = reshape(AA\Ab,[d2(1:3) 3]); drawnow; return; %======================================================================= %======================================================================= function MT = procrustes(Y1,Y2,Y3,B,M2) % Take a deformation field and determine the closest rigid-body % transform to match it, with weighing. % % Example Reference: % F. L. Bookstein (1997). "Landmark Methods for Forms Without % Landmarks: Morphometrics of Group Differences in Outline Shape" % Medical Image Analysis 1(3):225-243 M1 = B.mat; d = B.dim(1:3); [x1,x2,o] = ndgrid(1:d(1),1:d(2),1); x3 = 1:d(3); c1 = [0 0 0]; c2 = [0 0 0]; sw = 0; spm_progress_bar('init',length(x3),['Procrustes (1)'],'Planes completed'); for z=1:length(x3), y1 = double(Y1(:,:,z)); y2 = double(Y2(:,:,z)); y3 = double(Y3(:,:,z)); msk = find(isfinite(y1)); w = spm_sample_vol(B(1),x1(msk),x2(msk),o(msk)*z,0); swz = sum(w(:)); sw = sw+swz; c1 = c1 + [w'*[x1(msk) x2(msk)] swz*z ]; c2 = c2 + w'*[y1(msk) y2(msk) y3(msk)]; spm_progress_bar('set',z); end; spm_progress_bar('clear'); c1 = c1/sw; c2 = c2/sw; T1 = [eye(4,3) M1*[c1 1]']; T2 = [eye(4,3) M2*[c2 1]']; C = zeros(3); spm_progress_bar('init',length(x3),['Procrustes (2)'],'Planes completed'); for z=1:length(x3), y1 = double(Y1(:,:,z)); y2 = double(Y2(:,:,z)); y3 = double(Y3(:,:,z)); msk = find(isfinite(y1)); w = spm_sample_vol(B(1),x1(msk),x2(msk),o(msk)*z,0); C = C + [(x1(msk)-c1(1)).*w (x2(msk)-c1(2)).*w ( z-c1(3))*w ]' * ... [(y1(msk)-c2(1)) (y2(msk)-c2(2)) (y3(msk)-c2(3)) ]; spm_progress_bar('set',z); end; spm_progress_bar('clear'); [u,s,v] = svd(M1(1:3,1:3)*C*M2(1:3,1:3)'); R = eye(4); R(1:3,1:3) = v*u'; MT = T2*R*inv(T1); return; %======================================================================= %======================================================================= function [Y1,Y2,Y3] = create_def(T,VG,VF,Affine) % Generate a deformation field from its parameterisation. d2 = size(T); d = VG.dim(1:3); M = VF.mat\Affine*VG.mat; [x1,x2,o] = ndgrid(1:d(1),1:d(2),1); x3 = 1:d(3); B1 = spm_dctmtx(d(1),d2(1)); B2 = spm_dctmtx(d(2),d2(2)); B3 = spm_dctmtx(d(3),d2(3)); [pth,nam,ext] = fileparts(VG.fname); spm_progress_bar('init',length(x3),['Creating Def: ' nam],'Planes completed'); for z=1:length(x3), [y1,y2,y3] = defs(T,z,B1,B2,B3,x1,x2,x3,M); Y1(:,:,z) = single(y1); Y2(:,:,z) = single(y2); Y3(:,:,z) = single(y3); spm_progress_bar('set',z); end; spm_progress_bar('clear'); return; %======================================================================= %======================================================================= function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M) if ~isempty(sol), x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1)); y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2)); z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3)); else x1a = x0; y1a = y0; z1a = z0; end; x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4); y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4); z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4); return; %======================================================================= %======================================================================= function t = transf(B1,B2,B3,T) d2 = [size(T) 1]; t1 = reshape(T, d2(1)*d2(2),d2(3)); drawnow; t1 = reshape(t1*B3', d2(1), d2(2)); drawnow; t = B1*t1*B2'; return; %=======================================================================
github
lcnbeapp/beapp-master
cfg_getfile.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/matlabbatch/cfg_getfile.m
46,070
utf_8
3e6a6877315f1b08af13c88de5044295
function [t,sts] = cfg_getfile(varargin) % File selector % FORMAT [t,sts] = cfg_getfile(n,typ,mesg,sel,wd,filt,frames) % n - Number of files % A single value or a range. e.g. % 1 - Select one file % Inf - Select any number of files % [1 Inf] - Select 1 to Inf files % [0 1] - select 0 or 1 files % [10 12] - select from 10 to 12 files % typ - file type % 'any' - all files % 'batch' - SPM batch files (.m, .mat and XML) % 'dir' - select a directory % 'image' - Image files (".img" and ".nii") % Note that it gives the option to select % individual volumes of the images. % 'mat' - Matlab .mat files or .txt files (assumed to contain % ASCII representation of a 2D-numeric array) % 'mesh' - Mesh files (".gii" and ".mat") % 'nifti' - NIfTI files without the option to select frames % 'xml' - XML files % Other strings act as a filter to regexp. This means % that e.g. DCM*.mat files should have a typ of '^DCM.*\.mat$' % mesg - a prompt (default 'Select files...') % sel - list of already selected files % wd - Directory to start off in % filt - value for user-editable filter (default '.*') % frames - Image frame numbers to include (default '1') % % t - selected files % sts - status (1 means OK, 0 means window quit) % % FORMAT [t,ind] = cfg_getfile('Filter',files,typ,filt,frames) % filter the list of files (cell array) in the same way as the % GUI would do. There is an additional typ 'extimage' which will match % images with frame specifications, too. The 'frames' argument % is currently ignored, i.e. image files will not be filtered out if % their frame numbers do not match. % When filtering directory names, the filt argument will be applied to the % last directory in a path only. % t returns the filtered list (cell array), ind an index array, such that % t = files(ind). % % FORMAT cpath = cfg_getfile('CPath',path,cwd) % function to canonicalise paths: Prepends cwd to relative paths, processes % '..' & '.' directories embedded in path. % path - string matrix containing path name % cwd - current working directory [default '.'] % cpath - conditioned paths, in same format as input path argument % % FORMAT [files,dirs]=cfg_getfile('List',direc,filt) % Returns files matching the filter (filt) and directories within dire % direc - directory to search % filt - filter to select files with (see regexp) e.g. '^w.*\.img$' % files - files matching 'filt' in directory 'direc' % dirs - subdirectories of 'direc' % FORMAT [files,dirs]=cfg_getfile('ExtList',direc,filt,frames) % As above, but for selecting frames of 4D NIfTI files % frames - vector of frames to select (defaults to 1, if not % specified). If the frame number is Inf, all frames for the % matching images are listed. % FORMAT [files,dirs]=cfg_getfile('FPList',direc,filt) % FORMAT [files,dirs]=cfg_getfile('ExtFPList',direc,filt,frames) % As above, but returns files with full paths (i.e. prefixes direc to each) % FORMAT [files,dirs]=cfg_getfile('FPListRec',direc,filt) % FORMAT [files,dirs]=cfg_getfile('ExtFPListRec',direc,filt,frames) % As above, but returns files with full paths (i.e. prefixes direc to % each) and searches through sub directories recursively. % % FORMAT cfg_getfile('prevdirs',dir) % Add directory dir to list of previous directories. % FORMAT dirs=cfg_getfile('prevdirs') % Retrieve list of previous directories. % % This code is based on the file selection dialog in SPM5, with virtual % file handling turned off. %____________________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % % This code is part of a batch job configuration system for MATLAB. See % help matlabbatch % for a general overview. %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % John Ashburner and Volkmar Glauche % $Id: cfg_getfile.m 6251 2014-10-30 13:58:44Z volkmar $ t = {}; sts = false; if nargin > 0 && ischar(varargin{1}) switch lower(varargin{1}) case {'addvfiles', 'clearvfiles', 'vfiles'} cfg_message('matlabbatch:deprecated:vfiles', ... 'Trying to use deprecated ''%s'' call.', ... lower(varargin{1})); case 'cpath' cfg_message(nargchk(2,Inf,nargin,'struct')); t = cpath(varargin{2:end}); sts = true; case 'filter' filt = mk_filter(varargin{3:end}); t = varargin{2}; if numel(t) == 1 && isempty(t{1}) sts = 1; return; end; t1 = cell(size(t)); if any(strcmpi(varargin{3},{'dir','extdir'})) % only filter last directory in path for k = 1:numel(t) t{k} = cpath(t{k}); if t{k}(end) == filesep [p n] = fileparts(t{k}(1:end-1)); else [p n] = fileparts(t{k}); end if strcmpi(varargin{3},'extdir') t1{k} = [n filesep]; else t1{k} = n; end end else % only filter filenames, not paths for k = 1:numel(t) [p n e] = fileparts(t{k}); t1{k} = [n e]; end end [t1,sts1] = do_filter(t1,filt.ext); [t1,sts2] = do_filter(t1,filt.filt); sts = sts1(sts2); t = t(sts); case {'list', 'fplist', 'extlist', 'extfplist'} if nargin > 3 frames = varargin{4}; else frames = 1; % (ignored in listfiles if typ==any) end; if regexpi(varargin{1}, 'ext') % use frames descriptor typ = 'extimage'; else typ = 'any'; end filt = mk_filter(typ, varargin{3}, frames); [t sts] = listfiles(varargin{2}, filt); % (sts is subdirs here) sts = sts(~(strcmp(sts,'.')|strcmp(sts,'..'))); % remove '.' and '..' entries if regexpi(varargin{1}, 'fplist') % return full pathnames direc = cfg_getfile('cpath', varargin{2}); % remove trailing path separator if present direc = regexprep(direc, [filesep '$'], ''); if ~isempty(t) t = strcat(direc, filesep, t); end if nargout > 1 % subdirs too sts = cellfun(@(sts1)cpath(sts1, direc), sts, 'UniformOutput',false); end end case {'fplistrec', 'extfplistrec'} % list directory [f1 d1] = cfg_getfile(varargin{1}(1:end-3),varargin{2:end}); f2 = cell(size(d1)); d2 = cell(size(d1)); for k = 1:numel(d1) % recurse into sub directories [f2{k} d2{k}] = cfg_getfile(varargin{1}, d1{k}, ... varargin{3:end}); end t = vertcat(f1, f2{:}); if nargout > 1 sts = vertcat(d1, d2{:}); end case 'prevdirs', if nargin > 1 prevdirs(varargin{2}); end; if nargout > 0 || nargin == 1 t = prevdirs; sts = true; end; otherwise cfg_message('matlabbatch:usage','Inappropriate usage.'); end else [t,sts] = selector(varargin{:}); end %======================================================================= %======================================================================= function [t,ok] = selector(n,typ,mesg,already,wd,filt,frames,varargin) if nargin<1 || ~isnumeric(n) || numel(n) > 2 n = [0 Inf]; else if numel(n)==1, n = [n n]; end; if n(1)>n(2), n = n([2 1]); end; if ~isfinite(n(1)), n(1) = 0; end; end if nargin<2 || ~ischar(typ), typ = 'any'; end; if nargin<3 || ~(ischar(mesg) || iscellstr(mesg)) mesg = 'Select files...'; elseif iscellstr(mesg) mesg = char(mesg); end if nargin<4 || isempty(already) || (iscell(already) && isempty(already{1})) already = {}; else % Add folders of already selected files to prevdirs list pd1 = cellfun(@(a1)strcat(fileparts(a1),filesep), already, ... 'UniformOutput',false); prevdirs(pd1); end if nargin<5 || isempty(wd) || ~ischar(wd) if isempty(already) wd = pwd; else wd = fileparts(already{1}); if isempty(wd) wd = pwd; end end; end if nargin<6 || ~ischar(filt), filt = '.*'; end; if nargin<7 || ~(isnumeric(frames) || ischar(frames)) frames = '1'; elseif isnumeric(frames) frames = char(gencode_rvalue(frames(:)')); elseif ischar(frames) try ev = eval(frames); if ~isnumeric(ev) frames = '1'; end catch frames = '1'; end end ok = 0; t = ''; sfilt = mk_filter(typ,filt,eval(frames)); [col1,col2,col3,lf,bf] = colours; % delete old selector, if any fg = findobj(0,'Tag',mfilename); if ~isempty(fg) delete(fg); end % create figure fg = figure('IntegerHandle','off',... 'Tag',mfilename,... 'Name',mesg,... 'NumberTitle','off',... 'Units','Pixels',... 'MenuBar','none',... 'DefaultTextInterpreter','none',... 'DefaultUicontrolInterruptible','on',... 'Visible','off'); cfg_onscreen(fg); set(fg,'Visible','on'); sellines = min([max([n(2) numel(already)]), 4]); [pselp pcntp pfdp pdirp] = panelpositions(fg, sellines+1); uicontrol(fg,... 'style','text',... 'units','normalized',... 'position',posinpanel([0 sellines/(sellines+1) 1 1/(sellines+1)],pselp),... lf,... 'BackgroundColor',get(fg,'Color'),... 'ForegroundColor',col3,... 'HorizontalAlignment','left',... 'string',mesg,... 'tag','msg'); % Selected Files sel = uicontrol(fg,... 'style','listbox',... 'units','normalized',... 'Position',posinpanel([0 0 1 sellines/(sellines+1)],pselp),... lf,... 'Callback',@unselect,... 'tag','selected',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'Max',10000,... 'Min',0,... 'String',already,... 'Value',1); c0 = uicontextmenu('Parent',fg); set(sel,'uicontextmenu',c0); uimenu('Label','Unselect All', 'Parent',c0,'Callback',@unselect_all); % get cwidth for buttons tmp=uicontrol('style','text','string',repmat('X',[1,50]),bf,... 'units','normalized','visible','off'); fnp = get(tmp,'extent'); delete(tmp); cw = 3*fnp(3)/50; if strcmpi(typ,'image'), uicontrol(fg,... 'style','edit',... 'units','normalized',... 'Position',posinpanel([0.61 0 0.37 .45],pcntp),... 'Callback',@update_frames,... 'tag','frame',... lf,... 'BackgroundColor',col1,... 'String',frames,'UserData',eval(frames)); % 'ForegroundGolor',col3,... end; % Help uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',posinpanel([0.02 .5 cw .45],pcntp),... bf,... 'Callback',@heelp,... 'tag','?',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','?',... 'ToolTipString','Show Help'); uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',posinpanel([0.03+cw .5 cw .45],pcntp),... bf,... 'Callback',@editwin,... 'tag','Ed',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Ed',... 'ToolTipString','Edit Selected Files'); uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',posinpanel([0.04+2*cw .5 cw .45],pcntp),... bf,... 'Callback',@select_rec,... 'tag','Rec',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Rec',... 'ToolTipString','Recursively Select Files with Current Filter'); % Done dne = uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',posinpanel([0.05+3*cw .5 0.45-3*cw .45],pcntp),... bf,... 'Callback',@(h,e)delete(h),... 'tag','D',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Done',... 'Enable','off',... 'DeleteFcn',@null); if numel(already)>=n(1) && numel(already)<=n(2), set(dne,'Enable','on'); end; % Filter Button uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',posinpanel([0.51 .5 0.1 .45],pcntp),... bf,... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'Callback',@clearfilt,... 'String','Filt'); % Filter uicontrol(fg,... 'style','edit',... 'units','normalized',... 'Position',posinpanel([0.61 .5 0.37 .45],pcntp),... 'ForegroundColor',col3,... 'BackgroundColor',col1,... lf,... 'Callback',@(ob,ev)update(ob),... 'tag','regexp',... 'String',filt,... 'UserData',sfilt); % Directories db = uicontrol(fg,... 'style','listbox',... 'units','normalized',... 'Position',posinpanel([0.02 0 0.47 1],pfdp),... lf,... 'Callback',@click_dir_box,... 'tag','dirs',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'Max',1,... 'Min',0,... 'String','',... 'UserData',wd,... 'Value',1); % Files tmp = uicontrol(fg,... 'style','listbox',... 'units','normalized',... 'Position',posinpanel([0.51 0 0.47 1],pfdp),... lf,... 'Callback',@click_file_box,... 'tag','files',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'UserData',n,... 'Max',10240,... 'Min',0,... 'String','',... 'Value',1); c0 = uicontextmenu('Parent',fg); set(tmp,'uicontextmenu',c0); uimenu('Label','Select All', 'Parent',c0,'Callback',@select_all); % Drives if strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64'), % get fh for lists tmp=uicontrol('style','text','string','X',lf,... 'units','normalized','visible','off'); fnp = get(tmp,'extent'); delete(tmp); fh = 2*fnp(4); % Heuristics: why do we need 2* sz = get(db,'Position'); sz(4) = sz(4)-fh-2*0.01; set(db,'Position',sz); uicontrol(fg,... 'style','text',... 'units','normalized',... 'Position',posinpanel([0.02 1-fh-0.01 0.10 fh],pfdp),... 'HorizontalAlignment','left',... lf,... 'BackgroundColor',get(fg,'Color'),... 'ForegroundColor',col3,... 'String','Drive'); uicontrol(fg,... 'style','popupmenu',... 'units','normalized',... 'Position',posinpanel([0.12 1-fh-0.01 0.37 fh],pfdp),... lf,... 'Callback',@setdrive,... 'tag','drive',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'String',listdrives(false),... 'Value',1); end; [pd,vl] = prevdirs([wd filesep]); % Previous dirs uicontrol(fg,... 'style','popupmenu',... 'units','normalized',... 'Position',posinpanel([0.12 .05 0.86 .95*1/3],pdirp),... lf,... 'Callback',@click_dir_list,... 'tag','previous',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'String',pd,... 'Value',vl); uicontrol(fg,... 'style','text',... 'units','normalized',... 'Position',posinpanel([0.02 0 0.10 .95*1/3],pdirp),... 'HorizontalAlignment','left',... lf,... 'BackgroundColor',get(fg,'Color'),... 'ForegroundColor',col3,... 'String','Prev'); % Parent dirs uicontrol(fg,... 'style','popupmenu',... 'units','normalized',... 'Position',posinpanel([0.12 1/3+.05 0.86 .95*1/3],pdirp),... lf,... 'Callback',@click_dir_list,... 'tag','pardirs',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'String',pardirs(wd)); uicontrol(fg,... 'style','text',... 'units','normalized',... 'Position',posinpanel([0.02 1/3 0.10 .95*1/3],pdirp),... 'HorizontalAlignment','left',... lf,... 'BackgroundColor',get(fg,'Color'),... 'ForegroundColor',col3,... 'String','Up'); % Directory uicontrol(fg,... 'style','edit',... 'units','normalized',... 'Position',posinpanel([0.12 2/3 0.86 .95*1/3],pdirp),... lf,... 'Callback',@edit_dir,... 'tag','edit',... 'BackgroundColor',col1,... 'ForegroundColor',col3,... 'String',''); uicontrol(fg,... 'style','text',... 'units','normalized',... 'Position',posinpanel([0.02 2/3 0.10 .95*1/3],pdirp),... 'HorizontalAlignment','left',... lf,... 'BackgroundColor',get(fg,'Color'),... 'ForegroundColor',col3,... 'String','Dir'); resize_fun(fg); set(fg, 'ResizeFcn',@resize_fun); update(sel,wd) set(fg,'windowstyle', 'modal'); waitfor(dne); drawnow; if ishandle(sel), t = get(sel,'String'); if isempty(t) t = {''}; elseif sfilt.code == -1 % canonicalise non-empty folder selection t = cellfun(@(t1)cpath(t1, pwd), t, 'UniformOutput',false); end; ok = 1; end; if ishandle(fg), delete(fg); end; drawnow; return; %======================================================================= %======================================================================= function apos = posinpanel(rpos,ppos) % Compute absolute positions based on panel position and relative % position apos = [ppos(1:2)+ppos(3:4).*rpos(1:2) ppos(3:4).*rpos(3:4)]; %======================================================================= %======================================================================= function [pselp, pcntp, pfdp, pdirp] = panelpositions(fg, sellines) if nargin == 1 na = numel(get(findobj(fg,'Tag','selected'),'String')); n = get(findobj(fg,'Tag','files'),'Userdata'); sellines = min([max([n(2) na]), 4]); end lf = cfg_get_defaults('cfg_ui.lfont'); bf = cfg_get_defaults('cfg_ui.bfont'); % Create dummy text to estimate character height t=uicontrol('style','text','string','Xg','units','normalized','visible','off',lf); lfh = 1.05*get(t,'extent'); delete(t) t=uicontrol('style','text','string','Xg','units','normalized','visible','off',bf); bfh = 1.05*get(t,'extent'); delete(t) % panel heights % 3 lines for directory, parent and prev directory list % variable height for dir/file navigation % 2 lines for buttons, filter etc % sellines plus scrollbar for selected files pselh = sellines*lfh(4) + 1.2*lfh(4); pselp = [0 0 1 pselh]; pcnth = 2*bfh(4); pcntp = [0 pselh 1 pcnth]; pdirh = 3*lfh(4); pdirp = [0 1-pdirh 1 pdirh]; pfdh = 1-(pselh+pcnth+pdirh); pfdp = [0 pselh+pcnth 1 pfdh]; %======================================================================= %======================================================================= function null(varargin) %======================================================================= %======================================================================= function omsg = msg(ob,str) ob = sib(ob,'msg'); omsg = get(ob,'String'); set(ob,'String',str); if nargin>=3, set(ob,'ForegroundColor',[1 0 0],'FontWeight','bold'); else set(ob,'ForegroundColor',[0 0 0],'FontWeight','normal'); end; drawnow; return; %======================================================================= %======================================================================= function setdrive(ob,varargin) st = get(ob,'String'); vl = get(ob,'Value'); update(ob,st{vl}); return; %======================================================================= %======================================================================= function resize_fun(fg,varargin) % do nothing return; [pselp pcntp pfdp pdirp] = panelpositions(fg); set(findobj(fg,'Tag','msg'), 'Position',pselp); set(findobj(fg,'Tag','pcnt'), 'Position',pcntp); set(findobj(fg,'Tag','pfd'), 'Position',pfdp); set(findobj(fg,'Tag','pdir'), 'Position',pdirp); return; %======================================================================= %======================================================================= function [d,mch] = prevdirs(d) persistent pd if ~iscell(pd), pd = {}; end; if nargin == 0 d = pd; else if ~iscell(d) d = cellstr(d); end d = unique(d(:)); mch = cellfun(@(d1)find(strcmp(d1,pd)), d, 'UniformOutput',false); sel = cellfun(@isempty, mch); npd = numel(pd); pd = [pd(:);d(sel)]; mch = [mch{~sel} npd+(1:nnz(sel))]; d = pd; end return; %======================================================================= %======================================================================= function pd = pardirs(wd) if ispc fs = '\\'; else fs = filesep; end pd1 = textscan(wd,'%s','delimiter',fs,'MultipleDelimsAsOne',1); if ispc pd = cell(size(pd1{1})); pd{end} = pd1{1}{1}; for k = 2:numel(pd1{1}) pd{end-k+1} = fullfile(pd1{1}{1:k},filesep); end else pd = cell(numel(pd1{1})+1,1); pd{end} = filesep; for k = 1:numel(pd1{1}) pd{end-k} = fullfile(filesep,pd1{1}{1:k},filesep); end end %======================================================================= %======================================================================= function clearfilt(ob,varargin) set(sib(ob,'regexp'),'String','.*'); update(ob); return; %======================================================================= %======================================================================= function click_dir_list(ob,varargin) vl = get(ob,'Value'); ls = get(ob,'String'); update(ob,deblank(ls{vl})); return; %======================================================================= %======================================================================= function edit_dir(ob,varargin) update(ob,get(ob,'String')); return; %======================================================================= %======================================================================= function c = get_current_char(lb) fg = sib(lb, mfilename); c = get(fg, 'CurrentCharacter'); if ~isempty(c) % reset CurrentCharacter set(fg, 'CurrentCharacter', char(13)); end %======================================================================= %======================================================================= function click_dir_box(lb,varargin) c = get_current_char(lb); if isempty(c) || isequal(c,char(13)) vl = get(lb,'Value'); str = get(lb,'String'); pd = get(sib(lb,'edit'),'String'); while ~isempty(pd) && strcmp(pd(end),filesep) pd=pd(1:end-1); % Remove any trailing fileseps end sel = str{vl}; if strcmp(sel,'..'), % Parent directory [dr odr] = fileparts(pd); elseif strcmp(sel,'.'), % Current directory dr = pd; odr = ''; else dr = fullfile(pd,sel); odr = ''; end; update(lb,dr); if ~isempty(odr) % If moving up one level, try to set focus on previously visited % directory cdrs = get(lb, 'String'); dind = find(strcmp(odr, cdrs)); if ~isempty(dind) set(lb, 'Value',dind(1)); end end end return; %======================================================================= %======================================================================= function re = getfilt(ob) ob = sib(ob,'regexp'); ud = get(ob,'UserData'); re = struct('code',ud.code,... 'frames',get(sib(ob,'frame'),'UserData'),... 'ext',{ud.ext},... 'filt',{{get(sib(ob,'regexp'),'String')}}); return; %======================================================================= %======================================================================= function update(lb,dr) lb = sib(lb,'dirs'); if nargin<2 || isempty(dr) || ~ischar(dr) dr = get(lb,'UserData'); end; if ~(strcmpi(computer,'PCWIN') || strcmpi(computer,'PCWIN64')) dr = [filesep dr filesep]; else dr = [dr filesep]; end; dr(strfind(dr,[filesep filesep])) = []; [f,d] = listfiles(dr,getfilt(lb)); if isempty(d), dr = get(lb,'UserData'); [f,d] = listfiles(dr,getfilt(lb)); else set(lb,'UserData',dr); end; set(lb,'Value',1,'String',d); set(sib(lb,'files'),'Value',1,'String',f); set(sib(lb,'pardirs'),'String',pardirs(dr),'Value',1); [ls,mch] = prevdirs(dr); set(sib(lb,'previous'),'String',ls,'Value',mch); set(sib(lb,'edit'),'String',dr); if numel(dr)>1 && dr(2)==':', str = char(get(sib(lb,'drive'),'String')); mch = find(lower(str(:,1))==lower(dr(1))); if ~isempty(mch), set(sib(lb,'drive'),'Value',mch); end; end; return; %======================================================================= %======================================================================= function update_frames(lb,varargin) str = get(lb,'String'); %r = get(lb,'UserData'); try r = eval(['[',str,']']); catch msg(lb,['Failed to evaluate "' str '".'],'r'); beep; return; end; if ~isnumeric(r), msg(lb,['Expression non-numeric "' str '".'],'r'); beep; else set(lb,'UserData',r); msg(lb,''); update(lb); end; %======================================================================= %======================================================================= function select_all(ob,varargin) lb = sib(ob,'files'); set(lb,'Value',1:numel(get(lb,'String'))); drawnow; click_file_box(lb); return; %======================================================================= %======================================================================= function click_file_box(lb,varargin) c = get_current_char(lb); if isempty(c) || isequal(c, char(13)) vlo = get(lb,'Value'); if isempty(vlo), msg(lb,'Nothing selected'); return; end; lim = get(lb,'UserData'); ob = sib(lb,'selected'); str3 = get(ob,'String'); str = get(lb,'String'); lim1 = min([max([lim(2)-numel(str3),0]),numel(vlo)]); if lim1==0, msg(lb,['Selected ' num2str(size(str3,1)) '/' num2str(lim(2)) ' already.']); beep; set(sib(lb,'D'),'Enable','on'); return; end; vl = vlo(1:lim1); msk = false(size(str,1),1); if vl>0, msk(vl) = true; else msk = []; end; str1 = str( msk); str2 = str(~msk); dr = get(sib(lb,'edit'), 'String'); str1 = strcat(dr, str1); set(lb,'Value',min([vl(1),numel(str2)]),'String',str2); r = (1:numel(str1))+numel(str3); str3 = [str3(:);str1(:)]; set(ob,'String',str3,'Value',r); if numel(vlo)>lim1, msg(lb,['Retained ' num2str(lim1) '/' num2str(numel(vlo))... ' of selection.']); beep; elseif isfinite(lim(2)) if lim(1)==lim(2), msg(lb,['Selected ' num2str(numel(str3)) '/' num2str(lim(2)) ' files.']); else msg(lb,['Selected ' num2str(numel(str3)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']); end; else if size(str3,1) == 1, ss = ''; else ss = 's'; end; msg(lb,['Selected ' num2str(numel(str3)) ' file' ss '.']); end; if ~isfinite(lim(1)) || numel(str3)>=lim(1), set(sib(lb,'D'),'Enable','on'); end; end return; %======================================================================= %======================================================================= function obj = sib(ob,tag) persistent fg; if isempty(fg) || ~ishandle(fg) fg = findobj(0,'Tag',mfilename); end obj = findobj(fg,'Tag',tag); return; %if isempty(obj), % cfg_message('matlabbatch:usage',['Can''t find object with tag "' tag '".']); %elseif length(obj)>1, % cfg_message('matlabbatch:usage',['Found ' num2str(length(obj)) ' objects with tag "' tag '".']); %end; %return; %======================================================================= %======================================================================= function unselect(lb,varargin) vl = get(lb,'Value'); if isempty(vl), return; end; str = get(lb,'String'); msk = true(numel(str),1); if vl~=0, msk(vl) = false; end; str2 = str(msk); set(lb,'Value',min(vl(1),numel(str2)),'String',str2); lim = get(sib(lb,'files'),'UserData'); if numel(str2)>= lim(1) && numel(str2)<= lim(2), set(sib(lb,'D'),'Enable','on'); else set(sib(lb,'D'),'Enable','off'); end; if numel(str2) == 1, ss1 = ''; else ss1 = 's'; end; %msg(lb,[num2str(size(str2,1)) ' file' ss ' remaining.']); if numel(vl) == 1, ss = ''; else ss = 's'; end; msg(lb,['Unselected ' num2str(numel(vl)) ' file' ss '. ' ... num2str(numel(str2)) ' file' ss1 ' remaining.']); return; %======================================================================= %======================================================================= function unselect_all(ob,varargin) lb = sib(ob,'selected'); set(lb,'Value',[],'String',{},'ListBoxTop',1); msg(lb,'Unselected all files.'); lim = get(sib(lb,'files'),'UserData'); if lim(1)>0, set(sib(lb,'D'),'Enable','off'); end; return; %======================================================================= %======================================================================= function [f,d] = listfiles(dr,filt) try ob = sib(gco,'msg'); domsg = ~isempty(ob); catch domsg = false; end if domsg omsg = msg(ob,'Listing directory...'); end if nargin<2, filt = ''; end; if nargin<1, dr = '.'; end; de = dir(dr); if ~isempty(de), d = {de([de.isdir]).name}; if ~any(strcmp(d, '.')) d = [{'.'}, d(:)']; end; if filt.code~=-1, f = {de(~[de.isdir]).name}; else % f = d(3:end); f = d; end; else d = {'.','..'}; f = {}; end; if domsg msg(ob,['Filtering ' num2str(numel(f)) ' files...']); end f = do_filter(f,filt.ext); f = do_filter(f,filt.filt); ii = cell(1,numel(f)); if filt.code==1 && (numel(filt.frames)~=1 || filt.frames(1)~=1), if domsg msg(ob,['Reading headers of ' num2str(numel(f)) ' images...']); end for i=1:numel(f), try ni = nifti(fullfile(dr,f{i})); dm = [ni.dat.dim 1 1 1 1 1]; d4 = (1:dm(4))'; catch d4 = 1; end; if all(isfinite(filt.frames)) msk = false(size(filt.frames)); for j=1:numel(msk), msk(j) = any(d4==filt.frames(j)); end; ii{i} = filt.frames(msk); else ii{i} = d4; end; end elseif filt.code==1 && (numel(filt.frames)==1 && filt.frames(1)==1), for i=1:numel(f), ii{i} = 1; end; end; if domsg msg(ob,['Listing ' num2str(numel(f)) ' files...']); end [f,ind] = sortrows(f(:)); ii = ii(ind); msk = true(1,numel(f)); for i=2:numel(f), if strcmp(f{i-1},f{i}), if filt.code==1, tmp = sort([ii{i}(:) ; ii{i-1}(:)]); tmp(~diff(tmp,1)) = []; ii{i} = tmp; end; msk(i-1) = false; end; end; f = f(msk); if filt.code==1, % Combine filename and frame number(s) ii = ii(msk); nii = cellfun(@numel, ii); c = cell(sum(nii),1); fi = cell(numel(f),1); for k = 1:numel(fi) fi{k} = k*ones(1,nii(k)); end ii = [ii{:}]; fi = [fi{:}]; for i=1:numel(c), c{i} = sprintf('%s,%d', f{fi(i)}, ii(i)); end; f = c; elseif filt.code==-1, fs = filesep; for i=1:numel(f), f{i} = [f{i} fs]; end; end; f = f(:); d = unique(d(:)); if domsg msg(ob,omsg); end return; %======================================================================= %======================================================================= function [f,ind] = do_filter(f,filt) t2 = false(numel(f),1); filt_or = sprintf('(%s)|',filt{:}); t1 = regexp(f,filt_or(1:end-1)); if numel(f)==1 && ~iscell(t1), t1 = {t1}; end; for i=1:numel(t1), t2(i) = ~isempty(t1{i}); end; ind = find(t2); f = f(t2); return; %======================================================================= %======================================================================= function heelp(ob,varargin) [col1,col2,col3,fn] = colours; fg = sib(ob,mfilename); t = uicontrol(fg,... 'style','listbox',... 'units','normalized',... 'Position',[0.01 0.01 0.98 0.98],... fn,... 'BackgroundColor',col2,... 'ForegroundColor',col3,... 'Max',0,... 'Min',0,... 'tag','HelpWin',... 'String',' '); c0 = uicontextmenu('Parent',fg); set(t,'uicontextmenu',c0); uimenu('Label','Done', 'Parent',c0,'Callback',@helpclear); str = cfg_justify(t, {[... 'File Selection help. You can return to selecting files via the right mouse button (the "Done" option). '],... '',[... 'The panel at the bottom shows files that are already selected. ',... 'Clicking a selected file will un-select it. To un-select several, you can ',... 'drag the cursor over the files, and they will be gone on release. ',... 'You can use the right mouse button to un-select everything.'],... '',[... 'Directories are navigated by editing the name of the current directory (where it says "Dir"), ',... 'by going to one of the previously entered directories ("Prev"), ',... 'by going to one of the parent directories ("Up") or by navigating around ',... 'the parent or subdirectories listed in the left side panel.'],... '',[... 'Files matching the filter ("Filt") are shown in the panel on the right. ',... 'These can be selected by clicking or dragging. Use the right mouse button if ',... 'you would like to select all files. Note that when selected, the files disappear ',... 'from this panel. They can be made to reappear by re-specifying the directory ',... 'or the filter. '],... '',[... 'Both directory and file lists can also be browsed by typing the leading ',... 'character(s) of a directory or file name.'],... '',[... 'Note that the syntax of the filter differs from that used by most other file selectors. ',... 'The filter works using so called ''regular expressions''. Details can be found in the ',... 'MATLAB help text on ''regexp''. ',... 'The following is a list of symbols with special meaning for filtering the filenames:'],... ' ^ start of string',... ' $ end of string',... ' . any character',... ' \ quote next character',... ' * match zero or more',... ' + match one or more',... ' ? match zero or one, or match minimally',... ' {} match a range of occurrances',... ' [] set of characters',... ' [^] exclude a set of characters',... ' () group subexpression',... ' \w match word [a-z_A-Z0-9]',... ' \W not a word [^a-z_A-Z0-9]',... ' \d match digit [0-9]',... ' \D not a digit [^0-9]',... ' \s match white space [ \t\r\n\f]',... ' \S not a white space [^ \t\r\n\f]',... ' \<WORD\> exact word match',... '',[... 'Individual time frames of image files can also be selected. The frame filter ',... 'allows specified frames to be shown, which is useful for image files that ',... 'contain multiple time points. If your images are only single time point, then ',... 'reading all the image headers can be avoided by specifying a frame filter of "1". ',... 'The filter should contain a list of integers indicating the frames to be used. ',... 'This can be generated by e.g. "1:100", or "1:2:100".'],... '',[... 'The recursive selection button (Rec) allows files matching the regular expression to ',... 'be recursively selected. If there are many directories to search, then this can take ',... 'a while to run.'],... '',[... 'There is also an edit button (Ed), which allows you to edit your selection of files. ',... 'When you are done, then use the menu-button of your mouse to either cancel or accept your changes.'],''}); set(t,'String',str); return; %======================================================================= %======================================================================= function helpclear(ob,varargin) ob = get(ob,'Parent'); ob = get(ob,'Parent'); ob = findobj(ob,'Tag','HelpWin'); delete(ob); %======================================================================= %======================================================================= function t = cpath(t,d) switch filesep, case '/', mch = '^/'; fs = '/'; fs1 = '/'; case '\', mch = '^.:\\'; fs = '\'; fs1 = '\\'; otherwise; cfg_message('matlabbatch:usage','What is this filesystem?'); end if isempty(regexp(t,mch,'once')), if (nargin<2)||isempty(d), d = pwd; end; t = [d fs t]; end; % Replace occurences of '/./' by '/' (problems with e.g. /././././././') re = [fs1 '\.' fs1]; while ~isempty(regexp(t,re, 'once' )), t = regexprep(t,re,fs); end; t = regexprep(t,[fs1 '\.' '$'], fs); % Replace occurences of '/abc/../' by '/' re = [fs1 '[^' fs1 ']+' fs1 '\.\.' fs1]; while ~isempty(regexp(t,re, 'once' )), t = regexprep(t,re,fs,'once'); end; t = regexprep(t,[fs1 '[^' fs1 ']+' fs1 '\.\.' '$'],fs,'once'); % Replace '//' t = regexprep(t,[fs1 '+'], fs); %======================================================================= %======================================================================= function editwin(ob,varargin) [col1,col2,col3,lf,bf] = colours; fg = gcbf; lb = sib(ob,'selected'); str = get(lb,'String'); ac = allchild(fg); acv = get(ac,'Visible'); h = uicontrol(fg,... 'Style','Edit',... 'units','normalized',... 'String',str,... lf,... 'Max',2,... 'Tag','EditWindow',... 'HorizontalAlignment','Left',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'Position',[0.01 0.08 0.98 0.9],... 'Userdata',struct('ac',{ac},'acv',{acv})); ea = uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',[.01 .01,.32,.07],... bf,... 'Callback',@editdone,... 'tag','EditWindowAccept',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Accept'); ee = uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',[.34 .01,.32,.07],... bf,... 'Callback',@editeval,... 'tag','EditWindowEval',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Eval'); ec = uicontrol(fg,... 'Style','pushbutton',... 'units','normalized',... 'Position',[.67 .01,.32,.07],... bf,... 'Callback',@editclear,... 'tag','EditWindowCancel',... 'ForegroundColor',col3,... 'BackgroundColor',col1,... 'String','Cancel'); set(ac,'visible','off'); %======================================================================= %======================================================================= function editeval(ob,varargin) ob = get(ob, 'Parent'); ob = sib(ob, 'EditWindow'); str = get(ob, 'String'); if ~isempty(str) [out,sts] = cfg_eval_valedit(char(str)); if sts && (iscellstr(out) || ischar(out)) set(ob, 'String', cellstr(out)); else fgc = get(ob, 'ForegroundColor'); set(ob, 'ForegroundColor', 'red'); pause(1); set(ob, 'ForegroundColor', fgc); end end %======================================================================= %======================================================================= function editdone(ob,varargin) ob = get(ob,'Parent'); ob = sib(ob,'EditWindow'); str = cellstr(get(ob,'String')); if isempty(str) || isempty(str{1}) str = {}; else dstr = deblank(str); if ~isequal(str, dstr) c = questdlg(['Some of the filenames contain trailing blanks. This may ' ... 'be due to copy/paste of strings between MATLAB and the ' ... 'edit window. Do you want to remove any trailing blanks?'], ... 'Trailing Blanks in Filenames', ... 'Remove', 'Keep', 'Remove'); switch lower(c) case 'remove' str = dstr; end end filt = getfilt(ob); if filt.code >= 0 % filter files, but not dirs [p,n,e] = cellfun(@fileparts, str, 'uniformoutput',false); fstr = strcat(n, e); [fstr1,fsel] = do_filter(fstr, filt.ext); str = str(fsel); end end lim = get(sib(ob,'files'),'UserData'); if numel(str)>lim(2), msg(ob,['Retained ' num2str(lim(2)) ' of the ' num2str(numel(str)) ' files.']); beep; str = str(1:lim(2)); elseif isfinite(lim(2)), if lim(1)==lim(2), msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(2)) ' files.']); else msg(ob,['Selected ' num2str(numel(str)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']); end; else if numel(str) == 1, ss = ''; else ss = 's'; end; msg(ob,['Specified ' num2str(numel(str)) ' file' ss '.']); end; if ~isfinite(lim(1)) || numel(str)>=lim(1), set(sib(ob,'D'),'Enable','on'); else set(sib(ob,'D'),'Enable','off'); end; set(sib(ob,'selected'),'String',str,'Value',[]); acs = get(ob,'Userdata'); fg = gcbf; delete(findobj(fg,'-regexp','Tag','^EditWindow.*')); set(acs.ac,{'Visible'},acs.acv); %======================================================================= %======================================================================= function editclear(ob,varargin) fg = gcbf; acs = get(findobj(fg,'Tag','EditWindow'),'Userdata'); delete(findobj(fg,'-regexp','Tag','^EditWindow.*')); set(acs.ac,{'Visible'},acs.acv); %======================================================================= %======================================================================= function [c1,c2,c3,lf,bf] = colours c1 = [1 1 1]; c2 = [1 1 1]; c3 = [0 0 0]; lf = cfg_get_defaults('cfg_ui.lfont'); bf = cfg_get_defaults('cfg_ui.bfont'); if isempty(lf) lf = struct('FontName',get(0,'FixedWidthFontName'), ... 'FontWeight','normal', ... 'FontAngle','normal', ... 'FontSize',14, ... 'FontUnits','points'); end if isempty(bf) bf = struct('FontName',get(0,'FixedWidthFontName'), ... 'FontWeight','normal', ... 'FontAngle','normal', ... 'FontSize',14, ... 'FontUnits','points'); end %======================================================================= %======================================================================= function select_rec(ob, varargin) start = get(sib(ob,'edit'),'String'); filt = get(sib(ob,'regexp'),'Userdata'); filt.filt = {get(sib(ob,'regexp'), 'String')}; fob = sib(ob,'frame'); if ~isempty(fob) filt.frames = get(fob,'Userdata'); else filt.frames = []; end; ptr = get(gcbf,'Pointer'); try set(gcbf,'Pointer','watch'); sel = select_rec1(start,filt); catch set(gcbf,'Pointer',ptr); sel = {}; end; set(gcbf,'Pointer',ptr); already= get(sib(ob,'selected'),'String'); fb = sib(ob,'files'); lim = get(fb,'Userdata'); limsel = min(lim(2)-size(already,1),size(sel,1)); set(sib(ob,'selected'),'String',[already(:);sel(1:limsel)],'Value',[]); msg(ob,sprintf('Added %d/%d matching files to selection.', limsel, size(sel,1))); if ~isfinite(lim(1)) || size(sel,1)>=lim(1), set(sib(ob,'D'),'Enable','on'); else set(sib(ob,'D'),'Enable','off'); end; %======================================================================= %======================================================================= function sel=select_rec1(cdir,filt) sel={}; [t,d] = listfiles(cdir,filt); if ~isempty(t) sel = strcat([cdir,filesep],t); end; for k = 1:numel(d) if ~any(strcmp(d{k},{'.','..'})) sel1 = select_rec1(fullfile(cdir,d{k}),filt); sel = [sel(:); sel1(:)]; end; end; %======================================================================= %======================================================================= function sfilt=mk_filter(typ,filt,frames) if nargin<3, frames = 1; end; if nargin<2, filt = '.*'; end; if nargin<1, typ = 'any'; end; switch lower(typ), case {'any','*'}, code = 0; ext = {'.*'}; case {'image'}, code = 1; ext = {'.*\.nii(,\d+){0,2}$','.*\.img(,\d+){0,2}$','.*\.NII(,\d+){0,2}$','.*\.IMG(,\d+){0,2}$'}; case {'mesh'}, code = 0; ext = {'.*\.gii$','.*\.GII$','.*\.mat$','.*\.MAT$'}; case {'nifti'}, code = 0; ext = {'.*\.nii$','.*\.img$','.*\.NII$','.*\.IMG$'}; case {'gifti'}, code = 0; ext = {'.*\.gii$','.*\.GII$'}; case {'extimage'}, code = 1; ext = {'.*\.nii(,[0-9]*){0,2}$',... '.*\.img(,[0-9]*){0,2}$',... '.*\.NII(,[0-9]*){0,2}$',... '.*\.IMG(,[0-9]*){0,2}$'}; case {'xml'}, code = 0; ext = {'.*\.xml$','.*\.XML$'}; case {'mat'}, code = 0; ext = {'.*\.mat$','.*\.MAT$','.*\.txt','.*\.TXT'}; case {'batch'}, code = 0; ext = {'.*\.mat$','.*\.MAT$','.*\.m$','.*\.M$','.*\.xml$','.*\.XML$'}; case {'dir'}, code =-1; ext = {'.*'}; case {'extdir'}, code =-1; ext = {['.*' filesep '$']}; otherwise, code = 0; ext = {typ}; end; sfilt = struct('code',code,'frames',frames,'ext',{ext},... 'filt',{{filt}}); %======================================================================= %======================================================================= function drivestr = listdrives(reread) persistent mydrivestr; if isempty(mydrivestr) || reread driveLett = strcat(cellstr(char(('C':'Z')')), ':'); dsel = false(size(driveLett)); for i=1:numel(driveLett) dsel(i) = exist([driveLett{i} '\'],'dir')~=0; end mydrivestr = driveLett(dsel); end; drivestr = mydrivestr; %======================================================================= %=======================================================================
github
lcnbeapp/beapp-master
coor2D.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@meeg/coor2D.m
4,007
utf_8
f94070275bb14e35788e110abf929115
function [res, plotind] = coor2D(this, ind, val, mindist) % returns x and y coordinates of channels in 2D plane % FORMAT coor2D(this) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak, Laurence Hunt % $Id: coor2D.m 4372 2011-06-21 21:26:46Z vladimir $ megind = strmatch('MEG', chantype(this)); eegind = strmatch('EEG', chantype(this), 'exact'); otherind = setdiff(1:nchannels(this), [megind; eegind]); if nargin==1 || isempty(ind) if nargin<3 || (size(val, 2)<nchannels(this)) if ~isempty(megind) ind = megind; elseif ~isempty(eegind) ind = eegind; else ind = 1:nchannels(this); end else ind = 1:nchannels(this); end elseif ischar(ind) switch upper(ind) case 'MEG' ind = megind; case 'EEG' ind = eegind; otherwise ind = otherind; end end if nargin < 3 || isempty(val) if ~isempty(intersect(ind, megind)) if ~any(cellfun('isempty', {this.channels(megind).X_plot2D})) meg_xy = [this.channels(megind).X_plot2D; this.channels(megind).Y_plot2D]; elseif all(cellfun('isempty', {this.channels(megind).X_plot2D})) meg_xy = grid(length(megind)); else error('Either all or none of MEG channels should have 2D coordinates defined.'); end end if ~isempty(intersect(ind, eegind)) if ~any(cellfun('isempty', {this.channels(eegind).X_plot2D})) eeg_xy = [this.channels(eegind).X_plot2D; this.channels(eegind).Y_plot2D]; elseif all(cellfun('isempty', {this.channels(eegind).X_plot2D})) eeg_xy = grid(length(eegind)); else error('Either all or none of EEG channels should have 2D coordinates defined.'); end end if ~isempty(intersect(ind, otherind)) other_xy = grid(length(otherind)); end xy = zeros(2, length(ind)); plotind = zeros(1, length(ind)); for i = 1:length(ind) [found, loc] = ismember(ind(i), megind); if found xy(:, i) = meg_xy(:, loc); plotind(i) = 1; else [found, loc] = ismember(ind(i), eegind); if found xy(:, i) = eeg_xy(:, loc); plotind(i) = 2; else [found, loc] = ismember(ind(i), otherind); if found xy(:, i) = other_xy(:, loc); plotind(i) = 3; end end end end if nargin > 3 && ~isempty(mindist) xy = shiftxy(xy,mindist); end res = xy; else this = getset(this, 'channels', 'X_plot2D', ind, val(1, :)); this = getset(this, 'channels', 'Y_plot2D', ind, val(2, :)); res = this; end function xy = grid(n) ncol = ceil(sqrt(n)); x = 0:(1/(ncol+1)):1; x = 0.9*x+0.05; x = x(2:(end-1)); y = fliplr(x); [X, Y] = meshgrid(x, y); xy = [X(1:n); Y(1:n)]; function xy = shiftxy(xy,mindist) x = xy(1,:); y = xy(2,:); l=1; i=1; %filler mindist = mindist/0.999; % limits the number of loops while (~isempty(i) && l<50) xdiff = repmat(x,length(x),1) - repmat(x',1,length(x)); ydiff = repmat(y,length(y),1) - repmat(y',1,length(y)); xydist= sqrt(xdiff.^2 + ydiff.^2); %euclidean distance between all sensor pairs [i,j] = find(xydist<mindist*0.999); rm=(i<=j); i(rm)=[]; j(rm)=[]; %only look at i>j for m = 1:length(i); if (xydist(i(m),j(m)) == 0) diffvec = [mindist./sqrt(2) mindist./sqrt(2)]; else xydiff = [xdiff(i(m),j(m)) ydiff(i(m),j(m))]; diffvec = xydiff.*mindist./xydist(i(m),j(m)) - xydiff; end x(i(m)) = x(i(m)) - diffvec(1)/2; y(i(m)) = y(i(m)) - diffvec(2)/2; x(j(m)) = x(j(m)) + diffvec(1)/2; y(j(m)) = y(j(m)) + diffvec(2)/2; end l = l+1; end xy = [x; y];
github
lcnbeapp/beapp-master
cache.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@meeg/cache.m
754
utf_8
327310c88f9e84a225af302977c46fe6
function res = cache(this, stuff) % Method for retrieving/putting stuff from/into the temporary cache % FORMAT res = cache(obj, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: cache.m 1373 2008-04-11 14:24:03Z spm $ if ischar(stuff) % assume this is a retrieval res = getcache(this, stuff); else % assume this is a put name = inputname(2); res = setcache(this, name, stuff); end function res = getcache(this, stuff) if isfield(this.cache, stuff) eval(['res = this.cache.' stuff ';']); else res = []; end function this = setcache(this, name, stuff) eval(['this.cache(1).' name ' = stuff;']);
github
lcnbeapp/beapp-master
path.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@meeg/path.m
558
utf_8
7149045fd0a2ac178f0e2dcaf166b5e0
function res = path(this, name) % Method for getting/setting path % FORMAT res = path(this, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: path.m 1373 2008-04-11 14:24:03Z spm $ switch nargin case 1 res = getpath(this); case 2 res = setpath(this, name); otherwise end function res = getpath(this) try res = this.path; catch res = ''; end function this = setpath(this, name) this.path = name;
github
lcnbeapp/beapp-master
fname.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@meeg/fname.m
538
utf_8
00404808a43026efada0ed0cb853d259
function res = fname(this, name) % Method for getting/setting file name % FORMAT res = fname(this, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: fname.m 1373 2008-04-11 14:24:03Z spm $ switch nargin case 1 res = getfname(this); case 2 res = setfname(this, name); otherwise end function res = getfname(this) res = this.fname; function this = setfname(this, name) this.fname = name;
github
lcnbeapp/beapp-master
fnamedat.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@meeg/fnamedat.m
589
utf_8
39857f5d9ecf819f3bc1581bde7009cf
function res = fnamedat(this, name) % Method for getting/setting file name of data file % FORMAT res = fnamedat(this, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: fnamedat.m 1373 2008-04-11 14:24:03Z spm $ switch nargin case 1 res = getfnamedat(this); case 2 res = setfnamedat(this, name); otherwise end function res = getfnamedat(this) res = this.data.fnamedat; function this = setfnamedat(this, name) this.data.fnamedat = name;
github
lcnbeapp/beapp-master
privatepermission.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatepermission.m
827
utf_8
be8d85c3b8ab99ec9cf086139103335f
function varargout = permission(varargin) % Format % For getting the value % dat = permission(obj) % % For setting the value % obj = permission(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.permission; return; function obj = asgn(obj,dat) if ischar(dat) tmp = lower(deblank(dat(:)')); switch tmp, case 'ro', case 'rw', otherwise, error('Permission must be either "ro" or "rw"'); end obj.permission = tmp; else error('"permission" must be a character string.'); end; return;
github
lcnbeapp/beapp-master
privatescl_slope.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatescl_slope.m
680
utf_8
4f91ac10412885a1654d520cdaf4c008
function varargout = scl_slope(varargin) % Format % For getting the value % dat = scl_slope(obj) % % For setting the value % obj = scl_slope(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.scl_slope; return; function obj = asgn(obj,dat) if isnumeric(dat), % && numel(dat)<=1, obj.scl_slope = double(dat); else error('"scl_slope" must be numeric.'); end; return;
github
lcnbeapp/beapp-master
subsasgn.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/subsasgn.m
4,553
utf_8
8649bb5b2b003aef0a04f01504128d47
function obj = subsasgn(obj,subs,dat) % Overloaded subsasgn function for file_array objects. % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if isempty(subs) return; end; if ~strcmp(subs(1).type,'()'), if strcmp(subs(1).type,'.'), %error('Attempt to reference field of non-structure array.'); if numel(struct(obj))~=1, error('Can only change the fields of simple file_array objects.'); end; switch(subs(1).subs) case 'fname', obj = asgn(obj,@fname, subs(2:end),dat); %fname(obj,dat); case 'dtype', obj = asgn(obj,@dtype, subs(2:end),dat); %dtype(obj,dat); case 'offset', obj = asgn(obj,@offset, subs(2:end),dat); %offset(obj,dat); case 'dim', obj = asgn(obj,@dim, subs(2:end),dat); %obj = dim(obj,dat); case 'scl_slope', obj = asgn(obj,@scl_slope, subs(2:end),dat); %scl_slope(obj,dat); case 'scl_inter', obj = asgn(obj,@scl_inter, subs(2:end),dat); %scl_inter(obj,dat); case 'permission', obj = asgn(obj,@permission,subs(2:end),dat); %permission(obj,dat); otherwise, error(['Reference to non-existent field "' subs.subs '".']); end; return; end; if strcmp(subs(1).type,'{}'), error('Cell contents reference from a non-cell array object.'); end; end; if numel(subs)~=1, error('Expression too complicated');end; dm = size(obj); sobj = struct(obj); if length(subs.subs) < length(dm), l = length(subs.subs); dm = [dm(1:(l-1)) prod(dm(l:end))]; if numel(sobj) ~= 1, error('Can only reshape simple file_array objects.'); end; if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1, error('Can not reshape file_array objects with multiple slopes and intercepts.'); end; end; dm = [dm ones(1,16)]; do = ones(1,16); args = {}; for i=1:length(subs.subs), if ischar(subs.subs{i}), if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end; args{i} = int32(1:dm(i)); else args{i} = int32(subs.subs{i}); end; do(i) = length(args{i}); end; for j=1:length(sobj), if strcmp(sobj(j).permission,'ro'), error('Array is read-only.'); end end if length(sobj)==1 sobj.dim = dm; if numel(dat)~=1, subfun(sobj,double(dat),args{:}); else dat1 = double(dat) + zeros(do); subfun(sobj,dat1,args{:}); end; else for j=1:length(sobj), ps = [sobj(j).pos ones(1,length(args))]; dm = [sobj(j).dim ones(1,length(args))]; siz = ones(1,16); for i=1:length(args), msk = args{i}>=ps(i) & args{i}<(ps(i)+dm(i)); args2{i} = find(msk); args3{i} = int32(double(args{i}(msk))-ps(i)+1); siz(i) = numel(args2{i}); end; if numel(dat)~=1, dat1 = double(subsref(dat,struct('type','()','subs',{args2}))); else dat1 = double(dat) + zeros(siz); end; subfun(sobj(j),dat1,args3{:}); end end return function sobj = subfun(sobj,dat,varargin) va = varargin; dt = datatypes; ind = find(cat(1,dt.code)==sobj.dtype); if isempty(ind), error('Unknown datatype'); end; if dt(ind).isint, dat(~isfinite(dat)) = 0; end; if ~isempty(sobj.scl_inter), inter = sobj.scl_inter; if numel(inter)>1, inter = resize_scales(inter,sobj.dim,varargin); end; dat = double(dat) - inter; end; if ~isempty(sobj.scl_slope), slope = sobj.scl_slope; if numel(slope)>1, slope = resize_scales(slope,sobj.dim,varargin); dat = double(dat)./slope; else dat = double(dat)/slope; end; end; if dt(ind).isint, dat = round(dat); end; % Avoid warning messages in R14 SP3 wrn = warning; warning('off'); dat = feval(dt(ind).conv,dat); warning(wrn); nelem = dt(ind).nelem; if nelem==1, mat2file(sobj,dat,va{:}); elseif nelem==2, sobj1 = sobj; sobj1.dim = [2 sobj.dim]; sobj1.dtype = dt(find(strcmp(dt(ind).prec,{dt.prec}) & (cat(2,dt.nelem)==1))).code; dat = reshape(dat,[1 size(dat)]); dat = [real(dat) ; imag(dat)]; mat2file(sobj1,dat,int32([1 2]),va{:}); else error('Inappropriate number of elements per voxel.'); end; return function obj = asgn(obj,fun,subs,dat) if ~isempty(subs), tmp = feval(fun,obj); tmp = subsasgn(tmp,subs,dat); obj = feval(fun,obj,tmp); else obj = feval(fun,obj,dat); end;
github
lcnbeapp/beapp-master
privatedim.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatedim.m
762
utf_8
0ad58f05456fccb279755b25289027c4
function varargout = dim(varargin) % Format % For getting the value % dat = dim(obj) % % For setting the value % obj = dim(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.dim; return; function obj = asgn(obj,dat) if isnumeric(dat) && all(dat>=0) && all(rem(dat,1)==0), dat = [double(dat(:)') 1 1]; lim = max([2 find(dat~=1)]); dat = dat(1:lim); obj.dim = dat; else error('"dim" must be a vector of positive integers.'); end; return;
github
lcnbeapp/beapp-master
privatescl_inter.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatescl_inter.m
681
utf_8
341f747372c0465de4be134d3595e133
function varargout = scl_inter(varargin) % Format % For getting the value % dat = scl_inter(obj) % % For setting the value % obj = scl_inter(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.scl_inter; return; function obj = asgn(obj,dat) if isnumeric(dat), % && numel(dat)<=1, obj.scl_inter = double(dat); else error('"scl_inter" must be numeric.'); end; return;
github
lcnbeapp/beapp-master
privatefname.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatefname.m
648
utf_8
87ba48423085238dda8deb873c3a5a24
function varargout = fname(varargin) % Format % For getting the value % dat = fname(obj) % % For setting the value % obj = fname(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.fname; return; function obj = asgn(obj,dat) if ischar(dat) obj.fname = deblank(dat(:)'); else error('"fname" must be a character string.'); end; return;
github
lcnbeapp/beapp-master
privateoffset.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/privateoffset.m
697
utf_8
5b5493cb277651ae207a6e094e50f16f
function varargout = offset(varargin) % Format % For getting the value % dat = offset(obj) % % For setting the value % obj = offset(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.offset; return; function obj = asgn(obj,dat) if isnumeric(dat) && numel(dat)==1 && dat>=0 && rem(dat,1)==0, obj.offset = double(dat); else error('"offset" must be a positive integer.'); end; return;
github
lcnbeapp/beapp-master
privatedtype.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/privatedtype.m
2,225
utf_8
4e4a2cfe6a4a9d295f1b9f3eb3fd3eb1
function varargout = dtype(varargin) % Format % For getting the value % dat = dtype(obj) % % For setting the value % obj = dtype(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wring number of arguments.'); end; return; function t = ref(obj) d = datatypes; mch = find(cat(1,d.code)==obj.dtype); if isempty(mch), t = 'UNKNOWN'; else t = d(mch).label; end; if obj.be, t = [t '-BE']; else t = [t '-LE']; end; return; function obj = asgn(obj,dat) d = datatypes; if isnumeric(dat) if numel(dat)>=1, mch = find(cat(1,d.code)==dat(1)); if isempty(mch) || mch==0, fprintf('Invalid datatype (%d).', dat(1)); disp('First part of datatype should be of one of the following'); disp(sortrows([num2str(cat(1,d.code)) ... repmat(' ',numel(d),2) strvcat(d.label)])); %error(['Invalid datatype (' num2str(dat(1)) ').']); return; end; obj.dtype = double(dat(1)); end; if numel(dat)>=2, obj.be = double(dat(2)~=0); end; if numel(dat)>2, error('Too many elements in numeric datatype.'); end; elseif ischar(dat), dat1 = lower(dat); sep = find(dat1=='-' | dat1=='/'); sep = sep(sep~=1); if ~isempty(sep), c1 = dat1(1:(sep(1)-1)); c2 = dat1((sep(1)+1):end); else c1 = dat1; c2 = ''; end; mch = find(strcmpi(c1,lower({d.label}))); if isempty(mch), disp('First part of datatype should be of one of the following'); disp(sortrows([num2str(cat(1,d.code)) ... repmat(' ',numel(d),2) strvcat(d.label)])); %error(['Invalid datatype (' c1 ').']); return; else obj.dtype = double(d(mch(1)).code); end; if any(c2=='b'), if any(c2=='l'), error('Cannot be both big and little endian.'); end; obj.be = 1; elseif any(c2=='l'), obj.be = 0; end; else error('Invalid datatype.'); end; return;
github
lcnbeapp/beapp-master
subsref.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/subsref.m
5,222
utf_8
80f9298dd645012f0fe42fcb32d6beef
function varargout=subsref(obj,subs) % SUBSREF Subscripted reference % An overloaded function... %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if isempty(subs), return; end switch subs(1).type case '{}' error('Cell contents reference from a non-cell array object.'); case '.' varargout = access_fields(obj,subs); return; end if numel(subs)~=1, error('Expression too complicated'); end; dim = [size(obj) ones(1,16)]; nd = find(dim>1,1,'last')-1; sobj = struct(obj); if ~numel(subs.subs) [subs.subs{1:nd+1}] = deal(':'); elseif length(subs.subs) < nd l = length(subs.subs); dim = [dim(1:(l-1)) prod(dim(l:end))]; if numel(sobj) ~= 1 error('Can only reshape simple file_array objects.'); else if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1 error('Can not reshape file_array objects with multiple slopes and intercepts.'); end sobj.dim = dim; end end do = ones(16,1); args = cell(1,length(subs.subs)); for i=1:length(subs.subs) if ischar(subs.subs{i}) if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end if length(subs.subs) == 1 args{i} = 1:prod(dim); % possible overflow when int32() k = 0; for j=1:length(sobj) sobj(j).dim = [prod(sobj(j).dim) 1]; sobj(j).pos = [k+1 1]; k = k + sobj(j).dim(1); end else args{i} = 1:dim(i); end else args{i} = subs.subs{i}; end do(i) = length(args{i}); end if length(sobj)==1 t = subfun(sobj,args{:}); else dt = datatypes; dt = dt([dt.code]==sobj(1).dtype); % assuming identical datatypes t = zeros(do',func2str(dt.conv)); for j=1:length(sobj) ps = [sobj(j).pos ones(1,length(args))]; dm = [sobj(j).dim ones(1,length(args))]; for i=1:length(args) msk = find(args{i}>=ps(i) & args{i}<(ps(i)+dm(i))); args2{i} = msk; args3{i} = double(args{i}(msk))-ps(i)+1; end t = subsasgn(t,struct('type','()','subs',{args2}),subfun(sobj(j),args3{:})); end end varargout = {t}; %========================================================================== % function t = subfun(sobj,varargin) %========================================================================== function t = subfun(sobj,varargin) %sobj.dim = [sobj.dim ones(1,16)]; try args = cell(size(varargin)); for i=1:length(varargin) args{i} = int32(varargin{i}); end t = file2mat(sobj,args{:}); catch t = multifile2mat(sobj,varargin{:}); end if ~isempty(sobj.scl_slope) || ~isempty(sobj.scl_inter) slope = 1; inter = 0; if ~isempty(sobj.scl_slope), slope = sobj.scl_slope; end if ~isempty(sobj.scl_inter), inter = sobj.scl_inter; end if numel(slope)>1 slope = resize_scales(slope,sobj.dim,varargin); t = double(t).*slope; else t = double(t)*slope; end if numel(inter)>1 inter = resize_scales(inter,sobj.dim,varargin); end; t = t + inter; end %========================================================================== % function c = access_fields(obj,subs) %========================================================================== function c = access_fields(obj,subs) sobj = struct(obj); c = cell(1,numel(sobj)); for i=1:numel(sobj) %obj = class(sobj(i),'file_array'); obj = sobj(i); switch(subs(1).subs) case 'fname', t = fname(obj); case 'dtype', t = dtype(obj); case 'offset', t = offset(obj); case 'dim', t = dim(obj); case 'scl_slope', t = scl_slope(obj); case 'scl_inter', t = scl_inter(obj); case 'permission', t = permission(obj); otherwise error(['Reference to non-existent field "' subs(1).subs '".']); end if numel(subs)>1 t = subsref(t,subs(2:end)); end c{i} = t; end %========================================================================== % function val = multifile2mat(sobj,varargin) %========================================================================== function val = multifile2mat(sobj,varargin) % Convert subscripts into linear index [indx2{1:length(varargin)}] = ndgrid(varargin{:},1); ind = sub2ind(sobj.dim,indx2{:}); % Work out the partition dt = datatypes; dt = dt([dt.code]==sobj.dtype); sz = dt.size; mem = spm('memory'); % in bytes, has to be a multiple of 16 (max([dt.size])) s = ceil(prod(sobj.dim) * sz / mem); % Assign indices to partitions [x,y] = ind2sub([mem/sz s],ind(:)); c = histc(y,1:s); cc = [0 reshape(cumsum(c),1,[])]; % Read data in relevant partitions obj = sobj; val = zeros(length(x),1,func2str(dt.conv)); for i=reshape(find(c),1,[]) obj.offset = sobj.offset + mem*(i-1); obj.dim = [1 min(mem/sz, prod(sobj.dim)-(i-1)*mem/sz)]; val(cc(i)+1:cc(i+1)) = file2mat(obj,int32(1),int32(x(y==i))); end r = cellfun('length',varargin); if numel(r) == 1, r = [r 1]; end val = reshape(val,r);
github
lcnbeapp/beapp-master
disp.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/disp.m
887
utf_8
64720ef6ff6e10ebb67d01f5d3a04f7f
function disp(obj) % Display a file_array object % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if numel(struct(obj))>1, fprintf(' %s object: ', class(obj)); sz = size(obj); if length(sz)>4, fprintf('%d-D\n',length(sz)); else for i=1:(length(sz)-1), fprintf('%d-by-',sz(i)); end; fprintf('%d\n',sz(end)); end; else display(mystruct(obj)) end; return; %======================================================================= %======================================================================= function t = mystruct(obj) fn = fieldnames(obj); for i=1:length(fn) t.(fn{i}) = subsref(obj,struct('type','.','subs',fn{i})); end; return; %=======================================================================
github
lcnbeapp/beapp-master
offset.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/offset.m
697
utf_8
5b5493cb277651ae207a6e094e50f16f
function varargout = offset(varargin) % Format % For getting the value % dat = offset(obj) % % For setting the value % obj = offset(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.offset; return; function obj = asgn(obj,dat) if isnumeric(dat) && numel(dat)==1 && dat>=0 && rem(dat,1)==0, obj.offset = double(dat); else error('"offset" must be a positive integer.'); end; return;
github
lcnbeapp/beapp-master
scl_slope.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/scl_slope.m
680
utf_8
4f91ac10412885a1654d520cdaf4c008
function varargout = scl_slope(varargin) % Format % For getting the value % dat = scl_slope(obj) % % For setting the value % obj = scl_slope(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.scl_slope; return; function obj = asgn(obj,dat) if isnumeric(dat), % && numel(dat)<=1, obj.scl_slope = double(dat); else error('"scl_slope" must be numeric.'); end; return;
github
lcnbeapp/beapp-master
scl_inter.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/scl_inter.m
681
utf_8
341f747372c0465de4be134d3595e133
function varargout = scl_inter(varargin) % Format % For getting the value % dat = scl_inter(obj) % % For setting the value % obj = scl_inter(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.scl_inter; return; function obj = asgn(obj,dat) if isnumeric(dat), % && numel(dat)<=1, obj.scl_inter = double(dat); else error('"scl_inter" must be numeric.'); end; return;
github
lcnbeapp/beapp-master
fname.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/fname.m
648
utf_8
87ba48423085238dda8deb873c3a5a24
function varargout = fname(varargin) % Format % For getting the value % dat = fname(obj) % % For setting the value % obj = fname(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.fname; return; function obj = asgn(obj,dat) if ischar(dat) obj.fname = deblank(dat(:)'); else error('"fname" must be a character string.'); end; return;
github
lcnbeapp/beapp-master
dim.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/dim.m
762
utf_8
0ad58f05456fccb279755b25289027c4
function varargout = dim(varargin) % Format % For getting the value % dat = dim(obj) % % For setting the value % obj = dim(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.dim; return; function obj = asgn(obj,dat) if isnumeric(dat) && all(dat>=0) && all(rem(dat,1)==0), dat = [double(dat(:)') 1 1]; lim = max([2 find(dat~=1)]); dat = dat(1:lim); obj.dim = dat; else error('"dim" must be a vector of positive integers.'); end; return;
github
lcnbeapp/beapp-master
permission.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/permission.m
827
utf_8
be8d85c3b8ab99ec9cf086139103335f
function varargout = permission(varargin) % Format % For getting the value % dat = permission(obj) % % For setting the value % obj = permission(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.permission; return; function obj = asgn(obj,dat) if ischar(dat) tmp = lower(deblank(dat(:)')); switch tmp, case 'ro', case 'rw', otherwise, error('Permission must be either "ro" or "rw"'); end obj.permission = tmp; else error('"permission" must be a character string.'); end; return;
github
lcnbeapp/beapp-master
dtype.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@file_array/private/dtype.m
2,225
utf_8
4e4a2cfe6a4a9d295f1b9f3eb3fd3eb1
function varargout = dtype(varargin) % Format % For getting the value % dat = dtype(obj) % % For setting the value % obj = dtype(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wring number of arguments.'); end; return; function t = ref(obj) d = datatypes; mch = find(cat(1,d.code)==obj.dtype); if isempty(mch), t = 'UNKNOWN'; else t = d(mch).label; end; if obj.be, t = [t '-BE']; else t = [t '-LE']; end; return; function obj = asgn(obj,dat) d = datatypes; if isnumeric(dat) if numel(dat)>=1, mch = find(cat(1,d.code)==dat(1)); if isempty(mch) || mch==0, fprintf('Invalid datatype (%d).', dat(1)); disp('First part of datatype should be of one of the following'); disp(sortrows([num2str(cat(1,d.code)) ... repmat(' ',numel(d),2) strvcat(d.label)])); %error(['Invalid datatype (' num2str(dat(1)) ').']); return; end; obj.dtype = double(dat(1)); end; if numel(dat)>=2, obj.be = double(dat(2)~=0); end; if numel(dat)>2, error('Too many elements in numeric datatype.'); end; elseif ischar(dat), dat1 = lower(dat); sep = find(dat1=='-' | dat1=='/'); sep = sep(sep~=1); if ~isempty(sep), c1 = dat1(1:(sep(1)-1)); c2 = dat1((sep(1)+1):end); else c1 = dat1; c2 = ''; end; mch = find(strcmpi(c1,lower({d.label}))); if isempty(mch), disp('First part of datatype should be of one of the following'); disp(sortrows([num2str(cat(1,d.code)) ... repmat(' ',numel(d),2) strvcat(d.label)])); %error(['Invalid datatype (' c1 ').']); return; else obj.dtype = double(d(mch(1)).code); end; if any(c2=='b'), if any(c2=='l'), error('Cannot be both big and little endian.'); end; obj.be = 1; elseif any(c2=='l'), obj.be = 0; end; else error('Invalid datatype.'); end; return;
github
lcnbeapp/beapp-master
subsasgn.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@nifti/subsasgn.m
14,522
utf_8
86db451a023fd9a4a9252278adcab3ab
function obj = subsasgn(obj,subs,varargin) % Subscript assignment % See subsref for meaning of fields. % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ switch subs(1).type, case {'.'}, if numel(obj)~=nargin-2, error('The number of outputs should match the number of inputs.'); end; objs = struct(obj); for i=1:length(varargin), val = varargin{i}; obji = class(objs(i),'nifti'); obji = fun(obji,subs,val); objs(i) = struct(obji); end; obj = class(objs,'nifti'); case {'()'}, objs = struct(obj); if length(subs)>1, t = subsref(objs,subs(1)); % A lot of this stuff is a little flakey, and may cause Matlab to bomb. % %if numel(t) ~= nargin-2, % error('The number of outputs should match the number of inputs.'); %end; for i=1:numel(t), val = varargin{1}; obji = class(t(i),'nifti'); obji = subsasgn(obji,subs(2:end),val); t(i) = struct(obji); end; objs = subsasgn(objs,subs(1),t); else if numel(varargin)>1, error('Illegal right hand side in assignment. Too many elements.'); end; val = varargin{1}; if isa(val,'nifti'), objs = subsasgn(objs,subs,struct(val)); elseif isempty(val), objs = subsasgn(objs,subs,[]); else error('Assignment between unlike types is not allowed.'); end; end; obj = class(objs,'nifti'); otherwise error('Cell contents reference from a non-cell array object.'); end; return; %======================================================================= %======================================================================= function obj = fun(obj,subs,val) % Subscript referencing switch subs(1).type, case {'.'}, objs = struct(obj); for ii=1:numel(objs) obj = objs(ii); if any(strcmpi(subs(1).subs,{'dat'})), if length(subs)>1, val = subsasgn(obj.dat,subs(2:end),val); end; obj = assigndat(obj,val); objs(ii) = obj; continue; end; if isempty(obj.hdr), obj.hdr = empty_hdr; end; if ~isfield(obj.hdr,'magic'), error('Not a NIFTI-1 header'); end; if length(subs)>1, % && ~strcmpi(subs(1).subs,{'raw','dat'}), val0 = subsref(class(obj,'nifti'),subs(1)); val1 = subsasgn(val0,subs(2:end),val); else val1 = val; end; switch(subs(1).subs) case {'extras'} if length(subs)>1, obj.extras = subsasgn(obj.extras,subs(2:end),val); else obj.extras = val; end; case {'mat0'} if ~isnumeric(val1) || ndims(val1)~=2 || any(size(val1)~=[4 4]) || sum((val1(4,:)-[0 0 0 1]).^2)>1e-8, error('"mat0" should be a 4x4 matrix, with a last row of 0,0,0,1.'); end; if obj.hdr.qform_code==0, obj.hdr.qform_code=2; end; s = double(bitand(obj.hdr.xyzt_units,7)); if s d = findindict(s,'units'); val1 = diag([[1 1 1]/d.rescale 1])*val1; end; obj.hdr = encode_qform0(double(val1), obj.hdr); case {'mat0_intent'} if isempty(val1), obj.hdr.qform_code = 0; else if ~ischar(val1) && ~(isnumeric(val1) && numel(val1)==1), error('"mat0_intent" should be a string or a scalar.'); end; d = findindict(val1,'xform'); if ~isempty(d) obj.hdr.qform_code = d.code; end; end; case {'mat'} if ~isnumeric(val1) || ndims(val1)~=2 || any(size(val1)~=[4 4]) || sum((val1(4,:)-[0 0 0 1]).^2)>1e-8 error('"mat" should be a 4x4 matrix, with a last row of 0,0,0,1.'); end; if obj.hdr.sform_code==0, obj.hdr.sform_code=2; end; s = double(bitand(obj.hdr.xyzt_units,7)); if s d = findindict(s,'units'); val1 = diag([[1 1 1]/d.rescale 1])*val1; end; val1 = val1 * [eye(4,3) [1 1 1 1]']; obj.hdr.srow_x = val1(1,:); obj.hdr.srow_y = val1(2,:); obj.hdr.srow_z = val1(3,:); case {'mat_intent'} if isempty(val1), obj.hdr.sform_code = 0; else if ~ischar(val1) && ~(isnumeric(val1) && numel(val1)==1), error('"mat_intent" should be a string or a scalar.'); end; d = findindict(val1,'xform'); if ~isempty(d), obj.hdr.sform_code = d.code; end; end; case {'intent'} if ~valid_fields(val1,{'code','param','name'}) obj.hdr.intent_code = 0; obj.hdr.intent_p1 = 0; obj.hdr.intent_p2 = 0; obj.hdr.intent_p3 = 0; obj.hdr.intent_name = ''; else if ~isfield(val1,'code'), val1.code = obj.hdr.intent_code; end; d = findindict(val1.code,'intent'); if ~isempty(d), obj.hdr.intent_code = d.code; if isfield(val1,'param'), prm = [double(val1.param(:)) ; 0 ; 0; 0]; prm = [prm(1:length(d.param)) ; 0 ; 0; 0]; obj.hdr.intent_p1 = prm(1); obj.hdr.intent_p2 = prm(2); obj.hdr.intent_p3 = prm(3); end; if isfield(val1,'name'), obj.hdr.intent_name = val1.name; end; end; end; case {'diminfo'} if ~valid_fields(val1,{'frequency','phase','slice','slice_time'}) tmp = obj.hdr.dim_info; for bit=1:6, tmp = bitset(tmp,bit,0); end; obj.hdr.dim_info = tmp; obj.hdr.slice_start = 0; obj.hdr.slice_end = 0; obj.hdr.slice_duration = 0; obj.hdr.slice_code = 0; else if isfield(val1,'frequency'), tmp = val1.frequency; if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3, error('Invalid frequency direction'); end; obj.hdr.dim_info = bitset(obj.hdr.dim_info,1,bitget(tmp,1)); obj.hdr.dim_info = bitset(obj.hdr.dim_info,2,bitget(tmp,2)); end; if isfield(val1,'phase'), tmp = val1.phase; if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3, error('Invalid phase direction'); end; obj.hdr.dim_info = bitset(obj.hdr.dim_info,3,bitget(tmp,1)); obj.hdr.dim_info = bitset(obj.hdr.dim_info,4,bitget(tmp,2)); end; if isfield(val1,'slice'), tmp = val1.slice; if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3, error('Invalid slice direction'); end; obj.hdr.dim_info = bitset(obj.hdr.dim_info,5,bitget(tmp,1)); obj.hdr.dim_info = bitset(obj.hdr.dim_info,6,bitget(tmp,2)); end; if isfield(val1,'slice_time') tim = val1.slice_time; if ~valid_fields(tim,{'start','end','duration','code'}), obj.hdr.slice_code = 0; obj.hdr.slice_start = 0; obj.hdr.end_slice = 0; obj.hdr.slice_duration = 0; else % sld = double(bitget(obj.hdr.dim_info,5)) + 2*double(bitget(obj.hdr.dim_info,6)); if isfield(tim,'start'), ss = double(tim.start); if isnumeric(ss) && numel(ss)==1 && ~rem(ss,1), % && ss>=1 && ss<=obj.hdr.dim(sld+1) obj.hdr.slice_start = ss-1; else error('Inappropriate "slice_time.start".'); end; end; if isfield(tim,'end'), ss = double(tim.end); if isnumeric(ss) && numel(ss)==1 && ~rem(ss,1), % && ss>=1 && ss<=obj.hdr.dim(sld+1) obj.hdr.slice_end = ss-1; else error('Inappropriate "slice_time.end".'); end; end; if isfield(tim,'duration') sd = double(tim.duration); if isnumeric(sd) && numel(sd)==1, s = double(bitand(obj.hdr.xyzt_units,24)); d = findindict(s,'units'); if ~isempty(d) && d.rescale, sd = sd/d.rescale; end; obj.hdr.slice_duration = sd; else error('Inappropriate "slice_time.duration".'); end; end; if isfield(tim,'code'), d = findindict(tim.code,'sliceorder'); if ~isempty(d), obj.hdr.slice_code = d.code; end; end; end; end; end; case {'timing'} if ~valid_fields(val1,{'toffset','tspace'}), obj.hdr.pixdim(5) = 0; obj.hdr.toffset = 0; else s = double(bitand(obj.hdr.xyzt_units,24)); d = findindict(s,'units'); if isfield(val1,'toffset'), if isnumeric(val1.toffset) && numel(val1.toffset)==1, if d.rescale, val1.toffset = val1.toffset/d.rescale; end; obj.hdr.toffset = val1.toffset; else error('"timing.toffset" needs to be numeric with 1 element'); end; end; if isfield(val1,'tspace'), if isnumeric(val1.tspace) && numel(val1.tspace)==1, if d.rescale, val1.tspace = val1.tspace/d.rescale; end; obj.hdr.pixdim(5) = val1.tspace; else error('"timing.tspace" needs to be numeric with 1 element'); end; end; end; case {'descrip'} if isempty(val1), val1 = char(val1); end; if ischar(val1), obj.hdr.descrip = val1; else error('"descrip" must be a string.'); end; case {'cal'} if isempty(val1), obj.hdr.cal_min = 0; obj.hdr.cal_max = 0; else if isnumeric(val1) && numel(val1)==2, obj.hdr.cal_min = val1(1); obj.hdr.cal_max = val1(2); else error('"cal" should contain two elements.'); end; end; case {'aux_file'} if isempty(val1), val1 = char(val1); end; if ischar(val1), obj.hdr.aux_file = val1; else error('"aux_file" must be a string.'); end; case {'hdr'} error('hdr is a read-only field.'); obj.hdr = val1; otherwise error(['Reference to non-existent field ''' subs(1).subs '''.']); end; objs(ii) = obj; end obj = class(objs,'nifti'); otherwise error('This should not happen.'); end; return; %======================================================================= %======================================================================= function obj = assigndat(obj,val) if isa(val,'file_array'), sz = size(val); if numel(sz)>8, error('Too many dimensions in data.'); end; sz = [sz 1 1 1 1 1 1 1 1]; sz = sz(1:8); sval = struct(val); d = findindict(sval.dtype,'dtype'); if isempty(d) error(['Unknown datatype (' num2str(double(sval.datatype)) ').']); end; [pth,nam,suf] = fileparts(sval.fname); if any(strcmp(suf,{'.img','.IMG'})) val.offset = max(sval.offset,0); obj.hdr.magic = 'ni1'; elseif any(strcmp(suf,{'.nii','.NII'})) val.offset = max(sval.offset,352); obj.hdr.magic = 'n+1'; else error(['Unknown filename extension (' suf ').']); end; val.offset = (ceil(val.offset/16))*16; obj.hdr.vox_offset = val.offset; obj.hdr.dim(2:(numel(sz)+1)) = sz; nd = max(find(obj.hdr.dim(2:end)>1)); if isempty(nd), nd = 3; end; obj.hdr.dim(1) = nd; obj.hdr.datatype = sval.dtype; obj.hdr.bitpix = d.size*8; if ~isempty(sval.scl_slope), obj.hdr.scl_slope = sval.scl_slope; end; if ~isempty(sval.scl_inter), obj.hdr.scl_inter = sval.scl_inter; end; obj.dat = val; else error('"raw" must be of class "file_array"'); end; return; function ok = valid_fields(val,allowed) if isempty(val), ok = false; return; end; if ~isstruct(val), error(['Expecting a structure, not a ' class(val) '.']); end; fn = fieldnames(val); for ii=1:length(fn), if ~any(strcmpi(fn{ii},allowed)), fprintf('Allowed fieldnames are:\n'); for i=1:length(allowed), fprintf(' %s\n', allowed{i}); end; error(['"' fn{ii} '" is not a valid fieldname.']); end end ok = true; return;
github
lcnbeapp/beapp-master
subsref.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@nifti/subsref.m
8,717
utf_8
3e5580b77072a8d2a98deb98231f6bab
function varargout = subsref(opt,subs) % Subscript referencing % % Fields are: % dat - a file-array representing the image data % mat0 - a 9-parameter affine transform (from qform0) % Note that the mapping is from voxels (where the first % is considered to be at [1,1,1], to millimetres. See % mat0_interp for the meaning of the transform. % mat - a 12-parameter affine transform (from sform0) % Note that the mapping is from voxels (where the first % is considered to be at [1,1,1], to millimetres. See % mat1_interp for the meaning of the transform. % mat_intent - intention of mat. This field may be missing/empty. % mat0_intent - intention of mat0. This field may be missing/empty. % intent - interpretation of image. When present, this structure % contains the fields % code - name of interpretation % params - parameters needed to interpret the image % diminfo - MR encoding of different dimensions. This structure may % contain some or all of the following fields % frequency - a value of 1-3 indicating frequency direction % phase - a value of 1-3 indicating phase direction % slice - a value of 1-3 indicating slice direction % slice_time - only present when "slice" field is present. % Contains the following fields % code - ascending/descending etc % start - starting slice number % end - ending slice number % duration - duration of each slice acquisition % Setting frequency, phase or slice to 0 will remove it. % timing - timing information. When present, contains the fields % toffset - acquisition time of first volume (seconds) % tspace - time between sucessive volumes (seconds) % descrip - a brief description of the image % cal - a two-element vector containing cal_min and cal_max % aux_file - name of an auxiliary file % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ varargout = rec(opt,subs); return; function c = rec(opt,subs) switch subs(1).type, case {'.'}, c = {}; opts = struct(opt); for ii=1:numel(opts) opt = class(opts(ii),'nifti'); %if ~isstruct(opt) % error('Attempt to reference field of non-structure array.'); %end; h = opt.hdr; if isempty(h), %error('No header.'); h = empty_hdr; end; % NIFTI-1 FORMAT switch(subs(1).subs) case 'extras', t = opt.extras; case 'raw', % A hidden field if isa(opt.dat,'file_array'), tmp = struct(opt.dat); tmp.scl_slope = []; tmp.scl_inter = []; t = file_array(tmp); else t = opt.dat; end; case 'dat', t = opt.dat; case 'mat0', t = decode_qform0(h); s = double(bitand(h.xyzt_units,7)); if s d = findindict(s,'units'); if ~isempty(d) t = diag([d.rescale*[1 1 1] 1])*t; end; end; case 'mat0_intent', d = findindict(h.qform_code,'xform'); if isempty(d) || d.code==0, t = ''; else t = d.label; end; case 'mat', if h.sform_code > 0 t = double([h.srow_x ; h.srow_y ; h.srow_z ; 0 0 0 1]); t = t * [eye(4,3) [-1 -1 -1 1]']; else t = decode_qform0(h); end s = double(bitand(h.xyzt_units,7)); if s d = findindict(s,'units'); t = diag([d.rescale*[1 1 1] 1])*t; end; case 'mat_intent', if h.sform_code>0, t = h.sform_code; else t = h.qform_code; end; d = findindict(t,'xform'); if isempty(d) || d.code==0, t = ''; else t = d.label; end; case 'intent', d = findindict(h.intent_code,'intent'); if isempty(d) || d.code == 0, %t = struct('code','UNKNOWN','param',[]); t = []; else t = struct('code',d.label,'param',... double([h.intent_p1 h.intent_p2 h.intent_p3]), 'name',deblank(h.intent_name)); t.param = t.param(1:length(d.param)); end case 'diminfo', t = []; tmp = bitand( h.dim_info ,3); if tmp, t.frequency = double(tmp); end; tmp = bitand(bitshift(h.dim_info,-2),3); if tmp, t.phase = double(tmp); end; tmp = bitand(bitshift(h.dim_info,-4),3); if tmp, t.slice = double(tmp); end; % t = struct('frequency',bitand( h.dim_info ,3),... % 'phase',bitand(bitshift(h.dim_info,-2),3),... % 'slice',bitand(bitshift(h.dim_info,-4),3)) if isfield(t,'slice') sc = double(h.slice_code); ss = double(h.slice_start)+1; se = double(h.slice_end)+1; ss = max(ss,1); se = min(se,double(h.dim(t.slice+1))); sd = double(h.slice_duration); s = double(bitand(h.xyzt_units,24)); d = findindict(s,'units'); if d.rescale, sd = sd*d.rescale; end; ns = (se-ss+1); d = findindict(sc,'sliceorder'); if isempty(d) label = 'UNKNOWN'; else label = d.label; end; t.slice_time = struct('code',label,'start',ss,'end',se,'duration',sd); if 0, % Never t.times = zeros(1,double(h.dim(t.slice+1)))+NaN; switch sc, case 0, % Unknown t.times(ss:se) = zeros(1,ns); case 1, % sequential increasing t.times(ss:se) = (0:(ns-1))*sd; case 2, % sequential decreasing t.times(ss:se) = ((ns-1):-1:0)*sd; case 3, % alternating increasing t.times(ss:2:se) = (0:floor((ns+1)/2-1))*sd; t.times((ss+1):2:se) = (floor((ns+1)/2):(ns-1))*sd; case 4, % alternating decreasing t.times(se:-2:ss) = (0:floor((ns+1)/2-1))*sd; t.times(se:-2:(ss+1)) = (floor((ns+1)/2):(ns-1))*sd; end; end; end; case 'timing', to = double(h.toffset); dt = double(h.pixdim(5)); if to==0 && dt==0, t = []; else s = double(bitand(h.xyzt_units,24)); d = findindict(s,'units'); if d.rescale, to = to*d.rescale; dt = dt*d.rescale; end; t = struct('toffset',to,'tspace',dt); end; case 'descrip', t = deblank(h.descrip); msk = find(t==0); if any(msk), t=t(1:(msk(1)-1)); end; case 'cal', t = [double(h.cal_min) double(h.cal_max)]; if all(t==0), t = []; end; case 'aux_file', t = deblank(h.aux_file); case 'hdr', % Hidden field t = h; otherwise error(['Reference to non-existent field ''' subs(1).subs '''.']); end; if numel(subs)>1, t = subsref(t,subs(2:end)); end; c{ii} = t; end; case {'{}'}, error('Cell contents reference from a non-cell array object.'); case {'()'}, opt = struct(opt); t = subsref(opt,subs(1)); if length(subs)>1 c = {}; for i=1:numel(t), ti = class(t(i),'nifti'); ti = rec(ti,subs(2:end)); c = {c{:}, ti{:}}; end; else c = {class(t,'nifti')}; end; otherwise error('This should not happen.'); end;
github
lcnbeapp/beapp-master
create.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@nifti/create.m
1,922
utf_8
3d0a267602ecbe433be656c175acb2a2
function create(obj,wrt) % Create a NIFTI-1 file % FORMAT create(obj) % This writes out the header information for the nifti object % % create(obj,wrt) % This also writes out an empty image volume if wrt==1 % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ for i=1:numel(obj) create_each(obj(i)); end; function create_each(obj) if ~isa(obj.dat,'file_array'), error('Data must be a file-array'); end; fname = obj.dat.fname; if isempty(fname), error('No filename to write to.'); end; dt = obj.dat.dtype; ok = write_hdr_raw(fname,obj.hdr,dt(end-1)=='B'); if ~ok, error(['Unable to write header for "' fname '".']); end; write_extras(fname,obj.extras); if nargin>2 && any(wrt==1), % Create an empty image file if necessary d = findindict(obj.hdr.datatype, 'dtype'); dim = double(obj.hdr.dim(2:end)); dim((double(obj.hdr.dim(1))+1):end) = 1; nbytes = ceil(d.size*d.nelem*prod(dim(1:2)))*prod(dim(3:end))+double(obj.hdr.vox_offset); [pth,nam,ext] = fileparts(obj.dat.fname); if any(strcmp(deblank(obj.hdr.magic),{'n+1','nx1'})), ext = '.nii'; else ext = '.img'; end; iname = fullfile(pth,[nam ext]); fp = fopen(iname,'a+'); if fp==-1, error(['Unable to create image for "' fname '".']); end; fseek(fp,0,'eof'); pos = ftell(fp); if pos<nbytes, bs = 2048; % Buffer-size nbytes = nbytes - pos; buf = uint8(0); buf(bs) = 0; while(nbytes>0) if nbytes<bs, buf = buf(1:nbytes); end; nw = fwrite(fp,buf,'uint8'); if nw<min(bs,nbytes), fclose(fp); error(['Problem while creating image for "' fname '".']); end; nbytes = nbytes - nw; end; end; fclose(fp); end; return;
github
lcnbeapp/beapp-master
getdict.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@nifti/private/getdict.m
5,184
utf_8
eebe7d552eb3613897e82d860005c90e
function d = getdict % Dictionary of NIFTI stuff % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ persistent dict; if ~isempty(dict), d = dict; return; end; % Datatype t = true; f = false; table = {... 0 ,'UNKNOWN' ,'uint8' ,@uint8 ,1,1 ,t,t,f 1 ,'BINARY' ,'uint1' ,@logical,1,1/8,t,t,f 256 ,'INT8' ,'int8' ,@int8 ,1,1 ,t,f,t 2 ,'UINT8' ,'uint8' ,@uint8 ,1,1 ,t,t,t 4 ,'INT16' ,'int16' ,@int16 ,1,2 ,t,f,t 512 ,'UINT16' ,'uint16' ,@uint16 ,1,2 ,t,t,t 8 ,'INT32' ,'int32' ,@int32 ,1,4 ,t,f,t 768 ,'UINT32' ,'uint32' ,@uint32 ,1,4 ,t,t,t 1024,'INT64' ,'int64' ,@int64 ,1,8 ,t,f,f 1280,'UINT64' ,'uint64' ,@uint64 ,1,8 ,t,t,f 16 ,'FLOAT32' ,'float32' ,@single ,1,4 ,f,f,t 64 ,'FLOAT64' ,'double' ,@double ,1,8 ,f,f,t 1536,'FLOAT128' ,'float128',@crash ,1,16 ,f,f,f 32 ,'COMPLEX64' ,'float32' ,@single ,2,4 ,f,f,f 1792,'COMPLEX128','double' ,@double ,2,8 ,f,f,f 2048,'COMPLEX256','float128',@crash ,2,16 ,f,f,f 128 ,'RGB24' ,'uint8' ,@uint8 ,3,1 ,t,t,f}; dtype = struct(... 'code' ,table(:,1),... 'label' ,table(:,2),... 'prec' ,table(:,3),... 'conv' ,table(:,4),... 'nelem' ,table(:,5),... 'size' ,table(:,6),... 'isint' ,table(:,7),... 'unsigned' ,table(:,8),... 'min',-Inf,'max',Inf',... 'supported',table(:,9)); for i=1:length(dtype), if dtype(i).isint if dtype(i).unsigned dtype(i).min = 0; dtype(i).max = 2^(8*dtype(i).size)-1; else dtype(i).min = -2^(8*dtype(i).size-1); dtype(i).max = 2^(8*dtype(i).size-1)-1; end; end; end; % Intent table = {... 0 ,'NONE' ,'None',{} 2 ,'CORREL' ,'Correlation statistic',{'DOF'} 3 ,'TTEST' ,'T-statistic',{'DOF'} 4 ,'FTEST' ,'F-statistic',{'numerator DOF','denominator DOF'} 5 ,'ZSCORE' ,'Z-score',{} 6 ,'CHISQ' ,'Chi-squared distribution',{'DOF'} 7 ,'BETA' ,'Beta distribution',{'a','b'} 8 ,'BINOM' ,'Binomial distribution',... {'number of trials','probability per trial'} 9 ,'GAMMA' ,'Gamma distribution',{'shape','scale'} 10 ,'POISSON' ,'Poisson distribution',{'mean'} 11 ,'NORMAL' ,'Normal distribution',{'mean','standard deviation'} 12 ,'FTEST_NONC' ,'F-statistic noncentral',... {'numerator DOF','denominator DOF','numerator noncentrality parameter'} 13 ,'CHISQ_NONC' ,'Chi-squared noncentral',{'DOF','noncentrality parameter'} 14 ,'LOGISTIC' ,'Logistic distribution',{'location','scale'} 15 ,'LAPLACE' ,'Laplace distribution',{'location','scale'} 16 ,'UNIFORM' ,'Uniform distribition',{'lower end','upper end'} 17 ,'TTEST_NONC' ,'T-statistic noncentral',{'DOF','noncentrality parameter'} 18 ,'WEIBULL' ,'Weibull distribution',{'location','scale','power'} 19 ,'CHI' ,'Chi distribution',{'DOF'} 20 ,'INVGAUSS' ,'Inverse Gaussian distribution',{'mu','lambda'} 21 ,'EXTVAL' ,'Extreme Value distribution',{'location','scale'} 22 ,'PVAL' ,'P-value',{} 23 ,'LOGPVAL' ,'Log P-value',{} 24 ,'LOG10PVAL' ,'Log_10 P-value',{} 1001,'ESTIMATE' ,'Estimate',{} 1002,'LABEL' ,'Label index',{} 1003,'NEURONAMES' ,'NeuroNames index',{} 1004,'MATRIX' ,'General matrix',{'M','N'} 1005,'MATRIX_SYM' ,'Symmetric matrix',{} 1006,'DISPLACEMENT' ,'Displacement vector',{} 1007,'VECTOR' ,'Vector',{} 1008,'POINTS' ,'Pointset',{} 1009,'TRIANGLE' ,'Triangle',{} 1010,'QUATERNION' ,'Quaternion',{} 1011,'DIMLESS' ,'Dimensionless',{} }; intent = struct('code',table(:,1),'label',table(:,2),... 'fullname',table(:,3),'param',table(:,4)); % Units table = {... 0, 1,'UNKNOWN' 1,1000,'m' 2, 1,'mm' 3,1e-3,'um' 8, 1,'s' 16,1e-3,'ms' 24,1e-6,'us' 32, 1,'Hz' 40, 1,'ppm' 48, 1,'rads'}; units = struct('code',table(:,1),'label',table(:,3),'rescale',table(:,2)); % Reference space % code = {0,1,2,3,4}; table = {... 0,'UNKNOWN' 1,'Scanner Anat' 2,'Aligned Anat' 3,'Talairach' 4,'MNI_152'}; anat = struct('code',table(:,1),'label',table(:,2)); % Slice Ordering table = {... 0,'UNKNOWN' 1,'sequential_increasing' 2,'sequential_decreasing' 3,'alternating_increasing' 4,'alternating_decreasing'}; sliceorder = struct('code',table(:,1),'label',table(:,2)); % Q/S Form Interpretation table = {... 0,'UNKNOWN' 1,'Scanner' 2,'Aligned' 3,'Talairach' 4,'MNI152'}; xform = struct('code',table(:,1),'label',table(:,2)); dict = struct('dtype',dtype,'intent',intent,'units',units,... 'space',anat,'sliceorder',sliceorder,'xform',xform); d = dict; return; function varargout = crash(varargin) error('There is a NIFTI-1 data format problem (an invalid datatype).');
github
lcnbeapp/beapp-master
write_extras.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/spm8/@nifti/private/write_extras.m
829
utf_8
598b84950ce613b42919ce1f50a59132
function extras = write_extras(fname,extras) % Write extra bits of information %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id$ [pth,nam,ext] = fileparts(fname); switch ext case {'.hdr','.img','.nii'} mname = fullfile(pth,[nam '.mat']); case {'.HDR','.IMG','.NII'} mname = fullfile(pth,[nam '.MAT']); otherwise mname = fullfile(pth,[nam '.mat']); end if isstruct(extras) && ~isempty(fieldnames(extras)), savefields(mname,extras); end; function savefields(fnam,p) if length(p)>1, error('Can''t save fields.'); end; fn = fieldnames(p); for i_=1:length(fn), eval([fn{i_} '= p.' fn{i_} ';']); end; if str2num(version('-release'))>=14, fn = {'-V6',fn{:}}; end; if numel(fn)>0, save(fnam,fn{:}); end; return;
github
lcnbeapp/beapp-master
delete.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@xmltree/delete.m
1,189
utf_8
9ca7b2db1b9fc84848585e118ac9d026
function tree = delete(tree,uid) % XMLTREE/DELETE Delete (delete a subtree given its UID) % % tree - XMLTree object % uid - array of UID's of subtrees to be deleted %__________________________________________________________________________ % % Delete a subtree given its UID % The tree parameter must be in input AND in output %__________________________________________________________________________ % Copyright (C) 2002-2011 http://www.artefact.tk/ % Guillaume Flandin % $Id: delete.m 4460 2011-09-05 14:52:16Z guillaume $ %error(nargchk(2,2,nargin)); uid = uid(:); for i=1:length(uid) if uid(i)==1 warning('[XMLTree] Cannot delete root element.'); else p = tree.tree{uid(i)}.parent; tree = sub_delete(tree,uid(i)); tree.tree{p}.contents(find(tree.tree{p}.contents==uid(i))) = []; end end %========================================================================== function tree = sub_delete(tree,uid) if isfield(tree.tree{uid},'contents') for i=1:length(tree.tree{uid}.contents) tree = sub_delete(tree,tree.tree{uid}.contents(i)); end end tree.tree{uid} = struct('type','deleted');
github
lcnbeapp/beapp-master
save.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@xmltree/save.m
5,114
utf_8
1c7adbb3f79946f51f25d9031fcb515c
function varargout = save(tree, filename) % XMLTREE/SAVE Save an XML tree in an XML file % FORMAT varargout = save(tree,filename) % % tree - XMLTree % filename - XML output filename % varargout - XML string %__________________________________________________________________________ % % Convert an XML tree into a well-formed XML string and write it into % a file or return it as a string if no filename is provided. %__________________________________________________________________________ % Copyright (C) 2002-2011 http://www.artefact.tk/ % Guillaume Flandin % $Id: save.m 4460 2011-09-05 14:52:16Z guillaume $ %error(nargchk(1,2,nargin)); prolog = '<?xml version="1.0" ?>\n'; %- Return the XML tree as a string if nargin == 1 varargout{1} = [sprintf(prolog) ... print_subtree(tree,'',root(tree))]; %- Output specified else %- Filename provided if ischar(filename) [fid, msg] = fopen(filename,'w'); if fid==-1, error(msg); end if isempty(tree.filename), tree.filename = filename; end %- File identifier provided elseif isnumeric(filename) && numel(filename) == 1 fid = filename; prolog = ''; %- With this option, do not write any prolog else error('[XMLTree] Invalid argument.'); end fprintf(fid,prolog); save_subtree(tree,fid,root(tree)); if ischar(filename), fclose(fid); end if nargout == 1 varargout{1} = print_subtree(tree,'',root(tree)); end end %========================================================================== function xmlstr = print_subtree(tree,xmlstr,uid,order) if nargin < 4, order = 0; end xmlstr = [xmlstr blanks(3*order)]; switch tree.tree{uid}.type case 'element' xmlstr = sprintf('%s<%s',xmlstr,tree.tree{uid}.name); for i=1:length(tree.tree{uid}.attributes) xmlstr = sprintf('%s %s="%s"', xmlstr, ... tree.tree{uid}.attributes{i}.key,... tree.tree{uid}.attributes{i}.val); end if isempty(tree.tree{uid}.contents) xmlstr = sprintf('%s/>\n',xmlstr); else xmlstr = sprintf('%s>\n',xmlstr); for i=1:length(tree.tree{uid}.contents) xmlstr = print_subtree(tree,xmlstr, ... tree.tree{uid}.contents(i),order+1); end xmlstr = [xmlstr blanks(3*order)]; xmlstr = sprintf('%s</%s>\n',xmlstr,... tree.tree{uid}.name); end case 'chardata' xmlstr = sprintf('%s%s\n',xmlstr, ... entity(tree.tree{uid}.value)); case 'cdata' xmlstr = sprintf('%s<![CDATA[%s]]>\n',xmlstr, ... tree.tree{uid}.value); case 'pi' xmlstr = sprintf('%s<?%s %s?>\n',xmlstr, ... tree.tree{uid}.target, tree.tree{uid}.value); case 'comment' xmlstr = sprintf('%s<!-- %s -->\n',xmlstr,... tree.tree{uid}.value); otherwise warning(sprintf('Type %s unknown: not saved', ... tree.tree{uid}.type)); end %========================================================================== function save_subtree(tree,fid,uid,order) if nargin < 4, order = 0; end fprintf(fid,blanks(3*order)); switch tree.tree{uid}.type case 'element' fprintf(fid,'<%s',tree.tree{uid}.name); for i=1:length(tree.tree{uid}.attributes) fprintf(fid,' %s="%s"',... tree.tree{uid}.attributes{i}.key, ... tree.tree{uid}.attributes{i}.val); end if isempty(tree.tree{uid}.contents) fprintf(fid,'/>\n'); else fprintf(fid,'>\n'); for i=1:length(tree.tree{uid}.contents) save_subtree(tree,fid,... tree.tree{uid}.contents(i),order+1) end fprintf(fid,blanks(3*order)); fprintf(fid,'</%s>\n',tree.tree{uid}.name); end case 'chardata' fprintf(fid,'%s\n',entity(tree.tree{uid}.value)); case 'cdata' fprintf(fid,'<![CDATA[%s]]>\n',tree.tree{uid}.value); case 'pi' fprintf(fid,'<?%s %s?>\n',tree.tree{uid}.target, ... tree.tree{uid}.value); case 'comment' fprintf(fid,'<!-- %s -->\n',tree.tree{uid}.value); otherwise warning(sprintf('[XMLTree] Type %s unknown: not saved', ... tree.tree{uid}.type)); end %========================================================================== function str = entity(str) % This has the side effect of strtrim'ming the char array. str = char(strrep(cellstr(str), '&', '&amp;' )); str = char(strrep(cellstr(str), '<', '&lt;' )); str = char(strrep(cellstr(str), '>', '&gt;' )); str = char(strrep(cellstr(str), '"', '&quot;')); str = char(strrep(cellstr(str), '''', '&apos;'));
github
lcnbeapp/beapp-master
branch.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@xmltree/branch.m
1,750
utf_8
407ff520e9de6dc9150a5b4f44d75c90
function subtree = branch(tree,uid) % XMLTREE/BRANCH Branch Method % FORMAT uid = parent(tree,uid) % % tree - XMLTree object % uid - UID of the root element of the subtree % subtree - XMLTree object (a subtree from tree) %__________________________________________________________________________ % % Return a subtree from a tree. %__________________________________________________________________________ % Copyright (C) 2002-2011 http://www.artefact.tk/ % Guillaume Flandin % $Id: branch.m 4460 2011-09-05 14:52:16Z guillaume $ %error(nargchk(2,2,nargin)); if uid > length(tree) || ... numel(uid)~=1 || ... ~strcmp(tree.tree{uid}.type,'element') error('[XMLTree] Invalid UID.'); end subtree = xmltree; subtree = set(subtree,root(subtree),'name',tree.tree{uid}.name); %- fix by Piotr Dollar to copy attributes for the root node: subtree = set(subtree,root(subtree),'attributes',tree.tree{uid}.attributes); child = children(tree,uid); for i=1:length(child) l = length(subtree); subtree = sub_branch(tree,subtree,child(i),root(subtree)); subtree.tree{root(subtree)}.contents = [subtree.tree{root(subtree)}.contents l+1]; end %========================================================================== function tree = sub_branch(t,tree,uid,p) l = length(tree); tree.tree{l+1} = t.tree{uid}; tree.tree{l+1}.uid = l + 1; tree.tree{l+1}.parent = p; tree.tree{l+1}.contents = []; if isfield(t.tree{uid},'contents') contents = get(t,uid,'contents'); m = length(tree); for i=1:length(contents) tree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1]; tree = sub_branch(t,tree,contents(i),l+1); m = length(tree); end end
github
lcnbeapp/beapp-master
flush.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@xmltree/flush.m
1,413
utf_8
64502185e2efb9de8f36e36751a39517
function tree = flush(tree,uid) % XMLTREE/FLUSH Flush (Clear a subtree given its UID) % % tree - XMLTree object % uid - array of UID's of subtrees to be cleared % Default is root %__________________________________________________________________________ % % Clear a subtree given its UID (remove all the leaves of the tree) % The tree parameter must be in input AND in output %__________________________________________________________________________ % Copyright (C) 2002-2011 http://www.artefact.tk/ % Guillaume Flandin % $Id: flush.m 4460 2011-09-05 14:52:16Z guillaume $ %error(nargchk(1,2,nargin)); if nargin == 1, uid = root(tree); end uid = uid(:); for i=1:length(uid) tree = sub_flush(tree,uid(i)); end %========================================================================== function tree = sub_flush(tree,uid) if isfield(tree.tree{uid},'contents') % contents is parsed in reverse order because each child is % deleted and the contents vector is then eventually reduced for i=length(tree.tree{uid}.contents):-1:1 tree = sub_flush(tree,tree.tree{uid}.contents(i)); end end if strcmp(tree.tree{uid}.type,'chardata') ||... strcmp(tree.tree{uid}.type,'pi') ||... strcmp(tree.tree{uid}.type,'cdata') ||... strcmp(tree.tree{uid}.type,'comment') tree = delete(tree,uid); end
github
lcnbeapp/beapp-master
copy.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@xmltree/copy.m
1,634
utf_8
e6df62a4f41243b78ed8c517b15e493b
function tree = copy(tree,subuid,uid) % XMLTREE/COPY Copy Method (copy a subtree in another branch) % FORMAT tree = copy(tree,subuid,uid) % % tree - XMLTree object % subuid - UID of the subtree to copy % uid - UID of the element where the subtree must be duplicated %__________________________________________________________________________ % % Copy a subtree to another branch. % The tree parameter must be in input AND in output. %__________________________________________________________________________ % Copyright (C) 2002-2015 http://www.artefact.tk/ % Guillaume Flandin % $Id: copy.m 6480 2015-06-13 01:08:30Z guillaume $ %error(nargchk(2,3,nargin)); if nargin == 2 uid = parent(tree,subuid); end l = length(tree); tree = sub_copy(tree,subuid,uid); tree.tree{uid}.contents = [tree.tree{uid}.contents l+1]; % to have the copy next to the original and not at the end? % contents = get(tree,parent,'contents'); % i = find(contents==uid); % tree = set(tree,parent,'contents',[contents(1:i) l+1 contents(i+1:end)]); %========================================================================== function tree = sub_copy(tree,uid,p) l = length(tree); tree.tree{l+1} = tree.tree{uid}; tree.tree{l+1}.uid = l+1; tree.tree{l+1}.parent = p; tree.tree{l+1}.contents = []; if isfield(tree.tree{uid},'contents') contents = get(tree,uid,'contents'); m = length(tree); for i=1:length(contents) tree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1]; tree = sub_copy(tree,contents(i),l+1); m = length(tree); end end
github
lcnbeapp/beapp-master
convert.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@xmltree/convert.m
5,573
utf_8
05b85174fb85e5d62de81654b76ef7ab
function s = convert(tree,uid) % XMLTREE/CONVERT Converter an XML tree in a structure % % tree - XMLTree object % uid - uid of the root of the subtree, if provided. % Default is root % s - converted structure %__________________________________________________________________________ % % Convert an XMLTree into a structure, when possible. % When several identical tags are present, a cell array is used. % The root tag is not saved in the structure. % If provided, only the structure corresponding to the subtree defined % by the uid UID is returned. %__________________________________________________________________________ % Copyright (C) 2002-2015 http://www.artefact.tk/ % Guillaume Flandin % $Id: convert.m 6480 2015-06-13 01:08:30Z guillaume $ % Exemple: % tree = '<a><b>field1</b><c>field2</c><b>field3</b></a>'; % toto = convert(xmltree(tree)); % <=> toto = struct('b',{{'field1', 'field3'}},'c','field2') %error(nargchk(1,2,nargin)); % Get the root uid of the output structure if nargin == 1 % Get the root uid of the XML tree root_uid = root(tree); else % Uid provided by user root_uid = uid; end % Initialize the output structure % struct([]) should be used but this only works with Matlab 6 % So we create a field that we delete at the end %s = struct(get(tree,root_uid,'name'),''); % struct([]) s = struct('deletedummy',''); %s = sub_convert(tree,s,root_uid,{get(tree,root_uid,'name')}); s = sub_convert(tree,s,root_uid,{}); s = rmfield(s,'deletedummy'); %========================================================================== function s = sub_convert(tree,s,uid,arg) type = get(tree,uid,'type'); switch type case 'element' child = children(tree,uid); l = {}; ll = {}; for i=1:length(child) if isfield(tree,child(i),'name') ll = { ll{:}, get(tree,child(i),'name') }; end end for i=1:length(child) if isfield(tree,child(i),'name') name = get(tree,child(i),'name'); nboccur = sum(ismember(l,name)); nboccur2 = sum(ismember(ll,name)); l = { l{:}, name }; if nboccur || (nboccur2>1) arg2 = { arg{:}, name, {nboccur+1} }; else arg2 = { arg{:}, name}; end else arg2 = arg; end s = sub_convert(tree,s,child(i),arg2); end if isempty(child) s = sub_setfield(s,arg{:},''); end %- saving attributes : does not work with <a t='q'>b</a> %- but ok with <a t='q'><c>b</c></a> % attrb = attributes(tree,'get',uid); %- % if ~isempty(attrb) %- % arg2 = {arg{:} 'attributes'}; %- % s = sub_setfield(s,arg2{:},attrb); %- % end %- case 'chardata' s = sub_setfield(s,arg{:},get(tree,uid,'value')); %- convert strings into their numerical equivalent when possible %- e.g. string '3.14159' becomes double scalar 3.14159 % v = get(tree,uid,'value'); %- % cv = str2num(v); %- % if isempty(cv) %- % s = sub_setfield(s,arg{:},v); %- % else %- % s = sub_setfield(s,arg{:},cv); %- % end %- case 'cdata' s = sub_setfield(s,arg{:},get(tree,uid,'value')); case 'pi' % Processing instructions are evaluated if possible app = get(tree,uid,'target'); switch app case {'matlab',''} s = sub_setfield(s,arg{:},eval(get(tree,uid,'value'))); case 'unix' s = sub_setfield(s,arg{:},unix(get(tree,uid,'value'))); case 'dos' s = sub_setfield(s,arg{:},dos(get(tree,uid,'value'))); case 'system' s = sub_setfield(s,arg{:},system(get(tree,uid,'value'))); otherwise try s = sub_setfield(s,arg{:},feval(app,get(tree,uid,'value'))); catch warning('[XMLTree] Unknown target application'); end end case 'comment' % Comments are forgotten otherwise warning(sprintf('Type %s unknown : not saved',get(tree,uid,'type'))); end %========================================================================== function s = sub_setfield(s,varargin) % Same as setfield but using '{}' rather than '()' %if (isempty(varargin) | length(varargin) < 2) % error('Not enough input arguments.'); %end subs = varargin(1:end-1); for i = 1:length(varargin)-1 if (isa(varargin{i}, 'cell')) types{i} = '{}'; elseif ischar(varargin{i}) types{i} = '.'; subs{i} = varargin{i}; %strrep(varargin{i},' ',''); % deblank field name else error('Inputs must be either cell arrays or strings.'); end end % Perform assignment try s = builtin('subsasgn', s, struct('type',types,'subs',subs), varargin{end}); catch error(lasterr) end
github
lcnbeapp/beapp-master
editor.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@xmltree/editor.m
12,418
utf_8
80850644600bde45b47898d068ef0978
function editor(tree) %XMLTREE/EDITOR A Graphical User Interface for an XML tree % EDITOR(TREE) opens a new figure displaying the xmltree object TREE. % H = EDITOR(TREE) also returns the figure handle H. % % This is a beta version of <xmltree/view> successor % % See also XMLTREE %__________________________________________________________________________ % Copyright (C) 2002-2015 http://www.artefact.tk/ % Guillaume Flandin % $Id: editor.m 6480 2015-06-13 01:08:30Z guillaume $ %error(nargchk(1,1,nargin)); if ~isempty(getfilename(tree)) title = getfilename(tree); elseif ~isempty(inputname(1)) title = ['Variable ''' inputname(1) '''']; else title = 'Untitled'; end h = initWindow(title); setappdata(h,'handles',guihandles(h)); setappdata(h,'save',0); tree = set(tree,root(tree),'show',1); setappdata(h,'tree',tree); doUpdate([],[],h); set(h,'HandleVisibility','callback'); %========================================================================== function h = initWindow(title) wincolor = struct('bg', [0.8 0.8 0.8], ... 'fg', [1.0 1.0 1.0], ... 'title', [0.9 0.9 0.9]); title = [':: XMLTree Editor :: ' title]; h = figure('Name', title, ... 'Units', 'Points', ... 'NumberTitle', 'off', ... 'Resize', 'on', ... 'Color', wincolor.bg,... 'Position', [200 200 440 330], ... 'MenuBar', 'none', ... 'Tag', mfilename); set(h, 'CloseRequestFcn', {@doClose,h}); %- Left box uicontrol('Style', 'listbox', ... 'HorizontalAlignment','left', ... 'Units','Normalized', ... 'Visible','on',... 'BackgroundColor', wincolor.fg, ... 'Max', 1, ... 'Value', 1 , ... 'Enable', 'on', ... 'Position', [0.04 0.12 0.3 0.84], ... 'Callback', {@doList,h}, ... 'String', ' ', ... 'Tag', 'xmllistbox'); %- Right box uicontrol('Style', 'listbox', ... 'HorizontalAlignment','left', ... 'Units','Normalized', ... 'Visible','on',... 'BackgroundColor', wincolor.bg, ... 'Min', 0, ... 'Max', 2, ... 'Value', [], ... 'Enable', 'inactive', ... 'Position', [0.38 0.50 0.58 0.46], ... 'Callback', '', ... 'String', ' ', ... 'Tag', 'xmllist'); %- The Add button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.04 0.03 0.11 0.06], ... 'String', 'Add', ... 'Enable','on',... 'Tag', 'addbutton', ... 'Callback', {@doAdd,h}); %- The Modify button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.175 0.03 0.11 0.06], ... 'String', 'Modify', ... 'Enable','on',... 'Tag', 'modifybutton', ... 'Callback', {@doModify,h}); %- The Copy button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.310 0.03 0.11 0.06], ... 'String', 'Copy', ... 'Enable','on',... 'Tag', 'copybutton', ... 'Callback', {@doCopy,h}); %- The Delete button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.445 0.03 0.11 0.06], ... 'String', 'Delete', ... 'Enable','on',... 'Tag', 'delbutton', ... 'Callback', {@doDelete,h}); %- The Save button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.580 0.03 0.11 0.06], ... 'String', 'Save', ... 'Tag', 'savebutton', ... 'Callback', {@doSave,h}); %- The Run button %uicontrol('Style', 'pushbutton', ... % 'Units', 'Normalized', ... % 'Position', [0.715 0.03 0.11 0.06], ... % 'String', 'Run', ... % 'Enable', 'off', ... % 'Tag', 'runbutton', ... % 'Callback', {@doRun,h}); %- The Attributes button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.715 0.03 0.11 0.06], ... 'String', 'Attr.', ... 'Enable', 'on', ... 'Tag', 'runbutton', ... 'Callback', {@doAttributes,h}); %- The Close button uicontrol('Style', 'pushbutton', ... 'Units', 'Normalized', ... 'Position', [0.850 0.03 0.11 0.06], ... 'String', 'Close', ... 'Tag', 'closebutton', ... 'Callback', {@doClose,h}); %========================================================================== function doClose(fig,evd,h) s = getappdata(h, 'save'); status = 1; if s button = questdlg(sprintf('Save changes to the XML tree?'),... 'XMLTree Editor','Yes','No','Cancel','Yes'); if strcmp(button,'Yes') status = doSave([],[],h); elseif strcmp(button,'Cancel') status = 0; end end if status delete(h); end function doAdd(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); pos = get(handles.xmllistbox,'value'); uid = uidList(pos); answer = questdlg('Which kind of item to add?', ... 'XMLTree Editor :: Add','Node','Leaf','Node'); switch answer case 'Node' tree = add(tree,uid,'element','New_Node'); case 'Leaf' tree = add(tree,uid,'element','New_Leaf'); l = length(tree); tree = add(tree,l,'chardata','default'); end tree = set(tree,uid,'show',1); setappdata(h, 'tree', tree); setappdata(h, 'save', 1); doUpdate([],[],h); doList([],[],h); function doModify(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); pos = get(handles.xmllistbox,'value'); uid = uidList(pos); contents = children(tree,uid); if length(contents) > 0 && ... strcmp(get(tree,contents(1),'type'),'chardata') str = get(tree,contents(1),'value'); prompt = {'Name :','New value:'}; def = {get(tree,uid,'name'),str}; title = sprintf('Modify %s',get(tree,uid,'name')); lineNo = 1; answer = inputdlg(prompt,title,lineNo,def); if ~isempty(answer) tree = set(tree,uid,'name',answer{1}); str = answer{2}; tree = set(tree,contents(1),'value',str); setappdata(h, 'tree', tree); setappdata(h, 'save', 1); end else str = ['Tag ' get(tree,uid,'name')]; prompt = {'Name :'}; def = {get(tree,uid,'name'),str}; title = sprintf('Modify %s tag',get(tree,uid,'name')); lineNo = 1; answer = inputdlg(prompt,title,lineNo,def); if ~isempty(answer) tree = set(tree,uid,'name',answer{1}); str = ['Tag ' get(tree,uid,'name')]; setappdata(h, 'tree', tree); setappdata(h, 'save', 1); end end %- Trying to keep the slider active set(handles.xmllist, 'Enable', 'on'); set(handles.xmllist, 'String', ' '); set(handles.xmllist, 'Enable', 'Inactive'); set(handles.xmllist, 'String', str); doUpdate([],[],h); doList([],[],h); function doCopy(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); pos = get(handles.xmllistbox,'value'); uid = uidList(pos); if pos ~= 1 tree = copy(tree,uid); setappdata(h, 'tree', tree); setappdata(h, 'save', 1); doUpdate([],[],h); doList([],[],h); end function doDelete(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); pos = get(handles.xmllistbox,'value'); uid = uidList(pos); if pos > 1 tree = delete(tree,uid); set(handles.xmllistbox,'value',pos-1); setappdata(h, 'save', 1); end setappdata(h, 'tree', tree); doUpdate([],[],h); doList([],[],h); function status = doSave(fig,evd,h) tree = getappdata(h, 'tree'); [filename, pathname] = uiputfile({'*.xml' 'XML file (*.xml)'}, ... 'Save XML file as'); status = ~(isequal(filename,0) | isequal(pathname,0)); if status save(tree,fullfile(pathname, filename)); set(h,'Name',[':: XMLTree Editor :: ' filename]); setappdata(h, 'save', 0); end function doRun(fig,evd,h) warndlg('Not implemented','XMLTree :: Run'); function doAttributes(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); pos = get(handles.xmllistbox,'value'); uid = uidList(pos); attr = attributes(tree,'get',uid); if ~isempty(attr) fprintf('This element has %d attributes.\n',length(attr)); %%% %%% Do what you want with 'attr' %%% to modify them, use: %%% tree = attributes(tree,'set',uid,n,key,val) %%% to add one, use: %%% tree = attributes(tree,'add',uid,key,val) %%% to delete one, use: %%% tree = attributes(tree,'del',uid[,n]); %%% setappdata(h, 'tree', tree); setappdata(h, 'save', 1); %- only if attributes have been modified end %========================================================================== function doList(fig,evd,h) tree = getappdata(h, 'tree'); uidList = getappdata(h, 'uidlist'); handles = getappdata(h, 'handles'); uid = uidList(get(handles.xmllistbox, 'value')); %- Single mouse click if strcmp(get(h,'SelectionType'),'normal') contents = children(tree, uid); if length(contents) > 0 && ... strcmp(get(tree,contents(1),'type'),'chardata') str = get(tree,contents(1),'value'); set(handles.addbutton,'Enable','off'); elseif length(contents) == 0 str = ''; tree = add(tree,uid,'chardata',str); setappdata(h, 'tree', tree); set(handles.addbutton,'Enable','off'); else str = ['Tag ' get(tree,uid,'name')]; set(handles.addbutton,'Enable','on'); end if get(handles.xmllistbox,'value') == 1 set(handles.copybutton,'Enable','off'); set(handles.delbutton,'Enable','off'); else set(handles.copybutton,'Enable','on'); set(handles.delbutton,'Enable','on'); end %- Trying to keep the slider active set(handles.xmllist, 'Enable', 'on'); set(handles.xmllist, 'String', ' '); set(handles.xmllist, 'Enable', 'Inactive'); set(handles.xmllist, 'String', str); %- Double mouse click else tree = doFlip(tree, uid); setappdata(h, 'tree', tree); doUpdate([],[],h); end function doUpdate(fig,evd,h) tree = getappdata(h, 'tree'); handles = getappdata(h, 'handles'); [batchString, uidList] = doUpdateR(tree); set(handles.xmllistbox, 'String', batchString); setappdata(h, 'uidlist', uidList); %========================================================================== function [batchString, uidList] = doUpdateR(tree, uid, o) if nargin < 2, uid = root(tree); end if nargin < 3 || o == 0 o = 0; sep = ' '; else sep = blanks(4*o); end if attributes(tree,'length',uid) > 0 batchString = {[sep, get(tree, uid, 'name') ' *']}; else batchString = {[sep, get(tree, uid, 'name')]}; end uidList = [get(tree,uid,'uid')]; haselementchild = 0; contents = get(tree, uid, 'contents'); if isfield(tree, uid, 'show') && get(tree, uid, 'show') == 1 for i=1:length(contents) if strcmp(get(tree,contents(i),'type'),'element') [subbatchString, subuidList] = doUpdateR(tree,contents(i),o+1); batchString = {batchString{:} subbatchString{:}}; uidList = [uidList subuidList]; haselementchild = 1; end end if haselementchild == 1, batchString{1}(length(sep)) = '-'; end else for i=1:length(contents) if strcmp(get(tree,contents(i),'type'),'element') haselementchild = 1; end end if haselementchild == 1, batchString{1}(length(sep)) = '+'; end end function tree = doFlip(tree, uid) if isfield(tree,uid,'show') show = get(tree,uid,'show'); else show = 0; end tree = set(tree,uid,'show',~show);
github
lcnbeapp/beapp-master
find.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@xmltree/find.m
5,901
utf_8
b241bfaac569f137b8b809b7b66765f3
function list = find(varargin) % XMLTREE/FIND Find elements in a tree with specified characteristics % FORMAT list = find(varargin) % % tree - XMLTree object % xpath - string path with specific grammar (XPath) % uid - lists of root uid's % parameter/value - pair of pattern % list - list of uid's of matched elements % % list = find(tree,xpath) % list = find(tree,parameter,value[,parameter,value]) % list = find(tree,uid,parameter,value[,parameter,value]) % % Grammar for addressing parts of an XML document: % XML Path Language XPath (http://www.w3.org/TR/xpath) % Example: /element1//element2[1]/element3[5]/element4 %__________________________________________________________________________ % % Find elements in an XML tree with specified characteristics or given % a path (using a subset of XPath language). %__________________________________________________________________________ % Copyright (C) 2002-2011 http://www.artefact.tk/ % Guillaume Flandin % $Id: find.m 4460 2011-09-05 14:52:16Z guillaume $ % TODO: % - clean up subroutines % - find should only be documented using XPath (other use is internal) % - handle '*', 'last()' in [] and '@' % - if a key is invalid, should rather return [] than error ? if nargin==0 error('[XMLTree] A tree must be provided'); elseif nargin==1 list = 1:length(tree.tree); return elseif mod(nargin,2) list = sub_find_subtree1(varargin{1}.tree,root(varargin{1}),varargin{2:end}); elseif isa(varargin{2},'double') && ... ndims(varargin{2}) == 2 && ... min(size(varargin{2})) == 1 list = unique(sub_find_subtree1(varargin{1}.tree,varargin{2:end})); elseif nargin==2 && ischar(varargin{2}) list = sub_pathfinder(varargin{:}); else error('[XMLTree] Arguments must be parameter/value pairs.'); end %========================================================================== function list = sub_find_subtree1(varargin) list = []; for i=1:length(varargin{2}) res = sub_find_subtree2(varargin{1},... varargin{2}(i),varargin{3:end}); list = [list res]; end %========================================================================== function list = sub_find_subtree2(varargin) uid = varargin{2}; list = []; if sub_comp_element(varargin{1}{uid},varargin{3:end}) list = [list varargin{1}{uid}.uid]; end if isfield(varargin{1}{uid},'contents') list = [list sub_find_subtree1(varargin{1},... varargin{1}{uid}.contents,varargin{3:end})]; end %========================================================================== function match = sub_comp_element(varargin) match = 0; try % v = getfield(varargin{1}, varargin{2}); % slow... for i=1:floor(nargin/2) v = subsref(varargin{1}, struct('type','.','subs',varargin{i+1})); if strcmp(v,varargin{i+2}) match = 1; end end catch end % More powerful but much slower %match = 0; %for i=1:length(floor(nargin/2)) % bug: remove length !!! % if isfield(varargin{1},varargin{i+1}) % if ischar(getfield(varargin{1},varargin{i+1})) & ischar(varargin{i+2}) % if strcmp(getfield(varargin{1},varargin{i+1}),char(varargin{i+2})) % match = 1; % end % elseif isa(getfield(varargin{1},varargin{i+1}),'double') & ... % isa(varargin{i+2},'double') % if getfield(varargin{1},varargin{i+1}) == varargin{i+2} % match = 1; % end % else % warning('Cannot compare different objects'); % end % end %end %========================================================================== function list = sub_pathfinder(tree,pth) %- Search for the delimiter '/' in the path i = strfind(pth,'/'); %- Begin search by root list = root(tree); %- Walk through the tree j = 1; while j <= length(i) %- Look for recursion '//' if j<length(i) && i(j+1)==i(j)+1 recursive = 1; j = j + 1; else recursive = 0; end %- Catch the current tag 'element[x]' if j ~= length(i) element = pth(i(j)+1:i(j+1)-1); else element = pth(i(j)+1:end); end %- Search for [] brackets k = xml_findstr(element,'[',1,1); %- If brackets are present in current element if ~isempty(k) l = xml_findstr(element,']',1,1); val = str2num(element(k+1:l-1)); element = element(1:k-1); end %- Use recursivity if recursive list = find(tree,list,'name',element); %- Just look at children else if i(j)==1 % if '/root/...' (list = root(tree) in that case) if sub_comp_element(tree.tree{list},'name',element) % list = 1; % list still contains root(tree) else list = []; return; end else list = sub_findchild(tree,list,element); end end % If an element is specified using a key if ~isempty(k) if val < 1 || val > length(list)+1 error('[XMLTree] Bad key in the path.'); elseif val == length(list)+1 list = []; return; end list = list(val); end if isempty(list), return; end j = j + 1; end %========================================================================== function list = sub_findchild(tree,listt,elmt) list = []; for a=1:length(listt) for b=1:length(tree.tree{listt(a)}.contents) if sub_comp_element(tree.tree{tree.tree{listt(a)}.contents(b)},'name',elmt) list = [list tree.tree{tree.tree{listt(a)}.contents(b)}.uid]; end end end
github
lcnbeapp/beapp-master
xml_parser.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@xmltree/private/xml_parser.m
16,192
utf_8
7e44abd21a10863623b455d03e0651bb
function tree = xml_parser(xmlstr) % XML (eXtensible Markup Language) Processor % FORMAT tree = xml_parser(xmlstr) % % xmlstr - XML string to parse % tree - tree structure corresponding to the XML file %__________________________________________________________________________ % % xml_parser.m is an XML 1.0 (http://www.w3.org/TR/REC-xml) parser. % It aims to be fully conforming. It is currently not a validating % XML processor. % % A description of the tree structure provided in output is detailed in % the header of this m-file. %__________________________________________________________________________ % Copyright (C) 2002-2015 http://www.artefact.tk/ % Guillaume Flandin % $Id: xml_parser.m 6480 2015-06-13 01:08:30Z guillaume $ % XML Processor for GNU Octave and MATLAB (The Mathworks, Inc.) % Copyright (C) 2002-2015 Guillaume Flandin <[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 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 Pl. - Suite 330, Boston, MA 02111-1307, USA. %-------------------------------------------------------------------------- % Suggestions for improvement and fixes are always welcome, although no % guarantee is made whether and when they will be implemented. % Send requests to <[email protected]> % Check also the latest developments on the following webpage: % <http://www.artefact.tk/software/matlab/xml/> %-------------------------------------------------------------------------- % The implementation of this XML parser is much inspired from a % Javascript parser that used to be available at <http://www.jeremie.com/> % A C-MEX file xml_findstr.c is also required, to encompass some % limitations of the built-in FINDSTR function. % Compile it on your architecture using 'mex -O xml_findstr.c' command % if the compiled version for your system is not provided. % If this function does not behave as expected, comment the line % '#define __HACK_MXCHAR__' in xml_findstr.c and compile it again. %-------------------------------------------------------------------------- % Structure of the output tree: % There are 5 types of nodes in an XML file: element, chardata, cdata, % pi and comment. % Each of them contains an UID (Unique Identifier): an integer between % 1 and the number of nodes of the XML file. % % element (a tag <name key="value"> [contents] </name> % |_ type: 'element' % |_ name: string % |_ attributes: cell array of struct 'key' and 'value' or [] % |_ contents: double array of uid's or [] if empty % |_ parent: uid of the parent ([] if root) % |_ uid: double % % chardata (a character array) % |_ type: 'chardata' % |_ value: string % |_ parent: uid of the parent % |_ uid: double % % cdata (a litteral string <![CDATA[value]]>) % |_ type: 'cdata' % |_ value: string % |_ parent: uid of the parent % |_ uid: double % % pi (a processing instruction <?target value ?>) % |_ type: 'pi' % |_ target: string (may be empty) % |_ value: string % |_ parent: uid of the parent % |_ uid: double % % comment (a comment <!-- value -->) % |_ type: 'comment' % |_ value: string % |_ parent: uid of the parent % |_ uid: double % %-------------------------------------------------------------------------- % TODO/BUG/FEATURES: % - [compile] only a warning if TagStart is empty ? % - [attribution] should look for " and ' rather than only " % - [main] with normalize as a preprocessing, CDATA are modified % - [prolog] look for a DOCTYPE in the whole string even if it occurs % only in a far CDATA tag, bug even if the doctype is inside a comment % - [tag_element] erode should replace normalize here % - remove globals? uppercase globals rather persistent (clear mfile)? % - xml_findstr is indeed xml_strfind according to Mathworks vocabulary % - problem with entities: do we need to convert them here? (&eacute;) %-------------------------------------------------------------------------- %- XML string to parse and number of tags read global xmlstring Xparse_count xtree; %- Check input arguments %error(nargchk(1,1,nargin)); if isempty(xmlstr) error('[XML] Not enough parameters.') elseif ~ischar(xmlstr) || sum(size(xmlstr)>1)>1 error('[XML] Input must be a string.') end %- Initialize number of tags (<=> uid) Xparse_count = 0; %- Remove prolog and white space characters from the XML string xmlstring = normalize(prolog(xmlstr)); %- Initialize the XML tree xtree = {}; tree = fragment; tree.str = 1; tree.parent = 0; %- Parse the XML string tree = compile(tree); %- Return the XML tree tree = xtree; %- Remove global variables from the workspace clear global xmlstring Xparse_count xtree; %========================================================================== % SUBFUNCTIONS %-------------------------------------------------------------------------- function frag = compile(frag) global xmlstring xtree Xparse_count; while 1, if length(xmlstring)<=frag.str || ... (frag.str == length(xmlstring)-1 && strcmp(xmlstring(frag.str:end),' ')) return end TagStart = xml_findstr(xmlstring,'<',frag.str,1); if isempty(TagStart) %- Character data error('[XML] Unknown data at the end of the XML file.'); Xparse_count = Xparse_count + 1; xtree{Xparse_count} = chardata; xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:end))); xtree{Xparse_count}.parent = frag.parent; xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; frag.str = ''; elseif TagStart > frag.str if strcmp(xmlstring(frag.str:TagStart-1),' ') %- A single white space before a tag (ignore) frag.str = TagStart; else %- Character data Xparse_count = Xparse_count + 1; xtree{Xparse_count} = chardata; xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:TagStart-1))); xtree{Xparse_count}.parent = frag.parent; xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; frag.str = TagStart; end else if strcmp(xmlstring(frag.str+1),'?') %- Processing instruction frag = tag_pi(frag); else if length(xmlstring)-frag.str>4 && strcmp(xmlstring(frag.str+1:frag.str+3),'!--') %- Comment frag = tag_comment(frag); else if length(xmlstring)-frag.str>9 && strcmp(xmlstring(frag.str+1:frag.str+8),'![CDATA[') %- Litteral data frag = tag_cdata(frag); else %- A tag element (empty (<.../>) or not) if ~isempty(frag.end) endmk = ['/' frag.end '>']; else endmk = '/>'; end if strcmp(xmlstring(frag.str+1:frag.str+length(frag.end)+2),endmk) || ... strcmp(strip(xmlstring(frag.str+1:frag.str+length(frag.end)+2)),endmk) frag.str = frag.str + length(frag.end)+3; return else frag = tag_element(frag); end end end end end end %-------------------------------------------------------------------------- function frag = tag_element(frag) global xmlstring xtree Xparse_count; close = xml_findstr(xmlstring,'>',frag.str,1); if isempty(close) error('[XML] Tag < opened but not closed.'); else empty = strcmp(xmlstring(close-1:close),'/>'); if empty close = close - 1; end starttag = normalize(xmlstring(frag.str+1:close-1)); nextspace = xml_findstr(starttag,' ',1,1); attribs = ''; if isempty(nextspace) name = starttag; else name = starttag(1:nextspace-1); attribs = starttag(nextspace+1:end); end Xparse_count = Xparse_count + 1; xtree{Xparse_count} = element; xtree{Xparse_count}.name = strip(name); if frag.parent xtree{Xparse_count}.parent = frag.parent; xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; end if ~isempty(attribs) xtree{Xparse_count}.attributes = attribution(attribs); end if ~empty contents = fragment; contents.str = close+1; contents.end = name; contents.parent = Xparse_count; contents = compile(contents); frag.str = contents.str; else frag.str = close+2; end end %-------------------------------------------------------------------------- function frag = tag_pi(frag) global xmlstring xtree Xparse_count; close = xml_findstr(xmlstring,'?>',frag.str,1); if isempty(close) warning('[XML] Tag <? opened but not closed.') else nextspace = xml_findstr(xmlstring,' ',frag.str,1); Xparse_count = Xparse_count + 1; xtree{Xparse_count} = pri; if nextspace > close || nextspace == frag.str+2 xtree{Xparse_count}.value = erode(xmlstring(frag.str+2:close-1)); else xtree{Xparse_count}.value = erode(xmlstring(nextspace+1:close-1)); xtree{Xparse_count}.target = erode(xmlstring(frag.str+2:nextspace)); end if frag.parent xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; xtree{Xparse_count}.parent = frag.parent; end frag.str = close+2; end %-------------------------------------------------------------------------- function frag = tag_comment(frag) global xmlstring xtree Xparse_count; close = xml_findstr(xmlstring,'-->',frag.str,1); if isempty(close) warning('[XML] Tag <!-- opened but not closed.') else Xparse_count = Xparse_count + 1; xtree{Xparse_count} = comment; xtree{Xparse_count}.value = erode(xmlstring(frag.str+4:close-1)); if frag.parent xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; xtree{Xparse_count}.parent = frag.parent; end frag.str = close+3; end %-------------------------------------------------------------------------- function frag = tag_cdata(frag) global xmlstring xtree Xparse_count; close = xml_findstr(xmlstring,']]>',frag.str,1); if isempty(close) warning('[XML] Tag <![CDATA[ opened but not closed.') else Xparse_count = Xparse_count + 1; xtree{Xparse_count} = cdata; xtree{Xparse_count}.value = xmlstring(frag.str+9:close-1); if frag.parent xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count]; xtree{Xparse_count}.parent = frag.parent; end frag.str = close+3; end %-------------------------------------------------------------------------- function all = attribution(str) %- Initialize attributs nbattr = 0; all = cell(nbattr); %- Look for 'key="value"' substrings while 1, eq = xml_findstr(str,'=',1,1); if isempty(str) || isempty(eq), return; end id = sort([xml_findstr(str,'"',1,1),xml_findstr(str,'''',1,1)]); id=id(1); nextid = sort([xml_findstr(str,'"',id+1,1),xml_findstr(str,'''',id+1,1)]);nextid=nextid(1); nbattr = nbattr + 1; all{nbattr}.key = strip(str(1:(eq-1))); all{nbattr}.val = entity(str((id+1):(nextid-1))); str = str((nextid+1):end); end %-------------------------------------------------------------------------- function elm = element global Xparse_count; elm = struct('type','element','name','','attributes',[],'contents',[],'parent',[],'uid',Xparse_count); %-------------------------------------------------------------------------- function cdat = chardata global Xparse_count; cdat = struct('type','chardata','value','','parent',[],'uid',Xparse_count); %-------------------------------------------------------------------------- function cdat = cdata global Xparse_count; cdat = struct('type','cdata','value','','parent',[],'uid',Xparse_count); %-------------------------------------------------------------------------- function proce = pri global Xparse_count; proce = struct('type','pi','value','','target','','parent',[],'uid',Xparse_count); %-------------------------------------------------------------------------- function commt = comment global Xparse_count; commt = struct('type','comment','value','','parent',[],'uid',Xparse_count); %-------------------------------------------------------------------------- function frg = fragment frg = struct('str','','parent','','end',''); %-------------------------------------------------------------------------- function str = prolog(str) %- Initialize beginning index of elements tree b = 1; %- Initial tag start = xml_findstr(str,'<',1,1); if isempty(start) error('[XML] No tag found.') end %- Header (<?xml version="1.0" ... ?>) if strcmpi(str(start:start+2),'<?x') close = xml_findstr(str,'?>',1,1); if ~isempty(close) b = close + 2; else warning('[XML] Header tag incomplete.') end end %- Doctype (<!DOCTYPE type ... [ declarations ]>) start = xml_findstr(str,'<!DOCTYPE',b,1); % length('<!DOCTYPE') = 9 if ~isempty(start) close = xml_findstr(str,'>',start+9,1); if ~isempty(close) b = close + 1; dp = xml_findstr(str,'[',start+9,1); if (~isempty(dp) && dp < b) k = xml_findstr(str,']>',start+9,1); if ~isempty(k) b = k + 2; else warning('[XML] Tag [ in DOCTYPE opened but not closed.') end end else warning('[XML] Tag DOCTYPE opened but not closed.') end end %- Skip prolog from the xml string str = str(b:end); %-------------------------------------------------------------------------- function str = strip(str) str(isspace(str)) = ''; %-------------------------------------------------------------------------- function str = normalize(str) % Find white characters (space, newline, carriage return, tabs, ...) i = isspace(str); i = find(i == 1); str(i) = ' '; % replace several white characters by only one if ~isempty(i) j = i - [i(2:end) i(end)]; str(i(j == -1)) = []; end %-------------------------------------------------------------------------- function str = entity(str) str = strrep(str,'&lt;','<'); str = strrep(str,'&gt;','>'); str = strrep(str,'&quot;','"'); str = strrep(str,'&apos;',''''); str = strrep(str,'&amp;','&'); %-------------------------------------------------------------------------- function str = erode(str) if ~isempty(str) && str(1)==' ', str(1)=''; end; if ~isempty(str) && str(end)==' ', str(end)=''; end;
github
lcnbeapp/beapp-master
save.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@gifti/save.m
21,043
utf_8
747d3d8c45fa4a27160c0c333450a4dc
function save(this,filename,encoding) % Save GIfTI object in a GIfTI format file % FORMAT save(this,filename) % this - GIfTI object % filename - name of GIfTI file to be created [Default: 'untitled.gii'] % encoding - optional argument to specify encoding format, among % ASCII, Base64Binary, GZipBase64Binary, ExternalFileBinary, % Collada (.dae), IDTF (.idtf). [Default: 'GZipBase64Binary'] %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id$ % Check filename and file format %-------------------------------------------------------------------------- ext = '.gii'; if nargin == 1 filename = 'untitled.gii'; else if nargin == 3 && strcmpi(encoding,'collada') ext = '.dae'; end if nargin == 3 && strcmpi(encoding,'idtf') ext = '.idtf'; end [p,f,e] = fileparts(filename); if ~ismember(lower(e),{ext}) e = ext; end filename = fullfile(p,[f e]); end % Open file for writing %-------------------------------------------------------------------------- fid = fopen(filename,'wt'); if fid == -1 error('Unable to write file %s: permission denied.',filename); end % Write file %-------------------------------------------------------------------------- switch ext case '.gii' if nargin < 3, encoding = 'GZipBase64Binary'; end fid = save_gii(fid,this,encoding); case '.dae' fid = save_dae(fid,this); case '.idtf' fid = save_idtf(fid,this); otherwise error('Unknown file format.'); end % Close file %-------------------------------------------------------------------------- fclose(fid); %========================================================================== % function fid = save_gii(fid,this,encoding) %========================================================================== function fid = save_gii(fid,this,encoding) % Defaults for DataArray's attributes %-------------------------------------------------------------------------- [unused,unused,mach] = fopen(fid); if strncmp('ieee-be',mach,7) def.Endian = 'BigEndian'; elseif strncmp('ieee-le',mach,7) def.Endian = 'LittleEndian'; else error('[GIFTI] Unknown byte order "%s".',mach); end def.Encoding = encoding; def.Intent = 'NIFTI_INTENT_NONE'; def.DataType = 'NIFTI_TYPE_FLOAT32'; def.ExternalFileName = ''; def.ExternalFileOffset = ''; def.offset = 0; if strcmp(def.Encoding,'GZipBase64Binary') && ~usejava('jvm') warning(['Cannot save GIfTI in ''GZipBase64Binary'' encoding. ' ... 'Revert to ''Base64Binary''.']); def.Encoding = 'Base64Binary'; end % Edit object DataArray attributes %-------------------------------------------------------------------------- for i=1:length(this.data) % Revert the dimension storage d = this.data{i}.attributes.Dim; this.data{i}.attributes = rmfield(this.data{i}.attributes,'Dim'); this.data{i}.attributes.Dimensionality = num2str(length(d)); for j=1:length(d) this.data{i}.attributes.(sprintf('Dim%d',j-1)) = num2str(d(j)); end % Enforce some conventions this.data{i}.attributes.ArrayIndexingOrder = 'ColumnMajorOrder'; if ~isfield(this.data{i}.attributes,'DataType') || ... isempty(this.data{i}.attributes.DataType) warning('DataType set to default: %s', def.DataType); this.data{i}.attributes.DataType = def.DataType; end if ~isfield(this.data{i}.attributes,'Intent') || ... isempty(this.data{i}.attributes.Intent) warning('Intent code set to default: %s', def.Intent); this.data{i}.attributes.Intent = def.Intent; end this.data{i}.attributes.Encoding = def.Encoding; this.data{i}.attributes.Endian = def.Endian; this.data{i}.attributes.ExternalFileName = def.ExternalFileName; this.data{i}.attributes.ExternalFileOffset = def.ExternalFileOffset; switch this.data{i}.attributes.Encoding case {'ASCII', 'Base64Binary','GZipBase64Binary' } case 'ExternalFileBinary' extfilename = this.data{i}.attributes.ExternalFileName; if isempty(extfilename) [p,f] = fileparts(fopen(fid)); extfilename = [f '.dat']; end [p,f,e] = fileparts(extfilename); this.data{i}.attributes.ExternalFileName = fullfile(fileparts(fopen(fid)),[f e]); this.data{i}.attributes.ExternalFileOffset = num2str(def.offset); otherwise error('[GIFTI] Unknown data encoding: %s.',this.data{i}.attributes.Encoding); end end % Prolog %-------------------------------------------------------------------------- fprintf(fid,'<?xml version="1.0" encoding="UTF-8"?>\n'); fprintf(fid,'<!DOCTYPE GIFTI SYSTEM "http://www.nitrc.org/frs/download.php/115/gifti.dtd">\n'); fprintf(fid,'<GIFTI Version="1.0" NumberOfDataArrays="%d">\n',numel(this.data)); o = @(x) blanks(x*3); % MetaData %-------------------------------------------------------------------------- fprintf(fid,'%s<MetaData',o(1)); if isempty(this.metadata) fprintf(fid,'/>\n'); else fprintf(fid,'>\n'); for i=1:length(this.metadata) fprintf(fid,'%s<MD>\n',o(2)); fprintf(fid,'%s<Name><![CDATA[%s]]></Name>\n',o(3),... this.metadata(i).name); fprintf(fid,'%s<Value><![CDATA[%s]]></Value>\n',o(3),... this.metadata(i).value); fprintf(fid,'%s</MD>\n',o(2)); end fprintf(fid,'%s</MetaData>\n',o(1)); end % LabelTable %-------------------------------------------------------------------------- fprintf(fid,'%s<LabelTable',o(1)); if isempty(this.label) fprintf(fid,'/>\n'); else fprintf(fid,'>\n'); for i=1:length(this.label.name) if ~all(isnan(this.label.rgba(i,:))) label_rgba = sprintf(' Red="%f" Green="%f" Blue="%f" Alpha="%f"',... this.label.rgba(i,:)); else label_rgba = ''; end fprintf(fid,'%s<Label Key="%d"%s><![CDATA[%s]]></Label>\n',o(2),... this.label.key(i), label_rgba, this.label.name{i}); end fprintf(fid,'%s</LabelTable>\n',o(1)); end % DataArray %-------------------------------------------------------------------------- for i=1:length(this.data) fprintf(fid,'%s<DataArray',o(1)); if def.offset this.data{i}.attributes.ExternalFileOffset = num2str(def.offset); end fn = sort(fieldnames(this.data{i}.attributes)); oo = repmat({o(5) '\n'},length(fn),1); oo{1} = ' '; oo{end} = ''; for j=1:length(fn) if strcmp(fn{j},'ExternalFileName') [p,f,e] = fileparts(this.data{i}.attributes.(fn{j})); attval = [f e]; else attval = this.data{i}.attributes.(fn{j}); end fprintf(fid,'%s%s="%s"%s',oo{j,1},... fn{j},attval,sprintf(oo{j,2})); end fprintf(fid,'>\n'); % MetaData %---------------------------------------------------------------------- fprintf(fid,'%s<MetaData>\n',o(2)); for j=1:length(this.data{i}.metadata) fprintf(fid,'%s<MD>\n',o(3)); fprintf(fid,'%s<Name><![CDATA[%s]]></Name>\n',o(4),... this.data{i}.metadata(j).name); fprintf(fid,'%s<Value><![CDATA[%s]]></Value>\n',o(4),... this.data{i}.metadata(j).value); fprintf(fid,'%s</MD>\n',o(3)); end fprintf(fid,'%s</MetaData>\n',o(2)); % CoordinateSystemTransformMatrix %---------------------------------------------------------------------- for j=1:length(this.data{i}.space) fprintf(fid,'%s<CoordinateSystemTransformMatrix>\n',o(2)); fprintf(fid,'%s<DataSpace><![CDATA[%s]]></DataSpace>\n',o(3),... this.data{i}.space(j).DataSpace); fprintf(fid,'%s<TransformedSpace><![CDATA[%s]]></TransformedSpace>\n',o(3),... this.data{i}.space(j).TransformedSpace); fprintf(fid,'%s<MatrixData>%s</MatrixData>\n',o(3),... sprintf('%f ',this.data{i}.space(j).MatrixData)); fprintf(fid,'%s</CoordinateSystemTransformMatrix>\n',o(2)); end % Data (saved using MATLAB's ColumnMajorOrder) %---------------------------------------------------------------------- fprintf(fid,'%s<Data>',o(2)); tp = getdict; try tp = tp.(this.data{i}.attributes.DataType); catch error('[GIFTI] Unknown DataType.'); end switch this.data{i}.attributes.Encoding case 'ASCII' fprintf(fid, [tp.format ' '], this.data{i}.data); case 'Base64Binary' fprintf(fid,base64encode(typecast(this.data{i}.data(:),'uint8'))); % uses native machine format case 'GZipBase64Binary' fprintf(fid,base64encode(dzip(typecast(this.data{i}.data(:),'uint8')))); % uses native machine format case 'ExternalFileBinary' extfilename = this.data{i}.attributes.ExternalFileName; dat = this.data{i}.data; if isa(dat,'file_array') dat = subsref(dat,substruct('()',repmat({':'},1,numel(dat.dim)))); end if ~def.offset fide = fopen(extfilename,'w'); % uses native machine format else fide = fopen(extfilename,'a'); % uses native machine format end if fide == -1 error('Unable to write file %s: permission denied.',extfilename); end fseek(fide,0,1); fwrite(fide,dat,tp.class); def.offset = ftell(fide); fclose(fide); otherwise error('[GIFTI] Unknown data encoding.'); end fprintf(fid,'</Data>\n'); fprintf(fid,'%s</DataArray>\n',o(1)); end fprintf(fid,'</GIFTI>\n'); %========================================================================== % function fid = save_dae(fid,this) %========================================================================== function fid = save_dae(fid,this) o = @(x) blanks(x*3); % Split the mesh into connected components %-------------------------------------------------------------------------- s = struct(this); try C = spm_mesh_label(s.faces); d = []; for i=1:numel(unique(C)) d(i).faces = s.faces(C==i,:); u = unique(d(i).faces); d(i).vertices = s.vertices(u,:); a = 1:max(d(i).faces(:)); a(u) = 1:size(d(i).vertices,1); %a = sparse(1,double(u),1:1:size(d(i).vertices,1)); d(i).faces = a(d(i).faces); end s = d; end % Prolog & root of the Collada XML file %-------------------------------------------------------------------------- fprintf(fid,'<?xml version="1.0"?>\n'); fprintf(fid,'<COLLADA xmlns="http://www.collada.org/2008/03/COLLADASchema" version="1.5.0">\n'); % Assets %-------------------------------------------------------------------------- fprintf(fid,'%s<asset>\n',o(1)); fprintf(fid,'%s<contributor>\n',o(2)); fprintf(fid,'%s<author_website>%s</author_website>\n',o(3),... 'http://www.fil.ion.ucl.ac.uk/spm/'); fprintf(fid,'%s<authoring_tool>%s</authoring_tool>\n',o(3),spm('Ver')); fprintf(fid,'%s</contributor>\n',o(2)); fprintf(fid,'%s<created>%s</created>\n',o(2),datestr(now,'yyyy-mm-ddTHH:MM:SSZ')); fprintf(fid,'%s<modified>%s</modified>\n',o(2),datestr(now,'yyyy-mm-ddTHH:MM:SSZ')); fprintf(fid,'%s<unit name="millimeter" meter="0.001"/>\n',o(2)); fprintf(fid,'%s<up_axis>Z_UP</up_axis>\n',o(2)); fprintf(fid,'%s</asset>\n',o(1)); % Image, Materials, Effects %-------------------------------------------------------------------------- %fprintf(fid,'%s<library_images/>\n',o(1)); fprintf(fid,'%s<library_materials>\n',o(1)); for i=1:numel(s) fprintf(fid,'%s<material id="material%d" name="material%d">\n',o(2),i,i); fprintf(fid,'%s<instance_effect url="#material%d-effect"/>\n',o(3),i); fprintf(fid,'%s</material>\n',o(2)); end fprintf(fid,'%s</library_materials>\n',o(1)); fprintf(fid,'%s<library_effects>\n',o(1)); for i=1:numel(s) fprintf(fid,'%s<effect id="material%d-effect" name="material%d-effect">\n',o(2),i,i); fprintf(fid,'%s<profile_COMMON>\n',o(3)); fprintf(fid,'%s<technique sid="COMMON">\n',o(4)); fprintf(fid,'%s<lambert>\n',o(5)); fprintf(fid,'%s<emission>\n',o(6)); fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0 0 0 1]); fprintf(fid,'%s</emission>\n',o(6)); fprintf(fid,'%s<ambient>\n',o(6)); fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0 0 0 1]); fprintf(fid,'%s</ambient>\n',o(6)); fprintf(fid,'%s<diffuse>\n',o(6)); fprintf(fid,'%s<color>%f %f %f %d</color>\n',o(7),[0.5 0.5 0.5 1]); fprintf(fid,'%s</diffuse>\n',o(6)); fprintf(fid,'%s<transparent>\n',o(6)); fprintf(fid,'%s<color>%d %d %d %d</color>\n',o(7),[1 1 1 1]); fprintf(fid,'%s</transparent>\n',o(6)); fprintf(fid,'%s<transparency>\n',o(6)); fprintf(fid,'%s<float>%f</float>\n',o(7),0); fprintf(fid,'%s</transparency>\n',o(6)); fprintf(fid,'%s</lambert>\n',o(5)); fprintf(fid,'%s</technique>\n',o(4)); fprintf(fid,'%s</profile_COMMON>\n',o(3)); fprintf(fid,'%s</effect>\n',o(2)); end fprintf(fid,'%s</library_effects>\n',o(1)); % Geometry %-------------------------------------------------------------------------- fprintf(fid,'%s<library_geometries>\n',o(1)); for i=1:numel(s) fprintf(fid,'%s<geometry id="shape%d" name="shape%d">\n',o(2),i,i); fprintf(fid,'%s<mesh>\n',o(3)); fprintf(fid,'%s<source id="shape%d-positions">\n',o(4),i); fprintf(fid,'%s<float_array id="shape%d-positions-array" count="%d">',o(5),i,numel(s(i).vertices)); fprintf(fid,'%f ',repmat(s(i).vertices',1,[])); fprintf(fid,'</float_array>\n'); fprintf(fid,'%s<technique_common>\n',o(5)); fprintf(fid,'%s<accessor count="%d" offset="0" source="#shape%d-positions-array" stride="3">\n',o(6),size(s(i).vertices,1),i); fprintf(fid,'%s<param name="X" type="float" />\n',o(7)); fprintf(fid,'%s<param name="Y" type="float" />\n',o(7)); fprintf(fid,'%s<param name="Z" type="float" />\n',o(7)); fprintf(fid,'%s</accessor>\n',o(6)); fprintf(fid,'%s</technique_common>\n',o(5)); fprintf(fid,'%s</source>\n',o(4)); fprintf(fid,'%s<vertices id="shape%d-vertices">\n',o(4),i); fprintf(fid,'%s<input semantic="POSITION" source="#shape%d-positions"/>\n',o(5),i); fprintf(fid,'%s</vertices>\n',o(4)); fprintf(fid,'%s<triangles material="material%d" count="%d">\n',o(4),i,size(s(i).faces,1)); fprintf(fid,'%s<input semantic="VERTEX" source="#shape%d-vertices" offset="0"/>\n',o(5),i); fprintf(fid,'%s<p>',o(5)); fprintf(fid,'%d ',repmat(s(i).faces',1,[])-1); fprintf(fid,'</p>\n'); fprintf(fid,'%s</triangles>\n',o(4)); fprintf(fid,'%s</mesh>\n',o(3)); fprintf(fid,'%s</geometry>\n',o(2)); end fprintf(fid,'%s</library_geometries>\n',o(1)); % Scene %-------------------------------------------------------------------------- fprintf(fid,'%s<library_visual_scenes>\n',o(1)); fprintf(fid,'%s<visual_scene id="VisualSceneNode" name="SceneNode">\n',o(2)); for i=1:numel(s) fprintf(fid,'%s<node id="node%d">\n',o(3),i); fprintf(fid,'%s<instance_geometry url="#shape%d">\n',o(4),i); fprintf(fid,'%s<bind_material>\n',o(5)); fprintf(fid,'%s<technique_common>\n',o(6)); fprintf(fid,'%s<instance_material symbol="material%d" target="#material%d"/>\n',o(7),i,i); fprintf(fid,'%s</technique_common>\n',o(6)); fprintf(fid,'%s</bind_material>\n',o(5)); fprintf(fid,'%s</instance_geometry>\n',o(4)); fprintf(fid,'%s</node>\n',o(3)); end fprintf(fid,'%s</visual_scene>\n',o(2)); fprintf(fid,'%s</library_visual_scenes>\n',o(1)); fprintf(fid,'%s<scene>\n',o(1)); fprintf(fid,'%s<instance_visual_scene url="#VisualSceneNode" />\n',o(2)); fprintf(fid,'%s</scene>\n',o(1)); % End of XML %-------------------------------------------------------------------------- fprintf(fid,'</COLLADA>\n'); %========================================================================== % function fid = save_idtf(fid,this) %========================================================================== function fid = save_idtf(fid,this) o = inline('blanks(x*3)'); s = struct(this); % Compute normals %-------------------------------------------------------------------------- if ~isfield(s,'normals') try s.normals = spm_mesh_normals(... struct('vertices',s.vertices,'faces',s.faces),true); catch s.normals = []; end end % Split the mesh into connected components %-------------------------------------------------------------------------- try C = spm_mesh_label(s.faces); d = []; try if size(s.cdata,2) == 1 && (any(s.cdata>1) || any(s.cdata<0)) mi = min(s.cdata); ma = max(s.cdata); s.cdata = (s.cdata-mi)/ (ma-mi); else end end for i=1:numel(unique(C)) d(i).faces = s.faces(C==i,:); u = unique(d(i).faces); d(i).vertices = s.vertices(u,:); d(i).normals = s.normals(u,:); a = 1:max(d(i).faces(:)); a(u) = 1:size(d(i).vertices,1); %a = sparse(1,double(u),1:1:size(d(i).vertices,1)); d(i).faces = a(d(i).faces); d(i).mat = s.mat; try d(i).cdata = s.cdata(u,:); if size(d(i).cdata,2) == 1 d(i).cdata = repmat(d(i).cdata,1,3); end end end s = d; end % FILE_HEADER %-------------------------------------------------------------------------- fprintf(fid,'FILE_FORMAT "IDTF"\n'); fprintf(fid,'FORMAT_VERSION 100\n\n'); % NODES %-------------------------------------------------------------------------- for i=1:numel(s) fprintf(fid,'NODE "MODEL" {\n'); fprintf(fid,'%sNODE_NAME "%s"\n',o(1),sprintf('Mesh%04d',i)); fprintf(fid,'%sPARENT_LIST {\n',o(1)); fprintf(fid,'%sPARENT_COUNT %d\n',o(2),1); fprintf(fid,'%sPARENT %d {\n',o(2),0); fprintf(fid,'%sPARENT_NAME "%s"\n',o(3),'<NULL>'); fprintf(fid,'%sPARENT_TM {\n',o(3)); I = s(i).mat; % eye(4); for j=1:size(I,2) fprintf(fid,'%s',o(4)); fprintf(fid,'%f ',I(:,j)'); fprintf(fid,'\n'); end fprintf(fid,'%s}\n',o(3)); fprintf(fid,'%s}\n',o(2)); fprintf(fid,'%s}\n',o(1)); fprintf(fid,'%sRESOURCE_NAME "%s"\n',o(1),sprintf('Mesh%04d',i)); %fprintf(fid,'%sMODEL_VISIBILITY "BOTH"\n',o(1)); fprintf(fid,'}\n\n'); end % NODE_RESOURCES %-------------------------------------------------------------------------- for i=1:numel(s) fprintf(fid,'RESOURCE_LIST "MODEL" {\n'); fprintf(fid,'%sRESOURCE_COUNT %d\n',o(1),1); fprintf(fid,'%sRESOURCE %d {\n',o(1),0); fprintf(fid,'%sRESOURCE_NAME "%s"\n',o(2),sprintf('Mesh%04d',i)); fprintf(fid,'%sMODEL_TYPE "MESH"\n',o(2)); fprintf(fid,'%sMESH {\n',o(2)); fprintf(fid,'%sFACE_COUNT %d\n',o(3),size(s(i).faces,1)); fprintf(fid,'%sMODEL_POSITION_COUNT %d\n',o(3),size(s(i).vertices,1)); fprintf(fid,'%sMODEL_NORMAL_COUNT %d\n',o(3),size(s(i).normals,1)); if ~isfield(s(i),'cdata') || isempty(s(i).cdata) c = 0; else c = size(s(i).cdata,1); end fprintf(fid,'%sMODEL_DIFFUSE_COLOR_COUNT %d\n',o(3),c); fprintf(fid,'%sMODEL_SPECULAR_COLOR_COUNT %d\n',o(3),0); fprintf(fid,'%sMODEL_TEXTURE_COORD_COUNT %d\n',o(3),0); fprintf(fid,'%sMODEL_BONE_COUNT %d\n',o(3),0); fprintf(fid,'%sMODEL_SHADING_COUNT %d\n',o(3),1); fprintf(fid,'%sMODEL_SHADING_DESCRIPTION_LIST {\n',o(3)); fprintf(fid,'%sSHADING_DESCRIPTION %d {\n',o(4),0); fprintf(fid,'%sTEXTURE_LAYER_COUNT %d\n',o(5),0); fprintf(fid,'%sSHADER_ID %d\n',o(5),0); fprintf(fid,'%s}\n',o(4)); fprintf(fid,'%s}\n',o(3)); fprintf(fid,'%sMESH_FACE_POSITION_LIST {\n',o(3)); fprintf(fid,'%d %d %d\n',s(i).faces'-1); fprintf(fid,'%s}\n',o(3)); fprintf(fid,'%sMESH_FACE_NORMAL_LIST {\n',o(3)); fprintf(fid,'%d %d %d\n',s(i).faces'-1); fprintf(fid,'%s}\n',o(3)); fprintf(fid,'%sMESH_FACE_SHADING_LIST {\n',o(3)); fprintf(fid,'%d\n',zeros(size(s(i).faces,1),1)); fprintf(fid,'%s}\n',o(3)); if c fprintf(fid,'%sMESH_FACE_DIFFUSE_COLOR_LIST {\n',o(3)); fprintf(fid,'%d %d %d\n',s(i).faces'-1); fprintf(fid,'%s}\n',o(3)); end fprintf(fid,'%sMODEL_POSITION_LIST {\n',o(3)); fprintf(fid,'%f %f %f\n',s(i).vertices'); fprintf(fid,'%s}\n',o(3)); fprintf(fid,'%sMODEL_NORMAL_LIST {\n',o(3)); fprintf(fid,'%f %f %f\n',s(i).normals'); fprintf(fid,'%s}\n',o(3)); if c fprintf(fid,'%sMODEL_DIFFUSE_COLOR_LIST {\n',o(3)); fprintf(fid,'%f %f %f\n',s(i).cdata'); fprintf(fid,'%s}\n',o(3)); end fprintf(fid,'%s}\n',o(2)); fprintf(fid,'%s}\n',o(1)); fprintf(fid,'}\n'); end
github
lcnbeapp/beapp-master
gifti.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@gifti/gifti.m
3,728
utf_8
37f5d9e67cb8f5e79f2ac46e1486ffd0
function this = gifti(varargin) % GIfTI Geometry file format class % Geometry format under the Neuroimaging Informatics Technology Initiative % (NIfTI): % http://www.nitrc.org/projects/gifti/ % http://nifti.nimh.nih.gov/ %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id$ switch nargin case 0 this = giftistruct; this = class(this,'gifti'); case 1 if isa(varargin{1},'gifti') this = varargin{1}; elseif isstruct(varargin{1}) f = {'faces', 'face', 'tri' 'vertices', 'vert', 'pnt', 'cdata'}; ff = {'faces', 'faces', 'faces', 'vertices', 'vertices', 'vertices', 'cdata'}; [c, ia] = intersect(f,fieldnames(varargin{1})); if ~isempty(c) this = gifti; for i=1:length(c) this = subsasgn(this,... struct('type','.','subs',ff{ia(i)}),... varargin{1}.(c{i})); end elseif isempty(setxor(fieldnames(varargin{1}),... {'metadata','label','data'})) this = class(varargin{1},'gifti'); else error('[GIFTI] Invalid structure.'); end elseif ishandle(varargin{1}) this = struct('vertices',get(varargin{1},'Vertices'), ... 'faces', get(varargin{1},'Faces')); if ~isempty(get(varargin{1},'FaceVertexCData')); this.cdata = get(varargin{1},'FaceVertexCData'); end this = gifti(this); elseif isnumeric(varargin{1}) this = gifti; this = subsasgn(this,... struct('type','.','subs','cdata'),... varargin{1}); elseif ischar(varargin{1}) if size(varargin{1},1)>1 this = gifti(cellstr(varargin{1})); return; end [p,n,e] = fileparts(varargin{1}); if strcmpi(e,'.mat') try this = gifti(load(varargin{1})); catch error('[GIFTI] Loading of file %s failed.', varargin{1}); end elseif strcmpi(e,'.asc') || strcmpi(e,'.srf') this = read_freesurfer_file(varargin{1}); this = gifti(this); else this = read_gifti_file(varargin{1},giftistruct); this = class(this,'gifti'); end elseif iscellstr(varargin{1}) fnames = varargin{1}; this(numel(fnames)) = giftistruct; this = class(this,'gifti'); for i=1:numel(fnames) this(i) = gifti(fnames{i}); end else error('[GIFTI] Invalid object construction.'); end otherwise error('[GIFTI] Invalid object construction.'); end %========================================================================== function s = giftistruct s = struct(... 'metadata', ... struct(... 'name', {}, ... 'value', {} ... ), ... 'label', ... struct(... 'name', {}, ... 'index', {} ... ), ... 'data', ... struct(... 'attributes', {}, ... 'metadata', struct('name',{}, 'value',{}), ... 'space', {}, ... 'data', {} ... ) ... );
github
lcnbeapp/beapp-master
read_gifti_file.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@gifti/private/read_gifti_file.m
6,604
utf_8
3e691fdd0839d8cfad3929e4e181a5c1
function this = read_gifti_file(filename, this) % Low level reader of GIfTI 1.0 files % FORMAT this = read_gifti_file(filename, this) % filename - XML GIfTI filename % this - structure with fields 'metaData', 'label' and 'data'. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id$ % Import XML-based GIfTI file %-------------------------------------------------------------------------- try t = xmltree(filename); catch error('[GIFTI] Loading of XML file %s failed.', filename); end % Root element of a GIFTI file %-------------------------------------------------------------------------- if ~strcmp(get(t,root(t),'name'),'GIFTI') error('[GIFTI] %s is not a GIFTI 1.0 file.', filename); end attr = cell2mat(attributes(t,'get',root(t))); attr = cell2struct({attr.val},strrep({attr.key},':','___'),2); if ~all(ismember({'Version','NumberOfDataArrays'},fieldnames(attr))) error('[GIFTI] Missing mandatory attributes for GIFTI root element.'); end if str2double(attr.Version) ~= 1 warning('[GIFTI] Unknown specification version of GIFTI file (%s).',attr.Version); end nbData = str2double(attr.NumberOfDataArrays); % Read children elements %-------------------------------------------------------------------------- uid = children(t,root(t)); for i=1:length(uid) switch get(t,uid(i),'name') case 'MetaData' this.metadata = gifti_MetaData(t,uid(i)); case 'LabelTable' this.label = gifti_LabelTable(t,uid(i)); case 'DataArray' this.data{end+1} = gifti_DataArray(t,uid(i),filename); otherwise warning('[GIFTI] Unknown element "%s": ignored.',get(t,uid(i),'name')); end end if nbData ~= length(this.data) warning('[GIFTI] Mismatch between expected and effective number of datasets.'); end %========================================================================== function s = gifti_MetaData(t,uid) s = struct('name',{}, 'value',{}); c = children(t,uid); for i=1:length(c) for j=children(t,c(i)) s(i).(lower(get(t,j,'name'))) = get(t,children(t,j),'value'); end end %========================================================================== function s = gifti_LabelTable(t,uid) s = struct('name',{}, 'key',[], 'rgba',[]); c = children(t,uid); for i=1:length(c) a = attributes(t,'get',c(i)); s(1).rgba(i,1:4) = NaN; for j=1:numel(a) switch lower(a{j}.key) case {'key','index'} s(1).key(i) = str2double(a{j}.val); case 'red' s(1).rgba(i,1) = str2double(a{j}.val); case 'green' s(1).rgba(i,2) = str2double(a{j}.val); case 'blue' s(1).rgba(i,3) = str2double(a{j}.val); case 'alpha' s(1).rgba(i,4) = str2double(a{j}.val); otherwise end end s(1).name{i} = get(t,children(t,c(i)),'value'); end %========================================================================== function s = gifti_DataArray(t,uid,filename) s = struct(... 'attributes', {}, ... 'data', {}, ... 'metadata', struct([]), ... 'space', {} ... ); attr = cell2mat(attributes(t,'get',uid)); s(1).attributes = cell2struct({attr.val},{attr.key},2); s(1).attributes.Dim = []; for i=1:str2double(s(1).attributes.Dimensionality) f = sprintf('Dim%d',i-1); s(1).attributes.Dim(i) = str2double(s(1).attributes.(f)); s(1).attributes = rmfield(s(1).attributes,f); end s(1).attributes = rmfield(s(1).attributes,'Dimensionality'); if isfield(s(1).attributes,'ExternalFileName') && ... ~isempty(s(1).attributes.ExternalFileName) s(1).attributes.ExternalFileName = fullfile(fileparts(filename),... s(1).attributes.ExternalFileName); end c = children(t,uid); for i=1:length(c) switch get(t,c(i),'name') case 'MetaData' s(1).metadata = gifti_MetaData(t,c(i)); case 'CoordinateSystemTransformMatrix' s(1).space(end+1) = gifti_Space(t,c(i)); case 'Data' s(1).data = gifti_Data(t,c(i),s(1).attributes); otherwise error('[GIFTI] Unknown DataArray element "%s".',get(t,c(i),'name')); end end %========================================================================== function s = gifti_Space(t,uid) s = struct('DataSpace','', 'TransformedSpace','', 'MatrixData',[]); for i=children(t,uid) s.(get(t,i,'name')) = get(t,children(t,i),'value'); end s.MatrixData = reshape(str2num(s.MatrixData),4,4)'; %========================================================================== function d = gifti_Data(t,uid,s) tp = getdict; try tp = tp.(s.DataType); catch error('[GIFTI] Unknown DataType.'); end [unused,unused,mach] = fopen(1); sb = @(x) x; try if (strcmp(s.Endian,'LittleEndian') && ~isempty(strmatch('ieee-be',mach))) ... || (strcmp(s.Endian,'BigEndian') && ~isempty(strmatch('ieee-le',mach))) sb = @swapbyte; end catch % Byte Order can be absent if encoding is ASCII, assume native otherwise end switch s.Encoding case 'ASCII' d = sscanf(get(t,children(t,uid),'value'),tp.format); case 'Base64Binary' d = typecast(sb(base64decode(get(t,children(t,uid),'value'))), tp.cast); case 'GZipBase64Binary' d = typecast(dunzip(sb(base64decode(get(t,children(t,uid),'value')))), tp.cast); case 'ExternalFileBinary' [p,f,e] = fileparts(s.ExternalFileName); if isempty(p) s.ExternalFileName = fullfile(pwd,[f e]); end if false fid = fopen(s.ExternalFileName,'r'); if fid == -1 error('[GIFTI] Unable to read binary file %s.',s.ExternalFileName); end fseek(fid,str2double(s.ExternalFileOffset),0); d = sb(fread(fid,prod(s.Dim),['*' tp.class])); fclose(fid); else d = file_array(s.ExternalFileName, s.Dim, tp.class, ... str2double(s.ExternalFileOffset),1,0,'rw'); end otherwise error('[GIFTI] Unknown data encoding: %s.',s.Encoding); end if length(s.Dim) == 1, s.Dim(end+1) = 1; end switch s.ArrayIndexingOrder case 'RowMajorOrder' d = permute(reshape(d,fliplr(s.Dim)),length(s.Dim):-1:1); case 'ColumnMajorOrder' d = reshape(d,s.Dim); otherwise error('[GIFTI] Unknown array indexing order.'); end
github
lcnbeapp/beapp-master
isintent.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/gifti/@gifti/private/isintent.m
2,477
utf_8
611bd4b3bf09d89f88da3652cc8e6320
function [a, b] = isintent(this,intent) % Correspondance between fieldnames and NIfTI intent codes % FORMAT ind = isintent(this,intent) % this - GIfTI object % intent - fieldnames % a - indices of found intent(s) % b - indices of dataarrays of found intent(s) %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id$ a = []; b = []; if ischar(intent), intent = cellstr(intent); end for i=1:length(this(1).data) switch this(1).data{i}.attributes.Intent(14:end) case 'POINTSET' [tf, loc] = ismember('vertices',intent); if tf a(end+1) = loc; b(end+1) = i; end [tf, loc] = ismember('mat',intent); if tf a(end+1) = loc; b(end+1) = i; end case 'TRIANGLE' [tf, loc] = ismember('faces',intent); if tf a(end+1) = loc; b(end+1) = i; end case 'VECTOR' [tf, loc] = ismember('normals',intent); if tf a(end+1) = loc; b(end+1) = i; end case cdata [tf, loc] = ismember('cdata',intent); if tf a(end+1) = loc; b(end+1) = i; end if strcmp(this(1).data{i}.attributes.Intent(14:end),'LABEL') [tf, loc] = ismember('labels',intent); if tf a(end+1) = loc; b(end+1) = i; end end otherwise fprintf('Intent %s is ignored.\n',this.data{i}.attributes.Intent); end end %[d,i] = unique(a); %if length(d) < length(a) % warning('Several fields match intent type. Using first.'); % a = a(i); % b = b(i); %end function c = cdata c = { 'NONE' 'CORREL' 'TTEST' 'FTEST' 'ZSCORE' 'CHISQ' 'BETA' 'BINOM' 'GAMMA' 'POISSON' 'NORMAL' 'FTEST_NONC' 'CHISQ_NONC' 'LOGISTIC' 'LAPLACE' 'UNIFORM' 'TTEST_NONC' 'WEIBULL' 'CHI' 'INVGAUSS' 'EXTVAL' 'PVAL' 'LOGPVAL' 'LOG10PVAL' 'ESTIMATE' 'LABEL' 'NEURONAMES' 'GENMATRIX' 'SYMMATRIX' 'DISPVECT' 'QUATERNION' 'DIMLESS' 'TIME_SERIES' 'RGB_VECTOR' 'RGBA_VECTOR' 'NODE_INDEX' 'SHAPE' 'CONNECTIVITY_DENSE' 'CONNECTIVITY_DENSE_TIME' 'CONNECTIVITY_PARCELLATED' 'CONNECTIVITY_PARCELLATED_TIME' 'CONNECTIVITY_CONNECTIVITY_TRAJECTORY' };
github
lcnbeapp/beapp-master
sb_rhs_venant.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/simbio/sb_rhs_venant.m
1,317
utf_8
2a6743d0e11f6cd5ca8bc3f2a5bab884
function rhs = sb_rhs_venant(pos,dir,vol); % SB_RHS_VENANT % % $Id$ %find node closest to source position next_nd = sb_get_next_nd(pos,vol.pos); %find nodes neighbouring closest node if isfield(vol,'tet') ven_nd = sb_get_ven_nd(next_nd,vol.tet); elseif isfield(vol,'hex') ven_nd = sb_get_ven_nd(next_nd,vol.hex); else error('No connectivity information given!'); end %calculate rhs matrix loads = sb_calc_ven_loads(pos,dir,ven_nd,vol.pos); %assign values in sparse matrix i = reshape(ven_nd',[],1); j = reshape(repmat([1:size(ven_nd,1)],size(ven_nd,2),1),[],1); loads = reshape(loads',[],1); j = j(i~=0); loads = loads(i~=0); i = i(i~=0); rhs = sparse(i,j,loads,size(vol.pos,1),size(pos,1)); end function next_nd = sb_get_next_nd(pos,node); next_nd = zeros(size(pos,1),1); for i=1:size(pos,1) [dist, next_nd(i)] = min(sum(bsxfun(@minus,node,pos(i,:)).^2,2)); end end function ven_nd = sb_get_ven_nd(next_nd,elem); ven_nd = zeros(size(next_nd,1),1); for i=1:size(next_nd,1) [tmp1,tmp2] = find(elem == next_nd(i)); tmp = unique(elem(tmp1,:)); %tmp = tmp(tmp~=next_nd(i)); seems like this is not done in the %original. if(length(tmp) > size(ven_nd,2)) ven_nd = [ven_nd, zeros(size(ven_nd,1),length(tmp)-size(ven_nd,2))]; end ven_nd(i,1:length(tmp)) = tmp; end end
github
lcnbeapp/beapp-master
netcdf.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/netcdf/netcdf.m
5,097
utf_8
3cc73e65d1ed73e0a6836af118228033
function S = netcdf(File,varargin) % Function to read NetCDF files % S = netcdf(File) % Input Arguments % File = NetCDF file to read % Optional Input Arguments: % 'Var',Var - Read data for VarArray(Var), default [1:length(S.VarArray)] % 'Rec',Rec - Read data for Record(Rec), default [1:S.NumRecs] % Output Arguments: % S = Structure of NetCDF data organised as per NetCDF definition % Notes: % Only version 1, classic 32bit, NetCDF files are supported. By default % data are extracted into the S.VarArray().Data field for all variables. % To read the header only call S = netcdf(File,'Var',[]); % % SEE ALSO % --------------------------------------------------------------------------- S = []; try if exist(File,'file') fp = fopen(File,'r','b'); else fp = []; error('File not found'); end if fp == -1 error('Unable to open file'); end % Read header Magic = fread(fp,4,'uint8=>char'); if strcmp(Magic(1:3),'CDF') error('Not a NetCDF file'); end if uint8(Magic(4))~=1 error('Version not supported'); end S.NumRecs = fread(fp,1,'uint32=>uint32'); S.DimArray = DimArray(fp); S.AttArray = AttArray(fp); S.VarArray = VarArray(fp); % Setup indexing to arrays and records Var = ones(1,length(S.VarArray)); Rec = ones(1,S.NumRecs); for i = 1:2:length(varargin) if strcmp(upper(varargin{i}),'VAR') Var=Var*0; Var(varargin{i+1})=1; elseif strcmp(upper(varargin{i}),'REC') Rec=Rec*0; Rec(varargin{i+1})=1; else error('Optional input argument not recognised'); end end if sum(Var)==0 fclose(fp); return; end % Read non-record variables Dim = double(cat(2,S.DimArray.Dim)); ID = double(cat(2,S.VarArray.Type)); for i = 1:length(S.VarArray) D = Dim(S.VarArray(i).DimID+1); N = prod(D); RecID{i}=find(D==0); if isempty(RecID{i}) if length(D)==0 D = [1,1]; N = 1; elseif length(D)==1 D=[D,1]; end if Var(i) S.VarArray(i).Data = ReOrder(fread(fp,N,[Type(ID(i)),'=>',Type(ID(i))]),D); fread(fp,(Pad(N,ID(i))-N)*Size(ID(i)),'uint8=>uint8'); else fseek(fp,Pad(N,ID(i))*Size(ID(i)),'cof'); end else S.VarArray(i).Data = []; end end % Read record variables for k = 1:S.NumRecs for i = 1:length(S.VarArray) if ~isempty(RecID{i}) D = Dim(S.VarArray(i).DimID+1); D(RecID{i}) = 1; N = prod(D); if length(D)==1 D=[D,1]; end if Var(i) & Rec(k) S.VarArray(i).Data = cat(RecID{i},S.VarArray(i).Data,... ReOrder(fread(fp,N,[Type(ID(i)),'=>',Type(ID(i))]),D)); if N > 1 fread(fp,(Pad(N,ID(i))-N)*Size(ID(i)),'uint8=>uint8'); end else fseek(fp,Pad(N,ID(i))*Size(ID(i)),'cof'); end end end end fclose(fp); catch Err = lasterror; fprintf('%s\n',Err.message); if ~isempty(fp) && fp ~= -1 fclose(fp); end end % --------------------------------------------------------------------------------------- % Utility functions function S = Size(ID) % Size of NetCDF data type, ID, in bytes S = subsref([1,1,2,4,4,8],struct('type','()','subs',{{ID}})); function T = Type(ID) % Matlab string for CDF data type, ID T = subsref({'int8','char','int16','int32','single','double'},... struct('type','{}','subs',{{ID}})); function N = Pad(Num,ID) % Number of elements to read after padding to 4 bytes for type ID N = (double(Num) + mod(4-double(Num)*Size(ID),4)/Size(ID)).*(Num~=0); function S = String(fp) % Read a CDF string; Size,[String,[Padding]] S = fread(fp,Pad(fread(fp,1,'uint32=>uint32'),1),'uint8=>char').'; function A = ReOrder(A,S) % Rearrange CDF array A to size S with matlab ordering A = permute(reshape(A,fliplr(S)),fliplr(1:length(S))); function S = DimArray(fp) % Read DimArray into structure if fread(fp,1,'uint32=>uint32') == 10 % NC_DIMENSION for i = 1:fread(fp,1,'uint32=>uint32') S(i).Str = String(fp); S(i).Dim = fread(fp,1,'uint32=>uint32'); end else fread(fp,1,'uint32=>uint32'); S = []; end function S = AttArray(fp) % Read AttArray into structure if fread(fp,1,'uint32=>uint32') == 12 % NC_ATTRIBUTE for i = 1:fread(fp,1,'uint32=>uint32') S(i).Str = String(fp); ID = fread(fp,1,'uint32=>uint32'); Num = fread(fp,1,'uint32=>uint32'); S(i).Val = fread(fp,Pad(Num,ID),[Type(ID),'=>',Type(ID)]).'; end else fread(fp,1,'uint32=>uint32'); S = []; end function S = VarArray(fp) % Read VarArray into structure if fread(fp,1,'uint32=>uint32') == 11 % NC_VARIABLE for i = 1:fread(fp,1,'uint32=>uint32') S(i).Str = String(fp); Num = double(fread(fp,1,'uint32=>uint32')); S(i).DimID = double(fread(fp,Num,'uint32=>uint32')); S(i).AttArray = AttArray(fp); S(i).Type = fread(fp,1,'uint32=>uint32'); S(i).VSize = fread(fp,1,'uint32=>uint32'); S(i).Begin = fread(fp,1,'uint32=>uint32'); % Classic 32 bit format only end else fread(fp,1,'uint32=>uint32'); S = []; end
github
lcnbeapp/beapp-master
writeCPersist.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/ctf/writeCPersist.m
5,086
utf_8
0c56dc571aa56100f050678e5fe815ff
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% Function writeCPersist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeCPersist(filename,Tag) % Version 1.2 24 April 2007. Removed terminating null characters from charatcer strings % types 10,11) % Version 1.1 13 April 2007 % Write a CTF CPersist file. See document CTF MEG File Format, PN900-0066 % Inputs : filename : Name of the output file name including path % Tag: Structure array containing all of the tags, types, and data. % 31 Aug 2006: Recognizes type=1,...,17. If other data types are specified, % writeCPersist will print an error message. % Delete existing file so the new file has the correct creation data/time. if nargin==0 fprintf(['writeCPersist: Version 1.2 24 April 2007 Writes a CTF CPersist file.\n'... '\twriteCPersist(filename,Tag) writes a CPersist file from the contents of\n',... '\tstructure array Tag. Tag is in the format prepared by readCPersist.\n\n']); Tag=[]; return end if exist(filename)==2 delete(filename); end startString='WS1_'; EOFstring='EndOfParameters'; startVal=256.^[3:-1:0]*double(startString)'; % Integer version of startString fid=fopen(filename,'w','ieee-be'); EOFcount=0; % Make sure that the startString's and EOFstring's balance count=0; while count<length(Tag) count=count+1; if strcmp(Tag(count).name,startString) % start of Cpersist object fwrite(fid,startVal,'int32'); EOFcount=EOFcount-1; continue end fwrite(fid,length(Tag(count).name),'int32'); % end of CPersist object fwrite(fid,Tag(count).name,'char'); if strcmp(Tag(count).name,EOFstring); EOFcount=EOFcount+1; continue; end fwrite(fid,Tag(count).type,'int32'); if Tag(count).type==1 fwrite(fid,Tag(count).data,'int32'); elseif Tag(count).type==2 % Start embedded CPersist object elseif Tag(count).type==3 % binary list fwrite(fid,2*length(Tag(count).data),'int32'); fwrite(fid,Tag(count).data,'int16'); elseif Tag(count).type==4 % double fwrite(fid,Tag(count).data,'float64'); elseif Tag(count).type==5 % integer fwrite(fid,Tag(count).data,'int32'); elseif Tag(count).type==6 % short integer fwrite(fid,Tag(count).data,'int16'); elseif Tag(count).type==7 % unsigned short integer fwrite(fid,Tag(count).data,'uint16'); elseif Tag(count).type==8 % Boolean byte fwrite(fid,Tag(count).data,'uint8'); elseif Tag(count).type==9; % CStr32 nChar=min(32,length(Tag(count).data)); fwrite(fid,[double(Tag(count).data(1:nChar)) zeros(1,32-nChar)],'uint8'); elseif Tag(count).type==10; % CString fwrite(fid,length(Tag(count).data),'int32'); fwrite(fid,double(Tag(count).data),'uint8'); elseif Tag(count).type==11; % Cstring list. nList=size(Tag(count).data,1); fwrite(fid,nList,'int32'); for k=1:nList % Do not force termination of strings with nulls (char(0)) Cstring=[deblank(Tag(count).data(k,:))]; fwrite(fid,length(Cstring),'int32'); fwrite(fid,double(Cstring),'uint8'); end clear k CString nList; elseif Tag(count).type==12; % CStr32 list. nList=size(Tag(count).data,1); %size(data)=[nList 32] fwrite(fid,nList,'int32'); % Do not force termination of strings with nulls (char(0)) for k=1:nList strng=deblank(Tag(count).data(k,:)); nChar=min(32,length(strng)); Tag(count).data(k,:)=[strng(1:nChar) char(zeros(1,32-nChar))]; end fwrite(fid,double(Tag(count).data)','uint8'); clear k strng nChar nList; elseif Tag(count).type==13; % SensorClass list. fwrite(fid,length(Tag(count).data),'int32'); fwrite(fid,Tag(count).data,'int32') elseif Tag(count).type==14 % long integer fwrite(fid,Tag(count).data,'int32'); elseif Tag(count).type==15 % unsigned longinteger fwrite(fid,Tag(count).data,'uint32'); elseif Tag(count).type==16 % unsigned integer fwrite(fid,Tag(count).data,'uint32'); elseif Tag(count).type==17 % Boolean if ~any(Tag(count).data==[0 1]) fprintf('writeCPersist: tagname=%s type=%d value=%d? (Must =0 or 1)\n',... tagname,type,Tag(count).data); Tag(count).data=(Tag(count).data~=0); fprintf(' Set value=%d.\n',Tag(count).data); end fwrite(fid,Tag(count).data,'int32'); else fprintf('writeCPersist: Tag(%d) name=%s type=%d\n',count,Tag(count).name,Tag(count).type); fprintf('\t\t UNRECOGNIZED type.\n'); fclose(fid); break; end end % Loop over tags fclose(fid); % EOF_count should be zero at the end of the file if EOFcount~=0; fprintf('write_CPerist: EOFcount=%d Stop strings do not balance start strings.\n',... EOFcount); fprintf(' Start string=%s Stop string=%s\n',startString,EOFstring); end return %%%%%%%% End of writeCPersist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
lcnbeapp/beapp-master
getCTFBalanceCoefs.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/ctf/getCTFBalanceCoefs.m
20,490
utf_8
2c434fcbdb53fbc50ee3fbda72e98883
function [alphaMEG,MEGindex,MEGbalanceindex,alphaGref,Grefindex,Gbalanceindex]=... getCTFBalanceCoefs(ds,balanceType,unit); % Reads balance coefficients for SQUID data in phi0's, and converts to coefficients % for data in physical units. % Input : ds : (1) ds structure from readCTFds % balanceType : 'NONE' : No balancing % 'G1BR' : 1st order balancing % 'G2BR' : 2nd order balancing % 'G3BR' : 3rd order balancing % 'G3AR' : 3rd order balancing + adaptive % If only MEG balance table is requested, size(balanceType)=[1 5] % If Gref balance table is requested also, size(balanceType)=[2 4] % unit: Type of units. Option: 'fT','T','phi0','int'. % If unit is not entered, of unit=[], the default is unit='fT'. % Outputs : % alphaMEG,MEGindex,MEGbalanceindex : MEG balancing coefficients for data in fT or T. % Suppose data array returned by getTrial2 has size(data)=[npt nchan]. % nMEG = number of MEG channels in the data set. % MEG channels have sensorTypeIndex==5. % % MEGindex = list of MEG channels referred to the channel numbering in % the complete dataset (i.e. it is not referred to only the list of % SQUID sensors). % by looking for sensors with ds.res4.senres.sensorTypeIndex==5 % size(MEGindex)=[1 nMEG] % MEG data = data(:,MEGindex) % MEGbalanceindex = list of reference channels for MEG balancing. % size(MEGbalanceindex)=[1 nRef] % Reference data for MEG balancing = data(:,MEGbalanceindex) % alphaMEG = balance coefficients. size(alphaMEG)=[nRef nMEG] % % Balancing MEG data : % - Start with data AFTER converting to physical units. % (I.e. SQUID data must be in fT or T.) % - balanced_data(:,MEGindex)=data(:,MEGindex)-data(:,MEGbalanceindex)*alphaMEG % If user specifies balanceType=[], ' ' or 'none', then getCTFBalanceCoefs returns % alphaMEG=zeros(0,nMEG), MEGindex=list of MEG sensor channels, % MEGbalanceindex=[], alphaGref=zeros(0,nGef), Grefindex=list of Gref channels % and Gbalanceindex=[]; % alphaGref,Grefindex,Gbalanceindex : Reference-gradiometer balancing coeficients. % These output arrays are optional. If the calling statement includes % them, then this program extracts a table of balance coefficients for % the reference gradiometers from the G1BR table in the coefficient files. % nGref = no. of reference gradiometers channels in the data set % (sensorTypeIndex=1) % Grefindex = list of reference channels. size(Grefindex)=[1 nGref] % Gradient reference data = data(:,Grefindex) % Gbalanceindex = list of channels for balancing reference % gradiometers. size(Gbalanceindex)=[1 nGbalcoef] % Balancing reference data = data(:,Gbalanceindex) % alphaGref = balance coefficients for ref. grads. % size(alphaGref)=[nGbalcoef nGref] % % Balancing ref. gradiometer data : % - Use data AFTER converting to physical units. (I.e. data in fT or T.) % balanced_data(:,Grefindex)=data(:,Grefindex)-data(:,Gbalanceindex)*alphaGref % Calls function getRawCTFBalanceCoefs (included in this listing). if nargout==0 & nargin==0 fprintf(['\ngetCTFBalanceCoefs: Version 1.1 17 April 2007 ',... 'Reads balance coefficients from ds.res4.scrr.\n\n',... '\tMEG balancing : [alphaMEG,MEGindex,MEGbalanceindex]=',... 'getCTFBalanceCoefs(ds,balanceType,unit);\n\n',... '\tMEG & Gref balancing : [alphaMEG,MEGindex,MEGbalanceindex,',... 'alphaGref,Grefindex,Gbalanceindex]=\n',... '\t ',... 'getCTFBalanceCoefs(ds,balanceType,unit);\n\n']); return end balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR', 'G3AR'); balanceOptionsEnds = [size(balanceOptions, 1), 2]; % Which options are available for MEGs and Grefs. physical_options=strvcat('fT','T'); raw_options=strvcat('phi0','int'); unit_options=strvcat(physical_options,raw_options); default_unit='fT'; % Specify outputs in case of an early return due to an error. MEGindex=[]; Grefindex=[]; alphaMEG=[]; MEGbalanceindex=[]; alphaGref=[]; Gbalanceindex=[]; % Check that the inputs are sensible. if nargin<2 fprintf(['\ngetCTFBalanceCoefs: Only %d input arguments? ',... 'Must specify at least ds and balanceType.\n\n'],nargin); return elseif ~isstruct(ds) | isempty(ds) | ~ischar(balanceType) | isempty(balanceType) fprintf('\ngetCTFBalanceCoefs: Wrong argument types or sizes.\n\n'); whos ds balanceType return elseif ~isfield(ds,'res4') fprintf('\ngetCTFBalanceCoefs: Field res4 is missing from structure ds.\n\n'); ds return elseif size(balanceType,1)>2 fprintf('\ngetCTFBalanceCoefs: size(balanceType)=[');fprintf(' %d',size(balanceType));... fprintf('] Must be[1 4] or [2 4].\n\n'); return end % Must have 3 or 6 output arguments. Set balanceType(2,:)='NONE' if necessary. if ~any(nargout==[3 6]); fprintf(['\ngetCTFBalanceCoefs: Called with %d output arguments. ',... 'Must be 3 or 6.\n\n'],nargout); return elseif (nargout==3 & size(balanceType,1)>1) | (nargout==6 & size(balanceType,1)==1) balanceType=strvcat(deblank(balanceType(1,:)),'NONE'); end % At this point, size(balanceType,1)=2. % Check that balanceType has allowed values for k=1:size(balanceType,1) % k=1:MEGs, k=2:Grefs if isempty(strmatch(balanceType(k,:),balanceOptions(1:balanceOptionsEnds(k),:))) fprintf('\ngetCTFBalanceCoefs: balanceType(%d,:)=%s Not an allowed option.\n\n',... k,balanceType(k,:)); return end end % Check the data units, convert to lower case and flag incorrect unit specification if ~exist('unit'); unit=default_unit; elseif isempty(unit); unit=default_unit; elseif ~ischar(unit) fprintf('\ngetCTFBalanceCoefs: Input unit has the wrong type: class(unit)=%s\n\n',... class(unit)); return end unit=lower(unit); if isempty(strmatch(unit,lower(strvcat(physical_options,raw_options)))) fprintf('\ngetCTFBalanceCoefs: unit=%s. Must be one of ',unit); for k=1:size(unit_options,1);fprintf(' %s,',deblank(unit_options(k,:)));end; fprintf('\n\n'); return end physical=~isempty(strmatch(unit,lower(physical_options))); balanceType=upper(deblank(balanceType)); [betaMEG,MEGindex,MEGbalanceindex,betaGref,Grefindex,Gbalanceindex]=... getRawCTFBalanceCoefs(ds,balanceType); % No balancing is requested, just return lists of MEGindex and Grefindex. if isempty(MEGbalanceindex) alphaMEG=zeros(0,length(MEGindex)); MEGbalanceindex=[]; % force size=[0 0] end if isempty(Gbalanceindex) alphaGref=zeros(0,length(Grefindex)); Gbalanceindex=[]; % force size=[0 0] end if isempty(MEGbalanceindex) & isempty(Gbalanceindex) return end % betaMEG and betaGref are the balance coefficients when signals are in phi0's. % Convert to balance coefficients when signals are in physical units (T or fT). % invproperGain is introduced to take care of situations where bad channels % are labelled by setting their gain to zero. if physical properGain=zeros(1,ds.res4.no_channels); invproperGain=zeros(1,ds.res4.no_channels); for k=1:ds.res4.no_channels if any(ds.res4.senres(k).sensorTypeIndex==[0 1 5:7]) % SQUIDs only properGain(k)=ds.res4.senres(k).properGain; % properGain = phi0/T if properGain(k)~=0 invproperGain(k)=1/properGain(k); end end end end if ~isempty(MEGbalanceindex) if physical alphaMEG=betaMEG.*(properGain(MEGbalanceindex)'*invproperGain(MEGindex)); else alphaMEG=betaMEG; end end if ~isempty(Gbalanceindex) if physical alphaGref=betaGref.*(properGain(Gbalanceindex)'*invproperGain(Grefindex)); else alphaGref=betaGref; end end return %%%%%%%%%%% End of getBalanceCoef %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% Function getRawCTFBalanceCoefs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [betaMEG,MEGindex,Refindex,betaGref,Grefindex,Gbalanceindex]=... getRawCTFBalanceCoefs(ds,balanceType); % getRawCTFBalanceCoefs. Extracts raw-data (i.e. integer data) gradiometer balancing % coefficients from structure array ds.res4.scrr (ds is produced % by readCTFds). % Date : 24 OCt 2006 % Author : Harold Wilson % Inputs : ds : Structure returned by readCTFds. % balanceType : 'NONE' : No balancing % 'G1BR' : 1st order balancing % 'G2BR' : 2nd order balancing % 'G3BR' : 3rd order balancing % 'G3AR' : 3rd order balancing + adaptive % If only MEG balance table is requested, size(balanceType)=[1 4] % If Gref balance table is requested also, size(balanceType)=[2 4] % If balancing 'NONE' is specified, getRawCTFBalanceCoefs returns lists MEGindex and % Grefindex, and sets Refindex=[], Gbalanceindex=[]. % The reference gradiometers have only G1BR balancing coefficients. % Outputs : % betaMEG,MEGindex,Refindex : MEG balancing coefficients. % Suppose data array returned by getCTFdata has size(data)=[npt nchan]. % nMEG = number of MEG channels in the data set. % MEG channels have sensorTypeIndex==5. % % MEGindex = list of MEG channels in the data set. It is assembled % by looking for sensors with ds.res4.senres.sensorTypeIndex==5 % size(MEGindex)=[1 nMEG] % MEG data = data(:,MEGindex) % Refindex = list of reference channels for MEG balancing. % size(Refindex)=[1 nRef] % Reference data = data(:,Refindex) % betaMEG = balance coefficients. size(betaMEG)=[nRef nMEG] % % Balancing MEG data : % - Start with data BEFORE converting to physical units. % (I.e. SQUID data must be in phi0's or raw integers.) % - balanced_data(:,MEGindex)=data(:,MEGindex)-data(:,Refindex)*betaMEG % If user specifies balanceType=[] or ' ', then getRawCTFBalanceCoefs returns % betaMEG=zeros(1,nMEG),Refindex=3 and nRef=1; % betaGref,Grefindex,Gbalanceindex : Reference-gradiometer balancing coeficients. % These output arrays are optional. If the calling statement includes % them, then this program extracts a table of balance coefficients for % the reference gradiometers from the G1BR table in the coefficient files. % nGref = no. of reference gradiometers channels in the data set % (sensorTypeIndex=1) % Grefindex = list of reference channels. size(Grefindex)=[1 nGref] % Gradient reference data = data(:,Grefindex) % Gbalanceindex = list of channels for balancing reference % gradiometers. size(Gbalanceindex)=[1 nGbalcoef] % Balancing reference data = data(:,Gbalanceindex) % betaGref = balance coefficients for ref. grads. % size(betaGref)=[nGbalcoef nGref] % % Balancing ref. gradiometer data : % balanced_data(:,Grefindex)=data(:,Grefindex)-data(:,Gbalanceindex)*betaGref % No function calls. missingMEGMessage=0; missingGrefMessage=0; balanceOptions=strvcat('NONE','G1BR','G2BR','G3BR', 'G3AR'); balanceOptionsEnds = [size(balanceOptions, 1), 2]; % Which options are available for MEGs and Grefs. common_mode_only=0; Brefindex=[]; % Index list of reference magnetometers in the data arrays Grefindex=[]; % Index list of reference gradiometers in the data arrays MEGindex=[]; % Index list of MEG sensors in the data arrays Gbalanceindex=[]; % Index list of sensors used as references to balance the reference % gradiometers Refindex=[]; % Index list of sensors used to balance the MEG sensors betaMEG=[]; betaGref=[]; % Check that the inputs are sensible. if nargin<2 fprintf(['\ngetRawCTFBalanceCoefs: Only %d input arguments? ',... 'Must specify at least ds and balance.\n\n'],nargin); return elseif ~isstruct(ds) | isempty(ds) | ~ischar(balanceType) | isempty(balanceType) fprintf('\ngetRawCTFBalanceCoefs: Wrong argument types or sizes.\n\n'); whos ds balanceType return elseif ~isfield(ds,'res4') fprintf('\ngetRawCTFBalanceCoefs: Field res4 is missing from structure ds.\n\n'); ds return end % Check that the output list is OK. if nargout~=3 & nargout~=6 fprintf('\ngetRawCTFBalanceCoefs : Call specifies %d output arguments.\n',nargout); fprintf('\t\tMust have 3 output arguments (MEG balance coefficients)\n'); fprintf('\t\tor 6 output arguments (reference gradiometer balancing also).\n\n'); return elseif nargout==3 if size(balanceType,1)>1;balanceType=balanceType(1,:);end else if size(balanceType,1)==1;balanceType=strvcat(balanceType,'NONE');end end % Check that balanceType has allowed values for k=1:size(balanceType,1) % k=1:MEGs, k=2:Grefs if isempty(strmatch(balanceType(k,:),balanceOptions(1:balanceOptionsEnds(k),:))) fprintf('\ngetRawCTFBalanceCoefs: balance(%d,:)=%s Not an allowed option.\n\n',... k,balanceType(k,:)); return end end % Make lists of reference magnetometers, reference gradiometers and MEG sensors. for q=1:length(ds.res4.senres) if ds.res4.senres(q).sensorTypeIndex==0 Brefindex=[Brefindex q]; elseif ds.res4.senres(q).sensorTypeIndex==1 Grefindex=[Grefindex q]; elseif ds.res4.senres(q).sensorTypeIndex==5 % Allow other MEG sensors? MEGindex=[MEGindex q]; end end nBref=length(Brefindex); % Don't currently use Brefindex or nBref nGref=length(Grefindex); nMEG=length(MEGindex); nGbalcoef=0; % Set to zero until we know the number by examining ds.res4.scrr if nargout==6 & strcmp(balanceType(2,:),'NONE') Gbalanceindex=[]; betaGref=zeros(0,nGref); elseif nargout==6 & ~strcmp(balanceType(2,:),'NONE') m1=1; % Get coefficients for balancing the reference gradiometers. mtot=size(ds.res4.scrr,2); for n=1:nGref Gname=strtok(ds.res4.chanNames(Grefindex(n),:),['- ',char(0)]); nGchar=length(Gname); for m=[m1:mtot 1:(m1-1)] if strncmp(Gname,char(ds.res4.scrr(m).sensorName),nGchar) & ... strcmp('G1BR',char(ds.res4.scrr(m).coefType)); if nGbalcoef<=0 % 1st match. Initialize table and get list of references nGbalcoef=ds.res4.scrr(m).numcoefs; betaGref=zeros(nGbalcoef,nGref); % Assemble index array for balancing the reference gradiometers for q=1:nGbalcoef Refname=strtok(char(ds.res4.scrr(m).sensor(:,q))',['- ',char(0)]); pRef=strmatch(Refname,ds.res4.chanNames); if isempty(pRef) fprintf(['getRawCTFBalanceCoefs : Sensor %s appears in ',... 'ds.res4.scrr, but not in ds.res4.chanNames\n'],Refname); return end Gbalanceindex=[Gbalanceindex pRef]; end end % end setup of balancing table for Ref. gradiometers if ds.res4.scrr(m).numcoefs~=nGbalcoef fprintf('\ngetRawCTFBalanceCoefs : %s has %d coefficients\n',... ds.res4.chanNames(Grefindex(1),1:nGchar),nGbalcoef); fprintf(' %s " %d " ????\n\n',... ds.res4.chanNames(Grefindex(n),1:nGchar),ds.res4.scrr(m).numcoefs); betaGref=[]; % Force useless output. return end betaGref(:,n)=reshape(ds.res4.scrr(m).coefs(1:nGbalcoef),nGbalcoef,1); m1=m+1; break; % Break out of m-loop. Go to nect n value. end if (m==m1-1 & m1>1) | (m==mtot & m1==1) if missingGrefMessage==0 if strncmp(balanceType(2,:), balanceOptions(5,:), 4) % Avoid warning for all sensors for adaptive coefficients. fprintf('\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients for reference sensors.\n',... balanceType(2,:)); else fprintf(['\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients',... ' for sensor(s)'],balanceType(2,:)); fprintf('\n\t\t\t\t'); end end missingGrefMessage=missingGrefMessage+1; if ~strncmp(balanceType(2,:), balanceOptions(5,:), 4) if missingGrefMessage==10*round(missingGrefMessage/10) fprintf('\n\t\t\t\t'); end fprintf(' %s',Gname); end betaGRef(:,n)=zeros(nGbalcoef,1); return end end % End loop over m (searching for scrr(m).sensorName) end % End loop over n (list of reference gradiometers) end % End of section getting coefficients to balance the reference gradiometers. if missingGrefMessage>0;fprintf('\n');end if strcmp(balanceType(1,:),'NONE') Refindex=[]; betaMEG=zeros(0,nMEG); return end % Get balance coefficients for the MEG sensors nRef=0; % Pointers for search through ds.res4.scrr structure array. m1=1; mtot=size(ds.res4.scrr,2); for n=1:nMEG MEGname=strtok(ds.res4.chanNames(MEGindex(n),:),['- ',char(0)]); nChar=length(MEGname); for m=[m1:mtot 1:(m1-1)] if strncmp(MEGname,char(ds.res4.scrr(m).sensorName),nChar) & ... strcmp(balanceType(1,:),char(ds.res4.scrr(m).coefType)); if nRef<=0 nRef=ds.res4.scrr(m).numcoefs; betaMEG=zeros(nRef,nMEG); for q=1:nRef % Assemble index array for balancing the MEG sensors Refname=strtok(char(ds.res4.scrr(m).sensor(:,q))',['- ',char(0)]); pRef=strmatch(Refname,ds.res4.chanNames); if isempty(pRef) fprintf(['\ngetRawCTFBalanceCoefs : Sensor %s appears in ',... 'ds.res4.scrr, but not in ds.res4.chanNames\n\n'],Refname); return end Refindex=[Refindex pRef]; end end % end setup of balancing table for MEG sensors if ds.res4.scrr(m).numcoefs~=nRef fprintf('\ngetRawCTFBalanceCoefs : %s - %s has %d coefficients\n',... ds.res4.chanNames(MEGindex(1),1:nChar),balanceType,nRef); fprintf(' %s - %s " %d " ????\n\n',... ds.res4.chanNames(MEGindex(n),1:nChar),balanceType,... ds.res4.scrr(m).numcoefs); betaMEG=[]; % An output that will force an error in the calling program. return end betaMEG(:,n)=reshape(ds.res4.scrr(m).coefs(1:nRef),nRef,1); m1=m+1; break; end if (m==m1-1 & m1>1) | (m==mtot & m1==1) if missingMEGMessage==0 if strncmp(balanceType(2,:), balanceOptions(5,:), 4) % Avoid warning for all sensors for adaptive coefficients. fprintf('\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients for sensors.\n',... balanceType(2,:)); else fprintf(['\ngetRawCTFBalanceCoefs: Failed to find %s balance coefficients',... ' for sensor(s)'],balanceType(1,:)); fprintf('\n\t\t\t\t'); end end missingMEGMessage=missingMEGMessage+1; if ~strncmp(balanceType(2,:), balanceOptions(5,:), 4) if missingMEGMessage==10*round(missingMEGMessage/10) fprintf('\n\t\t\t\t'); end fprintf(' %s',MEGname); end betaMEG(:,n)=zeros(nRef,1); end end % End of loop over m (ds.res4.scrr table) end % End of loop over MEG sensors if missingMEGMessage>0;fprintf('\n');end if common_mode_only if size(betaMEG,1)>3 & nMEG>0 betaMEG=betaMEG(1:3,:); Refindex=Refindex(1:3); end if size(betaGref,1)>3 & nGref>0 betaGref=betaGref(1:3,:); Gbalanceindex=Gbalanceindex(1:3); end end return
github
lcnbeapp/beapp-master
writeCTFds.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/external/ctf/writeCTFds.m
68,946
utf_8
96615f4833d69490d5b3e47f6f86c538
function ds=writeCTFds(datasetname,ds,data,unit); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % This program creates datasets that can be analyzed by CTF software. % % % % Datasets created by this program MUST NOT BE USED FOR CLINICAL APPLICATIONS. % % % % Please do not redistribute it without permission from VSM MedTech Ltd. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Author : Harold Wilson % Version 1.3 5 October 2007 Spelling errors in some variables corrected. % Version 1.2 24 April 2007 Modified to write both MEG and fMEG .hc files. % writeCTFds.m Version 1.1 Prepares a CTF-format data set. MATLAB to CTF conversion. % Adds record of filter changes to hist and newds files. % Adds no-clinical-use messages. % Creates multiple meg4 files when the total size of the data array % >536870910 elements. % Operation : % 1. User reads a data set using readCTFds and getTrial2. % size(data)= [SAMPLES, CHANNELS, TRIALS]. % 2. After working on data in MATLAB, user adjusts ds structure to reflect changes. % (writeCTFds will adjust the number of channels, channel names and trial structure.) % 3. This program then creates a new CTF data set. % datasetname must include the complete path description. % If a data set with name datasetname already exists, writeCTFds will issue an error message. % The new directory contains files for each field of structure ds. If the field is % missing no file is created. If the field is empty, an empty file is created. % Files default.* are not created by writeCTFds. % 4. The following fields of structure ds.res4 are modified based on the size of array data : % no_samples % no_channels % no_trials. % If size(ds.res4.chanNames,1)<no_channels, additional channel names are created % as required. The additional channels are called MXT%%%. It is assumed that % there will be <1000 new channels. % Inputs : datasetname : Output dataset including path. Extension '.ds' is optional. % ds : Structure produced by readCTFds. % data : MEG data array. size(data)=[no_samples no_channels no_trials] % Array data may be single or double. % unit : Determines the unit of the SQUID and EEG signals: % If unit is missing or unit==[], the unit is set to 'fT'. % 'ft' or 'fT' : Convert to fT (MEG), uV (EEG) % 't' or 'T' : Convert to T (MEG), V (EEG) % 'phi0' : Convert to phi0 (MEG), uV (EEG) % 'int': Read plain integers from *.meg4-file % Outputs : - ds : The ds structure of the output data set. % - datasetout : the name of the output data set. % - A data set. The .hz and .hz2 subdirectories are not included. % Function calls % Included in this listing: % - check_senres: Does simple checks on the fields of the senres table. % - writeHc: Creates the new .hc file % - checkMrk: Checks structure ds.mrk to see if it is valid marker set. % - writeEEG: Creates the new .EEG file. % - writeBadSegments: Creates the new bad.segments file. % - writeClassFile: Creates the new ClassFile.cls file. % - writeVirtualChannels: Creates the new VirtualChannels file. % - updateDescriptors: Adds non-clinical-use and creation software messages to % infods, res4, newds and hist fields of ds. % - updateHLC: Adds head-coil movement information to infods. % - updateDateTime : Resets dattime fields of res4 and infods. % - updateBandwidth: Resets bandwidth of newds and infods. Adds res4 filter % description to ds.hist. % - getArrayField : Extracts one field of a structure array to make it easier to % manipulate. % - writeMarkerFile: Creates the new MarkerFile.mrk file. % - writeCPersist: Creates the new .acq and .infods files. % Other calls: % - writeRes4: Writes the new .res4 file. % Output files are opened with 'w' permission and 'ieee-be' machine format in order % to be compatible with the Linux acquisition and analysis software. Do not open files % with 'wt' permission because this will add an extra char(13) byte at the end of each % line of text. persistent printWarning bandwidthMessage delim=filesep; if nargin==0 & nargout==0 % Print a version number fprintf(['\twriteCTFds: Version 1.3 5 October 2007 ',... 'Creates v4.1 and v4.2 CTF data sets.\n',... '\tCall: ds=writeCTFds(datasetname,ds,data,unit);\n',... '\t\tdatasetname = Name of the new dataset including the path.\n',... '\t\tds = Structure describing the new dataset (ds.hc must be v1.2 format).\n',... '\t\tdata = data that will be written to the new dataset .meg4 file.\n',... '\t\tunit = physical units of the data.\n\n']); return end % Allowed 8-byte headers for res4 and meg4 files. res4_headers=strvcat(['MEG41RS',char(0)],['MEG42RS',char(0)]); meg4_headers=strvcat(['MEG41CP',char(0)],['MEG42CP',char(0)]); maxMEG4Size=2^31; % Maximum MEG$ file in bytes. (Limit set by Linux software) MAX_COILS=8; % Parameter that determines the size of the ds.res.senres structure. lenSensorName=32; % Channel names must be 32 characters printDefaultBandwidthMessage=0; % Print a message about default bandwidth? default_flp=0.25; % Default is flp=0.25*ds.res4.sample_rate clinicalUseMessage='NOT FOR CLINICAL USE'; creatorSoftware='writeCTFds'; % Added to .infods file meg4ChunkSize=2^20; % Write new .meg4 file in chunks of 4*meg4ChunkSize bytes. DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006 if ~exist('clinicalUseMessage'); clinicalUseMessage=char([]); end % Check inputs if nargin<3 fprintf(['\nwriteCTFds: Must supply inputs datasetname,ds,data. ',... 'Only %d input arguments are present.\n\n'],nargin); ds=-1; % Force an error in the calling program. return end % Check input argument unit. Convert unit to lower case. if exist('unit')~=1 unit='ft'; % default elseif isempty(unit) unit='ft'; % default elseif ischar(unit) unit=lower(unit); if ~strcmp(unit,'int') & ~strcmp(unit,'ft') & ~strcmp(unit,'t') & ~strcmp(unit,'phi0') fprintf(['\nwriteCTFds : unit=%s Not a valid option. Must be ',... '''fT'', ''T'', ''phi0'' or ''int''\n\n'],unit); ds=-1; % Force an error in the calling program. return end end % Check argument type if ~isstruct(ds) | ~isnumeric(data) | ~ischar(unit) | ~ischar(datasetname) fprintf('\nwriteCTFds: Some of the inputs are the wrong type.\n'); whos datasetname ds data unit; ds=-1; return elseif ~isfield(ds,'res4') | ~isfield(ds,'meg4') fprintf('\nwriteCTFds: Fields res4 and meg4 must be present in structure ds.\n\n'); ds % List the fields of structure ds. ds=-1; % Force an error in the calling program. return end % Refuse to write a data set with balanced reference gradiometers. balancedGref=0; for k=1:ds.res4.no_channels balancedGref=(ds.res4.senres(k).sensorTypeIndex==1 & ds.res4.senres(k).grad_order_no~=0); end if balancedGref fprintf('\nwriteCTFds: ds.res4.senres indicates balanced reference gradiometers.\n\n'); ds=-1; % Force an error in the calling program. return end clear k balancedGref; % Separate datasetname into a path and the baseName datasetname=deblank(datasetname); ksep=max([0 findstr(datasetname,delim)]); baseName=datasetname((ksep+1):length(datasetname)); path=datasetname(1:ksep); % String path is terminated by the file delimiter (or path=[]). % Remove the last .ds from baseName. kdot=max(findstr(baseName,'.ds')); if kdot==(length(baseName)-2) baseName=baseName(1:(max(kdot)-1)); else datasetname=[datasetname,'.ds']; end clear ksep kdot; % Save the name already in structure ds, and change to the new datset name. if isfield(ds,'baseName') olddatasetname=[ds.baseName,'.ds']; if isfield(ds, 'path') olddatasetname=[ds.path,olddatasetname]; end else olddatasetname=' None '; end ds.path=path; ds.baseName=baseName; % Does the dataset already exist? if exist(datasetname)==7 fprintf('\nwriteCTFds: Dataset %s already exists. Use a different name.\n\n',... datasetname); ds=-1; % Force an error in the calling program. return end if size(ds.res4.chanNames,2)~=lenSensorName fprintf(['\nwriteCTFds : size(ds.res4.chanNames)=[%d %d] ? Must ',... 'have %d-character channel names.\n\n'],size(ds.res4.chanNames),lenSensorName); ds=-1; return end % Check that the channel names have a sensor-file identification extensions. % If it is missing, print a warning message. % Sensor type indices : SQUIDs (0:7), ADCs (10), DACs(14), Clock (17), HLC (13,28,29) % See Document CTF MEG File Formats (PN 900-0088), RES4 File Format/ for index=[0:7 10 13 14 17 28 29] for k=find([ds.res4.senres.sensorTypeIndex]==index); if isempty(strfind(ds.res4.chanNames(k,:),'-')) fprintf(['writeCTFds: Channel %3d %s No sensor-file identification.',... ' (''-xxxx'' appended to channel name).\n',... '\t\tSome CTF software may not work with these channel names.\n'],... k,deblank(ds.res4.chanNames(k,:))); break; end end if isempty(strfind(ds.res4.chanNames(k,:),'-'));break;end end clear index k chanName; % Update the data description in the ds.res4 structure. [nSample, nChan, trials]=size(data); % Update ds.res4 fields to match the size of array data. ds.res4.no_trials=trials; ds.res4.no_channels=nChan; ds.res4.no_samples=nSample; ds.res4.epoch_time=nSample*trials/ds.res4.sample_rate; % Check if channels have been added or removed from array data. [no_chanNames len_chanNames]=size(ds.res4.chanNames); if no_chanNames<nChan % Assume that new channel are at the end of the data set. Add a fake extension. for kx=1:(nChan-no_chanNames) ds.res4.chanNames=... strvcat(ds.res4.chanNames,['MXT' num2str(kx,'%3.3d') '-0001' char(0)]); end fprintf('\tAdded %d SQUID channels to the end of ds.res4.chanNames table.\n',... nChan-no_chanNames); elseif no_chanNames>nChan fprintf(['\nlength(chanNames)=%d, but only %d channels of data. ',... 'writeCTFds cannot tell which channel names to remove.\n\n'],no_chanNames,nChan); ds=-1; return end clear no_chanNames len_chanNames; % The senres table may have been changed, especially if channels are added or removed. % Check structure senres, print error messages, and possibly fix the errors. [ds.res4.senres,status]=check_senres(ds.res4.senres,ds.res4.no_channels); if status<0;ds=-1;return;end clear status; % Check that ds.res4.numcoef is the size of structure array ds.res4.scrr. if isfield(ds.res4,'scrr') if ~isequal(size(ds.res4.scrr,2),ds.res4.numcoef) fprintf('Error in ds.res4: ds.res4.numcoef=%d, but size(ds.res4.scrr)=[',... ds.res4.numcoef); fprintf(' %d',size(ds.res4.scrr));fprintf('] ?\n'); return end elseif ds.res4.numcoef~=0 fprintf(['Error in ds.res4: ds.res4.numcoef=%d,',... ' but scrr is not a field of ds.res4\n'],ds.res4.numcoef); return end % Before converting data to integers, save HLC channels for motion analysis in function % make_new_infods. Pass HLCdata to function make_new_infods if isempty(strmatch('HLC',ds.res4.chanNames)) HLCdata=[]; else % Make a list of head-coil channels coil=0; HLClist=[]; while ~isempty(strmatch(['HLC00',int2str(coil+1)],ds.res4.chanNames)) coil=coil+1; for k=1:3 HLClist=[HLClist strmatch(['HLC00',int2str(coil),int2str(k)],ds.res4.chanNames)]; end end HLCdata=reshape(double(data(:,HLClist,:)),ds.res4.no_samples,3,coil,ds.res4.no_trials); clear coil k HLClist; end % Convert data to integers because CTF data sets are stored as raw numbers and % not as physical qunatities. The res4 file contains the calibrations for % converting back to physical units. Array data may be single precision, so % convert to double before doing any adjustments to the data. % Already checked that unit is valid. if strcmp(unit,'int') data=reshape(data,nSample,nChan*trials); for k=1:nChan*trials if strcmp(class(data),'single') data(:,k)=single(round(double(data(:,k)))); else data(:,k)=round(double(data(:,k))); end end data=reshape(data,nSample,nChan,trials); clear k; else for chan=1:nChan % Convert EEGs from uV to V, SQUIDs from fT to T SQUIDtype=any(ds.res4.senres(chan).sensorTypeIndex==[0:7]); EEGtype=any(ds.res4.senres(chan).sensorTypeIndex==[8 9]); if EEGtype & (strcmp(unit,'ft') | strtcmp(unit,'phi0')) alphaG=1e-6; elseif SQUIDtype & strcmp(unit,'ft') alphaG=1e-15; elseif SQUIDtype & strcmp(unit,'phi0') alphaG=1./(ds.res4.senres(chan).properGain*ds.res4.senres(chan).ioGain); else alphaG=1; end % Convert from physical units to integers using the gains in the senres table. for kt=1:trials buff=round(double(data(:,chan,kt))*(alphaG*... (ds.res4.senres(chan).properGain*ds.res4.senres(chan).qGain*ds.res4.senres(chan).ioGain))); if strcmp(class(data),'single') data(:,chan,kt)=single(buff); else data(:,chan,kt)=buff; end end end clear chan alphaG SQUIDtype EEGtype buff kt; end % Create the output dataset [status,msg]=mkdir(path,[baseName '.ds']); if status==0 | ~isempty(msg) fprintf('\nwriteCTFds: Failed to create directory.\n'); fprintf(' [status,msg]=mkdir(%s)\n',datasetname); fprintf(' returns status=%d, msg=%s',status,msg);fprintf('\n\n'); ds=-1; return end clear msg status; % Write the data file (meg4 file). Check ds.meg4.header and make sure that % the output .meg4 file has an acceptable header. headerMessage=1; if ~isfield(ds.meg4,'header'); % If ds.meg4.header is missing, add it. nChar=length(deblank(meg4_headers(1,:))); ds.meg4.header=[meg4_headers(1,1:min(7,nChar)) char(zeros(1,7-nChar))]; elseif isempty(strmatch(ds.meg4.header(1:7),meg4_headers(:,1:7),'exact')) ds.meg4.header=meg4_headers(1,1:7); else headerMessage=0; end if headerMessage; fprintf('writeCTFds: Set ds.meg4.header=%s\n',ds.meg4.header); end clear headerMessage; if isempty(printWarning) fprintf(['\nwriteCTFds: The data you are writing have been processed by software not\n',... '\tmanufactured by VSM MedTech Ltd. and that has not received marketing clearance\n',... '\tfor clinical applications. These data should not be later employed for clinical\n',... '\tand/or diagnostic purposes.\n\n']); printWarning=1; end % Write the meg4 file(s). If there are more than maxMEG4Size-8 bytes, then additional meg4 % files will be created. % Convert data to a 1-D array ndata=prod(size(data)); data=reshape(data,ndata,1); ptsPerTrial=nSample*nChan; maxPtsPerFile=ptsPerTrial*floor((maxMEG4Size-8)/(4*ptsPerTrial)); pt=0; % Last point written to the output file(s). while pt<ndata endPt=pt+min(ndata-pt,maxPtsPerFile); if pt==0 meg4Ext='.meg4'; else meg4Ext=['.',int2str(floor(pt/maxPtsPerFile)),'_meg4']; end fidMeg4=fopen([path,baseName,'.ds',delim,baseName,meg4Ext],'w','ieee-be'); fwrite(fidMeg4,[ds.meg4.header(1:7),char(0)],'uint8'); while pt<endPt pt1=min(pt+meg4ChunkSize,endPt); % Convert to double in case data is fwrite(fidMeg4,double(data((pt+1):pt1)),'int32'); % is single and write in short pt=pt1; % pieces. end fclose(fidMeg4); end % Update the .meg4 part of structure ds. ds.meg4.fileSize=4*ndata+8*(1+floor(ndata/maxPtsPerFile)); clear data pt pt1 ndata fidMeg4 ptsPerTrial maxPtsPerFile meg4Ext; % Add dataset names to .hist if ~isfield(ds,'hist');ds.hist=char([]);end ds.hist=[ds.hist char(10) char(10) datestr(now) ' :' char(10) ... ' Read into MATLAB as data set ' olddatasetname char(10) ... ' Rewritten by writeCTFds as data set ' datasetname char(10)]; % If infods doesn't exist or is empty create it. if ~isfield(ds,'infods');ds.infods=[];end if isempty(ds.infods) ds.infods=make_dummy_infods(isfield(ds,'hc'),~isempty(HLCdata),ds.res4.sample_rate); end % Update text fields of res4,infods, newds and hist. ds=updateDescriptors(ds,clinicalUseMessage,creatorSoftware); % Add HLC data to infods ds.infods=updateHLC(ds.infods,HLCdata); % Analyze structure array ds.res4.filters to make text info for .hist file and % bandwidth parameters for .newds file. fhp=0; % High-pass cutoff assuming no filters flp=default_flp*ds.res4.sample_rate; % Assumed lowpass cutoff. SHOULD THIS BE CHANGED? if isempty(bandwidthMessage) & printDefaultBandwidthMessage fprintf('writeCTFds: Lowpass filter set to flp=%0.2f*sample_rate\n',default_flp); bandwidthMessage=1; end ds=updateBandwidth(ds,fhp,flp); % Update date/time fields of infods and res4 ds=updateDateTime(ds); % Create the .res4 file in the output dataset. ds.res4=writeRes4([path,baseName,'.ds',delim,baseName,'.res4'],ds.res4,MAX_COILS); if ds.res4.numcoef<0 fprintf('\nwriteCTFds: writeRes4 returned ds.res4.numcoef=%d (<0??)\n\n',... ds.res4.numcoef); % Kill the output dataset. rmdir([path,baseName,'.ds'],'s'); ds=-1; return end % Create .hist file histfile=[path,baseName,'.ds',delim,baseName,'.hist']; fid=fopen(histfile,'w'); fwrite(fid,ds.hist,'uint8'); fclose(fid); % New .newds file if isfield(ds,'newds') fid=fopen([path,baseName,'.ds',delim,baseName,'.newds'],'w'); fwrite(fid,ds.newds,'uint8'); fclose(fid); end % New infods file. if isfield(ds,'infods') writeCPersist([path,baseName,'.ds',delim,baseName,'.infods'],ds.infods); end % new hc file if isfield(ds,'hc') ds.hc=writeHc([path,baseName,'.ds',delim,baseName,'.hc'],ds.hc,HLCdata(:,:,1)); end clear HLCdata; % MarkerFile.mrk if checkMrk(ds) writeMarkerFile([path,baseName,'.ds',delim,'MarkerFile.mrk'],ds.mrk); end % .EEG if isfield(ds,'EEG') writeEEG([path,baseName,'.ds',delim,baseName,'.EEG'],ds.EEG); end % .acq if isfield(ds,'acq'); % Check that ds.acq has the correct fields if isfield(ds.acq,'name') & isfield(ds.acq,'type') & isfield(ds.acq,'data') acqFilename=[path,baseName,'.ds',delim,baseName,'.acq']; writeCPersist(acqFilename,ds.acq); end end % bad.segments file if isfield(ds,'badSegments') writeBadSegments([path,baseName,'.ds',delim,'bad.segments'],ds.badSegments,... ds.res4.no_trials,ds.res4.no_samples/ds.res4.sample_rate); end % BadChannels if isfield(ds,'BadChannels'); if ischar(ds.BadChannels) & ~isempty(ds.BadChannels) fid=fopen([path,baseName,'.ds',delim,'BadChannels'],'w','ieee-be'); for k=1:size(ds.BadChannels,1) fprintf(fid,'%s\n',deblank(ds.BadChannels(k,:))); end fclose(fid); end end % ClassFile if check_cls(ds) writeClassFile([path,baseName,'.ds',delim,'ClassFile.cls'],ds.TrialClass); end % VirtualChannels if isfield(ds,'Virtual') writeVirtualChannels([path,baseName,'.ds',delim,'VirtualChannels'],ds.Virtual); end % processing.cfg if isfield(ds,'processing'); if ischar(ds.processing) fid=fopen([datasetname,delim,'processing.cfg'],'w','ieee-be'); fwrite(fid,ds.processing,'uint8'); fclose(fid); end end % Update the data set path and name ds.path=path; ds.baseName=baseName; return % *************** End of function writeCTFds ******************************************** % ************************************************************************************** % ************************************************************************************** % *************** Function check_senres ************************** function [senres,status]=check_senres(senres,numChan); % A user may have augmented the senres table, so check that all the fields have the % correct size. This will cause errors in programs that try to compute % sensor response using the geometry in the senres table. % Does "sanity" checks on the senres table. If there are obviously incorrect entries, it % tries to fix them, and prints a message. If the senres table does not specify coil % positions, orientations or areas, set them to zero, but give them the correct array % size. newChannelType=4; % Create the fake sensors as MEG magnetometers. This way offsets can be removed. status=-1; % Does the senres table have the correct no. of channels? no_senres=length(senres); if no_senres<numChan % Add channels. Assume that they are gradiometers. ioGain=1; qGain=2^20; gain=0.3; properGain=1e15/(qGain*ioGain*gain); % sensor gain in phi0/fT for kx=(no_senres+1):numChan senres(kx)=struct(... 'sensorTypeIndex',newChannelType,'originalRunNum',0,'coilShape',0,... 'properGain',properGain,'qGain',qGain,'ioGain',ioGain,... 'ioOffset',0,'numCoils',1,... 'grad_order_no',0,... 'gain',gain,... 'pos0',zeros(3,1),'ori0',zeros(3,1),... 'area',0.1,'numturns',1,... 'pos',[0 0 21]','ori',zeros(3,1)); end fprintf(['\tAdded %d SQUID channels to senres table. Nominal gain of each = ',... '%8.4f fT/step\n'],numChan-no_senres,gain); clear kx gain qGain ioGain properGain; elseif no_senres>numChan % Channels have been removed from the data set, but can't tell which elements of the % senres table to remove. fprintf(['length(senres)=%d, but only %d channels of data. writeCTFds can''t',... ' tell which channels to remove from senres table.\n'],no_senres,numChan); return end no_senres=length(senres); % Previous version of check_senres ensures that several fields had size [1 1]. % Seems unnecessary, so removed it. for k=1:no_senres % Check the fields that define pickup loops. Force the field defining the pickup % loops to have the correct size. It is not clear why the EEG channels and % the type=13,28,29 HLC channels need numCoils=1, and area>0. if any(senres(k).sensorTypeIndex==[0:7]) % SQUID channels correct_numCoils=rem(senres(k).sensorTypeIndex,4)+1; elseif any(senres(k).sensorTypeIndex==[13 28 29]) % HLC channels correct_numCoils=1; elseif any(senres(k).sensorTypeIndex==[8 9]) % EEG channels correct_numCoils=1; else correct_numCoils=0; end if senres(k).numCoils~=correct_numCoils & any(senres(k).sensorTypeIndex==[0:7]) fprintf('writeCTFds_test: senres(%d).sensorTypeIndex=%d but numCoils=%d??\n',... k,senres(k).sensorTypeIndex,senres(k).numCoils); fprintf(' Set numCoils=%d\n',correct_numCoils); senres(k).numCoils=correct_numCoils; end numCoils=senres(k).numCoils; if size(senres(k).pos0)~=[3 numCoils];pos0=zeros(3,numCoils);end if size(senres(k).ori0)~=[3 numCoils];ori0=zeros(3,numCoils);end if size(senres(k).pos)~=[3 numCoils];pos=zeros(3,numCoils);end if size(senres(k).ori)~=[3 numCoils];ori=zeros(3,numCoils);end if size(senres(k).numturns)~=[1 numCoils];numturns=zeros(1,numCoils);end if size(senres(k).area)~=[1 numCoils];area=zeros(3,numCoils);end end status=1; return % ************* End of function check_senres********************************************* % ************************************************************************************** % ************************************************************************************** % ************* function make_dummy_infods********************************************* function Tag=make_dummy_infods(exist_hc,exist_HLC,sample_rate); % If the user does not supply ds.infos, this code makes a dummy version. It has all of % the tags that Acq created in file Richard_SEF_20060606_04.infods. % *********************************************************************************** % *********************************************************************************** DATASET_HZ_UNKNOWN=round(2^31-1); % Peculiar requirement of DataEditor as of 23 Oct. 2006 fprintf('writeCTDds (make_dummy_infods): Creating a dummy infods file with all the tags.\n'); Tag(1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_PATIENT_INFO','type',2,'data',[]); Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_PATIENT_UID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011'); Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_FIRST','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_MIDDLE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_NAME_LAST','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_ID','type',10,'data','x'); Tag(length(Tag)+1)=struct('name','_PATIENT_BIRTHDATE','type',10,'data','19500101000000'); Tag(length(Tag)+1)=struct('name','_PATIENT_SEX','type',5,'data',2); Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_NAME','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_PACS_UID','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PATIENT_INSTITUTE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); Tag(length(Tag)+1)=struct('name','_PROCEDURE_INFO','type',2,'data',[]); Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_PROCEDURE_VERSION','type',5,'data',1); Tag(length(Tag)+1)=struct('name','_PROCEDURE_UID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_ACCESSIONNUMBER','type',10,'data','0'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_TITLE','type',10,'data','0'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_SITE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PROCEDURE_STATUS','type',5,'data',1); Tag(length(Tag)+1)=struct('name','_PROCEDURE_TYPE','type',5,'data',2); % Research type Tag(length(Tag)+1)=struct('name','_PROCEDURE_STARTEDDATETIME','type',10,... 'data','20060606164306'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_CLOSEDDATETIME','type',10,... 'data','19000100000000'); Tag(length(Tag)+1)=struct('name','_PROCEDURE_COMMENTS','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PROCEDURE_LOCATION','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_PROCEDURE_ISINDB','type',5,'data',0); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); Tag(length(Tag)+1)=struct('name','_DATASET_INFO','type',2,'data',[]); Tag(length(Tag)+1)=struct('name','WS1_','type',0,'data',[]); Tag(length(Tag)+1)=struct('name','_DATASET_VERSION','type',5,'data',2); Tag(length(Tag)+1)=struct('name','_DATASET_UID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0042'); Tag(length(Tag)+1)=struct('name','_DATASET_PATIENTUID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0011'); Tag(length(Tag)+1)=struct('name','_DATASET_PROCEDUREUID','type',10,... 'data','2.16.124.113000.000000.00000000000000.000000000.00000000.0041'); Tag(length(Tag)+1)=struct('name','_DATASET_STATUS','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_RPFILE','type',10,'data','default.rp'); Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPTITLE','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPPROTOCOL','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_PROCSTEPDESCRIPTION','type',10,... 'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONDATETIME','type',10,... 'data','Unknown'); Tag(length(Tag)+1)=struct('name','_DATASET_COLLECTIONSOFTWARE','type',10,... 'data','Acq '); Tag(length(Tag)+1)=struct('name','_DATASET_CREATORDATETIME','type',10,... 'data',sprintf('%d',floor(clock))); Tag(length(Tag)+1)=struct('name','_DATASET_CREATORSOFTWARE','type',10,... 'data','Acq '); Tag(length(Tag)+1)=struct('name','_DATASET_KEYWORDS','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_COMMENTS','type',10,... 'data','Dummy infods.'); Tag(length(Tag)+1)=struct('name','_DATASET_OPERATORNAME','type',10,'data',''); Tag(length(Tag)+1)=struct('name','_DATASET_LASTMODIFIEDDATETIME','type',10,... 'data',sprintf('%d',floor(clock))); if exist_hc nominalPositions=0; % Measured else nominalPositions=1; % Nominal end Tag(length(Tag)+1)=struct('name','_DATASET_NOMINALHCPOSITIONS','type',5,... 'data',nominalPositions); Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,... 'data','ds.res4.scrr'); Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,... 'data','ds.res4.senres'); %Tag(length(Tag)+1)=struct('name','_DATASET_COEFSFILENAME','type',10,... % 'data','/opt/ctf-5.1/hardware/M015/M015_1609.coef'); %Tag(length(Tag)+1)=struct('name','_DATASET_SENSORSFILENAME','type',10,... % 'data','/opt/ctf-5.1/hardware/M015/M015_1609.sens'); Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEM','type',10,'data','DSQ-2010'); Tag(length(Tag)+1)=struct('name','_DATASET_SYSTEMTYPE','type',10,'data','Untitled'); Tag(length(Tag)+1)=struct('name','_DATASET_LOWERBANDWIDTH','type',4,'data',0); Tag(length(Tag)+1)=struct('name','_DATASET_UPPERBANDWIDTH','type',4,'data',... round(0.25*sample_rate)); Tag(length(Tag)+1)=struct('name','_DATASET_ISINDB','type',5,'data',0); if exist_HLC HZ_MODE=5; elseif exist_hc HZ_MODE=1; else HZ_MODE=DATASET_HZ_UNKNOWN; end Tag(length(Tag)+1)=struct('name','_DATASET_HZ_MODE','type',5,'data',HZ_MODE); Tag(length(Tag)+1)=struct('name','_DATASET_MOTIONTOLERANCE','type',4,'data',0.005); Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTION','type',4,'data',0.005); Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONTRIAL','type',7,'data',0); Tag(length(Tag)+1)=struct('name','_DATASET_MAXHEADMOTIONCOIL','type',10,'data','1'); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); Tag(length(Tag)+1)=struct('name','EndOfParameters','type',-1,'data',[]); return % ************* End of function make_dummy_infods********************************************* % ************************************************************************************** % ************************************************************************************** % ************* Function writeHc********************************************* function hc=writeHc(hcFileName,hc,HLCdata); % Modified for v1.2 ds.hc structures. ds.hc.names has the exact, complete names of the % head coils. The coordinates relative to the subject may be ds.hc.head(MEG) OR % ds.hc.abdomen (fMEG). % Creates a .hc file in a CTF dataset % Inputs: hcFileName : Complete name of .hc file including path, basename and .hc ext. % hc : structure with nasion, left, right head coil positions in dewar and % CTF head coordinates. % HLCdata : head coil locations at the start of 1st trial. unit=m % coordinates=dewar. Used only if structure hc is empty and it is MEG % data (not fMEG data). % Output : hc : hc structure. hc=struct([]) on failure. hc is set to the coil positions % in array HLCdata if hc=[] on entry. % Check inputs if exist('hc')~=1 hc=struct([]); elseif ~isstruct(hc) hc=struct([]); end hcfields=fieldnames(hc); if exist('HLCdata')~=1 HLCdata=[]; elseif ~isnumeric(HLCdata) | size(HLCdata,1)~=3 | size(HLCdata,2)<3 HLCdata=[]; end % Check hc Filename if exist('hcFileName')~=1;hcFileName=char([]);end if ~ischar(hcFileName) | isempty(hcFileName) fprintf('writeCTFds (writeHc): Called writeHc with bad file name.\n'); hcFileName return end % Both hc and HLCdata bad? if length(hcfields)~=4 & isempty(HLCdata) fprintf('writeCTFds (writeHc): Called writeHc with bad hc and bad HLCdata.\n'); hc=struct([]) return elseif length(hcfields)~=4 rstandard=8/sqrt(2)*[1 1 0;-1 1 0;1 -1 0]'; rstandard(3,:)=-27; rdewar=100*HLCdata(:,1:3); % Convert from dewar coordinates to CTF head coordinates. originCTF=0.5*(hc.dewar(:,2)+hc.dewar(:,3)); % Unit vectors for the CTF coordinates uCTF(:,1)=hc.dewar(:,1)-originCTF; uCTF(:,3)=cross(uxCTF,hc.dewar(:,2)-hc.dewar(:,3)); uCTF(:,2)=cross(uCTF(:,3),uCTF(:,1)); uCTF=uCTF./(ones(3,1)*sqrt(sum(uCTF.^2,1))); rCTF=uCTF'*(rdewar-originCTF*ones(1,3)) hc=struct('names',strvcat('nasion','left ear','right ear'),... 'standard',rstandard,'dewar',rdewar,'head',rCTF); clear originCTF uCTF rstandard rdewar rCTF; end % Character strings for generating the .hc text file % Should never have both 'head' and 'abdomen' fields. labelword=strvcat('standard','measured','measured'); printField=[strmatch('standard',hcfields) strmatch('dewar',hcfields) ... strmatch('head',hcfields) strmatch('abdomen',hcfields)]; if ~strmatch('names',hcfields) | length(printField)~=3 fprintf(['writeCTFds (writeHc): Structure hc does not have all of the required fields.\n',... ' No .hc file will appear in the output dataset.\n']); hc; hc=struct([]); return end relative=strvcat('dewar','dewar',hcfields{printField(3)}); coilcoord=strvcat('standard','dewar',hcfields{printField(3)}); comp='xyz'; coilname=hc.names; fid=fopen(hcFileName,'w','ieee-be'); for k=1:size(coilcoord,1) rcoil=getfield(hc,coilcoord(k,:)); for coil=1:size(hc.names,1) clName=deblank(hc.names(coil,:)); fwrite(fid,[labelword(k,:) ' ' clName ' coil position relative to ',... deblank(relative(k,:)) ' (cm):' char(10)],'uint8'); for m=1:3 fwrite(fid,[char(9) comp(m) ' = ' num2str(rcoil(m,coil),'%7.5f') char(10)],'uint8'); end end end fclose(fid); status=0; return % ************* End of function writeHc********************************************* % ************************************************************************************** %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%Function checkMrk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function MarkerFileOK=checkMrk(ds); % Examines structure ds to see if a sensible MarkerFile can be created from ds.mrk. % Output: MarkerFileOK=1 : ds.mrk looks OK % MarkerFileOK=0 : ds.mrk cannot be a set of valid markers for these data. MarkerFileOK=isfield(ds,'mrk'); if MarkerFileOK MarkerFileOK=~isempty(ds.mrk); end if MarkerFileOK % Are the markers appropriate? minMarkerTrial=[]; minMarkerTime=[]; maxMarkerTrial=[]; maxMarkerTime=[]; for k=1:length(ds.mrk) maxMarkerTrial=max([maxMarkerTrial max(ds.mrk(k).trial)]); maxMarkerTime=max([maxMarkerTime max(ds.mrk(k).time)]); minMarkerTrial=min([minMarkerTrial min(ds.mrk(k).trial)]); minMarkerTime=min([minMarkerTime min(ds.mrk(k).time)]); end if isempty(maxMarkerTrial) | isempty(maxMarkerTime) MarkerFileOK=0; % Do not create MarkerFile.mrk if all of the marker classes are empty. else MarkerFileOK=(maxMarkerTrial<=ds.res4.no_trials & minMarkerTrial>=1 & ... maxMarkerTime<=(ds.res4.no_samples/ds.res4.sample_rate) & ... minMarkerTime>=(-ds.res4.preTrigPts/ds.res4.sample_rate)); if ~MarkerFileOK fprintf(['\nwriteCTFds (checkMrk): ds.mrk cannot possibly be a set of markers ',... 'for array(data).\n']); fprintf([' minMarkerTrial=%d (must be >=1) ',... 'maxMarkerTrial=%d (must be <=%d)\n'],... minMarkerTrial,maxMarkerTrial,ds.res4.no_trials); fprintf([' minMarkerTime=%7.4f (must be >=%7.4f) ',... 'maxMarkerTrial=%7.4f (must be <=%7.4f )\n'],... minMarkerTime,-ds.res4.preTrigPts/ds.res4.sample_rate,... maxMarkerTime,ds.res4.no_samples/ds.res4.sample_rate); fprintf(' MarkerFile.mrk will not be created.\n\n'); end end end return %%%%%%%%%%%%%% end of checkMrk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function writeEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeEEG(eegFileName,EEG); % Reads the EEG file of a dtaset and stores the infoemation in strucure array EEG. % EEG(k).chanName = channel name in the dataset (EEGmmm where mmm=channel number) % EEG(k).name = channel name given by the user (e.g. Fp4) % EEG(k).pos = electrode position in cm in CTF head coordinates % Check inputs if exist('eegFileName')~=1;eegFileName=char([]);end if ~ischar(eegFileName) | isempty(eegFileName) fprintf('writeCTFds (writeEEG): Called writeEEG with bad file name.\n'); eegFileName EEG=struct([]); end if exist('EEG')~=1 EEG=struct([]); elseif ~isstruct(EEG) EEG=struct([]); end if isempty(EEG);return;end fid=fopen(eegFileName,'w','ieee-be'); if fid<0 fprintf('writeCTFds (writeEEG): Could not open file %s\n',eegFileName); return end nEEG=length(EEG); for k=1:nEEG fprintf(fid,'%d\t%s\t%7.5f\t%7.5f\t%7.5f\n',EEG(k).chanNum,EEG(k).name,EEG(k).pos); end fclose(fid); return %%%%%%%%% End of writeEEG %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Function writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeBadSegments(badSegmentsFile,badSegments,nTrial,tTrial); % Creates a bad.segements file in a CTF data set from the information in structure % badSegments which is created by read_badSegments, or by the user. % If structure badSegments is empty, then the file is not created. % badSegments structure: % badSegments.trial = List of trial numbers % badSegments.StartTime = List of bad segment start times (relative to trial). % badSegments.EndTime = List of bad segment end times. % Check badSegmentsFile if exist('badSegmentsFile')~=1;badSegmentsFile=char([]);end if isempty(badSegmentsFile) | ~ischar(badSegmentsFile) fprintf('writeCTFds(writeBadSegments): Bad file name.\n'); badSegmentsFile return end % Check that structure badSegments is defined correctly if exist('badSegments')~=1 | exist('nTrial')~=1 return elseif ~isstruct(badSegments) | isempty(badSegments) return elseif ~isfield(badSegments,'trial') | ~isfield(badSegments,'StartTime') | ... ~isfield(badSegments,'EndTime') return elseif isempty(badSegments.trial) | isempty(badSegments.StartTime) | ... isempty(badSegments.EndTime) return elseif ~isequal(size(badSegments.trial),size(badSegments.StartTime),... size(badSegments.EndTime)) fprintf(['\nwriteCTFds (writeBadSegments): ',... 'The fields of structure badSegments do not all have the same size.\n']); return elseif any(badSegments.trial>nTrial) | any(badSegments.trial<1) | ... any(badSegments.EndTime>tTrial) fprintf(['\nwriteCTFds (writeBadSegments): ds.badSegments cannot possibly describe ',... 'bad segments for these data.\n',... '\tmin(badSegments.trial)=%d max(badSegments.trial)=%d ',... 'max(badSegments.EndTime)=%0.4f s\n\t\tDataset: nTrial=%d tTrial=%0.4f s\n'],... min(badSegments.trial),max(badSegments.trial),max(badSegments.EndTime),... nTrial,tTrial); fprintf('\t\tbad.segments file will not be created.\n\n'); return end % Convert all fields to simple vectors nSeg=prod(size(badSegments.trial)); trial=reshape(badSegments.trial,1,nSeg); StartTime=reshape(badSegments.StartTime,1,nSeg); EndTime=reshape(badSegments.EndTime,1,nSeg); fid=fopen(badSegmentsFile,'w','ieee-be'); if fid<0 fprintf('writeCTFds (writeBadSegments): Could not open file %s\n',badSegmentsFile); return end % Extra tabs are inserted to reproduce the format of bad.segments files produced by % DataEditor (5.3.0-experimental-linux-20060918). fprintf(fid,'%0.6g\t\t%0.6g\t\t%0.6g\t\t\n',[trial;StartTime;EndTime]); fclose(fid); return %%%%%%%%% End of writeBadSegments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%Function check_cls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ClassFileOK=check_cls(ds); % Examines structure ds to see if a sensible ClassFile can be created from ds.TrialClass. ClassFileOK=isfield(ds,'TrialClass'); if ClassFileOK ClassFileOK=~isempty(ds.TrialClass); end if ClassFileOK % Are the class trials appropriate? minClassTrial=[]; maxClassTrial=[]; for k=1:length(ds.TrialClass) maxClassTrial=max([maxClassTrial max(ds.TrialClass(k).trial)]); minClassTrial=min([minClassTrial min(ds.TrialClass(k).trial)]); end % Create ClassFile.cls even when the trail classes are empty. if ~isempty(maxClassTrial) ClassFileOK=(maxClassTrial<=ds.res4.no_trials & minClassTrial>=1); if ~ClassFileOK fprintf(['\nwriteCTFds (check_cls): ds.TrialClass cannot possibly be a set of ',... 'trial classes for array(data).\n minClassTrial=%d (must be >=1) ',... 'maxClassTrial=%d (must be <=%d)\n'],... minClassTrial,maxClassTrial,ds.res4.no_trials); fprintf(' ClassFile.cls will not be created.\n'); end end end return %%%%%%%%%%%%%% end of check_cls %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% Function writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeClassFile(ClassFile,TrialClass); % Write the ClassFile of a CTF data set. % The CLassFile allows a user to store a list of trial classifications in a data set. % The ClassFile format is defined in document CTF MEG File Formats, PN900-0088. % This format is rigid. % Inputs : % ClassFile : marker file including the full path and extension .mrk. % TrialClass : Structure creted by read_ClassFile. % Output : ClassFile.cls. % Check input TrialClass. if exist('TrialClass')~=1;TrialClass=[];end if isempty(TrialClass) | ~isstruct(TrialClass) fprintf('writeCTFds (writeClassFile): TrialClass is empty or is not a structure.\n'); TrialClass return end % Check ClassFile if exist('ClassFile')~=1;ClassFile=char([]);end if isempty(ClassFile) | ~ischar(ClassFile) fprintf('writeCTFds (writeClassFile): Bad file name.\n'); ClassFile end fid=fopen(ClassFile,'w','ieee-be'); if fid<0 fprintf('writeCTFds (writeClassFile): Could not open file %s\n',ClassFile); return end nClass=length(TrialClass); % Generate datasetname from ClassFIle. ksep=max([0 strfind(ClassFile,filesep)]); datasetname=ClassFile(1:ksep-1); if isempty(datasetname);datasetname=cd;end fprintf(fid,'PATH OF DATASET:\n%s\n\n\n',datasetname); fprintf(fid,'NUMBER OF CLASSES:\n%d\n\n\n',nClass); for k=1:nClass if k==1 % Add sign character to make output match the output of Acq. sgn=char([]); % There should be no real significance to this. else % Why does DataEditor places the + sign only on ClassID 2,3,...? sgn='+'; end No_of_Trials=prod(size(TrialClass(k).trial)); fprintf(fid,'CLASSGROUPID:\n%s%d\nNAME:\n%s\nCOMMENT:\n%s\n',... sgn,TrialClass(k).ClassGroupId,TrialClass(k).Name,TrialClass(k).Comment); fprintf(fid,'COLOR:\n%s\nEDITABLE:\n%s\nCLASSID:\n%s%d\nNUMBER OF TRIALS:\n%d\n',... TrialClass(k).Color,TrialClass(k).Editable,sgn,TrialClass(k).ClassId,No_of_Trials); fprintf(fid,'LIST OF TRIALS:\nTRIAL NUMBER\n'); % Subtract one so trial numbering starts at 0 in ClassFile.cls fprintf(fid,'%20d\n',reshape(TrialClass(k).trial,1,No_of_Trials)-1); fprintf(fid,'\n\n'); end fclose(fid); return %%%%%%%%%%%%%% end of writeClassFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%% Function writeVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function writeVirtualChannels(VirtualChannelsFile,Virtual); % Writes a VirtualChannels file using the information in structure Virtual. % S\tructure Virtual is prepared by read_VirtualChannels % Check VirtualChannelsFile if exist('VirtualChannelsFile')~=1;VirtualChannelsFile=char([]);end if isempty(VirtualChannelsFile) | ~ischar(VirtualChannelsFile) fprintf('write_VirtualChannelsFile: Bad file name.\n'); VirtualChannelsFile return end % Check structure array Virtual if exist('Virtual')~=1 fprintf('writeVirtualChannels: Must specify structure Virtual.\n'); return elseif isempty(Virtual) | ~isstruct(Virtual) return elseif ~isfield(Virtual,'Name') | ~isfield(Virtual,'wt'); return elseif isempty(Virtual(1).Name) return end fid=fopen(VirtualChannelsFile,'w','ieee-be'); if fid<0 fprintf('writeCTFds (writeVirtualChannels): Could not open file %s\n',VirtualChannelsFile); return end fprintf(fid,'//Virtual channel configuration\n\n'); for k=1:length(Virtual) fprintf(fid,'VirtualChannel\n{\n\tName:\t%s\n\tUnit:\t%s\n',... Virtual(k).Name,Virtual(k).Unit); for q=1:size(Virtual(k).wt) % Floating format chosen to match VirtualChanels file creatd by % DataEditor (5.3.0-experimental-linux-20060918). fprintf(fid,'\tRef:\t%s,%0.6g\n',deblank(Virtual(k).chan(q,:)),Virtual(k).wt(q)); end fprintf(fid,'}\n\n'); end fclose(fid); return %%%%%%%%%%%%%% end of writeVirtualChannels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function updateDescriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ds=updateDescriptors(ds,comment,creatorSoftware,HLCcntrl); % Makes sure that certain tags are in structure infods, and makes sure that information % is transfered to infods and newds from res4. Updates several fields of res4 with % clinical use message (=comment) and name of creator program. % Inputs: ds : ds structure produced by readCTFds. % comment : Character string that is added to infods tags listed in addCommentTag % and res4 fields listed in addCommentField % creatorSoftware : Character string indicating that the data set was % created by writeCTFds. Added to infods tags listed in addCreatorTag and % appName field of res4. % HLCcntrl: If ds.infods is missing or empty, HLCcntrl determines the % _DATA_HZ_MODE tage of infods. if noit present or empty, HLCcntrl=0. % Creates a dummy infods structure if necessary using function make_dummy_infods. % Changes infods and newds to match information in % ds.res4.nf_run_title % ds.res4.collect_descriptor % ds.res4.nf_subject_id % ds.res4.nf_operator % Adds comment (clinical use message) and creator software name to infods, newds and hist files. if ~isfield(ds,'infods');ds.infods=[];end % infods tags that will display the comment. addCommentTag=strvcat('_PATIENT_ID','_PATIENT_INSTITUTE','_PROCEDURE_COMMENTS',... '_DATASET_COMMENTS','_DATASET_STATUS','_DATASET_PROCSTEPTITLE'); % res4 text fields that will display the comment addCommentField=strvcat('appName','dataOrigin','dataDescription',... 'nf_run_title','nf_subject_id','run_description'); % res4 text string lengths (from document "CTF MEG File Formats", PN900-0088) addCommentLength=[256 256 256 256 32 -1]'; % -1 indicates variable length % infods tags that will display the creator software. addCreatorTag=strvcat('_PROCEDURE_COMMENTS','_DATASET_STATUS',... '_DATASET_COLLECTIONSOFTWARE','_DATASET_CREATORSOFTWARE'); % res4 text fields that will display the creator software. addCreatorField=strvcat('appName','run_description'); addCreatorLength=[256 -1]'; % List of infods tags that will be set to ds.res4.fields (not necessarily fields listed in % addCommentField or addCreatorField addRes4Tag=strvcat('_PATIENT_ID','_DATASET_PROCSTEPTITLE',... '_DATASET_PROCSTEPDESCRIPTION','_DATASET_OPERATORNAME'); % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Add the Tags to infods. In most cases they will already be there, but just to be sure. addTag=strvcat(addRes4Tag,addCommentTag,addCreatorTag); tagClass=strvcat('_PATIENT','_PROCEDURE','_DATASET'); % List of all the tag names as a character array tagName=getArrayField(ds.infods,'name')'; if length(ds.infods)==1;tagName=tagName';end tagType=getArrayField(ds.infods,'type'); tagPtr=1; % If a class is missing, inject the class starting at tagPtr+1. for k=1:size(tagClass,1) addIndex=strmatch(deblank(tagClass(k,:)),addTag)'; % Are there any tags to be added in this class? if isempty(addIndex);continue;end % List of infods tags in the tagClass, but excluding the CPerist type (which marks the % start of a class. infodsIndex=strmatch(deblank(tagClass(k,:)),tagName); if isempty(infodsIndex) % Create a new class of tags. if strcmp(deblank(tagName(tagPtr+1,:)),'EndOfParameters') & k>1; tagPtr=tagPtr+1; end nTag=length(ds.infods); tagName((tagPtr+4):(nTag+3),:)=tagName((tagPtr+1):nTag,:); ds.infods((tagPtr+4):(nTag+3))=ds.infods((tagPtr+1):nTag); ds.infods(tagPtr+1)=struct('name',[deblank(tagClass(k,:)),'_INFO'],'type',2,'data',[]); ds.infods(tagPtr+2)=struct('name','WS1_','type',0,'data',[]); ds.infods(tagPtr+3)=struct('name','EndOfParameters','type',-1,'data',[]); tagName=strvcat(tagName(1:tagPtr,:),... strvcat([deblank(tagClass(k,:)),'_INFO'],'WS1_','EndOfParameters'),... tagName(tagPtr+1:nTag,:)); nTag=nTag+3; tagPtr=tagPtr+2; else if ds.infods(max(infodsIndex)).type==2 tagPtr=max(infodsIndex)+1; % Class consists of no tags beyond the CPersist definition else tagPtr=max(infodsIndex); % Class contains at least one real tag. end clear infodsIndex; end for q=addIndex if isempty(strmatch(deblank(addTag(q,:)),tagName)) tagName=strvcat(tagName(1:tagPtr,:),deblank(addTag(q,:)),tagName(tagPtr+1:nTag,:)); ds.infods((tagPtr+2):(nTag+1))=ds.infods((tagPtr+1):nTag); ds.infods(tagPtr+1)=struct('name',deblank(addTag(q,:)),'type',10,'data',char([])); tagPtr=tagPtr+1; nTag=nTag+1; end end end clear k q nTag tagPtr infodsIndex addIndex; % All of the tags in addTag have been added to ds.infods. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if exist('creatorSoftware')~=1; creatorSoftware=char([]); elseif ~ischar(creatorSoftware) creatorSoftware=char([]); else creatorSoftware=deblank(creatorSoftware); end if exist('comment')~=1; comment=char([]); elseif ~ischar(comment) comment=char([]); else comment=deblank(comment); end tagName=getArrayField(ds.infods,'name')'; % Update the res4 fields : add creator message. % Don't check field length, but truncate later. for q=1:size(addCreatorField,1); strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:)))); if isempty(strfind(strng,creatorSoftware)) newStrng=creatorSoftware; if ~isempty(strng);newStrng=[strng ' ' newStrng];end ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),newStrng); end end clear q strng nChar strng0 ns; % Update the res4 fields : add comment (= clinical use message) % Don't check field length, but truncate later. for q=1:size(addCommentField,1); strng=deblank(getfield(ds.res4,deblank(addCommentField(q,:)))); if isempty(strfind(strng,comment)) newStrng=comment; if ~isempty(strng);newStrng=[strng ' ' newStrng];end ds.res4=setfield(ds.res4,deblank(addCommentField(q,:)),newStrng); end end clear strng newStrng q; % Update res4.run_description ds.res4.run_description=[ds.res4.run_description,char(0)]; ds.res4.rdlen=length(ds.res4.run_description); % Update infods entries from .res4 fields ds.infods(strmatch('_PATIENT_ID',tagName)).data=deblank(ds.res4.nf_subject_id); ds.infods(strmatch('_DATASET_PROCSTEPTITLE',tagName)).data=deblank(ds.res4.nf_run_title); ds.infods(strmatch('_DATASET_PROCSTEPDESCRIPTION',tagName)).data=... deblank(ds.res4.nf_collect_descriptor); ds.infods(strmatch('_DATASET_OPERATORNAME',tagName)).data=deblank(ds.res4.nf_operator); % Truncate the .res4. fields. Leave room for a final char(0). for q=1:size(addCreatorField,1); strng=deblank(getfield(ds.res4,deblank(addCreatorField(q,:)))); if length(strng)>addCreatorLength(q)-1 & addCreatorLength(q)>0 ds.res4=setfield(ds.res4,deblank(addCreatorField(q,:)),... strng(length(strng)+[-addCreatorLength(q)+2:0])); end end for q=1:size(addCommentField,1); strng=deblank(getfield(ds.res4,deblank(addCommentField(q,:)))); if length(strng)>addCommentLength(q)-1 & addCommentLength(q)>0 ds.res4=setfield(ds.res4,deblank(addCommentField(q,:)),... strng(length(strng)+[-addCommentLength(q)+2:0])); end end clear q strng; % Add creator software to infods tags. Have already cheked that the tags are there. for q=1:size(addCreatorTag,1) if isempty(strmatch(deblank(addCreatorTag(q,:)),addRes4Tag)) k=strmatch(deblank(addCreatorTag(q,:)),tagName); if length(k)==1 if isempty(strfind(ds.infods(k).data,creatorSoftware)) newStrng=creatorSoftware; if ~isempty(deblank(ds.infods(k).data)); newStrng=[deblank(ds.infods(k).data) ' ' newStrng]; end ds.infods(k).data=newStrng; end else fprintf('writeCTFds: Tag %s appears %d times in ds.infods ??\n',... deblank(addCreatorTag(q,:)),length(k)); end end end clear q k; % Add comment (clinical use statement) to ds.infods for q=1:size(addCommentTag,1) if isempty(strmatch(deblank(addCommentTag(q,:)),addRes4Tag)) k=strmatch(deblank(addCommentTag(q,:)),tagName); if length(k)==1 if isempty(strfind(ds.infods(k).data,comment)) newStrng=comment; if ~isempty(deblank(ds.infods(k).data)); newStrng=[deblank(ds.infods(k).data) ' ' newStrng]; end ds.infods(k).data=newStrng; end else fprintf(['writeCTFds (updateDescriptors): Tag %s appears %d times in ',... 'ds.infods ??\n'],deblank(addCommentTag(q,:)),length(k)); end end end clear q k; % Add the creator and comment information to the newds file if isfield(ds,'newds'); nChar=length(ds.newds); % Keyword positions aNpos=max(strfind(ds.newds,[char(9) 'appName:' char(9)])); if isempty(aNpos) fprintf(['writeCTFds (update_decsriptors): Keyword ''appName'' ',... 'does not appear in ds.newds.\n',... ' set ds.newds=[].\n']); ds.newds=char([]); else eol=max([11 min(strfind(ds.newds(aNpos+1:length(ds.newds)),char(10)))]); ds.newds=[ds.newds(1:(aNpos+eol-1)) ' ' creatorSoftware ' ' comment ... ds.newds((aNpos+eol):length(ds.newds))]; end clear nChar aNpos eol; end % Add clinical use message to hist file. if isfield(ds,'hist') & ~isempty(comment) ds.hist=[ds.hist char(10) comment char(10)]; end return %%%%%%%%%%%%%% End of updateDescriptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [infods,status]=updateHLC(infods,HLCdata); % Adds notes and continuous-head-localization tags to .infods file % Inputs : infods : Structure of tags to be written to output infods file. % HLCdata : 0 or [] or not defined - There are no HLC channels % (head-coil position) in the data. Just pass the existing tags to % the output dataset. % HLCdata : real array : size(HLCdata)=[samplesPerTrial 3 Ncoil nTrial] % Calculate the head motion tags. % Outputs : status : 0: Everything looks OK % 1: Couldn't find _DATASET tags. % <0: There is a problem with the new infods file. % Calls: % - getArrayField: Extracts field names from structure array S. % Defaults for the head localization tags. % Might do this better with a structure. HZ_MODE_UNKNOWN=2^31-1; % Bug in DataEditor and acquisition software, Oct. 2006 % Should be -1. % New dataset tags for HLC specification. addTag=strvcat('_DATASET_HZ_MODE',... '_DATASET_MOTIONTOLERANCE',... '_DATASET_MAXHEADMOTION',... '_DATASET_MAXHEADMOTIONTRIAL',... '_DATASET_MAXHEADMOTIONCOIL'); addTagType=[5 4 4 7 10]'; % Check HLCdata array. HLCdata=[] indicates no continuous head localization. if ~exist('HLCdata')==1 HLCdata=[]; elseif ~isempty(HLCdata) [samplesPerTrial nDim Ncoil nTrial]=size(HLCdata); if nDim~=3; fprintf('writeCTFds (updateHLC): size(HLCdata)=[');fprintf(' %d',size(HLCdata)); fprintf(']\n'); fprintf(' nDim=%d?? Setting HLCdata=[].\n',nDim); HLCdata=[]; end end % Assume that all the tag names are different. There is no checking when a tag listed in % addTag matches more than one entry in array name. name=getArrayField(infods,'name')'; %size(name)=[nTag lengthTag] DATASET_tags=strmatch('_DATASET',name)'; % size(DATASET_tags)=[1 nTag] if isempty(DATASET_tags) status=1; % No _DATASET tags. Don't add anything. else status=0; if isempty(HLCdata) TagValue(1)=HZ_MODE_UNKNOWN; TextTagValue=char(0); addTag=addTag(1,:); % Remove the other HLC tags addTagType=addTagType(1); else % ~isempty(HLCdata) % Remove HLC offsets. HLCoffset=squeeze(HLCdata(1,:,:,1)); for q=1:Ncoil for k=1:3 HLCdata(:,k,q,:)=HLCdata(:,k,q,:)-HLCoffset(k,q); end end % Calculate motions as displacement from the start of the dataset. absMotion=squeeze(sqrt(sum(HLCdata.^2,2))); %size(absMotion)=[samplesPerTrial Ncoil nTrial] maxCoilMotion=squeeze(max(absMotion,[],1)); % size(maxCoilMovement)=[Ncoil nTrial] maxHeadMotion=max(max(maxCoilMotion)); [mx maxHeadMotionCoil]=max(max(maxCoilMotion,[],2)); [mx maxHeadMotionTrial]=max(max(maxCoilMotion,[],1)); % Create a list of head motion tag values TagValue(1)=5; % Indicates continuous head localization TagValue(2)=max(2*maxHeadMotion,0.02); % _DATASET_MOTIONTOLERANCE TagValue(3)=maxHeadMotion; % _DATASET_MAXHEADMOTION % Subtract 1 from the trial so trial numbering starts at 0. TagValue(4)=maxHeadMotionTrial-1; % _DATASET_MAXHEADMOTIONTRIAL TextTagValue=char(zeros(4,1)); % Placeholder since tags1:4 are numerical % _MAXHEADMOTIONCOIL value TextTagValue=strvcat(TextTagValue,sprintf('%d',maxHeadMotionCoil)); TagValue=[TagValue 0]; % Placeholder only since the 5th tag is a text string. end % Add or insert tags. for q=1:size(addTag,1) nTag=length(infods); tagName=deblank(addTag(q,:)); TagNo=strmatch(tagName,name,'exact')'; if isempty(TagNo) % Insert a tag at the end of the _DATASET tags. TagNo=max(DATASET_tags)+1; infods((TagNo+1):(nTag+1))=infods(TagNo:nTag); name=strvcat(name(1:TagNo-1,:),tagName,name(TagNo:nTag,:)); DATASET_tags=[DATASET_tags TagNo]; end if addTagType(q)~=10 infods(TagNo)=struct('name',tagName,'type',addTagType(q),'data',TagValue(q)); else infods(TagNo)=struct('name',tagName,'type',addTagType(q),... 'data',deblank(TextTagValue(q,:))); end end % End loop over head position and head motion tags. clear q TagNo TextTagValue TagValue; end % End section add _DATASET tags return %%%%%%%%%%%%%% End of updateHLC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function updateBandwidth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ds=updateBandwidth(ds,fhp,flp); % Updates the bandwidth fields of infods and newds. % 3 possible dources of bandwidth: % 1. fhp,flp inputs (default) % 2. newds fiels % 3. res4.filter % 4. infods field % Almost always, fhp,flp will have the default values, but it could be defined in the % fields of ds, so check. Result: lots of code to achieve a simple result. % read fhp,flp from newds (if it exists) if isfield(ds,'newds') BWpos=max(strfind(ds.newds,[char(9) 'bandwidth:' char(9)])); % Keyword position if isempty(BWpos) fprintf(['writeCTFds (updateBandwidth): Keyword ''bandwidth:''',... 'does not appear in ds.newds.\n',... ' Field newds removed from structure ds.\n']); ds=rmfield(ds,'newds'); else % Get the bandwidth parameters from ds.newds. eol=max([13 min(strfind(ds.newds(BWpos+1:length(ds.newds)),char(10)))]); buff=sscanf(ds.newds((BWpos+13):(BWpos+eol)),'%f%c%f'); fhp=max(fhp,buff(1)); flp=min(flp,buff(3)); end clear eol buff BWpos; end % Get fhp, flp from res4. if ~isempty(ds.res4.filters) for kq=1:ds.res4.num_filters freq=ds.res4.filters(kq).freq; if ds.res4.filters(kq).fType==1; flp=min(flp,freq); elseif ds.res4.filters(kq).fType==2; fhp=max(fhp,freq); end end clear kq freq; end % Get fhp, flp from ds.infods if isfield(ds,'infods') name=getArrayField(ds.infods,'name')'; TagNo=strmatch('_DATASET_LOWERBANDWIDTH',name,'exact'); if ~isempty(TagNo);fhp=max(fhp,ds.infods(TagNo).data);end TagNo=strmatch('_DATASET_UPPERBANDWIDTH',name,'exact'); if ~isempty(TagNo);flp=min(flp,ds.infods(TagNo).data);end end % Now have fhp,flp. Update hist. Add all the res4 filters. if ~isempty(ds.res4.filters) if ~isfield(ds,'hist');hist=char([]);end ds.hist=[ds.hist 'Filters specified in res4 file :' char(10)]; for kq=1:ds.res4.num_filters freq=ds.res4.filters(kq).freq; if ds.res4.filters(kq).fType==1; ds.hist=[ds.hist ... num2str(kq,'%8d') ' Lowpass ' num2str(freq,'%6.2f') ' Hz' char(10)]; elseif ds.res4.filters(kq).fType==2; ds.hist=[ds.hist ... num2str(kq,'%8d') ' Highpass ' num2str(freq,'%6.2f') ' Hz' char(10)]; elseif ds.res4.filters(kq).fType==3; ds.hist=[ds.hist num2str(kq,'%8d') ' Notch ' num2str(freq,'%6.2f') ... ' Hz width=' num2str(ds.res4.filters(kq).Param,'%6.2f') ' Hz' char(10)]; else ds.hist=[ds.hist ' fType=',num2str(ds.res4.filters(kq).fType,'%d') char(10)]; end end ds.hist=[ds.hist ,... 'Bandwidth: ',num2str(fhp,'%0.3g'),' - ',num2str(flp,'%0.3g'),' Hz',char(10)]; clear kq freq; end % Update newds bandwidth if isfield(ds,'newds') BWpos=max(strfind(ds.newds,[char(9) 'bandwidth:' char(9)])); eol=max([12 min(strfind(ds.newds(BWpos+1:length(ds.newds)),char(10)))]); ds.newds=[ds.newds(1:BWpos+11) num2str(fhp,'%0.6f') ', ' num2str(flp,'%0.6f') ... ds.newds((BWpos+eol):length(ds.newds))]; clear BWpos eol; end % Update infods bandwidth tags. Lots of coding becasue it's possible that infods does % not already have bandwidth tags. name=getArrayField(ds.infods,'name')'; DATASET_tags=strmatch('_DATASET_',name); if ~isempty(DATASET_tags) addTag=strvcat('_DATASET_LOWERBANDWIDTH','_DATASET_UPPERBANDWIDTH'); TagValue=[fhp flp]; % Add or update tags. for q=1:size(addTag,1) nTag=length(ds.infods); TagNo=strmatch(deblank(addTag(q,:)),name,'exact')'; if isempty(TagNo) % Insert a tag at the end of the _DATASET tags. TagNo=max(DATASET_tags)+1; ds.infods((TagNo+1):(nTag+1))=ds.infods(TagNo:nTag); ds.infods(TagNo)=struct('name',deblank(addTag(q,:)),'type',4,'data',TagValue(q)); name=strvcat(name(1:TagNo-1,:),deblank(addTag(q,:)),name(TagNo:nTag,:)); DATASET_tags=[DATASET_tags TagNo]; else ds.infods(TagNo).data=TagValue(q); % Tag exists. Just update the value. end end % End loop over head position and head motion tags. clear q nTag DATASET_tags; else fprintf(['writeCTFds (updateBandwidth): Found no _DATASET tags in infods.\n'... '\t\t\tDid not add bandwidth tags.\n']); end return %%%%%%%%%%%%%% End of updateBandwidth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%% Function updateDateTime %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ds=updateDateTime(ds); % Update the dat/time fields of res4 and and infods datetime=floor(clock); if isfield(ds,'infods'); name=getArrayField(ds.infods,'name')'; DATASET_tags=strmatch('_DATASET_',name); if ~isempty(DATASET_tags) addTag=strvcat('_DATASET_CREATORDATETIME','_DATASET_LASTMODIFIEDDATETIME'); tagData=sprintf('%d%2.2d%2.2d%2.2d%2.2d%2.2d',datetime); tagType=10; for q=1:size(addTag,1) nTag=length(ds.infods); TagNo=strmatch(deblank(addTag(q,:)),name,'exact')'; if isempty(TagNo) % Insert a tag at the end of the _DATASET tags. TagNo=max(DATASET_tags)+1; ds.infods((TagNo+1):(nTag+1))=ds.infods(TagNo:nTag); name=strvcat(name(1:TagNo-1,:),deblank(addTag(q,:)),name(TagNo:nTag,:)); DATASET_tags=[DATASET_tags TagNo]; end ds.infods(TagNo)=struct('name',deblank(addTag(q,:)),'type',tagType,'data',tagData); end clear nTag TagNo name DATASET_tags addTag tagData tagType; else fprintf('writeCTFds (updateDateTime): Cannot find any _DATASET tags in ds.infods.\n'); end % End loop over head position and head motion tags. else fprintf('writeCTFds (updateDateTime): Cannot find ds.infods.\n'); end ds.res4.data_date=sprintf('%4d/%2.2d/%2.2d',datetime(1:3)); ds.res4.data_time=sprintf('%2.2d:%2.2d:%2.2d',datetime(4:6)); return %%%%%%%%%%%%%% End of updateDateTime %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% Function getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x=getArrayField(S,yfield) % Extracts one field of a structure array. % Inputs: S : structure array. % yfield: name of field of S (string) % Output: x. x(:,n)=S(n).yfield; size(x)=[size(yfield) length(S)] % Field sizes: Two options: % 1. size(S(n).yfield) is the same for all n. Any size allowed. % 2. S(n).yfield is a 2-D array for all structure elements S(n). % Then yfield of different array elements S(n) can have different sizes. % The array returned will be large enough to accomodate all of the data. sizeS=size(S); nS=prod(sizeS); S=reshape(S,1,nS); % Determine which array-size option to use. sizey=size(getfield(S,{1},yfield)); option1=1; option2=(length(sizey)==2); for n=2:nS sizeyn=size(getfield(S,{n},yfield)); option1=option1 & isequal(sizey,sizeyn); option2=option2 & length(sizeyn)==2; if option2 sizey=max([sizey;sizeyn],[],1); end end if option1 % All fields have the same size nY=prod(sizey); if isnumeric(getfield(S,{1},yfield)) x=zeros(nY,nS); elseif ischar(getfield(S,{1},yfield)) x=char(zeros(nY,nS)); end for n=1:nS x(:,n)=reshape(getfield(S,{n},yfield),nY,1); end x=reshape(x,[sizey nS]); elseif option2 % All fields have only two dimensions if isnumeric(getfield(S,{1},yfield)) x=zeros([sizey nS]); elseif ischar(getfield(S,{1},yfield)) x=char(zeros([sizey nS])); end for n=1:nS y=getfield(S,{n},yfield); sizeyn=size(y); x(1:sizeyn(1),1:sizeyn(2),n)=y; end else fprintf(['getArrayField: Field %s of the structure array has >2 dimensions ',... 'and not all field have the same size.\n'],yfield); x=[]; end x=squeeze(x); return %%%%%%%% End of getArrayField %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%