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
|
spm/spm5-master
|
pm_vdm_apply.m
|
.m
|
spm5-master/toolbox/FieldMap/pm_vdm_apply.m
| 9,736 |
utf_8
|
28012e22b682dfde3d59d9c2c7355c69
|
function varargout = pm_vdm_apply(ds,flags)
%
% Applies vdm (voxel displacement map) to distortion correct images volume by volume
% FORMAT pm_vdm_apply(ds,[flags])
% or
% FORMAT P = pm_vdm_apply(ds,[flags])
%
% ds - a structure the containing the fields:
%
% .P - Images to apply correction to.
%
% .sfP - Static field supplied by the user. It should be a
% filename or handle to a voxel-displacement map in
% the same space as the first EPI image of the time-
% series. If using the FieldMap toolbox, realignment
% should (if necessary) have been performed as part of
% the process of creating the VDM. Note also that the
% VDM must be in undistorted space, i.e. if it is
% calculated from an EPI based field-map sequence
% it should have been inverted before using it to correct
% images. Again, the FieldMap toolbox will do this for you.
% .jm - Jacobian Modulation. This option is currently disabled.
%
% ds can also be an array of structures, each struct corresponding
% to one sesssion and containing the corresponding images and
% fieldmap. A preceding realignment step will ensure that
% all images are in the space of the first image of the first session
% and they are all resliced in the space of that image.There will
% be a vdm file associated with each session but in practice,
% fieldmaps are not often measured per session. In this case the same
% fieldmap is used for each session.
%
% flags - a structure containing various options. The fields are:
%
% mask - mask output images (1 for yes, 0 for no)
% To avoid artifactual movement-related variance the realigned
% set of images can be internally masked, within the set (i.e.
% if any image has a zero value at a voxel than all images have
% zero values at that voxel). Zero values occur when regions
% 'outside' the image are moved 'inside' the image during
% realignment.
%
% mean - write mean image
% The average of all the realigned scans is written to
% mean*.img.
%
% interp - the interpolation method (see e.g. spm_bsplins.m).
%
% which - Values of 0 or 1 are allowed.
% 0 - don't create any resliced images.
% Useful if you only want a mean resliced image.
% 1 - reslice all the images.
%
% udc - Values 1 or 2 are allowed
% 1 - Do only unwarping (not correcting
% for changing sampling density).
% 2 - Do both unwarping and Jacobian correction.
%
%
% The spatially realigned and corrected images are written to the
% orginal subdirectory with the same filename but prefixed with an 'c'.
% They are all aligned with the first.
%_______________________________________________________________________
% @(#)spm_vdm_apply.m 1.0 Chloe Hutton 05/02/25
global defaults
def_flags = struct('mask', 1,...
'mean', 1,...
'interp', 4,...
'wrap', [0 1 0],...
'which', 1,...
'udc', 1);
defnames = fieldnames(def_flags);
%
% Replace hardcoded defaults with spm_defaults
% when exist and defined.
%
if exist('defaults','var') & isfield(defaults,'realign') & isfield(defaults.realign,'write')
wd = defaults.realign.write;
if isfield(wd,'interp'), def_flags.interp = wd.interp; end
if isfield(wd,'wrap'), def_flags.wrap = wd.wrap; end
if isfield(wd,'mask'), def_flags.mask = wd.mask; end
end
if nargin < 1 | isempty(ds)
ds = getfield(load(spm_get(1,'*_c.mat','Select Unwarp result file')),'ds');
end
%
% Do not allow Jacobian modulation
%
if ds(1).jm ~= 0
ds(1).jm=0;
def_flags.udc = 0;
end
%
% Replace defaults with user supplied values for all fields
% defined by user. Also, warn user of any invalid fields,
% probably reflecting misspellings.
%
if nargin < 2 | isempty(flags)
flags = def_flags;
end
for i=1:length(defnames)
if ~isfield(flags,defnames{i})
flags = setfield(flags,defnames{i},getfield(def_flags,defnames{i}));
end
end
flagnames = fieldnames(flags);
for i=1:length(flagnames)
if ~isfield(def_flags,flagnames{i})
warning(sprintf('Warning, unknown flag field %s',flagnames{i}));
end
end
ntot = 0;
for i=1:length(ds)
ntot = ntot + length(ds(i).P);
end
hold = [repmat(flags.interp,1,3) flags.wrap];
linfun = inline('fprintf(''%-60s%s'', x,repmat(sprintf(''\b''),1,60))');
%
% Create empty sfield for all structs.
%
[ds.sfield] = deal([]);
%
% Make space for output P-structs if required
%
if nargout > 0
oP = cell(length(ds),1);
end
%
% First, create mask if so required.
%
if flags.mask | flags.mean,
linfun('Computing mask..');
spm_progress_bar('Init',ntot,'Computing available voxels',...
'volumes completed');
[x,y,z] = ndgrid(1:ds(1).P(1).dim(1),1:ds(1).P(1).dim(2),1:ds(1).P(1).dim(3));
xyz = [x(:) y(:) z(:) ones(prod(ds(1).P(1).dim(1:3)),1)]; clear x y z;
if flags.mean
Count = zeros(prod(ds(1).P(1).dim(1:3)),1);
Integral = zeros(prod(ds(1).P(1).dim(1:3)),1);
end
if flags.mask
msk = zeros(prod(ds(1).P(1).dim(1:3)),1);
end
tv = 1;
for s=1:length(ds)
if isfield(ds(s),'sfP') & ~isempty(ds(s).sfP)
T = ds(s).sfP.mat\ds(1).P(1).mat;
txyz = xyz * T';
c = spm_bsplinc(ds(s).sfP,ds(s).hold);
ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold);
ds(s).sfield = ds(s).sfield(:);
clear c txyz;
end
for i = 1:prod(size(ds(s).P))
T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;
txyz = xyz * T';
msk = msk + real(txyz(:,1) < 1 | txyz(:,1) > ds(s).P(1).dim(1) |...
txyz(:,2) < 1 | txyz(:,2) > ds(s).P(1).dim(2) |...
txyz(:,3) < 1 | txyz(:,3) > ds(s).P(1).dim(3));
spm_progress_bar('Set',tv);
tv = tv+1;
end
if flags.mean, Count = Count + repmat(length(ds(s).P),prod(ds(s).P(1).dim(1:3)),1) - msk; end
%
% Include static field in estimation of mask.
%
if isfield(ds(s),'sfP') & ~isempty(ds(s).sfP)
T = inv(ds(s).sfP.mat) * ds(1).P(1).mat;
txyz = xyz * T';
msk = msk + real(txyz(:,1) < 1 | txyz(:,1) > ds(s).sfP.dim(1) |...
txyz(:,2) < 1 | txyz(:,2) > ds(s).sfP.dim(2) |...
txyz(:,3) < 1 | txyz(:,3) > ds(s).sfP.dim(3));
end
if isfield(ds(s),'sfield') & ~isempty(ds(s).sfield)
ds(s).sfield = [];
end
end
if flags.mask, msk = find(msk ~= 0); end
end
linfun('Reslicing fieldmap corrected images..');
spm_progress_bar('Init',ntot,'Reslicing','volumes completed');
tiny = 5e-2; % From spm_vol_utils.c
PO = ds(1).P(1);
PO.descrip = 'spm - fieldmap corrected';
jP = ds(1).P(1);
jP = rmfield(jP,{'fname','descrip','n','private'});
jP.dim = [jP.dim(1:3) 64];
jP.pinfo = [1 0]';
tv = 1;
for s=1:length(ds)
if isfield(ds(s),'sfP') & ~isempty(ds(s).sfP)
T = ds(s).sfP.mat\ds(1).P(1).mat;
txyz = xyz * T';
c = spm_bsplinc(ds(s).sfP,ds(s).hold);
ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold);
ds(s).sfield = ds(s).sfield(:);
clear c txyz;
end
for i = 1:length(ds(s).P)
linfun(['Reslicing volume ' num2str(tv) '..']);
%
% Read undeformed image.
%
T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;
txyz = xyz * T';
def = -ds(s).sfield;
txyz(:,2) = txyz(:,2) + def;
c = spm_bsplinc(ds(s).P(i),hold);
ima = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),hold);
%
% Write it if so required.
%
if flags.which
PO.fname = prepend(ds(s).P(i).fname,'c');
if flags.mask
ima(msk) = NaN;
end
ivol = reshape(ima,PO.dim(1:3));
tP = spm_write_vol(PO,ivol);
if nargout > 0
oP{s}(i) = tP;
end
end
%
% Build up mean image if so required.
%
if flags.mean
Integral = Integral + nan2zero(ima);
end
spm_progress_bar('Set',tv);
tv = tv+1;
end
if isfield(ds(s),'sfield') & ~isempty(ds(s).sfield)
ds(s).sfield = [];
end
end
if flags.mean
% Write integral image (16 bit signed)
%-----------------------------------------------------------
warning off; % Shame on me!
Integral = Integral./Count;
warning on;
PO = ds(1).P(1);
PO.fname = prepend(ds(1).P(1).fname, 'meanc');
PO.pinfo = [max(max(max(Integral)))/32767 0 0]';
PO.descrip = 'spm - mean undeformed image';
PO.dim(4) = 4;
ivol = reshape(Integral,PO.dim(1:3));
spm_write_vol(PO,ivol);
end
linfun(' ');
spm_figure('Clear','Interactive');
if nargout > 0
varargout{1} = oP;
end
return;
%_______________________________________________________________________
function PO = prepend(PI,pre)
[pth,nm,xt,vr] = spm_fileparts(deblank(PI));
PO = fullfile(pth,[pre nm xt vr]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vo = nan2zero(vi)
vo = vi;
vo(~isfinite(vo)) = 0;
return;
%_______________________________________________________________________
|
github
|
spm/spm5-master
|
FieldMap.m
|
.m
|
spm5-master/toolbox/FieldMap/FieldMap.m
| 75,872 |
utf_8
|
341ba2188382a38b6a854983335a641c
|
function varargout=FieldMap(varargin)
%
% FieldMap is an SPM2 Toolbox for creating field maps and unwarping EPI.
% A full description of the toolbox and a usage manual can be found in
% FieldMap.man. This can launched by the toolbox help button or using
% spm_help FieldMap.man.The theoretical and practical principles behind
% the toolbox are described in principles.man.
%
% FORMAT FieldMap
%
% FieldMap launches the gui-based toolbox. Help is available via the
% help button (which calls spm_help FieldMap.man). FieldMap is a multi
% function function so that the toolbox routines can also be accessed
% without using the gui. A description of how to do this can be found
% in FieldMap_ngui.m
%
% Input parameters and the mode in which the toolbox works can be
% customised using the defaults file called pm_defaults.m.
%
% Main data structure:
%
% IP.P : 4x1 cell array containing real part short TE,
% imaginary part short TE, real part long TE and
% imaginary part long TE.
% IP.pP : Cell containing pre-calculated phase map. N.B.
% IP.P and IP.pP are mutually exclusive.
% IP.epiP : Cell containing EPI image used to demonstrate
% effects of unwarping.
% IP.fmagP : Cell containing fieldmap magnitude image used for
% coregistration
% IP.wfmagP : Cell containing forward warped fieldmap magnitude
% image used for coregistration
% IP.uepiP : Cell containing unwarped EPI image.
% IP.nwarp : Cell containing non-distorted image.
% IP.vdmP : Cell containing the voxel displacement map (VDM)
% IP.et : 2x1 Cell array with short and long echo-time (ms).
% IP.epifm : Flag indicating EPI based field map (1) or not (0).
% IP.blipdir : Direction of phase-encode blips for k-space traversal
% (1 = positive or -1 = negative)
% IP.ajm : Flag indicating if Jacobian modulation should be applied
% (1) or not (0).
% IP.tert : Total epi readout time (ms).
% IP.maskbrain : Flag indicating whether to mask the brain for fieldmap creation
% IP.uflags : Struct containing parameters guiding the unwrapping.
% Further explanations of these parameters are in
% FieldMap.man and pm_make_fieldmap.m
% .iformat : 'RI' or 'PM'
% .method : 'Huttonish', 'Mark3D' or 'Mark2D'
% .fwhm : FWHM (mm) of Gaussian filter for field map smoothing
% .pad : Size (in-plane voxels) of padding kernel.
% .etd : Echo time difference (ms).
% .bmask
%
% IP.mflags : Struct containing parameters for brain maskin
% .template : Name of template for segmentation.
% .fwhm : fwhm of smoothing kernel for generating mask.
% .nerode : number of erosions
% .ndilate : number of dilations
% .thresh : threshold for smoothed mask.
% .reg : bias field regularisation
% .graphics : display or not
%
% IP.fm : Struct containing field map information
% IP.fm.upm : Phase-unwrapped field map (Hz).
% IP.fm.mask : Binary mask excluding the noise in the phase map.
% IP.fm.opm : "Raw" field map (Hz) (not unwrapped).
% IP.fm.fpm : Phase-unwrapped, regularised field map (Hz).
% IP.fm.jac : Partial derivative of field map in y-direction.
%
% IP.vdm : Struct with voxel displacement map information
% IP.vdm.vdm : Voxel displacement map (scaled version of IP.fm.fpm).
% IP.vdm.jac : Jacobian-1 of forward transform.
% IP.vdm.ivdm : Inverse transform of voxel displacement
% (used to unwarp EPI image if field map is EPI based)
% (used to warp flash image prior to coregistration when
% field map is flash based (or other T2 weighting).
% IP.vdm.ijac : Jacobian-1 of inverse transform.
% IP.jim : Jacobian sampled in space of EPI.
%
% IP.cflags : Struct containing flags for coregistration
% (these are the default SPM coregistration flags -
% defaults.coreg).
% .cost_fun
% .sep
% .tol
% .fwhm
%
%_______________________________________________________________________
% Refs and Background reading:
%
% Jezzard P & Balaban RS. 1995. Correction for geometric distortion in
% echo planar images from Bo field variations. MRM 34:65-73.
%
% Hutton C et al. 2002. Image Distortion Correction in fMRI: A Quantitative
% Evaluation, NeuroImage 16:217-240.
%
% Cusack R & Papadakis N. 2002. New robust 3-D phase unwrapping
% algorithms: Application to magnetic field mapping and
% undistorting echoplanar images. NeuroImage 16:754-764.
%
% Jenkinson M. 2003. Fast, automated, N-dimensional phase-
% unwrapping algorithm. MRM 49:193-197.
%
%_______________________________________________________________________
% Acknowledegments
%
% Wellcome Trust and IBIM Consortium
%_______________________________________________________________________
% UPDATE 02/07
% Updated version of FieldMap for SPM5.
%
% UPDATE 27/01/05
%_______________________________________________________________________
% FieldMap.m Jesper Andersson and Chloe Hutton 17/12/06
persistent PF FS WS PM % GUI related constants
persistent ID % Image display
persistent IP % Input and results
persistent DGW % Delete Graphics Window (if we created it)
global st % Global for spm_orthviews
% SPM5 Update
global defaults
spm_defaults
if nargin == 0
Action = 'welcome';
else
Action = varargin{1};
end
%
% We have tried to divide the Actions into 3 categories:
% 1) Functions that can be called directly from the GUI are at the
% beginning.
% 2) Next come other GUI-related 'utility' functions - ie those that
% care of the GUI behind the scenes.
% 3) Finally, call-back functions that are not GUI dependent and can
% be called from a script are situated towards the end.
% See FieldMap_ngui.m for details on how to use these.
%
switch lower(Action)
%=======================================================================
%
% Create and initialise GUI for FieldMap toolbox
%
%=======================================================================
case 'welcome'
% Unless specified, set visibility to on
if nargin==2
if ~strcmp(varargin{2},'off') & ~strcmp(varargin{2},'Off')
visibility = 'On';
else
visibility = 'Off';
end
else
visibility = 'On';
end
DGW = 0;
% Get all default values (these may effect GUI)
IP = FieldMap('Initialise');
%
% Since we are using persistent variables we better make sure
% there is no-one else out there.
%
if ~isempty(PM)
figure(PM);
set(PM,'Visible',visibility);
return
end
S = get(0,'ScreenSize');
WS = spm('WinScale');
FS = spm('FontSizes');
PF = spm_platform('fonts');
rect = [100 100 510 520].*WS;
PM = figure('IntegerHandle','off',...
'Name',sprintf('%s%s','FieldMap Toolbox, beta.ver.2.0',...
spm('GetUser',' (%s)')),...
'NumberTitle','off',...
'Tag','FieldMap',...
'Position',rect,...
'Resize','off',...
'Pointer','Arrow',...
'Color',[1 1 1]*.8,...
'MenuBar','none',...
'DefaultTextFontName',PF.helvetica,...
'DefaultTextFontSize',FS(10),...
'DefaultUicontrolFontName',PF.helvetica,...
'DefaultUicontrolFontSize',FS(10),...
'HandleVisibility','on',...
'Visible',visibility,...
'DeleteFcn','FieldMap(''Quit'');');
%-Create phase map controls
%-Frames and text
uicontrol(PM,'Style','Frame','BackgroundColor',spm('Colour'),...
'Position',[10 270 490 240].*WS);
uicontrol(PM,'Style','Text','String','Create field map in Hz',...
'Position',[100 480 300 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times,'FontAngle','Italic')
uicontrol(PM,'Style','Text','String','Short TE',...
'Position',[25 452 60 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String','ms',...
'Position',[78 430 30 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String','Long TE',...
'Position',[25 392 60 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String','ms',...
'Position',[78 370 30 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String',{'Mask brain:'},...
'Position',[30 310 80 35].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String',{'Precalculated','field map:'},...
'Position',[30 275 80 35].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String',{'Field map value:'},...
'Position',[240 280 100 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text','String',{'Hz'},...
'Position',[403 280 20 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
%-Objects with Callbacks
uicontrol(PM,'Style','radiobutton',...
'String','RI',...
'Position',[30 480 44 022].*WS,...
'ToolTipString','Select Real/Imaginary input images',...
'CallBack','FieldMap(''InputFormat'');',...
'UserData',1,...
'Tag','IFormat');
uicontrol(PM,'Style','radiobutton',...
'String','PM',...
'Position',[76 480 44 022].*WS,...
'ToolTipString','Select phase/magnitude input images',...
'CallBack','FieldMap(''InputFormat'');',...
'UserData',2,...
'Tag','IFormat');
uicontrol(PM,'Style','Edit',...
'Position',[30 430 50 024].*WS,...
'ToolTipString','Give shortest echo-time in ms',...
'CallBack','FieldMap(''EchoTime'');',...
'UserData',1,...
'Tag','ShortTime');
uicontrol(PM,'Style','Edit',...
'Position',[30 370 50 024].*WS,...
'ToolTipString','Give longest echo-time in ms',...
'CallBack','FieldMap(''EchoTime'');',...
'UserData',2,...
'Tag','LongTime');
% Here we set up appropriate gui
FieldMap('IFormat_Gui');
uicontrol(PM,'String','Calculate',...
'Position',[265 337 90 022].*WS,...
'Enable','Off',...
'ToolTipString','Go ahead and create unwrapped field map (in Hz)',...
'CallBack','FieldMap(''CreateFieldmap_Gui'');',...
'Tag','CreateFieldMap');
uicontrol(PM,'String','Write',...
'Position',[370 337 90 022].*WS,...
'Enable','Off',...
'ToolTipString','Write Analyze image containing fininshed field map (in Hz)',...
'CallBack','FieldMap(''WriteFieldMap_Gui'');',...
'Tag','WriteFieldMap');
uicontrol(PM,'String','Load',...
'Position',[125 280 90 022].*WS,...
'ToolTipString','Load Analyze image containing finished field map (in Hz)',...
'CallBack','FieldMap(''LoadFieldMap_Gui'');',...
'Tag','LoadFieldMap');
% Empty string written to Fieldmap value box
uicontrol(PM,'Style','Text',...
'Position',[340 280 50 020].*WS,...
'HorizontalAlignment','left',...
'String','');
%-Create voxel-displacement-map controls
%-Frames and text
uicontrol(PM,'Style','Frame','BackgroundColor',spm('Colour'),...
'Position',[10 10 490 250].*WS);
uicontrol(PM,'Style','Text',...
'String','Create voxel displacement map (VDM) and unwarp EPI',...
'Position',[70 235 350 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times,'FontAngle','Italic')
uicontrol(PM,'Style','Text',...
'String','EPI-based field map',...
'Position',[50 200 200 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text',...
'String','Polarity of phase-encode blips',...
'Position',[50 170 200 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text',...
'String','Apply Jacobian modulation',...
'Position',[50 140 200 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text',...
'String','Total EPI readout time',...
'Position',[50 110 200 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
uicontrol(PM,'Style','Text',...
'String','ms',...
'Position',[370 110 30 020].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times)
%-Objects with Callbacks
uicontrol(PM,'style','RadioButton',...
'String','Yes',...
'Position',[300 200 60 022].*WS,...
'ToolTipString','Field map is based on EPI data and needs inverting before use',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','EPI',...
'UserData',1);
uicontrol(PM,'style','RadioButton',...
'String','No',...
'Position',[370 200 60 022].*WS,...
'ToolTipString','Phase-map is based on non-EPI (Flash) data and can be used directly',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','EPI',...
'UserData',2);
uicontrol(PM,'style','RadioButton',...
'String','+ve',...
'Position',[370 170 60 022].*WS,...
'ToolTipString','K-space is traversed using positive phase-encode blips',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','BlipDir',...
'UserData',1);
uicontrol(PM,'style','RadioButton',...
'String','-ve',...
'Position',[300 170 60 022].*WS,...
'ToolTipString','K-space is traversed using negative phase-encode blips',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','BlipDir',...
'UserData',2);
uicontrol(PM,'style','RadioButton',...
'String','Yes',...
'Position',[300 140 60 022].*WS,...
'ToolTipString','Do Jacobian intensity modulation to compensate for compression/stretching',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','Jacobian',...
'UserData',1);
uicontrol(PM,'style','RadioButton',...
'String','No',...
'Position',[370 140 60 022].*WS,...
'ToolTipString','Don''t do Jacobian intensity modulation to compensate for compression/stretching',...
'CallBack','FieldMap(''RadioButton'');',...
'Tag','Jacobian',...
'UserData',2);
uicontrol(PM,'Style','Edit',...
'Position',[300 110 70 024].*WS,...
'ToolTipString','Give total time for readout of EPI echo train ms',...
'CallBack','FieldMap(''ReadOutTime'');',...
'Tag','ReadTime');
uicontrol(PM,'String','Load EPI image',...
'Position',[30 70 120 022].*WS,...
'ToolTipString','Load sample modulus EPI Analyze image',...
'CallBack','FieldMap(''LoadEpi_Gui'');',...
'Tag','LoadEpi');
uicontrol(PM,'String','Match VDM to EPI',...
'Position',[165 70 120 022].*WS,...
'ToolTipString','Match vdm to EPI (but only if you want to...)',...
'CallBack','FieldMap(''MatchVDM_gui'');',...
'Tag','MatchVDM');
uicontrol(PM,'String','Write unwarped',...
'Position',[300 70 120 022].*WS,...
'ToolTipString','Write unwarped EPI Analyze image',...
'CallBack','FieldMap(''WriteUnwarped_Gui'');',...
'Tag','WriteUnwarped');
uicontrol(PM,'String','Load structural',...
'Position',[30 30 120 022].*WS,...
'ToolTipString','Load structural image (but only if you want to...)',...
'CallBack','FieldMap(''LoadStructural_Gui'');',...
'Tag','LoadStructural');
uicontrol(PM,'String','Match structural',...
'Position',[164 30 120 022].*WS,...
'ToolTipString','Match structural image to EPI (but only if you want to...)',...
'CallBack','FieldMap(''MatchStructural_Gui'');',...
'Tag','MatchStructural');
uicontrol(PM,'String','Help',...
'Position',[320 30 80 022].*WS,...
'ToolTipString','Help',...
'CallBack','FieldMap(''Help_Gui'');',...
'ForegroundColor','g',...
'Tag','Help');
uicontrol(PM,'String','Quit',...
'Position',[420 30 60 022].*WS,...
'Enable','On',...
'ToolTipString','Exit toolbox',...
'CallBack','FieldMap(''Quit'');',...
'ForegroundColor','r',...
'Tag','Quit');
uicontrol(PM,'style','RadioButton',...
'String','Yes',...
'Position',[123 330 48 022].*WS,...
'ToolTipString','Mask brain using magnitude image before processing',...
'CallBack','FieldMap(''MaskBrain'');',...
'Tag','MaskBrain',...
'UserData',1);
uicontrol(PM,'style','RadioButton',...
'String','No',...
'Position',[173 330 46 022].*WS,...
'ToolTipString','Do not mask brain using magnitude image before processing',...
'CallBack','FieldMap(''MaskBrain'');',...
'Tag','MaskBrain',...
'UserData',2);
% Find list of default files and set up menu accordingly
def_files = FieldMap('GetDefaultFiles');
menu_items = FieldMap('DefFiles2MenuItems',def_files);
if length(menu_items)==1
uicontrol(PM,'String',menu_items{1},...
'Enable','Off',...
'ToolTipString','Site specific default files',...
'Position',[400 480 60 22].*WS);
else
uicontrol(PM,'Style','PopUp',...
'String',menu_items,...
'Enable','On',...
'ToolTipString','Site specific default files',...
'Position',[390 480 90 22].*WS,...
'callback','FieldMap(''DefaultFile_Gui'');',...
'UserData',def_files);
end
%-Apply defaults to buttons
FieldMap('SynchroniseButtons');
%
% Disable necessary buttons and parameters until phase-map is finished.
%
FieldMap('Reset_Gui');
%=======================================================================
%
% Make sure buttons reflect current parameter values
%
%=======================================================================
case 'synchronisebuttons'
% Set input format
if ~isempty(IP.uflags.iformat)
if strcmp(IP.uflags.iformat,'RI');
h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',1);
FieldMap('RadioOn',h);
IP.uflags.iformat = 'RI';
else
h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',2);
FieldMap('RadioOn',h);
IP.uflags.iformat = 'PM';
end
else % Default to RI
h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',1);
FieldMap('RadioOn',h);
IP.uflags.iformat = 'RI';
end
% Set brain masking defaults
if ~isempty(IP.maskbrain)
if IP.maskbrain == 1
h = findobj(get(PM,'Children'),'Tag','MaskBrain','UserData',1);
FieldMap('RadioOn',h);
IP.maskbrain = 1;
else
h = findobj(get(PM,'Children'),'Tag','MaskBrain','UserData',2);
FieldMap('RadioOn',h);
IP.maskbrain = 0;
end
else % Default to no
h = findobj(get(PM,'Children'),'Tag','MaskBrain','UserData',2);
FieldMap('RadioOn',h);
IP.maskbrain = 0;
end
% Set echo Times
if ~isempty(IP.et{1})
h = findobj(get(PM,'Children'),'Tag','ShortTime');
set(h,'String',sprintf('%2.2f',IP.et{1}));
end
if ~isempty(IP.et{2})
h = findobj(get(PM,'Children'),'Tag','LongTime');
set(h,'String',sprintf('%2.2f',IP.et{2}));
end
% Set EPI field map
if ~isempty(IP.epifm)
if IP.epifm
h = findobj(get(PM,'Children'),'Tag','EPI','UserData',1);
FieldMap('RadioOn',h);
IP.epifm = 1;
else
h = findobj(get(PM,'Children'),'Tag','EPI','UserData',2);
FieldMap('RadioOn',h);
IP.epifm = 0;
end
else % Default to yes
h = findobj(get(PM,'Children'),'Tag','EPI','UserData',1);
FieldMap('RadioOn',h);
IP.epifm = 1;
end
% Set apply jacobian
if ~isempty(IP.ajm)
if IP.ajm
h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',1);
FieldMap('RadioOn',h);
IP.ajm = 1;
else
h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',2);
FieldMap('RadioOn',h);
IP.ajm = 0;
end
else % Default to no
h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',2);
FieldMap('RadioOn',h);
IP.ajm = 0;
end
% Set blip direction
if ~isempty(IP.blipdir)
if IP.blipdir == 1
h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',1);
FieldMap('RadioOn',h);
IP.blipdir = 1;
elseif IP.blipdir == -1
h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',2);
FieldMap('RadioOn',h);
IP.blipdir = -1;
else
error('Invalid phase-encode direction');
end
else % Default to -1 = negative
h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',1);
FieldMap('RadioOn',h);
IP.blipdir = -1;
end
% Set total readout time
if ~isempty(IP.tert)
h = findobj(get(PM,'Children'),'Tag','ReadTime');
set(h,'String',sprintf('%2.2f',IP.tert));
end
%=======================================================================
%
% Input format was changed
%
%=======================================================================
case 'inputformat'
%
% Enforce radio behaviour.
%
index = get(gcbo,'UserData');
if index==1
partner = 2;
IP.uflags.iformat = 'RI';
else
partner = 1;
IP.uflags.iformat = 'PM';
end
h = findobj(get(PM,'Children'),'Tag','IFormat','UserData',partner);
maxv = get(gcbo,'Max');
value = get(gcbo,'Value');
if value == maxv
set(h,'Value',get(h,'Min'));
else
set(h,'Value',get(h,'Max'));
end
FieldMap('IFormat_Gui');
%=======================================================================
%
% A new default file has been chosen from the popup menu - gui version.
%
%=======================================================================
case 'defaultfile_gui'
m_file = get(gcbo,'UserData');
m_file = m_file(get(gcbo,'Value'));
m_file = m_file{1}(1:end-2);
IP = FieldMap('SetParams',m_file);
FieldMap('IFormat_Gui');
FieldMap('SynchroniseButtons');
%=======================================================================
%
% Load real or imaginary part of dual echo-time data - gui version.
%
%=======================================================================
case 'loadfile_gui'
FieldMap('Reset_Gui');
%
% File selection using gui
%
index = get(gcbo,'UserData');
FieldMap('LoadFile',index);
ypos = [445 420 385 360];
uicontrol(PM,'Style','Text','String',spm_str_manip(IP.P{index}.fname,['l',num2str(50)]),...
'Position',[220 ypos(index) 260 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times,...
'FontSize',FS(8));
FieldMap('Assert');
%=======================================================================
%
% Load phase and magnitude images - gui version.
%
%=======================================================================
case 'loadfilepm_gui'
FieldMap('Reset_Gui');
%
% File selection using gui
%
index = get(gcbo,'UserData');
FieldMap('LoadFilePM',index);
ypos = [445 420 385 360];
uicontrol(PM,'Style','Text','String',spm_str_manip(IP.P{index}.fname,['l',num2str(50)]),...
'Position',[220 ypos(index) 260 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times,...
'FontSize',FS(8));
FieldMap('Assert');
%=======================================================================
%
% Create unwrapped phase-map - gui version
%
%=======================================================================
case 'createfieldmap_gui'
%
% Create fieldmap from complex images...
%
status=FieldMap('CreateFieldMap',IP);
if ~isempty(status)
FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);
% Toggle relevant buttons
FieldMap('ToggleGUI','Off','CreateFieldMap');
FieldMap('ToggleGUI','On',str2mat('LoadFieldMap','WriteFieldMap'));
%
% Check that have correct parameters ready before allowing
% an image to be loaded for unwarping and hence conversion of
% fieldmap to voxel shift map.
%
if (FieldMap('GatherVDMData'))
FieldMap('FM2VDM',IP);
FieldMap('ToggleGUI','On',str2mat('LoadEpi','EPI',...
'BlipDir','Jacobian','ReadTime'));
end
end
%=======================================================================
%
% Load already prepared fieldmap (in Hz).
%
%=======================================================================
case 'loadfieldmap_gui'
%
% Reset all previously loaded field maps and images to unwarp
%
FieldMap('Reset_gui');
%
% Select a precalculated phase map
%
FieldMap('LoadFieldMap');
uicontrol(PM,'Style','Text','String',spm_str_manip(IP.pP.fname,['l',num2str(50)]),...
'Position',[220 307 260 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'),...
'FontName',PF.times,...
'FontSize',FS(8));
FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);
FieldMap('ToggleGUI','Off',str2mat('CreateFieldMap','WriteFieldMap',...
'MatchVDM','WriteUnwarped',...
'LoadStructural', 'MatchStructural'));
% Check that have correct parameters ready before allowing
% an image to be loaded for unwarping and hence conversion of
% fieldmap to voxel shift map.
%
if (FieldMap('GatherVDMData'))
FieldMap('FM2VDM',IP);
FieldMap('ToggleGUI','On',str2mat('LoadEpi','EPI',...
'BlipDir','Jacobian','ReadTime'));
end
%=======================================================================
%
% Write out field map in Hz - using GUI
%
%=======================================================================
case 'writefieldmap_gui'
FieldMap('Write',IP.P{1},IP.fm.fpm,'fpm_',64,'Fitted phase map in Hz');
%=======================================================================
%
% Load sample EPI image using gui, unwarp and display result
%
%=======================================================================
case 'loadepi_gui'
%
% Select and display EPI image
%
FieldMap('LoadEPI');
FieldMap('DisplayImage',IP.epiP,[.05 .5 .95 .2],2);
% The fm2vdm parameters may have been changed so must calculate
% the voxel shift map with current parameters.
if (FieldMap('GatherVDMData'))
FieldMap('FM2VDM',IP);
FieldMap('UnwarpEPI',IP);
FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);
% Once EPI has been unwarped can enable unwarp checks and structural stuff
FieldMap('ToggleGUI','On',str2mat('MatchVDM','WriteUnwarped','LoadStructural'));
end
%
% Redisplay phasemap in case .mat file associated with
% EPI image different from images that filadmap was
% estimated from.
%
FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);
%=======================================================================
%
% Coregister fieldmap magnitude image to EPI to unwarp using GUI
%
%=======================================================================
case 'matchvdm_gui'
if (FieldMap('GatherVDMData'))
FieldMap('MatchVDM',IP);
FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1)
FieldMap('UnwarpEPI',IP);
FieldMap('DisplayImage',IP.epiP,[.05 .5 .95 .2],2);
FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);
% Once EPI has been unwarped can enable unwarp checks
FieldMap('ToggleGUI','On',str2mat('MatchVDM','WriteUnwarped','LoadStructural'));
end
%=======================================================================
%
% Load structural image
%
%=======================================================================
case 'loadstructural_gui'
FieldMap('LoadStructural');
FieldMap('DisplayImage',IP.nwarp,[.05 0.0 .95 .2],4);
%
% Redisplay the other images to allow for recalculation
% of size of display.
%
FieldMap('DisplayImage',FieldMap('MakedP'),[.05 .75 .95 .2],1);
FieldMap('DisplayImage',IP.epiP,[.05 .5 .95 .2],2);
FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);
FieldMap('ToggleGUI','On','MatchStructural');
%=======================================================================
%
% Match structural image to unwarped EPI
%
%=======================================================================
case 'matchstructural_gui'
FieldMap('MatchStructural',IP);
FieldMap('DisplayImage',IP.nwarp,[.05 0.0 .95 .2],4);
%=======================================================================
%
% Write out unwarped EPI
%
%=======================================================================
case 'writeunwarped_gui'
unwarp_info=sprintf('Unwarped EPI:echo time difference=%2.2fms, EPI readout time=%2.2fms, Jacobian=%d',IP.uflags.etd, IP.tert,IP.ajm);
IP.uepiP = FieldMap('Write',IP.epiP,IP.uepiP.dat,'u',IP.epiP.dt(1),unwarp_info);
FieldMap('ToggleGUI','On', 'LoadStructural');
FieldMap('ToggleGUI','Off', 'WriteUnwarped');
%=======================================================================
%
% Help using spm_help
%
%=======================================================================
case 'help_gui'
FieldMap('help');
%=======================================================================
%
% Quit Toolbox
%
%=======================================================================
case 'quit'
Fgraph=spm_figure('FindWin','Graphics');
if ~isempty(Fgraph)
if DGW
delete(Fgraph);
Fgraph=[];
DGW = 0;
else
spm_figure('Clear','Graphics');
end
end
PM=spm_figure('FindWin','FieldMap');
if ~isempty(PM)
delete(PM);
PM=[];
end
%=======================================================================
%
% The following functions are GUI related functions that go on behind
% the scenes.
%=======================================================================
%
%=======================================================================
%
% Reset gui inputs when a new field map is to be calculated
%
%=======================================================================
case 'reset_gui'
% Clear any precalculated fieldmap name string
uicontrol(PM,'Style','Text','String','',...
'Position',[230 307 260 20].*WS,...
'ForegroundColor','k','BackgroundColor',spm('Colour'));
% Clear Fieldmap values
uicontrol(PM,'Style','Text',...
'Position',[350 280 50 020].*WS,...
'HorizontalAlignment','left',...
'String','');
% Disable input routes to make sure
% a new fieldmap is calculated.
%
FieldMap('ToggleGUI','Off',str2mat('CreateFieldMap','WriteFieldMap',...
'LoadEpi','WriteUnwarped','MatchVDM',...
'LoadStructural','MatchStructural',...
'EPI','BlipDir',...
'Jacobian','ReadTime'));
%
% A new input image implies all processed data is void.
%
IP.fm = [];
IP.vdm = [];
IP.jim = [];
IP.pP = [];
IP.epiP = [];
IP.uepiP = [];
IP.vdmP = [];
IP.fmagP = [];
IP.wfmagP = [];
ID = cell(4,1);
spm_orthviews('Reset');
spm_figure('Clear','Graphics');
%=======================================================================
%
% Use gui for Real and Imaginary or Phase and Magnitude.
%
%=======================================================================
case 'iformat_gui'
FieldMap('Reset_Gui');
% Load Real and Imaginary or Phase and Magnitude Buttons
if IP.uflags.iformat=='PM'
h=findobj('Tag','LoadRI');
set(h,'Visible','Off');
uicontrol(PM,'String','Load Phase',...
'Position',[125 450 90 022].*WS,...
'ToolTipString','Load Analyze image containing first phase image',...
'CallBack','FieldMap(''LoadFilePM_Gui'');',...
'UserData',1,...
'Tag','LoadPM');
uicontrol(PM,'String','Load Mag.',...
'Position',[125 425 90 022].*WS,...
'ToolTipString','Load Analyze image containing first magnitude image',...
'CallBack','FieldMap(''LoadFilePM_Gui'');',...
'UserData',2,...
'Tag','LoadPM');
uicontrol(PM,'String','Load Phase',...
'Position',[125 390 90 022].*WS,...
'ToolTipString','Load Analyze image containing second phase image',...
'CallBack','FieldMap(''LoadFilePM_Gui'');',...
'UserData',3,...
'Tag','LoadPM');
uicontrol(PM,'String','Load Mag.',...
'Position',[125 365 90 022].*WS,...
'ToolTipString','Load Analyze image containing second magnitudeimage',...
'CallBack','FieldMap(''LoadFilePM_Gui'');',...
'UserData',4,...
'Tag','LoadPM');
else
% make the objects we don't want invisible
h=findobj('Tag','LoadPM');
set(h,'Visible','Off');
uicontrol(PM,'String','Load Real',...
'Position',[125 450 90 022].*WS,...
'ToolTipString','Load Analyze image containing real part of short echo-time image',...
'CallBack','FieldMap(''LoadFile_Gui'');',...
'UserData',1,...
'Tag','LoadRI');
uicontrol(PM,'String','Load Imag',...
'Position',[125 425 90 022].*WS,...
'ToolTipString','Load Analyze image containing imaginary part of short echo-time image',...
'CallBack','FieldMap(''LoadFile_Gui'');',...
'UserData',2,...
'Tag','LoadRI');
uicontrol(PM,'String','Load Real',...
'Position',[125 390 90 022].*WS,...
'ToolTipString','Load Analyze image containing real part of long echo-time image',...
'CallBack','FieldMap(''LoadFile_Gui'');',...
'UserData',3,...
'Tag','LoadRI');
uicontrol(PM,'String','Load Imag',...
'Position',[125 365 90 022].*WS,...
'ToolTipString','Load Analyze image containing imaginary part of long echo-time image',...
'CallBack','FieldMap(''LoadFile_Gui'');',...
'UserData',4,...
'Tag','LoadRI');
end
%=======================================================================
%
% Brain masking or not
%
%=======================================================================
case 'maskbrain'
FieldMap('Reset_Gui');
%
% Enforce radio behaviour.
%
index = get(gcbo,'UserData');
if index==1
partner=2;
IP.maskbrain=1;
else
partner=1;
IP.maskbrain=0;
end
tag = get(gcbo,'Tag');
value = get(gcbo,'Value');
maxv = get(gcbo,'Max');
h = findobj(get(PM,'Children'),'Tag',tag,'UserData',partner);
if value == maxv
set(h,'Value',get(h,'Min'));
else
set(h,'Value',get(h,'Max'));
end
FieldMap('Assert');
%=======================================================================
%
% Echo time was changed or entered
%
%=======================================================================
case 'echotime'
FieldMap('Assert');
%=======================================================================
%
% Check if inputs are correct for calculating new phase map
%
%=======================================================================
case 'assert'
if ~isempty(IP.pP) % If we're using precalculated fieldmap.
go = 0;
else
go = 1;
for i=1:2
if isempty(IP.P{i}) go = 0; end
end
for i=3:4
if (isempty(IP.P{i}) & IP.uflags.iformat=='RI') go = 0; end
end
h = findobj(get(PM,'Children'),'Tag','ShortTime');
IP.et{1} = str2num(get(h,'String'));
h = findobj(get(PM,'Children'),'Tag','LongTime');
IP.et{2} = str2num(get(h,'String'));
if isempty(IP.et{1}) | isempty(IP.et{2}) | IP.et{2} < IP.et{1}
go = 0;
end
end
if go
FieldMap('ToggleGui','On','CreateFieldMap');
else % Switch off fieldmap creation
FieldMap('ToggleGui','Off','CreateFieldMap');
end
%=======================================================================
%
% Enable or disable specified buttons or parameters in GUI
%
%=======================================================================
case 'togglegui'
h = get(PM,'Children');
tags=varargin{3};
for n=1:size(varargin{3},1)
set(findobj(h,'Tag',deblank(tags(n,:))),'Enable',varargin{2});
end
%=======================================================================
%
% A radiobutton was pressed.
%
%=======================================================================
case 'radiobutton'
%
% Enforce radio behaviour.
%
index = get(gcbo,'UserData');
if index==1
partner=2;
else
partner=1;
end
tag = get(gcbo,'Tag');
value = get(gcbo,'Value');
maxv = get(gcbo,'Max');
h = findobj(get(PM,'Children'),'Tag',tag,'UserData',partner);
if value == maxv
set(h,'Value',get(h,'Min'));
else
set(h,'Value',get(h,'Max'));
end
% Update Hz to voxel displacement map if the input parameters are ok
if (FieldMap('GatherVDMData'))
FieldMap('FM2VDM',IP);
%
% Update unwarped EPI if one is loaded
%
if ~isempty(IP.epiP)
IP.uepiP = FieldMap('UnwarpEPI',IP);
FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);
FieldMap('ToggleGUI','On',str2mat('WriteUnwarped'));
end
end
%=======================================================================
%
% Enforce radio-button behaviour
%
%=======================================================================
case 'radioon'
my_gcbo = varargin{2};
index = get(my_gcbo,'UserData');
if index==1
partner=2;
else
partner=1;
end
set(my_gcbo,'Value',get(my_gcbo,'Max'));
h = findobj(get(PM,'Children'),'Tag',get(my_gcbo,'Tag'),'UserData',partner);
set(h,'Value',get(h,'Min'));
%=======================================================================
%
% Total readout-time was changed or entered
%
%=======================================================================
case 'readouttime'
%
% Update unwarped EPI
%
% This means the transformation phase-map to voxel displacement-map
% has changed, which means the inversion will have to be redone,
% which means (in the case of flash-based field map) coregistration
% between field-map and sample EPI image should be redone. Phew!
%
if (FieldMap('GatherVDMData'))
FieldMap('FM2VDM',IP);
% Update unwarped EPI if one is loaded
if ~isempty(IP.epiP)
IP.uepiP = FieldMap('UnwarpEPI',IP);
FieldMap('DisplayImage',IP.uepiP,[.05 .25 .95 .2],3);
FieldMap('ToggleGUI','On',str2mat('WriteUnwarped',...
'LoadStructural'));
end
FieldMap('ToggleGUI','On',str2mat('LoadEpi','EPI','BlipDir',...
'Jacobian','ReadTime'));
else
% If readtime is missing switch everything off...
FieldMap('ToggleGUI','Off',str2mat('LoadEpi','EPI',...
'BlipDir','Jacobian',...
'WriteUnwarped','LoadStructural',...
'MatchStructural', 'MatchVDM'));
end
%=======================================================================
%
% Sample UIControls pertaining to information needed for transformation
% phase-map -> voxel displacement-map
%
%=======================================================================
case 'gathervdmdata'
h = findobj(get(PM,'Children'),'Tag','EPI','UserData',1);
v = get(h,{'Value','Max'});
if v{1} == 1
IP.epifm = 1;
else
IP.epifm = 0;
end
h = findobj(get(PM,'Children'),'Tag','BlipDir','UserData',1);
v = get(h,{'Value','Max'});
if v{1} == 1 %% CHLOE: Changed
IP.blipdir = 1;
else
IP.blipdir = -1;
end
h = findobj(get(PM,'Children'),'Tag','Jacobian','UserData',1);
v = get(h,{'Value','Max'});
if v{1} == 1 %% CHLOE: Changed
IP.ajm = 1;
else
IP.ajm = 0;
end
h = findobj(get(PM,'Children'),'Tag','ReadTime');
IP.tert = str2num(get(h,'String'));
if isempty(IP.tert) | isempty(IP.fm) | isempty(IP.fm.fpm)
varargout{1} = 0;
FieldMap('ToggleGui','On','ReadTime');
else
varargout{1} = 1;
end
%=======================================================================
%
% Draw transversal and sagittal image.
%
%=======================================================================
case 'redrawimages'
global curpos;
for i=1:length(ID)
if ~isempty(ID{i}) & ~isempty(st.vols{i})
set(st.vols{i}.ax{2}.ax,'Visible','Off'); % Disable event delivery in Coronal
set(st.vols{i}.ax{2}.d,'Visible','Off'); % Make Coronal invisible
set(st.vols{i}.ax{1}.ax,'Position',ID{i}.tra_pos);
set(st.vols{i}.ax{1}.ax,'ButtonDownFcn',['FieldMap(''Orthviews'');']);
set(get(st.vols{i}.ax{1}.ax,'YLabel'),'String',ID{i}.label);
set(st.vols{i}.ax{3}.ax,'Position',ID{i}.sag_pos);
set(st.vols{i}.ax{3}.ax,'ButtonDownFcn',['FieldMap(''Orthviews'');']);
end
end
%=======================================================================
%
% Callback for orthviews
%
%=======================================================================
case 'orthviews'
if strcmp(get(gcf,'SelectionType'),'normal')
spm_orthviews('Reposition');,...
%spm_orthviews('set_pos2cm');,...
elseif strcmp(get(gcf,'SelectionType'),'extend')
spm_orthviews('Reposition');,...
%spm_orthviews('set_pos2cm');,...
spm_orthviews('context_menu','ts',1);
end;
curpos = spm_orthviews('pos',1);
set(st.in, 'String',sprintf('%3.3f',spm_sample_vol(st.vols{1},curpos(1),curpos(2),curpos(3),st.hld)));
%=======================================================================
%
% Display image.
%
%=======================================================================
case 'displayimage'
Fgraph=spm_figure('FindWin','Graphics');
if isempty(Fgraph)
st.fig=spm_figure('Create','Graphics','Graphics');
DGW = 1;
end
if ~isempty(ID{varargin{4}})
spm_orthviews('Delete',ID{varargin{4}}.h);
ID{varargin{4}} = [];
end
h = spm_orthviews('Image',varargin{2},[.01 .01 .01 .01]);
% Set bounding box to allow display of all images
spm_orthviews('MaxBB');
% Put everything in space of original EPI image.
if varargin{4} == 2
%spm_orthviews('Space',h); % This was deleted for some reason
end
%
% Get best possible positioning and scaling for
% transversal and sagittal views.
%
tra_pos = get(st.vols{varargin{4}}.ax{1}.ax,'Position');
sag_pos = get(st.vols{varargin{4}}.ax{3}.ax,'Position');
field_pos = varargin{3};
x_scale = field_pos(3) / (tra_pos(3) + sag_pos(3));
height = max([tra_pos(4) sag_pos(4)]);
y_scale = field_pos(4) / height;
if x_scale > y_scale % Height limiting
scale = y_scale;
dx = (field_pos(3) - scale*(tra_pos(3) + sag_pos(3))) / 3;
dy = 0;
else % Width limiting
scale = x_scale;
dx = 0;
dy = (field_pos(4) - scale*height) / 2;
end
tra_pos = [field_pos(1)+dx field_pos(2)+dy scale*tra_pos([3 4])];
sag_pos = [field_pos(1)+tra_pos(3)+2*dx field_pos(2)+dy scale*sag_pos([3 4])];
label = {'Fieldmap in Hz',...
'Warped EPI',...
'Unwarped EPI',...
'Structural'};
ID{varargin{4}} = struct('tra_pos', tra_pos,...
'sag_pos', sag_pos,...
'h', h,...
'label', label{varargin{4}});
FieldMap('RedrawImages');
st.in = uicontrol(PM,'Style','Text',...
'Position',[340 280 50 020].*WS,...
'HorizontalAlignment','left',...
'String','');
%=======================================================================
%=======================================================================
%
% The functions below are called by the various gui buttons but are
% not dependent on the gui to work. These functions can therefore also
% be called from a script bypassing the gui and can return updated
% variables.
%
%=======================================================================
%=======================================================================
%
%=======================================================================
%
% Create and initialise parameters for FieldMap toolbox
%
%=======================================================================
case 'initialise'
%
% Initialise parameters
%
ID = cell(4,1);
IP.P = cell(1,4);
IP.pP = [];
IP.fmagP = [];
IP.wfmagP = [];
IP.epiP = [];
IP.uepiP = [];
IP.nwarp = [];
IP.fm = [];
IP.vdm = [];
IP.et = cell(1,2);
IP.epifm = [];
IP.blipdir = [];
IP.ajm = [];
IP.tert = [];
IP.vdmP = []; %% Check that this should be there %%
IP.maskbrain = [];
IP.uflags = struct('iformat','','method','','fwhm',[],'bmask',[],'pad',[],'etd',[],'ws',[]);
IP.mflags = struct('template',[],'fwhm',[],'nerode',[],'ndilate',[],'thresh',[],'reg',[],'graphics',0);
% Initially set brain mask to be empty
IP.uflags.bmask = [];
% Set parameter values according to defaults
FieldMap('SetParams');
varargout{1}= IP;
%=======================================================================
%
% Sets parameters according to the defaults file that is being passed
%
%=======================================================================
case 'setparams'
if nargin == 1
pm_defaults; % "Default" default file
else
eval(varargin{2}); % Scanner or sequence specific default file
end
% Define parameters for fieldmap creation
IP.et{1} = pm_def.SHORT_ECHO_TIME;
IP.et{2} = pm_def.LONG_ECHO_TIME;
IP.maskbrain = pm_def.MASKBRAIN;
% Set parameters for unwrapping
IP.uflags.iformat = pm_def.INPUT_DATA_FORMAT;
IP.uflags.method = pm_def.UNWRAPPING_METHOD;
IP.uflags.fwhm = pm_def.FWHM;
IP.uflags.pad = pm_def.PAD;
IP.uflags.ws = pm_def.WS;
IP.uflags.etd = pm_def.LONG_ECHO_TIME - pm_def.SHORT_ECHO_TIME;
% Set parameters for brain masking
IP.mflags.template = pm_def.MFLAGS.TEMPLATE;
IP.mflags.fwhm = pm_def.MFLAGS.FWHM;
IP.mflags.nerode = pm_def.MFLAGS.NERODE;
IP.mflags.ndilate = pm_def.MFLAGS.NDILATE;
IP.mflags.thresh = pm_def.MFLAGS.THRESH;
IP.mflags.reg = pm_def.MFLAGS.REG;
IP.mflags.graphics = pm_def.MFLAGS.GRAPHICS;
% Set parameters for unwarping
IP.ajm = pm_def.DO_JACOBIAN_MODULATION;
IP.blipdir = pm_def.K_SPACE_TRAVERSAL_BLIP_DIR;
IP.tert = pm_def.TOTAL_EPI_READOUT_TIME;
IP.epifm = pm_def.EPI_BASED_FIELDMAPS;
varargout{1}= IP;
%=======================================================================
%
% Get a list of all the default files that are present
%
%=======================================================================
case 'getdefaultfiles'
fmdir = fullfile(spm('Dir'),'toolbox','FieldMap');
defdir = dir(fullfile(fmdir,'pm_defaults*.m'));
for i=1:length(defdir)
if defdir(i).name(12) ~= '.' & defdir(i).name(12) ~= '_'
error(sprintf('Error in default file spec: %s',defdir(i).name));
end
defnames{i} = defdir(i).name;
end
varargout{1} = defnames;
%=======================================================================
%
% Get list of menuitems from list of default files
%
%=======================================================================
case 'deffiles2menuitems'
for i=1:length(varargin{2})
if strcmp(varargin{2}{i},'pm_defaults.m');
menit{i} = 'Default';
else
endindx = strfind(varargin{2}{i},'.m');
menit{i} = varargin{2}{i}(13:(endindx-1));
end
end
varargout{1} = menit;
%=======================================================================
%
% Scale a phase map so that max = pi and min =-pi radians.
%
%=======================================================================
case 'scale'
F=varargin{2};
V=spm_vol(F);
vol=spm_read_vols(V);
mn=min(vol(:));
mx=max(vol(:));
vol=-pi+(vol-mn)*2*pi/(mx-mn);
varargout{1} = FieldMap('Write',V,vol,'sc',V.dt(1),V.descrip);
%=======================================================================
%
% Load real or imaginary part of dual echo-time data - NO gui.
%
%=======================================================================
case 'loadfile'
index=varargin{2};
prompt_string = {'Select short echo-time real',...
'Select short echo-time imaginary',...
'Select long echo-time real',...
'Select long echo-time imaginary'};
%IP.P{index} = spm_vol(spm_get(1,'*.img',prompt_string{index}));
% SPM
IP.P{index} = spm_vol(spm_select(1,'image',prompt_string{index}));
if isfield(IP,'pP') & ~isempty(IP.pP)
IP.pP = [];
end
varargout{1} = IP.P{index};
%=======================================================================
%
% Load phase or magnitude part of dual (possibly) echo-time data - NO gui.
%
%=======================================================================
case 'loadfilepm'
index=varargin{2};
prompt_string = {'Select phase image',...
'Select magnitude image',...
'Select second phase image or press done',...
'Select magnitude image or press done'};
if index<3
%IP.P{index} = spm_vol(spm_get(1,'*.img',prompt_string{index}));
% SPM5 Update
IP.P{index} = spm_vol(spm_select(1,'image',prompt_string{index}));
if index==1
do=spm_input('Scale this to radians?',1,'b','Yes|No',[1,0]);
Finter=spm_figure('FindWin','Interactive');
close(Finter);
if do==1
tmp=FieldMap('Scale',IP.P{index}.fname);
IP.P{index} = spm_vol(tmp.fname);
end
end
else
%IP.P{index} = spm_vol(spm_get([0 1],'*.img',prompt_string{index}));
% SPM5 Update
IP.P{index} = spm_vol(spm_select([0 1],'image',prompt_string{index}));
if index==3 & ~isempty(IP.P{index})
do=spm_input('Scale this to radians?',1,'b','Yes|No',[1,0]);
Finter=spm_figure('FindWin','Interactive');
close(Finter);
if do==1
tmp=FieldMap('Scale',IP.P{index}.fname);
IP.P{index} = spm_vol(tmp.fname);
end
end
end
if isfield(IP,'pP') & ~isempty(IP.pP)
IP.pP = [];
end
varargout{1} = IP.P{index};
%=======================================================================
%
% Load already prepared fieldmap (in Hz) - no gui
%
%=======================================================================
case 'loadfieldmap'
%
% Select field map
%
% 24/03/04 - Chloe change below to spm_get(1,'fpm_*.img')...
% IP.pP = spm_vol(spm_get(1,'fpm_*.img','Select field map'));
% SPM5 Update
IP.pP = spm_vol(spm_select(1,'^fpm.*\.img$','Select field map'));
IP.fm.fpm = spm_read_vols(IP.pP);
IP.fm.jac = pm_diff(IP.fm.fpm,2);
if isfield(IP,'P') & ~isempty(IP.P{1})
IP.P = cell(1,4);
end
varargout{1} = IP.fm;
varargout{2} = IP.pP;
%=======================================================================
%
% Create unwrapped phase-map - NO gui
%
%=======================================================================
case 'createfieldmap'
IP=varargin{2};
% First check that images are in same space.
if size([IP.P{1} IP.P{2} IP.P{3} IP.P{4}],2)==4
ip_dim=cat(1,[IP.P{1}.dim' IP.P{2}.dim' IP.P{3}.dim' IP.P{4}.dim']');
ip_mat=cat(2,[IP.P{1}.mat(:) IP.P{2}.mat(:) IP.P{3}.mat(:) IP.P{4}.mat(:)]');
else
ip_dim=cat(1,[IP.P{1}.dim' IP.P{2}.dim']');
ip_mat=cat(2,[IP.P{1}.mat(:) IP.P{2}.mat(:)]');
end
if any(any(diff(ip_dim,1,1),1)&[1,1,1])
errordlg({'Images don''t all have same dimensions'});
drawnow;
varargout{1}=[];
elseif any(any(diff(ip_mat,1,1),1))
errordlg({'Images don''t all have same orientation & voxel size'});
drawnow;
varargout{1}=[];
else
% Update flags for unwarping (in case TEs have been adjusted
IP.uflags.etd = IP.et{2}-IP.et{1};
% Clear any brain mask
IP.uflags.bmask = [];
% SPM5 Update
% If flag selected to mask brain and the field map is not based on EPI
if IP.maskbrain==1
IP.fmagP = FieldMap('Magnitude',IP);
IP.uflags.bmask = pm_brain_mask(IP.fmagP,IP.mflags);
varargout{2} = IP.fmagP;
end
IP.fm = pm_make_fieldmap([IP.P{1} IP.P{2} IP.P{3} IP.P{4}],IP.uflags);
varargout{1} = IP.fm;
end
%=======================================================================
%
% Convert field map to voxel displacement map and
% do necessary inversions of displacement fields.
%
%=======================================================================
case 'fm2vdm'
IP=varargin{2};
%
% If we already have memory mapped image pointer to voxel
% displacement map let's reuse it (so not to void possible
% realignment). If field-map is non-EPI based the previous
% realignment (based on different parameters) will be non-
% optimal and we should advice user to redo it.
%
% If no pointer already exist we'll make one.
%
if isfield(IP,'vdmP') & ~isempty(IP.vdmP)
msgbox({'Changing this parameter means that if previously',...
'you matched VDM to EPI, this result may no longer',...
'be optimal. In this case we recommend you redo the',...
'Match VDM to EPI.'},...
'Coregistration notice','warn','modal');
else
if ~isempty(IP.pP)
IP.vdmP = struct('dim', IP.pP.dim(1:3),...
'dt',[4 spm_platform('bigend')],...
'mat', IP.pP.mat);
IP.vdmP.fname=fullfile(spm_str_manip(IP.pP.fname, 'h'),['vdm5_' deblank(spm_str_manip(IP.pP.fname,'t'))]);
else
IP.vdmP = struct('dim', IP.P{1}.dim(1:3),...
'dt',[4 spm_platform('bigend')],...
'mat', IP.P{1}.mat);
IP.vdmP.fname=fullfile(spm_str_manip(IP.P{1}.fname, 'h'),['vdm5_' deblank(spm_str_manip(IP.P{1}.fname,'t'))]);
end
end
% Scale field map and jacobian by total EPI readout time
IP.vdm.vdm = IP.blipdir*IP.tert*1e-3*IP.fm.fpm;
IP.vdm.jac = IP.blipdir*IP.tert*1e-3*IP.fm.jac;
% Chloe added this: 26/02/05
% Put fieldmap parameters in descrip field of vdm
vdm_info=sprintf('Voxel Displacement Map:echo time difference=%2.2fms, EPI readout time=%2.2fms',IP.uflags.etd, IP.tert);
if IP.epifm ==1
spm_progress_bar('Init',3,'Inverting displacement map','');
spm_progress_bar('Set',1);
% Invert voxel shift map and multiply by -1...
IP.vdm.ivdm = pm_invert_phasemap(-1*IP.vdm.vdm);
IP.vdm.ijac = pm_diff(IP.vdm.ivdm,2);
spm_progress_bar('Set',2);
spm_progress_bar('Clear');
FieldMap('Write',IP.vdmP,IP.vdm.ivdm,'',IP.vdmP.dt(1),vdm_info);
else
FieldMap('Write',IP.vdmP,IP.vdm.vdm,'',IP.vdmP.dt(1),vdm_info);
end
varargout{1} = IP.vdm;
varargout{2} = IP.vdmP;
%=======================================================================
%
% Write out image
%
%=======================================================================
case 'write'
V=varargin{2};
vol=varargin{3};
name=varargin{4};
% Write out image
img=struct('dim', V.dim(1:3),...
'dt', [varargin{5} spm_platform('bigend')],...
'mat', V.mat);
img.fname=fullfile(spm_str_manip(V.fname, 'h'),[name deblank(spm_str_manip(V.fname,'t'))]);
img.descrip=varargin{6};
img=spm_write_vol(img,vol);
varargout{1}=img;
%=======================================================================
%
% Create fieldmap (Hz) struct for use when displaying image.
%
%=======================================================================
case 'makedp'
if isfield(IP,'vdmP') & ~isempty(IP.vdmP);
dP = struct('dim', IP.vdmP.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', [1 0]',...
'mat', IP.vdmP.mat,...
'dat', reshape(IP.fm.fpm,IP.vdmP.dim),...
'fname', 'display_image');
else
if isfield(IP,'P') & ~isempty(IP.P{1})
dP = struct('dim', IP.P{1}.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', [1 0]',...
'mat', IP.P{1}.mat,...
'dat', reshape(IP.fm.fpm,IP.P{1}.dim),...
'fname', 'display_image');
elseif isfield(IP,'pP') & ~isempty(IP.pP)
dP = struct('dim', IP.pP.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', [1 0]',...
'mat', IP.pP.mat,...
'dat', reshape(IP.fm.fpm,IP.pP.dim),...
'fname', 'display_image');
end
end
varargout{1} = dP;
%=======================================================================
%
% Load sample EPI image - NO gui
%
%=======================================================================
case 'loadepi'
%
% Select EPI
%
%IP.epiP = spm_vol(spm_get(1,'*.img','Select sample EPI image'));
% SPM5 Update
IP.epiP = spm_vol(spm_select(1,'image','Select sample EPI image'));
varargout{1} = IP.epiP;
%=======================================================================
%
% Create unwarped epi - NO gui
%
%=======================================================================
case 'unwarpepi'
%
% Update unwarped EPI
%
IP=varargin{2};
IP.uepiP = struct('fname', 'Image in memory',...
'dim', IP.epiP.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', IP.epiP.pinfo(1:2),...
'mat', IP.epiP.mat);
% Need to sample EPI and voxel shift map in space of EPI...
[x,y,z] = ndgrid(1:IP.epiP.dim(1),1:IP.epiP.dim(2),1:IP.epiP.dim(3));
xyz = [x(:) y(:) z(:)];
% Space of EPI is IP.epiP{1}.mat and space of
% voxel shift map is IP.vdmP{1}.mat
tM = inv(IP.epiP.mat\IP.vdmP.mat);
x2 = tM(1,1)*x + tM(1,2)*y + tM(1,3)*z + tM(1,4);
y2 = tM(2,1)*x + tM(2,2)*y + tM(2,3)*z + tM(2,4);
z2 = tM(3,1)*x + tM(3,2)*y + tM(3,3)*z + tM(3,4);
xyz2 = [x2(:) y2(:) z2(:)];
%
% Make mask since it is only meaningful to calculate undistorted
% image in areas where we have information about distortions.
%
msk = reshape(double(xyz2(:,1)>=1 & xyz2(:,1)<=IP.vdmP.dim(1) &...
xyz2(:,2)>=1 & xyz2(:,2)<=IP.vdmP.dim(2) &...
xyz2(:,3)>=1 & xyz2(:,3)<=IP.vdmP.dim(3)),IP.epiP.dim(1:3));
% Read in voxel displacement map in correct space
tvdm = reshape(spm_sample_vol(spm_vol(IP.vdmP.fname),xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
% Voxel shift map must be added to the y-coordinates.
uepi = reshape(spm_sample_vol(IP.epiP,xyz(:,1),...
xyz(:,2)+tvdm(:),xyz(:,3),1),IP.epiP.dim(1:3));% TEMP CHANGE
% Sample Jacobian in correct space and apply if required
if IP.ajm==1
if IP.epifm==1 % If EPI, use inverted jacobian
IP.jim = reshape(spm_sample_vol(IP.vdm.ijac,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
else
IP.jim = reshape(spm_sample_vol(IP.vdm.jac,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
end
uepi = uepi.*(1+IP.jim);
end
IP.uepiP.dat=uepi.*msk;
varargout{1}=IP.uepiP;
%=======================================================================
%
% Coregister fieldmap magnitude image to EPI to unwarp
%
%=======================================================================
case 'matchvdm'
IP=varargin{2};
%
% Need a fieldmap magnitude image
%
if isempty(IP.pP) & ~isempty(IP.P{1})
IP.fmagP=struct('dim', IP.P{1}.dim,...
'dt',IP.P{1}.dt,...
'pinfo', IP.P{1}.pinfo,...
'mat', IP.P{1}.mat);
IP.fmagP.fname=fullfile(spm_str_manip(IP.P{1}.fname, 'h'),['mag_' deblank(spm_str_manip(IP.P{1}.fname,'t'))]);
% If using real and imaginary data, calculate using sqrt(i1.^2 + i2.^2).
% If using phase and magnitude, use magnitude image.
if IP.uflags.iformat=='RI'
IP.fmagP = spm_imcalc(spm_vol([IP.P{1}.fname;IP.P{2}.fname]),IP.fmagP,'sqrt(i1.^2 + i2.^2)');
else
IP.fmagP = IP.P{2};
end
elseif ~isempty(IP.pP) & ~isempty(IP.fmagP)
msg=sprintf('Using %s for matching\n',IP.fmagP.fname);
disp(msg);
else
%IP.fmagP = spm_vol(spm_get(1,'*.img','Select field map magnitude image'));
% SPM5 Update
IP.fmagP = spm_vol(spm_select(1,'image','Select field map magnitude image'));
end
% Now we have field map magnitude image, we want to coregister it to the
% EPI to be unwarped.
% If using an EPI field map:
% 1) Coregister magnitude image to EPI.
% 2) Apply resulting transformation matrix to voxel shift map
% If using a non-EPI field map:
% 1) Forward warp magnitude image
% 2) Coregister warped magnitude image to EPI.
% 3) Apply resulting transformation matrix to voxel shift map
if IP.epifm==1
[mi,M] = FieldMap('Coregister',IP.epiP,IP.fmagP);
MM = IP.fmagP.mat;
else
% Need to sample magnitude image in space of EPI to be unwarped...
[x,y,z] = ndgrid(1:IP.epiP.dim(1),1:IP.epiP.dim(2),1:IP.epiP.dim(3));
xyz = [x(:) y(:) z(:)];
% Space of EPI is IP.epiP{1}.mat and space of fmagP is IP.fmagP.mat
tM = inv(IP.epiP.mat\IP.fmagP.mat);
x2 = tM(1,1)*x + tM(1,2)*y + tM(1,3)*z + tM(1,4);
y2 = tM(2,1)*x + tM(2,2)*y + tM(2,3)*z + tM(2,4);
z2 = tM(3,1)*x + tM(3,2)*y + tM(3,3)*z + tM(3,4);
xyz2 = [x2(:) y2(:) z2(:)];
wfmag = reshape(spm_sample_vol(IP.fmagP,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),1),IP.epiP.dim(1:3));
% Need to sample voxel shift map in space of EPI to be unwarped
tvdm = reshape(spm_sample_vol(IP.vdm.vdm,xyz2(:,1),...
xyz2(:,2),xyz2(:,3),0),IP.epiP.dim(1:3));
% Now apply warps to resampled forward warped magnitude image...
wfmag = reshape(spm_sample_vol(wfmag,xyz(:,1),xyz(:,2)-tvdm(:),...
xyz(:,3),1),IP.epiP.dim(1:3));
% Write out forward warped magnitude image
IP.wfmagP = struct('dim', IP.epiP.dim,...
'dt',[64 spm_platform('bigend')],...
'pinfo', IP.epiP.pinfo,...
'mat', IP.epiP.mat);
IP.wfmagP = FieldMap('Write',IP.epiP,wfmag,'wfmag_',4,'Voxel shift map');
% Now coregister warped magnitude field map to EPI
[mi,M] = FieldMap('Coregister',IP.epiP,IP.wfmagP);
% Update the .mat file of the forward warped mag image
spm_get_space(deblank(IP.wfmagP.fname),M*IP.wfmagP.mat);
% Get the original space of the fmap magnitude
MM = IP.fmagP.mat;
end
% Update .mat file for voxel displacement map
IP.vdmP.mat=M*MM;
spm_get_space(deblank(IP.vdmP.fname),M*MM);
varargout{1} = IP.vdmP;
%=======================================================================
%
% Invert voxel displacement map
%
%=======================================================================
case 'invert'
vdm = pm_invert_phasemap(IP.vdm.vdm);
varargout{1} = vdm;
%=======================================================================
%
% Get fieldmap magnitude image
%
%=======================================================================
case 'magnitude'
IP=varargin{2};
if isempty(IP.fmagP)
%
% Get fieldmap magnitude image
%
if isempty(IP.pP) & ~isempty(IP.P{1})
IP.fmagP=struct('dim', IP.P{1}.dim,...
'dt', IP.P{1}.dt,...
'pinfo', IP.P{1}.pinfo,...
'mat', IP.P{1}.mat);
IP.fmagP.fname=fullfile(spm_str_manip(IP.P{1}.fname, 'h'),['mag_' deblank(spm_str_manip(IP.P{1}.fname,'t'))]);
% If using real and imaginary data, calculate using sqrt(i1.^2 + i2.^2).
% If using phase and magnitude, use magnitude image.
if IP.uflags.iformat=='RI'
IP.fmagP = spm_imcalc(spm_vol([IP.P{1}.fname;IP.P{2}.fname]),IP.fmagP,'sqrt(i1.^2 + i2.^2)');
else
IP.fmagP = IP.P{2};
end
% else
% IP.fmagP = spm_vol(spm_get(1,'*.img','Select field map magnitude image'));
else
do_f = ~isfield(IP, 'fmagP');
if ~do_f, do_f = isempty(IP.fmagP); end
if do_f
IP.fmagP = spm_vol(spm_select(1,'image','Select field map magnitude image'));
end
end
end
varargout{1} = IP.fmagP;
%=======================================================================
%
% Load structural image
%
%=======================================================================
case 'loadstructural'
%IP.nwarp = spm_vol(spm_get(1,'*.img','Select structural image'));
% SPM5 Update
IP.nwarp = spm_vol(spm_select(1,'image','Select structural image'));
varargout{1} = IP.nwarp;
%=======================================================================
%
% Coregister structural image to unwarped EPI
%
%=======================================================================
case 'matchstructural'
IP = varargin{2};
[mi,M] = FieldMap('Coregister',IP.uepiP,IP.nwarp);
MM = IP.nwarp.mat;
IP.nwarp.mat=M*MM;
spm_get_space(deblank(IP.nwarp.fname),IP.nwarp.mat);
varargout{1}=mi;
%=======================================================================
%
% Coregister two images - NO gui
%
%=======================================================================
case 'coregister'
%
% Coregisters image VF to image VG (use VF and VG like in SPM code)
%
VG = varargin{2};
VF = varargin{3};
% Define flags for coregistration...
IP.cflags.cost_fun = defaults.coreg.estimate.cost_fun;
IP.cflags.sep = defaults.coreg.estimate.sep;
IP.cflags.tol = defaults.coreg.estimate.tol;
IP.cflags.fwhm = defaults.coreg.estimate.fwhm;
IP.cflags.graphics = 0;
% Voxel sizes (mm)
vxg = sqrt(sum(VG.mat(1:3,1:3).^2));
vxf = sqrt(sum(VF.mat(1:3,1:3).^2));
% Smoothnesses
fwhmg = sqrt(max([1 1 1]*IP.cflags.sep(end)^2 - vxg.^2, [0 0 0]))./vxg;
fwhmf = sqrt(max([1 1 1]*IP.cflags.sep(end)^2 - vxf.^2, [0 0 0]))./vxf;
% Need to load data smoothed in unit8 format (as in spm_coreg_ui)
% if isfield(VG,'dat')
% VG=rmfield(VG,'dat');
% end
if ~isfield(VG,'uint8')
VG.uint8 = loaduint8(VG);
VG = smooth_uint8(VG,fwhmg); % Note side effects
end
% if isfield(VF,'dat')
% VF=rmfield(VF,'dat');
% end
if ~isfield(VF,'uint8')
VF.uint8 = loaduint8(VF);
VF = smooth_uint8(VF,fwhmf); % Note side effects
end
x=spm_coreg(VG,VF,IP.cflags);
M = inv(spm_matrix(x));
MM = spm_get_space(deblank(VF.fname));
varargout{1}=spm_coreg(x,VG,VF,2,IP.cflags.cost_fun,IP.cflags.fwhm);
varargout{2}=M;
%=======================================================================
%
% Use spm_help to display help for FieldMap toolbox
%
%=======================================================================
case 'help'
spm_help('FieldMap.man');
return
end
%=======================================================================
%
% Smoothing functions required for spm_coreg
%
%=======================================================================
function V = smooth_uint8(V,fwhm)
% Convolve the volume in memory (fwhm in voxels).
lim = ceil(2*fwhm);
s = fwhm/sqrt(8*log(2));
x = [-lim(1):lim(1)]; x = smoothing_kernel(fwhm(1),x); x = x/sum(x);
y = [-lim(2):lim(2)]; y = smoothing_kernel(fwhm(2),y); y = y/sum(y);
z = [-lim(3):lim(3)]; z = smoothing_kernel(fwhm(3),z); z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
spm_conv_vol(V.uint8,V.uint8,x,y,z,-[i j k]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function krn = smoothing_kernel(fwhm,x)
% Variance from FWHM
s = (fwhm/sqrt(8*log(2)))^2+eps;
% The simple way to do it. Not good for small FWHM
% krn = (1/sqrt(2*pi*s))*exp(-(x.^2)/(2*s));
% For smoothing images, one should really convolve a Gaussian
% with a sinc function. For smoothing histograms, the
% kernel should be a Gaussian convolved with the histogram
% basis function used. This function returns a Gaussian
% convolved with a triangular (1st degree B-spline) basis
% function.
% Gaussian convolved with 0th degree B-spline
% int(exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= -0.5..0.5)
% w1 = 1/sqrt(2*s);
% krn = 0.5*(erf(w1*(x+0.5))-erf(w1*(x-0.5)));
% Gaussian convolved with 1st degree B-spline
% int((1-t)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= 0..1)
% +int((t+1)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t=-1..0)
w1 = 0.5*sqrt(2/s);
w2 = -0.5/s;
w3 = sqrt(s/2/pi);
krn = 0.5*(erf(w1*(x+1)).*(x+1) + erf(w1*(x-1)).*(x-1) - 2*erf(w1*x ).* x)...
+w3*(exp(w2*(x+1).^2) + exp(w2*(x-1).^2) - 2*exp(w2*x.^2));
krn(krn<0) = 0;
return;
%=======================================================================
%
% Load data function required for spm_coreg
%
%=======================================================================
function udat = loaduint8(V)
% Load data from file indicated by V into an array of unsigned bytes.
if size(V.pinfo,2)==1 & V.pinfo(1) == 2,
mx = 255*V.pinfo(1) + V.pinfo(2);
mn = V.pinfo(2);
else,
spm_progress_bar('Init',V.dim(3),...
['Computing max/min of ' spm_str_manip(V.fname,'t')],...
'Planes complete');
mx = -Inf; mn = Inf;
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
mx = max([max(img(:))+paccuracy(V,p) mx]);
mn = min([min(img(:)) mn]);
spm_progress_bar('Set',p);
end;
end;
spm_progress_bar('Init',V.dim(3),...
['Loading ' spm_str_manip(V.fname,'t')],...
'Planes loaded');
udat = uint8(0);
udat(V.dim(1),V.dim(2),V.dim(3))=0;
rand('state',100);
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
acc = paccuracy(V,p);
if acc==0,
udat(:,:,p) = uint8(round((img-mn)*(255/(mx-mn))));
else,
% Add random numbers before rounding to reduce aliasing artifact
r = rand(size(img))*acc;
udat(:,:,p) = uint8(round((img+r-mn)*(255/(mx-mn))));
end;
spm_progress_bar('Set',p);
end;
spm_progress_bar('Clear');
return;
function acc = paccuracy(V,p)
if ~spm_type(V.dt(1),'intt'),
acc = 0;
else,
if size(V.pinfo,2)==1,
acc = abs(V.pinfo(1,1));
else,
acc = abs(V.pinfo(1,p));
end;
end;
%_______________________________________________________________________
|
github
|
spm/spm5-master
|
spm_config_FieldMap.m
|
.m
|
spm5-master/toolbox/FieldMap/spm_config_FieldMap.m
| 21,721 |
utf_8
|
bbce33042158fb5cff2b9e4bc257f6ea
|
function job = spm_config_fieldmap
% Configuration file for FieldMap jobs
%_______________________________________________________________________
% Copyright (C) 2006 Wellcome Department of Imaging Neuroscience
% Chloe Hutton
% $Id: spm_config_FieldMap.m 1754 2008-05-29 13:56:00Z chloe $
%_______________________________________________________________________
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num)'],...
'name','tag','strtype','num');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num)'],...
'name','tag','fltr','num');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values})'],...
'name','tag','labels','values');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val})'],...
'name','tag','val');
repeat = inline(['struct(''type'',''repeat'',''name'',name,''tag'',tag,'...
'''values'',{values})'],'name','tag','values');
choice = inline(['struct(''type'',''choice'',''name'',name,''tag'',tag,'...
'''values'',{values})'],'name','tag','values');
%______________________________________________________________________
addpath(fullfile(spm('dir'),'toolbox','FieldMap'));
%------------------------------------------------------------------------
% File selection for Precalculated field map data (in Hz)
precalcfieldmap.type = 'files';
precalcfieldmap.name = 'Precalculated field map';
precalcfieldmap.tag = 'precalcfieldmap';
precalcfieldmap.num = [1 1];
precalcfieldmap.filter = 'image';
precalcfieldmap.help = {['Select a precalculated field map. This should be a ',...
'processed field map (ie phase unwrapped, masked if necessary and scaled to Hz), ',...
'for example as generated by the FieldMap toolbox and stored as an fpm_* file.']};
%------------------------------------------------------------------------
% File selection for Phase/Magnitude field map data
shortphase.type = 'files';
shortphase.name = 'Short Echo Phase Image';
shortphase.tag = 'shortphase';
shortphase.num = [1 1];
shortphase.filter = 'image';
shortphase.help = {['Select short echo phase image']};
shortmag.type = 'files';
shortmag.name = 'Short Echo Magnitude Image';
shortmag.tag = 'shortmag';
shortmag.num = [1 1];
shortmag.filter = 'image';
shortmag.help = {['Select short echo magnitude image']};
longphase.type = 'files';
longphase.name = 'Long Echo Phase Image';
longphase.tag = 'longphase';
longphase.num = [1 1];
longphase.filter = 'image';
longphase.help = {['Select long echo phase image']};
longmag.type = 'files';
longmag.name = 'Long Echo Magnitude Image';
longmag.tag = 'longmag';
longmag.num = [1 1];
longmag.filter = 'image';
longmag.help = {['Select long echo magnitude image']};
%------------------------------------------------------------------------
% File selection for Presubtracted Magnitude/Phase field map data
presubmag.type = 'files';
presubmag.name = 'Magnitude Image';
presubmag.tag = 'magnitude';
presubmag.num = [1 1];
presubmag.filter = 'image';
presubmag.help = {['Select a single magnitude image']};
presubphase.type = 'files';
presubphase.name = 'Phase Image';
presubphase.tag = 'phase';
presubphase.num = [1 1];
presubphase.filter = 'image';
presubphase.help = {['Select a single phase image. This should be the result from the ',...
'subtraction of two phase images (where the subtraction is usually done automatically by ',...
'the scanner software). The phase image will be scaled between +/- PI.']};
%------------------------------------------------------------------------
% File selection for Real/Imaginary field map data
shortreal.type = 'files';
shortreal.name = 'Short Echo Real Image';
shortreal.tag = 'shortreal';
shortreal.num = [1 1];
shortreal.filter = 'image';
shortreal.help = {['Select short echo real image']};
shortimag.type = 'files';
shortimag.name = 'Short Echo Imaginary Image';
shortimag.tag = 'shortimag';
shortimag.num = [1 1];
shortimag.filter = 'image';
shortimag.help = {['Select short echo imaginary image']};
longreal.type = 'files';
longreal.name = 'Long Echo Real Image';
longreal.tag = 'longreal';
longreal.num = [1 1];
longreal.filter = 'image';
longreal.help = {['Select long echo real image']};
longimag.type = 'files';
longimag.name = 'Long Echo Imaginary Image';
longimag.tag = 'longimag';
longimag.num = [1 1];
longimag.filter = 'image';
longimag.help = {['Select long echo imaginary image']};
%------------------------------------------------------------------------
% Options for doing segmentation used to create brain mask
template_filename = fullfile(spm('Dir'),'templates','T1.nii');
template.type = 'files';
template.name = 'Template image for brain masking';
template.tag = 'template';
template.num = [1 1];
template.filter = 'nii';
template.val = {template_filename};
template.help = {['Select template file for segmentation to create brain mask']};
fwhm.type = 'entry';
fwhm.name = 'FWHM';
fwhm.tag = 'fwhm';
fwhm.strtype = 'e';
fwhm.num = [1 1];
fwhm.val = {5};
fwhm.help = {'FWHM of Gaussian filter for smoothing brain mask.'};
nerode.type = 'entry';
nerode.name = 'Number of erosions';
nerode.tag = 'nerode';
nerode.strtype = 'e';
nerode.num = [1 1];
nerode.val = {1};
nerode.help = {'Number of erosions used to create brain mask.'};
ndilate.type = 'entry';
ndilate.name = 'Number of dilations';
ndilate.tag = 'ndilate';
ndilate.strtype = 'e';
ndilate.num = [1 1];
ndilate.val = {2};
ndilate.help = {'Number of dilations used to create brain mask.'};
thresh.type = 'entry';
thresh.name = 'Threshold';
thresh.tag = 'thresh';
thresh.strtype = 'e';
thresh.num = [1 1];
thresh.val = {0.5};
thresh.help = {'Threshold used to create brain mask from segmented data.'};
reg.type = 'entry';
reg.name = 'Regularization';
reg.tag = 'reg';
reg.strtype = 'e';
reg.num = [1 1];
reg.val = {0.02};
reg.help = {'Regularization value used in the segmentation. A larger value helps the segmentation to converge.'};
mflags.type = 'branch';
mflags.name = 'mflags';
mflags.tag = 'mflags';
mflags.val = {template,fwhm,nerode,ndilate,thresh,reg};
mflags.help = {['Different options used for the segmentation and creation of the brain mask.']};
%------------------------------------------------------------------------
% Options for phase unwrapping and processing field map
method.type = 'menu';
method.name = 'Unwrapping method';
method.tag = 'method';
method.labels = {'Mark3D','Mark2D','Huttonish'};
method.values = {'Mark3D' 'Mark2D' 'Huttonish'};
method.val = {'Mark3D'};
method.help = {'Select method for phase unwrapping'};
fwhm.type = 'entry';
fwhm.name = 'FWHM';
fwhm.tag = 'fwhm';
fwhm.strtype = 'e';
fwhm.num = [1 1];
fwhm.val = {10};
fwhm.help = {'FWHM of Gaussian filter used to implement weighted smoothing of unwrapped maps.'};
pad.type = 'entry';
pad.name = 'pad';
pad.tag = 'pad';
pad.strtype = 'e';
pad.num = [1 1];
pad.val = {0};
pad.help = {'Size of padding kernel if required.'};
ws.type='menu';
ws.name = 'Weighted smoothing';
ws.tag = 'ws';
ws.labels = {'Weighted Smoothing','No weighted smoothing'};
ws.values = {1 0};
ws.val = {1};
ws.help = {'Select normal or weighted smoothing.'};
uflags.type = 'branch';
uflags.name = 'uflags';
uflags.tag = 'uflags';
uflags.val = {method,fwhm,pad,ws};
uflags.help = {['Different options for phase unwrapping and field map processing']};
%------------------------------------------------------------------------
% Short and long echo times
et.type='entry';
et.name = 'Echo times [short TE long TE]';
et.tag = 'et';
et.strtype = 'e';
et.num = [1 2];
et.help = {'Enter the short and long echo times (in ms) of the data used to acquire the field map.'};
%------------------------------------------------------------------------
% Brain masking
maskbrain.type='menu';
maskbrain.name = 'Mask brain';
maskbrain.tag = 'maskbrain';
maskbrain.labels = {'Mask brain','No brain masking'};
maskbrain.values = {1 0};
maskbrain.help = {'Select masking or no masking of the brain. If masking is selected,',...
'the magnitude image is used to generate a mask of the brain.'};
%------------------------------------------------------------------------
% Blip direction
blipdir.type='menu';
blipdir.name = 'Blip direction';
blipdir.tag = 'blipdir';
blipdir.labels = {'-1','1'};
blipdir.values = {-1 1};
blipdir.help = {['Enter the blip direction. This is the polarity of the phase-encode blips',...
'describing the direction in which k-space is traversed along the y-axis',...
'during EPI acquisition with respect to the coordinate system used in SPM.',...
'In this coordinate system, the phase encode direction corresponds with the',...
'y-direction and is defined as positive from the posterior to the anterior of the',...
'head.']};
%------------------------------------------------------------------------
% Total EPI readout time
tert.type='entry';
tert.name = 'Total EPI readout time';
tert.tag = 'tert';
tert.strtype = 'e';
tert.num = [1 1];
tert.help = {'Enter the total EPI readout time (in ms). This is the time taken to',...
'acquire all of the phase encode steps required to cover k-space (ie one image slice).',...
'For example, if the EPI sequence has 64 phase encode steps, the total readout time is',...
'the time taken to acquire 64 echoes, e.g.',...
'total readout time = number of echoes × echo spacing.',...
'This time does not include i) the duration of the excitation, ii) the delay between,'...
'the excitation and the start of the acquisition or iii) time for fat saturation etc.'};
%------------------------------------------------------------------------
% EPI-based field map or not?
epifm.type='menu';
epifm.name = 'EPI-based field map?';
epifm.tag = 'epifm';
epifm.labels = {'non-EPI','EPI'};
epifm.values = {0 1};
epifm.help = {['Select non-EPI or EPI based field map. The field map data may be acquired using a non-EPI sequence (typically a',...
'gradient echo sequence) or an EPI sequence. The processing will be slightly different',...
'for the two cases. If using an EPI-based field map, the resulting Voxel Displacement',...
'Map will be inverted since the field map was acquired in distorted space.']};
%------------------------------------------------------------------------
% Jacobian modulation
ajm.type='menu';
ajm.name = 'Jacobian modulation?';
ajm.tag = 'ajm';
ajm.labels = {'Do not use','Use'};
ajm.values = {0 1};
ajm.val = {0};
ajm.help = {['Select whether or not to use Jacobian modulation. This will adjust',...
'the intensities of voxels that have been stretched or compressed but in general is',...
'not recommended for EPI distortion correction']};
%------------------------------------------------------------------------
% Defaults values used for field map creation
defaultsvals.type = 'branch';
defaultsvals.name = 'Defaults values';
defaultsvals.tag = 'defaultsval';
defaultsvals.val = {et,maskbrain,blipdir,tert,epifm,ajm,uflags,mflags};
defaultsvals.help = {['Defaults values']};
%------------------------------------------------------------------------
% Defaults parameter file used for field map creation
[default_file_path, tmpname] = fileparts(mfilename('fullpath'));
default_filename = sprintf('%s%s%s',default_file_path,filesep,'pm_defaults.m');
defaultsfile.type = 'files';
defaultsfile.name = 'Defaults File';
defaultsfile.tag = 'defaultsfile';
defaultsfile.num = [1 1];
defaultsfile.filter = 'm';
defaultsfile.ufilter = '^pm_defaults.*\.m$';
defaultsfile.val = {default_filename};
defaultsfile.dir = default_file_path;
defaultsfile.help = {[...
'Select the ''pm_defaults*.m'' file containing the parameters for the field map data. ',...
'Please make sure that the parameters defined in the defaults file are correct for ',...
'your field map and EPI sequence. To create your own defaults file, either edit the '...
'distributed version and/or save it with the name ''pm_defaults_yourname.m''.']};
%------------------------------------------------------------------------
% Choice for defaults input
defaults.type = 'choice';
defaults.name = 'FieldMap defaults';
defaults.tag = 'defaults';
defaults.values = {defaultsvals, defaultsfile};
defaults.help = {['FieldMap default values can be entered as a file or set of values.']};
%-----------------------------------------------------------------------
% Match anatomical image
matchanat.type = 'menu';
matchanat.name = 'Match anatomical image to EPI?';
matchanat.tag = 'matchanat';
matchanat.labels = {'match anat', 'none'};
matchanat.values = {1,0};
matchanat.val = {0};
matchanat.help = {[...
'Match the anatomical image to the distortion corrected EPI. This can be done',...
'to allow for visual inspection and comparison of the distortion corrected EPI.']};
%------------------------------------------------------------------------
% Select anatomical image for display and comparison
anat.type = 'files';
anat.name = 'Select anatomical image for comparison';
anat.tag = 'anat';
anat.filter = 'image';
anat.num = [0 1];
anat.val = {''};
anat.help = {[...
'Select an anatomical image for comparison with the distortion corrected EPI.']};
%-----------------------------------------------------------------------
% Write unwarped EPI image
writeunwarped.type = 'menu';
writeunwarped.name = 'Write unwarped EPI?';
writeunwarped.tag = 'writeunwarped';
writeunwarped.labels = {'write unwarped EPI', 'none'};
writeunwarped.values = {1,0};
writeunwarped.help = {[...
'Write out distortion corrected EPI image. The image is saved with the prefix u.']};
%-----------------------------------------------------------------------
% Name
sessname.type = 'entry';
sessname.name = 'Name extension for session specific vdm files';
sessname.tag = 'sessname';
sessname.strtype = 's';
sessname.num = [1 Inf];
sessname.val = {'session'};
sessname.help = {['This will be the name extension followed by an incremented',...
'integer for session specific vdm files.']};
%-----------------------------------------------------------------------
% Match VDM file to EPI image
matchvdm.type = 'menu';
matchvdm.name = 'Match VDM to EPI?';
matchvdm.tag = 'matchvdm';
matchvdm.labels = {'match vdm', 'none'};
matchvdm.values = {1,0};
matchvdm.help = {[...
'Match VDM file to EPI image. This option will coregister the field map data ',...
'to the selected EPI before doing distortion correction.']};
%------------------------------------------------------------------------
% Select a single EPI to unwarp
epi.type = 'files';
epi.name = 'Select EPI to Unwarp';
epi.tag = 'epi';
epi.filter = 'image';
epi.num = [0 1];
epi.val = {''};
epi.help = {[...
'Select an image to distortion correct. The corrected image will be saved',...
'with the prefix u. The original and the distortion corrected images can be',...
'displayed for comparison.']};
%------------------------------------------------------------------------
% Other options that are not included in the defaults file
% Define precalculated field map type of job
session.type = 'branch';
session.name = 'Session';
session.tag = 'session';
session.val = {epi};
session.help = {'Data for this session.'};
epi_session.type = 'repeat';
epi_session.name = 'EPI Sessions';
epi_session.values = {session};
epi_session.num = [1 Inf];
epi_session.help = {[...
'If a single VDM file will be used for multiple sessions, select the first EPI',...
'in each session. A copy of the VDM file will be matched to the first EPI in each',...
'session and save with a seprate name.']};
%------------------------------------------------------------------------
% If using precalculated field map and want to do a matching, need the
% magnitude image in same space as precalculated field map
magfieldmap.type = 'files';
magfieldmap.name = 'Select magnitude image in same space as fieldmap';
magfieldmap.tag = 'magfieldmap';
magfieldmap.filter = 'image';
magfieldmap.num = [0 1];
magfieldmap.val = {''};
magfieldmap.help = {[...
'Select magnitude image which is in the same space as the field map to do matching to EPI']};
%------------------------------------------------------------------------
% Define precalculated field map type of job
subj.type = 'branch';
subj.name = 'Subject';
subj.tag = 'subj';
subj.val = {precalcfieldmap,magfieldmap,defaults,epi_session,matchvdm,sessname,writeunwarped,anat,matchanat};
subj.help = {'Data for this subject or field map session.'};
data.type = 'repeat';
data.name = 'Data';
data.values = {subj};
data.num = [1 Inf];
data.help = {['Subjects or sessions for which individual field map data has been acquired.']};
precalcfieldmap.type = 'branch';
precalcfieldmap.name = 'Precalculated FieldMap (in Hz)';
precalcfieldmap.tag = 'precalcfieldmap';
precalcfieldmap.val = {data};
precalcfieldmap.prog = @fieldmap_precalcfieldmap;
precalcfieldmap.help = {[...
'Calculate a voxel displacement map (VDM) from a precalculated field map. This option ',...
'expects a processed field map (ie phase unwrapped, masked if necessary and scaled to Hz). ',...
'Precalculated field maps can be generated by the FieldMap toolbox and stored as fpm_* files.']};
%------------------------------------------------------------------------
% Define phase/magnitude type of job, double phase and magnitude file
subj.type = 'branch';
subj.name = 'Subject';
subj.tag = 'subj';
subj.val = {shortphase,shortmag,longphase,longmag,defaults,epi_session,matchvdm,sessname,writeunwarped,anat,matchanat};
subj.help = {['Data for this subject or field map session.']};
data.type = 'repeat';
data.name = 'Data';
data.values = {subj};
data.num = [1 Inf];
data.help = {['Subjects or sessions for which individual field map data has been acquired.']};
phasemag.type = 'branch';
phasemag.name = 'Phase and Magnitude Data';
phasemag.tag = 'phasemag';
phasemag.val = {data};
phasemag.prog = @fieldmap_phasemag;
phasemag.help = {[...
'Calculate a voxel displacement map (VDM) from double phase and magnitude field map data.'...
'This option expects two phase and magnitude pairs of data of two different ',...
'echo times.']};
%------------------------------------------------------------------------
% Define phase/magnitude type of job, presubtracted phase and single magnitude file
subj.type = 'branch';
subj.name = 'Subject';
subj.tag = 'subj';
subj.val = {presubphase,presubmag,defaults,epi_session,matchvdm,sessname,writeunwarped,anat,matchanat};
subj.help = {['Data for this subject or field map session.']};
data.type = 'repeat';
data.name = 'Data';
data.values = {subj};
data.num = [1 Inf];
data.help = {['Subjects or sessions for which individual field map data has been acquired.']};
presubphasemag.type = 'branch';
presubphasemag.name = 'Presubtracted Phase and Magnitude Data';
presubphasemag.tag = 'presubphasemag';
presubphasemag.val = {data};
presubphasemag.prog = @fieldmap_presubphasemag;
presubphasemag.help = {[...
'Calculate a voxel displacement map (VDM) from presubtracted phase and magnitude field map data. ',...
'This option expects a single magnitude image and a single phase image resulting from the ',...
'subtraction of two phase images (where the subtraction is usually done automatically by ',...
'the scanner software). The phase image will be scaled between +/- PI.']};
%------------------------------------------------------------------------
% Define real/imaginary type of job
subj.type = 'branch';
subj.name = 'Subject';
subj.tag = 'subj';
subj.val = {shortreal,shortimag,longreal,longimag,defaults,epi_session,matchvdm,sessname,writeunwarped,anat,matchanat};
subj.help = {['Data for this subject or field map session.']};
data.type = 'repeat';
data.name = 'Data';
data.values = {subj};
data.num = [1 Inf];
data.help = {['Subjects or sessions for which individual field map data has been acquired.']};
realimag.type = 'branch';
realimag.name = 'Real and Imaginary Data';
realimag.tag = 'realimag';
realimag.val = {data};
realimag.prog = @fieldmap_realimag;
realimag.help = {[...
'Calculate a voxel displacement map (VDM) from real and imaginary field map data. ',...
'This option expects two real and imaginary pairs of data of two different ',...
'echo times.']};
%------------------------------------------------------------------------
% Define field map job
job.type = 'choice';
job.name = 'FieldMap';
job.tag = 'fieldmap';
job.values = {presubphasemag,realimag,phasemag,precalcfieldmap};
p1 = [...
'The FieldMap toolbox generates unwrapped field maps which are converted to ',...
'voxel displacement maps (VDM) that can be used to unwarp geometrically ',...
'distorted EPI images. For references and an explantion of the theory behind the field map based ',...
'unwarping, see FieldMap_principles.man. ',...
'The resulting VDM files are saved with the prefix vdm and can be used in combination with Realign & Unwarp ',...
'to calculate and correct for the combined effects of static and movement-related ',...
'susceptibility induced distortions.'];
job.help = {p1,''};
%------------------------------------------------------------------------
function fieldmap_presubphasemag(job)
FieldMap_Run(job.subj);
%------------------------------------------------------------------------
function fieldmap_realimag(job)
FieldMap_Run(job.subj);
%------------------------------------------------------------------------
function fieldmap_phasemag(job)
Fieldmap_Run(job.subj);
%------------------------------------------------------------------------
function fieldmap_precalcfieldmap(job)
FieldMap_Run(job.subj);
%------------------------------------------------------------------------
|
github
|
spm/spm5-master
|
spm_TBR_fieldmap.m
|
.m
|
spm5-master/toolbox/FieldMap/spm_TBR_fieldmap.m
| 13,503 |
utf_8
|
89b1b6e02a00ef76ca59671d9b168743
|
function spm_TBR_fieldmap
% Convert Raw Siemens DICOM files from fieldmap sequence into something
% that SPM can use
% FORMAT spm_TBR_fieldmap
% Converted files are written to the current directory
%_______________________________________________________________________
% %W% %E%
%17.10.2003: change of smooth parameter from 2 to 16 in trajrecon
%10.12.2003: smooth parameter can be entered from dialog box
%11.02.2004: update version for converting fieldmap data
fprintf(1,'TBR 11.02.2004 Version for converting field map data \n');
spm_defaults;
global hdr
P = spm_get(Inf,'*','Select files');
%SliceOrder = spm_input('Slice Order', 2, 'm',...
% 'Ascending Slices|Descending Slices', str2mat('ascending','descending'));
SliceOrder = 'ascending';
% Select trajectory file
[d,f,s] = fileparts(which(mfilename));
t = load(spm_get(1,'traj_*_????-??-??_??-??.mat','Select trajectory',d));
% Select smoothing parameter
myline1='Enter the smoothing parameter in the following dialog box';
myline2='The default value is 4.0 pixels';
myline3='Choose a lower value if ghosting occurs in the images';
myline4='Choose a higher value if there are line artefacts in the images';
uiwait(msgbox({myline1,myline2,myline3,myline4},'Smoothing Info','modal'));
myprompt={'Enter the smoothing parameter (in pixels):'};
mydef={'4.0'};
mydlgTitle=['Smoothing parameter'];
mylineNo=1;
answer=inputdlg(myprompt,mydlgTitle,mylineNo,mydef);
myzelle=answer(1);
smooth_par=str2num(myzelle{1});
hdr = spm_dicom_headers(P);
[raw,guff] = select_fid(hdr);
% Find fieldmap data and extract it from the raw TBR data to be converted
[raw,pm_raw] = select_series(raw,cat(2,'ralf_flash_fieldmap',' ','chloe_epi_tbr',' ','ralf_epi_fieldmap_ff','ralf_epi_fieldmap_ff_shim'));
%spm_progress_bar('Init',length(hdr),['Writing Images'], 'Files written');
%for i=1:length(raw),
% convert_fid(raw{i},t.M,SliceOrder,smooth_par);
% spm_progress_bar('Set',i);
%end;
%spm_progress_bar('Clear');
spm_progress_bar('Init',length(pm_raw),['Processing Fieldmap'], 'Files written');
if ~isempty(pm_raw)
% Process fieldmap data if acquired
% Convert double echo fid
convert_pm(pm_raw,t.M,SliceOrder,smooth_par);
end
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [fid,other] = select_fid(hdr)
fid = {};
other = {};
for i=1:length(hdr),
if ~checkfields(hdr{i},'ImageType','StartOfCSAData') |...
~strcmp(deblank(hdr{i}.ImageType),'ORIGINAL\PRIMARY\RAW'),
other = {other{:},hdr{i}};
else,
fid = {fid{:},hdr{i}};
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function ok = checkfields(hdr,varargin)
ok = 1;
for i=1:(nargin-1),
if ~isfield(hdr,varargin{i}),
ok = 0;
break;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function clean = strip_unwanted(dirty)
msk = find((dirty>='a'&dirty<='z') | (dirty>='A'&dirty<='Z') |...
(dirty>='0'&dirty<='9') | dirty=='_');
clean = dirty(msk);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vol=trajrecon(meas,M,smooth_par)
% Oliver Joseph's TBR reconstruction
%17.10.2003: change of smooth parameter from 2 to 16
%11.11.2003: smoothing parameter has become input argument
% Regridded FT!!!!
% fid ( LINES, POINTS, SLICES )!!!
%-------------------------------------------------------------------
f1d=zeros(64,size(meas,2),size(meas,3));
for line=1:size(meas,2)
f1d(:,line,:)=M(:,:,line)*squeeze(meas(:,line,:));
end;
% Weighted phase reference smoothing
%-------------------------------------------------------------------
x = fftshift(-32:31)';
y = exp(-(x.^2)*(smooth_par/64)^2);
dd = f1d(:,65,:).*conj(f1d(:,66,:));
df = fft(dd,[],1);
df = df.*repmat(y,[1 1 size(meas,3)]);
dff = ifft(df,[],1);
d2 = exp(sqrt(-1)*angle(dff));
% Slice Based Phase correction %
%-------------------------------------------------------------------
f1d(:,2:2:64,:) = f1d(:,2:2:64,:).*repmat(d2,[1,32,1]);
% 2nd FT
% Need loop to prevent odd-number-of-slices fftshift problem
%-------------------------------------------------------------------
% Chloe's changes 27/02/03
% Need an additional conj to extract correct phase direction
% This doesn't effect the magnitude data
%for slice=1:size(f1d,3),
% vol(:,:,slice)=fftshift(fft(fftshift(conj(f1d(:,1:64,slice))),[],2));
%end
for slice=1:size(f1d,3),
vol(:,:,slice)=conj(fftshift(fft(fftshift(conj(f1d(:,1:64,slice))),[],2)));
end
% Don't calculate the magnitude here because we need complex data in case
% image is field map data
% vol = abs(vol);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function convert_pm(hdr,M,SliceOrder,smooth_par)
% Do the right thing with each type of field map
[other_hdr, fmap_hdr] = select_series(hdr,cat(2,'ralf_epi_fieldmap_ff','ralf_flash_fieldmap','ralf_epi_fieldmap_ff_shim'));
if ~isempty(fmap_hdr)
% Sort fieldmap data into short/long echo pairs ready for conversion if require
Fhdr=sort_fieldmap_data(fmap_hdr);
nfmap=length(Fhdr)/2;
TE={'short','long'};
% Processing each fieldmap requires converting two dicom files
for i=1:2:length(Fhdr) % Process each fieldmap as pair of images
% Need 4 cells to hold real and imaginary pair
npm=1;
V=cell(1,4);
for j=1:2 % Process each pair of images
index=(i-1)+j;
hdr=Fhdr{index};
% Sort out output filename
%-------------------------------------------------------------------
% fname = sprintf('f%s-%.4d.img', strip_unwanted(hdr.PatientID),hdr.SeriesNumber);
fname = sprintf('f%s-%.4d-%.6d.img', strip_unwanted(hdr.PatientID),...
hdr.SeriesNumber, hdr.AcquisitionNumber);
% Order of files for the field map routines is
% short_real, short_imag, short_mag
% long_real, long_imag, long_mag (are mags this really necessary?)
TEname = sprintf('%s',TE{j});
fname = [deblank(spm_str_manip(fname,'rt')) '-' deblank(TEname)];
[V{npm},V{npm+1}] = complex2spm(hdr,M,SliceOrder,fname,smooth_par);
npm=npm+2;
end
end
end
if ~isempty(other_hdr)
for i=1:length(other_hdr)
hdr=other_hdr{i};
% Sort out output filename
%-------------------------------------------------------------------
% fname = sprintf('f%s-%.4d.img', strip_unwanted(hdr.PatientID),hdr.SeriesNumber);
fname = sprintf('f%s-%.4d-%.6d.img', strip_unwanted(hdr.PatientID),...
hdr.SeriesNumber, hdr.AcquisitionNumber);
% Order of files for the field map
TEname = sprintf('TE%s',num2str(hdr.EchoTime));
fname = [deblank(spm_str_manip(fname,'rt')) '-' deblank(TEname)];
complex2spm(hdr,M,SliceOrder,fname,smooth_par);
end
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function varargout = complex2spm(hdr,M,SliceOrder,fname,smooth_par)
persistent SpacingBetweenSlices
% Dimensions and data
%-------------------------------------------------------------------
if hdr.Columns*hdr.Rows*2 ~= hdr.SizeOfCSAData,
warning(['Cant convert "' fname '".']);
return;
end;
nphase = 66; % <- may change
dim = [hdr.Columns/4 nphase hdr.Rows/nphase];
fd = fopen(hdr.Filename,'r','ieee-le');
if fd==-1,
warning(['Cant open "' hdr.Filename '" to create "' fname '".']);
return;
end;
fseek(fd,hdr.StartOfCSAData,-1);
cdata = fread(fd,hdr.SizeOfCSAData/4,'float');
fclose(fd);
cdata = reshape(cdata(1:2:end)+sqrt(-1)*cdata(2:2:end),dim);
if ~isempty(findstr('flash_fieldmap',hdr.SeriesDescription))
volume = flashrecon(cdata);
else
volume = trajrecon(cdata,M,smooth_par);
end
dim = [size(volume) spm_type('int16')];
% Orientation information as for TBR above
%-------------------------------------------------------------------
analyze_to_dicom = [diag([1 -1 1]) [0 (dim(2)+1) 0]'; 0 0 0 1]*[eye(4,3) [-1 -1 -1 1]'];
if isfield(hdr,'SpacingBetweenSlices'),
SpacingBetweenSlices = hdr.SpacingBetweenSlices;
else,
if isempty(SpacingBetweenSlices),
SpacingBetweenSlices = spm_input('Spacing Between Slices (mm)',1,'r','3.0',[1 1]);
end;
end;
vox = [hdr.PixelSpacing SpacingBetweenSlices];
pos = hdr.ImagePositionPatient';
orient = reshape(hdr.ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end;
% The image position vector is not correct. In dicom this vector points to
% the upper left corner of the image. Perhaps it is unlucky that this is
% calculated in the syngo software from the vector pointing to the center of
% the slice (keep in mind: upper left slice) with the enlarged FoV.
dicom_to_patient = [orient*diag(vox) pos ; 0 0 0 1];
truepos = dicom_to_patient *[([hdr.Columns hdr.Rows]-dim(1:2))/2 0 1]';
dicom_to_patient = [orient*diag(vox) truepos(1:3) ; 0 0 0 1];
patient_to_tal = diag([-1 -1 1 1]);
mat = patient_to_tal*dicom_to_patient*analyze_to_dicom;
% Re-arrange order of slices
switch SliceOrder,
case {'descending'},
order = 1:dim(3);
case {'ascending'},
order = dim(3):-1:1;
otherwise,
error('Unknown slice order');
end;
volume(:,:,order) = volume;
mat = mat*[eye(3) [0 0 -(order(1)-1)]'; 0 0 0 1];
% Really need to have SliceNormalVector - but it doesn't exist.
% Also need to do something else for interleaved volumes.
%-------------------------------------------------------------------
% SliceNormalVector = read_SliceNormalVector(hdr);
% if det([reshape(hdr.ImageOrientationPatient,[3 2]) SliceNormalVector(:)])<0;
% volume = volume(:,:,end:-1:1);
% mat = mat*[eye(3) [0 0 -(dim(3)-1)]'; 0 0 0 1];
% end;
% Possibly useful information
%-------------------------------------------------------------------
tim = datevec(hdr.AcquisitionTime/(24*60*60));
descrip = sprintf('%s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g TBR',...
hdr.MRAcquisitionType,...
deblank(hdr.ScanningSequence),...
hdr.RepetitionTime,hdr.EchoTime,hdr.FlipAngle,...
datestr(hdr.AcquisitionDate),tim(4),tim(5),tim(6));
% Construct name and write out real part of complex data
realname=sprintf('%s','real');
realfname=[deblank(spm_str_manip(fname,'rt')) '-' deblank(realname) '.img'];
V{1}=struct('fname',realfname,'dim',dim,'mat',mat,'descrip',descrip);
V{1}=spm_write_vol(V{1},real(volume));
% Construct name and write out imaginary part of complex data
imagname=sprintf('%s','imag');
imagfname=[deblank(spm_str_manip(fname,'rt')) '-' deblank(imagname) '.img'];
V{2}=struct('fname',imagfname,'dim',dim,'mat',mat,'descrip',descrip);
V{2}=spm_write_vol(V{2},imag(volume));
% Construct name and write out magnitude of complex data
magfname=[deblank(spm_str_manip(fname,'rt')) '.img'];
Vi=struct('fname',magfname,'dim',dim,'mat',mat,'descrip',descrip);
Vi=spm_write_vol(Vi,abs(volume));
varargout{1}=V{1};
varargout{2}=V{2};
return;
%_______________________________________________________________________
function F = sort_fieldmap_data(hdr)
% Want to extract the structures in the correct order to
% create a real and imaginary and a magnitude image for
% two volumes (or more?).
nfiles=length(hdr);
if nfiles==1
error('Need at least 2 dicom files for field map conversion');
return
end
sessions=[];
for i=1:nfiles
sessions(i)=hdr{i}.SeriesNumber;
end;
% Sort scans into sessions
fnum=1;
nfmap=1;
while fnum<=nfiles
nsess=find(sessions==sessions(fnum));
for i=1:length(nsess)
sesshdr{i}=hdr{nsess(i)};
end
% Split field maps up into pairs
n=2:2:length(nsess);
if ~isempty(n)
% These lines are commented out so that only the last fieldmaps
% images are written.
%
% for i=1:length(n)
% F{nfmap}=sesshdr{n(i)-1};
% F{nfmap+1}=sesshdr{n(i)};
% nfmap=nfmap+2;
% end
F{nfmap}=sesshdr{n(end)-1};
F{nfmap+1}=sesshdr{n(end)};
nfmap=nfmap+2;
end
fnum=fnum+length(nsess);
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [fid,sfid] = select_series(hdr,seriesname)
fid = {};
sfid = {};
for i=1:length(hdr),
if findstr(deblank(hdr{i}.SeriesDescription),seriesname),
sfid = {sfid{:},hdr{i}};
else,
fid = {fid{:},hdr{i}};
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vol=flashrecon(cdata)
% Ralf Deichman's flash recon
[ncol nphase nslc]=size(cdata);
cdata=ifftshift(fft(fftshift(cdata),[],1));
% Double conj to reverse y direction for consistency with TBR data
% in y-direction, but without changing phase direction.
vol=conj(ifftshift(fft(fftshift(conj(cdata(:,1:nphase-2,:))),[],2)));
vol=vol(ncol/4+1:ncol*3/4,:,:);
dim=size(vol);
|
github
|
spm/spm5-master
|
spm_config_dartel.m
|
.m
|
spm5-master/toolbox/DARTEL/spm_config_dartel.m
| 37,694 |
utf_8
|
d594870b15cec5b2f71e483ac93c2bce
|
function job = spm_config_dartel
% Configuration file for DARTEL jobs
%_______________________________________________________________________
% Copyright (C) 2007 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_dartel.m 1032 2007-12-20 14:45:55Z john $
if spm_matlab_version_chk('7') < 0,
job = struct('type','const',...
'name','Need MATLAB 7 onwards',...
'tag','old_matlab',...
'val',...
{{['This toolbox needs MATLAB 7 or greater. '...
'More recent MATLAB functionality has been used by this toolbox.']}});
return;
end;
addpath(fullfile(spm('dir'),'toolbox','DARTEL'));
%_______________________________________________________________________
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num)'],...
'name','tag','strtype','num');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num)'],...
'name','tag','fltr','num');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values})'],...
'name','tag','labels','values');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val})'],...
'name','tag','val');
repeat = inline(['struct(''type'',''repeat'',''name'',name,''tag'',tag,'...
'''values'',{values})'],'name','tag','values');
%_______________________________________________________________________
% IMPORTING IMAGES FOR USE WITH DARTEL
%------------------------------------------------------------------------
matname = files('Parameter Files','matnames','mat',[1 Inf]);
matname.ufilter = '.*seg_sn\.mat$';
matname.help = {...
['Select ''_sn.mat'' files containing the spatial transformation ',...
'and segmentation parameters. '...
'Rigidly aligned versions of the image that was segmented will '...
'be generated. '...
'The image files used by the segmentation may have moved. '...
'If they have, then (so the import can find them) ensure that they are '...
'either in the output directory, or the current working directory.']};
%------------------------------------------------------------------------
odir = files('Output Directory','odir','dir',[1 1]);
%odir.val = {'.'};
odir.help = {...
'Select the directory where the resliced files should be written.'};
%------------------------------------------------------------------------
bb = entry('Bounding box','bb','e',[2 3]);
bb.val = {ones(2,3)*NaN};
bb.help = {[...
'The bounding box (in mm) of the volume that is to be written ',...
'(relative to the anterior commissure). '...
'Non-finite values will be replaced by the bounding box of the tissue '...
'probability maps used in the segmentation.']};
%------------------------------------------------------------------------
vox = entry('Voxel size','vox','e',[1 1]);
vox.val = {1.5};
vox.help = {...
['The (isotropic) voxel sizes of the written images. '...
'A non-finite value will be replaced by the average voxel size of '...
'the tissue probability maps used by the segmentation.']};
%------------------------------------------------------------------------
orig = mnu('Image option','image',...
{'Original','Bias Corrected','Skull-Stripped','Bias Corrected and Skull-stripped','None'},...
{1,3,5,7,0});
orig.val = {0};
orig.help = {...
['A resliced version of the original image can be produced, which may have '...
'various procedures applied to it. All options will rescale the images so '...
'that the mean of the white matter intensity is set to one. '...
'The ``skull stripped'''' versions are the images simply scaled by the sum '...
'of the grey and white matter probabilities.']};
%------------------------------------------------------------------------
grey = mnu('Grey Matter','GM',{'Yes','No'},{1,0});
grey.val = {1};
grey.help = {'Produce a resliced version of this tissue class?'};
%------------------------------------------------------------------------
white = mnu('White Matter','WM',{'Yes','No'},{1,0});
white.val = {1};
white.help = grey.help;
%------------------------------------------------------------------------
csf = mnu('CSF','CSF',{'Yes','No'}, {1,0});
csf.val = {0};
csf.help = grey.help;
%------------------------------------------------------------------------
initial = branch('Initial Import','initial',{matname,odir,bb,vox,orig,grey,white,csf});
initial.help = {[...
'Images first need to be imported into a form that DARTEL can work with. '...
'This involves taking the results of the segmentation (*_seg_sn.mat)/* \cite{ashburner05} */, '...
'in order to have rigidly aligned tissue class images. '...
'Typically, there would be imported grey matter and white matter images, '...
'but CSF images can also be included. '...
'The subsequent DARTEL alignment will then attempt to nonlinearly register '...
'these tissue class images together.']};
initial.prog = @spm_dartel_import;
initial.vfiles = @vfiles_initial_import;
%------------------------------------------------------------------------
% RUNNING DARTEL TO MATCH A COMMON MEAN TO THE INDIVIDUAL IMAGES
%------------------------------------------------------------------------
iits = mnu('Inner Iterations','its',...
{'1','2','3','4','5','6','7','8','9','10'},...
{1,2,3,4,5,6,7,8,9,10});
iits.val = {3};
iits.help = {[...
'The number of Gauss-Newton iterations to be done within this '...
'outer iteration. After this, new average(s) are created, '...
'which the individual images are warped to match.']};
%------------------------------------------------------------------------
template = files('Template','template','nifti',[1 1]);
template.val = {};
template.help = {[...
'Select template. Smoother templates should be used '...
'for the early iterations. '...
'Note that the template should be a 4D file, with the 4th dimension '...
'equal to the number of sets of images.']};
%------------------------------------------------------------------------
rparam = entry('Reg params','rparam','e',[1 3]);
rparam.val = {[0.1 0.01 0.001]};
rparam.help = {...
['For linear elasticity, the parameters are mu, lambda and id. ',...
'For membrane and bending energy, the parameters are lambda, unused and id.',...
'id is a term for penalising absolute displacements, '...
'and should therefore be small.'],...
['Use more regularisation for the early iterations so that the deformations '...
'are smooth, and then use less for the later ones so that the details can '...
'be better matched.']};
%------------------------------------------------------------------------
K = mnu('Time Steps','K',{'1','2','4','8','16','32','64','128','256','512'},...
{0,1,2,3,4,5,6,7,8,9});
K.val = {6};
K.help = {...
['The number of time points used for solving the '...
'partial differential equations. A single time point would be '...
'equivalent to a small deformation model. '...
'Smaller values allow faster computations, but are less accurate in terms '...
'of inverse consistency and may result in the one-to-one mapping '...
'breaking down. Earlier iteration could use fewer time points, '...
'but later ones should use about 64 '...
'(or fewer if the deformations are very smooth).']};
%------------------------------------------------------------------------
slam = mnu('Smoothing Parameter','slam',{'None','0.5','1','2','4','8','16','32'},...
{0,0.5,1,2,4,8,16,32});
slam.val = {1};
slam.help = {...
['A LogOdds parameterisation of the template is smoothed using a multi-grid '...
'scheme. The amount of smoothing is determined by this parameter.']};
%------------------------------------------------------------------------
lmreg = entry('LM Regularisation','lmreg','e',[1 1]);
lmreg.val = {0.01};
lmreg.help = {...
['Levenberg-Marquardt regularisation. Larger values increase the '...
'the stability of the optimisation, but slow it down. A value of '...
'zero results in a Gauss-Newton strategy, but this is not recommended '...
'as it may result in instabilities in the FMG.']};
%------------------------------------------------------------------------
cycles = mnu('Cycles','cyc',{'1','2','3','4','5','6','7','8'},...
{1,2,3,4,5,6,7,8});
cycles.val = {3};
cycles.help = {[...
'Number of cycles used by the full multi-grid matrix solver. '...
'More cycles result in higher accuracy, but slow down the algorithm. '...
'See Numerical Recipes for more information on multi-grid methods.']};
%------------------------------------------------------------------------
its = mnu('Iterations','its',{'1','2','3','4','5','6','7','8'},...
{1,2,3,4,5,6,7,8});
its.val = {3};
its.help = {[...
'Number of relaxation iterations performed in each multi-grid cycle. '...
'More iterations are needed if using ``bending energy'''' regularisation, '...
'because the relaxation scheme only runs very slowly. '...
'See the chapter on solving partial differential equations in '...
'Numerical Recipes for more information about relaxation methods.']};
%------------------------------------------------------------------------
fmg = branch('Optimisation Settings','optim',{lmreg,cycles,its});
fmg.help = {[...
'Settings for the optimisation. If you are unsure about them, '...
'then leave them at the default values. '...
'Optimisation is by repeating a number of Levenberg-Marquardt '...
'iterations, in which the equations are solved using a '...
'full multi-grid (FMG) scheme. '...
'FMG and Levenberg-Marquardt are both described in '...
'Numerical Recipes (2nd edition).']};
%------------------------------------------------------------------------
param = branch('Outer Iteration','param',{iits,rparam,K,slam});
param.help = {...
['Different parameters can be specified for each '...
'outer iteration. '...
'Each of them warps the images to the template, and then regenerates '...
'the template from the average of the warped images. '...
'Multiple outer iterations should be used for more accurate results, '...
'beginning with a more coarse registration (more regularisation) '...
'then ending with the more detailed registration (less regularisation).']};
%------------------------------------------------------------------------
params = repeat('Outer Iterations','param',{param});
params.help = {[...
'The images are averaged, and each individual image is warped to '...
'match this average. This is repeated a number of times.']};
params.num = [1 Inf];
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [4 2 1e-6]; % rparam
param.val{3}.val{1} = 0; % K
param.val{4}.val{1} = 16;
params.val{1} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [2 1 1e-6]; % rparam
param.val{3}.val{1} = 0; % K
param.val{4}.val{1} = 8;
params.val{2} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [1 0.5 1e-6]; % rparam
param.val{3}.val{1} = 1; % K
param.val{4}.val{1} = 4;
params.val{3} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [0.5 0.25 1e-6]; % rparam
param.val{3}.val{1} = 2; % K
param.val{4}.val{1} = 2;
params.val{4} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [0.25 0.125 1e-6]; % rparam
param.val{3}.val{1} = 4; % K
param.val{4}.val{1} = 1;
params.val{5} = param;
param.val{1}.val{1} = 3; % iits
param.val{2}.val{1} = [0.125 0.0625 1e-6]; % rparam
param.val{3}.val{1} = 6; % K
param.val{4}.val{1} = 0.5;
params.val{6} = param;
%------------------------------------------------------------------------
data = files('Images','images','image',[1 Inf]);
data.ufilter = '^r.*';
data.help = {...
['Select a set of imported images of the same type '...
'to be registered by minimising '...
'a measure of difference from the template.']};
%------------------------------------------------------------------------
data = repeat('Images','images',{data});
data.num = [1 Inf];
data.help = {...
['Select the images to be warped together. '...
'Multiple sets of images can be simultaneously registered. '...
'For example, the first set may be a bunch of grey matter images, '...
'and the second set may be the white matter images of the same subjects.']};
%------------------------------------------------------------------------
code = mnu('Objective function','code',{'Sum of squares','Multinomial'},{0,2});
code.val = {2};
code.help = {...
['The objective function of the registration is specified here. '...
'Multinomial is preferred for matching binary images to an average tissue probability map. '...
'Sums of squares is more appropriate for regular images.']};
%------------------------------------------------------------------------
form = mnu('Regularisation Form','rform',...
{'Linear Elastic Energy','Membrane Energy','Bending Energy'},{0,1,2});
form.val = {0};
form.help = {[...
'The registration is penalised by some ``energy'''' term. Here, the form '...
'of this energy term is specified. '...
'Three different forms of regularisation can currently be used.']};
%------------------------------------------------------------------------
tname = entry('Template basename','template','s',[1 Inf]);
tname.val = {'Template'};
tname.help = {[...
'Enter the base for the template name. '...
'Templates generated at each outer iteration of the '...
'procedure will be basename_1.nii, basename_2.nii etc. If empty, then '...
'no template will be saved. Similarly, the estimated flow-fields will '...
'have the basename appended to them.']};
%------------------------------------------------------------------------
settings = branch('Settings','settings',{tname,form,params,fmg});
settings.help = {[...
'Various settings for the optimisation. '...
'The default values should work reasonably well for aligning tissue '...
'class images together.']};
%------------------------------------------------------------------------
warp = branch('Run DARTEL (create Templates)','warp',{data,settings});
warp.prog = @spm_dartel_template;
warp.check = @check_runjob;
warp.vfiles = @vfiles_runjob;
warp.help = {[...
'Run the DARTEL nonlinear image registration procedure. '...
'This involves iteratively matching all the selected images to '...
'a template generated from their own mean. '...
'A series of Template*.nii files are generated, which become increasingly '...
'crisp as the registration proceeds. '...
'/* An example is shown in figure \ref{Fig:averages}.'...
'\begin{figure} '...
'\begin{center} '...
'\epsfig{file=averages,width=140mm} '...
'\end{center} '...
'\caption{ '...
'This figure shows the intensity averages of grey (left) and '...
'white (right) matter images after different numbers of iterations. '...
'The top row shows the average after initial rigid-body alignment. '...
'The middle row shows the images after three iterations, '...
'and the bottom row shows them after 18 iterations. '...
'\label{Fig:averages}} '...
'\end{figure}*/']};
%------------------------------------------------------------------------
% RUNNING DARTEL TO MATCH A PRE-EXISTING TEMPLATE TO THE INDIVIDUALS
%------------------------------------------------------------------------
params1 = params;
params1.help = {[...
'The images are warped to match a sequence of templates. '...
'Early iterations should ideally use smoother templates '...
'and more regularisation than later iterations.']};
params1.values{1}.val{4} = template;
hlp = {[...
'Different parameters and templates can be specified '...
'for each outer iteration.']};
hlp1={[...
'The number of Gauss-Newton iterations to be done '...
'within this outer iteration.']};
params1.values{1}.help = hlp;
params1.values{1}.val{1}.help = hlp1;
for i=1:numel(params1.val),
params1.val{i}.val{4} = template;
params1.val{i}.val{1}.help = hlp1;
params1.val{i}.help = hlp;
end
settings1 = branch('Settings','settings',{form,params1,fmg});
settings1.help = {[...
'Various settings for the optimisation. '...
'The default values should work reasonably well for aligning tissue '...
'class images together.']};
warp1 = branch('Run DARTEL (existing Templates)','warp1',{data,settings1});
warp1.prog = @spm_dartel_warp;
warp1.check = @check_runjob;
warp1.vfiles = @vfiles_runjob1;
warp1.help = {[...
'Run the DARTEL nonlinear image registration procedure to match '...
'individual images to pre-existing template data. '...
'Start out with smooth templates, and select crisp templates for '...
'the later iterations.']};
% WARPING IMAGES TO MATCH TEMPLATES
%------------------------------------------------------------------------
K = mnu('Time Steps','K',{'1','2','4','8','16','32','64','128','256','512'},...
{0,1,2,3,4,5,6,7,8,9});
K.val = {6};
K.help = {...
['The number of time points used for solving the '...
'partial differential equations. Note that Jacobian determinants are not '...
'very accurate for very small numbers of time steps (less than about 16).']};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
ffields = files('Flow fields','flowfields','nifti',[1 Inf]);
ffields.ufilter = '^u_.*';
ffields.help = {...
['The flow fields store the deformation information. '...
'The same fields can be used for both forward or backward deformations '...
'(or even, in principle, half way or exaggerated deformations).']};
%------------------------------------------------------------------------
data = files('Images','images','nifti',[1 Inf]);
data.help = {...
['Select images to be warped. Note that there should be the same number '...
'of images as there are flow fields, such that each flow field '...
'warps one image.']};
%------------------------------------------------------------------------
data = repeat('Images','images',{data});
data.num = [1 Inf];
data.help = {...
['The flow field deformations can be applied to multiple images. '...
'At this point, you are choosing how many images each flow field '...
'should be applied to.']};
%------------------------------------------------------------------------
interp.type = 'menu';
interp.name = 'Interpolation';
interp.tag = 'interp';
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.val = {1};
interp.help = {...
['The method by which the images are sampled when being written in a ',...
'different space.'],...
[' Nearest Neighbour: ',...
' - Fastest, but not normally recommended.'],...
[' Bilinear Interpolation: ',...
' - OK for PET, or realigned fMRI.'],...
[' B-spline Interpolation: ',...
' - Better quality (but slower) interpolation/* \cite{thevenaz00a}*/, especially ',...
' with higher degree splines. Do not use B-splines when ',...
' there is any region of NaN or Inf in the images. '],...
};
%------------------------------------------------------------------------
jactransf = mnu('Modulation','jactransf',...
{'No modulation','Modulation','Sqrt Modulation'},...
{0,1,0.5});
jactransf.val = {0};
jactransf.help = {...
['This allows the spatially normalised images to be rescaled by the '...
'Jacobian determinants of the deformations. '...
'Note that the rescaling is only approximate for deformations generated '...
'using smaller numbers of time steps. '...
'The square-root modulation is for special applications, so can be '...
'ignored in most cases.']};
%------------------------------------------------------------------------
nrm = branch('Create Warped','crt_warped',{ffields,data,jactransf,K,interp});
nrm.prog = @spm_dartel_norm;
nrm.check = @check_norm;
nrm.vfiles = @vfiles_norm;
nrm.help = {...
['This allows spatially normalised images to be generated. '...
'Note that voxel sizes and bounding boxes can not be adjusted, '...
'and that there may be strange effects due to the boundary conditions used '...
'by the warping. '...
'Also note that the warped images are not in Talairach or MNI space. '...
'The coordinate system is that of the average shape and size of the '...
'subjects to which DARTEL was applied. '...
'In order to have MNI-space normalised images, then the Deformations '...
'Utility can be used to compose the individual DARTEL warps, '...
'with a deformation field that matches (e.g.) the Template grey matter '...
'generated by DARTEL, with one of the grey matter volumes '...
'released with SPM.']};
%------------------------------------------------------------------------
% GENERATING JACOBIAN DETERMINANT FIELDS
%------------------------------------------------------------------------
jac = branch('Jacobian determinants','jacdet',{ffields,K});
jac.help = {'Create Jacobian determinant fields from flowfields.'};
jac.prog = @spm_dartel_jacobian;
jac.vfiles = @vfiles_jacdet;
% WARPING TEMPLATES TO MATCH IMAGES
%------------------------------------------------------------------------
data = files('Images','images','nifti',[1 Inf]);
data.help = {...
['Select the image(s) to be inverse normalised. '...
'These should be in alignment with the template image generated by the '...
'warping procedure.']};
%------------------------------------------------------------------------
inrm = branch('Create Inverse Warped','crt_iwarped',{ffields,data,K,interp});
inrm.prog = @spm_dartel_invnorm;
inrm.vfiles = @vfiles_invnorm;
inrm.help = {...
['Create inverse normalised versions of some image(s). '...
'The image that is inverse-normalised should be in alignment with the '...
'template (generated during the warping procedure). '...
'Note that the results have the same dimensions as the ``flow fields'''', '...
'but are mapped to the original images via the affine transformations '...
'in their headers.']};
%------------------------------------------------------------------------
% KERNEL UTILITIES FOR PATTERN RECOGNITION
%------------------------------------------------------------------------
templ = files('Template','template','nifti',[0 1]);
templ.ufilter = '^Template.*';
templ.help = {[...
'Residual differences are computed between the '...
'warped images and template, and these are scaled by '...
'the square root of the Jacobian determinants '...
'(such that the sum of squares is the same as would be '...
'computed from the difference between the warped template '...
'and individual images).']};
%------------------------------------------------------------------------
data = files('Images','images','nifti',[1 Inf]);
data.ufilter = '^r.*c';
data.help = {'Select tissue class images (one per subject).'};
%------------------------------------------------------------------------
data = repeat('Images','images',{data});
data.num = [1 Inf];
data.help = {...
['Multiple sets of images are used here. '...
'For example, the first set may be a bunch of grey matter images, '...
'and the second set may be the white matter images of the '...
'same subjects. The number of sets of images must be the same '...
'as was used to generate the template.']};
fwhm = mnu('Smoothing','fwhm',{'None',' 2mm',' 4mm',' 6mm',' 8mm','10mm','12mm','14mm','16mm'},{0,2,4,6,8,10,12,14,16});
fwhm.val = {4};
fwhm.help = {[...
'The residuals can be smoothed with a Gaussian to reduce dimensionality. '...
'More smoothing is recommended if there are fewer training images.']};
flowfields = files('Flow fields','flowfields','nifti',[1 Inf]);
flowfields.ufilter = '^u_.*';
flowfields.help = {...
'Select the flow fields for each subject.'};
res = branch('Generate Residuals','resids',{data,flowfields,templ,K,fwhm});
res.help = {[...
'Generate residual images in a form suitable for computing a '...
'Fisher kernel. In principle, a Gaussian Process model can '...
'be used to determine the optimal (positive) linear combination '...
'of kernel matrices. The idea would be to combine the kernel '...
'from the residuals, with a kernel derived from the flow-fields. '...
'Such a combined kernel should then encode more relevant information '...
'than the individual kernels alone.']};
res.prog = @spm_dartel_resids;
res.check = @check_resids;
res.vfiles = @vfiles_resids;
%------------------------------------------------------------------------
lam = entry('Reg param','rparam','e',[1 1]);
lam.val = {0.1};
logodds = branch('Generate LogOdds','LogOdds',{data,flowfields,K,lam});
logodds.help = {'See Kilian Pohl''s recent work.'};
logodds.prog = @spm_dartel_logodds;
%------------------------------------------------------------------------
data = files('Data','images','nifti',[1 Inf]);
data.help = {'Select images to generate dot-products from.'};
msk = files('Weighting image','weight','image',[0 1]);
msk.val = {''};
msk.help = {[...
'The kernel can be generated so that some voxels contribute to '...
'the similarity measures more than others. This is achieved by supplying '...
'a weighting image, which each of the component images are multiplied '...
'before the dot-products are computed. This image needs to have '...
'the same dimensions as the component images, but orientation information '...
'(encoded by matrices in the headers) is ignored. '...
'If left empty, then all voxels are weighted equally.']};
kname = entry('Dot-product Filename','dotprod','s',[1,Inf]);
kname.help = {['Enter a filename for results (it will be prefixed by '...
'``dp_'''' and saved in the current directory).']};
reskern = branch('Kernel from Resids','reskern',{data,msk,kname});
reskern.help = {['Generate a kernel matrix from residuals. '...
'In principle, this same function could be used for generating '...
'kernels from any image data (e.g. ``modulated'''' grey matter). '...
'If there is prior knowledge about some region providing more '...
'predictive information (e.g. the hippocampi for AD), '...
'then it is possible to weight the generation of the kernel '...
'accordingly. '...
'The matrix of dot-products is saved in a variable ``Phi'''', '...
'which can be loaded from the dp_*.mat file. '...
'The ``kernel trick'''' can be used to convert these dot-products '...
'into distance measures for e.g. radial basis-function approaches.']};
reskern.prog = @spm_dartel_dotprods;
%------------------------------------------------------------------------
flowfields = files('Flow fields','flowfields','nifti',[1 Inf]);
flowfields.ufilter = '^u_.*';
flowfields.help = {'Select the flow fields for each subject.'};
kname = entry('Dot-product Filename','dotprod','s',[1,Inf]);
kname.help = {['Enter a filename for results (it will be prefixed by '...
'``dp_'''' and saved in the current directory.']};
rform = mnu('Regularisation Form','rform',...
{'Linear Elastic Energy','Membrane Energy','Bending Energy'},{0,1,2});
rform.val = {0};
rform.help = {[...
'The registration is penalised by some ``energy'''' term. Here, the '...
'form of this energy term is specified. '...
'Three different forms of regularisation can currently be used.']};
rparam = entry('Reg params','rparam','e',[1 3]);
rparam.val = {[0.125 0.0625 1e-6]};
rparam.help = {...
['For linear elasticity, the parameters are `mu'', `lambda'' and `id''. ',...
'For membrane and bending energy, '...
'the parameters are `lambda'', unused and `id''. ',...
'The term `id'' is for penalising absolute displacements, '...
'and should therefore be small.']};
flokern = branch('Kernel from Flows' ,'flokern',{flowfields,rform,rparam,kname});
flokern.help = {['Generate a kernel from flow fields. '...
'The dot-products are saved in a variable ``Phi'''' '...
'in the resulting dp_*.mat file.']};
flokern.prog = @spm_dartel_kernel;
%------------------------------------------------------------------------
kernfun = repeat('Kernel Utilities','kernfun',{res,reskern,flokern});
kernfun.help = {[...
'DARTEL can be used for generating Fisher kernels for '...
'various kernel pattern-recognition procedures. '...
'The idea is to use both the flow fields and residuals '...
'to generate two separate Fisher kernels (see the work of '...
'Jaakkola and Haussler for more information). '...
'Residual images need first to be generated in order to compute '...
'the latter kernel, prior to the dot-products being computed.'],[...
'The idea of applying pattern-recognition procedures is to obtain '...
'a multi-variate characterisation of the anatomical differences among '...
'groups of subjects. These characterisations can then be used to '...
'separate (eg) healthy individuals from particular patient populations. '...
'There is still a great deal of methodological work to be done, '...
'so the types of kernel that can be generated here are unlikely to '...
'be the definitive ways of proceeding. They are only just a few ideas '...
'that may be worth trying out. '...
'The idea is simply to attempt a vaguely principled way to '...
'combine generative models with discriminative models '...
'(see the ``Pattern Recognition and Machine Learning'''' book by '...
'Chris Bishop for more ideas). Better ways (higher predictive accuracy) '...
'will eventually emerge.'],[...
'Various pattern recognition algorithms are available freely over the '...
'Internet. Possible approaches include Support-Vector Machines, '...
'Relevance-Vector machines and Gaussian Process Models. '...
'Gaussian Process Models probably give the most accurate probabilistic '...
'predictions, and allow kernels generated from different pieces of '...
'data to be most easily combined.']};
% THE ENTRY POINT FOR DARTEL STUFF
%------------------------------------------------------------------------
job = repeat('DARTEL Tools','dartel',{initial,warp,warp1,nrm,jac,inrm,kernfun});
job.help = {...
['This toolbox is based around the ``A Fast Diffeomorphic Registration '...
'Algorithm'''' paper/* \cite{ashburner07} */. '...
'The idea is to register images by computing a ``flow field'''', '...
'which can then be ``exponentiated'''' to generate both forward and '...
'backward deformations. '...
'Currently, the software only works with images that have isotropic '...
'voxels, identical dimensions and which are in approximate alignment '...
'with each other. '...
'One of the reasons for this is that the approach assumes circulant '...
'boundary conditions, which makes modelling global rotations impossible. '...
'Another reason why the images should be approximately aligned is because '...
'there are interactions among the transformations that are minimised by '...
'beginning with images that are already almost in register. '...
'This problem could be alleviated by a time varying flow field, '...
'but this is currently computationally impractical.'],...
['Because of these limitations, images should first be imported. '...
'This involves taking the ``*_seg_sn.mat'''' files produced by the segmentation '...
'code of SPM5, and writing out rigidly transformed versions of '...
'the tissue class images, '...
'such that they are in as close alignment as possible with the tissue '...
'probability maps. '...
'Rigidly transformed original images can also be generated, '...
'with the option to have skull-stripped versions.'],...
['The next step is the registration itself. This can involve matching '...
'single images together, or it can involve the simultaneous registration '...
'of e.g. GM with GM, WM with WM and 1-(GM+WM) with 1-(GM+WM) '...
'(when needed, the 1-(GM+WM) class is generated implicitly, so there is '...
'no need to include this class yourself). '...
'This procedure begins by creating a mean of all the images, '...
'which is used as an initial template. '...
'Deformations from this template to each of the individual images '...
'are computed, and the template is then re-generated by applying '...
'the inverses of the deformations to the images and averaging. '...
'This procedure is repeated a number of times.'],...
['Finally, warped versions of the images (or other images that are '...
'in alignment with them) can be generated. '],[],[...
'This toolbox is not yet seamlessly integrated into the SPM package. '...
'Eventually, the plan is to use many of the ideas here as the default '...
'strategy for spatial normalisation. The toolbox may change with future '...
'updates. There will also be a number of '...
'other (as yet unspecified) extensions, which may include '...
'a variable velocity version (related to LDDMM). '...
'Note that the Fast Diffeomorphism paper only describes a sum of squares '...
'objective function. '...
'The multinomial objective function is an extension, '...
'based on a more appropriate model for aligning binary data to a template.']};
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vf = vfiles_initial_import(job)
opt = [job.GM, job.WM, job.CSF];
odir = job.odir{1};
matnames = job.matnames;
vf = {};
for i=1:numel(matnames),
vf1 = {};
[pth,nam,ext] = fileparts(matnames{i});
nam = nam(1:(numel(nam)-7));
if job.image,
fname = fullfile(odir,['r',nam, '.nii' ',1']);
vf1 = {fname};
end
for k1=1:numel(opt),
if opt(k1),
fname = fullfile(odir,['r','c', num2str(k1), nam, '.nii' ',1']);
vf1 = {vf1{:},fname};
end
end
vf = {vf{:},vf1{:}};
end
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_runjob(job)
n1 = numel(job.images);
n2 = numel(job.images{1});
chk = '';
for i=1:n1,
if numel(job.images{i}) ~= n2,
chk = 'Incompatible number of images';
break;
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function vf = vfiles_runjob(job)
vf = {};
n1 = numel(job.images);
n2 = numel(job.images{1});
[tdir,nam,ext] = fileparts(job.images{1}{1});
tname = deblank(job.settings.template);
if ~isempty(tname),
for it=0:numel(job.settings.param),
fname = fullfile(tdir,[tname '_' num2str(it) '.nii' ',1']);
vf = {vf{:},fname};
end
end
for j=1:n2,
[pth,nam,ext,num] = spm_fileparts(job.images{1}{j});
if ~isempty(tname),
fname = fullfile(pth,['u_' nam '_' tname '.nii' ',1']);
else
fname = fullfile(pth,['u_' nam '.nii' ',1']);
end
vf = {vf{:},fname};
end;
%_______________________________________________________________________
%_______________________________________________________________________
function vf = vfiles_runjob1(job)
vf = {};
n1 = numel(job.images);
n2 = numel(job.images{1});
for j=1:n2,
[pth,nam,ext,num] = spm_fileparts(job.images{1}{j});
fname = fullfile(pth,['u_' nam '.nii' ',1']);
vf = {vf{:},fname};
end;
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_norm(job)
chk = '';
PU = job.flowfields;
PI = job.images;
n1 = numel(PU);
for i=1:numel(PI),
if numel(PI{i}) ~= n1,
chk = 'Incompatible number of images';
break;
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function vf = vfiles_norm(job)
vf = {};
PU = job.flowfields;
PI = job.images;
jactransf = job.jactransf;
for i=1:numel(PU),
for m=1:numel(PI),
[pth,nam,ext,num] = spm_fileparts(PI{m}{i});
if jactransf,
fname = fullfile(pth,['mw' nam ext ',1']);
else
fname = fullfile(pth,['w' nam ext ',1']);
end;
vf = {vf{:},fname};
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function vf = vfiles_invnorm(job)
vf = {};
PU = job.flowfields;
PI = job.images;
for i=1:numel(PU),
[pth1,nam1,ext1,num1] = spm_fileparts(PU{i});
for m=1:numel(PI),
[pth2,nam2,ext2,num2] = spm_fileparts(PI{m});
fname = fullfile(pth1,['w' nam2 '_' nam1 ext2 ',1']);
vf = {vf{:},fname};
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function vf = vfiles_jacdet(job)
vf = {};
PU = job.flowfields;
for i=1:numel(PU),
[pth,nam,ext] = fileparts(PU{i});
fname = fullfile(pth,['jac_' nam(3:end) ext ',1']);
vf = {vf{:},fname};
end;
%_______________________________________________________________________
%_______________________________________________________________________
function chk = check_resids(job)
chk = '';
PU = job.flowfields;
PI = job.images;
n1 = numel(PU);
for i=1:numel(PI),
if numel(PI{i}) ~= n1,
chk = 'Incompatible number of images';
break;
end
end
%_______________________________________________________________________
%_______________________________________________________________________
function vf = vfiles_resids(job)
vf = {};
PI = job.images{1};
for i=1:numel(PI),
[pth,nam,ext] = fileparts(PI{i});
fname = fullfile(pwd,['resid_' nam '.nii',',1']);
vf = {vf{:},fname};
end
%_______________________________________________________________________
|
github
|
spm/spm5-master
|
spm_dartel_logodds.m
|
.m
|
spm5-master/toolbox/DARTEL/spm_dartel_logodds.m
| 4,130 |
utf_8
|
0ef776c3cdd4669c54e7331b35db163d
|
function spm_dartel_logodds(job)
% Generate LogOdds files
% FORMAT spm_dartel_logodds(job)
% job.flowfields
% job.images
% job.K
% job.rparam
%
% The aim is to obtain better pattern recognition through using
% LogOdds. See Killian Pohl's work for more info.
%_______________________________________________________________________
% Copyright (C) 2007 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_dartel_logodds.m 964 2007-10-19 16:35:34Z john $
PI = job.images;
PU = job.flowfields;
K = job.K;
lam= job.rparam;
n = numel(PI);
spm_progress_bar('Init',numel(PI{1}),'Creating LogOdds');
for i=1:numel(PI{1}),
% Derive deformations and Jacobian determinants from the
% flow fields.
NU = nifti(PU{i});
[pth,nam,ext,num] = spm_fileparts(NU.dat.fname);
fprintf('%s: def ',nam); drawnow;
u = single(squeeze(NU.dat(:,:,:,1,:)));
[y,dt] = dartel3('Exp',u,[K -1 1]);
y1 = double(y(:,:,:,1));
y2 = double(y(:,:,:,2));
y3 = double(y(:,:,:,3));
clear y
dt = max(dt,single(0));
f = zeros([NU.dat.dim(1:3),n+1],'single');
[pth,nam,ext,num] = spm_fileparts(PI{1}{i});
NI = nifti(fullfile(pth,[nam ext]));
NO = NI;
NO.dat.fname = fullfile('.',['logodds_' nam '.nii']);
NO.dat.scl_slope = 1.0;
NO.dat.scl_inter = 0.0;
NO.dat.dtype = 'float32-le';
NO.dat.dim = [NU.dat.dim(1:3) 1 n+1];
NO.mat = NU.mat;
NO.mat0 = NU.mat;
NO.mat_intent = 'Aligned';
NO.mat0_intent = 'Aligned';
NO.descrip = 'LogOdds';
create(NO);
vx = sqrt(sum(NU.mat(1:3,1:3).^2));
% Compute the warped tissue probabilities
f(:,:,:,end) = 1; % Background
for j=1:n,
fprintf('%d ', j); drawnow;
[pth,nam,ext,num] = spm_fileparts(PI{j}{i});
NI = nifti(fullfile(pth,[nam ext]));
if sum(sum((NI.mat - NU.mat ).^2)) < 0.0001 && ...
sum(sum((NI.mat0 - NU.mat0).^2)) < 0.0001,
ty1 = y1;
ty2 = y2;
ty3 = y3;
else
mat = NI.mat;
if isfield(NI,'extras') && isfield(NI.extras,'mat'),
mat1 = NI.extras.mat;
if size(mat1,3) >= j && sum(sum(mat1(:,:,j).^2)) ~=0,
mat = mat1;
end;
end;
M = mat\NU.mat0;
ty1 = M(1,1)*y1 + M(1,2)*y2 + M(1,3)*y3 + M(1,4);
ty2 = M(2,1)*y1 + M(2,2)*y2 + M(2,3)*y3 + M(2,4);
ty3 = M(3,1)*y1 + M(3,2)*y2 + M(3,3)*y3 + M(3,4);
end;
spl_param = [3 3 3 1 1 1];
cf = spm_bsplinc(NI.dat(:,:,:,1,1),spl_param);
f(:,:,:,j) = spm_bsplins(cf,ty1,ty2,ty3,spl_param);
f(:,:,:,end) = f(:,:,:,end) - f(:,:,:,j);
clear cf ty1 ty2 ty3
end;
clear y1 y2 y3
a = logodds(f,dt,lam,12,vx);
a = softmax(a);
fprintf('\n');
clear f dt
for j=1:n+1,
NO.dat(:,:,:,1,j) = log(a(:,:,:,j));
end
clear a
spm_progress_bar('Set',i);
end
spm_progress_bar('Clear');
function a = logodds(t,s,lam,its,vx)
if nargin<5, vx = [1 1 1]; end;
if nargin<4, its = 12; end;
if nargin<3, lam = 1; end;
a = zeros(size(t),'single');
d = size(t);
W = zeros([d(1:3) round((d(4)*(d(4)+1))/2)],'single');
for i=1:its,
sig = softmax(a);
gr = sig - t;
for k=1:d(4), gr(:,:,:,k) = gr(:,:,:,k).*s; end
gr = gr + optimN('vel2mom',a,[2 vx lam 0 0]);
jj = d(4)+1;
for j1=1:d(4),
W(:,:,:,j1) = sig(:,:,:,j1).*(1-sig(:,:,:,j1)).*s;
for j2=1:j1-1,
W(:,:,:,jj) = -sig(:,:,:,j1).*sig(:,:,:,j2).*s;
jj = jj+1;
end
end
a = a - optimN(W,gr,[2 vx lam 0 lam*1e-3 1 1]);
%a = a - mean(a(:)); % unstable
a = a - sum(sum(sum(sum(a))))/numel(a);
fprintf('.');
drawnow
end;
return;
function sig = softmax(a)
sig = zeros(size(a),'single');
for j=1:size(a,3),
aj = double(squeeze(a(:,:,j,:)));
aj = min(max(aj-mean(aj(:)),-700),700);
sj = exp(aj);
s = sum(sj,3);
for i=1:size(a,4),
sig(:,:,j,i) = single(sj(:,:,i)./s);
end
end;
|
github
|
spm/spm5-master
|
spm_dartel_smooth.m
|
.m
|
spm5-master/toolbox/DARTEL/spm_dartel_smooth.m
| 1,765 |
utf_8
|
3d5d4ff610b382c8068db96ecc345478
|
function [sig,a] = spm_dartel_smooth(t,lam,its,vx,a)
% A function for smoothing tissue probability maps
% FORMAT [sig,a_new] = spm_dartel_smooth(t,lam,its,vx,a_old)
%________________________________________________________
% (c) Wellcome Centre for NeuroImaging (2007)
% John Ashburner
% $Id: spm_dartel_smooth.m 3101 2009-05-08 11:17:29Z john $
if nargin<5, a = zeros(size(t),'single'); end
if nargin<4, vx = [1 1 1]; end;
if nargin<3, its = 16; end;
if nargin<2, lam = 1; end;
d = size(t);
W = zeros([d(1:3) round((d(4)*(d(4)+1))/2)],'single');
s = max(sum(t,4),eps('single'));
for k=1:d(4),
t(:,:,:,k) = max(min(t(:,:,:,k)./s,1-eps('single')),eps('single'));
end
for i=1:its,
%trnc= -log(eps('single'));
%a = max(min(a,trnc),-trnc);
sig = softmax(a);
gr = sig - t;
for k=1:d(4),
gr(:,:,:,k) = gr(:,:,:,k).*s;
end
gr = gr + optimNn('vel2mom',a,[2 vx lam 0 1e-4]);
jj = d(4)+1;
reg = 2*sqrt(eps('single'))*d(4)^2;
for j1=1:d(4),
W(:,:,:,j1) = (sig(:,:,:,j1).*(1-sig(:,:,:,j1)) + reg).*s;
for j2=(j1+1):d(4),
W(:,:,:,jj) = -sig(:,:,:,j1).*sig(:,:,:,j2).*s;
jj = jj+1;
end
end
a = a - optimNn(W,gr,[2 vx lam 0 1e-4 1 1]);
%a = a - mean(a(:)); % unstable
%a = a - sum(sum(sum(sum(a))))/numel(a);
fprintf(' %g,', sum(gr(:).^2)/numel(gr));
drawnow
end;
fprintf('\n');
sig = softmax(a);
return;
function sig = softmax(a)
sig = zeros(size(a),'single');
for j=1:size(a,3),
aj = double(squeeze(a(:,:,j,:)));
trunc = log(realmax*(1-eps));
aj = min(max(aj-mean(aj(:)),-trunc),trunc);
sj = exp(aj);
s = sum(sj,3);
for i=1:size(a,4),
sig(:,:,j,i) = single(sj(:,:,i)./s);
end
end;
|
github
|
spm/spm5-master
|
spm_dartel_import.m
|
.m
|
spm5-master/toolbox/DARTEL/spm_dartel_import.m
| 10,819 |
utf_8
|
2c3aa19bc0c8d505f1fd8a9a17a00005
|
function spm_dartel_import(job)
% Import subjects' data for use with DARTEL
% FORMAT spm_dartel_import(job)
% job.matnames - Names of *_seg_sn.mat files to use
% job.odir - Output directory
% job.bb - Bounding box
% job.vox - Voxel sizes
% job.GM/WM/CSF - Options fo different tissue classes
% job.image - Options for resliced original image
%
% Rigidly aligned images are generated using info from the seg_sn.mat
% files. These can be resliced GM, WM or CSF, but also various resliced
% forms of the original image (skull-stripped, bias corrected etc).
%____________________________________________________________________________
% Copyright (C) 2007 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_dartel_import.m 1085 2008-01-11 15:09:48Z john $
matnames = job.matnames;
for i=1:numel(matnames),
p(i) = load(matnames{i});
end;
if numel(p)>0,
tmp = strvcat(p(1).VG.fname);
p(1).VG = spm_vol(tmp);
b0 = spm_load_priors(p(1).VG);
end;
odir = job.odir{1};
bb = job.bb;
vox = job.vox;
iopt = job.image;
opt = [job.GM, job.WM, job.CSF];
for i=1:numel(p),
preproc_apply(p(i),odir,b0,bb,vox,iopt,opt,matnames{i});
end;
return;
%=======================================================================
%=======================================================================
function preproc_apply(p,odir,b0,bb,vx,iopt,opt,matname)
[pth0,nam,ext,num] = spm_fileparts(matname);
[pth ,nam,ext,num] = spm_fileparts(p.VF(1).fname);
P = path_search([nam,ext],{pth,odir,pwd,pth0});
if isempty(P),
fprintf('Could not find "%s"\n', [nam,ext]);
return;
end;
p.VF.fname = P;
T = p.flags.Twarp;
bsol = p.flags.Tbias;
d2 = [size(T) 1];
d = p.VF.dim(1:3);
[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);
x3 = 1:d(3);
d3 = [size(bsol) 1];
B1 = spm_dctmtx(d(1),d2(1));
B2 = spm_dctmtx(d(2),d2(2));
B3 = spm_dctmtx(d(3),d2(3));
bB3 = spm_dctmtx(d(3),d3(3),x3);
bB2 = spm_dctmtx(d(2),d3(2),x2(1,:)');
bB1 = spm_dctmtx(d(1),d3(1),x1(:,1));
mg = p.flags.mg;
mn = p.flags.mn;
vr = p.flags.vr;
K = length(p.flags.mg);
Kb = length(p.flags.ngaus);
lkp = []; for k=1:Kb, lkp = [lkp ones(1,p.flags.ngaus(k))*k]; end;
spm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed');
M = p.VG(1).mat\p.flags.Affine*p.VF.mat;
if iopt, idat = zeros(d(1:3),'single'); end;
dat = {zeros(d(1:3),'uint8'),zeros(d(1:3),'uint8'),zeros(d(1:3),'uint8')};
for z=1:length(x3),
% Bias corrected image
f = spm_sample_vol(p.VF,x1,x2,o*x3(z),0);
msk = (f==0) | ~isfinite(f);
cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f;
if iopt,
if bitand(iopt,2),
idat(:,:,z) = cr;
else
idat(:,:,z) = f;
end;
end;
[t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M);
q = zeros([d(1:2) Kb]);
bg = ones(d(1:2));
bt = zeros([d(1:2) Kb]);
for k1=1:Kb,
bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb);
end;
b = zeros([d(1:2) K]);
for k=1:K,
b(:,:,k) = bt(:,:,lkp(k))*mg(k);
end;
s = sum(b,3);
for k=1:K,
p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps);
q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s;
end;
sq = sum(q,3)+eps;
for k1=1:3,
tmp = q(:,:,k1);
tmp = tmp./sq;
tmp(msk) = 0;
dat{k1}(:,:,z) = uint8(round(255 * tmp));
end;
spm_progress_bar('set',z);
end;
spm_progress_bar('clear');
%[dat{1},dat{2},dat{3}] = clean_gwc(dat{1},dat{2},dat{3}, 2);
if iopt,
if bitand(iopt,2),
nwm = 0;
swm = 0;
for z=1:numel(x3),
nwm = nwm + sum(sum(double(dat{2}(:,:,z))));
swm = swm + sum(sum(double(dat{2}(:,:,z)).*idat(:,:,z)));
end;
idat = idat*(double(nwm)/double(swm));
end;
if bitand(iopt,4),
for z=1:numel(x3),
%msk = double(dat{1}(:,:,z)) ...
% + double(dat{2}(:,:,z)) ...
% + 0.5*double(dat{3}(:,:,z));
%msk = msk<128;
%tmp = idat(:,:,z);
%tmp(msk) = 0;
%idat(:,:,z) = tmp;
wt = (double(dat{1}(:,:,z))+double(dat{2}(:,:,z)))/255;
idat(:,:,z) = idat(:,:,z).*wt;
end;
end;
for z=1:numel(x3),
tmp = idat(:,:,z);
tmp(~isfinite(double(tmp))) = 0;
idat(:,:,z) = tmp;
end;
end;
% Sort out bounding box etc
[bb1,vx1] = bbvox_from_V(p.VG(1));
bb(~isfinite(bb)) = bb1(~isfinite(bb));
if ~isfinite(vx), vx = abs(prod(vx1))^(1/3); end;
bb(1,:) = vx*ceil(bb(1,:)/vx);
bb(2,:) = vx*floor(bb(2,:)/vx);
% Figure out the mapping from the volumes to create to the original
mm = [
bb(1,1) bb(1,2) bb(1,3)
bb(2,1) bb(1,2) bb(1,3)
bb(1,1) bb(2,2) bb(1,3)
bb(2,1) bb(2,2) bb(1,3)
bb(1,1) bb(1,2) bb(2,3)
bb(2,1) bb(1,2) bb(2,3)
bb(1,1) bb(2,2) bb(2,3)
bb(2,1) bb(2,2) bb(2,3)]';
vx2 = inv(p.VG(1).mat)*[mm ; ones(1,8)];
odim = abs(round((bb(2,:)-bb(1,:))/vx))+1;
%dimstr = sprintf('%dx%dx%d',odim);
dimstr = '';
vx1 = [
1 1 1
odim(1) 1 1
1 odim(2) 1
odim(1) odim(2) 1
1 1 odim(3)
odim(1) 1 odim(3)
1 odim(2) odim(3)
odim(1) odim(2) odim(3)]';
M = p.Affine*vx2/[vx1 ; ones(1,8)];
mat0 = p.VF.mat*M;
mat = [mm ; ones(1,8)]/[vx1 ; ones(1,8)];
fwhm = max(vx./sqrt(sum(p.VF.mat(1:3,1:3).^2))-1,0.01);
for k1=1:numel(opt),
if opt(k1),
dat{k1} = decimate(dat{k1},fwhm);
VT = struct('fname',fullfile(odir,['r',dimstr,'c', num2str(k1), nam, '.nii']),...
'dim', odim,...
'dt', [spm_type('uint8') spm_platform('bigend')],...
'pinfo',[1/255 0]',...
'mat',mat);
VT = spm_create_vol(VT);
Ni = nifti(VT.fname);
Ni.mat0 = mat0;
Ni.mat_intent = 'Aligned';
Ni.mat0_intent = 'Aligned';
create(Ni);
for i=1:odim(3),
tmp = spm_slice_vol(dat{k1},M*spm_matrix([0 0 i]),odim(1:2),1)/255;
VT = spm_write_plane(VT,tmp,i);
end;
end;
end;
if iopt,
%idat = decimate(idat,fwhm);
VT = struct('fname',fullfile(odir,['r',dimstr,nam, '.nii']),...
'dim', odim,...
'dt', [spm_type('float32') spm_platform('bigend')],...
'pinfo',[1 0]',...
'mat',mat);
VT.descrip = 'Resliced';
if bitand(iopt,2), VT.descrip = [VT.descrip ', bias corrected']; end;
if bitand(iopt,4), VT.descrip = [VT.descrip ', skull stripped']; end;
VT = spm_create_vol(VT);
Ni = nifti(VT.fname);
Ni.mat0 = mat0;
Ni.mat_intent = 'Aligned';
Ni.mat0_intent = 'Aligned';
create(Ni);
for i=1:odim(3),
tmp = spm_slice_vol(idat,M*spm_matrix([0 0 i]),odim(1:2),1);
VT = spm_write_plane(VT,tmp,i);
end;
end;
return;
%=======================================================================
%=======================================================================
function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M)
x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1));
y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2));
z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3));
x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);
y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);
z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);
return;
%=======================================================================
%=======================================================================
function t = transf(B1,B2,B3,T)
d2 = [size(T) 1];
t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));
t = B1*t1*B2';
return;
%=======================================================================
%=======================================================================
function dat = decimate(dat,fwhm)
% Convolve the volume in memory (fwhm in voxels).
lim = ceil(2*fwhm);
s = fwhm/sqrt(8*log(2));
x = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x);
y = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y);
z = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
spm_conv_vol(dat,dat,x,y,z,-[i j k]);
return;
%=======================================================================
%=======================================================================
function [g,w,c] = clean_gwc(g,w,c, level)
if nargin<4, level = 1; end;
b = w;
b(1) = w(1);
% Build a 3x3x3 seperable smoothing kernel
%-----------------------------------------------------------------------
kx=[0.75 1 0.75];
ky=[0.75 1 0.75];
kz=[0.75 1 0.75];
sm=sum(kron(kron(kz,ky),kx))^(1/3);
kx=kx/sm; ky=ky/sm; kz=kz/sm;
th1 = 0.15;
if level==2, th1 = 0.2; end;
% Erosions and conditional dilations
%-----------------------------------------------------------------------
niter = 32;
spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');
for j=1:niter,
if j>2, th=th1; else th=0.6; end; % Dilate after two its of erosion.
for i=1:size(b,3),
gp = double(g(:,:,i));
wp = double(w(:,:,i));
bp = double(b(:,:,i))/255;
bp = (bp>th).*(wp+gp);
b(:,:,i) = uint8(round(bp));
end;
spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);
spm_progress_bar('Set',j);
end;
th = 0.05;
for i=1:size(b,3),
gp = double(g(:,:,i))/255;
wp = double(w(:,:,i))/255;
cp = double(c(:,:,i))/255;
bp = double(b(:,:,i))/255;
bp = ((bp>th).*(wp+gp))>th;
g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));
w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));
c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));
end;
spm_progress_bar('Clear');
return;
%=======================================================================
%=======================================================================
function pthnam = path_search(nam,pth)
pthnam = '';
for i=1:numel(pth),
if exist(fullfile(pth{i},nam),'file'),
pthnam = fullfile(pth{i},nam);
return;
end;
end;
%=======================================================================
%=======================================================================
function [bb,vx] = bbvox_from_V(V)
vx = sqrt(sum(V(1).mat(1:3,1:3).^2));
if det(V(1).mat(1:3,1:3))<0, vx(1) = -vx(1); end;
o = V(1).mat\[0 0 0 1]';
o = o(1:3)';
bb = [-vx.*(o-1) ; vx.*(V(1).dim(1:3)-o)];
return;
|
github
|
spm/spm5-master
|
spm_hdw.m
|
.m
|
spm5-master/toolbox/HDW/spm_hdw.m
| 10,918 |
utf_8
|
264f8635ea0813aaa15de0175151b3cb
|
function spm_hdw(job)
% Warp a pair of same subject images together
%
% Very little support can be provided for the warping routine, as it
% involves optimising a very nonlinear objective function.
% Also, don't ask what the best value for the regularisation is.
%_______________________________________________________________________
% Copyright (C) 2006 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id$
for i=1:numel(job.data),
run_warping(job.data(i).mov{1},job.data(i).ref{1},job.warp_opts,job.bias_opts);
end;
%_______________________________________________________________________
%_______________________________________________________________________
function run_warping(PF,PG,warp_opts,bias_opts)
VG = spm_vol(PG);
VF = spm_vol(PF);
reg = warp_opts.reg;
nit = warp_opts.nits;
% Load the image pair as 8 bit.
%-----------------------------------------------------------------------
bo = bias_opts;
[VG.uint8,sf] = loaduint8(VG); % Template
VF.uint8 = bias_correction(VF,VG,bo.nits,bo.fwhm,bo.reg,bo.lmreg,sf);
% Try loading pre-existing deformation fields. Otherwise, create
% deformation fields from uniform affine transformations.
%-----------------------------------------------------------------------
[pth,nme,ext,num] = spm_fileparts(VF.fname);
ofname = fullfile(pth,['y_' nme '.nii']);
Def = cell(3,1);
if exist(ofname)==2,
P = [repmat(ofname,3,1), [',1,1';',1,2';',1,3']];
VT = spm_vol(P);
if any(abs(VT(1).mat\VG.mat - eye(4))>0.00001),
error('Incompatible affine transformation matrices.');
end;
Def{1} = spm_load_float(VT(1));
Def{2} = spm_load_float(VT(2));
Def{3} = spm_load_float(VT(3));
spm_affdef(Def{:},inv(VF.mat));
else,
fprintf('Generating uniform affine transformation field\n');
Def{1} = single(1:VG.dim(1))';
Def{1} = Def{1}(:,ones(VG.dim(2),1),ones(VG.dim(3),1));
Def{2} = single(1:VG.dim(2));
Def{2} = Def{2}(ones(VG.dim(1),1),:,ones(VG.dim(3),1));
Def{3} = reshape(single(1:VG.dim(3)),1,1,VG.dim(3));
Def{3} = Def{3}(ones(VG.dim(1),1),ones(VG.dim(2),1),:);
spm_affdef(Def{:},VF.mat\VG.mat);
end;
% Voxel sizes
%-----------------------------------------------------------------------
vxg = sqrt(sum(VG.mat(1:3,1:3).^2))';if det(VG.mat(1:3,1:3))<0, vxg(1) = -vxg(1); end;
vxf = sqrt(sum(VF.mat(1:3,1:3).^2))';if det(VF.mat(1:3,1:3))<0, vxf(1) = -vxf(1); end;
% Do warping
%-----------------------------------------------------------------------
fprintf('Warping (iterations=%d regularisation=%g)\n', nit, reg);
spm_warp(VG.uint8,VF.uint8,Def{:},[vxg vxf],[nit,reg,1,0]);
% Convert mapping from voxels to mm
%-----------------------------------------------------------------------
spm_affdef(Def{:},VF.mat);
% Write the deformations
%-----------------------------------------------------------------------
save_def(Def,VG.mat,ofname)
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [udat,sf] = loaduint8(V)
% Load data from file indicated by V into an array of unsigned bytes.
spm_progress_bar('Init',V.dim(3),...
['Computing max/min of ' spm_str_manip(V.fname,'t')],...
'Planes complete');
mx = -Inf;
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
mx = max([max(img(:)) mx]);
spm_progress_bar('Set',p);
end;
spm_progress_bar('Init',V.dim(3),...
['Loading ' spm_str_manip(V.fname,'t')],...
'Planes loaded');
sf = 255/mx;
udat = uint8(0);
udat(V.dim(1),V.dim(2),V.dim(3))=0;
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
udat(:,:,p) = round(max(min(img*sf,255),0));
spm_progress_bar('Set',p);
end;
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function t = transf(B1,B2,B3,T)
d2 = [size(T) 1];
t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));
t = B1*t1*B2';
return;
%_______________________________________________________________________
%_______________________________________________________________________
function udat = bias_correction(VF,VG,nits,fwhm,reg1,reg2,sf)
% This function is intended for doing bias correction prior
% to high-dimensional intra-subject registration. Begin by
% coregistering, then run the bias correction, and then do
% the high-dimensional warping. A version of the first image
% is returned out, that has the same bias as that of the second
% image. This allows warping of the corrected first image, to
% match the uncorrected second image.
%
% Ideally, it would all be combined into the same model, but
% that would require quite a lot of extra work. I should really
% sort out a good convergence criterion, and make it a proper
% Levenberg-Marquardt optimisation.
vx = sqrt(sum(VF.mat(1:3,1:3).^2));
d = VF.dim(1:3);
sd = vx(1)*VF.dim(1)/fwhm; d3(1) = ceil(sd*2); krn_x = exp(-(0:(d3(1)-1)).^2/sd.^2)/sqrt(vx(1));
sd = vx(2)*VF.dim(2)/fwhm; d3(2) = ceil(sd*2); krn_y = exp(-(0:(d3(2)-1)).^2/sd.^2)/sqrt(vx(2));
sd = vx(3)*VF.dim(3)/fwhm; d3(3) = ceil(sd*2); krn_z = exp(-(0:(d3(3)-1)).^2/sd.^2)/sqrt(vx(3));
Cbias = kron(krn_z,kron(krn_y,krn_x)).^(-2)*prod(d)*reg1;
Cbias = sparse(1:length(Cbias),1:length(Cbias),Cbias,length(Cbias),length(Cbias));
B3bias = spm_dctmtx(d(3),d3(3));
B2bias = spm_dctmtx(d(2),d3(2));
B1bias = spm_dctmtx(d(1),d3(1));
lmRb = speye(size(Cbias))*prod(d)*reg2;
Tbias = zeros(d3);
ll = Inf;
spm_chi2_plot('Init','Bias Correction','- Log-likelihood','Iteration');
for subit=1:nits,
% Compute objective function and its 1st and second derivatives
Alpha = zeros(prod(d3),prod(d3)); % Second derivatives
Beta = zeros(prod(d3),1); % First derivatives
oll = ll;
ll = 0.5*Tbias(:)'*Cbias*Tbias(:);
for z=1:VF.dim(3),
M1 = spm_matrix([0 0 z]);
M2 = VG.mat\VF.mat*M1;
f1o = spm_slice_vol(VF,M1,VF.dim(1:2),0);
f2o = spm_slice_vol(VG,M2,VF.dim(1:2),0);
msk = (f1o==0) & (f2o==0);
f1o(msk) = 0;
f2o(msk) = 0;
ro = transf(B1bias,B2bias,B3bias(z,:),Tbias);
msk = abs(ro)>0.01; % false(d(1:2));
% Use the form based on an integral for bias that is
% far from uniform.
f1 = f1o(msk);
f2 = f2o(msk);
r = ro(msk);
e = exp(r);
t1 = (f2.*e-f1);
t2 = (f1./e-f2);
ll = ll + 1/4*sum(sum((t1.^2-t2.^2)./r));
wt1 = zeros(size(f1o));
wt2 = zeros(size(f1o));
wt1(msk) = (2*(t1.*f2.*e+t2.*f1./e)./r + (t2.^2-t1.^2)./r.^2)/4;
wt2(msk) = ((f2.^2.*e.^2-f1.^2./e.^2+t1.*f2.*e-t2.*f1./e)./r/2 ...
- (t1.*f2.*e+t2.*f1./e)./r.^2 + (t1.^2-t2.^2)./r.^3/2);
% Use the simple symmetric form for bias close to uniform
f1 = f1o(~msk);
f2 = f2o(~msk);
r = ro(~msk);
e = exp(r);
t1 = (f2.*e-f1);
t2 = (f1./e-f2);
ll = ll + (sum(t1.^2)+sum(t2.^2))/4;
wt1(~msk) = (t1.*f2.*e-t2.*f1./e)/2;
wt2(~msk) = ((f2.*e).^2+t1.*f2.*e + (f1./e).^2+t2.*f1./e)/2;
b3 = B3bias(z,:)';
Beta = Beta + kron(b3,spm_krutil(wt1,B1bias,B2bias,0));
Alpha = Alpha + kron(b3*b3',spm_krutil(wt2,B1bias,B2bias,1));
end;
spm_chi2_plot('Set',ll/prod(d));
if subit > 1 && ll>oll,
% Hasn't improved, so go back to previous solution
Tbias = oTbias;
ll = oll;
lmRb = lmRb*10;
else
% Accept new solution
oTbias = Tbias;
Tbias = Tbias(:);
Tbias = Tbias - (Alpha + Cbias + lmRb)\(Beta + Cbias*Tbias);
Tbias = reshape(Tbias,d3);
end;
end;
udat = uint8(0);
udat(VF.dim(1),VF.dim(2),VF.dim(3)) = 0;
for z=1:VF.dim(3),
M1 = spm_matrix([0 0 z]);
f1 = spm_slice_vol(VF,M1,VF.dim(1:2),0);
r = transf(B1bias,B2bias,B3bias(z,:),Tbias);
f1 = f1./exp(r);
udat(:,:,z) = round(max(min(f1*sf,255),0));
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function save_def(Def,mat,fname)
% Save a deformation field as an image
dim = [size(Def{1},1) size(Def{1},2) size(Def{1},3) 1 3];
dtype = 'FLOAT32-BE';
off = 0;
scale = 1;
inter = 0;
dat = file_array(fname,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};
% Write Jacobian determinants
[pth,nme,ext,num] = spm_fileparts(fname);
jfname = fullfile(pth,['j' nme '.nii'])
dt = spm_def2det(Def{:},N.mat);
dat = file_array(jfname,dim(1:3),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 = 'NONE';
N.intent.name = 'Det';
N.descrip = 'Jacobian Determinant';
create(N);
N.dat(:,:,:) = dt;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function theory
% This function is never called. It simply contains my derivation of the
% objective function and its first and second derivatives for the LM
% optimisation. Note that this would simply be summed over all voxels.
% An estimate of the variance should maybe have been included, but I'll
% leave that for a future version.
% These will be used to simplify expressions
r = x1*p1+x2*p2;
e = exp(r);
t1 = (f2*e-f1)
t2 = (f1/e-f2)
% This is the actual objective function
maple int((exp(-(x1*p1+x2*p2)*(1-t))*f1-exp((x1*p1+x2*p2)*t)*f2)^2/2,t=0..1)
f = 1/4*(t1^2-t2^2)/r
% These are the first derivatives
maple diff(1/4*((f1-f2*exp(x1*p1+x2*p2))^2-(f2-f1/exp(x1*p1+x2*p2))^2)/(x1*p1+x2*p2),x1)
d1 = p1*1/4*(2*(t1*f2*e+t2*f1/e)/r + (t2^2-t1^2)/r^2)
% These are the second derivatives
maple diff(diff(1/4*((f1-f2*exp(x1*p1+x2*p2))^2-(f2-f1/exp(x1*p1+x2*p2))^2)/(x1*p1+x2*p2),x1),x2)
d2 = p1*p2*(1/2*(f2^2*e^2-f1^2/e^2+t1*f2*e-t2*f1/e)/r - (t1*f2*e+t2*f1/e)/r^2 + 1/2*(t1^2-t2^2)/r^3)
% However, the above formulation has problems in limiting case of zero bias,
% so this objective function is used for these regions
f = (t1^2+t2^2)/4
% First derivs
maple diff((f1-exp(x1*p1+x2*p2)*f2)^2/4 + (f1/exp(x1*p1+x2*p2)-f2)^2/4,x1)
d1 = (p1*t1*f2*e - p1*t2*f1/e)/2
% Second derivatives
maple diff(diff((f1-exp(x1*p1+x2*p2)*f2)^2/4 + (f1/exp(x1*p1+x2*p2)-f2)^2/4,x1),x2)
d2 = p1*p2*(f2^2*e^2+t1*f2*e + f1^2/e^2+t2*f1/e)/2
|
github
|
spm/spm5-master
|
subsasgn.m
|
.m
|
spm5-master/@file_array/subsasgn.m
| 4,391 |
utf_8
|
15f88c208f436610f7b87938c84835af
|
function obj = subsasgn(obj,subs,dat)
% Overloaded subsasgn function for file_array objects.
% _______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: subsasgn.m 945 2007-10-14 18:08:46Z volkmar $
if isempty(subs)
return;
end;
if ~strcmp(subs(1).type,'()'),
if strcmp(subs(1).type,'.'),
%error('Attempt to reference field of non-structure array.');
if numel(struct(obj))~=1,
error('Can only change the fields of simple file_array objects.');
end;
switch(subs(1).subs)
case 'fname', obj = asgn(obj,@fname, subs(2:end),dat); %fname(obj,dat);
case 'dtype', obj = asgn(obj,@dtype, subs(2:end),dat); %dtype(obj,dat);
case 'offset', obj = asgn(obj,@offset, subs(2:end),dat); %offset(obj,dat);
case 'dim', obj = asgn(obj,@dim, subs(2:end),dat); %obj = dim(obj,dat);
case 'scl_slope', obj = asgn(obj,@scl_slope,subs(2:end),dat); %scl_slope(obj,dat);
case 'scl_inter', obj = asgn(obj,@scl_inter,subs(2:end),dat); %scl_inter(obj,dat);
otherwise, error(['Reference to non-existent field "' subs.subs '".']);
end;
return;
end;
if strcmp(subs(1).type,'{}'), error('Cell contents reference from a non-cell array object.'); end;
end;
if numel(subs)~=1, error('Expression too complicated');end;
dm = size(obj);
sobj = struct(obj);
if length(subs.subs) < length(dm),
l = length(subs.subs);
dm = [dm(1:(l-1)) prod(dm(l:end))];
if numel(sobj) ~= 1,
error('Can only reshape simple file_array objects.');
end;
if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1,
error('Can not reshape file_array objects with multiple slopes and intercepts.');
end;
end;
dm = [dm ones(1,16)];
do = ones(1,16);
args = {};
for i=1:length(subs.subs),
if ischar(subs.subs{i}),
if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end;
args{i} = int32(1:dm(i));
else
args{i} = int32(subs.subs{i});
end;
do(i) = length(args{i});
end;
if length(sobj)==1
sobj.dim = dm;
if numel(dat)~=1,
subfun(sobj,double(dat),args{:});
else
dat1 = double(dat) + zeros(do);
subfun(sobj,dat1,args{:});
end;
else
for j=1:length(sobj),
ps = [sobj(j).pos ones(1,length(args))];
dm = [sobj(j).dim ones(1,length(args))];
siz = ones(1,16);
for i=1:length(args),
msk = args{i}>=ps(i) & args{i}<(ps(i)+dm(i));
args2{i} = find(msk);
args3{i} = int32(double(args{i}(msk))-ps(i)+1);
siz(i) = numel(args2{i});
end;
if numel(dat)~=1,
dat1 = double(subsref(dat,struct('type','()','subs',{args2})));
else
dat1 = double(dat) + zeros(siz);
end;
subfun(sobj(j),dat1,args3{:});
end
end
return
function sobj = subfun(sobj,dat,varargin)
va = varargin;
dt = datatypes;
ind = find(cat(1,dt.code)==sobj.dtype);
if isempty(ind), error('Unknown datatype'); end;
if dt(ind).isint, dat(~isfinite(dat)) = 0; end;
if ~isempty(sobj.scl_inter),
inter = sobj.scl_inter;
if numel(inter)>1,
inter = resize_scales(inter,sobj.dim,varargin);
end;
dat = double(dat) - inter;
end;
if ~isempty(sobj.scl_slope),
slope = sobj.scl_slope;
if numel(slope)>1,
slope = resize_scales(slope,sobj.dim,varargin);
dat = double(dat)./slope;
else
dat = double(dat)/slope;
end;
end;
if dt(ind).isint, dat = round(dat); end;
% Avoid warning messages in R14 SP3
wrn = warning;
warning('off');
dat = feval(dt(ind).conv,dat);
warning(wrn);
nelem = dt(ind).nelem;
if nelem==1,
mat2file(sobj,dat,va{:});
elseif nelem==2,
sobj1 = sobj;
sobj1.dim = [2 sobj.dim];
sobj1.dtype = dt(find(strcmp(dt(ind).prec,{dt.prec}) & (cat(2,dt.nelem)==1))).code;
dat = reshape(dat,[1 size(dat)]);
dat = [real(dat) ; imag(dat)];
mat2file(sobj1,dat,int32([1 2]),va{:});
else
error('Inappropriate number of elements per voxel.');
end;
return
function obj = asgn(obj,fun,subs,dat)
if ~isempty(subs),
tmp = feval(fun,obj);
tmp = subsasgn(tmp,subs,dat);
obj = feval(fun,obj,tmp);
else
obj = feval(fun,obj,dat);
end;
|
github
|
spm/spm5-master
|
subsref.m
|
.m
|
spm5-master/@file_array/subsref.m
| 3,491 |
utf_8
|
ad5a748cb36c7c36dc4231cafb53cea8
|
function varargout=subsref(obj,subs)
% SUBSREF Subscripted reference
% An overloaded function...
% _________________________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: subsref.m 315 2005-11-28 16:48:59Z john $
if isempty(subs)
return;
end;
if ~strcmp(subs(1).type,'()'),
if strcmp(subs(1).type,'.'),
%error('Attempt to reference field of non-structure array.');
%if numel(struct(obj))~=1,
% error('Can only access the fields of simple file_array objects.');
%end;
varargout = access_fields(obj,subs);
return;
end;
if strcmp(subs.type,'{}'), error('Cell contents reference from a non-cell array object.'); end;
end;
if numel(subs)~=1, error('Expression too complicated');end;
dim = [size(obj) ones(1,16)];
nd = max(find(dim>1))-1;
sobj = struct(obj);
if length(subs.subs) < nd,
l = length(subs.subs);
dim = [dim(1:(l-1)) prod(dim(l:end))];
if numel(sobj) ~= 1,
error('Can only reshape simple file_array objects.');
else
if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1,
error('Can not reshape file_array objects with multiple slopes and intercepts.');
end;
sobj.dim = dim;
end;
end;
do = ones(16,1);
args = {};
for i=1:length(subs.subs),
if ischar(subs.subs{i}),
if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end;
args{i} = int32(1:dim(i));
else
args{i} = int32(subs.subs{i});
end;
do(i) = length(args{i});
end;
if length(sobj)==1,
t = subfun(sobj,args{:});
else
t = zeros(do');
for j=1:length(sobj),
ps = [sobj(j).pos ones(1,length(args))];
dm = [sobj(j).dim ones(1,length(args))];
for i=1:length(args),
msk = find(args{i}>=ps(i) & args{i}<(ps(i)+dm(i)));
args2{i} = msk;
args3{i} = int32(double(args{i}(msk))-ps(i)+1);
end;
t = subsasgn(t,struct('type','()','subs',{args2}),subfun(sobj(j),args3{:}));
end
end
varargout = {t};
return;
function t = subfun(sobj,varargin)
%sobj.dim = [sobj.dim ones(1,16)];
t = file2mat(sobj,varargin{:});
if ~isempty(sobj.scl_slope) || ~isempty(sobj.scl_inter)
slope = 1;
inter = 0;
if ~isempty(sobj.scl_slope), slope = sobj.scl_slope; end;
if ~isempty(sobj.scl_inter), inter = sobj.scl_inter; end;
if numel(slope)>1,
slope = resize_scales(slope,sobj.dim,varargin);
t = double(t).*slope;
else
t = double(t)*slope;
end;
if numel(inter)>1,
inter = resize_scales(inter,sobj.dim,varargin);
end;
t = t + inter;
end;
return;
function c = access_fields(obj,subs)
%error('Attempt to reference field of non-structure array.');
%if numel(struct(obj))~=1,
% error('Can only access the fields of simple file_array objects.');
%end;
c = {};
sobj = struct(obj);
for i=1:numel(sobj),
%obj = class(sobj(i),'file_array');
obj = sobj(i);
switch(subs(1).subs)
case 'fname', t = fname(obj);
case 'dtype', t = dtype(obj);
case 'offset', t = offset(obj);
case 'dim', t = dim(obj);
case 'scl_slope', t = scl_slope(obj);
case 'scl_inter', t = scl_inter(obj);
otherwise, error(['Reference to non-existent field "' subs(1).type '".']);
end;
if numel(subs)>1,
t = subsref(t,subs(2:end));
end;
c{i} = t;
end;
return;
|
github
|
spm/spm5-master
|
disp.m
|
.m
|
spm5-master/@file_array/disp.m
| 936 |
utf_8
|
b554bdf3b9952d0af1a8bff9b3b2d79b
|
function disp(obj)
% Display a file_array object
% _______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: disp.m 253 2005-10-13 15:31:34Z guillaume $
if numel(struct(obj))>1,
fprintf(' %s object: ', class(obj));
sz = size(obj);
if length(sz)>4,
fprintf('%d-D\n',length(sz));
else
for i=1:(length(sz)-1),
fprintf('%d-by-',sz(i));
end;
fprintf('%d\n',sz(end));
end;
else
display(mystruct(obj))
end;
return;
%=======================================================================
%=======================================================================
function t = mystruct(obj)
fn = fieldnames(obj);
for i=1:length(fn)
t.(fn{i}) = subsref(obj,struct('type','.','subs',fn{i}));
end;
return;
%=======================================================================
|
github
|
spm/spm5-master
|
offset.m
|
.m
|
spm5-master/@file_array/private/offset.m
| 748 |
utf_8
|
c89ae4584631eea52eb87b0dfd4fd7d3
|
function varargout = offset(varargin)
% Format
% For getting the value
% dat = offset(obj)
%
% For setting the value
% obj = offset(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: offset.m 253 2005-10-13 15:31:34Z guillaume $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.offset;
return;
function obj = asgn(obj,dat)
if isnumeric(dat) && numel(dat)==1 && dat>=0 && rem(dat,1)==0,
obj.offset = double(dat);
else
error('"offset" must be a positive integer.');
end;
return;
|
github
|
spm/spm5-master
|
scl_slope.m
|
.m
|
spm5-master/@file_array/private/scl_slope.m
| 734 |
utf_8
|
73f54f5dbe19e718bd6b78dc882dc8af
|
function varargout = scl_slope(varargin)
% Format
% For getting the value
% dat = scl_slope(obj)
%
% For setting the value
% obj = scl_slope(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: scl_slope.m 253 2005-10-13 15:31:34Z guillaume $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.scl_slope;
return;
function obj = asgn(obj,dat)
if isnumeric(dat), % && numel(dat)<=1,
obj.scl_slope = double(dat);
else
error('"scl_slope" must be numeric.');
end;
return;
|
github
|
spm/spm5-master
|
scl_inter.m
|
.m
|
spm5-master/@file_array/private/scl_inter.m
| 735 |
utf_8
|
def2da385023fb5bdc7cc3ce9fcd3395
|
function varargout = scl_inter(varargin)
% Format
% For getting the value
% dat = scl_inter(obj)
%
% For setting the value
% obj = scl_inter(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: scl_inter.m 253 2005-10-13 15:31:34Z guillaume $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.scl_inter;
return;
function obj = asgn(obj,dat)
if isnumeric(dat), % && numel(dat)<=1,
obj.scl_inter = double(dat);
else
error('"scl_inter" must be numeric.');
end;
return;
|
github
|
spm/spm5-master
|
fname.m
|
.m
|
spm5-master/@file_array/private/fname.m
| 698 |
utf_8
|
c6216888cbebeb595fd5802255c31b22
|
function varargout = fname(varargin)
% Format
% For getting the value
% dat = fname(obj)
%
% For setting the value
% obj = fname(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: fname.m 253 2005-10-13 15:31:34Z guillaume $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.fname;
return;
function obj = asgn(obj,dat)
if ischar(dat)
obj.fname = deblank(dat(:)');
else
error('"fname" must be a character string.');
end;
return;
|
github
|
spm/spm5-master
|
dim.m
|
.m
|
spm5-master/@file_array/private/dim.m
| 810 |
utf_8
|
93395c42c87fe17ad7dcc88a6062ebf8
|
function varargout = dim(varargin)
% Format
% For getting the value
% dat = dim(obj)
%
% For setting the value
% obj = dim(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: dim.m 253 2005-10-13 15:31:34Z guillaume $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wrong number of arguments.');
end;
return;
function dat = ref(obj)
dat = obj.dim;
return;
function obj = asgn(obj,dat)
if isnumeric(dat) && all(dat>=0) && all(rem(dat,1)==0),
dat = [double(dat(:)') 1 1];
lim = max([2 find(dat~=1)]);
dat = dat(1:lim);
obj.dim = dat;
else
error('"dim" must be a vector of positive integers.');
end;
return;
|
github
|
spm/spm5-master
|
dtype.m
|
.m
|
spm5-master/@file_array/private/dtype.m
| 2,270 |
utf_8
|
380230a467432825a6b68b343c50cbc2
|
function varargout = dtype(varargin)
% Format
% For getting the value
% dat = dtype(obj)
%
% For setting the value
% obj = dtype(obj,dat)
% _______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: dtype.m 466 2006-03-01 15:14:22Z john $
if nargin==2,
varargout{1} = asgn(varargin{:});
elseif nargin==1,
varargout{1} = ref(varargin{:});
else
error('Wring number of arguments.');
end;
return;
function t = ref(obj)
d = datatypes;
mch = find(cat(1,d.code)==obj.dtype);
if isempty(mch), t = 'UNKNOWN'; else t = d(mch).label; end;
if obj.be, t = [t '-BE']; else t = [t '-LE']; end;
return;
function obj = asgn(obj,dat)
d = datatypes;
if isnumeric(dat)
if numel(dat)>=1,
mch = find(cat(1,d.code)==dat(1));
if isempty(mch) || mch==0,
fprintf('Invalid datatype (%d).', dat(1));
disp('First part of datatype should be of one of the following');
disp(sortrows([num2str(cat(1,d.code)) ...
repmat(' ',numel(d),2) strvcat(d.label)]));
%error(['Invalid datatype (' num2str(dat(1)) ').']);
return;
end;
obj.dtype = double(dat(1));
end;
if numel(dat)>=2,
obj.be = double(dat(2)~=0);
end;
if numel(dat)>2,
error('Too many elements in numeric datatype.');
end;
elseif ischar(dat),
dat1 = lower(dat);
sep = find(dat1=='-' | dat1=='/');
sep = sep(sep~=1);
if ~isempty(sep),
c1 = dat1(1:(sep(1)-1));
c2 = dat1((sep(1)+1):end);
else
c1 = dat1;
c2 = '';
end;
mch = find(strcmpi(c1,lower({d.label})));
if isempty(mch),
disp('First part of datatype should be of one of the following');
disp(sortrows([num2str(cat(1,d.code)) ...
repmat(' ',numel(d),2) strvcat(d.label)]));
%error(['Invalid datatype (' c1 ').']);
return;
else
obj.dtype = double(d(mch(1)).code);
end;
if any(c2=='b'),
if any(c2=='l'),
error('Cannot be both big and little endian.');
end;
obj.be = 1;
elseif any(c2=='l'),
obj.be = 0;
end;
else
error('Invalid datatype.');
end;
return;
|
github
|
spm/spm5-master
|
paint.m
|
.m
|
spm5-master/@slover/paint.m
| 10,059 |
utf_8
|
b0890caeac7c122fe24ae8dc9ed9c742
|
function obj = paint(obj, params)
% method to display slice overlay
% FORMAT paint(obj, params)
%
% Inputs
% obj - slice overlay object
% params - optional structure containing extra display parameters
% - refreshf - overrides refreshf in object
% - clf - overrides clf in object
% - userdata - if 0, does not add object to userdata field
% (see below)
%
% Outputs
% obj - which may have been filled with defaults
%
% paint attaches the object used for painting to the 'UserData' field of
% the figure handle, unless instructed not to with 0 in userdata flag
%
% $Id: paint.m,v 1.2 2005/05/06 22:59:56 matthewbrett Exp $
fig_struct_fields = {'Position', 'Units'};
if nargin < 2
params = [];
end
params = mars_struct('fillafromb', params, ...
struct('refreshf', obj.refreshf,...
'clf', obj.clf, ...
'userdata', obj.userdata));
% Fill any needed defaults
obj = fill_defaults(obj);
% check if object can be painted
if isempty(obj.img)
warning('No images, object cannot be painted')
return
end
% get coordinates for plane
X=1;Y=2;Z=3;
dims = obj.slicedef;
xmm = dims(X,1):dims(X,2):dims(X,3);
ymm = dims(Y,1):dims(Y,2):dims(Y,3);
zmm = obj.slices;
[y x] = meshgrid(ymm,xmm');
vdims = [length(xmm),length(ymm),length(zmm)];
% no of slices, and panels (an extra for colorbars)
nslices = vdims(Z);
minnpanels = nslices;
cbars = 0;
if ~isempty(obj.cbar)
cbars = length(obj.cbar);
minnpanels = minnpanels+cbars;
end
% Get figure data. The figure may be dead, in which case we may want to
% revive it. If so, we set position etc as stored.
% If written to, the axes may be specified already
dead_f = ~ishandle(obj.figure);
figno = figure(obj.figure);
if dead_f
set(figno, obj.figure_struct);
end
% (re)initialize axes and stuff
% check if the figure is set up correctly
if ~params.refreshf
axisd = flipud(findobj(obj.figure, 'Type','axes','Tag', 'slice overlay panel'));
npanels = length(axisd);
if npanels < vdims(Z)+cbars;
params.refreshf = 1;
end
end
if params.refreshf
% clear figure, axis store
if params.clf, clf; end
axisd = [];
% prevent print inversion problems
set(figno,'InvertHardCopy','off');
% put copy of object into UserData for callbacks
if params.userdata
set(figno, 'UserData', obj);
end
% calculate area of display in pixels
parea = obj.area.position;
if ~strcmp(obj.area.units, 'pixels')
ubu = get(obj.figure, 'units');
set(obj.figure, 'units','pixels');
tmp = get(obj.figure, 'Position');
ascf = tmp(3:4);
if ~strcmp(obj.area.units, 'normalized')
set(obj.figure, 'units',obj.area.units);
tmp = get(obj.figure, 'Position');
ascf = ascf ./ tmp(3:4);
end
set(figno, 'Units', ubu);
parea = parea .* repmat(ascf, 1, 2);
end
asz = parea(3:4);
% by default, make most parsimonious fit to figure
yxratio = length(ymm)*dims(Y,2)/(length(xmm)*dims(X,2));
if isempty(obj.xslices)
% iteration needed to optimize, surprisingly. Thanks to Ian NS
axlen(X,:)=asz(1):-1:1;
axlen(Y,:)=yxratio*axlen(X,:);
panels = floor(asz'*ones(1,size(axlen,2))./axlen);
estnpanels = prod(panels);
tmp = find(estnpanels >= minnpanels);
if isempty(tmp)
error('Whoops, cannot fit panels onto figure');
end
b = tmp(1); % best fitting scaling
panels = panels(:,b);
axlen = axlen(:, b);
else
% if xslices is specified, assume X is flush with X figure dimensions
panels([X:Y],1) = [obj.xslices; 0];
axlen([X:Y],1) = [asz(X)/panels(X); 0];
end
% Axis dimensions are in pixels. This prevents aspect ratio rescaling
panels(Y) = ceil(minnpanels/panels(X));
axlen(Y) = axlen(X)*yxratio;
% centre (etc) panels in display area as required
divs = [Inf 2 1];the_ds = [0;0];
the_ds(X) = divs(strcmp(obj.area.halign, {'left','center','right'}));
the_ds(Y) = divs(strcmp(obj.area.valign, {'bottom','middle','top'}));
startc = parea(1:2)' + (asz'-(axlen.*panels))./the_ds;
% make axes for panels
r=0;c=1;
npanels = prod(panels);
lastempty = npanels-cbars;
for i = 1:npanels
% panel userdata
if i<=nslices
u.type = 'slice';
u.no = zmm(i);
elseif i > lastempty
u.type = 'cbar';
u.no = i - lastempty;
else
u.type = 'empty';
u.no = i - nslices;
end
axpos = [r*axlen(X)+startc(X) (panels(Y)-c)*axlen(Y)+startc(Y) axlen'];
axisd(i) = axes(...
'Parent',figno,...
'XTick',[],...
'XTickLabel',[],...
'YTick',[],...
'YTickLabel',[],...
'Box','on',...
'XLim',[1 vdims(X)],...
'YLim',[1 vdims(Y)],...
'Units', 'pixels',...
'Position',axpos,...
'Tag','slice overlay panel',...
'UserData',u);
r = r+1;
if r >= panels(X)
r = 0;
c = c+1;
end
end
end
% sort out labels
if ischar(obj.labels)
do_labels = ~strcmp(lower(obj.labels), 'none');
else
do_labels = 1;
end
if do_labels
labels = obj.labels;
if iscell(labels.format)
if length(labels.format)~=vdims(Z)
error(...
sprintf('Oh dear, expecting %d labels, but found %d',...
vdims(Z), length(labels.contents)));
end
else
% format string for mm from AC labelling
fstr = labels.format;
labels.format = cell(vdims(Z),1);
acpt = obj.transform * [0 0 0 1]';
for i = 1:vdims(Z)
labels.format(i) = {sprintf(fstr,zmm(i)-acpt(Z))};
end
end
end
% split images into picture and contour
itypes = {obj.img(:).type};
tmp = strcmpi(itypes, 'contour');
contimgs = find(tmp);
pictimgs = find(~tmp);
% modify picture image colormaps with any new colours
npimgs = length(pictimgs);
lrn = zeros(npimgs,3);
cmaps = cell(npimgs);
for i = 1:npimgs
cmaps(i)={obj.img(pictimgs(i)).cmap};
lrnv = {obj.img(pictimgs(i)).outofrange{:}, obj.img(pictimgs(i)).nancol};
for j = 1:length(lrnv)
if prod(size(lrnv{j}))==1
lrn(i,j) = lrnv{j};
else
cmaps(i) = {[cmaps{i}; lrnv{j}(1:3)]};
lrn(i,j) = size(cmaps{i},1);
end
end
end
% cycle through slices displaying images
nvox = prod(vdims(1:2));
pandims = [vdims([2 1]) 3]; % NB XY transpose for display
zimg = zeros(pandims);
for i = 1:nslices
ixyzmm = [x(:)';y(:)';ones(1,nvox)*zmm(i);ones(1,nvox)];
img = zimg;
for j = 1:npimgs
thisimg = obj.img(pictimgs(j));
i1 = sf_slice2panel(thisimg, ixyzmm, obj.transform, vdims);
% rescale to colormap
[csdata badvals]= pr_scaletocmap(...
i1,...
thisimg.range(1),...
thisimg.range(2),...
thisimg.cmap,...
lrn(j,:));
% take indices from colormap to make true colour image
iimg = reshape(cmaps{j}(csdata(:),:),pandims);
tmp = repmat(logical(~badvals),[1 1 3]);
if strcmpi(thisimg.type, 'truecolour')
img(tmp) = img(tmp) + iimg(tmp)*thisimg.prop;
else % split colormap effect
img(tmp) = iimg(tmp)*thisimg.prop;
end
end
% threshold out of range values
img(img>1) = 1;
image('Parent', axisd(i),...
'ButtonDownFcn', obj.callback,...
'CData',img);
% do contour plot
for j=1:length(contimgs)
thisimg = obj.img(contimgs(j));
i1 = sf_slice2panel(thisimg, ixyzmm, obj.transform, vdims);
if any(any(isfinite(i1)))
i1(i1<min(thisimg.range))=min(thisimg.range);
i1(i1>max(thisimg.range))=max(thisimg.range);
if mars_struct('isthere', thisimg, 'linespec')
linespec = thisimg.linespec;
else
linespec = 'w-';
end
axes(axisd(i));
set(axisd(i),'NextPlot','add');
if mars_struct('isthere', thisimg, 'contours')
[c h] = contour(i1, thisimg.contours, linespec);
else
[c h] = contour(i1, linespec);
end
if ~isempty(h)
if ~mars_struct('isthere', thisimg, 'linespec')
% need to reset colours
% assumes contour value is in line UserData
% as seemed to be the case
convals = get(h, 'UserData');
if ~iscell(convals),convals = {convals};end
if ~isempty(convals)
[csdata badvals] = pr_scaletocmap(...
cat(1, convals{:}), ...
thisimg.range(1),...
thisimg.range(2),...
thisimg.cmap,...
[1 size(thisimg.cmap,1) 1]);
colvals = thisimg.cmap(csdata(:),:)*thisimg.prop;
set(h, {'Color'}, num2cell(colvals, 2));
end
end
if mars_struct('isthere', thisimg, 'linewidth')
set(h, 'LineWidth', thisimg.linewidth);
end
end
end
end
if do_labels
text('Parent',axisd(i),...
'Color', labels.colour,...
'FontUnits', 'normalized',...
'VerticalAlignment','bottom',...
'HorizontalAlignment','left',...
'Position', [1 1],...
'FontSize',labels.size,...
'ButtonDownFcn', obj.callback,...
'String', labels.format{i});
end
end
for i = (nslices+1):npanels
set(axisd(i),'Color',[0 0 0]);
end
% add colorbar(s)
for i = 1:cbars
axno = axisd(end-cbars+i);
cbari = obj.img(obj.cbar(i));
cml = size(cbari.cmap,1);
p = get(axno, 'Position'); % position of last axis
cw = p(3)*0.2;
ch = p(4)*0.75;
pc = p(3:4)/2;
[axlims idxs] = sort(cbari.range);
a=axes(...
'Parent',figno,...
'XTick',[],...
'XTickLabel',[],...
'Units', 'pixels',...
'YLim', axlims,...
'FontUnits', 'normalized',...
'FontSize', 0.075,...
'YColor',[1 1 1],...
'Tag', 'cbar',...
'Box', 'off',...
'Position',[p(1)+pc(1)-cw/2,p(2)+pc(2)-ch/2,cw,ch]...
);
ih = image('Parent', a,...
'YData', axlims(idxs),...
'CData', reshape(cbari.cmap,[cml,1,3]));
end % colourbars
% Get stuff for figure, in case it dies later
obj.figure_struct = mars_struct('split', get(figno), fig_struct_fields);
return
% subfunctions
% ------------
function i1 = sf_slice2panel(img, xyzmm, transform, vdims)
% to voxel space of image
vixyz = inv(transform*img.vol.mat)*xyzmm;
% raw data
if mars_struct('isthere', img.vol, 'imgdata')
V = img.vol.imgdata;
else
V = img.vol;
end
i1 = spm_sample_vol(V,vixyz(1,:),vixyz(2,:),vixyz(3,:), ...
[img.hold img.background]);
if mars_struct('isthere', img, 'func')
eval(img.func);
end
% transpose to reverse X and Y for figure
i1 = reshape(i1, vdims(1:2))';
return
|
github
|
spm/spm5-master
|
pr_basic_ui.m
|
.m
|
spm5-master/@slover/private/pr_basic_ui.m
| 3,598 |
utf_8
|
8626d5c4d641365e28e1cce491af5054
|
function obj = pr_basic_ui(imgs, dispf)
% GUI to request parameters for slover routine
% FORMAT obj = pr_basic_ui(imgs, dispf)
%
% GUI requests choices while accepting many defaults
%
% imgs - string or cell array of image names to display
% (defaults to GUI select if no arguments passed)
% dispf - optional flag: if set, displays overlay (default = 1)
%
% $Id: pr_basic_ui.m,v 1.1 2005/04/20 15:05:00 matthewbrett Exp $
if nargin < 1
imgs = '';
end
if isempty(imgs)
imgs = spm_select(Inf, 'image', 'Image(s) to display');
end
if ischar(imgs)
imgs = cellstr(imgs);
end
if nargin < 2
dispf = 1;
end
spm_input('!SetNextPos', 1);
% load images
nimgs = size(imgs);
% process names
nchars = 20;
imgns = spm_str_manip(imgs, ['rck' num2str(nchars)]);
% Get new default object
obj = slover;
% identify image types
cscale = [];
deftype = 1;
obj.cbar = [];
for i = 1:nimgs
obj.img(i).vol = spm_vol(imgs{i});
options = {'Structural','Truecolour', ...
'Blobs','Negative blobs','Contours'};
% if there are SPM results in the workspace, add this option
[XYZ Z M] = pr_get_spm_results;
if ~isempty(XYZ)
options = {'Structural with SPM blobs', options{:}};
end
itype = spm_input(sprintf('Img %d: %s - image type?', i, imgns{i}), '+1', ...
'm', char(options),options, deftype);
imgns(i) = {sprintf('Img %d (%s)',i,itype{1})};
[mx mn] = slover('volmaxmin', obj.img(i).vol);
if ~isempty(strmatch('Structural', itype))
obj.img(i).type = 'truecolour';
obj.img(i).cmap = gray;
obj.img(i).range = [mn mx];
deftype = 2;
cscale = [cscale i];
if strcmp(itype,'Structural with SPM blobs')
obj = add_spm(obj);
end
else
cprompt = ['Colormap: ' imgns{i}];
switch itype{1}
case 'Truecolour'
obj.img(i).type = 'truecolour';
dcmap = 'flow.lut';
drange = [mn mx];
cscale = [cscale i];
obj.cbar = [obj.cbar i];
case 'Blobs'
obj.img(i).type = 'split';
dcmap = 'hot';
drange = [0 mx];
obj.img(i).prop = 1;
obj.cbar = [obj.cbar i];
case 'Negative blobs'
obj.img(i).type = 'split';
dcmap = 'winter';
drange = [0 mn];
obj.img(i).prop = 1;
obj.cbar = [obj.cbar i];
case 'Contours'
obj.img(i).type = 'contour';
dcmap = 'white';
drange = [mn mx];
obj.img(i).prop = 1;
end
obj.img(i).cmap = sf_return_cmap(cprompt, dcmap);
obj.img(i).range = spm_input('Img val range for colormap','+1', 'e', drange, 2);
end
end
ncmaps=length(cscale);
if ncmaps == 1
obj.img(cscale).prop = 1;
else
remcol=1;
for i = 1:ncmaps
ino = cscale(i);
obj.img(ino).prop = spm_input(sprintf('%s intensity',imgns{ino}),...
'+1', 'e', ...
remcol/(ncmaps-i+1),1);
remcol = remcol - obj.img(ino).prop;
end
end
obj.transform = deblank(spm_input('Image orientation', '+1', ['Axial|' ...
' Coronal|Sagittal'], strvcat('axial','coronal','sagittal'), ...
1));
% use SPM figure window
obj.figure = spm_figure('GetWin', 'Graphics');
% slices for display
obj = fill_defaults(obj);
slices = obj.slices;
obj.slices = spm_input('Slices to display (mm)', '+1', 'e', ...
sprintf('%0.0f:%0.0f:%0.0f',...
slices(1),...
mean(diff(slices)),...
slices(end))...
);
% and do the display
if dispf, obj = paint(obj); end
return
% Subfunctions
% ------------
function cmap = sf_return_cmap(prompt,defmapn)
cmap = [];
while isempty(cmap)
[cmap w]= slover('getcmap', spm_input(prompt,'+1','s', defmapn));
if isempty(cmap), disp(w);end
end
return
|
github
|
spm/spm5-master
|
delete.m
|
.m
|
spm5-master/@xmltree/delete.m
| 1,062 |
utf_8
|
3d4e3ea2ee3b6465070509309e6064c2
|
function tree = delete(tree,uid)
% XMLTREE/DELETE Delete (delete a subtree given its UID)
%
% tree - XMLTree object
% uid - array of UID's of subtrees to be deleted
%_______________________________________________________________________
%
% Delete a subtree given its UID
% The tree parameter must be in input AND in output
%_______________________________________________________________________
% @(#)delete.m Guillaume Flandin 02/04/08
error(nargchk(2,2,nargin));
uid = uid(:);
for i=1:length(uid)
if uid(i)==1
warning('[XMLTree] Cannot delete root element.');
else
p = tree.tree{uid(i)}.parent;
tree = sub_delete(tree,uid(i));
tree.tree{p}.contents(find(tree.tree{p}.contents==uid(i))) = [];
end
end
%=======================================================================
function tree = sub_delete(tree,uid)
if isfield(tree.tree{uid},'contents')
for i=1:length(tree.tree{uid}.contents)
tree = sub_delete(tree,tree.tree{uid}.contents(i));
end
end
tree.tree{uid} = struct('type','deleted');
|
github
|
spm/spm5-master
|
save.m
|
.m
|
spm5-master/@xmltree/save.m
| 4,111 |
utf_8
|
78be08cb954d03761753a9fe98f56f2c
|
function varargout = save(tree, filename)
% XMLTREE/SAVE Save an XML tree in an XML file
% FORMAT varargout = save(tree,filename)
%
% tree - XMLTree
% filename - XML output filename
% varargout - XML string
%_______________________________________________________________________
%
% Convert an XML tree into a well-formed XML string and write it into
% a file or return it as a string if no filename is provided.
%_______________________________________________________________________
% @(#)save.m Guillaume Flandin 01/07/11
error(nargchk(1,2,nargin));
prolog = '<?xml version="1.0" ?>\n';
%- Return the XML tree as a string
if nargin == 1
varargout{1} = [sprintf(prolog) ...
print_subtree(tree,'',root(tree))];
%- Output specified
else
%- Filename provided
if isstr(filename)
[fid, msg] = fopen(filename,'w');
if fid==-1, error(msg); end
if isempty(tree.filename), tree.filename = filename; end
%- File identifier provided
elseif isnumeric(filename) & prod(size(filename)) == 1
fid = filename;
prolog = ''; %- With this option, do not write any prolog
else
error('[XMLTree] Invalid argument.');
end
fprintf(fid,prolog);
save_subtree(tree,fid,root(tree));
if isstr(filename), fclose(fid); end
if nargout == 1
varargout{1} = print_subtree(tree,'',root(tree));
end
end
%=======================================================================
function xmlstr = print_subtree(tree,xmlstr,uid,order)
if nargin < 4, order = 0; end
xmlstr = [xmlstr blanks(3*order)];
switch tree.tree{uid}.type
case 'element'
xmlstr = sprintf('%s<%s',xmlstr,tree.tree{uid}.name);
for i=1:length(tree.tree{uid}.attributes)
xmlstr = sprintf('%s %s="%s"', xmlstr, ...
tree.tree{uid}.attributes{i}.key,...
tree.tree{uid}.attributes{i}.val);
end
if isempty(tree.tree{uid}.contents)
xmlstr = sprintf('%s/>\n',xmlstr);
else
xmlstr = sprintf('%s>\n',xmlstr);
for i=1:length(tree.tree{uid}.contents)
xmlstr = print_subtree(tree,xmlstr, ...
tree.tree{uid}.contents(i),order+1);
end
xmlstr = [xmlstr blanks(3*order)];
xmlstr = sprintf('%s</%s>\n',xmlstr,...
tree.tree{uid}.name);
end
case 'chardata'
xmlstr = sprintf('%s%s\n',xmlstr, ...
entity(tree.tree{uid}.value));
case 'cdata'
xmlstr = sprintf('%s<![CDATA[%s]]>\n',xmlstr, ...
tree.tree{uid}.value);
case 'pi'
xmlstr = sprintf('%s<?%s %s?>\n',xmlstr, ...
tree.tree{uid}.target, tree.tree{uid}.value);
case 'comment'
xmlstr = sprintf('%s<!-- %s -->\n',xmlstr,...
tree.tree{uid}.value);
otherwise
warning(sprintf('Type %s unknown: not saved', ...
tree.tree{uid}.type));
end
%=======================================================================
function save_subtree(tree,fid,uid,order)
if nargin < 4, order = 0; end
fprintf(fid,blanks(3*order));
switch tree.tree{uid}.type
case 'element'
fprintf(fid,'<%s',tree.tree{uid}.name);
for i=1:length(tree.tree{uid}.attributes)
fprintf(fid,' %s="%s"',...
tree.tree{uid}.attributes{i}.key, ...
tree.tree{uid}.attributes{i}.val);
end
if isempty(tree.tree{uid}.contents)
fprintf(fid,'/>\n');
else
fprintf(fid,'>\n');
for i=1:length(tree.tree{uid}.contents)
save_subtree(tree,fid,...
tree.tree{uid}.contents(i),order+1)
end
fprintf(fid,blanks(3*order));
fprintf(fid,'</%s>\n',tree.tree{uid}.name);
end
case 'chardata'
fprintf(fid,'%s\n',entity(tree.tree{uid}.value));
case 'cdata'
fprintf(fid,'<![CDATA[%s]]>\n',tree.tree{uid}.value);
case 'pi'
fprintf(fid,'<?%s %s?>\n',tree.tree{uid}.target, ...
tree.tree{uid}.value);
case 'comment'
fprintf(fid,'<!-- %s -->\n',tree.tree{uid}.value);
otherwise
warning(sprintf('[XMLTree] Type %s unknown: not saved', ...
tree.tree{uid}.type));
end
%=======================================================================
function str = entity(str)
str = strrep(str,'&','&');
str = strrep(str,'<','<');
str = strrep(str,'>','>');
str = strrep(str,'"','"');
str = strrep(str,'''',''');
|
github
|
spm/spm5-master
|
branch.m
|
.m
|
spm5-master/@xmltree/branch.m
| 1,465 |
utf_8
|
f9fcdbd88e225cdfc499733a2854dc93
|
function subtree = branch(tree,uid)
% XMLTREE/BRANCH Branch Method
% FORMAT uid = parent(tree,uid)
%
% tree - XMLTree object
% uid - UID of the root element of the subtree
% subtree - XMLTree object (a subtree from tree)
%_______________________________________________________________________
%
% Return a subtree from a tree.
%_______________________________________________________________________
% @(#)branch.m Guillaume Flandin 02/04/17
error(nargchk(2,2,nargin));
if uid > length(tree) | ...
prod(size(uid))~=1 | ...
~strcmp(tree.tree{uid}.type,'element')
error('[XMLTree] Invalid UID.');
end
subtree = xmltree;
subtree = set(subtree,root(subtree),'name',tree.tree{uid}.name);
child = children(tree,uid);
for i=1:length(child)
l = length(subtree);
subtree = sub_branch(tree,subtree,child(i),root(subtree));
subtree.tree{root(subtree)}.contents = [subtree.tree{root(subtree)}.contents l+1];
end
%=======================================================================
function tree = sub_branch(t,tree,uid,p)
l = length(tree);
tree.tree{l+1} = t.tree{uid};
tree.tree{l+1}.uid = l + 1;
tree.tree{l+1}.parent = p;
tree.tree{l+1}.contents = [];
if isfield(t.tree{uid},'contents')
contents = get(t,uid,'contents');
m = length(tree);
for i=1:length(contents)
tree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1];
tree = sub_branch(t,tree,contents(i),l+1);
m = length(tree);
end
end
|
github
|
spm/spm5-master
|
flush.m
|
.m
|
spm5-master/@xmltree/flush.m
| 1,271 |
utf_8
|
96e2fc9e3b1f4af1a63337f8aaf4e40f
|
function tree = flush(tree,uid)
% XMLTREE/FLUSH Flush (Clear a subtree given its UID)
%
% tree - XMLTree object
% uid - array of UID's of subtrees to be cleared
% Default is root
%_______________________________________________________________________
%
% Clear a subtree given its UID (remove all the leaves of the tree)
% The tree parameter must be in input AND in output
%_______________________________________________________________________
% @(#)flush.m Guillaume Flandin 02/04/10
error(nargchk(1,2,nargin));
if nargin == 1,
uid = root(tree);
end
uid = uid(:);
for i=1:length(uid)
tree = sub_flush(tree,uid(i));
end
%=======================================================================
function tree = sub_flush(tree,uid)
if isfield(tree.tree{uid},'contents')
% contents is parsed in reverse order because each child is
% deleted and the contents vector is then eventually reduced
for i=length(tree.tree{uid}.contents):-1:1
tree = sub_flush(tree,tree.tree{uid}.contents(i));
end
end
if strcmp(tree.tree{uid}.type,'chardata') |...
strcmp(tree.tree{uid}.type,'pi') |...
strcmp(tree.tree{uid}.type,'cdata') |...
strcmp(tree.tree{uid}.type,'comment')
tree = delete(tree,uid);
end
|
github
|
spm/spm5-master
|
copy.m
|
.m
|
spm5-master/@xmltree/copy.m
| 1,497 |
utf_8
|
5afe1fb7338fdafff4202e08838794e1
|
function tree = copy(tree,subuid,uid)
% XMLTREE/COPY Copy Method (copy a subtree in another branch)
% FORMAT tree = copy(tree,subuid,uid)
%
% tree - XMLTree object
% subuid - UID of the subtree to copy
% uid - UID of the element where the subtree must be duplicated
%_______________________________________________________________________
%
% Copy a subtree to another branch
% The tree parameter must be in input AND in output
%_______________________________________________________________________
% @(#)copy.m Guillaume Flandin 02/04/08
error(nargchk(2,3,nargin));
if nargin == 2
uid = parent(tree,subuid);
end
l = length(tree);
tree = sub_copy(tree,subuid,uid);
tree.tree{uid}.contents = [tree.tree{uid}.contents l+1];
% pour que la copie soit a cote de l'original et pas a la fin ?
% contents = get(tree,parent,'contents');
% i = find(contents==uid);
% tree = set(tree,parent,'contents',[contents(1:i) l+1 contents(i+1:end)]);
%=======================================================================
function tree = sub_copy(tree,uid,p)
l = length(tree);
tree.tree{l+1} = tree.tree{uid};
tree.tree{l+1}.uid = l+1;
tree.tree{l+1}.parent = p;
tree.tree{l+1}.contents = [];
if isfield(tree.tree{uid},'contents')
contents = get(tree,uid,'contents');
m = length(tree);
for i=1:length(contents)
tree.tree{l+1}.contents = [tree.tree{l+1}.contents m+1];
tree = sub_copy(tree,contents(i),l+1);
m = length(tree);
end
end
|
github
|
spm/spm5-master
|
convert.m
|
.m
|
spm5-master/@xmltree/convert.m
| 3,929 |
utf_8
|
6247f0512cca7b09eccc0414b0e4d93d
|
function s = convert(tree,uid)
% XMLTREE/CONVERT Converter an XML tree in a Matlab structure
%
% tree - XMLTree object
% uid - uid of the root of the subtree, if provided.
% Default is root
% s - converted structure
%_______________________________________________________________________
%
% Convert an xmltree into a Matlab structure, when possible.
% When several identical tags are present, a cell array is used.
% The root tag is not saved in the structure.
% If provided, only the structure corresponding to the subtree defined
% by the uid UID is returned.
%_______________________________________________________________________
% @(#)convert.m Guillaume Flandin 02/04/11
% Exemple:
% tree: <toto><titi>field1</titi><tutu>field2</tutu><titi>field3</titi></toto>
% toto = convert(tree);
% <=> toto = struct('titi',{{'field1', 'field3'}},'tutu','field2')
error(nargchk(1,2,nargin));
% Get the root uid of the output structure
if nargin == 1
% Get the root uid of the XML tree
root_uid = root(tree);
else
% Uid provided by user
root_uid = uid;
end
% Initialize the output structure
% struct([]) should be used but this only works with Matlab 6
% So we create a field that we delete at the end
%s = struct(get(tree,root_uid,'name'),''); % struct([])
s = struct('deletedummy','');
%s = sub_convert(tree,s,root_uid,{get(tree,root_uid,'name')});
s = sub_convert(tree,s,root_uid,{});
s = rmfield(s,'deletedummy');
%=======================================================================
function s = sub_convert(tree,s,uid,arg)
type = get(tree,uid,'type');
switch type
case 'element'
child = children(tree,uid);
l = {};
ll = {};
for i=1:length(child)
if isfield(tree,child(i),'name')
ll = { ll{:}, get(tree,child(i),'name') };
end
end
for i=1:length(child)
if isfield(tree,child(i),'name')
name = get(tree,child(i),'name');
nboccur = sum(ismember(l,name));
nboccur2 = sum(ismember(ll,name));
l = { l{:}, name };
if nboccur | (nboccur2>1)
arg2 = { arg{:}, name, {nboccur+1} };
else
arg2 = { arg{:}, name};
end
else
arg2 = arg;
end
s = sub_convert(tree,s,child(i),arg2);
end
if isempty(child)
s = sub_setfield(s,arg{:},'');
end
case 'chardata'
s = sub_setfield(s,arg{:},get(tree,uid,'value'));
case 'cdata'
s = sub_setfield(s,arg{:},get(tree,uid,'value'));
case 'pi'
% Processing instructions are evaluated if possible
app = get(tree,uid,'target');
switch app
case {'matlab',''}
s = sub_setfield(s,arg{:},eval(get(tree,uid,'value')));
case 'unix'
s = sub_setfield(s,arg{:},unix(get(tree,uid,'value')));
case 'dos'
s = sub_setfield(s,arg{:},dos(get(tree,uid,'value')));
case 'system'
s = sub_setfield(s,arg{:},system(get(tree,uid,'value')));
otherwise
try,
s = sub_setfield(s,arg{:},feval(app,get(tree,uid,'value')));
catch,
warning('[Xmltree/convert] Unknown target application');
end
end
case 'comment'
% Comments are forgotten
otherwise
warning(sprintf('Type %s unknown : not saved',get(tree,uid,'type')));
end
%=======================================================================
function s = sub_setfield(s,varargin)
% Same as setfield but using '{}' rather than '()'
%if (isempty(varargin) | length(varargin) < 2)
% error('Not enough input arguments.');
%end
subs = varargin(1:end-1);
for i = 1:length(varargin)-1
if (isa(varargin{i}, 'cell'))
types{i} = '{}';
elseif isstr(varargin{i})
types{i} = '.';
subs{i} = varargin{i}; %strrep(varargin{i},' ',''); % deblank field name
else
error('Inputs must be either cell arrays or strings.');
end
end
% Perform assignment
try
s = builtin('subsasgn', s, struct('type',types,'subs',subs), varargin{end});
catch
error(lasterr)
end
|
github
|
spm/spm5-master
|
find.m
|
.m
|
spm5-master/@xmltree/find.m
| 5,146 |
utf_8
|
1e2038bcaac9fe80c3213b6c35c7ee5d
|
function list = find(varargin)
% XMLTREE/FIND Find elements in a tree with specified characteristics
% FORMAT list = find(varargin)
%
% tree - XMLTree object
% xpath - string path with specific grammar (XPath)
% uid - lists of root uid's
% parameter/value - pair of pattern
% list - list of uid's of matched elements
%
% list = find(tree,xpath)
% list = find(tree,parameter,value[,parameter,value])
% list = find(tree,uid,parameter,value[,parameter,value])
%
% Grammar for addressing parts of an XML document:
% XML Path Language XPath (http://www.w3.org/TR/xpath)
% Example: /element1//element2[1]/element3[5]/element4
%_______________________________________________________________________
%
% Find elements in an XML tree with specified characteristics or given
% a path (using a subset of XPath language).
%_______________________________________________________________________
% @(#)find.m Guillaume Flandin 01/10/29
% TODO:
% - clean up subroutines
% - find should only be documented using XPath (other use is internal)
% - handle '*', 'last()' in [] and '@'
% - if a key is invalid, should rather return [] than error ?
if nargin==0
error('[XMLTree] A tree must be provided');
elseif nargin==1
list = 1:length(tree.tree);
return
elseif mod(nargin,2)
list = sub_find_subtree1(varargin{1}.tree,root(tree),varargin{2:end});
elseif isa(varargin{2},'double') & ...
ndims(varargin{2}) == 2 & ...
min(size(varargin{2})) == 1
list = unique(sub_find_subtree1(varargin{1}.tree,varargin{2:end}));
elseif nargin==2 & ischar(varargin{2})
list = sub_pathfinder(varargin{:});
else
error('[XMLTree] Arguments must be parameter/value pairs.');
end
%=======================================================================
function list = sub_find_subtree1(varargin)
list = [];
for i=1:length(varargin{2})
res = sub_find_subtree2(varargin{1},...
varargin{2}(i),varargin{3:end});
list = [list res];
end
%=======================================================================
function list = sub_find_subtree2(varargin)
uid = varargin{2};
list = [];
if sub_comp_element(varargin{1}{uid},varargin{3:end})
list = [list varargin{1}{uid}.uid];
end
if isfield(varargin{1}{uid},'contents')
list = [list sub_find_subtree1(varargin{1},...
varargin{1}{uid}.contents,varargin{3:end})];
end
%=======================================================================
function match = sub_comp_element(varargin)
match = 0;
try,
% v = getfield(varargin{1}, varargin{2}); % slow...
for i=1:floor(nargin/2)
v = subsref(varargin{1}, struct('type','.','subs',varargin{i+1}));
if strcmp(v,varargin{i+2})
match = 1;
end
end
catch,
end
% More powerful but much slower
%match = 0;
%for i=1:length(floor(nargin/2)) % bug: remove length !!!
% if isfield(varargin{1},varargin{i+1})
% if ischar(getfield(varargin{1},varargin{i+1})) & ischar(varargin{i+2})
% if strcmp(getfield(varargin{1},varargin{i+1}),char(varargin{i+2}))
% match = 1;
% end
% elseif isa(getfield(varargin{1},varargin{i+1}),'double') & ...
% isa(varargin{i+2},'double')
% if getfield(varargin{1},varargin{i+1}) == varargin{i+2}
% match = 1;
% end
% else
% warning('Cannot compare different objects');
% end
% end
%end
%=======================================================================
function list = sub_pathfinder(tree,pth)
%- Search for the delimiter '/' in the path
i = findstr(pth,'/');
%- Begin search by root
list = root(tree);
%- Walk through the tree
j = 1;
while j <= length(i)
%- Look for recursion '//'
if j<length(i) & i(j+1)==i(j)+1
recursive = 1;
j = j + 1;
else
recursive = 0;
end
%- Catch the current tag 'element[x]'
if j ~= length(i)
element = pth(i(j)+1:i(j+1)-1);
else
element = pth(i(j)+1:end);
end
%- Search for [] brackets
k = xml_findstr(element,'[',1,1);
%- If brackets are present in current element
if ~isempty(k)
l = xml_findstr(element,']',1,1);
val = str2num(element(k+1:l-1));
element = element(1:k-1);
end
%- Use recursivity
if recursive
list = find(tree,list,'name',element);
%- Just look at children
else
if i(j)==1 % if '/root/...' (list = root(tree) in that case)
if sub_comp_element(tree.tree{list},'name',element)
% list = 1; % list still contains root(tree)
else
list = [];
return;
end
else
list = sub_findchild(tree,list,element);
end
end
% If an element is specified using a key
if ~isempty(k)
if val < 1 | val > length(list)+1
error('[XMLTree] Bad key in the path.');
elseif val == length(list)+1
list = [];
return;
end
list = list(val);
end
if isempty(list), return; end
j = j + 1;
end
%=======================================================================
function list = sub_findchild(tree,listt,elmt)
list = [];
for a=1:length(listt)
for b=1:length(tree.tree{listt(a)}.contents)
if sub_comp_element(tree.tree{tree.tree{listt(a)}.contents(b)},'name',elmt)
list = [list tree.tree{tree.tree{listt(a)}.contents(b)}.uid];
end
end
end
|
github
|
spm/spm5-master
|
view.m
|
.m
|
spm5-master/@xmltree/view.m
| 5,879 |
utf_8
|
b26972066a91937d42a5bb86239b92e4
|
function view(tree)
% XMLTREE/VIEW View Method
% FORMAT view(tree)
%
% tree - XMLTree object
%_______________________________________________________________________
%
% Display an XML tree in a graphical interface
%_______________________________________________________________________
% @(#)view.m Guillaume Flandin 02/04/08
error(nargchk(1,1,nargin));
%-Build the Graphical User Interface
%-----------------------------------------------------------------------
figH = findobj('Tag','mlBatchFigure'); %this tag doesn't exist so a new
% window is created ....
if isempty(figH)
h = xmltree_build_ui;
figH = h.fig;
else
set(figH,'Visible','on');
% recover all the handles
% h = struct(...);
end
drawnow;
%-New title for the main window
%-----------------------------------------------------------------------
set(figH,'Name',['XML TreeViewer:' getfilename(tree)]);
%-Initialize batch listbox
%-----------------------------------------------------------------------
tree = set(tree,root(tree),'show',1);
builtin('set',figH,'UserData',tree);
view_ui('update',figH);
%=======================================================================
function handleStruct = xmltree_build_ui
%- Create Figure
pixfactor = 72 / get(0,'screenpixelsperinch');
%- Figure window size and position
oldRootUnits = get(0,'Units');
set(0, 'Units', 'points');
figurePos = get(0,'DefaultFigurePosition');
figurePos(3:4) = [560 420];
figurePos = figurePos * pixfactor;
rootScreenSize = get(0,'ScreenSize');
if ((figurePos(1) < 1) ...
| (figurePos(1)+figurePos(3) > rootScreenSize(3)))
figurePos(1) = 30;
end
set(0, 'Units', oldRootUnits);
if ((figurePos(2)+figurePos(4)+60 > rootScreenSize(4)) ...
| (figurePos(2) < 1))
figurePos(2) = rootScreenSize(4) - figurePos(4) - 60;
end
%- Create Figure Window
handleStruct.fig = figure(...
'Name','XML TreeViewer', ...
'Units', 'points', ...
'NumberTitle','off', ...
'Resize','on', ...
'Color',[0.8 0.8 0.8],...
'Position',figurePos, ...
'MenuBar','none', ...
'Tag', 'BatchFigure', ...
'CloseRequestFcn','view_ui close');
%- Build batch listbox
batchListPos = [20 55 160 345] * pixfactor;
batchString = ' ';
handleStruct.batchList = uicontrol( ...
'Parent',handleStruct.fig, ...
'Style', 'listbox', ...
'HorizontalAlignment','left', ...
'Units','points', ...
'Visible','on',...
'BackgroundColor', [1 1 1], ...
'Max', 1, ...
'Value', 1 , ...
'Enable', 'on', ...
'Position', batchListPos, ...
'Callback', 'view_ui batchlist', ...
'String', batchString, ...
'Tag', 'BatchListbox');
%- Build About listbox
aboutListPos = [200 220 340 180] * pixfactor;
aboutString = ' ';
handleStruct.aboutList = uicontrol( ...
'Parent',handleStruct.fig, ...
'Style', 'list', ...
'HorizontalAlignment','left', ...
'Units','points', ...
'Visible','on',...
'BackgroundColor', [0.8 0.8 0.8], ...
'Min', 0, ...
'Max', 2, ...
'Value', [], ...
'Enable', 'inactive', ...
'Position', aboutListPos, ...
'Callback', '', ...
'String', aboutString, ...
'Tag', 'AboutListbox');
%- The Add button
addBtnPos = [20 20 70 25] * pixfactor;
handleStruct.add = uicontrol( ...
'Parent',handleStruct.fig, ...
'Style', 'pushbutton', ...
'Units', 'points', ...
'Position', addBtnPos, ...
'String', 'Add', ...
'Visible', 'on', ...
'Enable','on',...
'Tag', 'Add', ...
'Callback', 'view_ui add');
%'TooltipString', 'Add batch', ...
%- The modify button
modifyBtnPos = [95 20 70 25] * pixfactor;
handleStruct.modify = uicontrol( ...
'Parent',handleStruct.fig, ...
'Style', 'pushbutton', ...
'Units', 'points', ...
'Position', modifyBtnPos, ...
'String', 'Modify', ...
'Visible', 'on', ...
'Enable','on',...
'Tag', 'Modify', ...
'Callback', 'view_ui modify');
%'TooltipString', 'Modify batch', ...
%- The Copy button
copyBtnPos = [170 20 70 25] * pixfactor;
handleStruct.copy = uicontrol( ...
'Parent',handleStruct.fig, ...
'Style', 'pushbutton', ...
'Units', 'points', ...
'Position', copyBtnPos, ...
'String', 'Copy', ...
'Visible', 'on', ...
'Enable','on',...
'Tag', 'Copy', ...
'Callback', 'view_ui copy');
%'TooltipString', 'Copy batch', ...
%- The delete button
deleteBtnPos = [245 20 70 25] * pixfactor;
handleStruct.delete = uicontrol( ...
'Parent',handleStruct.fig, ...
'Style', 'pushbutton', ...
'Units', 'points', ...
'Position', deleteBtnPos, ...
'String', 'Delete', ...
'Visible', 'on', ...
'Enable','on',...
'Tag', 'Delete', ...
'Callback', 'view_ui delete');
%'TooltipString', 'Delete batch', ...
%- The save button
saveBtnPos = [320 20 70 25] * pixfactor;
handleStruct.save = uicontrol( ...
'Parent',handleStruct.fig, ...
'Style', 'pushbutton', ...
'Units', 'points', ...
'Position', saveBtnPos, ...
'String', 'Save', ...
'Visible', 'on', ...
'UserData',0,...
'Tag', 'Save', ...
'Callback', 'view_ui save');
%'TooltipString', 'Save batch', ...
%- The run button
runBtnPos = [395 20 70 25] * pixfactor;
handleStruct.run = uicontrol( ...
'Parent',handleStruct.fig, ...
'Style', 'pushbutton', ...
'Units', 'points', ...
'Position', runBtnPos, ...
'String', 'Run', ...
'Visible', 'on', ...
'Enable', 'on', ...
'Tag', 'Run', ...
'Callback', 'view_ui run');
%'TooltipString', 'Run batch', ...
%- The close button
closeBtnPos = [470 20 70 25] * pixfactor;
handleStruct.close = uicontrol( ...
'Parent',handleStruct.fig, ...
'Style', 'pushbutton', ...
'Units', 'points', ...
'Position', closeBtnPos, ...
'String', 'Close', ...
'Visible', 'on', ...
'Tag', 'Close', ...
'Callback', 'view_ui close');
%'TooltipString', 'Close window', ...
handleArray = [handleStruct.fig handleStruct.batchList handleStruct.aboutList handleStruct.add handleStruct.modify handleStruct.copy handleStruct.delete handleStruct.save handleStruct.run handleStruct.close];
set(handleArray,'Units', 'normalized');
|
github
|
spm/spm5-master
|
xml_parser.m
|
.m
|
spm5-master/@xmltree/private/xml_parser.m
| 14,392 |
utf_8
|
0380cbf01ef44fad90326b3fd342a11d
|
function tree = xml_parser(xmlstr)
% XML (eXtensible Markup Language) Processor
% FORMAT tree = xml_parser(xmlstr)
%
% xmlstr - XML string to parse
% tree - tree structure corresponding to the XML file
%_______________________________________________________________________
%
% xml_parser.m is an XML 1.0 (http://www.w3.org/TR/REC-xml) parser
% written in Matlab. It aims to be fully conforming. It is currently not
% a validating XML processor.
%
% A description of the tree structure provided in output is detailed in
% the header of this m-file.
%_______________________________________________________________________
% @(#)xml_parser.m Guillaume Flandin 2002/04/04
% XML Processor for MATLAB (The Mathworks, Inc.).
% Copyright (C) 2002-2003 Guillaume Flandin <[email protected]>
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
%-----------------------------------------------------------------------
% Please feel free to email the author any comment/suggestion/bug report
% to improve this XML processor in Matlab.
% Email: <[email protected]>
% Check also the latest developments on the following webpage:
% http://www.artefact.tk/software/matlab/xml/
%-----------------------------------------------------------------------
% The implementation of this XML parser is much inspired from a
% Javascript parser available at http://www.jeremie.com/
% A mex-file xml_findstr.c is also required, to encompass some
% limitations of the built-in findstr Matlab function.
% Compile it on your architecture using 'mex -O xml_findstr.c' command
% if the compiled version for your system is not provided.
% If this function behaves badly (crash or wrong results), comment the
% line '#define __HACK_MXCHAR__' in xml_findstr.c and compile it again.
%-----------------------------------------------------------------------
% Structure of the output tree:
% There are 5 types of nodes in an XML file: element, chardata, cdata,
% pi and comment.
% Each of them contains an UID (Unique Identifier): an integer between
% 1 and the number of nodes of the XML file.
%
% element (a tag <name key="value"> [contents] </name>
% |_ type: 'element'
% |_ name: string
% |_ attributes: cell array of struct 'key' and 'value' or []
% |_ contents: double array of uid's or [] if empty
% |_ parent: uid of the parent ([] if root)
% |_ uid: double
%
% chardata (a character array)
% |_ type: 'chardata'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% cdata (a litteral string <![CDATA[value]]>)
% |_ type: 'cdata'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% pi (a processing instruction <?target value ?>)
% |_ type: 'pi'
% |_ target: string (may be empty)
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
% comment (a comment <!-- value -->)
% |_ type: 'comment'
% |_ value: string
% |_ parent: uid of the parent
% |_ uid: double
%
%-----------------------------------------------------------------------
% TODO/BUG/FEATURES:
% - [compile] only a warning if TagStart is empty ?
% - [attribution] should look for " and ' rather than only "
% - [main] with normalize as a preprocessing, CDATA are modified
% - [prolog] look for a DOCTYPE in the whole string even if it occurs
% only in a far CDATA tag, bug even if the doctype is inside a comment
% - [tag_element] erode should replace normalize here
% - remove globals? uppercase globals rather persistent (clear mfile)?
% - xml_findstr is indeed xml_strfind according to Mathworks vocabulary
% - problem with entities: do we need to convert them here? (é)
%-----------------------------------------------------------------------
%- XML string to parse and number of tags read
global xmlstring Xparse_count xtree;
%- Check input arguments
error(nargchk(1,1,nargin));
if isempty(xmlstr)
error('[XML] Not enough parameters.')
elseif ~isstr(xmlstr) | sum(size(xmlstr)>1)>1
error('[XML] Input must be a string.')
end
%- Initialize number of tags (<=> uid)
Xparse_count = 0;
%- Remove prolog and white space characters from the XML string
xmlstring = normalize(prolog(xmlstr));
%- Initialize the XML tree
xtree = {};
tree = fragment;
tree.str = 1;
tree.parent = 0;
%- Parse the XML string
tree = compile(tree);
%- Return the XML tree
tree = xtree;
%- Remove global variables from the workspace
clear global xmlstring Xparse_count xtree;
%=======================================================================
% SUBFUNCTIONS
%-----------------------------------------------------------------------
function frag = compile(frag)
global xmlstring xtree Xparse_count;
while 1,
if length(xmlstring)<=frag.str | ...
(frag.str == length(xmlstring)-1 & strcmp(xmlstring(frag.str:end),' '))
return
end
TagStart = xml_findstr(xmlstring,'<',frag.str,1);
if isempty(TagStart)
%- Character data
error(sprintf(['[XML] Unknown data at the end of the XML file.\n' ...
' Please send me your XML file at [email protected]']));
xtree{Xparse_count} = chardata;
xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:end)));
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
frag.str = '';
elseif TagStart > frag.str
if strcmp(xmlstring(frag.str:TagStart-1),' ')
%- A single white space before a tag (ignore)
frag.str = TagStart;
else
%- Character data
xtree{Xparse_count} = chardata;
xtree{Xparse_count}.value = erode(entity(xmlstring(frag.str:TagStart-1)));
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
frag.str = TagStart;
end
else
if strcmp(xmlstring(frag.str+1),'?')
%- Processing instruction
frag = tag_pi(frag);
else
if length(xmlstring)-frag.str>4 & strcmp(xmlstring(frag.str+1:frag.str+3),'!--')
%- Comment
frag = tag_comment(frag);
else
if length(xmlstring)-frag.str>9 & strcmp(xmlstring(frag.str+1:frag.str+8),'![CDATA[')
%- Litteral data
frag = tag_cdata(frag);
else
%- A tag element (empty (<.../>) or not)
if ~isempty(frag.end)
endmk = ['/' frag.end '>'];
else
endmk = '/>';
end
if strcmp(xmlstring(frag.str+1:frag.str+length(frag.end)+2),endmk) | ...
strcmp(strip(xmlstring(frag.str+1:frag.str+length(frag.end)+2)),endmk)
frag.str = frag.str + length(frag.end)+3;
return
else
frag = tag_element(frag);
end
end
end
end
end
end
%-----------------------------------------------------------------------
function frag = tag_element(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'>',frag.str,1);
if isempty(close)
error('[XML] Tag < opened but not closed.');
else
empty = strcmp(xmlstring(close-1:close),'/>');
if empty
close = close - 1;
end
starttag = normalize(xmlstring(frag.str+1:close-1));
nextspace = xml_findstr(starttag,' ',1,1);
attribs = '';
if isempty(nextspace)
name = starttag;
else
name = starttag(1:nextspace-1);
attribs = starttag(nextspace+1:end);
end
xtree{Xparse_count} = element;
xtree{Xparse_count}.name = strip(name);
if frag.parent
xtree{Xparse_count}.parent = frag.parent;
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
end
if length(attribs) > 0
xtree{Xparse_count}.attributes = attribution(attribs);
end
if ~empty
contents = fragment;
contents.str = close+1;
contents.end = name;
contents.parent = Xparse_count;
contents = compile(contents);
frag.str = contents.str;
else
frag.str = close+2;
end
end
%-----------------------------------------------------------------------
function frag = tag_pi(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'?>',frag.str,1);
if isempty(close)
warning('[XML] Tag <? opened but not closed.')
else
nextspace = xml_findstr(xmlstring,' ',frag.str,1);
xtree{Xparse_count} = pri;
if nextspace > close | nextspace == frag.str+2
xtree{Xparse_count}.value = erode(xmlstring(frag.str+2:close-1));
else
xtree{Xparse_count}.value = erode(xmlstring(nextspace+1:close-1));
xtree{Xparse_count}.target = erode(xmlstring(frag.str+2:nextspace));
end
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+2;
end
%-----------------------------------------------------------------------
function frag = tag_comment(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,'-->',frag.str,1);
if isempty(close)
warning('[XML] Tag <!-- opened but not closed.')
else
xtree{Xparse_count} = comment;
xtree{Xparse_count}.value = erode(xmlstring(frag.str+4:close-1));
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+3;
end
%-----------------------------------------------------------------------
function frag = tag_cdata(frag)
global xmlstring xtree Xparse_count;
close = xml_findstr(xmlstring,']]>',frag.str,1);
if isempty(close)
warning('[XML] Tag <![CDATA[ opened but not closed.')
else
xtree{Xparse_count} = cdata;
xtree{Xparse_count}.value = xmlstring(frag.str+9:close-1);
if frag.parent
xtree{frag.parent}.contents = [xtree{frag.parent}.contents Xparse_count];
xtree{Xparse_count}.parent = frag.parent;
end
frag.str = close+3;
end
%-----------------------------------------------------------------------
function all = attribution(str)
%- Initialize attributs
nbattr = 0;
all = cell(nbattr);
%- Look for 'key="value"' substrings
while 1,
eq = xml_findstr(str,'=',1,1);
if isempty(str) | isempty(eq), return; end
id = xml_findstr(str,'"',1,1); % should also look for ''''
nextid = xml_findstr(str,'"',id+1,1);% rather than only '"'
nbattr = nbattr + 1;
all{nbattr}.key = strip(str(1:(eq-1)));
all{nbattr}.val = entity(str((id+1):(nextid-1)));
str = str((nextid+1):end);
end
%-----------------------------------------------------------------------
function elm = element
global Xparse_count;
Xparse_count = Xparse_count + 1;
elm = struct('type','element','name','','attributes',[],'contents',[],'parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function cdat = chardata
global Xparse_count;
Xparse_count = Xparse_count + 1;
cdat = struct('type','chardata','value','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function cdat = cdata
global Xparse_count;
Xparse_count = Xparse_count + 1;
cdat = struct('type','cdata','value','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function proce = pri
global Xparse_count;
Xparse_count = Xparse_count + 1;
proce = struct('type','pi','value','','target','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function commt = comment
global Xparse_count;
Xparse_count = Xparse_count + 1;
commt = struct('type','comment','value','','parent',[],'uid',Xparse_count);
%-----------------------------------------------------------------------
function frg = fragment
frg = struct('str','','parent','','end','');
%-----------------------------------------------------------------------
function str = prolog(str)
%- Initialize beginning index of elements tree
b = 1;
%- Initial tag
start = xml_findstr(str,'<',1,1);
if isempty(start)
error('[XML] No tag found.')
end
%- Header (<?xml version="1.0" ... ?>)
if strcmp(lower(str(start:start+2)),'<?x')
close = xml_findstr(str,'?>',1,1);
if ~isempty(close)
b = close + 2;
else
warning('[XML] Header tag incomplete.')
end
end
%- Doctype (<!DOCTYPE type ... [ declarations ]>)
start = xml_findstr(str,'<!DOCTYPE',b,1); % length('<!DOCTYPE') = 9
if ~isempty(start)
close = xml_findstr(str,'>',start+9,1);
if ~isempty(close)
b = close + 1;
dp = xml_findstr(str,'[',start+9,1);
if (~isempty(dp) & dp < b)
k = xml_findstr(str,']>',start+9,1);
if ~isempty(k)
b = k + 2;
else
warning('[XML] Tag [ in DOCTYPE opened but not closed.')
end
end
else
warning('[XML] Tag DOCTYPE opened but not closed.')
end
end
%- Skip prolog from the xml string
str = str(b:end);
%-----------------------------------------------------------------------
function str = strip(str)
a = isspace(str);
a = find(a==1);
str(a) = '';
%-----------------------------------------------------------------------
function str = normalize(str)
% Find white characters (space, newline, carriage return, tabs, ...)
i = isspace(str);
i = find(i == 1);
str(i) = ' ';
% replace several white characters by only one
if ~isempty(i)
j = i - [i(2:end) i(end)];
k = find(j == -1);
str(i(k)) = [];
end
%-----------------------------------------------------------------------
function str = entity(str)
str = strrep(str,'<','<');
str = strrep(str,'>','>');
str = strrep(str,'"','"');
str = strrep(str,''','''');
str = strrep(str,'&','&');
%-----------------------------------------------------------------------
function str = erode(str)
if ~isempty(str) & str(1)==' ' str(1)=''; end;
if ~isempty(str) & str(end)==' ' str(end)=''; end;
|
github
|
spm/spm5-master
|
subsasgn.m
|
.m
|
spm5-master/@nifti/subsasgn.m
| 14,575 |
utf_8
|
256d2fbe8798c850072f351ebee682ed
|
function obj = subsasgn(obj,subs,varargin)
% Subscript assignment
% See subsref for meaning of fields.
% _______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: subsasgn.m 253 2005-10-13 15:31:34Z 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 = class(objs(i),'nifti');
obji = fun(obji,subs,val);
objs(i) = struct(obji);
end;
obj = class(objs,'nifti');
case {'()'},
objs = struct(obj);
if length(subs)>1,
t = subsref(objs,subs(1));
% A lot of this stuff is a little flakey, and may cause Matlab to bomb.
%
%if numel(t) ~= nargin-2,
% error('The number of outputs should match the number of inputs.');
%end;
for i=1:numel(t),
val = varargin{1};
obji = class(t(i),'nifti');
obji = subsasgn(obji,subs(2:end),val);
t(i) = struct(obji);
end;
objs = subsasgn(objs,subs(1),t);
else
if numel(varargin)>1,
error('Illegal right hand side in assignment. Too many elements.');
end;
val = varargin{1};
if isa(val,'nifti'),
objs = subsasgn(objs,subs,struct(val));
elseif isempty(val),
objs = subsasgn(objs,subs,[]);
else
error('Assignment between unlike types is not allowed.');
end;
end;
obj = class(objs,'nifti');
otherwise
error('Cell contents reference from a non-cell array object.');
end;
return;
%=======================================================================
%=======================================================================
function obj = fun(obj,subs,val)
% Subscript referencing
switch subs(1).type,
case {'.'},
objs = struct(obj);
for ii=1:numel(objs)
obj = objs(ii);
if any(strcmpi(subs(1).subs,{'dat'})),
if length(subs)>1,
val = subsasgn(obj.dat,subs(2:end),val);
end;
obj = assigndat(obj,val);
objs(ii) = obj;
continue;
end;
if isempty(obj.hdr), obj.hdr = empty_hdr; end;
if ~isfield(obj.hdr,'magic'), error('Not a NIFTI-1 header'); end;
if length(subs)>1, % && ~strcmpi(subs(1).subs,{'raw','dat'}),
val0 = subsref(class(obj,'nifti'),subs(1));
val1 = subsasgn(val0,subs(2:end),val);
else
val1 = val;
end;
switch(subs(1).subs)
case {'extras'}
if length(subs)>1,
obj.extras = subsasgn(obj.extras,subs(2:end),val);
else
obj.extras = val;
end;
case {'mat0'}
if ~isnumeric(val1) || ndims(val1)~=2 || any(size(val1)~=[4 4]) || sum((val1(4,:)-[0 0 0 1]).^2)>1e-8,
error('"mat0" should be a 4x4 matrix, with a last row of 0,0,0,1.');
end;
if obj.hdr.qform_code==0, obj.hdr.qform_code=2; end;
s = double(bitand(obj.hdr.xyzt_units,7));
if s
d = findindict(s,'units');
val1 = diag([[1 1 1]/d.rescale 1])*val1;
end;
obj.hdr = encode_qform0(double(val1), obj.hdr);
case {'mat0_intent'}
if isempty(val1),
obj.hdr.qform_code = 0;
else
if ~ischar(val1) && ~(isnumeric(val1) && numel(val1)==1),
error('"mat0_intent" should be a string or a scalar.');
end;
d = findindict(val1,'xform');
if ~isempty(d)
obj.hdr.qform_code = d.code;
end;
end;
case {'mat'}
if ~isnumeric(val1) || ndims(val1)~=2 || any(size(val1)~=[4 4]) || sum((val1(4,:)-[0 0 0 1]).^2)>1e-8
error('"mat" should be a 4x4 matrix, with a last row of 0,0,0,1.');
end;
if obj.hdr.sform_code==0, obj.hdr.sform_code=2; end;
s = double(bitand(obj.hdr.xyzt_units,7));
if s
d = findindict(s,'units');
val1 = diag([[1 1 1]/d.rescale 1])*val1;
end;
val1 = val1 * [eye(4,3) [1 1 1 1]'];
obj.hdr.srow_x = val1(1,:);
obj.hdr.srow_y = val1(2,:);
obj.hdr.srow_z = val1(3,:);
case {'mat_intent'}
if isempty(val1),
obj.hdr.sform_code = 0;
else
if ~ischar(val1) && ~(isnumeric(val1) && numel(val1)==1),
error('"mat_intent" should be a string or a scalar.');
end;
d = findindict(val1,'xform');
if ~isempty(d),
obj.hdr.sform_code = d.code;
end;
end;
case {'intent'}
if ~valid_fields(val1,{'code','param','name'})
obj.hdr.intent_code = 0;
obj.hdr.intent_p1 = 0;
obj.hdr.intent_p2 = 0;
obj.hdr.intent_p3 = 0;
obj.hdr.intent_name = '';
else
if ~isfield(val1,'code'),
val1.code = obj.hdr.intent_code;
end;
d = findindict(val1.code,'intent');
if ~isempty(d),
obj.hdr.intent_code = d.code;
if isfield(val1,'param'),
prm = [double(val1.param(:)) ; 0 ; 0; 0];
prm = [prm(1:length(d.param)) ; 0 ; 0; 0];
obj.hdr.intent_p1 = prm(1);
obj.hdr.intent_p2 = prm(2);
obj.hdr.intent_p3 = prm(3);
end;
if isfield(val1,'name'),
obj.hdr.intent_name = val1.name;
end;
end;
end;
case {'diminfo'}
if ~valid_fields(val1,{'frequency','phase','slice','slice_time'})
tmp = obj.hdr.dim_info;
for bit=1:6,
tmp = bitset(tmp,bit,0);
end;
obj.hdr.dim_info = tmp;
obj.hdr.slice_start = 0;
obj.hdr.slice_end = 0;
obj.hdr.slice_duration = 0;
obj.hdr.slice_code = 0;
else
if isfield(val1,'frequency'),
tmp = val1.frequency;
if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3,
error('Invalid frequency direction');
end;
obj.hdr.dim_info = bitset(obj.hdr.dim_info,1,bitget(tmp,1));
obj.hdr.dim_info = bitset(obj.hdr.dim_info,2,bitget(tmp,2));
end;
if isfield(val1,'phase'),
tmp = val1.phase;
if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3,
error('Invalid phase direction');
end;
obj.hdr.dim_info = bitset(obj.hdr.dim_info,3,bitget(tmp,1));
obj.hdr.dim_info = bitset(obj.hdr.dim_info,4,bitget(tmp,2));
end;
if isfield(val1,'slice'),
tmp = val1.slice;
if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3,
error('Invalid slice direction');
end;
obj.hdr.dim_info = bitset(obj.hdr.dim_info,5,bitget(tmp,1));
obj.hdr.dim_info = bitset(obj.hdr.dim_info,6,bitget(tmp,2));
end;
if isfield(val1,'slice_time')
tim = val1.slice_time;
if ~valid_fields(tim,{'start','end','duration','code'}),
obj.hdr.slice_code = 0;
obj.hdr.slice_start = 0;
obj.hdr.end_slice = 0;
obj.hdr.slice_duration = 0;
else
% sld = double(bitget(obj.hdr.dim_info,5)) + 2*double(bitget(obj.hdr.dim_info,6));
if isfield(tim,'start'),
ss = double(tim.start);
if isnumeric(ss) && numel(ss)==1 && ~rem(ss,1), % && ss>=1 && ss<=obj.hdr.dim(sld+1)
obj.hdr.slice_start = ss-1;
else
error('Inappropriate "slice_time.start".');
end;
end;
if isfield(tim,'end'),
ss = double(tim.end);
if isnumeric(ss) && numel(ss)==1 && ~rem(ss,1), % && ss>=1 && ss<=obj.hdr.dim(sld+1)
obj.hdr.slice_end = ss-1;
else
error('Inappropriate "slice_time.end".');
end;
end;
if isfield(tim,'duration')
sd = double(tim.duration);
if isnumeric(sd) && numel(sd)==1,
s = double(bitand(obj.hdr.xyzt_units,24));
d = findindict(s,'units');
if ~isempty(d) && d.rescale, sd = sd/d.rescale; end;
obj.hdr.slice_duration = sd;
else
error('Inappropriate "slice_time.duration".');
end;
end;
if isfield(tim,'code'),
d = findindict(tim.code,'sliceorder');
if ~isempty(d),
obj.hdr.slice_code = d.code;
end;
end;
end;
end;
end;
case {'timing'}
if ~valid_fields(val1,{'toffset','tspace'}),
obj.hdr.pixdim(5) = 0;
obj.hdr.toffset = 0;
else
s = double(bitand(obj.hdr.xyzt_units,24));
d = findindict(s,'units');
if isfield(val1,'toffset'),
if isnumeric(val1.toffset) && numel(val1.toffset)==1,
if d.rescale,
val1.toffset = val1.toffset/d.rescale;
end;
obj.hdr.toffset = val1.toffset;
else
error('"timing.toffset" needs to be numeric with 1 element');
end;
end;
if isfield(val1,'tspace'),
if isnumeric(val1.tspace) && numel(val1.tspace)==1,
if d.rescale,
val1.tspace = val1.tspace/d.rescale;
end;
obj.hdr.pixdim(5) = val1.tspace;
else
error('"timing.tspace" needs to be numeric with 1 element');
end;
end;
end;
case {'descrip'}
if isempty(val1), val1 = char(val1); end;
if ischar(val1),
obj.hdr.descrip = val1;
else
error('"descrip" must be a string.');
end;
case {'cal'}
if isempty(val1),
obj.hdr.cal_min = 0;
obj.hdr.cal_max = 0;
else
if isnumeric(val1) && numel(val1)==2,
obj.hdr.cal_min = val1(1);
obj.hdr.cal_max = val1(2);
else
error('"cal" should contain two elements.');
end;
end;
case {'aux_file'}
if isempty(val1), val1 = char(val1); end;
if ischar(val1),
obj.hdr.aux_file = val1;
else
error('"aux_file" must be a string.');
end;
case {'hdr'}
error('hdr is a read-only field.');
obj.hdr = val1;
otherwise
error(['Reference to non-existent field ''' subs(1).subs '''.']);
end;
objs(ii) = obj;
end
obj = class(objs,'nifti');
otherwise
error('This should not happen.');
end;
return;
%=======================================================================
%=======================================================================
function obj = assigndat(obj,val)
if isa(val,'file_array'),
sz = size(val);
if numel(sz)>8,
error('Too many dimensions in data.');
end;
sz = [sz 1 1 1 1 1 1 1 1];
sz = sz(1:8);
sval = struct(val);
d = findindict(sval.dtype,'dtype');
if isempty(d)
error(['Unknown datatype (' num2str(double(sval.datatype)) ').']);
end;
[pth,nam,suf] = fileparts(sval.fname);
if any(strcmp(suf,{'.img','.IMG'}))
val.offset = max(sval.offset,0);
obj.hdr.magic = 'ni1';
elseif any(strcmp(suf,{'.nii','.NII'}))
val.offset = max(sval.offset,352);
obj.hdr.magic = 'n+1';
else
error(['Unknown filename extension (' suf ').']);
end;
val.offset = (ceil(val.offset/16))*16;
obj.hdr.vox_offset = val.offset;
obj.hdr.dim(2:(numel(sz)+1)) = sz;
nd = max(find(obj.hdr.dim(2:end)>1));
if isempty(nd), nd = 3; end;
obj.hdr.dim(1) = nd;
obj.hdr.datatype = sval.dtype;
obj.hdr.bitpix = d.size*8;
if ~isempty(sval.scl_slope), obj.hdr.scl_slope = sval.scl_slope; end;
if ~isempty(sval.scl_inter), obj.hdr.scl_inter = sval.scl_inter; end;
obj.dat = val;
else
error('"raw" must be of class "file_array"');
end;
return;
function ok = valid_fields(val,allowed)
if isempty(val), ok = false; return; end;
if ~isstruct(val),
error(['Expecting a structure, not a ' class(val) '.']);
end;
fn = fieldnames(val);
for ii=1:length(fn),
if ~any(strcmpi(fn{ii},allowed)),
fprintf('Allowed fieldnames are:\n');
for i=1:length(allowed), fprintf(' %s\n', allowed{i}); end;
error(['"' fn{ii} '" is not a valid fieldname.']);
end
end
ok = true;
return;
|
github
|
spm/spm5-master
|
subsref.m
|
.m
|
spm5-master/@nifti/subsref.m
| 8,769 |
utf_8
|
bfbe7ae31dda7943ef4df18002640485
|
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) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: subsref.m 253 2005-10-13 15:31:34Z 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 = class(opts(ii),'nifti');
%if ~isstruct(opt)
% error('Attempt to reference field of non-structure array.');
%end;
h = opt.hdr;
if isempty(h),
%error('No header.');
h = empty_hdr;
end;
% NIFTI-1 FORMAT
switch(subs(1).subs)
case 'extras',
t = opt.extras;
case 'raw', % A hidden field
if isa(opt.dat,'file_array'),
tmp = struct(opt.dat);
tmp.scl_slope = [];
tmp.scl_inter = [];
t = file_array(tmp);
else
t = opt.dat;
end;
case 'dat',
t = opt.dat;
case 'mat0',
t = decode_qform0(h);
s = double(bitand(h.xyzt_units,7));
if s
d = findindict(s,'units');
if ~isempty(d)
t = diag([d.rescale*[1 1 1] 1])*t;
end;
end;
case 'mat0_intent',
d = findindict(h.qform_code,'xform');
if isempty(d) || d.code==0,
t = '';
else
t = d.label;
end;
case 'mat',
if h.sform_code > 0
t = double([h.srow_x ; h.srow_y ; h.srow_z ; 0 0 0 1]);
t = t * [eye(4,3) [-1 -1 -1 1]'];
else
t = decode_qform0(h);
end
s = double(bitand(h.xyzt_units,7));
if s
d = findindict(s,'units');
t = diag([d.rescale*[1 1 1] 1])*t;
end;
case 'mat_intent',
if h.sform_code>0,
t = h.sform_code;
else
t = h.qform_code;
end;
d = findindict(t,'xform');
if isempty(d) || d.code==0,
t = '';
else
t = d.label;
end;
case 'intent',
d = findindict(h.intent_code,'intent');
if isempty(d) || d.code == 0,
%t = struct('code','UNKNOWN','param',[]);
t = [];
else
t = struct('code',d.label,'param',...
double([h.intent_p1 h.intent_p2 h.intent_p3]), 'name',deblank(h.intent_name));
t.param = t.param(1:length(d.param));
end
case 'diminfo',
t = [];
tmp = bitand( h.dim_info ,3); if tmp, t.frequency = double(tmp); end;
tmp = bitand(bitshift(h.dim_info,-2),3); if tmp, t.phase = double(tmp); end;
tmp = bitand(bitshift(h.dim_info,-4),3); if tmp, t.slice = double(tmp); end;
% t = struct('frequency',bitand( h.dim_info ,3),...
% 'phase',bitand(bitshift(h.dim_info,-2),3),...
% 'slice',bitand(bitshift(h.dim_info,-4),3))
if isfield(t,'slice')
sc = double(h.slice_code);
ss = double(h.slice_start)+1;
se = double(h.slice_end)+1;
ss = max(ss,1);
se = min(se,double(h.dim(t.slice+1)));
sd = double(h.slice_duration);
s = double(bitand(h.xyzt_units,24));
d = findindict(s,'units');
if d.rescale, sd = sd*d.rescale; end;
ns = (se-ss+1);
d = findindict(sc,'sliceorder');
if isempty(d)
label = 'UNKNOWN';
else
label = d.label;
end;
t.slice_time = struct('code',label,'start',ss,'end',se,'duration',sd);
if 0, % Never
t.times = zeros(1,double(h.dim(t.slice+1)))+NaN;
switch sc,
case 0, % Unknown
t.times(ss:se) = zeros(1,ns);
case 1, % sequential increasing
t.times(ss:se) = (0:(ns-1))*sd;
case 2, % sequential decreasing
t.times(ss:se) = ((ns-1):-1:0)*sd;
case 3, % alternating increasing
t.times(ss:2:se) = (0:floor((ns+1)/2-1))*sd;
t.times((ss+1):2:se) = (floor((ns+1)/2):(ns-1))*sd;
case 4, % alternating decreasing
t.times(se:-2:ss) = (0:floor((ns+1)/2-1))*sd;
t.times(se:-2:(ss+1)) = (floor((ns+1)/2):(ns-1))*sd;
end;
end;
end;
case 'timing',
to = double(h.toffset);
dt = double(h.pixdim(5));
if to==0 && dt==0,
t = [];
else
s = double(bitand(h.xyzt_units,24));
d = findindict(s,'units');
if d.rescale,
to = to*d.rescale;
dt = dt*d.rescale;
end;
t = struct('toffset',to,'tspace',dt);
end;
case 'descrip',
t = deblank(h.descrip);
msk = find(t==0);
if any(msk), t=t(1:(msk(1)-1)); end;
case 'cal',
t = [double(h.cal_min) double(h.cal_max)];
if all(t==0), t = []; end;
case 'aux_file',
t = deblank(h.aux_file);
case 'hdr', % Hidden field
t = h;
otherwise
error(['Reference to non-existent field ''' subs(1).subs '''.']);
end;
if numel(subs)>1,
t = subsref(t,subs(2:end));
end;
c{ii} = t;
end;
case {'{}'},
error('Cell contents reference from a non-cell array object.');
case {'()'},
opt = struct(opt);
t = subsref(opt,subs(1));
if length(subs)>1
c = {};
for i=1:numel(t),
ti = class(t(i),'nifti');
ti = rec(ti,subs(2:end));
c = {c{:}, ti{:}};
end;
else
c = {class(t,'nifti')};
end;
otherwise
error('This should not happen.');
end;
|
github
|
spm/spm5-master
|
create.m
|
.m
|
spm5-master/@nifti/create.m
| 1,968 |
utf_8
|
97e3c7636daec569ac9ade7c101a9def
|
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) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: create.m 433 2006-02-09 11:45:02Z john $
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
|
spm/spm5-master
|
getdict.m
|
.m
|
spm5-master/@nifti/private/getdict.m
| 5,236 |
utf_8
|
6ec804a6aefae92058e49a769c0ad025
|
function d = getdict
% Dictionary of NIFTI stuff
% _______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: getdict.m 253 2005-10-13 15:31:34Z guillaume $
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
|
spm/spm5-master
|
write_extras.m
|
.m
|
spm5-master/@nifti/private/write_extras.m
| 881 |
utf_8
|
f911d8116ee0db4474b22d4770ac0522
|
function extras = write_extras(fname,extras)
% Write extra bits of information
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: write_extras.m 473 2006-03-08 18:11:59Z john $
[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
|
mu-diff/mu-diff-master
|
FourierTruncation.m
|
.m
|
mu-diff-master/PreProcessing/Fourier/FourierTruncation.m
| 1,743 |
utf_8
|
3dc13ddb18ac350c223e698a55cd7138
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the N_p parameters for the Fourier series truncation.
% --------------------------------------------------------------
% M_modes = FourierTruncation(a, k)
%
% Input arguments:
% ----------------
%
% a [1 x N_scat] : Radii of the circular obstacles
% k [1 x 1] : wavenumber in the vacuum
% or [1 x N_scat] or in the obstacles
%
% Output arguments:
% -----------------
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
%
% Options:
% --------
% 1) M_modes = FourierTruncation(..., 'Min', MIN_VALUE)
% Set a minimal value for M_modes (default = 0)
%
% 2) M_modes = FourierTruncation(..., 'Tol', TOL)
% Set the tolerance in the formula to TOL
%
function M_modes = FourierTruncation(a, k, varargin)
N_scat = length(a);
nvarargin = length(varargin);
cpt_arg = 1;
MIN_VALUE = 0;
tolM = 10.^(-10);
while(cpt_arg <= nvarargin)
if(strcmp(varargin{cpt_arg}, 'Min'))
MIN_VALUE = varargin{cpt_arg + 1};
cpt_arg = cpt_arg +2;
elseif(strcmp(varargin{cpt_arg}, 'Tol'))
tolM = varargin{cpt_arg + 1};
cpt_arg = cpt_arg +2;
else
cpt_arg = cpt_arg +1;
end
end
M_modes = max(MIN_VALUE*ones(1,N_scat), max([2^2*ones(1,N_scat); floor(k.*a + (1/(2*sqrt(2))*log(2*sqrt(2)*pi*k.*a/tolM)).^(2/3).*(k.*a).^(1/3) +1)]));
end
|
github
|
mu-diff/mu-diff-master
|
CreateRandomDisks.m
|
.m
|
mu-diff-master/PreProcessing/Geometry/CreateRandomDisks.m
| 5,912 |
utf_8
|
fb6e9f420d87e58f281ba463962d828e
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Create and randomly distribue N_scat disks, with random centers and random radii inside the bos [xmin, xmax]x[ymin, ymax].
% [O, a] = CreateRandomDisks(xmin, xmax, ymin, ymax, N_scat, ...)
%
% Input Arguments:
% ----------------
% - xmin [1x1] : minimal abscissa limit of the box
% - xmax [1x1] : maximal abscissa limit of the box
% - ymin [1x1] : minimal ordinate limit of the box
% - ymax [1x1] : maximal ordinate limit of the box
% - N_scat [1x1] : number of desired circular scatterers
%
% Output Arguments:
% -----------------
% - O [2xN_scat] : coordinates of the center of the circular obstacles
% - a [1xN_scat] : radii of the obstacles
%
% OPTIONS :
% ---------
% [O, a] = CreateRandomDisks(xmin, xmax, ymin, ymax, N_scat, amin, amax,
% dmin, dmax, O_avoid, a_void, dmin_avoid, dmax_avoid)
% value name (default value) [size] : description
% - amin (=1) [1x1] : minimal radius of the disk
% - amax (=1) [1x1] : maximal radius of the disk
% - dmin (=realmin) [1x1] : minimal distance between two disks
% - dmax (=realmax) [1x1] : maximal distance between two disks (Carreful with this option!)
% - O_avoid [2xN] : center of N disks (possibly of zero-radius) that must stay out
% of every scatterers
% - a_avoid [1xN] : radii of the disks of center O_avoid
% - dmin [1x1] : minimal distance that disks must kept from the other disks (O_avoid, a_void)
% - dmin [1x1] : maximal distance that disks must kept from the other disks (O_avoid, a_void)
%
% Remarks:
% --------
% - if (dmax <= 0) then dmax = realmax (no limit)
% - if (dmin <= 0) then dmin = realmin (no limit)
% - Same for dmin_avoid and dmax_avoid
% - Be carreful with dmax. It is not the distance between the closest disk,
% but with ALL OTHER disks.
% - 1000 trials are done to place a disk. If after 1000 trials, a new disk
% cannot be inserted, the function assumes that it is impossible and an
% error message is returned.
function [O, a] = CreateRandomDisks(xmin, xmax, ymin, ymax, N_scat, varargin)
%Maximum number of trial (security)
trial_max = 1000;
%Initialization
O = zeros(2,N_scat);
a = zeros(1,N_scat);
amin = 1;
amax = 1;
dmin = realmin;
dmax = realmax;
O_avoid = [];
a_avoid = [];
dmin_avoid = realmin;
dmax_avoid = realmax;
%Reading arguments
opt_argin = length(varargin);
if(opt_argin >= 1) % Setting a minimal radius
amin = varargin{1};
end
if(opt_argin >= 2) % Setting a maximal radius
amax = varargin{2};
end
if(opt_argin >= 3) % Setting a minimal distance between two disks
dmin = varargin{3};
end
if(opt_argin >= 4) % Setting a maximal distance between two disks
dmax = varargin{4};
end
if(opt_argin >= 5) % Points to avoided (point source,...) ...
O_avoid = varargin{5}; % coordinates of the points to be avoided
end
if(opt_argin >= 6)% ... or not points but disks ! (for maybe old disks)
a_avoid = varargin{6}; % radii of the disks to be avoided
end
if(opt_argin >= 7)% dmin for the avoiding point/disks
dmin_avoid = varargin{7};
end
if(opt_argin >= 8)% dmax for the avoiding point/disks
dmax_avoid = varargin{8};
end
%Verification
if(amin > amax)
aux = amin;
amin = amax;
amax = aux;
warning('amin was greater than amax, exchanging values...');
end
if(dmax <=0)
dmax = realmax;
end
if(~isempty(O_avoid) && isempty(a_avoid))
a_avoid=zeros(1,size(O_avoid,2));
end
% Placement
for p = 1:N_scat
trial = 1;
[centre_new, radius_new] = BuildRandomDisk(xmin, xmax, ymin, ymax, amin, amax);
isOK = testDistance(O(:,1:p-1), a(1:p-1), xmin, xmax, ymin, ymax, dmin, dmax, centre_new, radius_new, O_avoid, a_avoid, dmin_avoid, dmax_avoid);
while ( ~isOK && trial < trial_max)
[centre_new, radius_new] = BuildRandomDisk(xmin, xmax, ymin, ymax, amin, amax);
isOK = testDistance(O(:,1:p-1), a(1:p-1), xmin, xmax, ymin, ymax, dmin, dmax, centre_new, radius_new, O_avoid, a_avoid, dmin_avoid, dmax_avoid);
trial = trial+1;
end
if (trial == trial_max)
error(['Cannot place obstacle number ',num2str(p)]);
end
%Obstacle is ok to be placed !
O(:,p) = centre_new;
a(p) = radius_new;
end
end
%%
%
function [centre_new, radius_new] = BuildRandomDisk(xmin, xmax, ymin, ymax, amin, amax)
real_xmin = xmin + amin;
real_xmax = xmax - amin;
real_ymin = ymin + amin;
real_ymax = ymax - amin;
x = real_xmin + (real_xmax - real_xmin).*rand(1,1);
y = real_ymin + (real_ymax - real_ymin).*rand(1,1);
%A possibly new disk:
centre_new = [x;y];
radius_new = amin + (amax - amin).*rand(1,1);
end
%%
function isOK = testDistance(O, a, xmin, xmax, ymin, ymax, dmin, dmax, centre_new, radius_new, O_avoid, a_avoid, dmin_avoid, dmax_avoid)
OO = [O, O_avoid];
aa = [a, a_avoid];
x = centre_new(1);
y = centre_new(2);
test_dist = CheckPlacement(OO, aa, dmin, dmax, centre_new, radius_new);
test_xmin = (x - radius_new >= xmin);
test_xmax = (x + radius_new <= xmax);
test_ymin = (y - radius_new >= ymin);
test_ymax = (y + radius_new <= ymax);
isOK = test_xmin*test_xmax*test_ymin*test_ymax*test_dist;
end
|
github
|
mu-diff/mu-diff-master
|
RemoveDisk.m
|
.m
|
mu-diff-master/PreProcessing/Geometry/RemoveDisk.m
| 3,832 |
utf_8
|
4bc04503c65ce423fcf27e5b6dac007c
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Remove some centers of disks from the matrix O
% ----------------------------------------------------------
% [O,a] = RemoveDisk(O, ...)
%
% Input (N_scat = number of obstacle = length(a))
% -----
% O_old [2 x N_scat_old] : Matrix of the coordinates of the center of the
% scatterers
% a_old [1 x N_scat_old] : Vector of the radii of the disks
%
% Output
% ------
% O [2 x N_scat] : Matrix of the coordinates of the center of the
% scatterers
% a [1 x N_scat_old] : Vector of the radii of the disks
%
% Options:
% --------
%
% [O,a] = RemoveDisk(..., 'X', [X1, X2, ..., XN])
% Remove all the points with X abscissa X1, X2, ..., or XN
%
% [O,a] = RemoveDisk(..., 'Y', [Y1, Y2, ..., YN])
% Remove all the points with Y ordinate Y1, Y2, ..., or YN
%
% [O,a] = RemoveDisk(..., 'XY', [[X1;Y1], [X2;Y2], ..., [XN;YN]])
% Remove all the points [X1;Y1], [X2;Y2], ..., and [XN;YN]
%
% [O,a] = RemoveDisk(..., 'Radius', [a1, a2, ..., aN])
% Remove all the disk with radius a1, a2, ..., or aN
%
% [O,a] = RemoveDisk(..., 'Verbosity', VERBOSITY)
% set VERBOSITY to 0 to avoid display message, to 1 to only show results,
% and to > 1 to see everything (default).
%
% See also CreateRandomDisks, RectangularLattice, TriangularLattice
function [O,a] = RemoveDisk(O_old, a_old, varargin)
Tol = 10^(-10);
X_to_avoid = [];
Y_to_avoid = [];
XY_to_avoid = [];
a_to_avoid = [];
nvarargin = length(varargin);
cpt_arg = 1;
VERBOSITY =2;
while(cpt_arg <= nvarargin)
if(strcmp(varargin{cpt_arg}, 'X'))
X_to_avoid = [X_to_avoid, varargin{cpt_arg+1}];
cpt_arg = cpt_arg+2;
elseif(strcmp(varargin{cpt_arg}, 'Y'))
Y_to_avoid = [Y_to_avoid, varargin{cpt_arg+1}];
cpt_arg = cpt_arg+2;
elseif(strcmp(varargin{cpt_arg}, 'XY'))
XY = varargin{cpt_arg+1};
XY_to_avoid = [XY_to_avoid, [XY(1);XY(2)]];
cpt_arg = cpt_arg+2;
elseif(strcmp(varargin{cpt_arg}, 'Radius'))
a_to_avoid = [a_to_avoid, varargin{cpt_arg+1}];
cpt_arg = cpt_arg+2;
elseif(strcmp(varargin{cpt_arg}, 'Verbosity'))
VERBOSITY = varargin{cpt_arg+1};
cpt_arg = cpt_arg+2;
end
end
N_scat_old = size(O_old,2);
N_scat_delete = 0;
N_scat = 0;
O = [];
a = [];
for p=1:N_scat_old
Xold = O_old(1,p);
Yold = O_old(2,p);
aold = a_old(p);
isOK = true;
for cpt=1:size(X_to_avoid,2)
if(abs(Xold - X_to_avoid(cpt))<Tol)
isOK = false;
break;
end
end
if(isOK)
for cpt=1:size(Y_to_avoid,2)
if(abs(Yold-Y_to_avoid(cpt))<Tol)
isOK = false;
break;
end
end
end
if(isOK)
for cpt=1:size(XY_to_avoid,2)
if(abs(Xold-XY_to_avoid(1, cpt))<Tol && abs(Yold-XY_to_avoid(2, cpt))<Tol)
isOK = false;
break;
end
end
end
if(isOK)
for cpt=1:size(a_to_avoid,2)
if(abs(aold - a_to_avoid(p))<Tol)
isOK = false;
break;
end
end
end
if(isOK)
O = [O, [Xold;Yold]];
a = [a, aold];
N_scat = N_scat +1 ;
else
if(VERBOSITY > 1)
disp(['Removing disk [',num2str(Xold),',',num2str(Yold),']']);
end
N_scat_delete = N_scat_delete+1;
end
end
if(VERBOSITY > 0)
disp(['Removed disks: ',num2str(N_scat_delete)]);
disp(['Old number of disks: ',num2str(N_scat_old)]);
disp(['New number of disks: ',num2str(N_scat)]);
end
end
|
github
|
mu-diff/mu-diff-master
|
RectangularLattice.m
|
.m
|
mu-diff-master/PreProcessing/Geometry/RectangularLattice.m
| 2,829 |
utf_8
|
1fed8fe50e710e5da5513a8ca5581047
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% TriangularLattice produces a set of center of obstacles (without radius)
% periodically placed as a rectangular lattice. If "x" designes a center
% then the results looks like:
% x x x x x
% x x x x x
% x x x x x
% x x x x x
% x x x x x
% x x x x x
%
% The number of rows Ny and the number of obstacles Nx can be specified in
% addition to the x-distance between two centers and the y-distance between
% two rows.
% By default, the first disks is located on (0,0) and is located on
% bottom-left of the lattice.
%
% -----------------------------------
% O = RectangularLattice(bx,by,Nx,Ny)
%
% OUTPUT ARGUMENTS:
% -----------------
% O [2 x N_scat] : Matrix of the centers of the disks
%
% INPUT ARGUMENTS:
% ----------------
% bx [1x1] : x-distance between two centers
% by [1x1] : y-distance between two row of obstacles
% Nx [1x1] : Number of obstacles on a row
% Ny [1x1] : Number of rows
%
% OPTIONS:
% --------
% RectangularLattice(..., 'Origin', Ostart)
% place the first disk on Ostart position, Ostart being a [2x1] vector.
% Default: [0;0].
%
% RectangularLattice(..., 'Direction', +/- 1)
% place the row in the increasing y (+1) or decreasing y (-1). Default: +1
%
% RectangularLattice(..., 'Center', Ocenter)
% center the collection on the point Ocenter.
% Default: none but erase Ostart ('Origin' option)
%
% See also TriangularLattice, CreateRandomDisks, PlotCircles
%
function O=RectangularLattice(bx, by, Nx, Ny, varargin)
% First point
Ostart=[0;0];
direction = 1; %from bottom to top
nvarargin = length(varargin);
cpt_arg = 1;
while(cpt_arg <= nvarargin)
if(strcmp(varargin{cpt_arg}, 'Origin'))
Ostart = varargin{cpt_arg+1};
cpt_arg = cpt_arg +2;
elseif(strcmp(varargin{cpt_arg}, 'Direction'))
direction = varargin{cpt_arg+1};
cpt_arg = cpt_arg +2;
elseif(strcmp(varargin{cpt_arg}, 'Center'))
Ocenter = varargin{cpt_arg+1};
xOstart = Ocenter(1) - bx*(Nx-1)/2;
yOstart = Ocenter(2) - by*(Ny-1)/2;
Ostart = [xOstart; yOstart];
cpt_arg = cpt_arg +2;
else
warning(['Unkown option ', varargin{cpt_arg}]);
cpt_arg = cpt_arg +1;
end
end
%Creation of the x-row of even or uneven index
x_vect=Ostart(1):bx:Ostart(1)+(Nx-1)*bx;
Ox =[];
Oy =[];
%Loop on every rows
for cpt = 0:Ny-1
current_y = Ostart(2) + direction *by *cpt;
Ox =[Ox, x_vect];
Oy = [Oy, current_y*ones(1,Nx)];
end
O = [Ox;Oy];
|
github
|
mu-diff/mu-diff-master
|
TriangularLattice.m
|
.m
|
mu-diff-master/PreProcessing/Geometry/TriangularLattice.m
| 2,994 |
utf_8
|
073b6e43e2cd142d63b28dde7bbc5824
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% TriangularLattice produces a set of center of obstacles (without radius)
% periodically placed as a triangular lattice. If "x" designes a center
% then the results looks like:
% x x x x x
% x x x x x
% x x x x x
% x x x x x
% x x x x x
% x x x x x
%
% The number of rows Ny and the number of obstacles Nx can be specified in
% addition to the x-distance between two centers and the y-distance between
% two rows.
% By default, the first disks is located on (0,0) and is located on
% bottom-left of the lattice.
%
% -----------------------------------
% O = TriangularLattice(bx,by,Nx,Ny)
%
% OUTPUT ARGUMENTS:
% -----------------
% O [2 x N_scat] : Matrix of the centers of the disks
%
% INPUT ARGUMENTS:
% ----------------
% bx [1x1] : x-distance between two centers
% by [1x1] : y-distance between two row of obstacles
% Nx [1x1] : Number of obstacles on a row
% Ny [1x1] : Number of rows
%
% OPTIONS:
% --------
% TriangularLattice(..., 'Origin', Ostart)
% place the first disk on Ostart position, Ostart being a [2x1] vector.
% Default: [0;0].
%
% TriangularLattice(..., 'Direction', +/- 1)
% place the row in the increasing y (+1) or decreasing y (-1). Default: +1
%
% TriangularLattice(..., 'Center', Ocenter)
% Center the collection on the point Ocenter.
% Default: none but erase Ostart ('Origin' option)
%
% See also RectangularLattice, CreateRandomDisks, PlotCircles
%
function O=TriangularLattice(bx, by, Nx, Ny, varargin)
% First point
Ostart=[0;0];
direction = 1; %from bottom to top
nvarargin = length(varargin);
cpt_arg = 1;
while(cpt_arg <= nvarargin)
if(strcmp(varargin{cpt_arg}, 'Origin'))
Ostart = varargin{cpt_arg+1};
cpt_arg = cpt_arg +2;
elseif(strcmp(varargin{cpt_arg}, 'Direction'))
direction = varargin{cpt_arg+1};
cpt_arg = cpt_arg +2;
elseif(strcmp(varargin{cpt_arg}, 'Center'))
Ocenter = varargin{cpt_arg+1};
xOstart = Ocenter(1) - bx*(Nx-1)/2;
yOstart = Ocenter(2) - by*(Ny-1)/2;
Ostart = [xOstart; yOstart];
cpt_arg = cpt_arg +2;
else
warning(['Unkown option ', varargin{cpt_arg}]);
cpt_arg = cpt_arg +1;
end
end
%Creation of the x-row of even or uneven index
x_even=Ostart(1):bx:Ostart(1)+(Nx-1)*bx;
x_uneven=Ostart(1)+bx/2:bx:Ostart(1)+bx/2+(Nx-2)*bx;
Ox =[];
Oy =[];
%Loop on every rows
for cpt = 0:Ny-1
current_y = Ostart(2) + direction *by *cpt;
if(mod(cpt,2)==0)
Ox =[Ox, x_even];
Oy = [Oy, current_y*ones(1,Nx)];
else
Ox =[Ox, x_uneven];
Oy = [Oy, current_y*ones(1,Nx-1)];
end
end
O = [Ox;Oy];
|
github
|
mu-diff/mu-diff-master
|
CheckPlacement.m
|
.m
|
mu-diff-master/PreProcessing/Geometry/CheckPlacement.m
| 3,082 |
utf_8
|
ba1901687415ebf8737ec50f44668aaa
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Check if the list of obstacles sent are well placed with respect to parameters.
%res = CheckPlacement(O, a) : will check if the list of disks of centers O
% and radii a do not overlap (=true)
% Input arguments:
% ----------------
%
% O [2, N_scat] : Coordinates of the N_scat disks
% a [1, N_scat] : Radii of the circular obstacles
%
% Output arguments:
% -----------------
% res [1x1] : true if obstacles are well placed, false otherwise
%
% Options 1: res = CheckPlacement(O, a, d_min, d_max)
% ---------------------------------------------------
% Will check if two disks are distant from at least d_min and at most
% from d_max
% dmin(=realmin) [1, 1] : minimal authorized distance between two disks
% dmax(=realmax) [1, 1] : maximal authorized distance between two disks
%
% Options 2: res = CheckPlacement(O, a, d_min, d_max, Onew, anew)
% ---------------------------------------------------------------
% Will check if the disk (Onew, anew) is well placed compare to all other
% disks, with the good distances. Note that other disks are then NOT
% checked.
% Onew [2, 1] : Coordinate of the new disk
% anew [1, 1] : Radius of the new disk
%
% Remarks:
% --------
% - If Onew is specified without anew, then Onew is not considered
% - If Onew and anew are specified then the disks (O,a) are NOT checked.
% They are assumed to be well placed.
% - Be carreful with dmax. It is not the distance between the closest disk,
% but with ALL OTHER disks.
function res = CheckPlacement(O, a, varargin)
res = true;
N_scat = length(a);
if(size(O,2) ~= N_scat)
error('O and a should have the same number of columns');
end
CheckAllObstacles = true;
dmin = realmin;
dmax = realmax;
if(nargin >= 3)
dmin = varargin{1};
end
if(nargin >= 4)
dmax = varargin{2};
end
if(nargin >= 6)
Onew = varargin{3};
anew = varargin{4};
CheckAllObstacles = false;
end
if(dmin <= 0)
dmin = realmin;
end
if(dmax <= 0)
dmax = realmax;
end
if(CheckAllObstacles) %check all obstacles of center O and radii a
for p =2:N_scat
if(res>0)
break;
end
Op = O(:,p);
ap = a(p);
res_min = any(sqrt((O(1,1:p-1) - Op(1)).^2+ (O(2,1:p-1) - Op(2)).^2) - a(1:p-1) - ap < dmin);
res_max = any(sqrt((O(1,1:p-1) - Op(1)).^2+ (O(2,1:p-1) - Op(2)).^2) - a(1:p-1) - ap > dmax);
res = res_min+res_max;
end
else % check only new obstacle with obstacles of center 0 and radii a
res_min = any(sqrt((O(1,:) - Onew(1)).^2+ (O(2,:) - Onew(2)).^2) - a - anew < dmin);
res_max = any(sqrt((O(1,:) - Onew(1)).^2+ (O(2,:) - Onew(2)).^2) - a - anew > dmax);
res = res_min+res_max;
end
res = ~res;
|
github
|
mu-diff/mu-diff-master
|
IncidentWave.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/IncidentWave.m
| 3,907 |
utf_8
|
d068ac23729929eac714cd7a72256ff0
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of an
% incident wave, either the trace of the normal derivative trace, for the
% multiple scattering problem by disks, in the Fourier bases.
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -u^inc, -dn
% u^inc, ...
% -------------------------------------------------------------------------
% B = IncidentWave(O, a, M_modes, k, TypeOfWave, Param)
%
% OUTPUT ARGUMETNS:
% -----------------
% B [sum(2*M_modes+1),1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% TypeOfWave [1 x 1] : Personal Data (0 - see below)),
% or [N_scat x 1] Plane wave (1), Dn Plane wave (2),
% Point source (3), Dn Point source (4),
% Precond Plane wave (5), Precond Dn Plane wave (6),
% Precond Point source (7), Precond Dn Point source (8),
% varagin (var) : Parameter of the incident wave (direction, ...)
%
% EXAMPLE:
% --------
% 1) For an incident plane wave of direction beta_inc = pi:
% > B = IncidentWave(O, a, M_modes, k, 1, beta_inc)
% 2) For a point source in OS =[XS,YS]:
% > B = IncidentWave(O, a, M_modes, k, 3, OS)
% 3) For 2 obstacles, a vector with (-u^inc, -dn u^inc) where u^inc is a
% plane wave of direction beta_inc:
% > B = IncidentWave(O, a, M_modes, k, [1,2], beta_inc)
%
% REMARK:
% -------
% - It is possible to mix plane wave and point source but the result is
% however probably strange. Consider calling this function twice instead.
% - mu-diff definition of plane wave of direction beta:
% uinc(X) = exp(i*beta*X)
% - mu-diff definition of point source wave from OS :
% uinc(X) = G(X,OS) = +0.25*i*H_0^(1)(k*\|X-OS\|)
%
% See also PlaneWave, DnPlaneWave, PointSource, DnPointSource,
% PlaneWavePrecond, DnPlaneWavePrecond, ParserIncidentWave
%
%
%%
function B = IncidentWave(O, a, M_modes, k, TypeOfWave, varargin)
if(isempty(varargin))
error('Missing argument! (direction of wave or position of point source)');
end
ScalarTypeOfWave = ParserIncidentWave(TypeOfWave);
%Initialization
N_scat = length(a);
Sum_modes = 2.*M_modes + 1;
B = zeros(sum(Sum_modes),1);
%Sp is a row-counter
Sp = 0;
%Loop on the obstacles (blocks of u_inc)
for p = 1:N_scat
%Center and radius of the scatterer p
Op = O(:,p);
ap = a(p);
%Vector of the modes associated with the scattererd number p
Np = M_modes(p);
MNp = [-Np:Np].';
this_wave = GetTypeOfWave(ScalarTypeOfWave, p);
B(Sp + MNp +(Np+1))= BlockIncidentWave(Op, ap, Np, k, this_wave, varargin{1:end});
%Upgrade of the row-counter
Sp = Sp + 2*Np+1;
end
end
%%
function this_wave = GetTypeOfWave(TypeOfWave, p)
if(length(TypeOfWave) == 1)
if(iscell(TypeOfWave))
this_wave= TypeOfWave{1};
else
this_wave= TypeOfWave;
end
else
if(iscell(TypeOfWave))
this_wave = TypeOfWave{p};
else
this_wave = TypeOfWave(p);
end
end
end
|
github
|
mu-diff/mu-diff-master
|
BlockIncidentWave.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/BlockIncidentWave.m
| 6,015 |
utf_8
|
f7870a9b04c4860dc610e68edbd04b32
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the block vector of (the opposite of) the coefficients of an
% incident wave, either the trace of the normal derivative trace, on one
% of the obstacles, in the Fourier bases.
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -u^inc, -dn
% u^inc, ...
% -------------------------------------------------------------------------
% Bp = BlockIncidentWave(Op, ap, Np, k, TypeOfWave, Param)
%
% OUTPUT ARGUMETNS:
% -----------------
% B [2*Np+1,1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% Op [2 x N_scat] : Vector of the center of the scatterer
% ap [1 x N_scat] : Radius of the scatterer
% Np [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% TypeOfWave [1 x 1] : Plane wave (1), Dn Plane wave (2),
% Point source (3), Dn Point source (4),
% Precond Plane wave (5), Precond Dn Plane wave (6)
% Param (var) : Parameter of the incident wave (direction, ...)
%
% REMARK:
% -------
% - It is not possible to mix plane wave and point source. This should be
% done by two call of this functions.
% - A plane wave of direction beta: uinc(X) = exp(i*beta*X)
% - A point source from OS : uinc(X) = G(X,OS) = 0.25*i*H_0^(k*\|X-OS\|)
%
% See also Incidentwave, PlaneWave, DnPlaneWave, PointSource, DnPointSource,
% PlaneWavePrecond, DnPlaneWavePrecond
%
%
function Bp = BlockIncidentWave(Op, ap, Np, k, TypeOfWave, varargin)
if(isempty(varargin))
error('Missing argument! (direction of wave or position of point source)');
end
if(~isscalar(TypeOfWave))
error('In block function, TypeOfWave must be a scalar');
end
%Initialization
Bp = zeros(2*Np+1,1);
MNp = [-Np:Np].';
ScalarTypeOfWave = ParserIncidentWave(TypeOfWave);
Param = varargin{1};
switch ScalarTypeOfWave
case -1, %Custom function
Bp = varargin{1}(Op, ap, Np, k, varargin{2:end});
case 0, %Zeros
case 1, %Plane wave
beta_inc = GetParam(TypeOfWave, Param);
Jm_kap = besselj(MNp,k*ap);
I = exp(1i*k*(Op(1)*cos(beta_inc) + Op(2)*sin(beta_inc)));
d_m = I*exp(1i*MNp*(pi/2-beta_inc));
Bp = - sqrt(2*pi*ap)* (d_m.*Jm_kap);
case 2, %Dn Plane wave
beta_inc = GetParam(TypeOfWave, Param);
dJm_kap = dbesselj(MNp,k*ap);
I = exp(1i*k*(Op(1)*cos(beta_inc) + Op(2)*sin(beta_inc)));
d_m = I*exp(1i*MNp*(pi/2-beta_inc));
Bp= - k*sqrt(2*pi*ap)* (d_m.*dJm_kap);
case 3, %Point source
XS = GetParam(TypeOfWave, Param);
betap = fangle(Op,XS);
bp = norm(Op-XS);
Jm_kap = besselj(MNp,k*ap);
Hm_kbp = besselh(-MNp,1,k*bp);
Exp_betap = exp(-1i*MNp*betap);
Bp= - 1i/4*sqrt(2*pi*ap)*Jm_kap.*Hm_kbp.*Exp_betap;
case 4, %Dn Point source
XS = GetParam(TypeOfWave, Param);
betap = fangle(Op,XS);
bp = norm(Op-XS);
dJm_kap = dbesselj(MNp,k*ap);
Hm_kbp = besselh(-MNp,1,k*bp);
Exp_betap = exp(-1i*MNp*betap);
Bp= - 1i*k/4*sqrt(2*pi*ap)*dJm_kap.*Hm_kbp.*Exp_betap;
case 5, %Precond Dirichlet Plane Wave (trace precond by single-layer)
beta_inc = GetParam(TypeOfWave, Param);
H1m_kap_inv = 1./besselh(MNp,1,k*ap);
I = exp(1i*k*(Op(1)*cos(beta_inc) + Op(2)*sin(beta_inc)));
d_m = I*exp(1i*MNp*(pi/2-beta_inc));
Bp= 1i*2*sqrt(2/pi/ap)* (d_m.*H1m_kap_inv);
case 6, %Precond Neumann Dn Plane Wave (dn trace precond by dn double-layer)
beta_inc = GetParam(TypeOfWave, Param);
dH1m_kap_inv = 1./dbesselh(MNp,1,k*ap);
I = exp(1i*k*(Op(1)*cos(beta_inc) + Op(2)*sin(beta_inc)));
d_m = I*exp(1i*MNp*(pi/2-beta_inc));
Bp= 1i*2*sqrt(2/pi/ap)/k* (d_m.*dH1m_kap_inv);
case 7, %Precond Dirichlet Point Source (trace precond by single-layer)
XS = GetParam(TypeOfWave, Param);
betap = fangle(Op,XS);
bp = norm(Op-XS);
Hm_kbp = besselh(-MNp,1,k*bp);
H1m_kap_inv = 1./besselh(MNp,1,k*ap);
Exp_betap = exp(-1i*MNp*betap);
Bp= - 1/sqrt(2*pi*ap)*Hm_kbp.*H1m_kap_inv.*Exp_betap;
case 8, %Precond Neumann Dn Point Source (dn trace precond by double-layer)
XS = GetParam(TypeOfWave, Param);
betap = fangle(Op,XS);
bp = norm(Op-XS);
Hm_kbp = besselh(-MNp,1,k*bp);
dH1m_kap_inv = 1./dbesselh(MNp,1,k*ap);
Exp_betap = exp(-1i*MNp*betap);
Bp= 1/(k*sqrt(2*pi*ap))*Hm_kbp.*dH1m_kap_inv.*Exp_betap;
end
end
%%
function param = GetParam(TypeOfWave, arg)
if( TypeOfWave == 1 || TypeOfWave == 2 || (TypeOfWave >=5 && TypeOfWave <=6))
%Plane wave
if(isscalar(arg))
param = arg;
else
error('Plane wave must be specified with a scalar argument (angle of direction)');
end
else
%Point source
if((isrow(arg) || iscolumn(arg)) && length(arg) == 2)
if(isrow(arg))
param = arg.';
else
param = arg;
end
else
error('Point source must be specified with [XS,YS] argument');
end
end
end
|
github
|
mu-diff/mu-diff-master
|
BlockDnPlaneWave.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Block/BlockDnPlaneWave.m
| 1,769 |
utf_8
|
0e492bd3fa6ee22cf50885d17c9a924b
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the normal
% derivative trace of an incident plane wave on one obstacle for the
% multiple scattering problem by disks, in the Fourier bases.
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -dn u^inc
% -------------------------------------------------------------------------
% Normal derivative trace of an incident plane wave of direction Beta (angle in radian)
% on the boundary Gamma :
% dn_x u^{inc}(x) = dn_x [exp(ik(cos(Beta).x_1 + sin(Beta).x_2))], for all =(x_1,x_2) in Gamma
% -------------------------------------------------------------------------
% Bp = BlockDnPlaneWave(Op, ap, Np, k, OS)
%
% OUTPUT ARGUMETNS:
% -----------------
% Bp [2*Np+1,1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% Op [2 x N_scat] : Vector of the center of the scatterer
% ap [1 x N_scat] : Radius of the scatterer
% Np [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% beta_inc [1 x 1] : Direction of the wave
%
% See also IncidentWave, BlockIncidentWave, DnPlaneWave
%
%
function Bp = BlockDnPlaneWave(Op, ap, Np, k, beta_inc)
Bp = BlockIncidentWave(Op, ap, Np, k, 2, beta_inc);
end
|
github
|
mu-diff/mu-diff-master
|
BlockDnPointSource.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Block/BlockDnPointSource.m
| 1,572 |
utf_8
|
2146c3aaa0eaa8f31687d9025b7d0c99
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the normal
% derivative trace of the Green function on one of the obstacles, for the
% multiple scattering problem by disks, in the Fourier bases.
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -dn G|_\Gamma
% -------------------------------------------------------------------------
% Green function: G(x,y) = 0.25*i*H_0^1(k\|x-y\|)
% -------------------------------------------------------------------------
% Bp = BlockDnPointSource(Op, ap, Np, k, OS)
%
% OUTPUT ARGUMETNS:
% -----------------
% Bp [2*Np+1,1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% Op [2 x N_scat] : Vector of the center of the scatterer
% ap [1 x N_scat] : Radius of the scatterer
% Np [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% OS [2 x 1] : Coordinates of the point source
%
% See also IncidentWave, BlockIncidentWave, DnPointSource
%
%
function Bp = BlockDnPointSource(Op, ap, Np, k, OS)
Bp = BlockIncidentWave(Op, ap, Np, k, 4, OS);
end
|
github
|
mu-diff/mu-diff-master
|
BlockDnPointSourcePrecond.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Block/BlockDnPointSourcePrecond.m
| 1,829 |
utf_8
|
cd4deeef917f15d9ad58b291c77f935d
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the normal
% derivative trace of an incident point source wave on one obstacle for the
% multiple scattering problem by disks, in the Fourier bases.
% The normal derivative trace itself is multiplied by the inverse of the
% dn double-layer operator (single scattering preconditioner for sound hard
% obstacles)
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -dn G|_\Gamma
% -------------------------------------------------------------------------
% Green function: G(x,y) = 0.25*i*H_0^1(k\|x-y\|)
% -------------------------------------------------------------------------
% Bp = BlockDnPointSourcePrecond(Op, ap, Np, k, OS)
%
% OUTPUT ARGUMETNS:
% -----------------
% Bp [2*Np+1,1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% Op [2 x N_scat] : Vector of the center of the scatterer
% ap [1 x N_scat] : Radius of the scatterer
% Np [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% OS [2 x 1] : Coordinates of the point source
%
% See also IncidentWave, BlockIncidentWave, PointSourcePrecond, DnPointSourcePrecond
%
%
function Bp = BlockDnPointSourcePrecond(Op, ap, Np, k, OS)
Bp = BlockIncidentWave(Op, ap, Np, k, 8, OS);
end
|
github
|
mu-diff/mu-diff-master
|
BlockDnPlaneWavePrecond.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Block/BlockDnPlaneWavePrecond.m
| 1,668 |
utf_8
|
2d44c3a75f8753902756d1c9a753f74b
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the normal
% derivative trace of an incident plane wave on one obstacle for the
% multiple scattering problem by disks, in the Fourier bases.
% The normal derivative trace itself is multiplied by the inverse of the
% dn double-layer operator (single scattering preconditioner for sound hard
% obstacles)
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -dn u^inc
% -------------------------------------------------------------------------
% Bp = BlockDnPlaneWavePrecond(Op, ap, Np, k, OS)
%
% OUTPUT ARGUMETNS:
% -----------------
% Bp [2*Np+1,1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% Op [2 x N_scat] : Vector of the center of the scatterer
% ap [1 x N_scat] : Radius of the scatterer
% Np [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% beta_inc [1 x 1] : Direction of the wave
%
% See also IncidentWave, BlockIncidentWave, DnPlaneWavePrecond
%
%
function Bp = BlockDnPlaneWavePrecond(Op, ap, Np, k, beta_inc)
Bp = BlockIncidentWave(Op, ap, Np, k, 6, beta_inc);
end
|
github
|
mu-diff/mu-diff-master
|
BlockPlaneWave.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Block/BlockPlaneWave.m
| 1,728 |
utf_8
|
bf6cd3f76386c3868d61d30dbd79e3eb
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the trace of
% an incident plane wave on one obstacle for the multiple scattering
% problem by disks, in the Fourier bases.
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -u^inc
% -------------------------------------------------------------------------
% Trace of an incident plane wave of direction Beta (angle in radian)
% on the boundary Gamma :
% u^{inc}(x) = exp(ik(cos(Beta).x_1 + sin(Beta).x_2)), for all x=(x_1,x_2) in Gamma
% -------------------------------------------------------------------------
% Bp = BlockPlaneWave(Op, ap, Np, k, beta_inc)
%
% OUTPUT ARGUMETNS:
% -----------------
% Bp [2*Np+1,1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% Op [2 x N_scat] : Vector of the center of the scatterer
% ap [1 x N_scat] : Radius of the scatterer
% Np [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% beta_inc [1 x 1] : Direction of the wave
%
%
% See also IncidentWave, BlockIncidentWave, PlaneWave
%
%
function Bp = BlockPlaneWave(Op, ap, Np, k, beta_inc)
Bp = IncidentWave(Op, ap, Np, k, 1, beta_inc);
end
|
github
|
mu-diff/mu-diff-master
|
BlockPointSourcePrecond.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Block/BlockPointSourcePrecond.m
| 1,793 |
utf_8
|
08af99aae0847897a5981088a1b2dc75
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the trace of
% an incident point source wave on one obstacle for the multiple scattering problem
% by disks, in the Fourier bases.
% The trace itself is multiplied by the inverse of the single-layer
% operator (single scattering preconditioner for sound soft obstacles)
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -G|_\Gamma
% -------------------------------------------------------------------------
% Green function: G(x,y) = 0.25*i*H_0^1(k\|x-y\|)
% -------------------------------------------------------------------------
% Bp = BlockPointSourcePrecond(Op, ap, Np, k, OS)
%
% OUTPUT ARGUMETNS:
% -----------------
% Bp [2*Np+1,1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% Op [2 x N_scat] : Vector of the center of the scatterer
% ap [1 x N_scat] : Radius of the scatterer
% Np [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% OS [2 x 1] : Coordinates of the point source
%
%
% See also IncidentWave, BlockIncidentWave, PointSourcePrecond, DnPointSourcePrecond
%
%
function Bp = BlockPointSourcePrecond(Op, ap, Np, k, OS)
Bp = BlockIncidentWave(Op, ap, Np, k, 7, OS);
end
|
github
|
mu-diff/mu-diff-master
|
BlockPointSource.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Block/BlockPointSource.m
| 1,520 |
utf_8
|
16efaa21ae207ac2c5367f5580c3db07
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the trace
% of the Green function for the multiple scattering problem by disks, in
% the Fourier bases.
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -G|_\Gamma
% -------------------------------------------------------------------------
% Green function: G(x,y) = 0.25*i*H_0^1(k\|x-y\|)
% -------------------------------------------------------------------------
% Bp = BlockPointSource(Op, ap, Np, k, OS)
%
% OUTPUT ARGUMETNS:
% -----------------
% Bp [2*Np+1,1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% Op [2 x N_scat] : Vector of the center of the scatterer
% ap [1 x N_scat] : Radius of the scatterer
% Np [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% OS [2 x 1] : Coordinates of the point source
%
% See also IncidentWave, BlockIncidentWave, PointSource
%
%
function Bp = BlockPointSource(Op, ap, Np, k, OS)
Bp = BlockIncidentWave(Op, ap, Np, k, 3, OS);
end
|
github
|
mu-diff/mu-diff-master
|
BlockPlaneWavePrecond.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Block/BlockPlaneWavePrecond.m
| 1,636 |
utf_8
|
6764f6e0c164d0c2f905e116fc5f919e
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the trace of
% an incident plane wave on one obstacle for the multiple scattering problem
% by disks, in the Fourier bases.
% The trace itself is multiplied by the inverse of the single-layer
% operator (single scattering preconditioner for sound soft obstacles)
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -u^inc
% -------------------------------------------------------------------------
% Bp = BlockPlaneWavePrecond(Op, ap, Np, k, beta_inc)
%
% OUTPUT ARGUMETNS:
% -----------------
% Bp [2*Np+1,1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% Op [2 x N_scat] : Vector of the center of the scatterer
% ap [1 x N_scat] : Radius of the scatterer
% Np [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% beta_inc [1 x 1] : Direction of the wave
%
%
% See also IncidentWave, BlockIncidentWave, PlaneWavePrecond
%
%
function Bp = BlockPlaneWavePrecond(Op, ap, Np, k, beta_inc)
Bp = BlockIncidentWave(Op, ap, Np, k, 5, beta_inc);
end
|
github
|
mu-diff/mu-diff-master
|
PlaneWavePrecond.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Full/PlaneWavePrecond.m
| 1,662 |
utf_8
|
1573dc7b5fdde392b7f73dd32679f550
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the trace of
% an incident plane wave for the multiple scattering problem by disks, in
% the Fourier bases.
% The trace itself is multiplied by the inverse of the single-layer
% operator (single scattering preconditioner for sound soft obstacles)
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -u^inc
% -------------------------------------------------------------------------
% B = PlaneWavePrecond(O, a, M_modes, k, beta_inc)
%
% OUTPUT ARGUMETNS:
% -----------------
% B [sum(2*M_modes+1),1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% beta_inc [1 x 1] : Direction of the wave
%
% See also IncidentWave, PlaneWave, DnPlaneWave, PointSource, DnPointSource,
% DnPlaneWavePrecond
%
%
function B = PlaneWavePrecond(O, a, M_modes, k, beta_inc)
B = IncidentWave(O, a, M_modes, k, 5, beta_inc);
end
|
github
|
mu-diff/mu-diff-master
|
DnPointSource.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Full/DnPointSource.m
| 1,661 |
utf_8
|
d154ccece043c42e4e2cf2e5e188b2ab
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the normal
% derivative trace of the Green function for the multiple scattering problem
% by disks, in the Fourier bases.
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -dn G|_\Gamma
% -------------------------------------------------------------------------
% Green function: G(x,y) = 0.25*i*H_0^1(k\|x-y\|)
% -------------------------------------------------------------------------
% B = DnPointSource(O, a, M_modes, k, OS)
%
% OUTPUT ARGUMETNS:
% -----------------
% B [sum(2*M_modes+1),1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% OS [2 x 1] : Coordinates of the point source
%
% See also IncidentWave, PlaneWave, DnPlaneWave, PointSource,
% PlaneWavePrecond, DnPlaneWavePrecond
%
%
function B = DnPointSource(O, a, M_modes, k, OS)
B = IncidentWave(O, a, M_modes, k, 4, OS);
end
|
github
|
mu-diff/mu-diff-master
|
PlaneWave.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Full/PlaneWave.m
| 1,778 |
utf_8
|
86cfbe6ed2b0c520214995d0680b1d22
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the trace of
% an incident plane wave for the multiple scattering problem by disks, in
% the Fourier bases.
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -u^inc
% -------------------------------------------------------------------------
% Trace of an incident plane wave of direction Beta (angle in radian)
% on the boundary Gamma :
% u^{inc}(x) = exp(ik(cos(Beta).x_1 + sin(Beta).x_2)), for all x=(x_1,x_2) in Gamma
% -------------------------------------------------------------------------
% B = IncidentWave(O, a, M_modes, k, beta_inc)
%
% OUTPUT ARGUMETNS:
% -----------------
% B [sum(2*M_modes+1),1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% beta_inc [1 x 1] : Direction of the wave
%
% See also IncidentWave, DnPlaneWave, PointSource, DnPointSource,
% PlaneWavePrecond, DnPlaneWavePrecond
%
%
function B = PlaneWave(O, a, M_modes, k, beta_inc)
B = IncidentWave(O, a, M_modes, k, 1, beta_inc);
end
|
github
|
mu-diff/mu-diff-master
|
DnPlaneWave.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Full/DnPlaneWave.m
| 1,827 |
utf_8
|
e26f3ffc5bdf949dd10d2e5726146e32
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the normal
% derivative trace of an incident plane wave for the multiple scattering
% problem by disks, in the Fourier bases.
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -dn u^inc
% -------------------------------------------------------------------------
% Normal derivative trace of an incident plane wave of direction Beta (angle in radian)
% on the boundary Gamma :
% dn_x u^{inc}(x) = dn_x [exp(ik(cos(Beta).x_1 + sin(Beta).x_2))], for all =(x_1,x_2) in Gamma
% -------------------------------------------------------------------------
% B = DnIncidentWave(O, a, M_modes, k, beta_inc)
%
% OUTPUT ARGUMETNS:
% -----------------
% B [sum(2*M_modes+1),1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% beta_inc [1 x 1] : Direction of the wave
%
% See also IncidentWave, PlaneWave, PointSource, DnPointSource,
% PlaneWavePrecond, DnPlaneWavePrecond
%
%
function B = DnPlaneWave(O, a, M_modes, k, beta_inc)
B = IncidentWave(O, a, M_modes, k, 2, beta_inc);
end
|
github
|
mu-diff/mu-diff-master
|
PointSourcePrecond.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Full/PointSourcePrecond.m
| 1,712 |
utf_8
|
9c3109013e37a0c120db7ebcdf0f007d
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the trace of
% an incident point source wave for the multiple scattering problem by disks,
% in the Fourier bases.
% The trace itself is multiplied by the inverse of the single-layer
% operator (single scattering preconditioner for sound soft obstacles)
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -u^inc
% -------------------------------------------------------------------------
% B = PointSourcePrecond(O, a, M_modes, k, beta_inc)
%
% OUTPUT ARGUMETNS:
% -----------------
% B [sum(2*M_modes+1),1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% beta_inc [1 x 1] : Direction of the wave
%
% See also IncidentWave, PlaneWave, DnPlaneWave, PointSource, DnPointSource,
% PlaneWavePrecond, DnPlaneWavePrecond, DnPointSourcePrecond
%
%
function B = PointSourcePrecond(O, a, M_modes, k, beta_inc)
B = IncidentWave(O, a, M_modes, k, 7, beta_inc);
end
|
github
|
mu-diff/mu-diff-master
|
PointSource.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Full/PointSource.m
| 1,639 |
utf_8
|
65a917806e365e04dc572a0aa55486ec
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the trace
% of the Green function for the multiple scattering problem by disks, in
% the Fourier bases.
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -G|_\Gamma
% -------------------------------------------------------------------------
% Green function: G(x,y) = 0.25*i*H_0^1(k\|x-y\|)
% -------------------------------------------------------------------------
% B = PointSource(O, a, M_modes, k, OS)
%
% OUTPUT ARGUMETNS:
% -----------------
% B [sum(2*M_modes+1),1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% OS [2 x 1] : Coordinates of the point source
%
% See also IncidentWave, PlaneWave, DnPlaneWave, DnPointSource,
% PlaneWavePrecond, DnPlaneWavePrecond
%
%
function B = PointSource(O, a, M_modes, k, OS)
B = IncidentWave(O, a, M_modes, k, 3, OS);
end
|
github
|
mu-diff/mu-diff-master
|
DnPlaneWavePrecond.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Full/DnPlaneWavePrecond.m
| 1,705 |
utf_8
|
6ba0086b988d5293f6242106abe10587
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the normal
% derivative trace of an incident plane wave for the multiple scattering
% problem by disks, in the Fourier bases.
% The normal derivative trace itself is multiplied by the inverse of the
% dn double-layer operator (single scattering preconditioner for sound hard
% obstacles)
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -u^inc
% -------------------------------------------------------------------------
% B = DnPlaneWavePrecond(O, a, M_modes, k, beta_inc)
%
% OUTPUT ARGUMETNS:
% -----------------
% B [sum(2*M_modes+1),1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% beta_inc [1 x 1] : Direction of the wave
%
% See also IncidentWave, PlaneWave, DnPlaneWave, PointSource, DnPointSource,
% PlaneWavePrecond
%
%
function B = DnPlaneWavePrecond(O, a, M_modes, k, beta_inc)
B = IncidentWave(O, a, M_modes, k, 6, beta_inc);
end
|
github
|
mu-diff/mu-diff-master
|
DnPointSourcePrecond.m
|
.m
|
mu-diff-master/PreProcessing/IncidentWave/Full/DnPointSourcePrecond.m
| 1,749 |
utf_8
|
9d32cb0b70da446431695611485beae9
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the vector of (the opposite of) the coefficients of the normal
% derivative trace of a point source wave for the multiple scattering
% problem by disks, in the Fourier bases.
% The normal derivative trace itself is multiplied by the inverse of the
% dn double-layer operator (single scattering preconditioner for sound hard
% obstacles)
% -------------------------------------------------------------------------
% REMARK: What is computed is the OPPOSITE of the coefficient: -dn u^inc
% -------------------------------------------------------------------------
% B = DnPointSourcePrecond(O, a, M_modes, k, beta_inc)
%
% OUTPUT ARGUMETNS:
% -----------------
% B [sum(2*M_modes+1),1] : Vector of the coefficients
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% beta_inc [1 x 1] : Direction of the wave
%
% See also IncidentWave, PlaneWave, DnPlaneWave, PointSource, DnPointSource,
% PlaneWavePrecond, DnPlaneWavePrecond, PointSourcePrecond
%
%
function B = DnPointSourcePrecond(O, a, M_modes, k, beta_inc)
B = IncidentWave(O, a, M_modes, k, 8, beta_inc);
end
|
github
|
mu-diff/mu-diff-master
|
SpIntegralOperator.m
|
.m
|
mu-diff-master/IntOperators/Sparse/SpIntegralOperator.m
| 4,745 |
utf_8
|
47279ad872da8312a1c54c0ed4d8d164
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of one of the integral operator
% SPARSE VERSION
% -------------------------------------------------------------------------
% A = SpIntegralOperator(O, a, M_modes, k, TypeOfOperator)
%
% OUTPUT ARGUMENTS:
% -----------------
% A [2*sum(M_modes+1) x 2*sum(M_modes+1)] : Matrix of the system
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Coordinates of the center of the disk 1
% a [1 x N_scat] : Radius of disk 1
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% TypeOfOperator (See below) : Specifies the integral operator.
% See Comon/Parser.m for correspondance.
%
% TypeOfOperator acceptable size/type:
% ------------------------------------
% - SINGLE VALUE: SpIntegralOperator(..., 2) or SpIntegralOperator(..., {'L'})
% - 2D ARRAY/CELL: IntegralOperator(..., T) then block (p,q) is of type
% T(p,q) or T{p,q}
%
% OPTIONS (weight):
% -----------------
% A = IntegralOperator(..., TypeOfOperator, Weight)
% where Weight is of the same size as TypeOfOperator and contains
% multiplicative constants to apply to the desired operator:
% - SCALAR value: SpIntegralOperator(..., 2, 0.5) produces 0.5*L
% - MATRIX value T, W: SpIntegralOperator(..., T, W) then block (p,q) is of type
% W(p,q)*T(p,q)
%
% REMARK: contrary to the dense function, it is not possible to directly sum
% two operators in sparse version. This can be done however in the Matrix-vector
% product functon.
%
% EXAMPLE:
% --------
% 1) Compute N (DnSingleLayer)
% > A = cell(3,1);
% > A = SpIntegralOperator(O, a, M_modes, k, 4)
%
% 2) For two obstacles on [-10,0] and [0,10] with radii 1 and 0.5, compute
% the matrix [L_11, 2*D_12; 3*N_21, 4*M_22]:
% > O = [-10, 0; 0, 10];
% > a = [1, 0.5]
% > A = cell(3,1);
% > TypeOfOp = [2,5;4,3];
% > Weight = [1,2;3,4];
% > A = SpIntegralOperator(O, a, M_modes, k, TypeOfOp, Weight)
%
% See also Parser, BlockIntegralOperator
% SpBlockIntegralOperator, SpIntegralOperator, SpSingleLayer,
% SpDnSingleLayer, SpDoubleLayer, SpDnDoubleLayer,
% SpPrecondOperator_Dirichlet, SpPrecondOperator_Neumann
%%
function A = SpIntegralOperator(O, a, M_modes, k, TypeOfOperator, varargin)
N_scat = length(a);
CheckSize(N_scat, TypeOfOperator, 'TypeOfOperator');
nvarargin = length(varargin);
if(nvarargin >= 1)
Weight = varargin{1};
else
Weight = ones(size(TypeOfOperator));
end
CheckSize(N_scat, Weight, 'Weight');
if(size(Weight) ~=size(TypeOfOperator))
error('Matrix of TypeOfOperator and Weight must be of same size!');
end
%Parse the typeofop to get a purely numeric array
ScalarTypeOfOperator = ParserIntegralOperator(TypeOfOperator);
%initialization of the Matrix A
Nmax = max(M_modes);
SizeMax = 2*Nmax+1;
A = cell(3,1);
A{1} = zeros(SizeMax, N_scat, N_scat);
A{2} = zeros(2*SizeMax-1, N_scat, N_scat);
A{3} = zeros(SizeMax, N_scat, N_scat);
%Loop on the obstacles (blocks of A)
for p = 1:N_scat
%Center and radius of the scatterer p
Op = O(:,p);
ap = a(p);
Np = M_modes(p);
for q = 1:N_scat
%Center and radius of the scatterer p
Oq = O(:,q);
aq = a(q);
Nq = M_modes(q);
%Get the type of the block and the weight
this_type = GetTypeOfOperatorOrWeight(ScalarTypeOfOperator, p, q);
this_weight = GetTypeOfOperatorOrWeight(Weight, p, q);
this_k = GetK(k, p);
%Compute the block matrix
[A{1}(:,p,q), A{2}(:,p,q), A{3}(:,p,q)] = ...
SpBlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, Nmax, ...
this_k, this_type, this_weight, varargin{2:end});
end
end
end
%%
function []= CheckSize(N_scat, A, name)
ni = size(A,1);
nj = size(A,2);
nk = size(A,3);
isErr = false;
if(nk>1)
isErr = true;
end
if(ni ~= 1 && ni ~= N_scat)
isErr = true;
end
if(ni ~=nj)
isErr = true;
end
if(isErr)
error('Wrong size of ', name, [' (either one valued or a ' ...
'N_scat x N_scat array or cell)']);
end
end
|
github
|
mu-diff/mu-diff-master
|
SpBlockIntegralOperator.m
|
.m
|
mu-diff-master/IntOperators/Sparse/SpBlockIntegralOperator.m
| 7,861 |
utf_8
|
dbd85f5bae94abc9ed610ace8e9f15ae
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of one of the integral operator in
% the Fourier basis
% SPARSE VERSION
% -------------------------------------------------------------------------
% [LeftPart, MiddlePart, RightPart] = SpBlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, Nmax, k, TypeOfOperator, ...)
%
% OUTPUT ARGUMENTS:
% -----------------
% LeftPart [2*Nmax+1, 1] : Left part in the off-diag. blocks and
% also the diagonal blocks of the matrix
% MiddlePart [2*(2*Nmax+1)-1, 1] : Middle part (Toeplitz part) of the
% off-diag. blocks
% RightPart [2*Nmax+1, 1] : Right part of the off-diag. blocks
%
%
% INPUT ARGUMENTS:
% ----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of
% obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of
% obstacle q
% Nmax [1 x 1] : Reference number N (max of every other Np)
% k [1 x 1] : Wavenumber in the vacuum
% TypeOfOperator (See below) : Specifies the integral operator.
% See Comon/Parser.m for correspondance.
%
% TypeOfOperator acceptable size/type:
% ------------------------------------
% - SINGLE VALUE: SpBlockIntegralOperator(..., 2) or SpBlockIntegralOperator(..., {'L'})
%
% OPTION:
% -------
% [...] = SpBlockIntegralOperator(..., TypeOfOperator, Weight)
% Weight [1 x 1] : multiplicative constant to apply to the operator
%
% EXAMPLE:
% --------
% SpBlockIntegralOperator(..., 2, 0.5) will produce 0.5*L
% OR: SpBlockIntegralOperator(..., {'L'}, 0.5) produces 0.5*L
%
% See also Parser, IntegralOperator,
% BlockIntegralOperator, SpIntegralOperator, BlockSingleLayer,
% BlockDnSingleLayer, BlockDoubleLayer, BlockDnDoubleLayer,
% BlockPrecondDirichlet, BlockPrecondNeumann
%%
function [LeftPart, MiddlePart, RightPart] = SpBlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, Nmax, k, TypeOfOperator, varargin)
ScalarTypeOfOperator = ParserIntegralOperator(TypeOfOperator);
nvarargin = length(varargin);
if(nvarargin >= 1)
Weight = varargin{1};
else
Weight = ones(size(ScalarTypeOfOperator));
end
if(length(Weight) ~=length(ScalarTypeOfOperator))
error('Matrix of TypeOfOperator and Weight must be of same size!');
end
if(length(ScalarTypeOfOperator) > 1)
error('TypeOfOperator must be a scalar in SpBlockIntegralOperator!');
end
SizeMax = 2*Nmax+1;
LeftPart = zeros(SizeMax,1);
MiddlePart = zeros(2*SizeMax-1,1);
RightPart = zeros(SizeMax,1);
%Vector of the modes associated with the scatterer 1 and 2
MNp = [-Np:Np].';
if (Op(1) == Oq(1) && Op(2) == Oq(2) && ap == aq) % Diagonal block (which is diagonal)
switch ScalarTypeOfOperator
case -1,%Custom operator
[LeftPart(1:2*Np+1), RightPart(1:2*Np+1)] = ...
varargin{2}(Op, ap, Np, Oq, aq, Nq, Nmax, k, varargin{3:end});
case 0, %Null matrix
case 1, %Identity
LeftPart(1:2*Np+1) = ones(2*Np+1,1);
case 2, % Single Layer
Jm_kap = besselj(MNp,k*ap);
H1m_kap = besselh(MNp,1,k*ap);
LeftPart(1:2*Np+1) = 1i*ap*pi*0.5*H1m_kap.*Jm_kap;
case 3, % Double Layer
dJm_kap = dbesselj(MNp,k*ap);
H1m_kap = besselh(MNp,1,k*ap);
LeftPart(1:2*Np+1) = 0.5 - 1i*k*ap*pi*0.5*H1m_kap.*dJm_kap;
case 4, % Dn Single Layer
dJm_kap = dbesselj(MNp,k*ap);
H1m_kap = besselh(MNp,1,k*ap);
LeftPart(1:2*Np+1) = -0.5 + 1i*k*ap*pi*0.5*H1m_kap.*dJm_kap;
case 5, % Dn Double Layer
dJm_kap = dbesselj(MNp,k*ap);
dH1m_kap = dbesselh(MNp,1,k*ap);
LeftPart(1:2*Np+1) = -1i*k^2*ap*pi*0.5*dH1m_kap.*dJm_kap;
case 6, % Single scattering preconditioned single layer (Dirichlet)
LeftPart(1:2*Np+1) = ones(2*Np+1,1);
case 7, % Single scattering preconditioned dn double layer (Neumann)
LeftPart(1:2*Np+1) = ones(2*Np+1,1);
end
%Weight is carried out by the left part
if(Weight ~= 1)
LeftPart(1:2*Np+1) = Weight*LeftPart(1:2*Np+1);
end
else %Off-diagonal blocks
MNq = [-Nq:Nq].';
% Common part to every integral operators:
% Distance and angle between centers
bpq = norm(Op - Oq);
alphapq=fangle(Op, Oq);
%Toeplitz Structure of the extra-diagonal block
C = [-Nq+Np:-1:-Nq-Np];
R = [-Nq+Np:1:Nq+Np];
% [Nq-(-Np):-1:-Nq-(-Np), -Nq+(Np)-1:-1:-Nq-(Np)];
%Like a convolution product
% Root_Vector = [R(end:-1:1), C(2:end)].';
%or a cross-corellation
Root_Vector = [C(end:-1:2), R].';
if(ScalarTypeOfOperator > 1)
MiddlePart(1:length(Root_Vector)) = 1i*pi*0.5*besselh(Root_Vector,1,k*bpq).*exp(1i.*Root_Vector.*alphapq);
else
MiddlePart(1:length(Root_Vector)) = zeros(size(Root_Vector));
end
%Uncommon part:
switch ScalarTypeOfOperator
case -1, %custom operator
[LeftPart(1:2*Np+1), RightPart(1:2*Nq+1)] = ...
varargin{2}(Op, ap, Np, Oq, aq, Nq, Nmax, k, varargin{3:end});
case 0, %Null matrix
case 1, %Identity (=> null on off diagonal blocks)
case 2, %Single Layer
Jm_kap = besselj(MNp,k*ap);
Jm_kaq = besselj(MNq,k*aq);
LeftPart(1:2*Np+1) = sqrt(ap)*Jm_kap;
RightPart(1:2*Nq+1) = sqrt(aq)*Jm_kaq;
case 3, %Double Layer
Jm_kap = besselj(MNp,k*ap);
dJm_kaq = dbesselj(MNq,k*aq);
LeftPart(1:2*Np+1) = -sqrt(ap)*Jm_kap;
RightPart(1:2*Nq+1) = k*sqrt(aq)*dJm_kaq;
case 4, %Dn Single Layer
dJm_kap = dbesselj(MNp,k*ap);
Jm_kaq = besselj(MNq,k*aq);
LeftPart(1:2*Np+1) = k*sqrt(ap)*dJm_kap;
RightPart(1:2*Nq+1) = sqrt(aq)*Jm_kaq;
case 5, %Dn Double Layer
dJm_kap = dbesselj(MNp,k*ap);
dJm_kaq = dbesselj(MNq,k*aq);
LeftPart(1:2*Np+1) = -k*sqrt(ap)*dJm_kap;
RightPart(1:2*Nq+1) = k*sqrt(aq)*dJm_kaq;
case 6, % Single scattering preconditioned single layer (Dirichlet)
H1m_kap_inv = 1./besselh(MNp,1,k*ap);
Jm_kaq = besselj(MNq,k*aq);
LeftPart(1:2*Np+1) = 1./sqrt(ap)*H1m_kap_inv;
RightPart(1:2*Nq+1) = 1/(1i*pi*0.5)*sqrt(aq)*Jm_kaq;
case 7, % Single scattering preconditioned dn double layer (Neumann)
dH1m_kap_inv = 1./dbesselh(MNp,1,k*ap);
dJm_kaq = dbesselj(MNq,k*aq);
LeftPart(1:2*Np+1) = 1./sqrt(ap)*dH1m_kap_inv;
RightPart(1:2*Nq+1) = 1/(1i*pi*0.5)*sqrt(aq)*dJm_kaq;
end
%Weight is carried out by the left part
if(Weight ~=1)
LeftPart(1:2*Np+1) = Weight*LeftPart(1:2*Np+1);
end
end
end
|
github
|
mu-diff/mu-diff-master
|
SpBlockDnSingleLayer.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Block/SpBlockDnSingleLayer.m
| 2,713 |
utf_8
|
b78158b6b2e74364d1e8da3585d8ab39
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the normal derivative trace of the
% single layer integral operator from obstacle q to obstacle p, in the
% Fourier basis:
% (N_q rho_q) |_{\Gamma_p}
% IMPORTANT REMARK: the jump relation are NOT taken into account and the
% identity operator is thus NOT contained in the obtained matrix. So it is
% not "really" the normal trace of the single layer if Gammap == Gammaq.
% SPARSE VERSION
% -------------------------------------------------------------------------
% Normal derivative trace of the Single-Layer operator for a density
% rho_q in H^{-1/2}(Gamma_q)
% for all x in \Gamma_p :
% N_q rho_q (x) = \int_{Gamma_q} dn_x G(x,y) rho_q(y) dy
%
% n = unit outward normal of the boundary Gamma_p of Omega_p, pointing
% outside Omega_p
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% [LeftPart, MiddlePart, RightPart] = SpBlockDnSingleLayer(Op, ap, Np, Oq, aq, Nq, Nmax, k)
%
% OUTPUT ARGUMENTS:
% -----------------
% LeftPart [2*Nmax+1, 1] : Left part in the off-diag. blocks and
% also the diagonal blocks of the matrix
% MiddlePart [2*(2*Nmax+1)-1, 1] : Middle part (Toeplitz part) of the
% off-diag. blocks
% RightPart [2*Nmax+1, 1] : Right part of the off-diag. blocks
%
%
% INPUT ARGUMENTS:
% ----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of
% obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of
% obstacle q
% Nmax [1 x 1] : Reference number N (max of every other Np)
% k [1 x 1] : Wavenumber in the vacuum
%
% See also SpBlockIntegralOperator, SpIntegralOperator, SpMatVec,
% BlockIntegralOperator, IntegralOperator
%
function [LeftPart, MiddlePart, RightPart] = SpBlockDnSingleLayer(Op, ap, Np, Oq, aq, Nq, Nmax, k)
[LeftPart, MiddlePart, RightPart] = SpBlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, Nmax, k, 2);
end
|
github
|
mu-diff/mu-diff-master
|
SpBlockPrecondNeumann.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Block/SpBlockPrecondNeumann.m
| 2,094 |
utf_8
|
fdc422eff1332a083a1df637ab35a177
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the integral operator obtained by
% preconditioning the dn double-layer by the single scattering of
% sound-hard obstacles (Neumann), from obstacle q to obstacle p, in the
% Fourier basis
% SPARSE VERSION
% -------------------------------------------------------------------------
% [LeftPart, MiddlePart, RightPart] = SpBlockPrecondNeumann(Op, ap, Np, Oq, aq, Nq, Nmax, k)
%
% OUTPUT ARGUMENTS:
% -----------------
% LeftPart [2*Nmax+1, 1] : Left part in the off-diag. blocks and
% also the diagonal blocks of the matrix
% MiddlePart [2*(2*Nmax+1)-1, 1] : Middle part (Toeplitz part) of the
% off-diag. blocks
% RightPart [2*Nmax+1, 1] : Right part of the off-diag. blocks
%
%
% INPUT ARGUMENTS:
% ----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of
% obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of
% obstacle q
% Nmax [1 x 1] : Reference number N (max of every other Np)
% k [1 x 1] : Wavenumber in the vacuum
%
% See also SpBlockIntegralOperator, SpIntegralOperator, SpMatVec,
% BlockIntegralOperator, IntegralOperator
%
function [LeftPart, MiddlePart, RightPart] = SpBlockPrecondNeumann(Op, ap, Np, Oq, aq, Nq, Nmax, k)
[LeftPart, MiddlePart, RightPart] = SpBlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, Nmax, k, 5);
end
|
github
|
mu-diff/mu-diff-master
|
SpBlockIdentity.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Block/SpBlockIdentity.m
| 1,845 |
utf_8
|
7a2fbc3230e3469074c38eac98812152
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the identity (p==q) or the null matrix (p~=q)
% -------------------------------------------------------------------------
% [LeftPart, MiddlePart, RightPart] = SpBlockIdentity(Op, ap, Np, Oq, aq, Nq, Nmax)
%
% OUTPUT ARGUMENTS:
% -----------------
% LeftPart [2*Nmax+1, 1] : Left part in the off-diag. blocks and
% also the diagonal blocks of the matrix
% MiddlePart [2*(2*Nmax+1)-1, 1] : Middle part (Toeplitz part) of the
% off-diag. blocks
% RightPart [2*Nmax+1, 1] : Right part of the off-diag. blocks
%
%
% INPUT ARGUMENTS:
% ----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of
% obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of
% obstacle q
% Nmax [1 x 1] : Reference number N (max of every other Np)
%
% See also SpBlockIntegralOperator, SpIntegralOperator, SpMatVec,
% BlockIntegralOperator, IntegralOperator, SpIdentity
%
function [LeftPart, MiddlePart, RightPart] = SpBlockIdentity(Op, ap, Np, Oq, aq, Nq, Nmax)
[LeftPart, MiddlePart, RightPart] = SpBlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, Nmax, 1, 1);
end
|
github
|
mu-diff/mu-diff-master
|
SpBlockDoubleLayer.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Block/SpBlockDoubleLayer.m
| 2,703 |
utf_8
|
4ddbeeaf3e546233dbcf7ac6b9a1e3e6
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the trace of the double-layer integral
% operator from obstacle q to obstacle p, in the Fourier basis:
% (M_q lambda_q) |_{\Gamma_p}
% IMPORTANT REMARK: the jump relation are NOT taken into account and the
% identity operator is thus NOT contained in the obtained matrix. So it is
% not "really" the normal trace of the single layer if Gammap == Gammaq.
% SPARSE VERSION
% -------------------------------------------------------------------------
% Trace of the double-layer operator for a density lambda_q in H^{-1/2}(Gamma_q)
% for all x in \Gamma_p (beware the minus sign!):
% M_q lambda_q (x) = -\int_{Gamma_q} dn_y G(x,y) lambda_q(y) dy
%
% n = unit outward normal of the boundary Gamma_p of Omega_p, pointing
% outside Omega_p
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% [LeftPart, MiddlePart, RightPart] = SpBlockDoubleLayer(Op, ap, Np, Oq, aq, Nq, Nmax, k)
%
% OUTPUT ARGUMENTS:
% -----------------
% LeftPart [2*Nmax+1, 1] : Left part in the off-diag. blocks and
% also the diagonal blocks of the matrix
% MiddlePart [2*(2*Nmax+1)-1, 1] : Middle part (Toeplitz part) of the
% off-diag. blocks
% RightPart [2*Nmax+1, 1] : Right part of the off-diag. blocks
%
%
% INPUT ARGUMENTS:
% ----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of
% obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of
% obstacle q
% Nmax [1 x 1] : Reference number N (max of every other Np)
% k [1 x 1] : Wavenumber in the vacuum
%
% See also SpBlockIntegralOperator, SpIntegralOperator, SpMatVec,
% BlockIntegralOperator, IntegralOperator
%
function [LeftPart, MiddlePart, RightPart] = SpBlockDoubleLayer(Op, ap, Np, Oq, aq, Nq, Nmax, k)
[LeftPart, MiddlePart, RightPart] = SpBlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, Nmax, k, 2);
end
|
github
|
mu-diff/mu-diff-master
|
SpBlockSingleLayer.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Block/SpBlockSingleLayer.m
| 2,443 |
utf_8
|
6bf50bec022f5448b728073b15bc70ad
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the trace of the single layer integral
% operator from obstacle q to obstacle p, in the Fourier basis:
% (L_q rho_q) |_{\Gamma_p}
% SPARSE VERSION
% -------------------------------------------------------------------------
% Trace of the Single-Layer operator for a density rho_q in H^{-1/2}(Gamma_q)
% for all x in \Gamma_p :
% L_q rho_q (x) = \int_{Gamma_q} G(x,y) rho_q(y) dy
%
% n = unit outward normal of the boundary Gamma_p of Omega_p, pointing
% outside Omega_p
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% [LeftPart, MiddlePart, RightPart] = SpBlockSingleLayer(Op, ap, Np, Oq, aq, Nq, Nmax, k)
%
% OUTPUT ARGUMENTS:
% -----------------
% LeftPart [2*Nmax+1, 1] : Left part in the off-diag. blocks and
% also the diagonal blocks of the matrix
% MiddlePart [2*(2*Nmax+1)-1, 1] : Middle part (Toeplitz part) of the
% off-diag. blocks
% RightPart [2*Nmax+1, 1] : Right part of the off-diag. blocks
%
%
% INPUT ARGUMENTS:
% ----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of
% obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of
% obstacle q
% Nmax [1 x 1] : Reference number N (max of every other Np)
% k [1 x 1] : Wavenumber in the vacuum
%
% See also SpBlockIntegralOperator, SpIntegralOperator, SpMatVec,
% BlockIntegralOperator, IntegralOperator
%
%%
function [LeftPart, MiddlePart, RightPart] = SpBlockSingleLayer(Op, ap, Np, Oq, aq, Nq, Nmax, k)
[LeftPart, MiddlePart, RightPart] = SpBlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, Nmax, k, 0);
end
|
github
|
mu-diff/mu-diff-master
|
SpBlockPrecondDirichlet.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Block/SpBlockPrecondDirichlet.m
| 2,092 |
utf_8
|
0dd32aa0308892a6f1103a389740f84a
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the integral operator obtained by
% preconditioning the single-layer by the single scattering of sound-soft
% obstacles (Dirichlet), from obstacle q to obstacle p, in the Fourier basis
% SPARSE VERSION
% -------------------------------------------------------------------------
% [LeftPart, MiddlePart, RightPart] = SpBlockPrecondDirichlet(Op, ap, Np, Oq, aq, Nq, Nmax, k)
%
% OUTPUT ARGUMENTS:
% -----------------
% LeftPart [2*Nmax+1, 1] : Left part in the off-diag. blocks and
% also the diagonal blocks of the matrix
% MiddlePart [2*(2*Nmax+1)-1, 1] : Middle part (Toeplitz part) of the
% off-diag. blocks
% RightPart [2*Nmax+1, 1] : Right part of the off-diag. blocks
%
%
% INPUT ARGUMENTS:
% ----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of
% obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of
% obstacle q
% Nmax [1 x 1] : Reference number N (max of every other Np)
% k [1 x 1] : Wavenumber in the vacuum
%
% See also SpBlockIntegralOperator, SpIntegralOperator, SpMatVec,
% BlockIntegralOperator, IntegralOperator
%
function [LeftPart, MiddlePart, RightPart] = SpBlockPrecondDirichlet(Op, ap, Np, Oq, aq, Nq, Nmax, k)
[LeftPart, MiddlePart, RightPart] = SpBlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, Nmax, k, 4);
end
|
github
|
mu-diff/mu-diff-master
|
SpBlockDnDoubleLayer.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Block/SpBlockDnDoubleLayer.m
| 2,537 |
utf_8
|
b88754d673b2a5e4d50b28e48587c5fa
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the normal derivative trace of the
% double layer integral operator from obstacle q to obstacle p,
% in the Fourier basis:
% (D_q lambda_q) |_{\Gamma_p}
% SPARSE VERSION
% -------------------------------------------------------------------------
% Normal derivative trace of the Double-Layer integral operator for a
% density lambda_q in H^{1/2}(Gamma_q) (beware the "minus" sign!)
% for all x in Gamma_p:
% D_q lambda_q(x) = - dn_x \int_{Gamma} dn_y G(x,y) lambda(y) dy
%
% n = unit outward normal of the boundary Gamma_p of Omega_p, pointing
% outside Omega_p
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% [LeftPart, MiddlePart, RightPart] = SpBlockDnDoubleLayer(Op, ap, Np, Oq, aq, Nq, Nmax, k)
%
% OUTPUT ARGUMENTS:
% -----------------
% LeftPart [2*Nmax+1, 1] : Left part in the off-diag. blocks and
% also the diagonal blocks of the matrix
% MiddlePart [2*(2*Nmax+1)-1, 1] : Middle part (Toeplitz part) of the
% off-diag. blocks
% RightPart [2*Nmax+1, 1] : Right part of the off-diag. blocks
%
%
% INPUT ARGUMENTS:
% ----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of
% obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of
% obstacle q
% Nmax [1 x 1] : Reference number N (max of every other Np)
% k [1 x 1] : Wavenumber in the vacuum
%
% See also SpBlockIntegralOperator, SpIntegralOperator, SpMatVec,
% BlockIntegralOperator, IntegralOperator
%
function [LeftPart, MiddlePart, RightPart] = SpBlockDnDoubleLayer(Op, ap, Np, Oq, aq, Nq, Nmax, k)
[LeftPart, MiddlePart, RightPart] = SpBlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, Nmax, k, 3);
end
|
github
|
mu-diff/mu-diff-master
|
SpPrecondNeumann.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Full/SpPrecondNeumann.m
| 1,407 |
utf_8
|
4870ae0a77c82798369debe245604ea9
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the integral operator obtained by preconditioning
% the Dn double-layer operator by its single-scattering operator for a
% collection of sound-hard obstacles (Neumann), in the Fourier basis.
% SPARSE VERSION.
% -------------------------------------------------------------------------
% A = SpPrecondNeumann(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A : cell(3,1) of the system
%
% Input Arguments (N_scat = length(a) = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
% k [1 x 1] : Wavenumber in the vacuum
%
% See also PrecondNeumann, SpBlockIntegralOperator, SpIntegralOperator, SpMatVec
%%
function A = SpPrecondNeumann(O, a, M_modes, k)
A = SpIntegralOperator(O, a, M_modes, k, 7);
end
|
github
|
mu-diff/mu-diff-master
|
SpDoubleLayer.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Full/SpDoubleLayer.m
| 1,705 |
utf_8
|
4b6b69459209e9fd624465ff0beecf89
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the trace of the double-layer integral operator
% in the Fourier basis.
% SPARSE VERSION.
% -------------------------------------------------------------------------
% Trace of the double-Layer operator M for a density lambda in H^{1/2}(Gamma)
% (beware the "minus" sign!).
% for all x in \Gamma :
% M lambda(x) = - \int_{Gamma} G(x,y) lambda(y) dy
%
% n = unit outward normal of the boundary Gamma of Omega, pointing
% outside Omega
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% A = SpDoubleLayer(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A : cell(3,1) of the system
%
% Input Arguments (N_scat = length(a) = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
% k [1 x 1] : Wavenumber in the vacuum
%
% See also DoubleLayer, SpBlockIntegralOperator, SpIntegralOperator, SpMatVec
%%
function A = SpDoubleLayer(O, a, M_modes, k)
A = SpIntegralOperator(O, a, M_modes, k, 3);
end
|
github
|
mu-diff/mu-diff-master
|
SpDnSingleLayer.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Full/SpDnSingleLayer.m
| 1,717 |
utf_8
|
102687e6537afe279286c13788e4e259
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the normal derivative trace of the single layer
% integral operator in the Fourier basis.
% SPARSE VERSION.
% -------------------------------------------------------------------------
% Normal derivative trace of the single-layer N operator for a density
% rho in H^{-1/2}(Gamma).
% for all x in \Gamma :
% N rho (x) = \int_{Gamma} dn_x G(x,y) rho(y) dy
%
% n = unit outward normal of the boundary Gamma of Omega, pointing
% outside Omega
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% A = SpDnSingleLayer(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A : cell(3,1) of the system
%
% Input Arguments (N_scat = length(a) = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
% k [1 x 1] : Wavenumber in the vacuum
%
% See also DnSingleLayer, SpBlockIntegralOperator, SpIntegralOperator, SpMatVec
%%
function A = SpDnSingleLayer(O, a, M_modes, k)
A = SpIntegralOperator(O, a, M_modes, k, 4);
end
|
github
|
mu-diff/mu-diff-master
|
SpDnDoubleLayer.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Full/SpDnDoubleLayer.m
| 1,756 |
utf_8
|
f8b7d7a919243a1b316cfee9ed4538c3
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the normal derivative trace of the double-layer
% integral operator in the Fourier basis.
% SPARSE VERSION
% -------------------------------------------------------------------------
% Normal derivative trace of the double-Layer operator D for a density
% lambda in H^{1/2}(Gamma) (beware the "minus" sign!)
% for all x in \Gamma :
% D lambda(x) = - dn_x \int_{Gamma} dn_y G(x,y) lambda(y) dy
%
% n = unit outward normal of the boundary Gamma of Omega, pointing
% outside Omega
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% A = SpDnDoubleLayer(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A : cell(3,1) of the system
%
% Input Arguments (N_scat = length(a) = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
% k [1 x 1] : Wavenumber in the vacuum
%
% See also DnDoubleLayer, SpBlockIntegralOperator, SpIntegralOperator, SpMatVec
%%
function A = SpDnDoubleLayer(O, a, M_modes, k)
A = SpIntegralOperator(O, a, M_modes, k, 5);
end
|
github
|
mu-diff/mu-diff-master
|
SpSingleLayer.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Full/SpSingleLayer.m
| 1,702 |
utf_8
|
f09b3fdd43ac9a88a7a77f1ae26294d2
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the trace of the single layer integral operator
% for the multiple scattering problem in the Fourier bases.
% SPARSE VERSION.
% -------------------------------------------------------------------------
% Trace of the single-layer operator L for a density rho in H^{-1/2}(Gamma)
% for all x in \Gamma :
% L rho (x) = \int_{Gamma} G(x,y) rho(y) dy
%
% n = unit outward normal of the boundary Gamma of Omega, pointing
% outside Omega
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% A = SpSingleLayer(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A : cell(3,1) of the system
%
% Input Arguments (N_scat = length(a) = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
% k [1 x 1] : Wavenumber in the vacuum
%
% See also SingleLayer, SpBlockIntegralOperator, SpIntegralOperator, SpMatVec
%%
function A = SpSingleLayer(O, a, M_modes, k)
A = SpIntegralOperator(O, a, M_modes, k, 2);
end
|
github
|
mu-diff/mu-diff-master
|
SpIdentity.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Full/SpIdentity.m
| 1,213 |
utf_8
|
258914574c33cb859d5d992a3f372c5e
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the identity operator for the multiple scattering
% problem in the Fourier bases.
% SPARSE VERSION.
% -------------------------------------------------------------------------
% I = SpIdentity(O, a, M_modes)
%
% Output Arguments :
% -----------------
% I : cell(3,1) of the system
%
% Input Arguments (N_scat = length(a) = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
%
% See also SpBlockIntegralOperator, SpIntegralOperator, SpMatVec
%%
function I = SpIdentity(O, a, M_modes)
I = SpIntegralOperator(O, a, M_modes, 1, 1);
end
|
github
|
mu-diff/mu-diff-master
|
SpPrecondDirichlet.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Interface/Full/SpPrecondDirichlet.m
| 1,412 |
utf_8
|
a21c1b5da72b1d0656f23d74db88d3aa
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the integral operator obtained by preconditioning
% the single-layer operator by its single-scattering operator for a
% collection of sound-soft obstacles (Dirichlet), in the Fourier basis.
% SPARSE VERSION.
% -------------------------------------------------------------------------
% A = SpPrecondDirichlet(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A : cell(3,1) of the system
%
% Input Arguments (N_scat = length(a) = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
% k [1 x 1] : Wavenumber in the vacuum
%
% See also PrecondDirichlet, SpBlockIntegralOperator, SpIntegralOperator, SpMatVec
%%
function A = SpPrecondDirichlet(O, a, M_modes, k)
A = SpIntegralOperator(O, a, M_modes, k, 6);
end
|
github
|
mu-diff/mu-diff-master
|
SpMatVec.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Functions/SpMatVec.m
| 2,751 |
utf_8
|
a8fae9a9150d9865690d1c50de3f2ef6
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Sparse matrix vector product between possibly multiple matrices A and a
% vector X. Matrices are stored as a cell and have the special structure:
% A{1} = LeftPart (off-diagonal blocks + diagonal blocks)
% A{2} = Toeplitz Part (off-diagonal blocks)
% A{3} = RightPart (off-diagonal blocks)
% -------------------------------------------------------------
% The matrix vector product is done through a cross-correlation using xcorr
% Matlab function.
% -------------------------------------------------------------
% Y = SpMatVec(X, M_modes, ListOfOperators, varargin)
%
% OUTPUT ARGUMENT:
% ----------------
% Y [size(X)] : A*X
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------------------------------------
%
% X [sum(2*M_modes+1), 1] : Vector
% M_Modes [N_scat, 1] : Truncation index in the Fourier series of
% obstacles
% ListOfOperators cell(NOp,1) : Cell array of integral operators (sparse storage)
%
% OPTION (weight):
% ----------------
% Y = SpMatVec(X, M_modes, ListOfOperators, ListOfWeight)
%
% ListOfWeight [length(ListOfOperators), 1] : list of multiplicative constant
% to apply to the operators
%
% EXAMPLE:
% --------
% Compute Y =(0.5*I + N)X, where I = identity and N = DnSingleLayer:
% > [A{1},A{2},A{3}] = SpDnSingleLayer(O, a, M_modes, k)
% > [I{1},I{2},I{3}] = SpIdentity(O, a, M_modes);
% > Y = SpMatVec(X, M_modes, [I,A], [0.5, 1]);
%
% See also SpSingleMatVec, SpBlockIntegralOperator, SpIntegralOperator, xcorr
%
function Y = SpMatVec(X, M_modes, ListOfOperators, varargin)
noperator = size(ListOfOperators, 2);
if(length(varargin) >= 1)
Weight = varargin{1};
if(iscell(Weight))
Weight = cell2mat(Weight);
end
else
Weight = ones(1,noperator);
end
%To do
if(length(varargin) >= 2)
OpMask = varargin{2};
else
OpMask = ones(1,noperator-1);
end
%Check
if(length(Weight) ~= noperator)
error('Weight must be of size size(ListOfOperators,2)');
end
if(length(OpMask) ~= noperator-1)
error('There must be ''size(ListOfOperators,2)-1'' operations');
end
Y = zeros(size(X));
for iOper = 1:noperator
if(noperator == 1)
A = ListOfOperators;
else
A = ListOfOperators{iOper};
end
this_weight = Weight(iOper);
Y = Y + this_weight*SpSingleMatVec(X, M_modes, A);
clear A this_weight;
end
|
github
|
mu-diff/mu-diff-master
|
SpAddIdentity.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Functions/SpAddIdentity.m
| 906 |
utf_8
|
08801067ddc4f132c3631bba00e3782b
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Returns A + alpha*I where A is a sparse operator already computed.
% A = SpAddIdentity(A, alpha, M_modes)
% The addition with identity can be done directly in the creation of the
% matrix A. This function is hence used as a "post-processing". The
% alpha-identity is added to the "Left-Part" of A (ie: A{1}).
%
% See also SpIntegralOperator, SpBlockIntegralOperator, SpMatVec
function A = SpAddIdentity(A, alpha, M_modes)
N_scat = size(A{1},2);
for p = 1:N_scat
Np = M_modes(p);
A{1}(1:2*Np+1,p,p) = alpha + A{1}(1:2*Np+1,p,p);
end
end
|
github
|
mu-diff/mu-diff-master
|
SpSingleMatVec.m
|
.m
|
mu-diff-master/IntOperators/Sparse/Functions/SpSingleMatVec.m
| 2,390 |
utf_8
|
c06a3cc43c811d4cecc95c6e0dd22bb7
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Sparse matrix vector product between a single matrix A and a vector X
% The matrix A is stored as a cell and has the special structure:
% A{1} = LeftPart (off-diagonal blocks + diagonal blocks)
% A{2} = Toeplitz Part (off-diagonal blocks)
% A{3} = RightPart (off-diagonal blocks)
% -------------------------------------------------------------
% The matrix vector product is done through a cross-correlation using xcorr
% Matlab function.
% -------------------------------------------------------------
% Y = SpSingleMatVec(X, M_modes, A)
%
% OUTPUT ARGUMENT:
% ----------------
% Y [size(X)] : A*X
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------------------------------------
%
% X [sum(2*M_modes+1), 1] : Vector
% M_Modes [N_scat, 1] : Truncation index in the Fourier series of
% obstacles
% A cell(3,1) : Integral operator (sparse storage)
%
%
% See also SpMatVec, SpBlockIntegralOperator, SpIntegralOperator, xcorr
%
function Y = SpSingleMatVec(X, M_modes, A)
N_scat = length(M_modes);
Y = zeros(size(X));
Sp = 0;
for p=1:N_scat
Np = M_modes(p);
Sq = 0;
for q =1: N_scat
Nq = M_modes(q);
if(q==p) %Diagonal part of the matrix.
Xp = X(Sp+1: Sp + 2*Np+1);
Y(Sp+1: Sp + 2*Np+1) = Y(Sp+1: Sp + 2*Np+1) + A{1}(1:2*Np+1,p,p).*Xp ;
else
Xq = X(Sq+1: Sq+2*Nq+1);
%Roughly speaking :
%A{1}(:,p,q) * A{2}(:,p,q) * A{3}(:,p,q) *Xq
%Where A{2} is Toeplitz, and A{1} and A{3} are diagonals.
Zq = A{3}(1:2*Nq+1,p,q).*Xq;
SizeRootVector = 2*Np + 2*Nq +1;
% Zq_extended = [Zq;zeros(SizeMax-SizeRootVector,1)];
cross_cor = xcorr(Zq, conj(A{2}(1:SizeRootVector,p,q)));
Y(Sp+1: Sp + 2*Np+1) = Y(Sp+1: Sp + 2*Np+1) + ...
A{1}(1:2*Np+1,p,q).*cross_cor(2*Nq+1:2*Nq+1+2*Np);
clear Zq Zq_extended cross_cor;
end
Sq = Sq + 2*Nq+1;
end
Sp = Sp + 2*Np+1;
end
|
github
|
mu-diff/mu-diff-master
|
IntegralOperator.m
|
.m
|
mu-diff-master/IntOperators/Dense/IntegralOperator.m
| 5,103 |
utf_8
|
fb4609332af019fba66a132cad158476
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of one of the integral operator
% -------------------------------------------------------------------------
% A = IntegralOperator(O, a, M_modes, k, TypeOfOperator)
%
% OUTPUT ARGUMENTS:
% -----------------
% A [2*sum(M_modes+1) x 2*sum(M_modes+1)] : Matrix of the system
%
% INPUT ARGUMENTS (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Coordinates of the center of the disk 1
% a [1 x N_scat] : Radius of disk 1
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
% or [1 x N_scat] if k is a row/column, then k(p) = wavenumber
% associated to obstacle p
% TypeOfOperator (See below) : Specifies the integral operator.
% See Comon/Parser.m for correspondance.
%
% TypeOfOperator acceptable size/type:
% ------------------------------------
% - SINGLE VALUE: IntegralOperator(..., 2) or IntegralOperator(..., {'L'})
% - ROW VECTOR/CELL: IntegralOperator(..., [1,4]) produces I+N
% OR IntegralOperator(..., {'I','N'}) produces I+N
% - 2D ARRAY/CELL: IntegralOperator(..., T) then block (p,q) is of type
% T(p,q) or T{p,q}
% - 3D ARRAY/CELL: IntegralOperator(..., T) then block (p,q) is the sum
% of the different types:
% T(p,q,1) + T(p,q,2) + ... T(p,q,end)
% T{p,q,1} + T{p,q,2} + ... T{p,q,end}
%
% OPTIONS (weight):
% -----------------
% A = IntegralOperator(..., TypeOfOperator, Weight)
% where Weight is of the same size as TypeOfOperator and contains
% multiplicative constants to apply to the desired operator:
% - SCALAR value: IntegralOperator(..., 2, 0.5) produces 0.5*L
% - ROW VECTOR value: IntegralOperator(..., [1,4], [0.5,1]) produces 0.5*I+N
% - MATRIX value T, W: IntegralOperator(..., T, W) then block (p,q) is of type
% W(p,q)*T(p,q)
% - 3D Matrix value T, W: IntegralOperator(..., T, W) then block (p,q) is the sum
% of the different types:
% W(p,q,1)*T(p,q,1) + W(p,q,2)*T(p,q,2) + ... W(p,q,end)*T(p,q,end)
%
% EXAMPLE:
% --------
% 1) Compute N (DnSingleLayer)
% > A = IntegralOperator(O, a, M_modes, k, 4);
%
% 2) For two obstacles in [-10,0] and [0,10] with radii 1 and 0.5, compute
% the matrix [L_11, 2*D_12; 3*N_21, 4*M_22]:
% > O = [-10, 0; 0, 10];
% > a = [1, 0.5]
% > TypeOfOp = [2,5;4,3];
% > Weight = [1,2;3,4];
% > A = IntegralOperator(O, a, M_modes, k, TypeOfOp, Weight);
%
% 3) Compute the single-scattering operator of the single-layer
% (off-diagonal block =0 and diagonal block = L_pp)
% > TypeOfOp = 2*eye(N_scat, N_scat);
% > A = IntegralOperator(O, a, M_modes, k, TypeOfOp);
%
% See also Parser, BlockIntegralOperator
% SpBlockIntegralOperator, SpIntegralOperator, SingleLayer,
% DnSingleLayer, DoubleLayer, DnDoubleLayer,
% PrecondOperator_Dirichlet, PrecondOperator_Neumann
%
function [A] = IntegralOperator(O, a, M_modes, k, TypeOfOperator, varargin)
ScalarTypeOfOperator = ParserIntegralOperator(TypeOfOperator);
nvarargin = length(varargin);
if(nvarargin >= 1)
Weight = varargin{1};
else
Weight = ones(size(ScalarTypeOfOperator));
end
if(size(Weight) ~=size(ScalarTypeOfOperator))
error('Matrix of TypeOfOperator and Weight must be of same size!');
end
%Initialization
N_scat = length(a);
Sum_modes = 2.*M_modes + 1;
sizeA = sum(Sum_modes);
A = zeros(sizeA, sizeA);
%Sp is a row-counter
Sp = 0;
%Loop on the obstacles
for p = 1:N_scat
%Center and radius of the scatterer p
Op = O(:,p);
ap = a(p);
%Vector of the modes associated with the scattererd number p
Np = M_modes(p);
MNp = [-Np:Np].';
%Sq is a column-counter
Sq = 0;
%Second loop on the obstacles
for q = 1:N_scat
%Center and radius of the scatterer p
Oq = O(:,q);
aq = a(q);
%Vector of the modes associated with the scattererd number q
Nq = M_modes(q);
MNq = [-Nq:Nq].';
%Compute the block matrix
this_TypeOfOperator = GetTypeOfOperatorOrWeight(ScalarTypeOfOperator, p, q);
this_weight = GetTypeOfOperatorOrWeight(Weight, p, q);
this_k = GetK(k, p);
A(Sp + MNp +(Np+1), Sq + MNq +(Nq+1)) = ...
BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, this_k, ...
this_TypeOfOperator, this_weight, varargin{2:end});
%Upgrade of the column-counter
Sq = Sq + 2*Nq+1;
end
%Upgrade of the row-counter
Sp = Sp + 2*Np+1;
end
end
|
github
|
mu-diff/mu-diff-master
|
BlockIntegralOperator.m
|
.m
|
mu-diff-master/IntOperators/Dense/BlockIntegralOperator.m
| 7,614 |
utf_8
|
978e35380f5b4e6ad95251e881109dd7
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of one of the integral operator in
% the Fourier basis
% -------------------------------------------------------------------------
% Apq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, TypeOfOperator, ...)
%
% OUTPUT ARGUMENTS:
% -----------------
% Apq [2*Np+1 x 2*Nq+1] : submatrix of the system
%
% INPUT ARGUMENTS:
% ----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of
% obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of
% obstacle q
% k [1 x 1] : Wavenumber in the vacuum
% TypeOfOperator (See below) : Specifies the integral operator.
% See Comon/Parser.m for correspondance.
%
% TypeOfOperator acceptable size/type:
% ------------------------------------
% - SINGLE VALUE: BlockIntegralOperator(..., 2) or BlockIntegralOperator(..., {'L'})
% - ROW VECTOR/CELL: multiple operators are computed and together. For example:
% TypeOfOperator = [1,4] or TypeOfOperator = {'I','N'}
% will produce I + N
%
% OPTIONS:
% --------
% Apq = blockIntegralOperator(..., TypeOfOperator, Weight)
% Weight [1 x 1] : multiplicative constant to apply to the operator(s)
% or [1 x Nop]
%
% EXAMPLES:
% ---------
% BlockIntegralOperator(..., 2, 0.5) will produce 0.5*L
% OR for the same result: BlockIntegralOperator(..., 'L', 0.5)
% BlockIntegralOperator(..., [1,4], [0.5,1]) will produce: 0.5*I + N
% OR BlockIntegralOperator(..., {'L','N'}, [0.5,1]) will produce: 0.5*I + N
%
% See also Parser, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator, BlockSingleLayer,
% BlockDnSingleLayer, BlockDoubleLayer, BlockDnDoubleLayer,
% BlockPrecondDirichlet, BlockPrecondNeumann
%%
function Apq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, TypeOfOperator, varargin)
nvarargin = length(varargin);
if(nvarargin >= 1)
Weight = varargin{1};
else
Weight = ones(size(TypeOfOperator));
end
if(size(Weight) ~=size(TypeOfOperator))
error('Matrix of TypeOfOperator and Weight must be of same size!');
end
ScalarTypeOfOperator = ParserIntegralOperator(TypeOfOperator);
nTypeOfOperator = length(ScalarTypeOfOperator);
%Initialization of the submatrix Apq
Apq = zeros(2*Np+1, 2*Nq+1);
%Vector of the modes associated with the scatterer 1 and 2
MNp = [-Np:Np].';
if (Op(1) == Oq(1) && Op(2) == Oq(2) && ap == aq) % Diagonal block (which is diagonal)
if(Np ~= Nq)
error('Obstacles are the same but with different number of modes !')
end
for iOperator=1:nTypeOfOperator
this_Operator = ScalarTypeOfOperator(iOperator);
this_weight = Weight(iOperator);
if(this_weight == 0)
continue;
end
switch this_Operator
case -1, %Custom operator
Apq = Apq + this_weight*varargin{2}(Op, ap, Np, Oq, aq, Nq, k, varargin{3:end});
case 0, %null Matrix
case 1, % Identity
Apq = Apq + this_weight*eye(2*Np+1, 2*Np+1);
case 2, % Single Layer
Jm_kap = besselj(MNp,k*ap);
H1m_kap = besselh(MNp,1,k*ap);
Apq = Apq + this_weight*diag(1i*ap*pi*0.5*H1m_kap.*Jm_kap);
case 3, % Double Layer
dJm_kap = dbesselj(MNp,k*ap);
H1m_kap = besselh(MNp,1,k*ap);
Apq = Apq + this_weight*diag(0.5 - 1i*k*ap*pi*0.5*H1m_kap.*dJm_kap);
case 4, % Dn Single Layer
dJm_kap = dbesselj(MNp,k*ap);
H1m_kap = besselh(MNp,1,k*ap);
Apq = Apq + this_weight*diag(-0.5 + 1i*k*ap*pi*0.5*H1m_kap.*dJm_kap);
case 5, % Dn Double Layer
dJm_kap = dbesselj(MNp,k*ap);
dH1m_kap = dbesselh(MNp,1,k*ap);
Apq = Apq + this_weight*diag(- 1i*k^2*ap*pi*0.5*dH1m_kap.*dJm_kap);
case 6, % Single scattering preconditioned integral operator for Dirichlet
Apq = Apq + this_weight*eye(2*Np+1, 2*Np+1);
case 7, % Single scattering preconditioned integral operator for Neumann
Apq = Apq + this_weight*eye(2*Np+1, 2*Np+1);
end
end
else %Off-diagonal blocks
if(norm(Op-Oq) - ap -aq <= 0)
error('Obstacles are overlapping !');
end
MNq = [-Nq:Nq].';
% Distance and angle between centers
bpq = norm(Op - Oq);
alphapq=fangle(Op, Oq);
%Toeplitz Structure of the extra-diagonal block
C = [-Nq-(-Np):-1:-Nq-Np];
R = [-Nq+(Np):1:Nq+(Np)];
T = toeplitz(C,R);
for iOperator=1:nTypeOfOperator
this_Operator = ScalarTypeOfOperator(iOperator);
this_weight = Weight(iOperator);
switch this_Operator
case -1, %Custom operator
Apq = Apq + this_weight*varargin{2}(Op, ap, Np, Oq, aq, Nq, k, varargin{3:end});
%case 0 and 1 are the null matrix
case 2, %Single Layer
Jm_kap = besselj(MNp,k*ap);
Jm_kaq = besselj(MNq,k*aq);
Apq = Apq + this_weight*1i*pi*0.5*sqrt(ap*aq)*diag(Jm_kap)*besselh(T,1,k*bpq).*exp(1i.*T.*alphapq)*diag(Jm_kaq);
case 3, % Double Layer
Jm_kap = besselj(MNp,k*ap);
dJm_kaq = dbesselj(MNq,k*aq);
Apq = Apq + this_weight*(-1i)*k*pi*0.5*sqrt(ap*aq)*diag(Jm_kap)*besselh(T,1,k*bpq).*exp(1i.*T.*alphapq)*diag(dJm_kaq);
case 4, % Dn Single Layer
dJm_kap = dbesselj(MNp,k*ap);
Jm_kaq = besselj(MNq,k*aq);
Apq = Apq + this_weight*1i*k*pi*0.5*sqrt(ap*aq)*diag(dJm_kap)*besselh(T,1,k*bpq).*exp(1i.*T.*alphapq)*diag(Jm_kaq);
case 5, % Dn Double Layer
dJm_kap = dbesselj(MNp,k*ap);
dJm_kaq = dbesselj(MNq,k*aq);
Apq = Apq + this_weight*(-1i)*k^2*pi*0.5*sqrt(ap*aq)*diag(dJm_kap)*besselh(T,1,k*bpq).*exp(1i.*T.*alphapq)*diag(dJm_kaq);
case 6, % Single scattering preconditioned integral operator for Dirichlet
H1m_kap_inv = 1./besselh(MNp,1,k*ap);
Jm_kaq = besselj(MNq,k*aq);
Apq = Apq + this_weight*sqrt(aq/ap)*diag(H1m_kap_inv)*besselh(T,1,k*bpq).*exp(1i.*T.*alphapq)*diag(Jm_kaq);
case 7, % Single scattering preconditioned integral operator for Neumann
dH1m_kap_inv = 1./dbesselh(MNp,1,k*ap);
dJm_kaq = dbesselj(MNq,k*aq);
Apq = Apq + this_weight*sqrt(aq/ap)*diag(dH1m_kap_inv)*besselh(T,1,k*bpq).*exp(1i.*T.*alphapq)*diag(dJm_kaq);
end
end
end
end
|
github
|
mu-diff/mu-diff-master
|
BlockSingleLayer.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Block/BlockSingleLayer.m
| 1,779 |
utf_8
|
4ea5cdf699ca1dd8b2801126f2d4a463
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the trace of the single layer integral
% operator from obstacle q to obstacle p, in the Fourier basis:
% (L_q rho_q) |_{\Gamma_p}
% -------------------------------------------------------------------------
% Trace of the Single-Layer operator for a density rho_q in H^{-1/2}(Gamma_q)
% for all x in \Gamma_p :
% L_q rho_q (x) = \int_{Gamma_q} G(x,y) rho_q(y) dy
%
% n = unit outward normal of the boundary Gamma_p of Omega_p, pointing
% outside Omega_p
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% Apq = BlockSingleLayer(Op, ap, Np, Oq, aq, Np, k)
%
% Output Arguments :
% -----------------
% Apq [2*Np+1 x 2*Nq+2] : Matrix of the system
%
% Input Arguments :
% -----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of obstacle q
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function Apq = BlockSingleLayer(Op, ap, Np, Oq, aq, Nq, k)
Apq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 2);
end
|
github
|
mu-diff/mu-diff-master
|
BlockPrecondNeumann.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Block/BlockPrecondNeumann.m
| 1,433 |
utf_8
|
863f6836746a396afa04dc63e86cd248
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the integral operator obtained by
% preconditioning the dn double-layer by the single scattering of
% sound-hard obstacles (Neumann), from obstacle q to obstacle p, in the
% Fourier basis
% -------------------------------------------------------------------------
% Apq = BlockPrecondNeumann(Op, ap, Np, Oq, aq, Np, k)
%
% Output Arguments :
% -----------------
% Apq [2*Np+1 x 2*Nq+2] : Matrix of the system
%
% Input Arguments :
% -----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of obstacle q
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function Apq = BlockPrecondNeumann(Op, ap, Np, Oq, aq, Nq, k)
Apq = blockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 7);
end
|
github
|
mu-diff/mu-diff-master
|
BlockIdentity.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Block/BlockIdentity.m
| 1,222 |
utf_8
|
92e66d5531c2b793a4ec3ec76087e29c
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the identity block (p = q) or the zero matrix (p ~= q)
% -------------------------------------------------------------------------
% Ipq = BlockIdentity(Op, ap, Np, Oq, aq, Np)
%
% Output Arguments :
% -----------------
% Apq [2*Np+1 x 2*Nq+2] : Matrix of the system
%
% Input Arguments :
% -----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of obstacle q
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator, Identity
%%
function Ipq = BlockIdentity(Op, ap, Np, Oq, aq, Nq)
Ipq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, 1, 1);
end
|
github
|
mu-diff/mu-diff-master
|
BlockDnSingleLayer.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Block/BlockDnSingleLayer.m
| 2,053 |
utf_8
|
9c47fbdf8d83541b2158d59b1ecb2e95
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the normal derivative trace of the
% single layer integral operator from obstacle q to obstacle p, in the
% Fourier basis:
% (N_q rho_q) |_{\Gamma_p}
% IMPORTANT REMARK: the jump relation are NOT taken into account and the
% identity operator is thus NOT contained in the obtained matrix. So it is
% not "really" the normal trace of the single layer if Gammap == Gammaq.
% -------------------------------------------------------------------------
% Normal derivative trace of the Single-Layer operator for a density
% rho_q in H^{-1/2}(Gamma_q)
% for all x in \Gamma_p :
% N_q rho_q (x) = \int_{Gamma_q} dn_x G(x,y) rho_q(y) dy
%
% n = unit outward normal of the boundary Gamma_p of Omega_p, pointing
% outside Omega_p
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% Apq = BlockDnSingleLayer(Op, ap, Np, Oq, aq, Np, k)
%
% Output Arguments :
% -----------------
% Apq [2*Np+1 x 2*Nq+2] : Matrix of the system
%
% Input Arguments :
% -----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of obstacle q
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function Apq = BlockDnSingleLayer(Op, ap, Np, Oq, aq, Nq, k)
Apq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 4);
end
|
github
|
mu-diff/mu-diff-master
|
BlockPrecondDirichlet.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Block/BlockPrecondDirichlet.m
| 1,434 |
utf_8
|
a075c93685a2acba223596bd88188a0f
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the integral operator obtained by
% preconditioning the single-layer by the single scattering of sound-soft
% obstacles (Dirichlet), from obstacle q to obstacle p, in the Fourier basis
% -------------------------------------------------------------------------
% Apq = BlockPrecondDirichlet(Op, ap, Np, Oq, aq, Np, k)
%
% Output Arguments :
% -----------------
% Apq [2*Np+1 x 2*Nq+2] : Matrix of the system
%
% Input Arguments :
% -----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of obstacle q
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function Apq = BlockPrecondDirichlet(Op, ap, Np, Oq, aq, Nq, k)
Apq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 6);
end
|
github
|
mu-diff/mu-diff-master
|
BlockDnDoubleLayer.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Block/BlockDnDoubleLayer.m
| 1,875 |
utf_8
|
fb9795a06cbffdcc61b88040b94640af
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the normal derivative trace of the
% double layer integral operator from obstacle q to obstacle p,
% in the Fourier basis:
% (D_q lambda_q) |_{\Gamma_p}
% -------------------------------------------------------------------------
% Normal derivative trace of the Double-Layer integral operator for a
% density lambda_q in H^{1/2}(Gamma_q) (beware the "minus" sign!)
% for all x in Gamma_p:
% D_q lambda_q(x) = - dn_x \int_{Gamma} dn_y G(x,y) lambda(y) dy
%
% n = unit outward normal of the boundary Gamma_p of Omega_p, pointing
% outside Omega_p
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% Apq = BlockDnDoubleLayer(Op, ap, Np, Oq, aq, Np, k)
%
% Output Arguments :
% -----------------
% Apq [2*Np+1 x 2*Nq+2] : Matrix of the system
%
% Input Arguments :
% -----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of obstacle q
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function Apq = BlockDnDoubleLayer(Op, ap, Np, Oq, aq, Nq, k)
Apq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 5);
end
|
github
|
mu-diff/mu-diff-master
|
BlockDoubleLayer.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Block/BlockDoubleLayer.m
| 2,043 |
utf_8
|
652b42bb81b75351be9f4b622eb20529
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix of the trace of the double-layer integral
% operator from obstacle q to obstacle p, in the Fourier basis:
% (M_q lambda_q) |_{\Gamma_p}
% IMPORTANT REMARK: the jump relation are NOT taken into account and the
% identity operator is thus NOT contained in the obtained matrix. So it is
% not "really" the normal trace of the single layer if Gammap == Gammaq.
% -------------------------------------------------------------------------
% Trace of the double-layer operator for a density lambda_q in H^{-1/2}(Gamma_q)
% for all x in \Gamma_p (beware the minus sign!):
% M_q lambda_q (x) = -\int_{Gamma_q} dn_y G(x,y) lambda_q(y) dy
%
% n = unit outward normal of the boundary Gamma_p of Omega_p, pointing
% outside Omega_p
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% Apq = BlockDoubleLayer(Op, ap, Np, Oq, aq, Np, k)
%
% Output Arguments :
% -----------------
% Apq [2*Np+1 x 2*Nq+2] : Matrix of the system
%
% Input Arguments :
% -----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of obstacle q
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function Apq = BlockDoubleLayer(Op, ap, Np, Oq, aq, Nq, k)
Apq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 3);
end
|
github
|
mu-diff/mu-diff-master
|
BlockCalderonProjector.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Block/BlockCalderonProjector.m
| 1,749 |
utf_8
|
94e2bf61553d42ad086c212fa3c0bee4
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the interaction matrix Cpq of the Calderon projector C given by
% C = [I/2+M, L; D, I/2+N]
% and hence
% Cpq = [0.5*Ipq+Mpq, Lpq ; Dpq, 0.5*Ipq+Npq]
% Note that Ipq = 0 if p~=q and Ipq = identity otherwise
% -------------------------------------------------------------------------
% Apq = BlockCalderonProjector(Op, ap, Np, Oq, aq, Nq, k)
%
% Output Arguments :
% -----------------
% Apq [2*Np+1 x 2*Nq+2] : Matrix of the system
%
% Input Arguments :
% -----------------
% Op [2 x 1] : Coordinates of the center of the disk p
% ap [1 x 1] : Radius of disk p
% Np [1 x 1] : Truncation index in the Fourier series of obstacle p
% Oq [2 x 1] : Coordinates of the center of the disk q
% aq [1 x 1] : Radius of disk q
% Nq [1 x 1] : Truncation index in the Fourier series of obstacle q
% k [1 x 1] : Wavenumber in the vacuum
%
% See also CalderonProjector, BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function Apq = BlockCalderonProjector(Op, ap, Np, Oq, aq, Nq, k)
Ipq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 1);
Lpq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 2);
Mpq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 3);
Npq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 4);
Dpq = BlockIntegralOperator(Op, ap, Np, Oq, aq, Nq, k, 5);
Apq = [0.5*Ipq+Mpq, Lpq; Dpq, 0.5*Ipq+Npq];
end
|
github
|
mu-diff/mu-diff-master
|
Identity.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Full/Identity.m
| 1,075 |
utf_8
|
851ccd718671188c331ef9e1af0b301a
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the identity matrix.
% -------------------------------------------------------------------------
% I = Identity(O, a, M_modes)
%
% Output Arguments :
% -----------------
% I [2*sum(M_modes+1) x 2*sum(M_modes+1)] : Matrix of the system
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Coordinates of the center of the disk 1
% a [1 x N_scat] : Radius of disk 1
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator, SpIdentity
%%
function I = Identity(O, a, M_modes)
I = IntegralOperator(O, a, M_modes, 1, 1);
end
|
github
|
mu-diff/mu-diff-master
|
DnSingleLayer.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Full/DnSingleLayer.m
| 1,629 |
utf_8
|
dd52e97e118d4c1131caf0b3cadf8193
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the normal derivative trace of the single layer
% integral operator in the Fourier basis.
% -------------------------------------------------------------------------
% Normal derivative trace of the single-layer N operator for a density
% rho in H^{-1/2}(Gamma).
% for all x in \Gamma :
% N rho (x) = \int_{Gamma} dn_x G(x,y) rho(y) dy
%
% n = unit outward normal of the boundary Gamma of Omega, pointing
% outside Omega
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% A = DnSingleLayer(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A [2*sum(M_modes+1) x 2*sum(M_modes+1)] : Matrix of the system
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Coordinates of the center of the disk 1
% a [1 x N_scat] : Radius of disk 1
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function [A] = DnSingleLayer(O, a, M_modes, k)
A = IntegralOperator(O, a, M_modes, k, 4);
end
|
github
|
mu-diff/mu-diff-master
|
PrecondDirichlet.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Full/PrecondDirichlet.m
| 1,319 |
utf_8
|
8b55270cc8a814cc81960cf23c0213a5
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the integral operator obtained by preconditioning
% the single-layer operator by its single-scattering operator for a
% collection of sound-soft obstacles (Dirichlet), in the Fourier basis.
% -------------------------------------------------------------------------
% A = PrecondDirichlet(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A [2*sum(M_modes+1) x 2*sum(M_modes+1)] : Matrix of the system
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Coordinates of the center of the disk 1
% a [1 x N_scat] : Radius of disk 1
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function A = PrecondDirichlet(O, a, M_modes, k)
A = IntegralOperator(O, a, M_modes, k, 6);
end
|
github
|
mu-diff/mu-diff-master
|
DnDoubleLayer.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Full/DnDoubleLayer.m
| 1,667 |
utf_8
|
2e39e758d667b30f85e0cd834ff14c17
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the normal derivative trace of the double-layer
% integral operator in the Fourier basis.
% -------------------------------------------------------------------------
% Normal derivative trace of the double-Layer operator D for a density
% lambda in H^{1/2}(Gamma) (beware the "minus" sign!)
% for all x in \Gamma :
% D lambda(x) = - dn_x \int_{Gamma} dn_y G(x,y) lambda(y) dy
%
% n = unit outward normal of the boundary Gamma of Omega, pointing
% outside Omega
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% A = DnDoubleLayer(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A [2*sum(M_modes+1) x 2*sum(M_modes+1)] : Matrix of the system
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Coordinates of the center of the disk 1
% a [1 x N_scat] : Radius of disk 1
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function A = DnDoubleLayer(O, a, M_modes, k)
A = IntegralOperator(O, a, M_modes, k, 5);
end
|
github
|
mu-diff/mu-diff-master
|
CalderonProjector.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Full/CalderonProjector.m
| 3,206 |
utf_8
|
556b9a9b3c5c85682d9b0b35dfa69d61
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the Calderon projector matrix C given by
% C = [I/2+M, L ; D, I/2+N]
% The result is
% [gamma_D u] = [I/2+M, L]*[gamma_D u]
% [gamma_N u] [D, I/2+N] [gamma_N u]
% where gamma_D u = Dirichlet trace of u on Gamma (boundary)
% and gamma_N u = normal.grad(u) on Gamma, where normal is directed
% outwardly to the obstacle
% -------------------------------------------------------------------------
% A = CalderonProjector(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A [4*sum(M_modes+1) x 4*sum(M_modes+1)] : Matrix of the system
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Coordinates of the center of the disk 1
% a [1 x N_scat] : Radius of disk 1
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockCalderonProjector, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
function A = CalderonProjector(O, a, M_modes, k, varargin)
%Initialization
N_scat = length(a);
nvarargin = length(varargin);
if(nvarargin >= 1)
Weight = varargin{1};
else
Weight = ones(N_scat,N_scat);
end
if(~isscalar(Weight) && (size(Weight,1)~=N_scat || size(Weight,2)~=N_scat))
error('Weight must be a N_scatxN_scat matrix');
end
Sum_modes = 2.*M_modes + 1;
sizeA = 2*sum(Sum_modes);
A = zeros(sizeA, sizeA);
%Sp is a row-counter
Sp = 0;
%Loop on the obstacles
for p = 1:N_scat
%Center and radius of the scatterer p
Op = O(:,p);
ap = a(p);
%Vector of the modes associated with the scattererd number p
Np = M_modes(p);
MNp = [-Np:Np].';
MNp_bis = 2*Np+1+[-Np:Np].';
MNp_twice = [MNp; MNp_bis];
%Sq is a column-counter
Sq = 0;
%Second loop on the obstacles
for q = 1:N_scat
%Center and radius of the scatterer p
Oq = O(:,q);
aq = a(q);
%Vector of the modes associated with the scattererd number q
Nq = M_modes(q);
MNq = [-Nq:Nq].';
MNq_bis = 2*Nq+1+[-Nq:Nq].';
MNq_twice = [MNq; MNq_bis];
%Compute the block matrix
this_k = GetK(k,p,q);
if(Weight(p,q) ~=0)
A(Sp + MNp_twice +(Np+1), Sq + MNq_twice +(Nq+1)) = BlockCalderonProjector(Op, ap, Np, Oq, aq, Nq, this_k);
end
%Upgrade of the column-counter
Sq = Sq + 2*(2*Nq+1);
end
%Upgrade of the row-counter
Sp = Sp + 2*(2*Np+1);
end
end
%%
function this_k = GetK(k,p,q)
if(~isscalar(k))
if(p~=q)
this_k = k(p);
else
this_k = k(p);
end
else
this_k = k;
end
end
|
github
|
mu-diff/mu-diff-master
|
PrecondNeumann.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Full/PrecondNeumann.m
| 1,318 |
utf_8
|
59ceaf388daa30b5f6a4f3dc9378665e
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the integral operator obtained by preconditioning
% the Dn double-layer operator by its single-scattering operator for a
% collection of sound-hard obstacles (Neumann), in the Fourier basis.
% -------------------------------------------------------------------------
% A = PrecondNeumann(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A [2*sum(M_modes+1) x 2*sum(M_modes+1)] : Matrix of the system
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Coordinates of the center of the disk 1
% a [1 x N_scat] : Radius of disk 1
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function [A] = PrecondNeumann(O, a, M_modes, k)
A = IntegralOperator(O, a, M_modes, k, 7);
end
|
github
|
mu-diff/mu-diff-master
|
SingleLayer.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Full/SingleLayer.m
| 1,578 |
utf_8
|
a666f6324768a25d3e557669b99adbf5
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the trace of the single layer integral operator
% in the Fourier basis.
% -------------------------------------------------------------------------
% Trace of the single-layer operator L for a density rho in H^{-1/2}(Gamma)
% for all x in \Gamma :
% L rho (x) = \int_{Gamma} G(x,y) rho(y) dy
%
% n = unit outward normal of the boundary Gamma of Omega, pointing
% outside Omega
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% A = SingleLayer(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A [2*sum(M_modes+1) x 2*sum(M_modes+1)] : Matrix of the system
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Coordinates of the center of the disk 1
% a [1 x N_scat] : Radius of disk 1
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
%%
function A = SingleLayer(O, a, M_modes, k)
A = IntegralOperator(O, a, M_modes, k, 2);
end
|
github
|
mu-diff/mu-diff-master
|
DoubleLayer.m
|
.m
|
mu-diff-master/IntOperators/Dense/Interface/Full/DoubleLayer.m
| 1,616 |
utf_8
|
801a915541b39510d0c8970d462ad270
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the matrix of the trace of the double-layer integral operator
% in the Fourier basis.
% -------------------------------------------------------------------------
% Trace of the double-Layer operator M for a density lambda in H^{1/2}(Gamma)
% (beware the "minus" sign!).
% for all x in \Gamma :
% M lambda(x) = - \int_{Gamma} G(x,y) lambda(y) dy
%
% n = unit outward normal of the boundary Gamma of Omega, pointing
% outside Omega
% G(x,y)=i/4*H_0^1(k\|\xx-\yy\|), zeroth order Hankel function of 1st kind
% -------------------------------------------------------------------------
% A = DoubleLayer(O, a, M_modes, k)
%
% Output Arguments :
% -----------------
% A [2*sum(M_modes+1) x 2*sum(M_modes+1)] : Matrix of the system
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Coordinates of the center of the disk 1
% a [1 x N_scat] : Radius of disk 1
% M_Modes [1 x N_scat] : Truncation index in the Fourier series of
% obstacles
% k [1 x 1] : Wavenumber in the vacuum
%
% See also BlockIntegralOperator, IntegralOperator,
% SpBlockIntegralOperator, SpIntegralOperator
function [A] = DoubleLayer(O, a, M_modes, k)
A = IntegralOperator(O, a, M_modes, k, 3);
end
|
github
|
mu-diff/mu-diff-master
|
RCS.m
|
.m
|
mu-diff-master/PostProcessing/FarField/RCS.m
| 1,845 |
utf_8
|
fd3c8eb5ad7797e3c7336d34713d980c
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the Radar Cross Section of a combination of single- and double-layer
% potentials, in the case of circular scatterers.
% RCS = 10.*log10(2.*pi*(abs(Far_Field)).^2);
% -------------------------------------------------------------------------
% R = RCS(O, a, M_modes, k, theta, Density, Weight)
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
% k [1 x 1] : Wavenumber in the vacuum
% theta [1 x N_angles] : Angles of observation (rad).
% Note that theta could be a vector.
% Density [N x 1] : Coefficients in the Fourier bases of the
% or [N x 1] density (or densities)
% N = 2*sum(M_modes+1).
% Weight [1 x 2] : Weight to apply to the potentials (coef. alpha_p)
% or [N_scat x 2] if Weight is a line, then Weight(p,j) = Weight(j).
%
% Output Arguments :
% -----------------
% R [N_angles x 1] : Vector of the Far Field F
%
%
%
function R = RCS(O, a, M_modes, k, theta, DensityCoef, TypeOfOperator)
%Compute far field
F = FarField(O, a, M_modes, k, theta, DensityCoef, TypeOfOperator);
%Compute Radar Cross Section
R = FarField_to_RCS(F);
end
|
github
|
mu-diff/mu-diff-master
|
FarField_to_RCS.m
|
.m
|
mu-diff-master/PostProcessing/FarField/FarField_to_RCS.m
| 1,026 |
utf_8
|
f38e6132f4a753d52d410af3b9c96b2f
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Given a Far field pattern, this function computes the Radar Cross
% Section (RCS).
%
% Syntax
% ------
% R = FarField_to_RCS(Far_Field)
%
% Input Arguments :
% -----------------
% Far_Field [N x 1] :Far Field pattern.
% it is supposed to be a vector containing the
% far field pattern for every angle of [0,2*pi].
% N is the number of points used to discretize [0,2pi]
% Output Argument :
% -----------------
% rcs [N x 1] :Radar Cross Section
%
% Result
% -------
% R = 10.*log10(2.*pi*(abs(Far_Field)).^2);
%
function R = FarField_to_RCS(Far_Field)
R = 10.*log10(2.*pi*(abs(Far_Field)).^2);
end
|
github
|
mu-diff/mu-diff-master
|
FarField.m
|
.m
|
mu-diff-master/PostProcessing/FarField/FarField.m
| 3,874 |
utf_8
|
24cccd2d3b57396ee58510005ef41612
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the Far Field Pattern of a combination of single- and double-layer
% potentials, in the case of circular scatterers.
% -------------------------------------------------------------------------
% [F] = FarField(O, a, M_modes, k, theta, Density, Weight)
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
% k [1 x 1] : Wavenumber in the vacuum
% theta [1 x N_angles] : Angles of observation (rad).
% Note that theta could be a vector.
% Density [N x 1] : Coefficients in the Fourier bases of the
% or [N x 1] density (or densities)
% N = 2*sum(M_modes+1).
% Weight [1 x 2] : Weight to apply to the potentials (coef. alpha_p)
% or [N_scat x 2] if Weight is a line, then Weight(p,j) = Weight(j).
%
% Output Arguments :
% -----------------
% F [N_angles x 1] : Vector of the Far Field F
%
% See also RCS, FarField_to_RCS
%
function F = FarField(O, a, M_modes, k, theta, Density, Weight)
TWO_DENSITIES=0;
if(size(Density,2)==2)
TWO_DENSITIES =1;
end
N_scat = length(a);
%thetaSER = theta*(2*pi/360);
C = zeros(length(theta),N_scat);
%Sp is a row-counter
Sp = 0;
for p=1:N_scat
Np = M_modes(p);
MNp = [-Np:Np];
ap = a(p);
Op = O(:,p);
OO = [0;0];
bp = norm(Op);
alphap = fangle(Op,OO);
EXP_1 = exp(-1i*k*bp*cos(theta-alphap)).';
Mde_theta1 = 1i*(theta-pi/2).'*MNp;
matWeight = getWeight(Weight, N_scat, p);
for iOper = 1:2
if(matWeight(iOper) == 0)
continue;
end
if(TWO_DENSITIES)
CurrentDensity=Density(Sp + MNp +(Np+1), iOper);
else
CurrentDensity=Density(Sp + MNp +(Np+1));
end
this_weight = matWeight(iOper);
FourierCoef = zeros(2*Np+1,1);
if(this_weight ~=0)
switch iOper
case 1, %Single Layer formulation
FourierCoef = sqrt(ap)*CurrentDensity.*besselj(MNp,k*ap).';
case 2,%Double Layer contribution
FourierCoef = -k*sqrt(ap)*CurrentDensity.*dbesselj(MNp,k*ap).';
end
C(:,p) = C(:,p) + this_weight*(exp(Mde_theta1)*FourierCoef).*EXP_1;
end
clear FourierCoef;
end
Sp = Sp +2*Np+1;
end
if (N_scat > 1)
F = sum(1i*exp(-1i*pi/4)*sqrt(1/k)/2*C.');
else
F = 1i*exp(-1i*pi/4)*sqrt(1/k)/2*C.';
end
F = F.';
end
%% Get the Weight of integral operators needed
function [matWeight] = getWeight(Weight, N_scat, p)
if(size(Weight, 2) ~=2)
error(['Weight is of wrong size: must be 1x2 or N_scatx2.']);
elseif((isrow(Weight) || iscolumn(Weight)))
matWeight = Weight;
elseif(size(Weight,3) == 1)
if(size(Weight,1) == N_scat && size(Weight,2) == 2);
matWeight = Weight(p,:);
else
error(['Weight is of wrong size: must be 1x2 or N_scatx2.']);
end
else
error('Weight has too much dimensions!');
end
end
|
github
|
mu-diff/mu-diff-master
|
FarFieldSingleLayer.m
|
.m
|
mu-diff-master/PostProcessing/FarField/Interface/FarFieldSingleLayer.m
| 1,770 |
utf_8
|
35d2ae1afc4919fd0a9e3696df523d0b
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the Far Field Pattern of a single-layer potential, in the case of circular scatterers.
% The density needs to be decomposed on the Fourier bases
% -------------------------------------------------------------------------
% Single-Layer potential of density rho :
% u(x) = \int_{Gamma} G(x,y) rho(y) dy.
% Gamma = boundary of the scatterers.
% -------------------------------------------------------------------------
% F = FarFieldSingleLayer(O, a, M_modes, k, Density, theta)
%
% Input Arguments (N_scat = number of obstacles):
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
% k [1 x 1] : Wavenumber in the vacuum
% Density [1 x N] : Coefficients in the Fourier bases of the
% density lambda.
% N = 2*sum(M_modes+1).
% theta [1 x N_angle] : Angle of observation (rad).
% Note that theta could be a vector.
%
% Output Arguments :
% -----------------
% F [1 x N_angle] : Vector of the Far Field F
%
%
%%
function F = FarFieldSingleLayer(O, a, M_modes, k, Density, theta)
F = FarField(O, a, M_modes, k, theta, Density, [1,0]);
end
|
github
|
mu-diff/mu-diff-master
|
RCSSingleLayer.m
|
.m
|
mu-diff-master/PostProcessing/FarField/Interface/RCSSingleLayer.m
| 1,884 |
utf_8
|
76aa54077634b30b3201aa39c758cb0a
|
% mu-diff - Copyright (C) 2014-2020 X. Antoine and B. Thierry, University of Lorraine, CNRS, France
%
% See the LICENSE.txt file for license information. Please report all
% bugs and problems to either (replace [at] and [dot] by arobase and dot)
% Xavier.Antoine [at] univ-lorraine [dot] fr
% BThierry [at] math.cnrs [dot] fr
%
% ~~~
% Compute the Radar Cross Section (RCS) of a single-layer potential, in the case of circular scatterers.
% The density needs to be decomposed on the Fourier bases
% -------------------------------------------------------------------------
% Single-Layer potential of density rho :
% u(x) = \int_{Gamma} G(x,y) rho(y) dy.
% Gamma = boundary of the scatterers.
% -------------------------------------------------------------------------
% Give the RCS of the single-layer potential
% RCS = 10.*log10(2.*pi*(abs(Far_Field)).^2);
% -------------------------------------------------------------------------
% R = RCSSingleLayer(O, a, M_modes, k, theta, Density)
%
% Input Arguments :
% -----------------
% O [2 x N_scat] : Vector of the centers of the scatterers
% a [1 x N_scat] : Vector of the radius of the scatterers
% M_modes [1 x N_Scat] : Vector of the "N_p", where "(2*N_p+1)" is the
% number of modes kept for the Fourier basis of the
% scatterer number "p".
% k [1 x 1] : Wavenumber in the vacuum
% Density [1 x N] : Coefficients in the Fourier bases of the
% density lambda.
% N = 2*sum(M_modes+1).
% theta [1 x N_angle] : Angle of observation (rad).
% Note that theta could be a vector.
%
% Output Arguments :
% -----------------
% RCS [1 x N_angle] : Vector of the RCS
%
function R = RCSSingleLayer(O, a, M_modes, k, theta, Density)
R = RCS(O, a, M_modes, k, theta, Density, [1,0]);
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.