function [ objects ] = rectangle2hypothesis( xyzBox, rule, room_points )
%RECTANGLE2HYPOTHESIS Popup rectangles to cuboids
%   Detailed explanation goes here
COUNTER_CLOCKWISE = true;
FITTINGRULES;
uni_room_points = zeros(8,3);
uni_room_points(POINTMAPPING{3},1) = room_points(:,1);
uni_room_points(POINTMAPPING{3},2) = room_points(:,2);
uni_room_points(POINTMAPPING{3},3) = room_points(:,3);

I = find(uni_room_points(1:4,1)<0 & uni_room_points(1:4,2)<0);
ID = rem([I I+1 I+2 I+3]-1,4) + 1;
uni_room_points = uni_room_points([ID ID+4],:);
wall_points = zeros(4,3,6);
wall_points(:,:,1) = uni_room_points([1 4 8 5],:);
wall_points(:,:,2) = uni_room_points([3 2 6 7],:);
wall_points(:,:,3) = uni_room_points([2 1 5 6],:);
wall_points(:,:,4) = uni_room_points([4 3 7 8],:);
wall_points(:,:,5) = uni_room_points([1 2 3 4],:);
wall_points(:,:,6) = uni_room_points([8 7 6 5],:);

LRDU_SURF = zeros(6,4);
LRDU_SURF(1,:) = [3 4 5 6];
LRDU_SURF(2,:) = [4 3 5 6];
LRDU_SURF(3,:) = [2 1 5 6];
LRDU_SURF(4,:) = [1 2 5 6];
LRDU_SURF(5,:) = [1 2 4 3];
LRDU_SURF(6,:) = [1 2 3 4];

normals = [1 0 0; -1 0 0; 0 1 0; 0 -1 0; 0 0 1; 0 0 -1];
normal_ids = [1 1 2 2 3 3];
main_angle = [pi/2 -pi/2 -pi 0 0];

