function f = dec2fix(x, nfracbits, nbits)

% DEC2FIX Convert decimal integer to binary string fixed point.
%
% Usage: F = DEC2FIX(X, NFRACBITS, NBITS)
%
% Converts the signed decimal integer given by X (either a scalar, vector,
% or matrix) to the two's complement representation as a string. If X is a
% vector or matrix, F(i, :) is the representation for X(i) (the shape of X
% is not preserved). Note that many fractional numbers that can be
% represented with a finite number of fractional digits cannot be
% represented by a finite number of fractional bits (specifically
% non-powers-of-two like 0.3), so input NFRACBITS is required to specify
% the precision for the number of fractional bits. Even powers-of-two
% fractional decimal numbers (like 0.5) require this input.
%
% Example:
%     >> dec2fix([2.3 2.4 -2.3 -2.4], 3)
%
%     ans =
%
%     010.010
%     010.011
%     101.110
%     101.101
%
% Inputs:
%   -X: decimal integers to convert to two's complement.
%   -NFRACBITS: number of bits to represent fractional part.
%   -NBITS: total number of bits in the representation including the
%   fractional bits (optional, default is the fewest number of bits
%   necessary to represent the integer portion).
%
% Outputs:
%   -F: fixed point representation of X as a string.
%
% See also: FIX2DEC, TWOS2DEC, DEC2TWOS, DEC2BIN, DEC2HEX, DEC2BASE.

error(nargchk(2, 3, nargin));
x = x(:);
maxx = max(abs(x));
nbits_min = max([nextpow2(maxx + (any(x == maxx))) + 1 + nfracbits, ...
    nfracbits]);

% Default number of bits.
if nargin < 3
    nbits = nbits_min;
elseif nbits < nbits_min
      warning('dec2twos:nbitsTooSmall', ['Minimum number of bits to ' ...
        'represent maximum input x is %i, which is greater than ' ...
        'input nbits = %i. Setting nbits = %i.'], ...
        nbits_min, nbits, nbits_min)
    nbits = nbits_min;
end

% Convert to two's complement string.
f = dec2twos(round(x * 2.^nfracbits), nbits);

% Insert binary point.
f(:, end+1) = '.';
f = f(:, [1:(nbits-nfracbits), nbits+1, (nbits-nfracbits+1):nbits]);


%  Figure 7.40      Feedback Control of Dynamic Systems, 5e
%                        Franklin, Powell, Emami
%
% script to generate Fig. 7.40
clf;
clear all;
np=1;
dp=[1, 0, 0];
nc=8.07*[1, 0.619];
dc=[1, 6.41];
num=conv(np,nc);
den=conv(dp,dc);
w=logspace(-1,2);
sys=tf(num,den);
[mag, ph]=bode(sys,w);
mag1=[mag(:,:); ones(size(mag(:,:)))];
ph1=[ph(:,:); -180*ones(size(ph(:,:)))];
subplot(211), loglog(w,mag1), grid;
xlabel('\omega (rad/sec)');
ylabel('Magnitude');
title('Fig.7.40 Bode plot for reduced-order controller for 1/s^2')
subplot(212) , semilogx(w,ph1) , grid
xlabel('\omega (rad/sec)');
ylabel('Phase (deg)');


classdef MW8 < PROBLEM
% <multi/many> <real> <large/none> <constrained>
% Constrained benchmark MOP proposed by Ma and Wang

