text:
function Xs = DVV_surrogate(X, Ns)
% Generates surrogate data for real and complex signals
%
% Surrogate data generation using iterated amplitude adjusted fourier
% transform (iAAFT) method for real-valued series, and complex iAAFT method
% for complex series.
%
%
% USAGE:    Xs = surrogate(X, Ns)
%
% INPUTS:
% X:        Input time series (can be real-valued or complex)
% Ns:       No. of surrogates to be generated
%
% OUTPUTS:
% Xs:   Generated surrogates
%
%
%   A Delay Vector Variance (DVV) toolbox for MATLAB
%   (c) Copyright Danilo P. Mandic 2008
%   http://www.commsp.ee.ic.ac.uk/~mandic/dvv.htm
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Default Parameters
if (nargin<1)
    error('Not enough Input arguments');
end
if (nargin<2)
    Ns = 25;
end

% Initial conditions and parameter initializations
iter = 0;
max_it = 1000;               % Maximum iterations
error_threshold = 1e-5;
MSE_start = 100;
MSE = 1000;

% Makes input vector X a column vector
if (size(X,2) > size(X,1))
    X = X';
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Implements univariate iAAFT algorithm for real-valued signals
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if (isreal(X))

    Xs = zeros(length(X),Ns);

    % Stores the Amplitude vector of the original time series
    X_amp = abs(fft(X));

    % Stores the sorted version(ascending) of the original time series
    X_sorted = sort(X);

    % Iteration process for multiple surrogate time series generation
    for a = 1:Ns

        % Random permutation of the original time series
        X_random = X(randperm(length(X)));

        % Initializations
        r_prev = X_random;
        MSE_prev = MSE_start;

        % Iterate untill convergence condition is met or max iterations are reached
        while (abs(MSE-MSE_prev) > error_threshold && iter < max_it)

            MSE_prev = MSE;

            % Amplitude spectrum matching
            ang_r_prev = angle(fft(r_prev));
            s = ifft(X_amp .* exp(ang_r_prev.*sqrt(-1)));

            % Rank ordering in order to scale to original signal distribution
            [s_sort, Ind] = sort(s);
            r(Ind,:) = X_sorted;

            % Convergence Metric calculation
            MSE = mean(abs(X_amp - abs(fft(r))));

            r_prev = r;
            iter = iter+1;
        end

        %         iter
        Xs(:,a) = r;
        iter = 0;
    end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Implements Complex iAAFT Algorithm for complex signals
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else

    % Initial conditions
    Xs = zeros(length(X),Ns);
    r_real = zeros(length(X),1);
    r_imag = zeros(length(X),1);
    r = zeros(length(X),1);
    r_prev = zeros(length(X),1);

    % Stores the Amplitude vector of the original time series
    X_amp = abs(fft(X));

    % Stores the sorted version(modulus, ascending), of the original time series
    C_sorted = sort(abs(X));

    % Sorted versions(real and imaginary), of original time series
    C_real_sorted = sort(real(X));
    C_imag_sorted = sort(imag(X));

    % Iteration process for multiple surrogate time series generation
    for a = 1:Ns

        % Random permutation of the original time series
        r_prev = X(randperm(length(X)));
        MSE_prev = MSE_start;

         % Iterate untill convergence condition is met or max iterations are reached
        while( abs(MSE-MSE_prev) > error_threshold && iter < max_it)

            MSE_prev = MSE;

            % Amplitude spectrum matching
            ang_r_prev = angle(fft(r_prev));
            s = ifft(X_amp .* exp(ang_r_prev.*sqrt(-1)));

            % Rank ordering real and imaginary parts of s to match that of original signal
            [temp , Ind_real] = sort(real(s));
            [temp , Ind_imag] = sort(imag(s));
            r_real(Ind_real) = C_real_sorted;
            r_imag(Ind_imag) = C_imag_sorted;

            r = complex(r_real, r_imag);

            % Rank ordering in order to scale to original signal distribution
            [temp, Ind_abs] = sort(abs(r));
            AUX1 = abs(temp);
            r(Ind_abs) = r(Ind_abs).*(abs(C_sorted)./(AUX1+(AUX1==0)));

            % Convergence Metric
            MSE = mean(abs(X_amp - abs(fft(r))));
            r_prev = r;
            iter = iter + 1;
        end

        %         iter
        Xs(:,a) = r;
        iter = 0;
    end

end


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%DENSE LUCAS KANADE PYRAMIDAL + ITERATIVE REFINMENT
%J.MARZAT - ENSEM / INRIA Rocquencourt (France) julien.marzat@gmail.com
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Data acquisition
im1=single((imread('yos_img_10.pgm')));
im2=single((imread('yos_img_11.pgm')));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%parameters : levels number, window size, iterations number, regularization
numLevels=3;
window=9;
iterations=1;
alpha = 0.001;

hw = floor(window/2);
t0=clock;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%pyramids creation
pyramid1 = im1;
pyramid2 = im2;
%init
for i=2:numLevels
    im1 = impyramid(im1, 'reduce');
    im2 = impyramid(im2, 'reduce');
    pyramid1(1:size(im1,1), 1:size(im1,2), i) = im1;
    pyramid2(1:size(im2,1), 1:size(im2,2), i) = im2;
end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Processing all levels
for p = 1:numLevels

    %current pyramid
    im1 = pyramid1(1:(size(pyramid1,1)/(2^(numLevels - p))), 1:(size(pyramid1,2)/(2^(numLevels - p))), (numLevels - p)+1);
    im2 = pyramid2(1:(size(pyramid2,1)/(2^(numLevels - p))), 1:(size(pyramid2,2)/(2^(numLevels - p))), (numLevels - p)+1);

    %init
    if p==1
    u=zeros(size(im1));
    v=zeros(size(im1));
    else
    %resizing
    u = 2 * imresize(u,size(u)*2,'bilinear');
    v = 2 * imresize(v,size(v)*2,'bilinear');
    end

    %refinment loop
    for r = 1:iterations

    u=round(u);
    v=round(v);

    %every pixel loop
        for i = 1+hw:size(im1,1)-hw
            for j = 1+hw:size(im2,2)-hw
            patch1 = im1(i-hw:i+hw, j-hw:j+hw);

            %moved patch
            lr = i-hw+v(i,j);
            hr = i+hw+v(i,j);
            lc = j-hw+u(i,j);
            hc = j+hw+u(i,j);

                  if (lr < 1)||(hr > size(im1,1))||(lc < 1)||(hc > size(im1,2))
                  %Regularized least square processing
                  else
                  patch2 = im2(lr:hr, lc:hc);

                  fx = conv2(patch1, 0.25* [-1 1; -1 1]) + conv2(patch2, 0.25*[-1 1; -1 1]);
                  fy = conv2(patch1, 0.25* [-1 -1; 1 1]) + conv2(patch2, 0.25*[-1 -1; 1 1]);
                  ft = conv2(patch1, 0.25*ones(2)) + conv2(patch2, -0.25*ones(2));

                  Fx = fx(2:window-1,2:window-1)';
                  Fy = fy(2:window-1,2:window-1)';
                  Ft = ft(2:window-1,2:window-1)';

                  A = [Fx(:) Fy(:)];
                  G=A'*A;

                  G(1,1)=G(1,1)+alpha; G(2,2)=G(2,2)+alpha;
                  U=1/(G(1,1)*G(2,2)-G(1,2)*G(2,1))*[G(2,2) -G(1,2);-G(2,1) G(1,1)]*A'*-Ft(:);
                  u(i,j)=u(i,j)+U(1); v(i,j)=v(i,j)+U(2);
                  end
            end
        end
    end
    etime(clock,t0)
end

%resizing
u=u(window:size(u,1)-window+1,window:size(u,2)-window+1);
v=v(window:size(v,1)-window+1,window:size(v,2)-window+1);

%colormap display
figure(1)
RGB1=showmap3(u,v,5);
imshow(RGB1);

author: Sable

repo: mcbench-benchmarks


text:
function distmap = test_depth_first_search(A,u)

distmap = -1*ones(size(A,1),1);

distmap = ipdouble(distmap);
distmap(u) = 0;

    function on_tree_edge(ei,u,v)
        distmap(v) = distmap(u)+1;
    end

depth_first_search(A,u,struct('tree_edge',@on_tree_edge));

distmap = double(distmap);
end

author: canlab

repo: CanlabCore

save_path: github-repos/MATLAB/canlab-CanlabCore


text:
function month_name = month_to_month_name_iranian ( m )

%*****************************************************************************80
%
%% MONTH_TO_MONTH_NAME_IRANIAN returns the name of an Iranian month.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    16 March 2013
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the month index.
%
%    Output, string MONTH_NAME, the month name.
%
  name = [ ...
    'Farvardin  ', 'Ordibehesht', 'Xordad     ', 'Tir        ', ...
    'Mordad     ', 'Shahrivar  ', 'Mehr       ', 'Aban       ', ...
    'Azar       ', 'Dey        ', 'Bahman     ', 'Esfand     ' ];

  if ( m < 1 || 12 < m )

    month_name = '??????????';

  else

    month_name = name(m,:);

  end

  return
end

author: johannesgerer

repo: jburkardt-m


text:
% pop_studydesign() - create a STUDY design structure.
%
% Usage:
%   >> [STUDY, ALLEEG] = pop_studydesign(STUDY, ALLEEG, key1, val1, ...);
%
% Inputs:
%   STUDY      - EEGLAB STUDY set
%   ALLEEG     - vector of the EEG datasets included in the STUDY structure
%
% Optional inputs:
%
% Authors: Arnaud Delorme, April 2010

% Copyright (C) Arnaud Delorme & Scott Makeig, SCCN/INC/UCSD, October 11, 2004, smakeig@ucsd.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function [STUDY allcom] = pop_studydesign(STUDY, ALLEEG, designind, varargin);

allcom = '';
if nargin < 2
    help pop_studydesign;
    return;
end;