objects = repmat(struct('out_points_w',[],'name',[],'type',[],'points',[],'x_w',[]),0,1);
object = struct('out_points_w',[],'name','other','type',[],'points',[],'x_w',zeros(7,1));
xyzBox = reshape(xyzBox', 3, 4)';

%% if left two points in lhs wall, add a hypothesis
[inside,~,~] = insideCone( wall_points(:,:,LRDU_SURF(rule,1)), xyzBox([1 4],:), 0 );
if all(inside)
    LID = LRDU_SURF(rule,1);
    wall_point = wall_points(:,:,LID);
    point4 = LineFaceIntersection(wall_point(1,:), normals(LID,:), [0 0 0], xyzBox(1,:));
    point3 = LineFaceIntersection(wall_point(1,:), normals(LID,:), [0 0 0], xyzBox(4,:));
    point1 = LineFaceIntersection(point4, normals(rule,:), [0 0 0], xyzBox(2,:));
    point2 = LineFaceIntersection(point3, normals(rule,:), [0 0 0], xyzBox(3,:));
    point5 = point1;    point6 = point2;
    point5(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);
    point6(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);

    object.out_points_w = [point1; point2; point3; point4; point5; point6];
    object.type = 9;
    object.points = object.out_points_w ./ repmat(sqrt(sum(object.out_points_w.^2,2)),1,3);
    object.x_w(1:3) = point3;
    object.x_w(4) = norm(point2-point3);
    object.x_w(5) = norm(point6-point2);
    object.x_w(6) = norm(point4-point3);
    object.x_w(7) = main_angle(rule);
    objects(end+1,1) = object;
end

%% if right two points in rhs wall, add a hypothesis
[inside,~,~] = insideCone( wall_points(:,:,LRDU_SURF(rule,2)), xyzBox([2 3],:), 0 );
if all(inside)
    RID = LRDU_SURF(rule,2);
    wall_point = wall_points(:,:,RID);
    point5 = LineFaceIntersection(wall_point(1,:), normals(RID,:), [0 0 0], xyzBox(2,:));
    point6 = LineFaceIntersection(wall_point(1,:), normals(RID,:), [0 0 0], xyzBox(3,:));
    point1 = LineFaceIntersection(point5, normals(rule,:), [0 0 0], xyzBox(1,:));
    point2 = LineFaceIntersection(point6, normals(rule,:), [0 0 0], xyzBox(4,:));
    point4 = point1;    point3 = point2;
    point4(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);
    point3(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);

    object.out_points_w = [point1; point2; point3; point4; point5; point6];
    object.type = 9;
    object.points = object.out_points_w ./ repmat(sqrt(sum(object.out_points_w.^2,2)),1,3);
    object.x_w(1:3) = point3;
    object.x_w(4) = norm(point2-point3);
    object.x_w(5) = norm(point6-point2);
    object.x_w(6) = norm(point4-point3);
    object.x_w(7) = main_angle(rule);
    objects(end+1,1) = object;
end

%% if bottom two points in floor, add a hypothesis
[inside,~,~] = insideCone( wall_points(:,:,LRDU_SURF(rule,3)), xyzBox([4 3],:), 0 );
if all(inside)
    DID = LRDU_SURF(rule,3);
    wall_point = wall_points(:,:,DID);
    point3 = LineFaceIntersection(wall_point(1,:), normals(DID,:), [0 0 0], xyzBox(4,:));
    point2 = LineFaceIntersection(wall_point(1,:), normals(DID,:), [0 0 0], xyzBox(3,:));
    point4 = LineFaceIntersection(point3, normals(rule,:), [0 0 0], xyzBox(1,:));
    point1 = LineFaceIntersection(point2, normals(rule,:), [0 0 0], xyzBox(2,:));
    point5 = point4;    point6 = point1;
    point5(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);
    point6(normal_ids(rule)) = wall_points(1,normal_ids(rule),rule);

    object.out_points_w = [point1; point2; point3; point4; point5; point6];
    object.type = 13;
    object.points = object.out_points_w ./ repmat(sqrt(sum(object.out_points_w.^2,2)),1,3);
    object.x_w(1:3) = point3;
    object.x_w(4) = norm(point2-point3);
    object.x_w(5) = norm(point5-point4);
    object.x_w(6) = norm(point4-point3);
    object.x_w(7) = main_angle(rule);
    objects(end+1,1) = object;
end

%% if all four points inside the wall, add a rectangle
[inside,~,~] = insideCone( wall_points(:,:,rule), xyzBox, 0 );
if all(inside)
    wall_point = wall_points(:,:,rule);
    point4 = LineFaceIntersection(wall_point(1,:), normals(rule,:), [0 0 0], xyzBox(1,:));
    point1 = LineFaceIntersection(wall_point(1,:), normals(rule,:), [0 0 0], xyzBox(2,:));
    point2 = LineFaceIntersection(wall_point(1,:), normals(rule,:), [0 0 0], xyzBox(3,:));
    point3 = LineFaceIntersection(wall_point(1,:), normals(rule,:), [0 0 0], xyzBox(4,:));
    point5 = point4;
    point8 = point1;
    point7 = point2;
    point6 = point3;

    object.out_points_w = [point1; point2; point3; point4; point5; point6; point7; point8];
    object.type = 1;
    object.points = object.out_points_w ./ repmat(sqrt(sum(object.out_points_w.^2,2)),1,3);
    object.x_w(1:3) = point3;
    object.x_w(4) = norm(point2-point3);
    object.x_w(5) = norm(point7-point2);
    object.x_w(6) = norm(point4-point3);
    object.x_w(7) = main_angle(rule);
    objects(end+1,1) = object;
end

end


%--- help for statespace/estimate ---
%
% ESTIMATE Maximum likelihood parameter estimation of state-space models
%
%  Syntax:
%
%    [EstMdl,estParams,EstParamCov,logL,Output] = estimate(Mdl,Y,params0)
%    [EstMdl,estParams,EstParamCov,logL,Output] = estimate(Mdl,Y,params0,
%                                                          name,value,...)
%
%  Description:
%
%    For observation vector y(t) and state vector x(t), estimate parameters
%    of the following general state-space model by maximum likelihood:
%
%    State equation:       x(t) = A(t) * x(t-1) + B(t) * u(t)
%    Observation equation: y(t) = C(t) * x(t)   + D(t) * e(t)
%
%    where u(t) and e(t) are uncorrelated, unit-variance white noise vector
%    processes. The length of x(t), y(t), u(t), and e(t) is m, n, k, and h,
%    respectively.
%
%    For models created explicitly by specifying coefficients A, B, C, and D,
%    unknown parameters to estimate are identified by the presence of NaNs in
%    these model coefficients. Unknown parameters identified by the presence
%    of NaNs in the mean vector (Mean0) and covariance matrix (Cov0) of initial
%    states x(0) are optionally estimated as well.
%
%    For models created implicitly by specifying a parameter mapping function
%    ParamMap, the mapping function is responsible for managing the presence
%    and placement of unknown parameters. In the implicit approach, the mapping
%    function alone defines the model, and is particularly convenient for
%    estimating complex models and for imposing certain parameter constraints.
%    Moreover, in more general settings in which the initial states are also
%    determined by unknown parameters, ParamMap may include additional output
%    arguments; refer to the SSM/DSSM constructor for more details.
%
%  Input Arguments:
%
%    Mdl - A state-space model with unknown parameters to estimate, created
%      by the SSM/DSSM constructor.
%
%    Y - Observed response data to which the model is fit. For time-invariant
%      models in which the length of each observation vector (n) is the same,
%      Y is a T-by-n matrix. For time-varying models in which the length of
%      the observation vector changes, Y is a T-by-1 cell array in which
%      each element contains a time-varying n-element vector of observations,
%      y(t), associated with the corresponding period. The last observation
%      is the most recent.
%
%    params0 - A vector containing the initial values of unknown
%      parameters associated with model coefficients A, B, C, and D, and
%      optionally the mean vector (Mean0) and covariance matrix (Cov0) of
%      initial states x(0), estimated by maximum likelihood. For models created
%      explicitly, parameters mapped to NaN values are found by a column-wise
%      search of A, followed by B, then C, then D, and finally Mean0 and Cov0.
%      For models created implicitly, the parameter function ParamMap is
%      solely responsible for mapping the initial parameter vector into model
%      coefficients A, B, C, and D, as well as additional information
%      regarding initial states and types if necessary.
%
%  Optional Input Name/Value Pairs:
%
%    'Univariate'  Logical value indicating whether to use the univariate
%                  treatment of a multivariate series. The default is false.
%
%    'SquareRoot'  Logical value indicating whether to use the square-root
%                  filter. The default is false.
%                  SSM only. No effects on DSSM.
%
%    'Tolerance'   A small, non-negative variance tolerance that controls
%                  whether an observed series is ignored if its forecast
%                  uncertainty falls below this threshold. Setting tolerance
%                  to a small number, say 1e-15, may help overcome numerical
%                  problems of the filter. The default is 0.
%
%    'Predictors'  T-by-d matrix of common predictor variables used to
%                  include a regression component in the observation equation.
%                  Observations at time t are deflated such that
%
%                  [y(t) - z(t)*b] = C * x(t) + D * e(t)
%
%                  where z(t) is a vector of predictor variables and b is
%                  the regression coefficient vector (see below). The default
%                  is an empty matrix (no regression component)
%
%    'Beta0'       d-by-n matrix of initial values of regression coefficients
%                  associated with predictors (see above). If the model contains
%                  a regression component, coefficients are estimated along
%                  with other unknown parameters in A, B, C, D, Mean0, and
%                  Cov0; the default initial values are obtained by ordinary
%                  least squares (OLS) by regressing Y on the explanatory
%                  variables.
%
%    'SwitchTime'  a positive integer that specifies the date after which the
%                  diffuse filter switches to the standard filter.
%                  The default is the earliest date when the smoothed
%                  initial states have a full-rank covariance matrix.
%                  DSSM only. No effects on SSM.
%
%    'CovMethod'   String or character vector indicating the method for
%                  computing the asymptotic parameter error covariance
%                  matrix of estimated parameters. Values are:
%
%                  VALUE             METHOD
%
%                  o 'hessian'       Negative inverted Hessian matrix
%                  o 'opg'           Outer product of gradients (default)
%                  o 'sandwich'      Both Hessian and outer product of gradients
%
%    'Options'     Optimization options created with OPTIMOPTIONS. If
%                  specified, default optimization parameters are replaced
%                  by those in options. The default OPTIMOPTIONS object depends
%                  on the optimization function used to estimate parameters.
%                  For constrained optimization, FMINCON is called and the
%                  algorithm used is interior point; for unconstrained
%                  optimization, FMINUNC is called and the algorithm is
%                  quasi-Newton. See documentation for OPTIMOPTIONS, FMINCON,
%                  and FMINUNC for details.
%
%    'Display'    String vector or cell vector of character vectors
%                 indicating what information to display in the command
%                 window. Values are:
%
%                 VALUE           DISPLAY
%
%                 o 'off'         No display to the command window.
%
%                 o 'params'      Display maximum likelihood parameter
%                                 estimates, standard errors, and t statistics.
%                                 This is the default.
%
%                 o 'iter'        Display iterative optimization information.
%
%                 o 'diagnostics' Display optimization diagnostics.
%
%                 o 'full'        Display 'params', 'iter', and 'diagnostics'.
%
%    The following optional name/value pairs are related to constrained
%    optimization performed by FMINCON (see FMINCON for details):
%
%    'Aineq'  Linear inequality matrix, such that for solution vector X
%             Aineq*X <= bineq. The number of rows is determined by the
%             number of constraints, and the number of columns by the number
%             of estimated parameters. Columns are ordered by estimated
%             parameters in A, B, C, D, Mean0, Cov0, and finally regression
%             coefficients for models with a regression component.
%
%    'bineq'  Linear inequality column vector, such that for solution vector
%             X Aineq*X <= bineq.
%
%    'Aeq'    Linear equality matrix, such that for solution vector X
%             Aeq*X = beq. The number of rows is determined by the
%             number of constraints, and the number of columns by the number
%             of estimated parameters. Columns are ordered by estimated
%             parameters in A, B, C, D, Mean0, Cov0, and finally regression
%             coefficients for models with a regression component.
%
%    'beq'    Linear equality column vector, such that for solution vector X
%             Aeq*X = beq.
%
%    'lb'     Lower bounds column vector on estimated parameters. Vector
%             elements are ordered by estimated parameters in A, B, C, D,
%             Mean0, Cov0, and finally regression coefficients for models with
%             a regression component.
%
%    'ub'     Upper bounds column vector on estimated parameters. Vector
%             elements are ordered by estimated parameters in A, B, C, D,
%             Mean0, Cov0, and finally regression coefficients for models with
%             a regression component.
%
%  Output Arguments:
%
%    EstMdl - A fitted state-space model with estimated model coefficients.
%      Provided the optimization converged successfully, the model is explicit
%      in its coefficients A, B, C, D, Mean0, and Cov0 regardless of whether
%      the input model (Mdl) was created explicitly or implicitly.
%
%    estParams - Vector of estimated parameter. The elements are ordered such
%      that any estimated parameters in A appear first, then B, then C, then
%      D, and finally Mean0 and Cov0. Additionally, if the observation equation
%      includes a regression component, then estimates of any regression
%      coefficients appear last.
%
%    EstParamCov - Variance-covariance matrix of estimated parameters. The
%      rows/columns are ordered such that variances/covariances of any
%      estimated parameters in A appear first, then B, then C, then D, and
%      finally Mean0 and Cov0. Additionally, if the observation equation
%      includes a regression component, then variances/covariances of any
%      estimated regression coefficients appear last.
%
%    logL - Log-likelihood of the observations.
%
%    Output - Output structure with the following fields:
%
%       o ExitFlag - Optimization exit flag that describes the exit condition.
%           See FMINCON or FMINUNC for additional details.
%
%       o Options - Optimization options, created with OPTIMOPTIONS, and used
%           by the optimizer.
%
%  Notes:
%
%    o Missing observations in Y are indicated by NaNs.
%
%    o Although creating a model explicitly by directly specifying parameters
%      (A, B, C, D, etc.) with NaN placeholders to indicate parameters to
%      estimate is more convenient than specifying a user-defined mapping
%      function ParamMap, the utility of an explicit approach is limited in
%      that each estimated parameter affects and is uniquely associated with
%      a single element of a coefficient matrix.
%
%    o The option of univariate treatment requires a diagonal D(t)*D(t)'.
%
%    o The state-space model itself does not store regression data or
%      coefficients. Instead, a regression component is used to deflate the
%      observations, such that the deflated data is given by y(t) - z(t)*b.
%
%    o Regression coefficients in the observation equation are estimated along
%      with other unknown parameters, and so parameter constraints may be
%      placed on regression coefficients as well other parameters by specifying
%      appropriate entries in 'Aineq', 'bineq', etc.
%
%    o If observations are multivariate, then the same regressors apply to all.
%
%    o If the state equation requires predictors, or each individual component
%      of the observation equation requires a set of distinct predictors, try
%      one of the following methods:
%
%        o Expand the states by a constant one.
%        o Expand the states by predictors.
%        o Return 8 output arguments from the user-supplied function
%          ParamMap, the last of which is the deflated observation data.
%
%    o Regression components in the observation equation are allowed only for
%      time-invariant observations, in which the input observation series Y
%      is of constant length and specified as a T-by-n matrix. Y specified as
%      a T-by-1 cell array indicates a time-varying observation series whose
%      length may change over time. If the length of each observation y(t)
%      changes, then it is unclear which regression coefficients are needed
%      to deflate a given observation.
%
%    o If no constraints are specified, FMINUNC is used; otherwise, FMINCON
%      is used for constrained optimization. Therefore, when specifying the
%      input Options, the input should be consistent with the solver (see
%      OPTIMOPTIONS, FMINCON, and FMINUNC for details).
%
%      Whenever possible, it is recommended to avoid equality/inequality
%      constraints by reparameterizing the model. For example, various
%      parameters may be exponentiated using EXP to ensure positivity.
%
%    o The observations in the starting periods are treated as if they were
%      presample data for exact initialization of the diffuse initial
%      states. We define the likelihood function as the joint density
%      of the observations after the algorithm is switched to
%      the standard Kalman filter. The variable 'SwitchTime' determines when
%      the standard Kalman filter starts.
%
%  See also SSM, DSSM, FILTER, SMOOTH, FORECAST, SIMULATE, SIMSMOOTH.
%
%    Other functions named estimate
%
%       abstvar/estimate         garch/estimate
%       arima/estimate           generic/estimate
%       conjugateblm/estimate    gjr/estimate
%       customblm/estimate       regARIMA/estimate
%       diffuseblm/estimate      semiconjugateblm/estimate
%       dsge/estimate            ssm/estimate
%       dssm/estimate            varm/estimate
%       egarch/estimate          vecm/estimate
%       empiricalblm/estimate
%


%COLORNAME Map between color names and RGB values
%
% RGB = COLORNAME(NAME) is the RGB-tristimulus value (1x3) corresponding to
% the color specified by the string NAME.  If RGB is a cell-array (1xN) of
% names then RGB is a matrix (Nx3) with each row being the corresponding
% tristimulus.
%
% XYZ = COLORNAME(NAME, 'xyz') as above but the XYZ-tristimulus value
% corresponding to the color specified by the string NAME.
%
% XY = COLORNAME(NAME, 'xy') as above but the xy-chromaticity coordinates
% corresponding to the color specified by the string NAME.
%
% NAME = COLORNAME(RGB) is a string giving the name of the color that is
% closest (Euclidean) to the given RGB-tristimulus value (1x3).  If RGB is
% a matrix (Nx3) then return a cell-array (1xN) of color names.
%
% NAME = COLORNAME(XYZ, 'xyz') as above but the color is the closest (Euclidean)
% to the given XYZ-tristimulus value.
%
% NAME = COLORNAME(XYZ, 'xy') as above but the color is the closest (Euclidean)
% to the given xy-chromaticity value with assumed Y=1.
%
% Notes::
% - Color name may contain a wildcard, eg. "?burnt"
% - Based on the standard X11 color database rgb.txt.
% - Tristimulus values are in the range 0 to 1

% 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

function r = colorname(a, varargin)

    opt.color = {'rgb', 'xyz', 'xy'};
    opt = tb_optparse(opt, varargin);

    persistent  rgbtable;

    mvtb_present = exist('tristim2cc');

    % ensure that the database is loaded
    if isempty(rgbtable)
        % load mapping table from file
        fprintf('loading rgb.txt\n');
        f = fopen('private/rgb.txt', 'r');
        k = 0;
        rgb = [];
        names = {};
        xy = [];

        while ~feof(f),
            line = fgets(f);
            if line(1) == '#',
                continue;
            end

            [A,count,errm,next] = sscanf(line, '%d %d %d');
            if count == 3
                k = k + 1;
                rgb(k,:) = A' / 255.0;
                names{k} = lower( strtrim(line(next:end)) );
                if mvtb_present
                    xy = tristim2cc( colorspace('RGB->XYZ', rgb) );
                end
            end
        end
        s.rgb = rgb;
        s.names = names;
        if mvtb_present
            s.xy = xy;
        end
        rgbtable = s;
    end

    if isstr(a)
        % map name to rgb/xy
        if a(1)  == '?'
            % just do a wildcard lookup
            r = namelookup(rgbtable, a(2:end), opt);
        else
            r = name2rgb(rgbtable, a, opt);
        end
    elseif iscell(a)
        % map multiple names to rgb
        r = [];
        for name=a,
            rgb = name2rgb(rgbtable, name{1}, opt.xy);
            if isempty(rgb)
                warning('Color %s not found', name{1});
            end
            r = [r; rgb];
        end
    else
        % map values to strings
        switch opt.color
            case 'rgb'
                if numel(a) == 3
                    r = rgb2name(rgbtable, a(:)');
                elseif numcols(a) ~= 3
                    error('RGB data must have 3 columns');
                else
                    r = {};
                    for i=1:numrows(a)
                        r{i} = rgb2name(rgbtable, a(i,:));
                    end
                end

            case 'xyz'
                if numel(a) == 3
                    rgb = colorspace('XYZ->RGB', a(:)');
                    r = rgb2name(rgbtable, rgb);
                elseif numcols(a) ~= 3
                    error('XYZ data must have 3 columns');
                else
                    rgb = colorspace('XYZ->RGB', a);

                    r = {};
                    for i=1:numrows(a)
                        r{i} = rgb2name(rgbtable, rgb(i,:));
                    end
                end

            case 'xy'
                if numel(a) == 2
                    Y = 1;  XYZ = 1/a(2);
                    X = a(1) * XYZ;
                    Z = (1-a(1)-a(2)) * XYZ;
                    rgb = colorspace('XYZ->RGB', [X Y Z]);
                    r = rgb2name(rgbtable, rgb);
                elseif numcols(a) ~= 2
                    error('xy data must have 2 columns');
                else
                    Y = ones(numrows(a),1);  XYZ = 1./a(:,2);
                    X = a(:,1) .* XYZ;
                    Z = (1-a(:,1)-a(:,2)) .* XYZ;
                    rgb = colorspace('XYZ->RGB', [X Y Z]);

                    r = {};
                    for i=1:numrows(a)
                        r{i} = rgb2name(rgbtable, rgb(i,:));
                    end
                end
        end

    end
end

function r = namelookup(table, s)
    s = lower(s);   % all matching done in lower case

    r = {};
    count = 1;
    for k=1:length(table.names),
        if ~isempty( findstr(table.names{k}, s) )
            r{count} = table.names{k};
            count = count + 1;
        end
    end
end

function out = name2rgb(table, s, opt)

    s = lower(s);   % all matching done in lower case

    for k=1:length(table.names),
        if strcmp(s, table.names(k)),
            rgb = table.rgb(k,:);
            switch opt.color
                case 'rgb'
                    out = rgb;
                case 'xy'
                    XYZ = colorspace('RGB->XYZ', r);
                    out = tristim2cc(XYZ);
                case 'xyz'
                    out = colorspace('RGB->XYZ', rgb);
            end
            return;
        end
    end
    out = [];
end

function r = rgb2name(table, v)
    d = table.rgb - ones(numrows(table.rgb),1) * v;
    n = colnorm(d');
    [z,k] = min(n);
    r = table.names{k};
end

function r = xy2name(table, v)
    d = table.xy - ones(numrows(table.xy),1) * v;
    n = colnorm(d');
    [z,k] = min(n);
    r = table.names{k};
end


classdef VademecumPtensorComputer < VademecumVariablesComputer

    properties (Access = private)
       pNorm
    end

    methods (Access = public)

        function obj = VademecumPtensorComputer(d)
            obj.init(d);
            obj.pNorm = d.pNorm;
        end

    end

    methods (Access = protected)

        function computeAmplificators(obj,imx,imy)
            obj.createAmplificatorInput();
            d = obj.amplificatorInput;
            d.pNorm = obj.pNorm;
            ga = AmplificatorComponentsCalculator(d);
            ga.compute();
            obj.vademecumData.variables{imx,imy}.Ptensor = ga.Phomog;
            obj.vademecumData.monomials = ga.monom;
        end

    end

end


function dlY = model(dlX,parameters,hyperparameters,doTraining)

numBlocks = hyperparameters.NumBlocks;
dropoutFactor = hyperparameters.DropoutFactor;

dlY = dlX;

% Residual blocks.
for k = 1:numBlocks
    dilationFactor = 2^(k-1);
    parametersBlock = parameters.("Block"+k);

    dlY = residualBlock(dlY,dilationFactor,dropoutFactor,parametersBlock,doTraining);
end

% Fully connect
weights = parameters.FC.Weights;
bias = parameters.FC.Bias;
dlY = fullyconnect(dlY,weights,bias,'DataFormat','CBT');

end


function [pairs,pOri,cOri] = getP2CPairs(job,varargin)
%

% all parent - child neighbors
pairs = neighbors(job.grains);

isParent = ismember(pairs, job.grains.id(job.isParent));
isChild = ismember(pairs, job.grains.id(job.isChild));

ind = any(isParent,2) & any(isChild,2);
pairs = pairs(ind,:);

% ensure parent is first
doFlip = isChild(ind,1);
pairs(doFlip,:) = fliplr(pairs(doFlip,:));

if  check_option(varargin,'quick') && length(pairs) > 10000
  ind = unique(randi(length(pairs),10000,1));
  pairs = pairs(ind,:);
end

% maybe there is nothing to do
if isempty(pairs)
  pOri = orientation(job.csParent);
  cOri = orientation(job.csChild);
  return
end

% compute the corresponding mean orientations
if job.useBoundaryOrientations

  % identify boundaries by grain pairs
  [gB,pairId] = job.grains.boundary.selectByGrainId(pairs);

  % extract boundary child orientations
  % TODO: this can be done faster
  pOri = job.ebsd('id',gB.ebsdId(:,1)).orientations;
  cOri = job.ebsdPrior('id',gB.ebsdId(:,2)).orientations;

  % average child orientations along the boundaries
  pOri = accumarray(pairId,pOri);
  cOri = accumarray(pairId,cOri);

else

  % simply the mean orientations of the grains
  pOri = job.grains('id',pairs(:,1)).meanOrientation;
  cOri = job.grains('id',pairs(:,2)).meanOrientation;

end

% translate to index if required
if check_option(varargin,'index'), pairs = job.grains.id2ind(pairs); end

end


function output = fourier2crsspctrm(cfg, freq)

% FOURIER2CRSSPCTRM transforms a fourier-containing freq-structure
% into a crsspctrm-containing freq-structure, in which the
% powerspectra are also contained in the cross-spectra, being a
% channelcombination of a channel with itself.
%
% Use as
%   [freq] = fourier2crsspctrm(cfg, freq)
%
% where you have the following configuration options:
%   cfg.channel    = cell-array with selection of channels,
%                    see CHANNELSELECTION for details
%   cfg.channelcmb = cell-array with selection of combinations between
%                    channels, see CHANNELCOMBINATION for details
%   cfg.keeptrials = 'yes' or 'no' (default)
%   cfg.foilim     = 2-element vector defining your frequency limits of
%                    interest. By default the whole frequency range of the
%                    input is taken.
%

% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip 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.
%
%    FieldTrip 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 FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

if ~isfield(cfg, 'channel'),     cfg.channel     = {'all'};                       end
if ~isfield(cfg, 'channelcmb'),  cfg.channelcmb  = {};                            end
if ~isfield(cfg, 'foilim'),      cfg.foilim      = [freq.freq(1) freq.freq(end)]; end
if ~isfield(cfg, 'keepfourier'), cfg.keepfourier = 'no';                          end
if ~isfield(cfg, 'feedback'),    cfg.feedback    = 'text';                        end

%select the channels on which the power-spectra will be computed
chn = ft_channelselection(cfg.channel,freq.label);
for j = 1:length(chn)
  chnindx(j,1) = find(strcmp(chn(j), freq.label));
  %chnindx(j,1) = find(strcmp(chn{j}, freq.label));
end

%convert the channelcombinations to indices
chncmb  = ft_channelcombination(cfg.channelcmb, freq.label);
cmbindx = zeros(size(chncmb,1),2);
for j = 1:size(chncmb,1)
  cmbindx(j,1) = find(strcmp(chncmb(j,1), freq.label));
  cmbindx(j,2) = find(strcmp(chncmb(j,2), freq.label));
  %cmbindx(j,1) = find(strcmp(chncmb{j,1}, freq.label));
  %cmbindx(j,2) = find(strcmp(chncmb{j,2}, freq.label));
end

%dimensionality of the input data
Nrpt   = length(freq.cumtapcnt);
Nfrq   = size(freq.fourierspctrm,3);
Ntim   = size(freq.fourierspctrm,4);
Nchn   = length(chnindx);
Ncmb   = size(cmbindx,1);

%%FIXME
%if Ntim>1, ft_error('correct handling of time-frequency data is not yet implemented, no information about tapers is available'); end

%keeping track of the tapers
%in the case of tfr fourier-data cumtapcnt is highly redundant; for each frequency
%the number of tapers is equal, as well as for each trial, thus it is sufficient to
%reduce the original cumtapcnt to a vector of Ntrlx1 containing the number of tapers
cumtapcnt = freq.cumtapcnt;
if ~isempty(strfind(freq.dimord, 'time')),
  %cumtapcnt is NtrlxNfrqxNtim; create just one column-vector
  cumtapcnt = ones(size(cumtapcnt,1),1).*unique(cumtapcnt(~isnan(cumtapcnt(:))));
end
sumtapcnt = cumsum([0; cumtapcnt(:)]);

powspctrm = zeros(Nrpt, Nchn, Nfrq, Ntim);
progress('init', cfg.feedback, 'computing single-trial power-spectral densities');
for j = 1:Nrpt
  progress(j/Nrpt, 'trial %d/%d\n', j, Nrpt);
  tmp1     = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], chnindx, :, :);
  tmp2     = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], chnindx, :, :);
  powspctrm(j, :, :, :) = squeeze(sum( tmp1 .* conj(tmp2), 1) ./ size(tmp1,1));
end
progress('close');

crsspctrm = complex(zeros(Nrpt, Ncmb, Nfrq, Ntim), zeros(Nrpt, Ncmb, Nfrq, Ntim));
progress('init', cfg.feedback, 'computing single-trial cross-spectral densities');
for j = 1:Nrpt
  progress(j/Nrpt, 'trial %d/%d\n', j, Nrpt);
  tmp1     = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], cmbindx(:,1), :, :);
  tmp2     = freq.fourierspctrm([1+sumtapcnt(j):sumtapcnt(j+1)], cmbindx(:,2), :, :);
  crsspctrm(j, :, :, :) = squeeze(sum( tmp1 .* conj(tmp2), 1) ./ size(tmp1,1));
