text:
function out_signal_dim = bci_Preflight(in_signal_dim)
% Check bci_Parameters variable (stored by BCI2000) for consistency.
% Out-Signal-Dim = bci_Preflight(In-Signal-Dim)
%
% In:
%  In-Signal-Dim  : a two-element vector of the form [#Channels, #Samples] which describes the input signal's dimensions
%
% Out:
%  Out-Signal-Dim : a two-element vector of the form [#Channels, #Samples] which describes the input signal's dimensions
%
%                                Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
%                                2010-09-08

global bci_Parameters;

% these variables are shared with Initialize and Process
global model meta_data outrate maxcpu outdims outform;

quicklog('bcilab-log.txt','called with in_signal_dim = [%i, %i]',in_signal_dim(1),in_signal_dim(2));

if in_signal_dim(1) <= 2
    quicklog('bcilab-log.txt','Haha, apparently bci_Preflight is being called with its own output by BCI2000... ignoring that for now.');
    out_signal_dim = in_signal_dim;
    return;
end

% --- model checks ---

quicklog('bcilab-log.txt','checking if model file (%s) is present ...',bci_Parameters.Model{1});

% check if the bci model is present
if ~exist(bci_Parameters.Model{1},'file')
    error('BCILAB:BCI2000_plugin:model_not_found',['Could not find the bci model file specified as ' bci_Parameters.Model '.']); end

% --- stream meta-data checks ---

quicklog('bcilab-log.txt','checking if stream parameters are present...');
quicklog('bcilab-log.txt','declared parameters: %s',hlp_tostring(fieldnames(bci_Parameters)'));

% try to get the sampling rate
try
    srate = sscanf(bci_Parameters.SamplingRate{1},'%i');
    if ~isscalar(srate)
        quicklog('bcilab-log.txt','SamplingRate is ill-formatted: %s...',hlp_tostring(srate));
        error('Sampling rate has the wrong size...');
    end
    quicklog('bcilab-log.txt','SamplingRate is %.1f...',srate);
catch
    quicklog('bcilab-log.txt','SamplingRate is unspecified...');
    srate = [];
end

% try to get the channel names
try
    channels = bci_Parameters.ChannelNames;
    quicklog('bcilab-log.txt','ChannelNames are %s...',hlp_tostring(channels));
catch
    quicklog('bcilab-log.txt','ChannelNames are unspecified...');
    channels = [];
end

quicklog('bcilab-log.txt','checking if the meta-data file (%s) is present...',bci_Parameters.MetaFile{1});

% check if the meta-data file exists
if exist(bci_Parameters.MetaFile{1},'file')
    quicklog('bcilab-log.txt','found meata-data file, now loading...');
    % yes: use it
    meta_data = utl_parse_metadata('datasource',bci_Parameters.MetaFile{1},'srate',srate,'chanlocs',channels);
    quicklog('bcilab-log.txt','success.');
else
    % no: check if the BCI2000 parameters are sufficient to determine the stream format
    quicklog('bcilab-log.txt','Found no meata-data file.');
    if ~isempty(channels) && ~isempty(srate)
        quicklog('bcilab-log.txt','But ChannelNames and SamplingRate are fine, proceeding...');
        % we're fine...
        meta_data = utl_parse_metadata('srate',srate,'chanlocs',channels);
    else
        % we're NOT fine -- take a look at the model to find out the original (source) data set
        quicklog('bcilab-log.txt','ChannelNames or SamplingRate parameters are not specified correctly!');
        quicklog('bcilab-log.txt','Now checking if the original training set was specified in the model and can be retrieved for reference.');

        % try to load the model (jumping through a few hoops, if necessary....)
        try
            quicklog('bcilab-log.txt','Trying to load the model file...');
            model = io_load(bci_Parameters.Model{1});
            quicklog('bcilab-log.txt','success.');
            if ~isfield(model,'tracking') || ~isfield(model.tracking,'prediction_function')
                quicklog('bcilab-log.txt','But the model file is lacking the correct properties - apparently the file contains a variable that is the model.');
                % the loaded model is lacking the appropriate fields; check if there are variables
                % in the loaded data which are valid models
                candidates = {};
                for f = fieldnames(model)'
                    fname = f{1};
                    if isfield(model.(fname),'tracking') && isfield(model.(fname).tracking,'prediction_function')
                        candidates{end+1} = fname; end %#ok<AGROW>
                end
                if length(candidates) > 1
                    quicklog('bcilab-log.txt','Model file contains multiple candidate model variables; choice is ambiguous - aborting...');
                    error('BCILAB:bci_Preflight:ambiguous',['The file given as the model contains multiple candiate variables:\n' ...
                        hlp_tostring(candidates) '; please pass a file name which contains only one model variable.']);
                elseif isempty(candidates)
                    quicklog('bcilab-log.txt','Model file contains no candidate model variable - aborting...');
                    error('BCILAB:bci_Preflight:load_error','The given file contains no valid model.');
                else
                    quicklog('bcilab-log.txt','Model was successfully identified.');
                    model = model.(candidates{1});
                end
            end
        catch le
            quicklog('bcilab-log.txt','Error loading the model; traceback: %s',le.message);
            error('BCILAB:bci_Preflight:load_error',['The given model string could not be parsed; traceback: ' le.message]);
        end

        % now try to load the source data...
        if ~isfield(model,'source_data')
            quicklog('bcilab-log.txt','Model contains no source_data field, thus the source data set cannot be identified - aborting.');
            error('BCILAB:bci_Preflight:load_error','The given model is lacking a source_data field (which should contain the name of the training set.');
        end
        if ~all(isfield(model.source_data,{'head','parts'}))
            quicklog('bcilab-log.txt','Model has a source_data field, but it does not refer to a single data set - aborting.');
            error('BCILAB:bci_Preflight:load_error','The source_data field of the given model does not refer to a single data set (but some structure that is unrecognized by this plugin). You will have to specify the stream meta-data either via the MetaFile field or via SamplingRate and ChannelNames parameters.');
        end

        quicklog('bcilab-log.txt','Successfully extracted the meta-data from the source file.');
        meta_data = exp_eval(model.source_data);

        if isfield(meta_data,'tracking')
            meta_data = rmfield(meta_data,'tracking');
            quicklog('bcilab-log.txt','Stripped ''tracking'' field from meta-data.');
        end
        if isfield(meta_data,'data')
            meta_data = rmfield(meta_data,'data');
            quicklog('bcilab-log.txt','Stripped ''data'' field from meta-data.');
        end

        if ~isempty(srate)
            quicklog('bcilab-log.txt','Overriding the sampling rate with BCI2000''s %.1f',srate);
            meta_data.srate = srate;
        end
    end
end

quicklog('bcilab-log.txt','Determined sampling rate is: %.1f',meta_data.srate);
quicklog('bcilab-log.txt','Determined channel count: %i',length(meta_data.chanlocs));
quicklog('bcilab-log.txt','Determined channel names are: %s',hlp_tostring({meta_data.chanlocs.labels}));

% check that the input signal dimension matches the number of channel names
if length(meta_data.chanlocs) ~= in_signal_dim(1)
    quicklog('bcilab-log.txt','Number of channel names (%i) does not match the input signal channel # supplied by BCI2000 (%i) - aborting...',length(meta_data.chanlocs),in_signal_dim(1));
    error('BCILAB:BCI2000_plugin:metadata_inconsistent',['The number of channel names (' num2str(length(meta_data.chanlocs)) ', specified in the ChannelNames parameter or the MetaFile) does not match the signal''s channel count (' num2str(in_signal_dim(1)) ').']);
end

quicklog('bcilab-log.txt','successfully matched specified and supplied channel numbers.');

% --- get remaining parameters ---
outforms = {'expectation','distribution','mode'};
outform = outforms{str2num(bci_Parameters.OutputForm{1})};
outrate = str2num(bci_Parameters.OutputRate{1});
maxcpu = str2num(bci_Parameters.MaxCPU{1});

quicklog('bcilab-log.txt','OutputForm is %s',outform);
quicklog('bcilab-log.txt','OutputRate is %.1f',outrate);
quicklog('bcilab-log.txt','MaxCPU is %.1f',maxcpu);

outdims = str2num(bci_Parameters.OutputChannels{1});
if outdims == 0
    quicklog('bcilab-log.txt','No number of output channels was specified; assuming univariate regression or classification...');
    if strcmp(outform,'distribution')
        quicklog('bcilab-log.txt','Since the OutputForm is ''distribution'', assuming that the output signal has 2 channels.');
        outdims = 2;
    else
        quicklog('bcilab-log.txt','Since the OutputForm is either ''mode'' or ''expectation'', assuming that the output signal has 1 channel.');
        outdims = 1;
    end
    % no output channel # specified; assume that we're doing univariate regression or classification
    disp(['Number of BCI output channels was not specified; assuming it is ' num2str(outdims)]);
end

out_signal_dim = [outdims, in_signal_dim(2)];

quicklog('bcilab-log.txt','Returing out_signal_dim = [%i, %i]',out_signal_dim(1),out_signal_dim(2));

if ~isempty(meta_data)
    quicklog('bcilab-log.txt','global meta_data variable is properly initialized.'); end

quicklog('bcilab-log.txt','finished successfully...');


text:
function out = isPerp(v1,v2)
% check whether v1 and v2 are orthogonal

out = isnull(dot(v1,v2));

author: mtex-toolbox

repo: mtex

save_path: github-repos/MATLAB/mtex-toolbox-mtex


text:
function [V,F]=platonic_solid(n,r)

% function [V,F]=platonic_solid(n,r)
% ------------------------------------------------------------------------
% PLATONIC_SOLID Creates the PATCH data, the vertices (V) and faces (F) for
% a given platonic solid (according to "n" see below) with radius (r)
%
% n=1 -> Tetrahedron
% n=2 -> Cube
% n=3 -> Octahedron
% n=4 -> Icosahedron
% n=5 -> Dodecahedron
%
% %%%Example
% clear all; close all; clc;
%
% r=1;
% figure;fig=gcf; clf(fig); colordef (fig, 'white'); units=get(fig,'units'); set(fig,'units','normalized','outerposition',[0 0 1 1]); set(fig,'units',units); set(fig,'Color',[1 1 1]);
% hold on;
%
% [V,F]=platonic_solid(1,r);
% subplot(2,3,1);
% patch('Faces',F,'Vertices',V,'FaceColor','b','FaceAlpha',0.6,'EdgeColor','k','LineWidth',2); axis equal; grid on; hold on; view(3); axis off;
%
% [V,F]=platonic_solid(2,r);
% subplot(2,3,2);
% patch('Faces',F,'Vertices',V,'FaceColor','b','FaceAlpha',0.6,'EdgeColor','k','LineWidth',2); axis equal; grid on; hold on; view(3); axis off;
%
% [V,F]=platonic_solid(3,r);
% subplot(2,3,3);
% patch('Faces',F,'Vertices',V,'FaceColor','b','FaceAlpha',0.6,'EdgeColor','k','LineWidth',2); axis equal; grid on; hold on; view(3); axis off;
%
% [V,F]=platonic_solid(4,r);
% subplot(2,3,4);
% patch('Faces',F,'Vertices',V,'FaceColor','b','FaceAlpha',0.6,'EdgeColor','k','LineWidth',2); axis equal; grid on; hold on; view(3); axis off;
%
% [V,F]=platonic_solid(5,r);
% subplot(2,3,5);
% patch('Faces',F,'Vertices',V,'FaceColor','b','FaceAlpha',0.6,'EdgeColor','k','LineWidth',2); axis equal; grid on; hold on; view(3); axis off;
%
%
% Kevin Mattheus Moerman
% kevinmoerman@hotmail.com
% 13/11/2009
% ------------------------------------------------------------------------

phi=(1+sqrt(5))/2;

switch n
    case 1 % Tetrahedron
        V1=[-0.5;0.5;0;0;];
        V2=[-sqrt(3)/6;  -sqrt(3)/6; sqrt(3)/3; 0];
        V3=[-0.25.*sqrt(2/3); -0.25.*sqrt(2/3); -0.25.*sqrt(2/3);  0.75.*sqrt(2/3)];
        F= [1 2 3; 1 2 4; 2 3 4; 1 3 4;];

    case 2 % Cube
        V1=[-1;  1; 1; -1; -1;  1; 1; -1;];
        V2=[-1; -1; 1;  1; -1; -1; 1;  1;];
        V3=[-1; -1;-1; -1;  1;  1; 1;  1;];
        F= [1 2 3 4; 1 2 6 5; 2 3 7 6; 3 4 8 7; 4 1 5 8; 5 6 7 8;];

    case 3 % Octahedron
        V1=[-1;  1; 1; -1;  0;   0;];
        V2=[-1; -1; 1;  1;  0;   0;];
        V3=[ 0;   0; 0;  0; -1;  1;];
        F= [1 2 5; 2 3 5; 3 4 5; 4 1 5; 1 2 6; 2 3 6; 3 4 6; 4 1 6;];

    case 4 % Icosahedron
        V1=[0;0;0;0;-1;-1;1;1;-phi;phi;phi;-phi;];
        V2=[-1;-1;1;1;-phi;phi;phi;-phi;0;0;0;0;];
        V3=[-phi;phi;phi;-phi;0;0;0;0;-1;-1;1;1;];
        F= [1 4 9;1 5 9;1 8 5;1 8 10;1 10 4; 12 2 5; 12 2 3; 12 3 6; 12 6 9; 12 9 5; 11 7 10; 11 10 8; 11 8 2; 11 2 3; 11 3 7; 2 5 8; 10 4 7; 3 6 7; 6 7 4; 6 4 9; ];

    case 5 % Dodecahedron
        V1=[1;(1/phi);-phi;phi;-1;0;-phi;1;-1;-1;1;(1/phi);-1;0;0;-(1/phi);phi;-(1/phi);1;0;];
        V2=[1;0;-(1/phi);(1/phi);1;-phi;(1/phi);-1;1;-1;-1;0;-1;-phi;phi;0;-(1/phi);0;1;phi;];
        V3=[[1;phi;0;0;-1;-(1/phi);0;1;1;1;-1;-phi;-1;(1/phi);-(1/phi);phi;0;-phi;-1;(1/phi);]];
        F=[1,2,16,9,20;2,16,10,14,8;16,9,7,3,10;7 9 20 15 5;5,7,3,13,18;3,13,6,14,10;6,13,18,12,11;6,11,17,8,14;11,12,19,4,17;1,2,8,17,4;1,4,19,15,20;12,18,5,15,19];

    otherwise
        warning('False input for n')
end

[THETA,PHI,R]=cart2sph(V1,V2,V3);
R=r.*ones(size(V1(:,1)));
[V1,V2,V3]=sph2cart(THETA,PHI,R);
V=[V1 V2 V3];

author: Sable

repo: mcbench-benchmarks


text:
function v = r8vec_house_column ( n, a, k )

%*****************************************************************************80
%
%% R8VEC_HOUSE_COLUMN defines a Householder premultiplier that "packs" a column.
%
%  Discussion:
%
%    The routine returns a vector V that defines a Householder
%    premultiplier matrix H(V) that zeros out the subdiagonal entries of
%    column K of the matrix A.
%
%       H(V) = I - 2 * v * v'
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 April 2005
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the matrix A.
%
%    Input, real A(N), column K of the matrix A.
%
%    Input, integer K, the column of the matrix to be modified.
%
%    Output, real V(N), a vector of unit L2 norm which defines an
%    orthogonal Householder premultiplier matrix H with the property
%    that the K-th column of H*A is zero below the diagonal.
%
  v(1:n) = 0.0;

  if ( k < 1 | n <= k )
    return
  end

  s = sqrt ( sum ( a(k:n).^2 ) );

  if ( s == 0.0 )
    return
  end

  v(k) = a(k) + abs ( s ) * r8_sign ( a(k) );
  v(k+1:n) = a(k+1:n);

  v(k:n) = v(k:n) / sqrt ( v(k:n).^2 );

  return
end

author: johannesgerer

repo: jburkardt-m


%% NISwGSP-06_SienaCathedralLibrary
% %{
imfolder = 'images\NISwGSP-06_SienaCathedralLibrary';
im_n = 14;
imfile = cell(im_n,1);
for ii = 1:im_n
    imfile{ii} = sprintf('%s\\image%02d.jpg', imfolder, ii);
end

im = cell(im_n,1);
for ii = 1:im_n
    im{ii} = imread(imfile{ii});
end

imsize = zeros(im_n,3);

for ii = 1:im_n
    imsize(ii,:) = size(im{ii});
    if imsize(ii,1) > 720
        scale = 720/size(im{ii}, 1);
        im{ii} = imresize(im{ii}, scale);

        imsize(ii,:) = size(im{ii});
    end
end

mosaic = REW_mosaic( im, [], 0, 'equi', 0.02, imfolder );
%}


text:
function outputStruct = runAlignment(fileName,outputPath,startImage,finalImage,parameters)
%runAlignment runs the alignment and segmentation routines on a .avi file
%   and saves the output files to a directorty
%
%   Input variables:
%
%       fileName -> avi file to be analyzed
%       outputPath -> path to which files are saved
%       startImage -> first image in path to be analyzed
%       finalImage -> last image in path to be analyzed
%       parameters -> struct containing non-default choices for parameters
%
%
%   Output variable:
%
%       outputStruct -> struct containing found alignment variables
%
% (C) Gordon J. Berman, 2014
%     Princeton University

    if ~exist(outputPath,'dir')
        mkdir(outputPath);
    end

    if nargin < 3 || isempty(startImage)
        startImage = 1;
    end

    if nargin < 4 || isempty(finalImage)
        finalImage = [];
    end

    if nargin < 5 || isempty(parameters)
        parameters = [];
    end

    parameters = setRunParameters(parameters);

    setup_parpool(parameters.numProcessors)

    [Xs,Ys,angles,areas,~,framesToCheck,svdskipped,areanorm] = ...
        alignImages_Radon_parallel_avi(fileName,startImage,finalImage,...
                                        outputPath,parameters);

    %See alignImages_Radon_parallel_avi for definitions of these variables
    outputStruct.Xs = Xs;
    outputStruct.Ys = Ys;
    outputStruct.angles = angles;
    outputStruct.areas = areas;
    outputStruct.parameters = parameters;
    outputStruct.framesToCheck = framesToCheck;
    outputStruct.svdskipped = svdskipped;
    outputStruct.areanorm = areanorm;

    if parameters.numProcessors > 1 && parameters.closeMatPool
        close_parpool
    end

author: gordonberman

repo: MotionMapper


text:
function test_issue1334

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_selectdata ft_channelselection

load(dccnpath('/home/common/matlab/fieldtrip/data/test/test_issue1334.mat'));

%%

cfg = [];
cfg.channel={'megref'}; % reference data

dataRef = ft_preprocessing(cfg, data);
assert(numel(dataRef.label)==27);

%%
% see https://github.com/fieldtrip/fieldtrip/pull/1342#issuecomment-601265279

data = [];
data.label = {};

% this should return empty, but it gave an error
assert(isempty(ft_channelselection('MLO', data)));

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function [ alphas, betas, thetas, final_likelihood] = CCNF_training_bfgs(thresholdX, thresholdFun, x, y, alphas, betas, thetas, lambda_a, lambda_b, lambda_th, similarityFNs, sparsityFNs, varargin)
%CCNF_training_bfgs Performs CCNF training using BFGS (or LBFGS)

    if(sum(strcmp(varargin,'const')))
        ind = find(strcmp(varargin,'const')) + 1;
        const = varargin{ind};
    else
        const = false;
    end

    if(iscell(x))
        num_seqs = numel(x);

        x = cell2mat(x)';
        % add a bias term
        x =  cat(1, ones(1,size(x,2)), x);

        % If all of the sequences are of the same length can flatten them
        % to the same matrix
        if(const)

            y = cell2mat(y);
            y = reshape(y, numel(y)/num_seqs, num_seqs);
        end

    else
        % if not a cell it has already been flattened, and is constant
        % (most likely)
        num_seqs = varargin{find(strcmp(varargin, 'num_seqs'))+1};
    end

    % Should try a bunch of seed for initialising theta?
    if(sum(strcmp(varargin,'reinit')))
        ind = find(strcmp(varargin,'reinit')) + 1;
        reinit = varargin{ind};
    else
        reinit = false;
    end

    % It is possible to predefine the components B^(k) and C^(k) required
    % to compute B and and C terms and partial derivative (from equations
    % 30 and 31 in Appendix B), also can predefine yB^(k)y and yC^(k)y,
    % as they also do not change through the iterations
    % In constant case Precalc_Bs are same across the sequences, same for
    % PrecalcBsFlat, however yB^(k)y is defined per sequence
    if(sum(strcmp(varargin,'PrecalcBs')) && sum(strcmp(varargin,'PrecalcBsFlat'))...
             && sum(strcmp(varargin,'Precalc_yBy')))
        ind = find(strcmp(varargin,'PrecalcBs')) + 1;
        Precalc_Bs = varargin{ind};

        ind = find(strcmp(varargin,'PrecalcBsFlat')) + 1;
        Precalc_Bs_flat = varargin{ind};

        ind = find(strcmp(varargin,'Precalc_yBys')) + 1;
        Precalc_yBys = varargin{ind};
    else
        % if these are not provided calculate them
        [ ~, Precalc_Bs, Precalc_Bs_flat, Precalc_yBys ] = CalculateSimilarities( num_seqs, x, similarityFNs, sparsityFNs, y, const);
    end

    % Reinitialisation attempts to find a better starting point for the
    % model training (sometimes helps sometimes doesn't)
    if(reinit)

        rng(0);

        % By default try 200 times, but can override
        num_reinit = 200;

        if(sum(strcmp(varargin,'num_reinit')))
            num_reinit = varargin{find(strcmp(varargin,'num_reinit')) + 1};
        end

        thetas_good = cell(num_reinit, 1);
        lhoods = zeros(num_reinit, 1);
        for i=1:num_reinit
            initial_Theta = randInitializeWeights(size(thetas,2)-1, numel(alphas));
            lhoods(i) = LogLikelihoodCCNF(y, x, alphas, betas, initial_Theta, lambda_a, lambda_b, lambda_th, Precalc_Bs_flat, [], [], [], [], const, num_seqs);
            thetas_good{i} = initial_Theta;
        end
        [~,ind_max] = max(lhoods);
        thetas = thetas_good{ind_max};
    end

    params = [alphas; betas; thetas(:)];

    if(any(strcmp(varargin,'lbfgs')))
        options = optimset('Algorithm','interior-point','GradObj','on', 'Hessian', 'lbfgs', 'TolX', thresholdX, 'TolFun', thresholdFun, 'display', 'off');
    else
        options = optimset('Algorithm','interior-point','GradObj','on', 'Hessian', 'bfgs', 'TolX', thresholdX, 'TolFun', thresholdFun, 'display', 'off');
    end

    if(any(strcmp(varargin,'max_iter')))
        options.MaxIter = varargin{find(strcmp(varargin,'max_iter')) + 1};
    end

    objectiveFun = @(params)objectiveFunction(params, numel(alphas), numel(betas), size(thetas), lambda_a, lambda_b, lambda_th, Precalc_Bs, x, y, Precalc_yBys, Precalc_Bs_flat, const);

    lowerBound = [zeros(numel(alphas)+numel(betas),1); -Inf(numel(thetas),1)];

    upperBound = Inf(numel(params),1);
    params = fmincon(objectiveFun, params, [], [],[],[], lowerBound, upperBound, [], options);
    alphas = params(1:numel(alphas));
    betas = params(numel(alphas)+1:numel(alphas)+numel(betas));
    thetas = reshape(params(numel(alphas) + numel(betas) + 1:end), size(thetas));

    final_likelihood = LogLikelihoodCCNF(y, x, alphas, betas, thetas, lambda_a, lambda_b, lambda_th, Precalc_Bs_flat, [], [], [], [], const, num_seqs);

end

function [loss, gradient] = objectiveFunction(params, numAlpha, numBeta, sizeTheta, lambda_a, lambda_b, lambda_th, PrecalcQ2s, x, y, PrecalcYqDs, PrecalcQ2sFlat, const)

    alphas = params(1:numAlpha);
    betas = params(numAlpha+1:numAlpha+numBeta);
    thetas = reshape(params(numAlpha + numBeta + 1:end), sizeTheta);

    num_seqs = size(PrecalcYqDs,1);

    [gradient, SigmaInvs, CholDecomps, Sigmas, bs, all_x_resp] = gradientCCNF(params, numAlpha, numBeta, sizeTheta, lambda_a, lambda_b, lambda_th, PrecalcQ2s, x, y, PrecalcYqDs, PrecalcQ2sFlat, const, num_seqs);

    % as bfgs does gradient descent rather than ascent, negate the results
    gradient = -gradient;
    loss = -LogLikelihoodCCNF(y, x, alphas, betas, thetas, lambda_a, lambda_b, lambda_th, PrecalcQ2sFlat, SigmaInvs, CholDecomps, Sigmas, bs, const, num_seqs, all_x_resp);
end

author: TadasBaltrusaitis

repo: OpenFace


text:
% ir_denoise_admm1_test
% illustrate using "ADMM" for image denoising (aka Split Bregman algorithm)

if ~isvar('yi'), printm 'generate noisy image'
%	xt = single(imread('cameraman.tif')');
%	sig = 6; clim = [0 250];
	xt = ellipse_im(2^7);
	sig = 2^-1; clim = [0 9];

	snr = @(x) -20*log(norm(x(:)-xt(:)) / norm(xt));

	rng(7)
	yi = xt + sig * randn(size(xt));
	im plc 2 2
	im(1, xt, clim, 'True')
	im(2, yi, clim, 'Noisy')
	xlabelf('SNR = %4.1f dB', snr(yi))
end

if ~isvar('xs'), printm 'run admm'
	[xs, snrs] = ir_denoise_admm1(yi, 'beta', 2^-1, ...
		'stop_diff_tol', 1e-4, 'chat', 0, ...
		'isave', 'all', ...
		'userfun', @(x, iter) snr(x), ...
		'niter', 2^5, 'shrink', [], 'rho', 1);
	xh = xs(:,:,end);
end

if 1 % figures
%	im plc 1 3
%	im(1, xt, clim)
%	im(2, yi, clim)
	im(3, xh, clim, 'Denoised')
	xlabelf('SNR = %4.1f dB', snr(xh))

	im subplot 4
	iters = 0:numel(snrs)-1;
	if im
		plot(iters, snrs, '-o')
		axis([0 20 20 55])
		xlabel 'ADMM iteration'
		ylabel 'SNR (dB)'
		ytick([25 53])
	end
%	ir_savefig cw ir_denoise_admm1_test
end

if 0 % movie of iterates
	tmp = xs(:,:,[1:20 end]);
	niter = size(tmp,3);
	bar = size(tmp,2) / niter;
	for ii=1:niter
                tmp(1:3, floor([1:bar]+(ii-1)*bar), ii) = 8;
        end
	clf, im(tmp)
%	movie2(tmp, 'clim', clim, 'fps', 10)
end

author: JeffFessler

repo: mirt

save_path: github-repos/MATLAB/JeffFessler-mirt


text:
function cvx_tic

%CVX_TIC Resets the CVX timing functionality.
%
%   CVX collects the following timing information:
%   --- Elapsed time since CVX_TIC was last called. If CVX_TIC was never
%       called, this measures the time since CVX was first initialized.
%   --- Elapsed time spent between top-level CVX_BEGIN and CVX_END comamnds
%   --- Elapsed time spent within the top-level CVX_END itself. This
%       includes final problem extraction, presolving, and solving.
%   --- Elapsed time spent calling the numerical solver.
%   To retrieve the current totals for these numbers, type CVX_TOC.
%   CVX_TIC resets these numbers to zero.

global cvx___
cvx_global
if ~isempty( cvx___.problems ),
    error( 'CVX_TIC can only be called when no models are in construction.' );
end
cvx___.timers(1) = tic;
cvx___.timers(2:4) = 0;

% Copyright 2005-2016 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.

author: cvxr

repo: CVX

save_path: github-repos/MATLAB/cvxr-CVX


text:
%%*******************************************************************
%%  Read in a problem in SDPA sparse format.
%%
%%  [blk,At,C,b] = read_sdpa(fname)
%%
%%  Input: fname = name of the file containing SDP data in
%%                 SDPA foramt.
%%  Important: the data is assumed to contain only
%%             semidefinite and linear blocks.
%%*****************************************************************
%% SDPT3: version 4.0
%% Copyright (c) 1997 by
%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************

   function [blk,At,C,b] = read_sdpa(fname);

%%
%%  Open the file for input
%%
   compressed = 0;
   if exist(fname)
      fid = fopen(fname,'r');
   elseif exist([fname,'.Z']);
      compressed = 1;
      unix(['uncompress ',fname,'.Z']);
      fid = fopen(fname,'r');
   elseif exist([fname,'.gz']);
      compressed = 2;
      unix(['gunzip ',fname,'.gz']);
      fid = fopen(fname,'r');
   else
      fprintf('*** Problem not found, please specify the correct path or problem name. \n');
      blk = []; At = []; C = []; b = [];
      return;
   end
%%
%%  Clean up special characters and comments from the file
%%
   [datavec,count] = fscanf(fid,'%c');
   linefeeds = findstr(datavec,char(10));
   comment_chars = '*"=';
   cumidx = [];
   for i=1:length(comment_chars)
      idx = findstr(datavec,comment_chars(i));
      cumidx = [cumidx,idx];
   end
   for j=length(cumidx):-1:1
      if (cumidx(j)==1) | (strcmp(datavec(cumidx(j)-1),char(10)))
         datavec(cumidx(j):linefeeds(min(find(cumidx(j)<linefeeds))))='';
      else
         datavec(cumidx(j):linefeeds(min(find(cumidx(j)<linefeeds)))-1)='';
      end
   end
   special_chars = ',{}()';
   cumidx=[];
   for i=1:length(special_chars)
      idx = findstr(datavec,special_chars(i));
      cumidx = [cumidx,idx];
   end
   datavec(cumidx) = blanks(length(cumidx));
   clear linefeeds;
%%
%% Close the file
%%
   fclose('all');
   if compressed==1; unix(['compress ',fname]); end;
   if compressed==2; unix(['gzip ',fname]); end;
%%
%%  Next, read in basic problem size parameters.
%%
   datavec = sscanf(datavec,'%f');
   if size(datavec,1) < size(datavec,2); datavec = datavec'; end;
   m = datavec(1);
   numblk  = datavec(2);
   blksize = datavec(2+[1:numblk]);
   if size(blksize,1) > size(blksize,2); blksize = blksize'; end
%%
%% Get input  b.
%%
   idxstrt = 2+numblk;
   b = datavec(idxstrt+[1:m]);
   idxstrt = idxstrt+m;
   b = -b;
%%
%% Construct blk
%%
   deblksize = 100;
   spblkidxtmp = find( (blksize>1) & (blksize < deblksize) );
   spblkidxtmp = sort(spblkidxtmp);
   deblkidx = find( (blksize<=1) | (blksize >= deblksize) );
   denumblk = length(deblkidx);
   linblkidx = zeros(1,denumblk);
   for p = 1:denumblk
      n = blksize(deblkidx(p));
      if (n > 1);
         blk{p,1} = 's'; blk{p,2} = n;
         n2 = n*(n+1)/2;
         At{p,1} = sparse(n2,m);
         C{p,1} = sparse(n,n);
      else
         linblkidx(p) = p;
         blk{p,1} = 'l'; blk{p,2} = abs(n);
         At{p,1} = sparse(abs(n),m);
         C{p,1} = sparse(abs(n),1);
      end
   end
   if ~isempty(spblkidxtmp)
      maxnumblk = 200;
      spnumblk = ceil(length(spblkidxtmp)/maxnumblk);
      for q = 1:spnumblk
         if (q < spnumblk)
            spblkidxall{q} = spblkidxtmp([(q-1)*maxnumblk+1: q*maxnumblk]);
         else
            spblkidxall{q} = spblkidxtmp([(q-1)*maxnumblk+1: length(spblkidxtmp)]);
         end
         tmp = blksize(spblkidxall{q});
         blk{denumblk+q,1} = 's';
         blk{denumblk+q,2} = tmp;
         n2 = sum(tmp.*(tmp+1))/2;
         At{denumblk+q,1} = sparse(n2,m);
         C{denumblk+q,1} = sparse(sum(tmp),sum(tmp));
      end
   else
      spnumblk = 0;
   end
   linblkidx(denumblk+[1:spnumblk]) = zeros(1,spnumblk);
%%
%% Construct single blocks of A,C
%%
   len = length(datavec);
   Y = reshape(datavec(idxstrt+1:len),5,(len-idxstrt)/5)';
   clear datavec;
   Y = sortrows(Y,[1 2]);
   matidx = [0; find(diff(Y(:,1)) ~= 0); size(Y,1)];
%%
   for k = 1:length(matidx)-1
      idx = [matidx(k)+1 : matidx(k+1)];
      Ytmp  = Y(idx,1:5);
      matno = Ytmp(1,1);
      Ytmp2 = Ytmp(:,2);
      for p = 1:denumblk
         n  = blksize(deblkidx(p));
         idx = find(Ytmp2 == deblkidx(p));
         ii = Ytmp(idx,3); jj = Ytmp(idx,4); vv =Ytmp(idx,5);
         len = length(idx);
         if (n > 1)
            idxtmp = find(ii > jj);
            if ~isempty(idxtmp);
               tmp = jj(idxtmp);
               jj(idxtmp) = ii(idxtmp); ii(idxtmp) = tmp;
            end
            tmp = -sparse(ii,jj,vv,n,n);
            tmp = tmp + triu(tmp,1)';
         else
            tmp = -sparse(ii,ones(len,1),vv,abs(n),1);
         end
         if (matno == 0)
            C{p,1} = tmp;
         else
            if (n > 1)
               At{p,1}(:,matno) = svec(blk(p,:),tmp,1);
            else
               At{p,1}(:,matno) = tmp;
            end
         end
      end
   end
%%
%% Construct big sparse block of A,C
%%
if (spnumblk > 0)
   Y1 = Y(:,1);
   diffY1 = find(diff([-1; Y1; inf]));
   for kk = 1:length(diffY1)-1
      idx = [diffY1(kk) : diffY1(kk+1)-1];
      matno = Y1(diffY1(kk));
      Ytmp  = Y(idx,1:5);
      Ytmp2 = Ytmp(:,2);
      maxYtmp2  = Ytmp2(length(Ytmp2));
      minYtmp2  = Ytmp2(1);
      diffYtmp2 = Ytmp2(find(diff([-1; Ytmp2])));
      for q = 1:spnumblk
         spblkidx    = spblkidxall{q};
         maxspblkidx = spblkidx(length(spblkidx));
         minspblkidx = spblkidx(1);
         count = 0;
         if (minYtmp2 <= maxspblkidx) & (maxYtmp2 >= minspblkidx)
            tmpblksize = blksize(spblkidx);
            n = sum(tmpblksize);
            cumspblksize = [0 cumsum(tmpblksize)];
            n2 = sum(tmpblksize.*(tmpblksize+1))/2;
            idx = zeros(n2,1); offset = zeros(n2,1);
            for t = [1:length(diffYtmp2)]
  	       p = find(spblkidx == diffYtmp2(t));
               if ~isempty(p)
	          idxtmp = find(Ytmp2 == spblkidx(p));
                  len = length(idxtmp);
     	          idx(count+[1:len]) = idxtmp;
                  offset(count+[1:len]) = cumspblksize(p);
                  count = count + len;
               end
            end
            idx = idx(1:count); offset = offset(1:count);
            ii = Ytmp(idx,3)+offset; jj = Ytmp(idx,4)+offset; vv = Ytmp(idx,5);
            idxtmp = find(ii > jj);
            if ~isempty(idxtmp);
               tmp = jj(idxtmp);
               jj(idxtmp) = ii(idxtmp); ii(idxtmp) = tmp;
            end
	    idxeq = find(ii==jj);
            tmp = spconvert([ii jj -vv; jj ii -vv; n n 0]) ...
                  + spconvert([ii(idxeq) jj(idxeq) vv(idxeq); n n 0]);
            if (matno == 0)
               C{denumblk+q,1} = tmp;
            else
               At{denumblk+q,1}(:,matno) = svec(blk(denumblk+q,:),tmp,1);
            end
         end
      end
   end
end
%%
%% put all linear blocks together as a single linear block
%%
   idx = find(linblkidx);
   if (length(idx) > 1)
      sdpidx = find(linblkidx==0);
      blktmp = 0; Atmp = []; Ctmp = [];
      for k = 1:length(idx)
          tmp = linblkidx(idx(k));
          blktmp = blktmp+blk{tmp,2};
          Atmp = [Atmp; At{tmp}];
          Ctmp = [Ctmp; C{tmp}];
      end
      At = At(sdpidx); C = C(sdpidx); blk = blk(sdpidx,:);
      len = length(sdpidx);
      blk(2:len+1,:) = blk;
      blk{1,1} = 'l'; blk{1,2} = blktmp;
      At(2:len+1,1) = At; C(2:len+1,1) = C;
      At{1,1} = Atmp; C{1,1} = Ctmp;
   end
%%******************************************************************

author: yu-jiang

repo: radpbook

save_path: github-repos/MATLAB/yu-jiang-radpbook


text:
classdef TestDescriptorExtractor
    %TestDescriptorExtractor

    properties (Constant)
        im = fullfile(mexopencv.root(),'test','tsukuba_l.png');
        extractors = { ...
            ... % features2d (opencv)
            'BRISK', 'ORB', 'KAZE', 'AKAZE', ...
            ... % xfeatures2d (opencv_contrib)
            'SIFT', 'SURF', ...
            'BriefDescriptorExtractor', 'DAISY', 'FREAK', 'LATCH', 'LUCID', ...
            'VGG', 'BoostDesc'
        };
    end

    methods (Static)
        function test_compute_img
            img = cv.imread(TestDescriptorExtractor.im, ...
                'Grayscale',true, 'ReduceScale',2);
            kpts0 = cv.FAST(img, 'Threshold',20);
            for i=1:numel(TestDescriptorExtractor.extractors)
                try
                    obj = cv.DescriptorExtractor(...
                        TestDescriptorExtractor.extractors{i});
                catch ME
                    %TODO: check if opencv_contrib/xfeatures2d is available
                    %error('mexopencv:testskip', 'contrib');
                    continue;
                end
                typename = obj.typeid();
                ntype = obj.defaultNorm();

                % KAZE/AKAZE descriptors only work with their own detectors
                switch TestDescriptorExtractor.extractors{i}
                    case 'KAZE'
                        if ~mexopencv.isOctave()
                            kpts = detect(cv.KAZE(), img);
                        else
                            %HACK: https://savannah.gnu.org/bugs/index.php?54800
                            o = cv.KAZE();
                            kpts = o.detect(img);
                        end
                    case 'AKAZE'
                        if ~mexopencv.isOctave()
                            kpts = detect(cv.AKAZE(), img);
                        else
                            %HACK: https://savannah.gnu.org/bugs/index.php?54800
                            o = cv.AKAZE();
                            kpts = o.detect(img);
                        end
                    otherwise
                        kpts = kpts0;
                end

                % LUCID works on RGB images
                if strcmp(TestDescriptorExtractor.extractors{i}, 'LUCID')
                    im = cv.cvtColor(img, 'GRAY2RGB');
                else
                    im = img;
                end

                [desc, kpts2] = obj.compute(im, kpts);
                validateattributes(kpts2, {'struct'}, {'vector'});
                assert(all(ismember(fieldnames(kpts), fieldnames(kpts2))));
                validateattributes(desc, {obj.descriptorType()}, ...
                    {'size',[numel(kpts2) obj.descriptorSize()]});
            end
        end

        function test_compute_imgset
            img = cv.imread(TestDescriptorExtractor.im, ...
                'Grayscale',true, 'ReduceScale',2);
            kpts0 = cv.FAST(img, 'Threshold',50);
            for i=1:numel(TestDescriptorExtractor.extractors)
                try
                    obj = cv.DescriptorExtractor(...
                        TestDescriptorExtractor.extractors{i});
                catch ME
                    %TODO: check if opencv_contrib/xfeatures2d is available
                    %error('mexopencv:testskip', 'contrib');
                    continue;
                end

                % KAZE/AKAZE descriptors only work with their own detectors
                switch TestDescriptorExtractor.extractors{i}
                    case 'KAZE'
                        if ~mexopencv.isOctave()
                            kpts = detect(cv.KAZE(), img);
                        else
                            %HACK: https://savannah.gnu.org/bugs/index.php?54800
                            o = cv.KAZE();
                            kpts = o.detect(img);
                        end
                    case 'AKAZE'
                        if ~mexopencv.isOctave()
                            kpts = detect(cv.AKAZE(), img);
                        else
                            %HACK: https://savannah.gnu.org/bugs/index.php?54800
                            o = cv.AKAZE();
                            kpts = o.detect(img);
                        end
                    otherwise
                        kpts = kpts0;
                end
                kpts = {kpts, kpts};

                % LUCID works on RGB images
                if strcmp(TestDescriptorExtractor.extractors{i}, 'LUCID')
                    im = cv.cvtColor(img, 'GRAY2RGB');
                else
                    im = img;
                end
                imgs = {im, im};

                [descs, kpts] = obj.compute(imgs, kpts);
                validateattributes(kpts, {'cell'}, {'vector'});
                validateattributes(descs, {'cell'}, ...
                    {'vector', 'numel',numel(imgs)});
                cellfun(@(d,k) validateattributes(d, ...
                    {obj.descriptorType()}, ...
                    {'size',[numel(k) obj.descriptorSize()]}), descs, kpts);
            end
        end
    end

end

author: kyamagu

repo: mexopencv

save_path: github-repos/MATLAB/kyamagu-mexopencv


text:
%SUBSASGN Subscript assignment overload for mappings
%
% This routine enables constructs like W.DATA = {DATA1, DATA2},
% i.e. the direct change of mapping fields.

author: marianux

repo: ecg-kit

save_path: github-repos/MATLAB/marianux-ecg-kit


text:
function value = boothroyd_condition ( n )

%*****************************************************************************80
%
%% BOOTHROYD_CONDITION returns the L1 condition of the BOOTHROYD matrix.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 April 2015
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of A.
%
%    Output, real VALUE, the L1 condition.
%
  a_norm = 0.0;
  for j = 1 : n
    s = 0.0;
    for i = 1 : n

      s = s + r8_choose ( n + i - 1, i - 1 ) * r8_choose ( n - 1, n - j ) ...
        * n / ( i + j - 1 );

    end
    a_norm = max ( a_norm, s );
  end

  b_norm = a_norm;

  value = a_norm * b_norm;

  return
end


text:
function incircle()
    %   Matlab script to input initial parameters for circle0 routine
    %   in main Map Window
    % turned into function by Celso G Reyes 2017

    error('replaced by circle_select_dlg');
    ZG=ZmapGlobal.Data; % used by get_zmap_globals

    %                                                R. Zuniga, 6/94

    report_this_filefun();
    %
    if isempty(ZG.newcat),
        ZG.newcat = copy(ZG.primeCatalog);
    end   % verify whether to start with
    % original catalogue
    % make the interface for input
    %
    fig=figure('ToolBar','none');
    clf;
    cla;
    set(fig,'Name','Circle-Map Control Panel');
    %  set(gcf,'visible','off');
    set(gca,'visible','off');
    set(fig,'pos',[ 0.22  0.4 0.30 0.30])

    %
    freq_field1=uicontrol('Style','edit',...
        'Position',[.80 .70 .15 .10],...
        'Units','normalized','String',num2str(ZG.ni),...
        'callback',@callbackfun_001);

    freq_field2=uicontrol('Style','edit',...
        'Position',[.80 .55 .15 .10],...
        'Units','normalized','String',num2str(rad),...
        'callback',@callbackfun_002);

    freq_field3=uicontrol('Style','edit',...
        'Position',[.70 .40 .22 .10],...
        'Units','normalized','String',num2str(ya0,5),...
        'callback',@callbackfun_003);

    freq_field4=uicontrol('Style','edit',...
        'Position',[.70 .25 .22 .10],...
        'Units','normalized','String',num2str(xa0,6),...
        'callback',@callbackfun_004);

    close_button=uicontrol('Style','Pushbutton',...
        'Position',[.05 .85 .15 .1 ],...
        'Units','normalized','Callback',@(~,~)close(),'String','Cancel');

    button1=uicontrol('Style','Pushbutton',...
        'Position',[.35 .15 .3 .1 ],...
        'Units','normalized',...
        'callback',@callbackfun_005,...
        'String','Center by Cursor');

    button2=uicontrol('Style','Pushbutton',...
        'Position',[.10 .05 .2 .1 ],...
        'Units','normalized',...
        'callback',@callbackfun_006,...
        'String','Fix Radius');

    button3=uicontrol('Style','Pushbutton',...
        'Position',[.70 .05 .3 .1 ],...
        'Units','normalized',...
        'callback',@callbackfun_007,...
        'String','ni Closest Events');

    txt5 = text(...
        'Position',[0. 0.75 0 ],...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Number of events (ni):');

    txt4 = text(...
        'Position',[0. 0.58 0 ],...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Radius (km):');

    txt3 = text(...
        'Position',[0. 0.41 0 ],...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Latitude of center:');

    txt2 = text(...
        'Position',[0. 0.24 0 ],...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Longitude of center:');

    set(gcf,'visible','on');

    function callbackfun_001(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ZG.ni=str2double(mysrc.String);
    end

    function callbackfun_002(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        rad=str2double(mysrc.String);
    end

    function callbackfun_003(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ya0=str2double(mysrc.String);
        mysrc.String=num2str(ya0,6);
    end

    function callbackfun_004(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        xa0=str2double(mysrc.String);
        mysrc.String=num2str(xa0,6);
    end

    function callbackfun_005(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ic = 1;
        circle0;
    end

    function callbackfun_006(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ic = 2;
        circle0;
    end

    function callbackfun_007(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ic = 3;
        circle0;
    end
    function circle0()
        %   "circle0"  selects events by :
        %   the Ni closest earthquakes to the center
        %   the maximum radius of a circle.
        %   the center point can be interactively selected or fixed by given
        %   coordinates (as given by incircle).
        %   Resets ZG.newcat and ZG.newt2.     Operates on the map window on  "primeCatalog".
        %                                                  R.Z. 6/94
        %
        % turned into function by Celso G Reyes 2017

        ZG=ZmapGlobal.Data; % used by get_zmap_globals

        report_this_filefun();

        delete(findobj('Tag','plos1'));
        new = a;
        figure(mess);
        clf
        set(gca,'visible','off')

        if ic == 1 | ic == 0
            te = text(0.01,0.90,'\newlinePlease use the LEFT mouse button or the cursor to \newlineselect the center point. The coordinates of the center \newlinewill be displayed on the control window.\newline \newlineOperates on the main subset of the catalogue. \newlineEvents selected form the new subset to operate on (ZG.newcat).');
            set(te,'FontSize',12);

            % Input center of circle with mouse
            %
            axes(h1)

            [xa0,ya0]  = ginput(1);

            stri1 = [ 'Circle: ' num2str(xa0,6) '; ' num2str(ya0,6)];
            stri = stri1;
            pause(0.1)
            set(gcf,'Pointer','arrow')
            plot(xa0,ya0,'+c');
            incircle

        elseif ic == 2
            figure(map);
            axes(h1)
            ZG.newt2 = ZG.primeCatalog.selectRadius(ya0, xa0, rad,'kilometer');
            %
            % plot events on map as 'x':

            set(gca,'NextPlot','add')
            plot(ZG.newt2.Longitude,ZG.newt2.Latitude,'xk','Tag','plos1');
            set(gcf,'Pointer','arrow')

            stri1 = [ 'Circle: ' num2str(xa0,6) '; ' num2str(ya0,6) '; R = ' num2str(rad) ' km'];
            stri = stri1;
            ZG.newt2.sort('Date');
            ZG.newcat = ZG.newt2;                   % resets ZG.newcat and ZG.newt2
            ctp=CumTimePlot(ZG.newt2);
            ctp.plot();

            ic = 1;

        elseif ic == 3
            figure(map);
            axes(h1)
            %  calculate distance for each earthquake from center point
            [ZG.newt2, max_km] = ZG.primeCatalog.selectClosestEvents(ya0, xa0, [], ni);
            messtext = ['Radius of selected Circle: ' num2str(max_km)  ' km' ];
            disp(messtext)

            % plot events on map as 'x':

            set(gca,'NextPlot','add')
            plot(ZG.newt2.Longitude,ZG.newt2.Latitude,'xk','Tag','plos1');
            set(gcf,'Pointer','arrow')

            ZG.newcat = ZG.newt2;                   % resets ZG.newcat

            stri1 = [ 'Circle: ' num2str(xa0,6) '; ' num2str(ya0,6)];
            stri = stri1;
            ctp=CumTimePlot(ZG.newt2);
            ctp.plot();

            ic = 1;

        end      % if ic
    end

end

author: CelsoReyes


text:
function [ZWD] = saast_wet(T, H, h)

% SYNTAX:
%   [ZWD] = saast_wet(T, H, h);
%
% INPUT:
%   T = air temperature
%   H = humidity
%   h = orthometric height
%
% OUTPUT:
%   ZWD = Zenith Wet Delay
%
% DESCRIPTION:
%   Zenith Wet Delay (ZWD) computation by Saastamoinen model.

%--- * --. --- --. .--. ... * ---------------------------------------------
%               ___ ___ ___
%     __ _ ___ / __| _ | __|
%    / _` / _ \ (_ |  _|__ \
%    \__, \___/\___|_| |___/
%    |___/                    v 1.0RC1
%
%--------------------------------------------------------------------------
%  Copyright (C) 2021 Geomatics Research & Development srl (GReD)
%  Written by:
%  Contributors:     ...
%  A list of all the historical goGPS contributors is in CREDITS.nfo
%--------------------------------------------------------------------------
%
%   This program is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%--------------------------------------------------------------------------
% 01100111 01101111 01000111 01010000 01010011
%--------------------------------------------------------------------------

% Convert C -> K
T = T + 273.15;

%height correction
H = H * exp(-0.0006396 * h);

% Convert humidity
H = H./100;

c = -37.2465 + 0.213166 * T - 2.56908 * (10^-4) * (T.^2);
e = H .* exp(c);

%ZWD (Saastamoinen model)
ZWD = 0.0022768 * (((1255 ./ T) + 0.05) .* e);

author: goGPS-Project


text:
function geometry_test0803 ()

%*****************************************************************************80
%
%% TEST0803 tests POLYGON_INRAD_DATA_2D, POLYGON_OUTRAD_DATA_2D, POLYGON_SIDE_DATA_2D;
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 March 2009
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST0803\n' );
  fprintf ( 1, '  For a REGULAR polygon in 2D:\n' );
  fprintf ( 1, '  the inradius, outradius and side are related.\n' );
  fprintf ( 1, '  POLYGON_INRAD_DATA_2D uses the inradius;\n' );
  fprintf ( 1, '  POLYGON_OUTRAD_DATA_2D uses the inradius;\n' );
  fprintf ( 1, '  POLYGON_SIDE_DATA_2D uses the inradius;\n' );

  for n = 3 : 5

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Number of polygonal sides = %d\n', n );

    side = 1.0;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Assuming SIDE = %f\n', side );

    [ area, radin, radout ] = polygon_side_data_2d ( n, side );

    fprintf ( 1, '    AREA =   %f\n', area );
    fprintf ( 1, '    RADIN =  %f\n', radin );
    fprintf ( 1, '    RADOUT = %f\n', radout );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Assuming RADIN = %f\n', radin );

    [ area, radout, side ] = polygon_inrad_data_2d ( n, radin );

    fprintf ( 1, '    AREA =   %f\n', area );
    fprintf ( 1, '    RADOUT = %f\n', radout );
    fprintf ( 1, '    SIDE =   %f\n', side );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Assuming RADOUT = %f\n', radout );

    [ area, radin, side ] = polygon_outrad_data_2d ( n, radout );

    fprintf ( 1, '    AREA =   %f\n', area );
    fprintf ( 1, '    RADIN =  %f\n', radin );
    fprintf ( 1, '    SIDE =   %f\n', side );

  end

  return
end


text:
function cache_dir = resolve_cache_dir(model, model_dir, opts)
%
% This file is part of the code that implements the following ICCV2015 accepted paper:
% title: "Object detection via a multi-region & semantic segmentation-aware CNN model"
% authors: Spyros Gidaris, Nikos Komodakis
% institution: Universite Paris Est, Ecole des Ponts ParisTech
% Technical report: http://arxiv.org/abs/1505.01749
% code: https://github.com/gidariss/mrcnn-object-detection
%
%
% AUTORIGHTS
% --------------------------------------------------------
% Copyright (c) 2015 Spyros Gidaris
%
% "Object detection via a multi-region & semantic segmentation-aware CNN model"
% Technical report: http://arxiv.org/abs/1505.01749
% Licensed under The MIT License [see LICENSE for details]
% ---------------------------------------------------------

cache_dir_base = fullfile(model_dir, 'cache_dir');
mkdir_if_missing(cache_dir_base);
if ~isempty(opts.cache_dir)
    assert(isempty(opts.cache_dir_name));
    cache_dir = opts.cache_dir;
elseif ~isempty(opts.cache_dir_name)
    assert(isempty(opts.cache_dir));
    cache_dir = fullfile(cache_dir_base, opts.cache_dir_name);
else
    if opts.use_detection_svms
        cache_dir = fullfile(model_dir, model.svm_cache_dir(2:end));
    else
        cache_dir = fullfile(model_dir, 'softmax');
    end
end
mkdir_if_missing(cache_dir);
end

author: gidariss

repo: mrcnn-object-detection


text:
function varargout = ackley(x)
%ACKLEY Ackley's function

if nargin == 0
    varargout{1} = [-8,-8];     % LB
    varargout{2} = [2,2];       % UB
    varargout{3} = [0,20];      % Zlim
    varargout{4} = [-26.5,60];  % view
    varargout{5} = [0,0];       % xmin
    varargout{6} = 'Ackley function';    % name
    varargout{7} = [-6,-5];     % default x0
    return;
end
    varargout{1} = -20 * exp(-0.2 * sqrt( sum(x .* x, 2)/ 2)) ...
        - exp(sum(cos(2*pi*x),2) / 2) ...
        + 20 + 2.7182818284590452353602874713526625;
    varargout{2} = [];
end

author: lacerbi

repo: optimviz

save_path: github-repos/MATLAB/lacerbi-optimviz


text:
function varargout = panel_raw_shortcuts(varargin)
% PANEL_RAW_SHORTCUTS: Edit keyboard shortcuts for the RAW Viewer.

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2012-2021

eval(macro_method);
end

%% ===== CREATE PANEL =====
function [bstPanelNew, panelName] = CreatePanel() %#ok<DEFNU>
    % Java initializations
    import java.awt.*;
    import javax.swing.*;
    panelName = 'EditShortcuts';
    % Get current shortcuts
    RawViewerOptions = bst_get('RawViewerOptions');

    % Create main panel
    jPanelNew = gui_component('Panel');
    jPanelNew.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    % PANEL: left panel (list of available categories)
    jPanelShort = gui_river([8,8], [0,10,15,10], 'Keyboard shortcuts');
    % Font size for the options
    TEXT_DIM = java_scaled('dimension', 50, 20);
    % Create 9 text boxes
    jText = javaArray('javax.swing.JTextField', 9);
    jRadioSimple = javaArray('javax.swing.JRadioButton', 9);
    jRadioExt = javaArray('javax.swing.JRadioButton', 9);
    jRadioPage = javaArray('javax.swing.JRadioButton', 9);
    jTextMin = javaArray('javax.swing.JTextField', 9);
    jTextMax = javaArray('javax.swing.JTextField', 9);
    jLabelSep = javaArray('javax.swing.JLabel', 9);
    jLabelUnits = javaArray('javax.swing.JLabel', 9);
    for i = 1:9
        % Event name
        gui_component('label', jPanelShort, 'br', sprintf('Shortcut %d: ', i));
        jText(i) = gui_component('text', jPanelShort, 'tab hfill', RawViewerOptions.Shortcuts{i,2}, {java_scaled('dimension', 120,22)});
        % Event type
        jRadioSimple(i) = gui_component('radio', jPanelShort, 'tab hfill', 'Simple', [], [], @UpdatePanel);
        jRadioPage(i) = gui_component('radio', jPanelShort, 'tab hfill', 'Full page', [], [], @UpdatePanel);
        jRadioExt(i) = gui_component('radio', jPanelShort, 'tab hfill', 'Extended', [], [], @UpdatePanel);
        jButtonGroup = ButtonGroup();
        jButtonGroup.add(jRadioSimple(i));
        jButtonGroup.add(jRadioPage(i));
        jButtonGroup.add(jRadioExt(i));
        switch (RawViewerOptions.Shortcuts{i,3})
            case 'simple',    jRadioSimple(i).setSelected(1);
            case 'page',      jRadioPage(i).setSelected(1);
            case 'extended',  jRadioExt(i).setSelected(1);
        end
        % Default epoch time
        if (length(RawViewerOptions.Shortcuts{i,4}) < 2)
            RawViewerOptions.Shortcuts{i,4} = [-0.1, 0.1];
        end
        % Epoch time
        jTextMin(i) = gui_component('texttime', jPanelShort, [], ' ', TEXT_DIM,[],[]);
        jLabelSep(i) = gui_component('label',    jPanelShort, [], '-');
        jTextMax(i) = gui_component('texttime', jPanelShort, [], ' ', TEXT_DIM,[],[]);
        jLabelUnits(i) = gui_component('label', jPanelShort, [], 'ms');
        gui_validate_text(jTextMin(i), [], jTextMax(i), {-100000, 100000, 100}, 'ms', 0, RawViewerOptions.Shortcuts{i,4}(1), []);
        gui_validate_text(jTextMax(i), jTextMin(i), [], {-100000, 100000, 100}, 'ms', 0, RawViewerOptions.Shortcuts{i,4}(2), []);
    end
    jPanelNew.add(jPanelShort, BorderLayout.CENTER);
    % Update selected options
    UpdatePanel();

    % PANEL: Selections buttons
    jPanelValidation = gui_river([10 0], [10 10 0 10]);
        % Cancel
        gui_component('button', jPanelValidation, 'br right', 'Cancel', [], [], @ButtonCancel_Callback);
        % Save
        gui_component('button', jPanelValidation, '', 'Save', [], [], @ButtonSave_Callback);
    jPanelNew.add(jPanelValidation, BorderLayout.SOUTH);

    % Create the BstPanel object that is returned by the function
    % => constructor BstPanel(jHandle, panelName, sControls)
    bstPanelNew = BstPanel(panelName, ...
                           jPanelNew, ...
                           struct('jText',        jText, ...
                                  'jRadioSimple', jRadioSimple, ...
                                  'jRadioPage',   jRadioPage, ...
                                  'jRadioExt',    jRadioExt, ...
                                  'jTextMin',     jTextMin, ...
                                  'jTextMax',     jTextMax));

%% =================================================================================
%  === CONTROLS CALLBACKS  =========================================================
%  =================================================================================
    %% ===== UPDATE PANEL =====
    function UpdatePanel(varargin)
        for k = 1:9
            isExt = jRadioExt(k).isSelected();
            jTextMin(k).setEnabled(isExt);
            jTextMax(k).setEnabled(isExt);
            jLabelSep(k).setEnabled(isExt);
            jLabelUnits(k).setEnabled(isExt);
        end
    end

    %% ===== VALIDATION BUTTONS =====
    function ButtonCancel_Callback(varargin)
        % Close panel without saving
        gui_hide(panelName);
    end
    function ButtonSave_Callback(varargin)
        % Save changes
        isOk = SaveShortcuts();
        if ~isOk
            return;
        end
        % Close panel
        gui_hide(panelName);
    end
end

%% =================================================================================
%  === INTERFACE CALLBACKS =========================================================
%  =================================================================================
%% ===== SAVE SHORTCUTS =====
function isOk = SaveShortcuts()
    isOk = 0;
    % Get current shortcuts
    RawViewerOptions = bst_get('RawViewerOptions');
    % Get panel controls handles
    ctrl = bst_get('PanelControls', 'EditShortcuts');
    % Get all the shortcuts
    for i = 1:9
        RawViewerOptions.Shortcuts{i,2} = strtrim(char(ctrl.jText(i).getText()));
        if ctrl.jRadioSimple(i).isSelected()
            RawViewerOptions.Shortcuts{i,3} = 'simple';
        elseif ctrl.jRadioPage(i).isSelected()
            RawViewerOptions.Shortcuts{i,3} = 'page';
        elseif ctrl.jRadioExt(i).isSelected()
            RawViewerOptions.Shortcuts{i,3} = 'extended';
            RawViewerOptions.Shortcuts{i,4} = [str2double(ctrl.jTextMin(i).getText()), str2double(ctrl.jTextMax(i).getText())] ./ 1000;
        end
    end
    % Reject shortcuts with same name and different types (simple/extended)
    evtNames = unique(lower(RawViewerOptions.Shortcuts(:,2)));
    if (length(evtNames) < 9)
        for i = 1:length(evtNames)
            iShortcut = find(strcmpi(RawViewerOptions.Shortcuts(:,2), evtNames{i}));
            if (length(iShortcut) > 1) && any(~strcmpi(RawViewerOptions.Shortcuts(iShortcut,3), RawViewerOptions.Shortcuts(iShortcut(1),3)))
                bst_error(['Event "' evtNames{i} '" cannot be linked to multiple shortcuts of different types.'], 'Save shortcuts', 0);
                return;
            end
        end
    end
    % Save shortcuts
    bst_set('RawViewerOptions', RawViewerOptions);
    % Return success
    isOk = 1;
end

author: brainstorm-tools


text:
function stroud_test41 ( )

%*****************************************************************************80
%
%% TEST41 tests TRIANGLE_UNIT_SET and TRIANGLE_SUB.
%
%  Discussion:
%
%    Break up the triangle into NSUB**2 equal subtriangles.  Approximate
%    the integral over the triangle by the sum of the integrals over each
%    subtriangle.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    06 April 2009
%
%  Author:
%
%    John Burkardt
%
  global FUNC_2D_INDEX;

  num = function_2d_num ( );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST41\n' );
  fprintf ( 1, '  TRIANGLE_UNIT_SET sets up a quadrature rule\n' );
  fprintf ( 1, '    on a triangle.\n' );
  fprintf ( 1, '  TRIANGLE_SUB applies it to subtriangles of an\n' );
  fprintf ( 1, '    arbitrary triangle.\n' );
  fprintf ( 1, '\n' );
%
%  Set the location of the triangle.
%
  xval(1) = 0.0;
  yval(1) = 0.0;

  xval(2) = 0.0;
  yval(2) = 1.0;

  xval(3) = 1.0;
  yval(3) = 0.0;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Triangle vertices:\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  %8f  %8f\n', xval(1), yval(1) );
  fprintf ( 1, '  %8f  %8f\n', xval(2), yval(2) );
  fprintf ( 1, '  %8f  %8f\n', xval(3), yval(3) );
%
%  Get the quadrature abscissas and weights for a unit triangle.
%
  rule = 3;
  order = triangle_unit_size ( rule );

  [ xtab, ytab, weight ] = triangle_unit_set ( rule, order );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Using unit triangle quadrature rule %d\n', rule );
  fprintf ( 1, '  Rule order = %d\n', order );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Function Nsub  Result\n' );
  fprintf ( 1, '\n' );
%
%  Set the function.
%
  for i = 1 : num

    FUNC_2D_INDEX = i;
%
%  Try an increasing number of subdivisions.
%
    for nsub = 1 : 5

      result = triangle_sub ( ...
        'function_2d', xval, yval, nsub, order, xtab, ytab, weight );

      fname = function_2d_name ( i );

      fprintf ( 1, '  %s  %2d  %12f\n', fname, nsub, result );

    end

  end

  return
end


text:
function [J] = Btu2J(Btu)
% Convert energy or work from British thermal units to joules.
% Chad A. Greene 2012
J = Btu*1055.0559 ;


text:
function [out, datadir] = readthisdataSplit(pathname, filename, range,nbatch)
% [out, datadir] = readthisdataSplit(pathname, filename, range,nbatch)
% Reads data. Splits reading so that it reades nbatch number of images at a time. It is faster (bug in dip_image?)
% Default for readimg data from Rainer and nbatch = 100;
% Example: [out, datadir] = readthisdataSplit('QD565_1',[],[0 100], 10);

if ~exist('nbatch', 'var')
    nbatch = 100;
end

if ~exist('pathname', 'var')
    pathname = '.';
end
if isempty(pathname)
    pathname = '.';
end
if ~exist('filename','var')
        filename = 'img_000000*__000.tif';
end
if isempty(filename)
    filename = 'img_000000*__000.tif';
end

if ~exist('range','var')
    range = [0,999];
end

nimages = range(2)-range(1)+1;
nsteps = ceil(nimages / nbatch);

% out = newim(sizeim(1),sizeim(2), nimages);
out = [];

for ii=0:nsteps-1
    rangetmp(1) = range(1)+ii*nbatch;
    r = rangetmp(1)+nbatch-1;
    rangetmp(2) = min(r,range(2));

    [outtmp, datadir] = readthisdata(pathname, filename, rangetmp);
%     out(:,:,rangetmp(1):rangetmp(2)) = outtmp;
    out = cat(3,out, outtmp);
end

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function varargout = splitting(on_off)
%SPLITTING   CHEBFUN splitting option.
%   SPLITTING('ON') allows the CHEBFUN constructor to split the interval by a
%   process of automatic subdivision and edge detection. This option is
%   recommended when working with functions with singularities or jumps.
%
%   SPLITTING('OFF') disables this kind of automatic splitting, and is
%   recommended for working with functions that are complicated but still
%   smooth. Even with splitting off, breakpoints may still be introduced by the
%   MAX, MIN, ABS, CEIL, FLOOR, and ROUND commands. One may switch freely back
%   and forth between the two modes during a Chebfun computation.
%
%   SPLITSTATE = SPLITTING(...) will return the current state splitting option
%   (as a string), before any changes are applied.
%
%   SPLITTING by itself, displays a string detailing the current splitting
%   state. By default, this is OFF.
%
% See also CHEBFUNPREF.

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

if ( nargout > 0 && nargin == 0 )
    % Return current splitting state:
    splitState = chebfunpref().splitting;

elseif ( nargin == 0 )
    % Display splitting state:
    switch ( chebfunpref().splitting )
        case 1
            disp('SPLITTING is currently ON.')
        case 0
            disp('SPLITTING is currently OFF.')
    end

else
    % Throw a warning:
    warning('CHEBFUN:splitting:deprecated', ...
        ['The syntax ''splitting on'' is deprecated.\n', ...
        'Please see CHEBFUNPREF documentation for further details.']);
    % But only throw it once:
    warning('off', 'CHEBFUN:splitting:deprecated');

    if ( nargout > 0 )
        splitState = chebfunpref().splitting;
    end

    if ( strcmpi(on_off, 'on') )
        chebfunpref.setDefaults('splitting', true);

    elseif strcmpi(on_off, 'off')
        chebfunpref.setDefaults('splitting', false);

    else
        error('CHEBFUN:splitting:UnknownOption',...
            'Unknown splitting option: only ON and OFF are valid options.')
    end

end

if ( nargout > 0 )
    onOffStr = {'off', 'on'};
    varargout{1} = onOffStr{splitState+1};
end

end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
%% getSubPaths
% Below is a demonstration of the features of the |getSubPaths| function

%%
clear; close all; clc;

%% Syntax
% |[pathNames]=getSubPaths(pathName);|

%% Description
% UNDOCUMENTED
%% Examples
%
%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>
%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
function varargout = process_segment_cat12( varargin )
% PROCESS_SEGMENT_CAT12: Run the segmentation of a T1 MRI with SPM12/CAT12.
%
% USAGE:     OutputFiles = process_segment_cat12('Run',     sProcess, sInputs)
%         [isOk, errMsg] = process_segment_cat12('Compute', iSubject, iAnatomy=[default], nVertices, isSphReg, isExtraMaps, isInteractive)
%                          process_segment_cat12('ComputeInteractive', iSubject, iAnatomy)

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c) University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2019-2023

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Segment MRI with CAT12';
    sProcess.Category    = 'Custom';
    sProcess.SubGroup    = {'Import', 'Import anatomy'};
    sProcess.Index       = 31;
    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/SegCAT12';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'import'};
    sProcess.OutputTypes = {'import'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 0;
    % Option: Subject name
    sProcess.options.subjectname.Comment = 'Subject name:';
    sProcess.options.subjectname.Type    = 'subjectname';
    sProcess.options.subjectname.Value   = '';
    % Option: Number of vertices
    sProcess.options.nvertices.Comment = 'Number of vertices (cortex): ';
    sProcess.options.nvertices.Type    = 'value';
    sProcess.options.nvertices.Value   = {15000, '', 0};
    % Option: TPM atlas
    SelectOptions = {...
        '', ...                            % Filename
        'Nifti1', ...                      % FileFormat
        'open', ...                        % Dialog type: {open,save}
        'Select TPM atlas...', ...         % Window title
        'ImportAnat', ...                  % LastUsedDir: {ImportData,ImportChannel,ImportAnat,ExportChannel,ExportData,ExportAnat,ExportProtocol,ExportImage,ExportScript}
        'single', ...                      % Selection mode: {single,multiple}
        'files', ...                       % Selection mode: {files,dirs,files_and_dirs}
        {{'.nii','.gz'}, 'MRI: NIfTI-1 (*.nii;*.nii.gz)', 'Nifti1'}, ... % Get all the available file formats
        'MriIn'};                          % DefaultFormats: {ChannelIn,DataIn,DipolesIn,EventsIn,MriIn,NoiseCovIn,ResultsIn,SspIn,SurfaceIn,TimefreqIn
    sProcess.options.tpmnii.Comment = 'TPM atlas: ';
    sProcess.options.tpmnii.Type    = 'filename';
    sProcess.options.tpmnii.Value   = SelectOptions;
    % Option: Spherical registration
    sProcess.options.sphreg.Comment = 'Use spherical registration
Required for atlases, group analysis and thickness maps';
    sProcess.options.sphreg.Type    = 'checkbox';
    sProcess.options.sphreg.Value   = 1;
    % Option: Volume atlases
    sProcess.options.vol.Comment = 'Compute volume parcellations';
    sProcess.options.vol.Type    = 'checkbox';
    sProcess.options.vol.Value   = 1;
    % Option: Import extra map
    sProcess.options.extramaps.Comment = 'Import additional cortical maps
Cortical thickness, gyrification index, sulcal depth';
    sProcess.options.extramaps.Type    = 'checkbox';
    sProcess.options.extramaps.Value   = 0;
    % Option: Compute cerebellum surfaces
    sProcess.options.cerebellum.Comment = 'Compute cerebellum surfaces [Experimental]';
    sProcess.options.cerebellum.Type    = 'checkbox';
    sProcess.options.cerebellum.Value   = 0;
    sProcess.options.cerebellum.Hidden  = 1;
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    Comment = sProcess.Comment;
end

%% ===== RUN =====
function OutputFiles = Run(sProcess, sInputs) %#ok<DEFNU>
    OutputFiles = {};
    % Number of vertices
    nVertices = sProcess.options.nvertices.Value{1};
    if isempty(nVertices) || (nVertices < 50)
        bst_report('Error', sProcess, [], 'Invalid number of vertices.');
        return
    end
    % Spherical registration?
    if isfield(sProcess.options, 'sphreg') && isfield(sProcess.options.sphreg, 'Value') && ~isempty(sProcess.options.sphreg.Value)
        isSphReg = sProcess.options.sphreg.Value;
    else
        isSphReg = 1;
    end
    % Volume atlases?
    if isfield(sProcess.options, 'vol') && isfield(sProcess.options.vol, 'Value') && ~isempty(sProcess.options.vol.Value)
        isVolumeAtlases = sProcess.options.vol.Value;
    else
        isVolumeAtlases = 0;
    end
    % Cerebellum?
    if isfield(sProcess.options, 'cerebellum') && isfield(sProcess.options.cerebellum, 'Value') && ~isempty(sProcess.options.cerebellum.Value)
        isCerebellum = sProcess.options.cerebellum.Value;
    else
        isCerebellum = 1;
    end
    % TPM atlas
    if isfield(sProcess.options, 'tpmnii') && isfield(sProcess.options.tpmnii, 'Value') && ~isempty(sProcess.options.tpmnii.Value) && ~isempty(sProcess.options.tpmnii.Value{1})
        TpmNii = sProcess.options.tpmnii.Value{1};
    else
        TpmNii = bst_get('SpmTpmAtlas');
    end
    % Thickness maps
    if isfield(sProcess.options, 'extramaps') && isfield(sProcess.options.extramaps, 'Value') && ~isempty(sProcess.options.extramaps.Value)
        isExtraMaps = sProcess.options.extramaps.Value;
    else
        isExtraMaps = 0;
    end
    % Get subject name
    SubjectName = file_standardize(sProcess.options.subjectname.Value);
    if isempty(SubjectName)
        bst_report('Error', sProcess, [], 'Subject name is empty.');
        return;
    end
    % Get subject
    [sSubject, iSubject] = bst_get('Subject', SubjectName);
    if isempty(iSubject)
        bst_report('Error', sProcess, [], ['Subject "' SubjectName '" does not exist.']);
        return
    end
    % Call processing function
    [isOk, errMsg] = Compute(iSubject, [], nVertices, 0, TpmNii, isSphReg, isVolumeAtlases, isExtraMaps, isCerebellum);
    % Handling errors
    if ~isOk
        bst_report('Error', sProcess, [], errMsg);
    elseif ~isempty(errMsg)
        bst_report('Warning', sProcess, [], errMsg);
    end
    % Return an empty structure
    OutputFiles = {'import'};
end

%% ===== COMPUTE CAT12 SEGMENTATION =====
function [isOk, errMsg] = Compute(iSubject, iAnatomy, nVertices, isInteractive, TpmNii, isSphReg, isVolumeAtlases, isExtraMaps, isCerebellum)
    errMsg = '';
    isOk = 0;
    % Initialize SPM12+CAT12
    [isInstalled, errMsg, PlugCat] = bst_plugin('Install', 'cat12', isInteractive, 1728);
    if ~isInstalled
        return;
    end
    bst_plugin('SetProgressLogo', 'cat12');
    % Check if SPM is in the path
    if ~exist('spm_jobman', 'file')
        errMsg = 'SPM must be in the Matlab path to use this feature.';
        return;
    end
    % Check if CAT12 is in the path
    if ~exist('cat12', 'file')
        errMsg = 'SPM subfolders must be in the Matlab path to use this feature (missing: spm12/toolbox/cat12).';
        return;
    end
    % Check CAT version
    [catName, catVer] = cat_version;
    if isempty(catVer)
        errMsg = 'Cannot identify CAT12 version: please re-install it.';
        return;
    end
    catVer = str2num(catVer);
    if (catVer < 1728)
        errMsg = [...
            'Please update CAT12.' 10 ...
            ' - Version of CAT installed on this computer: ' num2str(catVer) 10 ...
            ' - Minimum version of CAT supported by Brainstorm: 1728' 10 ...
            ' - http://www.neuro.uni-jena.de/cat/index.html#DOWNLOAD'];
        return;
    end
    % Get default TPM.nii template
    if isempty(TpmNii)
        TpmNii = bst_get('SpmTpmAtlas');
    end
    if isempty(TpmNii) || ~file_exist(TpmNii)
        error('Missing file TPM.nii');
    end

    % ===== GET SUBJECT =====
    % Get subject
    [sSubject, iSubject] = bst_get('Subject', iSubject);
    if isempty(sSubject)
        errMsg = 'Subject does not exist.';
        return
    end
    % Check if a MRI is available for the subject
    if isempty(sSubject.Anatomy)
        errMsg = ['No MRI available for subject "' sSubject.Name '".'];
        return
    end
    % Get default MRI if not specified
    if isempty(iAnatomy)
        iAnatomy = sSubject.iAnatomy;
    end

    % ===== DELETE EXISTING SURFACES =====
    % Confirm with user that the existing surfaces will be removed
    if isInteractive && ~isempty(sSubject.Surface)
        isDel = java_dialog('confirm', ['Warning: There are already surfaces in this subject.' 10 ...
            'Running CAT12 will remove all the existing surfaces.' 10 10 ...
            'Delete the existing files?' 10 10], 'CAT12 segmentation');
        if ~isDel
            errMsg = 'Process aborted by user.';
            return;
        end
    end

    % ===== VERIFY FIDUCIALS IN MRI =====
    % Load MRI file
    T1FileBst = sSubject.Anatomy(iAnatomy).FileName;
    sMri = in_mri_bst(T1FileBst);
    % If the SCS transformation is not defined: compute MNI transformation to get a default one
    if isempty(sMri) || ~isfield(sMri, 'SCS') || ~isfield(sMri.SCS, 'NAS') || ~isfield(sMri.SCS, 'LPA') || ~isfield(sMri.SCS, 'RPA') || (length(sMri.SCS.NAS)~=3) || (length(sMri.SCS.LPA)~=3) || (length(sMri.SCS.RPA)~=3) || ~isfield(sMri.SCS, 'R') || isempty(sMri.SCS.R) || ~isfield(sMri.SCS, 'T') || isempty(sMri.SCS.T)
        % Issue warning
        errMsg = 'Missing NAS/LPA/RPA: Computing the MNI normalization to get default positions.';
        % Compute MNI normalization
        [sMri, errNorm] = bst_normalize_mni(T1FileBst);
        % Handle errors
        if ~isempty(errNorm)
            errMsg = [errMsg 10 'Error trying to compute the MNI normalization: ' 10 errNorm 10 ...
                'Missing fiducials: the surfaces cannot be aligned with the MRI.'];
        end
    end
    % A vox2ras matrix must be present in the MRI for running CAT12
    sMri = mri_add_world(T1FileBst, sMri);

    % ===== SAVE MRI AS NII =====
    bst_progress('text', 'Saving temporary files...');
    % Create temporay folder for CAT12 output
    TmpDir = bst_get('BrainstormTmpDir', 0, 'cat12');
    % Save MRI in .nii format
    subjid = strrep(sSubject.Name, '@', '');
    NiiFile = bst_fullfile(TmpDir, [subjid, '.nii']);
    out_mri_nii(sMri, NiiFile);
    % If a "world transformation" was not available in the MRI in the database, it was set to a default when saving to .nii
    % Let's reload this file to get the transformation matrix, it will be used when importing the results
    if ~isfield(sMri, 'InitTransf') || isempty(sMri.InitTransf) || isempty(find(strcmpi(sMri.InitTransf(:,1), 'vox2ras')))
        % Load again the file, with the default vox2ras transformation
        [tmp, vox2ras] = in_mri_nii(NiiFile, 0, 0, 0);
        % Prepare the history of transformations
        if ~isfield(sMri, 'InitTransf') || isempty(sMri.InitTransf)
            sMri.InitTransf = cell(0,2);
        end
        % Add this transformation in the MRI
        sMri.InitTransf(end+1,[1 2]) = {'vox2ras', vox2ras};
        % Save modification on hard drive
        bst_save(file_fullpath(T1FileBst), sMri, 'v7');
    end

    % ===== INITIALIZE SPM+CAT =====
    % Switch to CAT12 expert mode
    cat12('expert');
    % Hide CAT12 figures
    set([findall(0, 'Type', 'Figure', 'Tag', 'Interactive'), ...
         findall(0, 'Type', 'Figure', 'Tag', 'CAT'), ...
         findall(0, 'Type', 'Figure', 'Tag', 'Graphics')], 'Visible', 'off');
    % Initialize SPM job manager
    spm_jobman('initcfg');

    % ===== CALL CAT12 SEGMENTATION =====
    bst_progress('text', 'Starting SPM batch...    (see command window)');
    % Create SPM batch
    matlabbatch{1}.spm.tools.cat.estwrite.data = {NiiFile};
    matlabbatch{1}.spm.tools.cat.estwrite.nproc = 0;                % Blocking call to CAT12
    matlabbatch{1}.spm.tools.cat.estwrite.opts.tpm = {TpmNii};      % User-defined TPM atlas
    matlabbatch{1}.spm.tools.cat.estwrite.output.bias.warped = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.GM.native   = 1;   % GM tissue maps
    matlabbatch{1}.spm.tools.cat.estwrite.output.GM.warped   = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.GM.mod      = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.GM.dartel   = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.WM.native   = 1;   % WM tissue maps
    matlabbatch{1}.spm.tools.cat.estwrite.output.WM.warped   = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.WM.mod      = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.WM.dartel   = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.native = 1;   % Tissue classes 4-6 to create own TPMs
    matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.warped = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.mod    = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.TPMC.dartel = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.native  = 1;   % CSF tissue maps
    matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.warped  = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.mod     = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.CSF.dartel  = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.label.native = 1;  % Label: background=0, CSF=1, GM=2, WM=3, WMH=4
    matlabbatch{1}.spm.tools.cat.estwrite.output.label.warped = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.label.dartel = 0;
    matlabbatch{1}.spm.tools.cat.estwrite.output.labelnative = 1;  % Confirmed useful by CGaser in CAT12.8
    % CAT12.8 now saves everything in ICBM152NLinAsym09 space: we can use directly the MNI deformation fields
    matlabbatch{1}.spm.tools.cat.estwrite.output.warps = [1 1];  % Non-linear MNI normalization deformation fields: [forward inverse]
    % Volume atlases
    if isVolumeAtlases
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.neuromorphometrics = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.lpba40             = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.cobra              = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.aal3               = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.anatomy3           = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.ibsr               = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.julichbrain        = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.hammers            = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.mori               = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.thalamus           = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_100Parcels_17Networks_order = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_200Parcels_17Networks_order = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_400Parcels_17Networks_order = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.Schaefer2018_600Parcels_17Networks_order = 1;
        matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.native = 1;  % Save atlases in native space
        matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.warped = 0;
        matlabbatch{1}.spm.tools.cat.estwrite.output.atlas.dartel = 0;
    else
        % No ROIs
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.noROI = struct([]);   % CGaser comment: Correct syntax to disable ROI processing for volumes
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.neuromorphometrics = 0;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.lpba40             = 0;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.cobra              = 0;
        matlabbatch{1}.spm.tools.cat.estwrite.output.ROImenu.atlases.hammers            = 0;
    end
    % Spherical registration (much slower)
    if isSphReg && ~isCerebellum    % CGaser comment: Cerebellum extraction is experimental, not to be used routinely
        matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 1;   % 1: lh+rh
    elseif isSphReg && isCerebellum
        matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 2;   % 2: lh+rh+cerebellum
    elseif ~isSphReg && ~isCerebellum
        matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 5;   % 5: lh+rh (fast, no registration, quick review only)
    elseif ~isSphReg && isCerebellum
        matlabbatch{1}.spm.tools.cat.estwrite.output.surface = 6;   % 6: lh+rh+cerebellum  (fast, no registration, quick review only)
    end
    % Extract additional surface parameters: Cortical thickness, Gyrification index, Sulcal depth (can't be imported for default anatomy)
    if isExtraMaps && (iSubject > 0)
        matlabbatch{1}.spm.tools.cat.estwrite.output.surf_measures = 1;  % Thickness maps
        % Separate SPM process (second element in the batch)
        matlabbatch{2}.spm.tools.cat.stools.surfextract.data_surf(1) = cfg_dep('CAT12: Segmentation (current release): Left Central Surface', substruct('.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}, '.','val', '{}',{1}), substruct('()',{1}, '.','lhcentral', '()',{':'}));
        matlabbatch{2}.spm.tools.cat.stools.surfextract.GI = 1;     % Gyrification index
        matlabbatch{2}.spm.tools.cat.stools.surfextract.SD = 1;     % Sulcal depth
        matlabbatch{2}.spm.tools.cat.stools.surfextract.nproc = 0;  % Blocking call to CAT12
    end

    % Run batch
    spm_jobman('run',matlabbatch);
    % Close CAT12 figures
    close([findall(0, 'Type', 'Figure', 'Tag', 'Interactive'), ...
           findall(0, 'Type', 'Figure', 'Tag', 'CAT')]);

    % ===== PROJECT ATLASES =====
    TessLhFile = file_find(TmpDir, 'lh.central.*.gii', 2);
    if exist('cat_surf_map_atlas', 'file') && file_exist(TessLhFile)
        % Get CAT12 dir
        CatDir = bst_fullfile(PlugCat.Path, PlugCat.SubFolder);
        % List of parcellations to project
        AnnotLhFiles = file_find(bst_fullfile(CatDir, 'atlases_surfaces'), 'lh.*.annot', 2, 0);
        % Import atlases (cat_surf_map_atlas calls both hemispheres at once)
        for iAnnot = 1:length(AnnotLhFiles)
            [fAnnotPath, fAnnotName] = bst_fileparts(AnnotLhFiles{iAnnot});
            bst_progress('text', ['Interpolating atlas: ' fAnnotName '...']);
            cat_surf_map_atlas(TessLhFile, AnnotLhFiles{iAnnot});
        end
    end

    % ===== IMPORT OUTPUT FOLDER =====
    % Import CAT12 anatomy folder
    isKeepMri = 1;
    errMsg = import_anatomy_cat(iSubject, TmpDir, nVertices, 0, [], isExtraMaps, isKeepMri);
    if ~isempty(errMsg)
        return;
    end
    % Delete temporary folder
    file_delete(TmpDir, 1, 1);
    % Remove logo
    bst_plugin('SetProgressLogo', []);
    % Return success
    isOk = 1;
end

%% ===== COMPUTE/INTERACTIVE =====
function ComputeInteractive(iSubject, iAnatomy) %#ok<DEFNU>
    % Get inputs
    if (nargin < 2) || isempty(iAnatomy)
        iAnatomy = [];
    end
    % Ask for number of vertices
    nVertices = java_dialog('input', 'Number of vertices on the cortex surface:', 'CAT12 segmentation', [], '15000');
    if isempty(nVertices)
        return
    end
    nVertices = str2double(nVertices);
    % Ask for volume atlases
    [isVolumeAtlases, isCancel] = java_dialog('confirm', ['Compute anatomical parcellations?' 10 10 ...
        ' - AAL3', 10 ...
        ' - Anatomy v3', 10 ...
        ' - CoBrALab' 10 ...
        ' - Hammers' 10 ...
        ' - IBSR', 10 ...
        ' - JulichBrain v2', 10 ...
        ' - LPBA40' 10 ...
        ' - Mori', 10 ...
        ' - Neuromorphometrics' 10 ...
        ' - Schaefer2018', 10 10], 'CAT12 MRI segmentation');
    if isCancel
        return
    end
    % Ask for cortical maps (not for default anatomy)
    if (iSubject > 0)
        [isExtraMaps, isCancel] = java_dialog('confirm', ['Compute cortical maps?' 10 10 ...
            ' - Cortical thickness', 10 ...
            ' - Gyrification index', 10 ...
            ' - Sulcal depth', 10 10], 'CAT12 MRI segmentation');
        if isCancel
            return
        end
    else
        isExtraMaps = 0;
    end
    % Open progress bar
    bst_progress('start', 'CAT12', 'CAT12 MRI segmentation...');
    % Run CAT12
    TpmNii = bst_get('SpmTpmAtlas');
    isInteractive = 1;
    isSphReg = 1;
    isCerebellum = 0;
    [isOk, errMsg] = Compute(iSubject, iAnatomy, nVertices, isInteractive, TpmNii, isSphReg, isVolumeAtlases, isExtraMaps, isCerebellum);
    % Error handling
    if ~isOk
        bst_error(errMsg, 'CAT12 MRI segmentation', 0);
    elseif ~isempty(errMsg)
        java_dialog('msgbox', ['Warning: ' errMsg]);
    end
    % Close progress bar
    bst_progress('stop');
end


text:
function varargout = maxDeltaVInputGUI(varargin)
% MAXDELTAVINPUTGUI MATLAB code for maxDeltaVInputGUI.fig
%      MAXDELTAVINPUTGUI, by itself, creates a new MAXDELTAVINPUTGUI or raises the existing
%      singleton*.
%
%      H = MAXDELTAVINPUTGUI returns the handle to a new MAXDELTAVINPUTGUI or the handle to
%      the existing singleton*.
%
%      MAXDELTAVINPUTGUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MAXDELTAVINPUTGUI.M with the given input arguments.
%
%      MAXDELTAVINPUTGUI('Property','Value',...) creates a new MAXDELTAVINPUTGUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before maxDeltaVInputGUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to maxDeltaVInputGUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help maxDeltaVInputGUI

% Last Modified by GUIDE v2.5 26-Jun-2013 19:03:07

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @maxDeltaVInputGUI_OpeningFcn, ...
                   'gui_OutputFcn',  @maxDeltaVInputGUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before maxDeltaVInputGUI is made visible.
function maxDeltaVInputGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to maxDeltaVInputGUI (see VARARGIN)

% Choose default command line output for maxDeltaVInputGUI
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

%Possible fix for people with display issues.
checkForCharUnitsInGUI(hObject);

options = varargin{1};
deltaVStrName = deltaVTypeEnum(options.quant2opt);
dvTypeStr =  {'Delta-V To Optimize:', deltaVStrName};
set(handles.dvtypelabel, 'String', dvTypeStr);

% UIWAIT makes maxDeltaVInputGUI wait for user response (see UIRESUME)
uiwait(handles.maxDeltaVInputGUI);

% --- Outputs from this function are returned to the command line.
function [maxDV, varargout] = maxDeltaVInputGUI_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
try
varargout{1} = handles.output;
maxDV = str2double(get(handles.maxDVText,'String'));
close(hObject);
catch
    varargout{1} = -1;
    maxDV = 0.0;
end

function maxDVText_Callback(hObject, eventdata, handles)
% hObject    handle to maxDVText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of maxDVText as text
%        str2double(get(hObject,'String')) returns contents of maxDVText as a double
newInput = attemptStrEval(get(hObject,'String'));
set(hObject, 'String', newInput);

% --- Executes during object creation, after setting all properties.
function maxDVText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to maxDVText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in okayButton.
function okayButton_Callback(hObject, eventdata, handles)
% hObject    handle to okayButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
errMsg = {};

maxDV = str2double(get(handles.maxDVText,'String'));
enteredStr = get(handles.maxDVText,'String');
numberName = 'Maximum delta-v';
lb = 0.01;
ub = 100;
isInt = false;
errMsg = validateNumber(maxDV, numberName, lb, ub, isInt, errMsg, enteredStr);

if(isempty(errMsg))
    uiresume(handles.maxDeltaVInputGUI);
else
    msgbox(errMsg,'Errors were found in maximum delta-v inputs','error');
end

author: Arrowstar

repo: ksptot

save_path: github-repos/MATLAB/Arrowstar-ksptot


text:
%FEACACHE FEATool data cache.
%
%   [ OUT ] = FEACACHE( VAR, SLOT, VAL ) Cache and retrieve data. VAR
%   designates a cache variable name, an integer SLOT retrieves, or
%   puts the argument VAL to that slot (cache{VAR,SLOT} = VAL).
%
%   Output OUT is either a requested VAR/SLOT pair, or with not input
%   arguments a struct ST_CACHE of cached expressions used by the
%   feacache, and evalexpr0, parseexpr, subcoef, and symvarbe.
%
%   FEACACHE(0) Clears the cache.

% Copyright 2013-2022 Precise Simulation, Ltd.

author: precise-simulation

repo: featool-multiphysics