%------------------------------- Reference --------------------------------
% Z. Ma and Y. Wang, Evolutionary constrained multiobjective optimization:
% Test suite construction and performance comparisons. IEEE Transactions on
% Evolutionary Computation, 2019, 23(6): 972-986.
%------------------------------- 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
        %% Default settings of the problem
        function Setting(obj)
            if isempty(obj.M); obj.M = 3; end
            if isempty(obj.D); obj.D = 15; end
            obj.lower    = zeros(1,obj.D);
            obj.upper    = ones(1,obj.D);
            obj.encoding = ones(1,obj.D);
        end
        %% Calculate objective values and constraint violations
        function Population = Evaluation(obj,varargin)
            X = varargin{1};
            X = max(min(X,repmat(obj.upper,size(X,1),1)),repmat(obj.lower,size(X,1),1));
            z = 1 - exp(-10*(X(:,obj.M:end) - ((obj.M:obj.D) - 1)/obj.D).^2);
            g = sum((1.5 + (0.1/obj.D)*z.^2 - 1.5*cos(2*pi*z)),2);
            PopObj = repmat(1+g,1,obj.M).*flip(cumprod([ones(size(X,1),1),cos(X(:,1:obj.M-1)*pi/2)],2),2).*[ones(size(X,1),1),sin(X(:,obj.M-1:-1:1)*pi/2)];
            l      = asin(PopObj(:,end)./sqrt(sum(PopObj.^2,2)));
            PopCon = sum(PopObj.^2,2) - (1.25 - 0.5*sin(6*l).^2).^2;
            Population  = SOLUTION(X,PopObj,PopCon,varargin{2:end});
            obj.FE      = obj.FE + length(Population);
        end
        %% Generate points on the Pareto front
        function R = GetOptimum(obj,N)
             R = UniformPoint(N,obj.M);
             R = R./repmat(sqrt(sum(R.^2,2)),1,obj.M);
             R(1-(1.25 - 0.5*sin(6*asin(R(:,end))).^2).^2>0,:) = [];
        end
        %% Generate the feasible region
        function R = GetPF(obj)
            if obj.M == 2
                [x,y] = meshgrid(linspace(0,1.2,400));
                z     = nan(size(x));
                fes   = x.^2 + y.^2 - (1.25-0.5*sin(6*asin(y./sqrt(x.^2+y.^2))).^2).^2 <= 0;
                z(fes & x.^2+y.^2>=1) = 0;
                R = {x,y,z};
            elseif obj.M == 3
                a = linspace(0,pi/2,40)';
                x = sin(a)*cos(a');
                y = sin(a)*sin(a');
                z = cos(a)*ones(size(a'));
                fes     = 1 - (1.25-0.5*sin(6*asin(z)).^2).^2 <= 0;
                z(~fes) = nan;
                R = {x,y,z};
            else
                R = [];
            end
        end
    end
end


function [Xnorm] = wL1norm(X,lambda)
% ||X||_wL1 = sum_i \lambda_ij|X_ij|
Xnorm = sum(sum(lambda.*abs(X),2));


function [Hq,tq,hq,Dq,Fq] = MFDFA1(signal,scale,q,m,Fig)
% Multifractal detrended fluctuation analysis (MFDFA)
%
% [Hq,tq,hq,Dq,Fq]=MFDFA(signal,scale,q,m,Fig);
%
% INPUT PARAMETERS---------------------------------------------------------
%
% signal:       input signal
% scale:        vector of scales
% q:            q-order that weights the local variations
% m:            polynomial order for the detrending
% Fig:          1/0 flag for output plot of Fq, Hq, tq and multifractal
%               spectrum (i.e. Dq versus hq).
%
% OUTPUT VARIABLES---------------------------------------------------------
%
% Hq:           q-order Hurst exponent
% tq:           q-order mass exponent
% hq:           q-order singularity exponent
% Dq:           q-order dimension
% Fq:           q-order scaling function
%
% EXAMPLE------------------------------------------------------------------
%
% load fractaldata
% scmin=16;
% scmax=1024;
% scres=19;
% exponents=linspace(log2(scmin),log2(scmax),scres);
% scale=round(2.^exponents);
% q=linspace(-5,5,101);
% m=1;
% signal1=multifractal;
% signal2=monofractal;
% signal3=whitenoise;
% [Hq1,tq1,hq1,Dq1,Fq1]=MFDFA1(signal1,scale,q,m,1);
% [Hq2,tq2,hq2,Dq2,Fq2]=MFDFA1(signal2,scale,q,m,1);
% [Hq3,tq3,hq3,Dq3,Fq3]=MFDFA1(signal3,scale,q,m,1);
%--------------------------------------------------------------------------
warning off
X=cumsum(signal-mean(signal));
if min(size(X))~=1||min(size(scale))~=1||min(size(q))~=1;
    error('Input arguments signal, scale and q must be a vector');
end
if size(X,2)==1;
   X=transpose(X);
end
if min(scale)<m+1
   error('The minimum scale must be larger than trend order m+1')
end
for ns=1:length(scale),
    segments(ns)=floor(length(X)/scale(ns));
    for v=1:segments(ns),
        Index=((((v-1)*scale(ns))+1):(v*scale(ns)));
        C=polyfit(Index,X(Index),m);
        fit=polyval(C,Index);
        RMS_scale{ns}(v)=sqrt(mean((X(Index)-fit).^2));
    end
    for nq=1:length(q),
        qRMS{nq,ns}=RMS_scale{ns}.^q(nq);
        Fq(nq,ns)=mean(qRMS{nq,ns}).^(1/q(nq));
    end
    Fq(q==0,ns)=exp(0.5*mean(log(RMS_scale{ns}.^2)));
end
for nq=1:length(q),
    C = polyfit(log2(scale),log2(Fq(nq,:)),1);
    Hq(nq) = C(1);
    qRegLine{nq} = polyval(C,log2(scale));
end
tq = Hq.*q-1;
hq = diff(tq)./(q(2)-q(1));
Dq = (q(1:end-1).*hq)-tq(1:end-1);

%OUTPUT FIGURE-------------------------------------------------------------
if Fig==1,
   qindex=[1,round(length(q)/2),length(q)];
   qindex2=[1,round((length(q)-1)/2),length(q)-1];

   %Variable settings---------
   qstart1=q(qindex(1));
   qmid1=q(qindex(2));
   qstop1=q(qindex(3));
   Hqstart1=Hq(qindex(1));
   Hqmid1=Hq(qindex(2));
   Hqstop1=Hq(qindex(3));
   tqstart1=tq(qindex(1));
   tqmid1=tq(qindex(2));
   tqstop1=tq(qindex(3));
   hqstart2=hq(qindex2(1));
   hqmid2=hq(qindex2(2));
   hqstop2=hq(qindex2(3));
   Dqstart1=Dq(qindex2(1));
   Dqmid1=Dq(qindex2(2));
   Dqstop1=Dq(qindex2(3));
   for nq=1:length(qindex),
       qRegFit(nq,:)=qRegLine{qindex(nq)};
   end
   X1=log2(scale);
   YMatrix1=[log2(Fq(qindex,:));qRegFit];
   X2=q;
   Y1=Hq;
   Y3=tq;
   X4=hq;
   Y5=Dq;
   %---------------------------
    q_end=num2str(max(q));
    if length(find(q==0))==1
       q_middle=0;
    else
       qm0=min(q)+((max(q)-min(q))/2);
       qm1=[q(find(q<qm0, 1, 'last' )),q(find(q>qm0, 1 ))];
       qm2=qm1-qm0;
       midind= qm2==min(qm2);
       q_middle=qm2(midind(1));
    end
    q_mid=num2str(q_middle);
    q_start=num2str(min(q));

    % Create figure
    figure1 = figure('PaperSize',[20.98 29.68],'Color',[1 1 1]);

    scaleInd=floor(min(log2(scale))):ceil(max(log2(scale)));
    for ns=1:length(scaleInd),
        scaletick{ns}=num2str(2^scaleInd(ns));
    end
    Fqind=floor(log2(min(min(Fq)))):ceil(log2(max(max(Fq))));
    for nf=1:length(Fqind),
        Fqtick{nf}=num2str(Fqind(nf));
    end

    % Create subplot
    subplot1 = subplot(2,2,1,'Parent',figure1,...
        'YTickLabel',Fqtick,...
        'XTickLabel',scaletick,...
        'XTick',scaleInd,...
        'LineWidth',2,...
        'FontSize',14);
    hold(subplot1,'all');

    % Create multiple lines using matrix input to plot
    plot1 = plot(X1,YMatrix1,'Parent',subplot1);
    set(plot1(1),'MarkerFaceColor',[1 0 0],'MarkerEdgeColor',[0 0 0],...
        'Marker','o',...
        'LineStyle','none',...
        'Color',[1 0 0],...
        'DisplayName',strcat('q = ',num2str(min(q))));
    set(plot1(2),'MarkerFaceColor',[0 0 1],'MarkerEdgeColor',[0 0 0],...
        'Marker','o',...
        'LineStyle','none',...
        'Color',[0 0 1],...
        'DisplayName',strcat('q = ',num2str(q_middle)));
    set(plot1(3),'MarkerFaceColor',[0 0.498 0],'MarkerEdgeColor',[0 0 0],...
        'Marker','o',...
        'LineStyle','none',...
        'Color',[0 0.498 0],...
        'DisplayName',strcat('q = ',num2str(max(q))));
    set(plot1(4),'LineWidth',2,'Color',[1 0 0],'DisplayName',strcat('q = ',num2str(min(q))));
    set(plot1(5),'MarkerFaceColor',[1 0 0],'MarkerEdgeColor',[1 1 1],...
        'LineWidth',2,...
        'Color',[0 0 1],...
        'DisplayName',strcat('q = ',num2str(q_middle)));
    set(plot1(6),'LineWidth',2,'Color',[0 0.498 0],'DisplayName',strcat('q = ',num2str(max(q))));

    % Create xlabel
    xlabel('Scale (segment sample size)','FontSize',14);

    % Create ylabel
    ylabel('log_2(Fq)','FontSize',14);

    % Create title
    title('Scaling function Fq (q-order RMS)','FontSize',14);

    qInd=floor(min(q)):ceil(max(q));
    for nq=1:length(qInd),
        qtick{nq}=num2str(qInd(nq));
    end

    % Create subplot
    subplot2 = subplot(2,2,2,'Parent',figure1,...
        'XTickLabel',qtick,...
        'XTick',qInd,...
        'LineWidth',2,...
        'FontSize',14);
    hold(subplot2,'all');

    % Create plot
    plot(X2,Y1,'Parent',subplot2,'Marker','o','LineStyle','none',...
        'Color',[0 0 1]);

    % Create xlabel
    xlabel('q','FontSize',16);

    % Create ylabel
    ylabel('Hq','FontSize',16);

    % Create title
    title('q-order Hurst exponent','FontSize',14);

    % Create plot
    plot(qstart1,Hqstart1,'Parent',subplot2,'MarkerFaceColor',[1 0 0],...
        'MarkerEdgeColor',[0 0 0],...
        'MarkerSize',8,...
        'Marker','o',...
        'LineWidth',2,...
        'LineStyle','none',...
        'Color',[1 0 0],...
        'DisplayName',strcat('Hq(',num2str(min(q)),') = ',num2str(Hq(q==min(q)))));

    % Create plot
    plot(qmid1,Hqmid1,'Parent',subplot2,'MarkerFaceColor',[0 0 1],...
        'MarkerEdgeColor',[0 0 0],...
        'MarkerSize',8,...
        'Marker','o',...
        'LineWidth',2,...
        'LineStyle','none',...
        'Color',[0 0 1],...
        'DisplayName',strcat('Hq(',num2str(q_middle),') = ',num2str(Hq(q==q_middle))));

    % Create plot
    plot(qstop1,Hqstop1,'Parent',subplot2,'MarkerFaceColor',[0 0.498 0],...
        'MarkerEdgeColor',[0 0 0],...
        'MarkerSize',8,...
        'Marker','o',...
        'LineWidth',2,...
        'LineStyle','none',...
        'Color',[0 0.498 0],...
        'DisplayName',strcat('Hq(',num2str(max(q)),') = ',num2str(Hq(q==max(q)))));

    % Create subplot
    subplot3 = subplot(2,2,3,'Parent',figure1,...
        'XTickLabel',qtick,...
        'XTick',qInd,...
        'LineWidth',2,...
        'FontSize',14);
    hold(subplot3,'all');

    % Create plot
    plot(X2,Y3,'Parent',subplot3,'Marker','o','LineStyle','none',...
        'Color',[0 0 1]);

    % Create xlabel
    xlabel('q','FontSize',16);

    % Create ylabel
    ylabel('tq','FontSize',16);

    % Create title
    title('q-order Mass exponent','FontSize',14);

    % Create plot
    plot(qstop1,tqstop1,'Parent',subplot3,'MarkerFaceColor',[0 0.498 0],...
        'MarkerEdgeColor',[0 0 0],...
        'MarkerSize',8,...
        'Marker','o',...
        'LineWidth',2,...
        'LineStyle','none',...
        'Color',[0 0.498 0],...
        'DisplayName',strcat('tq(',num2str(max(q)),') = ',num2str(tq(q==max(q)))));

    % Create plot
    plot(qstart1,tqstart1,'Parent',subplot3,'MarkerFaceColor',[1 0 0],...
        'MarkerEdgeColor',[0 0 0],...
        'MarkerSize',8,...
        'Marker','o',...
        'LineWidth',2,...
        'LineStyle','none',...
        'Color',[1 0 0],...
        'DisplayName',strcat('Hq(',num2str(min(q)),') = ',num2str(Hq(q==min(q)))));

    % Create plot
    plot(qmid1,tqmid1,'Parent',subplot3,'MarkerFaceColor',[0 0 1],...
        'MarkerEdgeColor',[0 0 0],...
        'MarkerSize',8,...
        'Marker','o',...
        'LineWidth',2,...
        'LineStyle','none',...
        'Color',[0 0 1],...
        'DisplayName',strcat('Hq(',num2str(q_middle),') = ',num2str(Hq(q==q_middle))));

    % Create subplot
    subplot4 = subplot(2,2,4,'Parent',figure1,'LineWidth',2,'FontSize',12);
    % Uncomment the following line to preserve the X-limits of the axes
    % xlim(subplot4,[0.2 1.8]);
    hold(subplot4,'all');

    % Create plot
    plot(X4,Y5,'Parent',subplot4,'Marker','o','LineStyle','none',...
        'Color',[0 0 1]);

    % Create xlabel
    xlabel('hq','FontSize',16);

    % Create ylabel
    ylabel('Dq','FontSize',16);

    % Create title
    title('Multifractal spectrum','FontSize',14);

    % Create plot
    plot(hqstart2,Dqstart1,'Parent',subplot4,'MarkerFaceColor',[1 0 0],...
        'MarkerEdgeColor',[0 0 0],...
        'MarkerSize',8,...
        'Marker','o',...
        'LineWidth',2,...
        'LineStyle','none',...
        'Color',[1 0 0],...
        'DisplayName',[strcat('Dq(',num2str(min(q)),') = ',num2str(Dq(q==min(q)))),sprintf('\n'),strcat('hq(',num2str(min(q)),') = ',num2str(hq(q==min(q))))]);

    % Create plot
    plot(hqmid2,Dqmid1,'Parent',subplot4,'MarkerFaceColor',[0 0 1],...
        'MarkerEdgeColor',[0 0 0],...
        'MarkerSize',8,...
        'Marker','o',...
        'LineWidth',2,...
        'LineStyle','none',...
        'Color',[0 0 1],...
        'DisplayName',[strcat('Dq(',num2str(q_middle),') = ',num2str(Dq(q==q_middle))),sprintf('\n'),strcat('hq(',num2str(q_middle),') = ',num2str(hq(q==q_middle)))]);

    % Create plot
    plot(hqstop2,Dqstop1,'Parent',subplot4,'MarkerFaceColor',[0 0.498 0],...
        'MarkerEdgeColor',[0 0 0],...
        'MarkerSize',8,...
        'Marker','o',...
        'LineWidth',2,...
        'LineStyle','none',...
        'Color',[0 0.498 0],...
        'DisplayName',[strcat('Dq(',num2str(max(q)),') = ',num2str(Dq(find(q==max(q))-1))),sprintf('\n'),strcat('hq(',num2str(max(q)),') = ',num2str(hq(find(q==max(q))-1)))]);

    % Create legend
    %legend1 = legend(subplot1,'show');
    %set(legend1,'Position',[0.4174 0.6072 0.09288 0.2055]);
    % Create legend
    legend1 = legend(subplot1,'show');
    set(legend1,'Position',[0.4126 0.6072 0.1024 0.2055]);

    % Create legend
    legend2 = legend(subplot3,'show');
    set(legend2,'Position',[0.3414 0.1576 0.1458 0.1714]);

    % Create legend
    legend3 = legend(subplot2,'show');
    set(legend3,'Position',[0.8171 0.7456 0.1528 0.1714]);

    % Create legend
    legend4 = legend(subplot4,'show');
    set(legend4,'Position',[0.8338 0.2436 0.1354 0.2764]);

    % Create textbox
    annotation(figure1,'textbox',[0.2726 0.638 0.1111 0.05249],...
        'String',{'Slope = Hq'},...
        'HorizontalAlignment','center',...
        'FontSize',14,...
        'FitBoxToText','off');

    % Create textbox
    annotation(figure1,'textbox',[0.6355 0.1669 0.2013 0.05518],...
        'String',{strcat('hq_m_a_x - hq_m_i_n = ',num2str(max(hq)-min(hq)))},...
        'HorizontalAlignment','center',...
        'FontSize',14,...
        'FitBoxToText','off',...
        'LineStyle','none');
end


function dFdz = deriv(F,z0,Fz0,type)
%DERIV Approximate gradient and Jacobian.
%   For real x0, deriv(F,x0) computes the gradient dF(x0)/dx or Jacobian
%   dF(x0)/dx^T of a real-valued function F(x) in the real variables x,
%   assuming F is analytic in x when x is complex. If this assumption is
%   not satisfied (e.g., when f is function of x' instead of x.'), use the
%   finite difference methods below. The input variables x may be a scalar,
%   vector, matrix, tensor or even a (nested) cell array of tensors.
%
%   For complex z0, deriv(F,z0) and deriv(F,z0,Fz0) are equivalent to
%   deriv(F,z0,Fz0,'gradient') if F(z0) is a real scalar, and
%   deriv(F,z0,Fz0,'Jacobian') otherwise. The input variables z may be a
%   scalar, vector, matrix, tensor or even a cell array of tensors.
%
%   deriv(f,z0,fz0,'gradient') approximates the real gradient df(z0)/dx or
%   scaled conjugate cogradient 2*conj(df(z0)/dz) of a real-valued function
%   f in the real variables x or complex variables z, respectively. The
%   scaled conjugate cogradient is defined as twice the complex conjugate
%   of the partial derivative of f w.r.t. the complex variables z, while
%   treating conj(z) as constant. The real gradient is returned if z0 is
%   real, else the scaled conjugate cogradient is returned. Note that the
%   former is equal to the latter if both z0 and f(z) are real. The input
%   fz0 should supply f(z0). If fz0 is [], it is computed as f(z0).
%
%   deriv(F,z0,Fz0,'Jacobian') approximates the Jacobian dF(z0)/dz^T in the
%   real or complex variables z. If F(z) is nonanalytic in z and depends on
%   conj(z), use 'Jacobian-C' instead. The input Fz0 should supply F(z0).
%   If Fz0 is [], it is computed as F(z0).
%
%   deriv(F,z0,Fz0,'Jacobian-C') approximates the complex Jacobian
%   [dF(z0)/dz^T dF(z0)/dconj(z)^T] of a function F in the complex
%   variables z. The partial derivatives in the complex Jacobian are w.r.t.
%   the complex variables z and conj(z), while treating conj(z) and z as
%   constant, respectively. The input Fz0 should supply F(z0). If Fz0 is
%   [], it is computed as F(z0).
%
%   See also gradient, diff.

%   Authors: Laurent Sorber (Laurent.Sorber@cs.kuleuven.be)
%            Marc Van Barel (Marc.VanBarel@cs.kuleuven.be)
%            Lieven De Lathauwer (Lieven.DeLathauwer@kuleuven-kulak.be)
%
%   References:
%   [1] L. Sorber, M. Van Barel, L. De Lathauwer, "Unconstrained
%       optimization of real functions in complex variables", SIAM J. Opt.,
%       Vol. 22, No. 3, 2012, pp. 879-898.

% If possible, use the i-trick.
dim = structure(z0);
z0 = serialize(z0);
F = @(z)serialize(F(deserialize(z,dim)));
if nargin < 3 && all(isreal(z0))
    % Assume F is analytic and both F and z0 are real-valued; return dF/dx.
    e = 2^floor(log2(nthroot(realmin(class(z0)),3)));
    p = zeros(size(z0));
    p(1) = e;
    dFdz = imag(F(z0+p*1i))/e;
    dFdz = [dFdz zeros(numel(dFdz),length(z0)-1)];
    for n = 2:length(z0)
        p(n-1) = 0; p(n) = e;
        dFdz(:,n) = imag(F(z0+p*1i))/e;
    end
    if size(dFdz,1) == 1
        dFdz = deserialize(dFdz(:),dim);
    end
    return;
elseif nargin < 3 || isempty(Fz0)
    Fz0 = F(z0);
end
Fz0 = serialize(Fz0);

% Define type of derivative.
if nargin < 4
    if numel(Fz0) == 1 && isreal(Fz0), type = 'gradient';
    else type = 'Jacobian'; end
end
dFdzIsGrad = any(strfind(type,'gradient'));
dFdzIsRealGrad = dFdzIsGrad && all(isreal(z0));
dFdzIsAnaJac = ~dFdzIsGrad && ~any(strfind(type,'-C'));

% Else use finite (complex) derivatives.
e = sqrt(eps(class(z0)));
p = zeros(size(z0));
p(1) = e*max(1,abs(real(z0(1))));
dFdx = (F(z0+p)-Fz0)/p(1);
if ~dFdzIsRealGrad || ~dFdzIsAnaJac
    p(1) = e*max(1,abs(imag(z0(1))))*1i;
    dFdy = (F(z0+p)-Fz0)/imag(p(1));
end
switch strtok(type,'-')
    case 'gradient'
        if dFdzIsRealGrad, dFdz = dFdx;
        else dFdz = real(dFdx)+real(dFdy)*1i; end
        dFdz = [dFdz zeros(numel(dFdz),length(z0)-1)];
    case 'Jacobian'
        if dFdzIsAnaJac
            dFdz = dFdx;
            dFdz = [dFdz zeros(numel(dFdz),length(z0)-1)];
        else
            dFdz = 0.5*cat(3,dFdx-dFdy*1i,dFdx+dFdy*1i);
            dFdz = cat(2,dFdz,zeros(size(dFdz,1),length(z0)-1,2));
        end
end
for n = 2:length(z0)
    p(n-1) = 0; p(n) = e*max(1,abs(real(z0(n))));
    dFdx = (F(z0+p)-Fz0)/p(n);
    if ~dFdzIsRealGrad || ~dFdzIsAnaJac
        p(n) = e*max(1,abs(imag(z0(n))))*1i;
        dFdy = (F(z0+p)-Fz0)/imag(p(n));
    end
    switch strtok(type,'-')
        case 'gradient'
            if dFdzIsRealGrad, dFdz(:,n) = dFdx;
            else dFdz(:,n) = real(dFdx)+real(dFdy)*1i; end
        case 'Jacobian'
            if dFdzIsAnaJac, dFdz(:,n) = dFdx;
            else dFdz(:,n,:) = 0.5*cat(3,dFdx-dFdy*1i,dFdx+dFdy*1i); end
    end
end
dFdz = dFdz(:,:);
if size(dFdz,1) == 1 && dFdzIsGrad
    dFdz = deserialize(dFdz(:),dim);
end

end

function [z,offset] = deserialize(z,dim,offset)
    if iscell(dim)
        v = z;
        z = cell(size(dim));
        if nargin < 3, offset = 0; end
        for i = 1:numel(z)
            if iscell(dim{i})
                [z{i},offset] = deserialize(v,dim{i},offset);
            else
                n = prod(dim{i}(:));
                z{i} = reshape(v(offset+(1:n)),dim{i});
                offset = offset+n;
            end
        end
    elseif ~isempty(dim)
        z = reshape(z,dim);
    end
end

function z = serialize(z)
    if iscell(z)
        for i = find(cellfun(@iscell,z(:).'))
            z{i} = serialize(z{i});
        end
        s = cellfun(@numel,z(:)); o = [0; cumsum(s)];
        c = z; z = zeros(o(end),1);
        for i = 1:length(s), z(o(i)+(1:s(i))) = c{i}(:); end
    else
        z = z(:);
    end
end

function dim = structure(z)
    if iscell(z)
        dim = cellfun(@size,z,'UniformOutput',false);
        for i = find(cellfun(@iscell,z(:).'))
            dim{i} = structure(z{i});
        end
    else
        dim = size(z);
        if numel(z) == dim(1), dim = []; end
    end
end


%% patchDetach
% Below is a demonstration of the features of the |patchDetach| function

%% Syntax
% |[Fs,Vs]=patchDetach(F,V,scalefactor);|

%% Description
% This function seperates the nodes (if shared) for all faces. If a
% constant or spatially varying scalefactor is provided the faces are
% scaled (around their mean) as well.

%% Examples

%%
clear; close all; clc;

%%
% Plot settings
fontSize=15;
plotColor1=0.25.*ones(1,3);
plotColor2=0.75.*ones(1,3);
edgeWidth=2;
markerSize=25;

%% Example: Seperate and scale faces homogeneously
%Defining geodesic dome triangulation
r=1; %sphere radius
n=2; %Refinements
[F,V,~]=geoSphere(n,r);

%Detach nodes and shrink faces
scaleFactor=0.5;
[Fs,Vs]=patchDetach(F,V,scaleFactor);

%%
%Plotting results

cFigure;
subplot(1,2,1); hold on;
gpatch(F,V,'rw','k',1,edgeWidth);
axisGeom(gca,fontSize);
camlight headlight;
view(2);

subplot(1,2,2); hold on;
gpatch(F,V,'rw','none',0.5);
gpatch(Fs,Vs,'bw','k',1,edgeWidth);
axisGeom(gca,fontSize);
camlight headlight;
view(2);

drawnow;

%% Example: Seperate and shrink faces in a spatially varying way

%%
% Create a spatially varying shrink factor between 0 and 1
scaleFactor=V(:,2);
scaleFactor=mean(scaleFactor(F),2);
scaleFactor=scaleFactor-min(scaleFactor(:));
scaleFactor=scaleFactor./max(scaleFactor(:));

%%
% Detach nodes and shrink faces
[Fs,Vs]=patchDetach(F,V,scaleFactor);

%%
% Plotting results

cFigure;
subplot(1,2,1); hold on;
gpatch(F,V,'rw','k',1,edgeWidth);
axisGeom(gca,fontSize);
camlight headlight;
view(2);

subplot(1,2,2); hold on;
gpatch(F,V,'rw','none',0.5);
gpatch(Fs,Vs,'bw','k',1,edgeWidth);
axisGeom(gca,fontSize);
camlight headlight;
view(2);

drawnow;

%%
%
% <<gibbVerySmall.gif>>
%
% _*GIBBON*_
% <www.gibboncode.org>
%
% _Kevin Mattheus Moerman_, <gibbon.toolbox@gmail.com>

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


function [me,ASAcontrol] = moderr_e(varargin)
%MODERR_E Model error
%   ME = MODERR_E(AR_EST,MA_EST,AR_REF,MA_REF,N_OBS) is the model error
%   of an ARMA model estimated from N_OBS observations, with parameter
%   vectors AR_EST and MA_EST, applied for modeling a reference process
%   with ARMA parameters AR_REF and MA_REF. It is a measure for the
%   accuracy of the estimated model. The lower the model error, the
%   better is the model accuracy. For estimated models, its asymptotic
%   minimum value equals the AR-order plus the MA-order of the reference
%   process.
%
%   MODERR_E is an ARMASA main function.

%   References: P. M. T. Broersen, The Quality of Models for ARMA
%               Processes, IEEE Transactions on Signal Processing,
%               Vol. 46, No. 6,, June 1998, pp. 1749-1752.

%Header
%==============================================================================

%Declaration of variables
%------------------------

%Declare and assign values to local variables
%according to the input argument pattern
[ar_est,ma_est,ar_ref,ma_ref,n_obs,ASAcontrol]=ASAarg(varargin, ...
{'ar_est'   ;'ma_est'   ;'ar_ref'   ;'ma_ref'   ;'n_obs'    ;'ASAcontrol'}, ...
{'isnumeric';'isnumeric';'isnumeric';'isnumeric';'isnumeric';'isstruct'  }, ...
{'ar_est'   ;'ma_est'   ;'ar_ref'   ;'ma_ref'   ;'n_obs'                 });

if isequal(nargin,1) & ~isempty(ASAcontrol)
      %ASAcontrol is the only input argument
   ASAcontrol.error_chk = 0;
   ASAcontrol.run = 0;
end

%ARMASA-function version information
%-----------------------------------

%This ARMASA-function is characterized by
%its current version,
ASAcontrol.is_version = [2000 12 30 20 0 0];
%and its compatability with versions down to,
ASAcontrol.comp_version = [2000 12 30 20 0 0];

%This function calls other functions of the ARMASA
%toolbox. The versions of these other functions must
%be greater than or equal to:
ASAcontrol.req_version.convol_e = [2000 12 13 21 0 0];
ASAcontrol.req_version.arma2cor_e = [2000 12 30 20 0 0];

%Checks
%------

if ~isfield(ASAcontrol,'error_chk') | ASAcontrol.error_chk
      %Perform standard error checks
   %Input argument format checks
   ASAcontrol.error_chk = 1;
   if ~isnum(ar_est)
      error(ASAerr(11,'ar_est'))
   elseif ~isvector(ar_est)
      error(ASAerr(15,'ar_est'))
   elseif size(ar_est,1)>1
      ar_est = ar_est';
      warning(ASAwarn(25,{'column';'ar_est';'row'},ASAcontrol))
   end
   if ~isnum(ma_est)
      error(ASAerr(11,'ma_est'))
   elseif ~isvector(ma_est)
      error(ASAerr(15,'ma_est'))
   elseif size(ma_est,1)>1
      ma_est = ma_est';
      warning(ASAwarn(25,{'column';'ma_est';'row'},ASAcontrol))
   end
   if ~isnum(ar_ref)
      error(ASAerr(11,'ar_ref'))
   elseif ~isvector(ar_ref)
      error(ASAerr(15,'ar_ref'))
   elseif size(ar_ref,1)>1
      ar_ref = ar_ref';
      warning(ASAwarn(25,{'column';'ar_ref';'row'},ASAcontrol))
   end
   if ~isnum(ma_ref)
      error(ASAerr(11,'ma_ref'))
   elseif ~isvector(ma_ref)
      error(ASAerr(15,'ma_ref'))
   elseif size(ma_ref,1)>1
      ma_ref = ma_ref';
      warning(ASAwarn(25,{'column';'ma_ref';'row'},ASAcontrol))
   end
   if ~isnum(n_obs) | ~isintscalar(n_obs)
      error(ASAerr(17,'n_obs'))
   end

   %Input argument value checks
   if ~(isreal(ar_est) & isreal(ma_est) & ...
         isreal(ar_ref) & isreal(ma_ref))
      error(ASAerr(13))
   end
   if ar_est(1)~=1
      error(ASAerr(23,{'ar_est','parameter'}))
   end
   if ma_est(1)~=1
      error(ASAerr(23,{'ma_est','parameter'}))
   end
   if ar_ref(1)~=1
      error(ASAerr(23,{'ar_ref','parameter'}))
   end
   if ma_ref(1)~=1
      error(ASAerr(23,{'ma_ref','parameter'}))
   end
   if n_obs<1
      error(ASAerr(41,'n_obs'))
   end
end

if ~isfield(ASAcontrol,'version_chk') | ASAcontrol.version_chk
      %Perform version check
   ASAcontrol.version_chk = 1;

   %Make sure the requested version of this function
   %complies with its actual version
   ASAversionchk(ASAcontrol);

   %Make sure the requested versions of the called
   %functions comply with their actual versions
   arma2cor_e(ASAcontrol);
   convol_e(ASAcontrol);
end

if ~isfield(ASAcontrol,'run') | ASAcontrol.run
   ASAcontrol.run = 1;
end

if ASAcontrol.run %Run the computational kernel
   ASAcontrol.version_chk = 0;
   ASAcontrol.error_chk = 0;

%Main
%=====================================================

%Determine the model error by evaluating the power
%gain of a modified ARMA model
[cor,gain] = arma2cor_e...
   (convol_e(ar_ref,ma_est,ASAcontrol),...
    convol_e(ar_est,ma_ref,ASAcontrol),0,ASAcontrol);
me = n_obs*(gain-1);

%Footer
%=====================================================

else %Skip the computational kernel
   %Return ASAcontrol as the first output argument
   if nargout>1
      warning(ASAwarn(9,mfilename,ASAcontrol))
   end
   me = ASAcontrol;
   ASAcontrol = [];
end

%Program history
%======================================================================
%
% Version                Programmer(s)          E-mail address
% -------                -------------          --------------
% former versions        P.M.T. Broersen        broersen@tn.tudelft.nl
% [2000 12 30 20 0 0]    W. Wunderink           wwunderink01@freeler.nl


function [data_matrix12, xvals2, yvals2, data_matrix22, bestx, besty, bestz] = surf_plot_tor(data_matrix1, xvals, yvals, xname, yname, zname, varargin)
% Stylized surface plot of one or two surfaces
%
% :Usage:
% ::
%
%    [data_matrix12, xvals2, yvals2, data_matrix22] = surf_plot_tor(data_matrix1, xvals, yvals, xname, yname, zname, [data_matrix2])
%
% :Examples: See classify_search_script3...in meta-analysis classification
% ::
%
%    surf_plot_tor(corrc_mean, mya, mys, 'Activation feature cutoff', 'Sensitivity feature cutoff', 'Classification accuracy', worstcat)
%
% xvals are columns, yvals are rows!
%
% ..
%    Tor Wager, Sept. 07
% ..

    data_matrix22 = [];

    ystep = 1/5 .* range(yvals) ./ length(yvals);
    xstep = 1/5 .* range(xvals) ./ length(xvals);

    [X,Y] = meshgrid(xvals,yvals);

%     if size(X, 1) == size(data_matrix1, 2)
%         error('Wrong sizes...are the x and y inputs flipped?');
%     end

    yvals2 = 0:ystep:max(yvals);
    xvals2 = 0:xstep:max(xvals);

    [X2,Y2] = meshgrid(xvals2,yvals2);
    data_matrix12 = interp2(X,Y,data_matrix1,X2,Y2,'cubic');

    create_figure('Surface plot');

    han = surf(X2,Y2,data_matrix12);

    xlabel('Activation feature cutoff')
    ylabel('Sensitivity feature cutoff')
    zlabel('Classification accuracy');

    xlabel(xname);
    ylabel(yname);
    zlabel(zname);

    set(han,'EdgeColor','none')
    grid on

    % lines
    plot3(X2(end,:),Y2(end,:),data_matrix12(end,:),'r','LineWidth',2);
    plot3(X2(end,:),Y2(end,:),data_matrix12(end,:),'r','LineWidth',3);

    for i = 10:10:size(X2,1)
        plot3(X2(i,:),Y2(i,:),data_matrix12(i,:),'Color',[.5 .5 .5],'LineWidth',1);
    end

    view(135, 30)
    drawnow

    scn_export_papersetup(600);

    if length(varargin) > 0
        data_matrix2 = varargin{1};

        data_matrix22 = interp2(X,Y,data_matrix2,X2,Y2,'cubic');
        hold on
        han2 = surf(X2,Y2,data_matrix22);
        set(han2,'EdgeColor','none')
        set(han,'FaceAlpha',.7)

        % lines
        plot3(X2(end,:),Y2(end,:),data_matrix22(end,:),'b','LineWidth',3);
        plot3(X2(1,:),Y2(1,:),data_matrix22(1,:),'k','LineWidth',1);

        for i = 10:10:size(X2,1)
            plot3(X2(i,:),Y2(i,:),data_matrix22(i,:),'Color',[.5 .5 .5],'LineWidth',1);
        end

    end

    % calc max and put max point on map
    % --------------------------------------------------
    if length(varargin) > 0
        % average two maps
        mymap = .5 * (data_matrix12 + data_matrix22);
        fprintf('Using average of two maps to calculate max.');
    else
        mymap = data_matrix12;
    end

    [bestsum] = max(mymap(:));
    [row, col] =  find(mymap == bestsum);
bestx = xvals2(col);
besty = yvals2(row);
bestz = mymap(row, col);

fprintf('Maximum: x = %3.3f, y = %3.3f, z = %3.3f\n', bestx, besty, bestz);

plotz = bestz;
if length(varargin) > 0
    max1 = data_matrix12(row, col);
    max2 = data_matrix22(row, col);
    plotz = max([max1 max2]);

    bestz = [bestz max1 max2];
    fprintf('Height at overall max: Map 1: %3.3f, Map 2: %3.3f\n', max1, max2);
end

% plot
plot3(bestx, besty, plotz, 'ko', 'MarkerSize', 10, 'MarkerFaceColor', 'k')

mylowerbound = get(gca,'ZLim'); mylowerbound = mylowerbound(1);
plot3([bestx bestx], [besty besty], [plotz mylowerbound], 'k-', 'LineWidth', 2);

myxlowerbound = get(gca,'XLim'); %myxlowerbound = myxlowerbound(1);
plot3([myxlowerbound], [besty besty], [mylowerbound mylowerbound], 'k-', 'LineWidth', 2);

myylowerbound = get(gca,'YLim'); %myylowerbound = myylowerbound(1);
plot3([bestx bestx], [myylowerbound], [mylowerbound mylowerbound], 'k-', 'LineWidth', 2);

set(gca, 'ZLim', get(gca, 'ZLim'));
axis vis3d

end


% HARRIS - Harris corner detector
%
% Usage:                 cim = harris(im, sigma)
%                [cim, r, c] = harris(im, sigma, thresh, radius, disp)
%  [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp)
%
% Arguments:
%            im     - image to be processed.
%            sigma  - standard deviation of smoothing Gaussian. Typical
%                     values to use might be 1-3.
%            thresh - threshold (optional). Try a value ~1000.
%            radius - radius of region considered in non-maximal
%                     suppression (optional). Typical values to use might
%                     be 1-3.
%            disp   - optional flag (0 or 1) indicating whether you want
%                     to display corners overlayed on the original
%                     image. This can be useful for parameter tuning. This
%                     defaults to 0
%
% Returns:
%            cim    - binary image marking corners.
%            r      - row coordinates of corner points.
%            c      - column coordinates of corner points.
%            rsubp  - If five return values are requested sub-pixel
%            csubp  - localization of feature points is attempted and
%                     returned as an additional set of floating point
%                     coords. Note that you may still want to use the integer
%                     valued coords to specify centres of correlation windows
%                     for feature matching.
%
% If thresh and radius are omitted from the argument list only 'cim' is returned
% as a raw corner strength image.  You may then want to look at the values
% within 'cim' to determine the appropriate threshold value to use. Note that
% the Harris corner strength varies with the intensity gradient raised to the
% 4th power.  Small changes in input image contrast result in huge changes in
% the appropriate threshold.
%
% Note that this code computes Noble's version of the detector which does not
% require the parameter 'k'.  See comments in code if you wish to use Harris'
% original measure.
%
% See also: NONMAXSUPPTS, DERIVATIVE5

% References:
% C.G. Harris and M.J. Stephens. "A combined corner and edge detector",
% Proceedings Fourth Alvey Vision Conference, Manchester.
% pp 147-151, 1988.
%
% Alison Noble, "Descriptions of Image Surfaces", PhD thesis, Department
% of Engineering Science, Oxford University 1989, p45.

% Copyright (c) 2002-2010 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% http://www.csse.uwa.edu.au/~pk/research/matlabfns/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.

% March    2002 - Original version
% December 2002 - Updated comments
% August   2005 - Changed so that code calls nonmaxsuppts
% August   2010 - Changed to use Farid and Simoncelli's derivative filters

function [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp)

    error(nargchk(2,5,nargin));
    if nargin == 4
	disp = 0;
    end

    if ~isa(im,'double')
	im = double(im);
    end

    subpixel = nargout == 5;

    % Compute derivatives and elements of the structure tensor.
    [Ix, Iy] = derivative5(im, 'x', 'y');
    Ix2 = gaussfilt(Ix.^2,  sigma);
    Iy2 = gaussfilt(Iy.^2,  sigma);
    Ixy = gaussfilt(Ix.*Iy, sigma);

    % Compute the Harris corner measure. Note that there are two measures
    % that can be calculated.  I prefer the first one below as given by
    % Nobel in her thesis (reference above).  The second one (commented out)
    % requires setting a parameter, it is commonly suggested that k=0.04 - I
    % find this a bit arbitrary and unsatisfactory.

    cim = (Ix2.*Iy2 - Ixy.^2)./(Ix2 + Iy2 + eps); % My preferred  measure.
%    k = 0.04;
%    cim = (Ix2.*Iy2 - Ixy.^2) - k*(Ix2 + Iy2).^2; % Original Harris measure.

    if nargin > 2   % We should perform nonmaximal suppression and threshold

	if disp  % Call nonmaxsuppts to so that image is displayed
	    if subpixel
		[r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh, im);
	    else
		[r,c] = nonmaxsuppts(cim, radius, thresh, im);
	    end
	else     % Just do the nonmaximal suppression
	    if subpixel
		[r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh);
	    else
		[r,c] = nonmaxsuppts(cim, radius, thresh);
	    end
	end
    end


%% Testing PSwarm

%% Rosenbrock [x = 1,1, fval = 0]
clc
fun = @(x) (1-x(1))^2 + 100 *(x(2) - x(1)^2)^2;
x0 = [0 0]';

opts = [];
opts.display = 2;

[x,fval,ef,iter,feval] = pswarm(fun,x0,-[10;10],[10;10],[],[],opts)

%% Constrained Rosenbrock [x = .9488,.9, fval = .0026]
clc
fun = @(x) (1-x(1))^2 + 100 *(x(2)-x(1)^2)^2;
x0 = [0 0]';
lb = [0;0];
ub = [1;0.9];

opts.display = 2;
opts.maxfeval = 1e6;

[x,fval,ef,iter] = pswarm(fun,x0,lb,ub,[],[],opts)


function [I,NextSigma,NextdeltaMu] = VarVolatility(x,mu,va,a,b)
% OTO: varational energy (and curvature) of volatile observer

if ~isinf(va)
    iva = va.^-1;
else
    iva = 0;
end
ex = exp(x(:));
v = a + ex;
I = -0.5.*iva*(x(:)-mu).^2 ...
    -0.5*log(v) ...
    -0.5*b./v;
dIdx = iva*(mu-x(:)) - 0.5.*ex./v + 0.5.*b.*ex./v.^2;
dI2dx2 = -iva -0.5.*a*ex./v.^2 -0.5.*b.*ex.*(ex-a)./v.^3;
NextSigma = -dI2dx2.^-1;
NextdeltaMu = NextSigma.*dIdx;


function yearly_tmin_correction(filenameout)

% this program is design to adjust the daily Tmin generated by WG using
% new yearly Tmin series produced by FFT.

% load the yearly averaged Tmin after FFT
load('Pnew_tmin');
tmin_FFT=Pnew_tmin';

% load WG generated daily Tmin
load(filenameout);
[n,m]=size(gTmin);
gTmin=gTmin';
tmin_WG=reshape(gTmin,[],1);

n=length(tmin_FFT); % years
m=length(tmin_WG);  % days

% calculate yearly Tmin generated by WG, namely (Y)
j=1;
Z=zeros(n,1);
for i=1:365:m
    Z(j,1)=mean(tmin_WG(i:i+365-1,1));
    j=j+1;
end

% calculate the ratio of yearly Tmin between those after FFT and
% generated by weather generator
for i=1:n
    tmin_ratio(i,1)=tmin_FFT(i,1)-Z(i,1);
end

% extend the yearly Tmin ratio to daily scale,the data in each
% year are the same
tmin_extent=zeros(m,1);
j=1;
for i=1:365:m
    tmin_extent(i:i+365-1,1)=tmin_ratio(j,1);
    j=j+1;
end

% adjust the daily Tmin generated by WG using above ratios
tmin_adjust=zeros(size(tmin_WG));
for i=1:m
    tmin_adjust(i,1)=tmin_WG(i,1)+tmin_extent(i,1);
end
yearly_corrected_tmin=tmin_adjust;
save('yearly_corrected_tmin','yearly_corrected_tmin')


% demo_triaxial     May 25, 2008

% this scriot demonstrates how to interact
% with the triaxial.m function which calculates
% the geodetic altitude of a spacecraft
% relative to a triaxial ellipsoid

% Orbital Mechanics with Matlab

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear all;

global flat

% conversion factor - degrees to radians

dtr = pi / 180.0;

% Earth gravitational constant (km**3/sec**2)

mu = 398600.4415;

% Earth equatorial radius (kilometers)

req = 6378.1363;

% Earth flattening factor

flat = 1.0 / 298.257;

% classical orbital elements

oev(1) = 8000.0d0;
oev(2) = 0.015d0;
oev(3) = 28.5d0 * dtr;
oev(4) = 120.0d0 * dtr;
oev(5) = 45.0d0 * dtr;
oev(6) = 30.0d0 * dtr;

% compute eci state vector

[rsc, vsc] = orb2eci(mu, oev);

% compute geodetic altitude

alt = triaxial(rsc);

clc; home;

fprintf('\n\nprogram demo_triaxial');

fprintf('\n\naltitude relative to a triaxial ellipsoid');
fprintf('\n-----------------------------------------');

fprintf('\n\naltitude =  %14.8f kilometers\n', alt);

oeprint1(mu, oev);


function submit()
  addpath('./lib');

  conf.assignmentSlug = 'anomaly-detection-and-recommender-systems';
  conf.itemName = 'Anomaly Detection and Recommender Systems';
  conf.partArrays = { ...
    { ...
      '1', ...
      { 'estimateGaussian.m' }, ...
      'Estimate Gaussian Parameters', ...
    }, ...
    { ...
      '2', ...
      { 'selectThreshold.m' }, ...
      'Select Threshold', ...
    }, ...
    { ...
      '3', ...
      { 'cofiCostFunc.m' }, ...
      'Collaborative Filtering Cost', ...
    }, ...
    { ...
      '4', ...
      { 'cofiCostFunc.m' }, ...
      'Collaborative Filtering Gradient', ...
    }, ...
    { ...
      '5', ...
      { 'cofiCostFunc.m' }, ...
      'Regularized Cost', ...
    }, ...
    { ...
      '6', ...
      { 'cofiCostFunc.m' }, ...
      'Regularized Gradient', ...
    }, ...
  };
  conf.output = @output;

  submitWithConfiguration(conf);
end

function out = output(partId, auxstring)
  % Random Test Cases
  n_u = 3; n_m = 4; n = 5;
  X = reshape(sin(1:n_m*n), n_m, n);
  Theta = reshape(cos(1:n_u*n), n_u, n);
  Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u);
  R = Y > 0.5;
  pval = [abs(Y(:)) ; 0.001; 1];
  yval = [R(:) ; 1; 0];
  params = [X(:); Theta(:)];
  if partId == '1'
    [mu sigma2] = estimateGaussian(X);
    out = sprintf('%0.5f ', [mu(:); sigma2(:)]);
  elseif partId == '2'
    [bestEpsilon bestF1] = selectThreshold(yval, pval);
    out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]);
  elseif partId == '3'
    [J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
                       n, 0);
    out = sprintf('%0.5f ', J(:));
  elseif partId == '4'
    [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
                             n, 0);
    out = sprintf('%0.5f ', grad(:));
  elseif partId == '5'
    [J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
                       n, 1.5);
    out = sprintf('%0.5f ', J(:));
  elseif partId == '6'
    [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
                             n, 1.5);
    out = sprintf('%0.5f ', grad(:));
  end
end


function g = gscale(f, varargin)
%GSCALE Scales the intensity of the input image.
%   G = GSCALE(F, 'full8') scales the intensities of F to the full
%   8-bit intensity range [0, 255].  This is the default if there is
%   only one input argument.
%
%   G = GSCALE(F, 'full16') scales the intensities of F to the full
%   16-bit intensity range [0, 65535].
%
%   G = GSCALE(F, 'minmax', LOW, HIGH) scales the intensities of F to
%   the range [LOW, HIGH]. These values must be provided, and they
%   must be in the range [0, 1], independently of the class of the
%   input. GSCALE performs any necessary scaling. If the input is of
%   class double, and its values are not in the range [0, 1], then
%   GSCALE scales it to this range before processing.
%
%   The class of the output is the same as the class of the input.

%   Copyright 2002-2004 R. C. Gonzalez, R. E. Woods, & S. L. Eddins
%   Digital Image Processing Using MATLAB, Prentice-Hall, 2004
%   $Revision: 1.5 $  $Date: 2003/11/21 14:36:09 $

if length(varargin) == 0 % If only one argument it must be f.
   method = 'full8';
else
   method = varargin{1};
end

if strcmp(class(f), 'double') & (max(f(:)) > 1 | min(f(:)) < 0)
   f = mat2gray(f);
end

% Perform the specified scaling.
switch method
case 'full8'
   g = im2uint8(mat2gray(double(f)));
case 'full16'
   g = im2uint16(mat2gray(double(f)));
case 'minmax'
   low = varargin{2}; high = varargin{3};
   if low > 1 | low < 0 | high > 1 | high < 0
      error('Parameters low and high must be in the range [0, 1].')
   end
   if strcmp(class(f), 'double')
      low_in = min(f(:));
      high_in = max(f(:));
   elseif strcmp(class(f), 'uint8')
      low_in = double(min(f(:)))./255;
      high_in = double(max(f(:)))./255;
   elseif strcmp(class(f), 'uint16')
      low_in = double(min(f(:)))./65535;
      high_in = double(max(f(:)))./65535;
   end
   % imadjust automatically matches the class of the input.
   g = imadjust(f, [low_in high_in], [low high]);
otherwise
   error('Unknown method.')
end


function inside = p07_inside ( m, n, point )

%*****************************************************************************80
%
%% P07_INSIDE reports if a point is inside the region in problem 07.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 April 2009
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the spatial dimension.
%
%    Input, integer N, the number of points.
%
%    Input, real POINT(M,N), the coordinates of the points.
%
%    Output, logical INSIDE(N), is TRUE if the point is in the region.
%
  inside(1:n) = 1;

  [ lo, hi ] = p07_box ( m );
%
%  Check whether points are in the bounding box.
%
  for j = 1 : n

    for i = 1 : m
      if ( point(i,j) < lo(i) | hi(i) < point(i,j) )
        inside(j) = 0;
        continue
      end

    end

  end
%
%  Check whether points in the bounding box are in the region.
%
  for j = 1 : n

    if ( ~inside(j) )
      continue
    end

    if ( cos ( point(1,j) ) < point(2,j) )
      inside(j) = 0;
      continue
    end

    if ( point(2,j) < -5.0 + 5.0 * point(1,j)^4 / ( 2.5 * pi )^4 )
      inside(j) = 0;
      continue
    end

  end

  return
end


function coeffs=string2MultiDimPoly(theString)
%%STRING2MULTIDIMPOLY Given a string representing a multidimensional
%           polynomial equation, convert it into a hyoermatrix
%           representation of the polynomial, as can be used in function
%           such as polyValMultiDim and polyDerMultiDim.
%
%INPUTS: theString The string representing the multivariate polynomial.
%           All coefficients come before variables. Variables are all x
%           followed by a number, such as x3. All numbers for variables
%           must be >0. The format of this string is the same as that
%           returned by multiDimPolyMat2String. For example,
%           '60*x2^2-4*x2^3+72*x1*x2+12' is a valid string.
%
%OUTPUTS: coeffs A hypermatrix of the coefficients for the multivariate
%                polynomial. These are arranged such that
%                coeffs(a1,a2,a3...an) corresponds to the coefficient of an
%                x1^(a1-1)*x2^(a2-1)*x3^(a3-1)...xn^(an-1) term.  Thus, the
%                number of indices coeffs takes is equal to the
%                dimensionality of x (not counting singleton dimensions at
%                the end of coeffs). Note that this ordering is the reverse
%                that used in the 1D polyval function that is built into
%                Matlab. The number of elements for each index in coeffs is
%                the maximum order of that dimension +1.
%
%This function just calls string2Terms and terms2MultiDimPolyMat.
%
%January 2016 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

coeffs=terms2MultiDimPolyMat(string2Terms(theString));

end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


classdef CEC2017_F23 < PROBLEM
% <single> <real> <constrained>
% CEC'2017 constrained optimization benchmark problem

%------------------------------- Reference --------------------------------
% G. Wu, R. Mallipeddi, and P. N. Suganthan, Problem definitions and
% evaluation criteria for the CEC 2017 competition on constrained real-
% parameter optimization, National University of Defense Technology, China,
% 2016.
%------------------------------- 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".
%--------------------------------------------------------------------------

    properties
        O;      % Optimal decision vector
        Mat;	% Rotation matrix
    end
    methods
        %% Default settings of the problem
        function Setting(obj)
            CallStack = dbstack('-completenames');
            load(fullfile(fileparts(CallStack(1).file),'CEC2017.mat'),'Data');
            obj.O = Data{12}.o;
            obj.M = 1;
            if isempty(obj.D) || obj.D < 30
                obj.D   = 10;
                obj.Mat = Data{12}.M_10;
            elseif obj.D < 50
                obj.D   = 30;
                obj.Mat = Data{12}.M_30;
            elseif obj.D < 100
                obj.D   = 50;
                obj.Mat = Data{12}.M_50;
            else
                obj.D   = 100;
                obj.Mat = Data{12}.M_100;
            end
            obj.lower    = zeros(1,obj.D) - 100;
            obj.upper    = zeros(1,obj.D) + 100;
            obj.encoding = ones(1,obj.D);
        end
        %% Calculate objective values
        function PopObj = CalObj(obj,PopDec)
            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);
            Z = Z*obj.Mat';
            PopObj = -20*exp(-0.2*sqrt(mean(Z.^2,2))) + 20 - exp(mean(cos(2*pi*Z),2)) + exp(1);
        end
        %% Calculate constraint violations
        function PopCon = CalCon(obj,PopDec)
            Z = PopDec - repmat(obj.O(1:size(PopDec,2)),size(PopDec,1),1);
            Z = Z*obj.Mat';
            PopCon(:,1) = sum(Z(:,2:end).^2,2) + 1 - abs(Z(:,1));
            PopCon(:,2) = abs(sum(Z.^2,2)-4) - 1e-4;
        end
    end
end


function outdata = luisFilter(data,  TR, cutoff, verbose)
% This is a low pass FIR filter using the Parks Mclellan design algorithm
% The phase introduced by the filter is linear and is un-done by
% filtering the data again, backwards
% if you want to see what it does to the data, use verbose=1
% if just want to filter the data, don't use the argument at all.
%
% :Usage:
% ::
%
%     function outdata = luisFilter(data,  TR, cutoff [, verbose])
%
% ..
%    Luis Hernandez. University of Michigan.  Last Edit 9/13/01
% ..

% ..
% close all
%
%%%%%%  These are the important lines of the code   %%%%%%%%%%%%%
% ..
    cutoff = cutoff / (2*TR)
    b = remez(10, [0 cutoff-0.05  cutoff+0.05  1], [1 1 0 0]);
    outdata = filtfilt(b,1, data);
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if (nargin==4)
    freqz(b)
    figure

    % Read the data from file
%    data = load(data_file);
%    data = data(:,2);
    len = size(data, 1);
    time = [1:len] * TR;
    subplot(2,1,1) , plot(time, abs(data));
    xlabel('sec.')

    % Fourier Transform the data
    fdata = fftshift(fft(data));
    scalefactor = max(abs(fdata));

    %frequency range:
    f = [1:len]';
    f = (f - len/2 ) * 1/(TR * len);
    whos
    % Plotting the data before the filter:

    subplot(2,1,1) , hold on,plot(time, abs(data))
    subplot(2,1,2), plot(f, abs(fdata));
    subplot(2,1,2), axis([0  1/(2*TR)  0  scalefactor]);
    xlabel('Hz.');

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Make  Fourier Domain Filter by hand
    %ffilt = ones(len, 1);
    %co  = len/2  +  cutoff * (TR * len);
    %ffilt(co:end) = exp(-((f(co:end) - cutoff).^2) / 0.001 );
    %co  = len/2  - cutoff * (TR * len);
    %ffilt(1:co)   = exp( -((f(1:co) + cutoff).^2) / 0.001 );

    %subplot(2,1,2) , hold on , plot(f, ffilt*scalefactor/2 ,'g');
    %whos

    % Apply the filter to the data and IFT it
    %fdata  = fdata .* ffilt;
    %data = ifft(fdata);

     % Fourier Transform the data
    outfdata = fftshift(fft(outdata));

    % Let's look at the impulse response of the filter:
    impulse= zeros(size(data));

    impulse(size(data,1)/2) = 0.1 *scalefactor;
    impulse_response = filtfilt(b,1,impulse);

    freq_response = fftshift(fft(impulse_response));
    freq_impulse = fftshift(fft(impulse));

    freq_gain = scalefactor/2 + 20*log10( abs(freq_response).^2 ./ abs(freq_impulse) ) ;

    %Plotting the reponse of the filter
    subplot(2,1,1) , hold on,plot(time, abs(outdata), 'r'), title ('Time Domain'), legend('Before', 'After')
    subplot(2,1,2), hold on, plot(f, abs(outfdata), 'r'), title ('Frequency Domain');

    subplot(2,1,2), hold on, plot(f, freq_gain, 'g'),legend('Before','After','Filter Response');

    %figure;
    %plot(f, freq_gain, 'g');
end

return


function [Price, ProbaITM , CI] = GetOptionPrice(Paths,Exercise,TimeToExpiry,RiskFreeRate,Optiontype)

switch Optiontype
    case 'Asian'

        MeanPrices = mean(Paths,1) ;
        OptionPricesAtMaturity = max(MeanPrices- Exercise,0);
           case 'Vanilla'
        OptionPricesAtMaturity = max(Paths(end,:)- Exercise,0);

end;
[MeanPriceAtMaturity, dummy,CI] = normfit(OptionPricesAtMaturity,0.01);
CI                     = CI* exp(-TimeToExpiry * RiskFreeRate);
Price                  = MeanPriceAtMaturity * exp(-TimeToExpiry * RiskFreeRate);
ProbaITM               = 100 * sum(OptionPricesAtMaturity > 0) ./ length(OptionPricesAtMaturity);


function [km2] = in22km2(in2)
% Convert area from square inches to square kilometers.
% Chad A. Greene 2012
km2 = in2*6.4516E-10;


function circlemulti(centers,radius,nop,style)

% H=CIRCLEMULTI(CENTER,RADIUS,NOP,STYLE)
% Draws multi circles specified by centres as rows of the matrix centres.
% example: circlemulti(10*rand(10,2), 3,20,'--r')
hold on
sc=size(centers,1);
if length(radius)==1
    radius = repmat(radius,sc,1);
end
for ii=1:sc
    circle(centers(ii,:),radius(ii),nop,style);
end


function [fStdDevB, fStdDevMc, fBValue, fMc, vBValues] = calc_BootstrapB(mCatalog, nNumberRuns, nMinNum, nCalculateMc, fBinning)
    % Computes standard deviation of b-value and Mc by bootstrapping the dataset.
    %
    % [fStdDevB, fStdDevMc, fBValue, fMc, vBValues] = calc_BootstrapB(mCatalog, nNumberRuns, nMinNum, nCalculateMc, fBinning)
    %
    %
    % Input parameters:
    %   mCatalog          Earthquake catalog to be used
    %   nNumberRuns       Number of simulation runs (Bootstrap)
    %   nMinNum           Minimum number of events > Mc for computing a b-value (after bottstrapping sample)
    %   nCalculateMC      Method to determine the magnitude of completeness (see also: help calc_Mc)
    %   fBinning          Magnitude binning of the catalog
    %
    % Output parameters:
    %   fStdDevB          Standard deviation of the computed b-values as the second moment of the b-value distribution
    %   fStdDevMc         Standard deviation of the computed Mc as the second moment of the Mc distribution
    %   fBValue           Mean b-value of bootstrapped samples
    %   fMc               Mean Mc of bootstrapped samples
    %   vBValues          Vector of all bootstrapped b-values
    %
    % Danijel Schorlemmer
    % June 18, 2003

    report_this_filefun();

    % Get number of events in catalog
    nLength = mCatalog.Count;
    % Init container
    mResult = [];
    % Bootstrap loop
    for nRuns = 1:nNumberRuns
        % Iniy the bootstrapped catalog
        mLoopCatalog = [];
        % Get the random selection of events (multiples allowed)
        vRnd = ceil(rand(nLength,1) * nLength);
        % Create the bootstrapped catalog
        mLoopCatalog = mCatalog.subset(vRnd);
        % Reduce bootstrapped catalog to all events with M >= Mc
        fMc = calc_Mc(mLoopCatalog, McMethods.McBestCombo, fBinning);
        vSel = mLoopCatalog(:,6) >= fMc;
        mLoopCatalog = mLoopCatalog(vSel,:);
        % If enough events remain, compute b-value
        if length(mLoopCatalog(:,1)) >= nMinNum
            % Calculate b-value from bootstrapped catalog
            [fBValue] =  calc_bmemag(mLoopCatalog, fBinning);
        else
            % Not enough events available
            fBValue = nan;
        end
        % Store the results
        mResult = [mResult; fBValue fMc];
    end
    % Return values
    fBValue = mean(mResult(:,1), 'omitnan');
    fMc = mean(mResult(:,2), 'omitnan');
    % Compute the standard deviation of Mc as the second moment of the Mc distribution
    vSel = ~isnan(mResult(:,2));
    vDist = mResult(vSel,2);
    fStdDevMc = std(vDist,1,'omitnan');
    % Compute the standard deviation of b as the second moment of the b distribution
    vSel = ~isnan(mResult(:,1));
    vBValues = mResult(vSel,1);
    fStdDevB = std(vBValues,1,'omitnan');
end


% Fig. 9.30   Feedback Control of Dynamic Systems, 5e
%             Franklin, Powell, Emami
%

clear all;
close all;

h=0.1;
N=1;
nn=1;
nb=nn*nn+1;
ai=0.1:0.001:nn;
NA=(4*N./(pi*ai)).*exp(-sqrt(-1)*asin(h./ai));
subplot(2,1,1)
plot(ai,abs(NA));
grid;
title('Describing function for hysteresis nonlinearity')
xlabel('a');
ylabel('Magnitude, |K_{eq}|');
pause;
ff=180/pi;
subplot(2,1,2)
plot(ai,ff*angle(NA));
grid;
xlabel('a')
ylabel('Phase, \angle K_{eq}, deg')
hold off


function demo4surf
% Demonstration of a bilinear surface.
%

% D.M. Spink
% Copyright (c) 2000

srf = nrb4surf([0.0 0.0 0.5],[1.0 0.0 -0.5],[0.0 1.0 -0.5],[1.0 1.0 0.5]);
nrbplot(srf,[10,10]);
title('Construction of a bilinear surface.');


function [error_x, error_y, fex, fey, ae] = stokespost_q1p0_p(jmpx,jmpy,els,xy,ev)
%stokespost_q1p0_p  computes Poisson error estimator for Q1-P0
%   [err_x, err_y, fex, fey, ae] = stokespost_q1p0_p(jmpx,jmpy,els,xy,ev);
%   input
%          jmpx, jmpy     component elementwise edge stress jumps
%          els            elementwise edge lengths
%          xy             vertex coordinate vector
%          ev             element mapping matrix
%   output
%          err_x, err_y   component of velocity elementwise error estimate
%          fex, fey       component elementwise rhs vectors
%          ae             elementwise Poisson problem matrices
%
%   IFISS function: DJS; 8 March 2005.
% Copyright (c) 2005 D.J. Silvester, H.C. Elman, A. Ramage
      fprintf('computing local error estimator... ')
      x=xy(:,1); y=xy(:,2);
      nel=length(ev(:,1));
      error_x=zeros(nel,1);  error_y=zeros(nel,1);
%
% set up 3x3 Gauss points
      gpt=sqrt(0.6);
      s(1) = -gpt; t(1) = -gpt; wt(1)=25/81;
      s(2) =  gpt; t(2) = -gpt; wt(2)=25/81;
      s(3) =  gpt; t(3) =  gpt; wt(3)=25/81;
      s(4) = -gpt; t(4) =  gpt; wt(4)=25/81;
      s(5) =  0.0; t(5) = -gpt; wt(5)=40/81;
      s(6) =  gpt; t(6) =  0.0; wt(6)=40/81;
      s(7) =  0.0; t(7) =  gpt; wt(7)=40/81;
      s(8) = -gpt; t(8) =  0.0; wt(8)=40/81;
      s(9) =  0.0; t(9) =  0.0; wt(9)=64/81;
%
% inner loop over elements
        for ivtx = 1:4
        xl_v(:,ivtx) = x(ev(:,ivtx));
        yl_v(:,ivtx) = y(ev(:,ivtx));
		end
        ae = zeros(nel,5,5); elerrx=zeros(5,nel);  elerry=zeros(5,nel);
        fex = zeros(nel,5); fey = zeros(nel,5);
% loop over Gauss points
         for igpt = 1:9
         sigpt=s(igpt);
         tigpt=t(igpt);
         wght=wt(igpt);
% evaluate derivatives etc
         [jac_v,invjac_v,phi_v,dphidx_v,dphidy_v] = deriv(sigpt,tigpt,xl_v,yl_v);
         [psi_v,dpsidx_v,dpsidy_v] = qderiv(sigpt,tigpt,xl_v,yl_v);
            for j = 1:5
               for i = 1:5
               ae(:,i,j) = ae(:,i,j)+wght*dpsidx_v(:,i+4).*dpsidx_v(:,j+4).*invjac_v(:);
               ae(:,i,j) = ae(:,i,j)+wght*dpsidy_v(:,i+4).*dpsidy_v(:,j+4).*invjac_v(:);
               end
            end
% end of Gauss point loop
         end
%
% include edge jumps (evaluated at the midpoint)
         for ee = 1:4
         fex(:,ee) = fex(:,ee) - jmpx(:,ee) .* els(:,ee)*(1/3);
         fey(:,ee) = fey(:,ee) - jmpy(:,ee) .* els(:,ee)*(1/3);
          end
%
% solve for local estimate
%         err=ae\fe;
%         elerr_p(ielem,1) = err'*fe;
%% sequential code
         for ielem = 1:nel
		 elerrx(:,ielem) = squeeze(ae(ielem,1:5,1:5))\(fex(ielem,1:5)');
		 elerry(:,ielem) = squeeze(ae(ielem,1:5,1:5))\(fey(ielem,1:5)');
	     end
%%
         for ivtx=1:5,
	     error_x(:) = error_x(:) + fex(:,ivtx) .* elerrx(ivtx,:)';
		 error_y(:) = error_y(:) + fey(:,ivtx) .* elerry(ivtx,:)';
		 end
%%
         fprintf('done.\n')
		 return


function I_out = vesselFilter(I_in, grid_spacing, scales, varargin)
%VESSELFILTER   Frangi's 3D vessel filter.
%
% DESCRIPTION:
%       vesselFilter filters a 3D image using Frangi's vessel filtering
%       algorithm [1-3]. The algorithm works by calculating the Hessian
%       matrix (containing second order gradients) at each image voxel. The
%       eigenvalues of this matrix are then ordered and used to classify
%       whether the voxel is part of a vessel. The algorithm is performed
%       over multiple scales by convolving the input image with a Gaussian
%       of the given input scales. The final output is taken as the maximum
%       of the vessel filtered image across all scales.
%
% USAGE:
%       I_out = vesselFilter(I_in, grid_spacing, scales)
%       I_out = vesselFilter(I_in, grid_spacing, scales, ...)
%
% INPUTS:
%       I_in         - 3D image data to filter
%       grid_spacing - [dx, dy, dz] in [m]
%       scales       - array of scales to use [m]
%
% OPTIONAL INPUTS:
%       Optional 'string', value pairs that may be used to modify the
%       default computational settings.
%
%       alpha        - Value of sensitivity parameter for metric that
%                      distinguishes between plate-like and other
%                      structures (vessel-like or ball-like).
%                      (default = 0.5)
%       beta         - Value of sensitivity parameter for metric that
%                      distinguishes between ball-like and other structures
%                      (vessel-like or plate-like).
%                      (default = 0.5)
%       c            - Value used to scale the sensitivity parameter for
%                      the noise metric (the sensitivity parameter itself
%                      is calculated automatically based on the magnitudes
%                      of the eigenvalues).
%                      (default = 1)
%       gamma        - normalisation factor for scale-space derivatives
%                      (default = 1)
%       DisplayUpdates - Boolean controlling whether command line updates
%                      are displayed (default = true)
%       Plot         - Boolean controlling whether a maximum intensity
%                      projection of the vessel filtered image at each
%                      scale is displayed (default = false)
%       Colormap     - colormap to use if 'Plot' is set to true (default =
%                      flipud(gray))
%
% OUTPUTS:
%       I_out        - vessel filtered image
%
% ABOUT:
%       author       - Bradley Treeby and Tanmayi Oruganti
%       date         - 9th May 2012
%       last update  - 21st August 2014
%
%       This function is based on original code by Dean Barratt and Yipeng
%       Hu, CMIC, UCL, 2006-2009
%
% REFERENCES:
%   [1] A. F. Frangi, W. J. Niessen, K. L. Vincken, M. A. Viergever (1998)
%       "Multiscale vessel enhancement filtering," MICCAI, pp. 130-137.
%   [2] R. Manniesing, M.A. Viergever, W.J. Niessen (2006) "Vessel
%       enhancing diffusion: A scale space representation of vessel
%       structures," Med. Image Anal. 10, pp. 815-25.
%   [3] T. Oruganti, J. Laufer, B. E. Treeby (2013) "Vessel filtering of
%       photoacoustic images," Proc. of SPIE, vol. 8581, p. 85811W-1.
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox
%
% See also interpftn, smooth

% This file is part of k-Wave. k-Wave 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.
%
% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY
% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
% more details.
%
% You should have received a copy of the GNU Lesser General Public License
% along with k-Wave. If not, see <http://www.gnu.org/licenses/>.

% start timer
start_time = clock;

% set default parameters
num_req_input_variables = 3;    % minimum number of input variables
alpha = 0.5;                    % value of sensitivity parameter for plate vs vessel/ball measure
beta = 0.5;                     % value of sensitivity parameter for ball vs vessel/plate measure
c_scale = 1;                    % scale value of sensitivity parameter for noise
gamma = 0;                      % normalisation factor for scale-space derivatives
origin_smoothness_const = 1e-6; % constant for Manniesing's origin smoothness term
disp_updates = true;            % boolean controlling display of command line updates
plot_updates = false;           % boolean controlling MIP display
color_map = flipud(gray);       % colormap to use if images are displayed
cardan_tol = 0.001;             % tolerance for finding complex roots using cardanRoots

% check user defined inputs
% replace with user defined values if provided
if nargin < num_req_input_variables
    error('Incorrect number of inputs');
elseif ~isempty(varargin)
    for input_index = 1:2:length(varargin)
        switch varargin{input_index}
            case 'alpha'
                alpha = varargin{input_index + 1};
            case 'beta'
                beta = varargin{input_index + 1};
            case 'c'
                c_scale = varargin{input_index + 1};
            case 'gamma'
                gamma = varargin{input_index + 1};
            case 'Display'
                disp_updates = varargin{input_index + 1};
            case 'DisplayUpdates'
                disp_updates = varargin{input_index + 1};
            case 'Plot'
                plot_updates = varargin{input_index + 1};
            case 'Colormap'
                color_map = varargin{input_index + 1};
            otherwise
                error('Unknown optional input');
        end
    end
end

% get size of input volume
sz = size(I_in);

% create k-space grid to use for spectral derivatives
kgrid = makeGrid(sz(1), grid_spacing(1), sz(2), grid_spacing(2), sz(3), grid_spacing(3));

% force wavenumber vectors to be in the correct directions for bsxfun
kx_vec = kgrid.kx_vec;
ky_vec = kgrid.ky_vec.';
kz_vec = permute(kgrid.kz_vec, [2 3 1]);

% compute 3D fft of input image
Ik = fftn(I_in);

% preallocate empty output image
I_out = zeros(size(I_in));

% loop through the scales defined by the user
for scale_index = 1:length(scales)

    % extract the current scale
    scale = scales(scale_index);

    % update command line status
    if disp_updates
        disp(['Computing Vesselness filter for scale ' num2str(scale) ':']);
        tic, fprintf('  Calculating derivatives... ');
    end

    % create normalised frequency domain gaussian at current scale
    FG = exp( (-0.5*scale^2)*(kgrid.kx.^2 + kgrid.ky.^2 + kgrid.kz.^2) );

    % compute components of Hessian matrix convolved with Gaussian
    Hxx = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*kx_vec).^2, FG)) )), [], 1);
    Hyy = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*ky_vec).^2, FG)) )), [], 1);
    Hzz = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*kz_vec).^2, FG)) )), [], 1);
    Hxy = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*kx_vec), bsxfun(@times, (1i*ky_vec), FG))) )), [], 1);
    Hxz = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*kx_vec), bsxfun(@times, (1i*kz_vec), FG))) )), [], 1);
    Hyz = reshape(real(ifftn( Ik .* ifftshift( bsxfun(@times, (1i*ky_vec), bsxfun(@times, (1i*kz_vec), FG))) )), [], 1);

    % update command line status
    if disp_updates
        toc, tic, fprintf('  Computing eigenvalues... ');
    end

    % compute trace of Hessian matrix
    P2 = -(Hxx + Hyy + Hzz);

    % compute principal minors of Hessian matrix
    M11 = Hyy.*Hzz - Hyz.^2;
    M22 = Hzz.*Hxx - Hxz.^2;
    M33 = Hxx.*Hyy - Hxy.^2;
    P1 = (M11 + M22 + M33);

    % compute determinant of Hessian matrix
    P0 = - Hxx.*M11 ...
         + Hxy.*(Hxy.*Hzz - Hyz.*Hxz) ...
         - Hxz.*(Hxy.*Hyz - Hyy.*Hxz);

    % find eigenvalues using roots of 3rd order polynomial
    P3 = 1;
    eigenval_mat = cardanRoots(P3, P2, P1, P0, cardan_tol).';

    % update command line status
    if disp_updates
        toc, tic, fprintf('  Sorting eigenvalues... ');
    end

    % sort eigenvalues based on their absolute values
    [~, ind] = sort(abs(eigenval_mat));
    ind = bsxfun(@plus, (0:numel(I_in)-1)*3, ind);
    eigenval_mat = eigenval_mat(ind);

    % update command line status
    if disp_updates
        toc, tic, fprintf('  Evaluating vesselness measure... ');
    end

    % calculate noise parameter dynamically if not given
    Rs = sqrt( abs(eigenval_mat(1, :)).^2 + abs(eigenval_mat(2, :)).^2 + abs(eigenval_mat(3, :)).^2 );
    c = c_scale*0.5*max(Rs(:));

    % calculate overall vesselness measure and scale by Lindeberg?s constant
    %   term 1: plate vs vessel/ball measure
    %   term 2: ball vs vessel/plate measure
    %   term 3: noise measure (Frobenius matrix norm of the Hessian)
    %   term 4: Manniesing's origin smoothness term
    V = scale.^(gamma) .* ...
        (1 - exp(-(abs(eigenval_mat(2, :))./abs(eigenval_mat(3, :))).^2./(2*alpha^2))) .* ...
        (exp(-(abs(eigenval_mat(1, :))./sqrt(abs(eigenval_mat(2, :).*eigenval_mat(3, :)))).^2./(2*beta^2))) .* ...
        (1 - exp(-Rs.^2./(2*c^2))) .* ...
        (exp(-(2*origin_smoothness_const.^2)./(abs(eigenval_mat(2, :)).*eigenval_mat(3, :).^2)));

    % eliminate structures with positive eigenvalues as these indicate
    % regions of low optical absorption on a background of high optical
    % absorption
    V(eigenval_mat(2, :) > 0 | eigenval_mat(3, :) > 0) = 0;

    % reshape to be the correct size
    V = reshape(V, sz);

    % take maximum response over multiple scales
    I_out = max(I_out, V);

    % display time elapsed
    if disp_updates
        toc
    end

    % plot steps if required
    if plot_updates

        % get suitable axis scaling
        [~, axis_scale, axis_prefix] = scaleSI(max([sz(1)*grid_spacing(1), sz(2)*grid_spacing(2)]));

        % plot figure
        figure;
        imagesc(kgrid.y_vec * axis_scale, kgrid.x_vec * axis_scale,  max(V, [], 3));
        axis image;
        colormap(color_map);
        title(['Vessel Filtered Image (MIP), Scale = ' num2str(scale)]);
        ylabel(['x [' axis_prefix 'm]']);
        xlabel(['y [' axis_prefix 'm]']);
        colorbar;
        drawnow;

        % plot final multi-scale image
        if scale_index == length(scales)
            figure;
            imagesc(kgrid.y_vec * axis_scale, kgrid.x_vec * axis_scale,  max(I_out, [], 3));
            axis image;
            colormap(color_map);
            title('Vessel Filtered Image (MIP), Multi-Scale');
            ylabel(['x [' axis_prefix 'm]']);
            xlabel(['y [' axis_prefix 'm]']);
            colorbar;
            drawnow;
        end
    end