end
progress('close');

output.dimord = freq.dimord;
output.freq   = freq.freq;
output.label  = chn;
output.labelcmb(:,1) = freq.label(cmbindx(:,1));
output.labelcmb(:,2) = freq.label(cmbindx(:,2));
output.cumtapcnt = freq.cumtapcnt;
try, output.grad = freq.grad; end
try, output.time = freq.time; end
output.powspctrm = powspctrm;
output.crsspctrm = crsspctrm;
if strcmp(cfg.keepfourier, 'yes'), output.fourierspctrm = freq.fourierspctrm; end

if isempty(output.crsspctrm), output = rmfield(output, 'crsspctrm'); end
if isempty(output.labelcmb ), output = rmfield(output, 'labelcmb' ); end

% add information about the version of this function to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id$';

% remember the configuration details of the input data
try, cfg.previous = freq.cfg; end

% remember the exact configuration details in the output
output.cfg = cfg;


%INITCAMERAMATRIX2D  Finds an initial camera matrix from 3D-2D point correspondences
%
%     cameraMatrix = cv.initCameraMatrix2D(objectPoints, imagePoints, imageSize)
%     [...] = cv.initCameraMatrix2D(..., 'OptionName', optionValue, ...)
%
% ## Input
% * __objectPoints__ Vector of vectors of the calibration pattern points in
%   the calibration pattern coordinate space. Cell array of cell array of
%   3-element vectors are accepted `{{[x,y,z],...}, ...}`.
% * __imagePoints__ Vector of vectors of the projections of the calibration
%   pattern points. Cell array of cell array of 2-element vectors are accepted
%   `{{[x,y],...}, ...}`.
% * __imageSize__ Image size in pixels used to initialize the principal point
%   `[w,h]`.
%
% ## Output
% * __cameraMatrix__ Camera matrix 3x3, `A = [fx 0 cx; 0 fy cy; 0 0 1]`
%
% ## Options
% * __AspectRatio__ If it is zero or negative, both `fx` and `fy` are
%   estimated independently. Otherwise, `fx = fy * AspectRatio`. default 1.0
%
% The function estimates and returns an initial camera matrix for the
% camera calibration process. Currently, the function only supports planar
% calibration patterns, which are patterns where each object point has
% z-coordinate=0.
%
% See also: cv.calibrateCamera
%


function parseOut = parser(lexIn)
%STRCONVPARSER    LL(1) parser for mathematical expressions
%  PARSEOUT = STRCONVPARSER(LEXIN) returns a syntax tree of expressions so that
%  it can be converted to a format Chebfun is able to work with. The input,
%  LEXIN, is the output of the method STRCONVLEXER(), and is a cell array of
%  strings, containaining the tokens of strings.
%
%  This method implements a LL(1) parser, a technique from compiler theory. For
%  more details, see e.g.,
%   [1] Aho, Sethi, Ullman, Compilers: Principles, Techniques, and Tools,
%       Addison-Wesley, 1986.
%
% See also: STRINGPARSER, STRINGPARSER/STR2ANON, STRINGPARSER/LEXER.

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

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Developers note: Usually, a parser relies on having access to pointers, which
% is not possible in MATLAB. We get around this issue using global variables.
%
% TODO: Can we now get around this? See #515.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Initialize all global variables
global NEXT
global COUNTER
global LEX
global STACK

