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 | philippboehmsturm/antx-master | read_itab_mhd.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_itab_mhd.m | 12,499 | utf_8 | 3f00166bb7197b9d65c619cfe0ac954d | function mhd = read_itab_mhd(filename)
fid = fopen(filename, 'rb');
% Name of structure
mhd.stname = fread(fid, [1 10], 'uint8=>char'); % Header identifier (VP_BIOMAG)
mhd.stver = fread(fid, [1 8], 'uint8=>char'); % Header version
mhd.stendian = fread(fid, [1 4], 'uint8=>char'); % LE (little endian) or BE (big endian) format
% Subject's INFOs
mhd.first_name = fread(fid, [1 32], 'uint8=>char'); % Subject's first name
mhd.last_name = fread(fid, [1 32], 'uint8=>char'); % Subject's family name
mhd.id = fread(fid, [1 32], 'uint8=>char'); % Subject's id
mhd.notes = fread(fid, [1 256], 'uint8=>char'); % Notes on measurement
% Other subj infos
mhd.subj_info.sex = fread(fid, [1 1], 'uint8=>char'); % Sex (M or F)
pad = fread(fid, [1 5], 'uint8');
mhd.subj_info.notes = fread(fid, [1 256], 'uint8=>char'); % Notes on subject
mhd.subj_info.height = fread(fid, [1 1], 'float'); % Height in cm
mhd.subj_info.weight = fread(fid, [1 1], 'float'); % Weight in kg
mhd.subj_info.birthday = fread(fid, [1 1], 'int32'); % Birtday (1-31)
mhd.subj_info.birthmonth = fread(fid, [1 1], 'int32'); % Birthmonth (1-12)
mhd.subj_info.birthyear = fread(fid, [1 1], 'int32'); % Birthyear (1900-2002)
% Data acquisition INFOs
mhd.time = fread(fid, [1 12], 'uint8=>char'); % time (ascii)
mhd.date = fread(fid, [1 16], 'uint8=>char'); % date (ascii)
mhd.nchan = fread(fid, [1 1], 'int32'); % total number of channels
mhd.nelech = fread(fid, [1 1], 'int32'); % number of electric channels
mhd.nelerefch = fread(fid, [1 1], 'int32'); % number of electric reference channels
mhd.nmagch = fread(fid, [1 1], 'int32'); % number of magnetic channels
mhd.nmagrefch = fread(fid, [1 1], 'int32'); % number of magnetic reference channels
mhd.nauxch = fread(fid, [1 1], 'int32'); % number of auxiliary channels
mhd.nparamch = fread(fid, [1 1], 'int32'); % number of parameter channels
mhd.ndigitch = fread(fid, [1 1], 'int32'); % number of digit channels
mhd.nflagch = fread(fid, [1 1], 'int32'); % number of flag channels
mhd.data_type = fread(fid, [1 1], 'int32'); % 0 - BE_SHORT (HP-PA, big endian)
% 1 - BE_LONG (HP-PA, big endian)
% 2 - BE_FLOAT (HP-PA, big endian)
% 3 - LE_SHORT (Intel, little endian)
% 4 - LE_LONG (Intel, little endian)
% 5 - LE_FLOAT (Intel, little endian)
% 6 - RTE_A_SHORT (HP-A900, big endian)
% 7 - RTE_A_FLOAT (HP-A900, big endian)
% 8 - ASCII
mhd.smpfq = fread(fid, [1 1], 'single'); % sampling frequency in Hz
mhd.hw_low_fr = fread(fid, [1 1], 'single'); % hw data acquisition low pass filter
mhd.hw_hig_fr = fread(fid, [1 1], 'single'); % hw data acquisition high pass filter
mhd.hw_comb = fread(fid, [1 1], 'int32'); % hw data acquisition 50 Hz filter (1-TRUE)
mhd.sw_hig_tc = fread(fid, [1 1], 'single'); % sw data acquisition high pass time constant
mhd.compensation= fread(fid, [1 1], 'int32'); % 0 - no compensation 1 - compensation
mhd.ntpdata = fread(fid, [1 1], 'int32'); % total number of time points in data
mhd.no_segments = fread(fid, [1 1], 'int32'); % Number of segments described in the segment structure
% INFOs on different segments
for i=1:5
mhd.sgmt(i).start = fread(fid, [1 1], 'int32'); % Starting time point from beginning of data
mhd.sgmt(i).ntptot = fread(fid, [1 1], 'int32'); % Total number of time points
mhd.sgmt(i).type = fread(fid, [1 1], 'int32');
mhd.sgmt(i).no_samples = fread(fid, [1 1], 'int32');
mhd.sgmt(i).st_sample = fread(fid, [1 1], 'int32');
end
mhd.nsmpl = fread(fid, [1 1], 'int32'); % Overall number of samples
% INFOs on different samples
for i=1:4096
mhd.smpl(i).start = fread(fid, [1 1], 'int32'); % Starting time point from beginning of data
mhd.smpl(i).ntptot = fread(fid, [1 1], 'int32'); % Total number of time points
mhd.smpl(i).ntppre = fread(fid, [1 1], 'int32'); % Number of points in pretrigger
mhd.smpl(i).type = fread(fid, [1 1], 'int32');
mhd.smpl(i).quality = fread(fid, [1 1], 'int32');
end
mhd.nrefchan = fread(fid, [1 1], 'int32'); % number of reference channels
mhd.ref_ch = fread(fid, [1 640], 'int32'); % reference channel list
mhd.ntpref = fread(fid, [1 1], 'int32'); % total number of time points in reference
% Header INFOs
mhd.raw_header_type = fread(fid, [1 1], 'int32'); % 0 - Unknown header
% 2 - rawfile (A900)
% 3 - GE runfile header
% 31 - ATB runfile header version 1.0
% 41 - IFN runfile header version 1.0
% 51 - BMDSys runfile header version 1.0
mhd.header_type = fread(fid, [1 1], 'int32'); % 0 - Unknown header
% 2 - rawfile (A900)
% 3 - GE runfile header
% 4 - old header
% 10 - 256ch normal header
% 11 - 256ch master header
% 20 - 640ch normal header
% 21 - 640ch master header
% 31 - ATB runfile header version 1.0
% 41 - IFN runfile header version 1.0
% 51 - BMDSys runfile header version 1.0
mhd.conf_file = fread(fid, [1 64], 'uint8=>char'); % Filename used for data acquisition configuration
mhd.header_size = fread(fid, [1 1], 'int32'); % sizeof(header) at the time of file creation
mhd.start_reference = fread(fid, [1 1], 'int32'); % start reference
mhd.start_data = fread(fid, [1 1], 'int32'); % start data
mhd.rawfile = fread(fid, [1 1], 'int32'); % 0 - not a rawfile 1 - rawfile
mhd.multiplexed_data = fread(fid, [1 1], 'int32'); % 0 - FALSE 1 - TRUE
mhd.isns = fread(fid, [1 1], 'int32'); % sensor code 1 - Single channel
% 28 - Original Rome 28 ch.
% 29 - ..............
% .. - ..............
% 45 - Updated Rome 28 ch. (spring 2009)
% .. - ..............
% .. - ..............
% 55 - Original Chieti 55 ch. flat
% 153 - Original Chieti 153 ch. helmet
% 154 - Chieti 153 ch. helmet from Jan 2002
% Channel's INFOs
for i=1:640
mhd.ch(i).type = fread(fid, [1 1], 'uint8');
pad = fread(fid, [1 3], 'uint8');
% type 0 - unknown
% 1 - ele
% 2 - mag
% 4 - ele ref
% 8 - mag ref
% 16 - aux
% 32 - param
% 64 - digit
% 128 - flag
mhd.ch(i).number = fread(fid, [1 1], 'int32'); % number
mhd.ch(i).label = fixstr(fread(fid, [1 16], 'uint8=>char')); % label
mhd.ch(i).flag = fread(fid, [1 1], 'uint8');
pad = fread(fid, [1 3], 'uint8');
% on/off flag 0 - working channel
% 1 - noisy channel
% 2 - very noisy channel
% 3 - broken channel
mhd.ch(i).amvbit = fread(fid, [1 1], 'float'); % calibration from LSB to mV
mhd.ch(i).calib = fread(fid, [1 1], 'float'); % calibration from mV to unit
mhd.ch(i).unit = fread(fid, [1 6], 'uint8=>char'); % unit label (fT, uV, ...)
pad = fread(fid, [1 2], 'uint8');
mhd.ch(i).ncoils = fread(fid, [1 1], 'int32'); % number of coils building up one channel
mhd.ch(i).wgt = fread(fid, [1 10], 'float'); % weight of coils
% position and orientation of coils
for j=1:10
mhd.ch(i).position(j).r_s = fread(fid, [1 3], 'float');
mhd.ch(i).position(j).u_s = fread(fid, [1 3], 'float');
end
end
% Sensor position INFOs
mhd.r_center = fread(fid, [1 3], 'float'); % sensor position in convenient format
mhd.u_center = fread(fid, [1 3], 'float');
mhd.th_center = fread(fid, [1 1], 'float'); % sensor orientation as from markers fit
mhd.fi_center= fread(fid, [1 1], 'float');
mhd.rotation_angle= fread(fid, [1 1], 'float');
mhd.cosdir = fread(fid, [3 3], 'float'); % for compatibility only
mhd.irefsys = fread(fid, [1 1], 'int32'); % reference system 0 - sensor reference system
% 1 - Polhemus
% 2 - head3
% 3 - MEG
% Marker positions for MRI integration
mhd.num_markers = fread(fid, [1 1], 'int32'); % Total number of markers
mhd.i_coil = fread(fid, [1 64], 'int32'); % Markers to be used to find sensor position
mhd.marker = fread(fid, [3 64], 'int32'); % Position of all the markers
mhd.best_chi = fread(fid, [1 1], 'float'); % Best chi_square value obtained in finding sensor position
mhd.cup_vertex_center = fread(fid, [1 1], 'float'); % dist anc sensor cente vertex (as entered
% from keyboard)
mhd.cup_fi_center = fread(fid, [1 1], 'float'); % fi angle of sensor center
mhd.cup_rotation_angle = fread(fid, [1 1], 'float'); % rotation angle of sensor center axis
mhd.dist_a1_a2 = fread(fid, [1 1], 'float'); % head informations
% (used to find subject's head dimensions)
mhd.dist_inion_nasion = fread(fid, [1 1], 'float');
mhd.max_circ = fread(fid, [1 1], 'float');
mhd.nasion_vertex_inion = fread(fid, [1 1], 'float');
% Data analysis INFOs
mhd.security = fread(fid, [1 1], 'int32'); % security flag
mhd.ave_alignement = fread(fid, [1 1], 'int32'); % average data alignement 0 - FALSE
% 1 - TRUE
mhd.itri = fread(fid, [1 1], 'int32'); % trigger channel number
mhd.ntpch = fread(fid, [1 1], 'int32'); % no. of time points per channel
mhd.ntppre = fread(fid, [1 1], 'int32'); % no. of time points of pretrigger
mhd.navrg = fread(fid, [1 1], 'int32'); % no. of averages
mhd.nover = fread(fid, [1 1], 'int32'); % no. of discarded averages
mhd.nave_filt = fread(fid, [1 1], 'int32'); % no. of applied filters
% Filters used before average
for i=1:15
mhd.ave_filt(i).type = fread(fid, [1 1], 'int32'); % type 0 - no filter
% 1 - bandpass - param[0]: highpass freq
% - param[1]: lowpass freq
% 2 - notch - param[0]: notch freq 1
% param[1]: notch freq 2
% param[2]: notch freq 3
% param[3]: notch freq 4
% param[4]: span
% 3 - artifact - param[0]: True/False
% 4 - adaptive - param[0]: True/False
% 5 - rectifier - param[0]: True/False
% 6 - heart - param[0]: True/False
% 7 - evoked - param[0]: True/False
% 8 - derivate - param[0]: True/False
% 9 - polarity - param[0]: True/False
mhd.ave_filt(i).param = fread(fid, [1 5], 'float'); % up to 5 filter parameters
end
mhd.stdev = fread(fid, [1 1], 'int32'); % 0 - not present
mhd.bas_start = fread(fid, [1 1], 'int32'); % starting data points for baseline
mhd.bas_end = fread(fid, [1 1], 'int32'); % ending data points for baseline
mhd.source_files = fread(fid, [1 32], 'int32'); % Progressive number of files (if more than one)
% template INFOs
mhd.ichtpl = fread(fid, [1 1], 'int32');
mhd.ntptpl = fread(fid, [1 1], 'int32');
mhd.ifitpl = fread(fid, [1 1], 'int32');
mhd.corlim = fread(fid, [1 1], 'float');
% Filters used before template
for i=1:15
mhd.tpl_filt(i).type = fread(fid, [1 1], 'int32'); % type 0 - no filter
% 1 - bandpass - param[0]: highpass freq
% - param[1]: lowpass freq
% 2 - notch - param[0]: notch freq 1
% param[1]: notch freq 2
% param[2]: notch freq 3
% param[3]: notch freq 4
% param[4]: span
% 3 - artifact - param[0]: True/False
% 4 - adaptive - param[0]: True/False
% 5 - rectifier - param[0]: True/False
% 6 - heart - param[0]: True/False
% 7 - evoked - param[0]: True/False
% 8 - derivate - param[0]: True/False
% 9 - polarity - param[0]: True/False
mhd.tpl_filt(i).param = fread(fid, [1 5], 'float'); % up to 5 filter parameters
end
% Just in case info
mhd.dummy = fread(fid, [1 64], 'int32');
% there seems to be more dummy data at the end...
fclose(fid);
function str = fixstr(str)
sel = find(str==0, 1, 'first');
if ~isempty(sel)
str = str(1:sel-1);
end
|
github | philippboehmsturm/antx-master | read_plexon_plx.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_plexon_plx.m | 19,999 | utf_8 | a7f91dc40ee54cdc3e4a2c14330bed5e | function [varargout] = read_plexon_plx(filename, varargin)
% READ_PLEXON_PLX reads header or data from a Plexon *.plx file, which
% is a file containing action-potential (spike) timestamps and waveforms
% (spike channels), event timestamps (event channels), and continuous
% variable data (continuous A/D channels).
%
% Use as
% [hdr] = read_plexon_plx(filename)
% [dat] = read_plexon_plx(filename, ...)
% [dat1, dat2, dat3, hdr] = read_plexon_plx(filename, ...)
%
% Optional input arguments should be specified in key-value pairs
% 'header' = structure with header information
% 'memmap' = 0 or 1
% 'feedback' = 0 or 1
% 'ChannelIndex' = number, or list of numbers (that will result in multiple outputs)
% 'SlowChannelIndex' = number, or list of numbers (that will result in multiple outputs)
% Copyright (C) 2007, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: read_plexon_plx.m 2528 2011-01-05 14:12:08Z eelspa $
% parse the optional input arguments
hdr = keyval('header', varargin);
memmap = keyval('memmap', varargin);
feedback = keyval('feedback', varargin);
ChannelIndex = keyval('ChannelIndex', varargin);
SlowChannelIndex = keyval('SlowChannelIndex', varargin);
EventIndex = keyval('EventIndex', varargin); % not yet used
% set the defaults
if isempty(memmap)
memmap=0;
end
if isempty(feedback)
feedback=1;
end
needhdr = isempty(hdr);
% start with empty return values
varargout = {};
% the datafile is little endian, hence it may be neccessary to swap bytes in
% the memory mapped data stream depending on the CPU type of this computer
if littleendian
swapFcn = @(x) x;
else
swapFcn = @(x) swapbytes(x);
end
% read header info from file, use Matlabs for automatic byte-ordering
fid = fopen(filename, 'r', 'ieee-le');
fseek(fid, 0, 'eof');
siz = ftell(fid);
fseek(fid, 0, 'bof');
if needhdr
if feedback, fprintf('reading header from %s\n', filename); end
% a PLX file consists of a file header, channel headers, and data blocks
hdr = PL_FileHeader(fid);
for i=1:hdr.NumDSPChannels
hdr.ChannelHeader(i) = PL_ChannelHeader(fid);
end
for i=1:hdr.NumEventChannels
hdr.EventHeader(i) = PL_EventHeader(fid);
end
for i=1:hdr.NumSlowChannels
hdr.SlowChannelHeader(i) = PL_SlowChannelHeader(fid);
end
hdr.DataOffset = ftell(fid);
if memmap
% open the file as meory mapped object, note that byte swapping may be needed
mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16');
end
dum = struct(...
'Type', [],...
'UpperByteOf5ByteTimestamp', [],...
'TimeStamp', [],...
'Channel', [],...
'Unit', [],...
'NumberOfWaveforms', [],...
'NumberOfWordsInWaveform', [] ...
);
% read the header of each data block and remember its data offset in bytes
Nblocks = 0;
offset = hdr.DataOffset; % only used when reading from memmapped file
hdr.DataBlockOffset = [];
hdr.DataBlockHeader = dum;
while offset<siz
if Nblocks>=length(hdr.DataBlockOffset);
% allocate another 1000 elements, this prevents continuous reallocation
hdr.DataBlockOffset(Nblocks+10000) = 0;
hdr.DataBlockHeader(Nblocks+10000) = dum;
if feedback, fprintf('reading DataBlockHeader %4.1f%%\n', 100*(offset-hdr.DataOffset)/(siz-hdr.DataOffset)); end
end
Nblocks = Nblocks+1;
if memmap
% get the header information from the memory mapped file
hdr.DataBlockOffset(Nblocks) = offset;
hdr.DataBlockHeader(Nblocks) = PL_DataBlockHeader(mm, offset-hdr.DataOffset, swapFcn);
% skip the header (16 bytes) and the data (int16 words)
offset = offset + 16 + 2 * double(hdr.DataBlockHeader(Nblocks).NumberOfWordsInWaveform * hdr.DataBlockHeader(Nblocks).NumberOfWaveforms);
else
% read the header information from the file the traditional way
hdr.DataBlockOffset(Nblocks) = offset;
hdr.DataBlockHeader(Nblocks) = PL_DataBlockHeader(fid, [], swapFcn);
fseek(fid, 2 * double(hdr.DataBlockHeader(Nblocks).NumberOfWordsInWaveform * hdr.DataBlockHeader(Nblocks).NumberOfWaveforms), 'cof'); % data consists of short integers
offset = ftell(fid);
end % if memmap
end
% this prints the final 100%
if feedback, fprintf('reading DataBlockHeader %4.1f%%\n', 100*(offset-hdr.DataOffset)/(siz-hdr.DataOffset)); end
% remove the allocated space that was not needed
hdr.DataBlockOffset = hdr.DataBlockOffset(1:Nblocks);
hdr.DataBlockHeader = hdr.DataBlockHeader(1:Nblocks);
end % if needhdr
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the spike channel data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(ChannelIndex)
if feedback, fprintf('reading spike data from %s\n', filename); end
if memmap
% open the file as meory mapped object, note that byte swapping may be needed
mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16');
end
type = [hdr.DataBlockHeader.Type];
chan = [hdr.DataBlockHeader.Channel];
ts = [hdr.DataBlockHeader.TimeStamp];
for i=1:length(ChannelIndex)
% determine the data blocks with continuous data belonging to this channel
sel = (type==1 & chan==hdr.ChannelHeader(ChannelIndex(i)).Channel);
sel = find(sel);
if isempty(sel)
warning('spike channel %d contains no data', ChannelIndex(i));
varargin{end+1} = [];
continue;
end
% the number of samples can potentially be different in each block
num = double([hdr.DataBlockHeader(sel).NumberOfWordsInWaveform]) .* double([hdr.DataBlockHeader(sel).NumberOfWaveforms]);
% check whether the number of samples per block makes sense
if any(num~=num(1))
error('spike channel blocks with diffent number of samples');
end
% allocate memory to hold the data
buf = zeros(num(1), length(sel), 'int16');
if memmap
% get the header information from the memory mapped file
datbeg = double(hdr.DataBlockOffset(sel) - hdr.DataOffset)/2 + 8 + 1; % expressed in 2-byte words, minus the file header, skip the 16 byte block header
datend = datbeg + num - 1;
for j=1:length(sel)
buf(:,j) = mm.Data(datbeg(j):datend(j));
end
% optionally swap the bytes to correct for the endianness
buf = swapFcn(buf);
else
% read the data from the file in the traditional way
offset = double(hdr.DataBlockOffset(sel)) + 16; % expressed in bytes, skip the 16 byte block header
for j=1:length(sel)
fseek(fid, offset(j), 'bof');
buf(:,j) = fread(fid, num(j), 'int16');
end
end % if memmap
% remember the data for this channel
varargout{i} = buf;
end %for ChannelIndex
end % if ChannelIndex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the continuous channel data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(SlowChannelIndex)
if feedback, fprintf('reading continuous data from %s\n', filename); end
dat = {};
if memmap
% open the file as meory mapped object, note that byte swapping may be needed
mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16');
end
type = [hdr.DataBlockHeader.Type];
chan = [hdr.DataBlockHeader.Channel];
ts = [hdr.DataBlockHeader.TimeStamp];
for i=1:length(SlowChannelIndex)
% determine the data blocks with continuous data belonging to this channel
sel = (type==5 & chan==hdr.SlowChannelHeader(SlowChannelIndex(i)).Channel);
sel = find(sel);
if isempty(sel)
error(sprintf('Continuous channel %d contains no data', SlowChannelIndex(i)));
% warning('Continuous channel %d contains no data', SlowChannelIndex(i));
% varargin{end+1} = [];
% continue;
end
% the number of samples can be different in each block
num = double([hdr.DataBlockHeader(sel).NumberOfWordsInWaveform]) .* double([hdr.DataBlockHeader(sel).NumberOfWaveforms]);
cumnum = cumsum([0 num]);
% allocate memory to hold the data
buf = zeros(1, cumnum(end), 'int16');
if memmap
% get the header information from the memory mapped file
datbeg = double(hdr.DataBlockOffset(sel) - hdr.DataOffset)/2 + 8 + 1; % expressed in 2-byte words, minus the file header, skip the 16 byte block header
datend = datbeg + num - 1;
for j=1:length(sel)
bufbeg = cumnum(j)+1;
bufend = cumnum(j+1);
% copy the data from the memory mapped file into the continuous buffer
buf(bufbeg:bufend) = mm.Data(datbeg(j):datend(j));
end
% optionally swap the bytes to correct for the endianness
buf = swapFcn(buf);
else
% read the data from the file in the traditional way
offset = double(hdr.DataBlockOffset(sel)) + 16; % expressed in bytes, skip the 16 byte block header
for j=1:length(sel)
bufbeg = cumnum(j)+1;
bufend = cumnum(j+1);
% copy the data from the file into the continuous buffer
fseek(fid, offset(j), 'bof');
buf(bufbeg:bufend) = fread(fid, num(j), 'int16');
end
end % if memmap
% remember the data for this channel
varargout{i} = buf;
end %for SlowChannelIndex
end % if SlowChannelIndex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the event channel data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(EventIndex)
type = [hdr.DataBlockHeader.Type];
chan = [hdr.DataBlockHeader.Channel];
ts = [hdr.DataBlockHeader.TimeStamp];
for i=1:length(EventIndex)
% determine the data blocks with continuous data belonging to this channel
sel = (type==0 & chan==hdr.EventHeader(EventIndex(i)).Channel);
sel = find(sel);
if isempty(sel)
warning('event channel %d contains no data', EventIndex(i));
varargin{end+1} = [];
continue;
end
% this still has to be implemented
keyboard
end % for EventIndex
end % if EventIndex
fclose(fid);
% always return the header as last
varargout{end+1} = hdr;
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTIONS for reading the different header elements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = PL_FileHeader(fid)
hdr.MagicNumber = fread(fid, 1, 'uint32=>uint32'); % = 0x58454c50;
hdr.Version = fread(fid, 1, 'int32' ); % Version of the data format; determines which data items are valid
hdr.Comment = fread(fid, [1 128], 'uint8=>char' ); % User-supplied comment
hdr.ADFrequency = fread(fid, 1, 'int32' ); % Timestamp frequency in hertz
hdr.NumDSPChannels = fread(fid, 1, 'int32' ); % Number of DSP channel headers in the file
hdr.NumEventChannels = fread(fid, 1, 'int32' ); % Number of Event channel headers in the file
hdr.NumSlowChannels = fread(fid, 1, 'int32' ); % Number of A/D channel headers in the file
hdr.NumPointsWave = fread(fid, 1, 'int32' ); % Number of data points in waveform
hdr.NumPointsPreThr = fread(fid, 1, 'int32' ); % Number of data points before crossing the threshold
hdr.Year = fread(fid, 1, 'int32' ); % Time/date when the data was acquired
hdr.Month = fread(fid, 1, 'int32' );
hdr.Day = fread(fid, 1, 'int32' );
hdr.Hour = fread(fid, 1, 'int32' );
hdr.Minute = fread(fid, 1, 'int32' );
hdr.Second = fread(fid, 1, 'int32' );
hdr.FastRead = fread(fid, 1, 'int32' ); % reserved
hdr.WaveformFreq = fread(fid, 1, 'int32' ); % waveform sampling rate; ADFrequency above is timestamp freq
hdr.LastTimestamp = fread(fid, 1, 'double'); % duration of the experimental session, in ticks
% The following 6 items are only valid if Version >= 103
hdr.Trodalness = fread(fid, 1, 'char' ); % 1 for single, 2 for stereotrode, 4 for tetrode
hdr.DataTrodalness = fread(fid, 1, 'char' ); % trodalness of the data representation
hdr.BitsPerSpikeSample = fread(fid, 1, 'char' ); % ADC resolution for spike waveforms in bits (usually 12)
hdr.BitsPerSlowSample = fread(fid, 1, 'char' ); % ADC resolution for slow-channel data in bits (usually 12)
hdr.SpikeMaxMagnitudeMV = fread(fid, 1, 'uint16'); % the zero-to-peak voltage in mV for spike waveform adc values (usually 3000)
hdr.SlowMaxMagnitudeMV = fread(fid, 1, 'uint16'); % the zero-to-peak voltage in mV for slow-channel waveform adc values (usually 5000); Only valid if Version >= 105 (usually either 1000 or 500)
% The following item is only valid if Version >= 105
hdr.SpikePreAmpGain = fread(fid, 1, 'uint16'); % so that this part of the header is 256 bytes
hdr.Padding = fread(fid, 46, 'char' ); % so that this part of the header is 256 bytes
% Counters for the number of timestamps and waveforms in each channel and unit.
% Note that these only record the counts for the first 4 units in each channel.
% channel numbers are 1-based - array entry at [0] is unused
hdr.TSCounts = fread(fid, [5 130], 'int32' ); % number of timestamps[channel][unit]
hdr.WFCounts = fread(fid, [5 130], 'int32' ); % number of waveforms[channel][unit]
% Starting at index 300, the next array also records the number of samples for the
% continuous channels. Note that since EVCounts has only 512 entries, continuous
% channels above channel 211 do not have sample counts.
hdr.EVCounts = fread(fid, 512, 'int32' ); % number of timestamps[event_number]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = PL_ChannelHeader(fid)
hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % Name given to the DSP channel
hdr.SIGName = fread(fid, [1 32], 'uint8=>char' ); % Name given to the corresponding SIG channel
hdr.Channel = fread(fid, 1, 'int32' ); % DSP channel number, 1-based
hdr.WFRate = fread(fid, 1, 'int32' ); % When MAP is doing waveform rate limiting, this is limit w/f per sec divided by 10
hdr.SIG = fread(fid, 1, 'int32' ); % SIG channel associated with this DSP channel 1 - based
hdr.Ref = fread(fid, 1, 'int32' ); % SIG channel used as a Reference signal, 1- based
hdr.Gain = fread(fid, 1, 'int32' ); % actual gain divided by SpikePreAmpGain. For pre version 105, actual gain divided by 1000.
hdr.Filter = fread(fid, 1, 'int32' ); % 0 or 1
hdr.Threshold = fread(fid, 1, 'int32' ); % Threshold for spike detection in a/d values
hdr.Method = fread(fid, 1, 'int32' ); % Method used for sorting units, 1 - boxes, 2 - templates
hdr.NUnits = fread(fid, 1, 'int32' ); % number of sorted units
hdr.Template = fread(fid, [64 5], 'int16' ); % Templates used for template sorting, in a/d values
hdr.Fit = fread(fid, 5, 'int32' ); % Template fit
hdr.SortWidth = fread(fid, 1, 'int32' ); % how many points to use in template sorting (template only)
hdr.Boxes = reshape(fread(fid, 4*2*5, 'int16' ), [4 2 5]); % the boxes used in boxes sorting
hdr.SortBeg = fread(fid, 1, 'int32' ); % beginning of the sorting window to use in template sorting (width defined by SortWidth)
hdr.Comment = fread(fid, [1 128], 'uint8=>char' );
hdr.Padding = fread(fid, 11, 'int32' );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = PL_EventHeader(fid)
hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % name given to this event
hdr.Channel = fread(fid, 1, 'int32' ); % event number, 1-based
hdr.Comment = fread(fid, [1 128], 'uint8=>char' );
hdr.Padding = fread(fid, 33, 'int32' );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = PL_SlowChannelHeader(fid)
hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % name given to this channel
hdr.Channel = fread(fid, 1, 'int32' ); % channel number, 0-based
hdr.ADFreq = fread(fid, 1, 'int32' ); % digitization frequency
hdr.Gain = fread(fid, 1, 'int32' ); % gain at the adc card
hdr.Enabled = fread(fid, 1, 'int32' ); % whether this channel is enabled for taking data, 0 or 1
hdr.PreAmpGain = fread(fid, 1, 'int32' ); % gain at the preamp
% As of Version 104, this indicates the spike channel (PL_ChannelHeader.Channel) of
% a spike channel corresponding to this continuous data channel.
% <=0 means no associated spike channel.
hdr.SpikeChannel = fread(fid, 1, 'int32' );
hdr.Comment = fread(fid, [1 128], 'uint8=>char' );
hdr.Padding = fread(fid, 28, 'int32' );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = PL_DataBlockHeader(fid, offset, swapFcn)
% % this is the conventional code, it has been replaced by code that works
% % with both regular and memmapped files
% hdr.Type = fread(fid, 1, 'int16=>int16' ); % Data type; 1=spike, 4=Event, 5=continuous
% hdr.UpperByteOf5ByteTimestamp = fread(fid, 1, 'uint16=>uint16' ); % Upper 8 bits of the 40 bit timestamp
% hdr.TimeStamp = fread(fid, 1, 'uint32=>uint32' ); % Lower 32 bits of the 40 bit timestamp
% hdr.Channel = fread(fid, 1, 'int16=>int16' ); % Channel number
% hdr.Unit = fread(fid, 1, 'int16=>int16' ); % Sorted unit number; 0=unsorted
% hdr.NumberOfWaveforms = fread(fid, 1, 'int16=>int16' ); % Number of waveforms in the data to folow, usually 0 or 1
% hdr.NumberOfWordsInWaveform = fread(fid, 1, 'int16=>int16' ); % Number of samples per waveform in the data to follow
if isa(fid, 'memmapfile')
mm = fid;
datbeg = offset/2 + 1; % the offset is in bytes (minus the file header), the memory mapped file is indexed in int16 words
datend = offset/2 + 8;
buf = mm.Data(datbeg:datend);
else
buf = fread(fid, 8, 'int16=>int16');
end
hdr.Type = swapFcn(buf(1));
hdr.UpperByteOf5ByteTimestamp = swapFcn(uint16(buf(2)));
hdr.TimeStamp = swapFcn(typecast(buf([3 4]), 'uint32'));
hdr.Channel = swapFcn(buf(5));
hdr.Unit = swapFcn(buf(6));
hdr.NumberOfWaveforms = swapFcn(buf(7));
hdr.NumberOfWordsInWaveform = swapFcn(buf(8));
|
github | philippboehmsturm/antx-master | read_eeglabevent.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_eeglabevent.m | 3,854 | utf_8 | 965c1662da2a0ca88263a3b4da4f7de7 | % read_eeglabevent() - import EEGLAB dataset events
%
% Usage:
% >> event = read_eeglabevent(filename, ...);
%
% Inputs:
% filename - [string] file name
%
% Optional inputs:
% 'header' - FILEIO structure header
%
% Outputs:
% event - FILEIO toolbox event structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2008-
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function event = read_eeglabevent(filename, varargin)
if nargin < 1
help read_eeglabheader;
return;
end;
hdr = keyval('header', varargin);
if isempty(hdr)
hdr = read_eeglabheader(filename);
end;
event = []; % these will be the output in FieldTrip format
oldevent = hdr.orig.event; % these are in EEGLAB format
missingFieldFlag=false;
if ~isfield(oldevent,'code') && ~isfield(oldevent,'value')
disp('Warning: No ''value'' field in the events structure.');
missingFieldFlag=true;
end;
if ~isfield(oldevent,'type')
disp('Warning: No ''type'' field in the events structure.');
missingFieldFlag=true;
end;
if missingFieldFlag
disp('EEGlab data files should have both a ''value'' field');
disp('to denote the generic type of event, as in ''trigger'', and a ''type'' field');
disp('to denote the nature of this generic event, as in the condition of the experiment.');
disp('Note also that this is the reverse of the FieldTrip convention.');
end;
for index = 1:length(oldevent)
if isfield(oldevent,'code')
type = oldevent(index).code;
elseif isfield(oldevent,'value')
type = oldevent(index).value;
else
type = 'trigger';
end;
% events can have a numeric or a string value
if isfield(oldevent,'type')
value = oldevent(index).type;
else
value = 'default';
end;
% this is the sample number of the concatenated data to which the event corresponds
sample = oldevent(index).latency;
% a non-zero offset only applies to trial-events, i.e. in case the data is
% segmented and each data segment needs to be represented as event. In
% that case the offset corresponds to the baseline duration (times -1).
offset = 0;
if isfield(oldevent, 'duration')
duration = oldevent(index).duration;
else
duration = 0;
end;
% add the current event in fieldtrip format
event(index).type = type; % this is usually a string, e.g. 'trigger' or 'trial'
event(index).value = value; % in case of a trigger, this is the value
event(index).sample = sample; % this is the sample in the datafile at which the event happens
event(index).offset = offset; % some events should be represented with a shifted time-axix, e.g. a trial with a baseline period
event(index).duration = duration; % some events have a duration, such as a trial
end;
if hdr.nTrials>1
% add the trials to the event structure
for i=1:hdr.nTrials
event(end+1).type = 'trial';
event(end ).sample = (i-1)*hdr.nSamples + 1;
event(end ).value = [];
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
end
end
|
github | philippboehmsturm/antx-master | read_bti_ascii.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_bti_ascii.m | 2,300 | utf_8 | 143e0b87252e8d5050bd771d895e0daf | function [file] = read_bti_ascii(filename);
% READ_BTI_ASCII reads general data from a BTI configuration file
%
% The file should be formatted like
% Group:
% item1 : value1a value1b value1c
% item2 : value2a value2b value2c
% item3 : value3a value3b value3c
% item4 : value4a value4b value4c
%
% Copyright (C) 2004, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: read_bti_ascii.m 945 2010-04-21 17:41:20Z roboos $
fid = fopen(filename, 'r');
if fid==-1
error(sprintf('could not open file %s', filename));
end
line = '';
while ischar(line)
line = cleanline(fgetl(fid))
if isempty(line) | line==-1 | isempty(findstr(line, ':'))
continue
end
% the line is not empty, which means that we have encountered a chunck of information
if findstr(line, ':')~=length(line)
[item, value] = strtok(line, ':');
value(1) = ' '; % remove the :
value = strtrim(value);
item = strtrim(item);
item(findstr(item, '.')) = '_';
item(findstr(item, ' ')) = '_';
if ischar(item)
eval(sprintf('file.%s = ''%s'';', item, value));
else
eval(sprintf('file.%s = %s;', item, value));
end
else
subline = cleanline(fgetl(fid));
error, the rest has not been implemented (yet)
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function line = cleanline(line)
if isempty(line) | line==-1
return
end
comment = findstr(line, '//');
if ~isempty(comment)
line(min(comment):end) = ' ';
end
line = strtrim(line);
|
github | philippboehmsturm/antx-master | openbdf.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/openbdf.m | 6,812 | utf_8 | cb49358a2a955b165a5c50127c25e3d8 | % openbdf() - Opens an BDF File (European Data Format for Biosignals) in MATLAB (R)
%
% Usage:
% >> EDF=openedf(FILENAME)
%
% Note: About EDF -> www.biosemi.com/faq/file_format.htm
%
% Author: Alois Schloegl, 5.Nov.1998
%
% See also: readedf()
% Copyright (C) 1997-1998 by Alois Schloegl
% [email protected]
% Ver 2.20 18.Aug.1998
% Ver 2.21 10.Oct.1998
% Ver 2.30 5.Nov.1998
%
% For use under Octave define the following function
% function s=upper(s); s=toupper(s); end;
% V2.12 Warning for missing Header information
% V2.20 EDF.AS.* changed
% V2.30 EDF.T0 made Y2K compatible until Year 2090
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
% Name changed for bdf files Sept 6,2002 T.S. Lorig
% Header updated for EEGLAB format (update web link too) - Arnaud Delorme 14 Oct 2002
function [DAT,H1]=openbdf(FILENAME)
SLASH='/'; % defines Seperator for Subdirectories
BSLASH=char(92);
cname=computer;
if cname(1:2)=='PC' SLASH=BSLASH; end;
fid=fopen(FILENAME,'r','ieee-le');
if fid<0
fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']);
return;
end;
EDF.FILE.FID=fid;
EDF.FILE.OPEN = 1;
EDF.FileName = FILENAME;
PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]);
SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]);
EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME));
EDF.FILE.Name = FILENAME(SPos+1:PPos-1);
if SPos==0
EDF.FILE.Path = pwd;
else
EDF.FILE.Path = FILENAME(1:SPos-1);
end;
EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext];
H1=char(fread(EDF.FILE.FID,256,'char')'); %
EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer
%if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end;
EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification
EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification
%EDF.H.StartDate = H1(169:176); % 8 Byte
%EDF.H.StartTime = H1(177:184); % 8 Byte
EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ];
% Y2K compatibility until year 2090
if EDF.VERSION(1)=='0'
if EDF.T0(1) < 91
EDF.T0(1)=2000+EDF.T0(1);
else
EDF.T0(1)=1900+EDF.T0(1);
end;
else ;
% in a future version, this is hopefully not needed
end;
EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header
% reserved = H1(193:236); % 44 Byte
EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records
EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec
EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals
EDF.Label = char(fread(EDF.FILE.FID,[16,EDF.NS],'char')');
EDF.Transducer = char(fread(EDF.FILE.FID,[80,EDF.NS],'char')');
EDF.PhysDim = char(fread(EDF.FILE.FID,[8,EDF.NS],'char')');
EDF.PhysMin= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'));
EDF.PhysMax= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'));
EDF.DigMin = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); %
EDF.DigMax = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); %
% check validity of DigMin and DigMax
if (length(EDF.DigMin) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n');
EDF.DigMin = -(2^15)*ones(EDF.NS,1);
end
if (length(EDF.DigMax) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n');
EDF.DigMax = (2^15-1)*ones(EDF.NS,1);
end
if (any(EDF.DigMin >= EDF.DigMax))
fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n');
end
% check validity of PhysMin and PhysMax
if (length(EDF.PhysMin) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n');
EDF.PhysMin = EDF.DigMin;
end
if (length(EDF.PhysMax) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n');
EDF.PhysMax = EDF.DigMax;
end
if (any(EDF.PhysMin >= EDF.PhysMax))
fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n');
EDF.PhysMin = EDF.DigMin;
EDF.PhysMax = EDF.DigMax;
end
EDF.PreFilt= char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); %
tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record
EDF.SPR = str2num(char(tmp)); % samples per data record
fseek(EDF.FILE.FID,32*EDF.NS,0);
EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./ ...
(EDF.DigMax-EDF.DigMin);
EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin;
tmp = find(EDF.Cal < 0);
EDF.Cal(tmp) = ones(size(tmp));
EDF.Off(tmp) = zeros(size(tmp));
EDF.Calib=[EDF.Off';(diag(EDF.Cal))];
%EDF.Calib=sparse(diag([1; EDF.Cal]));
%EDF.Calib(1,2:EDF.NS+1)=EDF.Off';
EDF.SampleRate = EDF.SPR / EDF.Dur;
EDF.FILE.POS = ftell(EDF.FILE.FID);
if EDF.NRec == -1 % unknown record size, determine correct NRec
fseek(EDF.FILE.FID, 0, 'eof');
endpos = ftell(EDF.FILE.FID);
EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2));
fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof');
H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records
end;
EDF.Chan_Select=(EDF.SPR==max(EDF.SPR));
for k=1:EDF.NS
if EDF.Chan_Select(k)
EDF.ChanTyp(k)='N';
else
EDF.ChanTyp(k)=' ';
end;
if findstr(upper(EDF.Label(k,:)),'ECG')
EDF.ChanTyp(k)='C';
elseif findstr(upper(EDF.Label(k,:)),'EKG')
EDF.ChanTyp(k)='C';
elseif findstr(upper(EDF.Label(k,:)),'EEG')
EDF.ChanTyp(k)='E';
elseif findstr(upper(EDF.Label(k,:)),'EOG')
EDF.ChanTyp(k)='O';
elseif findstr(upper(EDF.Label(k,:)),'EMG')
EDF.ChanTyp(k)='M';
end;
end;
EDF.AS.spb = sum(EDF.SPR); % Samples per Block
bi=[0;cumsum(EDF.SPR)];
idx=[];idx2=[];
for k=1:EDF.NS,
idx2=[idx2, (k-1)*max(EDF.SPR)+(1:EDF.SPR(k))];
end;
maxspr=max(EDF.SPR);
idx3=zeros(EDF.NS*maxspr,1);
for k=1:EDF.NS, idx3(maxspr*(k-1)+(1:maxspr))=bi(k)+ceil((1:maxspr)'/maxspr*EDF.SPR(k));end;
%EDF.AS.bi=bi;
EDF.AS.IDX2=idx2;
%EDF.AS.IDX3=idx3;
DAT.Head=EDF;
DAT.MX.ReRef=1;
%DAT.MX=feval('loadxcm',EDF);
return;
|
github | philippboehmsturm/antx-master | trialfun_general.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/trialfun/trialfun_general.m | 12,185 | utf_8 | dc7d6636a396f740e2ebe37b69175ce7 | function [trl, event] = trialfun_general(cfg)
% TRIALFUN_GENERAL determines trials/segments in the data that are
% interesting for analysis, using the general event structure returned
% by read_event. This function is independent of the dataformat
%
% The trialdef structure can contain the following specifications
% cfg.trialdef.eventtype = 'string'
% cfg.trialdef.eventvalue = number, string or list with numbers or strings
% cfg.trialdef.prestim = latency in seconds (optional)
% cfg.trialdef.poststim = latency in seconds (optional)
%
% If you want to read all data from a continous file in segments, you can specify
% cfg.trialdef.triallength = duration in seconds (can be Inf)
% cfg.trialdef.ntrials = number of trials
%
% If you specify
% cfg.trialdef.eventtype = '?'
% a list with the events in your datafile will be displayed on screen.
%
% See also FT_DEFINETRIAL, FT_PREPROCESSING
% Copyright (C) 2005-2008, Robert Oostenveld
%
% Subversion does not use the Log keyword, use 'svn log <filename>' or 'svn -v log | less' to get detailled information
% some events do not require the specification a type, pre or poststim period
% in that case it is more convenient not to have them, instead of making them empty
if isfield(cfg.trialdef, 'eventvalue') && isempty(cfg.trialdef.eventvalue ), cfg.trialdef = rmfield(cfg.trialdef, 'eventvalue' ); end
if isfield(cfg.trialdef, 'prestim') && isempty(cfg.trialdef.prestim ), cfg.trialdef = rmfield(cfg.trialdef, 'prestim' ); end
if isfield(cfg.trialdef, 'poststim') && isempty(cfg.trialdef.poststim ), cfg.trialdef = rmfield(cfg.trialdef, 'poststim' ); end
if isfield(cfg.trialdef, 'triallength') && isempty(cfg.trialdef.triallength ), cfg.trialdef = rmfield(cfg.trialdef, 'triallength'); end
if isfield(cfg.trialdef, 'ntrials') && isempty(cfg.trialdef.ntrials ), cfg.trialdef = rmfield(cfg.trialdef, 'ntrials' ); end
if isfield(cfg.trialdef, 'triallength')
% reading all segments from a continuous fie is incompatible with any other option
try, cfg.trialdef = rmfield(cfg.trialdef, 'eventvalue'); end
try, cfg.trialdef = rmfield(cfg.trialdef, 'prestim' ); end
try, cfg.trialdef = rmfield(cfg.trialdef, 'poststim' ); end
if ~isfield(cfg.trialdef, 'ntrials')
if isinf(cfg.trialdef.triallength)
cfg.trialdef.ntrials = 1;
else
cfg.trialdef.ntrials = inf;
end
end
end
% default rejection parameter
if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end
if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end
if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end
% read the header, contains the sampling frequency
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat);
% read the events
if isfield(cfg, 'event')
fprintf('using the events from the configuration structure\n');
event = cfg.event;
else
try
fprintf('reading the events from ''%s''\n', cfg.headerfile);
event = ft_read_event(cfg.headerfile, 'headerformat', cfg.headerformat, 'eventformat', cfg.eventformat, 'dataformat', cfg.dataformat);
catch
event = [];
end
end
% for the following, the trials do not depend on the events in the data
if isfield(cfg.trialdef, 'triallength')
if isinf(cfg.trialdef.triallength)
% make one long trial with the complete continuous data in it
trl = [1 hdr.nSamples*hdr.nTrials 0];
elseif isinf(cfg.trialdef.ntrials)
% cut the continous data into as many segments as possible
nsamples = round(cfg.trialdef.triallength*hdr.Fs);
trlbeg = 1:nsamples:(hdr.nSamples*hdr.nTrials - nsamples + 1);
trlend = trlbeg + nsamples - 1;
offset = zeros(size(trlbeg));
trl = [trlbeg(:) trlend(:) offset(:)];
else
% make the pre-specified number of trials
nsamples = round(cfg.trialdef.triallength*hdr.Fs);
trlbeg = (0:(cfg.trialdef.ntrials-1))*nsamples + 1;
trlend = trlbeg + nsamples - 1;
offset = zeros(size(trlbeg));
trl = [trlbeg(:) trlend(:) offset(:)];
end
return
end
sel = [];
trl = [];
val = [];
if strcmp(cfg.trialdef.eventtype, '?')
% no trials should be added, show event information using subfunction and exit
show_event(event);
return
end
if strcmp(cfg.trialdef.eventtype, 'gui') || (isfield(cfg.trialdef, 'eventvalue') && length(cfg.trialdef.eventvalue)==1 && strcmp(cfg.trialdef.eventvalue, 'gui'))
cfg.trialdef = select_event(event, cfg.trialdef);
usegui = 1;
else
usegui = 0;
end
if ~isfield(cfg.trialdef, 'eventvalue')
cfg.trialdef.eventvalue = [];
elseif ischar(cfg.trialdef.eventvalue)
% convert single string into cell-array, otherwise the intersection does not work as intended
cfg.trialdef.eventvalue = {cfg.trialdef.eventvalue};
end
% select all events of the specified type and with the specified value
if ~isempty(cfg.trialdef.eventtype)
sel = ismember({event.type}, cfg.trialdef.eventtype);
else
sel = true(size(event));
end
if ~isempty(cfg.trialdef.eventvalue)
% this cannot be done robustly in a single line of code
if ~iscell(cfg.trialdef.eventvalue)
valchar = ischar(cfg.trialdef.eventvalue);
valnumeric = isnumeric(cfg.trialdef.eventvalue);
else
valchar = ischar(cfg.trialdef.eventvalue{1});
valnumeric = isnumeric(cfg.trialdef.eventvalue{1});
end
for i=1:numel(event)
if (ischar(event(i).value) && valchar) || (isnumeric(event(i).value) && valnumeric)
sel(i) = sel(i) & ~isempty(intersect(event(i).value, cfg.trialdef.eventvalue));
end
end
end
% convert from boolean vector into a list of indices
sel = find(sel);
if usegui
% Checks whether offset and duration are defined for all the selected
% events and/or prestim/poststim are defined in trialdef.
if (any(cellfun('isempty', {event(sel).offset})) || ...
any(cellfun('isempty', {event(sel).duration}))) && ...
~(isfield(cfg.trialdef, 'prestim') && isfield(cfg.trialdef, 'poststim'))
% If at least some of offset/duration values and prestim/poststim
% values are missing tries to ask the user for prestim/poststim
answer = inputdlg({'Prestimulus latency (sec)','Poststimulus latency (sec)'}, 'Enter borders');
if isempty(answer) || any(cellfun('isempty', answer))
error('The information in the data and cfg is insufficient to define trials.');
else
cfg.trialdef.prestim=str2double(answer{1});
cfg.trialdef.poststim=str2double(answer{2});
if isnan(cfg.trialdef.prestim) || isnan(cfg.trialdef.poststim)
error('Illegal input for trial borders');
end
end
end % if specification is not complete
end % if usegui
for i=sel
% catch empty fields in the event table and interpret them meaningfully
if isempty(event(i).offset)
% time axis has no offset relative to the event
event(i).offset = 0;
end
if isempty(event(i).duration)
% the event does not specify a duration
event(i).duration = 0;
end
% determine where the trial starts with respect to the event
if ~isfield(cfg.trialdef, 'prestim')
trloff = event(i).offset;
trlbeg = event(i).sample;
else
% override the offset of the event
trloff = round(-cfg.trialdef.prestim*hdr.Fs);
% also shift the begin sample with the specified amount
trlbeg = event(i).sample + trloff;
end
% determine the number of samples that has to be read (excluding the begin sample)
if ~isfield(cfg.trialdef, 'poststim')
trldur = max(event(i).duration - 1, 0);
else
% this will not work if prestim was not defined, the code will then crash
trldur = round((cfg.trialdef.poststim+cfg.trialdef.prestim)*hdr.Fs) - 1;
end
trlend = trlbeg + trldur;
% add the beginsample, endsample and offset of this trial to the list
% if all samples are in the dataset
if trlbeg>0 && trlend<=hdr.nSamples.*hdr.nTrials,
trl = [trl; [trlbeg trlend trloff]];
if isnumeric(event(i).value),
val = [val; event(i).value];
else
val = [val; nan];
end
end
end
% append the vector with values
if ~isempty(val) && ~all(isnan(val))
trl = [trl val];
end
if usegui
% This complicated line just computes the trigger times in seconds and
% converts them to a cell array of strings to use in the GUI
eventstrings = cellfun(@num2str, mat2cell((trl(:, 1)- trl(:, 3))./hdr.Fs , ones(1, size(trl, 1))), 'UniformOutput', 0);
% Let us start with handling at least the completely unsegmented case
% semi-automatically. The more complicated cases are better left
% to the user.
if hdr.nTrials==1
selected = find(trl(:,1)>0 & trl(:,2)<=hdr.nSamples);
else
selected = find(trl(:,1)>0);
end
indx = select_channel_list(eventstrings, selected , 'Select events');
trl=trl(indx, :);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that shows event table
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function show_event(event)
if isempty(event)
fprintf('no events were found in the datafile\n');
return
end
eventtype = unique({event.type});
Neventtype = length(eventtype);
if Neventtype==0
fprintf('no events were found in the datafile\n');
else
fprintf('the following events were found in the datafile\n');
for i=1:Neventtype
sel = find(strcmp(eventtype{i}, {event.type}));
try
eventvalue = unique({event(sel).value}); % cell-array with string value
eventvalue = sprintf('''%s'' ', eventvalue{:}); % translate into a single string
catch
eventvalue = unique(cell2mat({event(sel).value})); % array with numeric values or empty
eventvalue = num2str(eventvalue); % translate into a single string
end
fprintf('event type: ''%s'' ', eventtype{i});
fprintf('with event values: %s', eventvalue);
fprintf('\n');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that allows the user to select an event using gui
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function trialdef=select_event(event, trialdef)
if isempty(event)
fprintf('no events were found in the datafile\n');
return
end
if strcmp(trialdef.eventtype, 'gui')
eventtype = unique({event.type});
else
eventtype ={trialdef.eventtype};
end
Neventtype = length(eventtype);
if Neventtype==0
fprintf('no events were found in the datafile\n');
else
% Two lists are built in parallel
settings={}; % The list of actual values to be used later
strsettings={}; % The list of strings to show in the GUI
for i=1:Neventtype
sel = find(strcmp(eventtype{i}, {event.type}));
emptyval=find(cellfun('isempty', {event(sel).value}));
if all(cellfun(@isnumeric, {event(sel).value}))
[event(sel(emptyval)).value]=deal(Inf);
eventvalue = unique([event(sel).value]);
else
if ~isempty(strmatch('Inf', {event(sel).value},'exact'))
% It's a very unlikely scenario but ...
warning('Event value''Inf'' cannot be handled by GUI selection. Mistakes are possible.')
end
[event(sel(emptyval)).value]=deal('Inf');
eventvalue = unique({event(sel).value});
if ~iscell(eventvalue)
eventvalue={eventvalue};
end
end
for j=1:length(eventvalue)
if (ischar(eventvalue(j)) && ~strcmp(eventvalue(j), 'Inf')) || ...
(isnumeric(eventvalue(j)) && eventvalue(j)~=Inf)
settings=[settings; [eventtype(i), eventvalue(j)]];
else
settings=[settings; [eventtype(i), {[]}]];
end
if isa(eventvalue, 'numeric')
strsettings=[strsettings; {['Type: ' eventtype{i} ' ; Value: ' num2str(eventvalue(j))]}];
else
strsettings=[strsettings; {['Type: ' eventtype{i} ' ; Value: ' eventvalue{j}]}];
end
end
end
if isempty(strsettings)
fprintf('no events of the selected type were found in the datafile\n');
return
end
[selection ok]= listdlg('ListString',strsettings, 'SelectionMode', 'single', 'Name', 'Select event', 'ListSize', [300 300]);
if ok
trialdef.eventtype=settings{selection,1};
trialdef.eventvalue=settings{selection,2};
end
end
|
github | philippboehmsturm/antx-master | trialfun_realtime.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/trialfun/trialfun_realtime.m | 3,914 | utf_8 | cd4643876036e59ef0a6f318dc0f5856 | function trl = trialfun_realtime(cfg)
% TRIALFUN_REALTIME can be used to segment a continuous stream of
% data in real-time. Trials are defined as [begsample endsample offset
% condition]
%
% The configuration structure can contain the following specifications
% cfg.minsample = the last sample number that was already considered (passed from rt_process)
% cfg.blocksize = in seconds. In case of events, offset is
% wrt the trigger.
% cfg.offset = the offset wrt the 0 point. In case of no events, offset is wrt
% prevSample. E.g., [-0.9 1] will read 1 second blocks with
% 0.9 second overlap
% cfg.bufferdata = {'first' 'last'}. If 'last' then only the last block of
% interest is read. Otherwise, all well-defined blocks are read (default = 'first')
% Copyright (C) 2009, Marcel van Gerven
%
% Subversion does not use the Log keyword, use 'svn log <filename>' or 'svn -v log | less' to get detailled information
if ~isfield(cfg,'minsample'), cfg.minsample = 0; end
if ~isfield(cfg,'blocksize'), cfg.blocksize = 0.1; end
if ~isfield(cfg,'offset'), cfg.offset = 0; end
if ~isfield(cfg,'bufferdata'), cfg.bufferdata = 'first'; end
if ~isfield(cfg,'triggers'), cfg.triggers = []; end
% blocksize and offset in terms of samples
cfg.blocksize = round(cfg.blocksize * cfg.hdr.Fs);
cfg.offset = round(cfg.offset * cfg.hdr.Fs);
% retrieve trials of interest
if isempty(cfg.event) % asynchronous mode
trl = trialfun_asynchronous(cfg);
else % synchronous mode
trl = trialfun_synchronous(cfg);
end
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function trl = trialfun_asynchronous(cfg)
trl = [];
prevSample = cfg.minsample;
if strcmp(cfg.bufferdata, 'last') % only get last block
% begsample starts blocksize samples before the end
begsample = cfg.hdr.nSamples*cfg.hdr.nTrials - cfg.blocksize;
% begsample should be offset samples away from the previous read
if begsample >= (prevSample + cfg.offset)
endsample = cfg.hdr.nSamples*cfg.hdr.nTrials;
if begsample < endsample && begsample > 0
trl = [begsample endsample 0 nan];
end
end
else % get all blocks
while true
% see whether new samples are available
newsamples = (cfg.hdr.nSamples*cfg.hdr.nTrials-prevSample);
% if newsamples exceeds the offset plus length specified in blocksize
if newsamples >= (cfg.offset+cfg.blocksize)
% we do not consider samples < 1
begsample = max(1,prevSample+cfg.offset);
endsample = max(1,prevSample+cfg.offset+cfg.blocksize);
if begsample < endsample && endsample <= cfg.hdr.nSamples*cfg.hdr.nTrials
trl = [trl; [begsample endsample 0 nan]];
end
prevSample = endsample;
else
break;
end
end
end
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function trl = trialfun_synchronous(cfg)
trl = [];
% process all events
for j=1:length(cfg.event)
if isempty(cfg.triggers)
curtrig = cfg.event(j).value;
else
[m1,curtrig] = ismember(cfg.event(j).value,cfg.triggers);
end
if isempty(curtrig), curtrig = nan; end
if isempty(cfg.triggers) || (~isempty(m1) && m1)
% catched a trigger of interest
% we do not consider samples < 1
begsample = max(1,cfg.event(j).sample + cfg.offset);
endsample = max(1,begsample + cfg.blocksize);
trl = [trl; [begsample endsample cfg.offset curtrig]];
end
end
end % function
|
github | philippboehmsturm/antx-master | select_channel_list.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/trialfun/private/select_channel_list.m | 5,910 | utf_8 | 809c334eb560bace022f65305426b3a5 | function [select] = select_channel_list(label, select, titlestr);
% SELECT_CHANNEL_LIST presents a dialog for selecting multiple elements
% from a cell array with strings, such as the labels of EEG channels.
% The dialog presents two columns with an add and remove mechanism.
%
% select = select_channel_list(label, initial, titlestr)
%
% with
% initial indices of channels that are initially selected
% label cell array with channel labels (strings)
% titlestr title for dialog (optional)
% and
% select indices of selected channels
%
% If the user presses cancel, the initial selection will be returned.
% Copyright (C) 2003, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.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: select_channel_list.m 2885 2011-02-16 09:41:58Z roboos $
if nargin<3
titlestr = 'Select';
end
pos = get(0,'DefaultFigurePosition');
pos(3:4) = [290 300];
dlg = dialog('Name', titlestr, 'Position', pos);
select = select(:)'; % ensure that it is a row array
userdata.label = label;
userdata.select = select;
userdata.unselect = setdiff(1:length(label), select);
set(dlg, 'userdata', userdata);
uicontrol(dlg, 'style', 'text', 'position', [ 10 240+20 80 20], 'string', 'unselected');
uicontrol(dlg, 'style', 'text', 'position', [200 240+20 80 20], 'string', 'selected ');
uicontrol(dlg, 'style', 'listbox', 'position', [ 10 40+20 80 200], 'min', 0, 'max', 2, 'tag', 'lbunsel')
uicontrol(dlg, 'style', 'listbox', 'position', [200 40+20 80 200], 'min', 0, 'max', 2, 'tag', 'lbsel')
uicontrol(dlg, 'style', 'pushbutton', 'position', [105 175+20 80 20], 'string', 'add all >' , 'callback', @label_addall);
uicontrol(dlg, 'style', 'pushbutton', 'position', [105 145+20 80 20], 'string', 'add >' , 'callback', @label_add);
uicontrol(dlg, 'style', 'pushbutton', 'position', [105 115+20 80 20], 'string', '< remove' , 'callback', @label_remove);
uicontrol(dlg, 'style', 'pushbutton', 'position', [105 85+20 80 20], 'string', '< remove all', 'callback', @label_removeall);
uicontrol(dlg, 'style', 'pushbutton', 'position', [ 55 10 80 20], 'string', 'Cancel', 'callback', 'close');
uicontrol(dlg, 'style', 'pushbutton', 'position', [155 10 80 20], 'string', 'OK', 'callback', 'uiresume');
label_redraw(dlg);
% wait untill the dialog is closed or the user presses OK/Cancel
uiwait(dlg);
if ishandle(dlg)
% the user pressed OK, return the selection from the dialog
userdata = get(dlg, 'userdata');
select = userdata.select;
close(dlg);
return
else
% the user pressed Cancel or closed the dialog, return the initial selection
return
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function label_redraw(h);
userdata = get(h, 'userdata');
set(findobj(h, 'tag', 'lbsel' ), 'string', userdata.label(userdata.select));
set(findobj(h, 'tag', 'lbunsel'), 'string', userdata.label(userdata.unselect));
% set the active element in the select listbox, based on the previous active element
tmp = min(get(findobj(h, 'tag', 'lbsel'), 'value'));
tmp = min(tmp, length(get(findobj(h, 'tag', 'lbsel'), 'string')));
if isempty(tmp) | tmp==0
tmp = 1;
end
set(findobj(h, 'tag', 'lbsel' ), 'value', tmp);
% set the active element in the unselect listbox, based on the previous active element
tmp = min(get(findobj(h, 'tag', 'lbunsel'), 'value'));
tmp = min(tmp, length(get(findobj(h, 'tag', 'lbunsel'), 'string')));
if isempty(tmp) | tmp==0
tmp = 1;
end
set(findobj(h, 'tag', 'lbunsel' ), 'value', tmp);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function label_addall(h, eventdata, handles, varargin);
h = get(h, 'parent');
userdata = get(h, 'userdata');
userdata.select = 1:length(userdata.label);
userdata.unselect = [];
set(findobj(h, 'tag', 'lbunsel' ), 'value', 1);
set(h, 'userdata', userdata);
label_redraw(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function label_removeall(h, eventdata, handles, varargin);
h = get(h, 'parent');
userdata = get(h, 'userdata');
userdata.unselect = 1:length(userdata.label);
userdata.select = [];
set(findobj(h, 'tag', 'lbsel' ), 'value', 1);
set(h, 'userdata', userdata);
label_redraw(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function label_add(h, eventdata, handles, varargin);
h = get(h, 'parent');
userdata = get(h, 'userdata');
if ~isempty(userdata.unselect)
add = userdata.unselect(get(findobj(h, 'tag', 'lbunsel' ), 'value'));
userdata.select = sort([userdata.select add]);
userdata.unselect = sort(setdiff(userdata.unselect, add));
set(h, 'userdata', userdata);
label_redraw(h);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function label_remove(h, eventdata, handles, varargin);
h = get(h, 'parent');
userdata = get(h, 'userdata');
if ~isempty(userdata.select)
remove = userdata.select(get(findobj(h, 'tag', 'lbsel' ), 'value'));
userdata.select = sort(setdiff(userdata.select, remove));
userdata.unselect = sort([userdata.unselect remove]);
set(h, 'userdata', userdata);
label_redraw(h);
end
|
github | philippboehmsturm/antx-master | ft_convert_units.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/ft_convert_units.m | 6,309 | utf_8 | 45851d8b795b40908878b5859ef0ef5c | function [obj] = ft_convert_units(obj, target)
% FT_CONVERT_UNITS changes the geometrical dimension to the specified SI unit.
% The units of the input object is determined from the structure field
% object.unit, or is estimated based on the spatial extend of the structure,
% e.g. a volume conduction model of the head should be approximately 20 cm large.
%
% Use as
% [object] = ft_convert_units(object, target)
%
% The following input objects are supported
% simple dipole position
% electrode definition
% gradiometer array definition
% volume conductor definition
% dipole grid definition
% anatomical mri
%
% Possible target units are 'm', 'dm', 'cm ' or 'mm'.
%
% See FT_READ_VOL, FT_READ_SENS
% Copyright (C) 2005-2008, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_convert_units.m 3885 2011-07-20 13:58:46Z jansch $
% This function consists of three parts:
% 1) determine the input units
% 2) determine the requested scaling factor to obtain the output units
% 3) try to apply the scaling to the known geometrical elements in the input object
% determine the unit-of-dimension of the input object
if isfield(obj, 'unit') && ~isempty(obj.unit)
% use the units specified in the object
unit = obj.unit;
else
% try to estimate the units from the object
type = ft_voltype(obj);
if ~strcmp(type, 'unknown')
switch type
case 'infinite'
% there is nothing to do to convert the units
unit = target;
case 'singlesphere'
size = obj.r;
case 'multisphere'
size = median(obj.r);
case 'concentric'
size = max(obj.r);
case 'nolte'
size = norm(range(obj.bnd.pnt));
case {'bem' 'dipoli' 'bemcp' 'asa' 'avo'}
size = norm(range(obj.bnd(1).pnt));
otherwise
error('cannot determine geometrical units of volume conduction model');
end % switch
% determine the units by looking at the size
unit = ft_estimate_units(size);
elseif ft_senstype(obj, 'meg')
size = norm(range(obj.pnt));
unit = ft_estimate_units(size);
elseif ft_senstype(obj, 'eeg')
size = norm(range(obj.pnt));
unit = ft_estimate_units(size);
elseif isfield(obj, 'pnt') && ~isempty(obj.pnt)
size = norm(range(obj.pnt));
unit = ft_estimate_units(size);
elseif isfield(obj, 'pos') && ~isempty(obj.pos)
size = norm(range(obj.pos));
unit = ft_estimate_units(size);
elseif isfield(obj, 'transform') && ~isempty(obj.transform)
% construct the corner points of the voxel grid in head coordinates
xi = 1:obj.dim(1);
yi = 1:obj.dim(2);
zi = 1:obj.dim(3);
pos = [
xi( 1) yi( 1) zi( 1)
xi( 1) yi( 1) zi(end)
xi( 1) yi(end) zi( 1)
xi( 1) yi(end) zi(end)
xi(end) yi( 1) zi( 1)
xi(end) yi( 1) zi(end)
xi(end) yi(end) zi( 1)
xi(end) yi(end) zi(end)
];
pos = warp_apply(obj.transform, pos);
size = norm(range(pos));
unit = ft_estimate_units(size);
elseif isfield(obj, 'fid') && isfield(obj.fid, 'pnt') && ~isempty(obj.fid.pnt)
size = norm(range(obj.fid.pnt));
unit = ft_estimate_units(size);
else
error('cannot determine geometrical units');
end % recognized type of volume conduction model or sensor array
end % determine input units
if nargin<2
% just remember the units in the output and return
obj.unit = unit;
return
elseif strcmp(unit, target)
% no conversion is needed
obj.unit = unit;
return
end
% give some information about the conversion
fprintf('converting units from ''%s'' to ''%s''\n', unit, target)
if strcmp(unit, 'm')
unit2meter = 1;
elseif strcmp(unit, 'dm')
unit2meter = 0.1;
elseif strcmp(unit, 'cm')
unit2meter = 0.01;
elseif strcmp(unit, 'mm')
unit2meter = 0.001;
end
% determine the unit-of-dimension of the output object
if strcmp(target, 'm')
meter2target = 1;
elseif strcmp(target, 'dm')
meter2target = 10;
elseif strcmp(target, 'cm')
meter2target = 100;
elseif strcmp(target, 'mm')
meter2target = 1000;
end
% combine the units into one scaling factor
scale = unit2meter * meter2target;
% volume conductor model
if isfield(obj, 'r'), obj.r = scale * obj.r; end
if isfield(obj, 'o'), obj.o = scale * obj.o; end
if isfield(obj, 'bnd'), for i=1:length(obj.bnd), obj.bnd(i).pnt = scale * obj.bnd(i).pnt; end, end
% gradiometer array
if isfield(obj, 'pnt1'), obj.pnt1 = scale * obj.pnt1; end
if isfield(obj, 'pnt2'), obj.pnt2 = scale * obj.pnt2; end
if isfield(obj, 'prj'), obj.prj = scale * obj.prj; end
% gradiometer array, electrode array, head shape or dipole grid
if isfield(obj, 'pnt'), obj.pnt = scale * obj.pnt; end
% fiducials
if isfield(obj, 'fid') && isfield(obj.fid, 'pnt'), obj.fid.pnt = scale * obj.fid.pnt; end
% dipole grid
if isfield(obj, 'pos'), obj.pos = scale * obj.pos; end
% anatomical MRI or functional volume
if isfield(obj, 'transform'),
H = diag([scale scale scale 1]);
obj.transform = H * obj.transform;
end
if isfield(obj, 'transformorig'),
H = diag([scale scale scale 1]);
obj.transformorig = H * obj.transformorig;
end
% remember the unit
obj.unit = target;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
% Use as
% r = range(x)
% or you can also specify the dimension along which to look by
% r = range(x, dim)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function r = range(x, dim)
if nargin==1
r = max(x) - min(x);
else
r = max(x, [], dim) - min(x, [], dim);
end
|
github | philippboehmsturm/antx-master | ft_apply_montage.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/ft_apply_montage.m | 9,812 | utf_8 | 61577f3dc8bb2e20a84da80e88d5bc1f | function [sens] = ft_apply_montage(sens, montage, varargin)
% FT_APPLY_MONTAGE changes the montage of an electrode or gradiometer array. A
% montage can be used for EEG rereferencing, MEG synthetic gradients, MEG
% planar gradients or unmixing using ICA. This function applies the montage
% to the sensor array. The sensor array can subsequently be used for
% forward computation and source reconstruction of the data.
%
% Use as
% [sens] = ft_apply_montage(sens, montage, ...)
% [data] = ft_apply_montage(data, montage, ...)
% [montage] = ft_apply_montage(montage1, montage2, ...)
% where the input is a FieldTrip sensor definition as obtained from FT_READ_SENS
% or a FieldTrip raw data structure as obtained from FT_PREPROCESSING.
%
% A montage is specified as a structure with the fields
% montage.tra = MxN matrix
% montage.labelnew = Mx1 cell-array
% montage.labelorg = Nx1 cell-array
%
% Additional options should be specified in key-value pairs and can be
% 'keepunused' string, 'yes' or 'no' (default = 'no')
% 'inverse' string, 'yes' or 'no' (default = 'no')
%
% If the first input is a montage, then the second input montage will be
% applied to the first. In effect the resulting montage will first do
% montage1, then montage2.
%
% See also FT_READ_SENS, FT_TRANSFORM_SENS
% Copyright (C) 2008, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_apply_montage.m 3391 2011-04-27 10:26:52Z jansch $
% get optional input arguments
keepunused = keyval('keepunused', varargin); if isempty(keepunused), keepunused = 'no'; end
inverse = keyval('inverse', varargin); if isempty(inverse), inverse = 'no'; end
feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'text'; end
bname = keyval('balancename', varargin); if isempty(bname), bname = ''; end
% check the consistency of the input sensor array or data
if isfield(sens, 'labelorg') && isfield(sens, 'labelnew')
% the input data structure is also a montage, i.e. apply the montages sequentially
sens.label = sens.labelnew;
end
% check the consistency of the montage
if size(montage.tra,1)~=length(montage.labelnew)
error('the number of channels in the montage is inconsistent');
elseif size(montage.tra,2)~=length(montage.labelorg)
error('the number of channels in the montage is inconsistent');
end
if strcmp(inverse, 'yes')
% apply the inverse montage, i.e. undo a previously applied montage
tmp.labelnew = montage.labelorg; % swap around
tmp.labelorg = montage.labelnew; % swap around
tmp.tra = full(montage.tra);
if rank(tmp.tra) < length(tmp.tra)
warning('the linear projection for the montage is not full-rank, the resulting data will have reduced dimensionality');
tmp.tra = pinv(tmp.tra);
else
tmp.tra = inv(tmp.tra);
end
montage = tmp;
end
% use default transfer from sensors to channels if not specified
if isfield(sens, 'pnt') && ~isfield(sens, 'tra')
nchan = size(sens.pnt,1);
sens.tra = sparse(eye(nchan));
end
% select and keep the columns that are non-empty, i.e. remove the empty columns
selcol = find(~all(montage.tra==0, 1));
montage.tra = montage.tra(:,selcol);
montage.labelorg = montage.labelorg(selcol);
clear selcol
% select and remove the columns corresponding to channels that are not present in the original data
remove = setdiff(montage.labelorg, intersect(montage.labelorg, sens.label));
selcol = match_str(montage.labelorg, remove);
% we cannot just remove the colums, all rows that depend on it should also be removed
selrow = false(length(montage.labelnew),1);
for i=1:length(selcol)
selrow = selrow & (montage.tra(:,selcol(i))~=0);
end
% convert from indices to logical vector
selcol = indx2logical(selcol, length(montage.labelorg));
% remove rows and columns
montage.labelorg = montage.labelorg(~selcol);
montage.labelnew = montage.labelnew(~selrow);
montage.tra = montage.tra(~selrow, ~selcol);
clear remove selcol selrow i
% add columns for the channels that are present in the data but not involved in the montage, and stick to the original order in the data
[add, ix] = setdiff(sens.label, montage.labelorg);
add = sens.label(sort(ix));
m = size(montage.tra,1);
n = size(montage.tra,2);
k = length(add);
if strcmp(keepunused, 'yes')
% add the channels that are not rereferenced to the input and output
montage.tra((m+(1:k)),(n+(1:k))) = eye(k);
montage.labelorg = cat(1, montage.labelorg(:), add(:));
montage.labelnew = cat(1, montage.labelnew(:), add(:));
else
% add the channels that are not rereferenced to the input montage only
montage.tra(:,(n+(1:k))) = zeros(m,k);
montage.labelorg = cat(1, montage.labelorg(:), add(:));
end
clear add m n k
% determine whether all channels are unique
m = size(montage.tra,1);
n = size(montage.tra,2);
if length(unique(montage.labelnew))~=m
error('not all output channels of the montage are unique');
end
if length(unique(montage.labelorg))~=n
error('not all input channels of the montage are unique');
end
% determine whether all channels that have to be rereferenced are available
if length(intersect(sens.label, montage.labelorg))~=length(montage.labelorg)
error('not all channels that are required in the montage are available in the data');
end
% reorder the columns of the montage matrix
[selsens, selmont] = match_str(sens.label, montage.labelorg);
montage.tra = double(sparse(montage.tra(:,selmont)));
montage.labelorg = montage.labelorg(selmont);
if isfield(sens, 'labelorg') && isfield(sens, 'labelnew')
% apply the montage on top of the other montage
sens = rmfield(sens, 'label');
if isa(sens.tra, 'single')
sens.tra = full(montage.tra) * sens.tra;
else
sens.tra = montage.tra * sens.tra;
end
sens.labelnew = montage.labelnew;
elseif isfield(sens, 'tra')
% apply the montage to the sensor array
if isa(sens.tra, 'single')
sens.tra = full(montage.tra) * sens.tra;
else
sens.tra = montage.tra * sens.tra;
end
sens.label = montage.labelnew;
% keep track of the order of the balancing and which one is the current
% one
if strcmp(inverse, 'yes')
if isfield(sens, 'balance')% && isfield(sens.balance, 'previous')
if isfield(sens.balance, 'previous') && numel(sens.balance.previous)>=1
sens.balance.current = sens.balance.previous{1};
sens.balance.previous = sens.balance.previous(2:end);
elseif isfield(sens.balance, 'previous')
sens.balance.current = 'none';
sens.balance = rmfield(sens.balance, 'previous');
else
sens.balance.current = 'none';
end
end
elseif ~strcmp(inverse, 'yes') && ~isempty(bname)
if isfield(sens, 'balance') && isfield(sens.balance, 'current')
if ~isfield(sens.balance, 'previous')
sens.balance.previous = {};
end
sens.balance.previous = [{sens.balance.current} sens.balance.previous];
sens.balance.current = bname;
sens.balance.(bname) = montage;
end
end
elseif isfield(sens, 'trial')
% apply the montage to the raw data that was preprocessed using fieldtrip
data = sens;
clear sens
Ntrials = numel(data.trial);
ft_progress('init', feedback, 'processing trials');
for i=1:Ntrials
ft_progress(i/Ntrials, 'processing trial %d from %d\n', i, Ntrials);
if isa(data.trial{i}, 'single')
% sparse matrices and single precision do not match
data.trial{i} = full(montage.tra) * data.trial{i};
else
data.trial{i} = montage.tra * data.trial{i};
end
end
ft_progress('close');
data.label = montage.labelnew;
% rename the output variable
sens = data;
clear data
elseif isfield(sens, 'fourierspctrm')
% apply the montage to the spectrally decomposed data
freq = sens;
clear sens
if strcmp(freq.dimord, 'rpttap_chan_freq')
siz = size(freq.fourierspctrm);
nrpt = siz(1);
nchan = siz(2);
nfreq = siz(3);
output = zeros(nrpt, size(montage.tra,1), nfreq);
for foilop=1:nfreq
output(:,:,foilop) = freq.fourierspctrm(:,:,foilop) * montage.tra';
end
elseif strcmp(freq.dimord, 'rpttap_chan_freq_time')
siz = size(freq.fourierspctrm);
nrpt = siz(1);
nchan = siz(2);
nfreq = siz(3);
ntime = siz(4);
output = zeros(nrpt, size(montage.tra,1), nfreq, ntime);
for foilop=1:nfreq
for toilop = 1:ntime
output(:,:,foilop,toilop) = freq.fourierspctrm(:,:,foilop,toilop) * montage.tra';
end
end
else
error('unsupported dimord in frequency data (%s)', freq.dimord);
end
% replace the Fourier spectrum
freq.fourierspctrm = output;
freq.label = montage.labelnew;
% rename the output variable
sens = freq;
clear freq
else
error('unrecognized input');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HELPER FUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = indx2logical(x, n)
y = false(1,n);
y(x) = true;
|
github | philippboehmsturm/antx-master | ft_headmodel_strip.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/ft_headmodel_strip.m | 2,512 | utf_8 | 78012ba16bcf9bde9845d01082ab86ee | function vol = ft_headmodel_strip(geom1, geom2, Pc, varargin)
% FT_HEADMODEL_STRIP creates an EEG volume conduction model that
% is described with an infinite conductive strip. You can think
% of this as two parallel planes containing a mass of conductive
% material (e.g. water) and externally to them a non-conductive material
% (e.g. air).
% geom1.pnt = Nx3 vector specifying N points through which the 'upper' plane is fitted
% D = distance of the parallel planes
% Pc = 1x3 vector specifying the spatial position of a point lying in the conductive strip
% (this determines the plane's normal's direction)
%
% Additional optional arguments include:
% 'sourcemodel' = 'monopole' or 'dipole' (default)
% 'conductivity' = number , conductivity value of the conductive halfspace (default = 1)
%
% Use as
% vol = ft_headmodel_strip(geom1, geom2, Pc, varargin)
%
% See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD
model = keyval('sourcemodel', varargin); if isempty(model), model='monopole'; end
cond = keyval('conductivity', varargin);
if isempty(cond), cond = 1; warning('Unknown conductivity value (set to 1)'); end
% the description of this volume conduction model consists of the
% description of the plane, and a point in the void halfspace
if isstruct(geom1) && isfield(geom1,'pnt')
pnt1 = geom1.pnt;
pnt2 = geom2.pnt;
elseif size(geom1,2)==3
pnt1 = geom1;
pnt2 = geom2;
else
error('incorrect specification of the geometry');
end
% fit a plane to the points
[N1,P1] = fit_plane(pnt1);
[N2,P2] = fit_plane(pnt2);
% checks if Pc is in the conductive part. If not, flip
incond = acos(dot(N1,(Pc-P1)./norm(Pc-P1))) > pi/2;
if ~incond
N1 = -N1;
end
incond = acos(dot(N2,(Pc-P2)./norm(Pc-P2))) > pi/2;
if ~incond
N2 = -N2;
end
vol = [];
vol.cond = cond;
vol.pnt1 = P1(:)'; % a point that lies on the plane that separates the conductive tissue from the air
vol.ori1 = N1(:)'; % a unit vector pointing towards the air
vol.ori1 = vol.ori1/norm(vol.ori1);
vol.pnt2 = P2(:)';
vol.ori2 = N2(:)';
vol.ori2 = vol.ori2/norm(vol.ori2);
if strcmpi(model,'monopole')
vol.type = 'strip_monopole';
else
error('unknow method')
end
function [N,P] = fit_plane(X)
% Fits a plane through a number of points in 3D cartesian coordinates
P = mean(X,1); % the plane is spanned by this point and by a normal vector
X = bsxfun(@minus,X,P);
[u, s, v] = svd(X, 0);
N = v(:,3); % orientation of the plane, can be in either direction
|
github | philippboehmsturm/antx-master | ft_prepare_vol_sens.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/ft_prepare_vol_sens.m | 19,902 | utf_8 | b77bd556a276e512906c25da310c1517 | function [vol, sens] = ft_prepare_vol_sens(vol, sens, varargin)
% FT_PREPARE_VOL_SENS does some bookkeeping to ensure that the volume
% conductor model and the sensor array are ready for subsequent forward
% leadfield computations. It takes care of some pre-computations that can
% be done efficiently prior to the leadfield calculations.
%
% Use as
% [vol, sens] = ft_prepare_vol_sens(vol, sens, ...)
% with input arguments
% sens structure with gradiometer or electrode definition
% vol structure with volume conductor definition
%
% The vol structure represents a volume conductor model, its contents
% depend on the type of model. The sens structure represents a sensor
% array, i.e. EEG electrodes or MEG gradiometers.
%
% Additional options should be specified in key-value pairs and can be
% 'channel' cell-array with strings (default = 'all')
% 'order' number, for single shell "Nolte" model (default = 10)
%
% The detailled behaviour of this function depends on whether the input
% consists of EEG or MEG and furthermoree depends on the type of volume
% conductor model:
% - in case of EEG single and concentric sphere models, the electrodes are
% projected onto the skin surface.
% - in case of EEG boundary element models, the electrodes are projected on
% the surface and a blilinear interpoaltion matrix from vertices to
% electrodes is computed.
% - in case of MEG and a multispheres model, a local sphere is determined
% for each coil in the gradiometer definition.
% - in case of MEG with a singleshell Nolte model, the volume conduction
% model is initialized
% In any case channel selection and reordering will be done. The channel
% order returned by this function corresponds to the order in the 'channel'
% option, or if not specified, to the order in the input sensor array.
%
% See also FT_READ_VOL, FT_READ_SENS, FT_TRANSFORM_VOL, FT_TRANSFORM_SENS, FT_COMPUTE_LEADFIELD
% Copyright (C) 2004-2009, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_prepare_vol_sens.m 3895 2011-07-24 15:16:53Z crimic $
% get the options
% fileformat = keyval('fileformat', varargin);
channel = keyval('channel', varargin); % cell-array with channel labels
order = keyval('order', varargin); % order of expansion for Nolte method; 10 should be enough for real applications; in simulations it makes sense to go higher
% set the defaults
if isempty(channel), channel = sens.label; end
if isempty(order), order = 10; end
% determine whether the input contains EEG or MEG sensors
iseeg = ft_senstype(sens, 'eeg');
ismeg = ft_senstype(sens, 'meg');
% determine the skin compartment
if ~isfield(vol, 'skin_surface')
if isfield(vol, 'bnd')
vol.skin_surface = find_outermost_boundary(vol.bnd);
elseif isfield(vol, 'r') && length(vol.r)<=4
[dum, vol.skin_surface] = max(vol.r);
end
end
% determine the inner_skull_surface compartment
if ~isfield(vol, 'inner_skull_surface')
if isfield(vol, 'bnd')
vol.inner_skull_surface = find_innermost_boundary(vol.bnd);
elseif isfield(vol, 'r') && length(vol.r)<=4
[dum, vol.inner_skull_surface] = min(vol.r);
end
end
% otherwise the voltype assignment to an empty struct below won't work
if isempty(vol)
vol = [];
end
% this makes them easier to recognise
sens.type = ft_senstype(sens);
vol.type = ft_voltype(vol);
if isfield(vol, 'unit') && isfield(sens, 'unit') && ~strcmp(vol.unit, sens.unit)
error('inconsistency in the units of the volume conductor and the sensor array');
end
if ismeg && iseeg
% this is something that could be implemented relatively easily
error('simultaneous EEG and MEG not yet supported');
elseif ~ismeg && ~iseeg
error('the input does not look like EEG, nor like MEG');
elseif ismeg
% keep a copy of the original sensor array, this is needed for the MEG multisphere model
sens_orig = sens;
% always ensure that there is a linear transfer matrix for combining the coils into gradiometers
if ~isfield(sens, 'tra');
Nchans = length(sens.label);
Ncoils = size(sens.pnt,1);
if Nchans~=Ncoils
error('inconsistent number of channels and coils');
end
sens.tra = sparse(eye(Nchans, Ncoils));
end
% select the desired channels from the gradiometer array
% order them according to the users specification
[selchan, selsens] = match_str(channel, sens.label);
% first only modify the linear combination of coils into channels
sens.label = sens.label(selsens);
sens.tra = sens.tra(selsens,:);
% subsequently remove the coils that do not contribute to any sensor output
selcoil = find(sum(sens.tra,1)~=0);
sens.pnt = sens.pnt(selcoil,:);
sens.ori = sens.ori(selcoil,:);
sens.tra = sens.tra(:,selcoil);
switch ft_voltype(vol)
case 'infinite'
% nothing to do
case 'singlesphere'
% nothing to do
case 'concentric'
% nothing to do
case 'neuromag'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if the forward model is computed using the external Neuromag toolbox,
% we have to add a selection of the channels so that the channels
% in the forward model correspond with those in the data.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[selchan, selsens] = match_str(channel, sens.label);
vol.chansel = selsens;
case 'multisphere'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% If the volume conduction model consists of multiple spheres then we
% have to match the channels in the gradiometer array and the volume
% conduction model.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% use the original sensor array instead of the one with a subset of
% channels, because we need the complete mapping of coils to channels
sens = sens_orig;
% remove the coils that do not contribute to any channel output
% since these do not have a corresponding sphere
selcoil = find(sum(sens.tra,1)~=0);
sens.pnt = sens.pnt(selcoil,:);
sens.ori = sens.ori(selcoil,:);
sens.tra = sens.tra(:,selcoil);
% the initial multisphere volume conductor has a local sphere per
% channel, whereas it should have a local sphere for each coil
if size(vol.r,1)==size(sens.pnt,1) && ~isfield(vol, 'label')
% it appears that each coil already has a sphere, which suggests
% that the volume conductor already has been prepared to match the
% sensor array
return
elseif size(vol.r,1)==size(sens.pnt,1) && isfield(vol, 'label')
if ~isequal(vol.label(:), sens.label(:))
% if only the order is different, it would be possible to reorder them
error('the coils in the volume conduction model do not correspond to the sensor array');
else
% the coil-specific spheres in the volume conductor should not have a label
% because the label is already specified for the coils in the
% sensor array
vol = rmfield(vol, 'label');
end
return
end
% the CTF way of representing the headmodel is one-sphere-per-channel
% whereas the FieldTrip way of doing the forward computation is one-sphere-per-coil
Nchans = size(sens.tra,1);
Ncoils = size(sens.tra,2);
Nspheres = size(vol.label);
if isfield(vol, 'orig')
% these are present in a CTF *.hdm file
singlesphere.o(1,1) = vol.orig.MEG_Sphere.ORIGIN_X;
singlesphere.o(1,2) = vol.orig.MEG_Sphere.ORIGIN_Y;
singlesphere.o(1,3) = vol.orig.MEG_Sphere.ORIGIN_Z;
singlesphere.r = vol.orig.MEG_Sphere.RADIUS;
% ensure consistent units
singlesphere = ft_convert_units(singlesphere, vol.unit);
% determine the channels that do not have a corresponding sphere
% and use the globally fitted single sphere for those
missing = setdiff(sens.label, vol.label);
if ~isempty(missing)
warning('using the global fitted single sphere for %d channels that do not have a local sphere', length(missing));
end
for i=1:length(missing)
vol.label(end+1) = missing(i);
vol.r(end+1,:) = singlesphere.r;
vol.o(end+1,:) = singlesphere.o;
end
end
multisphere = [];
% for each coil in the MEG helmet, determine the corresponding channel and from that the corresponding local sphere
for i=1:Ncoils
coilindex = find(sens.tra(:,i)~=0); % to which channel does this coil belong
if length(coilindex)>1
% this indicates that there are multiple channels to which this coil contributes,
% which happens if the sensor array represents a synthetic higher-order gradient.
[dum, coilindex] = max(abs(sens.tra(:,i)));
end
coillabel = sens.label{coilindex}; % what is the label of this channel
chanindex = strmatch(coillabel, vol.label, 'exact'); % what is the index of this channel in the list of local spheres
multisphere.r(i,:) = vol.r(chanindex);
multisphere.o(i,:) = vol.o(chanindex,:);
end
vol = multisphere;
% finally do the selection of channels and coils
% order them according to the users specification
[selchan, selsens] = match_str(channel, sens.label);
% first only modify the linear combination of coils into channels
sens.label = sens.label(selsens);
sens.tra = sens.tra(selsens,:);
% subsequently remove the coils that do not contribute to any sensor output
selcoil = find(sum(sens.tra,1)~=0);
sens.pnt = sens.pnt(selcoil,:);
sens.ori = sens.ori(selcoil,:);
sens.tra = sens.tra(:,selcoil);
% make the same selection of coils in the multisphere model
vol.r = vol.r(selcoil);
vol.o = vol.o(selcoil,:);
case 'nolte'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if the forward model is computed using the code from Guido Nolte, we
% have to initialize the volume model using the gradiometer coil
% locations
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute the surface normals for each vertex point
if ~isfield(vol.bnd, 'nrm')
fprintf('computing surface normals\n');
vol.bnd.nrm = normals(vol.bnd.pnt, vol.bnd.tri);
end
% estimate center and radius
[center,radius] = fitsphere(vol.bnd.pnt);
% initialize the forward calculation (only if gradiometer coils are available)
if size(sens.pnt,1)>0
vol.forwpar = meg_ini([vol.bnd.pnt vol.bnd.nrm], center', order, [sens.pnt sens.ori]);
end
case 'openmeeg'
% nothing ?
otherwise
error('unsupported volume conductor model for MEG');
end
elseif iseeg
% select the desired channels from the electrode array
% order them according to the users specification
if ~isfield(sens, 'tra')
Nchans = length(sens.label);
Ncontacts = length(sens.label);
else
Nchans = size(sens.tra,1);
Ncontacts = size(sens.tra,2);
end;
% In case of Nchans~=Ncontacts it is difficult to determine
% how to deal with contacts positions (keep the original positions)
if Nchans == Ncontacts
[selchan, selsens] = match_str(channel, sens.label);
sens.label = sens.label(selsens);
sens.pnt = sens.pnt(selsens,:);
else
warning('A sub-selection of channels will not be taken into account')
end
% create a 2D projection and triangulation
try
sens.prj = elproj(sens.pnt);
sens.tri = delaunay(sens.prj(:,1), sens.prj(:,2));
catch
warning('2D projection not done')
end
switch ft_voltype(vol)
case 'infinite'
% nothing to do
case {'halfspace', 'halfspace_monopole'}
% electrodes' all-to-all distances
numel = size(sens.pnt,1);
ref_el = sens.pnt(1,:);
md = dist( (sens.pnt-repmat(ref_el,[numel 1]))' );
% take the min distance as reference
md = min(md(1,2:end));
pnt = sens.pnt;
% scan the electrodes and reposition the ones which are in the
% wrong halfspace (projected on the plane)... if not too far away!
for i=1:size(pnt,1)
P = pnt(i,:);
is_in_empty = acos(dot(vol.ori,(P-vol.pnt)./norm(P-vol.pnt))) < pi/2;
if is_in_empty
dPplane = abs(dot(vol.ori, vol.pnt-P, 2));
if dPplane>md
error('Some electrodes are too distant from the plane: consider repositioning them')
else
% project point on plane
Ppr = pointproj(P,[vol.pnt vol.ori]);
pnt(i,:) = Ppr;
end
end
end
sens.pnt = pnt;
case {'strip_monopole'}
% electrodes' all-to-all distances
numel = size(sens.pnt,1);
ref_el = sens.pnt(1,:);
md = dist( (sens.pnt-repmat(ref_el,[numel 1]))' );
% choose min distance between electrodes
md = min(md(1,2:end));
pnt = sens.pnt;
% looks for contacts outside the strip which are not too far away
% and projects them on the nearest plane
for i=1:size(pnt,1)
P = pnt(i,:);
instrip1 = acos(dot(vol.ori1,(P-vol.pnt1)./norm(P-vol.pnt1))) > pi/2;
instrip2 = acos(dot(vol.ori2,(P-vol.pnt2)./norm(P-vol.pnt2))) > pi/2;
is_in_empty = ~(instrip1&instrip2);
if is_in_empty
dPplane1 = abs(dot(vol.ori1, vol.pnt1-P, 2));
dPplane2 = abs(dot(vol.ori2, vol.pnt2-P, 2));
if dPplane1>md || dPplane2>md
error('Some electrodes are too distant from the plane: consider repositioning them')
elseif dPplane2>dPplane1
% project point on nearest plane
Ppr = pointproj(P,[vol.pnt1 vol.ori1]);
pnt(i,:) = Ppr;
else
% project point on nearest plane
Ppr = pointproj(P,[vol.pnt2 vol.ori2]);
pnt(i,:) = Ppr;
end
end
end
sens.pnt = pnt;
case {'singlesphere', 'concentric'}
% ensure that the electrodes ly on the skin surface
radius = max(vol.r);
pnt = sens.pnt;
if isfield(vol, 'o')
% shift the the centre of the sphere to the origin
pnt(:,1) = pnt(:,1) - vol.o(1);
pnt(:,2) = pnt(:,2) - vol.o(2);
pnt(:,3) = pnt(:,3) - vol.o(3);
end
distance = sqrt(sum(pnt.^2,2)); % to the center of the sphere
if any((abs(distance-radius)/radius)>0.005)
warning('electrodes do not lie on skin surface -> using radial projection')
end
pnt = pnt * radius ./ [distance distance distance];
if isfield(vol, 'o')
% shift the center back to the original location
pnt(:,1) = pnt(:,1) + vol.o(1);
pnt(:,2) = pnt(:,2) + vol.o(2);
pnt(:,3) = pnt(:,3) + vol.o(3);
end
sens.pnt = pnt;
case {'bem', 'dipoli', 'asa', 'avo', 'bemcp', 'openmeeg'}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% do postprocessing of volume and electrodes in case of BEM model
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% project the electrodes on the skin and determine the bilinear interpolation matrix
if ~isfield(vol, 'tra')
% determine boundary corresponding with skin and inner_skull_surface
if ~isfield(vol, 'skin_surface')
vol.skin_surface = find_outermost_boundary(vol.bnd);
fprintf('determining skin compartment (%d)\n', vol.skin_surface);
end
if ~isfield(vol, 'source')
vol.source = find_innermost_boundary(vol.bnd);
fprintf('determining source compartment (%d)\n', vol.source);
end
if size(vol.mat,1)~=size(vol.mat,2) && size(vol.mat,1)==length(sens.pnt)
fprintf('electrode transfer and system matrix were already combined\n');
else
fprintf('projecting electrodes on skin surface\n');
% compute linear interpolation from triangle vertices towards electrodes
[el, prj] = project_elec(sens.pnt, vol.bnd(vol.skin_surface).pnt, vol.bnd(vol.skin_surface).tri);
tra = transfer_elec(vol.bnd(vol.skin_surface).pnt, vol.bnd(vol.skin_surface).tri, el);
% replace the original electrode positions by the projected positions
sens.pnt = prj;
if size(vol.mat,1)==size(vol.bnd(vol.skin_surface).pnt,1)
% construct the transfer from only the skin vertices towards electrodes
interp = tra;
else
% construct the transfer from all vertices (also inner_skull_surface/outer_skull_surface) towards electrodes
interp = [];
for i=1:length(vol.bnd)
if i==vol.skin_surface
interp = [interp, tra];
else
interp = [interp, zeros(size(el,1), size(vol.bnd(i).pnt,1))];
end
end
end
% incorporate the linear interpolation matrix and the system matrix into one matrix
% this speeds up the subsequent repeated leadfield computations
fprintf('combining electrode transfer and system matrix\n');
if strcmp(ft_voltype(vol), 'openmeeg')
nb_points_external_surface = size(vol.bnd(vol.skin_surface).pnt,1);
vol.mat = vol.mat((end-nb_points_external_surface+1):end,:);
vol.mat = interp(:,1:nb_points_external_surface) * vol.mat;
else
% convert to sparse matrix to speed up the subsequent multiplication
interp = sparse(interp);
vol.mat = interp * vol.mat;
% ensure that the model potential will be average referenced
avg = mean(vol.mat, 1);
vol.mat = vol.mat - repmat(avg, size(vol.mat,1), 1);
end
end
end
otherwise
error('unsupported volume conductor model for EEG');
end
% FIXME this needs carefull thought to ensure that the average referencing which is now done here and there, and that the linear interpolation in case of BEM are all dealt with consistently
% % always ensure that there is a linear transfer matrix for
% % rereferencing the EEG potential
% if ~isfield(sens, 'tra');
% sens.tra = sparse(eye(length(sens.label)));
% end
end % if iseeg or ismeg
function Ppr = pointproj(P,plane)
% projects a point on a plane
% plane(1:3) is a point on the plane
% plane(4:6) is the ori of the plane
Ppr = [];
ori = plane(4:6);
line = [P ori];
% get indices of line and plane which are parallel
par = abs(dot(plane(4:6), line(:,4:6), 2))<1e-14;
% difference between origins of plane and line
dp = plane(1:3) - line(:, 1:3);
% Divide only for non parallel vectors (DL)
t = dot(ori(~par,:), dp(~par,:), 2)./dot(ori(~par,:), line(~par,4:6), 2);
% compute coord of intersection point
Ppr(~par, :) = line(~par,1:3) + repmat(t,1,3).*line(~par,4:6);
|
github | philippboehmsturm/antx-master | ft_headmodel_halfspace.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/ft_headmodel_halfspace.m | 2,272 | utf_8 | 5fdcb390bd9403dbc7fc6c7b668ba15e | function vol = ft_headmodel_halfspace(geom, Pc, varargin)
% FT_HEADMODEL_HALFSPACE creates an EEG volume conduction model that
% is described with an infinite conductive halfspace. You can think
% of this as a plane with on one side a infinite mass of conductive
% material (e.g. water) and on the other side non-conductive material
% (e.g. air).
% geom.pnt = Nx3 vector specifying N points through which a plane is fitted
% Pc = 1x3 vector specifying the spatial position of a point lying in the conductive halfspace
% (this determines the plane normal's direction)
% Additional optional arguments include:
% 'sourcemodel' = 'monopole' or 'dipole' (default)
% 'conductivity' = number , conductivity value of the conductive halfspace (default = 1)
%
% Use as
% vol = ft_headmodel_halfspace(geom, Pc, varargin)
%
% See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD
model = keyval('sourcemodel', varargin); if isempty(model), model='dipole'; end
cond = keyval('conductivity', varargin);
if isempty(cond), cond = 1; warning('Unknown conductivity value (set to 1)'); end
% the description of this volume conduction model consists of the
% description of the plane, and a point in the void halfspace
if isstruct(geom) && isfield(geom,'pnt')
pnt = geom.pnt;
elseif size(geom,2)==3
pnt = geom;
else
error('incorrect specification of the geometry');
end
% fit a plane to the points
[N,P] = fit_plane(pnt);
% checks if Pc is in the conductive part. If not, flip
incond = acos(dot(N,(Pc-P)./norm(Pc-P))) > pi/2;
if ~incond
N = -N;
end
vol = [];
vol.cond = cond;
vol.pnt = P(:)'; % a point that lies on the plane that separates the conductive tissue from the air
vol.ori = N(:)'; % a unit vector pointing towards the air
vol.ori = vol.ori/norm(vol.ori);
if strcmpi(model,'dipole')
vol.type = 'halfspace';
elseif strcmpi(model,'monopole')
vol.type = 'halfspace_monopole';
else
error('unknow method')
end
function [N,P] = fit_plane(X)
% Fits a plane through a number of points in 3D cartesian coordinates
P = mean(X,1); % the plane is spanned by this point and by a normal vector
X = bsxfun(@minus,X,P);
[u, s, v] = svd(X, 0);
N = v(:,3); % orientation of the plane, can be in either direction
|
github | philippboehmsturm/antx-master | ft_headmodel_openmeeg.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/ft_headmodel_openmeeg.m | 7,135 | utf_8 | 633b647b11ba16d47bfe321c8ff32493 | function vol = ft_headmodel_bem_openmeeg(geom, varargin)
% FT_HEADMODEL_OPENMEEG creates a volume conduction model of the
% head using the boundary element method (BEM). This function takes
% as input the triangulated surfaces that describe the boundaries and
% returns as output a volume conduction model which can be used to
% compute leadfields.
%
% This function implements
% Gramfort et al. OpenMEEG: opensource software for quasistatic
% bioelectromagnetics. Biomedical engineering online (2010) vol. 9 (1) pp. 45
% http://www.biomedical-engineering-online.com/content/9/1/45
% doi:10.1186/1475-925X-9-45
% and
% Kybic et al. Generalized head models for MEG/EEG: boundary element method
% beyond nested volumes. Phys. Med. Biol. (2006) vol. 51 pp. 1333-1346
% doi:10.1088/0031-9155/51/5/021
%
% The implementation in this function is derived from the the OpenMEEG project
% and uses external command-line executables. See http://gforge.inria.fr/projects/openmeeg
% and http://gforge.inria.fr/frs/?group_id=435.
%
% Use as
% vol = ft_headmodel_openmeeg(geom, ...)
%
% Optional input arguments should be specified in key-value pairs and can
% include
% isolatedsource = string, 'yes' or 'no'
% hdmfile = string, filename with BEM headmodel
% conductivity = vector, conductivity of each compartment
%
% See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD
ft_hastoolbox('openmeeg', 1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the first part is largely shared with the dipoli and bemcp implementation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get the optional arguments
isolatedsource = keyval('isolatedsource', varargin);
hdmfile = keyval('hdmfile', varargin);
conductivity = keyval('conductivity', varargin);
% start with an empty volume conductor
vol = [];
if ~isempty(hdmfile)
hdm = ft_read_vol(hdmfile);
% copy the boundary of the head model file into the volume conduction model
vol.bnd = hdm.bnd;
if isfield(hdm, 'cond')
% also copy the conductivities
vol.cond = hdm.cond;
end
else
% copy the boundaries from the geometry into the volume conduction model
vol.bnd = geom.bnd;
end
% determine the number of compartments
numboundaries = length(vol.bnd);
if isempty(isolatedsource)
if numboundaries>1
% the isolated source compartment is by default the most inner one
isolatedsource = true;
else
isolatedsource = false;
end
else
% convert into a boolean
isolatedsource = istrue(cfg.isolatedsource);
end
if ~isfield(vol, 'cond')
% assign the conductivity of each compartment
vol.cond = conductivity;
end
% determine the nesting of the compartments
nesting = zeros(numboundaries);
for i=1:numboundaries
for j=1:numboundaries
if i~=j
% determine for a single vertex on each surface if it is inside or outside the other surfaces
curpos = vol.bnd(i).pnt(1,:); % any point on the boundary is ok
curpnt = vol.bnd(j).pnt;
curtri = vol.bnd(j).tri;
nesting(i,j) = bounding_mesh(curpos, curpnt, curtri);
end
end
end
if sum(nesting(:))~=(numboundaries*(numboundaries-1)/2)
error('the compartment nesting cannot be determined');
end
% for a three compartment model, the nesting matrix should look like
% 0 0 0 the first is the most outside, i.e. the skin
% 0 0 1 the second is nested inside the 3rd, i.e. the outer skull
% 0 1 1 the third is nested inside the 2nd and 3rd, i.e. the inner skull
[~, order] = sort(sum(nesting,2));
fprintf('reordering the boundaries to: ');
fprintf('%d ', order);
fprintf('\n');
% update the order of the compartments
vol.bnd = vol.bnd(order);
vol.cond = vol.cond(order);
vol.skin_surface = 1;
vol.source = numboundaries;
if isolatedsource
fprintf('using compartment %d for the isolated source approach\n', vol.source);
else
fprintf('not using the isolated source approach\n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this uses an implementation that was contributed by INRIA Odyssee Team
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% show the license once
openmeeg_license
% check that the binaries are ok
om_checkombin;
if vol.skin_surface ~= 1
error('the first compartment should be the skin, the last the source');
end
% flip faces for openmeeg convention
for ii=1:length(vol.bnd)
vol.bnd(ii).tri = fliplr(vol.bnd(ii).tri);
end
% store the current path and change folder to the temporary one
tmpfolder = cd;
try
cd(tempdir)
% write the triangulations to file
bndfile = {};
for ii=1:length(vol.bnd)
[junk,tname] = fileparts(tempname);
bndfile{ii} = [tname '.tri'];
om_save_tri(bndfile{ii}, vol.bnd(ii).pnt, vol.bnd(ii).tri);
end
% these will hold the shell script and the inverted system matrix
[~,tname] = fileparts(tempname);
if ~ispc
exefile = [tname '.sh'];
else
exefile = [tname '.bat'];
end
[~,tname] = fileparts(tempname);
condfile = [tname '.cond'];
[~,tname] = fileparts(tempname);
geomfile = [tname '.geom'];
[~,tname] = fileparts(tempname);
hmfile = [tname '.bin'];
[~,tname] = fileparts(tempname);
hminvfile = [tname '.bin'];
% write conductivity and geometry files
om_write_geom(geomfile,bndfile);
om_write_cond(condfile,vol.cond);
% Exe file
efid = fopen(exefile, 'w');
omp_num_threads = feature('numCores');
if ~ispc
fprintf(efid,'#!/usr/bin/env bash\n');
fprintf(efid,['export OMP_NUM_THREADS=',num2str(omp_num_threads),'\n']);
fprintf(efid,['om_assemble -HM ./' geomfile ' ./' condfile ' ./' hmfile ' 2>&1 > /dev/null\n']);
fprintf(efid,['om_minverser ./' hmfile ' ./' hminvfile ' 2>&1 > /dev/null\n']);
else
fprintf(efid,['om_assemble -HM ./' geomfile ' ./' condfile ' ./' hmfile '\n']);
fprintf(efid,['om_minverser ./' hmfile ' ./' hminvfile '\n']);
end
fclose(efid);
if ~ispc
dos(sprintf('chmod +x %s', exefile));
end
catch
cd(tmpfolder)
rethrow(lasterror)
end
try
% execute OpenMEEG and read the resulting file
if ispc
dos([exefile]);
else
version = om_getgccversion;
if version>3
dos(['./' exefile]);
else
error('non suitable GCC compiler version (must be superior to gcc3)');
end
end
vol.mat = om_load_sym(hminvfile,'binary');
cleaner(vol,bndfile,condfile,geomfile,hmfile,hminvfile,exefile)
cd(tmpfolder)
catch
warning('an error ocurred while running OpenMEEG');
disp(lasterr);
cleaner(vol,bndfile,condfile,geomfile,hmfile,hminvfile,exefile)
cd(tmpfolder)
end
% remember the type of volume conduction model
vol.type = 'openmeeg';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cleaner(vol,bndfile,condfile,geomfile,hmfile,hminvfile,exefile)
% delete the temporary files
for i=1:length(vol.bnd)
delete(bndfile{i})
end
delete(condfile);
delete(geomfile);
delete(hmfile);
delete(hminvfile);
delete(exefile);
|
github | philippboehmsturm/antx-master | normals.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/normals.m | 2,391 | utf_8 | 62a8e5ee7314da0eadbc13fa82ab95c1 | function [nrm] = normals(pnt, dhk, opt);
% NORMALS compute the surface normals of a triangular mesh
% for each triangle or for each vertex
%
% [nrm] = normals(pnt, dhk, 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: normals.m 2885 2011-02-16 09:41:58Z roboos $
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);
ndhk = size(dhk,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_dhk = zeros(ndhk, 3);
for i=1:ndhk
v2 = pnt(dhk(i,2),:) - pnt(dhk(i,1),:);
v3 = pnt(dhk(i,3),:) - pnt(dhk(i,1),:);
nrm_dhk(i,:) = cross(v2, v3);
end
if strcmp(opt, 'vertex')
% compute vertex normals
nrm_pnt = zeros(npnt, 3);
for i=1:ndhk
nrm_pnt(dhk(i,1),:) = nrm_pnt(dhk(i,1),:) + nrm_dhk(i,:);
nrm_pnt(dhk(i,2),:) = nrm_pnt(dhk(i,2),:) + nrm_dhk(i,:);
nrm_pnt(dhk(i,3),:) = nrm_pnt(dhk(i,3),:) + nrm_dhk(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_dhk ./ (sqrt(sum(nrm_dhk.^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 | philippboehmsturm/antx-master | eeg_strip_monopole.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/eeg_strip_monopole.m | 4,395 | utf_8 | 4fb35d2403ec2e536819e85eb6e68f20 | function [lf] = eeg_strip_monopole(rd, elc, vol)
% EEG_STRIP_MONOPOLE calculate the strip medium leadfield
% on positions pnt for a monopole at position rd and conductivity cond
% The halfspace solution requires a plane dividing a conductive zone of
% conductivity cond, from a non coductive zone (cond = 0)
%
% [lf] = eeg_strip_monopole(rd, elc, cond)
%
% Implemented from Malmivuo J, Plonsey R, Bioelectromagnetism (1993)
% http://www.bem.fi/book/index.htm
% Copyright (C) 2011, Cristiano Micheli
%
% This file is part of FieldTrip, see http://www.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: eeg_halfspace_monopole.m $
siz = size(rd);
if any(siz==1)
% positions are specified as a single vector
Npoles = prod(siz)/3;
rd = rd(:)'; % ensure that it is a row vector
elseif siz(2)==3
% positions are specified as a Nx3 matrix -> reformat to a single vector
Npoles = siz(1);
rd = rd';
rd = rd(:)'; % ensure that it is a row vector
else
error('incorrect specification of pole locations');
end
Nelc = size(elc,1);
lf = zeros(Nelc,Npoles);
for i=1:Npoles
% this is the position of dipole "i"
pole1 = rd((1:3) + 3*(i-1));
% distances electrodes - corrent poles
r1 = elc - ones(Nelc,1) * pole1;
% Method of mirror charges:
% Defines the position of mirror charge being symmetric to the plane
[pole2,pole3,pole4] = get_mirror_pos(pole1,vol);
% distances electrodes - mirror charge
r2 = elc - ones(Nelc,1) * pole2;
r3 = elc - ones(Nelc,1) * pole3;
r4 = elc - ones(Nelc,1) * pole4;
% denominator
R1 = (4*pi*vol.cond) * (sum(r1' .^2 ) )';
% denominator, mirror term
R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) )';
% denominator, mirror term of P1, plane 2
R3 = -(4*pi*vol.cond) * (sum(r3' .^2 ) )';
% denominator, mirror term of P2, plane 2
R4 = (4*pi*vol.cond) * (sum(r4' .^2 ) )';
% condition of poles falling in the non conductive halfspace
instrip1 = acos(dot(vol.ori1,(pole1-vol.pnt1)./norm(pole1-vol.pnt1))) > pi/2;
instrip2 = acos(dot(vol.ori2,(pole1-vol.pnt2)./norm(pole1-vol.pnt2))) > pi/2;
invacuum = ~(instrip1&instrip2);
if invacuum
warning('a pole lies on the vacuum side of the plane');
lf(:,i) = NaN(Nelc,1);
elseif any(R1)==0
warning('a pole coincides with one of the electrodes');
lf(:,i) = NaN(Nelc,1);
else
lf(:,i) = (1 ./ R1) + (1 ./ R2) + (1 ./ R3) + (1 ./ R4);
end
end
function [P2,P3,P4] = get_mirror_pos(P1,vol)
% calculates the position of a point symmetric to the pole, with respect to plane1
% and two points symmetric to the last ones, with respect to plane2
P2 = []; P3 = []; P4 = [];
% define the planes
pnt1 = vol.pnt1;
ori1 = vol.ori1;
pnt2 = vol.pnt2;
ori2 = vol.ori2;
if abs(dot(P1-pnt1,ori1))<eps || abs(dot(P1-pnt2,ori2))<eps
warning(sprintf ('point %f %f %f lies on the plane',P1(1),P1(2),P1(3)))
P2 = P1;
else
% define the planes
plane1 = def_plane(pnt1,ori1);
plane2 = def_plane(pnt2,ori2);
% distance plane1-point P1
d = abs(dot(ori1, plane1(:,1:3)-P1(:,1:3), 2));
% symmetric point
P2 = P1 + 2*d*ori1;
% distance plane2-point P1
d = abs(dot(ori2, plane2(:,1:3)-P1(:,1:3), 2));
% symmetric point
P3 = P1 + 2*d*ori2;
% distance plane2-point P2
d = abs(dot(ori2, plane2(:,1:3)-P2(:,1:3), 2));
% symmetric point
P4 = P2 + 2*d*ori2;
end
function plane = def_plane(pnt,ori)
% define the plane in parametric form
% define a non colinear vector vc with respect to the plane normal
vc = [1 0 0];
if abs(cross(ori, vc, 2))<eps
vc = [0 1 0];
end
% define plane's direction vectors
v1 = cross(ori, vc, 2); v1 = v1/norm(v1);
v2 = cross(pnt, ori, 2); v2 = v2/norm(v2);
plane = [pnt v1 v2];
|
github | philippboehmsturm/antx-master | meg_ini.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/meg_ini.m | 5,611 | utf_8 | d8c7a9c1bd90cd1d1c39b272bdd93c23 | function forwpar=meg_ini(vc,center,order,sens,refs,gradlocs,weights);
% initializes MEG-forward calculation
% usage: forwpar=meg_ini(vc,center,order,sens,refs,gradlocs,weights);
%
% input:
% vc: Nx6 matrix; N is the number of surface points
% the first three numbers in each row are the location
% and the second three are the orientation of the surface
% normal
% center: 3x1 vector denoting the center of volume the conductor
% order: desired order of spherical spherical harmonics;
% for 'real' realistic volume conductors order=10 is o.k
% sens: Mx6 matrix containing sensor location and orientation,
% format as for vc
% refs: optional argument. If provided, refs contains the location and oriantion
% (format as sens) of additional sensors which are subtracted from the original
% ones. This makes a gradiometer. One can also do this with the
% magnetometer version of this program und do the subtraction outside this program,
% but the gradiometer version is faster.
% gradlocs, weights: optional two arguments (they must come together!).
% gradlocs are the location of additional channels (e.g. to calculate
% a higher order gradiometer) and weights. The i.th row in weights contains
% the weights to correct if the i.th cannel. These extra fields are added!
% (has historical reasons).
%
% output:
% forpwar: structure containing all parameters needed for forward
% calculation
% note: it is assumed that locations are in cm.
% Copyright (C) 2003, Guido Nolte
%
% This file is part of FieldTrip, see http://www.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: meg_ini.m 3572 2011-05-24 10:12:03Z vlalit $
if nargin==4
if order>0;
coeff_sens=getcoeffs(sens,vc,center,order);
forwpar=struct('device_sens',sens,'coeff_sens',coeff_sens,'center',center,'order',order);
else
forwpar=struct('device_sens',sens,'center',center,'order',order);
end
elseif nargin==5
if order>0;
coeff_sens=getcoeffs(sens,vc,center,order);
coeff_refs=getcoeffs(refs,vc,center,order);
forwpar=struct('device_sens',sens,'device_ref',refs,'coeff_sens',coeff_sens,'coeff_ref',coeff_refs,'center',center,'order',order);
else
forwpar=struct('device_sens',sens,'device_ref',refs,'center',center,'order',order);
end
elseif nargin==7;
if order>0;
coeff_sens=getcoeffs(sens,vc,center,order);
coeff_refs=getcoeffs(refs,vc,center,order);
coeff_weights=getcoeffs(gradlocs,vc,center,order);
forwpar=struct('device_sens',sens,'device_ref',refs,'coeff_sens',coeff_sens,...
'coeff_ref',coeff_refs,'center',center,'order',order,...
'device_weights',gradlocs,'coeff_weights',coeff_weights,'weights',weights);
else
forwpar=struct('device_sens',sens,'device_ref',refs,'center',center,'order',order,...
'device_weights',gradlocs,'weights',weights);
end
else
error('you must provide 4,5 or 7 arguments');
end
return
function coeffs=getcoeffs(device,vc,center,order)
[ndip,ndum]=size(vc);
[nchan,ndum]=size(device);
x1=vc(:,1:3)-repmat(center',ndip,1);
n1=vc(:,4:6);
x2=device(:,1:3)-repmat(center',nchan,1);;
n2=device(:,4:6);
scale=10;
nbasis=(order+1)^2-1;
[bas,gradbas]=legs(x1,n1,order,scale);
bt=leadsphere_all(x1',x2',n2');
n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan);
b=dotproduct(n1rep,bt);
ctc=gradbas'*gradbas;
warning('OFF', 'MATLAB:nearlySingularMatrix');
coeffs=inv(ctc)*gradbas'*b;
warning('ON', 'MATLAB:nearlySingularMatrix');
return
function field=getfield(source,device,coeffs,center,order);
[ndip,ndum]=size(source);
[nchan,ndum]=size(device);
x1=source(:,1:3)-repmat(center',ndip,1);
n1=source(:,4:6);
x2=device(:,1:3)-repmat(center',nchan,1);;
n2=device(:,4:6);
%spherical
bt=leadsphere_all(x1',x2',n2');
n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan);
b=dotproduct(n1rep,bt);
field=b';
%correction
if order>0
scale=10;
[bas,gradbas]=legs(x1,n1,order,scale);
nbasis=(order+1)^2-1;
coeffs=coeffs(1:nbasis,:);
fcorr=gradbas*coeffs;
field=field-fcorr';
end
return
function out=crossproduct(x,y)
% usage: out=testprog(x,y)
% testprog calculates the cross-product of vector x and y
[n,m,k]=size(x);
out=zeros(3,m,k);
out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:);
out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:);
out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:);
return;
function out=dotproduct(x,y)
% usage: out=dotproduct(x,y)
% testprog calculates the dotproduct of vector x and y
[n,m,k]=size(x);
outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:);
out=reshape(outb,m,k);
return;
function result=norms(x);
[n,m,k]=size(x);
resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2);
result=reshape(resultb,m,k);
return;
|
github | philippboehmsturm/antx-master | eeg_halfspace_monopole.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/eeg_halfspace_monopole.m | 3,498 | utf_8 | 205ef9db3761f4010b438ba0b13e1d39 | function [lf] = eeg_halfspace_monopole(rd, elc, vol)
% EEG_HALFSPACE_MONOPOLE calculate the halfspace medium leadfield
% on positions pnt for a monopole at position rd and conductivity cond
% The halfspace solution requires a plane dividing a conductive zone of
% conductivity cond, from a non coductive zone (cond = 0)
%
% [lf] = eeg_halfspace_monopole(rd, elc, cond)
%
% Implemented from Malmivuo J, Plonsey R, Bioelectromagnetism (1993)
% http://www.bem.fi/book/index.htm
% Copyright (C) 2011, Cristiano Micheli
%
% This file is part of FieldTrip, see http://www.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: eeg_halfspace_monopole.m $
siz = size(rd);
if any(siz==1)
% positions are specified as a single vector
Npoles = prod(siz)/3;
rd = rd(:)'; % ensure that it is a row vector
elseif siz(2)==3
% positions are specified as a Nx3 matrix -> reformat to a single vector
Npoles = siz(1);
rd = rd';
rd = rd(:)'; % ensure that it is a row vector
else
error('incorrect specification of dipole locations');
end
Nelc = size(elc,1);
lf = zeros(Nelc,Npoles);
for i=1:Npoles
% this is the position of dipole "i"
pole1 = rd((1:3) + 3*(i-1));
% distances electrodes - corrent poles
r1 = elc - ones(Nelc,1) * pole1;
% Method of mirror charges:
% Defines the position of mirror charge being symmetric to the plane
pole2 = get_mirror_pos(pole1,vol);
% distances electrodes - mirror charge
r2 = elc - ones(Nelc,1) * pole2;
% denominator
R1 = (4*pi*vol.cond) * (sum(r1' .^2 ) )';
% denominator, mirror term
R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) )';
% condition of poles falling in the non conductive halfspace
invacuum = acos(dot(vol.ori,(pole1-vol.pnt)./norm(pole1-vol.pnt))) < pi/2;
if invacuum
warning('a pole lies on the vacuum side of the plane');
lf(:,i) = NaN(Nelc,1);
elseif any(R1)==0
warning('a pole coincides with one of the electrodes');
lf(:,i) = NaN(Nelc,1);
else
lf(:,i) = (1 ./ R1) + (1 ./ R2);
end
end
function P2 = get_mirror_pos(P1,vol)
% calculates the position of a point symmetric to pnt with respect to a plane
P2 = [];
% define the plane
pnt = vol.pnt;
ori = vol.ori; % already normalized
if abs(dot(P1-pnt,ori))<eps
warning(sprintf ('point %f %f %f lies in the symmetry plane',P1(1),P1(2),P1(3)))
P2 = P1;
else
% define the plane in parametric form
% define a non colinear vector vc with respect to the plane normal
vc = [1 0 0];
if abs(cross(ori, vc, 2))<eps
vc = [0 1 0];
end
% define plane's direction vectors
v1 = cross(ori, vc, 2); v1 = v1/norm(v1);
v2 = cross(pnt, ori, 2); v2 = v2/norm(v2);
plane = [pnt v1 v2];
% distance plane-point P1
d = abs(dot(ori, plane(:,1:3)-P1(:,1:3), 2));
% symmetric point
P2 = P1 + 2*d*ori;
end
|
github | philippboehmsturm/antx-master | leadfield_simbio.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/leadfield_simbio.m | 3,228 | utf_8 | 7f93a28d3282bf7918e8ab6e9cf3fe75 | function [lf] = leadfield_simbio(elc, vol, dip)
% LEADFIELD_SIMBIO leadfields for a set of dipoles
%
% [lf] = leadfield_simbio(elc, vol, headmeshfile);
%
% with input arguments
% elc positions of the electrodes (matrix of dimensions MX3)
% vol.brainmesh contains the positions of the vertices on which
% the potentials are calculated
% vol.headmesh contains the position of the vertices of the 'head mesh'
% which is needed to perform a FEM analysis, and an integer
% number.
% This is the output of a step in which from a labelled MRI a
% volumetric mesh of points is generated, and a label (or compartment)
% is assigned to each point
%
% The output lf is the leadfields matrix of dimensions M (rows) X N*3 (cols)
% Copyright (C) 2011, Cristiano Micheli
% store the current path and change folder to the temporary one
tmpfolder = cd;
try
if ~ispc
cd(tempdir)
[junk,tname] = fileparts(tempname);
exefile = [tname '.sh'];
[junk,tname] = fileparts(tempname);
elcfile = [tname '.elc'];
[junk,tname] = fileparts(tempname);
dipfile = [tname '.dip'];
[junk,tname] = fileparts(tempname);
parfile = [tname '.par'];
[junk,tname] = fileparts(tempname);
outfile = [tname];
% write the electrodes and dipoles positions in the temporary folder
disp('Writing the accessory files on disk...')
sb_write_elc(elc.pnt,elc.label,elcfile);
sb_write_dip(dip,dipfile);
% writes the parameters file
cfg = [];
cfg.cond = vol.cond;
cfg.labels = vol.labels;
sb_write_par(cfg,parfile);
% FIXME: vol in future will contain the mesh as well (right?)
% at the moment contains only a name of the vista file for memory
% reasons (vol.headmesh)
% Exe file
% FIXME: does SimBio have a switch for parallel processing (to run on more cores)?
efid = fopen(exefile, 'w');
if ~ispc
fprintf(efid,'#!/usr/bin/env bash\n');
% fprintf(efid,['ipm_linux_opt_Venant -i leadfieldmatrix_onbrainsurface -h ' vol.headmesh ' -s ./' elcfile, ...
% ' -g ' vol.brainmesh ' -leadfieldfile ' outfile ' -p ' parfile ' -fwd FEM -sens EEG 2>&1 > /dev/null\n']);
fprintf(efid,['ipm_linux_opt_Venant -i sourcesimulation -h ' vol.headmesh ' -s ./' elcfile, ...
' -dip ' dipfile ' -o ' outfile ' -p ' parfile ' -fwd FEM -sens EEG 2>&1 > /dev/null\n']);
end
fclose(efid);
dos(sprintf('chmod +x %s', exefile));
disp('SimBio is calculating the LeadFields, this may take some time ...')
stopwatch = tic;
dos(['./' exefile]);
disp([ 'elapsed time: ' num2str(toc(stopwatch)) ])
[lf] = sb_read_msr(outfile);
cleaner(dipfile,elcfile,outfile,exefile)
cd(tmpfolder)
end
catch
warning('an error occurred while running SimBio');
rethrow(lasterror)
cleaner(dipfile,elcfile,outfile,exefile)
cd(tmpfolder)
end
function cleaner(dipfile,elcfile,outfile,exefile)
delete(dipfile);
delete(elcfile);
delete(outfile);
delete(exefile);
delete([outfile '.fld']);
delete([outfile '.hex']);
delete([outfile '.pot']);
delete([outfile '.pts']);
delete(['*.v.ascii']);
delete(['*.v.potential']);
|
github | philippboehmsturm/antx-master | eeg_halfspace_medium_leadfield.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/eeg_halfspace_medium_leadfield.m | 3,539 | utf_8 | e8302f95ed59664fe0e90e561ed87e8c | function [lf] = eeg_halfspace_medium_leadfield(rd, elc, vol)
% HALFSPACE_MEDIUM_LEADFIELD calculate the halfspace medium leadfield
% on positions pnt for a dipole at position rd and conductivity cond
% The halfspace solution requires a plane dividing a conductive zone of
% conductivity cond, from a non coductive zone (cond = 0)
%
% [lf] = halfspace_medium_leadfield(rd, elc, cond)
% Copyright (C) 2011, Cristiano Micheli and Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.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: eeg_halfspace_medium_leadfield.m 3895 2011-07-24 15:16:53Z crimic $
siz = size(rd);
if any(siz==1)
% positions are specified as a single vector
Ndipoles = prod(siz)/3;
rd = rd(:)'; % ensure that it is a row vector
elseif siz(2)==3
% positions are specified as a Nx3 matrix -> reformat to a single vector
Ndipoles = siz(1);
rd = rd';
rd = rd(:)'; % ensure that it is a row vector
else
error('incorrect specification of dipole locations');
end
Nelc = size(elc,1);
lf = zeros(Nelc,3*Ndipoles);
for i=1:Ndipoles
% this is the position of dipole "i"
dip1 = rd((1:3) + 3*(i-1));
% distances electrodes - dipole
r1 = elc - ones(Nelc,1) * dip1;
% Method of mirror dipoles:
% Defines the position of mirror dipoles being symmetric to the plane
dip2 = get_mirror_pos(dip1,vol);
% distances electrodes - mirror dipole
r2 = elc - ones(Nelc,1) * dip2;
% denominator
R1 = (4*pi*vol.cond) * (sum(r1' .^2 ) .^ 1.5)';
% denominator, mirror term
R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) .^ 1.5)';
% condition of dipoles falling in the non conductive halfspace
invacuum = acos(dot(vol.ori,(dip1-vol.pnt)./norm(dip1-vol.pnt))) < pi/2;
if invacuum
warning('dipole lies on the vacuum side of the plane');
lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3);
elseif any(R1)==0
warning('dipole coincides with one of the electrodes');
lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3);
else
lf(:,(1:3) + 3*(i-1)) = (r1 ./ [R1 R1 R1]) + (r2 ./ [R2 R2 R2]);
end
end
function P2 = get_mirror_pos(P1,vol)
% calculates the position of a point symmetric to pnt with respect to a plane
P2 = [];
% define the plane
pnt = vol.pnt;
ori = vol.ori; % already normalized
if abs(dot(P1-pnt,ori))<eps
warning(sprintf ('point %f %f %f lies in the symmetry plane',P1(1),P1(2),P1(3)))
P2 = P1;
else
% define the plane in parametric form
% define a non colinear vector vc with respect to the plane normal
vc = [1 0 0];
if abs(cross(ori, vc, 2))<eps
vc = [0 1 0];
end
% define plane's direction vectors
v1 = cross(ori, vc, 2); v1 = v1/norm(v1);
v2 = cross(pnt, ori, 2); v2 = v2/norm(v2);
plane = [pnt v1 v2];
% distance plane-point P1
d = abs(dot(ori, plane(:,1:3)-P1(:,1:3), 2));
% symmetric point
P2 = P1 + 2*d*ori;
end
|
github | philippboehmsturm/antx-master | leadsphere_all.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/leadsphere_all.m | 2,351 | utf_8 | ec11c3c091e69a549689e1fa8755ad50 | function out=leadsphere_chans(xloc,sensorloc,sensorori)
% usage: out=leadsphere_chans(xloc,sensorloc,sensorori)
% Copyright (C) 2003, Guido Nolte
%
% This file is part of FieldTrip, see http://www.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: leadsphere_all.m 2885 2011-02-16 09:41:58Z roboos $
[n,nsens]=size(sensorloc); %n=3 m=?
[n,ndip]=size(xloc);
xlocrep=reshape(repmat(xloc,1,nsens),3,ndip,nsens);
sensorlocrep=reshape(repmat(sensorloc,ndip,1),3,ndip,nsens);
sensororirep=reshape(repmat(sensorori,ndip,1),3,ndip,nsens);
r2=norms(sensorlocrep);
veca=sensorlocrep-xlocrep;
a=norms(veca);
adotr2=dotproduct(veca,sensorlocrep);
gradf1=scal2vec(1./r2.*(a.^2)+adotr2./a+2*a+2*r2);
gradf2=scal2vec(a+2*r2+adotr2./a);
gradf=gradf1.*sensorlocrep-gradf2.*xlocrep;
F=a.*(r2.*a+adotr2);
A1=scal2vec(1./F);
A2=A1.^2;
A3=crossproduct(xlocrep,sensororirep);
A4=scal2vec(dotproduct(gradf,sensororirep));
A5=crossproduct(xlocrep,sensorlocrep);
out=1e-7*(A3.*A1-(A4.*A2).*A5); %%GRB change
return;
function out=crossproduct(x,y)
[n,m,k]=size(x);
out=zeros(3,m,k);
out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:);
out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:);
out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:);
return;
function out=dotproduct(x,y)
[n,m,k]=size(x);
outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:);
out=reshape(outb,m,k);
return;
function result=norms(x)
[n,m,k]=size(x);
resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2);
result=reshape(resultb,m,k);
return;
function result=scal2vec(x)
[m,k]=size(x);
% result=zeros(3,m,k);
% for i=1:3
% result(i,:,:)=x;
% end
result=reshape(repmat(x(:)', [3 1]), [3 m k]);
return
|
github | philippboehmsturm/antx-master | ft_hastoolbox.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/ft_hastoolbox.m | 15,262 | utf_8 | c0b501e52231cc82315936a092af6214 | function [status] = ft_hastoolbox(toolbox, autoadd, silent)
% FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally
% it will try to determine the path to the toolbox and install it
% automatically.
%
% Use as
% [status] = ft_hastoolbox(toolbox, autoadd, silent)
%
% autoadd = 0 means that it will not be added
% autoadd = 1 means that give an error if it cannot be added
% autoadd = 2 means that give a warning if it cannot be added
% autoadd = 3 means that it remains silent if it cannot be added
%
% silent = 0 means that it will give some feedback about adding the toolbox
% silent = 1 means that it will not give feedback
% Copyright (C) 2005-2010, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_hastoolbox.m 3873 2011-07-19 14:23:16Z tilsan $
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
persistent previous previouspath
if ~isequal(previouspath, path)
previous = [];
end
if isempty(previous)
previous = struct;
elseif isfield(previous, fixname(toolbox))
status = previous.(fixname(toolbox));
return
end
% this points the user to the website where he/she can download the toolbox
url = {
'AFNI' 'see http://afni.nimh.nih.gov'
'DSS' 'see http://www.cis.hut.fi/projects/dss'
'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab'
'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox'
'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm'
'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd'
'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com'
'BIOSIG' 'see http://biosig.sourceforge.net'
'EEG' 'see http://eeg.sourceforge.net'
'EEGSF' 'see http://eeg.sourceforge.net' % alternative name
'MRI' 'see http://eeg.sourceforge.net' % alternative name
'NEUROSHARE' 'see http://www.neuroshare.org'
'BESA' 'see http://www.megis.de, or contact Karsten Hoechstetter'
'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde'
'YOKOGAWA' 'see http://www.yokogawa.co.jp, or contact Nobuhiko Takahashi'
'YOKOGAWA_MEG_READER' 'contact Masayuki dot Mochiduki at jp.yokogawa.com'
'BEOWULF' 'see http://oostenveld.net, or contact Robert Oostenveld'
'MENTAT' 'see http://oostenveld.net, or contact Robert Oostenveld'
'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth'
'4D-VERSION' 'contact Christian Wienbruch'
'SIGNAL' 'see http://www.mathworks.com/products/signal'
'OPTIM' 'see http://www.mathworks.com/products/optim'
'IMAGE' 'see http://www.mathworks.com/products/image'
'SPLINES' 'see http://www.mathworks.com/products/splines'
'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica'
'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm'
'FILEIO' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'FORWINV' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne'
'BCI2000' 'see http://bci2000.org'
'NLXNETCOM' 'see http://www.neuralynx.com'
'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external'
'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php'
'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydes?ter'
'BEMCP' 'contact Christophe Phillips'
'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435'
'PRTOOLS' 'see http://www.prtools.org'
'ITAB' 'contact Stefania Della Penna'
'BSMART' 'see http://www.brain-smart.org'
'PEER' 'see http://fieldtrip.fcdonders.nl/development/peer'
'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki'
'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page'
'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS'
'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti'
'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0'
'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab'
'BCT' 'see http://www.brain-connectivity-toolbox.net/'
};
if nargin<2
% default is not to add the path automatically
autoadd = 0;
end
if nargin<3
% default is not to be silent
silent = 0;
end
% determine whether the toolbox is installed
toolbox = upper(toolbox);
switch toolbox
case 'AFNI'
status = (exist('BrikLoad') && exist('BrikInfo'));
case 'DSS'
status = exist('denss', 'file') && exist('dss_create_state', 'file');
case 'EEGLAB'
status = exist('runica', 'file');
case 'NWAY'
status = exist('parafac', 'file');
case 'SPM'
status = exist('spm.m'); % any version of SPM is fine
case 'SPM99'
status = exist('spm.m') && strcmp(spm('ver'),'SPM99');
case 'SPM2'
status = exist('spm.m') && strcmp(spm('ver'),'SPM2');
case 'SPM5'
status = exist('spm.m') && strcmp(spm('ver'),'SPM5');
case 'SPM8'
status = exist('spm.m') && strncmp(spm('ver'),'SPM8', 4);
case 'MEG-PD'
status = (exist('rawdata') && exist('channames'));
case 'MEG-CALC'
status = (exist('megmodel') && exist('megfield') && exist('megtrans'));
case 'BIOSIG'
status = (exist('sopen') && exist('sread'));
case 'EEG'
status = (exist('ctf_read_res4') && exist('ctf_read_meg4'));
case 'EEGSF' % alternative name
status = (exist('ctf_read_res4') && exist('ctf_read_meg4'));
case 'MRI' % other functions in the mri section
status = (exist('avw_hdr_read') && exist('avw_img_read'));
case 'NEUROSHARE'
status = (exist('ns_OpenFile') && exist('ns_SetLibrary') && exist('ns_GetAnalogData'));
case 'BESA'
status = (exist('readBESAtfc') && exist('readBESAswf'));
case 'EEPROBE'
status = (exist('read_eep_avr') && exist('read_eep_cnt'));
case 'YOKOGAWA'
status = (exist('hasyokogawa') && hasyokogawa('16bitBeta6'));
case 'YOKOGAWA16BITBETA3'
status = (exist('hasyokogawa') && hasyokogawa('16bitBeta3'));
case 'YOKOGAWA16BITBETA6'
status = (exist('hasyokogawa') && hasyokogawa('16bitBeta6'));
case 'YOKOGAWA_MEG_READER'
status = (exist('hasyokogawa') && hasyokogawa('1.4'));
case 'BEOWULF'
status = (exist('evalwulf') && exist('evalwulf') && exist('evalwulf'));
case 'MENTAT'
status = (exist('pcompile') && exist('pfor') && exist('peval'));
case 'SON2'
status = (exist('SONFileHeader') && exist('SONChanList') && exist('SONGetChannel'));
case '4D-VERSION'
status = (exist('read4d') && exist('read4dhdr'));
case {'STATS', 'STATISTICS'}
status = license('checkout', 'statistics_toolbox'); % also check the availability of a toolbox license
case {'OPTIM', 'OPTIMIZATION'}
status = license('checkout', 'optimization_toolbox'); % also check the availability of a toolbox license
case {'SPLINES', 'CURVE_FITTING'}
status = license('checkout', 'curve_fitting_toolbox'); % also check the availability of a toolbox license
case 'SIGNAL'
status = license('checkout', 'signal_toolbox'); % also check the availability of a toolbox license
case 'IMAGE'
status = license('checkout', 'image_toolbox'); % also check the availability of a toolbox license
case 'DCT'
status = license('checkout', 'distrib_computing_toolbox'); % also check the availability of a toolbox license
case 'FASTICA'
status = exist('fastica', 'file');
case 'BRAINSTORM'
status = exist('bem_xfer');
case 'FILEIO'
status = (exist('ft_read_header') && exist('ft_read_data') && exist('ft_read_event') && exist('ft_read_sens'));
case 'FORMWARD'
status = (exist('ft_compute_leadfield') && exist('ft_prepare_vol_sens'));
case 'DENOISE'
status = (exist('tsr') && exist('sns'));
case 'CTF'
status = (exist('getCTFBalanceCoefs') && exist('getCTFdata'));
case 'BCI2000'
status = exist('load_bcidat');
case 'NLXNETCOM'
status = (exist('MatlabNetComClient') && exist('NlxConnectToServer') && exist('NlxGetNewCSCData'));
case 'DIPOLI'
status = exist('dipoli.m', 'file');
case 'MNE'
status = (exist('fiff_read_meas_info', 'file') && exist('fiff_setup_read_raw', 'file'));
case 'TCP_UDP_IP'
status = (exist('pnet', 'file') && exist('pnet_getvar', 'file') && exist('pnet_putvar', 'file'));
case 'BEMCP'
status = (exist('bem_Cij_cog', 'file') && exist('bem_Cij_lin', 'file') && exist('bem_Cij_cst', 'file'));
case 'OPENMEEG'
status = exist('openmeeg.m', 'file');
case 'PLOTTING'
status = (exist('ft_plot_topo', 'file') && exist('ft_plot_mesh', 'file') && exist('ft_plot_matrix', 'file'));
case 'PRTOOLS'
status = (exist('prversion', 'file') && exist('dataset', 'file') && exist('svc', 'file'));
case 'ITAB'
status = (exist('lcReadHeader', 'file') && exist('lcReadData', 'file'));
case 'BSMART'
status = exist('bsmart');
case 'PEER'
status = exist('peerslave', 'file') && exist('peermaster', 'file');
case 'CONNECTIVITY'
status = exist('ft_connectivity_corr', 'file') && exist('ft_connectivity_granger', 'file');
case 'FREESURFER'
status = exist('MRIread', 'file') && exist('vox2ras_0to1', 'file');
case 'FNS'
status = exist('elecsfwd', 'file') && exist('img_get_gray', 'file');
case 'SIMBIO'
status = exist('ipm_linux_opt_Venant', 'file');
case 'GIFTI'
status = exist('gifti', 'file');
case 'XML4MAT'
status = exist('xml2struct.m', 'file') && exist('xml2whos.m', 'file');
case 'SQDPROJECT'
status = exist('sqdread.m', 'file') && exist('sqdwrite.m', 'file');
case 'BCT'
status = exist('macaque71.mat', 'file') && exist('motif4funct_wei.m', 'file');
otherwise
if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end
status = 0;
end
% it should be a boolean value
status = (status~=0);
% try to determine the path of the requested toolbox
if autoadd>0 && ~status
% for core fieldtrip modules
prefix = fileparts(which('ft_defaults'));
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for external fieldtrip modules
prefix = fullfile(fileparts(which('ft_defaults')), 'external');
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
licensefile = [lower(toolbox) '_license'];
if status && exist(licensefile, 'file')
% this will execute openmeeg_license and mne_license
% which display the license on screen for three seconds
feval(licensefile);
end
end
% for linux computers in the F.C. Donders Centre
prefix = '/home/common/matlab';
if ~status && (strcmp(computer, 'GLNX86') || strcmp(computer, 'GLNXA64'))
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for windows computers in the F.C. Donders Centre
prefix = 'h:\common\matlab';
if ~status && (strcmp(computer, 'PCWIN') || strcmp(computer, 'PCWIN64'))
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% use the matlab subdirectory in your homedirectory, this works on unix and mac
prefix = [getenv('HOME') '/matlab'];
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
if ~status
% the toolbox is not on the path and cannot be added
sel = find(strcmp(url(:,1), toolbox));
if ~isempty(sel)
msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2});
else
msg = sprintf('the %s toolbox is not installed', toolbox);
end
if autoadd==1
error(msg);
elseif autoadd==2
warning(msg);
else
% fail silently
end
end
end
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
if status
previous.(fixname(toolbox)) = status;
end
% remember the previous path, allows us to determine on the next call
% whether the path has been modified outise of this function
previouspath = path;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = myaddpath(toolbox, silent)
if exist(toolbox, 'dir')
if ~silent,
ws = warning('backtrace', 'off');
warning('adding %s toolbox to your Matlab path', toolbox);
warning(ws); % return to the previous warning level
end
addpath(toolbox);
status = 1;
else
status = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = fixname(toolbox)
out = lower(toolbox);
out(out=='-') = '_'; % fix dashes
out(out==' ') = '_'; % fix spaces
out(out=='/') = '_'; % fix forward slashes
out(out=='\') = '_'; % fix backward slashes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = hasfunction(funname, toolbox)
try
% call the function without any input arguments, which probably is inapropriate
feval(funname);
% it might be that the function without any input already works fine
status = true;
catch
% either the function returned an error, or the function is not available
% availability is influenced by the function being present and by having a
% license for the function, i.e. in a concurrent licensing setting it might
% be that all toolbox licenses are in use
m = lasterror;
if strcmp(m.identifier, 'MATLAB:license:checkouterror')
if nargin>1
warning('the %s toolbox is available, but you don''t have a license for it', toolbox);
else
warning('the function ''%s'' is available, but you don''t have a license for it', funname);
end
status = false;
elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction')
status = false;
else
% the function seems to be available and it gave an unknown error,
% which is to be expected with inappropriate input arguments
status = true;
end
end
|
github | philippboehmsturm/antx-master | leadfield_fns.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/leadfield_fns.m | 3,098 | utf_8 | b87f422810a9225ac5355f1190953a51 | function [lf] = leadfield_fns(dip, elc, vol)
% LEADFIELD_FNS leadfields for a set of dipoles
%
% [lf] = leadfield_fns(dip, elc, vol);
%
% with input arguments
% dip positions of the dipoles (matrix of dimensions NX3)
% elc positions of the electrodes (matrix of dimensions MX3)
%
% and vol being a structure with the element
% vol.meshfile file containing the 3D mesh filename
%
% The output lf is the leadfields matrix of dimensions M (rows) X N*3 (cols)
% Copyright (C) 2011, Cristiano Micheli and Hung Dang
% store the current path and change folder to the temporary one
tmpfolder = cd;
if ft_senstype(elc, 'meg')
error('FNS solver works for EEG data only!')
end
try
if ~ispc
cd(tempdir)
[junk,tname] = fileparts(tempname);
exefile = [tname '.sh'];
[junk,tname] = fileparts(tempname);
elecfile = [tname '.h5'];
[junk,tname] = fileparts(tempname);
confile = [tname '.csv'];
[junk,tname] = fileparts(tempname);
datafile = [tname '.h5'];
tolerance = 1e-8; % FIXME: initialize as input argument
% write the electrodes positions and the conductivity file in the temporary folder
fns_elec_write(elc.pnt,vsize,dimpos,elecfile); % FIXME: this does not work yet
fns_contable_write(vol.cond,confile);
% fns_write_dip(dip,dipfile); % FNS ideally this should work like this!
% Exe file
% FIXME: does FNS have a switch for parallel processing (to run on more cores)?
efid = fopen(exefile, 'w');
if ~ispc
fprintf(efid,'#!/usr/bin/env bash\n');
fprintf(efid,['elecsfwd --img ' vol.segfile ' --electrodes ./' elecfile ' --data ./', ...
datafile ' --contable ./' confile ' --TOL ' num2str(tolerance) ' 2>&1 > /dev/null\n']);
end
fclose(efid);
dos(sprintf('chmod +x %s', exefile));
dos(['./' exefile]);
cleaner(elecfile,datafile,confile,exefile)
% FNS calculates all solutions in all nodes (=voxels) at a time
% the following operations extract the system matrix solution for gray
% matter (FIXME: this code needs revision from FNS party)
[junk,tname] = fileparts(tempname);
regfile = [tname '.h5'];
exestr = sprintf('./img_get_gray --img %s --rgn %s',vol.segfile,regfile);
system(exestr)
% The following code extracts the matrix and uses it to calculate the
% leadfields
% FIXME: this code needs revision
[junk,tname] = fileparts(tempname);
recipfile = [tname '.h5'];
exestr = sprintf('./extract_data --data %s --rgn %s --newdata %s',datafile,regfile,recipfile);
system(exestr)
[data,compress,gridlocs,node_sizes,voxel_sizes] = fns_read_recipdata(recipfile);
[lf] = fns_leadfield(data,compress,node_sizes,dip);
cd(tmpfolder)
end
catch
warning('an error occurred while running FNS');
rethrow(lasterror)
cleaner(dipfile,elcfile,outfile,exefile)
cd(tmpfolder)
end
function cleaner(elecfile,datafile,confile,exefile,regfile,recipfile)
delete(elecfile);
delete(datafile);
delete(confile);
delete(exefile);
delete(regfile);
delete(recipfile);
|
github | philippboehmsturm/antx-master | eeg_leadfield1.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/eeg_leadfield1.m | 3,861 | utf_8 | 1fb67278560820b9d4d494e6eebc6e78 | function [lf, lforig] = eeg_leadfield1(R, elc, vol);
% EEG_LEADFIELD1 electric leadfield for a dipole in a single sphere
%
% [lf] = eeg_leadfield1(R, elc, vol)
%
% with input arguments
% R position dipole (vector of length 3)
% elc position electrodes
% and vol being a structure with the elements
% vol.r radius of sphere
% vol.c conductivity of sphere
% Copyright (C) 2002, Robert Oostenveld
%
% this implementation is adapted from
% Luetkenhoener, Habilschrift '92
% the original reference is
% R. Kavanagh, T. M. Darccey, D. Lehmann, and D. H. Fender. Evaluation of methods for three-dimensional localization of electric sources in the human brain. IEEE Trans Biomed Eng, 25:421-429, 1978.
%
% 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: eeg_leadfield1.m 946 2010-04-21 17:51:16Z roboos $
Nchans = size(elc, 1);
lf = zeros(Nchans,3);
% always take the outermost sphere, this makes comparison with the 4-sphere computation easier
[vol.r, indx] = max(vol.r);
vol.c = vol.c(indx);
% check whether the electrode ly on the sphere, allowing 0.5% tolerance
dist = sqrt(sum(elc.^2,2));
if any(abs(dist-vol.r)>vol.r*0.005)
warning('electrodes do not ly on sphere surface -> using projection')
end
elc = vol.r * elc ./ [dist dist dist];
% check whether the dipole is inside the brain [disabled for EEGLAB]
% if sqrt(sum(R.^2))>=vol.r
% error('dipole is outside the brain compartment');
% end
c0 = norm(R);
c1 = vol.r;
c2 = 4*pi*c0^2*vol.c;
if c0==0
% the dipole is in the origin, this can and should be handeled as an exception
[phi, el] = cart2sph(elc(:,1), elc(:,2), elc(:,3));
theta = pi/2 - el;
lf(:,1) = sin(theta).*cos(phi);
lf(:,2) = sin(theta).*sin(phi);
lf(:,3) = cos(theta);
% the potential in a homogenous sphere is three times the infinite medium potential
lf = 3/(c1^2*4*pi*vol.c)*lf;
else
for i=1:Nchans
% use another name for the electrode, in accordance with lutkenhoner1992
r = elc(i,:);
c3 = r-R;
c4 = norm(c3);
c5 = c1^2 * c0^2 - dot(r,R)^2; % lutkenhoner A.11
c6 = c0^2*r - dot(r,R)*R; % lutkenhoner, just after A.17
% the original code reads (cf. lutkenhoner1992 equation A.17)
% lf(i,:) = ((dot(R, r/norm(r) - (r-R)/norm(r-R))/(norm(cross(r,R))^2) + 2/(norm(r-R)^3)) * cross(R, cross(r, R)) + ((norm(r)^2-norm(R)^2)/(norm(r-R)^3) - 1/norm(r)) * R) / (4*pi*vol.c(1)*norm(R)^2);
% but more efficient execution of the code is achieved by some precomputations
if c5<1000*eps
% the dipole lies on a single line with the electrode
lf(i,:) = (2/c4^3 * c6 + ((c1^2-c0^2)/c4^3 - 1/c1) * R) / c2;
else
% nothing wrong, do the complete computation
lf(i,:) = ((dot(R, r/c1 - c3/c4)/c5 + 2/c4^3) * c6 + ((c1^2-c0^2)/c4^3 - 1/c1) * R) / c2;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fast cross product
function [c] = cross(a,b)
c = [a(2)*b(3)-a(3)*b(2) a(3)*b(1)-a(1)*b(3) a(1)*b(2)-a(2)*b(1)];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fast dot product
function [c] = dot(a,b)
c = sum(a.*b);
|
github | philippboehmsturm/antx-master | meg_forward.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/forward/private/meg_forward.m | 4,039 | utf_8 | 5ff9ecca3fb32155e35f2b871bc533fc | function field=meg_forward(dip_par,forwpar)
% calculates the magnetic field of n dipoles
% in a realistic volume conductor
% usage: field=meg_forward(dip_par,forwpar)
%
% input:
% dip_par nx6 matrix where each row contains location (first 3 numbers)
% and moment (second 3 numbers) of a dipole
% forwpar structure containing all information relevant for this
% calculation; forwpar is calculated with meg_ini
% You have here an option to include linear transformations in
% the forward model by specifying forpwar.lintrafo=A
% where A is an NxM matrix. Then field -> A field
% You can use that, e.g., if you can write the forward model
% with M magnetometer-channels plus a matrix multiplication
% transforming this to a (eventually higher order) gradiometer.
%
% output:
% field mxn matrix where the i.th column is the field in m channels
% of the i.th dipole
%
% note: No assumptions about units made (i.e. no scaling factors)
%
% Copyright (C) 2003, Guido Nolte
%
% 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: meg_forward.m 2885 2011-02-16 09:41:58Z roboos $
device_sens=forwpar.device_sens;
field_sens_sphere=getfield_sphere(dip_par,forwpar.device_sens,forwpar.center);
field=field_sens_sphere;clear field_sens_sphere;
if isfield(forwpar,'device_ref')
field=field-getfield_sphere(dip_par,forwpar.device_ref,forwpar.center);
end
if isfield(forwpar,'device_weights')
field=field+forwpar.weights*getfield_sphere(dip_par,forwpar.device_weights,forwpar.center);
end
if forwpar.order>0
coeff=forwpar.coeff_sens;
if isfield(forwpar,'device_ref')
coeff=coeff-forwpar.coeff_ref;
end
if isfield(forwpar,'device_weights')
coeff=coeff+forwpar.coeff_weights*forwpar.weights';
end
field=field+getfield_corr(dip_par,coeff,forwpar.center,forwpar.order);
end
if isfield(forwpar,'lintrafo');
field=forwpar.lintrafo*field;
end
return
function field=getfield_sphere(source,device,center);
[ndip,ndum]=size(source);
[nchan,ndum]=size(device);
x1=source(:,1:3)-repmat(center',ndip,1);
n1=source(:,4:6);
x2=device(:,1:3)-repmat(center',nchan,1);;
n2=device(:,4:6);
%spherical
bt=leadsphere_all(x1',x2',n2');
n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan);
b=dotproduct(n1rep,bt);
field=b';
return
function field=getfield_corr(source,coeffs,center,order);
[ndip,ndum]=size(source);
x1=source(:,1:3)-repmat(center',ndip,1);
n1=source(:,4:6);
%correction
if order>0
scale=10;
[bas,gradbas]=legs(x1,n1,order,scale);
nbasis=(order+1)^2-1;
coeffs=coeffs(1:nbasis,:);
field=-(gradbas*coeffs)';
end
return
function out=crossproduct(x,y)
% usage: out=testprog(x,y)
% testprog calculates the cross-product of vector x and y
[n,m,k]=size(x);
out=zeros(3,m,k);
out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:);
out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:);
out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:);
return;
function out=dotproduct(x,y)
% usage: out=dotproduct(x,y)
% testprog calculates the dotproduct of vector x and y
[n,m,k]=size(x);
outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:);
out=reshape(outb,m,k);
return;
function result=norms(x);
[n,m,k]=size(x);
resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2);
result=reshape(resultb,m,k);
return;
|
github | philippboehmsturm/antx-master | postpad.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/preproc/private/postpad.m | 2,013 | utf_8 | 2c9539d77ff0f85c9f89108f4dc811e0 | % Copyright (C) 1994, 1995, 1996, 1997, 1998, 2000, 2002, 2004, 2005,
% 2006, 2007, 2008, 2009 John W. Eaton
%
% This file is part of Octave.
%
% Octave 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.
%
% Octave 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 Octave; see the file COPYING. If not, see
% <http://www.gnu.org/licenses/>.
% -*- texinfo -*-
% @deftypefn {Function File} {} postpad (@var{x}, @var{l}, @var{c})
% @deftypefnx {Function File} {} postpad (@var{x}, @var{l}, @var{c}, @var{dim})
% @seealso{prepad, resize}
% @end deftypefn
% Author: Tony Richardson <[email protected]>
% Created: June 1994
function y = postpad (x, l, c, dim)
if nargin < 2 || nargin > 4
%print_usage ();
error('wrong number of input arguments, should be between 2 and 4');
end
if nargin < 3 || isempty(c)
c = 0;
else
if ~isscalar(c)
error ('postpad: third argument must be empty or a scalar');
end
end
nd = ndims(x);
sz = size(x);
if nargin < 4
% Find the first non-singleton dimension
dim = 1;
while dim < nd+1 && sz(dim)==1
dim = dim + 1;
end
if dim > nd
dim = 1;
elseif ~(isscalar(dim) && dim == round(dim)) && dim > 0 && dim< nd+1
error('postpad: dim must be an integer and valid dimension');
end
end
if ~isscalar(l) || l<0
error ('second argument must be a positive scalar');
end
if dim > nd
sz(nd+1:dim) = 1;
end
d = sz(dim);
if d >= l
idx = cell(1,nd);
for i = 1:nd
idx{i} = 1:sz(i);
end
idx{dim} = 1:l;
y = x(idx{:});
else
sz(dim) = l-d;
y = cat(dim, x, c * ones(sz));
end
|
github | philippboehmsturm/antx-master | sftrans.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/preproc/private/sftrans.m | 7,947 | utf_8 | f64cb2e7d19bcdc6232b39d8a6d70e7c | % Copyright (C) 1999 Paul Kienzle
%
% 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, see <http://www.gnu.org/licenses/>.
% usage: [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)
%
% Transform band edges of a generic lowpass filter (cutoff at W=1)
% represented in splane zero-pole-gain form. W is the edge of the
% target filter (or edges if band pass or band stop). Stop is true for
% high pass and band stop filters or false for low pass and band pass
% filters. Filter edges are specified in radians, from 0 to pi (the
% nyquist frequency).
%
% Theory: Given a low pass filter represented by poles and zeros in the
% splane, you can convert it to a low pass, high pass, band pass or
% band stop by transforming each of the poles and zeros individually.
% The following table summarizes the transformation:
%
% Transform Zero at x Pole at x
% ---------------- ------------------------- ------------------------
% Low Pass zero: Fc x/C pole: Fc x/C
% S -> C S/Fc gain: C/Fc gain: Fc/C
% ---------------- ------------------------- ------------------------
% High Pass zero: Fc C/x pole: Fc C/x
% S -> C Fc/S pole: 0 zero: 0
% gain: -x gain: -1/x
% ---------------- ------------------------- ------------------------
% Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S^2+FhFl pole: 0 zero: 0
% S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C
% S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
% Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl)
% S -> C -------- gain: -x gain: -1/x
% S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
% Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT)
% 2 z-1 pole: -1 zero: -1
% S -> - --- gain: (2-xT)/T gain: (2-xT)/T
% T z+1
% ---------------- ------------------------- ------------------------
%
% where C is the cutoff frequency of the initial lowpass filter, Fc is
% the edge of the target low/high pass filter and [Fl,Fh] are the edges
% of the target band pass/stop filter. With abundant tedious algebra,
% you can derive the above formulae yourself by substituting the
% transform for S into H(S)=S-x for a zero at x or H(S)=1/(S-x) for a
% pole at x, and converting the result into the form:
%
% H(S)=g prod(S-Xi)/prod(S-Xj)
%
% The transforms are from the references. The actual pole-zero-gain
% changes I derived myself.
%
% Please note that a pole and a zero at the same place exactly cancel.
% This is significant for High Pass, Band Pass and Band Stop filters
% which create numerous extra poles and zeros, most of which cancel.
% Those which do not cancel have a 'fill-in' effect, extending the
% shorter of the sets to have the same number of as the longer of the
% sets of poles and zeros (or at least split the difference in the case
% of the band pass filter). There may be other opportunistic
% cancellations but I will not check for them.
%
% Also note that any pole on the unit circle or beyond will result in
% an unstable filter. Because of cancellation, this will only happen
% if the number of poles is smaller than the number of zeros and the
% filter is high pass or band pass. The analytic design methods all
% yield more poles than zeros, so this will not be a problem.
%
% References:
%
% Proakis & Manolakis (1992). Digital Signal Processing. New York:
% Macmillan Publishing Company.
% Author: Paul Kienzle <[email protected]>
% 2000-03-01 [email protected]
% leave transformed Sg as a complex value since cheby2 blows up
% otherwise (but only for odd-order low-pass filters). bilinear
% will return Zg as real, so there is no visible change to the
% user of the IIR filter design functions.
% 2001-03-09 [email protected]
% return real Sg; don't know what to do for imaginary filters
function [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)
if (nargin ~= 5)
usage('[Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)');
end;
C = 1;
p = length(Sp);
z = length(Sz);
if z > p || p == 0
error('sftrans: must have at least as many poles as zeros in s-plane');
end
if length(W)==2
Fl = W(1);
Fh = W(2);
if stop
% ---------------- ------------------------- ------------------------
% Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl)
% S -> C -------- gain: -x gain: -1/x
% S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
if (isempty(Sz))
Sg = Sg * real (1./ prod(-Sp));
elseif (isempty(Sp))
Sg = Sg * real(prod(-Sz));
else
Sg = Sg * real(prod(-Sz)/prod(-Sp));
end
b = (C*(Fh-Fl)/2)./Sp;
Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
extend = [sqrt(-Fh*Fl), -sqrt(-Fh*Fl)];
if isempty(Sz)
Sz = [extend(1+rem([1:2*p],2))];
else
b = (C*(Fh-Fl)/2)./Sz;
Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
if (p > z)
Sz = [Sz, extend(1+rem([1:2*(p-z)],2))];
end
end
else
% ---------------- ------------------------- ------------------------
% Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S^2+FhFl pole: 0 zero: 0
% S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C
% S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
Sg = Sg * (C/(Fh-Fl))^(z-p);
b = Sp*((Fh-Fl)/(2*C));
Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
if isempty(Sz)
Sz = zeros(1,p);
else
b = Sz*((Fh-Fl)/(2*C));
Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
if (p>z)
Sz = [Sz, zeros(1, (p-z))];
end
end
end
else
Fc = W;
if stop
% ---------------- ------------------------- ------------------------
% High Pass zero: Fc C/x pole: Fc C/x
% S -> C Fc/S pole: 0 zero: 0
% gain: -x gain: -1/x
% ---------------- ------------------------- ------------------------
if (isempty(Sz))
Sg = Sg * real (1./ prod(-Sp));
elseif (isempty(Sp))
Sg = Sg * real(prod(-Sz));
else
Sg = Sg * real(prod(-Sz)/prod(-Sp));
end
Sp = C * Fc ./ Sp;
if isempty(Sz)
Sz = zeros(1,p);
else
Sz = [C * Fc ./ Sz];
if (p > z)
Sz = [Sz, zeros(1,p-z)];
end
end
else
% ---------------- ------------------------- ------------------------
% Low Pass zero: Fc x/C pole: Fc x/C
% S -> C S/Fc gain: C/Fc gain: Fc/C
% ---------------- ------------------------- ------------------------
Sg = Sg * (C/Fc)^(z-p);
Sp = Fc * Sp / C;
Sz = Fc * Sz / C;
end
end
|
github | philippboehmsturm/antx-master | filtfilt.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/preproc/private/filtfilt.m | 3,297 | iso_8859_1 | d01a26a827bc3379f05bbc57f46ac0a9 | % Copyright (C) 1999 Paul Kienzle
% Copyright (C) 2007 Francesco Potortì
% Copyright (C) 2008 Luca Citi
%
% 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, see <http://www.gnu.org/licenses/>.
% usage: y = filtfilt(b, a, x)
%
% Forward and reverse filter the signal. This corrects for phase
% distortion introduced by a one-pass filter, though it does square the
% magnitude response in the process. That's the theory at least. In
% practice the phase correction is not perfect, and magnitude response
% is distorted, particularly in the stop band.
%%
% Example
% [b, a]=butter(3, 0.1); % 10 Hz low-pass filter
% t = 0:0.01:1.0; % 1 second sample
% x=sin(2*pi*t*2.3)+0.25*randn(size(t)); % 2.3 Hz sinusoid+noise
% y = filtfilt(b,a,x); z = filter(b,a,x); % apply filter
% plot(t,x,';data;',t,y,';filtfilt;',t,z,';filter;')
% Changelog:
% 2000 02 [email protected]
% - pad with zeros to load up the state vector on filter reverse.
% - add example
% 2007 12 [email protected]
% - use filtic to compute initial and final states
% - work for multiple columns as well
% 2008 12 [email protected]
% - fixed instability issues with IIR filters and noisy inputs
% - initial states computed according to Likhterov & Kopeika, 2003
% - use of a "reflection method" to reduce end effects
% - added some basic tests
% TODO: (pkienzle) My version seems to have similar quality to matlab,
% but both are pretty bad. They do remove gross lag errors, though.
function y = filtfilt(b, a, x)
if (nargin ~= 3)
usage('y=filtfilt(b,a,x)');
end
rotate = (size(x, 1)==1);
if rotate % a row vector
x = x(:); % make it a column vector
end
lx = size(x,1);
a = a(:).';
b = b(:).';
lb = length(b);
la = length(a);
n = max(lb, la);
lrefl = 3 * (n - 1);
if la < n, a(n) = 0; end
if lb < n, b(n) = 0; end
% Compute a the initial state taking inspiration from
% Likhterov & Kopeika, 2003. "Hardware-efficient technique for
% minimizing startup transients in Direct Form II digital filters"
kdc = sum(b) / sum(a);
if (abs(kdc) < inf) % neither NaN nor +/- Inf
si = fliplr(cumsum(fliplr(b - kdc * a)));
else
si = zeros(size(a)); % fall back to zero initialization
end
si(1) = [];
y = zeros(size(x));
for c = 1:size(x, 2) % filter all columns, one by one
v = [2*x(1,c)-x((lrefl+1):-1:2,c); x(:,c);
2*x(end,c)-x((end-1):-1:end-lrefl,c)]; % a column vector
% Do forward and reverse filtering
v = filter(b,a,v,si*v(1)); % forward filter
v = flipud(filter(b,a,flipud(v),si*v(end))); % reverse filter
y(:,c) = v((lrefl+1):(lx+lrefl));
end
if (rotate) % x was a row vector
y = rot90(y); % rotate it back
end
|
github | philippboehmsturm/antx-master | bilinear.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/preproc/private/bilinear.m | 4,339 | utf_8 | 17250db27826cad87fa3384823e1242f | % Copyright (C) 1999 Paul Kienzle
%
% 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, see <http://www.gnu.org/licenses/>.
% usage: [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T)
% [Zb, Za] = bilinear(Sb, Sa, T)
%
% Transform a s-plane filter specification into a z-plane
% specification. Filters can be specified in either zero-pole-gain or
% transfer function form. The input form does not have to match the
% output form. 1/T is the sampling frequency represented in the z plane.
%
% Note: this differs from the bilinear function in the signal processing
% toolbox, which uses 1/T rather than T.
%
% Theory: Given a piecewise flat filter design, you can transform it
% from the s-plane to the z-plane while maintaining the band edges by
% means of the bilinear transform. This maps the left hand side of the
% s-plane into the interior of the unit circle. The mapping is highly
% non-linear, so you must design your filter with band edges in the
% s-plane positioned at 2/T tan(w*T/2) so that they will be positioned
% at w after the bilinear transform is complete.
%
% The following table summarizes the transformation:
%
% +---------------+-----------------------+----------------------+
% | Transform | Zero at x | Pole at x |
% | H(S) | H(S) = S-x | H(S)=1/(S-x) |
% +---------------+-----------------------+----------------------+
% | 2 z-1 | zero: (2+xT)/(2-xT) | zero: -1 |
% | S -> - --- | pole: -1 | pole: (2+xT)/(2-xT) |
% | T z+1 | gain: (2-xT)/T | gain: (2-xT)/T |
% +---------------+-----------------------+----------------------+
%
% With tedious algebra, you can derive the above formulae yourself by
% substituting the transform for S into H(S)=S-x for a zero at x or
% H(S)=1/(S-x) for a pole at x, and converting the result into the
% form:
%
% H(Z)=g prod(Z-Xi)/prod(Z-Xj)
%
% Please note that a pole and a zero at the same place exactly cancel.
% This is significant since the bilinear transform creates numerous
% extra poles and zeros, most of which cancel. Those which do not
% cancel have a 'fill-in' effect, extending the shorter of the sets to
% have the same number of as the longer of the sets of poles and zeros
% (or at least split the difference in the case of the band pass
% filter). There may be other opportunistic cancellations but I will
% not check for them.
%
% Also note that any pole on the unit circle or beyond will result in
% an unstable filter. Because of cancellation, this will only happen
% if the number of poles is smaller than the number of zeros. The
% analytic design methods all yield more poles than zeros, so this will
% not be a problem.
%
% References:
%
% Proakis & Manolakis (1992). Digital Signal Processing. New York:
% Macmillan Publishing Company.
% Author: Paul Kienzle <[email protected]>
function [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T)
if nargin==3
T = Sg;
[Sz, Sp, Sg] = tf2zp(Sz, Sp);
elseif nargin~=4
usage('[Zz, Zp, Zg]=bilinear(Sz,Sp,Sg,T) or [Zb, Za]=blinear(Sb,Sa,T)');
end;
p = length(Sp);
z = length(Sz);
if z > p || p==0
error('bilinear: must have at least as many poles as zeros in s-plane');
end
% ---------------- ------------------------- ------------------------
% Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT)
% 2 z-1 pole: -1 zero: -1
% S -> - --- gain: (2-xT)/T gain: (2-xT)/T
% T z+1
% ---------------- ------------------------- ------------------------
Zg = real(Sg * prod((2-Sz*T)/T) / prod((2-Sp*T)/T));
Zp = (2+Sp*T)./(2-Sp*T);
if isempty(Sz)
Zz = -ones(size(Zp));
else
Zz = [(2+Sz*T)./(2-Sz*T)];
Zz = postpad(Zz, p, -1);
end
if nargout==2, [Zz, Zp] = zp2tf(Zz, Zp, Zg); end
|
github | philippboehmsturm/antx-master | butter.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/preproc/private/butter.m | 3,559 | utf_8 | ad82b4c04911a5ea11fd6bd2cc5fd590 | % Copyright (C) 1999 Paul Kienzle
%
% 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, see <http://www.gnu.org/licenses/>.
% Generate a butterworth filter.
% Default is a discrete space (Z) filter.
%
% [b,a] = butter(n, Wc)
% low pass filter with cutoff pi*Wc radians
%
% [b,a] = butter(n, Wc, 'high')
% high pass filter with cutoff pi*Wc radians
%
% [b,a] = butter(n, [Wl, Wh])
% band pass filter with edges pi*Wl and pi*Wh radians
%
% [b,a] = butter(n, [Wl, Wh], 'stop')
% band reject filter with edges pi*Wl and pi*Wh radians
%
% [z,p,g] = butter(...)
% return filter as zero-pole-gain rather than coefficients of the
% numerator and denominator polynomials.
%
% [...] = butter(...,'s')
% return a Laplace space filter, W can be larger than 1.
%
% [a,b,c,d] = butter(...)
% return state-space matrices
%
% References:
%
% Proakis & Manolakis (1992). Digital Signal Processing. New York:
% Macmillan Publishing Company.
% Author: Paul Kienzle <[email protected]>
% Modified by: Doug Stewart <[email protected]> Feb, 2003
function [a, b, c, d] = butter (n, W, varargin)
if (nargin>4 || nargin<2) || (nargout>4 || nargout<2)
usage ('[b, a] or [z, p, g] or [a,b,c,d] = butter (n, W [, "ftype"][,"s"])');
end
% interpret the input parameters
if (~(length(n)==1 && n == round(n) && n > 0))
error ('butter: filter order n must be a positive integer');
end
stop = 0;
digital = 1;
for i=1:length(varargin)
switch varargin{i}
case 's', digital = 0;
case 'z', digital = 1;
case { 'high', 'stop' }, stop = 1;
case { 'low', 'pass' }, stop = 0;
otherwise, error ('butter: expected [high|stop] or [s|z]');
end
end
[r, c]=size(W);
if (~(length(W)<=2 && (r==1 || c==1)))
error ('butter: frequency must be given as w0 or [w0, w1]');
elseif (~(length(W)==1 || length(W) == 2))
error ('butter: only one filter band allowed');
elseif (length(W)==2 && ~(W(1) < W(2)))
error ('butter: first band edge must be smaller than second');
end
if ( digital && ~all(W >= 0 & W <= 1))
error ('butter: critical frequencies must be in (0 1)');
elseif ( ~digital && ~all(W >= 0 ))
error ('butter: critical frequencies must be in (0 inf)');
end
% Prewarp to the band edges to s plane
if digital
T = 2; % sampling frequency of 2 Hz
W = 2/T*tan(pi*W/T);
end
% Generate splane poles for the prototype butterworth filter
% source: Kuc
C = 1; % default cutoff frequency
pole = C*exp(1i*pi*(2*[1:n] + n - 1)/(2*n));
if mod(n,2) == 1, pole((n+1)/2) = -1; end % pure real value at exp(i*pi)
zero = [];
gain = C^n;
% splane frequency transform
[zero, pole, gain] = sftrans(zero, pole, gain, W, stop);
% Use bilinear transform to convert poles to the z plane
if digital
[zero, pole, gain] = bilinear(zero, pole, gain, T);
end
% convert to the correct output form
if nargout==2,
a = real(gain*poly(zero));
b = real(poly(pole));
elseif nargout==3,
a = zero;
b = pole;
c = gain;
else
% output ss results
[a, b, c, d] = zp2ss (zero, pole, gain);
end
|
github | philippboehmsturm/antx-master | statfun_roc.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/statfun/statfun_roc.m | 4,537 | utf_8 | 63873370a1727fc5e0bed4e16fd685f8 | function [s, cfg] = statfun_roc(cfg, dat, design)
% STATFUN_roc computes the area under the curve (AUC) of the
% Receiver Operator Characteristic (ROC). This is a measure of the
% separability of the data divided over two conditions. The AUC can
% be used to test statistical significance of being able to predict
% on a single observation basis to which condition the observation
% belongs.
%
% Use this function by calling one of the high-level statistics
% functions as
% [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...)
% [stat] = ft_freqstatistics(cfg, freq1, freq2, ...)
% [stat] = ft_sourcestatistics(cfg, source1, source2, ...)
% with the following configuration option:
% cfg.statistic = 'roc'
%
% Configuration options that are relevant for this function are
% cfg.ivar = number, index into the design matrix with the independent variable
% cfg.logtransform = 'yes' or 'no' (default = 'no')
%
% Note that this statfun performs a one sided test in which condition "1"
% is assumed to be larger than condition "2".
% A low-level example for this function is
% a = randn(1,1000) + 1;
% b = randn(1,1000);
% design = [1*ones(1,1000) 2*ones(1,1000)];
% auc = statfun_roc([], [a b], design);
% Copyright (C) 2008, Robert Oostenveld
if ~isfield(cfg, 'ivar'), cfg.ivar = 1; end
if ~isfield(cfg, 'logtransform'), cfg.logtransform = 'no'; end
if strcmp(cfg.logtransform, 'yes'),
dat = log10(dat);
end
if isfield(cfg, 'numbins')
% this function was completely reimplemented on 21 July 2008 by Robert Oostenveld
% the old function had a positive bias in the AUC (i.e. the expected value was not 0.5)
error('the option cfg.numbins is not supported any more');
end
% start with a quick test to see whether there appear to be NaNs
if any(isnan(dat(1,:)))
% exclude trials that contain NaNs for all observed data points
sel = all(isnan(dat),1);
dat = dat(:,~sel);
design = design(:,~sel);
end
% logical indexing is faster than using find(...)
selA = (design(cfg.ivar,:)==1);
selB = (design(cfg.ivar,:)==2);
% select the data in the two classes
datA = dat(:, selA);
datB = dat(:, selB);
nobs = size(dat,1);
na = size(datA,2);
nb = size(datB,2);
auc = zeros(nobs, 1);
for k = 1:nobs
% compute the area under the curve for each channel/time/frequency
a = datA(k,:);
b = datB(k,:);
% to speed up the AUC, the critical value is determined by the actual
% values in class B, which also ensures a regular sampling of the False Alarms
b = sort(b);
ca = zeros(nb+1,1);
ib = zeros(nb+1,1);
% cb = zeros(nb+1,1);
% ia = zeros(nb+1,1);
for i=1:nb
% for the first approach below, the critval could also be choosen based on e.g. linspace(min,max,n)
critval = b(i);
% for each of the two distributions, determine the number of correct and incorrect assignments given the critical value
% ca(i) = sum(a>=critval);
% ib(i) = sum(b>=critval);
% cb(i) = sum(b<critval);
% ia(i) = sum(a<critval);
% this is a much faster approach, which works due to using the sorted values in b as the critical values
ca(i) = sum(a>=critval); % correct assignments to class A
ib(i) = nb-i+1; % incorrect assignments to class B
end
% add the end point
ca(end) = 0;
ib(end) = 0;
% cb(end) = nb;
% ia(end) = na;
hits = ca/na;
fa = ib/nb;
% the numerical integration is faster if the points are sorted
hits = fliplr(hits);
fa = fliplr(fa);
if true
% this part is optional and should only be used when exploring the data
figure
plot(fa, hits, '.-')
xlabel('false positive');
ylabel('true positive');
title('ROC-curve');
end
% compute the area under the curve using numerical integration
auc(k) = numint(fa, hits);
end
s.stat = auc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NUMINT computes a numerical integral of a set of sampled points using
% linear interpolation. Alugh the algorithm works for irregularly sampled points
% along the x-axis, it will perform best for regularly sampled points
%
% Use as
% z = numint(x, y)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function z = numint(x, y)
if ~all(diff(x)>=0)
% ensure that the points are sorted along the x-axis
[x, i] = sort(x);
y = y(i);
end
n = length(x);
z = 0;
for i=1:(n-1)
x0 = x(i);
y0 = y(i);
dx = x(i+1)-x(i);
dy = y(i+1)-y(i);
z = z + (y0 * dx) + (dy*dx/2);
end
|
github | philippboehmsturm/antx-master | nanstd.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/statfun/private/nanstd.m | 2,445 | utf_8 | 5bfd7c73ce6d67e3163bdc51d464b590 | % nanstd() - std, not considering NaN values
%
% Usage: same as std()
% Author: Arnaud Delorme, CNL / Salk Institute, Sept 2003
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% This 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: nanstd.m 2885 2011-02-16 09:41:58Z roboos $
function out = nanstd(in, varargin)
if nargin < 1
help nanstd;
return;
end
if nargin == 1, flag = 0; end
if nargin < 3,
if size(in,1) ~= 1
dim = 1;
elseif size(in,2) ~= 1
dim = 2;
else
dim = 3;
end
end
if nargin == 2, flag = varargin{1}; end
if nargin == 3,
flag = varargin{1};
dim = varargin{2};
end
if isempty(flag), flag = 0; end
nans = find(isnan(in));
in(nans) = 0;
nonnans = ones(size(in));
nonnans(nans) = 0;
nonnans = sum(nonnans, dim);
nononnans = find(nonnans==0);
nonnans(nononnans) = 1;
out = sqrt((sum(in.^2, dim)-sum(in, dim).^2./nonnans)./(nonnans-abs(flag-1)));
out(nononnans) = NaN;
|
github | philippboehmsturm/antx-master | warning_once.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/statfun/private/warning_once.m | 3,060 | utf_8 | f046009e4f6ffe5745af9c5e527614e8 | function [ws warned] = warning_once(varargin)
%
% Use as
% warning_once(string)
% or
% warning_once(string, timeout)
% or
% warning_once(id, string, timeout)
% where timeout should be inf if you don't want to see the warning ever
% again. The default timeout value is 60 seconds.
%
% Can be used instead of the MATLAB built-in function WARNING, thus as
% s = warning_once(...)
% or
% warning_once(s)
% where s is a structure with fields 'identifier' and 'state', storing the
% state information.
% In other words, warning_once accepts as an input the same structure it
% returns as an output. This returns or restores the states of warnings to
% their previous values.
%
% Can also be used as
% [s w] = warning_once(...)
% where w is a boolean that indicates whether a warning as been
% thrown or not.
persistent stopwatch previous
if nargin < 1
error('You need to specify at least a warning message');
end
warned = false;
if isstruct(varargin{1})
warning(varargin{1});
return;
end
if nargin==3
msgid = varargin{1};
msgstr = varargin{2};
timeout = varargin{3};
elseif nargin==2
msgstr= ''; % this becomes irrelevant
msgid = varargin{1}; % this becomes the real msgstr
timeout = varargin{2};
elseif nargin==1
msgstr= ''; % this becomes irrelevant
msgid = varargin{1}; % this becomes the real msgstr
timeout = 60; % default timeout in seconds
end
if isempty(timeout)
error('Timeout ill-specified');
end
if isempty(stopwatch)
stopwatch = tic;
end
if isempty(previous)
previous = struct;
end
now = toc(stopwatch); % measure time since first function call
fname = fixname([msgid '_' msgstr]); % make a nice string that is allowed as structure fieldname, copy the subfunction from ft_hastoolbox
fname = decomma(fname);
if length(fname) > 63 % MATLAB max name
fname = fname(1:63);
end
if isfield(previous, fname) && now>previous.(fname).timeout
% it has timed out, give the warning again
ws = warning(msgid, msgstr);
previous.(fname).timeout = now+timeout;
previous.(fname).ws = ws;
warned = true;
elseif ~isfield(previous, fname)
% the warning has not been issued before
ws = warning(msgid, msgstr);
previous.(fname).timeout = now+timeout;
previous.(fname).ws = ws;
warned = true;
else
% the warning has been issued before, but has not timed out yet
ws = previous.(fname).ws;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = fixname(toolbox)
out = lower(toolbox);
out(out=='-') = '_'; % fix dashes
out(out==' ') = '_'; % fix spaces
out(out=='/') = '_'; % fix forward slashes
out(out=='\') = '_'; % fix backward slashes
while(out(1) == '_'), out = out(2:end); end; % remove preceding underscore
while(out(end) == '_'), out = out(1:end-1); end; % remove subsequent underscore
end
function nameout = decomma(name)
nameout = name;
indx = findstr(name,',');
nameout(indx)=[];
end |
github | philippboehmsturm/antx-master | nanmean.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/statfun/private/nanmean.m | 2,121 | utf_8 | 7e0ebd9ca56f2cd79f89031bbccebb9a | % nanmean() - Average, not considering NaN values
%
% Usage: same as mean()
% Author: Arnaud Delorme, CNL / Salk Institute, 16 Oct 2002
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% This 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: nanmean.m 2885 2011-02-16 09:41:58Z roboos $
function out = nanmean(in, dim)
if nargin < 1
help nanmean;
return;
end;
if nargin < 2
if size(in,1) ~= 1
dim = 1;
elseif size(in,2) ~= 1
dim = 2;
else
dim = 3;
end;
end;
tmpin = in;
tmpin(find(isnan(in(:)))) = 0;
out = sum(tmpin, dim) ./ sum(~isnan(in),dim);
|
github | philippboehmsturm/antx-master | nanvar.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/statfun/private/nanvar.m | 2,439 | utf_8 | 201826aeefbd74374df411fca75bb78f | % nanvar() - var, not considering NaN values
%
% Usage: same as var()
% Author: Arnaud Delorme, CNL / Salk Institute, Sept 2003
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% This 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: nanvar.m 2885 2011-02-16 09:41:58Z roboos $
function out = nanvar(in, varargin)
if nargin < 1
help nanvar;
return;
end
if nargin == 1, flag = 0; end
if nargin < 3,
if size(in,1) ~= 1
dim = 1;
elseif size(in,2) ~= 1
dim = 2;
else
dim = 3;
end
end
if nargin == 2, flag = varargin{1}; end
if nargin == 3,
flag = varargin{1};
dim = varargin{2};
end
if isempty(flag), flag = 0; end
nans = find(isnan(in));
in(nans) = 0;
nonnans = ones(size(in));
nonnans(nans) = 0;
nonnans = sum(nonnans, dim);
nononnans = find(nonnans==0);
nonnans(nononnans) = 1;
out = (sum(in.^2, dim)-sum(in, dim).^2./nonnans)./(nonnans-abs(flag-1));
out(nononnans) = NaN;
|
github | philippboehmsturm/antx-master | tinv.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/statfun/private/tinv.m | 7,634 | utf_8 | 8fe66ec125f91e1a7ac5f8d3cb2ac51a | function x = tinv(p,v);
% TINV Inverse of Student's T cumulative distribution function (cdf).
% X=TINV(P,V) returns the inverse of Student's T cdf with V degrees
% of freedom, at the values in P.
%
% The size of X is the common size of P and V. A scalar input
% functions as a constant matrix of the same size as the other input.
%
% This is an open source function that was assembled by Eric Maris using
% open source subfunctions found on the web.
% Subversion does not use the Log keyword, use 'svn log <filename>' or 'svn -v log | less' to get detailled information
if nargin < 2,
error('Requires two input arguments.');
end
[errorcode p v] = distchck(2,p,v);
if errorcode > 0
error('Requires non-scalar arguments to match in size.');
end
% Initialize X to zero.
x=zeros(size(p));
k = find(v < 0 | v ~= round(v));
if any(k)
tmp = NaN;
x(k) = tmp(ones(size(k)));
end
k = find(v == 1);
if any(k)
x(k) = tan(pi * (p(k) - 0.5));
end
% The inverse cdf of 0 is -Inf, and the inverse cdf of 1 is Inf.
k0 = find(p == 0);
if any(k0)
tmp = Inf;
x(k0) = -tmp(ones(size(k0)));
end
k1 = find(p ==1);
if any(k1)
tmp = Inf;
x(k1) = tmp(ones(size(k1)));
end
k = find(p >= 0.5 & p < 1);
if any(k)
z = betainv(2*(1-p(k)),v(k)/2,0.5);
x(k) = sqrt(v(k) ./ z - v(k));
end
k = find(p < 0.5 & p > 0);
if any(k)
z = betainv(2*(p(k)),v(k)/2,0.5);
x(k) = -sqrt(v(k) ./ z - v(k));
end
%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION distchck
%%%%%%%%%%%%%%%%%%%%%%%%%
function [errorcode,varargout] = distchck(nparms,varargin)
%DISTCHCK Checks the argument list for the probability functions.
errorcode = 0;
varargout = varargin;
if nparms == 1
return;
end
% Get size of each input, check for scalars, copy to output
isscalar = (cellfun('prodofsize',varargin) == 1);
% Done if all inputs are scalars. Otherwise fetch their common size.
if (all(isscalar)), return; end
n = nparms;
for j=1:n
sz{j} = size(varargin{j});
end
t = sz(~isscalar);
size1 = t{1};
% Scalars receive this size. Other arrays must have the proper size.
for j=1:n
sizej = sz{j};
if (isscalar(j))
t = zeros(size1);
t(:) = varargin{j};
varargout{j} = t;
elseif (~isequal(sizej,size1))
errorcode = 1;
return;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION betainv
%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = betainv(p,a,b);
%BETAINV Inverse of the beta cumulative distribution function (cdf).
% X = BETAINV(P,A,B) returns the inverse of the beta cdf with
% parameters A and B at the values in P.
%
% The size of X is the common size of the input arguments. A scalar input
% functions as a constant matrix of the same size as the other inputs.
%
% BETAINV uses Newton's method to converge to the solution.
% Reference:
% [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical
% Functions", Government Printing Office, 1964.
% B.A. Jones 1-12-93
if nargin < 3,
error('Requires three input arguments.');
end
[errorcode p a b] = distchck(3,p,a,b);
if errorcode > 0
error('Requires non-scalar arguments to match in size.');
end
% Initialize x to zero.
x = zeros(size(p));
% Return NaN if the arguments are outside their respective limits.
k = find(p < 0 | p > 1 | a <= 0 | b <= 0);
if any(k),
tmp = NaN;
x(k) = tmp(ones(size(k)));
end
% The inverse cdf of 0 is 0, and the inverse cdf of 1 is 1.
k0 = find(p == 0 & a > 0 & b > 0);
if any(k0),
x(k0) = zeros(size(k0));
end
k1 = find(p==1);
if any(k1),
x(k1) = ones(size(k1));
end
% Newton's Method.
% Permit no more than count_limit interations.
count_limit = 100;
count = 0;
k = find(p > 0 & p < 1 & a > 0 & b > 0);
pk = p(k);
% Use the mean as a starting guess.
xk = a(k) ./ (a(k) + b(k));
% Move starting values away from the boundaries.
if xk == 0,
xk = sqrt(eps);
end
if xk == 1,
xk = 1 - sqrt(eps);
end
h = ones(size(pk));
crit = sqrt(eps);
% Break out of the iteration loop for the following:
% 1) The last update is very small (compared to x).
% 2) The last update is very small (compared to 100*eps).
% 3) There are more than 100 iterations. This should NEVER happen.
while(any(abs(h) > crit * abs(xk)) & max(abs(h)) > crit ...
& count < count_limit),
count = count+1;
h = (betacdf(xk,a(k),b(k)) - pk) ./ betapdf(xk,a(k),b(k));
xnew = xk - h;
% Make sure that the values stay inside the bounds.
% Initially, Newton's Method may take big steps.
ksmall = find(xnew < 0);
klarge = find(xnew > 1);
if any(ksmall) | any(klarge)
xnew(ksmall) = xk(ksmall) /10;
xnew(klarge) = 1 - (1 - xk(klarge))/10;
end
xk = xnew;
end
% Return the converged value(s).
x(k) = xk;
if count==count_limit,
fprintf('\nWarning: BETAINV did not converge.\n');
str = 'The last step was: ';
outstr = sprintf([str,'%13.8f'],h);
fprintf(outstr);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION betapdf
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = betapdf(x,a,b)
%BETAPDF Beta probability density function.
% Y = BETAPDF(X,A,B) returns the beta probability density
% function with parameters A and B at the values in X.
%
% The size of Y is the common size of the input arguments. A scalar input
% functions as a constant matrix of the same size as the other inputs.
% References:
% [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical
% Functions", Government Printing Office, 1964, 26.1.33.
if nargin < 3,
error('Requires three input arguments.');
end
[errorcode x a b] = distchck(3,x,a,b);
if errorcode > 0
error('Requires non-scalar arguments to match in size.');
end
% Initialize Y to zero.
y = zeros(size(x));
% Return NaN for parameter values outside their respective limits.
k1 = find(a <= 0 | b <= 0 | x < 0 | x > 1);
if any(k1)
tmp = NaN;
y(k1) = tmp(ones(size(k1)));
end
% Return Inf for x = 0 and a < 1 or x = 1 and b < 1.
% Required for non-IEEE machines.
k2 = find((x == 0 & a < 1) | (x == 1 & b < 1));
if any(k2)
tmp = Inf;
y(k2) = tmp(ones(size(k2)));
end
% Return the beta density function for valid parameters.
k = find(~(a <= 0 | b <= 0 | x <= 0 | x >= 1));
if any(k)
y(k) = x(k) .^ (a(k) - 1) .* (1 - x(k)) .^ (b(k) - 1) ./ beta(a(k),b(k));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION betacdf
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function p = betacdf(x,a,b);
%BETACDF Beta cumulative distribution function.
% P = BETACDF(X,A,B) returns the beta cumulative distribution
% function with parameters A and B at the values in X.
%
% The size of P is the common size of the input arguments. A scalar input
% functions as a constant matrix of the same size as the other inputs.
%
% BETAINC does the computational work.
% Reference:
% [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical
% Functions", Government Printing Office, 1964, 26.5.
if nargin < 3,
error('Requires three input arguments.');
end
[errorcode x a b] = distchck(3,x,a,b);
if errorcode > 0
error('Requires non-scalar arguments to match in size.');
end
% Initialize P to 0.
p = zeros(size(x));
k1 = find(a<=0 | b<=0);
if any(k1)
tmp = NaN;
p(k1) = tmp(ones(size(k1)));
end
% If is X >= 1 the cdf of X is 1.
k2 = find(x >= 1);
if any(k2)
p(k2) = ones(size(k2));
end
k = find(x > 0 & x < 1 & a > 0 & b > 0);
if any(k)
p(k) = betainc(x(k),a(k),b(k));
end
% Make sure that round-off errors never make P greater than 1.
k = find(p > 1);
p(k) = ones(size(k));
|
github | philippboehmsturm/antx-master | ft_connectivity_corr.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/connectivity/ft_connectivity_corr.m | 6,929 | utf_8 | 5df12f8c9d22f66319d8a79480be037a | function [c, v, outcnt] = ft_connectivity_corr(input, varargin)
% FT_CONNECTIVITY_CORR computes correlation or coherence from a data-matrix
% containing a covariance or cross-spectral density
%
% Use as
% [c, v, n] = ft_connectivity_corr(input, varargin)
%
% The input data input should be organized as:
% Repetitions x Channel x Channel (x Frequency) (x Time)
% or
% Repetitions x Channelcombination (x Frequency) (x Time)
%
% The first dimension should be singleton if the input already contains
% an average
%
% Additional input arguments come as key-value pairs:
%
% hasjack 0 or 1 specifying whether the Repetitions represent
% leave-one-out samples
% complex 'abs', 'angle', 'real', 'imag', 'complex' for post-processing of
% coherency
% feedback 'none', 'text', 'textbar' type of feedback showing progress of
% computation
% dimord specifying how the input matrix should be interpreted
% powindx
% pownorm
% pchanindx
% allchanindx
%
% The output c contains the correlation/coherence, v is a variance estimate
% which only can be computed if the data contains leave-one-out samples,
% and n is the number of repetitions in the input data.
%
% This is a helper function to FT_CONNECTIVITYANALYSIS
%
% See also FT_CONNECTIVITYANALYSIS
% Copyright (C) 2009-2010 Donders Institute, Jan-Mathijs Schoffelen
%
% 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/>.
%
% FiXME: If output is angle, then jack-knifing should be done differently
% since it's circular variable
% $Id: ft_connectivity_corr.m 3815 2011-07-09 18:03:12Z jansch $
hasjack = keyval('hasjack', varargin); if isempty(hasjack), hasjack = 0; end
cmplx = keyval('complex', varargin); if isempty(cmplx), cmplx = 'abs'; end
feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'none'; end
dimord = keyval('dimord', varargin);
powindx = keyval('powindx', varargin);
pownorm = keyval('pownorm', varargin); if isempty(pownorm), pownorm = 0; end
pchanindx = keyval('pchanindx', varargin);
allchanindx = keyval('allchanindx', varargin);
if isempty(dimord)
error('input parameters should contain a dimord');
end
siz = [size(input) 1];
% do partialisation if necessary
if ~isempty(pchanindx),
% partial spectra are computed as in Rosenberg JR et al (1998) J.Neuroscience Methods, equation 38
chan = allchanindx;
nchan = numel(chan);
pchan = pchanindx;
npchan = numel(pchan);
newsiz = siz;
newsiz(2:3) = numel(chan); % size of partialised csd
A = zeros(newsiz);
% FIXME this only works for data without time dimension
if numel(siz)==5 && siz(5)>1, error('this only works for data without time'); end
for j = 1:siz(1) %rpt loop
AA = reshape(input(j, chan, chan, : ), [nchan nchan siz(4:end)]);
AB = reshape(input(j, chan, pchan,: ), [nchan npchan siz(4:end)]);
BA = reshape(input(j, pchan, chan, : ), [npchan nchan siz(4:end)]);
BB = reshape(input(j, pchan, pchan, :), [npchan npchan siz(4:end)]);
for k = 1:siz(4) %freq loop
%A(j,:,:,k) = AA(:,:,k) - AB(:,:,k)*pinv(BB(:,:,k))*BA(:,:,k);
A(j,:,:,k) = AA(:,:,k) - AB(:,:,k)/(BB(:,:,k))*BA(:,:,k);
end
end
input = A;
siz = size(input);
else
% do nothing
end
% compute the metric
if (length(strfind(dimord, 'chan'))~=2 || length(strfind(dimord, 'pos'))>0) && ~isempty(powindx),
% crossterms are not described with chan_chan_therest, but are linearly indexed
outsum = zeros(siz(2:end));
outssq = zeros(siz(2:end));
outcnt = zeros(siz(2:end));
ft_progress('init', feedback, 'computing metric...');
for j = 1:siz(1)
ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1));
if pownorm
p1 = reshape(input(j,powindx(:,1),:,:,:), siz(2:end));
p2 = reshape(input(j,powindx(:,2),:,:,:), siz(2:end));
denom = sqrt(p1.*p2); clear p1 p2
else
denom = 1;
end
tmp = complexeval(reshape(input(j,:,:,:,:), siz(2:end))./denom, cmplx);
outsum = outsum + tmp;
outssq = outssq + tmp.^2;
outcnt = outcnt + double(~isnan(tmp));
end
ft_progress('close');
elseif length(strfind(dimord, 'chan'))==2 || length(strfind(dimord, 'pos'))==2,
% crossterms are described by chan_chan_therest
outsum = zeros(siz(2:end));
outssq = zeros(siz(2:end));
outcnt = zeros(siz(2:end));
ft_progress('init', feedback, 'computing metric...');
for j = 1:siz(1)
ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1));
if pownorm
p1 = zeros([siz(2) 1 siz(4:end)]);
p2 = zeros([1 siz(3) siz(4:end)]);
for k = 1:siz(2)
p1(k,1,:,:,:,:) = input(j,k,k,:,:,:,:);
p2(1,k,:,:,:,:) = input(j,k,k,:,:,:,:);
end
p1 = p1(:,ones(1,siz(3)),:,:,:,:);
p2 = p2(ones(1,siz(2)),:,:,:,:,:);
denom = sqrt(p1.*p2); clear p1 p2;
else
denom = 1;
end
tmp = complexeval(reshape(input(j,:,:,:,:,:,:), siz(2:end))./denom, cmplx); % added this for nan support marvin
%tmp(isnan(tmp)) = 0; % added for nan support
outsum = outsum + tmp;
outssq = outssq + tmp.^2;
outcnt = outcnt + double(~isnan(tmp));
end
ft_progress('close');
end
n = siz(1);
if all(outcnt(:)==n)
outcnt = n;
end
%n1 = shiftdim(sum(~isnan(input),1),1);
%c = outsum./n1; % added this for nan support marvin
c = outsum./outcnt;
% correct the variance estimate for the under-estimation introduced by the jackknifing
if n>1,
if hasjack
%bias = (n1-1).^2; % added this for nan support marvin
bias = (outcnt-1).^2;
else
bias = 1;
end
%v = bias.*(outssq - (outsum.^2)./n1)./(n1 - 1); % added this for nan support marvin
v = bias.*(outssq - (outsum.^2)./outcnt)./(outcnt-1);
else
v = [];
end
function [c] = complexeval(c, str)
switch str
case 'complex'
%do nothing
case 'abs'
c = abs(c);
case 'angle'
c = angle(c); % negative angle means first row leads second row
case 'imag'
c = imag(c);
case 'real'
c = real(c);
case '-logabs'
c = -log(1 - abs(c).^2);
otherwise
error('complex = ''%s'' not supported', cmplx);
end
|
github | philippboehmsturm/antx-master | ft_connectivity_psi.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/connectivity/ft_connectivity_psi.m | 5,652 | utf_8 | d93ff0bd978058602e1526567a9db1a4 | function [c, v, n] = ft_connectivity_psi(input, varargin)
% FT_CONNECTIVITY_PSI computes the phase slope index from a data-matrix
% containing a cross-spectral density, according to FIXME include reference
%
% Use as
% [c, v, n] = ft_connectivity_psi(input, varargin)
%
% The input data input should be organized as:
% Repetitions x Channel x Channel (x Frequency) (x Time)
% or
% Repetitions x Channelcombination (x Frequency) (x Time)
%
% The first dimension should be singleton if the input already contains
% an average
%
% Additional input arguments come as key-value pairs:
%
% hasjack 0 or 1 specifying whether the Repetitions represent
% leave-one-out samples
% feedback 'none', 'text', 'textbar' type of feedback showing progress of
% computation
% dimord specifying how the input matrix should be interpreted
% powindx
% normalize
% nbin the number of frequency bins across which to integrate
%
% The output c contains the correlation/coherence, v is a variance estimate
% which only can be computed if the data contains leave-one-out samples,
% and n is the number of repetitions in the input data.
% If the phase slope index is positive, then the first chan (1st dim) becomes
% more lagged (or less leading) with higher frequency, indicating that it
% is causally driven by the second channel (2nd dim)
%
% This is a helper function to FT_CONNECTIVITYANALYSIS
%
% See also FT_CONNECTIVITYANALYSIS
% Copyright (C) 2009-2010 Donders Institute, Jan-Mathijs Schoffelen
%
% 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/>.
%
% FIXME: interpretation of the slope
% $Id: ft_connectivity_psi.m 3761 2011-07-02 17:09:44Z marvin $
hasjack = keyval('hasjack', varargin); if isempty(hasjack), hasjack = 0; end
feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'none'; end
dimord = keyval('dimord', varargin);
powindx = keyval('powindx', varargin);
normalize = keyval('normalize', varargin); if isempty(normalize), normalize = 'no'; end
nbin = keyval('nbin', varargin);
if isempty(dimord)
error('input parameters should contain a dimord');
end
if (length(strfind(dimord, 'chan'))~=2 || ~isempty(strfind(dimord, 'pos'))>0) && ~isempty(powindx),
%crossterms are not described with chan_chan_therest, but are linearly indexed
siz = size(input);
outsum = zeros(siz(2:end));
outssq = zeros(siz(2:end));
pvec = [2 setdiff(1:numel(siz),2)];
ft_progress('init', feedback, 'computing metric...');
%first compute coherency and then phaseslopeindex
for j = 1:siz(1)
ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1));
c = reshape(input(j,:,:,:,:), siz(2:end));
p1 = abs(reshape(input(j,powindx(:,1),:,:,:), siz(2:end)));
p2 = abs(reshape(input(j,powindx(:,2),:,:,:), siz(2:end)));
p = ipermute(phaseslope(permute(c./sqrt(p1.*p2), pvec), nbin, normalize), pvec);
outsum = outsum + p;
outssq = outssq + p.^2;
end
ft_progress('close');
elseif length(strfind(dimord, 'chan'))==2 || length(strfind(dimord, 'pos'))==2,
%crossterms are described by chan_chan_therest
siz = size(input);
outsum = zeros(siz(2:end));
outssq = zeros(siz(2:end));
pvec = [3 setdiff(1:numel(siz),3)];
ft_progress('init', feedback, 'computing metric...');
for j = 1:siz(1)
ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1));
p1 = zeros([siz(2) 1 siz(4:end)]);
p2 = zeros([1 siz(3) siz(4:end)]);
for k = 1:siz(2)
p1(k,1,:,:,:,:) = input(j,k,k,:,:,:,:);
p2(1,k,:,:,:,:) = input(j,k,k,:,:,:,:);
end
c = reshape(input(j,:,:,:,:,:,:), siz(2:end));
p1 = p1(:,ones(1,siz(3)),:,:,:,:);
p2 = p2(ones(1,siz(2)),:,:,:,:,:);
p = ipermute(phaseslope(permute(c./sqrt(p1.*p2), pvec), nbin, normalize), pvec);
p(isnan(p)) = 0;
outsum = outsum + p;
outssq = outssq + p.^2;
end
ft_progress('close');
end
n = siz(1);
c = outsum./n;
if n>1,
n = shiftdim(sum(~isnan(input),1),1);
if hasjack
bias = (n-1).^2;
else
bias = 1;
end
v = bias.*(outssq - (outsum.^2)./n)./(n - 1);
else
v = [];
end
%---------------------------------------
function [y] = phaseslope(x, n, norm)
m = size(x, 1); %total number of frequency bins
y = zeros(size(x));
x(1:end-1,:,:,:,:) = conj(x(1:end-1,:,:,:,:)).*x(2:end,:,:,:,:);
if strcmp(norm, 'yes')
coh = zeros(size(x));
coh(1:end-1,:,:,:,:) = (abs(x(1:end-1,:,:,:,:)) .* abs(x(2:end,:,:,:,:))) + 1;
%FIXME why the +1? get the coherence
for k = 1:m
begindx = max(1,k-n);
endindx = min(m,k+n);
y(k,:,:,:,:) = imag(nansum(x(begindx:endindx,:,:,:,:)./coh(begindx:endindx,:,:,:,:),1));
end
else
for k = 1:m
begindx = max(1,k-n);
endindx = min(m,k+n);
y(k,:,:,:,:) = imag(nansum(x(begindx:endindx,:,:,:,:),1));
end
end
|
github | philippboehmsturm/antx-master | beamformer_pcc.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/inverse/beamformer_pcc.m | 10,227 | utf_8 | bac50bab9f076969adba7e767bd9e0d5 | function [dipout] = beamformer_pcc(dip, grad, vol, dat, Cf, varargin)
% BEAMFORMER_PCC implements an experimental beamformer based on partial canonical
% correlations or coherences.
%
% Use and/or distribution of this function outside the F.C. Donders
% Centre is strictly prohibited!
%
% Copyright (C) 2005-2008, Robert Oostenveld & Jan-Mathijs Schoffelen
% Subversion does not use the Log keyword, use 'svn log <filename>' or 'svn -v log | less' to get detailled information
if mod(nargin-5,2)
% the first 5 arguments are fixed, the other arguments should come in pairs
error('invalid number of optional arguments');
end
% these optional settings do not have defaults
refchan = keyval('refchan', varargin);
refdip = keyval('refdip', varargin);
supchan = keyval('supchan', varargin);
supdip = keyval('supdip', varargin);
% these settings pertain to the forward model, the defaults are set in compute_leadfield
reducerank = keyval('reducerank', varargin);
normalize = keyval('normalize', varargin);
normalizeparam = keyval('normalizeparam', varargin);
% these optional settings have defaults
feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'text'; end
keepcsd = keyval('keepcsd', varargin); if isempty(keepcsd), keepcsd = 'no'; end
keepfilter = keyval('keepfilter', varargin); if isempty(keepfilter), keepfilter = 'no'; end
keepleadfield = keyval('keepleadfield', varargin); if isempty(keepleadfield), keepleadfield = 'no'; end
keepmom = keyval('keepmom', varargin); if isempty(keepmom), keepmom = 'yes'; end
lambda = keyval('lambda', varargin); if isempty(lambda ), lambda = 0; end
projectnoise = keyval('projectnoise', varargin); if isempty(projectnoise), projectnoise = 'yes'; end
realfilter = keyval('realfilter', varargin); if isempty(realfilter), realfilter = 'yes'; end
% convert the yes/no arguments to the corresponding logical values
keepcsd = strcmp(keepcsd, 'yes'); % see below
keepfilter = strcmp(keepfilter, 'yes');
keepleadfield = strcmp(keepleadfield, 'yes');
keepmom = strcmp(keepmom, 'yes');
projectnoise = strcmp(projectnoise, 'yes');
realfilter = strcmp(realfilter, 'yes');
% the postprocessing of the pcc beamformer always requires the csd matrix
keepcsd = 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% find the dipole positions that are inside/outside the brain
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(dip, 'inside') & ~isfield(dip, 'outside');
insideLogical = ft_inside_vol(dip.pos, vol);
dip.inside = find(insideLogical);
dip.outside = find(~dip.inside);
elseif isfield(dip, 'inside') & ~isfield(dip, 'outside');
dip.outside = setdiff(1:size(dip.pos,1), dip.inside);
elseif ~isfield(dip, 'inside') & isfield(dip, 'outside');
dip.inside = setdiff(1:size(dip.pos,1), dip.outside);
end
% select only the dipole positions inside the brain for scanning
dip.origpos = dip.pos;
dip.originside = dip.inside;
dip.origoutside = dip.outside;
if isfield(dip, 'mom')
dip.mom = dip.mom(:, dip.inside);
end
if isfield(dip, 'leadfield')
fprintf('using precomputed leadfields\n');
dip.leadfield = dip.leadfield(dip.inside);
end
if isfield(dip, 'filter')
fprintf('using precomputed filters\n');
dip.filter = dip.filter(dip.inside);
end
dip.pos = dip.pos(dip.inside, :);
dip.inside = 1:size(dip.pos,1);
dip.outside = [];
if ~isempty(refdip)
rf = ft_compute_leadfield(refdip, grad, vol, 'reducerank', reducerank, 'normalize', normalize);
else
rf = [];
end
if ~isempty(supdip)
sf = ft_compute_leadfield(supdip, grad, vol, 'reducerank', reducerank, 'normalize', normalize);
else
sf = [];
end
refchan = refchan; % these can be passed as optional inputs
supchan = supchan; % these can be passed as optional inputs
megchan = setdiff(1:size(Cf,1), [refchan supchan]);
Nrefchan = length(refchan);
Nsupchan = length(supchan);
Nmegchan = length(megchan);
Nchan = size(Cf,1); % should equal Nmegchan + Nrefchan + Nsupchan
Cmeg = Cf(megchan,megchan); % the filter uses the csd between all MEG channels
isrankdeficient = (rank(Cmeg)<size(Cmeg,1));
if isrankdeficient && ~isfield(dip, 'filter')
warning('cross-spectral density matrix is rank deficient')
end
% it is difficult to give a quantitative estimate of lambda, therefore also
% support relative (percentage) measure that can be specified as string (e.g. '10%')
if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%'
ratio = sscanf(lambda, '%f%%');
ratio = ratio/100;
lambda = ratio * trace(Cmeg)/size(Cmeg,1);
end
if projectnoise
% estimate the noise power, which is further assumed to be equal and uncorrelated over channels
if isrankdeficient
% estimated noise floor is equal to or higher than lambda
noise = lambda;
else
% estimate the noise level in the covariance matrix by the smallest singular value
noise = svd(Cmeg);
noise = noise(end);
% estimated noise floor is equal to or higher than lambda
noise = max(noise, lambda);
end
end
if realfilter
% construct the filter only on the real part of the CSD matrix, i.e. filter is real
invCmeg = pinv(real(Cmeg) + lambda*eye(Nmegchan));
else
% construct the filter on the complex CSD matrix, i.e. filter contains imaginary component as well
% this results in a phase rotation of the channel data if the filter is applied to the data
invCmeg = pinv(Cmeg + lambda*eye(Nmegchan));
end
% start the scanning with the proper metric
ft_progress('init', feedback, 'beaming sources\n');
for i=1:size(dip.pos,1)
if isfield(dip, 'leadfield') && isfield(dip, 'mom') && size(dip.mom, 1)==size(dip.leadfield{i}, 2)
% reuse the leadfield that was previously computed and project
lf = dip.leadfield{i} * dip.mom(:,i);
elseif isfield(dip, 'leadfield') && isfield(dip, 'mom')
% reuse the leadfield that was previously computed but don't project
lf = dip.leadfield{i};
elseif isfield(dip, 'leadfield') && ~isfield(dip, 'mom'),
% reuse the leadfield that was previously computed
lf = dip.leadfield{i};
elseif ~isfield(dip, 'leadfield') && isfield(dip, 'mom')
% compute the leadfield for a fixed dipole orientation
lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam) * dip.mom(:,i);
else
% compute the leadfield
lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam);
end
% concatenate scandip, refdip and supdip
lfa = [lf rf sf];
if isfield(dip, 'filter')
% use the provided filter
filt = dip.filter{i};
else
% construct the spatial filter
filt = pinv(lfa' * invCmeg * lfa) * lfa' * invCmeg; % use PINV/SVD to cover rank deficient leadfield
end
% concatenate the source filters with the channel filters
Ndip = size(lfa, 2);
filtn = zeros(Ndip+Nrefchan+Nsupchan, Nmegchan+Nrefchan+Nsupchan);
% this part of the filter relates to the sources
filtn(1:Ndip,megchan) = filt;
% this part of the filter relates to the channels
filtn((Ndip+1):end,setdiff(1:(Nmegchan+Nrefchan+Nsupchan), megchan)) = eye(Nrefchan+Nsupchan);
filt = filtn;
clear filtn
if keepcsd
dipout.csd{i} = filt * Cf * ctranspose(filt);
end
if projectnoise
dipout.noisecsd{i} = noise * (filt * ctranspose(filt));
end
if keepmom && ~isempty(dat)
dipout.mom{i} = filt * dat;
end
if keepfilter
dipout.filter{i} = filt;
end
if keepleadfield
dipout.leadfield{i} = lf;
end
ft_progress(i/size(dip.pos,1), 'beaming source %d from %d\n', i, size(dip.pos,1));
end % for all dipoles
ft_progress('close');
dipout.inside = dip.originside;
dipout.outside = dip.origoutside;
dipout.pos = dip.origpos;
% remember how all components in the output csd should be interpreted
scandiplabel = repmat({'scandip'}, 1, size(lf, 2)); % based on last leadfield
refdiplabel = repmat({'refdip'}, 1, size(rf, 2));
supdiplabel = repmat({'supdip'}, 1, size(sf, 2));
refchanlabel = repmat({'refchan'}, 1, Nrefchan);
supchanlabel = repmat({'supchan'}, 1, Nsupchan);
% concatenate all the labels
dipout.csdlabel = [scandiplabel refdiplabel supdiplabel refchanlabel supchanlabel];
% reassign the scan values over the inside and outside grid positions
if isfield(dipout, 'leadfield')
dipout.leadfield(dipout.inside) = dipout.leadfield;
dipout.leadfield(dipout.outside) = {[]};
end
if isfield(dipout, 'filter')
dipout.filter(dipout.inside) = dipout.filter;
dipout.filter(dipout.outside) = {[]};
end
if isfield(dipout, 'mom')
dipout.mom(dipout.inside) = dipout.mom;
dipout.mom(dipout.outside) = {[]};
end
if isfield(dipout, 'csd')
dipout.csd(dipout.inside) = dipout.csd;
dipout.csd(dipout.outside) = {[]};
end
if isfield(dipout, 'noisecsd')
dipout.noisecsd(dipout.inside) = dipout.noisecsd;
dipout.noisecsd(dipout.outside) = {[]};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute the pseudo inverse. This is the same as the
% standard Matlab function, except that the default tolerance is twice as
% high.
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision: 3009 $ $Date: 2009/01/07 13:12:03 $
% default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = pinv(A,varargin)
[m,n] = size(A);
if n > m
X = pinv(A',varargin{:})';
else
[U,S,V] = svd(A,0);
if m > 1, s = diag(S);
elseif m == 1, s = S(1);
else s = 0;
end
if nargin == 2
tol = varargin{1};
else
tol = 10 * max(m,n) * max(s) * eps;
end
r = sum(s > tol);
if (r == 0)
X = zeros(size(A'),class(A));
else
s = diag(ones(r,1)./s(1:r));
X = V(:,1:r)*s*U(:,1:r)';
end
end
|
github | philippboehmsturm/antx-master | beamformer_dics.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/inverse/beamformer_dics.m | 24,036 | utf_8 | e7b43ec321435a26a82211dbf8eba2b7 | function [dipout] = beamformer_dics(dip, grad, vol, dat, Cf, varargin)
% BEAMFORMER_DICS scans on pre-defined dipole locations with a single dipole
% and returns the beamformer spatial filter output for a dipole on every
% location. Dipole locations that are outside the head will return a
% NaN value.
%
% Use as
% [dipout] = beamformer_dics(dipin, grad, vol, dat, cov, varargin)
% where
% dipin is the input dipole model
% grad is the gradiometer definition
% vol is the volume conductor definition
% dat is the data matrix with the ERP or ERF
% cov is the data covariance or cross-spectral density matrix
% and
% dipout is the resulting dipole model with all details
%
% The input dipole model consists of
% dipin.pos positions for dipole, e.g. regular grid, Npositions x 3
% dipin.mom dipole orientation (optional), 3 x Npositions
%
% Additional options should be specified in key-value pairs and can be
% 'Pr' = power of the external reference channel
% 'Cr' = cross spectral density between all data channels and the external reference channel
% 'refdip' = location of dipole with which coherence is computed
% 'lambda' = regularisation parameter
% 'powmethod' = can be 'trace' or 'lambda1'
% 'feedback' = give ft_progress indication, can be 'text', 'gui' or 'none'
% 'fixedori' = use fixed or free orientation, can be 'yes' or 'no'
% 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no'
% 'realfilter' = construct a real-valued filter, can be 'yes' or 'no'
% 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no'
% 'keepleadfield' = remember the forward computation, can be 'yes' or 'no'
% 'keepcsd' = remember the estimated cross-spectral density, can be 'yes' or 'no'
%
% These options influence the forward computation of the leadfield
% 'reducerank' = reduce the leadfield rank, can be 'no' or a number (e.g. 2)
% 'normalize' = normalize the leadfield
% 'normalizeparam' = parameter for depth normalization (default = 0.5)
%
% If the dipole definition only specifies the dipole location, a rotating
% dipole (regional source) is assumed on each location. If a dipole moment
% is specified, its orientation will be used and only the strength will
% be fitted to the data.
% Copyright (C) 2003-2008, Robert Oostenveld
%
% Subversion does not use the Log keyword, use 'svn log <filename>' or 'svn -v log | less' to get detailled information
if mod(nargin-5,2)
% the first 5 arguments are fixed, the other arguments should come in pairs
error('invalid number of optional arguments');
end
% these optional settings do not have defaults
Pr = keyval('Pr', varargin);
Cr = keyval('Cr', varargin);
refdip = keyval('refdip', varargin);
powmethod = keyval('powmethod', varargin); % the default for this is set below
realfilter = keyval('realfilter', varargin); % the default for this is set below
% these settings pertain to the forward model, the defaults are set in compute_leadfield
reducerank = keyval('reducerank', varargin);
normalize = keyval('normalize', varargin);
normalizeparam = keyval('normalizeparam', varargin);
% these optional settings have defaults
feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'text'; end
keepcsd = keyval('keepcsd', varargin); if isempty(keepcsd), keepcsd = 'no'; end
keepfilter = keyval('keepfilter', varargin); if isempty(keepfilter), keepfilter = 'no'; end
keepleadfield = keyval('keepleadfield', varargin); if isempty(keepleadfield), keepleadfield = 'no'; end
lambda = keyval('lambda', varargin); if isempty(lambda ), lambda = 0; end
projectnoise = keyval('projectnoise', varargin); if isempty(projectnoise), projectnoise = 'yes'; end
fixedori = keyval('fixedori', varargin); if isempty(fixedori), fixedori = 'no'; end
subspace = keyval('subspace', varargin);
% convert the yes/no arguments to the corresponding logical values
keepcsd = strcmp(keepcsd, 'yes');
keepfilter = strcmp(keepfilter, 'yes');
keepleadfield = strcmp(keepleadfield, 'yes');
projectnoise = strcmp(projectnoise, 'yes');
fixedori = strcmp(fixedori, 'yes');
% FIXME besides regular/complex lambda1, also implement a real version
% default is to use the largest singular value of the csd matrix, see Gross 2001
if isempty(powmethod)
powmethod = 'lambda1';
end
% default is to be consistent with the original description of DICS in Gross 2001
if isempty(realfilter)
realfilter = 'no';
end
% use these two logical flags instead of doing the string comparisons each time again
powtrace = strcmp(powmethod, 'trace');
powlambda1 = strcmp(powmethod, 'lambda1');
if ~isempty(Cr)
% ensure that the cross-spectral density with the reference signal is a column matrix
Cr = Cr(:);
end
if isfield(dip, 'mom') && fixedori
error('you cannot specify a dipole orientation and fixedmom simultaneously');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% find the dipole positions that are inside/outside the brain
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(dip, 'inside') && ~isfield(dip, 'outside');
insideLogical = ft_inside_vol(dip.pos, vol);
dip.inside = find(insideLogical);
dip.outside = find(~dip.inside);
elseif isfield(dip, 'inside') && ~isfield(dip, 'outside');
dip.outside = setdiff(1:size(dip.pos,1), dip.inside);
elseif ~isfield(dip, 'inside') && isfield(dip, 'outside');
dip.inside = setdiff(1:size(dip.pos,1), dip.outside);
end
% select only the dipole positions inside the brain for scanning
dip.origpos = dip.pos;
dip.originside = dip.inside;
dip.origoutside = dip.outside;
if isfield(dip, 'mom')
dip.mom = dip.mom(:,dip.inside);
end
if isfield(dip, 'leadfield')
fprintf('using precomputed leadfields\n');
dip.leadfield = dip.leadfield(dip.inside);
end
if isfield(dip, 'filter')
fprintf('using precomputed filters\n');
dip.filter = dip.filter(dip.inside);
end
if isfield(dip, 'subspace')
fprintf('using subspace projection\n');
dip.subspace = dip.subspace(dip.inside);
end
dip.pos = dip.pos(dip.inside, :);
dip.inside = 1:size(dip.pos,1);
dip.outside = [];
% dics has the following sub-methods, which depend on the function input arguments
% power only, cortico-muscular coherence and cortico-cortical coherence
if ~isempty(Cr) && ~isempty(Pr) && isempty(refdip)
% compute cortico-muscular coherence, using reference cross spectral density
submethod = 'dics_refchan';
elseif isempty(Cr) && isempty(Pr) && ~isempty(refdip)
% compute cortico-cortical coherence with a dipole at the reference position
submethod = 'dics_refdip';
elseif isempty(Cr) && isempty(Pr) && isempty(refdip)
% only compute power of a dipole at the grid positions
submethod = 'dics_power';
else
error('invalid combination of input arguments for dics');
end
isrankdeficient = (rank(Cf)<size(Cf,1));
if isrankdeficient && ~isfield(dip, 'filter')
warning('cross-spectral density matrix is rank deficient')
end
% it is difficult to give a quantitative estimate of lambda, therefore also
% support relative (percentage) measure that can be specified as string (e.g. '10%')
if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%'
ratio = sscanf(lambda, '%f%%');
ratio = ratio/100;
lambda = ratio * trace(Cf)/size(Cf,1);
end
if projectnoise
% estimate the noise power, which is further assumed to be equal and uncorrelated over channels
if isrankdeficient
% estimated noise floor is equal to or higher than lambda
noise = lambda;
else
% estimate the noise level in the covariance matrix by the smallest singular value
noise = svd(Cf);
noise = noise(end);
% estimated noise floor is equal to or higher than lambda
noise = max(noise, lambda);
end
end
% the inverse only has to be computed once for all dipoles
if strcmp(realfilter, 'yes')
% the filter is computed using only the leadfield and the inverse covariance or CSD matrix
% therefore using the real-valued part of the CSD matrix here ensures a real-valued filter
invCf = pinv(real(Cf) + lambda * eye(size(Cf)));
else
invCf = pinv(Cf + lambda * eye(size(Cf)));
end
if isfield(dip, 'subspace')
fprintf('using source-specific subspace projection\n');
% remember the original data prior to the voxel dependent subspace projection
dat_pre_subspace = dat;
Cf_pre_subspace = Cf;
if strcmp(submethod, 'dics_refchan')
Cr_pre_subspace = Cr;
Pr_pre_subspace = Pr;
end
elseif ~isempty(subspace)
fprintf('using data-specific subspace projection\n');
% TODO implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM
if numel(subspace)==1,
% interpret this as a truncation of the eigenvalue-spectrum
% if <1 it is a fraction of the largest eigenvalue
% if >=1 it is the number of largest eigenvalues
dat_pre_subspace = dat;
Cf_pre_subspace = Cf;
[u, s, v] = svd(real(Cf));
if subspace<1,
sel = find(diag(s)./s(1,1) > subspace);
subspace = max(sel);
end
Cf = s(1:subspace,1:subspace);
% this is equivalent to subspace*Cf*subspace' but behaves well numerically
% by construction.
invCf = diag(1./diag(Cf));
subspace = u(:,1:subspace)';
dat = subspace*dat;
if strcmp(submethod, 'dics_refchan')
Cr = subspace*Cr;
end
else
Cf_pre_subspace = Cf;
Cf = subspace*Cf*subspace'; % here the subspace can be different from
% the singular vectors of Cy, so we have to do the sandwiching as opposed
% to line 216
if strcmp(realfilter, 'yes')
invCf = pinv(real(Cf));
else
invCf = pinv(Cf);
end
if strcmp(submethod, 'dics_refchan')
Cr = subspace*Cr;
end
end
end
% start the scanning with the proper metric
ft_progress('init', feedback, 'scanning grid');
switch submethod
case 'dics_power'
% only compute power of a dipole at the grid positions
for i=1:size(dip.pos,1)
if isfield(dip, 'leadfield') && isfield(dip, 'mom') && size(dip.mom, 1)==size(dip.leadfield{i}, 2)
% reuse the leadfield that was previously computed and project
lf = dip.leadfield{i} * dip.mom(:,i);
elseif isfield(dip, 'leadfield') && isfield(dip, 'mom')
% reuse the leadfield that was previously computed but don't project
lf = dip.leadfield{i};
elseif isfield(dip, 'leadfield') && ~isfield(dip, 'mom')
% reuse the leadfield that was previously computed
lf = dip.leadfield{i};
elseif ~isfield(dip, 'leadfield') && isfield(dip, 'mom')
% compute the leadfield for a fixed dipole orientation
lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam) * dip.mom(:,i);
else
% compute the leadfield
lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam);
end
if isfield(dip, 'subspace')
% do subspace projection of the forward model
lf = dip.subspace{i} * lf;
% the cross-spectral density becomes voxel dependent due to the projection
Cf = dip.subspace{i} * Cf_pre_subspace * dip.subspace{i}';
if strcmp(realfilter, 'yes')
invCf = pinv(dip.subspace{i} * (real(Cf_pre_subspace) + lambda * eye(size(Cf_pre_subspace))) * dip.subspace{i}');
else
invCf = pinv(dip.subspace{i} * (Cf_pre_subspace + lambda * eye(size(Cf_pre_subspace))) * dip.subspace{i}');
end
elseif ~isempty(subspace)
% do subspace projection of the forward model only
lforig = lf;
lf = subspace * lf;
% according to Kensuke's paper, the eigenspace bf boils down to projecting
% the 'traditional' filter onto the subspace
% spanned by the first k eigenvectors [u,s,v] = svd(Cy); filt = ESES*filt;
% ESES = u(:,1:k)*u(:,1:k)';
% however, even though it seems that the shape of the filter is identical to
% the shape it is obtained with the following code, the w*lf=I does not
% hold.
end
if fixedori
% compute the leadfield for the optimal dipole orientation
% subsequently the leadfield for only that dipole orientation will
% be used for the final filter computation
if isfield(dip, 'filter') && size(dip.filter{i},1)~=1
filt = dip.filter{i};
else
filt = pinv(lf' * invCf * lf) * lf' * invCf;
end
[u, s, v] = svd(real(filt * Cf * ctranspose(filt)));
maxpowori = u(:,1);
eta = s(1,1)./s(2,2);
lf = lf * maxpowori;
dipout.ori{i} = maxpowori;
dipout.eta{i} = eta;
if ~isempty(subspace), lforig = lforig * maxpowori; end
end
if isfield(dip, 'filter')
% use the provided filter
filt = dip.filter{i};
else
% construct the spatial filter
filt = pinv(lf' * invCf * lf) * lf' * invCf; % Gross eqn. 3, use PINV/SVD to cover rank deficient leadfield
end
csd = filt * Cf * ctranspose(filt); % Gross eqn. 4 and 5
if powlambda1
dipout.pow(i) = lambda1(csd); % compute the power at the dipole location, Gross eqn. 8
elseif powtrace
dipout.pow(i) = real(trace(csd)); % compute the power at the dipole location
end
if keepcsd
dipout.csd{i} = csd;
end
if projectnoise
if powlambda1
dipout.noise(i) = noise * lambda1(filt * ctranspose(filt));
elseif powtrace
dipout.noise(i) = noise * real(trace(filt * ctranspose(filt)));
end
if keepcsd
dipout.noisecsd{i} = noise * filt * ctranspose(filt);
end
end
if keepfilter
if ~isempty(subspace)
dipout.filter{i} = filt*subspace; %FIXME should this be subspace, or pinv(subspace)?
else
dipout.filter{i} = filt;
end
end
if keepleadfield
if ~isempty(subspace)
dipout.leadfield{i} = lforig;
else
dipout.leadfield{i} = lf;
end
end
ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1));
end
case 'dics_refchan'
% compute cortico-muscular coherence, using reference cross spectral density
for i=1:size(dip.pos,1)
if isfield(dip, 'leadfield')
% reuse the leadfield that was previously computed
lf = dip.leadfield{i};
elseif isfield(dip, 'mom')
% compute the leadfield for a fixed dipole orientation
lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize) .* dip.mom(i,:)';
else
% compute the leadfield
lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize);
end
if isfield(dip, 'subspace')
% do subspace projection of the forward model
lforig = lf;
lf = dip.subspace{i} * lf;
% the cross-spectral density becomes voxel dependent due to the projection
Cf = dip.subspace{i} * Cf_pre_subspace * dip.subspace{i}';
invCf = pinv(dip.subspace{i} * (Cf_pre_subspace + lambda * eye(size(Cf))) * dip.subspace{i}');
elseif ~isempty(subspace)
% do subspace projection of the forward model only
lforig = lf;
lf = subspace * lf;
% according to Kensuke's paper, the eigenspace bf boils down to projecting
% the 'traditional' filter onto the subspace
% spanned by the first k eigenvectors [u,s,v] = svd(Cy); filt = ESES*filt;
% ESES = u(:,1:k)*u(:,1:k)';
% however, even though it seems that the shape of the filter is identical to
% the shape it is obtained with the following code, the w*lf=I does not
% hold.
end
if fixedori
% compute the leadfield for the optimal dipole orientation
% subsequently the leadfield for only that dipole orientation will be used for the final filter computation
filt = pinv(lf' * invCf * lf) * lf' * invCf;
[u, s, v] = svd(real(filt * Cf * ctranspose(filt)));
maxpowori = u(:,1);
lf = lf * maxpowori;
dipout.ori{i} = maxpowori;
end
if isfield(dip, 'filter')
% use the provided filter
filt = dip.filter{i};
else
% construct the spatial filter
filt = pinv(lf' * invCf * lf) * lf' * invCf; % use PINV/SVD to cover rank deficient leadfield
end
if powlambda1
[pow, ori] = lambda1(filt * Cf * ctranspose(filt)); % compute the power and orientation at the dipole location, Gross eqn. 4, 5 and 8
elseif powtrace
pow = real(trace(filt * Cf * ctranspose(filt))); % compute the power at the dipole location
end
csd = filt*Cr; % Gross eqn. 6
if powlambda1
% FIXME this should use the dipole orientation with maximum power
coh = lambda1(csd)^2 / (pow * Pr); % Gross eqn. 9
elseif powtrace
coh = norm(csd)^2 / (pow * Pr);
end
dipout.pow(i) = pow;
dipout.coh(i) = coh;
if keepcsd
dipout.csd{i} = csd;
end
if projectnoise
if powlambda1
dipout.noise(i) = noise * lambda1(filt * ctranspose(filt));
elseif powtrace
dipout.noise(i) = noise * real(trace(filt * ctranspose(filt)));
end
if keepcsd
dipout.noisecsd{i} = noise * filt * ctranspose(filt);
end
end
if keepfilter
dipout.filter{i} = filt;
end
if keepleadfield
if ~isempty(subspace)
dipout.leadfield{i} = lforig;
else
dipout.leadfield{i} = lf;
end
end
ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1));
end
case 'dics_refdip'
if isfield(dip, 'subspace') || ~isempty(subspace)
error('subspace projections are not supported for beaming cortico-cortical coherence');
end
if fixedori
error('fixed orientations are not supported for beaming cortico-cortical coherence');
end
% compute cortio-cortical coherence with a dipole at the reference position
lf1 = ft_compute_leadfield(refdip, grad, vol, 'reducerank', reducerank, 'normalize', normalize);
% construct the spatial filter for the first (reference) dipole location
filt1 = pinv(lf1' * invCf * lf1) * lf1' * invCf; % use PINV/SVD to cover rank deficient leadfield
if powlambda1
Pref = lambda1(filt1 * Cf * ctranspose(filt1)); % compute the power at the first dipole location, Gross eqn. 8
elseif powtrace
Pref = real(trace(filt1 * Cf * ctranspose(filt1))); % compute the power at the first dipole location
end
for i=1:size(dip.pos,1)
if isfield(dip, 'leadfield')
% reuse the leadfield that was previously computed
lf2 = dip.leadfield{i};
elseif isfield(dip, 'mom')
% compute the leadfield for a fixed dipole orientation
lf2 = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize) .* dip.mom(i,:)';
else
% compute the leadfield
lf2 = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize);
end
if isfield(dip, 'filter')
% use the provided filter
filt2 = dip.filter{i};
else
% construct the spatial filter for the second dipole location
filt2 = pinv(lf2' * invCf * lf2) * lf2' * invCf; % use PINV/SVD to cover rank deficient leadfield
end
csd = filt1 * Cf * ctranspose(filt2); % compute the cross spectral density between the two dipoles, Gross eqn. 4
if powlambda1
pow = lambda1(filt2 * Cf * ctranspose(filt2)); % compute the power at the second dipole location, Gross eqn. 8
elseif powtrace
pow = real(trace(filt2 * Cf * ctranspose(filt2))); % compute the power at the second dipole location
end
if powlambda1
coh = lambda1(csd)^2 / (pow * Pref); % compute the coherence between the first and second dipole
elseif powtrace
coh = real(trace((csd)))^2 / (pow * Pref); % compute the coherence between the first and second dipole
end
dipout.pow(i) = pow;
dipout.coh(i) = coh;
if keepcsd
dipout.csd{i} = csd;
end
if projectnoise
if powlambda1
dipout.noise(i) = noise * lambda1(filt2 * ctranspose(filt2));
elseif powtrace
dipout.noise(i) = noise * real(trace(filt2 * ctranspose(filt2)));
end
if keepcsd
dipout.noisecsd{i} = noise * filt2 * ctranspose(filt2);
end
end
if keepleadfield
dipout.leadfield{i} = lf2;
end
ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1));
end
end % switch submethod
ft_progress('close');
dipout.inside = dip.originside;
dipout.outside = dip.origoutside;
dipout.pos = dip.origpos;
% reassign the scan values over the inside and outside grid positions
if isfield(dipout, 'leadfield')
dipout.leadfield(dipout.inside) = dipout.leadfield;
dipout.leadfield(dipout.outside) = {[]};
end
if isfield(dipout, 'filter')
dipout.filter(dipout.inside) = dipout.filter;
dipout.filter(dipout.outside) = {[]};
end
if isfield(dipout, 'ori')
dipout.ori(dipout.inside) = dipout.ori;
dipout.ori(dipout.outside) = {[]};
end
if isfield(dipout, 'pow')
dipout.pow(dipout.inside) = dipout.pow;
dipout.pow(dipout.outside) = nan;
end
if isfield(dipout, 'noise')
dipout.noise(dipout.inside) = dipout.noise;
dipout.noise(dipout.outside) = nan;
end
if isfield(dipout, 'coh')
dipout.coh(dipout.inside) = dipout.coh;
dipout.coh(dipout.outside) = nan;
end
if isfield(dipout, 'csd')
dipout.csd(dipout.inside) = dipout.csd;
dipout.csd(dipout.outside) = {[]};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to obtain the largest singular value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [s, ori] = lambda1(x)
% determine the largest singular value, which corresponds to the power along the dominant direction
[u, s, v] = svd(x);
s = s(1);
ori = u(:,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute the pseudo inverse. This is the same as the
% standard Matlab function, except that the default tolerance is twice as
% high.
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision: 3515 $ $Date: 2009/06/17 13:40:37 $
% default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = pinv(A,varargin)
[m,n] = size(A);
if n > m
X = pinv(A',varargin{:})';
else
[U,S,V] = svd(A,0);
if m > 1, s = diag(S);
elseif m == 1, s = S(1);
else s = 0;
end
if nargin == 2
tol = varargin{1};
else
tol = 10 * max(m,n) * max(s) * eps;
end
r = sum(s > tol);
if (r == 0)
X = zeros(size(A'),class(A));
else
s = diag(ones(r,1)./s(1:r));
X = V(:,1:r)*s*U(:,1:r)';
end
end
|
github | philippboehmsturm/antx-master | beamformer_lcmv.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/inverse/beamformer_lcmv.m | 15,746 | utf_8 | 8ca0fc938e68be4e5dbd350151138e77 | function [dipout] = beamformer_lcmv(dip, grad, vol, dat, Cy, varargin)
% BEAMFORMER_LCMV scans on pre-defined dipole locations with a single dipole
% and returns the beamformer spatial filter output for a dipole on every
% location. Dipole locations that are outside the head will return a
% NaN value.
%
% Use as
% [dipout] = beamformer_lcmv(dipin, grad, vol, dat, cov, varargin)
% where
% dipin is the input dipole model
% grad is the gradiometer definition
% vol is the volume conductor definition
% dat is the data matrix with the ERP or ERF
% cov is the data covariance or cross-spectral density matrix
% and
% dipout is the resulting dipole model with all details
%
% The input dipole model consists of
% dipin.pos positions for dipole, e.g. regular grid, Npositions x 3
% dipin.mom dipole orientation (optional), 3 x Npositions
%
% Additional options should be specified in key-value pairs and can be
% 'lambda' = regularisation parameter
% 'powmethod' = can be 'trace' or 'lambda1'
% 'feedback' = give ft_progress indication, can be 'text', 'gui' or 'none' (default)
% 'fixedori' = use fixed or free orientation, can be 'yes' or 'no'
% 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no'
% 'projectmom' = project the dipole moment timecourse on the direction of maximal power, can be 'yes' or 'no'
% 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no'
% 'keepleadfield' = remember the forward computation, can be 'yes' or 'no'
% 'keepmom' = remember the estimated dipole moment, can be 'yes' or 'no'
% 'keepcov' = remember the estimated dipole covariance, can be 'yes' or 'no'
%
% These options influence the forward computation of the leadfield
% 'reducerank' = reduce the leadfield rank, can be 'no' or a number (e.g. 2)
% 'normalize' = normalize the leadfield
% 'normalizeparam' = parameter for depth normalization (default = 0.5)
%
% If the dipole definition only specifies the dipole location, a rotating
% dipole (regional source) is assumed on each location. If a dipole moment
% is specified, its orientation will be used and only the strength will
% be fitted to the data.
% Copyright (C) 2003-2008, Robert Oostenveld
%
% Subversion does not use the Log keyword, use 'svn log <filename>' or 'svn -v log | less' to get detailled information
if mod(nargin-5,2)
% the first 5 arguments are fixed, the other arguments should come in pairs
error('invalid number of optional arguments');
end
% these optional settings do not have defaults
powmethod = keyval('powmethod', varargin); % the default for this is set below
subspace = keyval('subspace', varargin); % used to implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM
% these settings pertain to the forward model, the defaults are set in compute_leadfield
reducerank = keyval('reducerank', varargin);
normalize = keyval('normalize', varargin);
normalizeparam = keyval('normalizeparam', varargin);
% these optional settings have defaults
feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'text'; end
keepfilter = keyval('keepfilter', varargin); if isempty(keepfilter), keepfilter = 'no'; end
keepleadfield = keyval('keepleadfield', varargin); if isempty(keepleadfield), keepleadfield = 'no'; end
keepcov = keyval('keepcov', varargin); if isempty(keepcov), keepcov = 'no'; end
keepmom = keyval('keepmom', varargin); if isempty(keepmom), keepmom = 'yes'; end
lambda = keyval('lambda', varargin); if isempty(lambda ), lambda = 0; end
projectnoise = keyval('projectnoise', varargin); if isempty(projectnoise), projectnoise = 'yes'; end
projectmom = keyval('projectmom', varargin); if isempty(projectmom), projectmom = 'no'; end
fixedori = keyval('fixedori', varargin); if isempty(fixedori), fixedori = 'no'; end
% convert the yes/no arguments to the corresponding logical values
keepfilter = strcmp(keepfilter, 'yes');
keepleadfield = strcmp(keepleadfield, 'yes');
keepcov = strcmp(keepcov, 'yes');
keepmom = strcmp(keepmom, 'yes');
projectnoise = strcmp(projectnoise, 'yes');
projectmom = strcmp(projectmom, 'yes');
fixedori = strcmp(fixedori, 'yes');
% default is to use the trace of the covariance matrix, see Van Veen 1997
if isempty(powmethod)
powmethod = 'trace';
end
% use these two logical flags instead of doing the string comparisons each time again
powtrace = strcmp(powmethod, 'trace');
powlambda1 = strcmp(powmethod, 'lambda1');
if isfield(dip, 'mom') && fixedori
error('you cannot specify a dipole orientation and fixedmom simultaneously');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% find the dipole positions that are inside/outside the brain
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(dip, 'inside') && ~isfield(dip, 'outside');
insideLogical = ft_inside_vol(dip.pos, vol);
dip.inside = find(insideLogical);
dip.outside = find(~dip.inside);
elseif isfield(dip, 'inside') && ~isfield(dip, 'outside');
dip.outside = setdiff(1:size(dip.pos,1), dip.inside);
elseif ~isfield(dip, 'inside') && isfield(dip, 'outside');
dip.inside = setdiff(1:size(dip.pos,1), dip.outside);
end
% select only the dipole positions inside the brain for scanning
dip.origpos = dip.pos;
dip.originside = dip.inside;
dip.origoutside = dip.outside;
if isfield(dip, 'mom')
dip.mom = dip.mom(:, dip.inside);
end
if isfield(dip, 'leadfield')
fprintf('using precomputed leadfields\n');
dip.leadfield = dip.leadfield(dip.inside);
end
if isfield(dip, 'filter')
fprintf('using precomputed filters\n');
dip.filter = dip.filter(dip.inside);
end
if isfield(dip, 'subspace')
fprintf('using subspace projection\n');
dip.subspace = dip.subspace(dip.inside);
end
dip.pos = dip.pos(dip.inside, :);
dip.inside = 1:size(dip.pos,1);
dip.outside = [];
isrankdeficient = (rank(Cy)<size(Cy,1));
if isrankdeficient && ~isfield(dip, 'filter')
warning('covariance matrix is rank deficient')
end
% it is difficult to give a quantitative estimate of lambda, therefore also
% support relative (percentage) measure that can be specified as string (e.g. '10%')
if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%'
ratio = sscanf(lambda, '%f%%');
ratio = ratio/100;
lambda = ratio * trace(Cy)/size(Cy,1);
end
if projectnoise
% estimate the noise power, which is further assumed to be equal and uncorrelated over channels
if isrankdeficient
% estimated noise floor is equal to or higher than lambda
noise = lambda;
else
% estimate the noise level in the covariance matrix by the smallest singular value
noise = svd(Cy);
noise = noise(end);
% estimated noise floor is equal to or higher than lambda
noise = max(noise, lambda);
end
end
% the inverse only has to be computed once for all dipoles
invCy = pinv(Cy + lambda * eye(size(Cy)));
if isfield(dip, 'subspace')
fprintf('using source-specific subspace projection\n');
% remember the original data prior to the voxel dependent subspace projection
dat_pre_subspace = dat;
Cy_pre_subspace = Cy;
elseif ~isempty(subspace)
fprintf('using data-specific subspace projection\n');
% TODO implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM
if numel(subspace)==1,
% interpret this as a truncation of the eigenvalue-spectrum
% if <1 it is a fraction of the largest eigenvalue
% if >=1 it is the number of largest eigenvalues
dat_pre_subspace = dat;
Cy_pre_subspace = Cy;
[u, s, v] = svd(real(Cy));
if subspace<1,
sel = find(diag(s)./s(1,1) > subspace);
subspace = max(sel);
else
Cy = s(1:subspace,1:subspace);
% this is equivalent to subspace*Cy*subspace' but behaves well numerically
% by construction.
invCy = diag(1./diag(Cy));
subspace = u(:,1:subspace)';
dat = subspace*dat;
end
else
dat_pre_subspace = dat;
Cy_pre_subspace = Cy;
Cy = subspace*Cy*subspace'; % here the subspace can be different from
% the singular vectors of Cy, so we have to do the sandwiching as opposed
% to line 216
invCy = pinv(Cy);
dat = subspace*dat;
end
end
% start the scanning with the proper metric
ft_progress('init', feedback, 'scanning grid');
for i=1:size(dip.pos,1)
if isfield(dip, 'leadfield') && isfield(dip, 'mom') && size(dip.mom, 1)==size(dip.leadfield{i}, 2)
% reuse the leadfield that was previously computed and project
lf = dip.leadfield{i} * dip.mom(:,i);
elseif isfield(dip, 'leadfield') && isfield(dip, 'mom')
% reuse the leadfield that was previously computed but don't project
lf = dip.leadfield{i};
elseif isfield(dip, 'leadfield') && ~isfield(dip, 'mom')
% reuse the leadfield that was previously computed
lf = dip.leadfield{i};
elseif ~isfield(dip, 'leadfield') && isfield(dip, 'mom')
% compute the leadfield for a fixed dipole orientation
lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam) * dip.mom(:,i);
else
% compute the leadfield
lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam);
end
if isfield(dip, 'subspace')
% do subspace projection of the forward model
lf = dip.subspace{i} * lf;
% the data and the covariance become voxel dependent due to the projection
dat = dip.subspace{i} * dat_pre_subspace;
Cy = dip.subspace{i} * (Cy_pre_subspace + lambda * eye(size(Cy_pre_subspace))) * dip.subspace{i}';
invCy = pinv(dip.subspace{i} * (Cy_pre_subspace + lambda * eye(size(Cy_pre_subspace))) * dip.subspace{i}');
elseif ~isempty(subspace)
% do subspace projection of the forward model only
lforig = lf;
lf = subspace * lf;
% according to Kensuke's paper, the eigenspace bf boils down to projecting
% the 'traditional' filter onto the subspace
% spanned by the first k eigenvectors [u,s,v] = svd(Cy); filt = ESES*filt;
% ESES = u(:,1:k)*u(:,1:k)';
% however, even though it seems that the shape of the filter is identical to
% the shape it is obtained with the following code, the w*lf=I does not hold.
end
if fixedori
% compute the leadfield for the optimal dipole orientation
% subsequently the leadfield for only that dipole orientation will be used for the final filter computation
% filt = pinv(lf' * invCy * lf) * lf' * invCy;
% [u, s, v] = svd(real(filt * Cy * ctranspose(filt)));
% in this step the filter computation is not necessary, use the quick way to compute the voxel level covariance (cf. van Veen 1997)
[u, s, v] = svd(real(pinv(lf' * invCy *lf)));
eta = u(:,1);
lf = lf * eta;
if ~isempty(subspace), lforig = lforig * eta; end
dipout.ori{i} = eta;
end
if isfield(dip, 'filter')
% use the provided filter
filt = dip.filter{i};
else
% construct the spatial filter
filt = pinv(lf' * invCy * lf) * lf' * invCy; % van Veen eqn. 23, use PINV/SVD to cover rank deficient leadfield
end
if projectmom
[u, s, v] = svd(filt * Cy * ctranspose(filt));
mom = u(:,1);
filt = (mom') * filt;
end
if powlambda1
% dipout.pow(i) = lambda1(pinv(lf' * invCy * lf)); % this is more efficient if the filters are not present
dipout.pow(i) = lambda1(filt * Cy * ctranspose(filt)); % this is more efficient if the filters are present
elseif powtrace
% dipout.pow(i) = trace(pinv(lf' * invCy * lf)); % this is more efficient if the filters are not present, van Veen eqn. 24
dipout.pow(i) = trace(filt * Cy * ctranspose(filt)); % this is more efficient if the filters are present
end
if keepcov
% compute the source covariance matrix
dipout.cov{i} = filt * Cy * ctranspose(filt);
end
if keepmom && ~isempty(dat)
% estimate the instantaneous dipole moment at the current position
dipout.mom{i} = filt * dat;
end
if projectnoise
% estimate the power of the noise that is projected through the filter
if powlambda1
dipout.noise(i) = noise * lambda1(filt * ctranspose(filt));
elseif powtrace
dipout.noise(i) = noise * trace(filt * ctranspose(filt));
end
if keepcov
dipout.noisecov{i} = noise * filt * ctranspose(filt);
end
end
if keepfilter
if ~isempty(subspace)
dipout.filter{i} = filt*subspace;
%dipout.filter{i} = filt*pinv(subspace);
else
dipout.filter{i} = filt;
end
end
if keepleadfield
if ~isempty(subspace)
dipout.leadfield{i} = lforig;
else
dipout.leadfield{i} = lf;
end
end
ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1));
end
ft_progress('close');
dipout.inside = dip.originside;
dipout.outside = dip.origoutside;
dipout.pos = dip.origpos;
% reassign the scan values over the inside and outside grid positions
if isfield(dipout, 'leadfield')
dipout.leadfield(dipout.inside) = dipout.leadfield;
dipout.leadfield(dipout.outside) = {[]};
end
if isfield(dipout, 'filter')
dipout.filter(dipout.inside) = dipout.filter;
dipout.filter(dipout.outside) = {[]};
end
if isfield(dipout, 'mom')
dipout.mom(dipout.inside) = dipout.mom;
dipout.mom(dipout.outside) = {[]};
end
if isfield(dipout, 'ori')
dipout.ori(dipout.inside) = dipout.ori;
dipout.ori(dipout.outside) = {[]};
end
if isfield(dipout, 'cov')
dipout.cov(dipout.inside) = dipout.cov;
dipout.cov(dipout.outside) = {[]};
end
if isfield(dipout, 'noisecov')
dipout.noisecov(dipout.inside) = dipout.noisecov;
dipout.noisecov(dipout.outside) = {[]};
end
if isfield(dipout, 'pow')
dipout.pow(dipout.inside) = dipout.pow;
dipout.pow(dipout.outside) = nan;
end
if isfield(dipout, 'noise')
dipout.noise(dipout.inside) = dipout.noise;
dipout.noise(dipout.outside) = nan;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to obtain the largest singular value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = lambda1(x)
% determine the largest singular value, which corresponds to the power along the dominant direction
s = svd(x);
s = s(1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function to compute the pseudo inverse. This is the same as the
% standard Matlab function, except that the default tolerance is twice as
% high.
% Copyright 1984-2004 The MathWorks, Inc.
% $Revision: 3515 $ $Date: 2009/03/23 21:14:42 $
% default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = pinv(A,varargin)
[m,n] = size(A);
if n > m
X = pinv(A',varargin{:})';
else
[U,S,V] = svd(A,0);
if m > 1, s = diag(S);
elseif m == 1, s = S(1);
else s = 0;
end
if nargin == 2
tol = varargin{1};
else
tol = 10 * max(m,n) * max(s) * eps;
end
r = sum(s > tol);
if (r == 0)
X = zeros(size(A'),class(A));
else
s = diag(ones(r,1)./s(1:r));
X = V(:,1:r)*s*U(:,1:r)';
end
end
|
github | philippboehmsturm/antx-master | dipole_fit.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/inverse/dipole_fit.m | 10,387 | utf_8 | fc67cb906fbbba6425899fd253d10d9e | function [dipout] = dipole_fit(dip, sens, vol, dat, varargin)
% DIPOLE_FIT performs an equivalent current dipole fit with a single
% or a small number of dipoles to explain an EEG or MEG scalp topography.
%
% Use as
% [dipout] = dipole_fit(dip, sens, vol, dat, ...)
%
% Additional input arguments should be specified as key-value pairs and can include
% 'constr' = Structure with constraints
% 'display' = Level of display [ off | iter | notify | final ]
% 'optimfun' = Function to use [fminsearch | fminunc ]
% 'maxiter' = Maximum number of function evaluations allowed [ positive integer ]
% 'metric' = Error measure to be minimised [ rv | var | abs ]
% 'checkinside' = Boolean flag to check whether dipole is inside source compartment [ 0 | 1 ]
% 'weight' = weight matrix for maximum likelihood estimation, e.g. inverse noise covariance
%
% The following optional input arguments relate to the computation of the leadfields
% 'reducerank' = 'no' or number
% 'normalize' = 'no', 'yes' or 'column'
% 'normalizeparam' = parameter for depth normalization (default = 0.5)
%
% The maximum likelihood estimation implements
% Lutkenhoner B. "Dipole source localization by means of maximum
% likelihood estimation I. Theory and simulations" Electroencephalogr Clin
% Neurophysiol. 1998 Apr;106(4):314-21.
% Copyright (C) 2003-2008, Robert Oostenveld
%
% Subversion does not use the Log keyword, use 'svn log <filename>' or 'svn -v log | less' to get detailled information
% It is neccessary to provide backward compatibility support for the old function call
% in case people want to use it in conjunction with EEGLAB and the dipfit1 plugin.
% old style: function [dipout] = dipole_fit(dip, dat, sens, vol, constr), where constr is optional
% new style: function [dipout] = dipole_fit(dip, sens, vol, dat, varargin), where varargin is in key-value pairs
if nargin==4 && ~isstruct(sens) && isstruct(dat)
% looks like old style, the order of the input arguments has to be changed
warning('converting from old style input\n');
olddat = sens;
oldsens = vol;
oldvol = dat;
dat = olddat;
sens = oldsens;
vol = oldvol;
elseif nargin==5 && ~isstruct(sens) && isstruct(dat)
% looks like old style, the order of the input arguments has to be changed
% furthermore the additional constraint has to be fixed
warning('converting from old style input\n');
olddat = sens;
oldsens = vol;
oldvol = dat;
dat = olddat;
sens = oldsens;
vol = oldvol;
varargin = {'constr', varargin{1}}; % convert into a key-value pair
else
% looks like new style, i.e. with optional key-value arguments
% this is dealt with below
end
constr = keyval('constr', varargin); % default is not to have constraints
metric = keyval('metric', varargin); if isempty(metric), metric = 'rv'; end
checkinside = keyval('checkinside', varargin); if isempty(checkinside), checkinside = 0; end
display = keyval('display', varargin); if isempty(display), display = 'iter'; end
optimfun = keyval('optimfun', varargin); if isa(optimfun, 'char'), optimfun = str2fun(optimfun); end
maxiter = keyval('maxiter', varargin);
reducerank = keyval('reducerank', varargin); % for leadfield computation
normalize = keyval('normalize' , varargin); % for leadfield computation
normalizeparam = keyval('normalizeparam', varargin); % for leadfield computation
weight = keyval('weight', varargin); % for maximum likelihood estimation
if isempty(optimfun)
% determine whether the Matlab Optimization toolbox is available and can be used
if ft_hastoolbox('optim')
optimfun = @fminunc;
else
optimfun = @fminsearch;
end
end
if isempty(maxiter)
% set a default for the maximum number of iterations, depends on the optimization function
if isequal(optimfun, @fminunc)
maxiter = 100;
else
maxiter = 500;
end
end
% determine whether it is EEG or MEG
iseeg = ft_senstype(sens, 'eeg');
ismeg = ft_senstype(sens, 'meg');
if ismeg && iseeg
% this is something that I might implement in the future
error('simultaneous EEG and MEG not supported');
elseif iseeg
% ensure that the potential data is average referenced, just like the model potential
dat = avgref(dat);
end
% ensure correct dipole position and moment specification
dip = fixdipole(dip);
% reformat the position parameters in case of multiple dipoles, this
% should result in the matrix changing from [x1 y1 z1; x2 y2 z2] to
% [x1 y1 z1 x2 y2 z2] for the constraints to work
numdip = size(dip.pos, 1);
param = dip.pos';
param = param(:)';
% add the orientation to the nonlinear parameters
if isfield(constr, 'fixedori') && constr.fixedori
for i=1:numdip
% add the orientation to the list of parameters
[th, phi, r] = cart2sph(dip.mom(1,i), dip.mom(2,i), dip.mom(3,i));
param = [param th phi];
end
end
% reduce the number of parameters to be fitted according to the constraints
if isfield(constr, 'mirror')
param = param(constr.reduce);
end
% set the parameters for the optimization function
if isequal(optimfun, @fminunc)
options = optimset(...
'TolFun',1e-9,...
'TypicalX',ones(size(param)),...
'LargeScale','off',...
'HessUpdate','bfgs',...
'MaxIter',maxiter,...
'MaxFunEvals',2*maxiter*length(param),...
'Display',display);
elseif isequal(optimfun, @fminsearch)
options = optimset(...
'MaxIter',maxiter,...
'MaxFunEvals',2*maxiter*length(param),...
'Display',display);
else
warning('unknown optimization function "%s", using default parameters', func2str(optimfun));
end
% perform the optimization with either the fminsearch or fminunc function
[param, fval, exitflag, output] = optimfun(@dipfit_error, param, options, dat, sens, vol, constr, metric, checkinside, reducerank, normalize, normalizeparam, weight);
if exitflag==0
error('Maximum number of iterations exceeded before reaching the minimum, please try with another initial guess.')
end
% do linear optimization of dipole moment parameters
[err, mom] = dipfit_error(param, dat, sens, vol, constr, metric, checkinside, reducerank, normalize, normalizeparam, weight);
% expand the number of parameters according to the constraints
if isfield(constr, 'mirror')
param = constr.mirror .* param(constr.expand);
end
% get the dipole position and orientation
if isfield(constr, 'fixedori') && constr.fixedori
numdip = numel(param)/5;
ori = zeros(3,numdip);
for i=1:numdip
th = param(end-(2*i)+1);
phi = param(end-(2*i)+2);
[ori(1,i), ori(2,i), ori(3,i)] = sph2cart(th, phi, 1);
end
pos = reshape(param(1:(numdip*3)), 3, numdip)';
else
numdip = numel(param)/3;
pos = reshape(param, 3, numdip)';
end
% return the optimal dipole parameters
dipout.pos = pos;
if isfield(constr, 'fixedori') && constr.fixedori
dipout.mom = ori; % dipole orientation as vector
dipout.ampl = mom; % dipole strength
else
dipout.mom = mom; % dipole moment as vector or matrix, which represents both the orientation and strength as vector
end
% ensure correct dipole position and moment specification
dipout = fixdipole(dipout);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DIPFIT_ERROR computes the error between measured and model data
% and can be used for non-linear fitting of dipole position
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [err, mom] = dipfit_error(param, dat, sens, vol, constr, metric, checkinside, reducerank, normalize, normalizeparam, weight)
% flush pending graphics events, ensure that fitting is interruptible
drawnow;
if ~isempty(get(0, 'currentfigure')) && strcmp(get(gcf, 'tag'), 'stop')
% interrupt the fitting
close;
error('USER ABORT');
end;
% expand the number of parameters according to the constraints
if isfield(constr, 'mirror')
param = constr.mirror .* param(constr.expand);
end
% get the dipole positions and optionally also the orientation
if isfield(constr, 'fixedori') && constr.fixedori
numdip = numel(param)/5;
ori = zeros(3,numdip);
for i=1:numdip
th = param(end-(2*i)+1);
phi = param(end-(2*i)+2);
[ori(1,i), ori(2,i), ori(3,i)] = sph2cart(th, phi, 1);
end
pos = reshape(param(1:(numdip*3)), 3, numdip)';
else
numdip = numel(param)/3;
pos = reshape(param, 3, numdip)';
end
% check whether the dipole is inside the source compartment
if checkinside
inside = ft_inside_vol(pos, vol);
if ~all(inside)
error('Dipole is outside the source compartment');
end
end
% construct the leadfield matrix for all dipoles
lf = ft_compute_leadfield(pos, sens, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam);
if isfield(constr, 'fixedori') && constr.fixedori
lf = lf * ori;
end
% compute the optimal dipole moment and the model error
if ~isempty(weight)
% maximum likelihood estimation using the weigth matrix
mom = pinv(lf'*weight*lf)*lf'*weight*dat; % Lutkenhoner equation 5
dif = dat - lf*mom;
% compute the generalized goodness-of-fit measure
switch metric
case 'rv' % relative residual variance
num = dif' * weight * dif;
denom = dat' * weight * dat;
err = sum(num(:)) ./ sum(denom(:)); % Lutkenhonner equation 7, except for the gof=1-rv
case 'var' % residual variance
num = dif' * weight * dif';
err = sum(num(:));
otherwise
error('Unsupported error metric for maximum likelihood dipole fitting');
end
else
% ordinary least squares, this is the same as MLE with weight=eye(nchans,nchans)
mom = pinv(lf)*dat;
dif = dat - lf*mom;
% compute the ordinary goodness-of-fit measures
switch metric
case 'rv' % relative residual variance
err = sum(dif(:).^2) / sum(dat(:).^2);
case 'var' % residual variance
err = sum(dif(:).^2);
case 'abs' % absolute difference
err = sum(abs(dif));
otherwise
error('Unsupported error metric for dipole fitting');
end
end
if ~isreal(err)
% this happens for complex valued data, i.e. when fitting a dipole to spectrally decomposed data
% the error function should return a positive valued real number, otherwise fminunc fails
err = abs(err);
end
|
github | philippboehmsturm/antx-master | ft_hastoolbox.m | .m | antx-master/freiburgLight/matlab/spm8/external/fieldtrip/inverse/private/ft_hastoolbox.m | 15,262 | utf_8 | c0b501e52231cc82315936a092af6214 | function [status] = ft_hastoolbox(toolbox, autoadd, silent)
% FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally
% it will try to determine the path to the toolbox and install it
% automatically.
%
% Use as
% [status] = ft_hastoolbox(toolbox, autoadd, silent)
%
% autoadd = 0 means that it will not be added
% autoadd = 1 means that give an error if it cannot be added
% autoadd = 2 means that give a warning if it cannot be added
% autoadd = 3 means that it remains silent if it cannot be added
%
% silent = 0 means that it will give some feedback about adding the toolbox
% silent = 1 means that it will not give feedback
% Copyright (C) 2005-2010, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_hastoolbox.m 3873 2011-07-19 14:23:16Z tilsan $
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
persistent previous previouspath
if ~isequal(previouspath, path)
previous = [];
end
if isempty(previous)
previous = struct;
elseif isfield(previous, fixname(toolbox))
status = previous.(fixname(toolbox));
return
end
% this points the user to the website where he/she can download the toolbox
url = {
'AFNI' 'see http://afni.nimh.nih.gov'
'DSS' 'see http://www.cis.hut.fi/projects/dss'
'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab'
'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox'
'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm'
'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd'
'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com'
'BIOSIG' 'see http://biosig.sourceforge.net'
'EEG' 'see http://eeg.sourceforge.net'
'EEGSF' 'see http://eeg.sourceforge.net' % alternative name
'MRI' 'see http://eeg.sourceforge.net' % alternative name
'NEUROSHARE' 'see http://www.neuroshare.org'
'BESA' 'see http://www.megis.de, or contact Karsten Hoechstetter'
'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde'
'YOKOGAWA' 'see http://www.yokogawa.co.jp, or contact Nobuhiko Takahashi'
'YOKOGAWA_MEG_READER' 'contact Masayuki dot Mochiduki at jp.yokogawa.com'
'BEOWULF' 'see http://oostenveld.net, or contact Robert Oostenveld'
'MENTAT' 'see http://oostenveld.net, or contact Robert Oostenveld'
'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth'
'4D-VERSION' 'contact Christian Wienbruch'
'SIGNAL' 'see http://www.mathworks.com/products/signal'
'OPTIM' 'see http://www.mathworks.com/products/optim'
'IMAGE' 'see http://www.mathworks.com/products/image'
'SPLINES' 'see http://www.mathworks.com/products/splines'
'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica'
'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm'
'FILEIO' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'FORWINV' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip'
'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne'
'BCI2000' 'see http://bci2000.org'
'NLXNETCOM' 'see http://www.neuralynx.com'
'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external'
'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php'
'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydes?ter'
'BEMCP' 'contact Christophe Phillips'
'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435'
'PRTOOLS' 'see http://www.prtools.org'
'ITAB' 'contact Stefania Della Penna'
'BSMART' 'see http://www.brain-smart.org'
'PEER' 'see http://fieldtrip.fcdonders.nl/development/peer'
'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki'
'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page'
'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS'
'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti'
'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0'
'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab'
'BCT' 'see http://www.brain-connectivity-toolbox.net/'
};
if nargin<2
% default is not to add the path automatically
autoadd = 0;
end
if nargin<3
% default is not to be silent
silent = 0;
end
% determine whether the toolbox is installed
toolbox = upper(toolbox);
switch toolbox
case 'AFNI'
status = (exist('BrikLoad') && exist('BrikInfo'));
case 'DSS'
status = exist('denss', 'file') && exist('dss_create_state', 'file');
case 'EEGLAB'
status = exist('runica', 'file');
case 'NWAY'
status = exist('parafac', 'file');
case 'SPM'
status = exist('spm.m'); % any version of SPM is fine
case 'SPM99'
status = exist('spm.m') && strcmp(spm('ver'),'SPM99');
case 'SPM2'
status = exist('spm.m') && strcmp(spm('ver'),'SPM2');
case 'SPM5'
status = exist('spm.m') && strcmp(spm('ver'),'SPM5');
case 'SPM8'
status = exist('spm.m') && strncmp(spm('ver'),'SPM8', 4);
case 'MEG-PD'
status = (exist('rawdata') && exist('channames'));
case 'MEG-CALC'
status = (exist('megmodel') && exist('megfield') && exist('megtrans'));
case 'BIOSIG'
status = (exist('sopen') && exist('sread'));
case 'EEG'
status = (exist('ctf_read_res4') && exist('ctf_read_meg4'));
case 'EEGSF' % alternative name
status = (exist('ctf_read_res4') && exist('ctf_read_meg4'));
case 'MRI' % other functions in the mri section
status = (exist('avw_hdr_read') && exist('avw_img_read'));
case 'NEUROSHARE'
status = (exist('ns_OpenFile') && exist('ns_SetLibrary') && exist('ns_GetAnalogData'));
case 'BESA'
status = (exist('readBESAtfc') && exist('readBESAswf'));
case 'EEPROBE'
status = (exist('read_eep_avr') && exist('read_eep_cnt'));
case 'YOKOGAWA'
status = (exist('hasyokogawa') && hasyokogawa('16bitBeta6'));
case 'YOKOGAWA16BITBETA3'
status = (exist('hasyokogawa') && hasyokogawa('16bitBeta3'));
case 'YOKOGAWA16BITBETA6'
status = (exist('hasyokogawa') && hasyokogawa('16bitBeta6'));
case 'YOKOGAWA_MEG_READER'
status = (exist('hasyokogawa') && hasyokogawa('1.4'));
case 'BEOWULF'
status = (exist('evalwulf') && exist('evalwulf') && exist('evalwulf'));
case 'MENTAT'
status = (exist('pcompile') && exist('pfor') && exist('peval'));
case 'SON2'
status = (exist('SONFileHeader') && exist('SONChanList') && exist('SONGetChannel'));
case '4D-VERSION'
status = (exist('read4d') && exist('read4dhdr'));
case {'STATS', 'STATISTICS'}
status = license('checkout', 'statistics_toolbox'); % also check the availability of a toolbox license
case {'OPTIM', 'OPTIMIZATION'}
status = license('checkout', 'optimization_toolbox'); % also check the availability of a toolbox license
case {'SPLINES', 'CURVE_FITTING'}
status = license('checkout', 'curve_fitting_toolbox'); % also check the availability of a toolbox license
case 'SIGNAL'
status = license('checkout', 'signal_toolbox'); % also check the availability of a toolbox license
case 'IMAGE'
status = license('checkout', 'image_toolbox'); % also check the availability of a toolbox license
case 'DCT'
status = license('checkout', 'distrib_computing_toolbox'); % also check the availability of a toolbox license
case 'FASTICA'
status = exist('fastica', 'file');
case 'BRAINSTORM'
status = exist('bem_xfer');
case 'FILEIO'
status = (exist('ft_read_header') && exist('ft_read_data') && exist('ft_read_event') && exist('ft_read_sens'));
case 'FORMWARD'
status = (exist('ft_compute_leadfield') && exist('ft_prepare_vol_sens'));
case 'DENOISE'
status = (exist('tsr') && exist('sns'));
case 'CTF'
status = (exist('getCTFBalanceCoefs') && exist('getCTFdata'));
case 'BCI2000'
status = exist('load_bcidat');
case 'NLXNETCOM'
status = (exist('MatlabNetComClient') && exist('NlxConnectToServer') && exist('NlxGetNewCSCData'));
case 'DIPOLI'
status = exist('dipoli.m', 'file');
case 'MNE'
status = (exist('fiff_read_meas_info', 'file') && exist('fiff_setup_read_raw', 'file'));
case 'TCP_UDP_IP'
status = (exist('pnet', 'file') && exist('pnet_getvar', 'file') && exist('pnet_putvar', 'file'));
case 'BEMCP'
status = (exist('bem_Cij_cog', 'file') && exist('bem_Cij_lin', 'file') && exist('bem_Cij_cst', 'file'));
case 'OPENMEEG'
status = exist('openmeeg.m', 'file');
case 'PLOTTING'
status = (exist('ft_plot_topo', 'file') && exist('ft_plot_mesh', 'file') && exist('ft_plot_matrix', 'file'));
case 'PRTOOLS'
status = (exist('prversion', 'file') && exist('dataset', 'file') && exist('svc', 'file'));
case 'ITAB'
status = (exist('lcReadHeader', 'file') && exist('lcReadData', 'file'));
case 'BSMART'
status = exist('bsmart');
case 'PEER'
status = exist('peerslave', 'file') && exist('peermaster', 'file');
case 'CONNECTIVITY'
status = exist('ft_connectivity_corr', 'file') && exist('ft_connectivity_granger', 'file');
case 'FREESURFER'
status = exist('MRIread', 'file') && exist('vox2ras_0to1', 'file');
case 'FNS'
status = exist('elecsfwd', 'file') && exist('img_get_gray', 'file');
case 'SIMBIO'
status = exist('ipm_linux_opt_Venant', 'file');
case 'GIFTI'
status = exist('gifti', 'file');
case 'XML4MAT'
status = exist('xml2struct.m', 'file') && exist('xml2whos.m', 'file');
case 'SQDPROJECT'
status = exist('sqdread.m', 'file') && exist('sqdwrite.m', 'file');
case 'BCT'
status = exist('macaque71.mat', 'file') && exist('motif4funct_wei.m', 'file');
otherwise
if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end
status = 0;
end
% it should be a boolean value
status = (status~=0);
% try to determine the path of the requested toolbox
if autoadd>0 && ~status
% for core fieldtrip modules
prefix = fileparts(which('ft_defaults'));
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for external fieldtrip modules
prefix = fullfile(fileparts(which('ft_defaults')), 'external');
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
licensefile = [lower(toolbox) '_license'];
if status && exist(licensefile, 'file')
% this will execute openmeeg_license and mne_license
% which display the license on screen for three seconds
feval(licensefile);
end
end
% for linux computers in the F.C. Donders Centre
prefix = '/home/common/matlab';
if ~status && (strcmp(computer, 'GLNX86') || strcmp(computer, 'GLNXA64'))
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for windows computers in the F.C. Donders Centre
prefix = 'h:\common\matlab';
if ~status && (strcmp(computer, 'PCWIN') || strcmp(computer, 'PCWIN64'))
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% use the matlab subdirectory in your homedirectory, this works on unix and mac
prefix = [getenv('HOME') '/matlab'];
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
if ~status
% the toolbox is not on the path and cannot be added
sel = find(strcmp(url(:,1), toolbox));
if ~isempty(sel)
msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2});
else
msg = sprintf('the %s toolbox is not installed', toolbox);
end
if autoadd==1
error(msg);
elseif autoadd==2
warning(msg);
else
% fail silently
end
end
end
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
if status
previous.(fixname(toolbox)) = status;
end
% remember the previous path, allows us to determine on the next call
% whether the path has been modified outise of this function
previouspath = path;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = myaddpath(toolbox, silent)
if exist(toolbox, 'dir')
if ~silent,
ws = warning('backtrace', 'off');
warning('adding %s toolbox to your Matlab path', toolbox);
warning(ws); % return to the previous warning level
end
addpath(toolbox);
status = 1;
else
status = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = fixname(toolbox)
out = lower(toolbox);
out(out=='-') = '_'; % fix dashes
out(out==' ') = '_'; % fix spaces
out(out=='/') = '_'; % fix forward slashes
out(out=='\') = '_'; % fix backward slashes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = hasfunction(funname, toolbox)
try
% call the function without any input arguments, which probably is inapropriate
feval(funname);
% it might be that the function without any input already works fine
status = true;
catch
% either the function returned an error, or the function is not available
% availability is influenced by the function being present and by having a
% license for the function, i.e. in a concurrent licensing setting it might
% be that all toolbox licenses are in use
m = lasterror;
if strcmp(m.identifier, 'MATLAB:license:checkouterror')
if nargin>1
warning('the %s toolbox is available, but you don''t have a license for it', toolbox);
else
warning('the function ''%s'' is available, but you don''t have a license for it', funname);
end
status = false;
elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction')
status = false;
else
% the function seems to be available and it gave an unknown error,
% which is to be expected with inappropriate input arguments
status = true;
end
end
|
github | philippboehmsturm/antx-master | subsasgn.m | .m | antx-master/freiburgLight/matlab/spm8/@nifti/subsasgn.m | 14,541 | utf_8 | ffdb84b7956d93c2f9a0a980ccbe8a22 | function obj = subsasgn(obj,subs,varargin)
% Subscript assignment
% See subsref for meaning of fields.
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: subsasgn.m 4136 2010-12-09 22:22:28Z guillaume $
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 = nifti(objs(i));
obji = fun(obji,subs,val);
objs(i) = struct(obji);
end;
obj = nifti(objs);
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 = nifti(t(i));
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 = nifti(objs);
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(nifti(obj),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 = nifti(objs);
otherwise
error('This should not happen.');
end;
return;
%=======================================================================
%=======================================================================
function obj = assigndat(obj,val)
if isa(val,'file_array'),
sz = size(val);
if numel(sz)>7,
error('Too many dimensions in data.');
end;
sz = [sz 1 1 1 1 1 1 1];
sz = sz(1:7);
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' char(0)];
elseif any(strcmp(suf,{'.nii','.NII'}))
val.offset = max(sval.offset,352);
obj.hdr.magic = ['n+1' char(0)];
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 | philippboehmsturm/antx-master | subsref.m | .m | antx-master/freiburgLight/matlab/spm8/@nifti/subsref.m | 8,741 | utf_8 | 2d67123e4dc7e0b20a7ee19962324fee | 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: subsref.m 4136 2010-12-09 22:22:28Z guillaume $
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 = nifti(opts(ii));
%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 = nifti(t(i));
ti = rec(ti,subs(2:end));
c = {c{:}, ti{:}};
end;
else
c = {nifti(t)};
end;
otherwise
error('This should not happen.');
end;
|
github | philippboehmsturm/antx-master | create.m | .m | antx-master/freiburgLight/matlab/spm8/@nifti/create.m | 1,963 | utf_8 | 3c70cc73a693e9e93f4a3f3b60c91d1c | 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: create.m 1143 2008-02-07 19:33:33Z spm $
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 | philippboehmsturm/antx-master | getdict.m | .m | antx-master/freiburgLight/matlab/spm8/@nifti/private/getdict.m | 5,226 | utf_8 | 94716c88e3d44be3c8207f14a928510a | function d = getdict
% Dictionary of NIFTI stuff
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: getdict.m 1143 2008-02-07 19:33:33Z spm $
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 | philippboehmsturm/antx-master | write_extras.m | .m | antx-master/freiburgLight/matlab/spm8/@nifti/private/write_extras.m | 876 | utf_8 | f3686c5d5d6e88449972819a302e8c5c | function extras = write_extras(fname,extras)
% Write extra bits of information
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
%
% $Id: write_extras.m 1143 2008-02-07 19:33:33Z spm $
[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 | philippboehmsturm/antx-master | dti_cfg_roiop.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_cfg_roiop.m | 8,524 | utf_8 | e467a758ca89a2e0c0db8a3f85c54b63 | % configure file for operations on streamline trackings results
%
% for BATCH EDITOR system (Volkmar Glauche)
%
% File created by Susanne Schnell
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function roiop = dti_cfg_roiop
% ---------------------------------------------------------------------
% newfilename name of resulting mask after operation
% ---------------------------------------------------------------------
newfilename = cfg_entry;
newfilename.tag = 'newfilename';
newfilename.name = 'New File Name';
newfilename.val = {'.mat'};
newfilename.help = {'Type in the name of the new mask file, if you leave this empty a default file name is generated.'};
newfilename.strtype = 's';
newfilename.num = [1 Inf];
% ---------------------------------------------------------------------
% coordinated of the starting point for spherical growing
% ---------------------------------------------------------------------
coords = cfg_entry;
coords.tag = 'coords';
coords.name = 'coords';
coords.val = {[64 64 10]};
coords.help = {'Enter the coordinates for the midpoint of the sphere (x y z).'};
coords.strtype = 'e';
coords.num = [1 3];
% ---------------------------------------------------------------------
% number of voxels
% ---------------------------------------------------------------------
sizeSphere = cfg_entry;
sizeSphere.tag = 'sizeSphere';
sizeSphere.name = 'sizeSphere';
sizeSphere.val = {1};
sizeSphere.help = {'Enter the wanted size of the sphere to grow.'};
sizeSphere.strtype = 'e';
sizeSphere.num = [1 1];
% ---------------------------------------------------------------------
% number of voxels
% ---------------------------------------------------------------------
voxels = cfg_entry;
voxels.tag = 'voxels';
voxels.name = 'voxels';
voxels.val = {1};
voxels.help = {'Enter the number of voxels for Erosion or Dilation operation.'};
voxels.strtype = 'e';
voxels.num = [1 1];
% ---------------------------------------------------------------------
% mask, select the correct mask by a number
% ---------------------------------------------------------------------
mask2 = cfg_entry;
mask2.tag = 'mask2';
mask2.name = 'second mask number';
mask2.help = {'Select the mask by a number. You need to remember the mask position by yourself.'};
mask2.strtype = 'e';
mask2.num = [1 1];
% ---------------------------------------------------------------------
% mask, select the correct mask by a number
% ---------------------------------------------------------------------
mask1 = cfg_entry;
mask1.tag = 'mask1';
mask1.name = 'mask number';
mask1.help = {'Select the mask by a number. You need to remember the mask position by yourself.'};
mask1.strtype = 'e';
mask1.num = [1 1];
% ---------------------------------------------------------------------
% roiname
% ---------------------------------------------------------------------
roiname = cfg_files;
roiname.tag = 'roiname';
roiname.name = 'Load ROI';
roiname.help = {'Select a maskstruct (ROI).'};
roiname.filter = 'mat';
roiname.ufilter = '.*';
roiname.num = [1 1];
% ---------------------------------------------------------------------
% maskname name of resulting operation
% ---------------------------------------------------------------------
maskname = cfg_entry;
maskname.tag = 'maskname';
maskname.name = 'New Mask Name';
maskname.val = {'new_ROI'};
maskname.help = {'Type in the name of the new ROI, if you leave this empty a default file name is generated.'};
maskname.strtype = 's';
maskname.num = [1 Inf];
% ---------------------------------------------------------------------
% GrowSphere in ROI from point, input of maskstruct, masknumber, size in mm, the new maskname and the new filename
% ---------------------------------------------------------------------
GrowSphere = cfg_exbranch;
GrowSphere.tag = 'GrowSphere';
GrowSphere.name = 'GrowSphere in ROI';
GrowSphere.help = {'Let grow a sphere from a defined point, give the size in mm.'};
GrowSphere.val = {roiname maskname sizeSphere coords newfilename};
GrowSphere.prog = @(job)dti_roiop_ui('GrowSphere',job);
GrowSphere.vout = @vout;
% ---------------------------------------------------------------------
% Dilation of ROI, input of maskstruct, masknumber, number of voxels, the new maskname and the new filename
% ---------------------------------------------------------------------
Dilation = cfg_exbranch;
Dilation.tag = 'Dilation';
Dilation.name = 'Dilation of ROI';
Dilation.help = {'Make a dilation operation on the selected mask, give the number of voxels to dilate. This is a standard morphological operation.'};
Dilation.val = {roiname mask1 maskname voxels newfilename};
Dilation.prog = @(job)dti_roiop_ui('Dilation',job);
Dilation.vout = @vout;
% ---------------------------------------------------------------------
% Erosion of ROI, input of maskstruct, masknumber, number of voxels, the new maskname and the new filename
% ---------------------------------------------------------------------
Erosion = cfg_exbranch;
Erosion.tag = 'Erosion';
Erosion.name = 'Erosion of ROI';
Erosion.help = {'Make an Erosion operation on the selected mask, give the number of voxels to erose. This is a standard morphological operation.'};
Erosion.val = {roiname mask1 maskname voxels newfilename};
Erosion.prog = @(job)dti_roiop_ui('Erosion',job);
Erosion.vout = @vout;
% ---------------------------------------------------------------------
% XORop input of two ROIs, masknumbers, the new maskname and the new filename
% ---------------------------------------------------------------------
XORop = cfg_exbranch;
XORop.tag = 'XORop';
XORop.name = 'XOR operation on two masks';
XORop.help = {'Select two mask which you want to combine with logical XOR operation.'};
XORop.val = {roiname mask1 mask2 maskname newfilename};
XORop.prog = @(job)dti_roiop_ui('XORop',job);
XORop.vout = @vout;
% ---------------------------------------------------------------------
% ORop input of two ROIs, masknumbers, the new maskname and the new filename
% ---------------------------------------------------------------------
ORop = cfg_exbranch;
ORop.tag = 'ORop';
ORop.name = 'OR operation on two masks';
ORop.help = {'Select two mask which you want to combine with logical OR operation.'};
ORop.val = {roiname mask1 mask2 maskname newfilename};
ORop.prog = @(job)dti_roiop_ui('ORop',job);
ORop.vout = @vout;
% ---------------------------------------------------------------------
% ANDop input of two ROIs, masknumbers, the new maskname and the new filename
% ---------------------------------------------------------------------
ANDop = cfg_exbranch;
ANDop.tag = 'ANDop';
ANDop.name = 'AND operation on two masks';
ANDop.help = {'Select two mask which you want to combine with logical AND operation.'};
ANDop.val = {roiname mask1 mask2 maskname newfilename};
ANDop.prog = @(job)dti_roiop_ui('ANDop',job);
ANDop.vout = @vout;
% ---------------------------------------------------------------------
% Invert ROI, input of maskstruct, masknumber, new maskname and the new filename
% ---------------------------------------------------------------------
Invert = cfg_exbranch;
Invert.tag = 'Invert';
Invert.name = 'Invert ROI';
Invert.help = {'Invert the mask (1 becomes 0 and 0 becomes 1).'};
Invert.val = {roiname mask1 maskname newfilename};
Invert.prog = @(job)dti_roiop_ui('Invert',job);
Invert.vout = @vout;
% ---------------------------------------------------------------------
% roiop
% ---------------------------------------------------------------------
roiop = cfg_choice;
roiop.tag = 'roiop';
roiop.name = 'Operations with ROIs (maskstructs)';
roiop.help = {'Operations with ROIs (maskstructs).'};
roiop.values = {Invert ANDop ORop XORop Erosion Dilation GrowSphere};
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'MASKstruct After Operation';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}}); |
github | philippboehmsturm/antx-master | dti_cfg_fodop.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_cfg_fodop.m | 31,112 | utf_8 | a897d50b3c021cd3122ace13acc92304 | % configure file for operations on streamline trackings results
%
% for BATCH EDITOR system (Volkmar Glauche)
%
% File created by Marco Reisert
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function fodop = dti_cfg_fodop
% ---------------------------------------------------------------------
% filename1 name of HARDI
% ---------------------------------------------------------------------
filename1 = cfg_files;
filename1.tag = 'filename1';
filename1.name = 'Select the HARDI-mrstruct';
filename1.help = {'Select the mrstruct (usually something like blah_HARDI.mat'};
filename1.filter = 'mat';
filename1.ufilter = '.*';
filename1.num = [1 1];
% ---------------------------------------------------------------------
% filename1 name of HARDI2
% ---------------------------------------------------------------------
filenameHARDI1 = cfg_files;
filenameHARDI1.tag = 'filenameHARDI1';
filenameHARDI1.name = 'Select direction reference as HARDI-mrstruct';
filenameHARDI1.help = {'Select the mrstruct (usually something like blah_HARDI.mat'};
filenameHARDI1.filter = 'mat';
filenameHARDI1.ufilter = '.*';
filenameHARDI1.num = [1 1];
% ---------------------------------------------------------------------
% filename2 name of FOD
% ---------------------------------------------------------------------
filename2 = cfg_files;
filename2.tag = 'filename2';
filename2.name = 'Select the FOD-mrstruct';
filename2.help = {'Select the FOD-mrstruct (usually something like "blah_FOD.mat)"'};
filename2.filter = 'mat';
filename2.ufilter = '.*';
filename2.num = [1 1];
% ---------------------------------------------------------------------
% filename2 name of FOD
% ---------------------------------------------------------------------
filename4 = cfg_files;
filename4.tag = 'filename4';
filename4.name = 'Select the mrstruct containing the fiber density';
filename4.help = {'Select the mrstruct (usually something like "blah.mat)"'};
filename4.filter = 'mat';
filename4.ufilter = '.*';
filename4.num = [1 1];
% ---------------------------------------------------------------------
% filename2 name of FOD
% ---------------------------------------------------------------------
filenamePIcon = cfg_files;
filenamePIcon.tag = 'filenamePIcon';
filenamePIcon.name = 'Select the PICON file';
filenamePIcon.help = {'Select the *_PICON.mat file)"'};
filenamePIcon.filter = 'mat';
filenamePIcon.ufilter = '.*';
filenamePIcon.num = [1 1];
% ---------------------------------------------------------------------
% filename3 name of nifti
% ---------------------------------------------------------------------
filename3 = cfg_files;
filename3.tag = 'filename3';
filename3.name = 'Select a nifti as reference for reslicing';
filename3.help = {'Select the nifti (usually something like blah.nii)'};
filename3.filter = 'image';
filename3.ufilter = '.*';
filename3.num = [1 1];
% ---------------------------------------------------------------------
% filenameROIs name of nifti
% ---------------------------------------------------------------------
filenameROIs = cfg_files;
filenameROIs.tag = 'filenameROIs';
filenameROIs.name = 'Select a nifti containing labels';
filenameROIs.help = {'Select the nifti (usually something like blah.nii)'};
filenameROIs.filter = 'image';
filenameROIs.ufilter = '.*';
filenameROIs.num = [1 1];
% ---------------------------------------------------------------------
% filedef name of deformation field
% ---------------------------------------------------------------------
filedef = cfg_files;
filedef.tag = 'filedef';
filedef.name = 'Select the deformation field';
filedef.help = {'Select the deformation field (usually created by "New Segment", something like "yblah.nii"'};
filedef.filter = '.nii';
filedef.ufilter = '.*';
filedef.num = [1 1];
% ---------------------------------------------------------------------
% filedefi name of inverse deformation field
% ---------------------------------------------------------------------
filedefi = cfg_files;
filedefi.tag = 'filedefi';
filedefi.name = 'Select the inverse deformation field';
filedefi.help = {'Select the inverse deformation field (usually created by "New Segment", something like "iyblah.nii"'};
filedefi.filter = '.nii';
filedefi.ufilter = '.*';
filedefi.num = [1 1];
% ---------------------------------------------------------------------
% thresh, select the threshhold for creating a mask
% ---------------------------------------------------------------------
thresh = cfg_entry;
thresh.tag = 'thresh';
thresh.name = 'Threshold for creating a mask';
thresh.val = {0.5};
thresh.help = {'Threshold for creating a mask of voxels visited by at least this number of fibretracks. Default = 0'};
thresh.strtype = 'e';
thresh.num = [1 1];
% ---------------------------------------------------------------------
% roiname
% ---------------------------------------------------------------------
roiname = cfg_files;
roiname.tag = 'roiname';
roiname.name = 'White matter mask';
roiname.help = {'Select a nifti.'};
roiname.filter = '.mat|.nii';
roiname.ufilter = '.*';
roiname.num = [1 1];
% ---------------------------------------------------------------------
% Parameters of PItrack
% ---------------------------------------------------------------------
ParametersPI = {'ROI index', ...
'GMres tolerance', ...
'GMres maxit', ...
'GMres restart', ...
'Local Maxima Threshold', ...
'Dangular', ...
'FOD power', ...
'FOD threshold', ...
'Length Exponent', ...
'Boundary Condition',...
'Normalization Type',...
'Symmetry', ...
'Upsampling', ...
'Speed',
};
paramtagsPI = {'roisubset', 'tol','maxitgm','restart','thres_toMax','Dang','sh','myeps','kappa','boundary','normtype','sym','upsamp','speed'};
defaultsPI = {[], 10^-8, 500, 5,0.25, 0.01, 40, 0.01, 0.0 ,1,0,1,[1 1],0};
for k = 1:length(ParametersPI),
eval([paramtagsPI{k} ' = cfg_entry;']);
eval([paramtagsPI{k} '.tag = ''' paramtagsPI{k} '''; ']);
eval([paramtagsPI{k} '.name = ''' ParametersPI{k} '''; ']);
eval([paramtagsPI{k} '.help = {'' Choose the parameter: ' ParametersPI{k} '''}; ']);
eval([paramtagsPI{k} '.val = {' num2str(defaultsPI{k}) '};']);
eval([paramtagsPI{k} '.strtype = ''e'';']);
eval([paramtagsPI{k} '.num = [1 1];']);
end;
roisubset.num = [0 inf];
roisubset.val = {[]};
upsamp.num = [0 2];
upsamp.val = {[1 1]};
% ---------------------------------------------------------------------
% Parameters of Probtrax
% ---------------------------------------------------------------------
ParametersPX = {'ROI index', ...
'Walkers per Seed', ...
'Stepwidth',...
'Maximal fiber length',...
'Sigma',...
'Maximum angle',...
'Remove length Bias',...
'No Revisits'};
paramtagsPX = {'roisubset', 'nwalker','step','maxfiblen','sig','maxang','lenbias','norevisits'};
defaultsPX = {[], 5000,1,1000,0.2,80,1,0};
for k = 1:length(ParametersPX),
eval([paramtagsPX{k} ' = cfg_entry;']);
eval([paramtagsPX{k} '.tag = ''' paramtagsPX{k} '''; ']);
eval([paramtagsPX{k} '.name = ''' ParametersPX{k} '''; ']);
eval([paramtagsPX{k} '.help = {'' Choose the parameter: ' ParametersPX{k} '''}; ']);
eval([paramtagsPX{k} '.val = {' num2str(defaultsPX{k}) '};']);
eval([paramtagsPX{k} '.strtype = ''e'';']);
eval([paramtagsPX{k} '.num = [1 1];']);
end;
roisubset.num = [0 inf];
roipairs = cfg_entry;
roipairs.tag = 'roipairs';
roipairs.name = 'Select pairs of ROIs to create path trails (a [2 n] array of integers)';
roipairs.val = {[]};
roipairs.help = {'some help'};
roipairs.strtype = 'e';
roipairs.num = [2 inf];
% ---------------------------------------------------------------------
% Parameters of CSD/TFD
% ---------------------------------------------------------------------
Parameters = {'Oversampling Factor for computing TFD', ...
'Iterations CSD', ...
'FRF D-axial', ...
'FRF D-radial', ...
'L1-Regularization Strength',...
'Smoothing power',...
'Number Directions',...
'Tensororder TFD',...
'Global Tikhohnov TFD',...
'Boundary Variation Penalty'};
paramtags = {'osamp','maxit','Dax','Drad','lambdaL1','powsm','numdir','planorder','lambda1','lambda2' };
defaults = {2, 200, 1, 0.15, 50, 14, 128, 1, 0, 10^(-4) };
for k = 1:length(Parameters),
eval([paramtags{k} ' = cfg_entry;']);
eval([paramtags{k} '.tag = ''' paramtags{k} '''; ']);
eval([paramtags{k} '.name = ''' Parameters{k} '''; ']);
eval([paramtags{k} '.help = {'' Choose the parameter: ' Parameters{k} '''}; ']);
eval([paramtags{k} '.val = {' num2str(defaults{k}) '};']);
eval([paramtags{k} '.strtype = ''e'';']);
eval([paramtags{k} '.num = [1 1];']);
end;
% ---------------------------------------------------------------------
% Parameters of CSA
% ---------------------------------------------------------------------
ParametersCSA = {'SH cutoff', ...
'Laplace-Beltrami penalty', ...
'Number of Directions (output space)',...
'FRF D-axial'};
paramtagsCSA = {'shcutoff','laplacebeltrami','numdirsout','Dax'};
defaultsCSA = {6, 0.006, 128, 1 };
for k = 1:length(ParametersCSA),
eval([paramtagsCSA{k} ' = cfg_entry;']);
eval([paramtagsCSA{k} '.tag = ''' paramtagsCSA{k} '''; ']);
eval([paramtagsCSA{k} '.name = ''' ParametersCSA{k} '''; ']);
eval([paramtagsCSA{k} '.help = {'' Choose the parameter: ' ParametersCSA{k} '''}; ']);
eval([paramtagsCSA{k} '.val = {' num2str(defaultsCSA{k}) '};']);
eval([paramtagsCSA{k} '.strtype = ''e'';']);
eval([paramtagsCSA{k} '.num = [1 1];']);
end;
ParametersCSDFC = {'Number Iterations', ...
'Number CG rounds', ...
'Number of Directions (output space)',...
'FRF D-axial',...
'lambda AFC',...
'alpha curvature',...
'lambda FC (symmetric)',...
'lambda FC (asymmetric)',...
'lambda isotropic (symmetric)',...
'lambda isotropic (asymmetric)',...
'lambda Laplace Beltrami',...
'lambda Tikhonov (symmetric)',...
'lambda Tikhonov (asymmetric)',...
'symmetric output',...
};
paramtagsCSDFC = {'numit','numround','numoutdir','Daxial','lambda','alpha','purefc_sym','purefc_asym',...
'iso_sym','iso_asym','lambda_lb','gamma_sym','gamma_asym','symout'};
defaultsCSDFC = {50,4,128,1,0,1,0.005,0,0,0,0.0001,0,0,1};
defaultsCSDAFC = {50,4,128,1,0.005,1,0,0,0,0,0.0001,0,0,1};
for k = 1:length(ParametersCSDFC),
eval([paramtagsCSDFC{k} ' = cfg_entry;']);
eval([paramtagsCSDFC{k} '.tag = ''' paramtagsCSDFC{k} '''; ']);
eval([paramtagsCSDFC{k} '.name = ''' ParametersCSDFC{k} '''; ']);
eval([paramtagsCSDFC{k} '.help = {'' Choose the parameter: ' ParametersCSDFC{k} '''}; ']);
eval([paramtagsCSDFC{k} '.val = {' num2str(defaultsCSDFC{k}) '};']);
eval([paramtagsCSDFC{k} '.strtype = ''e'';']);
eval([paramtagsCSDFC{k} '.num = [1 1];']);
end;
% ---------------------------------------------------------------------
% roidef
% ---------------------------------------------------------------------
roidef = cfg_branch;
roidef.tag = 'roidef';
roidef.name = 'Definition of area of Reconstruction';
roidef.help = {'Choose a coregistered Nifti containing the probabilistiv white matter segmentation.'};
roidef.val = {roiname thresh};
% ---------------------------------------------------------------------
% newfilename name of resulting file
% ---------------------------------------------------------------------
newfilename = cfg_entry;
newfilename.tag = 'newfilename';
newfilename.name = 'New File Name (mrStruct)';
newfilename.val = {'.mat'};
newfilename.help = {'Type in the name of the new file, if you leave this empty a default file name is generated'};
newfilename.strtype = 's';
newfilename.num = [1 Inf];
newfilename2 = cfg_entry;
newfilename2.tag = 'newfilename';
newfilename2.name = 'New File Name (Nifti)';
newfilename2.val = {'.nii'};
newfilename2.help = {'Type in the name of the new file, if you leave this empty a default file name is generated'};
newfilename2.strtype = 's';
newfilename2.num = [1 Inf];
newfilenamemat = cfg_entry;
newfilenamemat.tag = 'newfilenamemat';
newfilenamemat.name = 'New File Name (.mat)';
newfilenamemat.val = {'.mat'};
newfilenamemat.help = {'Type in the name of the file contaning connectivity information. If you leave this empty a default file name is generated'};
newfilenamemat.strtype = 's';
newfilenamemat.num = [1 Inf];
interp = cfg_menu;
interp.tag = 'interp';
interp.name = 'Interpolation';
interp.help = {'The method by which the images are sampled when being written in a different space. Nearest Neighbour is fastest, but not normally recommended. It can be useful for re-orienting images while preserving the original intensities (e.g. an image consisting of labels). Bilinear Interpolation is OK for PET, or realigned and re-sliced fMRI. If subject movement (from an fMRI time series) is included in the transformations then it may be better to use a higher degree approach. Note that higher degree B-spline interpolation/* \cite{thevenaz00a,unser93a,unser93b}*/ is slower because it uses more neighbours.'};
interp.labels = {
'Nearest neighbour'
'Trilinear'
'2nd Degree B-Spline'
'3rd Degree B-Spline'
'4th Degree B-Spline'
'5th Degree B-Spline'
'6th Degree B-Spline'
'7th Degree B-Spline'
}';
interp.values = {0 1 2 3 4 5 6 7};
interp.def = @(x) 1;
sitype = cfg_menu;
sitype.tag = 'sitype';
sitype.name = 'Type of scalar map';
sitype.help = {'Type of scalar maps which is computed from the FOD.'};
sitype.labels = {
'Generalized Fractional Anisotropy'
'mean FOD'
'mean FOD (b0 normalized)'
'maximum FOD'
'maximum FOD (b0 normalized)'
}';
sitype.values = {0 1 2 3 4};
sitype.def = @(x) 0;
modifyFOD = cfg_menu;
modifyFOD.tag = 'modifyFOD';
modifyFOD.name = 'Scale FOD by TFD values';
modifyFOD.help = {'The original FOD scaling is overwritten by TFD.'};
modifyFOD.labels = {
'Yes'
'No'
}';
modifyFOD.values = {1 0};
modifyFOD.def = @(x) 0;
savePImaps = cfg_menu;
savePImaps.tag = 'savePImaps';
savePImaps.name = 'Save PImaps to generate Path trails.';
savePImaps.help = {'Information about path trails is saves'};
savePImaps.labels = {
'Yes'
'No'
}';
savePImaps.values = {1 0};
savePImaps.def = @(x) 0;
noutdir = cfg_menu;
noutdir.tag = 'noutdir';
noutdir.name = 'Number of Output Directions';
noutdir.help = {'Number of directions in output space'};
noutdir.labels = {
'32'
'64'
'128'
}';
noutdir.values = {32 64 128};
noutdir.def = @(x) 64;
modulate = cfg_menu;
modulate.tag = 'modulate';
modulate.name = 'Modulation';
modulate.help = {'The method with which the values are scaled. To preserve surface integrals a FOD is scaled by |Jn|^4 /det(J)^2, where J is the Jacobian of the deformation field. To preserve fiber density hte FOD is scaled by |Jn|^3 /det(J).'};
modulate.labels = {
'No modulation'
'Surface integral preserving modulation (Raeffel 2012)'
'Fiber Density Preserving modulation (Hong 2009)'
}';
modulate.values = {0 1 2};
modulate.def = @(x) 1;
axialsigma = cfg_entry;
axialsigma.tag = 'axialsigma';
axialsigma.name = 'Gaussian width in axial direction (in voxel units)';
axialsigma.val = {3};
axialsigma.help = {'Smoothing width in axial direction'};
axialsigma.strtype = 'e';
axialsigma.num = [1 1];
radialsigma = cfg_entry;
radialsigma.tag = 'radialsigma';
radialsigma.name = 'Gaussian width in radial direction (in voxel units)';
radialsigma.val = {1};
radialsigma.help = {'Smoothing width in radial direction'};
radialsigma.strtype = 'e';
radialsigma.num = [1 1];
noiselevel = cfg_entry;
noiselevel.tag = 'noiselevel';
noiselevel.name = 'Noise level (in signal units)';
noiselevel.val = {20};
noiselevel.help = {'Noise level used for MLE estimate (0 means level is estimated)'};
noiselevel.strtype = 'e';
noiselevel.num = [1 1];
ksz = cfg_entry;
ksz.tag = 'ksz';
ksz.name = 'Radius of kernel in voxel units';
ksz.val = {2};
ksz.help = {'size of filter cube'};
ksz.strtype = 'e';
ksz.num = [1 1];
% ---------------------------------------------------------------------
% fiout (nifti or mrstruct) with reslicing option
% ---------------------------------------------------------------------
nifti = cfg_exbranch;
nifti.tag = 'newfinamenifti';
nifti.name = 'New File Name (Nifti)';
nifti.help = {'You can choose a reference image for reslicing'};
nifti.val = {newfilename2};
niftireslice = cfg_exbranch;
niftireslice.tag = 'newfinameniftireslice';
niftireslice.name = 'New File Name (Nifti with Reslicing)';
niftireslice.help = {'Choose a filename'};
niftireslice.val = {filename3 newfilename2};
fiout = cfg_choice;
fiout.tag = 'fiout';
fiout.name = 'Output File';
fiout.help = {'Select mrStruct or Nifti as output type'};
fiout.values = {newfilename nifti niftireslice};
% ---------------------------------------------------------------------
% createFOD by CSD-L1
% ---------------------------------------------------------------------
newfilenameFOD = newfilename; newfilenameFOD.name = 'New File Name FOD (mrStruct)';
createbyCSD = cfg_exbranch;
createbyCSD.tag = 'createbyCSD';
createbyCSD.name = 'Create FOD by L1-based CSD';
createbyCSD.help = {'Create Fiber Orientation Distribution with CSD.'};
pp = (cellfun(@(x) [x ' '],paramtags,'uniformoutput',false)); pp = cat(2,pp{2:7});
createbyCSD.val = eval(['{filename1 roidef newfilenameFOD ' pp ' }']);
createbyCSD.prog = @(job)dti_fodop_ui('doL1CSD',job);
createbyCSD.vout = @vout;
% ---------------------------------------------------------------------
% createFOD by CSA (Aganj2009)
% ---------------------------------------------------------------------
newfilenameFOD = newfilename; newfilenameFOD.name = 'New File Name FOD (mrStruct)';
createbyCSA = cfg_exbranch;
createbyCSA.tag = 'createbyCSA';
createbyCSA.name = 'Create FOD by Constant Solid Angle (CSA) approach';
createbyCSA.help = {'Create Fiber Orientation Distribution with CSA approach (Aganj2009).'};
pp = (cellfun(@(x) [x ' '],paramtagsCSA,'uniformoutput',false)); pp = cat(2,pp{1:3});
createbyCSA.val = eval(['{filename1 newfilenameFOD ' pp ' }']);
createbyCSA.prog = @(job)dti_fodop_ui('doCSA',job);
createbyCSA.vout = @vout;
% ---------------------------------------------------------------------
% createFOD by CSD (Tournier)
% ---------------------------------------------------------------------
newfilenameFOD = newfilename; newfilenameFOD.name = 'New File Name FOD (mrStruct)';
createbyCSDt = cfg_exbranch;
createbyCSDt.tag = 'createbyCSDTournier';
createbyCSDt.name = 'Create FOD by CSD (Tournier)';
createbyCSDt.help = {'Create Fiber Orientation Distribution with CSD approach (Tournier).'};
pp = (cellfun(@(x) [x ' '],paramtagsCSA,'uniformoutput',false)); pp = cat(2,pp{[1 3 4]});
createbyCSDt.val = eval(['{filename1 newfilenameFOD roidef ' pp ' }']);
createbyCSDt.prog = @(job)dti_fodop_ui('doCSDTournier',job);
createbyCSDt.vout = @vout;
% ---------------------------------------------------------------------
% createFOD by CSD with fiber continuity
% ---------------------------------------------------------------------
createbyCSDFC = cfg_exbranch;
createbyCSDFC.tag = 'createbyCSFC';
createbyCSDFC.name = 'Create FOD by CSD-Fiber Continuity';
createbyCSDFC.help = {'Create Fiber Orientation Distribution by CSD with Fiber Continuity regularizer (Reisert).'};
pp = (cellfun(@(x) [x ' '],paramtagsCSDFC,'uniformoutput',false)); pp = cat(2,pp{:});
createbyCSDFC.val = eval(['{filename1 newfilenameFOD roidef ' pp ' }']);
createbyCSDFC.prog = @(job)dti_fodop_ui('doCSDFC',job);
createbyCSDFC.vout = @vout;
% ---------------------------------------------------------------------
% createFODTFD
% ---------------------------------------------------------------------
fioutTFD = fiout; fioutTFD.name = 'New File Name TFD (mrStruct or Nifti)';
createbyCSDTFD = cfg_exbranch;
createbyCSDTFD.tag = 'createbyCSDTFD';
createbyCSDTFD.name = 'Create FOD by L1-CSD with Tensor Divergence';
createbyCSDTFD.help = {'Create Fiber Orientation Distribution with CSD, where mean density per voxel is determined by TFD.'};
pp = (cellfun(@(x) [x ' '],paramtags,'uniformoutput',false)); pp = cat(2,pp{:});
createbyCSDTFD.val = eval(['{filename1 roidef newfilenameFOD fioutTFD ' pp ' }']);
createbyCSDTFD.prog = @(job)dti_fodop_ui('doL1CSD_TFD',job);
createbyCSDTFD.vout = @voutFODTFD;
% ---------------------------------------------------------------------
% createTFD
% ---------------------------------------------------------------------
filename1FOD = filename1;
filename1FOD.name = 'Select the FOD-mrstruct';
filename1FOD.help = {'Select the mrstruct (usually something like blah_FOD.mat'};
createbyTFD = cfg_exbranch;
createbyTFD.tag = 'createbyCSDTFD';
createbyTFD.name = 'Create TFD from FOD';
createbyTFD.help = {'Create tensor fiber density from given FOD.'};
pp = (cellfun(@(x) [x ' '],paramtags,'uniformoutput',false)); pp = cat(2,pp{[1 8:10]});
createbyTFD.val = eval(['{filename1FOD roidef fioutTFD modifyFOD ' pp ' }']);
createbyTFD.prog = @(job)dti_fodop_ui('doTFD',job);
createbyTFD.vout = @voutTFD;
% ---------------------------------------------------------------------
% deformFOD
% ---------------------------------------------------------------------
deformFOD = cfg_exbranch;
deformFOD.tag = 'deformFOD';
deformFOD.name = 'Deformation of FOD';
deformFOD.help = {'Non Rigid deformation of FODs by deformation fields created with NewSegment.'};
deformFOD.val = {filename2 filedef filedefi interp modulate noutdir newfilename};
deformFOD.prog = @(job)dti_fodop_ui('deformFOD',job);
deformFOD.vout = @vout;
% ---------------------------------------------------------------------
% deformFOD
% ---------------------------------------------------------------------
deformFDalong = cfg_exbranch;
deformFDalong.tag = 'deformFDalong';
deformFDalong.name = 'Deformation of FD along FOD';
deformFDalong.help = {'Non Rigid deformation of FD intepreted as mean of FOD.'};
deformFDalong.val = {filename2 filename4 filedef filedefi interp modulate newfilename};
deformFDalong.prog = @(job)dti_fodop_ui('deformFDalong',job);
deformFDalong.vout = @vout;
% ---------------------------------------------------------------------
% smoothFOD
% ---------------------------------------------------------------------
smoothFOD = cfg_exbranch;
smoothFOD.tag = 'smoothFOD';
smoothFOD.name = 'Anisotropic Smooth of FOD/HARDI';
smoothFOD.help = {'Smooth along the current FOD direction.'};
smoothFOD.val = {filename2 axialsigma radialsigma newfilename};
smoothFOD.prog = @(job)dti_fodop_ui('smoothFOD',job);
smoothFOD.vout = @vout;
% ---------------------------------------------------------------------
% smoothFOD
% ---------------------------------------------------------------------
smoothFODRic = cfg_exbranch;
smoothFODRic.tag = 'smoothFODRic';
smoothFODRic.name = 'Anisotropic Smooth of FOD/HARDI (Rician)';
smoothFODRic.help = {'Smooth along the current FOD direction.'};
smoothFODRic.val = {filename2 axialsigma radialsigma ksz noiselevel newfilename};
smoothFODRic.prog = @(job)dti_fodop_ui('smoothFODRic',job);
smoothFODRic.vout = @vout;
% ---------------------------------------------------------------------
% get mFOD
% ---------------------------------------------------------------------
getsiFOD = cfg_exbranch;
getsiFOD.tag = 'getsiFOD';
getsiFOD.name = 'Compute scalar map from FOD';
getsiFOD.help = {'Computes several types of scalar indices from FOD.'};
getsiFOD.val = {filename2 sitype fiout};
getsiFOD.prog = @(job)dti_fodop_ui('getsiFOD',job);
getsiFOD.vout = @voutSI;
% ---------------------------------------------------------------------
% resample HARDI
% ---------------------------------------------------------------------
resampleHARDI = cfg_exbranch;
resampleHARDI.tag = 'resampleHARDI';
resampleHARDI.name = 'Resample Diffusion directions of HARDI data';
resampleHARDI.help = {'Resamples Orientation Information.'};
resampleHARDI.val = {filename1 filenameHARDI1};
resampleHARDI.prog = @(job)dti_fodop_ui('resampleHARDI',job);
resampleHARDI.vout = @voutHARDI;
% ---------------------------------------------------------------------
% pathIntegral tracking
% ---------------------------------------------------------------------
outftr = cfg_branch;
outftr.tag = 'outftr';
outftr.name = 'Specify name of FTR';
outftr.val = {newfilenamemat};
outftr.help = {'Specify a output filename.'};
% ---------------------------------------------------------------------
% autoimg Automatically generate Output Filename
% ---------------------------------------------------------------------
noftr = cfg_const;
noftr.tag = 'noftr';
noftr.name = 'Produce no fiber tracks';
noftr.val = {true};
noftr.help = {'Produce no fiber tracks by streamlining.'};
% ---------------------------------------------------------------------
% outname Output Naming Scheme
% ---------------------------------------------------------------------
streamftr = cfg_choice;
streamftr.tag = 'streamftr';
streamftr.name = 'Produce Streamlines (single ROI)';
streamftr.values = {outftr noftr};
streamftr.help = {'Produce Streamlines'};
streamftrpaired = cfg_choice;
streamftrpaired.tag = 'streamftrpaired';
streamftrpaired.name = 'Produce Streamlines (ROI pairs)';
streamftrpaired.values = {outftr noftr};
streamftrpaired.help = {'Produce Streamlines.'};
PItrack = cfg_exbranch;
PItrack.tag = 'PItrack';
PItrack.name = 'Path Integral Connectivity';
PItrack.help = {'please help me out.'};
pp = (cellfun(@(x) [x ' '],paramtagsPI,'uniformoutput',false)); pp = cat(2,pp{:});
PItrack.val = eval(['{filename2 roiname thresh filenameROIs newfilenamemat savePImaps streamftr streamftrpaired ' pp ' }']);
PItrack.prog = @(job)dti_fodop_ui('PItrack',job);
PItrack.vout = @voutPITRACK;
PItrails = cfg_exbranch;
PItrails.tag = 'PItrails';
PItrails.name = 'Create PI trails';
PItrails.val = {filenamePIcon roipairs};
PItrails.prog = @(job)dti_fodop_ui('PItrails',job);
PItrails.vout = @voutPITRAILS;
% ---------------------------------------------------------------------
% probtrax
% ---------------------------------------------------------------------
PXtrack = cfg_exbranch;
PXtrack.tag = 'PXtrack';
PXtrack.name = 'Probtrackx';
PXtrack.help = {'please help me out.'};
pp = (cellfun(@(x) [x ' '],paramtagsPX,'uniformoutput',false)); pp = cat(2,pp{:});
PXtrack.val = eval(['{filename2 roiname thresh filenameROIs newfilenamemat ' pp ' }']);
PXtrack.prog = @(job)dti_fodop_ui('PXtrack',job);
PXtrack.vout = @voutPXTRACK;
% ---------------------------------------------------------------------
% mapop
% ---------------------------------------------------------------------
fodop = cfg_choice;
fodop.tag = 'fodop';
fodop.name = 'Operations with FODs';
fodop.help = {'Operations with fiber orientation distributions (FOD).'};
fodop.values = {createbyCSD createbyCSDt createbyCSDFC createbyCSA createbyTFD deformFOD smoothFOD smoothFODRic getsiFOD resampleHARDI PItrack PItrails PXtrack};
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'FOD mrstruct';
dep.src_output = substruct('.','FOD');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
function dep = voutPITRACK(job)
dep = cfg_dep;
dep.sname = 'PI Connectivity Information and (optionally) Maps';
dep.src_output = substruct('.','PIinfo');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
function dep = voutPXTRACK(job)
dep = cfg_dep;
dep.sname = 'ProbtrackX Connectivity Information';
dep.src_output = substruct('.','PXinfo');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
function dep = voutPITRAILS(job)
dep = cfg_dep;
dep.sname = 'Nifti with PI-trail maps';
dep.src_output = substruct('.','mapnames');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
function dep = voutHARDI(job)
dep = cfg_dep;
dep.sname = 'HARDI mrstruct';
dep.src_output = substruct('.','HARDI');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
function dep = voutSI(job)
dep = cfg_dep;
dep.sname = 'Scalar Index (nifti/mrstruct)';
dep.src_output = substruct('.','SIndex');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
function dep = voutFODTFD(job)
dep(1) = cfg_dep;
dep(1).sname = 'FOD mrstruct';
dep(1).src_output = substruct('.','FOD');
dep(1).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'TFD (nifti/mrstruct)';
dep(2).src_output = substruct('.','TFD');
dep(2).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
function dep = voutTFD(job)
dep = cfg_dep;
dep.sname = 'TFD mrstruct';
dep.src_output = substruct('.','TFD');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
|
github | philippboehmsturm/antx-master | dti_ftrop_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_ftrop_ui.m | 21,825 | utf_8 | 8306f6a3d43356357e4a0e43745657cf | % interface program for batch program
% Operations with streamline tracts (Mori Tracts).
% Author: Susanne Schnell
% PC 13.02.2009
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = dti_ftrop_ui(cmd, P)
switch cmd,
case 'selectbyROI'
autofname = '_selFTR.mat';
%load fibers and ROI
FTRStruct = ftrstruct_read(P.filename1{1});
ROI = maskstruct_read(P.roidef.roiname{1});
%% transform fibers into space defined ROI
t = inv(ROI.mrsProp.edges)*FTRStruct.hMatrix;
FTRStruct.curveSegCell = cellfun(@(x) 1+ (x-1)*t(1:3,1:3)' + repmat(t(1:3,4)',[size(x,1) 1]) , FTRStruct.curveSegCell,'uniformoutput',false);
if P.seltype == 0,
SelType = 'inArea';
else
SelType = 'endPointInArea' ; %'inArea';
end;
% select fibers
if isfield(P.roidef.mask,'masknumber')
ROInames = maskstruct_query(ROI,'maskNames');
if isfield(P.fibersubset,'fibernumber')
FiberNames = ftrstruct_query(FTRStruct, 'fiberNames');
[fibersNew, errStr]= ftrstruct_query(FTRStruct,SelType, maskstruct_query(ROI, 'getMRMask', ROInames{P.roidef.mask.masknumber}), FiberNames{P.fibersubset.fibernumber}, 1);
else
[fibersNew, errStr]= ftrstruct_query(FTRStruct,SelType, maskstruct_query(ROI, 'getMRMask', P.roidef.mask.maskname), P.fibersubset.fibername, 1);
end
else
if isfield(P.fibersubset,'fibernumber')
FiberNames = ftrstruct_query(FTRStruct, 'fiberNames');
[fibersNew, errStr]= ftrstruct_query(FTRStruct,SelType, maskstruct_query(ROI, 'getMRMask', P.roidef.mask.maskname), FiberNames{P.fibersubset.fibernumber}, 1);
else
[fibersNew, errStr]= ftrstruct_query(FTRStruct,SelType, maskstruct_query(ROI, 'getMRMask', P.roidef.mask.maskname), P.fibersubset.fibername, 1);
end
end
if ~isempty(errStr)
error(errStr)
end
if isempty(fibersNew)
error('No fibers selected!');
return;
end
roiNames= ftrstruct_query(FTRStruct, 'roiNames', []);
if isfield(P.roidef.mask,'masknumber')
roiNames{end + 1, 1}= ROInames{P.roidef.mask.masknumber};
else
roiNames{end + 1, 1}= P.roidef.mask.maskname;
end
fibersNew.roiName= roiNames;
fibersNew.name= P.fibername;
[FTRStruct, errStr]= ftrstruct_modify(FTRStruct, 'insertFiber', fibersNew);
%% transform fibers into fiber space
invt = inv(t);
FTRStruct.curveSegCell = cellfun(@(x) 1+ (x-1)*invt(1:3,1:3)' + repmat(invt(1:3,4)',[size(x,1) 1]) , FTRStruct.curveSegCell,'uniformoutput',false);
if ~isempty(errStr)
error(errStr)
end
case 'eliminatebyROI'
autofname = '_elimFTR.mat';
%eliminate fibers
FTRStruct = ftrstruct_read(P.filename1{1});
ROI = maskstruct_read(P.roidef.roiname{1});
%% transform fibers into space defined ROI
t = inv(ROI.mrsProp.edges)*FTRStruct.hMatrix;
FTRStruct.curveSegCell = cellfun(@(x) 1+ (x-1)*t(1:3,1:3)' + repmat(t(1:3,4)',[size(x,1) 1]) , FTRStruct.curveSegCell,'uniformoutput',false);
if isfield(P.roidef.mask,'masknumber')
ROInames = maskstruct_query(ROI,'maskNames');
if isfield(P.fibersubset,'fibernumber')
FiberNames = ftrstruct_query(FTRStruct, 'fiberNames');
[fibersNew, errStr]= ftrstruct_query(FTRStruct,'inArea',maskstruct_query(ROI, 'getMRMask', ROInames{P.roidef.mask.masknumber}), FiberNames{P.fibersubset.fibernumber}, 0);
else
[fibersNew, errStr]= ftrstruct_query(FTRStruct,'inArea',maskstruct_query(ROI, 'getMRMask', ROInames{P.roidef.mask.masknumber}), P.fibersubset.fibername, 0);
end
else
if isfield(P.fibersubset,'fibernumber')
FiberNames = ftrstruct_query(FTRStruct, 'fiberNames');
[fibersNew, errStr]= ftrstruct_query(FTRStruct,'inArea',maskstruct_query(ROI, 'getMRMask', P.roidef.mask.maskname), FiberNames{P.fibersubset.fibernumber}, 0);
else
[fibersNew, errStr]= ftrstruct_query(FTRStruct,'inArea',maskstruct_query(ROI, 'getMRMask', P.roidef.mask.maskname), P.fibersubset.fibername, 0);
end
end
if isempty(fibersNew)
return;
end
if ~isempty(errStr)
error(errStr)
end
roiNames= ftrstruct_query(FTRStruct, 'roiNames', []);
if isfield(P.roidef.mask,'masknumber')
roiNames{end + 1, 1}= ROInames{P.roidef.mask.masknumber};
else
roiNames{end + 1, 1}= P.roidef.mask.maskname;
end
fibersNew.roiName= roiNames;
fibersNew.name= P.fibername;
[FTRStruct, errStr]= ftrstruct_modify(FTRStruct, 'insertFiber', fibersNew);
%% transform fibers into fiber space
invt = inv(t);
FTRStruct.curveSegCell = cellfun(@(x) 1+ (x-1)*invt(1:3,1:3)' + repmat(invt(1:3,4)',[size(x,1) 1]) , FTRStruct.curveSegCell,'uniformoutput',false);
if ~isempty(errStr)
error(errStr)
end
case 'visitMapext'
autofname = '_visitMap.mat';
%load data
FTRStruct = ftrstruct_read(P.filename1{1});
ref = P.filename3{1};
[pathname finame ext] = fileparts(ref);
if strcmp(ext,'.mat');
mr = load(ref);
if isfield(mr,'mrStruct')
mr = mr.mrStruct;
elseif isfield(mr,'b0_image_struc')
mr = mr.b0_image_struc;
end;
else
mr = nifti_to_mrstruct('volume',{ref});
end;
vox = mr.vox;
t = inv(mr.edges)*FTRStruct.hMatrix;
FTRStruct.curveSegCell = cellfun(@(x) 1+ (x-1)*t(1:3,1:3)' + repmat(t(1:3,4)',[size(x,1) 1]) , FTRStruct.curveSegCell,'uniformoutput',false);
if isfield(P.fibersubset,'fibernumber')
fnum = P.fibersubset.fibernumber;
else
FiberNames = ftrstruct_query(FTRStruct, 'fiberNames');
fnum = find(cellfun(@(x) strcmp(x,P.fibersubset.fibername),FiberNames));
end;
if fnum == 1,
fnum = [];
else
fnum = fnum -1;
end;
reparam_step = 0.9*min(vox(1:3))/P.oversampling;
for k = 1:length(FTRStruct.curveSegCell),
FTRStruct.curveSegCell{k} = reparametrize_arclen(single(FTRStruct.curveSegCell{k})',double(reparam_step))';
end;
[fdrgb,fd,ep] = ftr2FDmaps(FTRStruct,size(mr.dataAy),fnum,P.oversampling);
if strcmp(P.newfilename,'.mat') || strcmp(P.newfilename,'.nii')
[pathname finame ] = fileparts(P.filename1{1});
outname = fullfile(pathname,finame);
ext = P.newfilename;
else
[pathname outname ext] = fileparts(P.newfilename);
outname = fullfile(pathname,outname);
end;
fdrgbname = [outname '_fdrgb'];
fdname = [outname '_fd'];
epname = [outname '_ep'];
mr.vox = mr.vox/P.oversampling;
mI = eye(4); mI(1:3,4) = -1;
sC = eye(3)/P.oversampling; sC(4,4) = 1;
mr.edges = mr.edges*inv(mI)*sC*mI;
if strcmp(ext,'.mat')
mr.memoryType = 'series3D';
mr.dataAy = fdrgb; mrstruct_write(mr,[fdrgbname '.mat']); out.fdrgb = {[fdrgbname '.mat']};
mr.memoryType = 'volume';
mr.dataAy = fd; mrstruct_write(mr,[fdname '.mat']); out.fd = {[fdname '.mat']};
mr.memoryType = 'volume';
mr.dataAy = ep; mrstruct_write(mr,[epname '.mat']); out.ep = {[epname '.mat']};
elseif strcmp(ext,'.nii')
mr.memoryType = 'series3D';
mr.dataAy = fdrgb; [res, errStr] = mrstruct_to_nifti(mr,[fdrgbname '.nii'],'float32'); out.fdrgb = {[fdrgbname '.nii']};
if ~isempty(errStr)
error(errStr)
end
mr.memoryType = 'volume';
mr.dataAy = fd; [res, errStr] = mrstruct_to_nifti(mr,[fdname '.nii'],'float32'); out.fd = {[fdname '.nii']};
if ~isempty(errStr)
error(errStr)
end
mr.memoryType = 'volume';
mr.dataAy = ep; [res, errStr] = mrstruct_to_nifti(mr,[epname '.nii'],'float32'); out.ep = {[epname '.nii']};
if ~isempty(errStr)
error(errStr)
end
end;
case 'visitMap'
autofname = '_visitMap.mat';
%load data
FTRStruct = ftrstruct_read(P.filename1{1});
DTD = dtdstruct_read(P.filename2{1});
t = inv(DTD.b0_image_struc.edges)*FTRStruct.hMatrix;
FTRStruct.curveSegCell = cellfun(@(x) 1+ (x-1)*t(1:3,1:3)' + repmat(t(1:3,4)',[size(x,1) 1]) , FTRStruct.curveSegCell,'uniformoutput',false);
if isfield(P.fibersubset,'fibernumber')
FiberNames = ftrstruct_query(FTRStruct, 'fiberNames');
%visit Mask
[map, errStr]= ftrstruct_query(FTRStruct, 'getVisitMap', FiberNames{P.fibersubset.fibernumber},size(DTD.b0_image_struc.dataAy));
else
[map, errStr]= ftrstruct_query(FTRStruct, 'getVisitMap', P.fibersubset.fibername,size(DTD.b0_image_struc.dataAy));
end
if ~isempty(errStr)
error(errStr)
end
case 'visitMask'
autofname = '_visitMask.mat';
%load data
FTRStruct = ftrstruct_read(P.filename1{1});
DTD = dtdstruct_read(P.filename2{1});
t = inv(DTD.b0_image_struc.edges)*FTRStruct.hMatrix;
FTRStruct.curveSegCell = cellfun(@(x) 1+ (x-1)*t(1:3,1:3)' + repmat(t(1:3,4)',[size(x,1) 1]) , FTRStruct.curveSegCell,'uniformoutput',false);
if isfield(P.fibersubset,'fibernumber')
FiberNames = ftrstruct_query(FTRStruct, 'fiberNames');
%visit Mask
[mask, errStr]= ftrstruct_query(FTRStruct, 'getVisitMask', FiberNames{P.fibersubset.fibernumber},size(DTD.b0_image_struc.dataAy),P.thresh);
else
%visit Mask
[mask, errStr]= ftrstruct_query(FTRStruct, 'getVisitMask',P.fibersubset.fibername,size(DTD.b0_image_struc.dataAy),P.thresh);
end
if ~isempty(errStr)
error(errStr)
end
case 'endpointMask'
autofname = '_endMask.mat';
% load data
FTRStruct = ftrstruct_read(P.filename1{1});
DTD = dtdstruct_read(P.filename2{1});
t = inv(DTD.b0_image_struc.edges)*FTRStruct.hMatrix;
FTRStruct.curveSegCell = cellfun(@(x) 1+ (x-1)*t(1:3,1:3)' + repmat(t(1:3,4)',[size(x,1) 1]) , FTRStruct.curveSegCell,'uniformoutput',false);
if isfield(P.fibersubset,'fibernumber')
FiberNames = ftrstruct_query(FTRStruct, 'fiberNames');
% endpointMask
[map, errStr]= ftrstruct_query(FTRStruct, 'getEndPointMap', FiberNames{P.fibersubset.fibernumber},size(DTD.b0_image_struc.dataAy));
else
[map, errStr]= ftrstruct_query(FTRStruct, 'getEndPointMap', P.fibersubset.fibername,size(DTD.b0_image_struc.dataAy));
end
if ~isempty(errStr)
error(errStr)
end
case 'deformFTR'
autofname = '_defFTR.mat';
try
FTRStruct = ftr_warp( P.filedefi{1},P.filedef{1}, P.filename1{1});
catch
error(lasterr);
end
case 'tractStats'
FTRStruct = ftrstruct_read(P.filename1{1});
mrProp = mrPropFromFTR(FTRStruct);
con = getContrasts(P,mrProp);
contrasts = {};
if not(isempty(con)),
contrasts = {con.mr};
end;
bundles = stat_along_tract(FTRStruct,contrasts);
[p n e] = fileparts(P.filename1{1});
txtfile = fullfile(p,[P.newfilename2 '.txt']);
fid = fopen(txtfile,'w');
fprintf(fid,'name fibcnt mean_length sdev_length max_length min_length prctile05_length prctile95_length\n');
for k = 1:length(bundles),
fprintf(fid,'%s\t%i\t%f\t%f\t%f\t%f\t%f\t%f\n',bundles(k).name ,bundles(k).fibcnt ,bundles(k).mean_length ,bundles(k).sdev_length ,bundles(k).max_length ,bundles(k).min_length ,bundles(k).prctile05_length ,bundles(k).prctile95_length);
end
fprintf(fid,'\n');
if isfield(bundles(1),'contrast')
fprintf(fid,'bundle contrast mean sdev min max prctile05 prctile95\n');
for k = 1:length(bundles),
for j = 1:length(bundles(k).contrast)
c = bundles(k).contrast(j);
bundles(k).contrast(j).name = con(j).name;
fprintf(fid,'%s\t%s\t%f\t%f\t%f\t%f\t%f\t%f\n',bundles(k).name,con(j).name,c.mean,c.sdev,c.min,c.max,c.prctile05,c.prctile95);
end;
end;
fprintf(fid,'\n');
end;
fclose(fid);
matfile = fullfile(p,[P.newfilename2 '.mat']);
save(matfile,'bundles');
out.files{1} = matfile;
case 'tractStatsROI'
% get FTR
ftr = ftrstruct_read(P.filename1{1});
mrProp = mrPropFromFTR(ftr);
% get Contrasts for tractometry
con = getContrasts(P,mrProp);
% get ROIs
[p n e] = fileparts(P.filename5{1});
mastru = false;
if strcmp(e,'.mat'),
dat = load(P.filename5{1});
if maskstruct_istype(dat),
roi = dat;
mastru = true;
elseif isfield(dat,'mrStruct'),
roi = dat;
end;
elseif strcmp(e,'.nii') | strcmp(e,'.hdr')
resliceFlags.mask= 0;
resliceFlags.mean= 0;
resliceFlags.interp= 0;
resliceFlags.which=1;
roi = nifti_to_mrstruct('volume', {P.filename5{1}},mrProp,pwd,resliceFlags);
end;
% selection type
if P.seltype == 0,
SelType = 'inArea';
else
SelType = 'endPointInArea' ; %'inArea';
end;
fuzzy = [];
if isfield(P.fuzzysel,'fuzzy'),
fuzzy.sigma = P.fuzzysel.fuzzy.sigmafuz;
fuzzy.thres = P.fuzzysel.fuzzy.threshfuz;
end;
if not(mastru),
if isempty(P.roinumber),
roiidx = unique(roi.dataAy(roi.dataAy(:)>0));
else
roiidx = P.roinumber;
end;
else
if isempty(P.roinumber),
roiidx = 1:length(roi.maskCell);
else
roiidx = P.roinumber;
end;
end;
Nrois = length(roiidx);
contrasts = {};
if not(isempty(con)),
contrasts = {con.mr};
end;
for k = 1:Nrois
mask = mrProp;
if not(mastru),
mask.dataAy = zeros(size(mask.dataAy));
mask.dataAy(roi.dataAy==roiidx(k)) = 1;
maskname = ['ROI' num2str(roiidx(k))];
else
mask = roi.mrsProp;
mask.dataAy = roi.maskCell{roiidx(k)};
maskname = roi.maskNamesCell{roiidx(k)};
end;
ftr.fiber = {};
fibsA = ftrstruct_query(ftr,SelType,mask,[],1,[],fuzzy);
bundles(k,k) = stat_along_tract([]);
if not(isempty(fibsA)),
fibsA.name = maskname;
ftr.fiber = {fibsA};
bundles(k,k) = stat_along_tract(ftr,contrasts);
for j = k+1:Nrois
fprintf('.');
if not(mastru),
mask.dataAy = zeros(size(mask.dataAy));
mask.dataAy(roi.dataAy==roiidx(j)) = 1;
maskname2 = ['ROI' num2str(roiidx(j))];
else
mask = roi.mrsProp;
mask.dataAy = roi.maskCell{roiidx(j)};
maskname2 = roi.maskNamesCell{roiidx(j)};
end;
fibs = ftrstruct_query(ftr,SelType,mask,1,1,[],fuzzy);
bundles(k,j) = stat_along_tract([]);
if not(isempty(fibs)),
fibs.name = [maskname '/' maskname2];
ftrn = ftr;
ftrn.fiber = {fibs};
bundles(k,j) = stat_along_tract(ftrn,contrasts);
end;
bundles(j,k) = bundles(k,j);
end
end;
fprintf('\n');
end
res.bundles = bundles;
bundles = arrayfun(@(x) setfield(x,'fibcnt',emptyToZero(x.fibcnt)),bundles);
res.Cmat = reshape([bundles(:).fibcnt],[Nrois Nrois]);
res.totnumfibs = length(ftr.curveSegCell);
matfile = fullfile(p,[P.newfilename2 '.mat']);
save(matfile,'-struct','res');
out.files{1} = matfile;
end
if not(strcmp(cmd,'visitMapext')) & not(strcmp(cmd,'tractStats')) & not(strcmp(cmd,'tractStatsROI')),
% newfilename
if strcmp(P.newfilename,'.mat') || isempty(P.newfilename)
[path,name] = fileparts(P.filename1{1});
filename = fullfile(path, [name(1:end-4), autofname]);
else
[path,name,ext] = fileparts(P.filename1{1});
[newpath,name,ext] = fileparts(P.newfilename);
if isempty(newpath)
filename = fullfile(path,[name ext]);
else
filename = fullfile(newpath,[name ext]);
end
end
%save result
if strcmp(cmd,'selectbyROI') || strcmp(cmd ,'eliminatebyROI') || strcmp(cmd ,'deformFTR')
[res, errStr] = ftrstruct_write(FTRStruct,filename);
if ~isempty(errStr)
error(errStr)
end
elseif strcmp(cmd,'visitMap')
map = mrstruct_init('volume',map,DTD.b0_image_struc);
mrstruct_write(map,filename);
elseif strcmp(cmd,'visitMask')
[res, errStr] = maskstruct_write(mask,filename);
if ~isempty(errStr)
error(errStr)
end
else
[mask, errStr] = maskstruct_init(DTD.b0_image_struc);
if ~isempty(errStr)
error(errStr)
end
[mask, errStr] = maskstruct_modify(mask,'createMask','endPointMask');
if ~isempty(errStr)
error(errStr)
end
[mask, errStr] = maskstruct_modify(mask,'setMask',map,'endPointMask');
if ~isempty(errStr)
error(errStr)
end
[res, errStr] = maskstruct_write(mask,filename);
if ~isempty(errStr)
error(errStr)
end
end
out.files{1} = filename;
end;
%%%% function to get gather contrasts for tractometry
function con = getContrasts(P,mrprop)
if isfield(P.contrastsel,'nocontrast'),
con = [];
return;
end;
cnt = 1;
for k = 1:length(P.contrastsel.filename4);
[p n e] = fileparts(P.contrastsel.filename4{k});
if strcmp(e,'.mat'),
dat = load(P.contrastsel.filename4{k});
if dtdstruct_istype(dat),
con(cnt).name = 'FA';
con(cnt).mr = dtdstruct_query(dat,'getFA');
cnt = cnt + 1;
con(cnt).name = 'Trace';
con(cnt).mr = dtdstruct_query(dat,'getTrace');
con(cnt).mr.dataAy = con(cnt).mr.dataAy*10^3;
cnt = cnt + 1;
con(cnt).name = 'EigAx';
con(cnt).mr = dtdstruct_query(dat,'getEigVal1');
con(cnt).mr.dataAy = con(cnt).mr.dataAy*10^3;
cnt = cnt + 1;
con(cnt).name = 'EigRad';
con(cnt).mr = dtdstruct_query(dat,'getEigVal2');
ev3 = dtdstruct_query(dat,'getEigVal3');
con(cnt).mr.dataAy = (con(cnt).mr.dataAy + ev3.dataAy)*0.5;
con(cnt).mr.dataAy = con(cnt).mr.dataAy*10^3;
cnt = cnt + 1;
elseif isfield(dat,'mrStruct'),
con(cnt).name = n;
con(cnt).mr = dat.mrStruct;
cnt = cnt + 1;
end;
elseif strcmp(e,'.nii') | strcmp(e,'.hdr')
mrStruct = nifti_to_mrstruct('volume', {P.contrastsel.filename4{k}},mrprop);
con(cnt).name = n;
con(cnt).mr = mrStruct;
cnt = cnt + 1;
end;
end;
function x = emptyToZero(x)
if isempty(x)
x = 0;
end;
function mrProp = mrPropFromFTR(ftr)
mrProp = mrstruct_init;
mrProp.edges = ftr.hMatrix;
mrProp.vox = ftr.vox;
sz = ceil(max( cat(1,ftr.curveSegCell{:})));
mrProp.dataAy = zeros(sz);
mrProp.memoryType = 'volume';
mrProp.dim3 = 'size_z';
|
github | philippboehmsturm/antx-master | dti_tensor_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_tensor_ui.m | 2,450 | utf_8 | df0595287593fef7a0809a1afc99a8e3 | % interface program for batch modus
%
% Author: Susanne Schnell
% PC 10.04.2008
function out = dti_tensor_ui(P)
if nargin == 1 && isstruct(P) && isfield(P, 'filename')
[path,nam,ext] = fileparts(P.filename{1});
filename = fullfile(path,nam);
savemode = bitset(bitset(0,1,P.singleslice),2,P.hardi);
if strcmp(ext,'.bin')
[ok, msg] = calculate_dti(filename(1:end-4),P.threshold,savemode);
out.files{1} = strcat(filename(1:end-4),'_DTD.mat');
elseif strcmp(ext,'.mat')
mr = mrstruct_read(strcat(filename,'.mat'));
if isfield(mr.user,'bvalue') && isfield(mr.user,'DEscheme') && isfield(mr.user,'nob0s')
if iscell(mr.user.DEscheme)
if exist(mr.user.DEscheme{1},'file')
[ok, msg] = calculate_dti(strcat(filename,'.mat'),P.threshold,savemode,load(mr.user.DEscheme{1}),mr.user.bvalue,mr.user.nob0s);
out.files{1} = strcat(filename,'_DTD.mat');
else
[ok, msg] = calculate_dti(strcat(filename,'.mat'),P.threshold,savemode,mr.user.DEscheme,mr.user.bvalue,mr.user.nob0s);
out.files{1} = strcat(filename,'_DTD.mat');
end
else
if exist(mr.user.DEscheme,'file')
[ok, msg] = calculate_dti(strcat(filename,'.mat'),P.threshold,savemode,load(mr.user.DEscheme),mr.user.bvalue,mr.user.nob0s);
out.files{1} = strcat(filename,'_DTD.mat');
else
[ok, msg] = calculate_dti(strcat(filename,'.mat'),P.threshold,savemode,mr.user.DEscheme,mr.user.bvalue,mr.user.nob0s);
out.files{1} = strcat(filename,'_DTD.mat');
end
end
else
error('Mrstruct does not contain the necessary information in field user (bvalue, DEscheme or nob0s is missing)');
end
clear mr
elseif isempty(ext)
if strcmp(filename(end-3:end),'_raw')
[ok, msg] = calculate_dti(filename(1:end-4),P.threshold,savemode);
out.files{1} = strcat(filename(1:end-4),'_DTD.mat');
else
[ok, msg] = calculate_dti(filename,P.threshold,savemode);
out.files{1} = strcat(filename,'_DTD.mat');
end
else
error('The filename for the raw data file is wrong or not supported.');
end
if ~strcmp(msg,'DTI calculation finished.')
error(msg);
end
end
|
github | philippboehmsturm/antx-master | dti_cfg_read.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_cfg_read.m | 10,578 | utf_8 | f114717b2ad4c9cfd8122e53f2b3a44e | % configure file for reading DWI data (Dicom, Bruker or other formats)
% DTI Configuration file
% BATCH system (Volkmar Glauche)
%
% File created by Susanne Schnell
function read_data = dti_cfg_read
% ---------------------------------------------------------------------
% dicom Input dicom file names
% ---------------------------------------------------------------------
dicom = cfg_files;
dicom.tag = 'dicom';
dicom.name = 'Dicom Images';
dicom.help = {'These are the images that will be needed for tensor calculation.'
'Choose more than one directory if you want to average the data (this is only possible if the datasets are acquired with identical sequence parameters)!'};
dicom.filter = 'dir';
dicom.num = [1 Inf];
% ---------------------------------------------------------------------
% exdicom Dicom conversion
% ---------------------------------------------------------------------
exdicom = cfg_exbranch;
exdicom.tag = 'exdicom';
exdicom.name = 'Import Dicom Data';
exdicom.help = {
'The tools are tested for Siemens Dicom VB12 and VB13. All other Dicom files can generall be read in, but diffusion specific information might be provided manually.'
};
exdicom.val = {dicom};
exdicom.prog = @(job)dti_readdata_ui('dicom',job);
exdicom.vout = @vout;
% ---------------------------------------------------------------------
% bruker Input bruker file names
% ---------------------------------------------------------------------
bruker = cfg_files;
bruker.tag = 'bruker';
bruker.name = 'Bruker Images';
bruker.help = {'This is the directory with the images that will be needed for tensor calculation.'};
bruker.filter = 'dir';
bruker.num = [1 1];
% ---------------------------------------------------------------------
% exbruker Bruker conversion
% ---------------------------------------------------------------------
exbruker = cfg_exbranch;
exbruker.tag = 'exbruker';
exbruker.name = 'Import Bruker Data';
exbruker.val = {bruker};
exbruker.prog = @(job)dti_readdata_ui('bruker',job);
exbruker.vout = @vout;
% ---------------------------------------------------------------------
% binary Input binary file name
% ---------------------------------------------------------------------
binary = cfg_files;
binary.tag = 'binary';
binary.name = 'Binary Data File';
binary.help = {'These are the images that will be needed for tensor calculation.'};
binary.filter = 'any';
binary.ufilter = '\.bin$';
binary.num = [1 1];
% ---------------------------------------------------------------------
% exbinary Binary conversion
% ---------------------------------------------------------------------
exbinary = cfg_exbranch;
exbinary.tag = 'exbinary';
exbinary.name = 'Import Binary Data';
exbinary.help = {'Binary is an inhouse format, which consists of two files: "_raw.bin" and "_info.mat" (see examples and manual).'
'mrstruct is also an inhouse format, but can be created by the user (see manual).'};
exbinary.val = {binary};
exbinary.prog = @(job)dti_readdata_ui('binary',job);
exbinary.vout = @vout;
% ---------------------------------------------------------------------
% descheme Input File containg diffusion encoding directions
% ---------------------------------------------------------------------
descheme = cfg_files;
descheme.tag = 'descheme';
descheme.name = 'DEscheme';
descheme.help = {'Please chose a text file (m-file or mat-file also possible) with diffusion encoding directions.'
'The scans without diffusion weighting (b = 0) should be in the beginning.'};
descheme.filter = 'any';
descheme.ufilter = '\.(txt)|(mat)|m$';
descheme.num = [1 1];
% ---------------------------------------------------------------------
% nob0s The amount of b=0 scans
% ---------------------------------------------------------------------
nob0s = cfg_entry;
nob0s.tag = 'nob0s';
nob0s.name = 'nob0s';
nob0s.val = {1};
nob0s.help = {'Enter the amount of scans without diffusion weighting (b = 0).'};
nob0s.strtype = 'e';
nob0s.num = [1 1];
% ---------------------------------------------------------------------
% threshold
% ---------------------------------------------------------------------
threshold = cfg_entry;
threshold.tag = 'threshold';
threshold.name = 'threshold';
threshold.val = {40};
threshold.help = {'Enter the threshold where the fit is performed.'};
threshold.strtype = 'e';
threshold.num = [1 1];
% ---------------------------------------------------------------------
% bvalue the b-weighting
% ---------------------------------------------------------------------
bvalue = cfg_entry;
bvalue.tag = 'bvalue';
bvalue.name = 'bvalue';
bvalue.val = {1000};
bvalue.help = {'Enter the bvalue other than b = 0.'};
bvalue.strtype = 'e';
bvalue.num = [1 Inf];
% ---------------------------------------------------------------------
% volname: name of appended volume structure
% ---------------------------------------------------------------------
volname = cfg_entry;
volname.tag = 'volname';
volname.name = 'volume structure name';
volname.val = {'mrStruct'};
volname.help = {'Enter the name of the mrstruct to be added'};
volname.strtype = 's';
volname.num = [1 Inf];
% ---------------------------------------------------------------------
% dtdname for append volume
% ---------------------------------------------------------------------
dtdname = cfg_files;
dtdname.tag = 'dtdname';
dtdname.name = 'DTD filename';
dtdname.help = {'Select the dtd-mat file for appending mrstruct.'};
dtdname.filter = '_DTD.mat';
dtdname.ufilter = '.*';
dtdname.num = [1 1];
% ---------------------------------------------------------------------
% filename of mrstruct for append volume
% ---------------------------------------------------------------------
filename2 = cfg_files;
filename2.tag = 'filename2';
filename2.name = 'Mrstruct Data File';
filename2.help = {'Select the mrstruct for appending to DTD-mat file.'};
filename2.filter = 'mat';
filename2.ufilter = '.*';
filename2.num = [1 1];
% ---------------------------------------------------------------------
% mrstruct Input mrstruct file name
% ---------------------------------------------------------------------
filename = cfg_files;
filename.tag = 'filename';
filename.name = 'Mrstruct Data File';
filename.help = {'These are the images saved as mrstruct that will be needed for tensor calculation.'};
filename.filter = 'mat';
filename.ufilter = '.*';
filename.num = [1 1];
% ---------------------------------------------------------------------
% mrstruct Input mrstruct file name
% ---------------------------------------------------------------------
filenameHARDI = cfg_files;
filenameHARDI.tag = 'filename';
filenameHARDI.name = 'mrStruct Data File containg HARDI information';
filenameHARDI.help = {'These are the images that will be needed for tensor calculation.'};
filenameHARDI.filter = 'mat';
filenameHARDI.ufilter = '.*';
filenameHARDI.num = [1 1];
% ---------------------------------------------------------------------
% append volume to DTD (mrstruct)
% ---------------------------------------------------------------------
append = cfg_exbranch;
append.tag = 'mrstruct';
append.name = 'append volume to DTD';
append.help = {'Select an mrstruct of the same volume size for adding and saving into the dtd-mat file.'};
append.val = {dtdname filename2 volname};
append.prog = @(job)dti_readdata_ui('append',job);
append.vout = @vout;
% ---------------------------------------------------------------------
% mrstruct Input mrstruct file name
% ---------------------------------------------------------------------
mrstruct = cfg_exbranch;
mrstruct.tag = 'mrstruct';
mrstruct.name = 'Mrstruct Depending Information';
mrstruct.help = {'Select mrstruct and additional diffusion specific information.', ...
'For the matlab structure (mrstruct) or binary file (two files needed: "_raw.bin" and "_info.mat").'};
mrstruct.val = {filename descheme bvalue nob0s};
mrstruct.prog = @(job)dti_readdata_ui('mrstruct',job);
mrstruct.vout = @vout;
% ---------------------------------------------------------------------
% compute DTD from HARDI
% ---------------------------------------------------------------------
fnameDTD = cfg_entry;
fnameDTD.tag = 'fnameDTD';
fnameDTD.name = 'File Name of the resulting DTD';
fnameDTD.help = {'Type in the name of the new file containing the tensor.'};
fnameDTD.strtype = 's';
fnameDTD.num = [1 Inf];
dir = cfg_files;
dir.tag = 'dir';
dir.name = 'Output directory';
dir.help = {'Select the output directory.'};
dir.filter = 'dir';
dir.num = [1 1];
out = cfg_branch;
out.tag = 'out';
out.name = 'User-specified output location';
out.val = {dir fnameDTD};
out.help = {'Specify output directory and filename.'};
auto = cfg_const;
auto.tag = 'auto';
auto.name = 'Automatically determine output filename';
auto.val = {1};
newfileDTD = cfg_choice;
newfileDTD.tag = 'newfile';
newfileDTD.name = 'Select output location';
newfileDTD.values = {auto out};
newfileDTD.help = {'Name and location can be specified explicitly, or they can be derived from the input filename.'};
computeDTD = cfg_exbranch;
computeDTD.tag = 'computeDTD';
computeDTD.name = 'compute DTD from HARDI';
computeDTD.help = {'Select an mrstruct (HARDI) for tensor estimation.'};
computeDTD.val = { filenameHARDI threshold newfileDTD};
computeDTD.prog = @(job)dti_readdata_ui('computeDTDfromHARDI',job);
computeDTD.vout = @vout;
% ---------------------------------------------------------------------
% read_data
% ---------------------------------------------------------------------
read_data = cfg_choice;
read_data.tag = 'ReadData';
read_data.name = 'Data Import';
read_data.values = {exdicom exbruker exbinary mrstruct append computeDTD};
read_data.help = {'Read Dicom, Bruker, Matlab structure (mrstruct) or binary file DWI data.'};
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'DWI Data';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
|
github | philippboehmsturm/antx-master | dti_logroi_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_logroi_ui.m | 5,221 | utf_8 | b1813b1996d402ef0c6a50e5cc6892d2 | % interface program for batch program
% roi log
% Author: Susanne Schnell
% Windows 22.02.2011
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = dti_logroi_ui(P)
logFName= fullfile(P.logpath{1}, P.newfilename);
dtd = dtdstruct_read(P.dtdname{1});
comStr= dtdstruct_query(dtd, 'getComStr');
ROI = maskstruct_read(P.roiname{1});
ROInames = maskstruct_query(ROI,'maskNames');
if isfield(P.status,'ValsRoi')
number = P.status.ValsRoi.mask1;
if number(2) == Inf
number = 1 : 1 : numel(ROInames);
end
if isempty(dtd.b0_image_struc.patient)
patientStr= 'dummyName';
else
patientStr= str2filename(dtd.b0_image_struc.patient);
end
% hole alle Bilddaten und eigenwerte
for i= 1:length(comStr)
dataVal= dtdstruct_query(dtd, strcat('get', comStr{i}));
paramCell{i}= dataVal.dataAy;
end
% Fuer alle nicht leeren ROIS
for i = 1:length(number)
roiName= ROInames{number(i)};
[idx, errStr]= maskstruct_query(ROI, 'getMaskIdx', roiName);
if ~isempty(errStr)
disp(errStr);
return
end
if ~isempty(idx)
logFName= fullfile(P.logpath{1}, str2filename(sprintf(P.newfilename, patientStr, roiName), 'extFileName'));
file_ID= fopen(logFName, 'wt');
if file_ID < 0
logFName= fullfile(P.logpath, str2filename(sprintf(P.newfilename, patientStr, roiName)));
file_ID= fopen(logFName, 'wt');
if file_ID < 0
disp(strcat('Could not create file ''', logFName, ''''));
return
end
end
dataMy= zeros(length(idx), length(comStr));
for j= 1:length(comStr)
fprintf(file_ID, ' %s ', comStr{j});
dataMy(:, j)= reshape(paramCell{j}(idx), [length(idx) 1]);
end
valStrMy= reshape(sprintf('%20.13g', dataMy')', [size(dataMy, 2)*20, size(dataMy, 1)])';
% num2str(dataMy, 10);
valStrMy(:, end)= double(sprintf('\n'));
fprintf(file_ID, '\n%s\n', valStrMy');
fclose(file_ID); %close file
end
end
else %log stats
modNo= length(comStr);
headLineStr= sprintf('Name\t DateOfBirth\t DataFileName\t ExaminationDate\t Roi_Name\t date_of_ROI_saving\t NumberOfPixels');
for i= 1:modNo
headLineStr= sprintf('%s\t mean(%s)\t std(%s)', headLineStr, comStr{i}, comStr{i});
end
if exist(logFName, 'file') == 2
file_ID= fopen(logFName, 'r+t');
if isempty(file_ID) || (file_ID < 0)
disp(strcat('Could not reopen file ''', logFName, ''''));
return
end
fseek(file_ID, 0, 'bof');
lStr= fgetl(file_ID);
fclose(file_ID);
if ~strcmp(lStr, headLineStr)
butStr= questdlg('The existing log file seems not to be compatible with the current dtdStrucht', ...
'ROI logging', 'continue', 'truncate', 'abort','abort');
if strcmp(butStr, 'continue')
file_ID= fopen(logFName, 'at');
elseif strcmp(butStr, 'truncate')
file_ID= fopen(logFName, 'wt');
fprintf(file_ID, '%s\n', headLineStr);
else
return;
end
else
file_ID= fopen(logFName, 'at');
end
else
file_ID= fopen(logFName, 'wt');
if isempty(file_ID) || (file_ID < 0)
disp(strcat('Could not create file ''', logFName, ''''));
return
end
fprintf(file_ID, '%s\n', headLineStr);
end
if isempty(P.dtdname)
fName= '<unknown>';
else
[p, fName, e]= fileparts(P.dtdname{1});
end
patientStr= dtdstruct_query(dtd, 'patient');
if isempty(patientStr)
patientStr= '<unknown>';
end
maskNames= maskstruct_query(ROI, 'maskNames');
for roiI= 1:numel(maskNames)
disp(['Logging ROI ',maskNames{roiI},' in ', logFName]);
roiIdx= maskstruct_query(ROI, 'getMaskIdx', maskNames{roiI});
fprintf(file_ID, '%s\t %s\t %s\t %s\t %s\t %s\t %d', ...
patientStr, '<unknown>', fName, '<unknown>', maskNames{roiI}, date, length(roiIdx));
for i= 1:modNo
tmpData = dtdstruct_query(dtd, strcat('get', comStr{i}));
if isempty(roiIdx)
fprintf(file_ID, '\t %s\t %s', ...
'<undef>', ...
'<undef>');
elseif length(roiIdx) == 1
fprintf(file_ID, '\t %s\t %s', ...
norm_numbers(tmpData.dataAy(roiIdx), 1, 8, 'E', 3), ...
'<undef>');
else
fprintf(file_ID, '\t %s\t %s', ...
norm_numbers(mean(tmpData.dataAy(roiIdx)), 1, 8, 'E', 3), ...
norm_numbers(std(tmpData.dataAy(roiIdx)), 1, 8, 'E', 3));
end
end
fprintf(file_ID, '\n');
end
fclose(file_ID);
disp(strcat('logROI: Map statistics are saved in ''', logFName, ''''));
end
out.files{1} = P.newfilename; |
github | philippboehmsturm/antx-master | dti_tracking_probabilistic_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_tracking_probabilistic_ui.m | 6,597 | utf_8 | e1f1bf9616e8f4b806d147847bb2af3c | % interface program for batch program
%
% Author: Susanne Schnell and Volkmar Glauche
% PC 25.07.2008
function out = dti_tracking_probabilistic_ui(P)
%load DTD, start and stop masks
dtdStruct = dtdstruct_read(P.filename{1});
switch char(fieldnames(P.seedchoice))
% P.seedchoice always has exactly one field, therefore this
% switch is correct
case 'seedroi'
if isfield(P.seedchoice.seedroi.seedmask,'seedname')
check = P.seedchoice.seedroi.seedmask.seedname;
if iscellstr(check)
check = size(check,1); % not tested!
else
check = 1;
end
else
check = P.seedchoice.seedroi.seedmask.seednumber;
end
[SeedMask errStr] = maskstruct_read(P.seedchoice.seedroi.seedfile{1});
[test, errStr, orInfo]= maskstruct_query(SeedMask, 'testMRDat', dtdStruct);
if test > 0
if ~orInfo % no valid orientation info available in maskStruct
SeedMask= maskstruct_modify(SeedMask, 'mrStructProb', ...
dtdstruct_query(dtdStruct, 'mrStructProb'));
end
elseif test == 0
[SeedMask, errStr, ok]= maskstruct_modify(SeedMask, 'coregister', dtdStruct);
if ~ok
error(['could not open maskStruct:' errStr]);
end
else
error('could not open maskStruct');
end
if numel(check) == 1 && isfinite(check)
if isfield(P.seedchoice.seedroi.seedmask,'seedname')
[SeedMask, errStr]= maskstruct_query(SeedMask, 'getMaskVc', P.seedchoice.seedroi.seedmask.seedname);
elseif isfield(P.seedchoice.seedroi.seedmask,'seednumber')
[SeedMask, errStr]= maskstruct_query(SeedMask, 'getMaskVc', P.seedchoice.seedroi.seedmask.seednumber);
end
if ~isempty(errStr)
error(errStr);
end
if isempty(SeedMask)
error('Selected ROI as seed region is empty');
end
else
% prepare jobs for multiple seeds ROIs
maxMaskNo = maskstruct_query(SeedMask,'maskNo');
if isfield(P.seedchoice.seedroi.seedmask,'seednumber')
if any(~isfinite(P.seedchoice.seedroi.seedmask.seednumber))
newseedmask = 1:maxMaskNo;
else
newseedmask = P.seedchoice.seedroi.seedmask.seednumber;
end
elseif isfielf(P.seedchoice.seedroi.seedmask,'seedname')
%% build up newseedmask?
newseedmask = P.seedchoice.seedroi.seedmask.seedname;
end
% set format of output filenames
[path,nam,ext] = fileparts(P.filename{1});
if isfield(P.newprobfile,'auto')
if length(nam) > 4 && strcmp(nam(end-3:end), '_DTD')
nam = nam(1:end-4);
end
nam = [nam '_MAP'];
P.newprobfile = struct('out',struct('dir',{{path}},'fname',''));
else
[p1,nam,ext] = fileparts(P.newprobfile.out.fname);
end
namfmt = sprintf('%s%%0%dd.mat', nam, floor(log10(maxMaskNo)+1));
% build job list
nj = cell(size(newseedmask));
for k = 1:numel(newseedmask)
nj{k}.dtijobs.tracking.probabilistic = P;
nj{k}.dtijobs.tracking.probabilistic.seedchoice.seedroi.seedmask.seednumber = newseedmask(k);
nj{k}.dtijobs.tracking.probabilistic.newprobfile.out.fname = sprintf(namfmt, newseedmask(k));
end
cj = cfg_util('initjob', nj);
cfg_util('run', cj);
jout = cfg_util('getAllOutputs', cj);
cfg_util('deljob', cj);
% construct cell array of filenames from the cell of
% individual job outputs.
jout = [jout{:}];
out.files = [jout.files]';
% finished after all jobs have completed
return;
end
case 'seedposition'
SeedMask = P.seedchoice.seedposition;
end
if isfield(P.defroi,'defthresh')
[faData errStr] = dtdstruct_query(dtdStruct, 'getFA');
if ~isempty(errStr)
error(errStr);
end
[trdData errStr] = dtdstruct_query(dtdStruct, 'getTrace');
if ~isempty(errStr)
error(errStr);
end
DefArea = (trdData.dataAy < P.defroi.defthresh.deftrace) & (faData.dataAy > P.defroi.defthresh.deffa);
else
DefArea = maskstruct_read(P.defroi.defarea.deffile{1});
[test, errStr, orInfo]= maskstruct_query(DefArea, 'testMRDat', dtdStruct);
if test > 0
if ~orInfo % no valid orientation info available in maskStruct
DefArea= maskstruct_modify(DefArea, 'mrStructProb', ...
dtdstruct_query(dtdStruct, 'mrStructProb'));
end
elseif test == 0
[DefArea, errStr, ok]= maskstruct_modify(DefArea, 'coregister', dtdStruct);
if ~ok
error(['could not open maskStruct:' errStr]);
end
else
error('could not open maskStruct');
end
if isfield(P.defroi.defarea.defmask,'defnumber')
[DefArea errStr] = maskstruct_query(DefArea, 'getMask',P.defroi.defarea.defmask.defnumber);
if ~isempty(errStr)
error(errStr);
end
else
[DefArea errStr] = maskstruct_query(DefArea,'getMask',P.defroi.defarea.defmask.defname);
if ~isempty(errStr)
error(errStr);
end
end
end
if P.probrand == 2
algName = 'ProbRandExt';
[probStruct errStr] = probstruct_op(strcat('apply_', algName),dtdStruct,double(SeedMask),DefArea,P.fibrelength,P.nowalks,P.exponent,P.revisits,400);
else
algName = 'ProbRand';
[probStruct errStr] = probstruct_op(strcat('apply_', algName),dtdStruct,double(SeedMask),DefArea,P.fibrelength,P.nowalks,P.exponent,[],[]);
end
if ~isempty(errStr)
error(errStr);
end
if isempty(probStruct)
error(lasterror);
end
% save file
[path,nam,ext] = fileparts(P.filename{1});
if isfield(P.newprobfile,'auto')
if length(nam) > 4 && strcmp(nam(end-3:end), '_DTD')
nam = nam(1:end-4);
end
out.files{1} = fullfile(path, [nam,'_MAP.mat']);
else
out.files{1} = fullfile(P.newprobfile.out.dir{1}, P.newprobfile.out.fname);
end
mrstruct_write(probStruct,out.files{1});
|
github | philippboehmsturm/antx-master | dti_cfg_realigndef.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_cfg_realigndef.m | 1,799 | utf_8 | 2cb9d8a00ab0f9e3655aa1a80af95057 | % configure file for operations on streamline trackings results
%
% for BATCH EDITOR system (Volkmar Glauche)
%
% File created by Susanne Schnell
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function realigndefi = dti_cfg_realigndef
yname = cfg_files;
yname.tag = 'yname';
yname.name = 'Load forward Deformation';
yname.help = {'......'};
yname.filter = 'nii';
yname.ufilter = '.*';
yname.num = [1 1];
iyname = cfg_files;
iyname.tag = 'iyname';
iyname.name = 'Load inverse Deformation';
iyname.help = {'......'};
iyname.filter = 'nii';
iyname.ufilter = '.*';
iyname.num = [1 1];
matname = cfg_files;
matname.tag = 'matname';
matname.name = 'Matrix for Realignment';
matname.help = {'......'};
matname.filter = 'mat';
matname.ufilter = '.*';
matname.num = [1 1];
% ---------------------------------------------------------------------
% Log ROI
% ---------------------------------------------------------------------
realigndefi = cfg_exbranch;
realigndefi.tag = 'realigndef';
realigndefi.name = 'Realignment of Deformation Field';
realigndefi.help = {'....'};
realigndefi.val = {yname iyname matname};
realigndefi.prog = @(job)dti_realigndef_ui(job);
realigndefi.vout = @vout;
% ---------------------------------------------------------------------
function dep = vout(job)
dep(1) = cfg_dep;
dep(1).sname = 'forward deformation';
dep(1).src_output = substruct('.','finame_y');
dep(1).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'inverse deformation';
dep(2).src_output = substruct('.','finame_iy');
dep(2).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
|
github | philippboehmsturm/antx-master | dti_mapop_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_mapop_ui.m | 2,705 | utf_8 | 5e6c82ecaa61351a9bd9ba57da0bdf0c | % interface program for batch program
%
% Author: Susanne Schnell
% PC 25.07.2008
function out = dti_mapop_ui(cmd, P)
switch cmd,
case 'normalize'
[path1 name1] = fileparts(P.filename1{1});
autofname = sprintf('%s_normMAP.mat',name1);
%normalization
probStruct = probstruct_read(P.filename1{1});
[probStruct,errStr] = probstruct_op('NORM',probStruct);
if ~isempty(errStr)
error(errStr)
end
case 'addition'
[path1 name1] = fileparts(P.filename1{1});
[path2 name2] = fileparts(P.filename2{1});
autofname = sprintf('%s_%s_addMAP.mat',name1, name2);
%addition
probStruct1 = probstruct_read(P.filename1{1});
probStruct2 = probstruct_read(P.filename2{1});
[probStruct,errStr] = probstruct_op('ADD',probStruct1,probStruct2);
if ~isempty(errStr)
error(errStr)
end
case 'multiplication'
[path1 name1] = fileparts(P.filename1{1});
[path2 name2] = fileparts(P.filename2{1});
autofname = sprintf('%s_%s_multMAP.mat',name1, name2);
% multiplication
probStruct1 = probstruct_read(P.filename1{1});
probStruct2 = probstruct_read(P.filename2{1});
[probStruct,errStr] = probstruct_op('MULT',probStruct1,probStruct2);
if ~isempty(errStr)
error(errStr)
end
case 'connmulti'
P1 = struct('filename1',{{}},'filename2',{{}},'newfilename','');
out.files = {};
for cm = 1:size(P.connmtx,1)
P1.filename1 = P.filenames(P.connmtx(cm,1));
P1.filename2 = P.filenames(P.connmtx(cm,2));
out1 = dti_mapop_ui('multiplication',P1);
out.files = [out.files(:); out1.files(:)];
end
return; % do not run the code below, this will be run by each
% instance in the loop above
case 'connmulti_check'
if max(P.connmtx(:)) > numel(P.filenames)
out = 'Connection matrix indices larger than number of supplied files.';
else
out = '';
end
return; % do not run the code below, this does not make sense for a
% check function
end
% newfilename
if strcmp(P.newfilename,'.mat') || isempty(P.newfilename)
path = fileparts(P.filename1{1});
filename = fullfile(path, autofname);
else
[path,name,ext] = fileparts(P.filename1{1});
[newpath,name,ext] = fileparts(P.newfilename);
if isempty(newpath)
filename = fullfile(path,[name ext]);
else
filename = fullfile(newpath,[name ext]);
end
end
%save result
ofilename = mrstruct_write(probStruct,filename);
out.files{1} = ofilename;
|
github | philippboehmsturm/antx-master | dti_tracking_global_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_tracking_global_ui.m | 3,644 | utf_8 | 2bd755f7a4be7fd467a7c2f5f42e3c3f | % interface program for batch program
%
% Author: Marco Reisert
% PC 2010
function out = dti_tracking_global_ui(P)
h = findobj(0,'tag','fiberGT_main');
if ~isempty(h)
delete(h);
end;
if isfield(P,'temp') %% GT accum
fiberGT_tool('loadFTR',P.filenameFTR{1});
ftr = fiberGT_tool('createEFTR',P.numits,P.numsamps,P.temp);
[path,nam,ext] = fileparts(P.filenameFTR{1});
[path_out,nam_out,ext_out] = fileparts(P.fname);
if isempty(path_out),
path_out = path;
end;
ftrname = fullfile(path_out,[nam_out ext_out]);
ftrstruct_write(ftr,ftrname);
out.ftr = {ftrname};
else
if isfield(P.fname,'filenameHARDI'),
fiberGT_tool('loadHARDI',P.fname.filenameHARDI{1});
[path,nam,ext] = fileparts(P.fname.filenameHARDI{1});
if length(nam) > 6 && strcmp(nam(end-5:end), '_HARDI')
nam = nam(1:end-6);
end
elseif isfield(P.fname,'filenameNII'),
fiberGT_tool('loadHARDI',P.fname.filenameNII);
[path,nam,ext] = fileparts(P.fname.filenameNII{1});
else
fiberGT_tool('loadDTD',P.fname.filenameDTD{1},1000);
[path,nam,ext] = fileparts(P.fname.filenameDTD{1});
if length(nam) > 4 && strcmp(nam(end-3:end), '_DTD')
nam = nam(1:end-4);
end
end
h = findobj(0,'tag','fiberGT_main');
if isfield(P.newfile,'auto')
out.ftr = {fullfile(path, [nam,'_FTR.mat'])};
out.fd = {fullfile(path, [nam,'_FTR_fd.mat'])};
out.epd = {fullfile(path, [nam,'_FTR_epd.mat'])};
else
[p n e] = fileparts(P.newfile.out.fname);
out.ftr = {fullfile(P.newfile.out.dir{1}, P.newfile.out.fname)};
out.fd = {fullfile(P.newfile.out.dir{1}, fullfile(p,[n '_fd' e]))};
out.epd = {fullfile(P.newfile.out.dir{1}, fullfile(p,[n '_epd' e]))};
end
fiberGT_tool('setFTRname',out.ftr{1});
if isfield(P.trackingarea,'maskstruct')
name = P.trackingarea.maskstruct.roiid;
fiberGT_tool('loadMaskStruct',P.trackingarea.maskstruct.filenameMASK{1},P.trackingarea.maskstruct.roiid);
elseif isfield(P.trackingarea,'masknii')
name = P.trackingarea.masknii.filenameMASKnii;
threshold = P.trackingarea.masknii.thresholdMask;
fiberGT_tool('loadMask',name{1},threshold);
else
fiberGT_tool('estimateMask');
end;
if P.parameters == 0,
fiberGT_tool('suggestSparse');
else
fiberGT_tool('suggestDense');
end;
if isfield(P.para_weight,'custom_para_weight'),
fiberGT_tool('setparam','weight',P.para_weight.custom_para_weight);
end;
if isfield(P.para_other,'custom_para_other'),
fiberGT_tool('setparam','startTemp',P.para_other.custom_para_other(1));
fiberGT_tool('setparam','stopTemp',P.para_other.custom_para_other(2));
fiberGT_tool('setparam','steps',P.para_other.custom_para_other(3));
fiberGT_tool('setparam','itnum',P.para_other.custom_para_other(4));
fiberGT_tool('setparam','width',P.para_other.custom_para_other(5));
fiberGT_tool('setparam','length',P.para_other.custom_para_other(6));
fiberGT_tool('setparam','chemPot2',P.para_other.custom_para_other(7));
fiberGT_tool('setparam','bfac',P.para_other.custom_para_other(8));
fiberGT_tool('setparam','connlike',P.para_other.custom_para_other(9));
end;
set(findobj(h,'tag','fiberGT_editfiblength'),'string',[num2str(P.minlen) ';' num2str(P.maxlen)]);
fiberGT_tool('start');
fiberGT_tool('saveFD');
end
h = findobj(0,'tag','fiberGT_main');
if ~isempty(h)
delete(h);
end;
|
github | philippboehmsturm/antx-master | dti_cfg_tensor.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_cfg_tensor.m | 3,326 | utf_8 | 0a0214fa5a8384168ed300355339ec67 | % configure file for calculation of tensors
% DTI Configuration file
% BATCH system (Volkmar Glauche)
%
% File created by Susanne Schnell
function tensor = dti_cfg_tensor
% ---------------------------------------------------------------------
% filename Input raw data filename
% ---------------------------------------------------------------------
filename = cfg_files;
filename.tag = 'filename';
filename.name = 'Raw data file name';
filename.help = {'These are the raw images that will be needed for tensor calculation.'
'Here only data of type "_raw.bin" or matlab structure "mrstruct" are possible, meaning before tensor calculation you need to run "Read Data"'};
filename.filter = 'any';
filename.ufilter = '_raw\.bin$';
filename.num = [1 1];
% ---------------------------------------------------------------------
% threshold threshold in B0 images at which tensors are defined as 0
% ---------------------------------------------------------------------
threshold = cfg_entry;
threshold.tag = 'threshold';
threshold.name = 'Threshold';
threshold.val = {40};
threshold.help = {'Enter the threshold in B0 images at which tensors are defined as 0.'...
'default = 40'};
threshold.strtype = 'e';
threshold.num = [1 1];
% ---------------------------------------------------------------------
% singleslice Save single slice as matlab structure?
% ---------------------------------------------------------------------
singleslice = cfg_menu;
singleslice.tag = 'singleslice';
singleslice.name = 'Single Slice Save';
singleslice.val = {0};
singleslice.help = {'Choose if you want to save each single slice as matlab structure (you need space on disk for that!)'
'default: No'};
singleslice.labels = {'No - don''t save each single slice as matlab structure'
'Yes - save each single slice as matlab structure'}';
singleslice.values = {0 1};
% ---------------------------------------------------------------------
% raw HARDI Save as matlab structure?
% ---------------------------------------------------------------------
hardisave = cfg_menu;
hardisave.tag = 'hardi';
hardisave.name = 'HARDI Save';
hardisave.val = {0};
hardisave.help = {'Choose if you want to save raw HARDI data as matlab structure (you need space on disk and memory for that!)'
'default: No'};
hardisave.labels = {'No - don''t save HARDI as matlab structure'
'Yes - save HARDI as matlab structure'}';
hardisave.values = {0 1};
% ---------------------------------------------------------------------
% tensor
% ---------------------------------------------------------------------
tensor = cfg_exbranch;
tensor.tag = 'tensor';
tensor.name = 'Tensor Calculation';
tensor.val = {filename singleslice hardisave threshold};
tensor.help = {'Calculates the DTI tensors.'};
tensor.prog = @dti_tensor_ui;
tensor.vout = @vout;
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'DTD data file';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}}); |
github | philippboehmsturm/antx-master | dti_readdata_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_readdata_ui.m | 4,631 | utf_8 | 2e017b9050bcc09910cd85a34b4f0ca2 | % interface program for batch program
% dti_read_data_ui: user interface for reading the raw data (main: dti_cfg_read.m)
%
% Author: Susanne Schnell
% PC 10.04.2008
function out = dti_readdata_ui(cmd,P)
switch cmd
case 'binary'
[path,nam,ext] = fileparts(P.binary{1});
if strcmp(ext,'.bin')
% open data file and check if all necessary diffusion
% information provided
[res, err] = dw_data_admin('open',P.binary{1}(1:end-8));
if isempty(res)
error(err)
end
if res == 0
error(err)
end
DE_scheme = dw_data_admin('get_diffDirs');
bvalue = dw_data_admin('get_bVal');
nob0s = dw_data_admin('get_user');
dw_data_admin('close');
if ~isempty(nob0s)
nob0s = nob0s.nob0s;
end
if ~isempty(DE_scheme) && ~isempty(bvalue) && ~isempty(nob0s)
out.files{1} = fullfile(path, [nam,ext]);
else
out.files = {};
error('The necessary diffusion information is missing. This data cannot processed using the batch modus. Please use the DTI&FiberTools GUI instead.');
end
else
out.files = {};
error('This input data file type is not supported yet.');
end
case 'mrstruct'
[path,nam,ext] = fileparts(P.filename{1});
if strcmp(ext,'.mat')
mr = mrstruct_read(P.filename{1});
mr.user.nob0s = P.nob0s;
mr.user.bvalue = P.bvalue;
mr.user.DEscheme = P.descheme;
mrstruct_write(mr,P.filename{1});
out.files{1} = P.filename{1};
else
out.files = {};
error('This input data file type is not a matlab variable and is not supported yet.');
end
case 'append'
[path,nam,ext] = fileparts(P.filename2{1});
if strcmp(ext,'.mat')
mr = mrstruct_read(P.filename2{1});
dtd = dtdstruct_read(P.dtdname{1});
[dtd, err] = dtdstruct_modify(dtd,'addStruct',mr,P.volname);
if ~isempty(err)
error(err);
out.files = {};
else
dtdstruct_write(dtd,P.dtdname{1});
out.files{1} = P.dtdname{1};
end
else
out.files = {};
error('This input data file type is not a matlab variable and is not supported yet.');
end
case 'dicom'
numberofdirs = numel(P.dicom);
for m = 1 : numberofdirs
[path,nam,ext] = fileparts(P.dicom{m});
list = dir(fullfile(path,'*.dcm'));
if m == 1
[out.files{1}, status, errorstring] = read_dti_dicom(path, list,0,[],1);
else
[out.files{1}, status, errorstring] = read_dti_dicom(path, list,1,out.files{1},m);
end
if ~isempty(errorstring)
error(errorstring);
end
if ~isequal(status,[1 1 1])
fprintf('The Dicom data does not privide all necessary information for the calculation of the tensors.\nThe reason for this might be that you don not work with Siemens Dicom.\n Please use the GUI instead (dti_tool) of the Batch Editor (see manual).\nAnother option would be that you read in your data into an mrstruct (see manual) and set up the batch using this as raw data.');
return
end
end
case 'bruker'
[out.files{1}, status, errorstring] = bruker_read_DTI_data('Filepath',P.bruker{1});
if ~isempty(errorstring)
error(errorstring);
end
if ~isequal(status,[1 1 1])
error('The Bruker data does not privide all necessary information for the calculation of the tensors.');
end
case 'computeDTDfromHARDI'
hr = mrstruct_read(P.filename{1});
if isfield(P.newfile,'auto')
[p n e] = fileparts(P.filename{1});
if not(isempty(strfind(n,'HARDI'))),
n = strrep(n,'HARDI','DTD');
else
n = [n '_DTD'];
end
outname = fullfile(p,[n e]);
else
outname = fullfile(P.newfile.out.dir{1}, P.newfile.out.fnameDTD);
end;
out.files{1} = outname;
dtd = convertHARDI2DTD(hr,P.threshold);
[res, errStr] = dtdstruct_write(dtd,outname);
if ~isempty(errStr)
error(errStr)
end
return;
end
|
github | philippboehmsturm/antx-master | dti_cfg_ftrop.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_cfg_ftrop.m | 19,167 | utf_8 | ca9466fe134d2495d20d21bc5bab6d28 | % configure file for operations on streamline trackings results
%
% for BATCH EDITOR system (Volkmar Glauche)
%
% File created by Susanne Schnell
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ftrop = dti_cfg_ftrop
% ---------------------------------------------------------------------
% filename1 name of ftrstruct
% ---------------------------------------------------------------------
filename1 = cfg_files;
filename1.tag = 'filename1';
filename1.name = 'Select the ftrstruct';
filename1.help = {'Select the ftrstruct (usually something like blah_FTR.mat'};
filename1.filter = 'mat';
filename1.ufilter = '.*';
filename1.num = [1 1];
% ---------------------------------------------------------------------
% filename2 name of dtdstruct
% ---------------------------------------------------------------------
filename2 = cfg_files;
filename2.tag = 'filename2';
filename2.name = 'Select the dtdstruct';
filename2.help = {'Select the dtdstruct (usually something like "blah_DTD.mat"'};
filename2.filter = '_DTD.mat';
filename2.ufilter = '.*';
filename2.num = [1 1];
% ---------------------------------------------------------------------
% filename2 name of dtdstruct
% ---------------------------------------------------------------------
filename3 = cfg_files;
filename3.tag = 'filename3';
filename3.name = 'Select reference frame';
filename3.help = {'A mrstruct, or a dtdstruct, or a nifti determining the volume of interest.'};
filename3.filter = '.mat|.nii';
filename3.ufilter = '.*';
filename3.num = [1 1];
% ---------------------------------------------------------------------
% filename2 name of dtdstruct
% ---------------------------------------------------------------------
filename4 = cfg_files;
filename4.tag = 'filename4';
filename4.name = 'Select Contrasts';
filename4.help = {'A mrstruct, or a dtdstruct, or a nifti used for tractometry'};
filename4.filter = '.mat|.nii';
filename4.ufilter = '.*';
filename4.num = [1 inf];
% ---------------------------------------------------------------------
% filename2 name of dtdstruct
% ---------------------------------------------------------------------
filename5 = cfg_files;
filename5.tag = 'filename5';
filename5.name = 'Select ROIs';
filename5.help = {'A maskstruct, mrsrtuct or a nifti containg ROIs'};
filename5.filter = '.mat|.nii';
filename5.ufilter = '.*';
filename5.num = [1 inf];
% ---------------------------------------------------------------------
% filedef name of deformation field
% ---------------------------------------------------------------------
filedef = cfg_files;
filedef.tag = 'filedef';
filedef.name = 'Select the deformation field';
filedef.help = {'Select the deformation field (usually created by "New Segment", something like "yblah.nii"'};
filedef.filter = '.nii';
filedef.ufilter = '.*';
filedef.num = [1 1];
% ---------------------------------------------------------------------
% filedefi name of inverse deformation field
% ---------------------------------------------------------------------
filedefi = cfg_files;
filedefi.tag = 'filedefi';
filedefi.name = 'Select the inverse deformation field';
filedefi.help = {'Select the inverse deformation field (usually created by "New Segment", something like "iyblah.nii"'};
filedefi.filter = '.nii';
filedefi.ufilter = '.*';
filedefi.num = [1 1];
% ---------------------------------------------------------------------
% maskname, select the correct mask by name
% ---------------------------------------------------------------------
maskname = cfg_entry;
maskname.tag = 'maskname';
maskname.name = 'Type in the name of the mask';
maskname.help = {'Type in the name of the mask with which the fibers will be selected.'};
maskname.strtype = 's';
maskname.num = [1 Inf];
% ---------------------------------------------------------------------
% masknumber, select the correct mask by a number
% ---------------------------------------------------------------------
masknumber = cfg_entry;
masknumber.tag = 'masknumber';
masknumber.name = 'Mask Number';
masknumber.help = {'Select the mask by a number. You need to remember the mask position by yourself.'};
masknumber.strtype = 'e';
masknumber.num = [1 1];
% ---------------------------------------------------------------------
% mask, select the correct mask by a number
% ---------------------------------------------------------------------
mask = cfg_choice;
mask.tag = 'mask';
mask.name = 'Mask Number or Mask Name';
mask.help = {'Select the mask by a number or name. Please take care to spell the name correctly.'...
'In case of mask number, you need to remember the mask position by yourself.'};
mask.values = {masknumber maskname};
% ---------------------------------------------------------------------
% roiname
% ---------------------------------------------------------------------
roiname = cfg_files;
roiname.tag = 'roiname';
roiname.name = 'Load ROI';
roiname.help = {'Select a maskstruct (ROI).'};
roiname.filter = 'mat';
roiname.ufilter = '.*';
roiname.num = [1 1];
% ---------------------------------------------------------------------
% roidef
% ---------------------------------------------------------------------
roidef = cfg_branch;
roidef.tag = 'roidef';
roidef.name = 'Definition of ROI';
roidef.help = {'Choose the maskstruct-file (ROI) and select the mask.'};
roidef.val = {roiname mask};
% ---------------------------------------------------------------------
% newfilename name of resulting file
% ---------------------------------------------------------------------
newfilename = cfg_entry;
newfilename.tag = 'newfilename';
newfilename.name = 'New File Name';
newfilename.val = {'.mat'};
newfilename.help = {'Type in the name of the new file, if you leave this empty a default file name is generated with the endings "_selFTR.mat", "_defFTR.mat", "_addMAP.mat" or "_multMAP.mat"'};
newfilename.strtype = 's';
newfilename.num = [1 Inf];
% ---------------------------------------------------------------------
% newfilename name of resulting file
% ---------------------------------------------------------------------
newfilename2 = cfg_entry;
newfilename2.tag = 'newfilename2';
newfilename2.name = 'Output File Name';
newfilename2.help = {'Type in the name of the file, where statistics is saved'};
newfilename2.strtype = 's';
newfilename2.num = [1 Inf];
% ---------------------------------------------------------------------
% fibername name of new fiber subset
% ---------------------------------------------------------------------
fibername = cfg_entry;
fibername.tag = 'fibername';
fibername.name = 'Name of fiber subset';
fibername.val = {'fiber_001'};
fibername.help = {'Type in the name of the new fiber subset'};
fibername.strtype = 's';
fibername.num = [1 Inf];
% ---------------------------------------------------------------------
% thresh, select the threshhold for creating a mask
% ---------------------------------------------------------------------
thresh = cfg_entry;
thresh.tag = 'thresh';
thresh.name = 'Threshold for creating a mask';
thresh.val = {0};
thresh.help = {'Threshold for creating a mask of voxels visited by at least this number of fibretracks. Default = 0'};
thresh.strtype = 'e';
thresh.num = [1 1];
% ---------------------------------------------------------------------
% fibernumber, select the correct fibersubset by a number
% ---------------------------------------------------------------------
fibernumber = cfg_entry;
fibernumber.tag = 'fibernumber';
fibernumber.name = 'Fibersubset Number';
fibernumber.val = {1};
fibernumber.help = {'Select the fiber subset by a number. You need to remember the position by yourself.'};
fibernumber.strtype = 'e';
fibernumber.num = [1 1];
% ---------------------------------------------------------------------
% oversampling
% ---------------------------------------------------------------------
osamp = cfg_entry;
osamp.tag = 'oversampling';
osamp.name = 'Oversampling Factor';
osamp.val = {1};
osamp.help = {'Select the oversampling factor. The voxelsize of the reference frame are divied by this factor.'};
osamp.strtype = 'e';
osamp.num = [1 1];
% ---------------------------------------------------------------------
% fibersubset, choose whether to select the fiber subset number or name
% ---------------------------------------------------------------------
fibersubset = cfg_choice;
fibersubset.tag = 'fibersubset';
fibersubset.name = 'Fibersubset Number or Name';
fibersubset.help = {'Select the fiber subset by a number or by name. You need to remember the correct spelling or the position by yourself.'};
fibersubset.values = {fibernumber fibername};
% ---------------------------------------------------------------------
% visitMask input only the ftrstruct
% ---------------------------------------------------------------------
endpointMask = cfg_exbranch;
endpointMask.tag = 'endpointMask';
endpointMask.name = 'Create end point mask';
endpointMask.help = {'Determines the endpoints of the fibertracks in the specified subset and creates a mask of it'
'Select the ftrstruct and the fiber subset.'};
endpointMask.val = {filename1 fibersubset filename2 newfilename};
endpointMask.prog = @(job)dti_ftrop_ui('endpointMask',job);
endpointMask.vout = @vout;
% ---------------------------------------------------------------------
% visitMask input the ftrstruct and a threshold
% ---------------------------------------------------------------------
visitMask = cfg_exbranch;
visitMask.tag = 'visitMask';
visitMask.name = 'Create a Visit Mask';
visitMask.help = {'Creates a mask of voxels visited by the fibertracks of the specified subset.'
'A single fibertrack visiting a voxel twice, will increment the voxel also by two. Select the ftrstruct and the fiber subset.'
'The resulting mask will be saved as maskstruct and can be loaded in "fiberviewer_tool" instead as ROI'
'by using the -> open -> ROI dialogue'};
visitMask.val = {filename1 fibersubset thresh filename2 newfilename};
visitMask.prog = @(job)dti_ftrop_ui('visitMask',job);
visitMask.vout = @vout;
% ---------------------------------------------------------------------
% visitMap input only the ftrstruct
% ---------------------------------------------------------------------
visitMap = cfg_exbranch;
visitMap.tag = 'visitMap';
visitMap.name = 'Create Visit Map';
visitMapext.help = {'Determines how often a voxel was visited by the fibertracks containing in the specified subset.'
'A single fibertrack visiting a voxel twice, will increment the voxel also by two. Select the ftrstruct and the fiber subset.'
'The resulting map will be saved as mrstruct and can be loaded in "fiberviewer_tool" instead of dtdstruct or in addition to'
'dtdstruct buy using the -> open -> append volume dialogue'};
visitMap.val = {filename1 fibersubset filename2 newfilename};
visitMap.prog = @(job)dti_ftrop_ui('visitMap',job);
visitMap.vout = @vout;
% ---------------------------------------------------------------------
% visitMap input only the ftrstruct
% ---------------------------------------------------------------------
visitMapext = cfg_exbranch;
visitMapext.tag = 'visitMapext';
visitMapext.name = 'Create Visit Map (extended)';
visitMap.help = {'Determines how often a voxel was visited by the fibertracks containing in the specified subset.'
'The tracts are rendered into the volume by trilinear interpolation. Three files are created: a color-coded tract density, and'
'a ordinaray gray-scale density, and endpoint densitity. Files may saved as mrstruct or nifits (extension of destination file determines type)'
'The reference image (nifti or mrstruct) determines volume of interest and voxelsizes.'};
visitMapext.val = {filename1 fibersubset filename3 osamp newfilename};
visitMapext.prog = @(job)dti_ftrop_ui('visitMapext',job);
visitMapext.vout = @voutFDext;
% ---------------------------------------------------------------------
% eliminatebyROI input of ftrstruct and ROI
% ---------------------------------------------------------------------
eliminatebyROI = cfg_exbranch;
eliminatebyROI.tag = 'eliminatebyROI';
eliminatebyROI.name = 'Eliminate fibers by ROI';
eliminatebyROI.help = {'Select the two maps you want to multiply. Multiplaction results depend on the probabilistic tracking method chosen. If the extended version was used you will have three maps: the merging fibre map, the connecting fibre map and all-in-one map.'};
eliminatebyROI.val = {filename1 fibersubset roidef fibername newfilename};
eliminatebyROI.prog = @(job)dti_ftrop_ui('eliminatebyROI',job);
eliminatebyROI.vout = @vout;
seltype = cfg_menu;
seltype.tag = 'seltype';
seltype.name = 'Selection Method';
seltype.help = {'Choose the way the fiber is defined to belong to a certain ROI.'};
seltype.labels = {
'visiting the area'
'endpoint in Area'
}';
seltype.values = {0 1};
seltype.val = {0};
% ---------------------------------------------------------------------
% selectbyROI input of one ftrstruct, a maskstruct and the new filename
% ---------------------------------------------------------------------
selectbyROI = cfg_exbranch;
selectbyROI.tag = 'selectbyROI';
selectbyROI.name = 'Select Fiber subsets by ROIs';
selectbyROI.help = {'Select fiber subsets with help of ROIs (maskstructs).'};
selectbyROI.val = {filename1 fibersubset roidef seltype fibername newfilename};
selectbyROI.prog = @(job)dti_ftrop_ui('selectbyROI',job);
selectbyROI.vout = @vout;
% ---------------------------------------------------------------------
% fuzzy or not fuzzy ?
% ---------------------------------------------------------------------
threshfuz = cfg_entry;
threshfuz.tag = 'threshfuz';
threshfuz.name = 'Threshold for selection';
threshfuz.val = {0.1};
threshfuz.help = {'threshold'};
threshfuz.strtype = 'e';
threshfuz.num = [1 1];
sigmafuz = cfg_entry;
sigmafuz.tag = 'sigmafuz';
sigmafuz.name = 'Sigma of Gaussian Smooth';
sigmafuz.val = {1};
sigmafuz.help = {'threshold'};
sigmafuz.strtype = 'e';
sigmafuz.num = [1 1];
fuzzy = cfg_branch;
fuzzy.tag = 'fuzzy';
fuzzy.name = 'Select parameters for fuzzy selection';
fuzzy.val = {threshfuz sigmafuz};
fuzzy.help = {'Specify a output filename.'};
nofuzzy = cfg_const;
nofuzzy.tag = 'nofuzzy';
nofuzzy.name = 'No fuzzy selection';
nofuzzy.val = {true};
nofuzzy.help = {'Select streamlines with hard ROI boundaries.'};
fuzzysel = cfg_choice;
fuzzysel.tag = 'fuzzysel';
fuzzysel.name = 'Use fuzzy Selection';
fuzzysel.values = {fuzzy nofuzzy};
fuzzysel.help = {'Use fuzzy selection to get more stabe fiber counts'};
%%%%%%%%%% contrast for tractometry
nocontrast = cfg_const;
nocontrast.tag = 'nocontrast';
nocontrast.name = 'No Contrast';
nocontrast.val = {true};
nocontrast.help = {'No contrast, just compute fiber counts.'};
contrastsel = cfg_choice;
contrastsel.tag = 'contrastsel';
contrastsel.name = 'Contrast for Tractometry';
contrastsel.values = {filename4 nocontrast};
contrastsel.help = {'Select a contrast along which statistics is done.'};
% ---------------------------------------------------------------------
% roinumbers
% ---------------------------------------------------------------------
roinumber = cfg_entry;
roinumber.tag = 'roinumber';
roinumber.name = 'ROI indices';
roinumber.help = {'Select the ROI indices (mask numbers) used for fiber selection (empty - all ROIs/masks are used).'};
roinumber.strtype = 'e';
roinumber.num = [0 inf];
roinumber.val = {[]};
% ---------------------------------------------------------------------
% tractStats
% ---------------------------------------------------------------------
tractStat = cfg_exbranch;
tractStat.tag = 'tractStats';
tractStat.name = 'Tract Statistics (Tractometry)';
tractStat.help = {'help yourself'};
tractStat.val = {filename1 contrastsel newfilename2};
tractStat.prog = @(job)dti_ftrop_ui('tractStats',job);
tractStat.vout = @vout;
% ---------------------------------------------------------------------
% tractStats
% ---------------------------------------------------------------------
tractStatROI = cfg_exbranch;
tractStatROI.tag = 'tractStatsROI';
tractStatROI.name = 'Tract Statistics with Fiber Selection';
tractStatROI.help = {'help yourself'};
tractStatROI.val = {filename1 contrastsel filename5 roinumber seltype fuzzysel newfilename2};
tractStatROI.prog = @(job)dti_ftrop_ui('tractStatsROI',job);
tractStatROI.vout = @vout;
% ---------------------------------------------------------------------
% deformFTR
% ---------------------------------------------------------------------
deformFTR = cfg_exbranch;
deformFTR.tag = 'deformFTR';
deformFTR.name = 'Deformation of Fibers';
deformFTR.help = {'Non Rigid deformation of fibers.'};
deformFTR.val = {filename1 filedef filedefi newfilename};
deformFTR.prog = @(job)dti_ftrop_ui('deformFTR',job);
deformFTR.vout = @vout;
% ---------------------------------------------------------------------
% mapop
% ---------------------------------------------------------------------
ftrop = cfg_choice;
ftrop.tag = 'ftrop';
ftrop.name = 'Operations with Streamline Tracts';
ftrop.help = {'Operations with streamline tracts (Mori Tracts).'};
ftrop.values = {selectbyROI eliminatebyROI visitMap visitMapext visitMask endpointMask tractStat tractStatROI deformFTR};
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'FTRstruct After Operation';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
function dep = voutFDext(job)
dep(1) = cfg_dep;
dep(1).sname = 'FD (rgb) mrstruct/nifti';
dep(1).src_output = substruct('.','fdrgb');
dep(1).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'FD mrstruct/nifti';
dep(2).src_output = substruct('.','fd');
dep(2).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
dep(3) = cfg_dep;
dep(3).sname = 'EP mrstruct/nifti';
dep(3).src_output = substruct('.','ep');
dep(3).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
|
github | philippboehmsturm/antx-master | dti_roiop_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_roiop_ui.m | 3,132 | utf_8 | bca6157b9659f55f4f4b3afc5971c41d | % interface program for batch program
% Operations with streamline tracts (Mori Tracts).
% Author: Susanne Schnell
% Linux 02.03.2010
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = dti_roiop_ui(cmd, P)
switch cmd
case 'Invert'
autofname = '_invers.mat';
%load ROI
ROI = maskstruct_read(P.roiname{1});
ROInames = maskstruct_query(ROI,'maskNames');
% INVERT
[ROI,errStr] = maskstruct_modify(ROI, 'inv',ROInames{P.mask1},P.maskname);
if ~isempty(errStr)
error(errStr)
end
case 'ANDop'
autofname = '_ANDop.mat';
%load ROI
ROI = maskstruct_read(P.roiname{1});
ROInames = maskstruct_query(ROI,'maskNames');
% AND
[ROI,errStr] = maskstruct_modify(ROI, 'AND',ROInames{P.mask1},ROInames{P.mask2,:},P.maskname);
if ~isempty(errStr)
error(errStr)
end
case 'ORop'
autofname = '_ORop.mat';
ROI = maskstruct_read(P.roiname{1});
ROInames = maskstruct_query(ROI,'maskNames');
% OR
[ROI,errStr] = maskstruct_modify(ROI, 'OR',ROInames{P.mask},ROInames{P.mask2},P.maskname);
if ~isempty(errStr)
error(errStr)
end
case 'XORop'
autofname = '_XORop.mat';
ROI = maskstruct_read(P.roiname{1});
ROInames = maskstruct_query(ROI,'maskNames');
% XOR
[ROI,errStr] = maskstruct_modify(ROI, 'OR',ROInames{P.mask1},ROInames{P.mask2},P.maskname);
if ~isempty(errStr)
error(errStr)
end
case 'Erosion'
autofname = '_erosed.mat';
% load data
ROI = maskstruct_read(P.roiname{1});
ROInames = maskstruct_query(ROI,'maskNames');
% EROSION
[ROI,errStr] = maskstruct_modify(ROI, 'erosion',ROInames{P.mask1},P.maskname,'XY',P.voxels);
if ~isempty(errStr)
error(errStr)
end
case 'Dilation'
autofname = '_dilated.mat';
% load data
ROI = maskstruct_read(P.roiname{1});
ROInames = maskstruct_query(ROI,'maskNames');
% DILATION
[ROI,errStr] = maskstruct_modify(ROI, 'dilatation',ROInames{P.mask1},P.maskname,'XY',P.voxels);
if ~isempty(errStr)
error(errStr)
end
case 'GrowSphere'
autofname = '_sphere.mat';
% load data
ROI = maskstruct_read(P.roiname{1});
% GROW SPHERE
[ROI,errStr] = maskstruct_modify(ROI, 'growSpheric',P.coords,P.sizeSphere{1},P.maskname);
if ~isempty(errStr)
error(errStr)
end
end
% newfilename
if strcmp(P.newfilename,'.mat') || isempty(P.newfilename)
[path,name] = fileparts(P.roiname{1});
filename = fullfile(path, [name, autofname]);
else
[path,name,ext] = fileparts(P.roiname{1});
[newpath,name,ext] = fileparts(P.newfilename);
if isempty(newpath)
filename = fullfile(path,[name ext]);
else
filename = fullfile(newpath,[name ext]);
end
end
%save result
maskstruct_write(ROI,filename);
out.files{1} = filename;
|
github | philippboehmsturm/antx-master | dti_realigndef_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_realigndef_ui.m | 1,717 | utf_8 | 5ae5f198e1cac875622a750f19dfa213 |
function out = dti_realigndef_ui(P)
mat = load(P.matname{1},'M');
fi = realign_def(P.yname{1},P.iyname{1},inv(mat.M));
out.finame_y = fi.y;
out.finame_iy = fi.iy;
function out = realign_def(yfi,iyfi,mat)
[yDef,ymat] = get_def(yfi);
[iyDef,iymat] = get_def(iyfi);
% realign y field
ymat = mat*ymat;
% realign iy field
niyDef{1} = single(iyDef{1}*mat(1,1) + iyDef{2}*mat(1,2) + iyDef{3}*mat(1,3) + mat(1,4));
niyDef{2} = single(iyDef{1}*mat(2,1) + iyDef{2}*mat(2,2) + iyDef{3}*mat(2,3) + mat(2,4));
niyDef{3} = single(iyDef{1}*mat(3,1) + iyDef{2}*mat(3,2) + iyDef{3}*mat(3,3) + mat(3,4));
iyDef = niyDef;
% save y field
[p n e] = fileparts(yfi);
out.y = save_def(yDef,ymat,[ n],p);
% save iy field
[p n e] = fileparts(iyfi);
out.iy = save_def(iyDef,iymat,[ n],p);
function [Def,mat] = get_def(file)
% Load a deformation field saved as an image
P = [repmat(file,3,1), [',1,1';',1,2';',1,3']];
V = spm_vol(P);
Def = cell(3,1);
Def{1} = spm_load_float(V(1));
Def{2} = spm_load_float(V(2));
Def{3} = spm_load_float(V(3));
mat = V(1).mat;
function fname = save_def(Def,mat,ofname,odir)
% Save a deformation field as an image
if isempty(ofname), fname = {}; return; end;
fname = {fullfile(odir,[ofname '.nii'])};
dim = [size(Def{1},1) size(Def{1},2) size(Def{1},3) 1 3];
dtype = 'FLOAT32';
off = 0;
scale = 1;
inter = 0;
dat = file_array(fname{1},dim,dtype,off,scale,inter);
N = nifti;
N.dat = dat;
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Aligned';
N.mat0_intent = 'Aligned';
N.intent.code = 'VECTOR';
N.intent.name = 'Mapping';
N.descrip = 'Deformation field';
create(N);
N.dat(:,:,:,1,1) = Def{1};
N.dat(:,:,:,1,2) = Def{2};
N.dat(:,:,:,1,3) = Def{3};
return; |
github | philippboehmsturm/antx-master | dti_fodop_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_fodop_ui.m | 24,151 | utf_8 | 7931aca2f4165bce4fa97cf75de79bfa | % interface program for batch program
% Operations with FODs
% Author: Marco Reisert
% PC 2012
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function out = dti_ftrop_ui(cmd, P)
switch cmd,
case 'PItrails'
picon = load(P.filenamePIcon{1});
[pa fi] = fileparts(P.filenamePIcon{1});
fi = fi(1:end-3);
roip = P.roipairs;
template = picon.maps.mrstructProp;
template.dim4 = 'unused';
template.user = [];
maps = picon.maps;
Im = maps.InterpolationMat;
crop = maps.cropRegion;
sz = [crop(2)-crop(1)+1 crop(4)-crop(3)+1 crop(6)-crop(5)+1];
sz(4) = size(maps.mrstructProp.user.bDir,2)*2;
for k = 1:size(roip,2),
t1 = reshape(Im*double(maps.data(:,roip(1,k))),sz);
t2 = reshape(Im*double(maps.data(:,roip(2,k))),sz);
map = sum(t1.*circshift(t2,[1 1 1 sz(4)/2]),4);
template.memoryType = 'volume';
template.dataAy = zeros(maps.size);
template.dataAy(crop(1):crop(2),crop(3):crop(4),crop(5):crop(6)) = map;
fname{k} = fullfile(pa,[fi sprintf('roi%i-%i.nii',roip(1,k),roip(2,k))]);
mrstruct_to_nifti(template, fname{k}, 'float32');
end;
out.mapnames = fname;
case 'PItrack'
fodname = P.filename2{1};
roiname = P.filenameROIs{1};
wmname = P.roiname{1};
thres = P.thresh;
roisubset = P.roisubset;
fod = mrstruct_read(fodname);
resliceFlags.mask= 0;
resliceFlags.mean= 0;
resliceFlags.interp= 0;
resliceFlags.which=1;
roi = loadsegmentation(roiname,1,fod,resliceFlags);
WM = loadsegmentation(wmname,1,fod,resliceFlags);
thres_toMax = P.thres_toMax;
P.saveftr = not(isfield(P.streamftr,'noftr'));
P.saveftrpairs = not(isfield(P.streamftrpaired,'noftr'));
[fods mask crop] = prepFODdata(fod.dataAy,fod.user.bDir,WM.dataAy>thres,P.sh,thres_toMax,P.normtype);
fod = rmfield(fod,'dataAy'); % save memory
rois = roi.dataAy(crop(1):crop(2),crop(3):crop(4),crop(5):crop(6));
result = PItracking(fods,mask,[fod.user.bDir -fod.user.bDir],rois,P,roisubset);
result.maps.mrstructProp = fod;
result.maps.cropRegion = crop;
result.maps.size = size(roi.dataAy);
result.roifilename = roiname;
result.roiidx = roisubset;
if P.savePImaps == 0,
result = rmfield(result,'maps');
end;
[p n e] = fileparts(P.filename2{1});
if strcmpi('fod',n(end-2:end)),
n = n(1:end-3);
end;
if P.saveftr
%%
ftr = ftrstruct_init;
ftr.hMatrix = fod.edges;
ftr.vox = fod.vox;
ftr.curveSegCell = cat(2,result.fibs{:})';
ftr.curveD = cellfun(@(x) [x(:,4)'; log(eps+abs(x(:,4)'))], ftr.curveSegCell,'uniformoutput',false);
ftr.curveSegCell = cellfun(@(x) x(:,[2 1 3]) + repmat([crop(1) crop(3) crop(5)],size(x,1),1), ftr.curveSegCell,'uniformoutput',false);
runf = 1;
for k = 1:length(result.fibs),
ftr.fiber{k}.name = ['ROI_' num2str(k)];
ftr.fiber{k}.curveID = runf:(runf+length(result.fibs{k})-1);
ftr.fiber{k}.roiName = ['ROI_' num2str(k)];
ftr.fiber{k}.user = [];
runf = runf + length(result.fibs{k});
end;
ftr.fiber = ftr.fiber';
ftr.connectCell = arrayfun(@(x)x ,(1:length(ftr.curveSegCell))','uniformoutput',false);
outnameftr = buildoutname(P.streamftr.outftr.newfilenamemat,p,n,'FTR','.mat');
save(outnameftr,'-struct','ftr');
end;
if P.saveftrpairs
%%
ftr = ftrstruct_init;
ftr.hMatrix = fod.edges;
ftr.vox = fod.vox;
ftr.curveSegCell = cat(2,result.fibsPaired{:})';
ftr.curveD = cellfun(@(x) [x(:,4)'; log(eps+abs(x(:,4)'))], ftr.curveSegCell,'uniformoutput',false);
ftr.curveSegCell = cellfun(@(x) x(:,[2 1 3]) + repmat([crop(1) crop(3) crop(5)]-2,size(x,1),1), ftr.curveSegCell,'uniformoutput',false);
runf = 1;
cnt = 1;
for k = 1:length(result.fibsPaired),
for j = 1:length(result.fibsPaired),
if k ~= j,
fibp = result.fibsPaired{j,k};
if not(isempty(fibp)),
ftr.fiber{cnt}.name = ['ROI_' num2str(k) '_' num2str(j)];
ftr.fiber{cnt}.curveID = runf:(runf+length(fibp)-1);
ftr.fiber{cnt}.roiName = ['ROI_' num2str(k) '_' num2str(j)];
ftr.fiber{cnt}.user = [];
runf = runf + length(fibp);
cnt = cnt + 1;
end;
end;
end;
end;
ftr.fiber = ftr.fiber';
ftr.connectCell = arrayfun(@(x)x ,(1:length(ftr.curveSegCell))','uniformoutput',false);
outnameftrpair = buildoutname(P.streamftr.outftr.newfilenamemat,p,n,'paired_FTR','.mat');
save(outnameftrpair,'-struct','ftr');
end;
savename = buildoutname(P.newfilenamemat,p,n,'PICON','.mat');
save(savename,'-struct','result');
out.PIinfo = {savename};
if P.saveftr,
out.PIinfo = [out.PIinfo {outnameftr}];
end;
if P.saveftrpairs,
out.PIinfo = [out.PIinfo {outnameftrpair}];
end;
case 'PXtrack'
fodname = P.filename2{1};
roiname = P.filenameROIs{1};
roisubset = P.roisubset;
fod = mrstruct_read(fodname);
if strcmp(P.newfilenamemat,'.mat')
[p n e] = fileparts(P.filename2{1});
n = n(1:end-4);
savename = fullfile(p,[n '_PXCON.mat']);
else
savename = P.newfilenamemat;
end;
resliceFlags.mask= 0;
resliceFlags.mean= 0;
resliceFlags.interp= 0;
resliceFlags.which=1;
roi = loadsegmentation(roiname,1,fod,resliceFlags);
usermask = sum(fod.dataAy,4)>0;
P.rev = false;
[cm_pt ROIsize Nfac] = probtrax_roi(repmat(fod.dataAy,[1 1 1 2]),[fod.user.bDir -fod.user.bDir]',usermask,roi.dataAy,P,roisubset);
result.roiidx = roisubset;
result.Cmat = cm_pt;
result.ROIsize = ROIsize;
result.Nfac = Nfac;
result.params = P;
save(savename,'-struct','result');
out.PXinfo = {savename};
case 'doL1CSD'
hrname = P.filename1{1};
wmname = P.roidef.roiname{1};
outname = P.newfilename;
params.csdL1.maxit = P.maxit;
params.csdL1.lambda = P.lambdaL1;
params.csdL1.powsm = P.powsm;
params.csdL1.numdir = P.numdir;
params.csdL1.D = [P.Dax P.Drad];
[mrfod] = computeCSDL1(hrname,wmname,params);
[p n e] = fileparts(hrname);
if strcmpi('hardi',n(end-4:end)),
n = n(1:end-5);
end;
outname = buildoutname(outname,p,n,'FOD','.mat');
mrstruct_write(mrfod,outname);
out.FOD = {outname};
case 'doCSDTournier'
hrname = P.filename1{1};
outname = P.newfilename;
shcut = P.shcutoff;
numdirs = P.numdirsout;
Dax = P.Dax;
wmname = P.roidef.roiname{1};
thres = P.roidef.thresh;
mr = mrstruct_read(hrname);
wm = loadsegmentation(wmname,1,mr);
mrfod = computeCSDSH(mr,wm.dataAy>thres,Dax,shcut,numdirs);
[p n e] = fileparts(hrname);
if strcmpi('hardi',n(end-4:end)),
n = n(1:end-5);
end;
outname = buildoutname(outname,p,n,'FOD','.mat');
mrstruct_write(mrfod,outname);
out.FOD = {outname};
case 'doCSDFC'
hrname = P.filename1{1};
outname = P.newfilename;
numdirs = P.numoutdir;
wmname = P.roidef.roiname{1};
thres = P.roidef.thresh;
numit = P.numit;
numround = P.numround;
Daxial = P.Daxial;
lambda = P.lambda;
alpha = P.alpha;
purefc_sym = P.purefc_sym;
purefc_asym = P.purefc_asym;
iso_sym = P.iso_sym;
iso_asym = P.iso_asym;
lambda_lb = P.lambda_lb;
gamma_sym = P.gamma_sym;
gamma_asym = P.gamma_asym;
symout = P.symout;
mr = mrstruct_read(hrname);
wm = loadsegmentation(wmname,1,mr);
if not(isfield(mr.user,'bfactor')),
mr.user.bfactor = 1000;
end;
if size(mr.user.bDir,1) ~= 3,
mr.user.bDir = mr.user.bDir';
end
mrfod = computeCSDFC(mr.dataAy ,mr.user.bDir,'mask',wm.dataAy>thres,'bDir',numdirs, ...
'numround',numround,'numit',numit,'lambda',lambda,'iso_sym',iso_sym,'iso_asym',iso_asym,'gamma_asym',gamma_asym,'gamma_sym',gamma_sym,'lambda_lb',lambda_lb, ...
'alpha',alpha,'kernwid',Daxial*mr.user.bfactor(1)/1000,'purefc_sym',purefc_sym,'purefc_asym',purefc_asym,'output_sym',symout,'mrprop',mr);
[p n e] = fileparts(hrname);
if strcmpi('hardi',n(end-4:end)),
n = n(1:end-5);
end;
outname = buildoutname(outname,p,n,'FOD','.mat');
mrstruct_write(mrfod,outname);
out.FOD = {outname};
case 'doCSA'
hrname = P.filename1{1};
outname = P.newfilename;
shcut = P.shcutoff;
penal = P.laplacebeltrami;
numdirs = P.numdirsout;
mr = mrstruct_read(hrname);
[mrfod] = computeCSAdODF(mr,numdirs,shcut,penal);
[p n e] = fileparts(hrname);
if strcmpi('hardi',n(end-4:end)),
n = n(1:end-5);
end;
outname = buildoutname(outname,p,n,'FOD','.mat');
mrstruct_write(mrfod,outname);
out.FOD = {outname};
case 'doL1CSD_TFD'
hrname = P.filename1{1};
wmname = P.roidef.roiname{1};
outname = P.newfilename;
if isfield(P.fiout,'newfilename'), % mrstruct
savemr_or_nifti = 1;
outnameTFD = P.fiout.newfilename;
elseif isfield(P.fiout,'newfinameniftireslice'), % nifti + reslice
savemr_or_nifti = 0;
ref = P.fiout.newfinameniftireslice.filename3{1};
outnameTFD = P.fiout.newfinameniftireslice.newfilename;
elseif isfield(P.fiout,'newfinamenifti'), % nifti
savemr_or_nifti = 0;
ref = [];
outnameTFD = P.fiout.newfinamenifti.newfilename;
end;
params.osamp = P.osamp;
params.csdL1.maxit = P.maxit;
params.csdL1.lambda = P.lambdaL1;
params.csdL1.powsm = P.powsm;
params.csdL1.numdir = P.numdir;
params.csdL1.D = [P.Dax P.Drad];
params.TFD.wmthres = P.roidef.thresh;
params.TFD.csfweight = 0;
params.TFD.gmweight = 0;
params.TFD.globalreg = 1;
params.TFD.lambda = [1 P.lambda1 P.lambda2];
params.TFD.planorder = P.planorder;
[mrres mrfod] = computeTensorFOD(hrname,wmname,[],[],params);
[p n e] = fileparts(hrname);
if strcmpi('hardi',n(end-4:end)),
n = n(1:end-5);
end;
outname = buildoutname(outname,p,n,'FOD','.mat');
mrstruct_write(mrfod,outname);
out.FOD = {outname};
if savemr_or_nifti == 1,
outnameTFD = buildoutname(outnameTFD,p,n,'TFD','.mat');
mrstruct_write(mrres,outnameTFD);
else,
outnameTFD = buildoutname(outnameTFD,p,n,'TFD','.nii');
if not(isempty(ref)),
tmpname = '/tmp/niftitomrstructconversiontmp.nii';
tmpnamer = '/tmp/rniftitomrstructconversiontmp.nii';
[res, errStr]= mrstruct_to_nifti(mrres, tmpname , 'float32');
flags.mean = false;
flags.which = 1;
spm_reslice({ ref tmpname },flags);
system(['cp ' tmpnamer ' ' outnameTFD]);
else,
[res, errStr]= mrstruct_to_nifti(mrres, outnameTFD , 'float32');
end;
end;
out.TFD = {outnameTFD};
case 'doTFD'
hrname = P.filename1{1};
wmname = P.roidef.roiname{1};
if isfield(P.fiout,'newfilename'), % mrstruct
savemr_or_nifti = 1;
outnameTFD = P.fiout.newfilename;
elseif isfield(P.fiout,'newfinameniftireslice'), % nifti + reslice
savemr_or_nifti = 0;
ref = P.fiout.newfinameniftireslice.filename3{1};
outnameTFD = P.fiout.newfinameniftireslice.newfilename;
elseif isfield(P.fiout,'newfinamenifti'), % nifti
savemr_or_nifti = 0;
ref = [];
outnameTFD = P.fiout.newfinamenifti.newfilename;
end;
params.osamp = P.osamp;
params.TFD.wmthres = P.roidef.thresh;
params.TFD.csfweight = 0;
params.TFD.gmweight = 0;
params.TFD.globalreg = 1;
params.TFD.lambda = [1 P.lambda1 P.lambda2];
params.TFD.planorder = P.planorder;
params.TFD.modifyFOD = P.modifyFOD;
[mrres] = computeTensorFD(hrname,wmname,[],[],params);
[p n e] = fileparts(hrname);
if strcmpi('fod',n(end-2:end)),
n = n(1:end-3);
end;
if savemr_or_nifti == 1,
outnameTFD = buildoutname(outnameTFD,p,n,'TFD','.mat');
mrstruct_write(mrres,outnameTFD);
else,
outnameTFD = buildoutname(outnameTFD,p,n,'TFD','.nii');
if not(isempty(ref)),
tmpname = '/tmp/niftitomrstructconversiontmp.nii';
tmpnamer = '/tmp/rniftitomrstructconversiontmp.nii';
[res, errStr]= mrstruct_to_nifti(mrres, tmpname , 'float32');
flags.mean = false;
flags.which = 1;
spm_reslice({ ref tmpname },flags);
system(['cp ' tmpnamer ' ' outnameTFD]);
else,
[res, errStr]= mrstruct_to_nifti(mrres, outnameTFD , 'float32');
end;
end;
out.TFD = {outnameTFD};
case 'deformFOD'
fodname = P.filename2{1};
iy = P.filedefi{1};
y = P.filedef{1};
interp = P.interp;
modulate = P.modulate;
outname = P.newfilename;
noutdir = P.noutdir;
deformedFOD = mrFOD_warp(iy,y,fodname,'modulate',modulate,'method',interp,'noutdir',noutdir);
[p n e] = fileparts(fodname);
if strcmpi('fod',n(end-2:end)),
n = n(1:end-3);
end;
outname = buildoutname(outname,p,n,'defFOD','.mat');
mrstruct_write(deformedFOD,outname);
out.FOD = {outname};
case 'deformFDalong'
fodname = P.filename2{1};
fdname = P.filename4{1};
iy = P.filedefi{1};
y = P.filedef{1};
interp = P.interp;
modulate = P.modulate;
outname = P.newfilename;
fod = mrstruct_read(fodname);
mfod = mean(fod.dataAy,4);
fd = mrstruct_read(fdname);
ratio = fd.dataAy ./ (eps+mfod);
for k = 1:size(fod.dataAy,4),
fod.dataAy(:,:,:,k) = fod.dataAy(:,:,:,k) .* ratio;
end
fod = mrFOD_warp(iy,y,fod,'modulate',modulate==1,'method',interp);
fd.dataAy = mean(fod.dataAy,4);
[p n e] = fileparts(fodname);
outname = buildoutname(outname,p,n,'def','.mat');
mrstruct_write(fd,outname);
case 'smoothFOD'
fodname = P.filename2{1};
axsig = P.axialsigma;
rasig = P.radialsigma;
outname = P.newfilename;
if rasig > axsig,
warning('smaller axial width than radial not yet implemented');
return;
end;
mr = mrstruct_read(fodname);
mrsm = mr;
bDir = mr.user.bDir;
sz = size(mr.dataAy);
[X Y Z] = ndgrid(-ceil(sz(1)/2):floor(sz(1)/2)-1,-ceil(sz(2)/2):floor(sz(2)/2)-1,-ceil(sz(3)/2):floor(sz(3)/2)-1);
X = fftshift(X); Y = fftshift(Y); Z = fftshift(Z);
R2 = X.^2 + Y.^2 + Z.^2;
isog = (exp(-R2/(2*axsig^2)));
mrsm.dataAy(isnan(mrsm.dataAy(:))) = 0;
for k = 1:size(mr.dataAy,4)
fgauss = fftn(exp(- (R2-(X*bDir(1,k) + Y*bDir(2,k) + Z*bDir(3,k)).^2) * (1/(2*rasig.^2) - 1/(2*axsig.^2))) .* isog);
mrsm.dataAy(:,:,:,k) = real(ifftn(fftn(squeeze(mrsm.dataAy(:,:,:,k))).*fgauss));
fprintf('.');
end;
[p n e] = fileparts(fodname);
ex = '';
if strcmpi('fod',n(end-2:end)),
ex = '_FOD';
n = n(1:end-3);
end;
if strcmpi('hardi',n(end-4:end)),
ex = '_HARDI';
n = n(1:end-5);
end;
outname = buildoutname(outname,p,n,['smoothed' ex],'.mat');
mrsm.dataAy = single(mrsm.dataAy);
mrstruct_write(mrsm,outname);
out.FOD = {outname};
case 'smoothFODRic'
fodname = P.filename2{1};
axsig = P.axialsigma;
rasig = P.radialsigma;
ksz = P.ksz;
noiselevel = P.noiselevel;
outname = P.newfilename;
if rasig > axsig,
warning('smaller axial width than radial not yet implemented');
return;
end;
mr = mrstruct_read(fodname);
mrsm = smoothAnisoRice(mr,axsig,rasig,ksz,noiselevel);
[p n e] = fileparts(fodname);
ex = '';
if strcmpi('fod',n(end-2:end)),
ex = '_FOD';
n = n(1:end-3);
end;
if strcmpi('hardi',n(end-4:end)),
ex = '_HARDI';
n = n(1:end-5);
end;
outname = buildoutname(outname,p,n,['smoothed' ex],'.mat');
mrsm.dataAy = single(mrsm.dataAy);
mrstruct_write(mrsm,outname);
out.FOD = {outname};
case 'resampleHARDI'
hardiname = P.filename1{1};
hardiref = P.filenameHARDI1{1};
mr = mrstruct_read(hardiname);
ref = mrstruct_read(hardiref);
bDir = ref.user.bDir;
clear ref;
mr = resampleHARDI(mr,bDir);
[p n e] = fileparts(hardiname);
outname = fullfile(p,['r' n e]);
mrstruct_write(mr,outname);
out.HARDI = {outname};
case 'getsiFOD'
fodname = P.filename2{1};
if isfield(P.fiout,'newfilename'), % mrstruct
savemr_or_nifti = 1;
outname = P.fiout.newfilename;
elseif isfield(P.fiout,'newfinameniftireslice'), % nifti + reslice
savemr_or_nifti = 0;
ref = P.fiout.newfinameniftireslice.filename3{1};
outname = P.fiout.newfinameniftireslice.newfilename;
elseif isfield(P.fiout,'newfinamenifti'), % nifti
savemr_or_nifti = 0;
ref = [];
outname = P.fiout.newfinamenifti.newfilename;
end;
mr = mrstruct_read(fodname);
mrmfod = mr;
if P.sitype == 0, % GFA
mrmfod.dataAy = sqrt(squeeze(var(mr.dataAy,[],4)) ./ squeeze(sum(mr.dataAy.^2,4)) * size(mr.dataAy,4));
mrfod.user.type = 'GFA';
elseif P.sitype == 1, % mean FOD
mrmfod.dataAy = squeeze(mean(mr.dataAy,4));
mrfod.user.type = 'meanFOD';
elseif P.sitype == 2, % mean FOD b0norm
mrmfod.dataAy = squeeze(mean(mr.dataAy,4))./(eps+mr.user.b0avg);
mrfod.user.type = 'meanFODb0norm';
elseif P.sitype == 3, %max FOD
mrmfod.dataAy = max(mr.dataAy,[],4);
mrfod.user.type = 'maxFOD';
elseif P.sitype == 4, %max FOD b0norm
mrmfod.dataAy = max(mr.dataAy,[],4)./(eps+mr.user.b0avg);
mrfod.user.type = 'maxFODb0norm';
end;
mrmfod.dim4 = 'unused';
[p n e] = fileparts(fodname);
if strcmpi('fod',n(end-2:end)),
n = n(1:end-3);
end;
if savemr_or_nifti == 1,
outname = buildoutname(outname,p,n,mrfod.user.type,'.mat');
mrstruct_write(mrmfod,outname);
else,
outname = buildoutname(outname,p,n,mrfod.user.type,'.nii');
if not(isempty(ref)),
tmpname = '/tmp/niftitomrstructconversiontmp.nii';
tmpnamer = '/tmp/rniftitomrstructconversiontmp.nii';
[res, errStr]= mrstruct_to_nifti(mrmfod, tmpname , 'float32');
flags.mean = false;
flags.which = 1;
spm_reslice({ ref tmpname },flags);
system(['cp ' tmpnamer ' ' outname]);
else,
[res, errStr]= mrstruct_to_nifti(mrmfod, outname , 'float32');
end;
end;
out.SIndex = {outname};
end
function outname = buildoutname(outname,p,n,str,ext)
if length(outname) >= 4,
if strcmpi(outname(1:4),ext),
if length(outname) > 5 & outname(5) == ',',
suffix = outname(6:end);
outname = fullfile(p,[n suffix str ext]);
return;
else,
outname = fullfile(p,[n str ext]);
return;
end;
end
end;
outname = fullfile(p,outname);
function m = loadsegmentation(name,osamp,mrprop,resliceflags)
mrprop.dataAy = zeros(size(mrprop.dataAy,1),size(mrprop.dataAy,2),size(mrprop.dataAy,3)); mrprop.dim4 = 'unused';
[p n e] = fileparts(name);
if isempty(mrprop.edges),
mrprop.edges = eye(4);
end;
mrprop.edges(1:3,1:3) = mrprop.edges(1:3,1:3)/osamp;
mrprop.vox = mrprop.vox/osamp;
mrprop.dataAy = zeros(size(mrprop.dataAy)*osamp);
if strcmpi(e(1:4),'.mat'),
if osamp ~= 1,
warning('oversampling > 1 not yet supported for masks of type mat');
end;
if length(e) > 4,
name = fullfile(p,[n e(1:4)]);
end;
ms = load(name);
if isfield(ms,'mrStruct');
m = ms.mrStruct;
elseif isfield(ms,'maskCell');
num = 1;
if length(e) > 4,
num = str2num(e(6:end));
end;
m = ms.mrsProp;
m.dataAy = ms.maskCell{num};
end;
elseif strcmpi(e(1:4),'.nii'),
if exist('resliceflags'),
m = nifti_to_mrstruct('volume',{name},mrprop,pwd,resliceflags);
else
m = nifti_to_mrstruct('volume',{name},mrprop);
end;
end;
|
github | philippboehmsturm/antx-master | dti_cfg_tracking.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_cfg_tracking.m | 36,311 | utf_8 | 0a532bd39e5f204d98fa948f848e14c0 |
% configure file for calculation of tensors
% DTI Configuration file
% BATCH system (Volkmar Glauche)
%
% File created by Susanne Schnell
function tracking = dti_cfg_tracking
% ---------------------------------------------------------------------
% filename Input dtdstruct
% ---------------------------------------------------------------------
filename = cfg_files;
filename.tag = 'filename';
filename.name = 'DTD file name';
filename.help = {'Select the calculated tensor file from the file selection menue("_DTD.mat").'};
filename.filter = 'mat';
filename.ufilter = '_DTD\.mat$';
filename.num = [1 1];
% ---------------------------------------------------------------------
% filename Input FTRstruct
% ---------------------------------------------------------------------
filenameFTR = cfg_files;
filenameFTR.tag = 'filenameFTR';
filenameFTR.name = 'FTR file name';
filenameFTR.help = {'Select the GT-FTR.'};
filenameFTR.filter = 'mat';
filenameFTR.ufilter = '_FTR\.mat$';
filenameFTR.num = [1 1];
% ---------------------------------------------------------------------
% startname, select the correct mask by name
% ---------------------------------------------------------------------
startname = cfg_entry;
startname.tag = 'startname';
startname.name = 'Type in the name of the mask';
startname.help = {'Type in the name of the mask.'};
startname.strtype = 's';
startname.num = [1 Inf];
% ---------------------------------------------------------------------
% startmask, select the correct mask by a number
% ---------------------------------------------------------------------
startnumber = cfg_entry;
startnumber.tag = 'startnumber';
startnumber.name = 'Mask Number';
startnumber.help = {['Select the mask by a number.'...
'You need to remember the mask position by yourself.']};
startnumber.strtype = 'e';
startnumber.num = [1 1];
% ---------------------------------------------------------------------
% startmask, select the correct mask by a number
% ---------------------------------------------------------------------
startmask = cfg_choice;
startmask.tag = 'startmask';
startmask.name = 'Select the mask by number or by name';
startmask.help = {['Select the mask either by a number or by the name.' ...
'The name has to be spelled correctly. For the number'...
'you need to remember the mask position by yourself.']};
startmask.values = {startname startnumber};
% ---------------------------------------------------------------------
% startfileROI as start mask (mori)
% ---------------------------------------------------------------------
startfile = cfg_files;
startfile.tag = 'startfile';
startfile.name = 'Load ROI as Start Mask';
startfile.help = {'Select a maskstruct as start mask, can be some region of interest.'};
startfile.filter = 'mat';
startfile.ufilter = '.*';
startfile.num = [1 1];
% ---------------------------------------------------------------------
% startdef starting criteria as mask (mori)
% ---------------------------------------------------------------------
startdef = cfg_branch;
startdef.tag = 'startdef';
startdef.name = 'Definition of Start Region';
startdef.help = {'Chose the mask-file as starting criteria and select the mask.'};
startdef.val = {startfile startmask};
% ---------------------------------------------------------------------
% stopname, select the correct mask by name
% ---------------------------------------------------------------------
stopname = cfg_entry;
stopname.tag = 'stopname';
stopname.name = 'Type in the name of the mask';
stopname.help = {'Type in the name of the mask.'};
stopname.strtype = 's';
stopname.num = [1 Inf];
% ---------------------------------------------------------------------
% stopnumber, select the correct mask by a number
% ---------------------------------------------------------------------
stopnumber = cfg_entry;
stopnumber.tag = 'stopnumber';
stopnumber.name = 'Mask Number';
stopnumber.help = {'Select the mask by a number.'};
stopnumber.strtype = 'e';
stopnumber.num = [1 1];
% ---------------------------------------------------------------------
% stopmask, select the correct mask by a number
% ---------------------------------------------------------------------
stopmask = cfg_choice;
stopmask.tag = 'stopmask';
stopmask.name = 'Mask Number or Name';
stopmask.help = {'Select the mask by a number or by name.'};
stopmask.values = {stopnumber stopname};
% ---------------------------------------------------------------------
% stopmask ROI as stop mask (mori)
% ---------------------------------------------------------------------
stopfile = cfg_files;
stopfile.tag = 'stopfile';
stopfile.name = 'Load ROI as Stop Mask';
stopfile.help = {'Load a file containing the stop mask.'};
stopfile.filter = 'mat';
stopfile.ufilter = '.*';
stopfile.num = [1 1];
% ---------------------------------------------------------------------
% stopdef stopping criteria as mask (mori)
% ---------------------------------------------------------------------
stopdef = cfg_branch;
stopdef.tag = 'stopdef';
stopdef.name = 'Definition of Stop Region';
stopdef.help = {'Chose the mask-file as stopping criteria and select the mask.'};
stopdef.val = {stopfile stopmask};
% ---------------------------------------------------------------------
% seedname, select the correct mask by name
% ---------------------------------------------------------------------
seedname = cfg_entry;
seedname.tag = 'seedname';
seedname.name = 'Type in the name of the mask';
seedname.help = {'Type in the name of the mask from which you want to start tracking.'};
seedname.strtype = 's';
seedname.num = [1 Inf];
% ---------------------------------------------------------------------
% seedmask, select the correct mask by a number (prob)
% ---------------------------------------------------------------------
seednumber = cfg_entry;
seednumber.tag = 'seednumber';
seednumber.name = 'Mask Number';
seednumber.help = {'Select the mask by a number. You need to remember the position number by yourself!', ...
'If more then one number is given, tracking will start from each of the specified masks.',...
'Specify ''Inf'' to use all masks in the given mask struct.'};
seednumber.strtype = 'e';
seednumber.num = [1 Inf];
% ---------------------------------------------------------------------
% seedmask, select the correct mask by a number (prob)
% ---------------------------------------------------------------------
seedmask = cfg_choice;
seedmask.tag = 'seedmask';
seedmask.name = 'Mask Number or Name';
seedmask.help = {'Select the mask by a number or by name. You need to remember the correct spelling. In case of'...
'a number you need to remember the position number by yourself!', ...
'If more then one number is given, tracking will start from each of the specified masks.',...
'Specify ''Inf'' to use all masks in the given mask struct.'};
seedmask.values = {seednumber seedname};
% ---------------------------------------------------------------------
% seedfile, filename of seedroi (prob)
% ---------------------------------------------------------------------
seedfile = cfg_files;
seedfile.tag = 'seedfile';
seedfile.name = 'Mask filename';
seedfile.help = {'Select a mask specifying the seed region.'};
seedfile.filter = 'mat';
seedfile.ufilter = '.*';
seedfile.num = [1 1];
% ---------------------------------------------------------------------
% seedroi MaskStruct containing Start Region (prob)
% ---------------------------------------------------------------------
seedroi = cfg_branch;
seedroi.tag = 'seedroi';
seedroi.name = 'MaskStruct containing Start Region';
seedroi.help = {'Chose the mask-file for the definition of the seed region and select the mask.'};
seedroi.val = {seedfile seedmask};
% ---------------------------------------------------------------------
% seedposition enter position of seed voxel (prob)
% ---------------------------------------------------------------------
seedposition = cfg_entry;
seedposition.tag = 'seedposition';
seedposition.name = 'Enter Position of the Seed Voxel';
seedposition.val{1} = [int16(1) int16(1) int16(1)];
seedposition.help = {'Chose the mask-file for the definition of the seed region and select the mask.'};
seedposition.strtype = 'e';
seedposition.num = [1 3];
% ---------------------------------------------------------------------
% seedchoice Definition of Start Region (prob)
% ---------------------------------------------------------------------
seedchoice = cfg_choice;
seedchoice.tag = 'seedchoice';
seedchoice.name = 'Definition of Start Region';
seedchoice.help = {['The seed region can be specified in different ' ...
'ways.']};
seedchoice.values = {seedroi seedposition};
% ---------------------------------------------------------------------
% defname, select the correct mask by name
% ---------------------------------------------------------------------
defname = cfg_entry;
defname.tag = 'defname';
defname.name = 'Type in the name of the mask';
defname.help = {'Type in the name of the mask in which tracking should be performed.'};
defname.strtype = 's';
defname.num = [1 Inf];
% ---------------------------------------------------------------------
% defmask, select the correct mask by a number (prob)
% ---------------------------------------------------------------------
defnumber = cfg_entry;
defnumber.tag = 'defnumber';
defnumber.name = 'Mask Number';
defnumber.help = {'Select the mask by a number. You need to remember the correct spelling. In case of',...
'a number you need to remember the position number by yourself!',...
'Or if you created and saved the mask in the fiberviewer_tool, check at which position',...
'or under which name your mask is listed.'};
defnumber.strtype = 'e';
defnumber.num = [1 1];
% ---------------------------------------------------------------------
% defmask, select the correct mask by a number (prob)
% ---------------------------------------------------------------------
defmask = cfg_choice;
defmask.tag = 'defmask';
defmask.name = 'Mask Number or Name';
defmask.help = {'Select the mask by a number or by name. You need to remember the position number by yourself! If you created and saved the mask in the fiberviewer_tool, check at which position your mask is listed.'};
defmask.values = {defnumber defname};
% ---------------------------------------------------------------------
% deffile definition of tracking area (saved in mask) (prob)
% ---------------------------------------------------------------------
deffile = cfg_files;
deffile.tag = 'deffile';
deffile.name = 'Mask filename';
deffile.help = {'Select the tracking mask in the file selection dialogue.'};
deffile.filter = 'mat';
deffile.ufilter = '.*';
deffile.num = [1 1];
% ---------------------------------------------------------------------
% defarea Input tracking area (prob)
% ---------------------------------------------------------------------
defarea = cfg_branch;
defarea.tag = 'defarea';
defarea.name = 'Definition of Tracking Area using a Mask';
defarea.help = {'Chose a mask file and select the mask defining the tracking area (e.g. white matter mask)'};
defarea.val = {deffile defmask};
% ---------------------------------------------------------------------
% deffa, definition of tracking area using FA (prob)
% ---------------------------------------------------------------------
deffa = cfg_entry;
deffa.tag = 'deffa';
deffa.name = 'FA threshold';
deffa.val = {0.1};
deffa.help = {'Enter the FA value above which tracking will be performed only. default = 0.1'};
deffa.strtype = 'e';
deffa.num = [1 1];
% ---------------------------------------------------------------------
% deffa, definition of tracking area using Trace (prob)
% ---------------------------------------------------------------------
deftrace = cfg_entry;
deftrace.tag = 'deftrace';
deftrace.name = 'Trace threshold';
deftrace.val = {0.002};
deftrace.help = {'Enter the Trace (mean diffusivity) value below which tracking will be performed only. default = 0.002'};
deftrace.strtype = 'e';
deftrace.num = [1 1];
% ---------------------------------------------------------------------
% defarea Input tracking area (prob)
% ---------------------------------------------------------------------
defthresh = cfg_branch;
defthresh.tag = 'defthresh';
defthresh.name = 'Definition of Tracking Area using Thresholds';
defthresh.help = {'Select thresholds for FA (tracking only above this threshold) and Trace (tracking only below this threshold).'};
defthresh.val = {deffa deftrace};
% ---------------------------------------------------------------------
% start Which criteria for starting tracking, mask or thresholds? (prob)
% ---------------------------------------------------------------------
defroi = cfg_choice;
defroi.name = 'Define Tracking Area';
defroi.tag = 'defroi';
defroi.values = {defarea defthresh};
defroi.help = {'Do you want to define the tracking area by thresholds or by masks?'};
% ---------------------------------------------------------------------
% fname name of resulting file containing the fibre tracks (prob)
% ---------------------------------------------------------------------
fname = cfg_entry;
fname.tag = 'fname';
fname.name = 'File Name of the resulting tracks';
fname.help = {'Type in the name of the new file containg the fibre tracks.'};
fname.strtype = 's';
fname.num = [1 Inf];
% ---------------------------------------------------------------------
% dir Output directory (prob)
% ---------------------------------------------------------------------
dir = cfg_files;
dir.tag = 'dir';
dir.name = 'Output directory';
dir.help = {'Select the output directory.'};
dir.filter = 'dir';
dir.num = [1 1];
% ---------------------------------------------------------------------
% out User-specified output location (prob)
% ---------------------------------------------------------------------
out = cfg_branch;
out.tag = 'out';
out.name = 'User-specified output location';
out.val = {dir fname};
out.help = {'Specify output directory and filename.'};
% ---------------------------------------------------------------------
% auto Automatically determine output filename (prob)
% ---------------------------------------------------------------------
auto = cfg_const;
auto.tag = 'auto';
auto.name = 'Automatically determine output filename';
auto.val = {1};
% ---------------------------------------------------------------------
% newprobfile Select output location (prob)
% ---------------------------------------------------------------------
newmorifile = cfg_choice;
newmorifile.tag = 'newmorifile';
newmorifile.name = 'Select output location';
newmorifile.values = {auto out};
newmorifile.help = {'Name and location can be specified explicitly, or they can be derived from the input DTD struct filename.'};
% ---------------------------------------------------------------------
% newprobfile Select output location (prob)
% ---------------------------------------------------------------------
newprobfile = cfg_choice;
newprobfile.tag = 'newprobfile';
newprobfile.name = 'Select output location';
newprobfile.values = {auto out};
newprobfile.help = {'Name and location can be specified explicitly, or they can be derived from the input DTD struct filename.'};
% ---------------------------------------------------------------------
% maxangle maximum allowed angle of fibre track (mori)
% ---------------------------------------------------------------------
maxangle = cfg_entry;
maxangle.tag = 'maxangle';
maxangle.name = 'Maximum Allowed Angle';
maxangle.val = {53.1};
maxangle.help = {'Type in the maximum angle a fibre tract can bend. default = 53.1'};
maxangle.strtype = 'e';
maxangle.num = [1 1];
% ---------------------------------------------------------------------
% minvox minumum amount of voxels for fibre tracts (mori)
% ---------------------------------------------------------------------
minvox = cfg_entry;
minvox.tag = 'minvox';
minvox.name = 'Minimum amount of voxels';
minvox.val = {5};
minvox.help = {'Enter the minimum length of the tract in amount of voxels. default = 5'};
minvox.strtype = 'e';
minvox.num = [1 1];
% ---------------------------------------------------------------------
% startfaLim start tracking if voxel has an FA value below (mori)
% ---------------------------------------------------------------------
startfaLim = cfg_entry;
startfaLim.tag = 'startfaLim';
startfaLim.name = 'Start at FA Limit';
startfaLim.val = {0.25};
startfaLim.help = {'Stop if voxel has an FA value above. default = 0.25'};
startfaLim.strtype = 'e';
startfaLim.num = [1 1];
% ---------------------------------------------------------------------
% startTrLim start tracking if voxel has a Trace value below (mori)
% ---------------------------------------------------------------------
startTrLim = cfg_entry;
startTrLim.tag = 'startTrLim';
startTrLim.name = 'Start at Trace Limit';
startTrLim.val = {0.0016};
startTrLim.help = {'Start if voxel has an Trace (= mean diffusivity) value below. default = 0.0016'};
startTrLim.strtype = 'e';
startTrLim.num = [1 1];
% ---------------------------------------------------------------------
% startthreshold select start criteria via thresholds (mori)
% ---------------------------------------------------------------------
startthreshold = cfg_branch;
startthreshold.tag = 'startthreshold';
startthreshold.name = 'Start Criteria via Threshold';
startthreshold.help = {'Select FA and Trace(D) thresholds as starting criteria for the streamline tracking.'};
startthreshold.val = {startfaLim startTrLim};
% ---------------------------------------------------------------------
% start Which criteria for starting tracking, mask or thresholds? (mori)
% ---------------------------------------------------------------------
start = cfg_choice;
start.name = 'Select Start Criteria';
start.tag = 'start';
start.values = {startdef startthreshold};
start.help = {'Chose between a mask or FA and Trace(D) thresholds as starting criteria.'};
% ---------------------------------------------------------------------
% stopfaLim stop tracking if voxel has an FA value below (mori)
% ---------------------------------------------------------------------
stopfaLim = cfg_entry;
stopfaLim.tag = 'stopfaLim';
stopfaLim.name = 'Stop at FA Limit';
stopfaLim.val = {0.15};
stopfaLim.help = {'Stop if voxel has an FA value below. default = 0.15'};
stopfaLim.strtype = 'e';
stopfaLim.num = [1 1];
% ---------------------------------------------------------------------
% stopTrLim stop tracking if voxel has a Trace value below (mori)
% ---------------------------------------------------------------------
stopTrLim = cfg_entry;
stopTrLim.tag = 'stopTrLim';
stopTrLim.name = 'Stop at Trace Limit';
stopTrLim.val = {0.002};
stopTrLim.help = {'Stop if voxel has an Trace (= mean diffusivity) value below. default = 0.002'};
stopTrLim.strtype = 'e';
stopTrLim.num = [1 1];
% ---------------------------------------------------------------------
% startthreshold select start criteria via thresholds (mori)
% ---------------------------------------------------------------------
stopthreshold = cfg_branch;
stopthreshold.tag = 'stopthreshold';
stopthreshold.name = 'Stop Criteria via Thresholds';
stopthreshold.help = {'Select FA and Trace(D) thresholds as stopping criteria for the streamline tracking.'};
stopthreshold.val = {stopfaLim stopTrLim};
% ---------------------------------------------------------------------
% stop Which criteria for stopping tracking, mask or thresholds? (mori)
% ---------------------------------------------------------------------
stop = cfg_choice;
stop.name = 'Select Stop Criteria';
stop.tag = 'stop';
stop.values = {stopdef stopthreshold};
stop.help = {'Chose between a mask or FA and Trace thresholds as start criteria.'};
% ---------------------------------------------------------------------
% randsampno how many streamlines to start (only if randsampler on yes)
% (mori)
% ---------------------------------------------------------------------
randsampno = cfg_entry;
randsampno.tag = 'randsampno';
randsampno.name = 'How many streamlines per voxel?';
randsampno.val = {2};
randsampno.help = {'How many streamlines should be started per voxel? This option is only possible if the Random Sampler is switched on. default = 2'};
randsampno.strtype = 'e';
randsampno.num = [1 1];
% ---------------------------------------------------------------------
% randsampler random start position within voxel? (mori)
% ---------------------------------------------------------------------
randsampler = cfg_menu;
randsampler.tag = 'randsampler';
randsampler.name = 'Switch on Random Sampler?';
randsampler.val = {2};
randsampler.help = {'Do you want more than one streamline, which start in random position in the voxel or not? default: No'};
randsampler.labels = {'Yes - start at random position in voxels'
'No - start in the middle of voxels'}';
randsampler.values = {1 2};
% ---------------------------------------------------------------------
% threshold threshold in B0 images at which tensors are defined as 0 (prob)
% ---------------------------------------------------------------------
exponent = cfg_entry;
exponent.tag = 'exponent';
exponent.name = 'Exponent';
exponent.val = {4};
exponent.help = {'Enter the exponent by which the underlying diffusion tensor should be sharpened. default = 4'};
exponent.strtype = 'e';
exponent.num = [1 1];
% ---------------------------------------------------------------------
% nowalks number of walks (prob)
% ---------------------------------------------------------------------
nowalks = cfg_entry;
nowalks.tag = 'nowalks';
nowalks.name = 'Number of Walks';
nowalks.val = {1000};
nowalks.help = {'Enter the amount of random walks. The default value of 1000 is rather a quick and dirt value. default = 1000'};
nowalks.strtype = 'e';
nowalks.num = [1 1];
% ---------------------------------------------------------------------
% fibrelength definitin of fibrelength (prob)
% ---------------------------------------------------------------------
fibrelength = cfg_entry;
fibrelength.tag = 'fibrelength';
fibrelength.name = 'Maximum Number of Voxels per Fibre';
fibrelength.val = {150};
fibrelength.help = {'Enter the maximum number of voxels a fibre can have. default = 150'};
fibrelength.strtype = 'e';
fibrelength.num = [1 1];
% ---------------------------------------------------------------------
% probrand chose between two probabilistic algorithms (prob)
% ---------------------------------------------------------------------
probrand = cfg_menu;
probrand.tag = 'probrand';
probrand.name = 'Probabilistic Algorithm';
probrand.val = {2};
probrand.help = {'Chose between two probabilistic algorithms both based on the diffusion tensor.'
'default: 2'};
probrand.labels = {'Probabilistic tracking'
'Extended probabilistic tracking'}';
probrand.values = {1 2};
% ---------------------------------------------------------------------
% revisits allow looping revisits of a voxel or not (prob)
% ---------------------------------------------------------------------
revisits = cfg_menu;
revisits.tag = 'revisits';
revisits.name = 'Allow Revisits';
revisits.val = {1};
revisits.help = {'Select if you want to allow looping revisits of a voxel or not. default: Yes'};
revisits.labels = {'Yes - allow revisits'
'No - do not allow revisits'}';
revisits.values = {1 0};
% ---------------------------------------------------------------------
% probabilistic Selection of parameters (prob)
% ---------------------------------------------------------------------
probabilistic = cfg_exbranch;
probabilistic.tag = 'probabilistic';
probabilistic.name = 'Probabilistic Tracking';
probabilistic.help = {'Select the tensor file and additional information necessary for the algorithm.'};
probabilistic.val = {filename seedchoice defroi nowalks revisits fibrelength probrand exponent newprobfile};
probabilistic.prog = @dti_tracking_probabilistic_ui;
probabilistic.vout = @vout;
% ---------------------------------------------------------------------
% mori Input mrstruct file name (mori)
% ---------------------------------------------------------------------
mori = cfg_exbranch;
mori.tag = 'mori';
mori.name = 'Mori Streamline Tracking';
mori.help = {'Select the dtdstruct file and the enter the tracking related parameters.'};
mori.val = {filename start stop maxangle randsampler minvox randsampno newmorifile};
mori.prog = @dti_tracking_mori_ui;
mori.vout = @vout;
% ---------------------------------------------------------------------
% GT Input mrstruct file name (global tracker)
% ---------------------------------------------------------------------
gtrack = cfg_exbranch;
gtrack.tag = 'GTtrack';
gtrack.name = 'Global Tracking';
gtrack.help = {'Select the dtdstruct file and the enter the tracking related parameters.'};
gtrack.val = GTvalList;
gtrack.prog = @dti_tracking_global_ui;
gtrack.vout = @voutGT;
% ---------------------------------------------------------------------
% GT fiber accum
% ---------------------------------------------------------------------
numsamps = cfg_entry;
numsamps.tag = 'numsamps';
numsamps.name = 'Number of Samples';
numsamps.val = {10};
numsamps.help = {'Enter the number of samples.'};
numsamps.strtype = 'e';
numsamps.num = [1 1];
numits = cfg_entry;
numits.tag = 'numits';
numits.name = 'Number of Iterations';
numits.val = {10^6};
numits.help = {'Enter the number of iterations per sample.'};
numits.strtype = 'e';
numits.num = [1 1];
temp = cfg_entry;
temp.tag = 'temp';
temp.name = 'Temperature';
temp.val = {0.1};
temp.help = {'Temperature where we are sampling.'};
temp.strtype = 'e';
temp.num = [1 1];
gtrack_accum = cfg_exbranch;
gtrack_accum.tag = 'GTtrack_accum';
gtrack_accum.name = 'Global Tracking / Accumulate FTRs ';
gtrack_accum.help = {'Select the GT FTR and enter the tracking related parameters.'};
gtrack_accum.val = {filenameFTR fname numsamps numits temp};
gtrack_accum.prog = @dti_tracking_global_ui;
takefirst = @(x) x(1);
gtrack_accum.vout = @(x) takefirst(voutGT(x));
% ---------------------------------------------------------------------
% tracking
% ---------------------------------------------------------------------
tracking = cfg_choice;
tracking.tag = 'tracking';
tracking.name = 'Fibre Tracking';
tracking.values = {probabilistic mori gtrack gtrack_accum};
tracking.help = {'Select the fibre tracking algorithm, select parameters and start tracking.'};
% -------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
% Common to both algorithms
dep = cfg_dep;
dep.sname = 'Fibre Tracking';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
function dep = voutGT(job)
% Common to both algorithms
dep(1) = cfg_dep;
dep(1).sname = 'Fibre Tracking (FTR)';
dep(1).src_output = substruct('.','ftr');
dep(1).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
dep(2) = cfg_dep;
dep(2).sname = 'Fibre Tracking (FD)';
dep(2).src_output = substruct('.','fd');
dep(2).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
dep(3) = cfg_dep;
dep(3).sname = 'Fibre Tracking (EPD)';
dep(3).src_output = substruct('.','epd');
dep(3).tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}});
%%%%%%%%%%%%% GLOBAL TRACKING batch, mrc 2010
function list = GTvalList
%%%%%%%%%%%%% DTD/HARDI file selection
fnameDTD = cfg_files;
fnameDTD.tag = 'filenameDTD';
fnameDTD.name = 'DTD filename';
fnameDTD.help = {'Select the calculated tensor file from the file selection menue("_DTD.mat").'};
fnameDTD.filter = 'mat';
fnameDTD.ufilter = '_DTD\.mat$';
fnameDTD.num = [1 1];
fnameHARDI = cfg_files;
fnameHARDI.tag = 'filenameHARDI';
fnameHARDI.name = 'HARDI filename';
fnameHARDI.help = {'Select the HARDI file from the file selection menue("_HARDI.mat").'};
fnameHARDI.filter = 'mat';
fnameHARDI.ufilter = '_HARDI\.mat$';
fnameHARDI.num = [1 1];
fnameNII = cfg_files;
fnameNII.tag = 'filenameNII';
fnameNII.name = 'Nifti DW filename';
fnameNII.help = {'Select Diffusion-weighted Nifti images.'};
fnameNII.filter = 'image';
fnameNII.ufilter = '.*';
fnameNII.num = [1 inf];
fname = cfg_choice;
fname.tag = 'fname';
fname.name = 'HARDI/Nifti/DTD filename';
fname.help = {'Select HARDI,DTD of Nifti for tracking.'};
fname.values = {fnameDTD fnameNII fnameHARDI};
fnameftr = cfg_entry;
fnameftr.tag = 'fname';
fnameftr.name = 'File Name of the resulting tracks';
fnameftr.help = {'Type in the name of the new file containg the fibre tracks.'};
fnameftr.strtype = 's';
fnameftr.num = [1 Inf];
dir = cfg_files;
dir.tag = 'dir';
dir.name = 'Output directory';
dir.help = {'Select the output directory.'};
dir.filter = 'dir';
dir.num = [1 1];
out = cfg_branch;
out.tag = 'out';
out.name = 'User-specified output location';
out.val = {dir fnameftr};
out.help = {'Specify output directory and filename.'};
auto = cfg_const;
auto.tag = 'auto';
auto.name = 'Automatically determine output filename';
auto.val = {1};
newfile = cfg_choice;
newfile.tag = 'newfile';
newfile.name = 'Select output location';
newfile.values = {auto out};
newfile.help = {'Name and location can be specified explicitly, or they can be derived from the input DTD struct filename.'};
%%%%%%%%%%%%% parameters
parameters = cfg_menu;
parameters.tag = 'parameters';
parameters.name = 'Parameter Suggestion';
parameters.val = {0};
parameters.help = {'Decide for a sparse (fast) or dense (slow and accurate) setting'};
parameters.labels = {'Sparse' 'Dense'}';
parameters.values = {0 1};
roiid = cfg_entry;
roiid.tag = 'roiid';
roiid.name = 'name';
roiid.val = {1};
roiid.help = {'Each ROI inside a maskstruct has unique name. Enter here the name of the mask which should be used as tracking area.'};
roiid.strtype = 's';
roiid.num = [1 inf];
%%%%%%%%%%%%% mask selection
estimate = cfg_const;
estimate.name = 'Estimate Mask';
estimate.tag = 'estimate';
estimate.help = {'A whole brain mask is automatically estimated.'};
estimate.val = {0};
fnameMASK = cfg_files;
fnameMASK.tag = 'filenameMASK';
fnameMASK.name = 'Maskstruct filename';
fnameMASK.help = {'Select a predetermined tracking area from a maskstruct file (".mat").'};
fnameMASK.filter = 'mat';
fnameMASK.ufilter = '.mat$';
fnameMASK.num = [1 1];
fnameMASKnii = cfg_files;
fnameMASKnii.tag = 'filenameMASKnii';
fnameMASKnii.name = 'Nifti filename';
fnameMASKnii.help = {'Select a predetermined tracking area from a Nifti file.'};
fnameMASKnii.filter = 'image';
fnameMASKnii.ufilter = '.*';
fnameMASKnii.num = [1 1];
roiid = cfg_entry;
roiid.tag = 'roiid';
roiid.name = 'name';
roiid.val = {'untitled'};
roiid.help = {'Each ROI inside a maskstruct has a unique name. Enter here the name of the mask which should be used as tracking area.'};
roiid.strtype = 's';
roiid.num = [1 inf];
thresholdMask = cfg_entry;
thresholdMask.tag = 'thresholdMask';
thresholdMask.name = 'Select Threshold';
thresholdMask.val = {0.5};
thresholdMask.help = {'Select a threshold (if mask is not binary).'};
thresholdMask.strtype = 'e';
thresholdMask.num = [1 1];
mask = cfg_branch;
mask.tag = 'maskstruct';
mask.name = 'Tracking Area from maskstruct-file';
mask.help = {'Select Tracking Area from maskstruct-file.'};
mask.val = {fnameMASK roiid};
masknii = cfg_branch;
masknii.tag = 'masknii';
masknii.name = 'Tracking Area from Nifti-file';
masknii.help = {'Select Tracking Area from Nifti-file.'};
masknii.val = {fnameMASKnii thresholdMask};
trackingarea = cfg_choice;
trackingarea.tag = 'trackingarea';
trackingarea.name = 'Tracking Area';
trackingarea.help = {'Select Tracking Area.'};
trackingarea.values = {mask masknii estimate};
%%%%%%%%% custom parameters
auto_para_weight = cfg_const;
auto_para_weight.name = 'Automatically determined weight based on suggestion';
auto_para_weight.tag = 'auto_para_weight';
auto_para_weight.help = {'The weight parameter is automatically determined during parameter suggestion (not suitable for group studies).'};
auto_para_weight.val = {0};
custom_para_weight = cfg_entry;
custom_para_weight.tag = 'custom_para_weight';
custom_para_weight.name = 'Custom Parameter';
custom_para_weight.val = {0.05};
custom_para_weight.help = {'Enter the segment weight'};
custom_para_weight.strtype = 'e';
custom_para_weight.num = [1 1];
para_weight = cfg_choice;
para_weight.tag = 'para_weight';
para_weight.name = 'Segment Weight';
para_weight.values = { auto_para_weight custom_para_weight};
para_weight.help = {'Choose automatically determined weight (not suitable for group studies) or customize the weight parameter'};
auto_para_other = cfg_const;
auto_para_other.name = 'Automatically determined parameters based on suggestion';
auto_para_other.tag = 'auto_para_other';
auto_para_other.help = {'All other parameters are automatically determined during parameter suggestion.'};
auto_para_other.val = {0};
custom_para_other = cfg_entry;
custom_para_other.tag = 'custom_para_other';
custom_para_other.name = 'Custom Parameters';
custom_para_other.val = {[0.1, 0.001 , 50 , 5*10^8 , 1 , 2 , 0.2 , 1, 0.5]};
custom_para_other.help = {'Enter a list of parameteres [start Temp , stop Temp, #Steps, #Iterations, Width(mm), Length(mm), Dens. Penalty, b-value'};
custom_para_other.strtype = 'e';
custom_para_other.num = [9 1];
para_other = cfg_choice;
para_other.tag = 'para_other';
para_other.name = 'Other Parameters';
para_other.values = { auto_para_other custom_para_other};
para_other.help = {'Choose automatically determined parameters or customize them'};
minlen = cfg_entry;
minlen.tag = 'minlen';
minlen.name = 'Minimum fiber length';
minlen.val = {10};
minlen.help = {'Enter the minimum number of segments per fiber (a number between 1 and 256)'};
minlen.strtype = 'e';
minlen.num = [1 1];
maxlen = cfg_entry;
maxlen.tag = 'maxlen';
maxlen.name = 'Maximum fiber length';
maxlen.val = {inf};
maxlen.help = {'Enter the maximum number of segments per fiber (a number between 1 and Inf)'};
maxlen.strtype = 'e';
maxlen.num = [1 1];
list = {fname newfile trackingarea parameters para_weight para_other minlen maxlen};
|
github | philippboehmsturm/antx-master | dti_tracking_mori_ui.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_tracking_mori_ui.m | 4,210 | utf_8 | 3a91e18befb281be99045f017aac7759 | % interface program for batch program
%
% Author: Susanne Schnell
% PC 25.07.2008
function out = dti_tracking_mori_ui(P)
%load DTD
[path,nam,ext] = fileparts(P.filename{1});
dtdStruct = dtdstruct_read(P.filename{1});
% create or load start mask
if isfield(P.start,'startdef')
%load mask as mrstruct
[startMask,errStr] = maskstruct_read(P.start.startdef.startfile{1});
if isequal(size(dtdStruct.b0_image_struc.dataAy), maskstruct_query(startMask, 'sizeAy'))
if isfield(P.start.startdef.startmask,'startnumber')
startMask = mrstruct_init('volume',...
double(maskstruct_query(startMask,'getMaskVc',P.start.startdef.startmask.startnumber)),dtdStruct.b0_image_struc);
elseif isfield(P.start.startdef.startmask,'startname')
startMask = mrstruct_init('volume',...
double(maskstruct_query(startMask,'getMask',P.start.startdef.startmask.startname)),dtdStruct.b0_image_struc);
end
startMask.user.upperLim_FA= 'undef'; startMask.user.lowerLim_FA= 'undef';
startMask.user.upperLim_TrD= 'undef'; startMask.user.lowerLim_TrD= 'undef';
else
error('error: invalid roidata of startmask');
end
if ~isempty(errStr)
error('Selected file for stop mask is not of type "mrstruct".')
end
else
mrStruct= dtdstruct_query(dtdStruct, 'getFA');
startMask= mrstruct_init('volume', ...
double(mrStruct.dataAy > P.start.startthreshold.startfaLim),mrStruct);
mrStruct= dtdstruct_query(dtdStruct, 'getTrace');
startMask.dataAy= double(startMask.dataAy & (mrStruct.dataAy < P.start.startthreshold.startTrLim));
startMask.user.upperLim_FA= [];
startMask.user.lowerLim_FA= [P.start.startthreshold.startfaLim];
startMask.user.upperLim_TrD= [P.start.startthreshold.startTrLim];
startMask.user.lowerLim_TrD= [];
end
% create or load stop mask
if isfield(P.stop,'stopdef')
%load mask as mrstruct
[stopMask,errStr] = maskstruct_read(P.stop.stopdef.stopfile{1});
if isequal(size(dtdStruct.b0_image_struc.dataAy), maskstruct_query(stopMask, 'sizeAy'))
if isfield(P.stop.stopdef.stopmask,'stopnumber')
stopMask = mrstruct_init('volume',...
double(maskstruct_query(stopMask,'getMaskVc',P.stop.stopdef.stopmask.stopnumber)),dtdStruct.b0_image_struc);
elseif isfield(P.stop.stopdef.stopmask,'stopname')
stopMask = mrstruct_init('volume',...
double(maskstruct_query(stopMask,'getMask',P.stop.stopdef.stopmask.stopname)),dtdStruct.b0_image_struc);
end
stopMask.user.upperLim_FA= 'undef';
stopMask.user.lowerLim_FA= 'undef';
stopMask.user.upperLim_TrD= 'undef';
stopMask.user.lowerLim_TrD= 'undef';
else
error('error: invalid roidata of startmask');
end
if ~isempty(errStr)
error('Selected file for stop mask is not of type "mrstruct".')
end
else
mrStruct= dtdstruct_query(dtdStruct, 'getFA');
stopMask= mrstruct_init('volume', double(mrStruct.dataAy > P.stop.stopthreshold.stopfaLim), mrStruct);
mrStruct= dtdstruct_query(dtdStruct, 'getTrace');
stopMask.dataAy= double(stopMask.dataAy & (mrStruct.dataAy < P.stop.stopthreshold.stopTrLim));
stopMask.user.upperLim_FA= [];
stopMask.user.lowerLim_FA= [P.stop.stopthreshold.stopfaLim];
stopMask.user.upperLim_TrD= [P.stop.stopthreshold.stopTrLim];
stopMask.user.lowerLim_TrD= [];
end
% random sampling?
if P.randsampler == 1
[ftrStruct, errStr]= ftrack_mori(dtdStruct, startMask, stopMask, abs(cos(pi*P.maxangle/180)), P.minvox, P.randsampno);
else
[ftrStruct, errStr]= ftrack_mori(dtdStruct, startMask, stopMask, abs(cos(pi*P.maxangle/180)), P.minvox, []);
end
% save file
if isempty(errStr)
[path,nam,ext] = fileparts(P.filename{1});
if isfield(P.newmorifile,'auto')
if length(nam) > 4 && strcmp(nam(end-3:end), '_DTD')
nam = nam(1:end-4);
end
out.files{1} = fullfile(path, [nam,'_FTR.mat']);
else
out.files{1} = fullfile(P.newmorifile.out.dir{1}, P.newmorifile.out.fname);
end
ftrstruct_write(ftrStruct,out.files{1});
else
error(errStr);
end
|
github | philippboehmsturm/antx-master | dti_cfg.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_cfg.m | 4,953 | utf_8 | 36f74f0a3a9c415582f98699a3c064f4 | % configure file for DTI tools
% BATCH system (Volkmar Glauche)
%
% File created by Susanne Schnell
%%
function dtijobs = dti_cfg
%_______________________________________________________________________
% dtijobs DTI tools
%_______________________________________________________________________
dtijobs = cfg_choice;
dtijobs.tag = 'dtijobs';
dtijobs.name = 'DTI tools';
dtijobs.help = {
'%* Menu and Toolbar'
'/*\subsection*{Menu and Toolbar}*/'
'The "File" and "Edit" menu offer options to load, save and run a job and to modify the configuration of the batch system. For each application which is known to the batch system, a separate pulldown menu lists the available modules. Depending on the application, these modules may be grouped into submenus. Application specific defaults can be edited by choosing "Edit Defaults" from the application menu. The toolbar offers some shortcuts to frequently used operations (e.g. load, save, run).'
'Jobs are saved as MATLAB .m files. These files contain a MATLAB script, which can be executed in MATLAB to recreate the job variable. Multiple jobs can be loaded at once. This allows to concatenate parts of a job.'
''
'%* Top Left Panel'
'/*\subsection*{Top Left Panel}*/'
'The current job, which is represented as a list of executable modules. Modules marked with DEP depend on the successful execution of other modules in the job. Modules marked with X still require some values to be set before the job can be run, although an incompletely specified job can still be saved and loaded.'
''
'%* Top Right Panel'
'/*\subsection*{Top Right Panel}*/'
'These are the configuration details for the currently selected module. Items marked with DEP depend on the successful execution of other modules in the job. Items marked with X still require some values to be set before the job can be run. Depending on the kind of detail currently selected, a choice of buttons appears below the Centre Right Panel to manipulate the current value.'
''
'%* Centre Right Panel'
'/*\subsection*{Centre Right Panel}*/'
'This panel shows the current value of the highlighted item (where relevant).'
''
'%* Edit Buttons'
'/*\subsection*{Edit Buttons}*/'
'Depending on the type of configuration item, different edit buttons appear.'
'/*\begin{description}*/'
'/*\item[Files]*/'
'%* Files'
'"Select Files" opens a file selection dialog box to select multiple files. "Edit Value" opens a generic value edit dialog to edit the list of files. "Dependencies" offers a list of outputs from other modules that can be used as an input to this item.'
'/*\item[Generic Value]*/'
'%* Generic Value'
'"Edit Value" opens a generic value edit dialog to edit the list of files. "Dependencies" offers a list of outputs from other modules that can be used as an input to this item.'
'%* Menu'
'/*\item[Menu]*/'
'"Edit Value" opens a selection dialog showing allowed menu options.'
'%* Choice'
'/*\item[Choice]*/'
'"Edit Value" opens a selection dialog showing allowed menu options. Depending on the choosen option the module configuration may change.'
'%* Repeat'
'/*\item[Repeat]*/'
'"Add Item", "Replicate Item", "Delete Item" allow to add new repeated items, to replicate or to delete items from the list. If more than one item or item type exists, a dialog popup will appear listing the available options. Multiple selections are allowed.'
'/*\end{description}*/'
''
'%* Bottom Panel'
'/*\subsection*{Bottom Panel}*/'
'This panel provides information about the meaning of the current item.'
'/*\begin{figure} \begin{center} \includegraphics[width=70mm]{images/batch_ui1} \includegraphics[width=70mm]{images/batch_ui2} \includegraphics[width=70mm]{images/ui3} \includegraphics[width=70mm]{images/ui4}\end{center} \caption{The SPM5 user interface. \emph{Top left:} The usual user-interface. \emph{Top right:} The Defaults user-interface. \emph{Bottom left:} The file selector (click the (?) button for more information about filtering filenames, or selecting individual volumes within a 4D file). \emph{Bottom right:} more online help can be obtained via the main help button.} \end{figure} */'
}';
dtijobs.values = {dti_cfg_read dti_cfg_tensor dti_cfg_tracking dti_cfg_mapop dti_cfg_ftrop dti_cfg_roiop dti_cfg_fodop dti_cfg_logroi dti_cfg_realigndef};
|
github | philippboehmsturm/antx-master | dti_cfg_logroi.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_cfg_logroi.m | 3,994 | utf_8 | 14549addf6386d4dc2dfc66057d488a6 | % configure file for operations on streamline trackings results
%
% for BATCH EDITOR system (Volkmar Glauche)
%
% File created by Susanne Schnell
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function logroi = dti_cfg_logroi
% ---------------------------------------------------------------------
% newfilename name of resulting mask after operation
% ---------------------------------------------------------------------
newfilename = cfg_entry;
newfilename.tag = 'newfilename';
newfilename.name = 'New File Name';
newfilename.val = {'.txt'};
newfilename.help = {'Type in the name of textfile to be generated.'};
newfilename.strtype = 's';
newfilename.num = [1 Inf];
% ---------------------------------------------------------------------
% path of log file
% ---------------------------------------------------------------------
logpath = cfg_files;
logpath.tag = 'logpath';
logpath.name = 'Output directory';
logpath.help = {'Select the output directory of the textfile.'};
logpath.filter = 'dir';
logpath.num = [1 1];
% ---------------------------------------------------------------------
% mask, select the correct mask by a number
% ---------------------------------------------------------------------
mask1 = cfg_entry;
mask1.tag = 'mask1';
mask1.name = 'mask number';
mask1.help = {'Select the mask by a number. You need to remember the mask position by yourself.'};
mask1.strtype = 'e';
mask1.num = [1 Inf];
% ---------------------------------------------------------------------
% roiname
% ---------------------------------------------------------------------
roiname = cfg_files;
roiname.tag = 'roiname';
roiname.name = 'Load ROI';
roiname.help = {'Select a maskstruct (ROI).'};
roiname.filter = 'mat';
roiname.ufilter = '.*';
roiname.num = [1 1];
% ---------------------------------------------------------------------
% Log statistics of ROIs
% ---------------------------------------------------------------------
StatsRois = cfg_branch;
StatsRois.tag = 'StatsRois';
StatsRois.name = 'Statistics of all ROIs';
StatsRois.help = {'Log the statistics of all ROIs.'};
% ---------------------------------------------------------------------
% Log values of one ROI
% ---------------------------------------------------------------------
ValsRoi = cfg_branch;
ValsRoi.tag = 'ValsRoi';
ValsRoi.name = 'Values of ROI';
ValsRoi.help = {'Log the values of one ROI.'};
ValsRoi.val = {mask1};
% ---------------------------------------------------------------------
% status
% ---------------------------------------------------------------------
status = cfg_choice;
status.tag = 'status';
status.name = 'Select what to log';
status.help = {'Select whether you want to log'};
status.values = {StatsRois ValsRoi};
% ---------------------------------------------------------------------
% dtdname
% ---------------------------------------------------------------------
dtdname = cfg_files;
dtdname.tag = 'dtdname';
dtdname.name = 'Load DTD';
dtdname.help = {'Select the corresponding DTD.'};
dtdname.filter = 'mat';
dtdname.ufilter = '_DTD.*';
dtdname.num = [1 1];
% ---------------------------------------------------------------------
% Log ROI
% ---------------------------------------------------------------------
logroi = cfg_exbranch;
logroi.tag = 'logroi';
logroi.name = 'Log ROI';
logroi.help = {'Log the stats or values of all or only one ROI.'};
logroi.val = {dtdname roiname logpath newfilename status};
logroi.prog = @(job)dti_logroi_ui(job);
logroi.vout = @vout;
% ---------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'MASKstruct After Operation';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}}); |
github | philippboehmsturm/antx-master | dti_cfg_mapop.m | .m | antx-master/freiburgLight/matlab/diffusion/common/dti_cfg_mapop.m | 5,856 | utf_8 | 4b15d7421a595eb83239744dd9f94fb1 | % configure file for calculation of tensors
% DTI Configuration file
% BATCH system (Volkmar Glauche)
%
% File created by Susanne Schnell
function mapop = dti_cfg_mapop
% ---------------------------------------------------------------------
% filename1 name of probabilistic map 1
% ---------------------------------------------------------------------
filename1 = cfg_files;
filename1.tag = 'filename1';
filename1.name = 'Select first Map';
filename1.help = {'help..'};
filename1.filter = 'mat';
filename1.ufilter = '.*';
filename1.num = [1 1];
% ---------------------------------------------------------------------
% filename2 name of probabilistic map 2
% ---------------------------------------------------------------------
filename2 = cfg_files;
filename2.tag = 'filename2';
filename2.name = 'Select second Map';
filename2.help = {'help..'};
filename2.filter = 'mat';
filename2.ufilter = '.*';
filename2.num = [1 1];
% ---------------------------------------------------------------------
% filenames names of probabilistic maps 1
% ---------------------------------------------------------------------
filenames = cfg_files;
filenames.tag = 'filenames';
filenames.name = 'Select List of Maps';
filenames.help = {'help..'};
filenames.filter = 'mat';
filenames.ufilter = '.*';
filenames.num = [2 inf];
% ---------------------------------------------------------------------
% newfilename name of resulting file
% ---------------------------------------------------------------------
newfilename = cfg_entry;
newfilename.tag = 'newfilename';
newfilename.name = 'New File Name';
newfilename.val = {'.mat'};
newfilename.help = {'Type in the name of the new file, if you leave this empty a default file name is generated with the endings "_normMAP.mat", "_addMAP.mat" or "_multMAP.mat"'};
newfilename.strtype = 's';
newfilename.num = [1 Inf];
% ---------------------------------------------------------------------
% connmtx connection matrix for multiple multiplications
% ---------------------------------------------------------------------
connmtx = cfg_entry;
connmtx.tag = 'connmtx';
connmtx.name = 'Connection matrix';
connmtx.help = {['Enter the indices of the maps you want to multiply in ' ...
'a #connections-by-2 array. The output filenames will ' ...
'be determined automatically from the inputs.']};
connmtx.strtype = 'n';
connmtx.num = [Inf 2];
% ---------------------------------------------------------------------
% addition input of two maps
% ---------------------------------------------------------------------
addition = cfg_exbranch;
addition.tag = 'addition';
addition.name = 'Addition';
addition.help = {'Select the two maps you want to add.'};
addition.val = {filename1 filename2 newfilename};
addition.prog = @(job)dti_mapop_ui('addition',job);
addition.vout = @vout;
% ---------------------------------------------------------------------
% multiplication input of two maps
% ---------------------------------------------------------------------
multiplication = cfg_exbranch;
multiplication.tag = 'multiplication';
multiplication.name = 'Multiplication (2 Maps)';
multiplication.help = {'Select the two maps you want to multiply. Multiplaction results depend on the probabilistic tracking method chosen. If the extended version was used you will have three maps: the merging fibre map, the connecting fibre map and all-in-one map.'};
multiplication.val = {filename1 filename2 newfilename};
multiplication.prog = @(job)dti_mapop_ui('multiplication',job);
multiplication.vout = @vout;
% ---------------------------------------------------------------------
% connmulti input of map list and connection matrix
% ---------------------------------------------------------------------
connmulti = cfg_exbranch;
connmulti.tag = 'connmulti';
connmulti.name = 'Multiplication (List of Maps)';
connmulti.help = {['Enter a list of maps and a #maps-by-2 matrix ' ...
'indicating which map pairs you want to multiply. Multiplaction results depend on the probabilistic tracking method chosen. If the extended version was used you will have three maps: the merging fibre map, the connecting fibre map and all-in-one map.']};
connmulti.val = {filenames connmtx};
connmulti.prog = @(job)dti_mapop_ui('connmulti',job);
connmulti.check = @(job)dti_mapop_ui('connmulti_check',job);
connmulti.vout = @vout;
% ---------------------------------------------------------------------
% normalize input of one map and the new filename
% ---------------------------------------------------------------------
normalize = cfg_exbranch;
normalize.tag = 'normalize';
normalize.name = 'Normalization';
normalize.help = {'Select the map to normalize and chose a filename for the resulting map'};
normalize.val = {filename1 newfilename};
normalize.prog = @(job)dti_mapop_ui('normalize',job);
normalize.vout = @vout;
% ---------------------------------------------------------------------
% mapop
% ---------------------------------------------------------------------
mapop = cfg_choice;
mapop.tag = 'mapop';
mapop.name = 'Operations with Probability Maps';
mapop.help = {'Mathematical operations with probability maps.'};
mapop.values = {normalize addition multiplication connmulti};
% ---------------------------------------------------------------------
% ---------------------------------------------------------------------
function dep = vout(job)
dep = cfg_dep;
dep.sname = 'ProbMap After Operation';
dep.src_output = substruct('.','files');
dep.tgt_spec = cfg_findspec({{'class','cfg_files','strtype','e'}}); |
github | michaelmendoza/deep-ssfp-master | disp3d.m | .m | deep-ssfp-master/legacy/data/disp3d.m | 16,393 | utf_8 | 22572ec3bf83307c92d1a0efa1a0493f | function [ output_args ] = disp3d( myimageIn, myimage_title, figure_control, image_type )
% -----------------------------------------------------------
% -------------------------- ABOUT --------------------------
% disp3d was made in July 2011 by Danny Park and Hyrum Griffin.
% It is a stand-alone function that will display a 3D dataset
% with a variety of gui tools to facilitate viewing.
%
% -----------------------------------------------------------
% ------------------------- INPUTS --------------------------
%
% The inputs must be in this order:
% disp3d( myimageIn, myimage_title, figure_control, image_type )
%
% myimageIn required
% -- This is the 3D dataset itself.
%
% myimage_title optional
% -- If specified this string will be displayed both above the
% -- image and in the figure title.
%
% figure_control optional
% -- This option is similar to the "figure()" command.
% -- There are 2 allowed values, 'new' and 'replace'.
% -- 'new' is the default value and will cause the image
% -- to appear in a new figure. 'replace' will search for
% -- an existing figure with the exact same title, and if
% -- it finds one it will replace that figure with the new
% -- one. If 'replace' cannot find an existing figure it
% -- will behave like 'new'.
%
% image_type optional
% -- Preloads which component of the image is displayed.
% -- The 4 allowed values are 'Magnitude', 'Phase', 'Real',
% -- and 'Imaginary'. If not specified, the viewer will
% -- default to 'Magnitude'.
%
% -----------------------------------------------------------
% -------------- INPUT ARG PARSING & VERIFYING --------------
if nargin < 1,
error('No image to display');
end
if nargin < 2,
myimage_title = 'No title specified';
end
if nargin < 3,
figure_control = 'new';
end
if nargin < 4,
image_type = 'Magnitude';
end
ChangeType(image_type);
if ~(strcmp(figure_control,'new') || strcmp(figure_control,'replace'))
figure_control = 'new';
end
if ndims(myimage)~=3,
error('myimage needs to be a 3D image');
end
% -----------------------------------------------------------
% --------------------- ADDITIONAL ARGS ---------------------
% BACKGROUND COLOR
% bgcolor will set the background color of the window. Colors
% are specified in rgb values ranging from 0 to 1.
bgcolor = [.8 .8 .8]; % [r g b] -> [.8 .8 .8] are default values
% SLIDER PADDING
% windowingSliderPadding is used to specify extra space to be
% given on either side of the windowing sliders. For example,
% if [0 0] is specified then there will be no padding. If
% [.25 .1] is specified then an additional 25% of the range
% will be padded on the left, and 10% on the right.
windowingSliderPadding = [.25 .25]; % [padOnLeft padOnRight]
% -----------------------------------------------------------
% ------------------------ CODE BODY ------------------------
mysize = size(myimage);
slice_dim = 3;
cur_slice = round(mysize(slice_dim)/2);
pmax = max(myimage(:));
pmin = min(myimage(:));
prev_click = 0;
check = 0;
% [right,up,wide,high]
if strcmp(figure_control,'new')
close_old = 0;
elseif strcmp(figure_control,'replace')
if ishandle(findobj('type','figure','name',['Display 3D Data: ' myimage_title]))
close_old = 1;
else
close_old = 0;
end
else
close_old = 0;
end
a = @click_callback; % Create a function handle to the click_callback function
% Create the window
f = figure('Visible','off',...
'NumberTitle','off',...
'Position',[0,0,600,600],...
'ButtonDownFcn',a,...
'Color',bgcolor,...
'Toolbar','figure');
% Coordinates of the image
axs_draw = axes('Units','pixels',...
'Position',[25,50,350,500]);
% variables for slice selection position
sliceControlX = 420;
sliceControlY = 535;
% Text saying Slice Selection
Slice_Text = uicontrol('Style','text',...
'FontSize',14,...
'BackgroundColor',bgcolor,...
'Position',[sliceControlX,sliceControlY,150,20],...
'String','Slice Selection');
% Text saying image dimensions
Dimensions = uicontrol('Style','text',...
'BackgroundColor',bgcolor,...
'Position',[sliceControlX+37,sliceControlY-30,75,15],...
'String',num2str(mysize));
% Dim1 Button
dim1btn = uicontrol('Style','pushbutton',...
'String',':',...
'Position',[sliceControlX+37,sliceControlY-30-30,25,20],...
'Callback',{@dim1btn_press});
% Dim2 Button
dim2btn = uicontrol('Style','pushbutton',...
'String',':',...
'Position',[sliceControlX+37+25,sliceControlY-30-30,25,20],...
'Callback',{@dim2btn_press});
% Dim3 Button
dim3btn = uicontrol('Style','pushbutton',...
'String',':',...
'Position',[sliceControlX+37+50,sliceControlY-30-30,25,20],...
'Callback',{@dim3btn_press});
% Slider used for slice selection
slider = uicontrol('Style', 'slider',...
'Min',1,'Max',mysize(slice_dim),'Value',round(mysize(slice_dim)/2),...
'SliderStep',[1/mysize(slice_dim) 1/20],...
'Position', [sliceControlX,sliceControlY-30-60,150,20],...
'Callback', {@slider_action});
% Checkbox
checkbox = uicontrol('Style','checkbox',...
'Min',0,'Max',1,...
'String',['Rotate View CCW 90' char(176)],...
'Value', 0,...
'BackgroundColor',bgcolor,...
'Position',[sliceControlX+10,sliceControlY-30-60-30,149,20],...
'Callback',{@checkbox_click});
% variables for slice selection position
windowControlX = sliceControlX;
windowControlY = 240;
% Text saying Windowing
Windowing_Text = uicontrol('Style','text',...
'FontSize',14,...
'BackgroundColor',bgcolor,...
'Position',[windowControlX,windowControlY,150,25],...
'String','Windowing');
% Text saying image max
ImMax = uicontrol('Style','text',...
'BackgroundColor',bgcolor,...
'Position',[windowControlX-25,windowControlY-30,200,15],...
'String',['Image Max = ' num2str(max(myimage(:)))]);
% Text saying image min
ImMin = uicontrol('Style','text',...
'BackgroundColor',bgcolor,...
'Position',[windowControlX-25,windowControlY-30-15,200,15],...
'String',['Image Min = ' num2str(min(myimage(:)))]);
sliderMin = -100;
sliderMax = 100;
sliderMinMap = pmin - (pmax-pmin)*windowingSliderPadding(1);
sliderMaxMap = pmax + (pmax-pmin)*windowingSliderPadding(2);
% Text saying window max
WinMax = uicontrol('Style','text',...
'BackgroundColor',bgcolor,...
'Position',[windowControlX-25,windowControlY-30-15-30,200,15],...
'String',['Window Max = ' num2str(pmax)]);
% Slider used for setting max window
WinMaxSlider = uicontrol('Style', 'slider',...
'Min',sliderMin,'Max',sliderMax,'Value',sliderMin+(sliderMax-sliderMin)*(windowingSliderPadding(1)+1)/(windowingSliderPadding(1)+1+windowingSliderPadding(2)),...
'SliderStep',[1/(sliderMax-sliderMin+1) 1/20],...
'Position',[windowControlX,windowControlY-30-15-30-20,150,20],...
'Callback', {@MaxSlider});
% Text saying window min
WinMin = uicontrol('Style','text',...
'BackgroundColor',bgcolor,...
'Position',[windowControlX-25,windowControlY-30-15-25-20-25,200,15],...
'String',['Window Min = ' num2str(pmin)]);
% Slider used for setting min window
WinMinSlider = uicontrol('Style', 'slider',...
'Min',sliderMin,'Max',sliderMax,'Value',sliderMin+(sliderMax-sliderMin)*(windowingSliderPadding(1))/(windowingSliderPadding(1)+1+windowingSliderPadding(2)),...
'SliderStep',[1/(sliderMax-sliderMin+1) 1/20],...
'Position',[windowControlX,windowControlY-30-15-25-20-25-20,150,20],...
'Callback', {@MinSlider});
% Reset Windowing Button
resetWindowing = uicontrol('Style','pushbutton',...
'String','Reset Windowing',...
'Position',[windowControlX+25,windowControlY-30-15-25-20-25-20-40,100,20],...
'Callback',{@window_reset});
% [right,up,wide,high]
% Radio Buttons
% Create the button group.
h = uibuttongroup('visible','off','Position',[.75 .52 .15 .15],'BackgroundColor',bgcolor);
% Create radio buttons in the button group.
r1 = uicontrol('Style','Radio','String','Magnitude','BackgroundColor',bgcolor,...
'pos',[5 65 80 20],'parent',h,'HandleVisibility','off');
r2 = uicontrol('Style','Radio','String','Phase','BackgroundColor',bgcolor,...
'pos',[5 45 80 20],'parent',h,'HandleVisibility','off');
r3 = uicontrol('Style','Radio','String','Real','BackgroundColor',bgcolor,...
'pos',[5 25 80 20],'parent',h,'HandleVisibility','off');
r4 = uicontrol('Style','Radio','String','Imaginary','BackgroundColor',bgcolor,...
'pos',[5 5 80 20],'parent',h,'HandleVisibility','off');
% Initialize some button group properties.
set(h,'SelectionChangeFcn',@selcbk);
set(h,'Visible','on');
switch image_type
case 'Magnitude'
set(h,'SelectedObject',[r1]);
case 'Phase'
set(h,'SelectedObject',[r2]);
case 'Real'
set(h,'SelectedObject',[r3]);
case 'Imaginary'
set(h,'SelectedObject',[r4]);
end
function selcbk(source,eventdata)
ChangeType(get(eventdata.NewValue,'String'));
pmax = max(myimage(:));
pmin = min(myimage(:));
set(ImMin,'String',['Image Min = ' num2str(min(myimage(:)))]);
set(ImMax,'String',['Image Max = ' num2str(max(myimage(:)))]);
sliderMinMap = pmin - (pmax-pmin)*windowingSliderPadding(1);
sliderMaxMap = pmax + (pmax-pmin)*windowingSliderPadding(2);
set(WinMaxSlider,'Value',sliderMin+(sliderMax-sliderMin)*(windowingSliderPadding(1)+1)/(windowingSliderPadding(1)+1+windowingSliderPadding(2)));
set(WinMinSlider,'Value',sliderMin+(sliderMax-sliderMin)*(windowingSliderPadding(1))/(windowingSliderPadding(1)+1+windowingSliderPadding(2)));
display_all();
end
% vname = @(x) inputname(1);
% image_title = vname(myimage)
% Change units to normalized so components resize properly
set([h,r1,r2,r3,r4,resetWindowing,axs_draw,Slice_Text,Dimensions,dim1btn,dim2btn,dim3btn,slider,checkbox,Windowing_Text,ImMax,ImMin,WinMax,WinMaxSlider,WinMin,WinMinSlider],'Units','normalized');
% center gui
movegui(f,'center');
display_all();
% make gui visible
set(f,'Visible','on');
function display_all()
if close_old == 1
pos = get(findobj('type','figure','name',['Display 3D Data: ' myimage_title]),'Position');
if iscell(pos)
pos = cell2mat(pos(1));
end
set(f,'Position',pos);
close(findobj('type','figure','name',['Display 3D Data: ' myimage_title]));
close_old = 0;
end
set(f,'Name',['Display 3D Data: ' myimage_title]);
switch slice_dim,
case 1
if check
imshow(squeeze(myimage(cur_slice,:,size(myimage,3):-1:1))',[pmin pmax]);
else
imshow(squeeze(myimage(cur_slice,:,:)),[pmin pmax]);
end
set(dim1btn,'String',num2str(cur_slice));
set(dim2btn,'String',':');
set(dim3btn,'String',':');
case 2
if check
imshow(squeeze(myimage(:,cur_slice,size(myimage,3):-1:1))',[pmin pmax]);
else
imshow(squeeze(myimage(:,cur_slice,:)),[pmin pmax]);
end
set(dim1btn,'String',':');
set(dim2btn,'String',num2str(cur_slice));
set(dim3btn,'String',':');
case 3
if check
imshow(squeeze(myimage(:,size(myimage,2):-1:1,cur_slice))',[pmin pmax]);
else
imshow(squeeze(myimage(:,:,cur_slice)),[pmin pmax]);
end
set(dim1btn,'String',':');
set(dim2btn,'String',':');
set(dim3btn,'String',num2str(cur_slice));
end
set(slider,'Value',cur_slice);
set(WinMaxSlider,'Value',(pmax - sliderMinMap)/(sliderMaxMap-sliderMinMap)*(sliderMax-sliderMin)+sliderMin);
set(WinMinSlider,'Value',(pmin - sliderMinMap)/(sliderMaxMap-sliderMinMap)*(sliderMax-sliderMin)+sliderMin);
set(WinMax,'String',['Window Max = ' num2str(pmax,4)]);
set(WinMin,'String',['Window Min = ' num2str(pmin,4)]);
title(myimage_title);
titlehandle = get(gca, 'title');
set(titlehandle, 'FontSize', 11)
end
function ChangeType(Type)
switch Type
case 'Magnitude'
myimage = abs(myimageIn);
case 'Phase'
myimage = unwrap(angle(myimageIn));
case 'Real'
myimage = real(myimageIn);
case 'Imaginary'
myimage = imag(myimageIn);
end
end
function dim1btn_press(source,eventdata)
str = get(source,'String');
if str == ':'
slice_dim = 1;
cur_slice = round(mysize(slice_dim)/2);
set(slider,'Max',mysize(slice_dim));
set(slider,'SliderStep',[1/mysize(slice_dim) 1/20]);
end
display_all();
end
function dim2btn_press(source,eventdata)
str = get(source,'String');
if str == ':'
slice_dim = 2;
cur_slice = round(mysize(slice_dim)/2);
set(slider,'Max',mysize(slice_dim));
set(slider,'SliderStep',[1/mysize(slice_dim) 1/20]);
end
display_all();
end
function dim3btn_press(source,eventdata)
str = get(source,'String');
if str == ':'
slice_dim = 3;
cur_slice = round(mysize(slice_dim)/2);
set(slider,'Max',mysize(slice_dim));
set(slider,'SliderStep',[1/mysize(slice_dim) 1/20]);
end
display_all();
end
function slider_action(source,eventdata)
cur_slice = round(get(source,'Value'));
display_all();
end
function checkbox_click(source,eventdata)
check = get(source,'Value');
display_all();
end
function click_callback(source,eventdata)
if strcmp(get(source,'SelectionType'),'normal')
%left click
prev_click = 0;
cur_slice = cur_slice - 1;
if cur_slice < 1,
cur_slice = 1;
end
elseif strcmp(get(source,'SelectionType'),'alt')
%right click
prev_click = 1;
cur_slice = cur_slice + 1;
if cur_slice > size(myimage,slice_dim),
cur_slice = size(myimage,slice_dim);
end
elseif strcmp(get(source,'SelectionType'),'open')
if prev_click == 0
%left click
cur_slice = cur_slice - 1;
if cur_slice < 1,
cur_slice = 1;
end
else
%right click
cur_slice = cur_slice + 1;
if cur_slice > size(myimage,slice_dim),
cur_slice = size(myimage,slice_dim);
end
end
end
display_all();
end
function MaxSlider(source,eventdata)
pmax = (get(source,'Value') - sliderMin)/(sliderMax-sliderMin)*(sliderMaxMap-sliderMinMap)+sliderMinMap;
if pmax > sliderMaxMap
pmax = sliderMaxMap;
end
if pmax <= pmin
pmax = pmin + (sliderMaxMap-sliderMinMap)/(sliderMax-sliderMin);
end
display_all();
end
function MinSlider(source,eventdata)
pmin = (get(source,'Value') - sliderMin)/(sliderMax-sliderMin)*(sliderMaxMap-sliderMinMap)+sliderMinMap;
if pmin < sliderMinMap
pmin = sliderMinMap;
end
if pmin >= pmax
pmin = pmax - (sliderMaxMap-sliderMinMap)/(sliderMax-sliderMin);
end
display_all();
end
function window_reset(source,eventdata)
pmax = max(myimage(:));
pmin = min(myimage(:));
display_all();
end
end
|
github | michaelmendoza/deep-ssfp-master | convert_knee.m | .m | deep-ssfp-master/legacy/data/convert_knee.m | 1,455 | utf_8 | 8ed61fc7cd6594d7e51221332f7bfa0f | % Converts data files to training data in a .mat
%basepath = "./10282017_SSPF Smoothing DL/";
%filenames = ["meas_MID885_trufi_phi0_FID4833.dat", "meas_MID894_trufi_phi90_FID4842.dat", ...
% "meas_MID903_trufi_phi180_FID4851.dat", "meas_MID912_trufi_phi270_FID4860.dat"];
basepath = "./Merry_SSFP_Scans/ssfpknee/";
filenames = ["meas_MID40_SSFPdjp_TR5_4_TE2_7_PC0_FA15_FID1540.dat","meas_MID42_SSFPdjp_TR5_4_TE2_7_PC90_FA15_FID1542.dat", ...
"meas_MID44_SSFPdjp_TR5_4_TE2_7_PC180_FA15_FID1544.dat", "meas_MID46_SSFPdjp_TR5_4_TE2_7_PC270_FA15_FID1546.dat"];
for f = 1:length(filenames)
f
filepath = strcat(basepath, filenames(f));
im = loadImg(filepath);
figure(f);
imshow(abs(im(:,:,4)),[]);
if(f == 1)
s = size(im);
imgs = zeros(s(1), s(2), s(3), length(filenames));
end
imgs(:,:,:,f) = im;
end
s = size(imgs);
em = zeros(s(1), s(2), s(3));
for ss = 1:s(3)
ss
im1 = imgs(:,:,ss,1); im2 = imgs(:,:,ss,2);
im3 = imgs(:,:,ss,3); im4 = imgs(:,:,ss,4);
em(:,:,ss) = EllipticalModel(im1, im2, im3, im4);
end
figure(6);
imshow(abs(em(:,:,4)), []);
save('trainDataLeg.mat', 'imgs', 'em');
function im = loadImg(filepath)
img = readMeasDataVB15(filepath);
s = size(img);
im = zeros(s(1), s(2), s(3));
for n = 1:s(4)
imgn = img(:,:,:,n);
imgn = fft3c(imgn);
im = im + imgn;
end
im = im / s(4);
end |
github | michaelmendoza/deep-ssfp-master | convert.m | .m | deep-ssfp-master/legacy/data/convert.m | 1,359 | utf_8 | 5e850290e48de5f7efdf62b6fb9e5072 | % Converts data files to training data in a .mat
basepath = "./11062017_SSFP_Smoothing_DL_Phantom/";
filenames = ["meas_MID164_trufi_phi0_FID6709.dat", "meas_MID165_trufi_phi90_FID6710.dat", ...
"meas_MID166_trufi_phi180_FID6711.dat", "meas_MID167_trufi_phi270_FID6712.dat"];
for f = 1:length(filenames)
f
filepath = strcat(basepath, filenames(f));
im = loadImg(filepath);
figure(f);
imshow(abs(im(:,:,64)),[]);
if(f == 1)
s = size(im);
imgs = zeros(s(1), s(2), s(3), length(filenames));
end
imgs(:,:,:,f) = im;
end
ss = imgs(:,:,:,1) .* imgs(:,:,:,1);
ss = ss + imgs(:,:,:,2) .* imgs(:,:,:,2);
ss = ss + imgs(:,:,:,3) .* imgs(:,:,:,3);
ss = ss + imgs(:,:,:,4) .* imgs(:,:,:,4);
figure(5);
imshow(abs(ss(:,:,64)), []);
s = size(imgs);
em = zeros(s(1), s(2), s(3));
for ss = 1:s(3)
ss
im1 = imgs(:,:,ss,1); im2 = imgs(:,:,ss,2);
im3 = imgs(:,:,ss,3); im4 = imgs(:,:,ss,4);
em(:,:,ss) = EllipticalModel(im1, im2, im3, im4);
end
figure(6);
imshow(abs(em(:,:,64)), []);
save('trainData.mat', 'imgs', 'em');
function im = loadImg(filepath)
img = readMeasDataVB15(filepath);
s = size(img);
im = zeros(s(1), s(2), s(3));
for n = 1:s(4)
imgn = img(:,:,:,n);
imgn = fft3c(imgn);
im = im + imgn;
end
im = im / s(4);
end |
github | michaelmendoza/deep-ssfp-master | EllipticalModel.m | .m | deep-ssfp-master/legacy/data/EllipticalModel.m | 2,709 | utf_8 | a4d235313127dec6afb2c22822e3a397 | % This function will attempt to follow the ellpitical signal model in the
% paper by Xiang, Qing-San and Hoff, Michael N. "Banding Artifact Removal
% for bSSFP Imaging with an Elliptical Signal Model", 2014.
% The function returns a complex image.
%
% I1 and I3 form one pair of 180 degree offset images, and I2 and I4 form
% the other pair.
function I = EllipticalModel(I1, I2, I3, I4)
% Iterate through each pixel and calculate M directly; then compare it to
% the maximum magnitude of all four input images. If it is greater,
% replace it with the complex sum value.
M = zeros(size(I1));
maximum = max(abs(I1), abs(I2));
maximum = max(abs(I3), maximum);
maximum = max(abs(I4), maximum);
CS = (I1 + I2 + I3 + I4) / 4;
for k = 1:size(I1,1)
for n = 1:size(I1,2)
M(k,n) = ((real(I1(k,n))*imag(I3(k,n)) - real(I3(k,n))*imag(I1(k,n)))*...
(I2(k,n) - I4(k,n)) - (real(I2(k,n))*imag(I4(k,n)) - real(I4(k,n))*...
imag(I2(k,n)))*(I1(k,n) - I3(k,n))) / ((real(I1(k,n)) - real(I3(k,n)))*...
(imag(I2(k,n)) - imag(I4(k,n))) + (real(I2(k,n)) - real(I4(k,n)))*...
(imag(I3(k,n)) - imag(I1(k,n)))); % Equation (13)
if (abs(M(k,n)) > maximum(k,n)) || isnan(M(k,n))
M(k,n) = CS(k,n); % This removes the really big singularities; without this the image is mostly black.
end
end
end
% Calculate the weight w for each pixel.
w1 = zeros(size(I1));
w2 = zeros(size(I1));
for k = 1:size(I1,1)
for n = 1:size(I1,2)
numerator1 = 0;
denominator1 = 0;
numerator2 = 0;
denominator2 = 0;
for x = -2:2
a = k + x;
for y = -2:2
b = n + y;
if (a < 1) || (b < 1) || (a > size(I1,1)) || (b > size(I1,2))
else
numerator1 = numerator1 + conj(I3(a,b) - M(a,b)) * (I3(a,b) - I1(a,b)) + ...
conj(I3(a,b) - I1(a,b)) * (I3(a,b) - M(a,b));
denominator1 = denominator1 + conj(I1(a,b) - I3(a,b)) * (I1(a,b) - I3(a,b));
numerator2 = numerator2 + conj(I4(a,b) - M(a,b)) * (I4(a,b) - I2(a,b)) + ...
conj(I4(a,b) - I2(a,b)) * (I4(a,b) - M(a,b));
denominator2 = denominator2 + conj(I2(a,b) - I4(a,b)) * (I2(a,b) - I4(a,b));
end
end
end
w1(k,n) = numerator1 / (2 * denominator1); % Equation (18) - first pair
w2(k,n) = numerator2 / (2 * denominator2); % Equation (18) - second pair
end
end
% Calculate the average weighted sum of image pairs.
I = (I1 .* w1 + I3 .* (1 - w1) + I2 .* w2 + I4 .* (1 - w2)) / 2; % Equation (14) - averaged
end |
github | vnnsrk/UCSD-master | q63.m | .m | UCSD-master/CSE 250A/hw6/Code/q63.m | 464 | utf_8 | 59831ecfacd5a21c7877dfc286d43907 | clc;
clear all;
close all;
x=-5:0.1:5;
f1 = fx(x);
Q1 = Qxy(x,-2);
Q2 = Qxy(x,3);
% Auxiliary functions
figure;
set(gcf,'color','w');
plot(x,f1,x,Q1,x,Q2);
grid on;
title('Plot of auxiliary functions');
xlabel('x');
ylabel('Function value');
legend('f (x)','Q (x, -2)','Q (x, 3)');
%% Helper functions
% Given function
function op=fx(x)
op = log(cosh(x));
end
% Auxiliary function
function op = Qxy(x, y)
op = fx(y) + (tanh(y)*(x-y)) + (0.5*(x-y).^2);
end |
github | vnnsrk/UCSD-master | computeSentenceProbabilities.m | .m | UCSD-master/CSE 250A/hw4/Code/computeSentenceProbabilities.m | 1,613 | utf_8 | 3645c0a44eddebf5ef21bbdd5ed5c342 | %% Function to compute probability of sentence
% Compute probability of words in a sentence using unigram and bigram
% models
function [uLog, bLog, pU, pB] = computeSentenceProbabilities(sentence, tokens, bigram)
% Make array of words in sentence
wordsU = strsplit(sentence);
beginSent = {'<s>'};
wordsB = [beginSent wordsU];
% Log-likelihood using unigram model
pWords = 1;
for i = 1:length(wordsU)
tmpInd = find(strcmp(tokens.words, wordsU{i}));
% If word not in vocab, assign "unknown" token
if(isempty(tmpInd))
tmpInd = 1;
end
pU(i) = tokens.priors(tmpInd);
% Compute unigram probability
pWords = pWords* pU(i);
end
uLog = log(pWords);
% Log-likelihood using bigram model
pWords = 1;
for i = 2:length(wordsB)
w1 = wordsB{i-1};
w2 = wordsB{i};
% Find index of adjacent words
ind1 = find(strcmp(tokens.words, w1));
if(isempty(tmpInd))
ind1 = 1;
end
ind2 = find(strcmp(tokens.words, w2));
if(isempty(tmpInd))
ind2 = 1;
end
cnt = 0;
% Find counts of this pair
for j = 1:length(bigram.count)
if((bigram.ind1(j) == ind1) && (bigram.ind2(j) == ind2))
cnt = bigram.count(j);
break;
end
end
% Compute bigram probability
pB(i-1) = (cnt / tokens.counts(ind1));
pWords = pWords*pB(i-1);
end
bLog = log(pWords);
end |
github | harsh-agarwal/understanding_CRF_using_GMM-master | calculate_the_likelihood_of_sketch_same_feature_neighbour_added.m | .m | understanding_CRF_using_GMM-master/calculate_the_likelihood_of_sketch_same_feature_neighbour_added.m | 8,715 | utf_8 | 092e0110e856bc10a13864bce895df98 | %% calculates the likelihood of a particular cnfciguration
%% for instance given a feature you calculated the you calculated it's likelihood of being a head and at the same time
%% it's likelohood of having leg as it's neighnour based on the training data that you have seen!
function [likelihood_matrix_part_wise,likelihood_matrix_pairwise,likelihood_matrix_neighbour]=calculate_the_likelihood_of_sketch_same_feature_neighbour_added(category,lab,segment_into_regions_without_annotations)
%% the idea is to consider the same approach just to penalise
%% this energy function if it destroys the relation between the neighbourhood matrix
% removing background
likelihood_matrix_part_wise = zeros(1,2);
segments_original = unique(segment_into_regions_without_annotations);
segments_original = segments_original(segments_original~=0);
individual_part_features = zeros(length(segments_original),5);
% we try getting the dimensions of a neighbourhood matrix that would
% define how stable the connectrivity becomes
load(sprintf('../part_labellings_for_sketches/%s.mat',category));
parts_total=parts_total(parts_total~=0);
size_of_neighbourhood_graph=max(parts_total);
neighbourhood_graph_now=zeros(size_of_neighbourhood_graph);
%% calculate the individual features and store them so that for pair wise you just have to concatenate
for j=1:length(segments_original)
% area of the object for relative area measurements
object_canvas=ones(321,321);
object_canvas(segment_into_regions_without_annotations==0)=0;
prop=regionprops(object_canvas,'Area');
area_of_object=prop.Area;
%find the regions that has this segment
idx=find(segment_into_regions_without_annotations==segments_original(j));
% will help us loading the relevant gaussian model
part_labelling_segment=unique(lab(idx));
% part feature calculation
part_canvas1=zeros(321,321);
part_canvas1(idx)=1;
properties=regionprops(part_canvas1,'Centroid','Area','Perimeter','Orientation','MajorAxisLength','MinorAxisLength',...
'Eccentricity');
centroid_of_part=(properties.Centroid)/10;
relative_area=(area_of_object)/(properties.Area);
roundedness=(properties.Perimeter)^2/(properties.Area);
individual_part_features(j,:)=[centroid_of_part(1) centroid_of_part(2) relative_area roundedness segments_original(j)];
%% load the relevant gaussian model and find a probability and then a likelihood and append that
load(sprintf('./Part_feature_gaussian_fits/%s/%d-GMM_model-3.mat',category,part_labelling_segment));
Y=mvnpdf(individual_part_features(j,1:4),gmm_model.mu,gmm_model.Sigma);
likelihood_matrix_part_wise=[likelihood_matrix_part_wise;segments_original(j) max(log(Y))];
end
likelihood_matrix_part_wise=likelihood_matrix_part_wise(2:end,:);
% number of pairs and what all
likelihood_matrix_pairwise=zeros(1,3);
if(length(segments_original)>1)
all_two_part_combinations=nchoosek(segments_original,2);
number_of_combinations_of_two_parts=nchoosek(length(segments_original),2);
likelihood_matrix_pairwise=zeros(1,3);
for j=1:number_of_combinations_of_two_parts
%segment1 what's the original labelling
segment1=all_two_part_combinations(j,1);
idx=find(segment_into_regions_without_annotations==segment1);
part_canvas1=zeros(321,321);
part_canvas1(idx)=1;
part_labelling_segment1=unique(lab(idx));
segment2=all_two_part_combinations(j,2);
idx=find(segment_into_regions_without_annotations==segment2);
part_canvas2=zeros(321,321);
part_canvas2(idx)=1;
part_labelling_segment2=unique(lab(idx));
% for instance they both represent head the we don't waant this
% feature vector
if(part_labelling_segment1==part_labelling_segment2)
continue;
end
[row1,col1]=find(individual_part_features(:,5)==segment1);
[row2,col2]=find(individual_part_features(:,5)==segment2);
base_feature1=individual_part_features(row1,1:4);
base_feature2=individual_part_features(row2,1:4);
% once here we know that the two segments represent different parts
%% let's calculate the feature vector
final_pairwise_feature=[base_feature1(1:4) base_feature2(1:4) segment1 segment2];
% load the gmm model that has the onformation related to these
% parts
if(part_labelling_segment1<part_labelling_segment2)
a=part_labelling_segment1;
b=part_labelling_segment2;
else
a=part_labelling_segment2;
b=part_labelling_segment1;
end
load(sprintf('./Pairwise_feature_gaussian_fits/%s/%d,%d-GMM_model-3.mat',category,a,b));
Y=mvnpdf(final_pairwise_feature(1:8),gmm_model.mu,gmm_model.Sigma);
likelihood_matrix_pairwise=[likelihood_matrix_pairwise;segment1 segment2 max(log(Y))];
combined=part_canvas1+part_canvas2;
cc=bwconncomp(combined);
if(cc.NumObjects==1)
neighbourhood_graph_now(part_labelling_segment1,part_labelling_segment2)=neighbourhood_graph_now(part_labelling_segment1,part_labelling_segment2)+1;
neighbourhood_graph_now(part_labelling_segment2,part_labelling_segment1)=neighbourhood_graph_now(part_labelling_segment2,part_labelling_segment1)+1;
end
end
likelihood_matrix_pairwise=likelihood_matrix_pairwise(2:end,:);
end
likelihood_matrix_neighbour=zeros(length(segments_original),2);
% load the avg neighbourhood matrix
load(sprintf('./mean_neighbourhood_matrices/%s/%s.mat',category,category));
for j=1:length(segments_original)
deviation=neighbourhood_graph_now-avg_neighbourhood_matrix;
deviation=abs(deviation);
idx=find(segment_into_regions_without_annotations==segments_original(j));
part_label_of_this_segment=unique(lab(idx));
likelihood_matrix_neighbour(j,2)=-log(sum(deviation(part_label_of_this_segment,:),2))*10;
end
end
%line 62
% area of the object for relative area
% object_canvas=ones(321,321);
% object_canvas(segment_into_regions_without_annotations==0)=0;
% prop=regionprops(object_canvas,'Area');
% area_of_object=prop.Area;
%
% %find the regions that has segment 1
% idx=find(segment_into_regions_without_annotations==segment1);
% part_canvas1=zeros(321,321);
% part_canvas1(idx)=1;
% properties1=regionprops(part_canvas1,'Centroid','Area','Perimeter','Orientation','MajorAxisLength','MinorAxisLength',...
% 'Eccentricity');
% ellipse_part1_mask=fitting_the_ellipse(properties1);
% centroid_of_part=(properties1.Centroid)/10;
% relative_area=(area_of_object)/(properties1.Area);
% roundedness=(properties1.Perimeter)^2/(properties1.Area);
% base_feature1=[centroid_of_part(1) centroid_of_part(2) relative_area roundedness segment1];
%
% %find the regions that has segment 2
% idx=find(segment_into_regions_without_annotations==segment2);
% part_canvas2=zeros(321,321);
% part_canvas2(idx)=1;
% properties2=regionprops(part_canvas2,'Centroid','Area','Perimeter','Orientation','MajorAxisLength','MinorAxisLength',...
% 'Eccentricity');
% ellipse_part2_mask=fitting_the_ellipse(properties2);
% centroid_of_part=(properties2.Centroid)/10;
% relative_area=(area_of_object)/(properties2.Area);
% roundedness=(properties2.Perimeter)^2/(properties2.Area);
% base_feature2=[centroid_of_part(1) centroid_of_part(2) relative_area roundedness segment2];
%
% % overlap=ellipse_part1_mask.*ellipse_part2_mask;
% % overlap_prop=regionprops(overlap,'Area');
% % if(isempty(overlap_prop)==1)
% % overlap_area=0;
% % else
% % overlap_area=overlap_prop.Area;
% % end
% % final_feature=[base_feature1(1:4) double(overlap_area)/double(properties1.Area) base_feature2(1:4) double(overlap_area)/double(properties2.Area)]; |
github | harsh-agarwal/understanding_CRF_using_GMM-master | Cls2Part.m | .m | understanding_CRF_using_GMM-master/Cls2Part.m | 2,039 | utf_8 | 828d1f873f20ef2642ca139587d2e2a8 | % helps you in defining which parts to annotate and by what!
function mapping = Cls2Part(ClasName)
switch ClasName,
case 'aeroplane'
%mapping.Parts = {'body', 'wing', 'tail', 'engine', 'wheel'};
mapping.Parts = {'body', 'wheels', 'tail', 'engine', 'wings'};
case 'bottle'
mapping.Parts = {'body'};
case 'cat'
mapping.Parts = {'head', 'body', 'leg', 'tail'};
case 'chair'
mapping.Parts = {'body'};
case 'diningtable'
mapping.Parts = {'body'};
case 'dog'
mapping.Parts = {'head', 'body', 'leg', 'tail'};
case 'cow'
mapping.Parts = {'head', 'body', 'leg', 'tail'};
case 'sheep'
mapping.Parts = {'head', 'body', 'leg', 'tail'};
case 'horse'
mapping.Parts = {'head', 'body', 'leg', 'tail'};
case 'person'
mapping.Parts = {'head', 'body', 'arm', 'leg'};
case 'pottedplant'
mapping.Parts = {'pot','plant'};
case 'bird'
mapping.Parts = {'body','dont care','tail','dont care','dont care','head','leg','wing'};
case 'bicycle'
mapping.Parts = {'wheel','saddle','handlebar','body'};
case 'bus'
mapping.Parts = {'body','mirror','window','wheel','headlight','door'};
case 'car'
mapping.Parts = {'body','mirror','window','wheel','headlight','door'};
case 'motorbike'
mapping.Parts = {'wheel','saddle','handlebar','body'};
case 'train'
mapping.Parts = {'body','dont care','dont care','dont care','headlight'};
case 'tvmonitor'
mapping.Parts = {'screen'};
case 'sofa'
mapping.Parts = {};
case 'boat'
mapping.Parts = {};
end
|
github | harsh-agarwal/understanding_CRF_using_GMM-master | fitting_the_ellipse.m | .m | understanding_CRF_using_GMM-master/fitting_the_ellipse.m | 716 | utf_8 | 95f4eba2dba10e00a738c56c5ca0b6e8 |
%% would give me the closest fitting ellipse that could fit into a particular part
function [mask] = fitting_the_ellipse(s)
phi=linspace(0,2*pi,50);
cosphi=cos(phi);
sinphi=sin(phi);
for k=1:length(s)
xbar=s(k).Centroid(1);
ybar=s(k).Centroid(2);
a=s(k).MajorAxisLength/2;
b=s(k).MinorAxisLength/2;
theta=pi*s(k).Orientation/180;
R=[ cos(theta) sin(theta)
-sin(theta) cos(theta)] ;
xy=[a*cosphi;b*sinphi];
xy=R*xy;
x=xy(1,:) + xbar;
y=xy(2,:) + ybar;
mask=poly2mask(x,y,321,321);
%imshow(mask);
end
end
|
github | harsh-agarwal/understanding_CRF_using_GMM-master | calculation_avg_neighbourhood_matrix.m | .m | understanding_CRF_using_GMM-master/calculation_avg_neighbourhood_matrix.m | 3,073 | utf_8 | b06e750d3236af1f955aad1235d43755 | % the script gives us a average neighbourhood graph
% for instance given a head how likely it is for it to have torso as it's neighbour, or the legs based on the training data
function calculation_avg_neighbourhood_matrix(category)
if((exist(sprintf('./mean_neighbourhood_matrices/%s',category),'dir'))==0)
mkdir(sprintf('./mean_neighbourhood_matrices/%s',category));
end
%get the list of mirrored and original images
fid=fopen(sprintf('../train_val_lists/chosen_train_%s_list.txt',category),'r');
gt_images=textscan(fid,'%s');
disp(category);
%part combination are to be considered and accordingly the features are
%to be formed by concatenating the individual features together
load(sprintf('../part_labellings_training_data/%s.mat',category));
parts_total = parts_total(parts_total~=0);
neighbourhood_graph_each=zeros(max(parts_total));
%% For each image we segment it an dtry building upon the neighbourhood graph
for i=1:length(gt_images{1,1})
%load each GT image
img_name_considered=char(gt_images{1,1}{i,1});
if(img_name_considered(1)=='n')
image=imread(sprintf('../GT_core/%s.png',char(gt_images{1,1}{i,1})));
else
image=imread(sprintf('../GT_pascal/%s.png',char(gt_images{1,1}{i,1})));
end
segmented_image = segmentation_into_regions(image);
segments_present = unique(segmented_image);
% background is obvious
segments_present = segments_present(segments_present~=0);
all_two_pair_combination=nchoosek(segments_present,2);
number_of_two_pair_combination=nchoosek(length(segments_present),2);
for j=1:number_of_two_pair_combination
%find_part_1
part_canvas1 = zeros(321);
idx = find(segmented_image==all_two_pair_combination(j,1));
part_canvas1(idx)=1;
part_labelling_segment1 = unique(image(idx));
part_canvas2 = zeros(321);
idx = find(segmented_image==all_two_pair_combination(j,2));
part_canvas2(idx) = 1;
part_labelling_segment2 = unique(image(idx));
if(part_labelling_segment1 == part_labelling_segment2)
continue;
end
combined=part_canvas1+part_canvas2;
cc=bwconncomp(combined);
if(cc.NumObjects==1)
neighbourhood_graph_each(part_labelling_segment1,part_labelling_segment2) = neighbourhood_graph_each...
(part_labelling_segment1,part_labelling_segment2)+1;
neighbourhood_graph_each(part_labelling_segment2,part_labelling_segment1) = neighbourhood_graph_each...
(part_labelling_segment2,part_labelling_segment1)+1;
end
end
end
avg_neighbourhood_matrix=neighbourhood_graph_each/length(gt_images{1,1});
save(sprintf('./mean_neighbourhood_matrices/%s/%s.mat',category,category),'avg_neighbourhood_matrix');
end |
github | harsh-agarwal/understanding_CRF_using_GMM-master | to_annotate_ten_sketches.m | .m | understanding_CRF_using_GMM-master/to_annotate_ten_sketches.m | 1,108 | utf_8 | 5f380b702d3077e821ec37e032c286c7 | %% got some data for the SVM
function to_annotate_ten_sketches(category)
img_list=dir(sprintf('../results_test_segmentation/raw_output_part_merged/%s_10000',category));
for i=3:12
load(sprintf('./training_for_certainity_and_uncertainity_of_segments/%s/%s.mat',category,char(img_list(i).name(1:end-4))));
load(sprintf('../results_test_segmentation/raw_output_part_merged/%s_10000/%s.mat',category,char(img_list(i).name(1:end-4))));
segmented_from_net=segmentation_into_regions(lab);
[part_probability,pairwise_probability,neighbourhood_probability]=calculate_the_likelihood_of_sketch_same_feature_neighbour_added(category,lab,segmented_from_net);
training_matrix(:,2)=part_probability(:,2);
training_matrix=[training_matrix,neighbourhood_probability(:,2)];
save(sprintf('./training_for_certainity_and_uncertainity_of_segments/%s/%s.mat',category,char(img_list(i).name(1:end-4))),'training_matrix');
%annotating_certain_and_uncertain_segments(category,char(img_list(i).name(1:end-4)));
%waitforbuttonpress;
end |
github | harsh-agarwal/understanding_CRF_using_GMM-master | post_process.m | .m | understanding_CRF_using_GMM-master/post_process.m | 975 | utf_8 | d1e14f87db9664d776542119c8ddc33a | %% the function to call to final post process
function post_process(category)
%create an image list
img_list = dir(sprintf('../results_test_segmentation/raw_output_part_merged/%s_10000',category));
%in a for loop take ech and every image and load the following
%corresponding file
disp(category);
for i=13:length(img_list)
load(sprintf('../results_test_segmentation/raw_output_part_merged/%s_10000/%s.mat',category,char(img_list(i).name(1:end-4))));
%replacement_via_neighbourhood_all_replace(category,char(img_list(i).name(1:end-4)),lab);
replacement_via_neighbourhood_same_feature_neighbourhood_added(category,char(img_list(i).name(1:end-4)),lab);
end
%load(sprintf('../results_test_segmentation/raw_output_part_merged/%s_10000/%s.mat',category,img_name));
%this would create a variable named as lab in the workspace so use it
%as an arguement for replacement_via_neighbourhood
end |
github | harsh-agarwal/understanding_CRF_using_GMM-master | show_segmented_image.m | .m | understanding_CRF_using_GMM-master/show_segmented_image.m | 1,014 | utf_8 | c195d77d389adcb0b867655dc949753c | %5 a head can have two blobs a code to visualise the segmented image
function show_segmented_image(lab,segmented)
image_orig=visualise_the_new_obtained_segmentation(lab);
count_total_regions=length(unique(segmented));
segment_number_present=unique(segmented);
segment_number_present=segment_number_present(segment_number_present~=0);
position_of_text=zeros(count_total_regions-1,2);
% calculating the position of the text
for n=1:count_total_regions-1
idx=find(segmented==n);
if(isempty(idx))
continue;
end
part_canvas=zeros(321,321);
part_canvas(idx)=1;
properties=regionprops(part_canvas);
position_of_text(n,:)= properties.Centroid;
end
%play the segmenteed image
figure;
img_with_parts_shown=insertText(image_orig,position_of_text,segment_number_present,...
'AnchorPoint','Center','TextColor','Black','BoxColor','white');
imshow(img_with_parts_shown);
|
github | harsh-agarwal/understanding_CRF_using_GMM-master | visualise_the_new_obtained_segmentation.m | .m | understanding_CRF_using_GMM-master/visualise_the_new_obtained_segmentation.m | 891 | utf_8 | 8f0b3148687fc411fb1a4d6e14bac30b | %% helps in visualising the segmentation that we have! Nomenclature a bit confusing
function [rlab]=visualise_the_new_obtained_segmentation(copy_lab)
copy_lab=copy_lab+1;
colors=[0,0,0; % backgorund
127,219,255; % sky blue
133,20,75; % maroon type
255,133,27; % brownish colour
237,247,37; % yellow
46,204,64; % Green
186,186,173; % grey
255,51,255; % Pink
122,82,82; % Combination of red and gray
255,255,255]; % White
unique(copy_lab);
R=copy_lab;G=copy_lab;B=copy_lab;
limit = max(max(R));
for k=1:limit
R(R==k) = colors(k,1);
G(G==k) = colors(k,2);
B(B==k) = colors(k,3);
end
rlab = im2uint16(uint8(cat(3,R,G,B)));
end
|
github | harsh-agarwal/understanding_CRF_using_GMM-master | to_fit_svm_on_data.m | .m | understanding_CRF_using_GMM-master/to_fit_svm_on_data.m | 858 | utf_8 | 65f62c69fec3a4c9e8c529c48d078c38 | %% training the SVM
function to_fit_svm_on_data(category)
if((exist(sprintf('./svm_models'),'dir'))==0)
mkdir(sprintf('./svm_models'));
end
if((exist(sprintf('./svm_models/%s',category),'dir'))==0)
mkdir(sprintf('./svm_models/%s',category));
end
img_list=dir(sprintf('./training_for_certainity_and_uncertainity_of_segments/%s',category));
X=[0 0];
Y=[0];
for i=3:length(img_list)
load(sprintf('./training_for_certainity_and_uncertainity_of_segments/%s/%s.mat',category,char(img_list(i).name(1:end-4))));
X1=training_matrix(:,2);
X2=training_matrix(:,4);
Y1=training_matrix(:,3);
X=[X;X1 X2];
Y=[Y;Y1];
end
X=X(2:end,:);
Y=Y(2:end,:);
svm_mdl=fitcsvm(X,Y);
save(sprintf('./svm_models/%s.mat',category),'svm_mdl');
end |
github | harsh-agarwal/understanding_CRF_using_GMM-master | calculate_uncertain_segments.m | .m | understanding_CRF_using_GMM-master/calculate_uncertain_segments.m | 445 | utf_8 | cee38d89d4a621ce47f5a7545d1171db | % we had trained an SVM model that would help us in categorising if given a part_probability whether it is
% cetain or incertain wbout the prediction!
function [uncertain_segments_index]=calculate_uncertain_segments(category,part_probability)
load(sprintf('svm_models/%s.mat',category));
certainity_uncertainity_matrix=predict(svm_mdl,part_probability(:,2));
uncertain_segments_index=find(certainity_uncertainity_matrix==0); |
github | jakobsj/AIRToolsII-master | calc_relaxpar.m | .m | AIRToolsII-master/auxil/calc_relaxpar.m | 8,628 | utf_8 | 68e147dc758570e549cad05da2780807 | function [relaxpar, casel, rho] = ...
calc_relaxpar(relaxparinput, rho, kmax, atma, n)
%CALC_RELAXPAR Compute the relaxation parameter for all methods
%
% relaxpar = calc_relaxpar(relaxparinput)
% [relaxpar, casel, rho] = ...
% calc_relaxpar(relaxparinput, rhoinput, kmax, atma, n)
%
% The short form is used by art and cart and sets the relaxpar either to
% default values of 1 or 0.25, respectively, or assigns a value given by
% the user. If the value given by the user is outside the allowed interval,
% a warning is given.
%
% The long form is used by sirt, and inputs and outputs are explained below.
%
% Input:
% relaxparinput Any relaxation parameter or flag determining method
% to use for determining relaxpar as specified by user.
% rho The spectral radius of the iteration matrix, if given
% by user.
% kmax The maximum number of SIRT iterations.
% atma A function handle to the iteration matrix that
% characterizes the SIRT method, for which to compute
% the spectral radius.
% n The number of columns in A.
%
% Output:
% relaxpar The computed relaxation parameter, or a vector of
% iteration-dependent relaxation parameters.
% casel A flag indicating whether a constant lambda is
% returned (casel=1), line search is to be used (casel=2)
% or the psi1/psi2 strategies to be used (casel=3).
% rho Computed spectral radius of the iteration matrix.
%
% See also: art, cart, sirt
% Code written by: Per Christian Hansen, Jakob Sauer Jorgensen, and
% Maria Saxild-Hansen, 2010-2017.
% This file is part of the AIR Tools II package and is distributed under
% the 3-Clause BSD License. A separate license file should be provided as
% part of the package.
%
% Copyright 2017 Per Christian Hansen, Technical University of Denmark and
% Jakob Sauer Jorgensen, University of Manchester.
% First determine whether called from art, cart or sirt. Just testing for
% the specific method name such as cimmino would not cover the case of
% custom methods.
stack = dbstack;
switch stack(2).name
case 'art'
% Default choice 1. If user gave as input, use that value and
% throw warning if outside [0,2], but proceed.
if isempty(relaxparinput)
relaxpar = 1;
elseif isnumeric(relaxparinput)
if (relaxparinput <= 0 || relaxparinput >= 2)
warning('MATLAB:UnstableRelaxParam',...
'The relaxpar value is outside the interval (0,2)');
end
relaxpar = relaxparinput;
elseif isa(relaxparinput,'function_handle')
relaxpar = -1000; % Place holder; function handle will be used
else
error('MATLAB:IllegalRelaxParam',...
['For ART methods the relaxpar must be a scalar or ',...
'function handle.'])
end
case 'cart'
% Default choice 0.25. If user gave as input, use that value and
% throw warning if outside [0,2], but proceed.
if isempty(relaxparinput)
relaxpar = 0.25;
elseif isnumeric(relaxparinput)
if relaxparinput <= 0 || relaxparinput >= 2
warning('MATLAB:UnstableRelaxParam',...
'The relaxpar value is outside the interval (0,2)');
end
relaxpar = relaxparinput;
else
error('MATLAB:IllegalRelaxParam',...
'For CART methods the relaxpar must be a scalar.')
end
case 'sirt'
% Check if the spectral radius is given.
if isnan(rho)
% If not, calculate the largest singular value.
optionsEIGS.disp = 0;
optionsEIGS.tol = 1e-4;
% Save existing random number generator settings to be restored
% after having specified a fixed random seed. This ensures a
% deterministic result (eigs without this is non-deterministic
% due to starting vector chosen using rand).
scurr = rng(0);
rho = eigs(atma,n,1,'lm',optionsEIGS);
rng(scurr);
end
% Determine the relaxation parameter relaxpar.
% If relaxparinput is nan, set default.
if isempty(relaxparinput)
% Define a default constant relaxpar value.
relaxpar = 1.9/rho;
casel = 1;
% If relaxpar is a scalar.
elseif ~ischar(relaxparinput)
% Checks if the given constant lambde value is illegal.
if relaxparinput <= 0 || relaxparinput >= 2/rho
warning('MATLAB:UnstableRelaxParam',...
['The relaxpar value '...
'is outside the interval (0,%f)'],2/rho)
end
relaxpar = relaxparinput;
casel = 1;
else
% Calculate the relaxpar value according to the chosen method.
if strncmpi(relaxparinput,'line',4)
% Method: Line search.
casel = 2;
relaxpar = [];
elseif strncmpi(relaxparinput,'psi1',4)
% Method: ENH psi1.
casel = 3;
% Precalculate the roots.
z = calczeta(2:kmax-1);
% Define the values for relaxpar according to the psi1
% strategy modified or not.
if strncmpi(relaxparinput,'psi1mod',7)
nu = 2;
relaxpar = [sqrt(2); sqrt(2); nu*2*(1-z)]/rho;
else
relaxpar = [sqrt(2); sqrt(2); 2*(1-z)]/rho;
end
elseif strncmpi(relaxparinput,'psi2',4)
% Method: ENH psi2.
casel = 3;
% Precalculate the roots.
kk = 2:kmax-1;
z = calczeta(kk);
% Define the values for relaxpar according to the psi2
% strategy modified or not.
if strncmpi(relaxparinput,'psi2Mod',7)
nu = 1.5;
relaxpar = [sqrt(2); sqrt(2);
nu*2*(1-z)./((1-z.^(kk')).^2)]/rho;
else
relaxpar = [sqrt(2); sqrt(2);
2*(1-z)./((1-z.^(kk')).^2)]/rho;
end
else
error(['The chosen relaxation strategy is not valid '...
'for this method.'])
end % end check of the class of relaxpar.
end % end check of relaxpar strategies.
otherwise
error(['This aux. function is only to be called ',...
'from within art, cart or sirt.'])
end
function z = calczeta(k)
%CALCZETA Calculates a specific root of a certain polynomial
%
% z = calczeta(k)
%
% Calculates the unique root in the interval [0 1] of the polynomial equation
% (2k -1)z^{k-1} - ( z^{k-2} + ... + z + 1 ) = 0
% by means of Newton's method.
%
% Input:
% k either a sorted vector or a scalar that determines the degree
% of the polynomial g(z).
% Output:
% z the found root(s).
%
% See also: cav, cimmino, drop, landweber, sart, symkaczmarz.
% Maria Saxild-Hansen and Per Chr. Hansen, May 4, 2010, DTU Compute.
% Reference: T. Elfving, T. Nikazad, and P. C. Hansen, Semi-convergence and
% relaxation parameters for a class of SIRT algorithms, Elec. Trans. on
% Numer. Anal., 37 (201), pp. 321-336.
if k(1) < 2
error('The polynomial is not defined for k < 2')
end
% The starting guess for Newton's method.
z0 = 1;
% The number of Newton iterations.
kmax = 6;
z = zeros(length(k),1);
% Finds the root with Newton's method for all the values in k.
for i = 1:length(k)
z(i) = myNewton(z0,kmax,k(i));
end
function [x,k] = myNewton(x0,kmax,grad)
% The Newton method specially defined for this problem.
% Initialize the parameters.
k = 0;
x = x0;
[f, df] = fung(x,grad);
h = f/df;
% Iterate using Newtoms method.
while k < kmax
k = k+1;
x = x - h;
[f, df] = fung(x,grad);
h = f/df;
end
function [f, df] = fung(x,k)
% Uses Horner's algorithm to evaluate the ploynomial and its derivative.
C = [0 2*k-1 -ones(1,k-1)];
f = C(1);
df = 0;
for i = 2:length(C)
df = df*x + f;
f = f*x + C(i);
end
|
github | jakobsj/AIRToolsII-master | paralleltomo.m | .m | AIRToolsII-master/testprobs/paralleltomo.m | 9,767 | utf_8 | e222ff99011ea558812f22f82fff4341 | function [A,b,x,theta,p,d] = paralleltomo(N,theta,p,d,isDisp,isMatrix)
%PARALLELTOMO Creates a 2D parallel-beam tomography test problem
%
% [A,b,x,theta,p,d] = paralleltomo(N)
% [A,b,x,theta,p,d] = paralleltomo(N,theta)
% [A,b,x,theta,p,d] = paralleltomo(N,theta,p)
% [A,b,x,theta,p,d] = paralleltomo(N,theta,p,d)
% [A,b,x,theta,p,d] = paralleltomo(N,theta,p,d,isDisp)
% [A,b,x,theta,p,d] = paralleltomo(N,theta,p,d,isDisp,isMatrix)
%
% This function uses the "line model" to create a 2D X-ray tomography test
% problem with an N-times-N pixel domain, using p parallel rays for each
% angle in the vector theta.
%
% Input:
% N Scalar denoting the number of discretization intervals in
% each dimesion, such that the domain consists of N^2 cells.
% theta Vector containing the projetion angles in degrees.
% Default: theta = 0:1:179.
% p Number of rays for each angle. Default: p = round(sqrt(2)*N).
% d Scalar denoting the distance from the first ray to the last.
% Default: d = p-1.
% isDisp If isDisp is non-zero it specifies the time in seconds
% to pause in the display of the rays. If zero (the default),
% no display is shown.
% isMatrix If non-zero, a sparse matrix is returned in A (default).
% If zero, instead a function handle is returned.
%
% Output:
% A If input isMatrix is 1 (default): coefficient matrix with
% N^2 columns and length(theta)*p rows.
% If input isMatrix is 0: A function handle representing a
% matrix-free version of A in which the forward and backward
% operations are computed as A(x,'notransp') and A(y,'transp'),
% respectively, for column vectors x and y of appropriate size.
% The size of A can be retrieved using A([],'size'). The matrix
% is never formed explicitly, thus saving memory.
% elements in A.
% b Vector containing the rhs of the test problem.
% x Vector containing the exact solution, with elements
% between 0 and 1.
% theta Vector containing the used angles in degrees.
% p The number of used rays for each angle.
% d The distance between the first and the last ray.
%
% See also: fancurvedtomo, fanlineartomo, seismictomo, seismicwavetomo,
% sphericaltomo.
% Reference: A. C. Kak and M. Slaney, Principles of Computerized
% Tomographic Imaging, SIAM, Philadelphia, 2001.
% Code written by: Per Christian Hansen, Jakob Sauer Jorgensen, and
% Maria Saxild-Hansen, 2010-2017.
% This file is part of the AIR Tools II package and is distributed under
% the 3-Clause BSD License. A separate license file should be provided as
% part of the package.
%
% Copyright 2017 Per Christian Hansen, Technical University of Denmark and
% Jakob Sauer Jorgensen, University of Manchester.
% Default value of the projection angles theta.
if nargin < 2 || isempty(theta)
theta = 0:179;
end
% Make sure theta is double precison to prevent round-off issues caused by
% single input.
theta = double(theta);
% Default value of the number of rays.
if nargin < 3 || isempty(p)
p = round(sqrt(2)*N);
end
% Default value of d.
if nargin < 4 || isempty(d)
d = p-1;
end
% Default illustration: False
if nargin < 5 || isempty(isDisp)
isDisp = 0;
end
% Default matrix or matrix-free function handle? Matrix
if nargin < 6 || isempty(isMatrix)
isMatrix = 1;
end
% Construct either matrix or function handle
if isMatrix
A = get_or_apply_system_matrix(N,theta,p,d,isDisp);
else
A = @(U,TRANSP_FLAG) get_or_apply_system_matrix(N,theta,p,d,isDisp,...
U,TRANSP_FLAG);
end
if nargout > 1
% Create phantom head as a reshaped vector.
x = phantomgallery('shepplogan',N);
x = x(:);
% Create rhs.
if isMatrix
b = A*x;
else
b = A(x,'notransp');
end
end
function A = get_or_apply_system_matrix(N,theta,p,d,isDisp,u,transp_flag)
% Define the number of angles.
nA = length(theta);
% The starting values both the x and the y coordinates.
x0 = linspace(-d/2,d/2,p)';
y0 = zeros(p,1);
% The intersection lines.
x = (-N/2:N/2)';
y = x;
% Prepare for illustration
if isDisp
AA = phantomgallery('smooth',N);
figure
end
% Deduce whether to set up matrix or apply to input, depending on whether
% input u is given.
isMatrix = (nargin < 6);
if isMatrix
% Initialize vectors that contains the row numbers, the column numbers
% and the values for creating the matrix A effiecently.
rows = zeros(2*N*nA*p,1);
cols = rows;
vals = rows;
idxend = 0;
II = 1:nA;
JJ = 1:p;
else
% If transp_flag is 'size', only return size of operator, otherwise set
% proper size of output.
switch transp_flag
case 'size'
A = [p*nA,N^2];
return
case 'notransp' % Forward project.
if length(u) ~= N^2
error('Incorrect length of input vector')
end
A = zeros(p*nA,1);
case 'transp' % Backproject
if length(u) ~= p*nA
error('Incorrect length of input vector')
end
A = zeros(N^2,1);
end
% If u is a Cartesian unit vector then we only want to compute a single
% row of A; otherwise we want to multiply with A or A'.
if strcmpi(transp_flag,'transp') && nnz(u) == 1 && sum(u) == 1
% Want to compute a single row of A, stored as a column vector.
ell = find(u==1);
JJ = mod(ell,p); if JJ==0, JJ = p; end
II = (ell-JJ)/p + 1;
else
% Want to multiply with A or A'.
II = 1:nA;
JJ = 1:p;
end
end
% Loop over the chosen angles.
for i = II
% Illustration of the domain.
if isDisp
clf
pause(isDisp)
imagesc((-N/2+.5):(N/2-0.5),(-N/2+.5):(N/2-0.5),flipud(AA))
colormap gray
axis xy
hold on
axis equal
axis(0.7*[-N N -N N])
end
% All the starting points for the current angle.
x0theta = cosd(theta(i))*x0-sind(theta(i))*y0;
y0theta = sind(theta(i))*x0+cosd(theta(i))*y0;
% The direction vector for all rays corresponding to the current angle.
a = -sind(theta(i));
b = cosd(theta(i));
% Loop over the rays.
for j = JJ
% Use the parametrisation of line to get the y-coordinates of
% intersections with x = constant.
tx = (x - x0theta(j))/a;
yx = b*tx + y0theta(j);
% Use the parametrisation of line to get the x-coordinates of
% intersections with y = constant.
ty = (y - y0theta(j))/b;
xy = a*ty + x0theta(j);
% Illustration of the rays.
if isDisp
plot(x,yx,'-','color',[220 0 0]/255,'linewidth',1.5)
plot(xy,y,'-','color',[220 0 0]/255,'linewidth',1.5)
set(gca,'Xtick',[],'Ytick',[])
pause(isDisp)
end
% Collect the intersection times and coordinates.
t = [tx; ty];
xxy = [x; xy];
yxy = [yx; y];
% Sort the coordinates according to intersection time.
[~,I] = sort(t);
xxy = xxy(I);
yxy = yxy(I);
% Skip the points outside the box.
I = (xxy >= -N/2 & xxy <= N/2 & yxy >= -N/2 & yxy <= N/2);
xxy = xxy(I);
yxy = yxy(I);
% Skip double points.
I = (abs(diff(xxy)) <= 1e-10 & abs(diff(yxy)) <= 1e-10);
xxy(I) = [];
yxy(I) = [];
% Calculate the length within cell and determines the number of
% cells which is hit.
aval = sqrt(diff(xxy).^2 + diff(yxy).^2);
col = [];
% Store the values inside the box.
if numel(aval) > 0
% If the ray is on the boundary of the box in the top or to the
% right the ray does not by definition lie with in a valid cell.
if ~((b == 0 && abs(y0theta(j) - N/2) < 1e-15) || ...
(a == 0 && abs(x0theta(j) - N/2) < 1e-15) )
% Calculates the midpoints of the line within the cells.
xm = 0.5*(xxy(1:end-1)+xxy(2:end)) + N/2;
ym = 0.5*(yxy(1:end-1)+yxy(2:end)) + N/2;
% Translate the midpoint coordinates to index.
col = floor(xm)*N + (N - floor(ym));
end
end
if ~isempty(col)
if isMatrix
% Create the indices to store the values to vector for
% later creation of A matrix.
idxstart = idxend + 1;
idxend = idxstart + numel(col) - 1;
idx = idxstart:idxend;
% Store row numbers, column numbers and values.
rows(idx) = (i-1)*p + j;
cols(idx) = col;
vals(idx) = aval;
else
% If any nonzero elements, apply forward or back operator
if strcmp(transp_flag,'notransp')
% Insert inner product with u into w.
A( (i-1)*p+j ) = aval'*u(col);
else % Adjoint operator.
A(col) = A(col) + u( (i-1)*p+j )*aval;
end
end
end
end % end j
end % end i
if isMatrix
% Truncate excess zeros.
rows = rows(1:idxend);
cols = cols(1:idxend);
vals = vals(1:idxend);
% Create sparse matrix A from the stored values.
A = sparse(rows,cols,vals,p*nA,N^2);
end
|
github | jakobsj/AIRToolsII-master | fanlineartomo.m | .m | AIRToolsII-master/testprobs/fanlineartomo.m | 11,166 | utf_8 | 31351e0798a56c5b1cfd228e5c1c5751 | function [A,b,x,theta,p,R,dw,sd] = ...
fanlineartomo(N,theta,p,R,dw,sd,isDisp,isMatrix)
%FANLINEARTOMO Creates 2D fan-beam linear-detector tomography test problem
%
% [A,b,x,theta,p,R,d] = fanlineartomo(N)
% [A,b,x,theta,p,R,d] = fanlineartomo(N,theta)
% [A,b,x,theta,p,R,d] = fanlineartomo(N,theta,p)
% [A,b,x,theta,p,R,d] = fanlineartomo(N,theta,p,R)
% [A,b,x,theta,p,R,d] = fanlineartomo(N,theta,p,R,dw)
% [A,b,x,theta,p,R,d] = fanlineartomo(N,theta,p,R,dw,sd)
% [A,b,x,theta,p,R,d] = fanlineartomo(N,theta,p,R,dw,sd,isDisp)
% [A,b,x,theta,p,R,d] = fanlineartomo(N,theta,p,R,dw,sd,isDisp,isMatrix)
%
% This function uses the "line model" to create a 2D X-ray tomography test
% problem with an N-times-N pixel domain, using p rays in fan formation for
% each angle in the vector theta. Unlike fancurvedtomo, in which the detector
% is curved, in fanlineartomo the detector is linear, corresponding to the
% central slice of a flat-panel detector.
%
% Input:
% N Scalar denoting the number of discretization intervals in
% each dimesion, such that the domain consists of N^2 cells.
% theta Vector containing the angles in degrees. Default: theta =
% 0:2:358.
% p Number of rays for each angle. Default: p = round(sqrt(2)*N).
% R The distance from the source to the center of the domain
% is R*N. Default: R = 2.
% dw Total width of linear detector. Same units as R.
% sd Source to detector distance. Same units as R.
% isDisp If isDisp is non-zero it specifies the time in seconds
% to pause in the display of the rays. If zero (the default),
% no display is shown.
% isMatrix If non-zero, a sparse matrix is returned in A (default).
% If zero, instead a function handle is returned.
%
% Output:
% A If input isMatrix is 1 (default): coefficient matrix with
% N^2 columns and length(theta)*p rows.
% If input isMatrix is 0: A function handle representing a
% matrix-free version of A in which the forward and backward
% operations are computed as A(x,'notransp') and A(y,'transp'),
% respectively, for column vectors x and y of appropriate size.
% The size of A can be retrieved using A([],'size'). The matrix
% is never formed explicitly, thus saving memory.
% b Vector containing the rhs of the test problem.
% x Vector containing the exact solution, with elements
% between 0 and 1.
% theta Vector containing the used angles in degrees.
% p The number of used rays for each angle.
% R The radius in side lengths.
% d The span of the rays.
%
% See also: paralleltomo, fancurvedtomo, seismictomo, seismicwavetomo,
% sphericaltomo.
% Reference: A. C. Kak and M. Slaney, Principles of Computerized
% Tomographic Imaging, SIAM, Philadelphia, 2001.
% Code written by: Per Christian Hansen, Jakob Sauer Jorgensen, and
% Maria Saxild-Hansen, 2010-2017.
% This file is part of the AIR Tools II package and is distributed under
% the 3-Clause BSD License. A separate license file should be provided as
% part of the package.
%
% Copyright 2017 Per Christian Hansen, Technical University of Denmark and
% Jakob Sauer Jorgensen, University of Manchester.
% Default illustration:
if nargin < 7 || isempty(isDisp)
isDisp = 0;
end
% Default value of sd.
if nargin < 6 || isempty(sd)
sd = 3;
end
sd = sd*N;
% Default value of dw.
if nargin < 5 || isempty(dw)
dw = 2.5;
end
dw = dw*N;
% Default value of R.
if nargin < 4 || isempty(R)
R = 2;
end
R = R*N;
% Default value of the number of rays p.
if nargin < 3 || isempty(p)
p = round(sqrt(2)*N);
end
% Default value of the angles theta.
if nargin < 2 || isempty(theta)
theta = 0:2:358;
end
% Make sure theta is double precison to prevent round-off issues caused by
% single input.
theta = double(theta);
% Default matrix or matrix-free function handle? Matrix
if nargin < 8 || isempty(isMatrix)
isMatrix = 1;
end
% Input check. The source must lie outside the domain.
if R < sqrt(2)/2*N
error('R must be greater than half squareroot 2')
end
% Construct either matrix or function handle
if isMatrix
A = get_or_apply_system_matrix(N,theta,p,R,dw,sd,isDisp);
else
A = @(U,TRANSP_FLAG) get_or_apply_system_matrix(...
N,theta,p,R,dw,sd,isDisp,U,TRANSP_FLAG);
end
if nargout > 1
% Create phantom head as a reshaped vector.
x = phantomgallery('shepplogan',N);
x = x(:);
% Create rhs.
if isMatrix
b = A*x;
else
b = A(x,'notransp');
end
end
if nargout > 5
R = R/N;
end
function A = get_or_apply_system_matrix(N,theta,p,R,dw,sd,isDisp,...
u,transp_flag)
% Anonymous function rotation matrix
Omega_x = @(omega_par) [cosd(omega_par) -sind(omega_par)];
Omega_y = @(omega_par) [sind(omega_par) cosd(omega_par)];
% nA denotes the number of angles.
nA = length(theta);
% The starting values both the x and the y coordinates.
x0 = 0;
y0 = R;
xy0 = [x0;y0];
% Width of detector element
dew = dw/p;
% Set angles to match linear detector
if mod(p,2)
depos = (1:(p-1)/2)*dew;
deposall = [-depos(end:-1:1),0,depos];
omega = 90-atand(sd./depos);
omega = [-omega(end:-1:1),0,omega];
else
depos = ((1:p/2)-0.5)*dew;
deposall = [-depos(end:-1:1),depos];
omega = 90-atand(sd./depos);
omega = [-omega(end:-1:1),omega];
end
% The intersection lines.
x = (-N/2:N/2)';
y = x;
% Prepare for illustration
if isDisp
AA = rand(N);
figure
end
% Deduce whether to set up matrix or apply to input, depending on whether
% input u is given.
isMatrix = (nargin < 8);
if isMatrix
% Initialize vectors that contains the row numbers, the column numbers
% and the values for creating the matrix A efficiently.
rows = zeros(2*N*nA*p,1);
cols = rows;
vals = rows;
idxend = 0;
II = 1:nA;
JJ = 1:p;
else
% If transp_flag is 'size', only return size of operator, otherwise set
% proper size of output.
switch transp_flag
case 'size'
A = [p*nA,N^2];
return
case 'notransp' % Forward project.
if length(u) ~= N^2, error('Incorrect length of input vector'), end
A = zeros(p*nA,1);
case 'transp' % Backproject
if length(u) ~= p*nA, error('Incorrect length of input vector'), end
A = zeros(N^2,1);
end
% If u is a Cartesian unit vector then we only want to compute a single
% row of A; otherwise we want to multiply with A or A'.
if strcmpi(transp_flag,'transp') && nnz(u) == 1 && sum(u) == 1
% Want to compute a single row of A, stored as a column vector.
ell = find(u==1);
JJ = mod(ell,p); if JJ==0, JJ = p; end
II = (ell-JJ)/p + 1;
else
% Want to multiply with A or A'.
II = 1:nA;
JJ = 1:p;
end
end
% Loop over the chosen angles of the source.
for i = II
% The starting points for the current angle theta.
x0theta = Omega_x(theta(i))*xy0;
y0theta = Omega_y(theta(i))*xy0;
% Illustration of the domain
if isDisp % illustration of source
clf
pause(isDisp)
imagesc((-N/2+.5):(N/2-0.5),(-N/2+.5):(N/2-0.5),flipud(AA))
colormap gray
axis xy
hold on
axis(1.1*R*[-1,1,-1,1])
axis equal
plot(x0theta,y0theta,'o','color',[60 179 113]/255,...
'linewidth',1.5,'markersize',10)
end
% The starting (center) direction vector (opposite xytheta) and
% normalized.
xytheta = [x0theta; y0theta];
abtheta = -xytheta/R;
% Loop over the rays.
for j = JJ
% The direction vector for the current ray.
a = Omega_x(omega(j))*abtheta;
b = Omega_y(omega(j))*abtheta;
xdtheta = Omega_x(theta(i))*[deposall(j); R-sd];
ydtheta = Omega_y(theta(i))*[deposall(j); R-sd];
% Illustration of rays
if isDisp
plot([x0theta,xdtheta],[y0theta,ydtheta],'-',...
'color',[220 0 0]/255,'linewidth',1.5)
axis(R*[-1,1,-1,1])
end
% Use the parametrisation of line to get the y-coordinates of
% intersections with x = k, i.e., x constant.
tx = (x - x0theta)/a;
yx = b*tx + y0theta;
% Use the parametrisation of line to get the x-coordinates of
% intersections with y = k, i.e., y constant.
ty = (y - y0theta)/b;
xy = a*ty + x0theta;
% Collect the intersection times and coordinates.
t = [tx; ty];
xxy = [x; xy];
yxy = [yx; y];
% Sort the coordinates according to intersection time.
[~,I] = sort(t);
xxy = xxy(I);
yxy = yxy(I);
% Skip the points outside the box.
I = (xxy >= -N/2 & xxy <= N/2 & yxy >= -N/2 & yxy <= N/2);
xxy = xxy(I);
yxy = yxy(I);
% Skip double points.
I = (abs(diff(xxy)) <= 1e-10 & abs(diff(yxy)) <= 1e-10);
xxy(I) = [];
yxy(I) = [];
% Illustration of the rays.
if isDisp
set(gca,'Xtick',[],'Ytick',[])
pause(isDisp)
end
% Calculate the length within cell and determines the number of
% cells which is hit.
aval = sqrt(diff(xxy).^2 + diff(yxy).^2);
col = [];
% Store the values inside the box.
if numel(aval) > 0
% Calculates the midpoints of the line within the cells.
xm = 0.5*(xxy(1:end-1)+xxy(2:end)) + N/2;
ym = 0.5*(yxy(1:end-1)+yxy(2:end)) + N/2;
% Translate the midpoint coordinates to index.
col = floor(xm)*N + (N - floor(ym));
end
if ~isempty(col)
if isMatrix
% Create the indices to store the values to vector for
% later creation of A matrix.
idxstart = idxend + 1;
idxend = idxstart + numel(col) - 1;
idx = idxstart:idxend;
% Store row numbers, column numbers and values.
rows(idx) = (i-1)*p + j;
cols(idx) = col;
vals(idx) = aval;
else
% If any nonzero elements, apply forward or back operator.
if strcmp(transp_flag,'notransp')
% Insert inner product with u into w.
A( (i-1)*p+j ) = aval'*u(col);
else % Adjoint operator.
A(col) = A(col) + u( (i-1)*p+j )*aval;
end
end
end
end % end j
end % end i
if isMatrix
% Truncate excess zeros.
rows = rows(1:idxend);
cols = cols(1:idxend);
vals = vals(1:idxend);
% Create sparse matrix A from the stored values.
A = sparse(rows,cols,vals,p*nA,N^2);
end
|
github | jakobsj/AIRToolsII-master | seismicwavetomo.m | .m | AIRToolsII-master/testprobs/seismicwavetomo.m | 9,213 | utf_8 | 0e9aaed7ca98d4984d6d14cb7c9fb3e2 | function [A,b,x,s,p,omega] = seismicwavetomo(N,s,p,omega,isDisp,isMatrix)
%SEISMICWAVETOMO Seismic tomography problem without the ray assumption
%
% [A,b,x,s,p] = seismicwavetomo(N)
% [A,b,x,s,p] = seismicwavetomo(N,s)
% [A,b,x,s,p] = seismicwavetomo(N,s,p)
% [A,b,x,s,p] = seismicwavetomo(N,s,p,omega)
% [A,b,x,s,p] = seismicwavetomo(N,s,p,omega,isDisp)
% [A,b,x,s,p] = seismicwavetomo(N,s,p,omega,isDisp,isMatrix)
%
% This function creates a 2D seismic travel-time tomography test problem
% with an N-times-N pixel domain, using s sources located on the right
% boundary and p receivers (seismographs) scattered along the left and top
% boundary. Waves are transmitted from each source to each receiver, and
% there is no high-frequency approximation, i.e., no assumption about rays.
% The wave is assumed to travel within the first Fresnel zone.
%
% In the limit where the wave frequency is infinite, the waves can be
% described by rays as done in the function seismictomo. But note that
% A and b do not converge to those of seismictomo as omega -> inf.
%
% Inupt:
% N Scalar denoting the number of discretization intervals in
% each dimesion, such that the domain consists of N^2 cells.
% s The number of sources in the right side of the domain
% (default s = N.
% p The number of receivers (seismographs) equally spaced on the
% surface and on the left side of the domain. Default p = 2*N.
% omega Dominant frequency of the propagating wave. Default = 10.
% isDisp If isDisp is nonzero it specifies the time in seconds to pause
% in the display of the rays. If zero (the default), then no
% display is shown.
% isMatrix If non-zero, a sparse matrix is returned in A (default).
% If zero, instead a function handle is returned.
%
% Output:
% A If input isMatrix is 1 (default): coefficient matrix with
% N^2 columns and length(theta)*p rows.
% If input isMatrix is 0: A function handle representing a
% matrix-free version of A in which the forward and backward
% operations are computed as A(x,'notransp') and A(y,'transp'),
% respectively, for column vectors x and y of appropriate size.
% The size of A can be retrieved using A([],'size'). The matrix
% is never formed explicitly, thus saving memory.
% b Vector containing the rhs of the test problem.
% x Vector containing the exact solution, with elements
% between 0 and 1.
% s The number of sources.
% p The number of receivers (seismographs).
% omega The frequency.
%
% See also: paralleltomo, fancurvedtomo, fanlineartomo, seismictomo,
% sphericaltomo.
% Reference: J. M. Jensen, B. H. Jacobsen, and J. Christensen-Dalsgaard,
% Sensitivity kernels for time-distance inversion, Solar Physics, 192
% (2000), pp. 231-239.
% Code written by: Per Christian Hansen, Jakob Sauer Jorgensen, and
% Maria Saxild-Hansen, 2010-2017.
% With contribution from Mikkel Brettschneider.
% This file is part of the AIR Tools II package and is distributed under
% the 3-Clause BSD License. A separate license file should be provided as
% part of the package.
%
% Copyright 2017 Per Christian Hansen, Technical University of Denmark and
% Jakob Sauer Jorgensen, University of Manchester.
% Default number of sources.
if nargin < 2 || isempty(s)
s = N;
end
% Default number of receivers (seismographs).
if nargin < 3 || isempty(p)
p = 2*N;
end
% Default frequency.
if nargin < 4 || isempty(omega)
omega = 10;
end
if nargin < 5 || isempty(isDisp)
isDisp = 0;
end
if nargin < 6 || isempty(isMatrix)
isMatrix = 1;
end
% Construct either matrix or function handle
if isMatrix
A = get_or_apply_system_matrix(N,s,p,omega,isDisp);
else
A = @(U,TRANSP_FLAG) get_or_apply_system_matrix(...
N,s,p,omega,isDisp,U,TRANSP_FLAG);
end
% Create the phantom.
if nargout > 1
x = phantomgallery('tectonic',N);
x = x(:);
if isMatrix
b = A*x;
else
b = A(x,'notransp');
end
end
function A = get_or_apply_system_matrix(N,s,p,omega,isDisp,u,transp_flag)
% Threshold for sparsity.
tol = 1e-6;
N2 = N/2;
% Determine the positions of the sources.
Ns = (N/s)/2;
x0 = N2*ones(s,1);
y0 = linspace(-N2+Ns,N2-Ns,s)';
% The positions of the seismographs.
p1 = ceil(p/2);
p2 = floor(p/2);
Np1 = (N/p1)/2;
Np2 = (N/p2)/2;
xp = [-N2*ones(p2,1); linspace(-N2+Np1,N2-Np1,p1)'];
yp = [linspace(-N2+Np2,N2-Np2,p2)'; N2*ones(p1,1)];
% The intersection lines.
xrange = (-N2+.5:N2-.5)';
yrange = (N2-.5:-1:-N2+.5)';
[xx,yy] = meshgrid(xrange,yrange);
% Prepare for illustration.
if isDisp
figure
end
% Deduce whether to set up matrix or apply to input from whether input u is
% given.
isMatrix = (nargin < 6);
if isMatrix
% Initialize the index for storing the results and the number of angles.
idxend = 0;
rows = zeros(2*N*s*p,1);
cols = rows;
vals = rows;
II = 1:s;
JJ = 1:p;
else
% If transp_flag is 'size', only return size of operator, otherwise set
% proper size of output.
switch transp_flag
case 'size'
A = [p*s,N^2];
return
case 'notransp' % Forward project.
if length(u) ~= N^2, error('Incorrect length of input vector'), end
A = zeros(p*s,1);
case 'transp' % Backproject
if length(u) ~= p*s, error('Incorrect length of input vector'), end
A = zeros(N^2,1);
end
% If u is a Cartesian unit vector then we only want to compute a single
% row of A; otherwise we want to multiply with A or A'.
if strcmpi(transp_flag,'transp') && nnz(u) == 1 && sum(u) == 1
% Want to compute a single row of A, stored as a column vector.
ell = find(u==1);
JJ = mod(ell,p); if JJ==0, JJ = p; end
II = (ell-JJ)/p + 1;
else
% Want to multiply with A or A'.
II = 1:s;
JJ = 1:p;
end
end
% Loop over all the sources.
for i = II
% Illustation of the domain
if isDisp
pause(isDisp)
clf;
hold on
axis xy equal
axis([-N2 N2 -N2 N2])
plot(x0,y0,'.','color','r','linewidth',2,'markersize',30)
plot(xp,yp,'s','MarkerEdgeColor','m',...
'MarkerFaceColor','m','MarkerSize',10,'linewidth',2)
end
% Loop over the seismographs.
for j = JJ
% Kreate sensitivity kernels
R = [xp(j) yp(j)];
S = [x0(i) y0(i)];
sens = simple_fat_kernel(R,S,omega/N,xx,yy);
sens(sens<tol) = 0;
[ym,xm,aval] = find(sens);
% Illustration of the sensitivity kernels.
if isDisp
imagesc(xrange,yrange,sens);
set(gca,'Xtick',[],'Ytick',[])
pause(isDisp)
end
%numvals = numel(aval);
col = [];
% Store the values inside the domain.
if numel(aval) > 0
% Translate the domain index to matrix index.
col = (xm-1)*N + ym;
end
if ~isempty(col)
if isMatrix
% Create the indices to store the values to a vector for
% later creation of A matrix.
idxstart = idxend + 1;
idxend = idxstart + numel(col) - 1;
idx = idxstart:idxend;
% Store row numbers, column numbers and values.
rows(idx) = (i-1)*p + j;
cols(idx) = col;
vals(idx) = aval;
else
% If any nonzero elements, apply forward or back operator
if strcmp(transp_flag,'notransp')
% Insert inner product with u into w.
A( (i-1)*p+j ) = aval'*u(col);
else % Adjoint operator.
A(col) = A(col) + u( (i-1)*p+j )*aval;
end
end
end
end % end j
end % end i
if isMatrix
% Truncate excess zeros.
rows = rows(1:idxend);
cols = cols(1:idxend);
vals = vals(1:idxend);
% Create sparse matrix A from the stored values.
A = sparse(rows,cols,vals,s*p,N^2);
end
function S = simple_fat_kernel(R,S,omega,xx,yy)
% Computation of Fresnel zones that describe the sensitivity of the solution
% to the seismic wave.
alpha = 10; % Chosen by inspection.
tSX = sqrt((xx-S(1)).^2 + (yy-S(2)).^2);
tRX = sqrt((xx-R(1)).^2 + (yy-R(2)).^2);
distSR = sqrt(sum((S-R).^2));
delta_t = tSX+tRX - distSR;
% Compute the sensitivity kernel.
S = cos(2*pi*delta_t.*omega).*exp(- (alpha*delta_t.*omega).^2 );
% Normalize S.
S = distSR.*S./sum(S(:));
|
github | jakobsj/AIRToolsII-master | fancurvedtomo.m | .m | AIRToolsII-master/testprobs/fancurvedtomo.m | 10,866 | utf_8 | 296ae1d0657c71c6fb395008035785ba | function [A,b,x,theta,p,R,d] = fancurvedtomo(N,theta,p,R,d,isDisp,isMatrix)
%FANCURVEDTOMO Creates 2D fan-beam curved-detector tomography test problem
%
% [A,b,x,theta,p,R,d] = fancurvedtomo(N)
% [A,b,x,theta,p,R,d] = fancurvedtomo(N,theta)
% [A,b,x,theta,p,R,d] = fancurvedtomo(N,theta,p)
% [A,b,x,theta,p,R,d] = fancurvedtomo(N,theta,p,R)
% [A,b,x,theta,p,R,d] = fancurvedtomo(N,theta,p,R,d)
% [A,b,x,theta,p,R,d] = fancurvedtomo(N,theta,p,R,d,isDisp)
% [A,b,x,theta,p,R,d] = fancurvedtomo(N,theta,p,R,d,isDisp,isMatrix)
%
% This function uses the "line model" to create a 2D X-ray tomography test
% problem with an N-times-N pixel domain, using p rays in fan formation for
% each angle in the vector theta. The detector is curved such that the angular
% increments between rays in each projection is constant.
%
% Input:
% N Scalar denoting the number of discretization intervals in
% each dimesion, such that the domain consists of N^2 cells.
% theta Vector containing the projetion angles in degrees.
% Default: theta = 0:2:358.
% p Number of rays for each angle. Default: p = round(sqrt(2)*N).
% R The distance from the source to the center of the domain
% is R*N. Default: R = 2.
% d Scalar that determines the angular span of the rays, in
% degrees. The default value is defined such that from the
% source at (0,R*N) the first ray hits the corner (-N/2,N/2)
% and the last ray hits the corner (N/2,N/2).
% isDisp If isDisp is non-zero it specifies the time in seconds
% to pause in the display of the rays. If zero (the default),
% no display is shown.
% isMatrix If non-zero, a sparse matrix is returned in A (default).
% If zero, instead a function handle is returned.
%
% Output:
% A If input isMatrix is 1 (default): coefficient matrix with
% N^2 columns and length(theta)*p rows.
% If input isMatrix is 0: A function handle representing a
% matrix-free version of A in which the forward and backward
% operations are computed as A(x,'notransp') and A(y,'transp'),
% respectively, for column vectors x and y of appropriate size.
% The size of A can be retrieved using A([],'size'). The matrix
% is never formed explicitly, thus saving memory.
% b Vector containing the rhs of the test problem.
% x Vector containing the exact solution, with elements
% between 0 and 1.
% theta Vector containing the used angles in degrees.
% p The number of used rays for each angle.
% R The radius in side lengths.
% d The span of the rays.
%
% See also: paralleltomo, fanlineartomo, seismictomo, seismicwavetomo,
% sphericaltomo.
% Reference: A. C. Kak and M. Slaney, Principles of Computerized
% Tomographic Imaging, SIAM, Philadelphia, 2001.
% Code written by: Per Christian Hansen, Jakob Sauer Jorgensen, and
% Maria Saxild-Hansen, 2010-2017.
% This file is part of the AIR Tools II package and is distributed under
% the 3-Clause BSD License. A separate license file should be provided as
% part of the package.
%
% Copyright 2017 Per Christian Hansen, Technical University of Denmark and
% Jakob Sauer Jorgensen, University of Manchester.
% Default illustration:
if nargin < 6 || isempty(isDisp)
isDisp = 0;
end
% Default value of R.
if nargin < 4 || isempty(R)
R = 2;
end
% Default value of d.
if nargin < 5 || isempty(d)
% Determine angular span. The first and last rays touch points
% (-N/2,N/2) and (N/2,N/2), respectively.
d = 2*atand(1/(2*R-1));
end
% Default value of the number of rays p.
if nargin < 3 || isempty(p)
p = round(sqrt(2)*N);
end
% Default value of the angles theta.
if nargin < 2 || isempty(theta)
theta = 0:2:358;
end
% Make sure theta is double precison to prevent round-off issues caused by
% single input.
theta = double(theta);
% Default matrix or matrix-free function handle? Matrix
if nargin < 7 || isempty(isMatrix)
isMatrix = 1;
end
% Input check. The source must lie outside the domain.
if R < sqrt(2)/2
error('R must be greater than half squareroot 2')
end
R = R*N;
% The width of the angle of the source.
if d < 0 || d > 180
error('The angle of the source must be in the interval [0 180]')
end
% Construct either matrix or function handle.
if isMatrix
A = get_or_apply_system_matrix(N,theta,p,R,d,isDisp);
else
A = @(U,TRANSP_FLAG) get_or_apply_system_matrix(...
N,theta,p,R,d,isDisp,U,TRANSP_FLAG);
end
if nargout > 1
% Create phantom head as a reshaped vector.
x = phantomgallery('shepplogan',N);
x = x(:);
% Create rhs.
if isMatrix
b = A*x;
else
b = A(x,'notransp');
end
end
if nargout > 5
R = R/N;
end
function A = get_or_apply_system_matrix(N,theta,p,R,d,isDisp,u,transp_flag)
% Anonymous function rotation matrix.
Omega_x = @(omega_par) [cosd(omega_par) -sind(omega_par)];
Omega_y = @(omega_par) [sind(omega_par) cosd(omega_par)];
% nA denotes the number of angles.
nA = length(theta);
% The starting values both the x and the y coordinates.
x0 = 0;
y0 = R;
xy0 = [x0;y0];
omega = linspace(-d/2,d/2,p);
% The intersection lines.
x = (-N/2:N/2)';
y = x;
% Prepare for illustration.
if isDisp
AA = phantomgallery('smooth',N);
figure
end
% Deduce whether to set up matrix or apply to input, deponding on whether
% input u is given.
isMatrix = (nargin < 7);
if isMatrix
% Initialize vectors that contains the row numbers, the column numbers
% and the values for creating the matrix A effiecently.
rows = zeros(2*N*nA*p,1);
cols = rows;
vals = rows;
idxend = 0;
II = 1:nA;
JJ = 1:p;
else
% If transp_flag is 'size', only return size of operator, otherwise set
% proper size of output.
switch transp_flag
case 'size'
A = [p*nA,N^2];
return
case 'notransp' % Forward project.
if length(u) ~= N^2, error('Incorrect length of input vector'), end
A = zeros(p*nA,1);
case 'transp' % Backproject
if length(u) ~= p*nA, error('Incorrect length of input vector'), end
A = zeros(N^2,1);
end
% If u is a Cartesian unit vector then we only want to compute a single
% row of A; otherwise we want to multiply with A or A'.
if strcmpi(transp_flag,'transp') && nnz(u) == 1 && sum(u) == 1
% Want to compute a single row of A, stored as a column vector.
ell = find(u==1);
JJ = mod(ell,p); if JJ==0, JJ = p; end
II = (ell-JJ)/p + 1;
else
% Want to multiply with A or A'.
II = 1:nA;
JJ = 1:p;
end
end
% Loop over the chosen angles of the source.
for i = II
% The starting points for the current angle theta.
x0theta = Omega_x(theta(i))*xy0;
y0theta = Omega_y(theta(i))*xy0;
% Illustration of the domain.
if isDisp % illustration of source.
clf
pause(isDisp)
imagesc((-N/2+.5):(N/2-0.5),(-N/2+.5):(N/2-0.5),flipud(AA))
colormap gray
axis xy
hold on
axis(1.1*R*[-1,1,-1,1])
axis equal
plot(x0theta,y0theta,'o','color',[60 179 113]/255,...
'linewidth',1.5,'markersize',10)
end
% The starting (center) direction vector (opposite xytheta) and
% normalized.
xytheta = [x0theta; y0theta];
abtheta = -xytheta/R;
% Loop over the rays.
for j = JJ
% The direction vector for the current ray.
a = Omega_x(omega(j))*abtheta;
b = Omega_y(omega(j))*abtheta;
% Illustration of rays.
if isDisp
plot([x0theta,x0theta+1.7*R*a],[y0theta,y0theta+1.7*R*b],'-',...
'color',[220 0 0]/255,'linewidth',1.5)
axis(R*[-1,1,-1,1])
end
% Use the parametrisation of line to get the y-coordinates of
% intersections with x = constant.
tx = (x - x0theta)/a;
yx = b*tx + y0theta;
% Use the parametrisation of line to get the x-coordinates of
% intersections with y = constant.
ty = (y - y0theta)/b;
xy = a*ty + x0theta;
% Collect the intersection times and coordinates.
t = [tx; ty];
xxy = [x; xy];
yxy = [yx; y];
% Sort the coordinates according to intersection time.
[~,I] = sort(t);
xxy = xxy(I);
yxy = yxy(I);
% Skip the points outside the box.
I = (xxy >= -N/2 & xxy <= N/2 & yxy >= -N/2 & yxy <= N/2);
xxy = xxy(I);
yxy = yxy(I);
% Skip double points.
I = (abs(diff(xxy)) <= 1e-10 & abs(diff(yxy)) <= 1e-10);
xxy(I) = [];
yxy(I) = [];
% Illustration of the rays.
if isDisp
set(gca,'Xtick',[],'Ytick',[])
pause(isDisp)
end
% Calculate the length within cell and determines the number of
% cells which is hit.
aval = sqrt(diff(xxy).^2 + diff(yxy).^2);
col = [];
% Store the values inside the box.
if numel(aval) > 0
% Calculates the midpoints of the line within the cells.
xm = 0.5*(xxy(1:end-1)+xxy(2:end)) + N/2;
ym = 0.5*(yxy(1:end-1)+yxy(2:end)) + N/2;
% Translate the midpoint coordinates to index.
col = floor(xm)*N + (N - floor(ym));
end
if ~isempty(col)
if isMatrix
% Create the indices to store the values to vector for
% later creation of A matrix.
idxstart = idxend + 1;
idxend = idxstart + numel(col) - 1;
idx = idxstart:idxend;
% Store row numbers, column numbers and values.
rows(idx) = (i-1)*p + j;
cols(idx) = col;
vals(idx) = aval;
else
% If any nonzero elements, apply forward or back operator.
if strcmp(transp_flag,'notransp')
% Insert inner product with u into w.
A( (i-1)*p+j ) = aval'*u(col);
else % Adjoint operator.
A(col) = A(col) + u( (i-1)*p+j )*aval;
end
end
end
end % end j
end % end i
if isMatrix
% Truncate excess zeros.
rows = rows(1:idxend);
cols = cols(1:idxend);
vals = vals(1:idxend);
% Create sparse matrix A from the stored values.
A = sparse(rows,cols,vals,p*nA,N^2);
end
|
github | jakobsj/AIRToolsII-master | phantomgallery.m | .m | AIRToolsII-master/testprobs/phantomgallery.m | 33,409 | utf_8 | 58d9457294d4e72613ea8dafe169d278 | function im = phantomgallery(name,N,P1,P2,P3)
%PHANTOMGALLERY A collection of 2D phantoms for use in test problems
%
% im = phantomgallery(name,N)
% im = phantomgallery(name,N,P1)
% im = phantomgallery(name,N,P1,P2)
% im = phantomgallery(name,N,P1,P2,P3)
%
% The phantom im is N-by-N with pixel values between 0 and 1, and the
% following phantom types are available:
%
% shepplogan: the Shepp-Logan phantom
% im = phantomgallery('shepplogan',N)
%
% smooth: a smooth image
% im = phantomgallery('smooth',N,P1)
% P1 = 1, 2, 3 or 4 defines four different smooth functions (default = 4)
% The image is constructed by adding four different Gaussian functions.
%
% binary: a random image with binary pixel values arranged in domains
% im = phantomgallery('binary',N,P1)
% P1 = seed for random number generator
% The image is dominated by horizontal structures.
%
% threephases: a random image with pixel values 0, 0.5, 1 arranged in domains
% im = phantomgallery('threephases',N,P1,P2)
% P1 = controls the number of domains (default = 100)
% P2 = seed for random number generator
% The image is a model of a three-phase object.
%
% threephasessmooth: similar to threephases, but the domains have smoothly
% varying pixel values and there is a smooth background
% im = phantomgallery('threephasessmooth',N,P1,P2,P3)
% P1 = controls the number of domains (default = 100)
% P2 = controls the intensity variation within each domain (default = 1.5)
% P3 = seed for random number generator
%
% fourphases: a random image similar to 'binary' but with three phases
% separated by (thin) structures that form the fourth phase
% im = phantomgallery('fourphases',N,P1)
% P1 = seed for random number generator
%
% grains: a random image with Voronoi cells
% im = phantomgallery('grains',N,P1,P2)
% P1 = number of cells in the image (default = 3*sqrt(N))
% P2 = seed for random number generator
% The image is a model of grains with different pixel intensities.
%
% ppower: a random image with patterns of nonzero pixels
% im = phantomgallery('ppower',N,P1,P2,P3)
% P1 = the ratio of nonzero pixels, between 0 and 1 (default = 0.3)
% P2 = the smoothness of the image, greater than 0 (default = 2)
% P3 = seed for random number generator
% The larger the P2 the larger the domains of nonzero pixels.
%
% tectonic: a test image for the seismic tomography test problems.
% im = phantomgallery('tectonic',N)
%
% To use these images in connection with the test problems use the commands:
% im = phantomgallery(name,N,...);
% x = im(:);
% A = matrix generated, e.g., by paralleltomo;
% b = A*x;
% Code written by: Per Christian Hansen, Jakob Sauer Jorgensen, and
% Maria Saxild-Hansen, 2010-2017.
% With contibutions by Mikhail Romanov, Technical University of Denmark
% and Knud Cordua, University of Copenhagen.
% This file is part of the AIR Tools II package and is distributed under
% the 3-Clause BSD License. A separate license file should be provided as
% part of the package.
%
% Copyright 2017 Per Christian Hansen, Technical University of Denmark and
% Jakob Sauer Jorgensen, University of Manchester.
if nargin < 2, error('Not enought input arguments'), end
switch name
case 'shepplogan'
im = myphantom(N);
case 'smooth'
if nargin == 2
im = smooth(N);
else
im = smooth(N,P1);
end
case 'binary'
if nargin == 2
im = binary(N);
else
im = binary(N,P1);
end
case 'threephases'
if nargin == 2
im = threephases(N);
elseif nargin == 3
im = threephases(N,P1);
else
im = threephases(N,P1,P2);
end
case 'threephasessmooth'
if nargin ==2
im = threephasessmooth(N);
elseif nargin == 3
im = threephasessmooth(N,P1);
elseif nargin == 4
im = threephasessmooth(N,P1,P2);
else
im = threephasessmooth(N,P1,P2,P3);
end
case 'fourphases'
if nargin == 2
im = fourphases(N);
else
im = fourphases(N,P1);
end
case 'grains'
if nargin == 2
im = grains(N);
elseif nargin == 3
im = grains(N,P1);
else
im = grains(N,P1,P2);
end
case 'ppower'
if nargin ==2
im = ppower(N);
elseif nargin == 3
im = ppower(N,P1);
elseif nargin == 4
im = ppower(N,P1,P2);
else
im = ppower(N,P1,P2,P3);
end
case 'tectonic'
im = tectonic(N);
otherwise
error('Illegal phantom name')
end
% Subfunctions here ----------------------------------------------------
function X = myphantom(N)
%MYPHANTOM creates the modified Shepp-Logan phantom
% X = myphantom(N)
%
% This function create the modifed Shepp-Logan phantom with the
% discretization N x N, and returns it as a vector.
%
% Input:
% N Scalar denoting the nubmer of discretization intervals in each
% dimesion, such that the phantom head consists of N^2 cells.
%
% Output:
% X The modified phantom head reshaped as a vector
% This head phantom is the same as the Shepp-Logan except the intensities
% are changed to yield higher contrast in the image.
%
% Peter Toft, "The Radon Transform - Theory and Implementation", PhD
% thesis, DTU Informatics, Technical University of Denmark, June 1996.
% A a b x0 y0 phi
% ---------------------------------
e = [ 1 .69 .92 0 0 0
-.8 .6624 .8740 0 -.0184 0
-.2 .1100 .3100 .22 0 -18
-.2 .1600 .4100 -.22 0 18
.1 .2100 .2500 0 .35 0
.1 .0460 .0460 0 .1 0
.1 .0460 .0460 0 -.1 0
.1 .0460 .0230 -.08 -.605 0
.1 .0230 .0230 0 -.606 0
.1 .0230 .0460 .06 -.605 0 ];
xn = ((0:N-1)-(N-1)/2)/((N-1)/2);
Xn = repmat(xn,N,1);
Yn = rot90(Xn);
X = zeros(N);
% For each ellipse to be added
for i = 1:size(e,1)
a2 = e(i,2)^2;
b2 = e(i,3)^2;
x0 = e(i,4);
y0 = e(i,5);
phi = e(i,6)*pi/180;
A = e(i,1);
x = Xn-x0;
y = Yn-y0;
index = find(((x.*cos(phi) + y.*sin(phi)).^2)./a2 + ...
((y.*cos(phi) - x.*sin(phi))).^2./b2 <= 1);
% Add the amplitude of the ellipse
X(index) = X(index) + A;
end
% Ensure nonnegative elements.
X(X<0) = 0;
function im = smooth(N,p)
%SMOOTH Creates a 2D test image of a smooth function
% Per Christian Hansen, May 8, 2012, DTU Compute.
if nargin==1, p = 4; end
% Generate the image.
[I,J] = meshgrid(1:N);
sigma = 0.25*N;
c = [0.6*N 0.6*N; 0.5*N 0.3*N; 0.2*N 0.7*N; 0.8*N 0.2*N];
a = [1 0.5 0.7 0.9];
im = zeros(N,N);
for i=1:p
im = im + a(i)*exp( - (I-c(i,1)).^2/(1.2*sigma)^2 - (J-c(i,2)).^2/sigma^2);
end
im = im/max(im(:));
% -----------------------------------------------------------------------
function im = binary(N,seed)
%BINARY Creates a 2D binary test image
% Per Christian Hansen, June 9, 2013, DTU Compute. This function uses
% software kindly provided by Knud Cordua, Univ. of Copenhagen.
if nargin==2, rng(seed), end
% Prepare to generate random image.
TrainingImage = getTI;
C = ones(3); % Needed in the two functions below.
nCat = 1; % Ditto.
H = CompHistTrain(TrainingImage,C,nCat) + ...
CompHistTrain(fliplr(TrainingImage),C,nCat) + eps;
% Generate a random image.
im = sequential_simulation_full_clique(H,nCat,N,N,C);
% -----------------------------------------------------------------------
function im = threephases(N,p,seed)
%THREEPHASES Creates a 2D test image with three different phases
% Per Christian Hansen, Sept. 30, 2014, DTU Compute.
if nargin==1 || isempty(p), p = 100; end
if nargin==3, rng(seed), end
% Generate first image.
[I,J] = meshgrid(1:N);
sigma1 = 0.025*N;
c1 = rand(p,2)*N;
im1 = zeros(N,N);
for i=1:p
im1 = im1 + exp(-abs(I-c1(i,1)).^3/(2.5*sigma1)^3 ...
-abs(J-c1(i,2)).^3/sigma1^3);
end
t1 = 0.35;
im1(im1 < t1) = 0;
im1(im1 >= t1) = 2;
% Generate second image.
sigma2 = 0.025*N;
c2 = rand(p,2)*N;
im2 = zeros(N,N);
for i=1:p
im2 = im2 + exp(-(I-c2(i,1)).^2/(2*sigma2)^2-(J-c2(i,2)).^2/sigma2^2);
end
t2 = 0.55;
im2(im2 < t2) = 0;
im2(im2 >= t2) = 1;
% Combine the two images.
im = im1 + im2;
im(im == 3) = 1;
im = im/max(im(:));
% -----------------------------------------------------------------------
function im = threephasessmooth(N,p,v,seed)
%THREEPHASESSMOOTH Variant of threephases with smoothly varying intensities.
% Per Christian Hansen and Mikhail Romanov, July 6, 2015, DTU Compute.
if nargin==1 || isempty(p), p = 100; v = 1.8; end
if nargin==2, v = 1.8; end
if nargin==4, rng(seed), end
% Generate first image.
[I,J] = meshgrid(1:N);
sigma1 = 0.025*N;
c1 = rand(p,2)*N;
im1 = zeros(N,N);
for i=1:p
im1 = im1 + exp(-abs(I-c1(i,1)).^3/(2.5*sigma1)^3 ...
-abs(J-c1(i,2)).^3/sigma1^3);
end
t1 = 0.35;
im1(im1 < t1) = 0;
I1 = find(im1 >= t1);
im1(I1) = (im1(I1) - min(im1(I1)))/max(im1(:))*v + 0.8;
% Generate second image.
sigma2 = 0.025*N;
c2 = rand(p,2)*N;
im2 = zeros(N,N);
for i=1:p
im2 = im2 + exp(-(I-c2(i,1)).^2/(2*sigma2)^2-(J-c2(i,2)).^2/sigma2^2);
end
t2 = 0.55;
im2(im2 < t2) = 0;
I2 = find(im2 >= t2);
im2(I2) = (im2(I2) - min(im2(I2)))/max(im2(:))*v + 0.3;
% Combine the two images onto a smooth background..
im = (v/3)*ppower(N,1,2.5);
im(im1 > 0) = im1(im1 > 0);
im(im2 > 0) = im2(im2 > 0);
im = im/max(im(:));
% -----------------------------------------------------------------------
function im = fourphases(N,seed)
%FOURPHASES Creates a 2D test image with three different phases
% Per Christian Hansen and Mikhail Romanov, March. 1, 2015, DTU Compute.
if nargin==2, rng(seed), end
x = 1 - phantomgallery('binary',N);
x = bwlabel(x);
im = (mod(x+1,4) == 0)*0.33 + (mod(x+2,4) == 0)*0.66 + (mod(x+3,4) == 0);
% -----------------------------------------------------------------------
function im = grains(N,numGrains,seed)
%GRAINS Creates a test image of Voronoi cells
% Jakob Sauer Jorgensen, October 9, 2012, DTU Compute.
if nargin==1 || isempty(numGrains), numGrains = round(3*sqrt(N)); end
if nargin==3, rng(seed), end
% Prepare to create a bigger image, to avoid strange boundary grains.
dN = round(N/10);
Nbig = N + 2*dN;
total_dim = Nbig^2;
% Random pixels whose coordinates (xG,yG,zG) are the "centre" of the grains.
xG = ceil(Nbig*rand(numGrains,1));
yG = ceil(Nbig*rand(numGrains,1));
% Set up voxel coordinates for distance computation.
[X,Y] = meshgrid(1:Nbig);
X = X(:);
Y = Y(:);
% For centre pixel k [xG(k),yG(k),zG(k)] compute the distance to all the
% voxels in the box and store the distances in column k.
distArray = zeros(total_dim,numGrains);
for k = 1:numGrains
distArray(:,k) = (X-xG(k)).^2 + (Y-yG(k)).^2;
end
% Determine to which grain each of the voxels belong. This is found as the
% centre with minimal distance to the given voxel.
[~,minIdx] = min(distArray,[],2);
% Reshape to 2D, subtract 1 to have 0 as minimal value, extract the
% middle part of the image, and scale to have 1 as maximum value.
im = reshape(minIdx,repmat(Nbig,1,2)) - 1;
im = im(dN+(1:N),dN+(1:N));
im = im/max(im(:));
% -----------------------------------------------------------------------
function F = ppower(N,relnz,p,seed)
%PPOWER Creates a 2D test image with patterns of nonzero pixels
% Per Christian Hansen and Jakob Sauer Jorgensen, July 6, 2015.
% Reference: J. S. Jorgensen, E. Y. Sidky, P. C. Hansen, and X. Pan,
% Empirical average-case relation between undersampling and sparsity in
% X-ray CT, submitted.
if nargin<2 || isempty(relnz), relnz = 0.3; end
if nargin<3 || isempty(p), p = 2; end
if nargin==4, rng(seed), end
if N/2 == round(N/2), Nodd = false; else Nodd = true; N = N+1; end
P = randn(N,N);
[I,J] = meshgrid(1:N);
U = ( ( (2*I-1)/N - 1).^2 + ( (2*J-1)/N - 1).^2 ).^(-p/2);
F = U.*exp(2*pi*sqrt(-1)*P);
F = abs(ifft2(F));
f = sort(F(:),'descend');
k = round(relnz*N^2);
F( F < f(k) ) = 0;
F = F/f(1);
if Nodd, F = F(1:end-1,1:end-1); end
% -----------------------------------------------------------------------
function x = tectonic(N)
% Creates a tectonic phantom of size N x N.
x = zeros(N);
N5 = round(N/5);
N13 = round(N/13);
N7 = round(N/7);
N20 = round(N/20);
% The right plate.
x(N5:N5+N7,5*N13:end) = 0.75;
% The angle of the right plate.
i = N5;
for j = 1:N20
if rem(j,2) ~= 0
i = i - 1;
x(i,5*N13+j:end) = 0.75;
end
end
% The left plate before the break.
x(N5:N5+N5,1:5*N13) = 1;
% The break from the left plate.
vector = N5:N5+N5;
for j = 5*N13:min(12*N13,N)
if rem(j,2) ~= 0
vector = vector + 1;
end
x(vector,j) = 1;
end
% ------ Below here: subfunctions for 'binary' --------------------------
function H = CompHistTrain(Z, N, sV)
%
% INPUTS
% Z binary valued training image (for now... )
% N binary neighborhood mask
% sV the image must have the categories 0,1,...,sV
%
% OUTPUT
% H image
nc = 1; mc = 1; pc = 1;
% Size of the training image and the neighbourhood mask.
[nZ, mZ, pZ] = size(Z);
[nN, mN, pN] = size(N);
sN = sum(N(:));
% Base of the conversion from neighborhood to ID
base = ((sV+1)*ones(1,sN)).^(0:sN-1);
% Indexes of the voxels
index = reshape(1:nZ*mZ*pZ, [nZ, mZ, pZ]);
% Histogram
H = zeros(1,(sV+1)^sN);
% For all inner voxels
for k = pc : pZ-(pN-pc)
for j = mc : mZ-(mN-mc)
for i = nc : nZ-(nN-nc)
% The indexes of the rectangular neighborhood
dim1 = i-nc+1 : i-nc+nN;
dim2 = j-mc+1 : j-mc+mN;
dim3 = k-pc+1 : k-pc+pN;
% Neighbors ID of the voxel
ijk = index(dim1,dim2,dim3);
% Voxel values of Nk
zijk = Z(ijk);
nijk = zijk(N==1);
% Identify neighborhood id:
hijk = n2id(nijk(:), base);
%Modified by ksc:
H(1, hijk) = H(1, hijk) + 1;
end
end
end
function sim = sequential_simulation_full_clique(H,sV,ny,nx,C)
%
% Input parameters:
% H: Histogram of patterns
% Sv: Number of categories (Sv=1 for two categories).
% ny: Number of vertical nodes in the simulated field
% nx: Number of horizontal nodes in the simulated field
% C: The clique (i.e. template for pattern scanning)
% N_real: Number of realizations to be produced.
%
% Output parameter:
% sim: An array with size = [ny nx] that contains the realization.
H_full_clique = H;
% Size of clique;
[NyC,NxC] = size(C);
% Initialize arrays:
sim = ones(ny,nx).*NaN;
prob = zeros(ny,nx);
% Simulate the first unconditional pattern:
norm = sum(H_full_clique);
cdf = cumsum(H_full_clique)/norm;
r = rand;
id = find(cdf>r,1);
prob(1,1) = H_full_clique(id)/norm;
sN = NyC*NxC;
n = id2n(id,sV,sN); % Find the pattern associated with the id
sim(1:NyC,1:NxC) = reshape(n,NyC,NxC);
% Simulate the first row of residuals/seperators:
i=1:NyC;
for j=NxC+1:nx
% Position of the full clique to be considered:
marginal=sim(i,j-NxC+1:j);
marginal(isnan(marginal))=-1;
% Find the position at which the known values are located:
ids=marg2id(marginal(:));
pdf=H_full_clique(ids)/sum(H_full_clique(ids));
cdf=cumsum(pdf)/sum(pdf);
r=rand;
pos=find(cdf>r,1);
id=ids(pos);
prob(1,j)=H_full_clique(id)/sum(H_full_clique);
n=id2n(id,sV,sN); % Find the pattern associated with the id
n=reshape(n,NyC,NxC);
sim(i,j)=n(:,end);
end
for i=NyC+1:ny
for j=NxC:nx
if j==NxC % Left side of the simulation area
% Position of the full clique to be considered:
marginal=sim(i-NyC+1:i,j-NxC+1:j);
marginal(isnan(marginal))=-1;
ids=marg2id(marginal(:));
if sum(H_full_clique(ids))==0,
error('Zero probabiltiy pattern event! Please add a homogeneous distribution'),
end
pdf=H_full_clique(ids)/sum(H_full_clique(ids));
cdf=cumsum(pdf)/sum(pdf);
r=rand;
pos=find(cdf>r,1);
id=ids(pos);
prob(i,j)=H_full_clique(id)/sum(H_full_clique);
n=id2n(id,sV,sN); % Find the pattern associated with the id
n=reshape(n,NyC,NxC);
sim(i,1:j)=n(end,:);
else % Rest of the nodes to be simulated:
% Position of the full clique to be considered:
marginal=sim(i-NyC+1:i,j-NxC+1:j);
marginal(isnan(marginal))=-1;
ids=marg2id(marginal(:));
if sum(H_full_clique(ids))==0,
error('Zero probabiltiy pattern event! Please add a homogeneous distribution'),
end
pdf=H_full_clique(ids)/sum(H_full_clique(ids));
cdf=cumsum(pdf)/sum(pdf);
r=rand;
pos=find(cdf>r,1);
id=ids(pos);
prob(i,j)=H_full_clique(id)/sum(H_full_clique);
n=id2n(id,sV,sN);
n=reshape(n,NyC,NxC);
sim(i,j)=n(end,end);
end
end
end
function n = id2n(id, sV, sN)
%
% INPUT
% id scalar, integer ID number of the neighborhood, id > 0
% sV scalar, number of different values the voxels can take, sV = 1
% for binary images
% sN scalar, number of neighbors of a voxel (not on the boundary)
%
% OUTPUT
% n vector, sN x 1, with the values of the voxels in the neighborhood
n = zeros(sN,1);
id = id - 1;
for i = 1:sN
idi = floor(id / (sV+1));
n(i) = id - (sV+1)*idi;
id = idi;
end
function id = n2id(n, base)
% n2id: assigns ID number to a neighborhood
%
% INPUT
% n vector, sN x 1, with the values of the voxels in the
% neighborhood
% base vector, 1 x sN, base = (sV*ones(1,sN)).^(0:sN-1), see id2n for
% definitions of sV and sN
%
% OUTPUT
% id scalar, integer ID number of the neighborhood, id > 0.
id = base * n + 1;
function id=marg2id(marginal)
% The id outcomes of this function should be used to calculate marginals by
% summing the probabilities related to these ids.
mm = zeros(length(marginal),1);
mm(marginal>-1) = 1;
marg_dim = sum(mm);
sV = 2; %(only tested for binary images, sV=2)
sN = length(marginal);
index = 1:sV^sN;
Index = zeros(sV^sN,marg_dim);
c = 0;
for i=1:sN
if marginal(i) >= 0
c = c+1;
% All indeces:
index_tmp = reshape(index,sV^(i-1),sV^sN/sV^(i-1));
% Indeces used for the particular numbers:
index_use = index_tmp(:,marginal(i)+1:2:sV^sN/sV^(i-1));
Index(index_use(:),c) = 1;
end
end
id = find(sum(Index,2)==marg_dim);
function A = getTI
%
% Create the binary training image.
IJ = [
9 1
10 1
22 1
23 1
24 1
46 1
47 1
48 1
59 1
60 1
61 1
76 1
77 1
78 1
79 1
9 2
10 2
22 2
23 2
24 2
25 2
45 2
46 2
47 2
48 2
59 2
60 2
61 2
75 2
76 2
77 2
78 2
8 3
9 3
10 3
22 3
23 3
24 3
25 3
26 3
44 3
45 3
46 3
47 3
58 3
59 3
60 3
74 3
75 3
76 3
77 3
8 4
9 4
10 4
21 4
22 4
23 4
25 4
26 4
27 4
44 4
45 4
58 4
59 4
60 4
73 4
74 4
75 4
76 4
8 5
9 5
10 5
21 5
22 5
23 5
26 5
27 5
28 5
43 5
44 5
45 5
57 5
58 5
59 5
72 5
73 5
74 5
75 5
8 6
9 6
10 6
20 6
21 6
22 6
28 6
29 6
30 6
42 6
43 6
44 6
55 6
56 6
57 6
58 6
59 6
71 6
72 6
73 6
8 7
9 7
10 7
20 7
21 7
29 7
30 7
31 7
42 7
43 7
53 7
54 7
55 7
56 7
57 7
58 7
59 7
70 7
71 7
72 7
73 7
8 8
9 8
10 8
20 8
21 8
29 8
30 8
31 8
42 8
43 8
53 8
54 8
55 8
58 8
59 8
69 8
70 8
71 8
72 8
8 9
9 9
10 9
19 9
20 9
21 9
30 9
31 9
42 9
43 9
52 9
53 9
54 9
58 9
59 9
69 9
70 9
71 9
8 10
9 10
10 10
19 10
20 10
21 10
30 10
31 10
32 10
41 10
42 10
43 10
51 10
52 10
53 10
58 10
59 10
60 10
68 10
69 10
70 10
8 11
9 11
10 11
19 11
20 11
21 11
30 11
31 11
32 11
41 11
42 11
43 11
50 11
51 11
52 11
58 11
59 11
60 11
68 11
69 11
70 11
9 12
10 12
11 12
19 12
20 12
21 12
30 12
31 12
32 12
41 12
42 12
43 12
49 12
50 12
51 12
59 12
60 12
68 12
69 12
70 12
10 13
11 13
12 13
19 13
20 13
21 13
30 13
31 13
32 13
41 13
42 13
43 13
49 13
50 13
51 13
59 13
60 13
68 13
69 13
70 13
10 14
11 14
12 14
13 14
19 14
20 14
21 14
30 14
31 14
32 14
41 14
42 14
43 14
49 14
50 14
51 14
59 14
60 14
61 14
68 14
69 14
70 14
10 15
11 15
12 15
13 15
14 15
15 15
19 15
20 15
21 15
30 15
31 15
32 15
40 15
41 15
42 15
43 15
49 15
50 15
51 15
60 15
61 15
62 15
68 15
69 15
70 15
11 16
12 16
13 16
14 16
15 16
16 16
17 16
20 16
21 16
30 16
31 16
32 16
40 16
41 16
42 16
43 16
49 16
50 16
51 16
60 16
61 16
62 16
69 16
70 16
71 16
11 17
12 17
15 17
16 17
17 17
18 17
19 17
20 17
21 17
30 17
31 17
32 17
39 17
40 17
41 17
42 17
43 17
44 17
49 17
50 17
51 17
61 17
62 17
63 17
70 17
71 17
72 17
11 18
12 18
17 18
18 18
19 18
20 18
21 18
22 18
31 18
32 18
33 18
38 18
39 18
40 18
42 18
43 18
44 18
49 18
50 18
51 18
61 18
62 18
63 18
71 18
72 18
11 19
12 19
19 19
20 19
21 19
22 19
31 19
32 19
33 19
38 19
39 19
43 19
44 19
50 19
51 19
62 19
63 19
64 19
71 19
72 19
73 19
11 20
12 20
13 20
20 20
21 20
22 20
31 20
32 20
33 20
37 20
38 20
39 20
43 20
44 20
50 20
51 20
52 20
62 20
63 20
64 20
72 20
73 20
12 21
13 21
20 21
21 21
22 21
31 21
32 21
33 21
37 21
38 21
43 21
44 21
45 21
50 21
51 21
52 21
63 21
64 21
65 21
72 21
73 21
74 21
12 22
13 22
14 22
21 22
22 22
23 22
24 22
32 22
33 22
36 22
37 22
38 22
44 22
45 22
50 22
51 22
52 22
63 22
64 22
65 22
73 22
74 22
13 23
14 23
22 23
23 23
24 23
32 23
33 23
36 23
37 23
44 23
45 23
50 23
51 23
52 23
63 23
64 23
65 23
73 23
74 23
75 23
13 24
14 24
15 24
23 24
24 24
25 24
32 24
33 24
34 24
35 24
36 24
37 24
44 24
45 24
46 24
51 24
52 24
63 24
64 24
73 24
74 24
75 24
14 25
15 25
16 25
24 25
25 25
32 25
33 25
34 25
35 25
36 25
44 25
45 25
46 25
51 25
52 25
62 25
63 25
64 25
73 25
74 25
75 25
76 25
1 26
14 26
15 26
16 26
25 26
26 26
32 26
33 26
34 26
35 26
44 26
45 26
46 26
51 26
52 26
53 26
62 26
63 26
64 26
73 26
74 26
75 26
76 26
1 27
15 27
16 27
17 27
25 27
26 27
32 27
33 27
44 27
45 27
46 27
51 27
52 27
53 27
61 27
62 27
63 27
72 27
73 27
74 27
75 27
76 27
77 27
1 28
2 28
15 28
16 28
17 28
25 28
26 28
32 28
33 28
34 28
44 28
45 28
46 28
51 28
52 28
53 28
61 28
62 28
63 28
72 28
73 28
74 28
76 28
77 28
1 29
2 29
15 29
16 29
25 29
26 29
31 29
32 29
33 29
34 29
35 29
45 29
46 29
52 29
53 29
60 29
61 29
62 29
72 29
73 29
76 29
77 29
78 29
1 30
2 30
15 30
16 30
25 30
26 30
30 30
31 30
32 30
33 30
34 30
35 30
36 30
45 30
46 30
52 30
53 30
54 30
60 30
61 30
71 30
72 30
73 30
76 30
77 30
78 30
1 31
2 31
3 31
14 31
15 31
16 31
24 31
25 31
26 31
30 31
31 31
32 31
34 31
35 31
36 31
44 31
45 31
46 31
47 31
52 31
53 31
54 31
59 31
60 31
61 31
71 31
72 31
73 31
77 31
78 31
2 32
3 32
13 32
14 32
15 32
24 32
25 32
30 32
31 32
35 32
36 32
43 32
44 32
45 32
46 32
47 32
48 32
53 32
54 32
59 32
60 32
71 32
72 32
77 32
78 32
2 33
3 33
4 33
13 33
14 33
15 33
24 33
25 33
29 33
30 33
31 33
35 33
36 33
42 33
43 33
44 33
46 33
47 33
48 33
53 33
54 33
59 33
60 33
71 33
72 33
77 33
78 33
79 33
3 34
4 34
13 34
14 34
24 34
25 34
29 34
30 34
35 34
36 34
37 34
41 34
42 34
43 34
46 34
47 34
48 34
53 34
54 34
55 34
59 34
60 34
70 34
71 34
72 34
77 34
78 34
79 34
3 35
4 35
12 35
13 35
14 35
24 35
25 35
29 35
30 35
35 35
36 35
37 35
41 35
42 35
43 35
46 35
47 35
48 35
54 35
55 35
56 35
58 35
59 35
60 35
70 35
71 35
72 35
77 35
78 35
79 35
3 36
4 36
5 36
12 36
13 36
14 36
23 36
24 36
25 36
28 36
29 36
30 36
35 36
36 36
37 36
40 36
41 36
42 36
46 36
47 36
48 36
55 36
56 36
57 36
58 36
59 36
70 36
71 36
72 36
78 36
79 36
3 37
4 37
5 37
12 37
13 37
14 37
23 37
24 37
28 37
29 37
35 37
36 37
37 37
40 37
41 37
42 37
45 37
46 37
47 37
57 37
58 37
59 37
70 37
71 37
72 37
78 37
79 37
3 38
4 38
5 38
12 38
13 38
14 38
22 38
23 38
24 38
28 38
29 38
35 38
36 38
37 38
40 38
41 38
42 38
45 38
46 38
47 38
57 38
58 38
59 38
69 38
70 38
71 38
78 38
79 38
3 39
4 39
5 39
11 39
12 39
13 39
14 39
22 39
23 39
24 39
27 39
28 39
29 39
35 39
36 39
37 39
40 39
41 39
44 39
45 39
46 39
57 39
58 39
59 39
69 39
70 39
71 39
78 39
79 39
80 39
3 40
4 40
5 40
11 40
12 40
13 40
22 40
23 40
24 40
27 40
28 40
29 40
35 40
36 40
37 40
40 40
41 40
42 40
43 40
44 40
45 40
57 40
58 40
59 40
69 40
70 40
71 40
78 40
79 40
80 40
3 41
4 41
11 41
12 41
13 41
21 41
22 41
23 41
27 41
28 41
29 41
35 41
36 41
37 41
40 41
41 41
42 41
43 41
56 41
57 41
58 41
59 41
60 41
69 41
70 41
71 41
78 41
79 41
80 41
3 42
4 42
10 42
11 42
12 42
21 42
22 42
23 42
28 42
29 42
35 42
36 42
40 42
41 42
42 42
56 42
57 42
58 42
59 42
60 42
69 42
70 42
71 42
78 42
79 42
80 42
3 43
4 43
10 43
11 43
12 43
21 43
22 43
28 43
29 43
35 43
36 43
40 43
41 43
42 43
55 43
56 43
57 43
59 43
60 43
61 43
69 43
70 43
71 43
78 43
79 43
80 43
3 44
4 44
9 44
10 44
11 44
20 44
21 44
22 44
28 44
29 44
30 44
34 44
35 44
36 44
40 44
41 44
42 44
55 44
56 44
57 44
60 44
61 44
69 44
70 44
77 44
78 44
79 44
3 45
4 45
9 45
10 45
11 45
20 45
21 45
29 45
30 45
34 45
35 45
40 45
41 45
42 45
55 45
56 45
57 45
60 45
61 45
69 45
70 45
77 45
78 45
79 45
2 46
3 46
4 46
9 46
10 46
11 46
19 46
20 46
21 46
29 46
30 46
34 46
35 46
40 46
41 46
42 46
54 46
55 46
56 46
60 46
61 46
62 46
68 46
69 46
70 46
77 46
78 46
79 46
2 47
3 47
9 47
10 47
11 47
18 47
19 47
20 47
21 47
30 47
31 47
32 47
33 47
34 47
35 47
40 47
41 47
42 47
54 47
55 47
56 47
61 47
62 47
68 47
69 47
70 47
76 47
77 47
78 47
2 48
3 48
9 48
10 48
11 48
17 48
18 48
19 48
20 48
21 48
22 48
30 48
31 48
32 48
33 48
34 48
41 48
42 48
53 48
54 48
55 48
61 48
62 48
68 48
69 48
70 48
76 48
77 48
78 48
2 49
3 49
4 49
9 49
10 49
11 49
16 49
17 49
18 49
21 49
22 49
31 49
32 49
33 49
41 49
42 49
52 49
53 49
54 49
61 49
62 49
63 49
67 49
68 49
69 49
75 49
76 49
77 49
2 50
3 50
4 50
9 50
10 50
11 50
14 50
15 50
16 50
17 50
21 50
22 50
23 50
32 50
33 50
34 50
41 50
42 50
51 50
52 50
53 50
54 50
62 50
63 50
67 50
68 50
69 50
75 50
76 50
77 50
3 51
4 51
10 51
11 51
12 51
13 51
14 51
15 51
22 51
23 51
24 51
32 51
33 51
34 51
41 51
42 51
51 51
52 51
53 51
62 51
63 51
67 51
68 51
74 51
75 51
76 51
3 52
4 52
5 52
10 52
11 52
12 52
13 52
14 52
23 52
24 52
33 52
34 52
41 52
42 52
43 52
51 52
52 52
62 52
63 52
64 52
65 52
66 52
67 52
68 52
74 52
75 52
76 52
4 53
5 53
6 53
11 53
12 53
13 53
23 53
24 53
33 53
34 53
41 53
42 53
43 53
51 53
52 53
63 53
64 53
65 53
66 53
73 53
74 53
75 53
4 54
5 54
6 54
11 54
12 54
13 54
23 54
24 54
25 54
33 54
34 54
42 54
43 54
51 54
52 54
63 54
64 54
65 54
66 54
73 54
74 54
75 54
4 55
5 55
6 55
12 55
13 55
14 55
23 55
24 55
25 55
33 55
34 55
42 55
43 55
51 55
52 55
63 55
64 55
65 55
73 55
74 55
75 55
4 56
5 56
6 56
12 56
13 56
14 56
23 56
24 56
25 56
33 56
34 56
35 56
42 56
43 56
51 56
52 56
53 56
63 56
64 56
65 56
73 56
74 56
75 56
4 57
5 57
6 57
12 57
13 57
14 57
15 57
23 57
24 57
25 57
33 57
34 57
35 57
42 57
43 57
44 57
51 57
52 57
53 57
63 57
64 57
65 57
73 57
74 57
75 57
4 58
5 58
6 58
13 58
14 58
15 58
23 58
24 58
25 58
33 58
34 58
35 58
42 58
43 58
44 58
52 58
53 58
54 58
63 58
64 58
65 58
73 58
74 58
75 58
4 59
5 59
14 59
15 59
16 59
22 59
23 59
24 59
33 59
34 59
43 59
44 59
53 59
54 59
63 59
64 59
65 59
74 59
75 59
4 60
5 60
15 60
16 60
22 60
23 60
33 60
34 60
43 60
44 60
53 60
54 60
55 60
64 60
65 60
66 60
74 60
75 60
76 60
4 61
5 61
15 61
16 61
17 61
21 61
22 61
23 61
33 61
34 61
44 61
45 61
54 61
55 61
65 61
66 61
67 61
75 61
76 61
77 61
4 62
5 62
15 62
16 62
17 62
21 62
22 62
23 62
32 62
33 62
34 62
44 62
45 62
54 62
55 62
56 62
66 62
67 62
68 62
75 62
76 62
77 62
4 63
5 63
16 63
17 63
21 63
22 63
32 63
33 63
34 63
44 63
45 63
54 63
55 63
56 63
66 63
67 63
68 63
76 63
77 63
78 63
4 64
5 64
16 64
17 64
18 64
20 64
21 64
22 64
32 64
33 64
34 64
44 64
45 64
46 64
55 64
56 64
67 64
68 64
69 64
77 64
78 64
4 65
5 65
16 65
17 65
18 65
20 65
21 65
22 65
31 65
32 65
33 65
44 65
45 65
46 65
55 65
56 65
57 65
67 65
68 65
69 65
77 65
78 65
79 65
4 66
5 66
6 66
16 66
17 66
18 66
20 66
21 66
30 66
31 66
32 66
44 66
45 66
46 66
56 66
57 66
67 66
68 66
69 66
78 66
79 66
80 66
4 67
5 67
6 67
16 67
17 67
18 67
19 67
20 67
21 67
30 67
31 67
32 67
45 67
46 67
56 67
57 67
58 67
67 67
68 67
69 67
79 67
80 67
4 68
5 68
6 68
16 68
17 68
18 68
19 68
20 68
29 68
30 68
31 68
45 68
46 68
57 68
58 68
59 68
67 68
68 68
69 68
79 68
80 68
81 68
5 69
6 69
16 69
17 69
18 69
19 69
28 69
29 69
30 69
31 69
44 69
45 69
46 69
47 69
57 69
58 69
59 69
60 69
67 69
68 69
69 69
79 69
80 69
81 69
5 70
6 70
15 70
16 70
17 70
18 70
28 70
29 70
30 70
44 70
45 70
46 70
58 70
59 70
60 70
67 70
68 70
79 70
80 70
81 70
5 71
6 71
15 71
16 71
17 71
27 71
28 71
29 71
30 71
44 71
45 71
46 71
59 71
60 71
61 71
67 71
68 71
79 71
80 71
5 72
6 72
14 72
15 72
16 72
26 72
27 72
29 72
30 72
44 72
45 72
46 72
59 72
60 72
61 72
66 72
67 72
68 72
78 72
79 72
80 72
4 73
5 73
6 73
13 73
14 73
15 73
25 73
26 73
27 73
29 73
30 73
31 73
43 73
44 73
45 73
59 73
60 73
61 73
66 73
67 73
68 73
78 73
79 73
4 74
5 74
6 74
12 74
13 74
14 74
15 74
25 74
26 74
27 74
30 74
31 74
43 74
44 74
45 74
59 74
60 74
61 74
66 74
67 74
68 74
77 74
78 74
79 74
4 75
5 75
11 75
12 75
13 75
14 75
24 75
25 75
26 75
30 75
31 75
32 75
43 75
44 75
45 75
59 75
60 75
61 75
66 75
67 75
76 75
77 75
78 75
3 76
4 76
5 76
11 76
12 76
13 76
23 76
24 76
25 76
31 76
32 76
43 76
44 76
45 76
59 76
60 76
61 76
66 76
67 76
76 76
77 76
78 76
3 77
4 77
11 77
12 77
13 77
22 77
23 77
24 77
31 77
32 77
33 77
43 77
44 77
45 77
59 77
60 77
61 77
65 77
66 77
67 77
75 77
76 77
77 77
2 78
3 78
4 78
11 78
12 78
13 78
22 78
23 78
32 78
33 78
42 78
43 78
44 78
45 78
58 78
59 78
60 78
65 78
66 78
67 78
75 78
76 78
77 78
1 79
2 79
3 79
11 79
12 79
13 79
21 79
22 79
23 79
32 79
33 79
34 79
42 79
43 79
44 79
57 79
58 79
59 79
60 79
65 79
66 79
75 79
76 79
77 79
1 80
2 80
3 80
11 80
12 80
13 80
14 80
20 80
21 80
22 80
32 80
33 80
34 80
43 80
44 80
57 80
58 80
59 80
65 80
66 80
75 80
76 80
77 80
1 81
2 81
12 81
13 81
14 81
15 81
19 81
20 81
32 81
33 81
34 81
43 81
44 81
45 81
56 81
57 81
58 81
64 81
65 81
66 81
75 81
76 81
77 81
1 82
2 82
13 82
14 82
15 82
16 82
17 82
18 82
19 82
32 82
33 82
34 82
44 82
45 82
46 82
55 82
56 82
57 82
58 82
64 82
65 82
75 82
76 82
77 82
14 83
15 83
16 83
17 83
18 83
32 83
33 83
34 83
45 83
46 83
47 83
55 83
56 83
57 83
64 83
65 83
75 83
76 83
77 83
15 84
16 84
17 84
32 84
33 84
34 84
46 84
47 84
48 84
54 84
55 84
56 84
57 84
64 84
65 84
75 84
76 84
];
A = sparse(IJ(:,1),IJ(:,2),1);
A = full(A); |
github | jakobsj/AIRToolsII-master | seismictomo.m | .m | AIRToolsII-master/testprobs/seismictomo.m | 9,003 | utf_8 | 25f3cb17c60fb0759abbc4980eee1842 | function [A,b,x,s,p] = seismictomo(N,s,p,isDisp,isMatrix)
%SEISMICTOMO Creates a 2D seismic travel-time tomography test problem
%
% [A,b,x,s,p] = seismictomo(N)
% [A,b,x,s,p] = seismictomo(N,s)
% [A,b,x,s,p] = seismictomo(N,s,p)
% [A,b,x,s,p] = seismictomo(N,s,p,isDisp)
% [A,b,x,s,p] = seismictomo(N,s,p,isDisp,isMatrix)
%
% This function uses the "line model" to create a 2D seismic travel-time
% tomography test problem with an N-times-N pixel domain, using s sources
% located on the right boundary and p receivers (seismographs) scattered
% along the left and top boundary. The rays are transmitted from each
% source to each receiver.
%
% Inupt:
% N Scalar denoting the number of discretization intervals in
% each dimesion, such that the domain consists of N^2 cells.
% s The number of sources in the right side of the domain.
% Default s = N.
% p The number of receivers (seismographs) equally spaced on the
% surface and on the left side of the domain. Default p = 2*N.
% isDisp If isDisp is nonzero it specifies the time in seconds
% to pause in the display of the rays. If zero (the default),
% no display is shown.
% isMatrix If non-zero, a sparse matrix is returned in A (default).
% If zero, instead a function handle is returned.
%
% Output:
% A If input isMatrix is 1 (default): coefficient matrix with
% N^2 columns and length(theta)*p rows.
% If input isMatrix is 0: A function handle representing a
% matrix-free version of A in which the forward and backward
% operations are computed as A(x,'notransp') and A(y,'transp'),
% respectively, for column vectors x and y of appropriate size.
% The size of A can be retrieved using A([],'size'). The matrix
% is never formed explicitly, thus saving memory.
% b Vector containing the rhs of the test problem.
% x Vector containing the exact solution, with elements
% between 0 and 1.
% s The number of sources.
% p The number of receivers (seismographs).
%
% See also: paralleltomo, fancurvedtomo, fanlineartomo, seismicwavetomo,
% sphericaltomo.
% Code written by: Per Christian Hansen, Jakob Sauer Jorgensen, and
% Maria Saxild-Hansen, 2010-2017.
% This file is part of the AIR Tools II package and is distributed under
% the 3-Clause BSD License. A separate license file should be provided as
% part of the package.
%
% Copyright 2017 Per Christian Hansen, Technical University of Denmark and
% Jakob Sauer Jorgensen, University of Manchester.
if nargin < 5 || isempty(isMatrix)
isMatrix = 1;
end
if nargin < 4 || isempty(isDisp)
isDisp = 0;
end
% Default number of sources.
if nargin < 2 || isempty(s)
s = N;
end
if length(s)>1, error('s must be a scaler'), end
% Default number of receivers (seismographs).
if nargin < 3 || isempty(p)
p = 2*N;
end
% Construct either matrix or function handle
if isMatrix
A = get_or_apply_system_matrix(N,s,p,isDisp);
else
A = @(U,TRANSP_FLAG) get_or_apply_system_matrix(...
N,s,p,isDisp,U,TRANSP_FLAG);
end
% Create the phantom.
if nargout > 1
x = phantomgallery('tectonic',N);
x = x(:);
if isMatrix
b = A*x;
else
b = A(x,'notransp');
end
end
function A = get_or_apply_system_matrix(N,s,p,isDisp,u,transp_flag)
N2 = N/2;
% Determine the positions of the sources.
Ns = (N/s)/2;
x0 = N2*ones(s,1);
y0 = linspace(-N2+Ns,N2-Ns,s)';
% The intersection lines.
x = (-N2:N2)';
y = (-N2:N2)';
% The positions of the seismographs.
p1 = ceil(p/2);
p2 = floor(p/2);
Np1 = (N/p1)/2;
Np2 = (N/p2)/2;
xp = [-N2*ones(p2,1); linspace(-N2+Np1,N2-Np1,p1)'];
yp = [linspace(-N2+Np2,N2-Np2,p2)'; N2*ones(p1,1)];
% Prepare for illustration.
if isDisp
AA = phantomgallery('tectonic',N); % rand(N);
figure
end
% Deduce whether to set up matrix or apply to input, depending on whether
% input u is given.
isMatrix = (nargin < 5);
if isMatrix
% Initialize the index for storing the results and the number of angles.
idxend = 0;
rows = zeros(2*N*s*p,1);
cols = rows;
vals = rows;
II = 1:s;
JJ = 1:p;
else
% If transp_flag is 'size', only return size of operator, otherwise set
% proper size of output.
switch transp_flag
case 'size'
A = [p*s,N^2];
return
case 'notransp' % Forward project.
if length(u) ~= N^2, error('Incorrect length of input vector'), end
A = zeros(p*s,1);
case 'transp' % Backproject
if length(u) ~= p*s, error('Incorrect length of input vector'), end
A = zeros(N^2,1);
end
% If u is a Cartesian unit vector then we only want to compute a single
% row of A; otherwise we want to multiply with A or A'.
if strcmpi(transp_flag,'transp') && nnz(u) == 1 && sum(u) == 1
% Want to compute a single row of A, stored as a column vector.
ell = find(u==1);
JJ = mod(ell,p); if JJ==0, JJ = p; end
II = (ell-JJ)/p + 1;
else
% Want to multiply with A or A'.
II = 1:s;
JJ = 1:p;
end
end
% Loop over all the sources.
for i = II
% Illustation of the domain
if isDisp
clf
pause(isDisp)
imagesc((-N2+.5):(N2-0.5),(-N2+.5):(N2-0.5),flipud(AA))
colormap gray
hold on
axis xy
axis equal
axis([-N2 N2 -N2 N2])
plot(x0,y0,'o','color',[60 179 113]/255,'linewidth',2,...
'markersize',10)
plot(xp,yp,'sb','MarkerSize',10,'linewidth',2)
end
% Determine the direction vector (a b).
a = xp - x0(i);
b = yp - y0(i);
% Loop over the seismographs.
for j = JJ
% Use the parametrization of a line to get the y-coordinates of
% intersections with x = constant.
tx = (x - x0(i))/a(j);
yx = b(j)*tx + y0(i);
% Use the parametrisation of a line to get the y-coordinates of
% intersections with y = constant.
ty = (y - y0(i))/b(j);
xy = a(j)*ty + x0(i);
% Illustration of the rays.
if isDisp
plot(x,yx,'-','color',[220 0 0]/255,'linewidth',1.5)
plot(xy,y,'-','color',[220 0 0]/255,'linewidth',1.5)
set(gca,'Xtick',[],'Ytick',[])
pause(isDisp)
end
% Collect the intersection coordinates and times.
t = [tx; ty];
xxy = [x; xy];
yxy = [yx; y];
% Sort the times.
[~,I] = sort(t);
xxy = xxy(I);
yxy = yxy(I);
% Skip the points outside the box.
I = find(xxy >= -N2 & xxy <= N2 & yxy >= -N2 & yxy <= N2);
xxy = xxy(I);
yxy = yxy(I);
% Skip double points.
I = find(abs(diff(xxy)) <= 1e-10 & abs(diff(yxy)) <= 1e-10);
xxy(I) = [];
yxy(I) = [];
% Calculate the lengths within the cells and the determine the
% number of cells which are hit.
aval = sqrt(diff(xxy).^2 + diff(yxy).^2);
%numvals = numel(aval);
col = [];
% Store the values inside the box.
if numel(aval) > 0
% Calculates the midpoints of the line within the cells.
xm = 0.5*(xxy(1:end-1) + xxy(2:end)) + N2;
ym = 0.5*(yxy(1:end-1) + yxy(2:end)) + N2;
% Translate the midpoint coordinates to index.
col = floor(xm)*N + (N - floor(ym));
end
if ~isempty(col)
if isMatrix
% Create the indices to store the values to a vector for
% later creation of A matrix.
idxstart = idxend + 1;
idxend = idxstart + numel(col) - 1;
idx = idxstart:idxend;
% Store row numbers, column numbers and values.
rows(idx) = (i-1)*p + j;
cols(idx) = col;
vals(idx) = aval;
else
% If any nonzero elements, apply forward or back operator
if strcmp(transp_flag,'notransp')
% Insert inner product with u into w.
A( (i-1)*p+j ) = aval'*u(col);
else % Adjoint operator.
A(col) = A(col) + u( (i-1)*p+j )*aval;
end
end
end
end % end j
end % end i
if isMatrix
% Truncate excess zeros.
rows = rows(1:idxend);
cols = cols(1:idxend);
vals = vals(1:idxend);
% Create sparse matrix A from the stored values.
A = sparse(rows,cols,vals,s*p,N^2);
end
|
github | jakobsj/AIRToolsII-master | sphericaltomo.m | .m | AIRToolsII-master/testprobs/sphericaltomo.m | 9,004 | utf_8 | cfa790c762f9aa4e5885890185e2bd35 | function [A,b,x,angles,numCircles] = ...
sphericaltomo(N,angles,numCircles,isDisp,isMatrix)
%SPHERICALTOMO Creates a 2D spherical Radon tomography test problem
%
% [A,b,x,angles,numCircles] = sphericaltomo(N)
% [A,b,x,angles,numCircles] = sphericaltomo(N,angles)
% [A,b,x,angles,numCircles] = sphericaltomo(N,angles,numCircles)
% [A,b,x,angles,numCircles] = sphericaltomo(N,angles,numCircles,isDisp)
% [A,b,x,angles,numCircles] = sphericaltomo(N,angles,numCircles,...
% isDisp,isMatrix)
%
% This function genetates a tomography test problem based on the spherical
% Radon tranform where data consists of integrals along circles. This type
% of problem arises, e.g., in photoacoustic imaging.
%
% The image domain is a square centered at the origin. The centers for the
% integration circles are placed on a circle just outside the image domain.
% For each circle center we integrate along a number of concentric circles
% with equidistant radii, using the periodic trapezoidal rule.
%
% Input:
% N Scalar denoting the number of pixels in each dimesion, such
% that the image domain consists of N^2 cells.
% angles Vector containing the angles to the circle centers in
% degrees. Default: angles = 0:2:358.
% numCircles Number of concentric integration circles for each center.
% Default: numCircles = round(sqrt(2)*N).
% isDisp If isDisp is non-zero it specifies the time in seconds
% to pause in the display of the rays. If zero (the default),
% no display is shown.
% isMatrix If non-zero, a sparse matrix is returned in A (default).
% If zero, instead a function handle is returned.
%
% Output:
% A If input isMatrix is 1 (default): coefficient matrix with
% N^2 columns and length(angles)*p rows.
% If input isMatrix is 0: A function handle representing a
% matrix-free version of A in which the forward and backward
% operations are computed as A(x,'notransp') and A(y,'transp'),
% respectively, for column vectors x and y of appropriate size.
% The size of A can be retrieved using A([],'size'). The matrix
% is never formed explicitly, thus saving memory.
% b Vector containing the rhs of the test problem.
% x Vector containing the exact solution, with elements
% between 0 and 1.
% angles Similar to input.
% numCircles Similar to input.
%
% See also: paralleltomo, fancurvedtomo, fanlineartomo, seismictomo,
% seismicwavetomo.
% Code written by: Per Christian Hansen, Jakob Sauer Jorgensen, and
% Maria Saxild-Hansen, 2010-2017.
% Based on Matlab code written by Juergen Frikel, OTH Regensburg.
% This file is part of the AIR Tools II package and is distributed under
% the 3-Clause BSD License. A separate license file should be provided as
% part of the package.
%
% Copyright 2017 Per Christian Hansen, Technical University of Denmark and
% Jakob Sauer Jorgensen, University of Manchester.
% Default value of the angles to the circle centers.
if nargin < 2 || isempty(angles)
angles = 0:2:358;
end
% Make sure angles is double precison to prevent round-off issues caused by
% single input.
angles = double(angles);
% Default value of the number of circles.
if nargin < 3 || isempty(numCircles)
numCircles = round(sqrt(2)*N);
end
% Default illustration: False
if nargin < 4 || isempty(isDisp)
isDisp = 0;
end
% Default matrix or matrix-free function handle? Matrix
if nargin < 5 || isempty(isMatrix)
isMatrix = 1;
end
% Construct either matrix or function handle
if isMatrix
A = get_or_apply_system_matrix(N,angles,numCircles,isDisp);
else
A = @(U,TRANSP_FLAG) get_or_apply_system_matrix(N,angles,numCircles,...
isDisp,U,TRANSP_FLAG);
end
if nargout > 1
% Create phantom head as a reshaped vector.
x = phantomgallery('shepplogan',N);
x = x(:);
% Create rhs.
if isMatrix
b = A*x;
else
b = A(x,'notransp');
end
end
function A = ...
get_or_apply_system_matrix(N,angles,numCircles,isDisp,u,transp_flag)
% Define the number of angles.
nA = length(angles);
% Radii for the circles.
radii = linspace(0,2,numCircles+1);
radii = radii(2:end);
% Image coordinates.
centerImg = ceil(N/2);
% Determine the quarature parameters.
dx = sqrt(2)/N;
nPhi = ceil((4*pi/dx)*radii);
dPhi = 2*pi./nPhi;
% Prepare for illustration
if isDisp
AA = phantomgallery('smooth',N);
figure
end
% Deduce whether to set up matrix or apply to input, depending on whether
% input u is given.
isMatrix = (nargin < 5);
if isMatrix
% Initialize vectors that contains the row numbers, the column numbers
% and the values for creating the matrix A effiecently.
rows = zeros(2*N*nA*numCircles,1);
cols = rows;
vals = rows;
idxend = 0;
II = 1:nA;
JJ = 1:numCircles;
else
% If transp_flag is 'size', only return size of operator, otherwise set
% proper size of output.
switch transp_flag
case 'size'
A = [numCircles*nA,N^2];
return
case 'notransp' % Forward project.
if length(u) ~= N^2
error('Incorrect length of input vector')
end
A = zeros(numCircles*nA,1);
case 'transp' % Backproject
if length(u) ~= numCircles*nA
error('Incorrect length of input vector')
end
A = zeros(N^2,1);
end
% If u is a Cartesian unit vector then we only want to compute a single
% row of A; otherwise we want to multiply with A or A'.
if strcmpi(transp_flag,'transp') && nnz(u) == 1 && sum(u) == 1
% Want to compute a single row of A, stored as a column vector.
ell = find(u==1);
JJ = mod(ell,numCircles); if JJ==0, JJ = numCircles; end
II = (ell-JJ)/numCircles + 1;
else
% Want to multiply with A or A'.
II = 1:nA;
JJ = 1:numCircles;
end
end
% Loop over angles.
for m = II
% Illustration of the domain.
if isDisp
clf
pause(isDisp)
imagesc(0.5:N-0.5,0.5:N-0.5,flipud(AA))
colormap gray
axis xy
hold on
axis equal
axis([-0.3*N 1.3*N -0.3*N 1.3*N])
end
% Angular position of source.
xix = cosd(angles(m));
xiy = sind(angles(m));
% Loop over the circles.
for n = JJ
% (x,y) coordinates of circle.
k = (0:nPhi(n))*dPhi(n);
xx = (xix + radii(n)*cos(k))/dx + centerImg;
yy = (xiy + radii(n)*sin(k))/dx + centerImg;
% Illustration of the circle.
if isDisp
plot(xx,yy,'-','color',[220 0 0]/255,'linewidth',1.5)
set(gca,'Xtick',[],'Ytick',[])
pause(isDisp)
end
% Round to get pixel index.
col = round( xx );
row = round( yy );
% Discard if outside box domain.
IInew = find(col>0 & col<=N & row>0 & row<=N);
row = row(IInew);
col = col(IInew);
J = (N-row+1) + (col-1)*N;
% Convert to linear index and bin
Ju = unique(J);
w = histc(J,Ju);
% Determine rows, columns and weights.
i = (m-1)*numCircles + n;
ii = repmat(i,length(Ju),1);
jj = Ju(:);
aa = (2*pi*radii(n)/nPhi(n))*w(:);
% Store the values, if any.
if ~isempty(jj)
if isMatrix
% Create the indices to store the values to vector for
% later creation of A matrix.
idxstart = idxend + 1;
idxend = idxstart + numel(jj) - 1;
idx = idxstart:idxend;
% Store row numbers, column numbers and values.
rows(idx) = ii;
cols(idx) = jj;
vals(idx) = aa;
else
% If any nonzero elements, apply forward or back operator
if strcmp(transp_flag,'notransp')
% Insert inner product with u into w.
A( i ) = aa'*u(jj);
else % Adjoint operator.
A(jj) = A(jj) + u( i )*aa;
end
end
end
end
end
if isMatrix
% Truncate excess zeros.
rows = rows(1:idxend);
cols = cols(1:idxend);
vals = vals(1:idxend);
% Create sparse matrix A from the stored values.
A = sparse(rows,cols,vals,numCircles*nA,N^2);
end |
github | gegey2008/ML-DP-master | loadImage.m | .m | ML-DP-master/tutorials/image/segmentation_felzenszwalb/loadImage.m | 508 | utf_8 | b92c98ca1dc61943322b703c3188994e | %%
% Load Image
function image = loadImage(filePath,Im_size)
if nargin == 0
fprintf('Error: No argv !');
elseif nargin == 1
Im_size = 224;
elseif nargin > 2
fprintf('Error: argv number more than 2 !');
end
im = imread(filePath);
im = imresize(im, [Im_size, Im_size], 'bilinear');
image.im = im;
image.width = size(im, 1);
image.height = size(im, 2);
image.r = im(:,:,1);
image.g = im(:,:,2);
image.b = im(:,:,3);
end |
github | gegey2008/ML-DP-master | random_rgb.m | .m | ML-DP-master/tutorials/image/segmentation_felzenszwalb/random_rgb.m | 170 | utf_8 | 2f23a206f1c3d95b027baf0c00022c1c | %%
% random color
function c = random_rgb()
c.r = uint8(round(255*rand(1,1)));
c.g = uint8(round(255*rand(1,1)));
c.b = uint8(round(255*rand(1,1)));
end |
github | gegey2008/ML-DP-master | findSet.m | .m | ML-DP-master/tutorials/image/segmentation_felzenszwalb/findSet.m | 262 | utf_8 | eb53ad8c78580f51d860af2d49d5db33 | %%
% implement disjoint set by union-by-rank
% https://www.geeksforgeeks.org/union-find-algorithm-set-2-union-by-rank/
%%
function [y, elts] = findSet(x, elts)
y = x;
while(y ~= elts(y).p)
y = elts(y).p;
end
elts(x).p = y;
end |
github | gegey2008/ML-DP-master | joinSet.m | .m | ML-DP-master/tutorials/image/segmentation_felzenszwalb/joinSet.m | 512 | utf_8 | fbc374f1c891913a9ee4cc707a512825 | %%
% implement disjoint set by union-by-rank
% https://www.geeksforgeeks.org/union-find-algorithm-set-2-union-by-rank/
%%
function [elts, num] = joinSet(x, y, elts, num)
if (elts(x).rank > elts(y).rank)
elts(y).p = x;
elts(x).size = elts(x).size + elts(y).size;
else
elts(x).p = y;
elts(y).size = elts(y).size + elts(x).size;
if(elts(x).rank == elts(y).rank)
elts(y).rank = elts(y).rank + 1;
end
end
num = num - 1;
end |
github | gegey2008/ML-DP-master | diffIntensity.m | .m | ML-DP-master/tutorials/image/segmentation_felzenszwalb/diffIntensity.m | 200 | utf_8 | 264fba293e775bfd57dbe71094daa7f2 | %%
% compute diff
function weight = diffIntensity(r, g, b, x1, y1, x2, y2)
weight = sqrt((r(x1,y1)-r(x2,y2)).^2 + (g(x1,y1)-g(x2,y2)).^2 ...
+ (b(x1,y1)-b(x2,y2)).^2);
end |
github | gegey2008/ML-DP-master | makeSet.m | .m | ML-DP-master/tutorials/image/segmentation_felzenszwalb/makeSet.m | 296 | utf_8 | 4522a1b20ba2b516e6aa9f44e3e659b8 | %%
% implement disjoint set by union-by-rank
%%
function [elts, num] = makeSet(elements)
num = elements;
for i = 1 : elements;
elts(i).rank = 0;
elts(i).size = 1;
elts(i).p = i; %parent node, arrange all node as parent node by weight
end
end |
github | pcluteijn/MazeLearning-master | fncPrimsMaze.m | .m | MazeLearning-master/fncPrimsMaze.m | 13,729 | utf_8 | d4ce5d5d96c87381eea7d2b18d4300f1 | function [M,H,S] = fncPrimsMaze(nrows,ncols,seed,doPlot,doAnimate,doVertex)
% Maze generation algorithm (Prim's)
% -------------------------------------------------------------------------
%
% Function :
% [M,H] = fncPrimsMaze(nrows,ncols,seed,doPlot,doAnimate,doVertex)
%
% Inputs :
% nrows - Number of horizontal lines
% ncols - Number of vertical lines
% seed - Random number generation seed (optional)
% doPlot - Returns a maze plot (optional)
% doAnimate - Animate the maze creation (optional)
% doVertex - Highlight the vertex points and deadends (optional)
%
% Outputs :
% M - Multi layer cell array containing the maze structure,
% where layers 1-4 (left,up,right,down) contain the wall
% locations. Layer 5 contains the dead-end locations.
% H(n,rcd) - History of maze generation with locations (r&c) and
% directions (d).
%
% -------------------------------------------------------------------------
% Author : P.C. Luteijn
% email : [email protected]
% Date : July 2017
% Comment : Function generates a maze according to Prim's algorithm,
% with an option to plot the maze.
%
% Final remark, positive y-axis points down, positive x-axis
% points right. So down is up and up is down.
%
% -------------------------------------------------------------------------
% random number generation
if not(exist('seed')) || seed <= 0
S = randi(2^32);
seed = S;
else
S = seed;
end
rng(S);
% visited cells
V = zeros(nrows,ncols,2);
% maze structure
M = zeros(nrows,ncols,7);
% history record
H = zeros(nrows*nrows,3);
% randomized initial location
nr = ceil(rand(1)*nrows);
nc = ceil(rand(1)*ncols);
% declare iterator
n = 0;
% start timer
tic;
% START PRIM'S MAZE ITERATION ROUTINE
% ---------------------------------------------------------------------
% run loop until all cells have been visited
while length(V(V(:,:,1)==0)) > 0
% iteration for history tracking
n = n + 1;
% weight
w = rand(1,4);
% options, i.e. possible neighbouring cell locations
optR = [ nr , nr+1, nr , nr-1 ];
optC = [ nc-1, nc , nc+1, nc ];
% DETERMINE COURSE
% -----------------------------------------------------------------
% check if the current cell location has been visited, if it has
% then the walkback routine is started
if V(nr,nc) == 0
% scan for connections between neigbouring cells
for i = 1:4
% edge constraint
if ( optR(i) < 1 && optC(i) >= 1 ), c(i) = 0;
elseif ( optR(i) >= 1 && optC(i) < 1 ), c(i) = 0;
elseif ( optR(i) < 1 && optC(i) < 1 ), c(i) = 0;
elseif ( optR(i) > nrows && optC(i) <= ncols ), c(i) = 0;
elseif ( optR(i) <= nrows && optC(i) > ncols ), c(i) = 0;
elseif ( optR(i) > nrows && optC(i) > ncols ), c(i) = 0;
% focus on legal cells
else
% check if cell is empty
if V(optR(i),optC(i),1) == 0
% Set connection
c(i) = 1;
else
% Set zero connection
c(i) = 0;
end
end
end
% decision
[~,choice] = max(w.*c);
% Update new location, pays respect to deadends by reversing
% direction defining the deadend
if sum(c) == 0
% previous direction
pdir = revDir(H(n-1,3));
% update : visited cell
V(nr,nc,1) = pdir; % point back
V(nr,nc,2) = 5; % dead-end
% update : maze structure
M(nr,nc,pdir) = 1; % current direction
M(nr,nc,5) = 1; % dead-end layer
% update : history
H(n,:) = [nr,nc,pdir];
% set same location
nr = H(n,1);
nc = H(n,2);
else
% update : history
H(n,:) = [nr,nc,choice];
% update : visited cell
V(nr,nc,1) = choice;
% update : maze structure (current & previous direction)
if n == 1
M(nr,nc,choice) = 1;
else
pdir = revDir(H(n-1,3));
M(nr,nc,choice) = 1; % current direction
M(nr,nc,pdir) = 1; % previous direction
end
% set new location
nr = optR(choice);
nc = optC(choice);
end
% WALKBACK ROUTINE
% -----------------------------------------------------------------
% walkback to new vertex location with neighbouring potential
% unvisited cells, when a vertex is found a choice is made if there
% exist multiple branches.
else
% start walkback routine
for j = 1:n
% walkback location
nr = H(n-j,1);
nc = H(n-j,2);
% options
optR = [ nr , nr+1, nr , nr-1 ];
optC = [ nc-1, nc , nc+1, nc ];
% weight
w = rand(1,4);
% find neighbouring free cell
% and create a connection array
for k = 1:4
% edge constraint
if ( optR(k) < 1 && optC(k) >= 1 ), c(k) = 0;
elseif ( optR(k) >= 1 && optC(k) < 1 ), c(k) = 0;
elseif ( optR(k) < 1 && optC(k) < 1 ), c(k) = 0;
elseif ( optR(k) > nrows && optC(k) <= ncols ), c(k) = 0;
elseif ( optR(k) <= nrows && optC(k) > ncols ), c(k) = 0;
elseif ( optR(k) > nrows && optC(k) > ncols ), c(k) = 0;
% focus on legal cells
else
% check if cell is empty
if V(optR(k),optC(k),1) == 0
c(k) = 1;
else
c(k) = 0;
end
end
end
% decision upon empty cell found
if max(c) == 1
% desicion
[~,choice] = max(w.*c);
% ceeate history record
H(n,1) = nr;
H(n,2) = nc;
H(n,3) = choice;
% add to maze structure
M(nr,nc,choice) = 1; % current direction
V(nr,nc,2) = 1; % mark vertex point
% update new location
nr = optR(choice);
nc = optC(choice);
% terminate loop
break;
% if no free cells are connected, remaining get filled up
% this will most likely never occur, but put there just to
% be sure! ;)
elseif j == n
[r0,c0] = find(M(:,:,1)==0); M(r0,c0,1) = -1;
warning('Unreachable cells have been found!')
end
end
end
end
% Record generation time
t1 = toc;
% OUTPUT STATS TO CONSOLE
% ---------------------------------------------------------------------
% Separator line
strLine = []; for i=1:66; strLine = [ strLine '-']; end
fprintf([strLine '\n']);
% Some maze statistics
strSPos = [ '(' num2str(nr) ',' num2str(nc) ')' ];
strSize = [ num2str(nrows) ' by ' num2str(ncols) ];
% Output to console
fprintf('Seed : %16i [-]\n',seed);
fprintf('Size : %16s \n',strSize);
fprintf('Start Position : %16s \n',strSPos);
fprintf('Generation Time : %16.2f [s]\n',t1);
fprintf('Vertex Count : %16i [-]\n',length(find(V(:,:,2)==1)));
fprintf('Dead-end Count : %16i [-]\n',length(find(V(:,:,2)==5)));
fprintf([strLine '\n']);
% PLOT PRIM'S MAZE
% ---------------------------------------------------------------------
% plots the complete maze
try
if doPlot
% color array
arrColor = [ ...
1.0 1.0 1.0 ; ... % white
0.6 1.0 0.6 ; ... % green
1.0 0.6 0.6 ]; % red
% border size
bs = 0.2;
% create figure
figure(...
'Name', 'Prims Maze', ...
'Units', 'pixels', ...
'Position', [600,200,800,800], ...
'Color', 'black' )
% create basis canvas
rectangle( ...
'Position', [0,0,1,1], ...
'FaceColor', [0, 0, 0], ...
'EdgeColor', 'k',...
'LineWidth', 3 )
axis([1, ncols+1, 0, nrows ])
ax = gca;
ax.Color = 'black';
ax.XColor = 'black';
ax.YColor = 'black';
ax.Units = 'Normalized';
ax.Position = [0.02,0.02,0.96,0.96];
% draw maze history by stacking rectangles
hold on
for i = 1:length(H)
% Animate
try
if doAnimate
pause(4/(nrows*ncols));
end
catch
end
% get location
x = H(i,2);
y = nrows - H(i,1);
pos = [ x, y, 1, 1 ];
% get current direction
cd = H(i,3);
% highlight vertex locations
vtx = V(H(i,1),H(i,2),2);
try
if vtx >= 1 && vtx <= 4 && doVertex
iclr = 2;
elseif vtx == 5 && doVertex
iclr = 3;
else
iclr = 1;
end
catch
iclr = 1;
end
% draw cell
pcell = pos + [ bs, bs, -2*bs, -2*bs ];
rectangle( ...
'Position', pcell, ...
'FaceColor', arrColor(iclr,:), ...
'EdgeColor', arrColor(iclr,:),...
'LineWidth', 3 )
% path direction
if cd == 1 % ==[ LEFT ]==
pcarve = [ x-bs, y+bs, 2*bs, 1-2*bs ];
elseif cd == 2 % ==[ UP ]==
pcarve = [ x+bs, y-bs, 1-2*bs, 2*bs ];
elseif cd == 3 % ==[ RIGHT ]==
pcarve = [ x+1-bs, y+bs, 2*bs, 1-2*bs ];
elseif cd == 4 % ==[ DOWN ]==
pcarve = [ x+bs, y+1-bs, 1-2*bs, 2*bs ];
end
% carve path
rectangle( ...
'Position', pcarve, ...
'FaceColor', [1, 1, 1], ...
'EdgeColor', [1, 1, 1],...
'LineWidth', 3 )
% Animate
try
if doCreateGif
[A,map] = rgb2ind(frame2im(getframe(gcf)),256);
delay_time = 10/(nrows*ncols);
if i == 1
imwrite(A,map,'prims_maze.gif','gif', ...
'LoopCount', Inf, ...
'DelayTime', delay_time );
else
imwrite(...
A,map,'prims_maze.gif','gif', ...
'WriteMode', 'append', ...
'DelayTime', delay_time );
end
end
catch
end
end
% end hold draw mode
hold off
end
catch
end
end
function out = revDir(in)
% Reverse direction
if in == 1
out = 3;
elseif in == 2
out = 4;
elseif in == 3
out = 1;
elseif in == 4
out = 2;
end
end
% ------------------------------------------------------------------------
% EoF
% ------------------------------------------------------------------------
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.