end

% display total time elapsed
if disp_updates
    disp(['  Total computation time ' scaleTime(etime(clock, start_time))]);
end

% end of function
end

% =========================================================================
% SUB FUNCTIONS
% =========================================================================

function roots = cardanRoots(varargin)
% Find roots of third order polynomials using Cardan's formula
%
% INPUT
%   P: (n x 4) array, each row corresponds to coefficients of each
%   polynomial, P(:,1)*x^3 + P(:,2)*x^2 + P(:,3)*x + P(:,4)
% OUTPUT
%   roots: (n x 3) array, each row correspond to the roots of P
%
% To adjust the parameter below which the the discriminant is considerered
% as nil, use
%   CardanRoots(P, tol)
% Adjusting tol is useful to avoid the real roots become complex due to
% numerical accuracy. The default TOL is 0
%
% http://www.sosmath.com/algebra/factor/fac11/fac11.html
% http://mathforum.org/dr.math/faq/faq.cubic.equations.html
%
% See also: roots, ParabolaRoots, eig3
%
% Author: Bruno Luong <brunoluong@yahoo.com>
% History:
%     Original 20-May-2010

% Copyright (c) 2010, Bruno Luong
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in
%       the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.

% Adjustable parameter
tol = 0;

if nargin<4
    P = varargin{1};
    a = P(:,1);
    b = P(:,2);
    c = P(:,3);
    d = P(:,4);
    if nargin>=2
        tol = varargin{2};
    end