if nargin < 3 && ~isstr(STUDY)

    %% create GUI
    [ usrdat.factors usrdat.factorvals usrdat.factsubj] = std_getindvar(STUDY, 'both', 1);

    usrdat.factors     = { 'None' usrdat.factors{:} };
    usrdat.factorvals  = { {}     usrdat.factorvals{:} };
    usrdat.factsubj    = { {}     usrdat.factsubj{:} };
    usrdat.subjects    = STUDY.subject;
    usrdat.datasetinfo = STUDY.datasetinfo;
    usrdat.design      = STUDY.design;
    usrdat.filepath    = STUDY.filepath;
    for ind = 1:length(usrdat.design)
        usrdat.design(ind).deletepreviousfiles = 0;
    end;

    % build menu
    popupselectsubj = { 'Select all subjects' };
    for ind1 = 1:length(usrdat.factors)
        if ~isempty(usrdat.factsubj{ind1})
            if any(cellfun(@length, usrdat.factsubj{ind1}) ~= length(usrdat.subjects))
                for ind2 = 1:length(usrdat.factorvals{ind1})
                    if ~iscell(usrdat.factorvals{ind1}{ind2}) % not a combined value
                        tmpval = encodevals(usrdat.factorvals{ind1}(ind2));
                        popupselectsubj{end+1} = [ num2str(usrdat.factors{ind1}) ' - ' tmpval{1} ];
                    end;
                end;
            end;
        end;
    end;

    cb_rename = 'pop_studydesign(''rename'', gcbf);';
    cb_add    = 'pop_studydesign(''add'', gcbf);';
    cb_del    = 'pop_studydesign(''del'', gcbf);';
    cb_listboxfact1 = 'pop_studydesign(''selectfact'', gcf, 0);';
    cb_listboxfact2 = 'pop_studydesign(''selectfact'', gcf, 1);';
    cb_selectsubj   = 'pop_studydesign(''selectsubj'', gcbf);';
    cb_combinevals1 = 'pop_studydesign(''combinevals'', gcbf, 0);';
    cb_combinevals2 = 'pop_studydesign(''combinevals'', gcbf, 1);';
    cb_lbval        = 'pop_studydesign(''updatedesign'', gcbf);';
    cb_selectdesign = 'pop_studydesign(''selectdesign'', gcbf);';
    cb_selectdata   = 'pop_studydesign(''selectdatatrials'', gcbf);';
    cb_selectfolder = 'pop_studydesign(''selectfolder'', gcbf);';
    cb_setfolder    = 'pop_studydesign(''updatedesign'', gcbf);';
    uilist = { { 'style' 'text'       'string' 'Select STUDY design' 'fontweight' 'bold' } ...
               { 'style' 'listbox'    'string' { usrdat.design.name } 'tag' 'listboxdesign' 'callback' cb_selectdesign 'value' STUDY.currentdesign } ...
               { 'style' 'pushbutton' 'string' 'Add design'    'callback' cb_add } ...
               { 'style' 'pushbutton' 'string' 'Rename design' 'callback' cb_rename } ...
               { 'style' 'pushbutton' 'string' 'Delete design' 'callback' cb_del } ...
               { 'style' 'text'       'string' 'Subjects' 'fontweight' 'bold' } ...
               { 'style' 'text'       'string' 'Independent variable 1   ' 'fontweight' 'bold' } ...
               { 'style' 'text'       'string' 'Independent variable 2   ' 'fontweight' 'bold' } ...
               { 'style' 'listbox'    'string' usrdat.subjects 'tag' 'lbsubj' 'min' 0 'max' 2 'value' 1 'callback' cb_lbval } ...
               { 'style' 'listbox'    'string' usrdat.factors  'tag' 'lbfact0' 'callback' cb_listboxfact1 'value' 2 } ...
               { 'style' 'listbox'    'string' usrdat.factors  'tag' 'lbfact1' 'callback' cb_listboxfact2 'value' 1 } ...
               { 'style' 'text'       'string' 'Ind. var. 1 values ' } ...
               { 'style' 'text'       'string' 'Ind. var. 2 values' } ...
               { 'style' 'listbox'    'string' '' 'tag' 'lbval0' 'min' 0 'max' 2 'callback' cb_lbval } ...
               { 'style' 'listbox'    'string' '' 'tag' 'lbval1' 'min' 0 'max' 2 'callback' cb_lbval } ...
               { 'style' 'popupmenu'  'string' popupselectsubj 'tag' 'popupselect' 'callback' cb_selectsubj } ...
               { 'style' 'pushbutton' 'string' 'Combine selected values' 'tag' 'combine1' 'callback' cb_combinevals1 } ...
               { 'style' 'pushbutton' 'string' 'Combine selected values' 'tag' 'combine2' 'callback' cb_combinevals2 } ...
               { 'style' 'popupmenu'  'string' 'Paired statistics|Unpaired statistics' 'tag' 'lbpair0' 'callback' cb_lbval } ...
               { 'style' 'popupmenu'  'string' 'Paired statistics|Unpaired statistics' 'tag' 'lbpair1' 'callback' cb_lbval } ...
               { 'style' 'pushbutton' 'string' 'Use only specific datasets/trials' 'callback' cb_selectdata } ...
               { 'style' 'edit'       'string' '' 'tag' 'edit_selectdattrials' 'callback' cb_lbval } ...
               { 'style' 'text'       'string' 'Store pre-computed files in folder' } ...
               { 'style' 'edit'       'string' '' 'tag' 'edit_storedir' 'callback' cb_setfolder } ...
               { 'style' 'pushbutton' 'string' '...' 'callback' cb_selectfolder } ...
               { 'style' 'checkbox'   'string' 'Delete all pre-computed datafiles associated with this specific STUDY design' 'tag' 'chk_del' 'callback' cb_lbval } ...
               { 'style' 'checkbox'   'string' 'Save the STUDY' 'tag' 'chk_save' 'value' 1 } };
%               { 'style' 'checkbox'  'string' 'Paired statistics' 'tag' 'lbpair0' 'callback' cb_lbval } ...
%               { 'style' 'checkbox'  'string' 'Paired statistics' 'tag' 'lbpair1' 'callback' cb_lbval } ...

    geometry = { {3 18 [1 1] [2 1] } ...
                 {3 18 [1 2] [2 3] } ...
                 {3 18 [3 2] [1 1] } ...
                 {3 18 [3 3] [1 1] } ...
                 {3 18 [3 4] [1 1] } ...
                 {3 18 [1 5] [1 1] } ...
                 {3 18 [2 5] [1 1] } ...
                 {3 18 [3 5] [1 1] } ...
                 {3 18 [1 6] [1 8] } ...
                 {3 18 [2 6] [0.98 3] } ...
                 {3 18 [3 6] [0.98 3] } ...
                 {3 18 [2 9] [1 1] } ...
                 {3 18 [3 9] [1 1] } ...
                 {3 18 [2 10] [0.98 3] } ...
                 {3 18 [3 10] [0.98 3] } ...
                 {3 18 [1 14] [1 1] } ...
                 {3 18 [2 13] [1 1] } ...
                 {3 18 [3 13] [1 1] } ...
                 {3 18 [2 14] [1 1] } ...
                 {3 18 [3 14] [1 1] } ...
                 {3 18 [1    15.5] [1.3 1] } ...
                 {3 18 [2.25 15.5] [1.7 1] } ...
                 {3 18 [1    16.5] [1.3 1] } ...
                 {3 18 [2.25 16.5] [1.2 1] } ...
                 {3 18 [3.45 16.5] [0.55 1] } ...
                 {3 18 [1 17.5] [3 1] } ...
                 {3 18 [1 19] [3 1] } ...
                 };

    for i = 1:length(geometry), geometry{i}{3} = geometry{i}{3}-1; end;
    streval = [ 'pop_studydesign(''selectdesign'', gcf);' ];
    [tmp usrdat tmp2 result] = inputgui('uilist', uilist, 'title', 'Edit STUDY design -- pop_studydesign()', 'helpbut', 'Web help', 'helpcom',  'web(''http://sccn.ucsd.edu/wiki/Chapter_03:_Working_with_STUDY_designs'', ''-browser'')', 'geom', geometry, 'userdata', usrdat, 'eval', streval);
    if isempty(tmp), return; end;

    % call std_makedesign
    % -------------------
    des    = usrdat.design;
    allcom = '';
    if length(des) < length(STUDY.design)
        for index = length(des)+1:length(STUDY.design)
            fprintf('Deleting STUDY design %d\n', index);
            com    = 'STUDY.design(index).name = '';'; eval(com);
            allcom = [ allcom 10 com ];
        end;
    end;
    for index = 1:length(des)
        tmpdes  = rmfield(des(index), 'deletepreviousfiles');
        rmfiles = fastif(des(index).deletepreviousfiles, 'limited', 'off');
        if index > length(STUDY.design) || ~isequal(STUDY.design(index), tmpdes) || strcmpi(rmfiles, 'on')
            fprintf('Updating/creating STUDY design %d\n', index);

            % test if file exist and issue warning
            if length(STUDY.design) >= index && isfield('cell', STUDY.design) && ~isempty(STUDY.design(index).cell) && ...
                ~isempty(dir([ STUDY.design(index).cell(1).filebase '.*' ])) &&  strcmpi(rmfiles, 'off')
                if ~isequal(tmpdes.variable(1).label, STUDY.design(index).variable(1).label) || ...
                     ~isequal(tmpdes.variable(2).label, STUDY.design(index).variable(2).label) || ...
                      ~isequal(tmpdes.include, STUDY.design(index).include) || ...
                       ~isequal(tmpdes.variable(1).value, STUDY.design(index).variable(1).value) || ...
                        ~isequal(tmpdes.cases.value, STUDY.design(index).cases.value) || ...
                         ~isequal(tmpdes.variable(2).value, STUDY.design(index).variable(2).value)
                    res = questdlg2(strvcat([ 'Precomputed data files exist for design ' int2str(index) '.' ], ' ', ...
                                       'Modifying this design without deleting the associated files', ...
                                       'might mean that they will stay on disk and will be unusable'), ...
                                       'STUDY design warning', 'Abort', 'Continue', 'Continue');
                    if strcmpi(res, 'Abort'), return; end;
                end;
            end;
            [STUDY com] = std_makedesign(STUDY, ALLEEG, index, tmpdes, 'delfiles', rmfiles);
            allcom = [ allcom 10 com ];
        else
            fprintf('STUDY design %d not modified\n', index);
        end;
    end;
    if result.listboxdesign ~= STUDY.currentdesign
        fprintf('Selecting STUDY design %d\n', result.listboxdesign);
        com = sprintf('STUDY = std_selectdesign(STUDY, ALLEEG, %d);', result.listboxdesign); eval(com);
        allcom = [ allcom 10 com ];
    end;
    if result.chk_save == 1
        fprintf('Resaving STUDY\n');
        [STUDY ALLEEG com] = pop_savestudy(STUDY, ALLEEG, 'savemode', 'resave');
        allcom = [ allcom 10 com ];
    end;
    if ~isempty(allcom), allcom(1) = []; end;

