%op_CSIIntegrate.m
%Brenden Kadota, Sunnybrook 2021.
%
% USAGE:
% in=op_CSIintegrate(in);
%
% DESCRIPTION:
% Integrates the spectrum from ppmmin to ppmmax in all csi voxels.
%
% INPUTS:
% in        = CSI FID-A data structure
% pmmmin    = lower integration bounds
% ppmmax    = upper integration bounds
% mode      = mode (optional):
%                        -'re' (integral performed on real part (default)).
%                        -'im' (integral performed on imaginary part).
%                        -'mag' (integral performed on magnitude part).
%
% OUTPUTS:
% out       = map of integrated area
function [map, signal, noised] = op_CSIgetSNR(MRSIStruct, NAAppmmin, NAAppmmax, noiseppmmin, noiseppmmax)
    arguments
        MRSIStruct (1, 1) struct
        NAAppmmin (1, 1) double = nan
        NAAppmmax (1, 1) double = nan
        noiseppmmin (1, 1) double = nan
        noiseppmmax (1, 1) double = nan
    end
    checkArguments(MRSIStruct);
    arguments = removeNanArguments(NAAppmmin, NAAppmmax, noiseppmmin, noiseppmmax);

    MRSIStruct = reshapeDimensions(MRSIStruct, {'y', 'x', 't'});
    map = zeros(getSizeFromDimensions(MRSIStruct, {'y', 'x', 'extras'}));
    signal = zeros(getSizeFromDimensions(MRSIStruct, {'y', 'x', 'extras'}));
    noised = zeros(getSizeFromDimensions(MRSIStruct, {'y', 'x', 'extras'}));
    for e = 1:getSizeFromDimensions(MRSIStruct, {'extras'})
        for x = 1:getSizeFromDimensions(MRSIStruct, {'x'})
            for y = 1:getSizeFromDimensions(MRSIStruct, {'y'})
                voxel = op_CSItoMRS(MRSIStruct, x, y, "Extra", e);
                [voxSNR, voxSignal, voxNoiseD] = op_getSNR(voxel, arguments{:});
                signal(y, x, e) = voxSignal;
                noised(y, x, e) = voxNoiseD;
                map(y, x, e) = voxSNR;
            end
        end
    end
end

function checkArguments(in)
    if(in.flags.spectralFT == 0)
        error('FID-A Error: Input type invalid. Please fourier transform along the spectral dimension');
    end
    if(in.flags.spatialFT == 0)
        error('FID-A Error: Input type invalid. Please fourier transform along the spacial dimension');
    end
end

function args = removeNanArguments(NAAppmmin, NAAppmmax, noiseppmmin, noiseppmmax)
    args = {NAAppmmin, NAAppmmax, noiseppmmin, noiseppmmax};
    emptyIndecies = zeros(1, size(args, 2), 'logical');
    for iArgument = 1:length(args)
        if(isnan(args{iArgument}))
            emptyIndecies(iArgument) = 1;
        end
    end
    args(emptyIndecies) = [];
end


%SELCLASSFixed mapping for selecting a single class from a dataset
%
%	[B,J] = SELCLASS(A,CLASS,NAME)
%	[B,J]  = A*SELCLASS([],CLASS,NAME)
%	[B,J]  = A*SELCLASS(CLASS,NAME)
%
% INPUT
%   A      Dataset
%   CLASS  Integer: Indices of desired classes in CLASSNAMES(A)
%          String array:  Class names
%          Cell array: Indices of desired classes in CLASSNAMES(A)
%          Default C = {}, i.e. return all classes separated out in a cell
%          array.
%   NAME   Integer: Index of desired labeling, see GETLABLISTNAMES
%          String:  Name of desired labeling, see GETLABLISTNAMES
%          Default: actual LABLIST
%
% OUTPUT
%   B   Desired classes of the dataset A. In case CLASS is a cell array, B
%       is a cell array of the desired classes. In case CLASS is empty, B
%       is a cell array of all classes.
%   J   Indices of returned objects in dataset A: B = A(J,:). In case CLASS
%       is a cell array, J is a cell array as well.
%
% DESCRIPTION
% B is a subset of the dataset A defined by the set of classes (CLASS). In
% case of a multi-labeling system (see MULTI_LABELING) the desired CLASS
% should refer to the label list NAME.
%
% In case A is soft labeled or is a target dataset by B = SELCLASS(A,CLASS)
% the entire dataset is returned, but the labels or targets are reduced to
% the selected class (target) CLASS.
%
% In case CLASS is a cell array the outputs are organised as cell arrays.
%
% EXAMPLES
% a = gendatm; b = selclass(a,[2 3 4]); % selects 3 classes
% a = gendatm; b = a*selclass;         % returns every class in a cell
% a = gendatb;
% a = addlabels(a,genlab(25*ones(4,1)),'4class'); % add second label list
% b = a*selclass('4class'); % returns 4 cells, preserves label list.
%
% SEE ALSO (PRTools Guide)
% DATASETS, SELDAT, CLASSNAMES, GENDAT, GETLABLIST, GETCLASSI, REMCLASS,
% GETLABLISTNAMES, MULTI_LABELING

% Copyright: R.P.W. Duin, r.p.w.duin@37steps.com

function [b,J] = selclass(varargin)

  argin = shiftargin(varargin,{'vector','cell','char'});
  argin = shiftargin(argin,'char',2);
  argin = setdefaults(argin,[],{},[]);

  if mapping_task(argin,'definition')
    b = define_mapping(argin,'fixed');

  else			% Evaluate

    [a,clas,lablist] = deal(argin{:});
    isa(a,'prdataset');
    if ~isempty(lablist)
      curn = curlablist(a);
      a = changelablist(a,lablist);
      [b,J] = feval(mfilename,a,clas);
      if iscell(b)
        for n=1:numel(b)
          b{n} = changelablist(b{n},curn);
        end
      else
        b = changelablist(b,curn);
      end
    else
      if iscell(clas)
        if  isempty(clas)
          for n=1:getsize(a,3);
            clas{n} = n;
          end
        end
        if isdataset(a)
          b = prdataset;
        else
          b = prdatafile;
        end
        J = cell(1,numel(clas));
        b = cell(1,numel(clas));
        for n=1:numel(clas)
          [b{n},J{n}] = seldat(a,clas{n});
        end
      else
        [b,J] = seldat(a,clas);
      end
    end

  end


function g = linKernGradient(kern, x, varargin)

% LINKERNGRADIENT Gradient of LIN kernel's parameters.
% FORMAT
% DESC computes the gradient of functions with respect to the
% linear
% kernel's parameters. As well as the kernel structure and the
% input positions, the user provides a matrix PARTIAL which gives
% the partial derivatives of the function with respect to the
% relevant elements of the kernel matrix.
% ARG kern : the kernel structure for which the gradients are being
% computed.
% ARG x : the input locations for which the gradients are being
% computed.
% ARG partial : matrix of partial derivatives of the function of
% interest with respect to the kernel matrix. The argument takes
% the form of a square matrix of dimension  numData, where numData is
% the number of rows in X.
% RETURN g : gradients of the function of interest with respect to
% the kernel parameters. The ordering of the vector should match
% that provided by the function kernExtractParam.
%
% FORMAT
% DESC computes the derivatives as above, but input locations are
% now provided in two matrices associated with rows and columns of
% the kernel matrix.
% ARG kern : the kernel structure for which the gradients are being
% computed.
% ARG x1 : the input locations associated with the rows of the
% kernel matrix.
% ARG x2 : the input locations associated with the columns of the
% kernel matrix.
% ARG partial : matrix of partial derivatives of the function of
% interest with respect to the kernel matrix. The matrix should
% have the same number of rows as X1 and the same number of columns
% as X2 has rows.
% RETURN g : gradients of the function of interest with respect to
% the kernel parameters.
%
% SEEALSO linKernParamInit, kernGradient, linKernDiagGradient, kernGradX
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006, 2009

% KERN

if nargin < 4
  [k, sk] = linKernCompute(kern, x);
else
  [k, sk] = linKernCompute(kern, x, varargin{1});
end
g(1) = sum(sum(varargin{end}.*sk));


%% Simple rotation model images stitcher
% A basic example on image stitching.
%
% In this demo, we show how to use the high-level stitching API provided by
% |cv.Stitcher|, and we learn how to use preconfigured stitcher configurations
% to stitch images using different camera models.
%
% Sources:
%
% * <https://docs.opencv.org/3.3.1/d8/d19/tutorial_stitcher.html>
% * <https://github.com/opencv/opencv/blob/3.3.1/samples/cpp/stitching.cpp>
%

%% Input images (two or more)
imgs = {
    imread(fullfile(mexopencv.root(),'test','b1.jpg')), ...
    imread(fullfile(mexopencv.root(),'test','b2.jpg'))
};
for i=1:numel(imgs)
    subplot(1,numel(imgs),i), imshow(imgs{i})
end

%% Options

% Try to use GPU. The default value is false.
% All default values are for CPU mode.
try_use_gpu = false;

% Determines configuration of stitcher. The default is 'Panorama' mode
% suitable for creating photo panoramas. Option 'Scans' is suitable for
% stitching materials under affine transformation, such as scans.
smode = 'Panorama';

% Internally create three chunks of each image to increase stitching success
divide_images = false;

%%
if divide_images
    for i=1:numel(imgs)
        sz = size(imgs{i});
        imgs{i} = {
            cv.Rect.crop(imgs{i}, [0       0 sz(2)/2 sz(1)]), ...
            cv.Rect.crop(imgs{i}, [sz(2)/3 0 sz(2)/2 sz(1)]), ...
            cv.Rect.crop(imgs{i}, [sz(2)/2 0 sz(2)/2 sz(1)])
        };
    end
    imgs = [imgs{:}];
end

%% Stitch
stitcher = cv.Stitcher('Mode',smode, 'TryUseGPU',try_use_gpu);
tic
pano = stitcher.stitch(imgs);
toc

%% Panorama result
figure, imshow(pano)


function [brainAreas,vals,labels] = fs_loadCtab(ctabFile)
%
% Load a FreeSurfer .ctab file.  This is generally a file containing the
% labels and indices into a FreeSurfer segmaentation a segmentation.
%
% ctab = fs_loadCtab(ctabFile)
%
% INPUTS:
%    ctabFile - the fullpath to a file ending eith the .ctab exstension.
%               Freesurfer generates two as result of the full segmentation
%               and parcellation process. These files are generally stored
%               in: $SUBJECTS_DIR/<subject>/label/
%
% OUTPUT:
%    brainAreas - is a cell array containing:
%                 brainAreas.val:  The values for each brain areas as coded
%                                  in FreeSurfer.
%                 brainAreas.name: The corresponding labels, names for each
%                                  brain areas.
%    vals       - The values for each brain areas as coded in FreeSurfer
%    labels     - The corresponding labels, names for each
%                 brain areas.
%    colors     - The RGB colors for each brain area in the segmentation.
%
% EXAMPLE:
%    fsDir = getenv('SUBJECTS_DIR');
%    subject = 'pestilli_test';
%    segmentation = 'aparc.annot.a2009s';
%    segFile = fullfile(fsDir,subject,'label',sprintf('%s.ctab',segmentation));
%    ba = fs_loadCtab(segFile,' ',1);
%
% Written by Franco Pestilli (c) Stanford University 2013, Vistasoft

% Read the .ctab file
ctab = importdata(ctabFile,' ',1);

% Extract the labels names and corresponding values, and  colors.
vals             = cellfun(@str2num,ctab.textdata(:,1));
labels           = ctab.textdata(:,2);
brainAreas.name  = labels(:);
brainAreas.val   = vals;
brainAreas.colors= zeros(size(labels,1),3);
brainAreas.colors(vals>0,:) = ctab.data(:,1:3);

end


function disp(t,name)
%DISP Command window display of a ttensor.
%
%   DISP(T) displays a ttensor with no name.
%
%   DISP(T,NAME) display a ttensor with the given name.
%
%   See also TTENSOR.
%
%MATLAB Tensor Toolbox.
%Copyright 2015, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2015) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

if ~exist('name','var')
    name = 'ans';
end

fprintf(1,'%s is a ttensor of size %s\n', name, tt_size2str(size(t)));
disp(t.core, sprintf('\t%s.core',name));

for j = 1 : ndims(t)
    fprintf('\t%s.U{%d} = \n', name, j);
    output = tt_matrix2cellstr(t.u{j});
    fprintf('\t\t%s\n',output{:});
end


function e = end(f, k, n)
%END   Rightmost point of a CHEBFUN domain (or last row/col of quasimatrix).
%   END(F, K, N) This function is called for indexing expressions involving a
%   CHEBFUN F when END is part of the K-th index out of N indices.
%
%   If F is a column CHEBFUN and K is 1, this function returns the last point
%   in F's domain. If K is 2, it returns the index of F's last column.
%
%   If F is a row CHEBFUN and K is 1, this function returns the index of F's
%   last row. If K is 2, it returns the last point in F's domain.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

if ( n > 2 )
    error('CHEBFUN:CHEBFUN:end:ngt2', 'Index exceeds CHEBFUN dimensions.');
end

if ( ((k == 2) && ~f(1).isTransposed) || ...
     ((k == 1) && f(1).isTransposed && (n > 1)) )
    % 'end' row/column of the array-valued CHEBFUN.
    if ( isempty(f) )
        e = 0;
    else
        e = numColumns(f);
    end

else
    % 'end' of the domain.
    e = f(1).domain(end);

end

end


