function [A] = testIJmatlabhypre (inputmatlab, matrix_or_vector, filename, varargin)
%TESTIJMATLABHYPRE Test IJ Martix Conversion between MATLAB and HYPRE Formats.
%
%    This program was tested on Matlab 7.1.
%
%   Description:
%     [A] = testIJmatlabhypre (inputmatlab, matrix_or_vector, filename,
%     varargin) calculates the accuracy  of MATLAB to HYPRE and HYPRE to
%     MATLAB conversion of input matrix or vector.
%
%     To calculate the accuracy of conversion [A], this function converts
%     matrix (or vector) bidirectionally between MATLAB and HYPRE formats
%     and calculates the difference between the input matrix and the result
%     of bidirectional conversion of the input matrix.
%
%     The input format can be either MATLAB or HYPRE. If the input format
%     is MATLAB then the intermediate format is HYPRE. If the input format
%     is HYPRE then the intermediate format is MATLAB.
%
%     The function performs two conversions: forward conversion from input
%     format to intermediate format and backward conversion from
%     intermediate format to input format. The result of such bidirectional
%     conversion is a matrix in the same format as the input matrix.
%
%     [A] = testIJmatlabhypre (inputmatlab, matrix_or_vector, filename,
%     numprocs) calculates the accuracy of MATLAB-HYPRE-MATLAB conversion
%     performed on number of processors given by numprocs.
%
%     [A] = testIJmatlabhypre (inputmatlab, matrix_or_vector, filename, ,
%     imax) calculates the accuracy of HYPRE-MATLAB-HYPRE matrix conversion,
%     where imax is the size of a sparse square HYPRE matrix.
%
%   Inputs:
%     Inputmatlab = 'matlab' if input file is in MATLAB format
%                    'hypre' if input file is in HYPRE format
%     matrix_or_vector = 'matrix' if input file is a matrix
%                      = 'vector' if input file is a vector
%     filename = full file name of the input file
%
%   Example:
%     A = testIJmatlabhypre( 'matlab', 'matrix', 'mymatrix' )
%     will produce the difference [A] between input MATLAB matrix
%     and the result of MATLAB-HYPRE-MATLAB conversion of the input
%     matrix.
%
%     A = testIJmatlabhypre( 'hypre', 'vector', 'mymatrix' )
%     will produce the difference [A] between input HYPRE vector
%     and the result of HYPRE-MATLAB-HYPRE conversion of the input
%     vector.
%
%     A = testIJmatlabhypre( 'matlab', 'matrix', 'mymatrix', 2 )
%     will produce the difference [A] between input MATLAB matrix
%     and the result of MATLAB-HYPRE-MATLAB conversion of the input
%     matrix ran on two processors.
%
%     A = testIJmatlabhypre( 'hypre', 'matrix', 'mymatrix' )
%     will produce the difference [A] between input sparse square HYPRE
%     matrix of size given by imax and the result of HYPRE-MATLAB-HYPRE
%     conversion of the input matrix.
%
%   See also matlabIJ2hypre, matlab2hypreParVectors.m,
%      hypreIJ2matlab.m, hypreParVectors2matlab.m
%
%   Author: Diana Zakaryan, Dept of Mathematics, University of Colorado,
%      Denver, 15-Mar-2005.
%

if nargin > 3
    numprocs = varargin{1}
end

if nargin > 4
    imax = varargin{2}
end

if nargin > 5
    matrix_filename = varargin{3};
    vector_filename = varargin{4};
    A=hypreIJ2matlab(matrix_filename,imax);
    B=hypreParVectors2matlab(vector_filename,1);
    if size(A,2)~=size(B,1)
        error('Dimentions must agree')
    else
    size(A*B)
    end
    clear ('A', 'B');
end

% find out if the check is for matlab format to hypre format
if size(inputmatlab,2) == 6
    % find out if the check is for matrix
    if size(matrix_or_vector,2) == 6
        % code for matlab to hypre in matrix
        % todo add code to check if .mat file or ascii file
        load (filename);
        % converts a matlab formatted matrix to
        % hypre formatted one

        matlab2hypreIJ (matlab_smatrix, numprocs, 'temp_m_hypre');
        imax = size(matlab_smatrix, 1);

        % converts a hypre formatted matrix to
        % matlab formatted one
        matlab_out_m = hypreIJ2matlab ('temp_m_hypre', imax);

        % compare input and output files;
        A1=matlab_smatrix - matlab_out_m
        fprintf('the min of the difference is: %\n', num2str(min(A1)));
        fprintf('the max of the difference is: %\n', num2str(max(A1)));
        clear('matlab_out_m');
        delete ('../temp_m_hypre.*');

    % find out if the check is for vector
    elseif size(matrix_or_vector,2) == 7
        %code for matlab to hypre in vector
        load (filename);

        % converts a matlab formatted vector to
        % hypre formatted one
        matlab2hypreParVectors (matlab_vector,numprocs,'temp_v_hypre');
        % converts a hypre formatted vector to
        % matlab formatted one
        matlab_out_v = hypreParVectors2matlab('temp_v_hypre',1);

        % compare input and output files;
        A2=matlab_vector - matlab_out_v;
        fprintf('the min of the difference is: %\n', num2str(min(A2)));
        fprintf('the max of the difference is: %\n', num2str(max(A2)));
        clear('matlab_out_v');
        delete ('../temp_v_hypre.*');
    else
        %return error message
    end

% find out if the check is for hypre format to matlab format
elseif size(inputmatlab,2) == 5
    % find out if the check is for matrix
    if size(matrix_or_vector,2) == 6
        % code for hypre to matlab in matrix
        % converts a hypre formatted matrix to
        % matlab formatted one
        A=hypreIJ2matlab('matrix',imax);
        % converts a matlab formatted matrix to
        % hypre formatted one
        matlab2hypreIJ(A,numprocs,'matrix_test') %note that for this particular comparison
        % numprocs should be initialized as 2.
        for i=0:numprocs
            s=int2str(i);
            hypre_data_m1=dlmread(strcat('matrix','.0000',s));
            hypre_data_m2=dlmread(strcat('matrix_test','.0000',s));
            % compare input and output files;
            B1=hypre_data_m1-hypre_data_m2
        end

    % find out if the check is for vector
    elseif size(matrix_or_vector,2) == 7
        % converts a hypre formatted vector to
        % matlab formatted one
        A=hypreParVectors2matlab('vectors',1);
        % converts a matlab formatted vector to
        % hypre formatted one
        matlab2hypreParVectors(A,numprocs,'vector_test');
        for i=0:(numprocs-1)
            s=int2str(i);
            hypre_data_v1 = dlmread( strcat('vectors','.0.',s));
            hypre_data_v2 = dlmread( strcat('vector_test','.0.',s));
            % compare input and output files;
            B2=hypre_data_v1-hypre_data_v2
        end
        for i=0:(numprocs-1)
            s=int2str(i);
            hypre_data_v1 = dlmread( strcat('vectors','.0','.INFO.',s));
            hypre_data_v2 = dlmread( strcat('vector_test','.0','.INFO.',s));
            % compare 'INFO' input and output files;
            B3=hypre_data_v1-hypre_data_v2
        end
    else
        %return error message
    end
end


classdef JointPD < Controller
    % This class defines a PD feedback control on the joint space
    %
    % @author ayonga @date 2016-10-14
    %
    % Copyright (c) 2016, AMBER Lab
    % All right reserved.
    %
    % Redistribution and use in source and binary forms, with or without
    % modification, are permitted only in compliance with the BSD 3-Clause
    % license, see
    % http://www.opensource.org/licenses/bsd-license.php

    methods

        function obj = JointPD(name)
            % The controller class constructor function
            %
            % Parameters:
            % name: the controller name @type char

            % call superclass constructor
            obj = obj@Controller(name);

            % initialize default control parameters
            ep = 10;
            obj.Param.kp = ep^2;
            obj.Param.kd = 2*ep;
        end

        function u = calcControl(obj, t, x, vfc, gfc, plant, params, logger)
            % Computes the PD feedback control law on joint space
            %
            % Parameters:
            % t: the time instant @type double
            % x: the states @type colvec
            % vfc: the vector field f(x) @type colvec
            % gfc: the vector field g(x) @type colvec
            % plant: the continuous domain @type DynamicalSystem
            % params: the control parameters @type struct
            % logger: the data logger object @type SimLogger
            %
            % Return values:
            % u: the computed torque @type colvec

            [qd, dqd] = calcDesiredStates(plant, t, x, params);

            % compute error terms
            qerr = qa - qd;
            dqerr = dqa - dqd;

            % feedback controller
            u = - obj.Param.kp*qerr - obj.Param.kd*dqerr;

            if ~isempty(logger)
                calc = logger.calc;

                calc.qerr = qerr;
                calc.dqerr = dqerr;
                calc.qd = qd;
                calc.dqd = dqd;
                calc.u = u;

                logger.calc = calc;
            end

        end
    end

end


function out=airdata(uu)
%
% Fake air data - this will be replaced with real air data in Chapter 4
%
% modified 12/11/2009 - RB

    % process inputs to function
    pn          = uu(1);             % North position (meters)
    pe          = uu(2);             % East position (meters)
    h           = -uu(3);            % altitude (meters)
    u           = uu(4);             % body velocity along x-axis (meters/s)
    v           = uu(5);             % body velocity along y-axis (meters/s)
    w           = uu(6);             % body velocity along z-axis (meters/s)
    phi         = 180/pi*uu(7);      % roll angle (degrees)
    theta       = 180/pi*uu(8);      % pitch angle (degrees)
    psi         = 180/pi*uu(9);      % yaw angle (degrees)
    p           = 180/pi*uu(10);     % body angular rate along x-axis (degrees/s)
    q           = 180/pi*uu(11);     % body angular rate along y-axis (degrees/s)
    r           = 180/pi*uu(12);     % body angular rate along z-axis (degrees/s)

    Va = sqrt(u^2+v^2+w^2);
    alpha = atan2(w,u);
    beta  = asin(v);
    wn    = 0;
    we    = 0;
    wd    = 0;

    out = [Va; alpha; beta; wn; we; wd];


