classdef m_01_collie1_1p_1s < MARRMoT_model
% Class for hydrologic conceptual model: Collie River 1 (traditional bucket model)

% Copyright (C) 2019, 2021 Wouter J.M. Knoben, Luca Trotter
% This file is part of the Modular Assessment of Rainfall-Runoff Models
% Toolbox (MARRMoT).
% MARRMoT is a free software (GNU GPL v3) and distributed WITHOUT ANY
% WARRANTY. See <https://www.gnu.org/licenses/> for details.

% Model reference
% Jothityangkoon, C., M. Sivapalan, and D. Farmer (2001), Process controls
% of water balance variability in a large semi-arid catchment: downward
% approach to hydrological model development. Journal of Hydrology, 254,
% 174198. doi: 10.1016/S0022-1694(01)497-6.

    properties
        % model-specific attributes
    end
    methods

        % creator method
        function obj = m_01_collie1_1p_1s()
            obj.numStores = 1;                                             % number of model stores
            obj.numFluxes = 2;                                             % number of model fluxes
            obj.numParams = 1;

            obj.JacobPattern  = [1];                                       % Jacobian matrix of model store ODEs

            obj.parRanges = [1   , 2000];      % Smax [mm]

            obj.StoreNames = {"S1"};                                       % Names for the stores
            obj.FluxNames  = {"ea", "qse"};                                % Names for the fluxes

            obj.FluxGroups.Ea = 1;                                         % Index or indices of fluxes to add to Actual ET
            obj.FluxGroups.Q  = 2;                                         % Index or indices of fluxes to add to Streamflow
        end

        % INITialisation function
        function obj = init(obj)
        end

        % MODEL_FUN are the model governing equations in state-space formulation
        function [dS, fluxes] = model_fun(obj, S)
            % parameters
            theta   = obj.theta;
            S1max   = theta(1);                         % Maximum soil moisture storage [mm]

            % delta_t
            delta_t = obj.delta_t;

            % stores
            S1 = S(1);

            % climate input
            t = obj.t;                             % this time step
            climate_in = obj.input_climate(t,:);   % climate at this step
            P  = climate_in(1);
            Ep = climate_in(2);

            % fluxes functions
            flux_ea   = evap_7(S1, S1max, Ep, delta_t);
            flux_qse  = saturation_1(P,S1,S1max);

            % stores ODEs
            dS1 = P - flux_ea  - flux_qse;

            % outputs
            dS = [dS1];
            fluxes = [flux_ea, flux_qse];
        end

        % STEP runs at the end of every timestep
        function obj = step(obj)
        end
    end
end


function [A,B,C,G] = ospls(X,Y,nhidden,opts)

% OSPLS  Sparse orthogonalized partial least squares where the elastic
% net is implemented using either a native implementation or the glmnet package
%
% The native implementation supports arbitrary alpha (ridge penalty) and
% lambda (lasso penalty) values and supports a coupling matrix for alpha to
% implement smoothing. It requires a fixed value for lambda.
%
% The glmnet implementation is much faster but uses alpha to mix between
% ridge and lasso while lambda determines that amount of regularization. It
% also does not support a coupling matrix. It learns the optimal lambda
% using inner cross-validation.
%
% X: ninput x nsamples input data matrix
% Y: noutput x nsamples output data matrix
% nhidden: number of components [1]
% opts: glmnet parameters
%
% A: noutput x nhidden weight matrix
% B: ninput x nhidden weight matrix
% C: 1 x nhidden bias vector
% G: output parameters for debugging purposes

% Parse inputs

if nargin < 3,
    nhidden = 1;
end

ninput = size(X,1);
noutput = size(Y,1);
nsamples = size(X,2);

if nhidden > 1,

    G = cell(1,nhidden);

    % Run nhidden times sequentially

    R = Y;
    A = zeros(noutput,nhidden);
    B = zeros(ninput,nhidden);
    C = zeros(1,nhidden);
    for i=1:nhidden,
        [A(:,i),B(:,i),C(i),G{i}] = ospls(X,R,1,opts);
        if i < nhidden,    % deflate
            Z = B(:,i)'*X + C(i); % hidden activations
            R = R - A(:,i)*Z; % Y activations after deflation
        end
        if opts.verbose,
            fprintf('done %d out of %d; proportion selected %g\n',i,nhidden,nnz(B(:,i))/ninput);
        end
    end