function [p,priors]=create_parameters(start_from_mode)
p=struct();
%--- Targeted steady state values
p.alpha = 0.30; %(1) the average labor income share is 70% (page 15 of paper)
p.r = 1.01; %(2) the average real prime loan rate is 4% per annum (page 15 of paper)
p.ky = 4.6194; %(3) the capital-output ratio is on average 1.15 at the annual frequency (page 15 of paper)
p.ik = 0.2093/4; % (4) the investment-capital ratio is on average 0.209 at the annual frequency
p.qlLeOY = 2.60; %(5) the average land-output ratio is 0.65 at the annual frequency
p.theta_bar = 0.75;  %(6) the average nonfarm and nonfiancial businesses' loan-asset ratio is 0.75 at the annual frequency (page 15 of paper)
p.qlLhOY = 5.8011; %(7) the average housing output ratio is 1.45 at the annual frequency
p.n = 1/4; %(8) average market hours is 25% of time endowment
p.lbar = 1; %arbitrary

priors=struct();
priors.gamma_h          ={ 0.7  , 0.0256, 0.7761 , 'beta_pdf(0.9)'     , .00000001     , .99999999999};
priors.gamma_e          ={ 0.7  , 0.0256, 0.7761 , 'beta_pdf(0.9)'     , .00000001     , .99999999999};
priors.omega            ={ 3.0  , 0.1020, 5.994  , 'gamma_pdf(0.9)'    , .00001        , 10          };
priors.g_trans          ={ 0.375, 0.1   , 1.5    , 'gamma_pdf(0.9)'    , .00001        , 10          };
priors.lambda_qbar_trans={ 1.25 , 0.1   , 1.5    , 'gamma_pdf(0.9)'    , .00001        , 10          };
priors.rho_a            ={ 0.9  , 0.0256, 0.7761 , 'beta_pdf(0.9)'     , .00000001     , .99999999999};
priors.rho_z            ={ 0.9  , 0.0256, 0.7761 , 'beta_pdf(0.9)'     , .00000001     , .99999999999};
priors.rho_v            ={ 0.9  , 0.0256, 0.7761 , 'beta_pdf(0.9)'     , .00000001     , .99999999999};
priors.rho_q            ={ 0.9  , 0.0256, 0.7761 , 'beta_pdf(0.9)'     , .00000001     , .99999999999};
priors.rho_mu           ={ 0.9  , 0.0256, 0.7761 , 'beta_pdf(0.9)'     , .00000001     , .99999999999};
priors.rho_phi          ={ 0.9  , 0.0256, 0.7761 , 'beta_pdf(0.9)'     , .00000001     , .99999999999};
priors.rho_psi          ={ 0.9  , 0.0256, 0.7761 , 'beta_pdf(0.9)'     , .00000001     , .99999999999};
priors.rho_xitheta      ={ 0.9  , 0.0256, 0.7761 , 'beta_pdf(0.9)'     , .00000001     , .99999999999};
priors.sig_Eps_a        ={ 0.01 , 0.0001, 2      , 'inv_gamma_pdf(0.9)', 0.000000000001, 100         };
priors.sig_Eps_z        ={ 0.01 , 0.0001, 2      , 'inv_gamma_pdf(0.9)', 0.000000000001, 100         };
priors.sig_Eps_v        ={ 0.01 , 0.0001, 2      , 'inv_gamma_pdf(0.9)', 0.000000000001, 100         };
priors.sig_Eps_q        ={ 0.01 , 0.0001, 2      , 'inv_gamma_pdf(0.9)', 0.000000000001, 100         };
priors.sig_Eps_mu       ={ 0.01 , 0.0001, 2      , 'inv_gamma_pdf(0.9)', 0.000000000001, 100         };
priors.sig_Eps_phi      ={ 0.01 , 0.0001, 2      , 'inv_gamma_pdf(0.9)', 0.000000000001, 100         };
priors.sig_Eps_psi      ={ 0.01 , 0.0001, 2      , 'inv_gamma_pdf(0.9)', 0.000000000001, 100         };
priors.sig_Eps_xitheta  ={ 0.01 , 0.0001, 2      , 'inv_gamma_pdf(0.9)', 0.000000000001, 100         };

if start_from_mode
    priors.gamma_e{1}= 0.658435028;
    priors.gamma_h{1}= 0.497555761;
    priors.omega{1}= 0.175347074;
    priors.g_trans{1}= 0.422109209;
    priors.lambda_qbar_trans{1}= 1.21261837;
    priors.rho_a{1}=  0.905471687;
    priors.rho_v{1}= 0.00947706131;	%rho_{nu_z}
    priors.rho_mu{1}= 0.294889827;	   %rho_{nu_q}
    priors.rho_psi{1}=  0.982918278;
    priors.rho_q{1}= 0.561965864;
    priors.rho_xitheta{1}= 0.980427788;
    priors.rho_phi{1}=  0.999758433;
    priors.rho_z{1}= 0.426298781;	 %rho_z
    priors.sig_Eps_z{1}=     0.00418908791;
    priors.sig_Eps_v{1}=   0.00365910563;
    priors.sig_Eps_q{1}=     0.00415238812;
    priors.sig_Eps_mu{1}=   0.00288990925;
    priors.sig_Eps_a{1}=     0.101281626;
    priors.sig_Eps_phi{1}=   0.0462334747;
    priors.sig_Eps_psi{1}=    0.00731583619;
    priors.sig_Eps_xitheta{1}= 0.0111777605;
end

% add the initial conditions of the priors to the parameters
%------------------------------------------------------------
fields=fieldnames(priors);
for ip=1:numel(fields)
    name=fields{ip};
    p.(name)=priors.(name){1};
end

end


% c = str2cell(v)
% c = str2cell(v,delim[s])
%
%	creates a cell array <c> from input array <v>
%	seperated by delimiter[s] <del>
%
% v	: a string/vector of a ML supported data class
% delim	: array of delimiter[s]				[def: isspace]
%	  v-class	syntax
%	  ----------------------
%	  char		'xyz'
%	  other		[1 2 pi]
%
% note:
%	an input matrix (NxM) will be turned into a
%	1x(N*M) row vector WITHOUT warning!
%
% examples:
%	s='this is a ;;; test case; +-0 ;;;_;;; or; +;+ 1';
%	c=str2cell(s,' +-;0_')
%		'this'
%		'is'
%		'a'
%		'test'
%		'case'
%		'or'
%		'1'
%
%	d=[pi pi 1 2 pi 4 5 6 pi];
%	c=str2cell(d,[pi 5])
%		[1x2 double]	% contents: 1 2
%		[         4]
%		[         6]

% created:
%	us	13-Nov-2000
% modified:
%	us	20-Dec-2003		/ TMW
%	us	06-Jun-2005 20:05:27

%--------------------------------------------------------------------------------
function	c=str2cell(s,varargin)

	if	nargin < 1
		help str2cell
		return;
	end

% make sure we have a row vec
		s=s(:).';

% check input
	if	nargin < 2
	if	ischar(s)
		ix=~isspace(s);
	else
		ix=ones(size(s));
	end
	else
		ix=~ismember(s,varargin{1});
	if	~isempty(find(isnan(varargin{1})))
		ix=ix&~isnan(s);
	end
	end

% find indices of delim[s]
		dx=diff(ix);
		k=sort([findstr(dx,-1) findstr(dx,1)+1]);
	if	~isempty(k)
	if	ix(1) == 1
		k=[1 k];
	end
	if	ix(end) == 1
		k=[k length(ix)];
	end
	else
		k=1:length(s);
		k=sort([k k]);
	end
		k=reshape(k,2,[]).';

% create cell[s]
		nk=size(k,1);
		c=cell(nk,1);
	for	i=1:nk
		c{i}=s(k(i,1):k(i,2));
	end
		return;


function r8cc_write ( col_file, row_file, a_file, m, n, nz_num, col, row, a )

%*****************************************************************************80
%
%% R8CC_WRITE writes a R8CC matrix to three files.
%
%  Discussion:
%
%    The R8CC format is the double precision sparse compressed column
%    format.  Associated with this format, we have an M by N matrix
%    with NZ_NUM nonzero entries.  We construct the column pointer
%    vector COL of length N+1, such that entries of column J will be
%    stored in positions COL(J) through COL(J+1)-1.  This indexing
%    refers to both the ROW and A vectors, which store the row indices
%    and the values of the nonzero entries.  The entries of the
%    ROW vector corresponding to each column are assumed to be
%    ascending sorted.
%
%    The R8CC format is equivalent to the MATLAB "sparse" format,
%    and the Harwell Boeing "real unsymmetric assembled" (RUA) format.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 September 2006
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Iain Duff, Roger Grimes, John Lewis,
%    User's Guide for the Harwell-Boeing Sparse Matrix Collection,
%    October 1992
%
%  Parameters:
%
%    Input, string COL_FILE, ROW_FILE, A_FILE, the names of the
%    files containing the column pointers, row entries, and matrix entries.
%
%    Input, integer M, N, the number of rows and columns in the matrix.
%
%    Input, integer NZ_NUM, the number of nonzero elements in the matrix.
%
%    Input, integer COL(N+1), the column pointers.
%
%    Input, integer ROW(NZ_NUM), the row indices.
%
%    Input, real A(NZ_NUM), the nonzero elements
%    of the matrix.
%