else
    [a, b, c, d] = deal(varargin{1:4});
    if nargin>=5
        tol = varargin{5};
    end
end

if ~isequal(a,1)
    b = b./a;
    c = c./a;
    d = d./a;
end

b2 = b.^2;

p = -b2/3 + c;
q = ((2/27)*b2-(1/3)*c).*b + d;
delta = q.^2 + (4/27)*p.^3;

% Three cases of discriminant sign
iscmplx = imag(p) | imag(q);
notcmplx = ~iscmplx;
deltanull = notcmplx & abs(delta)<tol; % = 0
deltaneg = notcmplx & delta<0;
deltapos = notcmplx & ~(deltanull | deltaneg);

n = size(delta,1);
roots = zeros(n, 3, class(delta));

if any(deltanull)
    idx = find(deltanull);
    roots(idx,:) = CardanNull(p(idx), q(idx));
end

if any(deltaneg)
    idx = find(deltaneg);
    roots(idx,:) = CardanNeg(q(idx), delta(idx));
end

if any(deltapos)
    idx = find(deltapos);
    roots(idx,:) = CardanPos(q(idx), delta(idx));
end

if any(iscmplx)
    idx = find(iscmplx);
    roots(idx,:) = CardanCmplx(p(idx), q(idx), delta(idx));