% Enter the main routine
parseMain(lexIn);

% Return the stored stack
parseOut = STACK;

% Clear all global variables
NEXT = [];
COUNTER = [];
LEX = [];
STACK = [];

end

function parseMain(lexIn)
%PARSEMAIN  The main parsing routine, starts the recursive parsing.

global NEXT
global STACK
global LEX
global COUNTER

COUNTER = 1;
LEX = lexIn;
NEXT = char(LEX(COUNTER, 2));
STACK = [];

% Our expression can only start with certain labels, make sure we are
% starting with one of them.
validTypes = {'NUM', 'VAR', 'INDVAR', 'PDEVAR', 'LAMBDA',...
            'FUNC1', 'FUNC2', 'FUNC3', 'UN-', 'UN+', 'LPAR'};

if ( any(strcmp(NEXT, validTypes)) )

    % Enter the recursion and check for successful termination.
    parseExpA();

    % We've put a $ at the end of the lexer output. Hence, we have only
    % successfully parsed our string if the only remaining token left is a
    % $ sign.
    success = match('$');

    if ( ~success )
        reportError('Parse:end', ...
            'Input expression ended in unexpected manner.');
    end

else

    reportError('Parse:start', 'Input field started with unaccepted symbol.');

end

end

% The following is the allowed grammar of mathematical expressions in the
% chebgui (¬ denotes an empty symbol):
%
%   ExpA    -> ExpA   COMMA  Exp0
%   ExpA    -> Exp0
%   Exp0    -> Exp0   OP=    Exp05
%   Exp0    -> Exp05
%   Exp05   -> Exp05  OPREL  Exp1       where OPREL can be OP>, OP>=, OP<, OP<=
%   Exp05   -> Exp1
%   Exp1    -> Exp1   OP+    Exp2
%   Exp1    -> Exp1   OP-    Exp2
%   Exp1    -> Exp2
%   Exp2    -> Exp2   OP*    Exp3
%   Exp2    -> Exp2   OP/    Exp3
%   Exp2    -> Exp3
%   Exp3    -> Exp3   OP^    Exp4
%   Exp3    -> Exp4
%   Exp4    ->        UN+    Exp4
%   Exp4    ->        UN-    Exp4
%   Exp4    -> Exp5
%   Exp5    -> NUM
%   Exp5    -> INDVAR
%   Exp5    -> PDEVAR
%   Exp5    -> LAMBDA
%   Exp5    -> VAR
%   Exp5    -> VAR ExpDer
%   Exp5    -> VAR LPAR ExpList RPAR
%   Exp5    -> VAR ExpDer LPAR ExpList RPAR
%   Exp5    -> FUNC1 LPAR Exp1 RPAR
%   Exp5    -> FUNC2 LPAR Exp1 COMMA Exp1 RPAR]
%   Exp5    -> FUNC3 LPAR Exp1 COMMA Exp1 COMMA Exp1 RPAR
%   Exp5    -> LPAR Exp1 RPAR
%   ExpDer  -> DER
%   ExpDer  -> ¬
%   ExpList -> Exp1
%   ExpList -> Exp1 COMMA STR

function parseExpA()

parseExp0();
parseExpApr();

end

function parseExp0()

parseExp05();
parseExp0pr();

end

function parseExp05()

parseExp1();
parseExp05pr();

end

function parseExp1()

parseExp2();
parseExp1pr();

end

function parseExp2()

parseExp3();
parseExp2pr();

end

function parseExp3()

parseExp4();
parseExp3pr();

end

function parseExp4()

parseExp5();

end

function parseExp5()

global NEXT
global COUNTER
global LEX

% We begin by checking whether we have hit a terminal case. In that case,
% we push that into the stack. We need to treat variables with _ in the
% names separately, as we only allow certain operators around the time
% derivative.
if ( strcmp(NEXT, 'VAR') )
    % Create a new tree for later use, corresponding to the dependent
    % variable
    tempLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...
        'pdeflag', 0);

    % Push the variable onto the stack so that we can take the correct
    % actions if we have derivatives or expressions on the form u(...)
    % involved. If not, we'll simply pop it later.
    push(tempLeaf);

    % Begin by advancing as usual.
    advance();

    % If there follows a derivative symbol, ', we parse that
    parseExpDer();

    % If we then have a u(3) or u(3,left) situation (or u'(3) etc.), we
    % parse that as required
    parseExpList();

elseif ( any(strcmp(NEXT, {'NUM', 'INDVAR', 'LAMBDA', 'STR'})) )
    newLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...
        'pdeflag', 0);
    push(newLeaf);
    advance();

elseif ( strcmp(NEXT, 'PDEVAR') )
    newLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...
        'pdeflag', 1);
    push(newLeaf);
    advance();

elseif ( strcmp(NEXT, 'FUNC1') ) % Functions which take one argument
    parseFunction1();

elseif ( strcmp(NEXT, 'FUNC2') ) % Functions which take two arguments
    parseFunction2();

elseif ( strcmp(NEXT, 'FUNC3') ) % Functions which take three arguments
    parseFunction3();

elseif ( strcmp(NEXT, 'LPAR') )
    advance();
    parseExp05();

    % Check if NEXT symbol is ')' as it should be. If not, there is a
    % parenthesis imbalance in the expression and we return an error.
    m = match('RPAR');
    if ( ~m )
        reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')
    end

elseif  ( strcmp(NEXT, 'UN-') || strcmp(NEXT, 'UN+') || ...
          strcmp(NEXT, 'OP-') || strcmp(NEXT,'OP+') )
    % If + or - reaches this far, we have an unary operator.
    % ['UN', char(NEXT(3))] determines whether we have UN+ or UN-.
    newCenterNode = {{char(LEX(COUNTER)), ['UN', char(NEXT(3))]}};
    advance();
    parseExp4();

    rightArg = pop();

    pdeflag = rightArg.pdeflag;

    newTree = struct('center', newCenterNode, 'right', rightArg, ...
        'pdeflag',pdeflag);
    push(newTree);
else

    reportError('Parse:terminal', ...
        ['Unrecognized character in input field:', NEXT]);
end

end

function parseFunction1()

global COUNTER
global LEX

functionName = char(LEX(COUNTER));
advance();