%
%  Write the column information.
%
  output_unit = fopen ( col_file, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8CC_WRITE - Fatal error!\n' );
    fprintf ( 1, '  Could not open the output file "%s".\n', col_file );
    error ( 'R8CC_WRITE - Fatal error!' );
  end

  for k = 1 : n + 1

    fprintf ( output_unit, '%8d\n', col(k) );

  end

  fclose ( output_unit );
%
%  Write the row information.
%
  output_unit = fopen ( row_file, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8CC_WRITE - Fatal error!\n' );
    fprintf ( 1, '  Could not open the output file "%s".\n', row_file );
    error ( 'R8CC_WRITE - Fatal error!' );
  end

  for k = 1 : nz_num

    fprintf ( output_unit, '%8d\n', row(k) );

  end

  fclose ( output_unit );
%
%  Write the value information.
%
  output_unit = fopen ( a_file, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8CC_WRITE - Fatal error!\n' );
    fprintf ( 1, '  Could not open the output file "%s".\n', a_file );
    error ( 'R8CC_WRITE - Fatal error!' );
  end

  for k = 1 : nz_num

    fprintf ( output_unit, '%14f\n', a(k) );

  end

  fclose ( output_unit );

  return
end


function test_bug1760

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_multiplotER ft_multiplotTFR

cd(dccnpath('/home/common/matlab/fieldtrip/data/test'))
load bug1760.mat

figure
ft_multiplotER(cfg, freq);


function varargout=m2v(varargin)
%
% vol=m2v(node,face,Nxyz)
%  or
% vol=m2v(node,face,xi,yi,zi)
%
% shortcut for mesh2vol, rasterizing a teterahedral mesh to a volume using graphics
%
% author: Qianqian Fang (fangq <at> nmr.mgh.harvard.edu)
%
% input/output: please see details in the help for mesh2vol
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

[varargout{1:nargout}]=mesh2vol(varargin{:});


% op_CSIZeroBaseline
%
% Takes mean of ppm baseline and substracts spectra by this baseline. This makes
% the ppm baseline zero.
%
% INPUT
% MRSIStruct            = MRSI structure used in FID-A
% ppmBaselineRange      = ppm range of the baseline
%
% OUTPUT
% MRSIStruct            = MRSI ouput

function MRSIStruct = op_CSIzeroBaseline(MRSIStruct, ppmBaselineRange)
    [MRSIStruct, prevPermute, prevShape] = reshapeDimensions(MRSIStruct, {'t', 'y', 'x'});
    data = getData(MRSIStruct);
    ppm = getPPM(MRSIStruct);
    ppmBaselineIndex = ppm > ppmBaselineRange(1) & ppm < ppmBaselineRange(2);
    for e = 1:getSizeFromDimensions(MRSIStruct, {'extras'})
        for x = 1:getSizeFromDimensions(MRSIStruct, {'x'})
            for y = 1:getSizeFromDimensions(MRSIStruct, {'y'})
                voxelBaselineData = mean(data(ppmBaselineIndex, y, x, e));
                realBaseline = real(voxelBaselineData);
                imagBaseline = imag(voxelBaselineData);
                data(:, y, x, e) = data(:, y, x, e) - realBaseline - 1i * imagBaseline;
            end
        end
    end
    MRSIStruct = setData(MRSIStruct, data);
    MRSIStruct = reshapeBack(MRSIStruct, prevPermute, prevShape);

end


%tstoolbox/mex/takens_estimator
%   Syntax:
%
%     * D = takens_estimator(pointset, query_indices, relative_range,
%       exclude)
%     * D = takens_estimator(atria, pointset, query_indices,
%       relative_range, exclude)
%
%   Input arguments:
%
%     * atria - output of nn_prepare for pointset (optional)
%       (cf. Section )
%     * pointset - a N by D double matrix containing the coordinates of
%       the point set, organized as N points of dimension D
%     * query_indices - query points are taken out of the pointset,
%       query_indices is a vector of length R which contains the indices
%       of the query points (indices may vary from 1 to N)
%     * relative_range - search radius, relative to attractor diameter (0
%       < relative_range < 1)
%     * exclude - in case the query points are taken out of the pointset,
%       exclude specifies a range of indices which are omitted from
%       search. For examples if the index of the query point is 124 and
%       exclude is set to 3, points with indices 121 to 127 are omitted
%       from search. Using exclude = 0 means: exclude self-matches
%
%   Output arguments:
%
%     * D - scalar value, estimation of correlation dimension
%
% Copyright 1997-2001 DPI Goettingen, License http://www.physik3.gwdg.de/tstool/gpl.txt


function draw_spheres(time, period, S, figure_handle)
% DRAW_SPHERES - Plot the spherical obstacles

persistent scatter_handle

if mod(time, period) == 0 && S.is_active_spheres
    [~,n_obs] = size(S.S);
    s = repmat(400*600,n_obs,1);
    X = S.S(1,:)';
    Y = S.S(2,:)';
    Z = S.S(3,:)';
    colors = repmat(0.5,3, n_obs);

    if time == 0
        scatter_handle = scatter3(X, Y, Z, s, colors', '.');
        hold on

        axis square;
        view(32,47);
        xlabel('x position [m]');
        ylabel('y position [m]');
        zlabel('z position [m]');

%     else
%         set(scatter_handle, 'Xdata', Y, ...
%             'Ydata', X, ...
%             'Zdata', Z, ...
%             'Marker', '.', ...
%             'SizeData', s, ...
%             'CData', colors');

    end
end


function Y = eminus(A,B)
Y = bsxfun(@minus, A, B);


clear all;
close all;
clc
%%
load('ExperimentInformation.mat');
load('GridCellAnalysis.mat');
load('NAT.mat');
%% paremater settings
AngleSmooth=2;
AngleBinsize=3; % cm
SpeedThreadhold=2.5; %cm/mm
MinEventCount=100;
MinSNR=3;
Shuffling=1000;
Shuffling_mininterval=30; %second
%% shuffling
SelectedFrame_raw=cell(ExperimentInformation.Session,ExperimentInformation.TotalCell); %% which frame in each session should be used to do analyses for each cell
SelectedFrame_filtered=cell(ExperimentInformation.Session,ExperimentInformation.TotalCell); %% which frame in each session should be used to do analyses for each cell, filtered by some cratirial
TurningCurve_whole=cell(ExperimentInformation.Session,ExperimentInformation.TotalCell);
TurningCurve_firsthalf=cell(ExperimentInformation.Session,ExperimentInformation.TotalCell);
TurningCurve_secondthalf=cell(ExperimentInformation.Session,ExperimentInformation.TotalCell);
TurningCurveStat_whole=cell(ExperimentInformation.Session,ExperimentInformation.TotalCell);
TurningCurveStat_firsthalf=cell(ExperimentInformation.Session,ExperimentInformation.TotalCell);
TurningCurveStat_secondthalf=cell(ExperimentInformation.Session,ExperimentInformation.TotalCell);
CellForAnalysis=cell(ExperimentInformation.Session,1);
MVL_shuffled=zeros(ExperimentInformation.TotalCell,Shuffling+3,ExperimentInformation.Session);
Correlation_shuffled=zeros(ExperimentInformation.TotalCell,Shuffling+3,ExperimentInformation.Session);

for j=1:1:ExperimentInformation.Session
    k=1;
    for i=1:1:ExperimentInformation.TotalCell
       SelectedFrame_raw=find(~isnan(NAT{1,j}(:,4*i+10)));
        SelectedFrame_filtered=intersect(find(~isnan(NAT{1,j}(:,4*i+10))),find(NAT{1,j}(:,6)==1));% filter out the frames with speed valid
        SelectedFrame_filtered=intersect(SelectedFrame_filtered,find(NAT{1,j}(:,5)>SpeedThreadhold));% filter out the frames with speed threadhold
        SelectedFrame_filtered_firstHalf=SelectedFrame_filtered(find(SelectedFrame_filtered<=ExperimentInformation.FrameinEachSession(j)/2));
        SelectedFrame_filtered_secondHalf=SelectedFrame_filtered(find(SelectedFrame_filtered>ExperimentInformation.FrameinEachSession(j)/2));
        HeadDirectionTrain=NAT{1,j}(SelectedFrame_filtered,4);
        HeadDirectionTrain_firstHalf=NAT{1,j}(SelectedFrame_filtered_firstHalf,4);
        HeadDirectionTrain_secondHalf=NAT{1,j}(SelectedFrame_filtered_secondHalf,4);
        Event_filtered=intersect(find(NAT{1,j}(:,4*i+12)>0),find(NAT{1,j}(:,6)==1));% filter out the frames with speed valid
        Event_filtered=intersect(Event_filtered,find(NAT{1,j}(:,5)>SpeedThreadhold));% filter out the frames with speed threadholds
        Event_firstHalf=NAT{1,j}(SelectedFrame_filtered_firstHalf,[1 4*i+12]);
        Event_secondHalf=NAT{1,j}(SelectedFrame_filtered_secondHalf,[1 4*i+12]);
        if length(Event_filtered)>MinEventCount && ExperimentInformation.CellSNR(i)>3 && ~ismember(i,ExperimentInformation.RepeatCell)
            EventTrain=NAT{1,j}(SelectedFrame_filtered,[1 4*i+12]);
            Event_firstHalf=NAT{1,j}(SelectedFrame_filtered_firstHalf,[1 4*i+12]);
            Event_secondHalf=NAT{1,j}(SelectedFrame_filtered_secondHalf,[1 4*i+12]);
            CellForAnalysis{j,1}(k)=i;
            for n=1:1:Shuffling
                xmin=Shuffling_mininterval*ExperimentInformation.Trackingframerate;
                xmax=size(length(SelectedFrame_filtered),1)-xmin;
                ShiftFrame=round(xmin+rand(1,1)*(xmax-xmin));
                EventTrain_shuffled=circshift(EventTrain,ShiftFrame);
                EventTrain_shuffled(:,1)=EventTrain(:,1);
                EventTrain_shuffled_firstHalf=EventTrain_shuffled(1:size(HeadDirectionTrain_firstHalf,1),:);
                EventTrain_shuffled_secondHalf=EventTrain_shuffled(size(HeadDirectionTrain_firstHalf,1)+1:end,:);
                TurningCurve_shuffled=SpatialTuning_BNT.TurnningCurver_power(HeadDirectionTrain,...
                    EventTrain_shuffled(:,2),...
                    AngleBinsize,...
                    1/(ExperimentInformation.Trackingframerate/ExperimentInformation.ImagingPlane),...
                    AngleSmooth);
                TurnningCurveStastics_shuffled=SpatialTuning_BNT.tcStatistics(TurningCurve_shuffled,AngleBinsize, 50);
                MVL_shuffled(i,n,j)=TurnningCurveStastics_shuffled.r;

                TurningCurve_firstHalf_shuffled=SpatialTuning_BNT.TurnningCurver_power(HeadDirectionTrain_firstHalf,...
                    EventTrain_shuffled_firstHalf(:,2),...
                    AngleBinsize,...
                    1/(ExperimentInformation.Trackingframerate/ExperimentInformation.ImagingPlane),...
                    AngleSmooth);
                %                 TurnningCurveStastics_firstHalf=SpatialTuning_BNT.tcStatistics(TurningCurve_firstHalf,AngleBinsize, 50);

                TurningCurve_secondHalf_shuffled=SpatialTuning_BNT.TurnningCurver_power(HeadDirectionTrain_secondHalf,...
                    EventTrain_shuffled_secondHalf(:,2),...
                    AngleBinsize,...
                    1/(ExperimentInformation.Trackingframerate/ExperimentInformation.ImagingPlane),...
                    AngleSmooth);
                %                 TurnningCurveStastics_secondHalf=SpatialTuning_BNT.tcStatistics(TurningCurve_secondHalf,AngleBinsize, 50);

                Correlation_shuffled(i,n,j)=corr(TurningCurve_firstHalf_shuffled(:,2),TurningCurve_secondHalf_shuffled(:,2));
                MVL_shuffled(i,Shuffling+1,j)=prctile(MVL_shuffled(i,1:Shuffling,j),95);
                MVL_shuffled(i,Shuffling+2,j)=prctile(MVL_shuffled(i,1:Shuffling,j),99);
                Correlation_shuffled(i,Shuffling+1,j)=prctile(Correlation_shuffled(i,1:Shuffling,j),95);
                Correlation_shuffled(i,Shuffling+2,j)=prctile(Correlation_shuffled(i,1:Shuffling,j),99);
                TurningCurve_whole{j,i}=SpatialTuning_BNT.TurnningCurver_power(HeadDirectionTrain,...
                    EventTrain(:,2),...
                    AngleBinsize,...
                    1/(ExperimentInformation.Trackingframerate/ExperimentInformation.ImagingPlane),...
                    AngleSmooth);
                TurningCurveStat_whole{j,i}=SpatialTuning_BNT.tcStatistics(TurningCurve_whole{j,i}, AngleBinsize, 50);
                MVL_shuffled(i,Shuffling+3,j)=TurningCurveStat_whole{j,i}.r;
                TurningCurve_firsthalf{j,i}=SpatialTuning_BNT.TurnningCurver_power(HeadDirectionTrain_firstHalf,...
                    Event_firstHalf(:,2),...
                    AngleBinsize,...
                    1/(ExperimentInformation.Trackingframerate/ExperimentInformation.ImagingPlane),...
                    AngleSmooth);
                TurningCurveStat_firsthalf{j,i}=SpatialTuning_BNT.tcStatistics(TurningCurve_firsthalf{j,i}, AngleBinsize, 50);
                TurningCurve_secondthalf{j,i}=SpatialTuning_BNT.TurnningCurver_power(HeadDirectionTrain_secondHalf,...
                    Event_secondHalf(:,2),...
                    AngleBinsize,...
                    1/(ExperimentInformation.Trackingframerate/ExperimentInformation.ImagingPlane),...
                    AngleSmooth);
                TurningCurveStat_secondthalf{j,i}=SpatialTuning_BNT.tcStatistics(TurningCurve_secondthalf{j,i},AngleBinsize, 50);
                Correlation_shuffled(i,Shuffling+3,j)=corr(TurningCurve_firsthalf{j,i}(:,2),TurningCurve_secondthalf{j,i}(:,2));
                disp([num2str(i),'-',num2str(n)]);
            end
            k=k+1;
        else
        end
    end
end
%% identify HD cells
IsHDCell=cell(ExperimentInformation.Session,1);
for j=1:1:ExperimentInformation.Session
    g=1;
    for i=1:1:ExperimentInformation.TotalCell
            if MVL_shuffled(i,Shuffling+3,j)>MVL_shuffled(i,Shuffling+1,j) && Correlation_shuffled(i,Shuffling+3,j)>Correlation_shuffled(i,Shuffling+1,j)
                IsHDCell{j,1}(g)=i;
                g=g+1;
            else
            end
    end
end
%% save HD cell information
HDCellAnalysis=struct;
HDCellAnalysis.IsHDCell=IsHDCell;
HDCellAnalysis.TurningCurve_whole=TurningCurve_whole;
HDCellAnalysis.TurningCurve_firsthalf=TurningCurve_firsthalf;
HDCellAnalysis.TurningCurve_secondthalf=TurningCurve_secondthalf;
HDCellAnalysis.TurningCurveStat_whole=TurningCurveStat_whole;
HDCellAnalysis.TurningCurveStat_firsthalf=TurningCurveStat_firsthalf;
HDCellAnalysis.TurningCurveStat_secondthalf=TurningCurveStat_secondthalf;
HDCellAnalysis.CellForAnalysis=CellForAnalysis;
HDCellAnalysis.MVL_shuffled=MVL_shuffled;
HDCellAnalysis.Correlation_shuffled=Correlation_shuffled;
HDCellAnalysis.Shuffling=Shuffling;
HDCellAnalysis.AngleSmooth=AngleSmooth;
HDCellAnalysis.AngleBinsize=AngleBinsize; % cm
HDCellAnalysis.SpeedThreadhold=SpeedThreadhold; %cm/mm
HDCellAnalysis.MinEventCount=MinEventCount;
HDCellAnalysis.MinSNR=MinSNR;
HDCellAnalysis.Shuffling_mininterval=Shuffling_mininterval; %second
%% plot  whole-session calcium activity maps, colored by head-direction, for all HD cells
close all
figure
x0=-100;
y0=-100;
width=3440;
height=1200;
set(gcf,'position',[x0,y0,width,height])
j=1;
coluum=20;
S=0;
for k=1:1:size(HDCellAnalysis.IsHDCell{j,1},2)
    i=HDCellAnalysis.IsHDCell{j,1}(k);
    P=mod(k,coluum);
    if P==0
        P=coluum;

    elseif P==1
        S=S+1;
    else
    end
    SelectedFrame_filtered=intersect(find(~isnan(NAT{1,j}(:,4*i+10))),find(NAT{1,j}(:,6)==1));% filter out the frames with speed valid
    SelectedFrame_filtered=intersect(SelectedFrame_filtered,find(NAT{1,j}(:,5)>2.5));% filter out the frames with speed threadhold
    Event_filtered=intersect(find(NAT{1,j}(:,4*i+12)>0),find(NAT{1,j}(:,6)==1));% filter out the frames with speed valid
    Event_filtered=intersect(Event_filtered,find(NAT{1,j}(:,5)>2.5));% filter out the frames with speed threadhold
    Bestshift=GridCellAnalysis.GridBestShift(i);
    Position=NAT{1,j}(Event_filtered,2:3);
    Position(:,1)=Position(:,1)+ (Bestshift*cos(NAT{1,j}(Event_filtered,4) * pi/180));
    Position(:,2)=Position(:,2)+ (Bestshift*sin(NAT{1,j}(Event_filtered,4) * pi/180));

    Event=NAT{1,j}(Event_filtered,4*i+12);
    Direction=NAT{1,j}(Event_filtered,4);
    Max=max(Event(:));
    scatter(Position(:,1)+100*(P-1),Position(:,2)-100*(S-1),10*(sqrt(Event./Max)),Direction,'filled','MarkerFaceAlpha',0.8)
    colormap(gca,hsv)
    caxis([0 360]);
%     colorbar;
    ylim([-100*(round(size(HDCellAnalysis.IsHDCell{j,1},2)/coluum)+0.5),50])
    xlim([-50,100*coluum])
    daspect([1 1 1]);
    hold on
    axis off
end
set(gca,'color',[1 1 1]);
set(gcf,'color',[1 1 1]);

%% plot  whole-session HD tuning for all HD cells
close all
figure
x0=10;
y0=10;
width=4000;
height=1400;
set(gcf,'position',[x0,y0,width,height])
j=1;
for k=1:1:size(HDCellAnalysis.IsHDCell{j,1},2)
    i=HDCellAnalysis.IsHDCell{j,1}(k);
    subplot(9,20,k,'align')
    Occupancy=preprocessing.circularSmooth(TurningCurve_whole{j,i}(:,3),AngleSmooth);
    Tuning=TurningCurve_whole{j,i}(:,2);
    MaxTime=max(Occupancy);
    MaxTuning=max(Tuning);
    Occupancy=0.5*Occupancy./MaxTime;
    Tuning=Tuning./MaxTuning;
    H=polarplot([TurningCurve_whole{j,i}(:,1)/180*pi;TurningCurve_whole{j,i}(1,1)/180*pi],[Occupancy;Occupancy(1)],'color',[0.6 0.6 0.6],'LineWidth',1);
    hold on
    H=polarplot([TurningCurve_whole{j,i}(:,1)/180*pi;TurningCurve_whole{j,i}(1,1)/180*pi],[Tuning;Tuning(1)],'color',[0 0 0],'LineWidth',1.5);
    Ax = gca;
    Ax.RTick = [];
    Ax.RTickLabel = [];
    Ax.ThetaTickLabel = [];
    Ax.ThetaTick  = [0 90 180 270];
    Ax.RLim=[0 1];
    AX.FontSize=0;
    Ax.ThetaAxis.Color = [1 1 1];
    AX.RColor = [1 1 1];
    set(gca,'GridColor',[0 0 0]);
    set(gca,'GridAlpha',1);
    set(gca,'RGrid','off');
    set(H,'LineWidth',1);
    AX.RAxis.Visible='off';
%     title(['P-time: ',num2str(MaxTime,'%.2f'),' s',', P-tuning: ',num2str(MaxTuning,'%.2f')])
end
set(gca,'color',[1 1 1]);
set(gcf,'color',[1 1 1]);

%%
save ([ExperimentInformation.RawDataAddress,'\HDCellAnalysis.mat'],'HDCellAnalysis','-v7.3');
disp('HD cell analysis was done!');


% new procedure: generate motor seed/map in trialRes space
% find top 100 cells correlating to motor, screen with Rh4+Rh5(+Rh6??) masks

% corr sweep (0.5-0.7) to get top %2 cells, then kmeans, save; rank by stim-lock, save
clear all; close all; clc

%% folder setup
isSaveFig = 1;
isPlotFig = 1;

outputDir = GetOutputDataDir;
saveDir = [];
saveDir{1} = fullfile(outputDir,'motor_map_notseed_lrRes_1_kmeans_030417');
saveDir{2} = fullfile(outputDir,'motor_map_notseed_lrRes_2_autoclus_030417');
if ~exist(saveDir{1}, 'dir'), mkdir(saveDir{1}), end;
if ~exist(saveDir{2}, 'dir'), mkdir(saveDir{2}), end;

%% init

hfig = figure;
InitializeAppData(hfig);
ResetDisplayParams(hfig);

setappdata(hfig,'isMotorseed',0);
setappdata(hfig,'isTrialRes',1);

%% run fish
range_fish = GetFishRange;%[1:3,5:18];
M_thres_reg = zeros(3,18);
M_numTopCorr = zeros(1,18);
M_motorseedRegs = cell(1,18);
M_compareMotorCellNumber = zeros(2,18);

for i_fish = range_fish
    ClusterIDs = [1,1];
    [~,~,~,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,ClusterIDs);

    MASKs = getappdata(hfig,'MASKs');
    CellXYZ_norm = getappdata(hfig,'CellXYZ_norm');
    absIX = getappdata(hfig,'absIX');

    %% get motor regressors
    [~,~,regressor_m_raw] = GetMotorRegressor(behavior,i_fish);
    Reg = regressor_m_raw([1,3],:);

    %% regression (in tRes), thresholding by % of cells (instead of corr thres)

    %     [~,Reg_tRes] = GetTrialAvrLongTrace(hfig,Reg);
    %     [~,M_0_tRes] = GetTrialAvrLongTrace(hfig,M_0);

%     Reg = FindClustermeans(gIX_seed,M);
    Reg_LR = Reg-repmat(mean(Reg),2,1);

    %     Corr = corr(Reg_tRes_LR',M_0_tRes');
    Corr = corr(Reg_LR',M_0');
    [Corr_sorted,IX_corr] = sort(Corr,2,'descend');

    %     [corr_max,IX] = max(Corr,[],1);
    %     [~,I] = sort(corr_max,'descend');

    M_target_prctcell= [1,2,3];
    for i_numcell = 1:2,
        nCells_total = size(M_0,1);
        prctcell = M_target_prctcell(i_numcell);
        nCells_target = round(prctcell/100 * nCells_total);

        %% target cell number: counting cells in hindbrain only

        Msk_IDs = 114; % mask for full hindbrain

        % isScreenMskFromAllCells
        cIX = (1:length(absIX))';
        gIX = ones(size(cIX));
        [cIX_hb,gIX_hb] = ScreenCellsWithMasks(Msk_IDs,cIX,gIX,MASKs,CellXYZ_norm,absIX);

        I_hb = ismember(IX_corr,cIX_hb);
        cum_I_hb1 = cumsum(I_hb(1,:));
        cum_I_hb2 = cumsum(I_hb(2,:));
        lastIX{1} = find(cum_I_hb1==nCells_target,1,'first');
        lastIX{2} = find(cum_I_hb2==nCells_target,1,'first');

        % cut off the desired number of cells to display
        for i_lr = 1:2
            cIX = IX_corr(i_lr,1:lastIX{i_lr})';
            gIX = ceil((1:length(cIX))'/(length(cIX)/20));
            M = UpdateIndices_Manual(hfig,cIX,gIX);
            [~,M_tRes] = GetTrialAvrLongTrace(hfig,M);
            setappdata(hfig,'M',M_tRes);

            M_thres_reg(i_lr,i_fish) = Corr_sorted(i_lr,lastIX{i_lr});
            M_compareMotorCellNumber(i_lr,i_fish) = length(cIX);

            %% clustering: trying Autoclus here!
            if i_numcell==1
                %%
                numK = 16; % manual
                gIX = Kmeans_Direct(M_tRes,numK);
            else
                cIX_reg = cIX;%(1:size(M_0,1))';
                [cIX,gIX] = AutoClustering(cIX,gIX,M_0,cIX_reg);
                UpdateIndices_Manual(hfig,cIX,gIX);
            end
            %% Plot anat
            if isPlotFig,

                I = LoadCurrentFishForAnatPlot(hfig,cIX,gIX);
                f{i_lr} = DrawCellsOnAnat(I);
%                 f{i_lr} = figure('Position',[50,100,1400,800]);
%                 % isCentroid,isPlotLines,isPlotBehavior,isPlotRegWithTS
%                 subplot(121)
%                 setappdata(hfig,'isPlotBehavior',1);
%                 setappdata(hfig,'isStimAvr',0);
%                 setappdata(hfig,'isPlotLines',0);
%                 %             UpdateTimeIndex(hfig);
%                 DrawTimeSeries(hfig,cIX,gIX);
%
%                 % right plot
%                 ax = subplot(122);
%                 I = LoadCurrentFishForAnatPlot(hfig,cIX,gIX);
%                 DrawCellsOnAnat(I,ax);

            end
        end

        combineFiguresLR(f{1},f{2});

        % Save plot
        if isSaveFig,
            filename = fullfile(saveDir{i_numcell}, ['Fish',num2str(i_fish),'_motormap_',num2str(prctcell),'%_each']);
            saveas(gcf, filename, 'png');
            close(gcf)
        end

    end
end

%%
% range_fish excludes Fish 4
% M_compareMotorCellNumber(:,4) = NaN;
% figure;bar(M_compareMotorCellNumber')

github-repos/MATLAB/xiuyechen-FishExplorer/FishExplorer-c61392cf0835480d64fc03c15f1992935fdc7106/figure scripts/SensoryMotor/arc code/motormap, tRes versions, comparisons, w Clusters or Autoclus to follow/fig3_motormap_trialRes_lrRes_notseed.m


function[image, oriImSize] = e2s2_prepareImage(net, image, maxImageSize)
% [image, oriImSize] = e2s2_prepareImage(net, image, maxImageSize)
%
% Resize the image and subtract the mean image.
%
% Copyright by Holger Caesar, 2015

% Resize image
oriImSize = size(image);
resizeFactor = maxImageSize / max(oriImSize(1:2));
targetSize = ceil(oriImSize(1:2) .* resizeFactor); % ceil corresponds to Matlab's imresize behavior
image = imresize(image, resizeFactor);
assert(size(image, 1) == targetSize(1) && size(image, 2) == targetSize(2));

if numel(net.meta.normalization.averageImage) == 3,
    % Subtract fixed number from each channel
    image(:, :, 1) = image(:, :, 1) - net.meta.normalization.averageImage(1);
    image(:, :, 2) = image(:, :, 2) - net.meta.normalization.averageImage(2);
    image(:, :, 3) = image(:, :, 3) - net.meta.normalization.averageImage(3);
else
    % Resize averageImage and subtract it from each image
    % Note: This cannot be done on the gpu as Matlab's gpu-compatible
    % imresize function can only resize by a constant factor and the image
    % might not be square.
    averageImage = net.meta.normalization.averageImage ./ 255;
    averageImage = imresize(averageImage, targetSize);
    image = image - averageImage;
end;


function varargout = gamma(varargin)

switch class(varargin{1})

    case 'sdpvar'
        varargout{1} = InstantiateElementWise(mfilename,varargin{:});

    case 'char'

        operator = CreateBasicOperator('convex','positive','callback');
        operator.derivative =@(x)psi(0,x).*gamma(x);
        operator.stationary = [1.46163214496836234126 8.856031944108888e-01];
        operator.range = [gamma(1.46163214496836234126) inf];
        operator.domain = [0 inf];

        varargout{1} = [];
        varargout{2} = operator;
        varargout{3} = varargin{3};

    otherwise
        error(['SDPVAR/' upper(mfilename) ' called with weird argument']);
end


function P = polyhedron(C)
%POLYHEDRON (Overloaded)

P = Polyhedron(lmi(C));


 function x = read_zubal_attn(varargin)
%function x = read_zubal_attn(options)
%| read in zubal attenuation phantom from data directory,
%| and assign it attenuation coefficients in inverse mm units.
%| options
%|	'nx'		desired size
%|	'ny'
%|	'ddir'		data directory

if nargin==1 && streq(varargin{1}, 'test'), read_zubal_attn_test, return, end

if nargout == 0, ir_usage, end

arg.ddir = '';
arg.file = 'zubal,attn.raw';
arg.nx = 128;
arg.ny = [];
arg = vararg_pair(arg, varargin);
if isempty(arg.ny), arg.ny = arg.nx; end

x = read_zubal_attn_do(arg.ddir, arg.file, arg.nx, arg.ny);

function x = read_zubal_attn_do(ddir, file, nx, ny)

% guess .../data directory by looking parallel to '.../transmission' directory
if ~isvar('ddir') || isempty(ddir)
	t = path_find_dir([filesep 'transmission']);
	ddir = strrep(t, 'transmission', 'data');
end

if ~exist(ddir, 'dir')
	warning(sprintf('cannot find data directory %s', ddir))
	error(sprintf('edit path in %s.m for your installation', mfilename))
end

file = [ddir filesep file];
if ~exist(file, 'file')
%	os_run(sprintf([ddir filesep 'do,attn,zubal %s'], file)) % here is how to create!
	error 'cannot find zubal phantom raw data'
end

fp = fopen(file, 'rb');
if (fp == -1), error 'open file', end
x = fread(fp, [128 128], 'uint8');
if fclose(fp), error 'close file', end

x = x(:,[(end-10):end 1:(end-11)]); % center it nicely

% assign attenuation coefficients in inverse mm units
mulist = [0.002 0.0096 0.0120];
for ii=1:length(mulist)
	x(x == ii) = mulist(ii);
end

x = ir_phantom_resize(x, nx, ny);

function read_zubal_attn_test
x = read_zubal_attn('nx', 120, 'ny', 90);
im(x, 'zubal phantom: transmission'), cbar


% THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION IS RELEASED "AS IS."  THE U.S. GOVERNMENT MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, CONCERNING THIS SOFTWARE AND ANY ACCOMPANYING DOCUMENTATION, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT WILL THE U.S. GOVERNMENT BE LIABLE FOR ANY DAMAGES, INCLUDING ANY LOST PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, OR INABILITY TO USE, THIS SOFTWARE OR ANY ACCOMPANYING DOCUMENTATION, EVEN IF INFORMED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.
%
% file: test_prop_diff.m
%
% use: run "test_prop_diff" and then examine "test_prop_diff_results.csv" in the work folder and
%      compare it to the "test_prop_diff_results_reference.csv" distributed with the code.
%      Failure to run or significant differences in results may indicate installation problems.
%
% change log:
%   030106 tdr created
%
% function y = prop_diff(x1,n1,x2,n2,delta)
% x - number of positive events
% n - number of trials
% delta - the difference of interest
% y - Pr (p1 - p2 >= delta), where p1_hat = x1/n1 and p2_hat = x2/n2

function test_prop_diff

n1s = [1 30 100 1e5];
n2s = n1s;
deltas = [-0.5 0 1e-2 0.9];

fid = fopen('test_prop_diff_results.csv','w');
fprintf(fid,'%s\n','delta, n1, n2, x1, x2, p1_hat, p2_hat, Pr(p1 - p2 >= delta)');

for delta = deltas
   for n1 = n1s
      if n1 < 10
         x1s = [0 1 round(n1/2) n1];
      else
         x1s = [0 1 round(n1/3) round(n1/2) n1-1 n1];
      end;
      for n2 = n2s
         if n2 < 10
            x2s = [0 1 round(n2/2) n2];
         else
            x2s = [0 1 round(n2/3) round(n2/2) n2-1 n2];
         end;
         for x1 = x1s
            for x2 = x2s
               result_array = [delta n1 n2 x1 x2 x1/n1 x2/n2 prop_diff(x1,n1,x2,n2,delta)];
               fprintf(fid,'%8.6f, %d, %d, %d, %d, %8.6f, %8.6f, %8.6f\n',result_array);
		    end;
         end;
      end;
   end;
end;

fclose(fid);


%   atlasNew = updateTinC(atlas,X,Y)
%
%Author: B. Fischer
%Purpose:
%   Deform an image, say atlas, so that values in the implicit function,
%   atlas(1:M,1:N) are mapped to the positions in atlas(X,Y).
%   This function is used in the elastic matching algorithms in the
%   Analysis/Atlas directory.
%
%   It was written in C- by Bernd.  It appears that the values in X,Y
%   must match the coordinates (size) of atlas.  No linear interpolation is
%   performed, just a deformation of the cartesian coordinates.
%
%  These notes by BW.
%


filename='Throne_Tetrahedra_SYM';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance'};
weights = [1];
constraint = {'volume'};
optimizer = 'SLERP'; incrementFactor = 1;
filterType = 'P1';
constraint_case = 'INEQUALITY';
line_search_initiator = 'INCREASING LAST STEP';

nsteps = 10;
Vfrac_final = 0.1;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

printing = false;

Vfrac_initial = 1;
optimality_initial = 1e-3;
constr_initial = 1e-3;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;

% plotting = true;
% showBC = true;


function [ cost, grad, numTotal, pred_cell ] = drdae_discrim_obj( ...
    theta, eI, data_cell, targets_cell, fprop_only, pred_out)
% Copyright (c) 2014-present University of Illinois at Urbana-Champaign
% All rights reserved.
%
% Developed by:     Po-Sen Huang, Paris Smaragdis
%                   Department of Electrical and Computer Engineering
%                   Department of Computer Science
%
% discrim. training (not joint)
%
%PRNN_OBJ MinFunc style objective for Deep Recurrent Denoising Autoencoder
%   theta is the full parameter vector
%   eI contains experiment / network architecture
%   data_cell is a cell array of matrices. Each a distinct length is a cell
%             entry. Each matrix has a time series example in each column
%   targets_cell is parallel to data, but contains the labels for each time
%   fprop_only is a flag that only computes the cost, no gradient
%   numTotal is total number of frames evaluated
%   pred_out is a binary flag for whether pred_cell is populated
%            pred_cell only filled properly when utterances one per cell

%% Debug: Turns this into an identity-function for debugging rest of system
if isfield(eI, 'objReturnsIdentity') && eI.objReturnsIdentity
    cost = 0; grad = 0; numTotal = 0;
    for l = 1:numel(data_cell)
        numUtterances = size(data_cell{l}, 2);
        original_vector = reshape(data_cell{l}, eI.winSize*eI.featDim, []);
        midPnt = ceil(eI.winSize/2);
        original_vector = original_vector((midPnt-1)*14+1 : midPnt*14, :);
        pred_cell{l} = reshape(original_vector, [], numUtterances);
    end
    return;
end

return_activation = 0;

%% Load data from globals if not passed in (happens when run on RPC slave)
global g_data_cell;
global g_targets_cell;
isSlave = false;
if isempty(data_cell)
    data_cell = g_data_cell;
    targets_cell = g_targets_cell;
    isSlave = true;
end;
pred_cell = cell(1,numel(data_cell));
act_cell = cell(1,numel(data_cell));
%% default short circuits to false
if ~isfield(eI, 'shortCircuit')
    eI.shortCircuit = 0;
end;

%% default dropout to false
if ~isfield(eI, 'dropout')
  eI.dropout = 0;
end;

%% setup weights and accumulators
[stack, W_t] = rnn_params2stack(theta, eI);
cost = 0; numTotal = 0;
outputDim = eI.layerSizes(end);
%% setup structures to aggregate gradients
stackGrad = cell(1,numel(eI.layerSizes));
% W_t_grad = zeros(size(W_t));
if isfield(eI, 'fullRNN') && eI.fullRNN==1
   W_t_grad = cell(1,numel(eI.layerSizes)-1);
    for l = 1:numel(eI.layerSizes)-1
        W_t_grad{l}.W = zeros(size(W_t{l}.W));
    end
else
   W_t_grad = zeros(size(W_t));
end

for l = 1:numel(eI.layerSizes)
    stackGrad{l}.W = zeros(size(stack{l}.W));
    stackGrad{l}.b = zeros(size(stack{l}.b));
end
if eI.shortCircuit
    stackGrad{end}.W_ss = zeros(size(stack{end}.W_ss));
end;
%% check options
if ~exist('fprop_only','var')
    fprop_only = false;
end;
if ~exist('pred_out','var')
    pred_out = false;
end;

% DROPOUT: vector of length of hidden layers with 0 or 1
% (to drop or keep activation unit) with prob=0.5
hActToDrop = cell(numel(eI.layerSizes-1),1);
for i=1:numel(eI.layerSizes)-1
 if eI.dropout
    hActToDrop{i} = 1/eI.dropout * binornd(1,eI.dropout, eI.layerSizes(i),1);
 else
   hActToDrop{i} = ones(eI.layerSizes(i),1);
 end
end

%% loop over each distinct length
for c = 1:numel(data_cell)
    data = data_cell{c};
    targets = {};
    if ~isempty(targets_cell), targets = targets_cell{c}; end;
    uttPred = [];
    T =size(data,1) / eI.inputDim;
    % store hidden unit activations at each time instant
    hAct = cell(numel(eI.layerSizes)-1, T);
    for t = 1:T
        %% forward prop all hidden layers
        for l = 1:numel(eI.layerSizes)-1
            if l == 1
                hAct{1,t} = stack{1}.W * data((t-1)*eI.inputDim+1:t*eI.inputDim, :);
            else
                hAct{l,t} = stack{l}.W * hAct{l-1,t};
            end;
            hAct{l,t} = bsxfun(@plus, hAct{l,t}, stack{l}.b);
            % temporal recurrence. limited to single layer for now
            if l == eI.temporalLayer && t > 1
                hAct{l,t} = hAct{l,t} + W_t * hAct{l,t-1};
            end;
            % nonlinearity
            if strcmpi(eI.activationFn,'tanh')
                hAct{l,t} = tanh(hAct{l,t});
            elseif strcmpi(eI.activationFn,'logistic')
                hAct{l,t} = 1./(1+exp(-hAct{l,t}));
            elseif strcmpi(eI.activationFn,'RELU')
                hAct{l,t} = max(0,hAct{l,t});
            else
                error('unrecognized activation function: %s',eI.activationFn);
            end;
            %dropout (hActToDrop will be all ones if no dropout specified)
            hAct{1,t} = bsxfun(@times, hAct{1,t}, hActToDrop{l});
        end;
        % forward prop top layer not done here to avoid caching it
    end;
    %% compute cost and backprop through time
    if  eI.temporalLayer
        delta_t = zeros(eI.layerSizes(eI.temporalLayer),size(data,2));
    end;
    for t = T:-1:1
        l = numel(eI.layerSizes);
        %% forward prop output layer for this timestep
        curPred = bsxfun(@plus, stack{l}.W * hAct{l-1,t}, stack{l}.b);
        % add short circuit to regression prediction if model has it
        if eI.shortCircuit
            curPred = curPred + stack{end}.W_ss ...
                * data((t-1)*eI.inputDim+1:t*eI.inputDim, :);
        end;
        if pred_out, uttPred = [curPred, uttPred]; end;
        % skip loss computation if no targets given
        if isempty(targets), continue; end;

        curTargets = targets((t-1)*outputDim+1:t*outputDim, :);

        if eI.cleanonly==0,
        curTargets_neg = [curTargets(outputDim/2+1:outputDim,:); curTargets(1:outputDim/2,:)];
        end
        if eI.cleanonly==1,
            delta = curPred  - curTargets;
            cost = cost + 0.5 * sum( sum((curPred - curTargets).^2));
        else
            delta = (1- eI.r) * curPred + eI.r * curTargets_neg - curTargets;
            cost = cost + 0.5 * ( sum( sum((curPred - curTargets).^2))-  eI.r* sum( sum((curPred - curTargets_neg).^2)));
        end

        if fprop_only, continue; end;
        %% regression layer gradient and delta
        stackGrad{l}.W = stackGrad{l}.W + delta * hAct{l-1,t}';
        stackGrad{l}.b = stackGrad{l}.b + sum(delta,2);
        % short circuit layer
        if eI.shortCircuit
            stackGrad{end}.W_ss = stackGrad{end}.W_ss + delta ...
                * data((t-1)*eI.inputDim+1:t*eI.inputDim, :)';
        end;
        delta = stack{l}.W' * delta;
        %% backprop through hidden layers
        for l = numel(eI.layerSizes)-1:-1:1
            % aggregate temporal delta term if this is the recurrent layer
            if l == eI.temporalLayer
                delta = delta + delta_t;
            end;
            % push delta through activation function for this layer
            % tanh unit choice assumed
            if strcmpi(eI.activationFn,'tanh')
                delta = delta .* (1 - hAct{l,t}.^2);
            elseif strcmpi(eI.activationFn,'logistic')
                delta = delta .* hAct{l,t} .* (1 - hAct{l,t});
             elseif strcmpi(eI.activationFn,'RELU')
                delta = delta .* double(hAct{l,t}>0);
            else
                error('unrecognized activation function: %s',eI.activationFn);
            end;

            % gradient of bottom-up connection for this layer
            if l > 1
                stackGrad{l}.W = stackGrad{l}.W + delta * hAct{l-1,t}';
            else
                stackGrad{l}.W = stackGrad{l}.W + delta * data((t-1)*eI.inputDim+1:t*eI.inputDim, :)';
            end;
            % gradient for bias
            stackGrad{l}.b = stackGrad{l}.b + sum(delta,2);

            % compute derivative and delta for temporal connections
            if l == eI.temporalLayer && t > 1
                 W_t_grad = W_t_grad + delta * hAct{l,t-1}';
                 % push delta through temporal weights
                 delta_t = W_t' * delta;
            end;
            % push delta through bottom-up weights
            if l > 1
                delta = stack{l}.W' * delta;
            end;
        end
    end
    pred_cell{c} = uttPred;
    % Return the activations for this utterance.
    if return_activation,
      act_cell{c} = cell2mat(hAct);
    end
    % keep track of how many examples seen in total
    numTotal = numTotal + T * size(targets,2);
end

%% stack gradients into single vector and compute weight cost
wCost = numTotal * eI.lambda * sum(theta.^2);
grad = rnn_stack2params(stackGrad, eI, W_t_grad, true);
grad = grad + 2 * numTotal * eI.lambda * theta;

%% clipping
if isfield(eI,'clip') && eI.clip~=0, % if eI.clip==0, no clip
  if eI.clip > 0 % method one -clip the whole
      norm_grad = norm(grad);
      fprintf('norm_grad:%f\n', norm_grad);
      % avoid numerial problem
      if norm_grad <0 || norm_grad > 1e15 || isnan(norm_grad) || isinf(norm_grad),
          grad = zeros(size(grad));
          fprintf('set gradient to zeros\n');
      end
      if norm_grad > eI.clip
         grad = eI.clip * grad/ norm_grad;
      end
  else % method two - clip each entry
      clip_value = -1*eI.clip;
      grad(grad > clip_value)=clip_value;
      grad(grad < -clip_value)=-clip_value;
  end
end

%%
avCost = cost/numTotal;
avWCost = wCost/numTotal;
cost = cost + wCost;

% print output
if ~isSlave && ~isempty(targets_cell)
    fprintf('loss:  %f  wCost:  %f \t',avCost, avWCost);

    if isfield(eI, 'fullRNN') && eI.fullRNN==1
        fprintf('wNorm: %f  rNorm: %f  oNorm: %f\n',sum(stack{1}.W(:).^2),...
            sum(W_t{1}.W(:).^2), sum(stack{end}.W(:).^2));
    else
        fprintf('wNorm: %f  rNorm: %f  oNorm: %f\n',sum(stack{1}.W(:).^2),...
            sum(W_t(:).^2), sum(stack{end}.W(:).^2));
    end
end;


classdef DPCA < Algorithms.CDAlg
    properties
        nPCUsed = uint8(255);
    end
    methods
        function obj = DPCA(k)
            obj@Algorithms.CDAlg('Differential Principal Component Analysis', '');
            if exist('k', 'var'), obj.nPCUsed=uint8(k); end
        end
        [DI, k] = detectChange(obj, t1, t2);
    end
end


function ThrowFcn2(~,~, game, res1, N, M, FinishBtn, SelectBtn)

%% GET OFFENDER/DEFENDER DATA
offender = get(game.OffenseTxt, 'UserData');
defender = get(game.DefenseTxt, 'UserData');

Noff = get(game.board(offender).Text, 'UserData');
Ndef = get(game.board(defender).Text, 'UserData');

offOcc = get(game.board(offender).Patch, 'UserData');
defOcc = get(game.board(defender).Patch, 'UserData');

%% SET THROWBUTTON
set(game.ThrowBtnDef, 'Enable', 'off', 'Callback', [])

%% GET NUMBER OF TROOPS TO DEFEND WITH
while true
    N(2) = str2double(inputdlg('Number of defending troops', 'How many troops?', 1, {'1'}));

    if isempty(N(2)) || isnan(N(2))
        continue
    end
    if N(2) > Ndef
        uiwait(msgbox(sprintf('Maximum number of defending troops is %d', Ndef)))
        continue
    end
    if N(2) <= 0
        uiwait(msgbox('Defend with at least 1 unit'))
        continue
    end

    break
end

%% NUMBER OF DICE TO BE USED
M(2) = N(2) * (N(2) <= 2) + 2 * (N(2) > 2);

%% RESULT
res2 = round(rand(1,M(2)) * 5) + 1;
for i = 4 : M(2) + 3
    j = i - 3;
    imshow(sprintf('dice/%d.jpg', res2(j)), 'Parent', game.dice(i));
end
for i = M(2) + 4 : 5
    imshow('dice/7.jpg', 'Parent', game.dice(i));
end

%% INCREMENT COUNTER
set(FinishBtn, 'UserData', get(FinishBtn, 'UserData') + 1);

%% DETERMINE WINNER
X = sort(res1, 'descend');
Y = sort(res2, 'descend');
res = [X(1:min(M)); Y(1:min(M))];

for i = 1:min(M)
    if res(1,i) > res(2,i)
        set(game.board(defender).Text, 'String', num2str(Ndef - 1), ...
                                       'UserData', Ndef - 1);
        Ndef = Ndef - 1;
        playerdata = get(game.Players(defOcc(1)), 'UserData');
        playerdata(1) = playerdata(1) - 1;
        set(game.Players(defOcc(1)), 'UserData', playerdata)
        set(game.Players(defOcc(1)), 'String', info(defOcc(1), game))
    else
        set(game.board(offender).Text, 'String', num2str(Noff - 1), ...
                                       'UserData', Noff - 1);
        Noff = Noff - 1;
        playerdata = get(game.Players(offOcc(1)), 'UserData');
        playerdata(1) = playerdata(1) - 1;
        set(game.Players(offOcc(1)), 'UserData', playerdata)
        set(game.Players(offOcc(1)), 'String', info(offOcc(1), game))
    end
end

if Ndef == 0 % Invasion!
    uiwait(msgbox(sprintf('Victory! You invaded %s!', game.board(defender).Name)))

    % Update Board
    set(game.board(offender).Patch, 'UserData', [offOcc(1), 0], ...
                                    'FaceColor', game.cmap(offOcc(1), :))
    set(game.board(defender).Patch, 'UserData', [offOcc(1), 0], ...
                                    'FaceColor', game.cmap(offOcc(1), :))
    set(game.board(offender).Text, 'String', num2str(Noff - N(1)), ...
                                   'Color', [0 0 0], ...
                                   'UserData', Noff - N(1))
    set(game.board(defender).Text, 'String', num2str(N(1)), ...
                                   'UserData', N(1))

    % Update Scoreboard
    playerdata = get(game.Players(offOcc(1)), 'UserData');
    playerdata(2) = playerdata(2) + 1;
    set(game.Players(offOcc(1)), 'UserData', playerdata)
    set(game.Players(offOcc(1)), 'String', info(offOcc(1), game))
    playerdata = get(game.Players(defOcc(1)), 'UserData');
    playerdata(2) = playerdata(2) - 1;
    set(game.Players(defOcc(1)), 'UserData', playerdata)
    set(game.Players(defOcc(1)), 'String', info(defOcc(1), game))
end

%% RE-ACTIVATE FINISH/SELECT/OFFENSE BUTTON AND RESET TEXT
set(game.ThrowBtnOff, 'Enable', 'on')
set(game.txtH, 'String', 'Offender may throw the dice')
set(FinishBtn, 'Enable', 'on')
set(SelectBtn, 'Enable', 'on')


function vw = computeMeanMap(vw,scanList,forceSave)
% Computing the mean functional image for each tSeries
%
%  vw = computeMeanMap(vw,[scanList],[forceSave])
%
% The mean functional images are combined into a parameter map and
% calls setParameterMap to set vw.map = meanMap.
%
% scanList:
%   0 - do all scans
%   number or list of numbers - do only those scans
%   default - prompt user via selectScans dialog
%
% forceSave: 1 = true (overwrite without dialog)
%            0 = false (query before overwriting)
%           -1 = do not save
%
% If you change this function make parallel changes in:
%    computeCorAnal, computeResStdMap, computeStdMap
%
% djh, 12/30/98
% djh, 2/22/2001 updated to version 3
% ras, 01/05, added forceSave flag
% ras 10/05, checks if the meanMap file is saved already

if notDefined('forceSave'), forceSave = 0; end

% nScans = numScans(vw);
nScans = viewGet(vw,'numscans');

if strcmp(vw.mapName,'meanMap')
    % If exists, initialize to existing map
    map=vw.map;
elseif exist(fullfile(dataDir(vw),'meanMap.mat'),'file')
    % load from the mean map file
    load(fullfile(dataDir(vw),'meanMap.mat'),'map')
else
    % Otherwise, initialize to empty cell array
    map = cell(1,nScans);
end

% (Re-)set scanList
if ~exist('scanList','var')
    scanList = er_selectScans(vw);
elseif scanList == 0
    scanList = 1:nScans;
end
if isempty(scanList),  error('Analysis aborted: scan list is empty.'); end

% Compute it
waitHandle = mrvWaitbar(0,'Computing mean images from the tSeries.  Please wait...');
ncScans = length(scanList);
for iScan = 1:ncScans
    scan = scanList(iScan);
    dims = viewGet(vw, 'sliceDims', scan);
    map{scan} = NaN*ones(dataSize(vw,scan));
    switch lower(viewGet(vw, 'viewType'))
        case 'inplane'
            % since data in the inplane view is stored as a nifti, we can
            % get the whole data slab in one call to load tseries rather
            % than looping over slices.
            [~, nii] = loadtSeries(vw,scan);
            tSeries = niftiGet(nii, 'data');
            timeDim = length(size(tSeries));
            map{scan} = mean(tSeries, timeDim);

        otherwise
            for slice = sliceList(vw,scan)
                tSeries = loadtSeries(vw,scan,slice);
                nValid = sum(isfinite(tSeries));
                tSeries(isnan(tSeries(:))) = 0;

                % if there is one time point, we will have problems, so duplicate
                % the data
                if size(tSeries,1) == 1,
                    tSeries = repmat(tSeries, 3, 1);
                    nValid = sum(isfinite(tSeries));
                end

                tmp = sum(tSeries) ./ nValid;
                if strcmp(vw.viewType,'Inplane')
                    map{scan}(:,:,slice) = reshape(tmp,dims);
                else
                    map{scan}(:,:,slice) = tmp;
                end
            end
    end
    mrvWaitbar(scan/ncScans)
end
close(waitHandle);

% Set Parameter MAp
vw = setParameterMap(vw, map, 'meanMap');

% Save file
if forceSave >= 0, saveParameterMap(vw, [], forceSave); end

return


classdef form_acc < mp.form_ac
%MP.FORM_ACC  MATPOWER Formulation class for AC cartesian voltage formulations
%   Each concrete Network Model Element class must inherit, at least
%   indirectly, from both MP.NM_ELEMENT and MP.FORM.
%
%   Subclass of MP.FORM_AC.
%   MP.FORM provides properties and methods related to the specific
%   formulation (e.g. DC version, AC polar power version, etc.)
%
%   Properties
%       (model parameters inherited from MP.FORM_AC)
%
%   Methods
%       form_name() - returns string w/name of formulation ('AC-cartesian formulation')
%       form_tag() - returns string w/short label for formulation ('acc')

%   MATPOWER
%   Copyright (c) 2019-2021, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

%     properties
%     end

    methods
        function name = form_name(obj)
            name = 'AC-cartesian';
        end

        function tag = form_tag(obj)
            tag = 'acc';
        end

        function vtypes = model_vvars(obj)
            vtypes = {'vr', 'vi'};
        end

        function [Iu, Iw] = port_inj_current_jac(obj, ...
                n, v_, Y, M, invdiagvic, diagSlincJ)
            % [Iu, Iw] = obj.port_inj_current_jac(...)

            %% intermediate terms
            E = invdiagvic * (conj(M) - invdiagvic * diagSlincJ);

%             %% linear current term
%             Iu = Y;
%             Iw = 1j * Y;
%
%             %% + current from linear power term
%             Iu = Iu + E;
%             Iw = Iw - 1j * E;

            Iu = Y + E;
            Iw = 1j * (Y - E);
        end

        function [Iuu, Iuw, Iww] = port_inj_current_hess_v(obj, x_, lam, v_, z_, diaginvic, Y, M, diagSlincJ, dlamJ)
            % [Iuu, Iuw, Iww] = obj.port_inj_current_hess_v(x_, lam)
            % [Iuu, Iuw, Iww] = obj.port_inj_current_hess_v(x_, lam, sysx)
            % [Iuu, Iuw, Iww] = obj.port_inj_current_hess_v(x_, lam, sysx, idx)
            % [...] = obj.port_inj_current_hess_vz(x_, lam, v_, z_, diaginvic, Y, M, diagSlincJ, dlamJ)

            if nargin < 10
                sysx = v_;
                if nargin < 5
                    idx = []
                else
                    idx = z_;
                end
                [Y, M, N, s] = obj.get_params(idx, {'Y', 'M', 'N', 's'});
                [v_, z_, vi_] = obj.x2vz(x_, sysx, idx);

                %% compute linear power injections
                if isempty(z_)
                    Slin = M*v_ + s;
                else
                    Slin = M*v_ + N*z_ + s;
                end

                n  = length(v_);    %% number of all port voltages
                ni = length(vi_);   %% number of selected port voltages
                diaginvic = sparse(1:ni, 1:ni, 1 ./ conj(vi_), ni, ni);
                if isempty(idx)     %% all ports
                    diagSlincJ = sparse(1:n, 1:n, conj(Slin), n, n);
                    dlamJ      = sparse(1:n, 1:n, lam, n, n);
                else                %% selected ports
                    diagSlincJ = sparse(1:ni, idx, conj(Slin), ni, n);
                    dlamJ      = sparse(1:ni, idx, lam, ni, n);
                end
            else
                n  = length(v_);    %% number of all port voltages
                ni = length(lam);
            end

            %% intermediate terms
            % A = diaginvic * conj(M);
            % B = diaginvic * conj(N);
            % C = diaginvic * diaginvic * diagSlincJ;
            D = (diaginvic * dlamJ).';
            E = diaginvic * (conj(M) - diaginvic * diagSlincJ);
            % E = A - C;
            F = D * E;
            G = -(F.' + F);
            % H = -D * B;

            %% linear current term
            %% second derivatives all zero

            %% current from linear power term
            Iuu = G;
            Iuw = -1j * G;
            Iww = -G;
        end

        function [Iuzr, Iuzi, Iwzr, Iwzi] = port_inj_current_hess_vz(obj, x_, lam, v_, z_, diaginvic, N, dlamJ)
            % [Iuzr, Iuzi, Iwzr, Iwzi] = obj.port_inj_current_hess_vz(x_, lam)
            % [...] = obj.port_inj_current_hess_vz(x_, lam, sysx)
            % [...] = obj.port_inj_current_hess_vz(x_, lam, sysx, idx)
            % [...] = obj.port_inj_current_hess_vz(x_, lam, v_, z_, diaginvic, N, dlamJ)

            if nargin < 8
                sysx = v_;
                if nargin < 5
                    idx = []
                else
                    idx = z_;
                end
                N = obj.get_params(idx, 'N');
                [v_, z_, vi_] = obj.x2vz(x_, sysx, idx);

                n  = length(v_);    %% number of all port voltages
                ni = length(vi_);   %% number of selected port voltages
                diaginvic = sparse(1:ni, 1:ni, 1 ./ conj(vi_), ni, ni);
                if isempty(idx)     %% all ports
                    dlamJ = sparse(1:n, 1:n, lam, n, n);
                else                %% selected ports
                    dlamJ = sparse(1:ni, idx, lam, ni, n);
                end
            else
                n  = length(v_);    %% number of all port voltages
                ni = length(lam);
            end

            %% intermediate terms
            % A = diaginvic * conj(M);
            B = diaginvic * conj(N);
            % C = diaginvic * diaginvic * diagSlincJ;
            D = (diaginvic * dlamJ).';
            % E = diaginvic * (conj(M) - diaginvic * diagSlincJ);
            % E = A - C;
            % F = D * E;
            % G = -(F.' + F);
            H = -D * B;

            %% current from linear power term
            Iuzr = H;
            Iuzi = -1j * H;
            Iwzr = Iuzi;
            Iwzi = -H;
        end

        function [Su, Sw] = port_inj_power_jac(obj, ...
                n, v_, Y, M, diagv, diagvi, diagIlincJ)
            % [Su, Sw] = obj.port_inj_power_jac(...)

            %% intermediate terms
%             A = diagIlincJ;
            B = diagvi * conj(Y);

%             %% linear power term
%             Su = M;
%             Sw = 1j * M;
%
%             %% + power from linear current term
%             Su = Su + A + B;
%             Sw = Sw + 1j * (A - B);

            A = M + diagIlincJ;
            Su = A + B;
            Sw = 1j * (A - B);
        end

        function [Suu, Suw, Sww] = port_inj_power_hess_v(obj, x_, lam, v_, z_, diagvi, Y, M, diagIlincJ, dlamJ)
            % [Suu, Suw, Sww] = obj.port_inj_power_hess_v(x_, lam)
            % [Suu, Suw, Sww] = obj.port_inj_power_hess_v(x_, lam, sysx)
            % [Suu, Suw, Sww] = obj.port_inj_power_hess_v(x_, lam, sysx, idx)
            % [...] = obj.port_inj_power_hess_v(x_, lam, v_, z_, diagvi, Y, M, diagIlincJ, dlamJ)

            if nargin < 10
                sysx = v_;
                if nargin < 5
                    idx = []
                else
                    idx = z_;
                end
                [Y, L, M, i] = obj.get_params(idx, {'Y', 'L', 'M', 'i'});
                [v_, z_, vi_] = obj.x2vz(x_, sysx, idx);

                %% compute linear current injections
                if isempty(z_)
                    Ilin = Y*v_ + i;
                else
                    Ilin = Y*v_ + L*z_ + i;
                end

                n  = length(v_);    %% number of all port voltages
                ni = length(vi_);   %% number of selected port voltages
                diagvi = sparse(1:ni, 1:ni, vi_, ni, ni);
                if isempty(idx)     %% all ports
                    diagIlincJ = sparse(1:n, 1:n, conj(Ilin), n, n);
                    dlamJ      = sparse(1:n, 1:n, lam, n, n);
                else                %% selected ports
                    diagIlincJ = sparse(1:ni, idx, conj(Ilin), ni, n);
                    dlamJ      = sparse(1:ni, idx, lam, ni, n);
                end
            else
                n  = length(v_);    %% number of all port voltages
                ni = length(lam);
            end

            %% intermediate terms
            % D = dlamJ.';
            E = dlamJ.' * conj(Y);  %% D * conj(Y);
            % F = E + E.';
            % G = 1j * (E - E.');

            %% linear power term
            %% second derivatives all zero

            %% power from linear current term
            Suu = E + E.';          %% F
            Suw = 1j * (E.' - E);   %% G.'
            Sww = Suu;
        end

        function [Suzr, Suzi, Swzr, Swzi] = port_inj_power_hess_vz(obj, x_, lam, v_, z_, diagvi, L, dlamJ)
            % [Suzr, Suzi, Swzr, Swzi] = obj.port_inj_power_hess_vz(x_, lam)
            % [...] = obj.port_inj_power_hess_vz(x_, lam, sysx)
            % [...] = obj.port_inj_power_hess_vz(x_, lam, sysx, idx)
            % [...] = obj.port_inj_power_hess_vz(x_, lam, v_, z_, diagvi, L, dlamJ)

            if nargin < 8
                sysx = v_;
                if nargin < 5
                    idx = []
                else
                    idx = z_;
                end
                L = obj.get_params(idx, 'L');
                [v_, z_, vi_] = obj.x2vz(x_, sysx, idx);

                n  = length(v_);    %% number of all port voltages
                ni = length(vi_);   %% number of selected port voltages
                diagvi = sparse(1:ni, 1:ni, vi_, ni, ni);
                if isempty(idx)     %% all ports
                    dlamJ = sparse(1:n, 1:n, lam, n, n);
                else                %% selected ports
                    dlamJ = sparse(1:ni, idx, lam, ni, n);
                end
            else
                n  = length(v_);    %% number of all port voltages
                ni = length(lam);
            end

            %% intermediate terms
            D = dlamJ.';
            H = D * conj(L);

            %% power from linear current term
            Suzr = H;
            Suzi = -1j * H;
            Swzr = 1j * H;
            Swzi = H;
        end

        function [va, vm] = aux_data_va_vm(obj, ad)
            v_ = ad.vr + 1j * ad.vi;
            va = angle(v_);
            vm = abs(v_);
        end

        function [g, dg] = va_fcn(obj, xx, idx, lim)
            %% lim can be a vector value for equality constraint or
            %% upper bound on va, or a cell array with {vamin, vamax}
            %% for double bounds

            %% unpack data
            [vr, vi] = deal(xx{:});

            %% compute voltage angle mismatch
            if isempty(idx)
                va = angle(vr + 1j * vi);
            else
                va = angle(vr(idx) + 1j * vi(idx));
            end
            if iscell(lim)
                g = [ lim{1} - va;
                      va - lim{2}   ];
            else
                g = va - lim;
            end

            if nargout > 1
                %% compute partials of voltage angle w.r.t vr and vi
                nn = length(vr);
                if isempty(idx)
                    idx = 1:nn;
                end
                n = length(idx);
                vm2 = vr(idx).^2 + vi(idx).^2;
                dva_dvr = sparse(1:n, idx, -vi(idx) ./ vm2, n, nn);
                dva_dvi = sparse(1:n, idx,  vr(idx) ./ vm2, n, nn);
                if iscell(lim)
                    dg = [ -dva_dvr -dva_dvi;       %% va w.r.t vr, vi
                            dva_dvr  dva_dvi  ];    %% va w.r.t vr, vi
                else
                    dg = [dva_dvr dva_dvi];         %% va w.r.t vr, vi
                end
            end
        end

        function d2G = va_hess(obj, xx, lam, idx)
            %% unpack data
            [vr, vi] = deal(xx{:});
            nn = length(vr);

            %% evaluate Hessian of voltage angle function
            if isempty(idx)
                vvr = vr;
                vvi = vi;
                idx = 1:nn;
            else
                vvr = vr(idx);
                vvi = vi(idx);
            end
            vvr2 = vvr.^2;
            vvi2 = vvi.^2;
            vvm4 = (vvr2 + vvi2).^2;
            n = length(idx);
            if length(lam) == n     %% upper bound or equality
                lamvm4 = lam ./ vvm4;
            else                    %% doubly bounded (use lam_ub-lam_lb)
                lamvm4 = (lam(n+1:2*n) - lam(1:n)) ./ vvm4;
            end
            d2vref_rr = sparse(idx, idx, 2 * lamvm4 .*  vvr .* vvi,   nn, nn);
            d2vref_ri = sparse(idx, idx,     lamvm4 .* (vvi2 - vvr2), nn, nn);

            %% construct Hessian
            d2G = [ d2vref_rr  d2vref_ri;
                    d2vref_ri -d2vref_rr ];
        end

        function [g, dg] = vm2_fcn(obj, xx, idx, lim)
            %% lim can be a scalar value for equality constraint or
            %% upper bound on vm^2, or a cell array with {vm2min, vm2max}
            %% for double bounds

            %% unpack data
            [vr, vi] = deal(xx{:});

            %% compute voltage magnitude^2 mismatch
            if isempty(idx)
                vm2 = vr.^2 + vi.^2;
            else
                vm2 = vr(idx).^2 + vi(idx).^2;
            end
            if iscell(lim)
                g = [ lim{1} - vm2;
                      vm2 - lim{2}   ];
            else
                g = vm2 - lim;
            end

            if nargout > 1
                %% compute partials of voltage magnitude^2 w.r.t vr and vi
                nn = length(vr);
                if isempty(idx)
                    idx = 1:nn;
                end
                n = length(idx);
                dvm_dvr = sparse(1:n, idx, 2 * vr(idx), n, nn);
                dvm_dvi = sparse(1:n, idx, 2 * vi(idx), n, nn);
                if iscell(lim)
                    dg = [ -dvm_dvr -dvm_dvi;
                            dvm_dvr  dvm_dvi  ];    %% vm2 w.r.t vr, vi
                else
                    dg = [ dvm_dvr dvm_dvi ];       %% vm2 w.r.t vr, vi
                end
            end
        end

        function d2G = vm2_hess(obj, xx, lam, idx)
            %% unpack data
            [vr, vi] = deal(xx{:});
            nn = length(vr);

            %% evaluate Hessian of voltage magnitude^2 function
            if isempty(idx)
                idx = 1:nn;
            end
            n = length(idx);
            if length(lam) == n     %% upper bound or equality
                dlam = sparse(idx, idx, 2*lam, nn, nn);
            else                    %% doubly bounded (use lam_ub-lam_lb)
                dlam = sparse(idx, idx, 2*(lam(n+1:2*n) - lam(1:n)), nn, nn);
            end

            %% construct Hessian
            zz = sparse(nn, nn);
            d2G = [dlam zz; zz dlam];
        end
    end     %% methods
end         %% classdef


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MRiLab auto generated file: DO NOT EDIT!     %
% Generated by MRiLab "DoWriteXML2m" Generator %
% MRiLab Version 1.3                           %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [rfAmp,rfPhase,rfFreq,rfCoil,GzAmp,GyAmp,GxAmp,ADC,Ext,uts,ts,flags]=PSD_SPGR3DGM
global VCtl
global VVar
CV1=2e-3;
CV10=0;
CV11=0;
CV12=0;
CV13=0;
CV14=0;
CV2=3e-3;
CV3=abs(rem(VVar.TRCount,2)*2-1);
CV4=100e-3;
CV5=4000;
CV6=-4.0*42.576*7;
CV7=0;
CV8=0;
CV9=0;
rfAmpAll=[];
rfPhaseAll=[];
rfFreqAll=[];
rfCoilAll=[];
GzAmpAll=[];
GyAmpAll=[];
GxAmpAll=[];
ADCAll=[];
ExtAll=[];
rfTimeAll=[];
GzTimeAll=[];
GyTimeAll=[];
GxTimeAll=[];
ADCTimeAll=[];
ExtTimeAll=[];
SEtAll=[];
uts=[];
ts=[];
flags=[];
if VCtl.PlotSeq == 1
rfAmp=[];
rfPhase=[];
rfFreq=[];
rfCoil=[];
GzAmp=[];
GyAmp=[];
GxAmp=[];
ADC=[];
Ext=[];
Freq=1;
Notes='regular TR section';
AttributeOpt={'on','off'};
Switch=AttributeOpt{1};
TREnd=Inf;
TRStart=1;
tE=VCtl.TR;
tS=0;
if VVar.TRCount<TRStart | VVar.TRCount>TREnd | mod(VVar.TRCount-TRStart,Freq)~=0 | strcmp(Switch,'off')
% do nothing
else
ts = [ts tS tE];
end
ts = [0 max(ts)-min(ts)];
return;
end
%==============Pulses 1==============
rfAmp=[];
rfPhase=[];
rfFreq=[];
rfCoil=[];
GzAmp=[];
GyAmp=[];
GxAmp=[];
ADC=[];
Ext=[];
rfTime=[];
GzTime=[];
GyTime=[];
GxTime=[];
ADCTime=[];
ExtTime=[];
Freq=1;
Notes='regular TR section';
AttributeOpt={'on','off'};
Switch=AttributeOpt{1};
TREnd=Inf;
TRStart=1;
tE=VCtl.TR;
tS=0;
if isempty(tS) | isempty(tE) | (tS>=tE)
error('SE setting is incorrect for Pulses 1!');
end
if VVar.TRCount<TRStart | VVar.TRCount>TREnd | mod(VVar.TRCount-TRStart,Freq)~=0 | strcmp(Switch,'off')
% do nothing
else
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{1};
AttributeOpt={'Non','Hamming','Hanning'};
p.Apod=AttributeOpt{2};
p.CoilID=1;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=VCtl.FlipAng;
p.Notes='sinc rf pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.TBP=4;
p.dt=20e-6;
p.rfFreq=0;
p.rfPhase=0;
p.tEnd=CV4+0.6e-3;
p.tStart=CV4+0.1e-3;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp1,rfPhase1,rfFreq1,rfCoil1,rfTime1]=rfSinc(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil1(1)
rfAmp=[rfAmp rfAmp1];
rfPhase=[rfPhase rfPhase1];
rfFreq=[rfFreq rfFreq1];
rfCoil=[rfCoil rfCoil1];
rfTime=[rfTime rfTime1];
end
else
rfAmp=[rfAmp rfAmp1];
rfPhase=[rfPhase rfPhase1];
rfFreq=[rfFreq rfFreq1];
rfCoil=[rfCoil rfCoil1];
rfTime=[rfTime rfTime1];
end
end
p=[];
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{2};
AttributeOpt={'Non','Hamming','Hanning'};
p.Apod=AttributeOpt{2};
p.CoilID=1;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=0;
p.Notes='sinc rf pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.TBP=4;
p.dt=0.2e-3;
p.rfFreq=0;
p.rfPhase=0;
p.tEnd=VCtl.TR;
p.tStart=CV4+0.7e-3;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp2,rfPhase2,rfFreq2,rfCoil2,rfTime2]=rfSinc(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil2(1)
rfAmp=[rfAmp rfAmp2];
rfPhase=[rfPhase rfPhase2];
rfFreq=[rfFreq rfFreq2];
rfCoil=[rfCoil rfCoil2];
rfTime=[rfTime rfTime2];
end
else
rfAmp=[rfAmp rfAmp2];
rfPhase=[rfPhase rfPhase2];
rfFreq=[rfFreq rfFreq2];
rfCoil=[rfCoil rfCoil2];
rfTime=[rfTime rfTime2];
end
end
p=[];
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{2};
p.CoilID=1;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=CV5;
p.Notes='Gaussian rf pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.dt=100e-6;
p.rfFreq=CV6;
p.rfPhase=0;
p.tEnd=CV4;
p.tStart=0;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp3,rfPhase3,rfFreq3,rfCoil3,rfTime3]=rfGaussian(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil3(1)
rfAmp=[rfAmp rfAmp3];
rfPhase=[rfPhase rfPhase3];
rfFreq=[rfFreq rfFreq3];
rfCoil=[rfCoil rfCoil3];
rfTime=[rfTime rfTime3];
end
else
rfAmp=[rfAmp rfAmp3];
rfPhase=[rfPhase rfPhase3];
rfFreq=[rfFreq rfFreq3];
rfCoil=[rfCoil rfCoil3];
rfTime=[rfTime rfTime3];
end
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Gz1Sign=1;
p.Gz2Sign=0;
p.Notes='cartesian phase';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.t1End=CV4+CV2;
p.t1Start=CV4+CV1;
p.t2End=VCtl.TE+CV2;
p.t2Start=VCtl.TE+CV1;
p.tRamp=100e-6;
if strcmp(p.Switch,'on')
[GzAmp1,GzTime1]=GzCartesian(p);
GzAmp=[GzAmp GzAmp1];
GzTime=[GzTime GzTime1];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Gy1Sign=1;
p.Gy2Sign=0;
p.Notes='cartesian phase';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.t1End=CV4+CV2;
p.t1Start=CV4+CV1;
p.t2End=VCtl.TE+CV2;
p.t2Start=VCtl.TE+CV1;
p.tRamp=100e-6;
if strcmp(p.Switch,'on')
[GyAmp1,GyTime1]=GyCartesian(p);
GyAmp=[GyAmp GyAmp1];
GyTime=[GyTime GyTime1];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Gx1Sign=-1;
p.Gx2Sign=1;
p.Gx3Sign=0;
p.Notes='cartesian frequency';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.t1Start=CV4+CV1;
p.t2Middle=VCtl.TE;
p.t3Start=VCtl.TE+CV1;
p.tRamp=100e-6;
if strcmp(p.Switch,'on')
[GxAmp1,GxTime1]=GxCartesian(p);
GxAmp=[GxAmp GxAmp1];
GxTime=[GxTime GxTime1];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Notes='cartesian readout';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.tMiddle=VCtl.TE;
if strcmp(p.Switch,'on')
[ADC1,ADCTime1]=ADCCartesian(p);
ADC=[ADC ADC1];
ADCTime=[ADCTime ADCTime1];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Ext=5;
p.Notes='calculate remaining scan time';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.tStart=0;
if strcmp(p.Switch,'on')
[Ext1,ExtTime1]=ExtBit(p);
Ext=[Ext Ext1];
ExtTime=[ExtTime ExtTime1];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Ext=1;
p.Notes='reset K space location';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.tStart=CV4+0.6e-3;
if strcmp(p.Switch,'on')
[Ext2,ExtTime2]=ExtBit(p);
Ext=[Ext Ext2];
ExtTime=[ExtTime ExtTime2];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Ext=6;
p.Notes='dephase Mxy';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.tStart=VCtl.TR*(99/100);
if strcmp(p.Switch,'on')
[Ext3,ExtTime3]=ExtBit(p);
Ext=[Ext Ext3];
ExtTime=[ExtTime ExtTime3];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Ext=6;
p.Notes='dephase Mxy';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.tStart=CV4+0.05e-3;
if strcmp(p.Switch,'on')
[Ext4,ExtTime4]=ExtBit(p);
Ext=[Ext Ext4];
ExtTime=[ExtTime ExtTime4];
end
p=[];
%--------------------
SEt=[tS tE];
rfAmp(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];
rfPhase(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];
rfFreq(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];
rfCoil(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];
GzAmp(GzTime<0 | GzTime>SEt(2)-SEt(1)) = [];
GyAmp(GyTime<0 | GyTime>SEt(2)-SEt(1)) = [];
GxAmp(GxTime<0 | GxTime>SEt(2)-SEt(1)) = [];
ADC(ADCTime<0 | ADCTime>SEt(2)-SEt(1)) = [];
Ext(ExtTime<0 | ExtTime>SEt(2)-SEt(1)) = [];
rfTime(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];
GzTime(GzTime<0 | GzTime>SEt(2)-SEt(1)) = [];
GyTime(GyTime<0 | GyTime>SEt(2)-SEt(1)) = [];
GxTime(GxTime<0 | GxTime>SEt(2)-SEt(1)) = [];
ADCTime(ADCTime<0 | ADCTime>SEt(2)-SEt(1)) = [];
ExtTime(ExtTime<0 | ExtTime>SEt(2)-SEt(1)) = [];
rfAmp(abs(rfAmp)<eps) = 0;
rfTime = rfTime + SEt(1);
GzTime = GzTime + SEt(1);
GyTime = GyTime + SEt(1);
GxTime = GxTime + SEt(1);
ADCTime = ADCTime + SEt(1);
ExtTime = ExtTime + SEt(1);
rfAmpAll=[rfAmpAll rfAmp];
rfPhaseAll=[rfPhaseAll rfPhase];
rfFreqAll=[rfFreqAll rfFreq];
rfCoilAll=[rfCoilAll rfCoil];
GzAmpAll=[GzAmpAll GzAmp];
GyAmpAll=[GyAmpAll GyAmp];
GxAmpAll=[GxAmpAll GxAmp];
ADCAll=[ADCAll ADC];
ExtAll=[ExtAll Ext];
rfTimeAll=[rfTimeAll rfTime];
GzTimeAll=[GzTimeAll GzTime];
GyTimeAll=[GyTimeAll GyTime];
GxTimeAll=[GxTimeAll GxTime];
ADCTimeAll=[ADCTimeAll ADCTime];
ExtTimeAll=[ExtTimeAll ExtTime];
SEtAll=[SEtAll SEt];
end
%====================================
if isempty(rfTimeAll)
error('rf sequence line can not be empty! Master Tx coil element must be used.');
end
if isempty(GzTimeAll)
error('GzSS sequence line can not be empty!');
end
if isempty(GyTimeAll)
error('GyPE sequence line can not be empty!');
end
if isempty(GxTimeAll)
error('GxR sequence line can not be empty!');
end
if isempty(ADCTimeAll)
error('ADC sequence line can not be empty!');
end
if isempty(ExtTimeAll)
error('Ext sequence line can not be empty!');
end
SEflag=repmat([0 0 0 0 0 0]',[1 2]);
rfflag=repmat([1 0 0 0 0 0]',[1 max(size(rfTimeAll))]);
Gzflag=repmat([0 1 0 0 0 0]',[1 max(size(GzTimeAll))]);
Gyflag=repmat([0 0 1 0 0 0]',[1 max(size(GyTimeAll))]);
Gxflag=repmat([0 0 0 1 0 0]',[1 max(size(GxTimeAll))]);
ADCflag=repmat([0 0 0 0 1 0]',[1 max(size(ADCTimeAll))]);
Extflag=repmat([0 0 0 0 0 1]',[1 max(size(ExtTimeAll))]);
ts=[[min(SEtAll) max(SEtAll)] rfTimeAll GzTimeAll GyTimeAll GxTimeAll ADCTimeAll ExtTimeAll]-min(SEtAll);
flags=[SEflag rfflag Gzflag Gyflag Gxflag ADCflag Extflag];
[ts,ind]=sort(ts);
uts=unique(ts);
flags=flags(:,ind);
[rfTime,ind]=sort(rfTimeAll-min(SEtAll));
rfAmp=rfAmpAll(:,ind);
rfPhase=rfPhaseAll(:,ind);
rfFreq=rfFreqAll(:,ind);
rfCoil=rfCoilAll(:,ind);
[GzTime,ind]=sort(GzTimeAll-min(SEtAll));
GzAmp=GzAmpAll(:,ind);
[GyTime,ind]=sort(GyTimeAll-min(SEtAll));
GyAmp=GyAmpAll(:,ind);
[GxTime,ind]=sort(GxTimeAll-min(SEtAll));
GxAmp=GxAmpAll(:,ind);
[ADCTime,ind]=sort(ADCTimeAll-min(SEtAll));
ADC=ADCAll(:,ind);
[ExtTime,ind]=sort(ExtTimeAll-min(SEtAll));
Ext=ExtAll(:,ind);
rfAmp(1) = 0;
rfPhase(1) = 0;
rfFreq(1) = 0;
GzAmp(1) = 0;
GyAmp(1) = 0;
GxAmp(1) = 0;
ADC(1) = 0;
Ext(1) = 0;
rfAmp(end) = 0;
rfPhase(end) = 0;
rfFreq(end) = 0;
GzAmp(end) = 0;
GyAmp(end) = 0;
GxAmp(end) = 0;
ADC(end) = 0;
Ext(end) = 0;
end


classdef BackgroundSubtractorMOG < handle
    %BACKGROUNDSUBTRACTORMOG  Gaussian Mixture-based Background/Foreground Segmentation Algorithm
    %
    % The class implements the algorithm described in [KB2001].
    %
    % ## References
    % [KB2001]:
    % > Pakorn KaewTraKulPong and Richard Bowden. "An improved adaptive
    % > background mixture model for real-time tracking with shadow detection".
    % > In Video-Based Surveillance Systems, pages 135-144. Springer, 2002.
    % > [PDF](http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf)
    %
    % See also: cv.BackgroundSubtractorMOG.BackgroundSubtractorMOG,
    %  cv.BackgroundSubtractorMOG.apply,
    %  cv.BackgroundSubtractorMOG.getBackgroundImage
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    properties (Dependent)
        % The number of last frames that affect the background model.
        History
        % The number of gaussian components in the background model.
        % The model needs to be reinitalized to reserve memory.
        NMixtures
        % The "background ratio" parameter of the algorithm.
        % If a foreground pixel keeps semi-constant value for about
        % `BackgroundRatio * History` frames, it's considered background and
        % added to the model as a center of a new component. It corresponds to
        % `TB` parameter in the paper.
        BackgroundRatio
        % Sigma of noise
        NoiseSigma
    end

    %% BackgroundSubtractor
    methods
        function this = BackgroundSubtractorMOG(varargin)
            %BACKGROUNDSUBTRACTORMOG  Creates mixture-of-gaussian background subtractor
            %
            %     bs = cv.BackgroundSubtractorMOG()
            %     bs = cv.BackgroundSubtractorMOG('OptionName', optionValue, ...)
            %
            % ## Options
            % * __History__ Length of the history. default 200
            % * __NMixtures__ Number of Gaussian mixtures. default 5
            % * __BackgroundRatio__ Background ratio. default 0.7
            % * __NoiseSigma__ Noise strength (standard deviation of the
            %   brightness or each color channel). 0 means some automatic
            %   value. default 0
            %
            % Default constructor sets all parameters to default values.
            %
            % See also: cv.BackgroundSubtractorMOG
            %
            this.id = BackgroundSubtractorMOG_(0, 'new', varargin{:});
        end

        function delete(this)
            %DELETE  Destructor
            %
            %     bs.delete()
            %
            % See also: cv.BackgroundSubtractorMOG
            %
            if isempty(this.id), return; end
            BackgroundSubtractorMOG_(this.id, 'delete');
        end

        function fgmask = apply(this, im, varargin)
            %APPLY  Updates the background model and computes the foreground mask
            %
            %     fgmask = bs.apply(im)
            %     fgmask = bs.apply(im, 'OptionName', optionValue, ...)
            %
            % ## Input
            % * __im__ Next video frame.
            %
            % ## Output
            % * __fgmask__ The output foreground mask as an 8-bit binary image
            %   (0 for background, 255 for foregound).
            %
            % ## Options
            % * __LearningRate__ The value between 0 and 1 that indicates how
            %   fast the background model is learnt. Negative parameter value
            %   makes the algorithm to use some automatically chosen learning
            %   rate. 0 means that the background model is not updated at all,
            %   1 means that the background model is completely reinitialized
            %   from the last frame. default -1
            %
            % See also: cv.BackgroundSubtractorMOG.getBackgroundImage
            %
            fgmask = BackgroundSubtractorMOG_(this.id, 'apply', im, varargin{:});
        end

        function bgImg = getBackgroundImage(this)
            %GETBACKGROUNDIMAGE  Computes a background image
            %
            %     bgImg = bs.getBackgroundImage()
            %
            % ## Output
            % * __bgImg__ The output background image.
            %
            % ### Note
            % Method not implemented for this class, throws exception.
            %
            % See also: cv.BackgroundSubtractorMOG.apply
            %
            bgImg = BackgroundSubtractorMOG_(this.id, 'getBackgroundImage');
        end
    end

    %% Algorithm
    methods (Hidden)
        function clear(this)
            %CLEAR  Clears the algorithm state
            %
            %     obj.clear()
            %
            % See also: cv.BackgroundSubtractorMOG.empty
            %
            BackgroundSubtractorMOG_(this.id, 'clear');
        end

        function b = empty(this)
            %EMPTY  Returns true if the algorithm is empty
            %
            %     b = obj.empty()
            %
            % ## Output
            % * __b__ Returns true if the algorithm is empty (e.g. in the very
            %   beginning or after unsuccessful read).
            %
            % See also: cv.BackgroundSubtractorMOG.clear
            %
            b = BackgroundSubtractorMOG_(this.id, 'empty');
        end

        function name = getDefaultName(this)
            %GETDEFAULTNAME  Returns the algorithm string identifier
            %
            %     name = obj.getDefaultName()
            %
            % ## Output
            % * __name__ This string is used as top level XML/YML node tag
            %   when the object is saved to a file or string.
            %
            % See also: cv.BackgroundSubtractorMOG.save, cv.BackgroundSubtractorMOG.load
            %
            name = BackgroundSubtractorMOG_(this.id, 'getDefaultName');
        end

        function save(this, filename)
            %SAVE  Saves the algorithm to a file
            %
            %     obj.save(filename)
            %
            % ## Input
            % * __filename__ Name of the file to save to.
            %
            % This method stores the algorithm parameters in a file storage.
            %
            % See also: cv.BackgroundSubtractorMOG.load
            %
            BackgroundSubtractorMOG_(this.id, 'save', filename);
        end

        function load(this, fname_or_str, varargin)
            %LOAD  Loads algorithm from a file or a string
            %
            %     obj.load(fname)
            %     obj.load(str, 'FromString',true)
            %     obj.load(..., 'OptionName',optionValue, ...)
            %
            % ## Input
            % * __fname__ Name of the file to read.
            % * __str__ String containing the serialized model you want to
            %   load.
            %
            % ## Options
            % * __ObjName__ The optional name of the node to read (if empty,
            %   the first top-level node will be used). default empty
            % * __FromString__ Logical flag to indicate whether the input is a
            %   filename or a string containing the serialized model.
            %   default false
            %
            % This method reads algorithm parameters from a file storage.
            % The previous model state is discarded.
            %
            % See also: cv.BackgroundSubtractorMOG.save
            %
            BackgroundSubtractorMOG_(this.id, 'load', fname_or_str, varargin{:});
        end
    end

    %% Getters/Setters
    methods
        function value = get.History(this)
            value = BackgroundSubtractorMOG_(this.id, 'get', 'History');
        end
        function set.History(this, value)
            BackgroundSubtractorMOG_(this.id, 'set', 'History', value);
        end

        function value = get.NMixtures(this)
            value = BackgroundSubtractorMOG_(this.id, 'get', 'NMixtures');
        end
        function set.NMixtures(this, value)
            BackgroundSubtractorMOG_(this.id, 'set', 'NMixtures', value);
        end

        function value = get.BackgroundRatio(this)
            value = BackgroundSubtractorMOG_(this.id, 'get', 'BackgroundRatio');
        end
        function set.BackgroundRatio(this, value)
            BackgroundSubtractorMOG_(this.id, 'set', 'BackgroundRatio', value);
        end

        function value = get.NoiseSigma(this)
            value = BackgroundSubtractorMOG_(this.id, 'get', 'NoiseSigma');
        end
        function set.NoiseSigma(this, value)
            BackgroundSubtractorMOG_(this.id, 'set', 'NoiseSigma', value);
        end
    end

end