end

roots = bsxfun(@minus, roots, b/3);

end

function roots = CardanNull(p, q)

    S1 = 3*q./p;
    S2 = -0.5*S1;
    roots = [S1 S2 S2];  % double real solutions

end

function roots = CardanNeg(q, delta)

    alfa = -q;
    beta = sqrt(-delta);
    r2 = alfa.^2-delta;
    rho = (4^(1/3))*exp(log(r2)/6);
    theta = atan2(beta,alfa)/3;
    alfa = rho.*cos(theta);
    beta = rho.*sin(theta);
    S1 = alfa;
    x = (-0.5)*alfa;
    y = (sqrt(3)/2)*beta;
    S2 = x-y;
    S3 = x+y;
    roots = [S1 S2 S3];

end

function roots = CardanPos(q, delta)

    sqrtdelta = sqrt(delta);
    u3 = (-q+sqrtdelta)/2;
    v3 = (-q-sqrtdelta)/2;

    % Cubic roots of u3 and v3
    u = sign(u3).*exp(log(abs(u3))/3);
    v = sign(v3).*exp(log(abs(v3))/3);

    S1 = u+v;
    % Complex solutions
    j = complex(-0.5,sqrt(3)/2);
    j2 = complex(-0.5,-sqrt(3)/2);
    S2 = j*u+j2*v;
    S3 = conj(S2);
    roots = [S1 S2 S3];