if ( match('LPAR') )
    parseExp1();

    if ( match('COMMA') )
        reportError('Parse:func1', ...
            ['Method ''', functionName, ''' only takes one input argument.']);
    elseif ( ~match('RPAR') )
        reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')
    end

    rightArg =  pop();
    if ( rightArg.pdeflag )
        error('CHEBFUN:STRINGPARSER:parser:PDE', ...
            'Cannot use time derivative as function arguments.')
    end
    % Can assume no pde if we reach here
    newTree = struct('center', {{functionName, 'FUNC1'}}, ...
        'right', rightArg, 'pdeflag', 0);
    push(newTree);
else
    reportError('Parse:parenths', ...
        'Need parenthesis when using functions in input fields.')
end

end

function parseFunction2()

global NEXT
global COUNTER
global LEX

% Function which allow one or two arguments
oneArgAllowed = {'diff', 'cumsum', 'airy', 'mean'};
functionName = char(LEX(COUNTER));
advance();

% Here we need ( as the next symbol
if ( strcmp(NEXT, 'LPAR') )
    advance();
    parseExp1();

    firstArg =  pop();
    if ( firstArg.pdeflag )
        error('CHEBFUN:STRINGPARSER:parser:PDE', ...
            'Cannot use time derivative as function arguments.')
    end

    % Check whether we have a comma, if so, continue as normal
    if ( match('COMMA') )
        parseExp1();
        m = match('RPAR');
        if ( ~m )
            reportError('Parse:parenths', ...
                'Parenthesis imbalance in input fields.')
        end

        secondArg =  pop();
        if ( secondArg.pdeflag )
            error('CHEBFUN:STRINGPARSER:parser:PDE', ...
                'Cannot use time derivative as function arguments.')
        end

        % Can assume no pde if we reach here
        newTree = struct('left', firstArg, ...
            'center', {{functionName, 'FUNC2'}}, ...
            'right', secondArg,'pdeflag',0);
        push(newTree);

    elseif ( match('RPAR') )
        if ( any(strcmp(functionName, oneArgAllowed)) )
            % Have hit a function which allows one or two args.

            % If we only had one argument, we convert the function to type
            % FUNC1.  Can assume no PDE if we reach here
            newTree = struct('center', {{functionName, 'FUNC1'}}, ...
                'right', firstArg, 'pdeflag', 0);
            push(newTree);
        else
            % We tried to call a method which requires two args with only one.
            reportError('Parse:func2', ['Method ''', functionName, ...
                ''' requires two input arguments.']);
        end

    else
        reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')
    end

else
    reportError('Parse:parenths', ...
        'Need parenthesis when using functions in input fields.')
end

end

function parseFunction3()

global NEXT
global COUNTER
global LEX

% Function which allow one or two arguments
oneArgAllowed = {'sum', 'integral'};
twoArgAllowed = {'feval', 'fred', 'volt'};
functionName = char(LEX(COUNTER));
advance();

% Here we need ( as the next symbol
if ( strcmp(NEXT, 'LPAR') )
    advance();
    parseExp1();
    firstArg = pop();
    if ( firstArg.pdeflag )
        error('CHEBFUN:STRINGPARSER:parser:PDE', ...
            'Cannot use time derivative as function arguments.')
    end

    % Check whether we have a comma, if so, continue as normal
    if ( match('COMMA') )
        parseExp1();
        secondArg = pop();
        if ( secondArg.pdeflag )
            error('CHEBFUN:STRINGPARSER:parser:PDE', ...
                'Cannot use time derivative as function arguments.')
        end

        if ( match('COMMA') ) % and again
            parseExp1();
            thirdArg = pop();

            % Define the new branch
            newTree = struct('left', firstArg, ...
                'center', {{functionName, 'FUNC3'}}, ...
                'right', secondArg, 'arg', thirdArg, 'pdeflag', 0);

            if ( ~match('RPAR') ) % Check the final parenthesis
                reportError('Parse:parenths', ...
                    'Parenthesis imbalance in input fields.')
            end
        elseif ( match('RPAR') && any(strcmp(functionName, twoArgAllowed)) )
            % This was actually a two argument function in disguise
            newTree = struct('left', firstArg, ...
                'center', {{functionName, 'FUNC2'}},...
                'right', secondArg, 'pdeflag', 0);
        else
            reportError('Parse:parenths', ...
                'Parenthesis imbalance in input fields.')
        end
        push(newTree);

    elseif ( match('RPAR') )
        if ( any(strcmp(functionName,oneArgAllowed)) )
            % Have hit a function which allows one or two args.

            % If we only had one argument, convert the function to type FUNC1.
            % Can assume no PDE if we reach here.
            newTree = struct('center', {{functionName, 'FUNC1'}}, ...
                'right', firstArg, 'pdeflag', 0);
            push(newTree);
        else
            % We tried to call a method which requires two args with only one.
            reportError('Parse:func2', ['Method ''', functionName, ...
                ''' requires two input arguments.']);
        end

    else
        reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')
    end

else
    reportError('Parse:parenths', 'Need parenthesis when using functions in input fields.')
end

end

function parseExp1pr()

global NEXT

if ( strcmp(NEXT, 'OP+') )

    advance();
    leftArg  = pop();
    parseExp2();
    rightArg = pop();

    pdeflag = leftArg.pdeflag || rightArg.pdeflag;

    newTree = struct('left', leftArg, 'center', {{'+', 'OP+'}}, ...
        'right', rightArg, 'pdeflag', pdeflag);
    push(newTree);
    parseExp1pr();

elseif ( strcmp(NEXT, 'OP-') )
    advance();
    leftArg  = pop();
    parseExp2();
    rightArg = pop();

    pdeflag = leftArg.pdeflag || rightArg.pdeflag;
    newTree = struct('left', leftArg, 'center', {{'-', 'OP-'}}, ...
        'right', rightArg, 'pdeflag', pdeflag);
    push(newTree);
    parseExp1pr();
elseif ( strcmp(NEXT, 'RPAR') || strcmp(NEXT, '$') || strcmp(NEXT, 'OP=') )
	% Do nothing
else % If we don't have ) or the end symbol now something has gone wrong.
%     reportError('Parse:end','Syntax error in input fields.')
end

end

function parseExp2pr()

global NEXT

if ( strcmp(NEXT,'OP*') )
    leftArg  = pop();   % Pop from the stack the left argument
    advance();          % Advance in the input
    parseExp3();
    rightArg = pop();  % Pop from the stack the right argument

    % Check whether we have _ variables
    if ( leftArg.pdeflag || rightArg.pdeflag )
        error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot multiply time derivative')
    end

    % Can assume no PDE if we reach here
    newTree = struct('left', leftArg, 'center', {{'.*', 'OP*'}}, ...
        'right', rightArg, 'pdeflag', 0);
    push(newTree);
    parseExp2pr();

elseif ( strcmp(NEXT,'OP/') )
    leftArg  = pop();   % Pop from the stack the left argument
    advance();          % Advance in the input
    parseExp3();
    rightArg = pop();  % Pop from the stack the right argument

    % Check whether we have _ variables
    if ( leftArg.pdeflag || rightArg.pdeflag )
        error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot divide with time derivatives')
    end

    % Can assume no PDE if we reach here
    newTree = struct('left', leftArg, 'center', {{'./', 'OP/'}}, ...
        'right', rightArg, 'pdeflag', 0);
    push(newTree);
    parseExp2pr();
else
    % Do nothing
end

end

function parseExp3pr()

global NEXT

if ( strcmp(NEXT,'OP^') )
    leftArg  = pop();
    advance();
    parseExp4();
    rightArg = pop();

    % Check whether we have _ variables
    if ( leftArg.pdeflag || rightArg.pdeflag )
        error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot take powers with time derivative')
    end

    % Can assume no pde if we reach here
    newTree = struct('left', leftArg, 'center', {{'.^', 'OP^'}}, ...
        'right', rightArg, 'pdeflag', 0);
    push(newTree);
    parseExp3pr();

elseif ( ~isempty(strfind(NEXT, 'DER')) )
    leftArg  = pop();

    % Check whether we have _ variables
    if ( leftArg.pdeflag )
        error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot differentiate time derivative')
    end

    newTree = struct('center', {{'D', NEXT}}, 'right', leftArg, 'pdeflag', 0);
    push(newTree);
    advance();
    parseExp3pr();
else
    % Do nothing
end

end

function parseExpDer()
% parseExpDer deals with ' denoting derivatives on the dependent variables
% in the problem.

global NEXT

if ( ~isempty(strfind(NEXT, 'DER')) )
    leftArg  = pop();

    % Check whether we have _ variables
    if ( leftArg.pdeflag )
        error('CHEBFUN:STRINGPARSER:parser:PDE','Cannot differentiate time derivative')
    end

    newTree = struct('center', {{'D', NEXT}}, 'right', leftArg, 'pdeflag', 0);
    push(newTree);
    advance();
else
    % Do nothing
end

end

function parseExpList()
% parseExpList deals with potential arguments to the dependent variables in
% the problem, e.g. u(3,left).

global NEXT
global COUNTER
global LEX

if ( match('LPAR') ) % We are in a u(3) or u(3,left) situation
    % The first argument expression can only be of type EXP05 or higher
    % (no = or comma-dividers are allowed)
    parseExp1();
    % Check whether we are in in u(3) or u(3,left) situation. If we
    % have a match with ), we must have a feval with two arguments. If
    % we have a match with a comma, we must have a feval with three
    % arguments, but if there is no match, we have parenthesis
    % imbalance.
    if ( match('RPAR') )
        % Here we only had one argument in u(...), so we create a feval of type
        % FUNC2 (since the feval method has two input arguments)
        secondArg = pop();
        firstArg = pop();

        % Can assume no PDE if we reach here
        newTree = struct('left', firstArg, 'center', {{'feval', 'FUNC2'}}, ...
            'right', secondArg,'pdeflag', 0);
        push(newTree);

    elseif ( match('COMMA') )
        % Here we only had two arguments in u(...), so we create a
        % feval of type FUNC3 (since the feval method has three input
        % arguments)

        % Check whether we have any of the allowed option type as the
        % second argument. If not, throw an error.
        if ( strcmp(NEXT,'STR') )
            % We got a match! But we also need to check for parenthesis
            % balance. Store the option as a temporary leaf
            optLeaf = struct('center', {{char(LEX(COUNTER)), char(NEXT)}}, ...
                'pdeflag', 0);
            % Advance and check for parenth. balance
            advance();
            if ( match('RPAR') )
                % Create a feval of type FUNC3 (since the feval method
                % has three input arguments)
                secondArg = pop();
                firstArg = pop();
                thirdArg = optLeaf;

                % Can assume no pde if we reach here
                newTree = struct('left', firstArg, ...
                    'center', {{'feval', 'FUNC3'}}, 'right', secondArg, ...
                    'arg',thirdArg, 'pdeflag', 0);
                push(newTree);
            else
                reportError('Parse:parenths', ...
                    'Parenthesis imbalance in input fields.')
            end
        else
            reportError('Parse:secondArg', ...
                'Invalid second argument to u(0,...) type of expression.')
        end

    else % There must be a parenthesis imbalance.
        reportError('Parse:parenths', 'Parenthesis imbalance in input fields.')
    end
else % We reach here for the default behaviour, e.g. u' = 1, no parentheses involved
    % Do nothing, since we've already pushed the variable onto the
    % stack.
end

end

function parseExp0pr()

global NEXT

if ( strcmp(NEXT, 'OP=') )

    leftArg  = pop();
    advance();
    parseExp05();

    rightArg = pop();

    pdeflag = leftArg.pdeflag || rightArg.pdeflag;

    newTree = struct('left', leftArg, 'center', {{'=', 'OP='}}, ...
        'right', rightArg, 'pdeflag', pdeflag);
    push(newTree);
else
	% Do nothing
end

end

function parseExpApr()

global NEXT

if ( strcmp(NEXT, 'COMMA') )

    advance();
    leftArg  = pop();
    parseExpA();
    rightArg = pop();

    pdeflag = leftArg.pdeflag || rightArg.pdeflag;

    newTree = struct('left', leftArg, 'center', {{',', 'COMMA'}}, ...
        'right', rightArg, 'pdeflag', pdeflag);
    push(newTree);
else
	% Do nothing
end

end

function parseExp05pr()

global NEXT

if ( any(strcmp(NEXT, {'OP>', 'OP>=', 'OP<', 'OP<='})) )
    tempOpType = NEXT;
    tempOpLabel = tempOpType(3:end);

    advance();
    leftArg  = pop();
    parseExp1();
    rightArg = pop();

    pdeflag = leftArg.pdeflag || rightArg.pdeflag;

    newTree = struct('left', leftArg, 'center', {{tempOpLabel, tempOpType}}, ...
        'right', rightArg, 'pdeflag', pdeflag);
    push(newTree);
else
	% Do nothing
end

end

function advance()
%ADVANCE    Move to the next token in the output from the lexer.
global NEXT
global COUNTER
global LEX

COUNTER = COUNTER + 1;
NEXT = char(LEX(COUNTER,2));

end

function m = match(label)

global NEXT
m = strcmp(label, NEXT);

% If we found a match and are not at the end of output, we want to advance
% to the NEXT symbol
if ( m && ~strcmp(label, '$') )
    advance();
end

end

function push(new)
%PUSH   Push a tree to the stack of syntax trees
global STACK

if ( ~stackRows() )
    STACK = new;
else
    % Ensure number of fields matches
    [STACK, new] = mergeFields(STACK, new);
    % Update the Stack
    STACK = [STACK ; new];
end

end

function p = pop()
%POP    Pop a tree from the stack.
global STACK

% Throw a sensible error if we have an empty stack
if ( isempty(STACK) )
    reportError('Parse:end', 'Syntax error in input expression (Empty stack)');
end

p = STACK(end,:);
STACK(end,:) = [];

end

function m = stackRows()

global STACK
[m, n] = size(STACK); %#ok<NASGU>

end

% TODO:  Can we get rid of this function entirely?
function reportError(id, msg)

error(['CHEBFUN:', id], msg);
% ME = MException(id,msg);
% throw(ME);

end

function [a, b] = mergeFields(a, b)

aFields = fieldnames(a);
bFields = fieldnames(b);

for k = 1:numel(aFields)
    if ( ~isfield(b, aFields{k}) )
        b.(aFields{k}) = [];
    end
end

for k = 1:numel(bFields)
    if ( ~isfield(a, bFields{k}) )
        a.(bFields{k}) = [];
    end
end

end


function show_per_class_table( soa, soa_ids, res_id, measure )

% Pascal classes names
classes={'aeroplane', 'bicycle'  , 'bird'       , 'boat'       ,...
         'bottle'   , 'bus'      , 'car'        , 'cat'        ,...
         'chair'    , 'cow'      , 'diningtable', 'dog'        ,...
         'horse'    , 'motorbike', 'person'     , 'pottedplant',...
         'sheep'    , 'sofa'     , 'train'      , 'tvmonitor'  };

% Allocate
all_res = zeros(length(soa_ids),length(classes)+1);
ncands = zeros(length(res_id),1);

% Fill
for ii=1:length(soa_ids)
    ncands(ii) = soa.(soa_ids{ii}).mean_n_masks(res_id(ii));
    for kk=1:length(classes)
        if strcmp(measure,'jaccard_object')
            res = soa.(soa_ids{ii}).per_class_results{kk}.meanmax;
        else
            res = soa.(soa_ids{ii}).per_class_results{kk}.global_J;
        end
        all_res(ii,kk) = res(res_id(ii));
    end
    res = soa.(soa_ids{ii}).(measure);
    all_res(ii,end) = res(res_id(ii));
end

% Get the maximums to set in boldface
[~,max_ids] = max(all_res,[],1);
disp(['MCG is the best in ' num2str(sum(max_ids(1:end-1)==1)) ' categories'])

% Show header
to_disp = '    Method &   NCands & ';
for kk=1:length(classes)
    to_disp = [to_disp sprintf('%14s',classes{kk}) ' & ']; %#ok<AGROW>
end
to_disp = [to_disp '        Global \\'];
disp(to_disp)

% Show table
for ii=1:length(soa_ids)
    curr_n_reg = soa.(soa_ids{ii}).mean_n_masks(res_id(ii));
    to_disp = [sprintf('%10s', soa_ids{ii}) ' & ' sprintf('%4s%d',' ', round(curr_n_reg)) ' & '];
    for kk=1:length(classes)
        if (ii==max_ids(kk))
            to_disp = [to_disp sprintf('%13s',['\textbf{' sprintf('%2.1f',100*all_res(ii,kk))]) '} & ']; %#ok<AGROW>
        else
            to_disp = [to_disp sprintf('%13s',sprintf('%2.1f',100*all_res(ii,kk))) '  & ']; %#ok<AGROW>
        end
    end
    if (ii==max_ids(end))
        to_disp = [to_disp sprintf('%13s',['\textbf{' sprintf('%2.1f',100*all_res(ii,end))]) '} \\ ']; %#ok<AGROW>
    else
        to_disp = [to_disp sprintf('%13s',sprintf('%2.1f',100*all_res(ii,end))) '  \\']; %#ok<AGROW>
    end
    disp(to_disp)
end

end


function tdetx = tdet(x,K)
% tdetx = tdet(x,K)
%
% TDET  Computes twice determinant for Lorentz block
%
% **********  INTERNAL FUNCTION OF SEDUMI **********
%
% See also sedumi

% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA  (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
%   Dept. Econometrics & O.R., Tilburg University, the Netherlands.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
%   Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
%   CRL, McMaster University, Canada.
%   Supported by the Netherlands Organization for Scientific Research (NWO).
%
% 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.,  51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA

if isempty(K.q)
    tdetx = zeros(0,1);
else
    ix = K.mainblks;
    tdetx = x(ix(1):ix(2)-1).^2 - ddot(x(ix(2):ix(3)-1),x,K.qblkstart);
end


function Tr_Im=rotate3D(Im, T, R)
% rotate 3D volume by T & R

[row,col,layer] = size(Im);
Tr_Im = tformarray(Im, T, R, [1 2 3], [1 2 3], [row, col,layer], [], []);

end


classdef PoleFigure < dynProp & dynOption
%
% The class *PoleFigure* is used to store experimetnal pole figure
% intensitied, i.e., XRD, synchrotron or neuron data. It provides several
% <PoleFigureCorrection.html data correction methods> as well as the
% <PoleFigure2ODF.html reconstruction of an orientation density function
% (ODF)>. Importing pole figure data is explained in <PoleFigureImport.html
% this section>.
%
% Input
%  h     - crystal directions (@vector3d | @Miller)
%  r     - specimen directions (@S2Grid)
%  intensities - diffraction counts (double)
%  CS,SS - crystal, specimen @symmetry
%
% Options
%  superposition - weights for superposed crystal directions
%  background    - background intensities
%
% Class Properties
%  allH - cell of @Miller
%  allR - cell of @vector3d
%  allI - cell of diffraction intensities
%  c    - structure coefficients
%  SS   - specimen symmetry
%
% Dependent Class Properties
%  CS      - @crystalSymmetry
%  h       - @Miller direction of single pole figure
%  r       - specimen directions
%  intensities - diffraction intensities
%  antipodal -
%
% See also
% ImportPoleFigureData loadPoleFigure loadPoleFigure_generic
% This section describes the class *PoleFigure* and gives an overview of
% the functionality MTEX offers to analyze pole figure data.

  properties
    allH = {}           % crystal directions
    allR = {}           % specimen directions
    allI = {}           % intensities
    c = {}              % structure coefficients for superposed pole figures
    SS = specimenSymmetry       % specimen symmetry
  end

  properties (Dependent = true)
    CS                  % crystal symmetry
    h                   % crystal direction of single pole figure
    r                   % specimen directions
    intensities         % diffraction intensities
    antipodal
  end

  methods

    function pf = PoleFigure(h,r,intensities,varargin)
      % constructor

      if nargin == 0, return;end

      pf.allH = ensurecell(h);
      pf.allR = ensurecell(r);
      if numel(pf.allR) == 1, pf.allR = repmat(pf.allR,size(pf.allH));end
      if ~check_option(varargin,'complete'), pf.allR{1}.antipodal = true;end
      pf.allI = ensurecell(intensities);

      pf.c = ensurecell(get_option(varargin,'superposition',...
        cellfun(@(x) ones(1,length(x)),pf.allH,'uniformoutput',false)));

      % normalize structure coefficients
      %pf.c = cellfun(@(x) x./sum(x),pf.c,'uniformOutput',false);

      % extract symmetries
      pf.CS = getClass(varargin,'crystalSymmetry',pf.CS);
      pf.SS = getClass(varargin,'specimenSymmetry',pf.SS);

    end

    function pf = set.CS(pf,CS)

      for i = 1:length(pf.allH)
        pf.allH{i}.CS = CS;
      end
    end

    function CS = get.CS(pf)

      CS = pf.allH{1}.CS;

    end

    function h = get.h(pf)
      h = pf.allH;
      h = horzcat(h{:});
    end

    function r = get.r(pf)
      try
        r = [pf.allR{:}];
      catch
        for i = 1:numel(pf.allR)
          pf.allR{i} = pf.allR{i}(:);
        end
        r = vertcat(pf.allR{:});
      end
    end

    function i = get.intensities(pf)
      try
        i = [pf.allI{:}];
      catch
        for i = 1:numel(pf.allI)
          pf.allI{i} = pf.allI{i}(:);
        end
        i = vertcat(pf.allI{:});
      end
    end

    function pf = set.intensities(pf,i)

      if numel(i) == 1
        for ipf = 1:numel(pf.allI)

          pf.allI{ipf} = i*ones(size(pf.allI{ipf}));

        end
      else
        cs = cumsum([0,cellfun('prodofsize',pf.allI)]);

        for ipf = 1:numel(pf.allI)
          pf.allI{ipf} = reshape(i(cs(ipf)+1:cs(ipf+1)),size(pf.allI{ipf}));
        end
      end
    end

    function out = get.antipodal(pf)
      out = pf.allR{1}.antipodal;
    end

    function pf = set.antipodal(pf,value)
      for i = 1:pf.numPF
        pf.allR{i}.antipodal = value;
      end
    end

    function varargout = size(pf,varargin)
      [varargout{1:nargout}] = size(pf.r,varargin{:});
    end

    function varargout = length(pf,ip)
      if nargin == 2
        if isempty(ip)
          varargout{1} = cellfun(@length,pf.allR);
        else
          [varargout{1:nargout}] = length(pf.allR{ip});
        end
      else
        [varargout{1:nargout}] = length(pf.r);
      end
    end

    function n = numPF(pf)
      n = numel(pf.allH);
    end

    function e = end(pf,i,n)
      % overloaded end function

      if n==1
        e = numel(pf.r);
      else
        e = size(pf.r,i);
      end
    end

  end

  methods (Static = true)
    [pf,interface,options] = load(fname,varargin)
  end

end


function y = residuals(fit,type)

% Residuals (or a few other things) from a locfit() fit.
%
% Input arguments:
%   fit - the locfit() fit.
%   type (optional) type of residuals. Valid types are
%     'dev'    (deviance, the default)
%     'd2'     (deviance squared)
%     'pearson'(Pearson)
%     'raw'    (observed - fitted)
%     'ldot'   (derivative of log-likelihood)
%     'lddot'  (second derivative)
%     'fit'    (fitted values - no transformation)
%     'mean'   (fitted values - with back transformation)
%
%  Author: Catherine Loader.

if (nargin<2) type = 'dev'; end;

y = predict(fit,'d','restyp',type);

return;


function [vin, vout] = EdgeExtract(img, imgf)
    S = im2double(img);
    vin = [diff(S,1,1); S(1,:,:) - S(end,:,:)];
    img_filtered = im2double(imgf);
    S = im2double(img_filtered);
    vout = [diff(S,1,1); S(1,:,:) - S(end,:,:)];
end


% MatrixUser, a multi-dimensional matrix analysis software package
% https://sourceforge.net/projects/matrixuser/
%
% The MatrixUser is a matrix analysis software package developed under Matlab
% Graphical User Interface Developing Environment (GUIDE). It features
% functions that are designed and optimized for working with multi-dimensional
% matrix under Matlab. These functions typically includes functions for
% multi-dimensional matrix display, matrix (image stack) analysis and matrix
% processing.
%
% Author:
%   Fang Liu <leoliuf@gmail.com>
%   University of Wisconsin-Madison
%   Aug-30-2014

% load image matrix from system screenshot

function MU_load_screenshot(handles)

try
    import java.awt.*;
    rob=Robot;
    t=java.awt.Toolkit.getDefaultToolkit();
    rec=java.awt.Rectangle(t.getScreenSize());
    img=rob.createScreenCapture(rec);
    filehandle=java.io.File('__scrnsht_temp.bmp');
    javax.imageio.ImageIO.write(img,'bmp',filehandle);
    imdata = imread('__scrnsht_temp.bmp','bmp'); % temporary file
    delete('__scrnsht_temp.bmp'); % temp file removed
    if ~MU_load_matrix('sns', imdata, 1)
        error('Loading image from screenshot failed!');
    end

catch me
    error_msg{1,1}='Error!!! Getting image information from system screenshot aborted.';
    error_msg{2,1}=me.message;
    errordlg(error_msg);
    return;
end

end


function my_grad(V,F,u,k)
%MY_GRAD Compute the numerical gradient operator for triangle meshes
%
% my_grad(V,F);
%
% Inputs:
%  V,F  the input mesh for which to compute the gradient operator
% Outputs:
%  G  the sparse gradient matrix
%

G = ...

end


function [ res ] = pesq3( reference_sig, degraded_sig, Fs, fileNum )
% A wrapper for the objective Perceptual Evaluation of Speech Quality measure
%
% Syntax:	[ res ] = pesq3( reference_sig, degraded_sig, Fs, fileNum )
%
% Inputs:
% 	reference_sig - Reference (clean, talker, sender) speech signal
% 	degraded_sig - Degraded (noisy, listener, receiver) speech signal
% 	Fs - Sampling Frequency
%   fileNum - An ID number to append to the temporary audio files. Useful
%   when several instances are to be run together (in parallel).
%
% Outputs:
% 	res - Raw PESQ result for narrowband and MOS-LQO result for wideband
%
% See also: pesq2mos.m

% Author: Jacob Donley
% University of Wollongong
% Email: jrd089@uowmail.edu.au
% Copyright: Jacob Donley 2017
% Date: 03 October 2015
% Revision: 0.1
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin < 4
    fileNum = 0;
end
temp_path = [pwd filesep '+Miscellaneous\+Temporary\'];
ref_path = [ 'tmp_ref' num2str(fileNum) '.wav'];
deg_path = [ 'tmp_deg' num2str(fileNum) '.wav'];

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

max_val = max(abs([reference_sig(:); degraded_sig(:)]));

audiowrite([temp_path ref_path], reference_sig / max_val, Fs);
audiowrite([temp_path deg_path], degraded_sig / max_val, Fs);

res = pesq2_mtlb(ref_path, ...
                 deg_path, ...
                 Fs, 'wb', [pwd filesep '+Tools\pesq_NoResFile.exe'], ...
                 temp_path);

end


% dim_red_type: dimension reduction type: one of the strings: '', 'pca', 'ica'
% new_dim: relevant only if dim_red_type is not ''
function lmm(numClusters, is_sampled, dim_red_type, new_dim, numOfEMIter, numOfCpus)

    fv_init;

    if ~exist('numOfEMIter', 'var')
        numOfEMIter = 10;
    end

    if ~exist('numOfCpus', 'var')
        numOfCpus = 4;
    end

    word2vec_sqrt = false;

    mult_factor = LMM_HGLMM_MULT_FACTOR;

    output(1, 'LMM_HGLMM_MULT_FACTOR = %d\n', LMM_HGLMM_MULT_FACTOR);

    vectors_file_name = add_data_dir_base('GoogleNews_vectors_norm.mat');
    output_file_name = add_data_dir_base(sprintf('GoogleNews_norm_lmm_%d.mat', numClusters));

    if word2vec_sqrt
        vectors_file_name = fname_concat(vectors_file_name, '_sqrt');
        output_file_name = fname_concat(output_file_name, '_sqrt');
    end

    if is_sampled
        vectors_file_name = fname_concat(vectors_file_name, '_sampled');
        output_file_name = fname_concat(output_file_name, '_sampled');
    end

    if strcmp(dim_red_type,'pca') || strcmp(dim_red_type,'ica')
        post_fix = sprintf('_%s_%d', dim_red_type, new_dim);
        vectors_file_name = fname_concat(vectors_file_name, post_fix);
        output_file_name = fname_concat(output_file_name, post_fix);
    end

    output(1, 'reading vectors file %s\n', vectors_file_name);
    load(vectors_file_name);
    output(1, 'done\n');

    output(1, 'Calculating LMM, %d clusters\n', numClusters);

    % multiply by LMM_HGLMM_MULT_FACTOR=10 due to numerical issue
    % transpose because the rows should be the samples
    vectors_ = mult_factor * vectors_';

    % create a random initialization
    initPriors = (1.0 / numClusters) * ones(numClusters,1);
    muInit=vectors_(randsample(size(vectors_,1),numClusters),:);
    init_b=repmat(sum(abs(vectors_ - repmat(median(vectors_),size(vectors_,1),1))) / size(vectors_,1),numClusters,1);

    % calculate LMM

    output(1, 'numOfCpus = %d\n', numOfCpus);
    output(1, 'numOfEMIter = %d\n', numOfEMIter);

    [n_means,n_covariances,n_priors,samplesWeightsOut]=LMMMex(double(vectors_), double(muInit), double(init_b), double(initPriors), numOfEMIter, 0.01, numOfCpus);

    save(output_file_name, 'n_means', 'n_covariances', 'n_priors', 'mult_factor', '-v7.3');

    output(1, 'saved to file: %s\n', output_file_name);
end


clear
close all

plotx2east

load martensite_single_grain

[grains,ebsd('indexed').grainId] =...
    calcGrains(ebsd('indexed'),'angle',3*degree);

cond_grains = ismember(grains.id,unique(ebsd(ids_of_interest).grainId));

%%
job = parentGrainReconstructor(ebsd,grains) % define job
job.useBoundaryOrientations = true;
clearvars grains ebsd

job.p2c = orientation.NishiyamaWassermann(job.p2c.CS,job.p2c.SS);

%%
job.calcHyperGraph2('threshold',5*degree,'c2c')

numIters = [3 10 50];
grainId = 1844;

for k = 1:length(numIters);
    if k == 1
        job.clusterHyperGraph2('numIter',numIters(k),'inflationPower',1,'keepGraph')
        graphplotfunc(job,cond_grains,grainId,k,numIters)
    else
        job.clusterHyperGraph2('numIter',numIters(k) - numIters(k-1),'inflationPower',1,'keepGraph')
        graphplotfunc(job,cond_grains,grainId,k,numIters)
    end
end

for k = 1:length(numIters);
    if k == 1
        job.clusterHyperGraph2('numIter',numIters(k),'inflationPower',1.05,'keepGraph')
        graphplotfunc(job,cond_grains,grainId,k,numIters)
    else
        job.clusterHyperGraph2('numIter',numIters(k) - numIters(k-1),'inflationPower',1.05,'keepGraph')
        graphplotfunc(job,cond_grains,grainId,k,numIters)
    end
end

%%
function graphplotfunc(job,cond_grains,grainId,k,numIters)

pOri = variants(job.p2c, job.grains.meanOrientation, job.votes.parentId(:,1));

nextAxis
plot(job.grains(cond_grains),...
    pOri(cond_grains))
lims = job.ebsd.extent;
xlim([lims(1) lims(2)])
ylim([lims(3) lims(4)])

text(lims(1)+5,lims(4)-10, [num2str(numIters(k)) ' iterations'],...
    'HorizontalAlignment','left',...
    'FontSize',20, 'FontWeight','bold','BackgroundColor', 'white')

end


function [weight] = corn_kernel(data, w, c)
% This program output the final portfolio the CORN strategy on data
% This version has one expert, thus straightforwardly go expert.
%
% function [weight] = corn_kernel(data, w, c)
%
% weight: final portfolio, used for next rebalance
%
% data: market sequence vectors
% w: window size
% c: correlation coefficient threshold
%
% Example: [weight] = corn_kernel(data, w, c);

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

weight = corn_expert(data, w, c);

% if (size(weight, 1) == 1),
%     weight=weight';
% end

end


%Extracts the grid for the grid defined on
%http://www.vision.ee.ethz.ch/~cwengert/calibration_toolbox.php
%
%Input:         im      The image to process
%               show    0 to not display any information graphically
%               minArea The minimum area a grid dot occupies
%               maxArea The minimum area a grid dot occupies
%Output:        success 1 if everything went ok
%               stats   The processed blobs of this image
%               id0     The index of the main bar
%               id1     The index of the second main bar
%               searchPoints    The potential grid points
%
%
%Christian Wengert
%Computer Vision Laboratory
%ETH Zurich
%Sternwartstrasse 7
%CH-8092 Zurich
%www.vision.ee.ethz.ch/cwengert
%wengert@vision.ee.ethz.ch

function [success, stats, cnt, id0, id1, searchPoints] = gridextractor(im, show, minArea, maxArea)
    %crop image
    if(nargin==1)
        show=0;
    end
    success = 0;
    stats = [];
    cnt = 0;
    searchPoints = [];
    %Indices for main bars
    idx = [];
    ids = [];
    id0 = -1;
    id1 = -1;
    x_ = [];
    X_ = [];
    %Show the image
    if(show)
        if(isfloat(im))
             imshow(im/255.0),hold on
        else
            imshow(im),hold on
        end
    end
    %Get the size of the image
    [h,w,bpp] = size(im);
    if(h<=0 & w<=0)
        return
    end
    if(bpp==3)
        img = rgb2gray(im);
    else
        img = im;
    end

    %used to filter for ellipticity
    minEllipticity = 1.95;
    maxEllipticity = 8;
    minSolidity = 0.80;
     %Used to filter by closeness to border->to close to border cannot be
     %correct
    borderRect = [0+50, 0+50, w-50, h-50];

    x0 = w/2;
    y0 = h/2;
    imc = im;
    for i=1:w
        for j=1:h
            r = sqrt((x0-i)*(x0-i) + (y0-j)*(y0-j));
            if(r>160)
                imc(j,i) = 0;
            end
        end
    end

    %Rather median filter
    imb = medfilt2(img,[3 3]);

    %Threshold
    h1 = fspecial('gaussian',100, 15);
    imf= (imfilter(im, h1));
    imt = ( imclose(medfilt2(im<imf,[3 3]), ones(5)))    ;
    %Label
    iml = bwlabel(imt,8);
    %Extract features
    stats=regionprops(iml,'Centroid','Area','Orientation','MajorAxisLength','MinorAxisLength','ConvexHull','BoundingBox','Solidity');

    %Extract values and put them into vectors, just makes it easier
    areas = [stats.Area];
    pts = [stats.Centroid];
    ptsx = pts(1:2:end);
    ptsy = pts(2:2:end);
    majors = [stats.MajorAxisLength];
    minors = [stats.MinorAxisLength];
    solidity = [stats.Solidity];

    %Now get the two major things
    cnt = 0;
    for i=1:length(stats)
        %Filter on closeness to border
        if(stats(i).Centroid(1)>borderRect(1) & stats(i).Centroid(1)<borderRect(3) & stats(i).Centroid(2) > borderRect(2) & stats(i).Centroid(2) <borderRect(4))
            %Filter area
            if(areas(i)>minArea & areas(i)<maxArea & solidity(i) > minSolidity)
                idx = [idx;i];
                %Filter on ellipticity
                if((majors(i)/minors(i))>minEllipticity & (majors(i)/minors(i))<maxEllipticity )
                    if(show)
                        plot(stats(i).Centroid(1),stats(i).Centroid(2),'r+')
                    end
                    ids = [ids;i];
                    cnt = cnt+1;
                    %Delete it from searchPoints, serves as an ellipticity
                    %filter!
                    idx(end) = [];
                end
            end
        end
    end
    %Show area filtered blobs
    if(show)
          for i=1:length(idx)
            plot(stats(idx(i)).Centroid(1),stats(idx(i)).Centroid(2),'go')
        end
    end
    try
        %Extract the main bars
        if(cnt==2)
            if(areas(ids(1))>areas(ids(2)))
                id0 = ids(1); id1 = ids(2);
            else
                id0 = ids(2); id1 = ids(1);
            end
            %Test angle between main lines
            dir0 = (stats(id1).Centroid-stats(id0).Centroid);
            dir0 = dir0/norm(dir0);
            %get the orientation of main bar
            orientation = stats(id0).Orientation;
            y = tand(orientation);
            dir90 = [-1,y];
            dir90 = dir90/norm(dir90);
            %Check angle
            theta = acos((dir0*dir90')/(norm(dir0)*norm(dir90)))/pi*180;
            if(theta<70 | theta>110)
                 disp('gridextractor:: Could not find both main bars, bar-count = 1. ')
                 stats = [];
                 searchPoints = [];
                 success = 0;
                 cnt = 0;
                 id0 = 0;
                 id1 = 0;
            else
                searchPoints = [areas(idx);...
                                ptsx(idx);...
                                ptsy(idx)];
                success = 1;
                if(show)
                    text(stats(id0).Centroid(1)+5,stats(id0).Centroid(2)+5,'0','Color','m');
                    text(stats(id1).Centroid(1)+5,stats(id1).Centroid(2)+5,'1','Color','m');
                end
            end
        elseif(cnt>2)
            disp('gridextractor:: Found too many possible candidates, trying to choose the correct ones')
            %get the two blobs that are closest to each other!
            a = [];
            xb = [];
            %Sort by Area
            for i=1:length(ids)
                xb = [xb, [stats(ids(i)).Centroid(1);stats(ids(i)).Centroid(2)]];
                if(xb(1,i) > 50 | xb(1,i) < (w-50) | xb(2,i) > 50 | xb(2,i) < (h-50))
                    a = [a;stats(ids(i)).Area];
                else
                    a = [a;-1];
                end
            end

            [a,ixxx] = sort(a);
            %Take the two biggest ones
            id0 = ids(ixxx(end));
            id1 = ids(ixxx(end-1));

             %Directions
            dir0 = (stats(id1).Centroid-stats(id0).Centroid);
            dir0 = dir0/norm(dir0);
            %get the orientation of main bar
            orientation = stats(id0).Orientation;
            y = tand(orientation);
            dir90 = [-1,y];
            dir90 = dir90/norm(dir90);
            %Check angle
            theta = acos((dir0*dir90')/(norm(dir0)*norm(dir90)))/pi*180;
            if(theta<80 | theta>100)
                id1 = ids(ixxx(end-2));
                %Test again
                dir0 = (stats(id1).Centroid-stats(id0).Centroid);
                dir0 = dir0/norm(dir0);
                %get the orientation of main bar
                orientation = stats(id0).Orientation;
                y = tand(orientation);
                dir90 = [-1,y];
                dir90 = dir90/norm(dir90);
                %Check angle
                theta = acos((dir0*dir90')/(norm(dir0)*norm(dir90)))/pi*180;
                if(theta<80 | theta>100)
                     disp('gridextractor:: Could not find both main bars, bar-count = 1. ')
                     stats = [];
                     searchPoints = [];
                     success = 0;
                     cnt = 0;
                     id0 = 0;
                     id1 = 0;
                end
            end

            if(show)
                text(stats(id0).Centroid(1)+5,stats(id0).Centroid(2)+5,'0','Color','y');
                text(stats(id1).Centroid(1)+5,stats(id1).Centroid(2)+5,'1','Color','y');
            end
            cnt = 2;
            success = 1;
            searchPoints = [areas(idx);...
                            ptsx(idx);...
                            ptsy(idx)];
        else
            disp('gridextractor:: Could not find both main bars, bar-count = 1. ')
            stats = [];
            searchPoints = [];
            success = 0;
            cnt = 0;
            id0 = 0;
            id1 = 0;
        end
    catch
        disp('gridextractor:: Problems extracting the main bars. Please verify whether it is visible in this image.')
        s = lasterror;
        disp(['gridextractor:: ' s.message ' in function ' s.stack.name ' in ' s.stack.file ' @line ' num2str(s.stack.line)])
        stats = [];
        searchPoints = [];
        success = 0;
        cnt = 0;
        id0 = 0;
        id1 = 0;
    end


function geo_params = drawparticals(geo_param, pf_param)
geo_param = repmat(geo_param, [1,pf_param.p_num]);
geo_params = geo_param + randn(6,pf_param.p_num).*repmat(pf_param.affsig(:),[1,pf_param.p_num]);
end


function [z, logPrQ_z] = sampleStateSeq_PrecompSoftEv( ii, Etaii, LL, TargetPsi)

logPrQ_z = 0;
T = size( LL,2 );

if exist( 'TargetPsi', 'var' ) && ~isempty( TargetPsi )
    % Translate from TargetPsi's feature IDs to
    %    corresponding IDs in F, theta, prevStateSeq, etc.
    z = TargetPsi.stateSeq(ii).z;
    for aa = 1:length( TargetPsi.activeFeatIDs )
        z( z == TargetPsi.activeFeatIDs(aa) ) = TargetPsi.externalFeatIDs(aa);
    end
    TargetPsi.stateSeq(ii).z = z;
end

availFeatIDs = Etaii.availFeatIDs;
if length( availFeatIDs ) == 1
    z = availFeatIDs(1) * ones(1,T);
    return;
end
pi_z = Etaii.eta;
pi_z = bsxfun( @rdivide, pi_z, sum(pi_z,2)  );

pi_init = 1/length(pi_z)*ones( 1, length(pi_z) );

% Safely convert provided *log* soft evidence matrix
%  into proper probabilities
%  (up to a prop. constant, so stays in range of CPU)
normC = max( LL, [], 1);
LL = bsxfun( @minus, LL, normC );
likelihood = exp( LL );

if ~exist( 'TargetPsi', 'var') || isempty( TargetPsi )
    % ------------------------------------------- Actually sample z(t)
    [js, logQ] = SampleHMMStateSeqWithQsC( pi_z, likelihood, pi_init, -1, randi([1 100000]) );
    z = availFeatIDs( js );
else % ----------------------------- Calc prob of moving to Target's z
    jseq = zeros(1,T);
    for jj = 1:length( availFeatIDs )
        jseq( TargetPsi.stateSeq(ii).z == availFeatIDs(jj) ) = jj;
    end
    [js,logQ] = SampleHMMStateSeqWithQsC( pi_z, likelihood, pi_init, jseq, randi([1 100000]) );
    z = availFeatIDs( js );
end

if nargout > 1
    if exist( 'logQ', 'var' )
        logPrQ_z = logPrQ_z + logQ;
    else
        logPrQ_z = logPrQ_z + sum( log( qs ) );
    end
end

end % main function

%
% % Initialize state and sub-state sequences:
% qs = zeros(1,T);


function [xc_incoherent_collapsed_pow xc_incoherent_collapsed_frq n_comb_xc n_comb_sp xc_incoherent_single xc_incoherent sp_incoherent sp] = ...
    xcorr_pss(capbuf,f_search_set,ds_comb_arm,fc,sampling_carrier_twist,k_factor,xc)

% Copyright 2012 Evrytania LLC (http://www.evrytania.com)
%
% Written by James Peroulas <james@evrytania.com>
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU Affero 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 Affero General Public License for more details.
%
% You should have received a copy of the GNU Affero General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

% Perform the main correlations necessary to detect the PSS

error(nargchk(7,7,nargin));
error(chk_param(capbuf,'capbuf','vector','horizontal'));
error(chk_param(f_search_set,'f_search_set','vector','real'));
error(chk_param(ds_comb_arm,'ds_comb_arm','scalar','real','integer','>=',0));
error(chk_param(fc,'fc','scalar','real','>',0));

% % Create the time domain pss signals
% persistent pss_td
% persistent pss_td_populated
% if (isempty(pss_td_populated))
%   pss_td=NaN(3,128+9);
%   for t=0:2
%     temp=pss(t);
%     %temp=temp(6:67);
%     temp=[0 temp(32:end) zeros(1,65) temp(1:31)];
%     temp_td=idft(temp)*sqrt(128/62);
%     pss_td(t+1,:)=[temp_td(end-8:end) temp_td];
%   end
%   pss_td_populated=1;
% end

n_cap=length(capbuf);
n_f=length(f_search_set);

% % Correlate against the PSS
% xc=NaN(3,n_cap-136,n_f);
% for foi=1:n_f
% %   f_off=f_search_set(foi);
%   for t=1:3
% %     temp=conj(fshift(pss_td(t,:),f_off,fs_lte/16)/137);
% %     for k=1:n_cap-136
% %       xc(t,k,foi)=sum(temp.*capbuf(k:k+136));
% %     end
%     col_idx = (t-1)*n_f + foi;
%     xc(t,:,foi)=corr_store(1:(n_cap-136),col_idx);
%   end
% end

% Calculate the received power in the vicinity of the possible PSS
sp=NaN(1,n_cap-136-137);
capbufx2=absx2(capbuf);
sp(1)=sum(capbufx2(1:137*2));
for k=2:n_cap-136-137
  sp(k)=sp(k-1)-capbufx2(k-1)+capbufx2(k+137*2-1);
end
sp=sp/(137*2);
assert(any(isnan(sp))==0);

% Perform incoherent combining
xc_incoherent=NaN(3,9600,n_f);
xc_incoherent_single=NaN(3,9600,n_f);
n_comb_xc=floor((size(xc,2)-100)/9600);
for foi=1:n_f

  if sampling_carrier_twist == 1
      f_off=f_search_set(foi);
      % fc*k_factor is the receiver's actual RX center frequency.
      k_factor=(fc-f_off)/fc;
%   else
%       k_factor = 1; % because it is already corrected outside
  end

  for t=1:3
    %xc_incoherent_single(t,:,foi)=sum(transpose(reshape(absx2(xc(t,1:n_comb_xc*9600,foi)),9600,n_comb_xc)),1)/n_comb_xc;
    %xc_incoherent_single(t,:,foi)=absx2(xc(t,1:9600,foi));
    xc_incoherent_single(t,:,foi)=zeros(1,9600);
    for m=1:n_comb_xc
      actual_time_offset=(m-1)*.005*k_factor;
      actual_start_index=round(actual_time_offset*fs_lte/16)+1;
%       xc_incoherent_single(t,:,foi)=xc_incoherent_single(t,:,foi)+absx2(xc(t,actual_start_index:actual_start_index+9599,foi));
      xc_incoherent_single(t,:,foi)=xc_incoherent_single(t,:,foi)+xc(t,actual_start_index:actual_start_index+9599,foi);
    end
  end
  xc_incoherent_single(:,:,foi)=xc_incoherent_single(:,:,foi)/n_comb_xc;
  % Combine adjacent samples that might be different taps from the same channel.
  xc_incoherent(:,:,foi)=xc_incoherent_single(:,:,foi);
  for t=1:ds_comb_arm
    for k=1:3
      xc_incoherent(k,:,foi)=xc_incoherent(k,:,foi)+tshift(xc_incoherent_single(k,:,foi),-t)+tshift(xc_incoherent_single(k,:,foi),t);
    end
  end
  xc_incoherent(:,:,foi)=xc_incoherent(:,:,foi)/(2*ds_comb_arm+1);
end
sp_incoherent=NaN(1,9600);
n_comb_sp=floor(length(sp)/9600);
sp_incoherent=sum(transpose(reshape(sp(1:n_comb_sp*9600),9600,n_comb_sp)),1)/n_comb_sp;

% Align the correlations and the signal power measurements.
% xc(:,1) represents the correlation from capture buffer offset 1 to 137.
% sp(1) represents the signal power for samples 1 through 274.
% Suppose capbuf(1) contains the first sample of an SSS and thus the PSS is
% located from samples 138 to 274. The pss correlation peak will be located
% at time sample 138. This PSS correlation peak must be compared against
% the signal power for samples 1 through 274. Thus, the signal power must
% be cyclically shifted right by 137 samples.
sp_incoherent=tshift(sp_incoherent,137);

% For each time offset and PSS index, find the peak correlation
% among all the frequencies.
xc_incoherent_collapsed_pow=NaN(3,9600);
xc_incoherent_collapsed_frq=NaN(3,9600);
for t=1:3
  [pow frq]=max(transpose(shiftdim(xc_incoherent(t,:,:),1)),[],1);
  xc_incoherent_collapsed_pow(t,:)=pow;
  xc_incoherent_collapsed_frq(t,:)=frq;
end


report_this_filefun(mfilename('fullpath'));

l = isnan(tmap);
tmap(l) = 1;

%l = tmap< 0.1;
%tmap(l) = nan;

[lat,lon] = meshgrat(tmap,tmapleg);
%[smap,smapleg] = country2mtx('switzerland',100);
%[lat0, lon0] = meshgrat(smap,smapleg);

% tmap = km2deg(tmap/1);
[X , Y]  = meshgrid(gx,gy);

%sw = interp2(lon0,lat0,smap,lon,lat);

ren = interp2(X,Y,re4,lon,lat);

mi = min(min(ren));
l =  isnan(ren);
ren(l) = mi-100;

figure_w_normalized_uicontrolunits('pos',[150 500 1000 700])

hold on; axis off
axesm('MapProjection','eqaconic','MapParallels',[],...
    'MapLatLimit',[s4_south s3_north],'MapLonLimit',[s2_west s1_east])

meshm(ren,tmapleg,size(tmap),tmap);

daspectm('m',10);
tightmap
view([0 90])
camlight; lighting phong
set(gca,'projection','perspective');

load worldlo
%h = displaym(POline); set(h(1),'color',[0.9 0.9 0.9],'Linewidth',1.7)
h2 = displaym(PPpoint);
%h = displaym(PPtext); trimcart(h);
plotm(mainfault(:,2), mainfault(:,1),'m','Linewidth',4);

pl = plotm(ma(:,2),ma(:,1),'hw');
set(pl,'LineWidth',1.5,'MarkerSize',12,...
    'MarkerFaceColor','y','MarkerEdgeColor','k')

zdatam(handlem('allline'),10000) % keep line on surface
%zdatam(handlem('alltext'),10000) % keep line on surface

j = jet;
j = j(64:-1:1,:);
j = [ [ 0.85 0.9 0.9] ; j];
caxis([ 95 2000]);

colormap(j); brighten(0.1);

axis off; set(gcf,'color','k')

setm(gca,'ffacecolor','k')
setm(gca,'fedgecolor','w','flinewidth',3);

setm(gca,'mlabellocation',0.5)
setm(gca,'meridianlabel','on')
setm(gca,'plabellocation',0.5)
setm(gca,'parallellabel','on')
setm(gca,'Fontcolor','w','Fontweight','bold','FontSize',15,'Labelunits','dm')

h5 = colorbar;
set(h5,'position',[0.8 0.35 0.01 0.3],'TickDir','out','Ycolor','w','Xcolor','w',...
    'Fontweight','bold','FontSize',15);
set(gcf,'Inverthardcopy','off');