classdef metricTree < handle
%%METRICTREE A metric tree class for performing searches in a radius
%            around a given point. If a C++ class interface for the metric
%            tree has been compiled, then its functions will be called in
%            place of the Matlab routines, since the C++ implementation
%            can be significantly faster.
%
%The metric tree data structure is implemented as described in [1] and [2].
%
%This implementation builds the tree from a batch of data all at once. As
%long as there are not numerous points equidistance from a given point, the
%tree will be balanced. The Euclidean distance is used as the metric,
%though the code could be changed to replace it with almost any distance
%metric that satisfies the triangle inequality.
%
%Note that unlike certain metric tree implementations, not all of the nodes
%are held in the leaves.
%
%Modification of the CPPData member of this class or of the error checking
%code in the members can potentially lead to Matlab crashing as CPPData is
%a pointer to data in the C++ implementation.
%
%REFERENCES:
%[1] J. K. Uhlmann. (1991, Nov.) Implementing metric trees to satisfy
%    general proximity/similarity queries. [Online]. Available:
%    http://people.cs.missouri.edu/ uhlmannj/ImplementGH.pdf
%[2] J. K. Uhlmann, "Satisfying general proximity/similarity queries with
%    metric trees," Information Processing Letters, vol. 40, no. 4, pp.
%    175-179, 25 Nov. 1991.
%
%December 2013 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

    properties
        DATAIDX%The index of the data at a node.
        innerChild
        outerChild
        innerRadii
        outerRadii
        data%A matrix of the data points.

        CPPData%Only used if an interface to a C++ implementation exists.
    end

    methods
        function newTree=metricTree(k,N)
        %%METRICTREE Construct a new metric tree with space to hold a given
        %            number of nodes.
        %
        %INPUTS: k The dimensionality of the nodes that will be placed in
        %          the tree.
        %        N The number of nodes that the tree will hold.
        %
        %OUTPUTS: newTree A new metricTree instance with the proper amount
        %                 of space.
        %
        %Once a tree has been allocated, it can be initialized using the
        %buildTreeFromBatch method. The size of the data batch given with
        %that method should match the size of the tree allocated here.
            if(exist('metricTreeCPPInt','file'))
                newTree.CPPData=metricTreeCPPInt('metricTreeCPP',k,N);
            else
                newTree.DATAIDX=zeros(N,1);
                newTree.innerChild=zeros(N,1);
                newTree.outerChild=zeros(N,1);
                newTree.innerRadii=zeros(N,1);
                newTree.outerRadii=zeros(N,1);
                newTree.data=[];
            end
        end

        function buildTreeFromBatch(theTree,dataBatch)
        %BUILDTREEFROMBATCH Build a metric tree from a batch of data.
        %
        %INPUTS: theTree The implicitly passed metricTree object.
        %      dataBatch A kXN array of points that are to be stored in
        %                the metric tree. k is the dimensionality of the
        %                points and N is the number of points.
        %
        %The tree is constructed roughly as described in [1].
        %
        %REFERENCES:
        %[1] J. K. Uhlmann. (1991, Nov.) Implementing metric trees to
        %    satisfy general proximity/similarity queries. [Online].
        %    Available: http://people.cs.missouri.edu/ uhlmannj/ImplementGH.pdf

            N=size(dataBatch,2);
            if(exist('metricTreeCPPInt','file'))
                N=metricTreeCPPInt('getN',theTree.CPPData);
                k=metricTreeCPPInt('getk',theTree.CPPData);

                if(N~=size(dataBatch,2)||k~=size(dataBatch,1))
                   error('The data batch given does not match the preallocated size');
                end

                metricTreeCPPInt('buildTreeFromBatch',theTree.CPPData,dataBatch);
            else
                theTree.data=dataBatch;

                %Preallocate an adjacency matrix that will be used in the
                %recursion.
                adjMat=zeros(N,1);
                idx=(1:N)';
                theTree.treeGrow(adjMat,dataBatch,idx,1);
            end
        end

        function [retSet,distSet]=searchRadius(theTree,point,radius)
        %%SEARCHRADIUS Return all of the points in the metric tree that are
        %              located within a given search radius of within a
        %              given radius about a given point.
        %
        %INPUTS: theTree The implicitly passed metricTree object.
        %          point A kXm matrix of k-dimensional points about which
        %                range searches will be performed.
        %         radius An mX1 vector of the search radii about each
        %                point.
        %
        %OUTPUTS: retSet An instance of the ClusterSet class containing all
        %                of the items within the given radius for each
        %                point. If no points in the tree fall into a given
        %                region, then the corresponding clusterSize element
        %                in the ClusterSet will be zero.
        %        distSet An instance of the clusterSet class containing all
        %                of the distances associated with the found items
        %                in retSet

            m1=size(point,2);
            m2=size(radius,1);

            if(m1~=m2)
                error('Inconsistent numbers of points and radii given.');
            end

            if(exist('metricTreeCPPInt','file'))
                [retSet,distSet]=metricTreeCPPInt('searchRadius',theTree.CPPData,point,radius);
                %Convert indices to Matlab indices
                retSet.clusterEls=retSet.clusterEls+1;
            else
                %Create the new ClusterSet instances with m1 empty clusters.
                retSet=ClusterSet([],zeros(m1,1),zeros(m1,1));
                distSet=ClusterSet([],zeros(m1,1),zeros(m1,1));

                %Add the clusters
                for curPoint=1:m1
                    [idxRange,distList]=theTree.searchRadRecur(point(:,curPoint),radius(curPoint),1);

                    retSet.clusterSizes(curPoint)=size(idxRange,1);
                    retSet.clusterEls=[retSet.clusterEls;idxRange];
                    distSet.clusterSizes(curPoint)=size(idxRange,1);
                    distSet.clusterEls=[distSet.clusterEls;distList];
                    if(curPoint<m1)
                        retSet.offsetArray(curPoint+1)=retSet.offsetArray(curPoint)+retSet.clusterSizes(curPoint);
                        distSet.offsetArray(curPoint+1)=distSet.offsetArray(curPoint)+distSet.clusterSizes(curPoint);
                    end
                end
            end
        end

        function display(theTree)
        %%DISPLAY Display information about the tree, including whether the
        %         C++ implementation (wrapped by a Matlab class) or the
        %         Matlab-only implementation is being used.

            if(exist('metricTreeCPPInt','file'))
                display('A metric tree as implemented via a mex wrapper around a C++ class.')
            else
                display('A metric tree as implemented as a Matlab class.')
            end
            theTree.disp();
        end

        function copyDataFromCPP(theTree)
    %%COPYDATAFROMCPP Copy the data that makes up the structure of the tree
    %                 out of C++ into the variables in the Matlab kdTree
    %                 class. This can be useful when debugging the C++
    %                 implementation. This function just raises an error
    %                 when executed when using the Matlab implementation.

            if(exist('metricTreeCPPInt','file'))
                [theTree.DATAIDX,theTree.innerChild,theTree.outerChild,theTree.innerRadii,theTree.outerRadii,theTree.data]=metricTreeCPPInt('getAllData',theTree.CPPData);
            else
                error('This metric tree class instance does not stem from a C++ class');
            end
        end

        function delete(theTree)
        %%DELETE The destructor method. This method is used when the metric
        %        tree is implemented as a C++ class. This method prevents a
        %        memory leak.

            if(exist('metricTreeCPPInt','file'))
                metricTreeCPPInt('~metricTreeCPP',theTree.CPPData);
            end
        end
    end

    methods(Access=private)
        function [idxRange,distList]=searchRadRecur(theTree,point,r2,curNode)
        %%SEARCHRADRECUR A recursion function for performing a search of a
        %                particular radius about a point.

            distCur=dist(point,theTree.data(:,theTree.DATAIDX(curNode)));
            if(distCur<=r2)
                idxRange=theTree.DATAIDX(curNode);
                distList=distCur;
            else
                idxRange=[];
                distList=[];
            end

            if(distCur+r2>=theTree.outerRadii(curNode)&&theTree.outerChild(curNode)~=-1)
                [idxRest,distSqRest]=theTree.searchRadRecur(point,r2,theTree.outerChild(curNode));
                idxRange=[idxRange;idxRest];
                distList=[distList;distSqRest];
            end

            if(distCur-r2<=theTree.innerRadii(curNode)&&theTree.innerChild(curNode)~=-1)
                [idxRest,distSqRest]=theTree.searchRadRecur(point,r2,theTree.innerChild(curNode));
                idxRange=[idxRange;idxRest];
                distList=[distList;distSqRest];
            end
        end

        function nextFreeNode=treeGrow(theTree,adjMat,dataBatch,idx,curNode)
        %%TREEGROW A recursion function for creating a new metric tree.

            NSubTree=size(dataBatch,2);

            %The first index in idx is added to the tree.
            theTree.DATAIDX(curNode)=idx(1);

            %If this is a leaf node.
            if(NSubTree==1)
                theTree.innerChild(curNode)=-1;
                theTree.outerChild(curNode)=-1;
                theTree.innerRadii(curNode)=-Inf;
                theTree.outerRadii(curNode)=Inf;
                nextFreeNode=curNode+1;
                return
            end

            %Fill the NCurX1 subvector of adjMat with all pairwise
            %distances from the current point to the other points in idx.
            NSubTree=NSubTree-1;
            for curPoint=1:NSubTree
                adjMat(curPoint)=dist(dataBatch(:,1),dataBatch(:,curPoint+1));
            end

            %Next, sort the points
            [adjMat(1:NSubTree), sortIdx]=sort(adjMat(1:NSubTree));

            idx=idx(2:end);
            idx=idx(sortIdx);

            dataBatch=dataBatch(:,2:end);
            dataBatch=dataBatch(:,sortIdx);

            %Find the first occurance of the median distance.
            midIdx=findFirstMax(adjMat(1:ceil((NSubTree+1)/2)));

            %The inner and outer radii of how things are split in terms of
            %distances from the given point.
            theTree.outerRadii(curNode)=adjMat(midIdx);
            if(midIdx>1)
                theTree.innerRadii(curNode)=adjMat(midIdx-1);
            else
                theTree.innerRadii(curNode)=-Inf;
            end

            %Continue the recursion.
            theTree.outerChild(curNode)=curNode+1;
            nextFreeNode=theTree.treeGrow(adjMat,dataBatch(:,midIdx:end),idx(midIdx:end),curNode+1);

            %If a full partitioning of the nodes took place
            if(midIdx>1)
                theTree.innerChild(curNode)=nextFreeNode;
                nextFreeNode=theTree.treeGrow(adjMat,dataBatch(:,1:(midIdx-1)),idx(1:(midIdx-1)),nextFreeNode);
            else
                theTree.innerChild(curNode)=-1;
            end
        end
    end