else

    % Run for a single hidden unit

    B = zeros(ninput,1);
    C = 0;
    iter = 0;
    maxiter = 100;
    tol = nhidden*noutput*(1e-10);

    % Initialize A to first principal component of Y

    optseig.disp = 0;
    if nsamples < noutput,
        [d1,d2] = eigs(Y'*Y,[],1,'LM',optseig);
        A = Y*d1;
        A = A/sqrt(A'*A);
    else
        [A,d2] = eigs(Y*Y',[],1,'LM',optseig);
    end

    glmnetopts = glmnetSet;

    g = ft_mv_glmnet('method',opts.method,'family','gaussian','validator',ft_mv_crossvalidator('nfolds',5,'metric','correlation'));

    FN = fieldnames(glmnetopts);
    for c=1:length(FN)
      g.(FN{c}) = glmnetopts.(FN{c});
    end
    FN = fieldnames(opts);
    for c=1:length(FN)
      if isfield(glmnetopts,FN{c})
        g.(FN{c}) = opts.(FN{c});
      end
    end

    Aold = A;
    while iter < maxiter,

        if opts.verbose > 1,
            fprintf('   now starting iteration %d\n',iter+1);
        end

        Z = A'*Y;    % reconstruct Z given A from output Y

        % Use glmnet elastic net code to fit reconstructed Z given input X
        try

          f = g.train(X',Z');

          B = f.weights(1:(end-1));
          C = f.weights(end);

        catch

          % we end up in the catch block when the number of included
          % variables pmax has been exceeded; this should not happen
          warning(lasterr);

          B = zeros(ninput,1);
          C = 0;

          % this implies that deflation has no effect anymore

        end

        Z = B'*X + C;   % reconstruct Z given B and C

        % Find optimal A under constraint A'*A = 1

        Syz = Y*Z'/nsamples;
        denom = sqrt(Syz'*Syz);
        if denom,
            A = Syz/denom;
        else
            A = Aold;
        end
        if any(isnan(A(:))),    % check...
            error('nans!!!\n');
        end

        if sumsqr(A - Aold) < tol,
            if opts.verbose > 1,
                fprintf('   done!!\n',iter+1);
            end
		    iter = maxiter;
        else
	        iter = iter + 1;
            Aold = A;
        end
    end

    G = f;

end


classdef RWMOP34 < PROBLEM
% <multi> <real> <constrained>
% Synchronous pptimal pulse-width modulation of 11-level inverters

%------------------------------- Reference --------------------------------
% A. Kumar, G. Wu, M. Ali, Q. Luo, R. Mallipeddi, P. Suganthan, and S. Das,
% A benchmark-suite of real-world constrained multi-objective optimization
% problems and some baseline results, Swarm and Evolutionary Computation,
% 2021, 67: 100961.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        %% Initialization
        function Setting(obj)
            obj.M        = 2;
            obj.D        = 30;
            obj.lower    = zeros(1,30);
            obj.upper    = 90*ones(1,30);
            obj.encoding = ones(1,obj.D);
        end
        %% Evaluate multiple solutions
        function Population = Evaluation(obj,varargin)
            x = varargin{1};
            m = 0.3333;
            s = [1,-1,1,1,1,-1,-1,-1,1,1,1,1,-1,-1,1,-1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1];
            k = [5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,53,55,59,61,65,67,71,73,77,79,83,85,91,95,97];
            % Objective function
            for i = 1 : size(x,1)
                su = 0;
                for j = 1 : 31
                    su2 = 0;
                    for l = 1 : size(x,2)
                        su2 = su2 + s(l).*cos(k(j).*x(i,l)*pi/180);
                    end
                    su = su + su2.^2./k(j).^4;
                end
                f(i,1) = (su).^0.5./(sum(1./k.^4)).^0.5;
            end
            f(:,2) = (sum(s.*cos(x*pi/180),2)-m).^2;
            % Constraints
            for i = 1 : size(x,2)-1
                g(:,i) = x(:,i)-x(:,i+1)+1e-6;
            end
            Population = SOLUTION(varargin{1},f,g,varargin{2:end});
            obj.FE     = obj.FE + length(Population);
        end
        %% Generate a point for hypervolume calculation
        function R = GetOptimum(obj,~)
            R = [6.1063821e-01   1.1108847e-01];
        end
    end
end


function [gx,dgdx] = g_odds(x,P,u,in)

x = x-max(x);
gx = (exp(x)+0)./sum(exp(x)+0);

n = size(x,1);
I = eye(n);
dgdx = (I - gx*ones(1,n))*diag(gx);


% Copyright (C) 1993-2014, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com

%%begin

% Our SLAM system requires a number of components:
% * a vehicle
% * a map that defines the positions of some known landmarks in the world
% * a sensor, a range-bearing sensor in this case
% * a SLAM filter

% Creating the vehicle.  First we define the covariance of the vehicles's odometry
% which reports distance travelled and change in heading angle

V = diag([0.005, 0.5*pi/180].^2);

% then use this to create an instance of a Vehicle class
veh = Vehicle(V);

% and then add a "driver" to move it between random waypoints in a square
% region with dimensions from -10 to +10

veh.add_driver( RandomPath(10) );

% Creating the map.  The map covers a square region with dimensions from
% -10 to +10 and contains 20 randomly placed landmarks
map = Map(20, 10);

% Creating the sensor.  We firstly define the covariance of the sensor measurements
% which report distance and bearing angle
W = diag([0.1, 1*pi/180].^2);

% and then use this to create an instance of the Sensor class.
sensor = RangeBearingSensor(veh, map, W, 'animate');
% Note that the sensor is mounted on the moving robot and observes the features
% in the world so it is connected to the already created Vehicle and Map objects.

% Create the filter.  First we need to determine the initial covariance of the
% vehicle, this is our uncertainty about its pose (x, y, theta)
P0 = diag([0.005, 0.005, 0.001].^2);

% Now we create an instance of the EKF filter class
ekf = EKF(veh, V, P0, sensor, W, []);
% and connect it to the vehicle and the sensor and give estimates of the vehicle
% and sensor covariance (we never know this is practice).

% Now we will run the filter for 1000 time steps.  At each step the vehicle
% moves, reports its odometry and the sensor measurements and the filter updates
% its estimate of the vehicle's pose
ekf.run(1000);
% all the results of the simulation are stored within the EKF object

% First let's plot the map
clf; map.plot()
% and then overlay the path actually taken by the vehicle
veh.plot_xy('b');
% and then overlay the path estimated by the filter
ekf.plot_xy('r');
% which we see are pretty close

% Now let's plot the error in estimating the pose
ekf.plot_error()
% and this is overlaid with the estimated covariance of the error.

% Remember that the SLAM filter has not only estimated the robot's pose, it has
% simultaneously estimated the positions of the landmarks as well.  How well did it
% do at that task?  We will show the landmarks in the map again
map.plot();
% and this time overlay the estimated landmark (with a +) and the 3sigma
% uncertainty bounds as green ellipses
ekf.plot_map(3,'g');


classdef NSGAIIconflict < ALGORITHM
% <many> <real/integer/label/binary/permutation>
% NSGA-II with conflict-based partitioning strategy
% NS     ---  2 --- Number of subspaces
% cycles --- 10 --- Number of cycles

%------------------------------- Reference --------------------------------
% A. L. Jaimes, C. A. Coello Coello, H. Aguirre, and K. Tanaka, Objective
% space partitioning using conflict information for solving many-objective
% problems, Information Sciences, 2014, 268: 305-327.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Parameter setting
            [NS,cycles] = Algorithm.ParameterSet(2,10);
            Gc          = ceil(Problem.maxFE/Problem.N/cycles);

            %% Generate random population
            Psi        = {1:Problem.M};
            Population = Problem.Initialization();
            [~,FrontNo,CrowdDis] = EnvironmentalSelection(Population,Problem.N,Psi);

            %% Optimization
            phase = true;
            while Algorithm.NotTerminated(Population)
                MatingPool = TournamentSelection(2,Problem.N,FrontNo,-CrowdDis);
                Offspring  = OperatorGA(Problem,Population(MatingPool));
                [Population,FrontNo,CrowdDis] = EnvironmentalSelection([Population,Offspring],Problem.N,Psi);
                if ~phase && mod(ceil(Problem.FE/Problem.N),Gc)/Gc < 0.3
                    % Change to the approximation phase
                    Psi   = {1:Problem.M};
                    phase = true;
                elseif phase && mod(ceil(Problem.FE/Problem.N),Gc)/Gc >= 0.3
                    % Change to the partitioning phase
                    Psi   = ConflictPartition(Population.objs,NS);
                    phase = false;
                end
            end
        end
    end
end


function [cum_ret, cumprod_ret, daily_ret, daily_portfolio, exp_ret] ...
    = cornk_run(fid, data, K, L, pc, tc, opts)
% This program simulates the CORN-K algorithm. This definition is slightly
% different from the algorithm in LHG11, as we define a percentage of all
% experts here, rather than a specified number of experts. NOTE.
%
% function [cum_ret, cumprod_ret, daily_ret, daily_portfolio, exp_ret] ...
%    = cornk_run(fid, data, K, L, pc, tc, opts)
%
% cum_ret: a number representing the final cumulative wealth.
% cumprod_ret: cumulative return until each trading period
% daily_ret: individual returns for each trading period
% daily_portfolio: individual portfolio for each trading period
% exp_ret: experts' return
%
% data: market sequence vectors
% fid: handle for write log file
% K: maximum window size
% L: splits into L parts, in each K, useless in CORN-U, L=1
% pc: top-k percentage of K*L
% tc: transaction cost rate parameter
% opts: option parameter for behvaioral control
%
% Example: [cum_ret, cumprod_ret, daily_ret, daily_portfolio, exp_ret] ...
%            = cornk_run(fid, data, K, L, pc, tc, opts);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This file is part of OLPS: http://OLPS.stevenhoi.org/
% Original authors: Bin LI, Steven C.H. Hoi
% Contributors:
% Change log:
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[n, m] = size(data);

% Variables for return, start with uniform weight
% cumprod_ret = 1;
% daily_ret = 1;
% weight = ones(nStocks, 1)/nStocks;

cum_ret = 1;
cumprod_ret = ones(n, 1);
daily_ret = ones(n, 1);
day_weight = ones(m, 1)/m;  %#ok<*NASGU>
day_weight_o = zeros(m, 1);
daily_portfolio = zeros(n, m);

% Variables for expert
exp_ret = ones(K, L);
exp_w = ones(K*L, m)/m;

% print file head
fprintf(fid, '-------------------------------------\n');
if (~opts.quiet_mode)
    fprintf(fid, 'Parameters [K=%d, L=%d, pc=%f, tc=%f\n]', K, L, pc, tc);
    fprintf(fid, 'day\t Daily Return\t Total return\n');
end
if (opts.progress)
	progress = waitbar(0,'Executing Algorithm...');
end
for t = 1:1:n,
    % Calculate t's portfolio
    if (t >=2)
        [day_weight, exp_w] ...
            = cornk_kernel(data(1:t-1, :), K, L, pc, exp_ret, exp_w);
    end

    % Normalize the constraint
    day_weight = day_weight./sum(day_weight);
    daily_portfolio(t, :) = day_weight';

    % Cal t's return and total return
    daily_ret(t, 1) = (data(t, :)*day_weight)*(1-tc/2*sum(abs(day_weight-day_weight_o)));
    cum_ret = cum_ret * daily_ret(t, 1);
    cumprod_ret(t, 1) = cum_ret;

    % Normalize the portfolio
    day_weight_o = day_weight.*data(t, :)'/daily_ret(t, 1);

    % Cal t's experts return
    for k=1:K,
        for l=1:L,
            exp_ret(k, l) = exp_ret(k, l)*data(t, :)*exp_w((k-1)*L+l, :)';
        end
    end

    % Debug information
    fprintf(fid, '%d\t%f\t%f\n', t, daily_ret(t, 1), cum_ret);
    if (~opts.quiet_mode)
        if (~mod(t, opts.display_interval)),
            fprintf(1, '%d\t%f\t%f\n', t, daily_ret(t, 1), cum_ret);
        end
    end
    if (opts.progress)
		if mod(t, 50) == 0
			waitbar((t/n));
		end
	end
end

% Debug Information
fprintf(fid, 'CORN topK (K:%d, L:%d, pc:%.2f, tc:%.4f), Final return: %.2f\n', ...
    K, L, pc, tc, cum_ret);

fprintf(fid, 'CORN topK, Experts return:\n');
fprintf(fid, '%f\t', exp_ret);
fprintf(fid, '\n');
fprintf(fid, '-------------------------------------\n');

fprintf(1, 'CORN topK (K:%d, L:%d, pc:%.2f, tc:%.4f), Final return: %.2f\n', ...
    K, L, pc, tc, cum_ret);
if (~opts.quiet_mode)
    fprintf(1, 'CORN topK, Experts return:\n');
    fprintf(1, '%f\t', exp_ret);
    fprintf(1, '\n');
end
fprintf(fid, '-------------------------------------\n');
	if (opts.progress)
		close(progress);
	end
end


%kkstats 'Compute Statistics of Data Object'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros kstats.pane file
%
% Parameters:
% InputFile: i 'Input ', required: 'Input object'
% InputFile: igate 'Gating Input', optional: 'Gating input data object'
% OutputFile: f 'ASCII Output ', optional: 'Formatted ASCII output file'
% OutputFile: o 'Binary Output', optional: 'Binary output statistics file'
% Toggle: whole 'Whole Data Set', default: 0: 'compute single set of statistics for entire data set'
% Toggle: w 'Width ', default: 0: 'include width in processing unit'
% Toggle: h 'Height ', default: 0: 'include height in processing unit'
% Toggle: d 'Depth ', default: 0: 'include depth in processing unit'
% Toggle: t 'Time ', default: 0: 'include time in processing unit'
% Toggle: e 'Element', default: 0: 'include elements in processing unit'
% Toggle: all 'Calculate ALL Statistics', default: 0: 'compute and store all statistics information'
% Toggle: mean 'mean', default: 0: 'compute mean'
% Toggle: sum 'total integral', default: 0: 'compute total integral'
% Toggle: var 'variance', default: 0: 'compute variance'
% Toggle: wmin 'width coordinate', default: 0: 'store width coordinate of the minimum value'
% Toggle: psum 'pos part of integral', default: 0: 'compute positive part of integral'
% Toggle: sd 'std deviation', default: 0: 'compute standard deviation'
% Toggle: hmin 'height coordinate', default: 0: 'store height coordinate of the minimum value'
% Toggle: nsum 'neg part of integral', default: 0: 'compute negative part of integral'
% Toggle: rms 'rms', default: 0: 'compute root mean square'
% Toggle: dmin 'depth coordinate', default: 0: 'store depth coordinate of the minimum value'
% Toggle: pts 'total contributing pts', default: 0: 'compute total number of contributing points'
% Toggle: skew 'skewness', default: 0: 'compute skewness'
% Toggle: tmin 'time coordinate', default: 0: 'store time coordinate of the minimum value'
% Toggle: ppts 'positive points', default: 0: 'compute number of positive contributing points'
% Toggle: kur 'kurtosis', default: 0: 'compute kurtosis'
% Toggle: emin 'elements coordinate', default: 0: 'store elements coordinate of the minimum value'
% Toggle: npts 'negative points', default: 0: 'compute number of negative contributing points'
% Toggle: minval 'minimum', default: 0: 'compute minimum value'
% Toggle: zpts 'zero points', default: 0: 'compute number of zero-valued contributing pts'
% Toggle: maxval 'maximum', default: 0: 'compute maximum value'
% Toggle: wmax 'width coordinate', default: 0: 'store width coordinate of the maximum value'
% Toggle: wsize 'data width', default: 0: 'store size of objects width dimension'
% Toggle: hmax 'height coordinate', default: 0: 'store height coordinate of the maximum value'
% Toggle: hsize 'data height', default: 0: 'store size of objects height dimension'
% Toggle: dmax 'depth coordinate', default: 0: 'store depth coordinate of the maximum value'
% Toggle: dsize 'data depth', default: 0: 'store size of objects depth dimension'
% Toggle: tmax 'time coordinate', default: 0: 'store time coordinate of the maximum value'
% Toggle: tsize 'time size', default: 0: 'store size of objects time dimension'
% Toggle: emax 'elements coordinate', default: 0: 'store elements coordinate of the maximum value'
% Toggle: esize 'elements size', default: 0: 'store size of objects elements dimension'
%
% Example: [f, o] = kkstats({i, igate}, {'i','';'igate','';'f','';'o','';'whole',0;'w',0;'h',0;'d',0;'t',0;'e',0;'all',0;'mean',0;'sum',0;'var',0;'wmin',0;'psum',0;'sd',0;'hmin',0;'nsum',0;'rms',0;'dmin',0;'pts',0;'skew',0;'tmin',0;'ppts',0;'kur',0;'emin',0;'npts',0;'minval',0;'zpts',0;'maxval',0;'wmax',0;'wsize',0;'hmax',0;'hsize',0;'dmax',0;'dsize',0;'tmax',0;'tsize',0;'emax',0;'esize',0})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% kstats - Compute Statistics of Data Object
%
%  DESCRIPTION
% .I kstats
% computes the mean, variance, standard deviation, RMS level, skew, kurtosis,
% minimum value, maximum value, and integral (positive, negative, and total
% sums) of the Input data object (i).  Information such as the number of
% unmasked or ungated points (positive, negative, zero-valued, and total counts),
% the coordinates of the minimum and maximum values, and the dimensions of the
% data object are also provided.
% .so $DATAMANIP/repos/shared/man/sections/mask_stats
% .so $DATAMANIP/repos/shared/man/sections/map_force
% All statistics and information will reflect the mapping.  For example,
% if the dimensions of the data are requested (wsize, hsize, etc), kstats
% returns the dimensionality after mapping.
% .cI $DATAMANIP/repos/shared/man/sections/fail_1input
% All statistics are calculated as double, and the Binary Output data type
% is double.
%
% Location and time data do not affect the statistics calculations, and are
% not transferred to the output object.
%
% A flag can be set for each statistic and information option so that a
% subset of all available options can be calculated and stored or printed.
% The flags are mutually exclusive with the "Calculate All Statistics"
% flag (all).  (The command line flag names are: mean, var, sd, rms, skew,
% kur, minval, maxval, wmin, hmin, dmin, tmin, emin, wmax, hmax, dmax, tmax,
% emax, sum, psum, nsum, pts, ppts, npts, zpts, wsize, hsize, dsize, tsize,
% and esize.) If no flag is specified when running kstats from the command
% line, all statistics and information will be stored.
%
% Statistics are computed according to the equations given below.  In the
% equations, N is the number of samples, SUM is the sum from i=0 to i=N-1,
% and x(i) is the sample value of x at i.
%
%  "Mean (-mean)"
% mean = (1/N) * SUM(x(i))  i=0..N-1
%
%  "Variance (-var)"
% variance = (1/(N-1)) * (SUM (x(i) - mean)**2)  i=0..N-1
%
%  "Standard Deviation (-sd)"
% standard deviation = sqrt(variance)
%
%  "RMS (-rms)"
% RMS  = sqrt(1/N * SUM(x(i)**2))  i=0..N-1
%
%  "Skewness (-skew)"
% Skewness is a measure of the tendency of the deviations from the mean to be
% larger in one direction than in the other.  It is a measure of the asymmetry
% of a distribution about its mean.  A positive skew value signifies a
% distribution whose tail extends out towards more positive x, and a negative
% tail signifies a distribution whose tail extends out towards more negative x.
% Population skewness is unitless and is defined as:
% E[((x-mean)/(stddev))**3],
% where stddev is the standard deviation of the data.
% .I kstats
% computes the sample skewness as:
% skew = 1/N * SUM( ((x(i) - mean)/stddev) **3 )  i=0..N-1
% If the variance is equal to zero, skewness will be set to 0.0.
%
%  "Kurtosis"
% Kurtosis is a unitless measure of the tail heaviness of a distribution
% and is defined as:
% E[((x-mean)/(stddev))^4] - 3,
% where stddev is the standard deviation of the data.
% .I kstats
% computes the sample kurtosis as:
% kurtosis= (1/N * SUM( ((x(i) - mean)/stddev) **4)) - 3  i=0..N-1
% If the variance is equal to zero, kurtosis will be set to 0.0.
%
%  "Sums or Integrals (-sum, -psum, -nsum)"
% total integral = SUM x(i)
% positive part of integral = SUM x(i),  for all x(i) > 0
% negative part of integral = SUM x(i),  for all x(i) < 0
%
%  "Define Processing Unit"
% To support analysis of subregions within the data object, such as lines,
% planes, volumes, and vectors, an option for defining processing units, or
% regions, is provided.  These regions are defined by the settings of the
% Processing Unit options, which can be either the Whole Data Set (whole),
% or any combination of Width (w), Height (h), Depth (d), Time (t), and
% Elements (e).  Statistics for each region will be computed and printed
% separately. If none of these flags are supplied, then a single set of
% statistics will be computed for the entire data object.
%
%  "Gating Input"
% .so $DATAMANIP/repos/shared/man/sections/gate_simple
%
%  "ASCII Output"
% The "ASCII Output" (f) option allows the user to specify a device or file
% for printing the specified information in formatted ASCII.  A filename
% of # will send the output to stderr.  If neither an "ASCII Output"
% or a "Binary Output" is supplied, the formatted ASCII will automatically
% go to stdout.
%
%  "Binary Output"
% If the "Binary Output" (-o) is selected, the selected statistics and
% information are stored in as double float data in the given file.
% Each statistic is stored as an element of a N-D vector defined along the
% "elements" dimension of the output object.  N is the number of statistics
% and information specified by the user.  The order in which the information
% is stored in the statistics vector is given in the output object's comment
% attribute.
% When M sets of statistics are calculated for M multiple regions of the
% input data object (see discussion on independent region analysis above),
% the statistics vectors are incremented along the width dimension of the
% output statistics object - the output object would have a resulting
% dimensionality of width=M, elements=N (height = depth = time = 1).  For
% example, if the input data object had the dimensionality width = 256,
% height = 256, elements = 7 (depth = time = 1), and the user defined the
% analysis regions to be width-height, the output statistics object would
% have dimensionality width = 7, elements = N (height = depth = time = 1).
% Where the vector at w=0 would contain information pertaining to the first
% region (starting at w=0, h=0, d=0, t=0, e=0), the vector at w=1 would
% contain information about the second region (starting at w=0, h=0, d=0, t=0,
% e=1), and so forth.
%
%
%
%  EXAMPLES
% kstats -i object.xv -f ascii -all
%
% Will create an ASCII statitics file.  Since the -region option is not specified,
% kstats defaults to calculating statistical information for the object
% as a whole.
% kstats -i object.xv -f ascii_file -region -e
%
% Will create an ASCII statistics file. The statistical information is now
% calculated by slicing the object along the element dimension. For example,
% on a 3-band RGB color image, this would compute the statistics for each
% RGB vector.
%
%  "SEE ALSO"
%
%  RESTRICTIONS
% kstats cannot compute complex statistics at this time.  If you wish to
% process the real and imaginary components of a complex data set
% independently, first separate components using kcmplx2real.
%
% In the current implementation, the statistics are accumulated.  This
% can result in overflow.  kstats will be rewritten in the future
% to better handle large values and large data sets.
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kkstats(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kkstats(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'igate', '__input';'f', '__output';'o', '__output';'whole', 0;'w', 0;'h', 0;'d', 0;'t', 0;'e', 0;'all', 0;'mean', 0;'sum', 0;'var', 0;'wmin', 0;'psum', 0;'sd', 0;'hmin', 0;'nsum', 0;'rms', 0;'dmin', 0;'pts', 0;'skew', 0;'tmin', 0;'ppts', 0;'kur', 0;'emin', 0;'npts', 0;'minval', 0;'zpts', 0;'maxval', 0;'wmax', 0;'wsize', 0;'hmax', 0;'hsize', 0;'dmax', 0;'dsize', 0;'tmax', 0;'tsize', 0;'emax', 0;'esize', 0};
maxval={0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
minval={0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
istoggle=[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
was_set=istoggle * 0;
paramtype={'InputFile','InputFile','OutputFile','OutputFile','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle','Toggle'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=0; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(1,1);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
[varargout{:}]=callKhoros([w 'kstats"  '],Inputs,narglist);


% matperm() - transpose and sign rows of x to match y (run after matcorr() )
%
% Usage: >> [permx indperm] = matperm(x,y,indx,indy,corr);
%
% Inputs:
%   x     = first input matrix
%   y     = matrix with same number of columns as x
%   indx  = column containing row indices for x (from matcorr())
%   indy  = column containing row indices for y (from matcorr())
%   corr  = column of correlations between indexed rows of x,y (from matcorr())
%           (used only for its signs, +/-)
% Outputs:
%   permx   = the matrix x permuted and signed according to (indx, indy,corr)
%             to best match y. Rows of 0s added to x to match size of y if nec.
%   indperm = permutation index turning x into y;
%
% Authors: Scott Makeig, Sigurd Enghoff & Tzyy-Ping Jung
%          SCCN/INC/UCSD, La Jolla, 2000

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

% 04-22-99  Adjusted for fixes and speed by Sigurd Enghoff & Tzyy-Ping Jung
% 01-25-02  Reformated help & license, added links -ad

function [permx,indperm]= matperm(x,y,indx,indy,corr)

[m,n] = size(x);
[p,q] = size(y);
[ix,z] = size(indx);
[iy,z] = size(indy);
oldm = m;

errcode=0;
if  ix ~= iy | p ~= iy,
 fprintf('matperm: indx and indy must be column vectors, same height as y.\n');
 errcode=1
end;

if n~=q,
   fprintf('matperm(): two matrices must be same number of columns.\n');
   errcode=2;
else
  if m<p,
  		x = [x;zeros(p-m,n)];	% add rows to x to match height of y
  		p=m;
  elseif p<m,
  		y = [y;zeros(m-p,n)];	% add rows to y to match height of x
  		m=p;
  end;
end;
if errcode==0,
%
% Return the row permutation of matrix x most correlated with matrix y:
%  plus the resulting permutation index
%
  indperm = [1:length(indx)]';	% column vector [1 2 ...nrows]
  permx  = x(indx,:);
  indperm = indperm(indx,:);
  ydni(indy) = 1:length(indy);
  permx = permx(ydni,:);% put x in y row-order
  indperm = indperm(ydni,:);
  permx = permx.*(sgn(corr(ydni))*ones(1,size(permx,2)));
								 % make x signs agree with y
  permx = permx(1:oldm,:);		 % throw out bottom rows if
								 % they were added to match y
  indperm = indperm(1:oldm,:);
end;

return

function vals=sgn(data)

 vals = 2*(data>=0)-1;

return


function [dynpcm2] = Pa2dynpcm2(Pa)
% Convert units of pressure from pascals to dynes per centimeter squared.
% Chad A Greene 2012
dynpcm2 = Pa*10;


function out = optPriceVal(type, Price, Strike, Rate, Time, Vol, Yield, Strike2, Spread)
% OPTPRICE: Pricing function for basic and composite European options.
%
% OPTPRICE provides the means to calculate the price of certian options for
% which a closed-form solution via the Black-Scholes model is known.  It is
% meant to be called using the GUI in one of the following syntaxes:
%

% Sanitize the inputs
if any(isnan(Price(:))) || ~isnumeric(Price) || isempty(Price) || ~isreal(Price) || any(Price(:) < 0)
    error('optPriceVal:InvalidPrice', ...
        'Spot price must be a positive number')
elseif any(isnan(Strike(:))) || ~isnumeric(Strike) || isempty(Strike) || ~isreal(Strike) || any(Strike(:) < 0)
    error('optPriceVal:InvalidStrike', ...
        'Strike price must be a positive number')
elseif any(isnan(Rate(:))) ||~isnumeric(Rate) || isempty(Rate) || ~isreal(Rate) || any(Rate(:) < 0)
    error('optPriceVal:InvalidRate', ...
        'Risk free rate must be a positive number')
elseif any(isnan(Time(:))) ||~isnumeric(Time) || isempty(Time) || ~isreal(Time) || any(Time(:) < 0)
    error('optPriceVal:InvalidTime', ...
        'Time to expiration must be a positive number')
elseif any(isnan(Vol(:))) ||~isnumeric(Vol) || isempty(Vol) || ~isreal(Vol) || any(Vol(:) < 0)
    error('optPriceVal:InvalidVol', ...
        'Volatility must be a positive number')
elseif any(isnan(Yield(:))) ||~isnumeric(Yield) || isempty(Yield) || ~isreal(Yield) || any(Yield(:) < 0)
    error('optPriceVal:InvalidYield', ...
        'Yield must be a positive number')
end
% Optional sanitation of inputs, depending on the option:
switch type
    case {'Strangle', 'Bull Spread', 'Bear Spread'}
        if isnan(Strike2) || ~isnumeric(Strike2) || isempty(Strike2) || ~isreal(Strike2) || Strike2 < 0
            error('optPriceVal:InvalidStrike', ...
                'Strike price must be a positive number')
        end
    case 'Butterfly'
        if isnan(Spread) || ~isnumeric(Spread) || isempty(Spread) || ~isreal(Spread) || Spread < 0 || Spread > 1
            error('optPriceVal:InvalidSpread', ...
                'Spread must be a positive number between 0 and 1')
        end
end

switch type
    case 'Call'
        out = blsprice(Price, Strike, Rate, Time, Vol, Yield);
    case 'Put'
        [dummy, out] = blsprice(Price, Strike, Rate, Time, Vol, Yield);
    case 'Straddle'
        % A Straddle is just a Call and Put option bought at the same
        % strike price and with the same dates involved.
        [Call, Put] = blsprice(Price, Strike, Rate, Time, Vol, Yield);
        out = Call + Put;
    case 'Strangle'
        % A strangle is similar to the straddle, except that there are two
        % strike prices involved: one for the put, and the other for the
        % call.
        Call = blsprice(Price, Strike2, Rate, Time, Vol, Yield);
        [dummy, Put] = blsprice(Price, Strike, Rate, Time, Vol, Yield);
        out = Call + Put;
    case 'Bull Spread'
        % A Bull Spread is formed by buying a call option with a given
        % strike price and then selling another call option with a higher
        % strike price.
        Call1 = blsprice(Price, Strike, Rate, Time, Vol, Yield);
        Call2 = blsprice(Price, Strike2, Rate, Time, Vol, Yield);
        out = Call1 - Call2;
        % Strike2 should be larger than Strike; if not, we'll just
        % tacitly invert them rather than giving an error message.
        if Strike2 < Strike
            out = -out;
        end
    case 'Bear Spread'
        % A Bear Spread is formed by buying a call option with a given
        % strike price and then selling another call option with a lower
        % strike price.
        Call1 = blsprice(Price, Strike, Rate, Time, Vol, Yield);
        Call2 = blsprice(Price, Strike2, Rate, Time, Vol, Yield);
        out = Call2 - Call1;
        % Strike2 should be larger than Strike; if not, we'll just
        % tacitly invert them rather than giving an error message.
        if Strike2 < Strike
            out = -out;
        end
    case 'Butterfly'
        % A Butterfly option involves 4 call options at differing strike
        % prices:
        % Long 1 call at (1 - Spread)*Strike
        % Short 2 calls at Strike
        % Long 1 call at (1 + Spread)*Strike
        Call1 = blsprice(Price, (1-Spread)*Strike, Rate, Time, Vol, Yield);
        Call2 = blsprice(Price, Strike, Rate, Time, Vol, Yield);
        Call3 = blsprice(Price, (1+Spread)*Strike, Rate, Time, Vol, Yield);
        out = Call1 - 2*Call2 + Call3;
    otherwise
        error('optPriceVal:UnknownOption', ...
        ['Invalid option type.  Valid choices are Call, Put, Straddle, '...
        'Strangle, Bull Spread, Bear Spread, or Butterfly'])
end


function r8po_print_some ( n, a, ilo, jlo, ihi, jhi, title )

%*****************************************************************************80
%
%% R8PO_PRINT_SOME prints some of a R8PO matrix.
%
%  Discussion:
%
%    The R8PO storage format is appropriate for a symmetric positive definite
%    matrix and its inverse.  (The Cholesky factor of a R8PO matrix is an
%    upper triangular matrix, so it will be in R8GE storage format.)
%
%    Only the diagonal and upper triangle of the square array are used.
%    This same storage scheme is used when the matrix is factored by
%    R8PO_FA, or inverted by R8PO_INVERSE.  For clarity, the lower triangle
%    is set to zero.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 April 2006
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the matrix.
%
%    Input, real A(N,N), the R8PO matrix.
%
%    Input, integer ILO, JLO, IHI, JHI, the first row and
%    column, and the last row and column to be printed.
%
%    Input, string TITLE, a title.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '%s\n', title );

  incx = 5;
%
%  Print the columns of the matrix, in strips of 5.
%
  for j2lo = jlo : incx : jhi

    j2hi = j2lo + incx - 1;
    j2hi = min ( j2hi, n );
    j2hi = min ( j2hi, jhi );

    inc = j2hi + 1 - j2lo;

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Col: ' );

    for j = j2lo : j2hi
      fprintf ( 1, '%7d       ', j );
    end

    fprintf ( 1, '\n' );
    fprintf ( 1, '  Row\n' );
    fprintf ( 1, '  ---\n' );
%
%  Determine the range of the rows in this strip.
%
    i2lo = max ( ilo, 1 );
    i2hi = min ( ihi, n );

    for i = i2lo : i2hi

      fprintf ( 1, '%4d  ', i );
%
%  Print out (up to) 5 entries in row I, that lie in the current strip.
%
      for j2 = 1 : inc

        j = j2lo - 1 + j2;

        if ( i <= j )
          aij = a(i,j);
        else
          aij = a(j,i);
        end

        fprintf ( 1, '%12g  ', aij );

      end

      fprintf ( 1, '\n' );

    end

  end

  return
end


function exact = p32_exact ( )

%*****************************************************************************80
%
%% P32_EXACT returns the exact integral for problem 32.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 November 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real EXACT, the value of the integral.
%
  exact = - 0.5 * ( exp ( pi ) + 1.0 );

  return
end


function trans = lineSymmetry(line)
%LINESYMMETRY create line symmetry as 2D affine transform
%
%   TRANS = lineSymmetry(LINE);
%   where line is given as [x0 y0 dx dy], return the affine tansform
%   corresponding to the desired line symmetry
%
%
%   See also:
%   lines2d, transforms2d, transformPoint, translation, homothecy
%
%   ---------
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 19/01/2005.
%

% deprecation warning
warning('geom2d:deprecated', ...
    '''lineSymmetry'' is deprecated, use ''createLineReflection'' instead');

% call current implementation
trans = createLineReflection(line);


function dr=tide_pl(eu,rp,GMp,pos)

global glc
GME=3.986004415E+14; %earth gravitational constant
H3=0.292; L3=0.015;
dr=zeros(3,1);

r=norm(rp);
if r<=0,return;end

ep=rp/r;

K2=GMp/GME*glc.RE_WGS84^4/r^3;
K3=K2*glc.RE_WGS84/r;
latp=asin(ep(3)); lonp=atan2(ep(2),ep(1));
cosp=cos(latp); sinl=sin(pos(1)); cosl=cos(pos(1));

%step1 in phase (degree2)
p=(3*sinl*sinl-1)/2;
H2=0.6078-0.0006*p;
L2=0.0847+0.0002*p;
a=dot(ep,eu);
dp=K2*3*L2*a;
du=K2*(H2*(1.5*a^2-0.5)-3*L2*a^2);

%step1 in phase (degree3)
dp=dp+K3*L3*(7.5*a^2-1.5);
du=du+K3*(H3*(2.5*a^3-1.5*a)-L3*(7.5*a^2-1.5)*a);

%step1 out-of-phase (only radial)
du=du+3.0/4.0*0.0025*K2*sin(2.0*latp)*sin(2.0*pos(1))*sin(pos(2)-lonp);
du=du+3.0/4.0*0.0022*K2*cosp*cosp*cosl*cosl*sin(2.0*(pos(2)-lonp));

dr(1)=dp*ep(1)+du*eu(1);
dr(2)=dp*ep(2)+du*eu(2);
dr(3)=dp*ep(3)+du*eu(3);

return


function [bbci, data]= bbci_calibrate_csp_tiny(bbci, data)
%BBCI_CALIBRATE_CSP_TINY - Calibrate for SMR Modulations with CSP (Tiny ver.)
%
%This function is called by bbci_calibrate
%(if BBCI.calibate.fcn is set to @bbci_calibrate_csp_tiny).
%Via BBCI.calibrate.settings, the details can be specified, see below.
%
%Synopsis:
% [BBCI, DATA]= bbci_calibrate_csp_tiny(BBCI, DATA)
%
%Arguments:
%  BBCI -  the field 'calibrate.settings' holds parameters specific to
%          calibrate CSP-based BCI processing.
%  DATA -  holds the calibration data
%
%Output:
%  BBCI - Updated BBCI structure in which all necessary fields for
%     online operation are set, see bbci_apply_structures.
%  DATA - As input.
%
%BBCI.calibrate.settings may include the following parameters:
%  ival: [1x2 DOUBLE] interval on which CSP is performed.
%  band: [1x2 DOUBLE] frequency band on which CSP is performed.
%  clab: [CELL] Labels of the channels that are used for classification,
%     default {'not','E*','Fp*','AF*','OI*','I*','*9','*10'}.
%  nPatters: [INT>0] number of CSP patterns which are considered from each
%     side of the eigenvalue spectrum. Note, that not neccessarily all of
%     these are used for classification, see settings.pattern.
%     Default is 3.
%  model: [CHAR or CELL] Classification model.
%     Default {'RLDAshrink', 'gamma',0, store_means',1, 'scaling',1}.

% 11-2011 Benjamin Blankertz

default_clab=  {'not','E*','Fp*','AF*','OI*','I*','*9','*10'};
default_model= {@train_RLDAshrink, 'Gamma',0, 'StoreMeans',1, 'Scaling',1};

props= {'clab'         default_clab   'CELL{CHAR}'
        'ival'         [750 3750]     '!DOUBLE[1 2]'
        'band'         [8 33]         '!DOUBLE[1 2]'
        'nPatterns'    3              '!INT'
        'model'        default_model  'FUNC|CELL'
        'filtOrder'    5              '!INT'
       };
opt= opt_setDefaults('bbci.calibrate.settings', props);

[filt_b,filt_a]= butter(opt.filtOrder, opt.band/data.cnt.fs*2);
cnt_flt= proc_filt(data.cnt, filt_b, filt_a);

bbci.signal.clab= data.cnt.clab(util_chanind(data.cnt, opt.clab));

fv= proc_segmentation(cnt_flt, data.mrk, opt.ival, 'clab',bbci.signal.clab);
[fv_csp, csp_w, A, la]= proc_csp(fv, 'SelectFcn',...
                                 {@cspselect_equalPerClass, opt.nPatterns});

bbci.signal.proc= {{@online_linearDerivation, csp_w}, ...
                   {@online_filt, filt_b, filt_a}};

bbci.feature.ival= [-750 0];
bbci.feature.proc= {@proc_variance, @proc_logarithm};

fv_csp= bbci_calibrate_evalFeature(fv_csp, bbci.feature);
bbci.classifier.C= trainClassifier(fv_csp, opt.model);

bbci.quit_condition.marker= 255;


function [predtrain,predtest] = predict_test(datatest,hull,alpha,b,zeta);

switch datatest.dag_type
	case {'grid + input_space' , 'mkl + input_space', 'bimkl + input_space' }

 		% prepare data
		predtest = zeros(datatest.n,1)+b;
		ai1=1;
		for i1=1:size(hull,1)
			Xloctest = get_data_reduced(hull(i1,:),datatest);
			predtest = predtest + zeta(i1) * Xloctest * ( Xloctrain' * alpha );
		end
end


%% housekeeping
clear
close all
clc()

%% Create dataset
clc

do_plot=false;

scale=100;

[db,varlist0]=create_dataset(scale,do_plot);

varlist=fieldnames(varlist0);
%% Choose a model type: see cell "create the structural VAR model" below

for imod=1:7

model_type=imod-1;

% set up the restrictions
%---------------------------
close()

% create restrictions on parameters as well as markov chains
%------------------------------------------------------------
switch model_type
    case 0
        % constant-parameter model
        [restrictions,markov_chains,switch_prior]=create_restrictions_and_markov_chains0();
    case 1
        % Coefficients are switching regimes across all equations
        % (synchronized case)
        [restrictions,markov_chains,switch_prior]=create_restrictions_and_markov_chains1();
    case 2
        % Coefficients and variances have different chains, different
        % regimes, and different durations
        [restrictions,markov_chains,switch_prior]=create_restrictions_and_markov_chains2();
    case 3
        % Only coefficients in monetary policy equation are changing
        [restrictions,markov_chains,switch_prior]=create_restrictions_and_markov_chains3();
    case 4
        % Only variance in monetary policy equation is changing
        [restrictions,markov_chains,switch_prior]=create_restrictions_and_markov_chains4();
    case 5
        % Both coefficients and variances in monetary policy equation
        % change with two independent Markov processes
        [restrictions,markov_chains,switch_prior]=create_restrictions_and_markov_chains5();
    case 6 % ok
        % Only variances in ALL three equations switch
        [restrictions,markov_chains,switch_prior]=create_restrictions_and_markov_chains6();
    otherwise
        error('the coded model types are 0, 1, 2, 3, 4 and 6')
end

% Create the VAR
%----------------

clc

nlags=2;

exog={};

panel=[];

constant=true;

% first we create a template structure
% ------------------------------------
sv0=svar(varlist,exog,nlags,constant,panel,markov_chains);

% set priors
%-----------

var_prior=svar.prior_template();

var_prior.type='sz';

prior=struct('var',var_prior,'nonvar',switch_prior);

is_prior=true;

if ~is_prior

    prior=rmfield(prior,'var');

end

% Find posterior mode
%-------------------------

sv=sv0;

sv=estimate(sv,db,{'1960Q1','2015Q2'},prior,restrictions);

end


classdef ENSMOEAD < ALGORITHM
% <multi/many> <real/integer>
% Ensemble of different neighborhood sizes based MOEA/D
% NS --- 25:25:100 --- Set of neighborhood sizes
% LP ---        50 --- Learning period

%------------------------------- Reference --------------------------------
% S. Zhao, P. N. Suganthan, and Q. Zhang, Decomposition-based multi-
% objective evolutionary algorithm with an ensemble of neighborhood sizes,
% IEEE Transactions on Evolutionary Computation, 2012, 16(3): 442-446.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            %% Parameter setting
            [NS,LP] = Algorithm.ParameterSet(25:25:100,50);

            %% Generate the weight vectors
            [W,Problem.N] = UniformPoint(Problem.N,Problem.M);
            % Maximum number of solutions replaced by each offspring
            nr = ceil(Problem.N/100);

            %% Detect all the neighbours of each solution
            B = pdist2(W,W);
            [~,B] = sort(B,2);

            %% Generate random population
            Population = Problem.Initialization();
            Z          = min(Population.objs,[],1);
            % Utility for each subproblem
            Pi = ones(Problem.N,1);
            % Old Tchebycheff function value of each solution on its subproblem
            oldObj = max(abs((Population.objs-repmat(Z,Problem.N,1)).*W),[],2);

            %% Optimization
            p           = ones(1,length(NS))./length(NS);
            FEs         = zeros(1,length(NS));
            FEs_success = zeros(1,length(NS));
            while Algorithm.NotTerminated(Population)
                % Select neighborhood size for each subproblem
                ns = RouletteWheelSelection(Problem.N,1./p);

                % Apply MOEA/D-DRA for one generation
                for subgeneration = 1 : 5
                    % Choose I
                    Bounday = find(sum(W<1e-3,2)==Problem.M-1)';
                    I = [Bounday,TournamentSelection(10,floor(Problem.N/5)-length(Bounday),-Pi)];

                    % For each solution in I
                    for i = I
                        % Choose the parents
                        if rand < 0.9
                            P = B(i,randperm(NS(ns(i))));
                        else
                            P = randperm(Problem.N);
                        end

                        % Generate an offspring
                        Offspring = OperatorDE(Problem,Population(i),Population(P(1)),Population(P(2)));

                        % Update the ideal point
                        Z = min(Z,Offspring.obj);

                        % Update the solutions in P by Tchebycheff approach
                        g_old   = max(abs(Population(P).objs-repmat(Z,length(P),1)).*W(P,:),[],2);
                        g_new   = max(repmat(abs(Offspring.obj-Z),length(P),1).*W(P,:),[],2);
                        replace = find(g_old>=g_new,nr);
                        Population(P(replace)) = Offspring;
                        if ~isempty(replace)
                            FEs_success(ns(i)) = FEs_success(ns(i)) + 1;
                        end
                        FEs(ns(i)) = FEs(ns(i)) + 1;
                    end
                end
                if ~mod(ceil(Problem.FE/Problem.N),10)
                    % Update Pi for each solution
                    newObj    = max(abs((Population.objs-repmat(Z,Problem.N,1)).*W),[],2);
                    DELTA     = (oldObj-newObj)./oldObj;
                    Temp      = DELTA < 0.001;
                    Pi(~Temp) = 1;
                    Pi(Temp)  = (0.95+0.05*DELTA(Temp)/0.001).*Pi(Temp);
                    oldObj    = newObj;
                end
                if ~mod(ceil(Problem.FE/Problem.N),LP)
                    % Update the probability of choosing each neighborhood size
                    R           = FEs_success./FEs;
                    p           = R./sum(R);
                    FEs         = zeros(1,length(NS));
                    FEs_success = zeros(1,length(NS));
                end
            end
        end
    end
end


for i=1:2000
    input(i,:)=10*rand(1,2)-5;
    output(i)=input(i,1)^2+input(i,2)^2;
end
output=output';

save data input output


function score = HV(Population,optimum)
% <max> <multi/many> <real/integer/label/binary/permutation> <large/none> <constrained/none> <expensive/none> <multimodal/none> <sparse/none> <dynamic/none> <robust/none>
% Hypervolume

%------------------------------- Reference --------------------------------
% E. Zitzler and L. Thiele, Multiobjective evolutionary algorithms: A
% comparative case study and the strength Pareto approach, IEEE
% Transactions on Evolutionary Computation, 1999, 3(4): 257-271.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2023 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

    PopObj = Population.best.objs;
    if size(PopObj,2) ~= size(optimum,2)
        score = nan;
    else
        [N,M]  = size(PopObj);
        fmin   = min(min(PopObj,[],1),zeros(1,M));
        fmax   = max(optimum,[],1);
        PopObj = (PopObj-repmat(fmin,N,1))./repmat((fmax-fmin)*1.1,N,1);
        PopObj(any(PopObj>1,2),:) = [];
        RefPoint = ones(1,M);
        if isempty(PopObj)
            score = 0;
        elseif M < 4
            % Calculate the exact HV value
            pl = sortrows(PopObj);
            S  = {1,pl};
            for k = 1 : M-1
                S_ = {};
                for i = 1 : size(S,1)
                    Stemp = Slice(cell2mat(S(i,2)),k,RefPoint);
                    for j = 1 : size(Stemp,1)
                        temp(1) = {cell2mat(Stemp(j,1))*cell2mat(S(i,1))};
                        temp(2) = Stemp(j,2);
                        S_      = Add(temp,S_);
                    end
                end
                S = S_;
            end
            score = 0;
            for i = 1 : size(S,1)
                p     = Head(cell2mat(S(i,2)));
                score = score + cell2mat(S(i,1))*abs(p(M)-RefPoint(M));
            end
        else
            % Estimate the HV value by Monte Carlo estimation
            SampleNum = 1e6;
            MaxValue  = RefPoint;
            MinValue  = min(PopObj,[],1);
            Samples   = unifrnd(repmat(MinValue,SampleNum,1),repmat(MaxValue,SampleNum,1));
            for i = 1 : size(PopObj,1)
                drawnow('limitrate');
                domi = true(size(Samples,1),1);
                m    = 1;
                while m <= M && any(domi)
                    domi = domi & PopObj(i,m) <= Samples(:,m);
                    m    = m + 1;
                end
                Samples(domi,:) = [];
            end
            score = prod(MaxValue-MinValue)*(1-size(Samples,1)/SampleNum);
        end
    end
end

function S = Slice(pl,k,RefPoint)
    p  = Head(pl);
    pl = Tail(pl);
    ql = [];
    S  = {};
    while ~isempty(pl)
        ql  = Insert(p,k+1,ql);
        p_  = Head(pl);
        cell_(1,1) = {abs(p(k)-p_(k))};
        cell_(1,2) = {ql};
        S   = Add(cell_,S);
        p   = p_;
        pl  = Tail(pl);
    end
    ql = Insert(p,k+1,ql);
    cell_(1,1) = {abs(p(k)-RefPoint(k))};
    cell_(1,2) = {ql};
    S  = Add(cell_,S);
end

function ql = Insert(p,k,pl)
    flag1 = 0;
    flag2 = 0;
    ql    = [];
    hp    = Head(pl);
    while ~isempty(pl) && hp(k) < p(k)
        ql = [ql;hp];
        pl = Tail(pl);
        hp = Head(pl);
    end
    ql = [ql;p];
    m  = length(p);
    while ~isempty(pl)
        q = Head(pl);
        for i = k : m
            if p(i) < q(i)
                flag1 = 1;
            else
                if p(i) > q(i)
                    flag2 = 1;
                end
            end
        end
        if ~(flag1 == 1 && flag2 == 0)
            ql = [ql;Head(pl)];
        end
        pl = Tail(pl);
    end
end

function p = Head(pl)
    if isempty(pl)
        p = [];
    else
        p = pl(1,:);
    end
end

function ql = Tail(pl)
    if size(pl,1) < 2
        ql = [];
    else
        ql = pl(2:end,:);
    end
end

function S_ = Add(cell_,S)
    n = size(S,1);
    m = 0;
    for k = 1 : n
        if isequal(cell_(1,2),S(k,2))
            S(k,1) = {cell2mat(S(k,1))+cell2mat(cell_(1,1))};
            m = 1;
            break;
        end
    end
    if m == 0
        S(n+1,:) = cell_(1,:);
    end
    S_ = S;
end


function ori = discreteSample(SO3F,npoints,varargin)
% draw a random sample
%

% spread points over different centers
ic = discretesample([SO3F.weights(:);SO3F.c0], npoints).';

isUniform = ic == length(SO3F.weights)+1;

% some uniform random orientations
ori = orientation.rand(length(ic),SO3F.CS,SO3F.SS);

% the remaining points
npoints = nnz(~isUniform);
if npoints == 0, return; end

% take random rotational axes for the remaining samples
axis = vector3d.rand(npoints);

% random rotational angles
M = 1000000; % discretisation parameter

hw = min(4*SO3F.psi.halfwidth,90*degree);
t = linspace(cos(hw),1,M);

% compute cummulative distribution function
c = 4 / pi * cumsum(sqrt(1-t.^2) .* SO3F.psi.eval(t)) / M;
c = c ./ c(end);

% random sample with respect to the CDF
r = rand(npoints,1);
[~,id] = histc(r,c);
angle = 2 * acos(t(id)).';

% set up random orientations
ori(~isUniform) = times(reshape(SO3F.center(ic(~isUniform)),[],1), ...
  rotation.byAxisAngle(axis,angle),false);

% random symmetry elements
ori = ori .* SO3F.CS.rot(randi(SO3F.CS.numSym,npoints,1));
if SO3F.SS.numSym>1
  ori = SO3F.SS.rot(randi(SO3F.SS.numSym,npoints,1)) .* ori;
end


function [bic, loglik, penalty] = computebic(pathname, filename, ncomp_vec, dpixc, penalty_type)
% [bic, loglik, penalty] = computebic(pathname, filename, ncomp_vec, dpixc, penalty_type)
% penalty_type = 1 : original NMF
% penalty_type = 2 : original NMF + multidimensinoal data
% penalty_type = 3 : hidden + multidimensinoal data

if ~exist('penalty_type','var')
    penalty_type = 1;
end

for ii=1:length(ncomp_vec)
%     if strcmp(pathname(end), '/')
%         load ([pathname filename num2str(ncomp_vec(ii))])
%     else
%         load ([pathname '/' filename num2str(ncomp_vec(ii))])
%     end
%     load ([pathname filename num2str(ncomp_vec(ii)) '/' filename num2str(ncomp_vec(ii))]);
    load ([pathname '/' filename num2str(ncomp_vec(ii))]);
    loglik(ii) = -ddivergence(reshape(dpixc,peval.numpix, peval.nt),res.w*res.h);
    switch penalty_type
        case 1 % orig
            if ii==1 fprintf ('Penalty: original NMF\n'); end
            penalty(ii) = 0.5*peval.ncomp*(peval.nt+peval.numpix)*log(peval.nt*peval.numpix); %orig
        case 2 % orig + multidiensional data
            if ii==1 fprintf ('Penalty: original NMF + multidimensional data\n'); end
            penalty(ii) = 0.5*peval.ncomp*(peval.nt+peval.numpix)*log(peval.nt);
        case 3 % hidden + multidimensional data
            if ii==1 fprintf ('Penalty: multidimensional + hidden\n'); end
            penalty(ii) = 0.5*peval.ncomp*(peval.numpix)*log(peval.nt);
    end

% penalty(ii) = 0.5*peval.ncomp*(peval.nt+peval.numpix)*log(peval.nt*peval.numpix);
% penalty(ii) = 0.5*peval.ncomp*(peval.nt+peval.numpix)*log(peval.nt*peval.numpix); %orig
% penalty(ii) = 0.5*peval.ncomp*(peval.numpix)*log(peval.nt); %hidden +
% multidimensional data
% penalty(ii) = 0.5*peval.ncomp*(peval.nt+peval.numpix)*log(peval.nt); % orig + multidiensional data

%     bic(ii) = -ddivergence(reshape(dpixc,peval.numpix, peval.nt),res.w*res.h) - 0.5*peval.ncomp*peval.nt*log(peval.nt*peval.numpix);
end
bic =  loglik - penalty;


function [meanDistMatrix, maxDistMatrix] = mtrComputeFiberDistMatrix(fg)

% Find all pair differences between fibers in the fiber group
meanDistMatrix = zeros(length(fg.fibers));
maxDistMatrix = zeros(length(fg.fibers));

disp('Computing distances between all paths could take awhile.');
percentMark = 10;
percentInc = 10;
for ii = 1:length(fg.fibers)-1
    for jj = ii+1:length(fg.fibers)
        [indices, bestSqDistIJ] = nearpoints(fg.fibers{ii}, fg.fibers{jj});
        [indices, bestSqDistJI] = nearpoints(fg.fibers{jj}, fg.fibers{ii});
        meanDistMatrix(ii,jj) = mean([mean(sqrt(bestSqDistIJ)) mean(sqrt(bestSqDistJI))]);
        meanDistMatrix(jj,ii) = meanDistMatrix(ii,jj);
        maxDistMatrix(ii,jj) = mean(sqrt([max(bestSqDistIJ) max(bestSqDistJI)]));
        maxDistMatrix(jj,ii) = maxDistMatrix(ii,jj);
    end
    percentCompleted = round(ii/length(fg.fibers)*100);
    if( percentCompleted >= percentMark )
        disp(['Completed ' num2str(percentCompleted) ' %' ]);
        percentMark = percentMark+percentInc;
    end
end


function [gKern1, gKern2, gVarmeans, gVarcovars, gInd] = rbfard2biasVardistPsi2Gradient(rbfardKern, biasKern, vardist, Z, covGrad, learnInducing)

% RBFARD2BIASVARDISTPSI2GRADIENT description.

% VARGPLVM

if nargin < 6
    learnInducing = 1;
end

% variational means
N = size(vardist.means,1);
%  inducing variables
[M Q] = size(Z);

[Psi2, Pnobias, Psi1] = rbfard2biasVardistPsi2Compute(rbfardKern, biasKern, vardist, Z);

% inverse variances
A = rbfardKern.inputScales;

% gradient wrt variance of the rbfard2 kernel
gKernvar = sum(sum(Psi2.*covGrad))/rbfardKern.variance;
% gradient for the bias parameter
gKern2 = sum(sum(Pnobias.*covGrad));
Bnm = biasKern.variance*ones(size(Psi1));
BPsi1Covg = Psi1.*(Bnm*covGrad);

%-- New: preallocation
    gVarmeans = zeros(N,Q);
    gVarcovars = zeros(N,Q);
    gInd = zeros(M,Q);
%---

% compute the gradient wrt lengthscales, variational means and variational variances
for q=1:vardist.latentDimension
%
    S_q = vardist.covars(:,q);
    Mu_q = vardist.means(:,q);
    Z_q = Z(:,q)';

    % B3_q term (without A(q); see report)
    B_q = (repmat(Mu_q,[1 M]) - repmat(Z_q,[N 1]))./repmat(A(q)*S_q + 1, [1 M]);

    % derivatives wrt variational means and inducing inputs
    tmp = (B_q.*BPsi1Covg);

    % variational means: you sum out the columns (see report)
    gVarmeans(:,q) = -A(q)*sum(tmp,2);

    % inducing inputs: you sum out the rows
    if learnInducing
        gInd(:,q) = A(q)*sum(tmp,1)';
    end

    %
    B_q = (B_q.*(repmat(Mu_q,[1 M]) - repmat(Z_q,[N 1])));

    % B1_q term (see report)
    B1_q = (repmat(S_q, [1 M]) + B_q)./repmat((A(q)*S_q + 1), [1 M]);

    % gradients wrt kernel hyperparameters (lengthscales)
    gKernlengcs(q) = -0.5*sum(sum(B1_q.*BPsi1Covg));

    % gradient wrt variational covars (diagonal covariance matrices)
    gVarcovars(:,q) = sum((BPsi1Covg./repmat((A(q)*S_q + 1), [1 M])).*(A(q)*B_q - 1),2);

    %
end
%

gKern1 = [gKernvar 2*gKernlengcs];

% gVarmeans is N x Q matrix (N:number of data, Q:latent dimension)
% this will unfold this matrix column-wise
gVarmeans = 2*gVarmeans(:)';

% gVarcovars is N x Q matrix (N:number of data, Q:latent dimension)
% this will unfold this matrix column-wise
gVarcovars = repmat(A,[N 1]).*gVarcovars;
gVarcovars = gVarcovars(:)';

% gInd is M x Q matrix (M:number of inducing variables, Q:latent dimension)
% this will unfold this matrix column-wise
gInd = 2*gInd(:)';


function burnInfoText = printDVManeuversFMSToTextbox(hDvManInfoText, departBody, flybyBody, dVDepartVectNTW, ePreDepartOrbit, eTA, departBodyInfo, flyByDVVectNTW,  form, paddLen)
%printDVManeuversFMSToTextbox Summary of this function goes here
%   Detailed explanation goes here
        hRule = getHRule();

        ePeriod = computePeriod(ePreDepartOrbit(1), departBodyInfo.gm);

        burnInfoText{1} = ['Burn Information to Depart ', cap1stLetter(departBody)];
        burnInfoText{end+1} = hRule;
        burnInfoText{end+1} = [paddStr('Total Delta-V = ',paddLen), num2str(norm(dVDepartVectNTW), form), ' km/s'];
        burnInfoText{end+1} = [paddStr('Prograde Delta-V = ',paddLen), num2str(1000*dVDepartVectNTW(1), form), ' m/s'];
        burnInfoText{end+1} = [paddStr('Orbit Normal Delta-V = ',paddLen), num2str(1000*dVDepartVectNTW(2), form), ' m/s'];
        burnInfoText{end+1} = [paddStr('Radial Delta-V = ',paddLen), num2str(1000*dVDepartVectNTW(3), form), ' m/s'];
        burnInfoText{end+1} = '---------------------';
        burnInfoText{end+1} = [paddStr('Departure True Anomaly = ',paddLen), num2str(rad2deg(eTA), form), ' deg'];
        MA = AngleZero2Pi(computeMeanFromTrueAnom(eTA, ePreDepartOrbit(2)));
        eN = computeMeanMotion(ePreDepartOrbit(1), departBodyInfo.gm);
        secFromPeri = MA/eN;
        burnInfoText{end+1} = [paddStr('Departure Time Past Peri. = ',paddLen), num2str(secFromPeri, form), ' sec'];
        burnInfoText{end+1} = [paddStr('Departure Time Before Peri. = ',paddLen), num2str(ePeriod-secFromPeri, form), ' sec'];
        burnInfoText{end+1} = hRule;
        burnInfoText{end+1} = ['Burn Information to Depart ', cap1stLetter(flybyBody)];
        burnInfoText{end+1} = hRule;
        burnInfoText{end+1} = [paddStr('Total Delta-V = ',paddLen), num2str(norm(flyByDVVectNTW), form), ' km/s'];
        burnInfoText{end+1} = [paddStr('Prograde Delta-V = ',paddLen), num2str(1000*flyByDVVectNTW(1), form), ' m/s'];
        burnInfoText{end+1} = [paddStr('Orbit Normal Delta-V = ',paddLen), num2str(1000*flyByDVVectNTW(2), form), ' m/s'];
        burnInfoText{end+1} = [paddStr('Radial Delta-V = ',paddLen), num2str(1000*flyByDVVectNTW(3), form), ' m/s'];
        %flyby burn occurs at periapse per the algorithm - this is hardcoded below (next two lines)
        burnInfoText{end+1} = '---------------------';
        burnInfoText{end+1} = [paddStr('Departure True Anomaly = ',paddLen), num2str(rad2deg(0.0), form), ' deg'];
        burnInfoText{end+1} = [paddStr('Departure Time Past Peri. = ',paddLen), num2str(0.0, form), ' sec'];
        burnInfoText{end+1} = [paddStr('Departure Time Before Peri. = ',paddLen), num2str(0.0, form), ' sec'];
        set(hDvManInfoText,'String',burnInfoText);

        %first number is type of time in the second element: 0 is UT, 1 is
        %time past periapse;
        %Note: Code after this method is called may modify UserData
        %(specifically to change the type to strict UT time)
        set(hDvManInfoText, 'UserData', [1, secFromPeri, 1000*dVDepartVectNTW(1), 1000*dVDepartVectNTW(2), 1000*dVDepartVectNTW(3)]);
end