end

function roots = CardanCmplx(p, q, delta)

    sqrtdelta = sqrt(delta);
    u3 = (-q+sqrtdelta)/2;
    v3 = (-q-sqrtdelta)/2;

    % we need u*v = -p/3
    p = (-1/3)*p;
    iu = abs(u3)>abs(v3);
    u = zeros(size(u3),class(u3));
    v = zeros(size(v3),class(v3));
    u(iu) = exp(log(u3(iu))/3);
    v(iu) = p(iu)./u(iu);
    v(~iu) = exp(log(v3(~iu))/3);
    u(~iu) = p(~iu)./v(~iu);

    S1 = u+v;

    j = complex(-0.5,sqrt(3)/2);
    j2 = complex(-0.5,-sqrt(3)/2);
    S2 = j*u+j2*v;
    S3 = j2*u+j*v;
    roots = [S1 S2 S3];

end


function wc = FWT2_PO(x,L,qmf)
% FWT2_PO -- 2-d MRA wavelet transform (periodized, orthogonal)
%  Usage
%    wc = FWT2_PO(x,L,qmf)
%  Inputs
%    x     2-d image (n by n array, n dyadic)
%    L     coarse level
%    qmf   quadrature mirror filter
%  Outputs
%    wc    2-d wavelet transform
%
%  Description
%    A two-dimensional Wavelet Transform is computed for the
%    array x.  To reconstruct, use IWT2_PO.
%
%  See Also
%    IWT2_PO, MakeONFilter
%
	[n,J] = quadlength(x);
	wc = x;
	nc = n;
	for jscal=J-1:-1:L, % from fine (J) to coarse (L)
		top = (nc/2+1):nc; bot = 1:(nc/2);
		for ix=1:nc,
			row = wc(ix,1:nc);
			wc(ix,bot) = DownDyadLo(row,qmf);
			wc(ix,top) = DownDyadHi(row,qmf);
		end
		for iy=1:nc,
			row = wc(1:nc,iy)';
			wc(top,iy) = DownDyadHi(row,qmf)';
			wc(bot,iy) = DownDyadLo(row,qmf)';
		 end
		nc = nc/2; % downsampling
	end