end

function val= dist(a,b)
%%DIST Evaluate the Euclidean distance between two vectors.

    %The square root must be used to obey the triangle inequality.
    diff=a-b;
    val=sqrt(diff'*diff);
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.


function [ labels, valid_ids, vid_ids, vid_names  ] = extract_SEMAINE_labels( SEMAINE_dir, recs, aus )
%EXTRACT_SEMAINE_LABELS Summary of this function goes here
%   Detailed explanation goes here

    % Get the right eaf file

    aus_SEMAINE = [2 12 17 25 28 45];

    inds_to_use = [];

    for i=1:numel(aus)

        inds_to_use = cat(1, inds_to_use, find(aus_SEMAINE == aus(i)));

    end

    labels = cell(numel(recs), 1);
    valid_ids = cell(numel(recs), 1);
    vid_names = cell(numel(recs), 1);
    vid_ids = zeros(numel(recs), 2);

    for i=1:numel(recs)

        file = dir([SEMAINE_dir, '/', recs{i}, '/*.eaf']);

        vid_ids(i,:) = dlmread([SEMAINE_dir, '/', recs{i}, '.txt'], ' ');

        vid_names_c = dir([SEMAINE_dir, '/', recs{i}, '/*.avi']);
        [~, vid_names{i},~] = fileparts(vid_names_c.name);

        xml_file = [SEMAINE_dir, recs{i}, '\' file.name];
        [root_xml, name_xml, ~] = fileparts(xml_file);

        activations = ParseSEMAINEAnnotations([SEMAINE_dir, recs{i}, '/' file.name]);

        if(size(activations,1) < vid_ids(i,2))
            vid_ids(i,2) = size(activations,1);
            if(vid_ids(i,2) > 2999)
                vid_ids(i,1) = vid_ids(i,2) - 2999;
            end
        end

        labels{i} = activations(vid_ids(i,1)+1:vid_ids(i,2), 1 + inds_to_use);

        % all indices in SEMAINE are valid
        valid_ids{i} = ones(size(labels{i},1),1);

    end

end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright 2014 the National Renewable Energy Laboratory and Sandia Corporation
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Run the WEC-Sim RM3 Test Case for 1DOF w/PTO
% This script will run the RM3 in WEC-Sim for irregular waves with Hs=2.5[m]
% and Tp=8[s]. The RM3 WEC models has 2 bodies, restricted to heave motion
% only, and has PTO damping=1200[kN-s/m].

global plotNO
locdir=pwd;
%% Run Simulation
wecSim;                     % Run Simulation

%% Post-Process Data
% Body 1
B1.WEC_Sim_new.time=output.bodies(1).time;
Hshift1=output.bodies(1).position(1,3);
B1.WEC_Sim_new.heave=output.bodies(1).position(:,3)-Hshift1;
%Body 2
B2.WEC_Sim_new.time=output.bodies(2).time;
Hshift2=output.bodies(2).position(1,3);
B2.WEC_Sim_new.heave=output.bodies(2).position(:,3)-Hshift2;
% Relative Motion
Rel.WEC_Sim_new.time=B1.WEC_Sim_new.time;
Rel.WEC_Sim_new.heave=B1.WEC_Sim_new.heave-B2.WEC_Sim_new.heave;
% Spectrum
Sp.WEC_Sim_new.m0 = calcSpectralMoment(waves.omega,waves.spectrum,0);
Sp.WEC_Sim_new.m2 = calcSpectralMoment(waves.omega,waves.spectrum,2);

%% Load Data
irrCICouput_new=output;        % Keeps the new run in the workspace
load('irregularCIC_org.mat')    % Load Previous WEC-Sim Data

%% Post-Process Data
% Body 1
B1.WEC_Sim_org.time=output.bodies(1).time;
Hshift1=output.bodies(1).position(1,3);
B1.WEC_Sim_org.heave=output.bodies(1).position(:,3)-Hshift1;
%Body 2
B2.WEC_Sim_org.time=output.bodies(2).time;
Hshift2=output.bodies(2).position(1,3);
B2.WEC_Sim_org.heave=output.bodies(2).position(:,3)-Hshift2;
% Relative Motion
Rel.WEC_Sim_org.time=B1.WEC_Sim_org.time;
Rel.WEC_Sim_org.heave=B1.WEC_Sim_org.heave-B2.WEC_Sim_org.heave;
% Spectrum
Sp.WEC_Sim_org.m0 = calcSpectralMoment(waves.omega,waves.spectrum,0);
Sp.WEC_Sim_org.m2 = calcSpectralMoment(waves.omega,waves.spectrum,2);

clear Hshift1 Hshift2

%% Quantify Maximum Difference Between Saved and Current WEC-Sim Runs
[irregularCIC.B1_H_max ,irregularCIC.B1_H_I]=max(abs(B1.WEC_Sim_org.heave-B1.WEC_Sim_new.heave));
[irregularCIC.B2_H_max ,irregularCIC.B2_H_I]=max(abs(B2.WEC_Sim_org.heave-B2.WEC_Sim_new.heave));
[irregularCIC.Rel_H_max,irregularCIC.Rel_H_I]=max(abs(Rel.WEC_Sim_org.heave-Rel.WEC_Sim_new.heave));

irregularCIC.B1  = B1;
irregularCIC.B2  = B2;
irregularCIC.Rel = Rel;
irregularCIC.Sp  = Sp;

save('irregularCIC','irregularCIC')

%% Plot Old vs. New Comparison
if plotNO==1 % global variable
    cd ../..
    plotOldNew(B1,B2,Rel,[irregularCIC.B1_H_max ,irregularCIC.B1_H_I],...
        [irregularCIC.B2_H_max ,irregularCIC.B2_H_I],...
        [irregularCIC.Rel_H_max,irregularCIC.Rel_H_I],'IrregularCIC');
    cd(locdir)
end
%% Clear output and .slx directory

try
	rmdir('output','s')
	rmdir('slprj','s')
	delete('RM3.slx.autosave', 'RM3_sfun.mexmaci64')
catch
end


function img_pad=ImgPad(img_in, pad_size, op_type, varargin)
%Perform matrix border padding and the corresponding inverse transform
% Input: mat_in - the input matrix
%             pad_size - the size of padding
%             op_type - the operation type (0:padding, 1: recovering)
%             varargin: the padding method when op_type=0
%Output: mat_out - result of the operation
% 2016-10-19 jlfeng
[nr,nc]=size(img_in);
pad_size_half=ceil(pad_size/2);
if (0==op_type)
    switch(varargin{1})
        case 0
            pad_type='symmetric';
        case 1
            pad_type='replicate';
        case 2
            pad_type='replicate';
    end
    img_pad=padarray(img_in,[pad_size_half,pad_size_half],pad_type,'both');
elseif (1==op_type)
    img_pad=img_in(pad_size_half+1:nr-pad_size_half,pad_size_half+1:nc-pad_size_half);
else
    error('Unknown operation type.');
end


function test_tutorial_plotting

% WALLTIME 00:15:00
% MEM 4gb
% DEPENDENCY ft_multiplotER ft_singleplotER ft_topoplotER ft_singleplotTFR ft_multiplotTRF ft_megplanar ft_combineplanar ft_volumereslice

% this tutorial reflects the plotting tutorial up to March 2017
% around that time we did a data visualization workshop at the donders for which I created an updated tutorial

% see http://www.fieldtriptoolbox.org/tutorial/plotting
% this testscript corresponds to the version on the wiki at 23 December 2012

% use the tutorial dataset from home/common

load(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/plotting/avgFC.mat'));
load(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/plotting/GA_FC.mat'));
load(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/plotting/TFRhann.mat'));
load(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/plotting/statERF.mat'));
load(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/plotting/statTFR.mat'));
load(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/plotting/sourceDiff.mat'));

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

%%%%%%%%% Singleplot Functions %%%%%%%%%
% ft_singleplotER
cfg = [];
cfg.xlim = [-0.2 1.0];
cfg.ylim = [-1e-13 3e-13];
cfg.channel = 'MLC24';
clf;
ft_singleplotER(cfg,avgFC);

% MATLAB toolbox alternative of ft_singleplotER
selected_data = avgFC.avg(9,241:601); %MLC24 is the 9th channel, -0.2 to 1.0 is sample 241 to 601
time = avgFC.time(241:601);
figure;
plot(time, selected_data)
xlim([-0.2 1.0])
ylim([-1e-13 3e-13])

% ft_singleplotTFR
cfg = [];
cfg.baseline = [-0.5 -0.1];
cfg.baselinetype = 'absolute';
cfg.zlim = [-1.5e-27 1.5e-27];
cfg.channel       = 'MLC*';
cfg.renderer      = 'painters'; % might be needed if colorbar does not print properly
figure;ft_singleplotTFR(cfg, TFRhann); colorbar;

cfg.channel       = 'MRC*';
figure;ft_singleplotTFR(cfg, TFRhann); colorbar;

%%%%%%%%% Topoplot Functions %%%%%%%%%
cfg = [];
cfg.xlim = [0.3 0.5];
cfg.zlim = [0 6e-14];
cfg.layout = 'CTF151.lay';
cfg.parameter = 'individual'; % the default (avg) is not present
figure; ft_topoplotER(cfg,GA_FC); colorbar;

cfg = [];
cfg.xlim = [0.9 1.3];
cfg.ylim = [15 20];
cfg.zlim = [-1e-27 1e-27];
cfg.baseline = [-0.5 -0.1];
cfg.baselinetype = 'absolute';
cfg.layout = 'CTF151.lay';
figure; ft_topoplotTFR(cfg,TFRhann)

% multiple topoplots in one figure
cfg.xlim = -0.4:0.2:1.4;
cfg.comment = 'xlim';
cfg.commentpos = 'title';
figure; ft_topoplotTFR(cfg,TFRhann)

% data selection options prior to calling topoplot
% not specific to topoplot
cfg = [];
cfg.xlim = [0.9 1.3];
cfg.ylim = [15 20];
cfg.zlim = [-1e-27 1e-27];
cfg.baseline = [-0.5 -0.1];
cfg.baselinetype = 'absolute';
cfg.layout = 'CTF151.lay';

% specific to topoplot - option 1 (regular colours)
cfg.gridscale = 300;
cfg.style = 'straight';
cfg.marker = 'labels';
figure; ft_topoplotTFR(cfg,TFRhann)

% specific to topoplot - option 2 (gray scale)
cfg.gridscale = 300;
cfg.contournum = 10;
cfg.colormap = gray(10);
figure; ft_topoplotTFR(cfg,TFRhann)

% specific to topoplot - option 3 (spring colormap)
cfg.gridscale = 300;
cfg.contournum = 4;
cfg.colormap = spring(4);
cfg.markersymbol = '.';
cfg.markersize = 12;
cfg.markercolor = [0 0.69 0.94];
figure; ft_topoplotTFR(cfg,TFRhann)

%%%%%%%%% Plotting with interactive mode / multiplots  %%%%%%%%%

cfg = [];
cfg.baseline = [-0.5 -0.1];
cfg.zlim = [-3e-27 3e-27];
cfg.baselinetype = 'absolute';
cfg.layout = 'CTF151.lay';
cfg.interactive = 'yes';
figure; ft_multiplotTFR(cfg,TFRhann)

cfg = [];
cfg.xlim = [-0.2 1.0];
cfg.ylim = [-1e-13 3e-13];
cfg.layout = 'CTF151.lay';
cfg.interactive = 'yes';
figure; ft_multiplotER(cfg,avgFC);

%%%%%%%%% Connectivity plots  %%%%%%%%%

cfg = [];
cfg.covariance = 'yes';
tmp1 = ft_timelockanalysis(cfg, avgFC);

cfg = [];
cfg.method = 'corr';
tmp2 = ft_connectivityanalysis(cfg, tmp1);

cohFC      = tmp2;
cohFC.coh  = tmp2.corr;
cohFC.freq = 1;
cohFC = rmfield(cohFC, 'coh');

cfg = [];
cfg.foi = 1;
cfg.layout = 'CTF151.lay';
figure; ft_topoplotCC(cfg, cohFC);

%%%%%%%%% Cluster plots  %%%%%%%%%

% timelocked data
cfg = [];
cfg.zlim = [-6 6]; %Tvalues
cfg.alpha = 0.05;
cfg.layout = 'CTF151.lay';
figure; ft_clusterplot(cfg,statERF);

% freq data
cfg = [];
cfg.zlim = [-5 5];
cfg.alpha = 0.05;
cfg.layout = 'CTF151.lay';
ft_clusterplot(cfg,statTFR);

%%%%%%%% beamforming plotting  %%%%%%%

% (1) multiple axial slices

%% load MRI and interpolate functional source data to MRI
mri = ft_read_mri(dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/plotting/Subject01.mri'));
mri = ft_volumereslice([], mri);

cfg            = [];
cfg.downsample = 2;
cfg.parameter  = 'pow';
sourceDiffInt  = ft_sourceinterpolate(cfg, sourceDiff , mri);

%% plot multiple 2D axial slices
cfg = [];
cfg.method        = 'slice';
cfg.funparameter  = 'pow';
cfg.maskparameter = cfg.funparameter;
cfg.funcolorlim   = [0.0 1.2];
cfg.opacitylim    = [0.0 1.2];
cfg.opacitymap    = 'rampup';
ft_sourceplot(cfg, sourceDiffInt);

%% (2) ortho plot
% volume normalise
cfg = [];
cfg.coordsys      = 'ctf';
cfg.nonlinear     = 'no';
sourceDiffIntNorm = ft_volumenormalise(cfg, sourceDiffInt);

% plot ortho
cfg = [];
cfg.method        = 'ortho';
cfg.funparameter  = 'pow';
cfg.maskparameter = cfg.funparameter;
cfg.funcolorlim   = [0.0 1.2];
cfg.opacitylim    = [0.0 1.2];
cfg.opacitymap    = 'rampup';
figure; ft_sourceplot(cfg, sourceDiffIntNorm);

%% (3) MNI surface
cfg = [];
cfg.method         = 'surface';
cfg.funparameter   = 'pow';
cfg.maskparameter  = cfg.funparameter;
cfg.funcolorlim    = [0.0 1.2];
cfg.funcolormap    = 'jet';
cfg.opacitylim     = [0.0 1.2];
cfg.opacitymap     = 'rampup';
cfg.projmethod     = 'nearest';
cfg.surffile      = 'surface_white_both.mat';
cfg.surfdownsample = 10;
ft_sourceplot(cfg, sourceDiffIntNorm);
view ([90 0])


function [img, newInds] = rotateStack90(img, axis, varargin)
%ROTATESTACK90 Rotate a 3D image by 90 degrees around one image axis
%
%   RES = rotateStack90(IMG, AXIS);
%   IMG is a 3D image (either gray scale or color), and AXIS is the axis
%   number, in matrix convention: 1-> y axis, 2->x-axis, 3->z-axis.
%   AXIS can also be specified as letter: 'x', 'y' or 'z'.
%
%   RES = rotateStack90(IMG, AXIS, NUMBER);
%   Apply NUMBER rotation around the axis. NUMBER is the number of
%   rotations to apply, between 1 and 3. NUMER can also be negative, in
%   this case the rotation is performed in reverse direction.
%
%   [RES INDS] = rotateStack90(...);
%   Returns also informations about rotation.
%
%
%   Example
%   img = discreteBall(1:90, 1:100, 1:110, [50 50 50 30 20 10]);
%   img2 = rotateStack90(img, 'x');
%   figure(1); clf;
%   subplot(121); imshow(rot90(img(:,:,50)));
%   title('rotated slice');
%   subplot(122); imshow(squeeze(img2(50,:,:)));
%   title('slice of rotated image');
%
%   See also
%   imStacks, stackRotate90
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2010-05-18,    using Matlab 7.9.0.529 (R2009b)
% http://www.pfl-cepia.inra.fr/index.php?page=slicer
% Copyright 2010 INRA - Cepia Software Platform.

% parse axis, and check bounds
axis = parseAxisIndex_ijk(axis);

% positive or negative rotation
n = 1;
if ~isempty(varargin)
    n = varargin{1};
end

% ensure n is between 0 (no rotation) and 3 (rotation in inverse direction)
n = mod(mod(n, 4) + 4, 4);

% convert between 1 and 4
if n==0
    n = 4;
end

% all permutations: row for axis (ijk ordering), column for number of
% rotations, from 1 to 4
% permDimParams = {...
%     [2 3], [], [2 3]; ...
%     [1 3], [], [1 3]; ...
%     [1 2], [], [1 2] };
permDimParams = {...
    [1 3 2], [1 2 3], [1 3 2], [1 2 3]; ...
    [3 2 1], [1 2 3], [3 2 1], [1 2 3]; ...
    [2 1 3], [1 2 3], [2 1 3], [1 2 3] };

% all axis flipping: row for axis (ijk ordering), column for number of
% rotations, from 1 to 4
flipDimParams = {...
    3, [2 3], 2, []; ...
    1, [1 3], 3, []; ...
    2, [1 2], 1, [] } ;

newIndParams = {...
    [3 2 1], [1 2 3], [3 2 1], [1 2 3]; ...
    [1 3 2], [1 2 3], [1 3 2], [1 2 3]; ...
    [2 1 3], [1 2 3], [2 1 3], [1 2 3]};

% compute rotation params in ijk ordering
permInds = permDimParams{axis, n};
flipInds = flipDimParams{axis, n};
newInds  = newIndParams{axis, n};

% in case of a color image, need to adapt indices
if length(size(img))>3
    % convert index 3 to index 4
    permInds(permInds==3) = 4;
    % insert color index into indices array
    permInds = [permInds(1:2) 3 permInds(3)];

    % convert indices of dimensions to permute
    flipInds(flipInds==3) = 4;
end

% apply matrix dimension permutation
img = permute(img, permInds);

% depending on rotation, some dimensions must be fliped
for i=1:length(flipInds)
    img = flip(img, flipInds(i));
end


% Script file to find parameters for simplified valve actuator model
% Copyright 2010 MathWorks, Inc.

% This script file invokes optimization process to find out a suitable
% approximation to the characteristic of the 2-Position Valve Actuator with
% a simple, Simulink-based model of the actuator

% Required characteristics
t_on = 0.2;         % [s]
stroke = 0.005;     % [m]
gain = stroke/12;   % 12 is a command signal

% Two actuator parameters, time constant and delay time are determined
% during optimization

% Set initial values for variable parameters
x0 = [0.1 0.2/3];

% Perform optimization
[x,fval,exitflag,output] = ...
    fminsearch(@obj_find_simple_valve_driver_param,x0, ...
    optimset('Tolx',1e-6,'Display','iter'));


report_this_filefun(mfilename('fullpath'));

% drap a colormap onto topography
l = isnan(tmap);
tmap(l) = 1;

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

[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-20;

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

exfig=figure_exists('Mcomp worldmap',0);
if exfig==0
    ui=figure_w_normalized_uicontrolunits( 'Name','Mcomp worldmap',...
        'NumberTitle','off');
    figure_w_normalized_uicontrolunits(ui)
end

clf
hold on; axis off
axesm('MapProjection','robinson')

%axesm('MapProjection','eqacylin','MapParallels',[],...
%   'MapLatLimit',[s4_south s3_north],'MapLonLimit',[s2_west s1_east])

ll = tmap < 0 & ren < 0;
ren(ll) = ren(ll)*0 + 20;
meshm(ren,tmapleg,size(tmap),tmap);

daspectm('m',30);
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);

% pl = plotm(ma(:,2),ma(:,1),'hw');
%  set(pl,'LineWidth',1.5,'MarkerSize',12,...
% 'MarkerFaceColor','w','MarkerEdgeColor','k')
%load coast.mat
%c = coast;
% plotm(c(:,1), c(:,2),'k','Linewidth',1);
% 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.9 0.9 0.9 ] ; j];
j = [ [ 0.9 0.9 0.9 ] ; j; [ 0.5 0.5 0.5] ];
%j = [ [ 0.9 0.9 0.9 ] ; j ];

caxis([ min(min(re4)) max(max(re4)) ]);
caxis([3.98 5.2])
colormap(j); brighten(0.1);

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

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

setm(gca,'mlabellocation',60)
setm(gca,'meridianlabel','on')
setm(gca,'plabellocation',15)
setm(gca,'parallellabel','on')
setm(gca,'Fontcolor','w','FontSize',7,'Fontweight','bold','Labelunits','degrees')
setm(gca,'Labelformat','none')
setm(gca,'Grid','on')
setm(gca,'GLineStyle','-')

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


function [net, info] = cnn_mnist(varargin)
%CNN_MNIST  Demonstrates MatConvNet on MNIST

run(fullfile(fileparts(mfilename('fullpath')),...
  '..', '..', 'matlab', 'vl_setupnn.m')) ;

opts.batchNormalization = false ;
opts.networkType = 'simplenn' ;
[opts, varargin] = vl_argparse(opts, varargin) ;

sfx = opts.networkType ;
if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end
opts.expDir = fullfile(vl_rootnn, 'data', ['mnist-baseline-' sfx]) ;
[opts, varargin] = vl_argparse(opts, varargin) ;

opts.dataDir = fullfile(vl_rootnn, 'data', 'mnist') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = [2]; end;

% --------------------------------------------------------------------
%                                                         Prepare data
% --------------------------------------------------------------------

net = cnn_mnist_init('batchNormalization', opts.batchNormalization, ...
                     'networkType', opts.networkType) ;

if exist(opts.imdbPath, 'file')
  imdb = load(opts.imdbPath) ;
else
  imdb = getMnistImdb(opts) ;
  mkdir(opts.expDir) ;
  save(opts.imdbPath, '-struct', 'imdb') ;
end

net.meta.classes.name = arrayfun(@(x)sprintf('%d',x),1:10,'UniformOutput',false) ;

% --------------------------------------------------------------------
%                                                                Train
% --------------------------------------------------------------------

switch opts.networkType
  case 'simplenn', trainfn = @cnn_train ;
  case 'dagnn', trainfn = @cnn_train_dag ;
end

[net, info] = cnn_train_binary(net, imdb, getBatch(opts), ...
  'expDir', opts.expDir, ...
  net.meta.trainOpts, ...
  opts.train, ...
  'val', find(imdb.images.set == 3)) ;

% --------------------------------------------------------------------
function fn = getBatch(opts)
% --------------------------------------------------------------------
switch lower(opts.networkType)
  case 'simplenn'
    fn = @(x,y) getSimpleNNBatch(x,y) ;
  case 'dagnn'
    bopts = struct('numGpus', numel(opts.train.gpus)) ;
    fn = @(x,y) getDagNNBatch(bopts,x,y) ;
end

% --------------------------------------------------------------------
function [images, labels] = getSimpleNNBatch(imdb, batch)
% --------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;

% --------------------------------------------------------------------
function inputs = getDagNNBatch(opts, imdb, batch)
% --------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if opts.numGpus > 0
  images = gpuArray(images) ;
end
inputs = {'input', images, 'label', labels} ;

% --------------------------------------------------------------------
function imdb = getMnistImdb(opts)
% --------------------------------------------------------------------
% Preapre the imdb structure, returns image data with mean image subtracted
files = {'train-images-idx3-ubyte', ...
         'train-labels-idx1-ubyte', ...
         't10k-images-idx3-ubyte', ...
         't10k-labels-idx1-ubyte'} ;

if ~exist(opts.dataDir, 'dir')
  mkdir(opts.dataDir) ;
end

for i=1:4
  if ~exist(fullfile(opts.dataDir, files{i}), 'file')
    url = sprintf('http://yann.lecun.com/exdb/mnist/%s.gz',files{i}) ;
    fprintf('downloading %s\n', url) ;
    gunzip(url, opts.dataDir) ;
  end
end

f=fopen(fullfile(opts.dataDir, 'train-images-idx3-ubyte'),'r') ;
x1=fread(f,inf,'uint8');
fclose(f) ;
x1=permute(reshape(x1(17:end),28,28,60e3),[2 1 3]) ;

f=fopen(fullfile(opts.dataDir, 't10k-images-idx3-ubyte'),'r') ;
x2=fread(f,inf,'uint8');
fclose(f) ;
x2=permute(reshape(x2(17:end),28,28,10e3),[2 1 3]) ;

f=fopen(fullfile(opts.dataDir, 'train-labels-idx1-ubyte'),'r') ;
y1=fread(f,inf,'uint8');
fclose(f) ;
y1=double(y1(9:end)')+1 ;

f=fopen(fullfile(opts.dataDir, 't10k-labels-idx1-ubyte'),'r') ;
y2=fread(f,inf,'uint8');
fclose(f) ;
y2=double(y2(9:end)')+1 ;

set = [ones(1,numel(y1)) 3*ones(1,numel(y2))];
data = single(reshape(cat(3, x1, x2),28,28,1,[]));
dataMean = mean(data(:,:,:,set == 1), 4);
data = bsxfun(@minus, data, dataMean) ;

imdb.images.data = data ;
imdb.images.data_mean = dataMean;
imdb.images.labels = cat(2, y1, y2) ;
imdb.images.set = set ;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;


function [poolfeat] = filelist_feature(dataset_name, filelist, feature, c)
%
% Copyright Aditya Khosla http://mit.edu/khosla
%
% Please cite this paper if you use this code in your publication:
%   A. Khosla, J. Xiao, A. Torralba, A. Oliva
%   Memorability of Image Regions
%   Advances in Neural Information Processing Systems (NIPS) 2012
%

if(~isempty(dataset_name) && c.common_dictionary==0)
    c.cache=[c.cache '/' dataset_name '/'];
end

p = c.feature_config.(feature);
if(~isfield(p, 'dictionary'))
    c.feature_config.(feature).dictionary = build_dictionary(filelist, feature, c);
end

if(isempty(c.feature_config.(feature).dictionary))
    % Feature does not require LLC encoding + max pooling
    poolfeat = cell(length(filelist), 1);
    parfor i=1:length(filelist)
        img = imgread(filelist{i}, p);
        poolfeat{i} = extract_feature(feature, img, c);
    end
    poolfeat=cell2mat(poolfeat);
else
    % Feature requires LLC encoding + max pooling
    llcfeat = cell(length(filelist), 1);
    info = cell(length(filelist), 1);
    parfor i=1:length(filelist)
        img = imgread(filelist{i}, p);
        [llcfeat{i}, x, y, wid, hgt] = llc_feature(feature, img, c);
        info{i}.x = x; info{i}.y = y; info{i}.wid = wid; info{i}.hgt = hgt;
    end
    poolfeat = max_pooling(llcfeat, info, c.pool_region, p.pyramid_levels);
end

poolfeat = cast(poolfeat, c.precision);


classdef C10MOP8 < EvoXBenchProblem
% <multi> <real> <large/none> <expensive/none>

%------------------------------- Reference --------------------------------
% Z. Lu, R. Cheng, Y. Jin, K. C. Tan, and K. Deb, Neural architecture
% search as multiobjective optimization benchmarks: Problem formulation and
% performance assessment, IEEE Transactions on Evolutionary Computation,
% 2023.
%--------------------------------------------------------------------------

    methods
        %% Default settings of the problem
        function Setting(obj)
            config.name = 'darts';
            config.args.objs = 'err&params';
            config.args.normalized_objectives = false;
            obj.Setting@EvoXBenchProblem(config);
        end
    end
end


function test_ft_sourcewrite

% WALLTIME 00:10:00
% MEM 2gb
% DEPENDENCY ft_sourcewrite

gridsize = 38*48*41;
nsamples = 20;
source = [];
source.dim = [38,48,41];
source.pos = randn(gridsize,3);
source.time = 1:nsamples;
source.pow = randn(gridsize,nsamples);
source.inside = 1:gridsize;

cfg = [];
cfg.parameter = 'pow';
cfg.filename = tempname;
cfg.filetype = 'nifti';
ft_sourcewrite(cfg, source)
delete([cfg.filename '.nii'])


function h = rdivide(f, g, pref)
%./   Pointwise CHEBFUN right divide.
%   F./G returns a CHEBFUN that represents the function F(x)/G(x).
%   If F and G are array-valued column (row) CHEBFUNs, they must have the same
%   number of columns (rows).
%
% See also MRDIVIDE, TIMES.

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

% Trivial empty case:
if ( isempty(f) || isempty(g) )
    h = chebfun();
    return
end

% Trivial zero numerator case:
if ( isnumeric(f) && ~any(f) )
    h = 0*g;
    return
end

if ( nargin < 3 )
    pref = chebfunpref();
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CHEBFUN ./ CHEBFUN %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ( isa(f,'chebfun') && isa(g, 'chebfun') )

    % Check the number of columns match:
    if ( numColumns(f) ~= numColumns(g) )
        if ( numColumns(f) == 1 )
            h = g;
            for k = 1:numColumns(g)
                h(k) = rdivide(f, g(k));
            end
        elseif ( numColumns(g) == 1 )
            h = f;
            for k = 1:numColumns(f)
                h(k) = rdivide(f(k), g);
            end
        else
            error('CHEBFUN:CHEBFUN:rdivide:quasi', ...
                'Chebfun quasimatrix dimensions must agree.')
        end
        return
    end

    if ( numel(f) == 1 && numel(g) == 1 )
        % CHEBFUN case :

        % If one of the two CHEBFUNs uses a PERIODICTECH reprensetation,
        % cast it to a NONPERIODICTECH.
        if ( ~isPeriodicTech(f.funs{1}) && isPeriodicTech(g.funs{1}) )
            g = chebfun(g, g.domain, 'tech', get(f.funs{1}, 'tech'));
        elseif ( isPeriodicTech(f.funs{1}) && ~isPeriodicTech(g.funs{1}) )
            f = chebfun(f, f.domain, 'tech', get(g.funs{1}, 'tech'));
        end

        % Array-valued CHEBFUN case:
        h = columnRdivide(f, g, pref);
    else
        % QUASIMATRIX case:

        % Convert to a cell array:
        f = mat2cell(f);
        g = mat2cell(g);
        % Loop over the columns:
        for k = numel(f):-1:1
            h(k) = columnRdivide(f{k}, g{k}, pref);
        end
    end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CHEBFUN ./ constant %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif ( isa(f, 'chebfun') )

    numColsF = numColumns(f);
    numelF = numel(f);
    numelG = numel(g);

    % Different cases:
    if ( numColsF == 1 )
        % e.g., x./[1 2 3]
        h = columnRdivide(f, g, pref);
    elseif ( numelG == 1 )
        % e.g., [x sin(x)]./2
        for k = numelF:-1:1
            h(k) = columnRdivide(f(k), g, pref);
        end
    elseif ( numelG == numColsF )
        % e.g., [x sin(x) exp(x)]./[1 2 3]
        if ( numel(f) == 1 )
            h = columnRdivide(f, g, pref);
        else
            f = mat2cell(f);
            for k = numColsF:-1:1
                h(k) = columnRdivide(f{k}, g(k), pref);
            end
        end
    else
        error('CHEBFUN:CHEBFUN:rdivide:dim', ...
            'Chebfun quasimatrix dimensions must agree.');
    end

%%%%%%%%%%%%%%%%%%%%%%%%%%%% constant ./ CHEBFUN %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
else

    numColsG = numColumns(g);
    numelF = numel(f);
    numelG = numel(g);

    % Different cases:
    if ( numColsG == 1 )
        % e.g., [1 2 3]./(2+x)
        for k = numelF:-1:1
            h(k) = columnRdivide(f(k), g, pref);
        end
        h = quasi2cheb(h);
    elseif ( numelF == 1 )
        % e.g., 2./(2+[x x abs(x)])
        g = mat2cell(g);
        for k = numColsG:-1:1
            h(k) = columnRdivide(f, g{k}, pref);
        end
        try h = quasi2cheb(h); catch, end
    elseif ( numelF == numColsG )
        % e.g., [1 2]./(2+[x sin(x)])
        g = mat2cell(g);
        for k = numColsG:-1:1
            h(k) = columnRdivide(f(k), g{k}, pref);
        end
        try h = quasi2cheb(h); catch, end
    else
        error('CHEBFUN:CHEBFUN:rdivide:dim', ...
            'Chebfun quasimatrix dimensions must agree.');
    end

end

end

function h = columnRdivide(f, g, pref)

% If g is numeric then call TIMES():
if ( isnumeric(g) )
    if ( any(g == 0) )
        % note g could be a vector, with some zero components
        % TODO:  Return identically Inf/NaN CHEBFUN instead?
        error('CHEBFUN:CHEBFUN:rdivide:columnRdivide:divisionByZero', ...
            'Division by zero.')
    end
    h = f.*(1./g);
    return
end

% Check for zero FUNs:
for k = 1:numel(g.funs)
    if ( iszero(g.funs{k}) )
        % TODO:  Return CHEBFUN with identically Inf/NaN FUN instead?
        error('CHEBFUN:CHEBFUN:rdivide:columnRdivide:divisionByZeroChebfun', ...
            'Division by CHEBFUN with identically zero FUN.');
    end
end

% Add breaks at the roots of g:
g = addBreaksAtRoots(g, pref);

if ( isa(f, 'chebfun') )

    % Check that the domains are the same:
    if ( ~domainCheck(f, g) )
        error('CHEBFUN:CHEBFUN:rdivide:columnRdivide:domain', ...
            'Inconsistent domains.');
    end

    % Check that the orientation is the same:
    if ( xor(f.isTransposed, g.isTransposed) )
        error('CHEBFUN:CHEBFUN:rdivide:columnRdivide:dim', ...
            'Matrix dimension do not agree (transposed)');
    end

    % Introduce matching breakpoints in f and g:
    [f, g] = overlap(f, g);

    % Copy g to h in preparation for output:
    h = g;

    % Loop over the FUNS:
    for k = 1:numel(g.funs)
        h.funs{k} = rdivide(f.funs{k}, g.funs{k});
    end

    % Divide the pointValues:
    h.pointValues = f.pointValues./g.pointValues;

    % Avoid NaN or Inf from divide by zero where possible:
    hpv = h.pointValues; fpv = f.pointValues; gpv = g.pointValues;
    idx = (isnan(hpv) & ~(isnan(fpv) | isnan(gpv))) | ...
        (isinf(hpv) & (abs(fpv) < 100*chebfuneps*vscale(f)));
    if ( any(idx) )
        pvavg = (feval(h, h.domain, 'left') + feval(h, h.domain, 'right'))/2;
        h.pointValues(idx) = pvavg(idx);
    end

else

    % Copy g to h in preparation for output:
    h = g;

    % Loop over the FUNS:
    for k = 1:numel(g.funs)
        h.funs{k} = rdivide(f, g.funs{k});
    end

    % Divide the pointValues:
    h.pointValues = f./g.pointValues;

end

end


function varargout = process_test_parametric2p( varargin )
% PROCESS_TEST_PARAMETRIC2P: Parametric two-sample tests (dependent=paired).

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

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Parametric test: Paired';
    sProcess.Category    = 'Stat2';
    sProcess.SubGroup    = 'Test';
    sProcess.Index       = 102;
    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Statistics';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'data',  'results',  'timefreq',  'matrix'};
    sProcess.OutputTypes = {'pdata', 'presults', 'ptimefreq', 'pmatrix'};
    sProcess.nInputs     = 2;
    sProcess.nMinFiles   = 2;
    sProcess.isPaired    = 1;
    sProcess.isSeparator = 1;

    % === GENERIC EXTRACT OPTIONS
    % Label
    sProcess.options.extract_title.Comment    = 'Select data to test:';
    sProcess.options.extract_title.Type       = 'label';
    % Options
    sProcess = process_extract_values('DefineExtractOptions', sProcess);
    % DISABLE ABSOLUTE VALUE
    sProcess.options.isabs.Value = 0;
    sProcess.options.isnorm.Value = 0;
    sProcess.options.isabs.Hidden = 1;
    sProcess.options.isnorm.Hidden = 1;

    % === OUTPUT COMMENT
    sProcess.options.Comment.Comment = 'Comment (empty=default): ';
    sProcess.options.Comment.Type    = 'text';
    sProcess.options.Comment.Value   = '';

    % === TEST: title
    sProcess.options.test_title.Comment    = '
Test statistic:';
    sProcess.options.test_title.Type       = 'label';
    % === TEST: type
    sProcess.options.test_type.Comment = {['Paired Student''s t-test        (A-B)~N(m,v)
' ...
                                           't = mean(A-B) / std(A-B) * sqrt(n)      df=n-1']; ...
                                          'ttest_paired'};
    sProcess.options.test_type.Type    = 'radio_label';
    sProcess.options.test_type.Value   = 'ttest_paired';
    % === TAIL FOR THE TEST STATISTIC
    sProcess.options.tail.Comment  = {'One-tailed (-)', 'Two-tailed', 'One-tailed (+)', ''; ...
                                      'one-', 'two', 'one+', ''};
    sProcess.options.tail.Type     = 'radio_linelabel';
    sProcess.options.tail.Value    = 'two';
end

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

%% ===== RUN =====
function sOutput = Run(sProcess, sInputsA, sInputsB) %#ok<DEFNU>
    sOutput = process_test_parametric2('Run', sProcess, sInputsA, sInputsB);
end


function colornames_deltaE(palette,rgb)
% Create a figure comparing the color difference (deltaE) calculations used in COLORNAMES.
%
% (c) 2014-2019 Stephen Cobeldick
%
%%% Syntax:
%  colornames_deltaE(palette,rgb)
%
% Creates a figure showing the supplied colormap as horizontal color bands,
% overlaid with columns of the closest named colors from the selected
% palette. Each column shows one color difference (deltaE) calculation.
%
% Note: Requires the function COLORNAMES and its associated MAT file (FEX 48155).
%
% For more information on color difference concepts and formulae:
% https://en.wikipedia.org/wiki/Color_difference
% http://www.colorwiki.com/wiki/Delta_E:_The_Color_Difference
%
%% Examples %%
%
% colornames_deltaE('html4',jet(18))
%
% colornames_deltaE('x11',summer(18))
%
% colornames_deltaE('matlab',jet(18))
%
%% Input and Output Arguments %%
%
%%% Inputs (all inputs are optional):
% palette = CharRowVector, the name of a palette supported by COLORNAMES.
% rgb     = Numeric Array, size Nx3, each row is an RGB triple (0<=rgb<=1).
%
%%% Outputs:
% none
%
% See also COLORNAMES COLORNAMES_CUBE COLORNAMES_VIEW MAXDISTCOLOR COLORMAP

% Get list of palettes and color difference metrics:
[fnm,~,dtE] = colornames();
%
% Define default values:
if nargin<2
	N = 16;
	map = get(0,'defaultFigureColormap');
	rgb = interp1(linspace(1,N,size(map,1)),map,1:N);
end
if nargin<1
	palette = fnm{1+rem(round(now*1e7),numel(fnm))};
end
%
persistent fgh axh txh
%
% Text lightness threshold:
thr = 0.54;
%
if isempty(fgh)||~ishghandle(fgh)
	fgh = figure('HandleVisibility','callback', 'IntegerHandle','off',...
		'NumberTitle','off', 'Name',mfilename, 'Color','white', 'Toolbar','none');
	axh = axes('Parent',fgh, 'Visible','off', 'XTick',[], 'YTick',[],...
		'Units','normalized', 'Position',[0,0,1,1]);
else
	try %#ok<TRYNC>
		cla(axh)
	end
end
%
assert(ischar(palette)&&isrow(palette),'First input <palette> must be a 1xN char.')
idz = strcmpi(palette,fnm);
assert(any(idz),'Palette ''%s'' is not supported. Call COLORNAMES() to list all palettes.',palette)
set(fgh,'Name',sprintf('%s (palette = ''%s'')',mfilename,fnm{idz}))
%
assert(ismatrix(rgb)&&size(rgb,2)==3&&isreal(rgb)&&all(0<=rgb(:)&rgb(:)<=1),...
	'Second input argument can be a colormap of RGB values (size Nx3).')
colormap(axh,rgb);
%
N = size(rgb,1);
x = [0;0;1;1];
y = [0;1;1;0];
X = repmat(x,1,N);
Y = bsxfun(@plus,y,N-1:-1:0);%0:N-1);
patch(X,Y,1:N, 'Parent',axh, 'EdgeColor','none', 'FaceColor','flat', 'CDataMapping','direct');
%
dEn = numel(dtE);
[cnc,RGB] = cellfun(@(t)colornames(palette,rgb,t),dtE, 'uni',false);
BAW = cellfun(@(c)(c*[0.298936;0.587043;0.114021])<thr,RGB, 'uni',false);
%
tmp = @(s,n) text((2*n-1)*ones(1,N)/(2*dEn), mean(Y.',2), zeros(1,N),...
	s, 'Parent',axh, 'HorizontalAlignment','center');
txh = cellfun(tmp, cnc, num2cell(1:dEn), 'uni',false);
tmp = @(h,c,b) set(h(:), {'BackgroundColor'},num2cell(c,2), {'Color'},num2cell(b(:,[1,1,1]),2));
cellfun(tmp, txh, RGB, BAW)
%
set(axh,'YLim',[0,N+1]);
text((1:2:2*dEn)/(2*dEn), N+ones(1,dEn)/2, zeros(1,dEn), dtE(:),...
	'Parent',axh, 'HorizontalAlignment','center', 'Color','black');
%
drawnow()
%
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%colornames_deltaE


classdef VademecumComputerAndPlotter < handle

    properties (GetAccess = public, SetAccess = private)
        vademecumData
    end

    properties (Access = private)
        fileName
        outPutPath
        vademecumPlotter
        vadVariables
    end

    methods (Access = public)

        function obj = VademecumComputerAndPlotter(d)
            obj.init(d)
        end

        function compute(obj)
            obj.calculateVademecumPlotterData();
            obj.plotVademecum();
            obj.printData();
        end

        function fI = getFeasibleIndex(obj)
            vp = obj.vademecumPlotter;
            fI = vp.feasibleIndex;
        end
    end

    methods (Access = private)

        function init(obj,d)
            obj.fileName   = d.fileName;
            obj.outPutPath = d.outPutPath;
        end

        function calculateVademecumPlotterData(obj)
            obj.calculateVademecumData();
            obj.transformVademecumCellDataInMatrix();
            d = obj.vademecumData;
            d.fileName   = obj.fileName;
            d.outPutPath = obj.outPutPath;
            obj.vademecumData = d;
        end

        function calculateVademecumData(obj)
            d.fileName = obj.fileName;
            d.outPutPath = obj.outPutPath;
            vc = VademecumPinvComputer(d);
            vc.compute();
            obj.vadVariables = vc.vademecumData;
        end

        function transformVademecumCellDataInMatrix(obj)
            mxV = obj.vadVariables.domVariables.mxV;
            myV = obj.vadVariables.domVariables.myV;
            for imx = 1:length(mxV)
                for imy = 1:length(myV)
                    vad = obj.vadVariables.variables{imx,imy};
                    variables.C(:,:,imx,imy)     = vad.Ctensor;
                    variables.invP(:,:,imx,imy)  = vad.Pinvtensor;
                    variables.Ptensor(:,:,imx,imy) = vad.Ptensor;
                    variables.volume(imx,imy)    = vad.volume;
                end
            end
            obj.vademecumData = variables;
            obj.vademecumData.mxV = mxV;
            obj.vademecumData.myV = myV;
        end

        function plotVademecum(obj)
            d = obj.vademecumData;
            obj.vademecumPlotter = VademecumPlotters(d);
            obj.vademecumPlotter.plot();
        end

        function printData(obj)
            d.outPutPath = [obj.outPutPath,obj.fileName];
            d.Ctensor  = obj.vademecumData.C;
            d.Ptensor  = obj.vademecumData.Ptensor;
            d.volume   = obj.vademecumData.volume;
            p = VademecumDataPrinter(d);
           % p.print();
        end

    end

end


function femI = genP1IFEM3D(mesh,fem,btM,btP)
%% Usage: Generate Quadrature Information on Interface Elements
%         Each interface tetrahedron is cut into 4 to 9 small tetrahedra
%
% femI.t --- global index on small tetrahedra
% femI.bas --- nt-4-4 matrix stores basis functions on all small tetra
% femI.gx --- Gaussian x nodes
% femI.gy --- Gaussian y nodes
% femI.gz --- Gaussian z nodes
% femI.gw --- Gaussian weights
% femI.area --- Areas of all small tetra
% femI.quadT --- number of small tetras of each interface element
% femI.locID --- order of local index, to match with the basis function

% ***** The following info only used for partial penalty IFEM *****

% femI.bas1 --- nti-4-4 basis function on 1st piece of interface element
% femI.bas2 --- nti-4-4 basis function on 2nd piece of interface element
% femI.plusPC --- 1 or 2 denotes which piece corresponds to btP.

% Last Modified by Xu Zhang 08/02/2020

%%
ntI = -min(mesh.tLoc);
t = zeros(8*ntI,4); bas = zeros(8*ntI,4,4); A = zeros(8*ntI,1);
gx = zeros(8*ntI,4); gy = zeros(8*ntI,4); gz = zeros(8*ntI,4);
QelemID = zeros(8*ntI,1);
quadT = zeros(ntI,1); locIDvec = zeros(ntI,4);
bas1 = zeros(ntI,4,4); bas2 = zeros(ntI,4,4); plusPC = zeros(ntI,1);
intID = find(mesh.tLoc<0);
id = 0;
for i = 1:ntI
    tID = intID(i);
    t_e = mesh.t_e(tID,:);
    intpt = mesh.eIntP(-mesh.eLoc(t_e(mesh.eLoc(t_e)<0)),:);
    pLocK = mesh.pLoc(mesh.t(tID,:));
    vert0 = mesh.p(mesh.t(tID,:),:);
    if size(intpt,1) == 3 % Type 1 Interface Element (3 intersection pts)
        if pLocK(1) == -1 && pLocK(2) == 1 && pLocK(3) == 1 && pLocK(4) == 1
            locID = [1,2,3,4]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;
        elseif pLocK(1) == 1 && pLocK(2) == -1 && pLocK(3) == 1 && pLocK(4) == 1
            locID = [2,3,4,1]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;
        elseif pLocK(1) == 1 && pLocK(2) == 1 && pLocK(3) == -1 && pLocK(4) == 1
            locID = [3,4,1,2]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;
        elseif pLocK(1) == 1 && pLocK(2) == 1 && pLocK(3) == 1 && pLocK(4) == -1
            locID = [4,1,2,3]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;
        elseif pLocK(1) == 1 && pLocK(2) == -1 && pLocK(3) == -1 && pLocK(4) == -1
            locID = [1,2,3,4]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;
        elseif pLocK(1) == -1 && pLocK(2) == 1 && pLocK(3) == -1 && pLocK(4) == -1
            locID = [2,3,4,1]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;
        elseif pLocK(1) == -1 && pLocK(2) == -1 && pLocK(3) == 1 && pLocK(4) == -1
            locID = [3,4,1,2]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;
        elseif pLocK(1) == -1 && pLocK(2) == -1 && pLocK(3) == -1 && pLocK(4) == 1
            locID = [4,1,2,3]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;
        end
        p1 = [vert(1,:);intpt]; t1 = delaunay(p1);
        p2 = [vert(2:4,:);intpt];t2 = delaunay(p2);
    elseif size(intpt,1) == 4 % Type 2 Interface Element (4 intersection pts)
        if pLocK(1) == -1 && pLocK(2) == -1 && pLocK(3) == 1 && pLocK(4) == 1
            locID = [1,2,3,4]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;
        elseif pLocK(1) == -1 && pLocK(2) == 1 && pLocK(3) == -1 && pLocK(4) == 1
            locID = [1,3,2,4]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;
        elseif pLocK(1) == -1 && pLocK(2) == 1 && pLocK(3) == 1 && pLocK(4) == -1
            locID = [1,4,2,3]; vert = vert0(locID,:); coef = [btM,btP]; plusPC(i) = 2;
        elseif pLocK(1) == 1 && pLocK(2) == -1 && pLocK(3) == -1 && pLocK(4) == 1
            locID = [1,4,2,3]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;
        elseif pLocK(1) == 1 && pLocK(2) == -1 && pLocK(3) == 1 && pLocK(4) == -1
            locID = [1,3,2,4]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;
        elseif pLocK(1) == 1 && pLocK(2) == 1 && pLocK(3) == -1 && pLocK(4) == -1
            locID = [1,2,3,4]; vert = vert0(locID,:); coef = [btP,btM]; plusPC(i) = 1;
        end
        p1 = [vert(1:2,:);intpt]; t1 = delaunay(p1);
        p2 = [vert(3:4,:);intpt]; t2 = delaunay(p2);
    else
        stp = 1;
    end
    [BAS1,BAS2] = basIFE3DP1coef(vert,intpt,coef);
    X1 = p1(t1(:,1),:); X2 = p1(t1(:,2),:); X3 = p1(t1(:,3),:); X4 = p1(t1(:,4),:);
    [gx1, gy1, gz1] = gaussPtetra(X1,X2,X3,X4,fem.ng);
    A1 = tetraArea(X1,X2,X3,X4);

    X1 = p2(t2(:,1),:); X2 = p2(t2(:,2),:); X3 = p2(t2(:,3),:); X4 = p2(t2(:,4),:);
    [gx2, gy2, gz2] = gaussPtetra(X1,X2,X3,X4,fem.ng);
    A2 = tetraArea(X1,X2,X3,X4);

    nt1 = size(t1,1); nt2 = size(t2,1);
    bas(id+1:id+nt1,:,1) = repmat(BAS1(1,:),nt1,1);
    bas(id+1:id+nt1,:,2) = repmat(BAS1(2,:),nt1,1);
    bas(id+1:id+nt1,:,3) = repmat(BAS1(3,:),nt1,1);
    bas(id+1:id+nt1,:,4) = repmat(BAS1(4,:),nt1,1);
    bas(id+nt1+1:id+nt1+nt2,:,1) = repmat(BAS2(1,:),nt2,1);
    bas(id+nt1+1:id+nt1+nt2,:,2) = repmat(BAS2(2,:),nt2,1);
    bas(id+nt1+1:id+nt1+nt2,:,3) = repmat(BAS2(3,:),nt2,1);
    bas(id+nt1+1:id+nt1+nt2,:,4) = repmat(BAS2(4,:),nt2,1);
    gx(id+1:id+nt1+nt2,:) = [gx1;gx2];
    gy(id+1:id+nt1+nt2,:) = [gy1;gy2];
    gz(id+1:id+nt1+nt2,:) = [gz1;gz2];
    A(id+1:id+nt1+nt2,:) = [A1;A2];
    QelemID(id+1:id+nt1+nt2) = tID;

    temp = fem.t(tID,:);
    temp2 = temp(locID);
    t(id+1:id+nt1+nt2,:) = repmat(temp2,nt1+nt2,1);
    locIDvec(i,:) = locID;
    quadT(i) = nt1+nt2;

    bas1(i,:,1) = BAS1(1,:); bas2(i,:,1) = BAS2(1,:);
    bas1(i,:,2) = BAS1(2,:); bas2(i,:,2) = BAS2(2,:);
    bas1(i,:,3) = BAS1(3,:); bas2(i,:,3) = BAS2(3,:);
    bas1(i,:,4) = BAS1(4,:); bas2(i,:,4) = BAS2(4,:);

    id = id+nt1+nt2;
end
t(id+1:end,:) = []; bas(id+1:end,:,:) = []; A(id+1:end) = [];
gx(id+1:end,:) = []; gy(id+1:end,:) = []; gz(id+1:end,:) = [];
QelemID(id+1:end,:) = [];
femI = struct('t',t,'bas',bas,'gx',gx,'gy',gy,'gz',gz,'area',A,'gw',fem.gw,...
    'quadT',quadT,'locID',locIDvec,'bas1',bas1,'bas2',bas2,'plusPC',plusPC,...
    'QelemID',QelemID);


function [It, Ix, Iy] = partial_deriv(images, uv_prev, interpolation_method, deriv_filter, b)

%PARTIAL_DERIV   Spatio-temporal derivatives
%   P = PARTIAL_DERIV(IMAGES, INIT) computes the spatio-temporal derivatives
%
%   Author: Deqing Sun, Department of Computer Science, Brown University
%   Contact: dqsun@cs.brown.edu
%   $Date: 2007-11-30 $
%   $Revision $
%
% Copyright 2007-2010, Brown University, Providence, RI. USA
%
%                          All Rights Reserved
%
% All commercial use of this software, whether direct or indirect, is
% strictly prohibited including, without limitation, incorporation into in
% a commercial product, use in a commercial service, or production of other
% artifacts for commercial purposes.
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for research purposes is hereby granted without fee,
% provided that the above copyright notice appears in all copies and that
% both that copyright notice and this permission notice appear in
% supporting documentation, and that the name of the author and Brown
% University not be used in advertising or publicity pertaining to
% distribution of the software without specific, written prior permission.
%
% For commercial uses contact the Technology Venture Office of Brown University
%
% THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO
% THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
% FITNESS FOR ANY PARTICULAR PURPOSE.  IN NO EVENT SHALL THE AUTHOR OR
% BROWN UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
% DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
% PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
% ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
% THIS SOFTWARE.

if nargin == 2
    interpolation_method = 'cubic';
end;

if nargin == 4
    h = deriv_filter;
else
    h = [1 -8 0 8 -1]/12; % used in Wedel etal "improved TV L1"
end;

if nargin < 5
    b = 0.5;    %blending ratio
end;

H   = size(images, 1);
W   = size(images, 2);

[x,y]   = meshgrid(1:W,1:H);
x2      = x + uv_prev(:,:,1);
y2      = y + uv_prev(:,:,2);

% Record out of boundary pixels
B = (x2>W) | (x2<1) | (y2>H) | (y2<1);

if size(images, 4) ~= 1
    B = repmat(B, [1 1 size(images, 3)]);
end;

if size(images, 4) == 1
    img1 = images(:,:,1);
    img2 = images(:,:,2);
else
    img1 = images(:,:,:,1);
    img2 = images(:,:,:,2);
end;

if strcmp(interpolation_method, 'bi-cubic')

    %h = [-0.5, 0, 0.5]; % consistent with bi-cubic interpolation

    % Bicubic interpolation
    if nargout == 1

        if size(images, 4) == 1
            % gray-level
            warpIm = interp2_bicubic(images(:,:,2),x2,y2, h);
        else
            % color
            warpIm  = zeros(size(images(:,:,:,1)));
            for j = 1:size(images,3)
                warpIm(:,:,j) = interp2_bicubic(images(:,:,j, 2),x2,y2, h);
            end;
        end;

    elseif nargout == 3

        if size(images, 4) == 1
            % gray-level
            [warpIm Ix Iy] = interp2_bicubic(images(:,:,2),x2,y2, h);
        else
            % color
            warpIm  = zeros(size(images(:,:,:,1)));
            Ix      = warpIm;
            Iy      = warpIm;
            for j = 1:size(images,3)
                [warpIm(:,:,j) Ix(:,:,j) Iy(:,:,j)] = interp2_bicubic(images(:,:,j,2),x2,y2, h);
            end;
        end;

    else
        error('partial_deriv: number of output wrong!');
    end;

    indx        = isnan(warpIm);
    if size(images, 4) == 1
        It          = warpIm - images(:,:,1);
    else
        It          = warpIm - images(:,:,:,1);
    end;

    % Disable those out-of-boundary pixels in warping
    It(indx)    = 0;
    if nargout == 3

        % Temporal average
        I1x = imfilter(img1, h,  'corr', 'symmetric', 'same');  %
        I1y = imfilter(img1, h', 'corr', 'symmetric', 'same');

        % b = 0.6;    % recommended in Wedal etal "improved TV-L1" 2008
        % b = 0.5;
%         b = 1;

        Ix  = b*Ix+(1-b)*I1x;
        Iy  = b*Iy+(1-b)*I1y;

        Ix(indx) = 0;
        Iy(indx) = 0;
    end;

elseif strcmp(interpolation_method, 'bi-linear') || strcmp(interpolation_method, 'cubic')

    if strcmp(interpolation_method, 'bi-linear')
        method = 'linear';
    else
        method = 'cubic';
    end;

    % Matlab built-in
    if size(images, 4) == 1
        % Gray-level
        warpIm  = interp2(x,y,images(:,:,2),x2,y2,method);
        It      = warpIm - images(:,:,1);

    else
        % Color
        warpIm  = zeros(size(images(:,:,:,1)));
        for j = 1:size(images,3)
            warpIm(:,:,j) = interp2(x,y,images(:,:,j,2),x2,y2,method, NaN);
        end;
        It      = warpIm - images(:,:,:,1);

    end;

        % spline-based bicubic interpolation code with incorrect derivatives (below)
%         if size(images, 4) == 1
%             % gray-level
%             warpIm = interp2_bicubic(images(:,:,2),x2,y2, h);
%             It      = warpIm - images(:,:,1);
%         else
%             % color
%             warpIm  = zeros(size(images(:,:,:,1)));
%             for j = 1:size(images,3)
%                 warpIm(:,:,j) = interp2_bicubic(images(:,:,j, 2),x2,y2, h);
%             end;
%             It      = warpIm - images(:,:,:,1);
%         end;

    if nargout == 3

        % First compute derivative then warp
        I2x = imfilter(img2, h,  'corr', 'symmetric', 'same');
        I2y = imfilter(img2, h', 'corr', 'symmetric', 'same');

        if size(images, 4) == 1
            % Gray-level
            Ix  = interp2(x,y,I2x,x2,y2,method);
            Iy  = interp2(x,y,I2y,x2,y2,method);

%             % spline-based bicubic interpolation code with incorrect derivatives
%             Ix  = interp2_bicubic(I2x,x2,y2, h);
%             Iy  = interp2_bicubic(I2y,x2,y2, h);

        else
            % Color
            Ix  = zeros(size(images(:,:,:,1)));
            Iy  = Ix;

            for j = 1:size(images,3)
                Ix(:,:,j)  = interp2(x,y,I2x(:,:,j),x2,y2,method);
                Iy(:,:,j)  = interp2(x,y,I2y(:,:,j),x2,y2,method);
            end;

        end;

        % warp then derivative
%         if size(images, 4) == 1
%             tmp           = images(:,:,1);
%         else
%             tmp           = images(:,:,:,1);
%         end;
%         warpIm(B) = tmp(B);
%         Ix        = imfilter(warpIm, h,  'corr', 'symmetric', 'same');  %
%         Iy        = imfilter(warpIm, h', 'corr', 'symmetric', 'same');
        % end of warp then derivative

        % Temporal average
        I1x = imfilter(img1, h,  'corr', 'symmetric', 'same');  %
        I1y = imfilter(img1, h', 'corr', 'symmetric', 'same');

        % b = 0.6;    % recommended in Wedal etal "improved TV-L1" 2008
        % b = 0.5;

        Ix  = b*Ix+(1-b)*I1x;
        Iy  = b*Iy+(1-b)*I1y;

    end;

    % Disable those out-of-boundary pixels in warping
    It(B)   = 0;
    if nargout == 3
        Ix(B) = 0;
        Iy(B) = 0;
    end;

else
    error('partial_deriv: unknown interpolation method!');
end;


function calpak_test689 ( )

%*****************************************************************************80
%
%% CALPAK_TEST689 tests YMD_TO_DECIMAL
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    20 April 2013
%
%  Author:
%
%    John Burkardt
%
  dhi = 1;
  dlo = 1;
  fhi = 0.0;
  flo = 0.0;
  mhi = 1;
  mlo = 1;
  seed = 123456789;
  yhi = 1970;
  ylo = 1960;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST689\n' );
  fprintf ( 1, '  YMD_TO_DECIMAL converts a date to a year and decimal.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  YMD                            Y.F\n' );
  fprintf ( 1, '\n' );

  for i = 1 : 10

    [ y, m, d, f, seed ] = ymdf_uniform_common ( ylo, mlo, dlo, flo, yhi, ...
      mhi, dhi, fhi, seed );

    s = ymd_to_s_common ( y, m, d );

    yf = ymd_to_decimal ( y, m, d );

    fprintf ( 1, '  %10s  %14.4f\n', s, yf );

  end

  return
end