elseif isstr(STUDY)
    com = STUDY;
    fig = ALLEEG;
    usrdat = get(fig, 'userdata');
    datinfo  = usrdat.datasetinfo;
    des      = usrdat.design;
    filepath = usrdat.filepath;

    switch com
        % summary of callbacks
        % case 'add', Add new study design
        % case 'del', Delete study design
        % case 'rename', Rename study design
        %
        % case 'selectdesign', select a specific design
        % case 'updatedesign', update the study information (whenever the
        %                      user click on a button
        %
        % case 'selectfact', select a specific ind. var. (update value listboxes)
        % case 'combinevals', combine values in value listboxes
        % case 'selectsubj', select specific subjects
        %
        % case 'selectdatatrials', new GUI to select specific dataset and trials
        % case 'selectdatatrialssel', % select in the GUI above
        % case 'selectdatatrialsadd', % add new selection in the GUI above

        case 'add', % Add new study design
            inde  = find( cellfun(@isempty,{ des.name }));
            if isempty(inde), inde = length(des)+1; end;
            des(inde(1)) = des(1);
            des(inde(1)).name = sprintf('Design %d', inde(1));
            set(findobj(fig, 'tag', 'listboxdesign'), 'string', { des.name }, 'value', inde(1));
            usrdat.design = des;
        	set(fig, 'userdata', usrdat);
            pop_studydesign( 'selectstudy', fig);
            return;

        case 'del', % Delete study design
            val = get(findobj(fig, 'tag', 'listboxdesign'), 'value');
            if val == 1
                warndlg2('The first STUDY design cannot be removed, only modified');
                return;
            end;
            des(val).name = '';
            set(findobj(fig, 'tag', 'listboxdesign'), 'value', 1, 'string', { des.name } );
            usrdat.design = des;
        	set(fig, 'userdata', usrdat);
            pop_studydesign( 'selectstudy', fig);
            return;

        case 'rename', % Rename study design
            val        = get(findobj(fig, 'tag', 'listboxdesign'), 'value');
            strs       = get(findobj(fig, 'tag', 'listboxdesign'), 'string');
            result     = inputdlg2( { 'Study design name:                                                                    ' }, ...
                                      'Rename Study Design', 1,  { strs{val} }, 'pop_studydesign');
            if isempty(result), return; end;
            des(val).name  = result{1};
            set(findobj(fig, 'tag', 'listboxdesign'), 'string', { des.name } );

        case 'selectdesign', % select a specific design
            val  = get(findobj(fig, 'tag', 'listboxdesign'), 'value');
            if isempty(des(val).name)
                set(findobj(fig, 'tag', 'lbfact0'), 'string', '', 'value', 1);
                set(findobj(fig, 'tag', 'lbfact1'), 'string', '', 'value', 1);
                set(findobj(fig, 'tag', 'lbval0') , 'string', '', 'value', 1);
                set(findobj(fig, 'tag', 'lbval1') , 'string', '', 'value', 1);
                set(findobj(fig, 'tag', 'lbpair0'), 'value', 1);
                set(findobj(fig, 'tag', 'lbpair1'), 'value', 1);
                set(findobj(fig, 'tag', 'lbsubj') , 'value' , 1, 'string', '');
                set(findobj(fig, 'tag', 'chk_del'), 'value', des(val).deletepreviousfiles );
                set(findobj(fig, 'tag', 'edit_selectdattrials'), 'string', '' );
                % do not change file path
                return;
            end;
            val1 = strmatch(des(val).variable(1).label, usrdat.factors, 'exact'); if isempty(val1), val1 = 1; end;
            val2 = strmatch(des(val).variable(2).label, usrdat.factors, 'exact'); if isempty(val2), val2 = 1; end;
            set(findobj(fig, 'tag', 'lbfact0'), 'string', usrdat.factors, 'value', val1);
            set(findobj(fig, 'tag', 'lbfact1'), 'string', usrdat.factors, 'value', val2);
            valfact1 = strmatchmult(des(val).variable(1).value, usrdat.factorvals{val1});
            valfact2 = strmatchmult(des(val).variable(2).value, usrdat.factorvals{val2});
            if isempty(valfact1), listboxtop1 = 1; else listboxtop1 = valfact1(1); end;
            if isempty(valfact2), listboxtop2 = 1; else listboxtop2 = valfact2(1); end;
            set(findobj(fig, 'tag', 'lbval0'), 'string', encodevals(usrdat.factorvals{val1}), 'value', valfact1, 'listboxtop', listboxtop1);
            set(findobj(fig, 'tag', 'lbval1'), 'string', encodevals(usrdat.factorvals{val2}), 'value', valfact2, 'listboxtop', listboxtop2);
            valsubj = strmatchmult(des(val).cases.value, usrdat.subjects);
            set(findobj(fig, 'tag', 'lbsubj'), 'string', usrdat.subjects, 'value', valsubj);
            if isempty(des(val).include), str = ''; else str = vararg2str(des(val).include); end;
            set(findobj(fig, 'tag', 'chk_del'), 'value', des(val).deletepreviousfiles );
            set(findobj(fig, 'tag', 'edit_selectdattrials'), 'string', str );
            set(findobj(fig, 'tag', 'popupselect'), 'value', 1 );
            set(findobj(fig, 'tag', 'lbpair0'), 'value', fastif(isequal(des(val).variable(1).pairing,'on'),1,2));
            set(findobj(fig, 'tag', 'lbpair1'), 'value', fastif(isequal(des(val).variable(2).pairing,'on'),1,2));
            if ~isfield(des, 'filepath') || isempty(des(val).filepath), des(val).filepath = ''; end;
            set(findobj(fig, 'tag', 'edit_storedir'), 'string', des(val).filepath);

        case 'updatedesign', % update the study information (whenever the user click on a button)
            val    = get(findobj(fig, 'tag', 'listboxdesign'), 'value');
            val1   = get(findobj(fig, 'tag', 'lbfact0'), 'value');
            val2   = get(findobj(fig, 'tag', 'lbfact1'), 'value');
            valf1  = get(findobj(fig, 'tag', 'lbval0'),  'value');
            valf2  = get(findobj(fig, 'tag', 'lbval1'),  'value');
            valp1  = get(findobj(fig, 'tag', 'lbpair0'), 'value');
            valp2  = get(findobj(fig, 'tag', 'lbpair1'), 'value');
            vals   = get(findobj(fig, 'tag', 'lbsubj'),  'value');
            valchk = get(findobj(fig, 'tag', 'chk_del'), 'value');
            filep  = get(findobj(fig, 'tag', 'edit_storedir'), 'string');
            strs   = get(findobj(fig, 'tag', 'edit_selectdattrials'),  'string');
            valpaired = { 'on' 'off' };

            if ~strcmpi(des(val).variable(1).label, usrdat.factors{val1})
                des(val).variable(1).label = usrdat.factors{val1};
                des(val).variable(1).value = usrdat.factorvals{val1}(valf1);
            end;
            if ~strcmpi(des(val).variable(2).label, usrdat.factors{val2})
                des(val).variable(2).label = usrdat.factors{val2};
                des(val).variable(2).value = usrdat.factorvals{val2}(valf2);
            end;
            if ~isequal(mysort(des(val).variable(1).value), mysort(usrdat.factorvals{val1}(valf1)))
                des(val).variable(1).value = usrdat.factorvals{val1}(valf1);
            end;
            if ~isequal(mysort(des(val).variable(2).value), mysort(usrdat.factorvals{val2}(valf2)))
                des(val).variable(2).value = usrdat.factorvals{val2}(valf2);
            end;
            if ~isequal(mysort(des(val).cases.value), mysort(usrdat.subjects(vals)))
                des(val).cases.value = usrdat.subjects(vals);
            end;
            if ~isequal(des(val).variable(1).pairing, valpaired{valp1})
                des(val).variable(1).pairing = valpaired{valp1};
            end;
            if ~isequal(des(val).variable(2).pairing, valpaired{valp2})
                des(val).variable(2).pairing = valpaired{valp2};
            end;
            if ~isequal(des(val).deletepreviousfiles, valchk)
                des(val).deletepreviousfiles = 1;
            end;
            if ~isfield(des, 'filepath') || ~isequal(des(val).filepath, filep)
                des(val).filepath = filep;
            end;
            if ~isequal(des(val).include, strs)
                try,
                    des(val).include = eval( [ '{' strs '}' ]);
                catch,
                    disp('Error while decoding list of parameters');
                    des(val).include = {};
                    set(findobj(fig, 'tag', 'edit_selectdattrials'),  'string', '');
                end;
            end;

        case 'selectfact', % select a specific ind. var. (update value listboxes)
            factval = designind;
            val   = get(findobj(fig, 'tag', 'listboxdesign'), 'value');
            val1  = get(findobj(fig, 'tag', [ 'lbfact' num2str(factval) ]), 'value');
            val2  = get(findobj(fig, 'tag', [ 'lbfact' num2str(~factval) ]), 'value');
%             if val1 == val2 && val1 ~= 1
%                 warndlg2('Cannot select twice the same independent variable');
%                 val1 = 1;
%                 set(findobj(fig, 'tag', [ 'lbfact' num2str(factval) ]), 'value', val1);
%             end;
            valfact = [1:length(usrdat.factorvals{val1})];
            set(findobj(fig, 'tag', ['lbval' num2str(factval) ]), 'string', encodevals(usrdat.factorvals{val1}), 'value', valfact, 'listboxtop', 1);
            pop_studydesign('updatedesign', fig);
            return;

        case 'combinevals', %  combine values in value listboxes
            factval = designind;
            val1    = get(findobj(fig, 'tag', [ 'lbfact' num2str(factval) ]), 'value');
            vals    = get(findobj(fig, 'tag', [ 'lbval'  num2str(factval) ]), 'value');
            strs    = get(findobj(fig, 'tag', [ 'lbval'  num2str(factval) ]), 'string');
            if length(vals) == 1
                warndlg2('You need to select several values to combine them');
                return;
            end;
            if ~iscell(usrdat.factorvals{val1})
                warndlg2('Cannot combine values from numerical variables');
                return;
            end;
            % combine values for string and integers
            if isstr(usrdat.factorvals{val1}{1}) || iscell(usrdat.factorvals{val1}{1})
                tmpcell = {};
                for indCell = vals(:)'
                    if iscell(usrdat.factorvals{val1}{indCell})
                        tmpcell = { tmpcell{:} usrdat.factorvals{val1}{indCell}{:} };
                    else
                        tmpcell = { tmpcell{:} usrdat.factorvals{val1}{indCell} };
                    end;
                end;
                usrdat.factorvals{val1}{end+1} = unique_bc(tmpcell);
            else
                usrdat.factorvals{val1}{end+1} = unique_bc([ usrdat.factorvals{val1}{vals} ]);
            end;
            set(findobj(fig, 'tag', ['lbval' num2str(factval) ]), 'string', encodevals(usrdat.factorvals{val1}));

        case 'selectsubj', % select specific subjects
            val = get(findobj(fig, 'tag', 'popupselect'), 'value');
            str = get(findobj(fig, 'tag', 'popupselect'), 'string');
            str = str{val};
            if val == 1,
                subjbox = get(findobj(fig, 'tag', 'lbsubj'), 'string');
                set(findobj(fig, 'tag', 'lbsubj'), 'value', [1:length(subjbox)]);
                return;
            end;
            indunders = findstr( ' - ', str);
            factor    = str(1:indunders-1);
            factorval = str(indunders+3:end);

            % select subjects
            eval( [ 'allsetvals = { datinfo.' factor '};' ]);
            indset = strmatch(factorval, allsetvals, 'exact');
            subjects = unique_bc( { datinfo(indset).subject } );

            % change the subject listbox
            val     = get(findobj(fig, 'tag', 'popupselect'), 'value');
            subjbox = get(findobj(fig, 'tag', 'lbsubj'), 'string');
            indsubj = [];
            for ind = 1:length(subjects);
                indsubj(ind) = strmatch(subjects{ind}, subjbox, 'exact');
            end;
            set(findobj(fig, 'tag', 'lbsubj'), 'value', indsubj);
            set(findobj(fig, 'tag', 'popupselect'), 'value', 1);
            pop_studydesign('updatedesign', fig);
            return;
            %set(findobj(get(gcbf, ''userdata''), ''tag'', ''edit_selectdattrials''

        case 'selectdatatrials', % select specific dataset and trials
            cb_sel = 'pop_studydesign(''selectdatatrialssel'',gcbf);';
            cb_add = 'pop_studydesign(''selectdatatrialsadd'',gcbf);';
            uilist = { { 'style' 'text'    'string' strvcat('Press ''Add'' to add data', 'selection. Multiple variables', 'are combined using AND.') } ...
                       { 'style' 'text'    'string' 'Select data based on variable', 'fontweight' 'bold' } ...
                       { 'style' 'listbox' 'string' usrdat.factors  'tag' 'lbfact2' 'callback' cb_sel 'value' 1 } ...
                       { 'style' 'text'    'string' 'Select data based on value(s)' 'fontweight' 'bold' } ...
                       { 'style' 'listbox' 'string' encodevals(usrdat.factorvals{1}) 'tag' 'lbval2' 'min' 0 'max' 2} };
            cb_renamehelp = [ 'set(findobj(gcf, ''tag'', ''help''), ''string'', ''Add'');' ...
                              'set(findobj(gcf, ''tag'', ''cancel''), ''string'', ''Erase'', ''callback'', ''set(findobj(''''tag'''', ''''edit_selectdattrials''''), ''''string'''', '''''''');'');' ...
                              'set(findobj(gcf, ''tag'', ''ok''), ''string'', ''Close'');' ];
            usrdat.fig = fig;
            inputgui('uilist', uilist, 'geometry', { [1] [1] [1] [1] [1] }, 'geomvert', [2 1 2.5 1 2.5], ...
                'helpcom', cb_add, 'userdata', usrdat, 'eval', cb_renamehelp);
            pop_studydesign('updatedesign', fig);
            return;

        case 'selectdatatrialssel', % select in the GUI above
            val1  = get(findobj(fig, 'tag', 'lbfact2'), 'value');
            valfact = [1:length(usrdat.factorvals{val1})];
            tmpval = get(findobj(fig, 'tag', 'lbval2'), 'value');
            if max(tmpval) > max(valfact)
                set(findobj(fig, 'tag', 'lbval2'), 'value', valfact, 'string', encodevals(usrdat.factorvals{val1}));
            else
                set(findobj(fig, 'tag', 'lbval2'), 'string', encodevals(usrdat.factorvals{val1}), 'value', valfact);
            end;
            return;

        case 'selectfolder',
            res = uigetdir;
            if ~isempty(findstr(filepath, res)) && findstr(filepath, res) == 1 && ~isequal(filepath, res)
                res = res(length(filepath)+2:end);
            end;
            if res(1) == 0, return; end;
            set(findobj(fig, 'tag', 'edit_storedir'), 'string', res);
            pop_studydesign('updatedesign', fig);
            return;

        case 'selectdatatrialsadd', % Add button in the GUI above
            val1    = get(findobj(fig, 'tag', 'lbfact2'), 'value');
            val2    = get(findobj(fig, 'tag', 'lbval2') , 'value');
            objedit = findobj(usrdat.fig, 'tag', 'edit_selectdattrials');
            str     = get(objedit, 'string');
            if ~isempty(str), str = [ str ',' ]; end;
            set(objedit, 'string', [ str vararg2str( { usrdat.factors{val1} usrdat.factorvals{val1}(val2) }) ]);
            return;

    end;
    usrdat.design = des;
	set(fig, 'userdata', usrdat);
end;

function res = strmatchmult(a, b);
    if isempty(b), res = []; return; end;
    res = zeros(1,length(a));
    for index = 1:length(a)
        tmpi = std_indvarmatch(a{index}, b);
        res(index) = tmpi(1); % in case there is a duplicate
    end;
    %[tmp ind] = mysetdiff(b, a);
    %res = setdiff_bc([1:length(b)], ind);

function cellarray = mysort(cellarray)
    return; % was crashing for combinations of selection
            % also there is no reason the order should be different
    if ~isempty(cellarray) && isstr(cellarray{1})
        cellarray = sort(cellarray);
    end;

function [cellout inds ] = mysetdiff(cell1, cell2);
    if (~isempty(cell1) && isstr(cell1{1})) || (~isempty(cell2) && isstr(cell2{1}))
         [ cellout inds ] = setdiff_bc(cell1, cell2);
    else [ cellout inds ] = setdiff_bc([ cell1{:} ], [ cell2{:} ]);
         cellout = mattocell(cellout);
    end;

% encode string an numerical values for list boxes
function cellout = encodevals(cellin)
    if isempty(cellin)
        cellout = {};
    elseif ~iscell(cellin)
        cellout = { num2str(cellin) };
    elseif ischar(cellin{1}) || iscell(cellin{1})
        for index = 1:length(cellin)
            if isstr(cellin{index})
                cellout{index} = cellin{index};
            else
                cellout{index} =  cellin{index}{1};
                for indcell = 2:length(cellin{index})
                    cellout{index} = [ cellout{index} ' & ' cellin{index}{indcell} ];
                end;
            end;
        end;
    else
        for index = 1:length(cellin)
            if length(cellin{index}) == 1
                cellout{index} = num2str(cellin{index});
            else
                cellout{index} =  num2str(cellin{index}(1));
                for indcell = 2:length(cellin{index})
                    cellout{index} = [ cellout{index} ' & ' num2str(cellin{index}(indcell)) ];
                end;
            end;
        end;
    end;

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
function print2eps(name, fig, bb_padding, varargin)
%PRINT2EPS  Prints figures to eps with improved line styles
%
% Examples:
%   print2eps filename
%   print2eps(filename, fig_handle)
%   print2eps(filename, fig_handle, bb_padding)
%   print2eps(filename, fig_handle, bb_padding, options)
%
% This function saves a figure as an eps file, with two improvements over
% MATLAB's print command. First, it improves the line style, making dashed
% lines more like those on screen and giving grid lines their own dotted
% style. Secondly, it substitutes original font names back into the eps
% file, where these have been changed by MATLAB, for up to 11 different
% fonts.
%
%IN:
%   filename - string containing the name (optionally including full or
%              relative path) of the file the figure is to be saved as. A
%              ".eps" extension is added if not there already. If a path is
%              not specified, the figure is saved in the current directory.
%   fig_handle - The handle of the figure to be saved. Default: gcf().
%   bb_padding - Scalar value of amount of padding to add to border around
%                the cropped image, in points (if >1) or percent (if <1).
%                Can be negative as well as positive; Default: 0.
%                May be a 2-element vector of padding and crop amount.
%   options - Additional parameter strings to be passed to print.

%{
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-

% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928)
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
%}
%{
% 14/11/11: Fix a MATLAB bug rendering black or white text incorrectly.
%           Thanks to Mathieu Morlighem for reporting the issue and
%           obtaining a fix from TMW.
% 08/12/11: Added ability to correct fonts. Several people have requested
%           this at one time or another, and also pointed me to printeps
%           (fex id: 7501), so thank you to them. My implementation (which
%           was not inspired by printeps - I'd already had the idea for my
%           approach) goes slightly further in that it allows multiple
%           fonts to be swapped.
% 14/12/11: Fix bug affecting font names containing spaces. Thanks to David
%           Szwer for reporting the issue.
% 25/01/12: Add a font not to be swapped. Thanks to Anna Rafferty and Adam
%           Jackson for reporting the issue. Also fix a bug whereby using a
%           font alias can lead to another font being swapped in.
% 10/04/12: Make the font swapping case insensitive.
% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
%           reporting the issue.
% 26/10/12: Fix issue to do with swapping fonts changing other fonts and
%           sizes we don't want, due to listeners. Thanks to Malcolm Hudson
%           for reporting the issue.
% 22/03/13: Extend font swapping to axes labels. Thanks to Rasmus Ischebeck
%           for reporting the issue.
% 23/07/13: Bug fix to font swapping. Thanks to George for reporting the
%           issue.
% 13/08/13: Fix MATLAB feature of not exporting white lines correctly.
%           Thanks to Sebastian Heßlinger for reporting it.
% 24/02/15: Fix for Matlab R2014b bug (issue #31): LineWidths<0.75 are not
%           set in the EPS (default line width is used)
% 25/02/15: Fixed issue #32: BoundingBox problem caused uncropped EPS/PDF files
% 05/03/15: Fixed issue #43: Inability to perform EPS file post-processing
% 06/03/15: Improved image padding & cropping thanks to Oscar Hartogensis
% 21/03/15: Fixed edge-case of missing handles having a 'FontName' property
% 26/03/15: Attempt to fix issue #45: white lines in subplots do not print correctly
% 27/03/15: Attempt to fix issue #44: white artifact lines appearing in patch exports
% 30/03/15: Fixed issue #52: improved performance on HG2 (R2014b+)
% 09/04/15: Comment blocks consolidation and minor code cleanup (no real code change)
% 12/04/15: Fixed issue #56: bad cropping
% 14/04/15: Workaround for issue #45: lines in image subplots are exported in invalid color
%}

    options = {'-loose'};
    if nargin > 3
        options = [options varargin];
    elseif nargin < 3
        bb_padding = 0;
        if nargin < 2
            fig = gcf();
        end
    end

    % Retrieve crop value (2nd element of bb_padding vector, or default=0)
    try
        bb_crop = bb_padding(2);
        bb_padding = bb_padding(1);  % reached this point, so it's a vector
    catch
        bb_crop = 0;  % scalar value, so use default bb_crop value of 0
    end

    % Construct the filename
    if numel(name) < 5 || ~strcmpi(name(end-3:end), '.eps')
        name = [name '.eps']; % Add the missing extension
    end

    % Set paper size
    old_pos_mode = get(fig, 'PaperPositionMode');
    old_orientation = get(fig, 'PaperOrientation');
    set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');

    % Find all the used fonts in the figure
    font_handles = findall(fig, '-property', 'FontName');
    fonts = get(font_handles, 'FontName');
    if isempty(fonts)
        fonts = {};
    elseif ~iscell(fonts)
        fonts = {fonts};
    end

    % Map supported font aliases onto the correct name
    fontsl = lower(fonts);
    for a = 1:numel(fonts)
        f = fontsl{a};
        f(f==' ') = [];
        switch f
            case {'times', 'timesnewroman', 'times-roman'}
                fontsl{a} = 'times-roman';
            case {'arial', 'helvetica'}
                fontsl{a} = 'helvetica';
            case {'newcenturyschoolbook', 'newcenturyschlbk'}
                fontsl{a} = 'newcenturyschlbk';
            otherwise
        end
    end
    fontslu = unique(fontsl);

    % Determine the font swap table
    matlab_fonts = {'Helvetica', 'Times-Roman', 'Palatino', 'Bookman', 'Helvetica-Narrow', 'Symbol', ...
        'AvantGarde', 'NewCenturySchlbk', 'Courier', 'ZapfChancery', 'ZapfDingbats'};
    matlab_fontsl = lower(matlab_fonts);
    require_swap = find(~ismember(fontslu, matlab_fontsl));
    unused_fonts = find(~ismember(matlab_fontsl, fontslu));
    font_swap = cell(3, min(numel(require_swap), numel(unused_fonts)));
    fonts_new = fonts;
    for a = 1:size(font_swap, 2)
        font_swap{1,a} = find(strcmp(fontslu{require_swap(a)}, fontsl));
        font_swap{2,a} = matlab_fonts{unused_fonts(a)};
        font_swap{3,a} = fonts{font_swap{1,a}(1)};
        fonts_new(font_swap{1,a}) = font_swap(2,a);
    end

    % Swap the fonts
    if ~isempty(font_swap)
        fonts_size = get(font_handles, 'FontSize');
        if iscell(fonts_size)
            fonts_size = cell2mat(fonts_size);
        end
        M = false(size(font_handles));

        % Loop because some changes may not stick first time, due to listeners
        c = 0;
        update = zeros(1000, 1);
        for b = 1:10 % Limit number of loops to avoid infinite loop case
            for a = 1:numel(M)
                M(a) = ~isequal(get(font_handles(a), 'FontName'), fonts_new{a}) || ~isequal(get(font_handles(a), 'FontSize'), fonts_size(a));
                if M(a)
                    set(font_handles(a), 'FontName', fonts_new{a}, 'FontSize', fonts_size(a));
                    c = c + 1;
                    update(c) = a;
                end
            end
            if ~any(M)
                break;
            end
        end

        % Compute the order to revert fonts later, without the need of a loop
        [update, M] = unique(update(1:c));
        [M, M] = sort(M);
        update = reshape(update(M), 1, []);
    end

    % MATLAB bug fix - black and white text can come out inverted sometimes
    % Find the white and black text
    black_text_handles = findall(fig, 'Type', 'text', 'Color', [0 0 0]);
    white_text_handles = findall(fig, 'Type', 'text', 'Color', [1 1 1]);
    % Set the font colors slightly off their correct values
    set(black_text_handles, 'Color', [0 0 0] + eps);
    set(white_text_handles, 'Color', [1 1 1] - eps);

    % MATLAB bug fix - white lines can come out funny sometimes
    % Find the white lines
    white_line_handles = findall(fig, 'Type', 'line', 'Color', [1 1 1]);
    % Set the line color slightly off white
    set(white_line_handles, 'Color', [1 1 1] - 0.00001);

    % Workaround for issue #45: lines in image subplots are exported in invalid color
    % In this case the -depsc driver solves the problem, but then all the other workarounds
    % below (for all the other issues) will fail, so it's better to let the user decide by
    % just issuing a warning and accepting the '-depsc' input parameter
    epsLevel2 = ~any(strcmpi(options,'-depsc'));
    if epsLevel2
        % Use -depsc2 (EPS color level-2) if -depsc (EPS color level-3) was not specifically requested
        options{end+1} = '-depsc2';
        % Issue a warning if multiple images & lines were found in the figure, and HG1 with painters renderer is used
        isPainters = any(strcmpi(options,'-painters'));
        if isPainters && ~using_hg2 && numel(findall(fig,'Type','image'))>1 && ~isempty(findall(fig,'Type','line'))
            warning('YMA:export_fig:issue45', ...
                    ['Multiple images & lines detected. In such cases, the lines might \n' ...
                     'appear with an invalid color due to an internal MATLAB bug (fixed in R2014b). \n' ...
                     'Possible workaround: add a ''-depsc'' or ''-opengl'' parameter to the export_fig command.']);
        end
    end

    % Print to eps file
    print(fig, options{:}, name);

    % Do post-processing on the eps file
    try
        % Read the EPS file into memory
        fstrm = read_write_entire_textfile(name);
    catch
        fstrm = '';
    end

    % Fix for Matlab R2014b bug (issue #31): LineWidths<0.75 are not set in the EPS (default line width is used)
    try
        if ~isempty(fstrm) && using_hg2(fig)
            % Convert miter joins to line joins
            %fstrm = regexprep(fstrm, '\n10.0 ML\n', '\n1 LJ\n');
            % This is faster (the original regexprep could take many seconds when the axes contains many lines):
            fstrm = strrep(fstrm, sprintf('\n10.0 ML\n'), sprintf('\n1 LJ\n'));

            % In HG2, grid lines and axes Ruler Axles have a default LineWidth of 0.5 => replace en-bulk (assume that 1.0 LineWidth = 1.333 LW)
            %   hAxes=gca; hAxes.YGridHandle.LineWidth, hAxes.YRuler.Axle.LineWidth
            %fstrm = regexprep(fstrm, '(GC\n2 setlinecap\n1 LJ)\nN', '$1\n0.667 LW\nN');
            % This is faster:
            fstrm = strrep(fstrm, sprintf('GC\n2 setlinecap\n1 LJ\nN'), sprintf('GC\n2 setlinecap\n1 LJ\n0.667 LW\nN'));

            % This is more accurate but *MUCH* slower (issue #52)
            %{
            % Modify all thin lines in the figure to have 10x LineWidths
            hLines = findall(fig,'Type','line');
            hThinLines = [];
            for lineIdx = 1 : numel(hLines)
                thisLine = hLines(lineIdx);
                if thisLine.LineWidth < 0.75 && strcmpi(thisLine.Visible,'on')
                    hThinLines(end+1) = thisLine; %#ok<AGROW>
                    thisLine.LineWidth = thisLine.LineWidth * 10;
                end
            end

            % If any thin lines were found
            if ~isempty(hThinLines)
                % Prepare an EPS with large-enough line widths
                print(fig, options{:}, name);
                % Restore the original LineWidths in the figure
                for lineIdx = 1 : numel(hThinLines)
                    thisLine = handle(hThinLines(lineIdx));
                    thisLine.LineWidth = thisLine.LineWidth / 10;
                end

                % Compare the original and the new EPS files and correct the original stream's LineWidths
                fstrm_new = read_write_entire_textfile(name);
                idx = 500;  % skip heading with its possibly-different timestamp
                markerStr = sprintf('10.0 ML\nN');
                markerLen = length(markerStr);
                while ~isempty(idx) && idx < length(fstrm)
                    lastIdx = min(length(fstrm), length(fstrm_new));
                    delta = fstrm(idx+1:lastIdx) - fstrm_new(idx+1:lastIdx);
                    idx = idx + find(delta,1);
                    if ~isempty(idx) && ...
                            isequal(fstrm(idx-markerLen+1:idx), markerStr) && ...
                            ~isempty(regexp(fstrm_new(idx-markerLen+1:idx+12),'10.0 ML\n[\d\.]+ LW\nN')) %#ok<RGXP1>
                        value = str2double(regexprep(fstrm_new(idx:idx+12),' .*',''));
                        if isnan(value), break; end  % something's wrong... - bail out
                        newStr = sprintf('%0.3f LW\n',value/10);
                        fstrm = [fstrm(1:idx-1) newStr fstrm(idx:end)];
                        idx = idx + 12;
                    else
                        break;
                    end
                end
            end
            %}

            % This is much faster although less accurate: fix all non-gray lines to have a LineWidth of 0.75 (=1 LW)
            % Note: This will give incorrect LineWidth of 075 for lines having LineWidth<0.75, as well as for non-gray grid-lines (if present)
            %       However, in practice these edge-cases are very rare indeed, and the difference in LineWidth should not be noticeable
            %fstrm = regexprep(fstrm, '([CR]C\n2 setlinecap\n1 LJ)\nN', '$1\n1 LW\nN');
            % This is faster (the original regexprep could take many seconds when the axes contains many lines):
            fstrm = strrep(fstrm, sprintf('\n2 setlinecap\n1 LJ\nN'), sprintf('\n2 setlinecap\n1 LJ\n1 LW\nN'));
        end
    catch err
        fprintf(2, 'Error fixing LineWidths in EPS file: %s\n at %s:%d\n', err.message, err.stack(1).file, err.stack(1).line);
    end

    % Reset the font and line colors
    set(black_text_handles, 'Color', [0 0 0]);
    set(white_text_handles, 'Color', [1 1 1]);
    set(white_line_handles, 'Color', [1 1 1]);

    % Reset paper size
    set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);

    % Reset the font names in the figure
    if ~isempty(font_swap)
        for a = update
            set(font_handles(a), 'FontName', fonts{a}, 'FontSize', fonts_size(a));
        end
    end

    % Bail out if EPS post-processing is not possible
    if isempty(fstrm)
        warning('Loading EPS file failed, so unable to perform post-processing. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
        return
    end

    % Replace the font names
    if ~isempty(font_swap)
        for a = 1:size(font_swap, 2)
            %fstrm = regexprep(fstrm, [font_swap{1,a} '-?[a-zA-Z]*\>'], font_swap{3,a}(~isspace(font_swap{3,a})));
            fstrm = regexprep(fstrm, font_swap{2,a}, font_swap{3,a}(~isspace(font_swap{3,a})));
        end
    end

    % Move the bounding box to the top of the file (HG2 only), or fix the line styles (HG1 only)
    if using_hg2(fig)
        % Move the bounding box to the top of the file (HG2 only)
        [s, e] = regexp(fstrm, '%%BoundingBox: [^%]*%%');
        if numel(s) == 2
            fstrm = fstrm([1:s(1)-1 s(2):e(2)-2 e(1)-1:s(2)-1 e(2)-1:end]);
        end
    else
        % Fix the line styles (HG1 only)
        fstrm = fix_lines(fstrm);
    end

    % Apply the bounding box padding & cropping, replacing Matlab's print()'s bounding box
    if bb_crop
        % Calculate a new bounding box based on a bitmap print using crop_border.m
        % 1. Determine the Matlab BoundingBox and PageBoundingBox
        [s,e] = regexp(fstrm, '%%BoundingBox: [^%]*%%'); % location BB in eps file
        if numel(s)==2, s=s(2); e=e(2); end
        aa = fstrm(s+15:e-3); % dimensions bb - STEP1
        bb_matlab = cell2mat(textscan(aa,'%f32%f32%f32%f32'));  % dimensions bb - STEP2

        [s,e] = regexp(fstrm, '%%PageBoundingBox: [^%]*%%'); % location bb in eps file
        if numel(s)==2, s=s(2); e=e(2); end
        aa = fstrm(s+19:e-3); % dimensions bb - STEP1
        pagebb_matlab = cell2mat(textscan(aa,'%f32%f32%f32%f32'));  % dimensions bb - STEP2

        % 2. Create a bitmap image and use crop_borders to create the relative
        %    bb with respect to the PageBoundingBox
        [A, bcol] = print2array(fig, 1, '-opengl');
        [aa, aa, aa, bb_rel] = crop_borders(A, bcol, bb_padding);

        % 3. Calculate the new Bounding Box
        pagew = pagebb_matlab(3)-pagebb_matlab(1);
        pageh = pagebb_matlab(4)-pagebb_matlab(2);
        %bb_new = [pagebb_matlab(1)+pagew*bb_rel(1) pagebb_matlab(2)+pageh*bb_rel(2) ...
        %          pagebb_matlab(1)+pagew*bb_rel(3) pagebb_matlab(2)+pageh*bb_rel(4)];
        bb_new = pagebb_matlab([1,2,1,2]) + [pagew,pageh,pagew,pageh].*bb_rel;  % clearer
        bb_offset = (bb_new-bb_matlab) + [-1,-1,1,1];  % 1px margin so that cropping is not TOO tight

        % Apply the bounding box padding
        if bb_padding
            if abs(bb_padding)<1
                bb_padding = round((mean([bb_new(3)-bb_new(1) bb_new(4)-bb_new(2)])*bb_padding)/0.5)*0.5; % ADJUST BB_PADDING
            end
            add_padding = @(n1, n2, n3, n4) sprintf(' %d', str2double({n1, n2, n3, n4}) + [-bb_padding -bb_padding bb_padding bb_padding] + bb_offset);
        else
            add_padding = @(n1, n2, n3, n4) sprintf(' %d', str2double({n1, n2, n3, n4}) + bb_offset); % fix small but noticeable bounding box shift
        end
        fstrm = regexprep(fstrm, '%%BoundingBox:[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)', '%%BoundingBox:${add_padding($1, $2, $3, $4)}');
    end

    % Fix issue #44: white artifact lines appearing in patch exports
    % Note: the problem is due to the fact that Matlab's print() function exports patches
    %       as a combination of filled triangles, and a white line appears where the triangles touch
    % In the workaround below, we will modify such dual-triangles into a filled rectangle.
    % We are careful to only modify regexps that exactly match specific patterns - it's better to not
    % correct some white-line artifacts than to change the geometry of a patch, or to corrupt the EPS.
    %   e.g.: '0 -450 937 0 0 450 3 MP PP 937 0 0 -450 0 450 3 MP PP' => '0 -450 937 0 0 450 0 0 4 MP'
    fstrm = regexprep(fstrm, '\n([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) 3 MP\nPP\n\2 \1 \3 3 MP\nPP\n','\n$1 $2 $3 0 0 4 MP\nPP\n');
    fstrm = regexprep(fstrm, '\n([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) 3 MP\nPP\n\2 \3 \1 3 MP\nPP\n','\n$1 $2 $3 0 0 4 MP\nPP\n');
    fstrm = regexprep(fstrm, '\n([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) 3 MP\nPP\n\3 \1 \2 3 MP\nPP\n','\n$1 $2 $3 0 0 4 MP\nPP\n');
    fstrm = regexprep(fstrm, '\n([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) ([-\d.]+ [-\d.]+) 3 MP\nPP\n\3 \2 \1 3 MP\nPP\n','\n$1 $2 $3 0 0 4 MP\nPP\n');

    % Write out the fixed eps file
    read_write_entire_textfile(name, fstrm);
end

repo: gspbox


text:
function [v_INTERP,ind_Start,ind_End] = FitzHugh_Nagumo_1d(dt_IBM,T_final)
%function FitzHugh_Nagumo_1d(dt_IBM,T_final)

%
% This script solves the FitzHugh-Nagumo Equations in 1d, which are
% a reduced order model of the more complicated Hodgkin-Huxley Equations.
%
% Author:  Nick Battista
% Created: 09/11/2015
% University: UNC-CH
%
% Equations:
% dv/dt = D*Laplacian(v) + v*(v-a)*(v-1) - w - I(t)
% dw/dt = eps*(v-gamma*w)
%
% Inputs:
% dt_IBM: time-step from immersed boundary code
% T_final: final time for immersed boundary simulation
%
% Variables & Parameters:
% v(x,t): membrane potential
% w(x,t): blocking mechanism
% D:      diffusion rate of potential
% a:      threshold potential
% gamma:  resetting rate
% eps:    strength of blocking
% I(t):   initial condition for applied activation
%

%USER-INPUT FROM MODEL:
numPtsAlongTube = 78;    % # of Lag. Muscle Pts Along Tube
ind_Start = 155;         % first index for muscle between tube in spring count
ind_End = 232;           % last index for muscle between tube in spring count
dt_IBM = dt_IBM*2500;    % scale time-info
T_final_Ca = T_final;    % Stays on time-scale of IBM
T_final = T_final * 2500;% scale time-info

% Save Movie?
PLAY_MOVIE = 0; % (1 for YES, 0 for NO)

% Parameters in model %
D = 10.0;       % Diffusion coefficient
a = 0.3;        % Threshold potential (Note: a=0.3 is traveling wave value, a=0.335 is interesting)
gamma = 1.0;    % Resetting rate (Note: large values give 'funky thick' traveling wave, gamma = 1.0 is desired)
eps = 0.001;    % Blocking strength (Note: eps = 0.001 is desired)
I_mag = 0.05;   % Activation strength

% Discretization/Simulation Parameters %
factor = 4;     % 4x the resolution of the FHN model than IBM for tube
N = factor*numPtsAlongTube-1; % # of discretized points for FHN model (finer resolution than IBM mesh)
L = 500;        % Length of domain, [0,L]
dx = L/N;       % Spatial Step
x = 0:dx:L;     % Computational Domain

% Temporal  Parameters %
Np = 10;              % Set the number of pulses
pulse = T_final/Np;   % determines the length of time between pulses.
numFHN = 10;          % # that relates # of time-steps of FHN to IBM
dt = dt_IBM / numFHN; % Time-step for FitzHugh-Nagumo (fraction of IBM time-step)
NT = T_final / dt;    % Total # of time-steps to be taken for FHN
NT_IBM = T_final / dt_IBM; % Total # of time-steps for IBM
i1 = 0.25;%0.475;     % fraction of total length where current starts
i2 = 0.3;%0.525;      % fraction of total length where current ends
dp = pulse/50;        % Set the duration of the current pulse
pulse_time = 0;       % pulse time is used to store the time that the next pulse of current will happen
IIapp=zeros(1,N+1);   % this vector holds the values of the applied current along the length of the neuron
dptime = T_final/100; % This sets the length of time frames that are saved to make a movie.

% Initialization %
v = zeros(1,N+1);
w = v;
t=0;
ptime = 0;
store = 1;       % counter for storing data to match time-steps from IBM
tVec = 0:dt:T_final;
Nsteps = length(tVec);
vStore = zeros(NT_IBM,N+1); vStore(store,:) = v;
wStore = zeros(NT_IBM,N+1); wStore(store,:) = w;
IIappStore=vStore;
store = store+1; % update storage counter

% Compute Calcium-Dynamics a-priori for activation wave!
% (returns Ca: free calcium ions, Caf: bound to filaments Ca-ions)
fprintf('     --> Solving Calcium Dynamics Model\n');
[Ca,Caf] = Calcium_Dynamics(Nsteps,T_final_Ca);
fprintf('     --> Finished calculating Calcium Dynamics\n');

%
% **** % **** BEGIN SIMULATION! **** % **** %
%
for i=2:Nsteps;

     % Update the time
    t = t+dt;

    % Give Laplacian
    DD_v_p = give_Me_Laplacian(v,dx);

    % Gives activation wave (either from prescribed or Calcium-Dynamics model)
    %[IIapp,pulse_time] = Iapp(pulse_time,i1,i2,I_mag,N,pulse,dp,t,IIapp);
    IIapp = Iapp_from_Calcium_Dynamics(i,i1,i2,N,Caf);

    % Update potential and blocking mechanism, using Forward Euler
    vN = v + dt * ( D*DD_v_p - v.*(v-a).*(v-1) - w + IIapp );
    wN = w + dt * ( eps*( v - gamma*w ) );

    % Update time-steps
    v = vN;
    w = wN;

    % Store time-step values
    if mod(i-1,numFHN) == 0
        vStore(store,:) = v;
        wStore(store,:) = w;
        IIappStore(store,:) = IIapp;
        store = store + 1;
    end

    % PLAY MOVIE?
    if PLAY_MOVIE == 1
        %This is used to determine if the current time step will be a frame in the movie
        if t > ptime,
            figure(1)
            plot(x, v);
            axis([0 L -0.5 1.5]);
            xlabel('Distance (x)');
            ylabel('Electropotenital (v)');
            ptime = ptime+dptime;
            fprintf('Time(s): %d\n',t);
            pause(0.01);
        end
    end

end %END TIME-STEPPING LOOP

% Compute electro-potential at associated Lagrangian Pts.
v_INTERP = compute_IBM_Potential_At_IBM_Lag_Pts(factor,numPtsAlongTube,vStore);
%IIapp_INTERP = compute_IBM_Potential_At_IBM_Lag_Pts(factor,numPtsAlongTube,IIappStore);

% TEST SOLUTION
%  pause();
%  x=1:1:78;
%  for i=1:10:length(v_INTERP(:,1))
%     plot(x,v_INTERP(i,:),'-');
%     %plot(x,IIapp_INTERP(i,:),'-');
%     axis([0 79 -0.5 1.5]);
%     pause(0.01);
%  end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION: computes the electro-potential, v(x,t), at the correct points
% along the IBM's Lagrangian Structure
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [v_INTERP] = compute_IBM_Potential_At_IBM_Lag_Pts(factor,numPtsAlongTube,vStore)

% v: row: electro-potential
% factor: resolution of FHN:IBM
% vStore: membrane potential along tube

v_INTERP = zeros(length(vStore(:,1)),numPtsAlongTube);

ct = 1;
for j=1:length(vStore(1,:))
   if ( mod(j-1,factor) == 0 )
       v_INTERP(:,ct) = vStore(:,j);
       ct = ct+1;
   end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION: the CALCIUM inspired injection function, Iapp = activation wave
% for system, and returns the activation signal between i1 and i2 in
% geometry along tube
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function IIapp = Iapp_from_Calcium_Dynamics(ith_step,i1,i2,N,Caf)

    % Resets activation to zero
    IIapp = zeros(1,N+1);

    % Activates the proper region based on Calcium-Dynamics
    for j=(floor(i1*N):floor(i2*N))
        coeff = 0.5;                 % Coefficient to scale activation wave accordingly
        IIapp(j) = coeff*Caf(ith_step); % Activation of bound Calcium to filaments
    end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION: the injection function, Iapp = activation wave for system, and
% returns both the activation as well as updated pulse_time
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [app,pulse_time] = Iapp(pulse_time,i1,i2,I_mag,N,pulse,dp,t,app)

    %Check to see if there should be a pulse
    if t > (pulse_time),

        % Sets pulsing region to current amplitude of I_mag x\in[i1*N,i2*N]
        for j=(floor(i1*N):floor(i2*N)),
            app(j) = I_mag;
        end

        % Checks if the pulse is over & then resets pulse_time to the next pulse time.
        if t > (pulse_time+dp),
            pulse_time = pulse_time+pulse;
        end

    else

        % Resets to no activation
        app = zeros(1,N+1);

    end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FUNCTION: gives Laplacian of the membrane potential, note: assumes
% periodicity and uses the 2nd order central differencing operator.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function DD_v = give_Me_Laplacian(v,dx)

Npts = length(v);
DD_v = zeros(1,Npts);

for i=1:Npts
   if i==1
       %DD_v(i) = ( v(i+1) - 2*v(i) + v(end) ) / dx^2;
       DD_v(i) = ( v(i+1) - 2*v(i) + 0 ) / dx^2;
   elseif i == Npts
       %DD_v(i) = ( v(1) - 2*v(i) + v(i-1) ) / dx^2;
       DD_v(i) = ( 0 - 2*v(i) + v(i-1) ) / dx^2;
   else
       DD_v(i) = ( v(i+1) - 2*v(i) +  v(i-1) ) /dx^2;
   end

end

author: nickabattista


text:
classdef prtPreProcMinMaxColumns < prtPreProc

    properties (SetAccess=private)

        name = 'MinMax Columns'  %  MinMax Rows
        nameAbbreviation = 'MMC'  % MMR
    end

    properties
        %no properties
        minVals = [];
        maxVals = [];
    end

    methods

        function self = prtPreProcMinMaxColumns(varargin)
            self = prtUtilAssignStringValuePairs(self,varargin{:});
        end
    end

    methods (Access = protected, Hidden = true)

        function self = trainAction(self,DataSet) %#ok<INUSD>
            %do nothing
            self.minVals = min(DataSet.getObservations);
            self.maxVals = max(DataSet.getObservations);
            invalidInds = find(self.minVals == self.maxVals);
            %Do nothing for invalid indices
            self.minVals(invalidInds) = 0;
            self.maxVals(invalidInds) = 1;
        end

        function DataSet = runAction(self,DataSet)

            theData = DataSet.getObservations;

            theData = bsxfun(@minus,theData,self.minVals);
            theData = bsxfun(@rdivide,theData,self.maxVals - self.minVals);

            %what should we do about outliers?  they will not be zero or
            %one...
            DataSet = DataSet.setObservations(theData);
        end

    end

end

author: covartech

repo: PRT

save_path: github-repos/MATLAB/covartech-PRT


text:
function TSeriesOutlierCheck(dataType, scans, criterion);
%
% TSeriesOutlierCheck(<dataType='Original'>, <scans=all>, <zitFiles>);
%
% = or =
%
% TSeriesOutlierCheck(<dataType='Original'>, <scans=all>, <threshold>);
%
% Checks for outlier frames in Inplane TSeries. If outlier frames are
% found, offers the option to replace the outlier frames with the
% average of the surrounding frames.
%
% The criterion for finding outliers can be specified in one of two ways:
% (1) 'zits' files, or (2) a standard deviation threshold from the mean.
%
% 'zits' files are text files created at the Lucas Center for reporting
% outlier voxels (of the form 'P*.7.zits'). If these are provided, will
% read these files to find the outlier points.
%
% If a standard deviation is provided, will look for frames whose mean is
% greater than <threshold> standard deviations from the mean. If the third
% argument is unspecified, will set a threshold of 2 std dev.
%
% This function needs to be run from a session's home directory.
%
% *** STILL BEING WRITTEN ***
%
% ras, 04/2006.
if notDefined('dataType'),  dataType = 'Original';       end
if notDefined('criterion'), criterion = 2;               end
if notDefined('scans'),
    % take all
    scans = length(dir(fullfile(pwd, 'Inplane', dataType, 'TSeries', 'Scan*')));
end

if isstr(criterion) | iscell(criterion)
    % zits files specified: read through them

else
    % std dev threshold specified

end

return

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function slComplete(searchlight, removeFiles)
% slComplete(searchlight, removeFiles)
% SEARCHLIGHT - COMPLETE
% ---------------------------------------------------------
% Verifies presence of all necessary portions of searchlight, finishing by
% inserting all of them into a parameter map for loading into mrVista.
%
% INPUTS
%   searchlight - Structure generated by slInit.
%   removeFiles - Off by default, when set to true it will clean up files
%       as it reads them in.
%
% OUTPUTS
%   N/A
%
% USAGE
%   After running a searchlight, passing it to slComplete to construct a
%   parameter map.  In this case, we choose to remove the files.
%       searchlight = slInit(...);
%       slRun(searchlight, ...);
%       slComplete(searchlight, true);
%
% See also SLINIT, SLRUN, SLSPAWN, SVMINIT.
%
% renobowen@gmail.com [2010]
%

if notDefined('removeFiles'), removeFiles = false; end

totalProcesses = searchlight.processes * searchlight.partitions;
if (isSearchlightComplete(searchlight, totalProcesses))
    processSearchlight(searchlight, totalProcesses, removeFiles);
end

end

function bool = isSearchlightComplete(searchlight, totalProcesses)
for i = 1:totalProcesses
    if (~exist(sprintf('%s/%s/searchlight%04d.mat', searchlight.path, searchlight.tmpDir, i), 'file'))
        bool = false;
        return;
    end
end
bool = true;
end

function processSearchlight(searchlight, processes, removeFiles)
svm = searchlight.svm;
svm = rmfield(svm, 'data'); % this is to save space

for i = 1:processes
    filename = sprintf('%s/%s/searchlight%04d.mat', searchlight.path, searchlight.tmpDir, i);
    tmp = load(filename);
    nCenters = size(tmp.centers, 2);
    for j = 1:nCenters
        if (~isempty(tmp.meanAccs(j)))
            if (strcmpi(searchlight.searchView, 'gray'))
                map{1}(tmp.centers(1, j)) = tmp.meanAccs(j);
            else
                map{1}(tmp.centers(1, j), tmp.centers(2, j), tmp.centers(3, j)) = tmp.meanAccs(j);
            end
        end
    end
    if (removeFiles), delete(filename); end
end
growBy = tmp.growBy;
fprintf('done.\n');

if (removeFiles), rmdir(sprintf('%s/%s', searchlight.path, searchlight.tmpDir)); end

filename = sprintf('%s/%s.mat', searchlight.path, searchlight.tmpDir);
mapName = 'searchlight';
if exist('mapBootstrap','var')
    save(filename, 'map', 'mapName', 'growBy', 'svm', 'mapBootstrap', '-v7.3');
else
    save(filename, 'map', 'mapName', 'growBy', 'svm', '-v7.3');
end
fprintf('Saved to: %s\n', filename);

end


text:
function p23_default ( dim_num )

%*****************************************************************************80
%
%% P23_DEFAULT sets default values for problem 23.
%
%  Discussion:
%
%    If a problem uses vector parameters, then the spatial dimension
%    DIM_NUM is needed as input, so that the vector parameters can be
%    properly dimensioned.
%
%    Every problem keeps a count of the number of function calls.  Calling
%    this routine causes that count to be reset to 0.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DIM_NUM, the dimension of the problem.
%
  i4 = 0;
  p23_i4 ( 'D', '*', i4 );

  r8 = 0.0;
  p23_r8 ( 'D', '*', r8 );

  i4vec = [];
  p23_i4vec ( 'D', '*', dim_num, i4vec );

  return
end


text:
function varn = detVarNames(svar)
%Determine variable names, in order, index free
%e.g. [ h1, h2, m1, m2, m3] becomes {h [1 2]; m [3 4 5]}

%Initialize
varn = []; k = 1;
%Search each var
for i = 1:length(svar)
    str = char(svar(i)); found = 0;
    for j = 1:length(str)
        if(uint8(str(j)) < 65 || uint8(str(j)) > 126)
            found = 1;
            break; %found a number, assume end of name
        end
    end
    %If we found it, remove number (last index found)
    if(found)
        nvar = str(1:j-1); %New variable name
    else
        nvar = str;
    end
    %See where to place it
    if(isempty(varn))
        varn = {nvar i};
        k = k + 1;
    elseif(strcmp(varn{k-1,1},nvar)) %same as old one
        varn{k-1,2} = [varn{k-1,2} i]; %#ok<AGROW>
    else %new one
        varn = [varn; {nvar} i]; %#ok<AGROW>
        k = k + 1;
    end
end

author: vigente

repo: gerardus

save_path: github-repos/MATLAB/vigente-gerardus


text:
function string = user_string(string_name, string)
%USER_STRING  Get/set a user specific string
%
% Examples:
%   string  = user_string(string_name)
%   isSaved = user_string(string_name, new_string)
%
% Function to get and set a string in a system or user specific file. This
% enables, for example, system specific paths to binaries to be saved.
%
% The specified string will be saved in a file named <string_name>.txt,
% either in a subfolder named .ignore under this file's folder, or in the
% user's prefdir folder (in case this file's folder is non-writable).
%
% IN:
%   string_name - String containing the name of the string required, which
%                 sets the filename storing the string: <string_name>.txt
%   new_string  - The new string to be saved in the <string_name>.txt file
%
% OUT:
%   string  - The currently saved string. Default: ''
%   isSaved - Boolean indicating whether the save was succesful

% Copyright (C) Oliver Woodford 2011-2014, Yair Altman 2015-

% This method of saving paths avoids changing .m files which might be in a
% version control system. Instead it saves the user dependent paths in
% separate files with a .txt extension, which need not be checked in to
% the version control system. Thank you to Jonas Dorn for suggesting this
% approach.

% 10/01/2013 - Access files in text, not binary mode, as latter can cause
%              errors. Thanks to Christian for pointing this out.
% 29/05/2015 - Save file in prefdir if current folder is non-writable (issue #74)

    if ~ischar(string_name)
        error('string_name must be a string.');
    end
    % Create the full filename
    fname = [string_name '.txt'];
    dname = fullfile(fileparts(mfilename('fullpath')), '.ignore');
    file_name = fullfile(dname, fname);
    if nargin > 1
        % Set string
        if ~ischar(string)
            error('new_string must be a string.');
        end
        % Make sure the save directory exists
        %dname = fileparts(file_name);
        if ~exist(dname, 'dir')
            % Create the directory
            try
                if ~mkdir(dname)
                    string = false;
                    return
                end
            catch
                string = false;
                return
            end
            % Make it hidden
            try
                fileattrib(dname, '+h');
            catch
            end
        end
        % Write the file
        fid = fopen(file_name, 'wt');
        if fid == -1
            % file cannot be created/updated - use prefdir if file does not already exist
            % (if file exists but is simply not writable, don't create a duplicate in prefdir)
            if ~exist(file_name,'file')
                file_name = fullfile(prefdir, fname);
                fid = fopen(file_name, 'wt');
            end
            if fid == -1
                string = false;
                return;
            end
        end
        try
            fprintf(fid, '%s', string);
        catch
            fclose(fid);
            string = false;
            return
        end
        fclose(fid);
        string = true;
    else
        % Get string
        fid = fopen(file_name, 'rt');
        if fid == -1
            % file cannot be read, try to read the file in prefdir
            file_name = fullfile(prefdir, fname);
            fid = fopen(file_name, 'rt');
            if fid == -1
                string = '';
                return
            end
        end
        string = fgetl(fid);
        fclose(fid);
    end
end

author: optimaltransport


text:
function H=tricontour(tri,x,y,z,v,levels,color)
%TRICONTOUR Contour plot for triangulated data.
%   TRICONTOUR(TRI,X,Y,Z,Levels) displays the contour plot based on
%   triangles defined in the M-by-3 face matrix TRI as a surface. A
%   row of TRI contains indexes into the X,Y, and Z vertex vectors
%   to define a single triangular face.
%
%   TRICONTOUR(TRI,X,Y,Z,V,Levels) displays the contour plot based on
%   triangles defined in the M-by-3 face matrix TRI as a surface. A
%   row of TRI contains indexes into the X,Y, and Z vertex vectors
%   to define a single triangular face. The contours are determined
%   by the values V and the Levels.
%
%   H = TRICONTOUR(...) a vector H of handles to LINE or PATCH objects,
%   one handle per line. TRICONTOUR is not compatible with CLABEL.
%
%   The contours are normally colored based on the current colormap
%   and are drawn as PATCH objects. You can override this behavior
%   with the syntax CONTOUR(...,'LINESPEC') to draw the contours as
%   LINE objects with the color and linetype specified.
%
%   Example:
%      x=rand(20); y=rand(20); z=rand(20); tri=delaunay(x,y);
%      tricontour(tri,x,y,z,.3:.1:1); colorbar
%
%   See also CONTOUR, CONTOURF, TRICONTOURF

%----- LGPL --------------------------------------------------------------------
%
%   Copyright (C) 2011-2013 Stichting Deltares.
%
%   This library is free software; you can redistribute it and/or
%   modify it under the terms of the GNU Lesser General Public
%   License as published by the Free Software Foundation version 2.1.
%
%   This library is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%   Lesser General Public License for more details.
%
%   You should have received a copy of the GNU Lesser General Public
%   License along with this library; if not, see <http://www.gnu.org/licenses/>.
%
%   contact: delft3d.support@deltares.nl
%   Stichting Deltares
%   P.O. Box 177
%   2600 MH Delft, The Netherlands
%
%   All indications and logos of, and references to, "Delft3D" and "Deltares"
%   are registered trademarks of Stichting Deltares, and remain the property of
%   Stichting Deltares. All rights reserved.
%
%-------------------------------------------------------------------------------
%   http://www.deltaressystems.com
%   $HeadURL: https://svn.oss.deltares.nl/repos/delft3d/trunk/src/tools_lgpl/matlab/quickplot/progsrc/tricontour.m $
%   $Id: tricontour.m 2498 2013-05-16 12:38:27Z jagers $

error(nargchk(5,7,nargin));
getdata=0;
if nargin==7
    if strcmp(color,'getdata')
        getdata=1;
        lin = '*';
        col = '*';
    else
        [lin,col,mark,msg] = colstyle(color);
        if ~isempty(msg)
            error(msg)
        end
    end
elseif nargin==6
    if ischar(levels)
        color=levels;
        levels=v;
        v=z;
        z=[];
        if strcmp(color,'getdata')
            getdata=1;
            lin = '*';
            col = '*';
        else
            [lin,col,mark,msg] = colstyle(color);
            if ~isempty(msg)
                error(msg)
            end
        end
    else
        lin = '';
        col = '';
    end
else
    levels=v;
    v=z;
    z=[];
    lin = '';
    col = '';
end

if ~getdata
    ax = newplot;
    if isempty(col) % no color spec was given
        colortab = get(ax,'colororder');
        ncol = size(colortab,1);
    end
end

x=transpose(x(:));
y=transpose(y(:));
zdef=~isempty(z);
if zdef
    z=transpose(z(:));
end
v=transpose(v(:));

Patches=1:size(tri,1);
nlevels = length(levels);
if getdata
    H=cell(1,nlevels);
else
    H=zeros(1,nlevels);
end
NonEmptyLevel=zeros(1,nlevels);
for LevelNr=1:nlevels
    level=levels(LevelNr);
    Nlarger=sum(v(tri)>level,2);
    Nsmaller=sum(v(tri)<level,2);
    NaN_tri=any(isnan(v(tri)),2);
    Nsmaller(NaN_tri)=3;
    Nlarger(NaN_tri)=0;
    CLIndex=1+4*Nlarger+Nsmaller;
    Cutslevel=[0 3 2 0 3 3 3 0 2 3 0 0 0 0 0];
    NLevel=sum(Cutslevel(CLIndex));
    XLevel=repmat(NaN,[NLevel 1]);
    YLevel=XLevel;
    if zdef
        ZLevel=XLevel;
    end
    LvlOffset=0;

    % patches with three equal
    % Patch=Patches(CLIndex==1);

    % patches with two equal
    Patch=Patches((CLIndex==2) | (CLIndex==5));
    if ~isempty(Patch)
        LvlIndex=LvlOffset+(1:3:(3*length(Patch)));
        LvlIndex=[LvlIndex;LvlIndex+1];
        Index=tri(Patch,:);
        [Dummy,Permutation]=sort(v(Index)==level,2);
        Index=Index((Permutation-1)*size(Index,1)+transpose(1:size(Index,1))*[1 1 1]);
        % first element has elevation different from level
        Index=Index(:,[2 3]);
        XPoint=transpose(x(Index));
        XLevel(LvlIndex(:))=XPoint(:);
        YPoint=transpose(y(Index));
        YLevel(LvlIndex(:))=YPoint(:);
        if zdef
            ZPoint=transpose(z(Index));
            ZLevel(LvlIndex(:))=ZPoint(:);
        end
        LvlOffset=LvlOffset+3*length(Patch);
    end

    % patches with one equal, one larger and one smaller
    Patch=Patches(CLIndex==6);
    if ~isempty(Patch)
        LvlIndex=LvlOffset+(1:3:(3*length(Patch)));
        LvlIndex=[LvlIndex;LvlIndex+1];
        Index=tri(Patch,:);
        [Dummy,Permutation]=sort(v(Index),2);
        Index=Index((Permutation-1)*size(Index,1)+transpose(1:size(Index,1))*[1 1 1]);
        % second element has elevation equal to level
        VTemp=v(Index);
        Lambda=min(1,(level-VTemp(:,1))./(VTemp(:,3)-VTemp(:,1)));
        XPoint=transpose([transpose(x(Index(:,1)))+Lambda.*transpose(x(Index(:,3))-x(Index(:,1))) transpose(x(Index(:,2)))]);
        XLevel(LvlIndex(:))=XPoint(:);
        YPoint=transpose([transpose(y(Index(:,1)))+Lambda.*transpose(y(Index(:,3))-y(Index(:,1))) transpose(y(Index(:,2)))]);
        YLevel(LvlIndex(:))=YPoint(:);
        if zdef
            ZPoint=transpose([transpose(z(Index(:,1)))+Lambda.*transpose(z(Index(:,3))-z(Index(:,1))) transpose(z(Index(:,2)))]);
            ZLevel(LvlIndex(:))=ZPoint(:);
        end
        LvlOffset=LvlOffset+3*length(Patch);
    end

    % patches with two larger and one smaller
    Patch=Patches(CLIndex==10);
    if ~isempty(Patch)
        LvlIndex=LvlOffset+(1:3:(3*length(Patch)));
        LvlIndex=[LvlIndex;LvlIndex+1];
        Index=tri(Patch,:);
        [Dummy,Permutation]=sort(v(Index)<level,2);
        Index=Index((Permutation-1)*size(Index,1)+transpose(1:size(Index,1))*[1 1 1]);
        % last element has elevation less than level
        VTemp=v(Index);
        Lambda=min(1,(level-VTemp(:,3)*ones(1,2))./(VTemp(:,[1 2])-VTemp(:,3)*ones(1,2)));
        XPoint=transpose(transpose(x(Index(:,3)))*ones(1,2)+Lambda.*(x(Index(:,[1 2]))-transpose(x(Index(:,3)))*ones(1,2)));
        XLevel(LvlIndex(:))=XPoint(:);
        YPoint=transpose(transpose(y(Index(:,3)))*ones(1,2)+Lambda.*(y(Index(:,[1 2]))-transpose(y(Index(:,3)))*ones(1,2)));
        YLevel(LvlIndex(:))=YPoint(:);
        if zdef
            ZPoint=transpose(transpose(z(Index(:,3)))*ones(1,2)+Lambda.*(z(Index(:,[1 2]))-transpose(z(Index(:,3)))*ones(1,2)));
            ZLevel(LvlIndex(:))=ZPoint(:);
        end
        LvlOffset=LvlOffset+3*length(Patch);
    end

    % patches with two smaller and one larger
    Patch=Patches(CLIndex==7);
    if ~isempty(Patch)
        LvlIndex=LvlOffset+(1:3:(3*length(Patch)));
        LvlIndex=[LvlIndex;LvlIndex+1];
        Index=tri(Patch,:);
        [Dummy,Permutation]=sort(v(Index)>level,2);
        Index=Index((Permutation-1)*size(Index,1)+transpose(1:size(Index,1))*[1 1 1]);
        % last element has elevation larger than level
        VTemp=v(Index);
        Lambda=min(1,(level-VTemp(:,[1 2]))./(VTemp(:,3)*ones(1,2)-VTemp(:,[1 2])));
        XPoint=transpose(x(Index(:,[1 2]))+Lambda.*(transpose(x(Index(:,3)))*ones(1,2)-x(Index(:,[1 2]))));
        XLevel(LvlIndex(:))=XPoint(:);
        YPoint=transpose(y(Index(:,[1 2]))+Lambda.*(transpose(y(Index(:,3)))*ones(1,2)-y(Index(:,[1 2]))));
        YLevel(LvlIndex(:))=YPoint(:);
        if zdef
            ZPoint=transpose(z(Index(:,[1 2]))+Lambda.*(transpose(z(Index(:,3)))*ones(1,2)-z(Index(:,[1 2]))));
            ZLevel(LvlIndex(:))=ZPoint(:);
        end
        LvlOffset=LvlOffset+3*length(Patch);
    end

    % patches with one equal and two larger or two smaller
    Patch=Patches((CLIndex==3) | (CLIndex==9));
    if ~isempty(Patch)
        LvlIndex=LvlOffset+(1:2:(2*length(Patch)));
        Index=tri(Patch,:);
        [Dummy,Permutation]=sort(v(Index)==level,2);
        Index=Index((Permutation-1)*size(Index,1)+transpose(1:size(Index,1))*[1 1 1]);
        % third element has elevation equal to level
        Index=Index(:,3);
        XPoint=x(Index);
        XLevel(LvlIndex(:))=XPoint(:);
        YPoint=y(Index);
        YLevel(LvlIndex(:))=YPoint(:);
        if zdef
            ZPoint=z(Index);
            ZLevel(LvlIndex(:))=ZPoint(:);
        end
        LvlOffset=LvlOffset+2*length(Patch);
    end

    VLevel=level*ones(size(XLevel));

    NonEmptyLevel(LevelNr)=1;
    if getdata
        if zdef
            H{LevelNr}={XLevel YLevel ZLevel LevelNr};
        else
            H{LevelNr}={XLevel YLevel LevelNr};
        end
    elseif isempty(col) && isempty(lin)
        if ~zdef
            ZLevel=VLevel;
        end
        NewH = patch('XData',transpose([XLevel;XLevel]), ...
            'YData',transpose([YLevel;YLevel]), ...
            'ZData',transpose([ZLevel;ZLevel]), ...
            'CData',transpose([VLevel;VLevel]), ...
            'facecolor','none', ...
            'edgecolor','flat',...
            'userdata',level, ...
            'parent',ax);
        H(LevelNr)=NewH;
    else
        if ~zdef
            ZLevel=VLevel;
        end
        NewH = line('XData',XLevel, ...
            'YData',YLevel, ...
            'ZData',ZLevel, ...
            'userdata',level, ...
            'parent',ax);
        H(LevelNr)=NewH;
    end
end

levels=levels(logical(NonEmptyLevel));

if getdata
    % do nothing
elseif isempty(col) && ~isempty(lin)
    nlvl = length(levels);
    colortab = colortab(mod(1:nlvl,ncol)+1,:);
    for i = 1:length(H)
        set(H(i),'linestyle',lin,'color',colortab(i,:));
    end
else
    if ~isempty(lin)
        set(H,'linestyle',lin);
    end
    if ~isempty(col)
        set(H,'color',col);
    end
end

author: CHLNDDEV