%
% Copyright (c) 1993. David L. Donoho
%

%
%  Part of Wavelab Version 850
%  Built Tue Jan  3 13:20:40 EST 2006
%  This is Copyrighted Material
%  For Copying permissions see COPYING.m
%  Comments? e-mail wavelab@stat.stanford.edu


function c=ref_fftreal(f)
%REF_FFTREAL  Reference FFTREAL
%
%  FFTREAL is computed by doing an FFT, and keeping only the positive
%  frequencies.

L=size(f,1);
c=fft(f);

c=c(1:floor(L/2)+1,:);


function BrainNet=SR(BOLD,lambda)
% FC Network Construction using Sparse Representation (SR)
%
% Inpute:
% BOLD. A cell array with size of N x 1, each cell is a matrix of BOLD signals (#time points x #ROIs) from one of N subject
%       Each subject may have different #time points but should have the same #ROIs
% lambda. parameter for sparsity
%
% Output:
% BrainNet. FC network (#ROIs x #ROIs x #Subjects)
%
% Requires SLEP toolbox: http://www.yelab.net/software/SLEP/
%
% By Yu Zhang, zhangyu0112@gmail.com
% IDEA lab https://www.med.unc.edu/bric/ideagroup
% Department of Radiology and BRIC, UNC Chapel Hill

%% Initialize parameters for SLEP toolbox
opts=[];
opts.init=2;    % starting point: starting from a zero point here
opts.tFlag=0;   % termination criterion
opts.nFlag=0;   % normalization option: 0-without normalization
opts.rFlag=1;   % regularization % the input parameter 'rho' is a ratio in (0, 1)
opts.rsL2=0;    % the squared two norm term in min  1/2 || A x - y||^2 + 1/2 rsL2 * ||x||_2^2 + z * ||x||_1
opts.mFlag=0;   % treating it as compositive function
opts.lFlag=0;   % Nemirovski's line search

%% Construct FC networks using sparse representation
[nTime,nROI]=size(BOLD{1});
nSubj=length(BOLD);
BrainNet=zeros(nROI,nROI,nSubj,'single');
for i=1:nSubj
    temp=BOLD{i};
    temp=temp-repmat(mean(temp,2),1,nROI);     % centralization
    tempNet=zeros(nROI,nROI);
    for j=1:nROI
        ndic=setdiff(1:nROI,j);
        y=temp(:,j);
        A=temp(:,ndic);
        x=LeastR(A,y,lambda,opts);
        tempNet(ndic,j)=x;
    end
    tempNet=(tempNet+tempNet')/2;              % form symmetric adjancency matrix (main diag are zeros)
    tempNet=tempNet-diag(diag(tempNet));       % ignore self connections
    BrainNet(:,:,i)=tempNet;
end


clear all; close all; clear classes; clc;

%% Set flags.
inspect_only = false;

%% Create shapes.
a = 420;  % lattice constant
t = 1;  % slab thickness

% permittivity, r/a, and omega*a/(2*pi*c) are taken from p.234 of John D.
% Joannopoulos? et al., "Photonic Crystals: Molding the Flow of Light," 2nd
% edition so that the frequency lies in a band gap.
eps_diel = 11.4;
r = 0.25*a;  % hole radius
wvlen = a/0.3;  % omega*a/(2*pi*c) = k*a/(2*pi) = a/lambda = 0.3

ad = 25;  % divider for a
td = 10;  % divider for t
dd = 10;  % divider for d = 2*r

mx = 25.5;  % half integer puts domain boundary between cylinders and makes PML works better
my = 7.5;
slab_yn = Box([-mx*a mx*a; -my*a -0.5*a; 0 t], [a/ad, a/ad, t]);
slab_yp = Box([-mx*a mx*a; 0.5*a my*a; 0 t], [a/ad, a/ad, t]);

rod = CircularCylinder(Axis.z, t, [0 0 t/2], r, [2*r/dd, 2*r/dd, t]);

%% Solve the system.
gray = [0.5 0.5 0.5];  % [r g b]
src_loc = 6*a;
[E, H, obj_array, src_array, J] = maxwell_run(...
	'OSC', 1e-9, wvlen, ...
	'DOM', {'vacuum', 'white', 1.0}, [-mx*a mx*a; -my*a my*a; 0 t], [a/ad a/ad t], BC.p, [7*a 2*a 0], 2, 1e-4, ...
	'OBJ', ...
		{'dielectric', gray, eps_diel}, periodize_shape(rod, {[a 0 0], [0 a 0], [0 0 t]}, slab_yn), ...
		{'dielectric', gray, eps_diel}, periodize_shape(rod, {[a 0 0], [0 a 0], [0 0 t]}, slab_yp), ...
	'SRCJ', PointSrc(Axis.z, [src_loc, 0, 0.5]), ...
	inspect_only);

%% Visualize the solution.
if ~inspect_only
	figure;
	clear opts
% 	opts.withgrid = true;
	opts.withobjsrc = false;
	opts.withabs = true;
	opts.withpml = false;
	opts.phase = pi/2;
	figure(1)
	vis2d(E{Axis.z}, Axis.z, 0.5, obj_array, src_array, opts)
	%%
	figure(2)
	vis2d(H{Axis.y}, Axis.z, 0.5, obj_array, src_array, opts)

	%%
	flux_loc = 3*a;
	power_right = powerflux_patch(E, H, Axis.x, src_loc + flux_loc);
	power_left = -powerflux_patch(E, H, Axis.x, src_loc - flux_loc);
	fprintf('power:\n');
	fprintf('right = %s\n', num2str(power_right));
	fprintf('left = %s\n', num2str(power_left));
	fprintf('error = %s%%\n',num2str((power_left-power_right)/power_right*100));

	%%
	Sx = poynting(Axis.x, E{Axis.y}, E{Axis.z}, H{Axis.y}, H{Axis.z}, Axis.y, 0);
	[array, l] = Sx.data_original;
	figure(3)
	plot(l{2}, abs(array))
	mx*a - 10*a

% 	%%
% 	xs = E{Axis.z}.grid3d.l{Axis.x,GT.prim};
% 	ez = NaN(size(xs));
% 	i = 0;
% 	for x = xs
% 		i = i + 1;
% 		ez(i) = E{Axis.z}.value([x 0 t/2]);
% 	end
% 	%%
% 	figure(4);
% 	plot(xs, imag(ez));
%
% 	%%
% 	xs = E{Axis.z}.grid3d.l{Axis.x,GT.prim};
% 	hy = NaN(size(xs));
% 	i = 0;
% 	for x = xs
% 		i = i + 1;
% 		hy(i) = H{Axis.y}.value([x 0 t/2]);
% 	end
% 	%%
% 	figure(5);
% 	plot(xs, real(hy));
%
% 	%%
% % 	sx = real(imag(ez) .* real(hy));
% % 	sx = imag(ez .* conj(hy));
% 	sx = real(ez .* conj(hy));
% 	figure(6);
% 	plot(xs, abs(sx));
%
% 	% Need to verify if the same problem occurs for precisely selected frequency
% 	% for defect waveguide.
end


function I = mutualinfo1(A,B)
%==================================================
%This is a prog in the MutualInfo 0.9 package written by
% Hanchuan Peng.
%
% I = mutualinfo(vec1,vec2)
% calculate the mutual information of two vectors
%
% For small images this function is faster than
% function 'mutualinfo2'.
%==================================================

pA = estpa(A);
HA = estentropy(pA);

pB = estpa(B);
HB = estentropy(pB);

pAB = estpab(A,B);
HAB = estjointentropy(pAB);

I = HA + HB - HAB;
return


%Script cmssnn;
%Center of mass calculation
%xc, yc; xcc, ycc - coordinates of center
%of mass of curve and spot
%(interior of the curve) correspondingly
%mss - mass (square) of a spot
mss=sum(sum(~J3));
xcc=0;ycc=0;
  for i=1:si;
    for j=1:sj;
      if ~J3(i,j)
        xcc=xcc+i;
        ycc=ycc+j;
      end
    end
  end
    xcc=xcc/mss;
    ycc=ycc/mss;

xc=mean(X0);
yc=mean(Y0);

    kz=[];
for iz=1:numel(X0);
  kz=[kz max(sqrt((X0(iz)-X0(iz+1:end)).^2+(Y0(iz)-Y0(iz+1:end)).^2))];
end
[uz1,uz]=max(kz);
[kz1,kz2]=max(sqrt((X0(uz)-X0(1:end)).^2+(Y0(uz)-Y0(1:end)).^2));


function test_gppde_2d

% $$$ x_g = -5:0.5:5;
% $$$ [x1_g, x2_g] = meshgrid(
T = 1;
L = 1;
%[x1_g, x2_g] = meshgrid(linspace(-0*T,3*T,60), linspace(-1*L,2*L,40));
min_L = 0.0*L;
max_L = 1.0*L;
min_T = 0.0*T;
max_T = 1.0*T;
[x1_g, x2_g] = meshgrid(linspace(min_T,max_T,40), linspace(min_L,max_L,40));
X_g = [x1_g(:), x2_g(:)];
[x1_f, x2_f] = meshgrid(linspace(0,T,45), linspace(0,L,45));
X_f = [x1_f(:), x2_f(:)];

% Define the partial differential equation
N_g = size(X_g, 1);
switch 1
 case 1
  %
  % HEAT EQUATION (d_t - d_x^2 = 0)
  %
  theta = [1 1/10]; % [scale, length scale]
  s2_y = theta(1)^2 * 1e-5;

  D = [1 0;     % differentiation
       0 2];
  alpha = [-1;   % coefficients
           0.02]; % (<- heat conduction)

  % Spatial boundary fixed to zero
  N_y = 30;
  bound1 = [linspace(min_T,max_T,N_y)', min_L*ones(N_y,1)];
  bound2 = [linspace(min_T,max_T,N_y)', max_L*ones(N_y,1)];
  X_y = [bound1; bound2];
  y = zeros(size(X_y,1),1);
  % Initial function at time T=min_T
  T_obs = min_T + 0.1*(max_T-min_T);
  bound_init = [T_obs*ones(N_y,1), linspace(min_L,max_L,N_y)'];
  X_y = [X_y; bound_init];
  y_init = 2*exp( -0.5*(bound_init(:,2)-0.5*(min_L+max_L)).^2 / 0.1^2);
  y = [y; y_init] + sqrt(s2_y)*randn(size(X_y,1),1);

  equation = 'Heat equation';

 case 2
  %
  % WAVE EQUATION (d_t^2 - d_x^2 = 0)
  %
  theta = [1 1/30]; % [scale, length scale]
  s2_y = theta(1)^2 * 1e-4;

  D = [2 0;
       0 2];
  alpha = [-1;
           16]; % speed ^ 2
  % Spatial boundary fixed to zero
  N_y = 100;
  bound1 = [linspace(min_T,max_T,N_y)', min_L*ones(N_y,1)];
  bound2 = [linspace(min_T,max_T,N_y)', max_L*ones(N_y,1)];
  X_y = [bound1; bound2];
  y = zeros(size(X_y,1),1);
% $$$   % Initial function at time T=min_T
% $$$   bound_init = [min_T*ones(N_y,1), linspace(min_L,max_L,N_y)'];
% $$$   X_y = [X_y; bound_init];
% $$$   y_init = 2*exp( -0.5*(bound_init(:,2)-0.5*(min_L+max_L)).^2 / 0.03^2);
% $$$   y = [y; y_init];
  y = y + sqrt(s2_y)*randn(size(X_y,1),1);

  equation = 'Wave equation';

 case 3
  %
  % LAPLACE EQUATION (d_x^2 + d_y^2 = 0)
  %
  theta = [1 1/20]; % [scale, length scale]
  s2_y = theta(1)^2 * 1e-5;

  D = [2 0;
       0 2];
  alpha = [1;
           1];
  X_y = zeros(0,2);
  y = zeros(0,1);

end
g = zeros(N_g,1);

% Inference: Get posterior predictive distribution
[m_f, V_f] = gppde(X_y, y, s2_y, theta, X_g, g, alpha, D, X_f);
% $$$ figure
% $$$ imagesc(V_f);

% Draw posterior predictive samples
samples = 1;
I_f = speye(length(V_f));
s2_f = 1e-8; % numerical reasons
L_f = chol(V_f + s2_f*I_f, 'lower');
f = bsxfun(@plus, L_f * randn(length(L_f),samples), m_f);
figure
for i = 1:samples
  subplot(ceil(sqrt(samples)), ceil(sqrt(samples)), i);
%  pcolor(reshape(f(:,i), size(x1_f)));
  contourf(x1_f, x2_f, reshape(f(:,i), size(x1_f)), 100);
  shading('flat')
  map_colormap();
  cl = max( abs(f(:,i)) );
  set(gca, 'clim', [-cl, cl])
  title(equation)
  xlabel('time');
  xlabel('time');
  ylabel('location');
  set(gca, 'xtick', [], 'ytick', []);
end