classdef GLMO < ALGORITHM
% <multi> <real/integer> <large/none>
% Grouped and linked mutation operator algorithm
% optimiser      --- 3 --- The optimisation method. 1 = SMPSO, 2 = NSGA-II, 3 = NSGA-III. Default = NSGA-III
% typeOfGroups   --- 2 --- Grouping method, 1 = linear, 2 = ordered, 3 = random. Default = ordered
% numberOfGroups --- 4 --- The number of varibale Groups. Default = 4

%------------------------------- Reference --------------------------------
% H. Zille, Large-scale Multi-objective Optimisation: New Approaches and a
% Classification of the State-of-the-Art, PhD Thesis, Otto von Guericke
% University Magdeburg, 2019.
% -----------------------------------------------------------------------
%  Copyright (C) 2020 Heiner Zille
%
%  This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0
%  International License. (CC BY-NC-SA 4.0). To view a copy of this license,
%  visit http://creativecommons.org/licenses/by-nc-sa/4.0/ or see the
%  pdf-file "License-CC-BY-NC-SA-4.0.pdf" that came with this code.
%
%  You are free to:
%  * Share ? copy and redistribute the material in any medium or format
%  * Adapt ? remix, transform, and build upon the material
%  Under the following terms:
%  * Attribution ? You must give appropriate credit, provide a link to the
%     license, and indicate if changes were made. You may do so in any reasonable
%     manner, but not in any way that suggests the licensor endorses you or your use.
%  * NonCommercial ? You may not use the material for commercial purposes.
%  * ShareAlike ? If you remix, transform, or build upon the material, you must
%    distribute your contributions under the same license as the original.
%  * No additional restrictions ? You may not apply legal terms or technological
%    measures that legally restrict others from doing anything the license permits.
%
%  Author of this Code:
%   Heiner Zille <heiner.zille@ovgu.de> or <heiner.zille@gmail.com>
%
%  This code is based on the following publications:
%
%  1) Heiner Zille
%     "Large-scale Multi-objective Optimisation: New Approaches and a Classification of the State-of-the-Art"
%     PhD Thesis, Otto von Guericke University Magdeburg, 2019
%     http://dx.doi.org/10.25673/32063
%
%  2) Heiner Zille, Hisao Ishibuchi, Sanaz Mostaghim and Yusuke Nojima
%     "Mutation Operators Based on Variable Grouping for Multi-objective Large-scale Optimization"
%     IEEE Symposium Series on Computational Intelligence (SSCI), IEEE, Athens, Greece, December 2016
%     https://ieeexplore.ieee.org/document/7850214
%
%  This file is intended to work with the PlatEMO framework version 2.5.
%  Date of publication of this code: 06.04.2020
%  Last Update of this code: 06.04.2020
%  A newer version of this algorithm may be available. Please contact the author
%  or see http://www.ci.ovgu.de/Research/Codes.html.
%
% The files may have been modified in Feb 2021 by the authors of the Platemo framework to work with the Platemo 3.0 release.
% -----------------------------------------------------------------------

    methods
        function main(Algorithm,Problem)
            [optimiser,typeOfGroups,numberOfGroups] = Algorithm.ParameterSet(3,2,4);
            if optimiser == 1
                GLMO_SMPSO(Algorithm,Problem,numberOfGroups,typeOfGroups);
            elseif optimiser == 2
                GLMO_NSGAII(Algorithm,Problem,numberOfGroups,typeOfGroups);
            else
                GLMO_NSGAIII(Algorithm,Problem,numberOfGroups,typeOfGroups);
            end
        end
        function GLMO_SMPSO(Algorithm,Problem,numberOfGroups,typeOfGroups)
            Population       = Problem.Initialization();
            Pbest            = Population;
            [Gbest,CrowdDis] = GLMO_UpdateGbest(Population,Problem.N);
            while Algorithm.NotTerminated(Gbest)
                Population       = GLMO_SMPSOOperator(Problem, Population, Pbest, Gbest(TournamentSelection(2,Problem.N,-CrowdDis)), numberOfGroups, typeOfGroups);
                [Gbest,CrowdDis] = GLMO_UpdateGbest([Gbest,Population],Problem.N);
                Pbest            = GLMO_UpdatePbest(Pbest,Population);
            end
        end
        function GLMO_NSGAII(Algorithm,Problem,numberOfGroups,typeOfGroups)
            Population = Problem.Initialization();
            [~,FrontNo,CrowdDis] = GLMO_NSGAIIEnvironmentalSelection(Population,Problem.N);
            while Algorithm.NotTerminated(Population)
                MatingPool = TournamentSelection(2,Problem.N,FrontNo,-CrowdDis);
                Offspring  = GLMO_GA(Problem, Population(MatingPool), numberOfGroups, typeOfGroups);
                [Population,FrontNo,CrowdDis] = GLMO_NSGAIIEnvironmentalSelection([Population,Offspring],Problem.N);
            end
        end
        function GLMO_NSGAIII(Algorithm,Problem,numberOfGroups,typeOfGroups)
            [Z,Problem.N] = UniformPoint(Problem.N,Problem.M);
            Population    = Problem.Initialization();
            Zmin          = min(Population(all(Population.cons<=0,2)).objs,[],1);
            while Algorithm.NotTerminated(Population)
                MatingPool = TournamentSelection(2,Problem.N,sum(max(0,Population.cons),2));
                Offspring  = GLMO_GA(Problem, Population(MatingPool), numberOfGroups, typeOfGroups);
                Zmin       = min([Zmin;Offspring(all(Offspring.cons<=0,2)).objs],[],1);
                Population = GLMO_NSGAIIIEnvironmentalSelection([Population,Offspring],Problem.N,Z,Zmin);
            end
        end
    end
end


function [Fp, Fi] = triangle_triangle_adjacency(F)
  % TRIANGLE_TRIANGLE_ADJACENCY Build a face adjacency data structure for a
  % **manifold** triangle mesh. From each face we can find where on its
  % neighboring faces it's incident.
  %
  % [Fp, Fi] = triangle_triangle_adjacency(F)
  %
  % Input:
  %   F  list of face indices, #faces by 3
  % Output:
  %   Fp  #faces by 3, where Fp(i,j) tells the index of the neighboring triangle
  %     to the jth edge of the ith triangle in F. -1 if the jth edge of the ith
  %     triangle in F is a border edge. (jth edge refers to the edge opposite
  %     the jth vertex: so triangle in a triangle (a,b,c), the 1st edge is
  %     b-->c, the 2nd is c-->b and the 3rd is a-->b
  %   Fi  #faces by 3, where Fi(i,j) tells the position on the neighboring
  %     triangle to the jth edge of the ith triangle in F. -1 if the jth edge
  %     if the ith triangle in F is a border edge. Uses the same indexing of
  %     positions of edges on a triangle as above.
  %
  % For example:
  %
  % F = [ 1 3 2;
  %       2 3 4];
  % [Fp, Fi] = triangle_triangle_adjacency(F);
  % Fp =
  %     2    -1    -1
  %    -1    -1     1
  % Fi =
  %     3    -1    -1
  %    -1    -1     1
  %

  if size(F,2) == 3

    % get list of edges (1st edges then 2nd edges then 3rd edges)
    E = [F(:,2) F(:,3); F(:,3) F(:,1); F(:,1) F(:,2)];

    % sparse adjacency matrix where (i,j) = k, k is the index of i-->j in edge
    % list if i-->j AND j-->i exist in edge list. This way is slightly faster
    % than building a proper adjacency list first.
    Ei = sparse(E(:,1),E(:,2),1:size(E,1));
    % adjacency list of edges as if edges represent undirected graph
    unadj = Ei>0;
    % "non-adjacency" list, (i,j) > 0 iff i-->j exists but j-->i does not exist
    nonadj = unadj-(unadj');
    adj = ((unadj + nonadj)==1).*Ei;

    % need to get mapping from sparse ordering to original order
    [ii jj si] = find(adj);
    % this is slightly faster than sorting the above by ii, which is the same
    [ii jj v] = find(adj');
    % build map from edges to their corresponding faces
    E2F = repmat(1:size(F,1),1,3)';
    % initialize adjacency map to -1
    Fp = -ones(size(E,1),1);
    Fp(si) = E2F(v);
    Fp = reshape(Fp,size(F));
    % build map from edges to edge positions
    I = reshape(repmat((1:3),size(F,1),1),1,3*size(F,1))';
    % use corresponding edges to find positions of correponding faces
    Fi = -ones(size(E,1),1);
    Fi(si) = I(v);
    Fi = reshape(Fi,size(F));
  else
    error('Not supported yet...');
  end

end


function a = ge( x, y )

%Disciplined convex programming information for GE (>=):
%   The right-hand side of a less-than constraint must be convex. The
%   left-hand side must be concave. Of course, real constant and affine
%   expressions are both convex and concave and can be used on either
%   side as well.
%
%Disciplined geometric programming information for GE (>=):
%   The right-hand side of a less-than constraint must be log-convex---
%   including positive constants, monomials, posynomials, generalized
%   posynomials, and products thereof. The left-hand side must be log-
%   concave---including positive constants, monomials, reciprocals of
%   log-convex expressions, and products thereof.
%
%Note that CVX does not distinguish between strict greater-than (>) and
%greater-than-or-equal (<=) constraints; they are treated identically.
%Feasible interior-point solvers tend to return points which satisfy
%strict inequality, but not all solvers do.

evalin( 'caller', 'cvx_verify' );
b = cvx_pushcnstr( x, y, '>=' );
if nargout, a = b; end

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


% Script to run a suite of test problems
% We have six test problems wherein the local Matlab client (possibly) uses
% the ithaca cluster with the Parallel Computing Toolbox

% The various test examples are in folders within the current directory

%%
clear all

local = pwd; addpath(local);

%% md_wrap
% md_program runs a 'molecular dynamics' simulation and writes some results
% to the the Command Window

 try
   fprintf(1,'\n \n Run the parallel MD example \n');
   cd('./john_md');
   nw = 4;
   results = md_wrap(nw);
% Show that we have retrieved results to the local workspace
   fprintf(1,'\n Final potential energy  %14f \n ',results{1}.pe(end))
   cd(local)
   clear all
   fprintf(1,'Results have been cleared \n')
 catch MD
     disp('Trouble with MD_WRAP')
     cd(local)
     MD %#ok
     MD.message
 end

%% systolic_ithaca
% systolic_ithaca creates and submits a job with a systolic array to filter
% an audio file. The job runs on ithaca.arc.vt.edu and requires a parallel
% configiguration file ithaca_2009b.
% The original and the filtered files are played on the local machine
% (assuming it has speakers).

 local = pwd;
 try
   fprintf(1,'\n \n Run the systolic array example \n');
   cd ./lyrics
   systolic_ithaca
   cd(local)
   clear all
 catch SYSTOLIC
     disp('Trouble with systolic_ithaca')
     cd(local)
     SYSTOLIC %#ok
 end

%% dist_knap
% dist_knap  creates a job with four tasks. Each task loops through
% a range of possible weight combinations to find those that sum to a given
% value

 local = pwd;
 try
   fprintf(1,'\n \n Run the knapsack example \n');
   cd ./knap
   dist_knap
   cd(local)
   clear all
 catch KNAP
     disp('Trouble with dist_knap')
     cd(local)
     KNAP %#ok
 end

%% color_segmentation
% colorSegmentationSol2  creates a matlabpool and uses an spmd construct
% to extract parts of an image with a given color. This version creates
% several images on the cluster - these are a Composite variable on the
% local client. After running the filter we write a jpg file on the client.

 local = pwd;
 try
   fprintf(1,'\n \n Run the color segmentation example \n');
   cd ./color_segmentation
   filteredImage=colorSegmentationSol2('ithaca');
   cd(local)
% Display some information about the result
   fprintf(1,'\n  The binary image files are referenced as a Composite variable on the client \n')
   fprintf(1,' We retrieve one of these (four) images to a jpeg file on the client \n');
   fprintf(1,' This could take awhile \n \n ');
%
    jj = 3; % pick one
%  for jj=1:length(filteredImage)
    f_Image = filteredImage{jj};
    disp('size of the image array  ');  size(f_Image)
    imwrite( f_Image, ['fab_' int2str(jj) '.jpg'], 'jpg')
%  end
   fprintf(1,'Results have been written to the local directory \n');
   fprintf(1,'Now close the matlabpool \n');
   matlabpool close
   clear all
 catch COLOR
     disp('Trouble with color_segmentation')
     if matlabpool('size') > 0
        matlabpool close force ithaca_2009b
     end
     cd(local)
     COLOR %#ok
     COLOR.message
 end

%% birthday
% brunbirthday  creates a batch job that uses a matlabpool and a parfor
% construct. The job runs a number of realizations (Monte Carlo) to
% generate an estimate for the probability that at least two people in a
% group (or 30) have the same birthday.

 local = pwd;
 try
   fprintf(1,'\n \n Run the birthday example \n');
   cd ./birthday
   nw = 4;
   prob = brunbirthday(nw)  %#ok
   cd(local)
   fprintf(1,'The brunbirthday script destroys the batch job \n');
   clear all
 catch BIRTH
     disp('Trouble with birthday')
     if matlabpool('size') > 0
        matlabpool close force ithaca_2009b
     end
     cd(local)
     BIRTH %#ok
     BIRTH.message
 end


function view = installTalairachCoordinates(view);
%loadTalairachCoordinates() Load Tal. coordinates from file and convert the
%to Volume ROIs
%The Gray (Volume) window must be open.
%
% Authors RFD and JR 09/18/01
% 2002.01.17 RFD modified initialization to allow GRAY view as well as
% volume.

global mrSESSION

if ~strcmp(view.viewType,'Volume') & ~strcmp(view.viewType,'Gray');

    error('view must be VOLUME or GRAY')

end

transform = loadTalairachXform(mrSESSION.subject);

talDat = loadTalairachCoordinates;

xyz=[talDat{1}',talDat{2}',talDat{3}'];

roiNames = cellstr(talDat{4});

roiColors = cellstr(talDat{5});

% Let the user select from the available coords

[idx,ok] = listdlg('PromptString','Select Talairach coordinates',...

       'SelectionMode','multiple',...

       'ListString',roiNames);

if ~ok %user has aborted selection

    return

end

xyz=xyz(idx,:);

roiNames=roiNames(idx);

roiColors=roiColors(idx);

vCoords = talairachToVol(xyz, transform.vol2Tal);

for(ii=[1:size(vCoords,1)])

    view = newROI(view, roiNames{ii}, 1, roiColors{ii});

    view.ROIs(view.selectedROI).coords = round(vCoords(ii,:))';

%     roi.name = roiNames{ii};%['Talairach_',num2str(tc(ii,1)),'_',num2str(tc(ii,2)),'_',num2str(tc(ii,3)),''];

%     roi.coords = round(vCoords(ii,:))';

%     roi.color = roiColors{ii};

%     roi.viewType = view.viewType;

%     view = addROI(view,roi);

end


function s = plus(f, g)
%+   Addition of DELTAFUN objects.
%   F + G adds F and G, where F and G may be DELTAFUN objects or scalars.
%
% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

%%

% If one of the arguments is empty:
if ( isempty(f) || isempty(g) )
    % Return with an empty DELTAFUN:
    s = deltafun;
    return
end

% One of the arguments (i.e., f or g) is necessarily a DELTAFUN object.
% (Otherwise, this overloaded plus would not have been called!). Ensure it is f:
if ( ~isa(f, 'deltafun') )
    s = plus(g, f);
    return
end

% Cast g to a DELTAFUN if it is a double or a different kind of FUN:
if ( isa(g, 'double') )
    g = deltafun(0*f.funPart + g);
elseif ( isa(g, 'fun') )
    g = deltafun(g);
end

% Add the funParts:
funPart = f.funPart + g.funPart;

% Add the delta functions:
[deltaMag, deltaLoc] = deltafun.mergeDeltas(f.deltaMag, f.deltaLoc, ...
    g.deltaMag, g.deltaLoc);

% Assemble the output DELTAFUN:
s = deltafun(funPart, struct('deltaMag', deltaMag, 'deltaLoc', deltaLoc));

% Simplify:
s = simplifyDeltas(s);

end


%
% [At,b,c,K]=readsdpa(fname)
%
% Reads in a problem in SDPA sparse format, and returns it in SeDuMi
% format.
%
% 7/20/07  Modified to handle comments and other cruft in the SDPA
% file.  In particular,
%
%    1. Initial comment lines beginning with " or * are ignored.
%    2. In the first three lines, any extraneous characters after
%       the numbers are ignored.
%    3. In the block description, any occurrences of "{", ",", "}", "(",
%       and ")" are converted into spaces.
%
function [At,b,c,K]=readsdpa(fname)
%
% Open the file for reading.
%
fid=fopen(fname,'r');
if (fid == -1),
  fprintf('file does not exist!\n');
  return;
end;
%
% Skip over the initial comments.
%
inputline=fgetl(fid);
while (inputline(1)=='"' || inputline(1)=='*')
  inputline=fgetl(fid);
end
%
% Read in m.
%
m=sscanf(inputline,'%d',1);
inputline=fgetl(fid);
%
% Read in nblocks.
%
nblocks=sscanf(inputline,'%d',1);
inputline=fgetl(fid);
%
% Read in the raw block sizes.
%
inputline=regexprep(inputline,'[\,(){}]',' ');
rawblocksizes=sscanf(inputline,'%d',nblocks);
inputline=fgetl(fid);
%
% Compute the actual block sizes, figure out block types, and figure out
% where in the vectors stuff will go.
%
blocksizes=abs(rawblocksizes);
blocktypes=zeros(nblocks,1);
for i=1:nblocks,
  if (rawblocksizes(i) < 0)
     blocktypes(i)=1;
  else
     blocktypes(i)=2;
  end;
end;
blockbases=zeros(nblocks,1);
lpbase=1;
for i=1:nblocks,
  if (blocktypes(i)==1)
    blockbases(i)=lpbase;
    lpbase=lpbase+blocksizes(i);
  end;
end;
K.l=lpbase-1;
sdpbase=lpbase;
K.s=[];
for i=1:nblocks,
  if (blocktypes(i)==2)
    blockbases(i)=sdpbase;
    sdpbase=sdpbase+blocksizes(i)^2;
    K.s=[K.s blocksizes(i)];
  end;
end;
n=sdpbase-1;
%
% Now, read in the right hand side.
%
b=zeros(m,1);
inputline=regexprep(inputline,'[\,(){}]',' ');
b=sscanf(inputline,'%le',m);
%
% Now, read in the entries in the constraints and c.
%
c=zeros(1,n);
At=sparse(n,m);
[entries,count]=fscanf(fid,'%d %d %d %d %le',[5,inf]);
count=count/5;
[entriesm,entriesn]=size(entries);
for i=1:entriesn,
  if (entries(1,i)==0),
    block=entries(2,i);
    if (blocktypes(block)==1)
%
% LP data.
%
      c(1,blockbases(block)+entries(3,i)-1)=entries(5,i);
    else
%
% SDP block entry
%
      c(1,blockbases(block)+(entries(3,i)-1)*blocksizes(block)+ ...
        entries(4,i)-1)=entries(5,i);
      c(1,blockbases(block)+(entries(4,i)-1)*blocksizes(block)+ ...
        entries(3,i)-1)=entries(5,i);
    end;
  else
%
% Constraint entry.
%
    block=entries(2,i);
    constraint=entries(1,i);
    if (blocktypes(block)==1)
%
% LP data.
%
      At(blockbases(block)+entries(3,i)-1,constraint)=entries(5,i);
    else
%
% SDP block entry
%
      At(blockbases(block)+(entries(3,i)-1)*blocksizes(block)+ ...
        entries(4,i)-1,constraint)=entries(5,i);
      At(blockbases(block)+(entries(4,i)-1)*blocksizes(block)+ ...
        entries(3,i)-1,constraint)=entries(5,i);
    end;
  end;
end;
%
% Fix up the sign of c to match SeDuMi's convention.  Also, make c
% a column vector to match SeDuMi's fromsdpa().
%
c=-c';


function layer = genNetworkLSTMEncoderDecoder(para)
if isfield(para, 'LastActivation4MSE')==0
    para.LastActivation4MSE = 'linear';
end

layer{1}.name = 'Input';        % this is an input layer
layer{end}.inputIdx = 1;    % specifies the index of GCC in Visible_tr
layer{end}.dim = [1 1]*double(para.inputDim);             % [input dim; output dim];

if isfield(para, 'useFbank') && para.useFbank
    MelWindow = mel_window_FE(40, 256, 16000)';
    MelWindow(:,end+1) = 0;
    layer{end+1}.name = 'Affine';
    layer{end}.prev = -1;
    layer{end}.W = MelWindow;
    layer{end}.b = zeros(40,1);
    layer{end}.dim = [40 layer{end-1}.dim(1)];
    layer{end}.update = 0;

    layer{end+1}.name = 'log';
    layer{end}.prev = -1;
    layer{end}.const = 1e-7;
    layer{end}.dim = [1 1]*layer{end-1}.dim(1);
end

layer{end+1}.name = 'delta';
layer{end}.prev = -1;
layer{end}.dim = [3 1]*layer{end-1}.dim(1);

layer{end+1}.name = 'Affine';
layer{end}.prev = -1;
layer{end}.W = [];
layer{end}.b = [];
layer{end}.dim = [1 1]*layer{end-1}.dim(1);
layer{end}.update = 0;

layerLSTM = genNetworkLSTM(para);
for i=1:length(layerLSTM)
    layerLSTM{i} = rmfield(layerLSTM{i}, 'next');
end

layerLSTM = layerLSTM(2:end);

layerLSTM{1}.prev = -1;
layerLSTM{1}.dim(2) = layer{end}.dim(1);

layer = [layer layerLSTM];

if isfield(para, 'labelDelay')
    layer{end}.labelDelay = para.labelDelay;
end
if isfield(para, 'costFrameSelection');
    layer{end}.costFrameSelection = para.costFrameSelection;
end

layer{end-2}.name = 'multi_softmax';
layer{end-2}.TaskVocabSizes = para.outputDim/para.ngram_len;

layer{end}.name = 'multi_cross_entropy';
layer{end}.TaskVocabSizes = para.outputDim/para.ngram_len;
layer = FinishLayer(layer);
end


function [biomassValues, targetValues] = runProductionEnvelope(model, targetRxn, biomassRxn, nPts)
% runProductionEnvelope
%   Calculates the byproduct secretion envelope
%
% Input:
%   model            a model structure
%   targetRxn        identifier of target metabolite production reaction
%   biomassRxn       identifier of biomass reaction
%   nPts             number of points in the plot (opt, default 20)
%
% Output:
%   biomassValues    Biomass values for plotting
%   targetValues     Target upper and lower bounds for plotting
%
% Modified from COBRA Toolbox productionEnvelope.m
%
% Usage: [biomassValues, targetValues] = runProductionEnvelope(model, targetRxn, biomassRxn, nPts)

if nargin < 4
    nPts = 20;
end

% Run FBA to get upper bound for biomass
model   = setParam(model,'obj',biomassRxn,1);
[solMax,hsSol]  = solveLP(model);
solMax  = solMax.x(logical(model.c));
model.c = -model.c;
solMin  = solveLP(model,0,[],hsSol);
solMin  = solMin.x(logical(model.c));

% Create biomass range vector
biomassValues = linspace(solMin,solMax,nPts);
targetUpperBound = nan(1,numel(biomassValues));
targetLowerBound = nan(1,numel(biomassValues));

fprintf('Creating production envelope...   0%% complete');
% Max/min for target production
model = setParam(model,'obj',targetRxn,1);
for i = 1:length(biomassValues)
    progress=pad(num2str(floor(i/numel(biomassValues)*100)),3,'left');
    fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b%s%% complete',progress);
    model1 = setParam(model,'eq',biomassRxn,biomassValues(i));
    sol = solveLP(model1,0,[],hsSol);
    if (sol.stat > 0)
        targetUpperBound(i) = sol.x(logical(model.c));
    else
        targetUpperBound(i) = NaN;
    end
    model1.c = -model1.c;
    sol = solveLP(model1,0,[],hsSol);
    if (sol.stat > 0)
        targetLowerBound(i) = sol.x(logical(model1.c));
    else
        targetLowerBound(i) = NaN;
    end
end
fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\bCOMPLETE\n');

% Plot results
plot([biomassValues fliplr(biomassValues)],[targetUpperBound fliplr(targetLowerBound)],'blue','LineWidth',2);
axis tight;
ylabel([strrep(targetRxn,'_','-') ' (mmol/gDW h)']);
xlabel('Growth rate (1/h)');
targetValues = [targetLowerBound; targetUpperBound];
end


classdef S2FunHarmonicSym < S2FunHarmonic
% a class represeneting a symmetrised function on the sphere

properties
  s = []; % symmetry
end

properties (Dependent = true)
  CS
  SS
end

methods
  function sF = S2FunHarmonicSym(fhat, s)
    if nargin == 0, return; end
    sF.fhat = fhat;
    sF.s = s;
  end

  function CS = get.CS(sF)
    CS = sF.s;
  end

  function SS = get.SS(sF)
    SS = sF.s;
  end

end

methods (Static = true)
  sF = quadrature(f, varargin);
end

end


function change = delta(ct, mt, y, b)

% delta 函数是非均匀突变使用的非均匀分布。
% 此函数根据当前发电量、最大发电量和可能的偏差量返回变化。
%
% ct - current generation
% mt - maximum generation
% y  - maximum amount of change, i.e. distance from parameter value to bounds
% b  - shape parameter

%%
r = ct / mt;
if(r > 1)
  r = 0.99;
end
change = y * (rand * (1 - r)) ^ b;

github-repos/MATLAB/Time9Y-Matlab-Machine/Matlab-Machine-6590d27c49bb2c9415613f132fc2b50fea982c60/009_Optimize time series prediction of BP neural network based on genetic algorithm/goat/delta.m


% SRH is a robust pitch tracker.
%
% Octave compatible
%
% Description
%  The Summation of the Residual Harmonics (SRH) method is described in [1].
%  This algorithm exploits a criterion taking into the strength of the
%  harmonics and subharmonics of the residual excitation signal in order to
%  determine both voicing decision and F0 estimates. It is shown in [1] to
%  be particularly interesting in adverse conditions (low SNRs with various
%  types of additive noises).
%
%
% Inputs
%  wave            : [samples] [Nx1] input signal (speech signal)
%  fs              : [Hz]      [1x1] sampling frequency
%  f0min           : [Hz]      [1x1] minimum possible F0 value
%  f0max           : [Hz]      [1x1] maximum possible F0 value
%  hopsize         : [ms]      [1x1] time interval between two consecutive
%                    frames (i.e. defines the rate of feature extraction).
%
% Outputs
%  F0s             : vector containing the F0 estimates (values are
%                    provided even in unvoiced parts).
%  VUVDecisions    : vector containing the binary voicing decisions.
%  SRHVal          : vector containing the SRH values (according the
%                    harmonic criterion - voicing decision are derived from
%                    these values by simple thresholding).
%  time            : [s] Analysis instants of the features described above.
%
% Example
%  Please see the HOWTO_glottalsource.m example file.
%
% References
%  [1] T.Drugman, A.Alwan, "Joint Robust Voicing Detection and Pitch Estimation
%      Based on Residual Harmonics", Interspeech11, Firenze, Italy, 2011.
%      Publication available at the following link:
%      http://tcts.fpms.ac.be/~drugman/files/IS11-Pitch.pdf
%
% Copyright (c) 2011 University of Mons, FNRS
%
% License
%  This code is a part of the GLOAT toolbox with the following
%  licence:
%  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.
%
% This function is part of the Covarep project: http://covarep.github.io/covarep
%
% Author
%  Thomas Drugman thomas.drugman@umons.ac.be
%
% Modified
%  John Kane kanejo@tcd.ie September 27th 2014 - Bug fix and efficiency

function [F0s,VUVDecisions,SRHVal,time] = pitch_srh(wave,fs,f0min,f0max,hopsize)

if length(wave)/fs<0.1
    display('SRH error: the duration of your file should be at least 100ms long');
    pause(0.001)
    F0s=0;VUVDecisions=0;SRHVal=0;time=0;
end

if f0max<=f0min
    display('You look funny! Your f0min should be lower than f0max!!')
    pause(0.001)
end

if fs>16000
    display('Sample rate is bigger than 16kHz. Audio is resampled.')
    wave=resample(wave,16000,fs);
    fs=16000;
end

if nargin < 5
    hopsize=10;
end

%% Setings
nHarmonics = 5;
SRHiterThresh = 0.1;
SRHstdThresh = 0.05;
VoicingThresh = 0.07;
VoicingThresh2 = 0.085;
LPCorder=round(3/4*fs/1000);
Niter=2;

%% Compute LP residual
[res] = lpcresidual(wave,round(25/1000*fs),round(5/1000*fs), ...
                    LPCorder);

%% Create frame matrix
waveLen = length(wave);
clear wave;
frameDuration = round(100/1000*fs)-2; % Minus 2 to make equivalent
                                      % to original
frameDuration = round(frameDuration/2)*2; % Enforce evenness of the frame's length
shift = round(hopsize/1000*fs);
halfDur = round(frameDuration/2);
time = halfDur+1:shift:waveLen-halfDur;
N = length(time);
frameMat=zeros(frameDuration,N);
for n=1:N
    frameMat(:,n) = res(time(n)-halfDur:time(n)+halfDur-1);
end
clear res;

%% Create window matrix and apply to frames
win = blackman(frameDuration);
frameMat = bsxfun(@times, frameMat, win);

%% Do mean subtraction
frameMat = bsxfun(@minus, frameMat, mean(frameMat, 1));

%% Compute spectrogram matrix
specMat = zeros(floor(fs/2), size(frameMat, 2));
idx = 1:floor(fs/2);
for i = 1:size(frameMat,2)
    tmp = abs(fft(frameMat(:, i), fs));
    specMat(:, i) = tmp(idx);
end
clear frameMat tmp idx;
specMat = bsxfun(@rdivide, specMat, sqrt(sum(specMat.^2, 1)));

%% Estimate the pitch track in 2 iterations
no_pitch_range_adjustment = true;
for Iter=1:Niter

    [F0s,SRHVal] = SRH( specMat, nHarmonics, f0min, f0max );

    if max(SRHVal) > SRHiterThresh
        F0medEst = median( F0s( SRHVal > SRHiterThresh ) );

        % Only refine F0 limits if within the original limits
        if round(0.5*F0medEst) > f0min
            f0min=round(0.5*F0medEst);
            no_pitch_range_adjustment = false;
        end
        if round(2*F0medEst) < f0max
            f0max=round(2*F0medEst);
            no_pitch_range_adjustment = false;
        end
    end
    if no_pitch_range_adjustment
        break
    end
end
clear specMat;
time=time/fs;

%% Voiced-Unvoiced decisions are derived from the value of SRH (Summation of
%% Residual Harmonics)
VUVDecisions = zeros(1,N);

if std(SRHVal) > SRHstdThresh
   VoicingThresh = VoicingThresh2;
end

VUVDecisions( SRHVal > VoicingThresh ) = 1;

end

function [F0,SRHVal] = SRH( specMat, nHarmonics, f0min, f0max )

% Function to compute Summation of Residual harmonics function
% on a spectrogram matrix, with each column corresponding to one
% spectrum.

% Initial settings
N = size(specMat, 2);
SRHmat = zeros(f0max,N);

fSeq = f0min:f0max;
fLen = length(fSeq);

% Prepare harmonic indeces matrices.
plusIdx = repmat( (1:nHarmonics)',1,fLen) .* repmat(fSeq,nHarmonics,1);
subtrIdx = round( repmat( (1:nHarmonics-1)'+.5,1,fLen) .* ...
                  repmat(fSeq,nHarmonics-1,1) );

% avoid costly repmat operation by adjusting indices
plusIdx = mod(plusIdx-1,size(specMat,1))+1;
subtrIdx = mod(subtrIdx-1,size(specMat,1))+1;

% Do harmonic summation
for n=1:N
    specMatCur = specMat(:,n);
    SRHmat(fSeq,n) = ( sum( specMatCur(plusIdx), 1 ) - ...
                       sum( specMatCur(subtrIdx), 1 ) )';
end

% Retrieve f0 and SRH value
[SRHVal,F0] = max( SRHmat );

end


function Population = EnvironmentalSelection(Population,N,kappa)
% The environmental selection of IBEA

%------------------------------- 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".
%--------------------------------------------------------------------------

    Next = 1 : length(Population);
    [Fitness,I,C] = CalFitness(Population.objs,kappa);
    while length(Next) > N
        [~,x]   = min(Fitness(Next));
        Fitness = Fitness + exp(-I(Next(x),:)/C(Next(x))/kappa);
        Next(x) = [];
    end
    Population = Population(Next);
end


function sum_wf(handles,einzelmat)
    imagefile = get(handles.im_file_edit, 'String');
    outpath = get(handles.out_dir_edit, 'String');
    if outpath(length(outpath))~='\'
        outpath = [outpath,'\'];
    end

    %Obtain info on image type, etc
    file_info = get_file_info2(imagefile, handles);

    load(einzelmat,'image_sum','x_size','y_size','x_offset','y_offset');

    exf       = str2double(get(handles.exf_edit,'String')); %expansion factor
    ishift     = str2double(get(handles.ishift,'String'));
    jshift     = str2double(get(handles.jshift,'String'));
    xw_render = str2double(get(handles.xw_render_edit,'String'));
    yw_render = str2double(get(handles.yw_render_edit,'String'));

    if xw_render ~= 0
        xw=xw_render;
    else
        xw=x_size;
    end
    if yw_render ~= 0
        yw=yw_render;
    else
        yw=y_size;
    end

    x_off=x_offset+ishift;
    y_off=y_offset+jshift;

    wf_sum=zeros(yw,xw);
    wf_sum=image_sum(y_off:y_off+yw-1,x_off:x_off+xw-1);
    wf_sum=wf_sum/max(max(wf_sum));
    wf_sum=wf_sum/max(max(wf_sum));

    imex=zeros(yw*exf,xw*exf);
    for j=1:yw
        for i=1:xw
            x0=(i-1)*exf+1;
            x1=x0+exf-1;
            y0=(j-1)*exf+1;
            y1=y0+exf-1;
            imex(y0:y1,x0:x1)=wf_sum(j,i);
        end
    end

    figure
    imagesc(imex)
    title(['Expanded Widefield Sum: Frames: ',num2str(file_info.start),'-',num2str(file_info.stop)])
    colormap gray
    axis image

    if get(handles.write_image_checkbox,'Value') %write to file if box is checked
        if (file_info.part_name(length(file_info.part_name)) == '_') %Avoid saving with repeat seperators
            wf_sum_file=[outpath,'\',file_info.part_name,num2str(file_info.start),'-',num2str(file_info.stop),'exp',num2str(exf),'_wf.tif'];
        else
            wf_sum_file=[outpath,'\',file_info.part_name,num2str(file_info.start),'-',num2str(file_info.stop),'_exp',num2str(exf),'_wf.tif'];
        end
        imwrite(uint8(imex*255),wf_sum_file,'Compression','none');
    end


function metoffice_plot_fa(Q)

[D,N] = size(Q.X);
M = size(Q.W,2);

E2 = reshape(Q.CovX, [D^2, N]);
E = sqrt(E2(1:(D+1):end,:));

hax = tserrorplot(Q.X',2*E');
ylim_centered(hax);
ylim_scale(hax, 1.2);


function rez  = template_learning(rez, tF, st3)

wPCA  = rez.wPCA;
iC = rez.iC;
ops = rez.ops;

xcup = rez.xcup;
ycup = rez.ycup;

wroll = [];
tlag = [-2, -1, 1, 2];
for j = 1:length(tlag)
    wroll(:,:,j) = circshift(wPCA, tlag(j), 1)' * wPCA;
end

%% split templates into batches
rmin = 0.6;
nlow = 100;
n0 = 0;
use_CCG = 0;

Nchan = rez.ops.Nchan;
Nk = size(iC,2);
yunq = unique(rez.yc);

ktid = int32(st3(:,2)) + 1;
tmp_chan = iC(1, :);
ss = double(st3(:,1)) / ops.fs;

dmin = rez.ops.dmin;
ycenter = (min(rez.yc) + dmin-1):(2*dmin):(max(rez.yc)+dmin+1);
dminx = rez.ops.dminx;
xcenter = (min(rez.xc) + dminx-1):(2*dminx):(max(rez.xc)+dminx+1);
[xcenter, ycenter] = meshgrid(xcenter, ycenter);
xcenter = xcenter(:);
ycenter = ycenter(:);

Wpca = zeros(6, Nchan, 1000, 'single');
nst = numel(ktid);
hid = zeros(nst,1 , 'int32');

% ycup = rez.yc;

tic

for j = 1:numel(ycenter)
    if rem(j,5)==1
        fprintf('time %2.2f, GROUP %d/%d, units %d \n', toc, j, numel(ycenter), n0)
    end

    y0 = ycenter(j);
    x0 = xcenter(j);
    xchan = (abs(ycup - y0) < dmin) & (abs(xcup - x0) < dminx);
    itemp = find(xchan);

    if isempty(itemp)
        continue;
    end
    tin = ismember(ktid, itemp);
    pid = ktid(tin);
    data = tF(tin, :, :);

    if isempty(data)
        continue;
    end
%     size(data)

    ich = unique(iC(:, itemp));
%     ch_min = ich(1)-1;
%     ch_max = ich(end);

    if numel(ich)<1
        continue;
    end

    nsp = size(data,1);
    dd = zeros(nsp, 6, numel(ich), 'single');
    for k = 1:length(itemp)
        ix = pid==itemp(k);
        % how to go from channels to different order
        [~,ia,ib] = intersect(iC(:,itemp(k)), ich);
        dd(ix, :, ib) = data(ix,:,ia);
    end

    kid = run_pursuit(dd, nlow, rmin, n0, wroll, ss(tin), use_CCG);

    [~, ~, kid] = unique(kid);
    nmax = max(kid);
    for t = 1:nmax
%         Wpca(:, ch_min+1:ch_max, t + n0) = gather(sq(mean(dd(kid==t,:,:),1)));
        Wpca(:, ich, t + n0) = gather(sq(mean(dd(kid==t,:,:),1)));
    end

    hid(tin) = gather(kid + n0);
    n0 = n0 + nmax;
end
Wpca = Wpca(:,:,1:n0);
toc
%%
rez.W = zeros(61,0, 3, 'single');
rez.U = zeros(ops.Nchan,0,3, 'single');
rez.mu = zeros(1,0, 'single');
for  t = 1:n0
    dWU = wPCA * gpuArray(Wpca(:,:,t));
    [w,s,u] = svdecon(dWU);
    wsign = -sign(w(21,1));
    rez.W(:,t,:) = gather(wsign * w(:,1:3));
    rez.U(:,t,:) = gather(wsign * u(:,1:3) * s(1:3,1:3));
    rez.mu(t) = gather(sum(sum(rez.U(:,t,:).^2))^.5);
    rez.U(:,t,:) = rez.U(:,t,:) / rez.mu(t);
end

%%
rez.ops.wPCA = wPCA;


function net= addLayers(net, opts, dbTrain)

    methodOpts= strsplit(opts.method, '_');
    [~, sz]= relja_netOutputDim(net);
    D= sz(3);

    if ismember('preL2', methodOpts)
        % normalize feature-wise
        net.layers{end+1}= struct('type', 'normalize', 'name', 'preL2', ...
            'param', [2*D, 1e-12, 1, 0.5], 'precious', 0);
        methodOpts= removeOpt(methodOpts, 'preL2');
        doPreL2= true;
    else
        doPreL2= false;
    end

    if ismember('max', methodOpts)
        methodOpts= removeOpt(methodOpts, 'max');
        net.layers{end+1}= layerTotalMaxPool('max:core');

    elseif ismember('avg', methodOpts)
        methodOpts= removeOpt(methodOpts, 'avg');
        net.layers{end+1}= layerTotalAvgPool('avg:core');

    elseif any( ismember( {'vlad', 'vladv2'}, methodOpts) )

        if doPreL2
            L2str= '_preL2';
        else
            L2str= '';
        end

        whichDesc= sprintf('%s_%s%s', opts.netID, opts.layerName, L2str);

        k= 64;
        paths= localPaths();
        trainDescFn= sprintf('%s%s_%s_traindescs.mat', paths.initData, dbTrain.name, whichDesc);
        clstFn= sprintf('%s%s_%s_k%03d_clst.mat', paths.initData, dbTrain.name, whichDesc, k);

        clsts= getClusters(net, opts, clstFn, k, dbTrain, trainDescFn);

        load( trainDescFn, 'trainDescs');
        load( clstFn, 'clsts');
        net.meta.sessionID= sprintf('%s_%s', net.meta.sessionID, dbTrain.name);

        % --- VLAD layer

        if ismember('vladv2', methodOpts)
            methodOpts= removeOpt(methodOpts, 'vladv2');

            % set alpha for sparsity
            [~, dsSq]= yael_nn(clsts, trainDescs, 2); clear trainDescs;
            alpha= -log(0.01)/mean( dsSq(2,:)-dsSq(1,:) ); clear dsSq;

            net.layers{end+1}= layerVLADv2('vlad:core');
            net.layers{end}= net.layers{end}.constructor({alpha*2*clsts, -alpha*sum(clsts.^2,1), -clsts});

        elseif ismember('vlad', methodOpts)
            % see comments on vladv2 vs vlad in the README_more.md

            methodOpts= removeOpt(methodOpts, 'vlad');

            % set alpha for sparsity
            clstsAssign= relja_l2normalize_col(clsts);
            dots= sort(clstsAssign'*trainDescs, 1, 'descend'); clear trainDescs;
            alpha= -log(0.01)/mean( dots(1,:) - dots(2,:) ); clear dots;

            net.layers{end+1}= layerVLAD('vlad:core');
            net.layers{end}= net.layers{end}.constructor({alpha*clstsAssign, clsts});

        else
            error('Unsupported method "%s"', opts.method);
        end

        if ismember('intra', methodOpts)
            % --- intra-normalization
            net.layers{end+1}= struct('type', 'normalize', 'name', 'vlad:intranorm', ...
                'param', [2*D, 1e-12, 1, 0.5], 'precious', 0);
            methodOpts= removeOpt(methodOpts, 'intra');
        end

    else
        error('Unsupported method "%s"', opts.method);
    end

    % --- final normalization
    net.layers{end+1}= layerWholeL2Normalize('postL2');

    % --- check if all options are used
    if ~isempty(methodOpts)
        error('Unsupported options (method=%s): %s', opts.method, strjoin(methodOpts, ', '));
    end

    net.meta.sessionID= sprintf('%s_%s', net.meta.sessionID, opts.method);
    net.meta.epoch= 0;

end

function opts= removeOpt(opts, optName)
    opts(ismember(opts, optName))= [];
end


% Profiler extension for Normalized Leaky Kernel Affine Projection
% Algorithm
%
% This file is part of the Kernel Adaptive Filtering Toolbox for Matlab.
% https://github.com/steven2358/kafbox/

classdef nlkapa_profiler < nlkapa

    properties (GetAccess = 'public', SetAccess = 'private')
        elapsed = 0; % elapsed time
    end

    methods

        function kaf = nlkapa_profiler(parameters) % constructor
            if nargin<1, parameters = struct(); end
            kaf = kaf@nlkapa(parameters);
        end

        function flops = lastflops(kaf) % flops for last iteration
            % numbers of operations
            m1 = 1;
            m2 = 1;
            m3 = 1;
            m4 = 1;

            floptions = struct(...
                'sum', m1, ...
                'mult', m2, ...
                'div', m3, ...
                sprintf('%s_kernel',kaf.kerneltype), [m4,1,size(kaf.dict,2)]);

            flops = nan; % dummy. kflops(floptions);
        end

        %% flops breakdown

        % [space for remarks on number of operations used above]

        %%

        function train_profiled(kaf,x,y)
            t1 = tic;
            kaf.train(x,y);
            t2 = toc(t1);
            kaf.elapsed = kaf.elapsed + t2;
        end

        function bytes = lastbytes(kaf) % bytes used in last iteration
            m = size(kaf.dict,1);
            m2 = 1;
            bytes = nan; % dummy. (m2 + m*size(kaf.dict,2)); % 8 bytes for double precision
            % [list variables]
        end

    end
end


function findedgedof3(node,edge,range,varargin)
%% FINDEDGEDOF3 highlights some dofs associated to edges
%
% Copyright (C) Long Chen. See COPYRIGHT.txt for details.

hold on
N = size(node,1);
% set up range
if (nargin<=2) || (isempty(range))
    range = (1:size(edge,1))'+N;
end
if islogical(range)
    range = find(range);
end
if size(range,2)>size(range,1)
    range = range';
end
dofrange = range;
range = range - N;
midEdge = (node(edge(range,1),:)+node(edge(range,2),:))/2;
if length(range)<size(edge,1)
    h = line([node(edge(range,1),1); node(edge(range,2),1)],...
             [node(edge(range,1),2); node(edge(range,2),2)],...
             [node(edge(range,1),3); node(edge(range,2),3)],...
             'LineWidth',1.5,'Color','r');
else
    h = plot3(midEdge(:,1),midEdge(:,2),midEdge(:,3),'r.','MarkerSize', 22);
end
if nargin > 3
    if strcmp(varargin{1},'noindex') || strcmp(varargin{1},'index')
        startidx = 2;
    else
        startidx = 1;
    end
    set(h,varargin{startidx:end});
end
if (nargin <=3) || ~(strcmp(varargin{1},'noindex'))
    text(midEdge(:,1)+0.025,midEdge(:,2)-0.025,midEdge(:,3),int2str(dofrange), ...
         'FontSize',14,'FontWeight','bold','Color','k');
end
%% TODO: help and example


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

%%
clear; close all; clc;

%% Syntax
% |[domNode]=amfStruct2xml(amf,fileName,optionStruct);|

%% Description
% This function provides the basis for coding AMF files.

%% Example:

%%
% Create example mesh

[F,V]=geoSphere(2,50); %Faces and vertices
c=[1 0 0]; %RGB Color

volume1_Name='sphere';
material1_Name='sphere material';

%%
cFigure;
title('Model to export to AMF')
gpatch(F,V,c);
axisGeom; camlight headlight;
drawnow;

%%
% Define file name
defaultFolder = fileparts(fileparts(mfilename('fullpath')));
savePath=fullfile(defaultFolder,'data','temp');
fileName=fullfile(savePath,'tempModel.amf');

%%
% Create AMF structure

% Define AMF units and version
amf.ATTR.unit='mm'; %Set units
amf.ATTR.version='1.1'; %Set AMF version

% Add optional metadata here
amf.metadata{1}.ATTR.type='name';
amf.metadata{1}.VAL='Sphere mesh';

amf.metadata{2}.ATTR.type='author';
amf.metadata{2}.VAL='GIBBON';

% object definition

%-> vertices
amf.object{1}.ATTR.id=1;
for q=1:1:size(V,1) %Loop over all vertices
    amf.object{1}.mesh.vertices.vertex{q}.coordinates.x=V(q,1);
    amf.object{1}.mesh.vertices.vertex{q}.coordinates.y=V(q,2);
    amf.object{1}.mesh.vertices.vertex{q}.coordinates.z=V(q,3);
end

%-> volume -> triangle
amf.object{1}.mesh.volume{1}.ATTR.materialid=1;
amf.object{1}.mesh.volume{1}.metadata{1}.ATTR.type='name';
amf.object{1}.mesh.volume{1}.metadata{1}.VAL=volume1_Name;

for q=1:1:size(F,1) %Loop over all triangles (note zero indexing hence -1)
    amf.object{1}.mesh.volume{1}.triangle{q}.v1=F(q,1)-1;
    amf.object{1}.mesh.volume{1}.triangle{q}.v2=F(q,2)-1;
    amf.object{1}.mesh.volume{1}.triangle{q}.v3=F(q,3)-1;
end

% material
amf.material{1}.ATTR.id=1;
amf.material{1}.metadata.ATTR.type='name';
amf.material{1}.metadata.VAL=material1_Name;
amf.material{1}.color.r=c(1);
amf.material{1}.color.g=c(2);
amf.material{1}.color.b=c(3);

%% Export xml
amfStruct2xml(amf,fileName);

%% zip file
[pathName,fileNameClean,c]=fileparts(fileName);
zipName=fullfile(pathName,[fileNameClean,'.zip']);
zip(zipName,fileName);
movefile(zipName,fileName);


%==============================================================================
% This code is part of the Matlab-based toolbox
% FAIR - Flexible Algorithms for Image Registration.
% For details see
% - https://github.com/C4IR and
% - http://www.siam.org/books/fa06/
%==============================================================================
%
%   - data                 Hand, Omega=(0,20)x(0,25),
%   - viewer               viewImage2D
%   - interpolation        splineInter
%   - distance             SSD
%   - regularizer          mbElastic
%   - optimizer            Gauss-Newton
% ===============================================================================

close all, help(mfilename)

% load data, initialize image viewer, interpolator, transformation, distance
setup2DhandData
imgModel('reset','imgModel','splineInter','regularizer','moments','theta',1e-2);
trafo('reset','trafo','affine2D');
distance('reset','distance','SSD');
regularizer('reset','regularizer','mbElastic','alpha',1e3,'mu',1,'lambda',0);

PIRobj = @PIRobjFctn;
PIRopt = optPara('GN');

NPIRobj = @NPIRobjFctn;
NPIRopt = optPara('NPIR-GN')

[yc,wc,his] = MLIR(ML,'PIRobj',PIRobj,'PIRopt',PIRopt,'NPIRobj',NPIRobj,...
  'NPIRopt',NPIRopt,'pause',1,'parametric',1);

% ===============================================================================


function [vertices, faces] = collapseEdgesWithManyFaces(vertices, faces, varargin)
%COLLAPSEEDGESWITHMANYFACES Remove mesh edges adjacent to more than two faces.
%
%   [V2, F2] = collapseEdgesWithManyFaces(V, F)
%   Count the number of faces adjacent to each edge, and collapse the edges
%   adjacent to more than two faces.
%
%
%   Example
%   collapseEdgesWithManyFaces
%
%   See also
%       trimMesh, isManifoldMesh

% ------
% Author: David Legland
% E-mail: david.legland@inrae.fr
% Created: 2019-01-31, using Matlab 9.5.0.944444 (R2018b)
% Copyright 2019-2022 INRA - Cepia Software Platform

verbose = false;
while length(varargin) > 1 && ischar(varargin{1})
    name = varargin{1};
    if strcmpi(name, 'verbose')
        verbose = varargin{2};
    else
        error(['Unknown optional argument: ' name]);
    end
    varargin(1:2) = [];
end

while true
    % compute edge to vertex mapping
    edges = meshEdges(faces);

    % compute number of faces incident to each edge
    edgeFaces = trimeshEdgeFaces(faces);
    edgeFaceDegrees = sum(edgeFaces > 0, 2);

    inds = find(edgeFaceDegrees > 2);

    if isempty(inds)
        break;
    end

    edge = edges(inds(1), :);
    if verbose
        fprintf('remove edge with index %d: (%d, %d)\n', inds(1), edge);
    end
    [vertices, faces] = mergeMeshVertices(vertices, faces, edge);
end

% trim
[vertices, faces] = trimMesh(vertices, faces);


classdef DualUpdater_AugmentedLagrangian < handle

    properties (Access = private)
       dualVariable
       penalty
       constraint
       nConstr
       constraintCase
    end

    methods (Access = public)

        function obj = DualUpdater_AugmentedLagrangian(cParams)
            obj.init(cParams)
        end

        function update(obj)
            obj.updateDual();
        end

        function updatePenalty(obj,rho)
            obj.penalty = rho;
        end

    end

    methods (Access = private)

        function init(obj,cParams)
            obj.constraint     = cParams.constraint;
            obj.constraintCase = cParams.constraintCase;
            obj.dualVariable   = cParams.dualVariable;
            obj.nConstr        = cParams.constraint.nSF;
        end

        function compute(obj,i)
            l   = obj.dualVariable.value(i);
            rho = obj.penalty;
            c   = obj.constraint.value(i);
            l   = l + rho.*c;
            obj.dualVariable.value(i) = l;
        end

        function updateDual(obj)
            for i = 1:obj.nConstr
                switch obj.constraintCase{i}
                    case 'INEQUALITY'
                        isZero = obj.checkDual(i);
                        if isZero
                            obj.dualVariable.value(i) = 0;
                        else
                            obj.compute(i);
                            obj.dualVariable.value(i) = max(0,obj.dualVariable.value(i));
                        end
                    otherwise
                        obj.compute(i);
                end
            end
        end

        function isZero = checkDual(obj,i)
            g      = obj.constraint.value(i,1);
            l      = obj.dualVariable.value(i,1);
            rho    = obj.penalty;
            isZero = g < -l/rho;
        end

    end

end


function setdt (delt)

% this function allows for the specification of the delta-t value
% (delta-t = tt - ut1) to be used in the calculation of sidereal
% time and the terrestrial-to-celestial transformation.  it allows
% these calculations to be performed, correctly, using ut1 as the
% time argument for the earth rotation angle and tdb as the time
% argument for the precession and nutation components.  this
% function, if used, should be called before any function
% related to earth rotation (e.g., sidtim or tercel) for a given
% date.  the value of delta-t specified here will be used until
% explicitly changed.

%  delt = value of delta-t (tt-ut1) in seconds (in)

% note 1:  the computed value of sidereal time, and the equivalent
% earth orientation angles, are relatively insensitive to the value
% of delta-t: up to only ~3 microarcseconds per second of delta-t.
% therefore, for many applications, this function either need not
% be called at all, or can be called just once for a wide range of
% dates (e.g., a year).  if this call is not used, a default
% value of delta-t of 64 seconds is used, which is appropriate to
% 2000.0.

% note 2:  the input time arguments to sidtim and tercel (tjdh and
% tjdl) are expressed in ut1 regardless of whether this call is
% used.

% ported from NOVAS 3.1

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

global dt

dt = delt / 86400.0d0;

end


function [v,psnrall] = gapwnnm_int( y, opt )
%GAPWNNM_INT Integrated GAP and WNNM for snapshot compressive imaging.
%   Note integrated version of GAP-WNNM instead of embedded for
%   acceleration of WNNM with less block-match process for multiple
%   iterations.
%   Reference(s)
%     [1] Y. Liu, X. Yuan, J. Suo, D.J. Brady, and Q. Dai, Rank Minimization
%         for Snapshot Compressive Imaging, preprint, 2018.
%   Code credit
%     Xin Yuan, Bell Labs, xyuan@bell-labs.com, initial version Jul 2,
%       2015.
%     Yang Liu, Tsinghua University, y-liu16@mails.tsinghua.edu.cn, last
%       update Jul 13, 2018.
%   See also GAPDENOISE.
if nargin<2
    opt = [];
end
% [0] default parameter configuration, to be specified
A  = @(x) M_func(x);
At = @(z) Mt_func(z);
if isfield(opt,'Mfunc'),  A  = @(x) opt.Mfunc(x);  end
if isfield(opt,'Mtfunc'), At = @(z) opt.Mtfunc(z); end
% Phisum   = ;
% v0       = At(y); % start point (initialization of iteration)
lambda   = 1;     % correction coefficiency
maxiter  = 300;     % maximum number of iteration
acc      = 1;       % enable acceleration
sigma    = 10/255;  % noise deviation
flag_iqa = true;    % flag of showing image quality assessments
save_iter_image = false; % flag of saving all the images of the iteration
                         %  process (true only necessary)
                         %  require assigned directory opt.iter_image_dir

if isfield(opt,'Phisum'),     Phisum = opt.Phisum;   end
if isfield(opt,'v0'),             v0 = opt.v0;       end
if isfield(opt,'lambda'),   lambda   = opt.lambda;   end
if isfield(opt,'maxiter'),   maxiter = opt.maxiter;  end
if isfield(opt,'acc'),           acc = opt.acc;      end
if isfield(opt,'sigma'),       sigma = opt.sigma;    end
if isfield(opt,'flag_iqa'), flag_iqa = opt.flag_iqa; end
if isfield(opt,'save_iter_image'), save_iter_image = opt.save_iter_image; end

if ~exist('v0','var') || isempty(v0)
    v0 = At(y); % start point (initialization of iteration)
end
y1 = zeros(size(y),'like',y);
psnrall = []; % return empty with no ground truth
% ssimall = []; % return empty with no ground truth
% [1] start iteration
v = v0; % initialization
% opt.sigma = sigma;
k = 1; % current number of iteration
nonlocalarr = uint32.empty;
vindarr     = uint8.empty;
for isig = 1:length(maxiter)
    opt.sigma = sigma(isig);
    for iter = 1:maxiter(isig)
        for ii = 1:1
            % [1.1] Euclidean projection
            yb = A(v);
            if acc % enable acceleration
                y1 = y1+(y-yb);
                v = v+lambda*(At((y1-yb)./Phisum)); % v=v+lambda*(At*A)^-1*At*dy
            else
                v = v+lambda*(At((y-yb)./Phisum));
            end
        end
        % [1.2] Denoising to match the video prior
        % WNNM video denoising (MATLAB-style matrix version)
        % v = wnnm_vdenoise(v,[],opt); % opt.sigma
        noisyv = v;
        para = vdefparaconf(opt); % default parameter configuration

        [nrow,ncol,nframe] = size(noisyv); % grayscale video (color todo)
        % [1] pre-calculation of the indexes of the neighbors within the search
        %     window
        [neighborindarr,neighbornumarr,selfindarr] = neighborind([nrow ncol],para);

        % [2] WNNM denoisng for several iterations
        estv = noisyv;
        for iit = 1:para.iternum
            % correction between adjacent iterations
            if ~para.adaptboost %
                estv = estv + para.delta*(noisyv-estv);
            else % adaptive boosting for WNNM-based denoising
                Eestv = mean(abs(estv(:)).^2);
                Enoise  = para.abeta*abs(para.nsigma^2-var(noisyv(:)-estv(:)));
                rho = sqrt(Eestv)/(sqrt(Eestv)+sqrt(max(Eestv-Enoise,0)));
                fprintf('    Iteration % 2d, rho = %.3f.\n',iit,rho);
                estv = estv + (1-rho)*(noisyv-estv);
            end
            % use all frames for denoising
            curvall = zeros(nrow,ncol,nframe,nframe);
            curfall = zeros(nrow,ncol,nframe,nframe);

            % [2.1] video to patches
            [rawpatchmat,nsigmamat] = v2patch(estv,noisyv,para);
            blockmatch_period = para.blockmatch_period;
            % inner loop to reuse the block-matching results
                if mod(k,blockmatch_period) == 1 % block matching periodically
                    nonlocalarr = uint32.empty;
                    vindarr     = uint8.empty;
                    parfor (iframe = 1:nframe,nframe) % maximum nframe parpool for optimal
                    % [2.2] calculate the patches with non-local similarity for each
                    %       key patch
                    [curnonlocalarr,curvindarr] = vblockmatch(iframe,rawpatchmat,...
                        neighborindarr,neighbornumarr,selfindarr,para);
                    nonlocalarr(:,:,iframe) = curnonlocalarr;
                    vindarr(:,:,iframe) = curvindarr;
                    end
                end
                if iit==1 % initial noise level of each patch
                    nsigmamat = para.nsigma*ones(size(nsigmamat));
                end
            % frame-wise denosing using parfor instead of for to get accelerated
            % performance, requiring Parallel Computing Toolbox.
            parfor (iframe = 1:nframe,nframe) % maximum nframe parpool for optimal
            % for iframe = 1:nframe % maximum nframe parpool for optimal
                % use all frames for denoising
                % inner loop to reuse the block-matching results
                % if mod(k,blockmatch_period) == 1 % block matching periodically
                %     % [2.2] calculate the patches with non-local similarity for each
                %     %       key patch
                %     [nonlocalarr(:,:,iframe),vindarr(:,:,iframe)] = vblockmatch(iframe,rawpatchmat,...
                %         neighborindarr,neighbornumarr,selfindarr,para);
                % end
                curnonlocalarr = nonlocalarr(:,:,iframe);
                curvindarr = vindarr(:,:,iframe);
                % [2.3] patch estimation by means of WNNM
                [estpatchmat,frqpatchmat] = vpatchestimate(iframe,curnonlocalarr,...
                    curvindarr,rawpatchmat,nsigmamat,selfindarr,para);
                % [2.4] aggregate overlapped patches to the whole image
                [curv,curf] = patch2v(estpatchmat,frqpatchmat,size(noisyv),...
                    para.patchsize);
                % use all frames for denoising
                curvall(:,:,:,iframe) = curv;
                curfall(:,:,:,iframe) = curf;
            end
            % use all frames for denoising
            v_ = sum(curvall,ndims(curvall));
            f_ = sum(curfall,ndims(curfall));

            estv = v_./(f_+eps);

            if mod(iit-1,para.innerloop)==0
                % % [2.2] calculate the patches with non-local similarity for
                % %       each key patch
                % [nonlocalarr,vindarr] = vblockmatch(cframe,rawpatchmat,...
                %     neighborindarr,neighbornumarr,selfindarr,para);
                % less non-local patches with lower noise level
                para.patchnum = para.patchnum-10;
            end
            % [1.4] save and show intermediate results of psnr and ssim
            if flag_iqa && isfield(opt,'orig') && (~isempty(opt.orig))
                psnrall(k) = psnr(double(estv),double(opt.orig)); % record all psnr
                % ssimall(k) = ssim(double(estv),opt.orig); % record all ssim
                if (mod(k,5)==0)
                    fprintf('  GAP-%s iteration % 4d, sigma %.1f, PSNR %2.2f dB.\n',...
                        upper(opt.denoiser),k,opt.sigma*255,psnrall(k));
                end
                if save_iter_image % save all the images of the iteration process
                    MAXB = opt.MAXB;
                    % save each frame in the assigned directory
                    nim = size(estv,ndims(estv)); % number of frames in the video
                    for iim = 1:nim
                        im = estv(:,:,iim);
                        impsnr = psnr(im,opt.orig(:,:,iim));
                        imssim = ssim(im,opt.orig(:,:,iim));
                        if k == 1 % mkdir for the first iteration
                            subdir = sprintf('%s/frame%02d',opt.iter_image_dir,iim); % frame-wise
                            if ~exist(subdir,'dir')
                                mkdir(subdir);
                            end
                        end
                        imwrite(uint8(im*MAXB),sprintf('%s/frame%02d/frame%02d_iter%03d_sigma%.1f_psnr%2.2f_ssim%.4f.png',...
                            opt.iter_image_dir,iim,iim,k,opt.sigma*MAXB,impsnr,imssim));
                    end
                end
            end
            k = k+1;
        end % WNNM loop [iternum]
        v = estv;
        % % [1.3] update noise standard deviation
        % nsigma = eta*sqrt(abs(sigma^2-var(v(:)-v0(:))));
        % opt.sigma = nsigma;

    end % GAP loop [maxiter]
end % sigma loop [length(sigma)]

end


% Codes for CVPR-15 work `Face Alignment by Coarse-to-Fine Shape Searching'
% Any question please contact Shizhan Zhu: zhshzhutah2@gmail.com
% Released on July 25, 2015

function [resultPose,weight] = poseVoting(resultPose_samples,voteIterTot)
% resultPose_samples : M * dim * samplings
% voteIterTot : scalar
%
% resultPose : M * dim
% weight : M * samplings

if ~exist('voteIterTot','var')
    voteIterTot = 100;
end;
M = size(resultPose_samples,1);
dim = size(resultPose_samples,2);
samplings = size(resultPose_samples,3);
% assert(dim <= 3);
resultPose = zeros(M,dim);
weight = zeros(M,samplings);
parfor k = 1:M
    candidate = reshape(resultPose_samples(k,:,:),dim,samplings);
    d = dist(candidate);
    d = d / mean(d(:));
    ed = exp(-d.^2);
    for i = 1:size(ed,1), ed(i,i) = 0;end;
    w = zeros(samplings,voteIterTot);
    w(:,1) = 1 / samplings;
    for i = 1:voteIterTot-1
        for j = 1:samplings, w(:,i+1) = w(:,i+1) + ed(:,j).*w(j,i);end;
        w(:,i+1) = w(:,i+1) / sum(w(:,i+1));
    end;
    weight(k,:) = w(:,voteIterTot)';
    resultPose(k,:) = w(:,voteIterTot)' * candidate';
end;

end


function [C_df,Df] = extract_DF_F(Y,A,C,P,options,AY)

% extract DF/F signals after performing NMF
% inputs:  Y raw data (d X T matrix, d # number of pixels, T # of timesteps)
%          A matrix of spatial components (d x K matrix, K # of components)
%          C matrix of temporal components (K x T matrix)
%          P neuron structure, used to read the baseline activity for each
%                    component of C
%          options structure used for specifying method for determining DF
%           default method is the median of the trace. By changing
%           options.df_prctile an arbitray percentile can be used (between 0 and 100).
%           a moving window can also be established by specifying options.df_window
%          AY pass is the product A'*Y otherwise compute it

% outputs:  C_df temporal components in the DF/F domain
%           Df   background for each component to normalize the filtered raw data

% Written by:
% Eftychios A. Pnevmatikakis, Simons Foundation, 2016

%memmaped = isobject(Y);
defoptions = CNMFSetParms;
if nargin < 5 || isempty(options)
    options = defoptions;
end
if ~isfield(options,'df_prctile') || isempty(options.df_prctile)
    options.df_prctile = defoptions.df_prctile;
end
if ~isfield(options,'df_window') || isempty(options.df_window)
    options.df_window = defoptions.df_window;
end
if ~isfield(options,'full_A') || isempty(options.full_A); full_A = defoptions.full_A; else full_A = options.full_A; end

[K,T] = size(C);

if ~exist('AY','var')
    AY = mm_fun(A,Y);
end

Bas = zeros(K,T);

if ~(nargin < 5 || isempty(P))
    bas_val = cell2mat(P.b);
    Ntr = size(bas_val,2);
    if Ntr > 1
        ln = diff(P.cs_frtrs);
        for i = 1:Ntr
            Bas(:,:,P.cs_frtrs(i)+1:P.cs_frtrs(i+1)) = repmat(bas_val(:,i),1,ln(i));
        end
    else
        Bas = repmat(bas_val,1,T);
    end
end

nA = sqrt(sum(A.^2))';
AA = A'*A;
AA(1:K+1:end) = 0;

Cf = bsxfun(@times,C - Bas,nA(:).^2);

C2 = AY - AA*C;

if isempty(options.df_window) || (options.df_window > size(C,2))
    if options.df_prctile == 50
        Df = median(C2,2);
    else
        Df = prctile(C2,options.df_prctile,2);
    end
    C_df = bsxfun(@times,Cf,1./Df(:));
else
    if options.df_prctile == 50
        if verLessThan('matlab','2015b')
            warning('Median filtering at the boundaries might be inaccurate due to zero padding.')
            Df = medfilt1(C2,options.df_window,[],2);
        else
            Df = medfilt1(C2,options.df_window,[],2,'truncate');
        end
    else
        Df = zeros(size(C2));
        for i = 1:size(Df,1);
            df_temp = running_percentile(C2(i,:), options.df_window, options.df_prctile);
            Df(i,:) = df_temp(:)';
        end
    end
    C_df = Cf./Df;
end


width = 16;
height = 12;
fontsize = 9;
plot_folder = 'projects/seminar/output/';
% filename = ['data/eco/plugs/02/09/2012-07-13.mat'];
day = '2012-07-13';
household = 02;
dataset = 'eco';
plot_title = 'Laptop consumption - 2012-07-13';
plot_filename = 'laptop-2012-07-13';
appliance_id = getApplianceID('Laptop');
granularity = 1;
appliance_consumption = read_plug_data(dataset, ...
                                household, ...
                                appliance_id, ...
                                evaluation_days, ...
                                granularity);

idx_start = 1;
idx_stop = 86400;

% total_consumption = read_smartmeter_data(dataset, ...
%                                     num2str(household, '%02d'), ...
%                                     evaluation_days, ...
%                                     granularity, ...
%                                     'powerallphases');

%% plot
if ~exist(plot_folder, 'dir')
    mkdir(plot_folder);
end
fig = figure;
xvals = datenum(day)+(idx_start:idx_stop)/86400;
plot(xvals, appliance_consumption);
% dateformat: http://ch.mathworks.com/help/matlab/ref/datetick.html#btpnuk4-1
% dateFormat = 15;
dateFormat = 'HH:MM AM';
datetick('x',dateFormat);
% legend(['Smart meter', appliance_names_inferred], 'Location', 'NorthWest');
title(plot_title);
ylabel('Power [W]');
xlabel('Time of day');
fig = make_report_ready(fig, 'size', [width, height], 'fontsize', fontsize);
saveas(fig, [plot_folder, plot_filename, '.png'], 'png');
print('-depsc2', '-cmyk', '-r600', [plot_folder, plot_filename, '.eps']);
close(fig);


function roff = i4cvv_offset ( m, nr )

%*****************************************************************************80
%
%% I4CVV_OFFSET determines the row offsets of an I4CVV.
%
%  Discussion:
%
%    An I4CVV is a "vector of vectors" of I4's.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    04 December 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer M, the number of rows in the array.
%
%    Input, integer NR(M), the row sizes.
%
%    Output, integer ROFF(M+1), the row offsets.
%
  roff = zeros ( m + 1, 1 );

  roff(1) = 0;
  for i = 1 : m
    roff(i+1) = roff(i) + nr(i);
  end

  return
end


function y = bessels(x, type, varargin)
    lut_table = [];
    lut_signs = [];
    if numel(varargin) >= 2
        lut_table = varargin{1};
        lut_signs = varargin{2};
    end
    if strcmp(type, 'I0')

    elseif strcmp(type, 'logI0')
        idxs = x >= 120;
        idxm = x < 0;
        y = x*0;
        y(idxs) = x(idxs) - 1/2 * log(2*pi*x(idxs));

        idd = (~idxs) & (~idxm);
        if ~isempty(lut_table)
            y(idd) = lut_table(round(x(idd) * 10^lut_signs) + 1);
        else
            y(idd) = log(besseli(0, x(idd)));
        end

    elseif strcmp(type, 'I1I0')
        idxs = x >= 120;
        idxm = x < 0;
        y = x*0;
        y(idxs) = 1;

        idd = (~idxs) & (~idxm);
        if ~isempty(lut_table)
            y(idd) = lut_table(round(x(idd) * 10^lut_signs) + 1);
        else
            y(idd) = besseli(1, x(idd))./besseli(0, x(idd));
        end

    end
end


% This script evaluates the percentage of space time covered by
%alarms
%
re = [];

% Stefan Wiemer    4/95

report_this_filefun(mfilename('fullpath'));

abo = abo2;

for tre2 = min(abo(:,4)):0.1:max(abo(:,4)-0.1)
    abo = abo2;
    abo(:,5) = abo(:,5)* par1/365 + a(1,3);
    l = abo(:,4) >= tre2;
    abo = abo(l,:);
    l = abo(:,3) < tresh;
    abo = abo(l,:);
    hold on

    % space time volume covered by alarms
    if isempty(abo) == 1
        Va = 0;
    else
        Va = sum(pi*abo(:,3).^2)*iala;
    end

    % All space time
    [len, ncu] = size(cumuall);

    r = loc(3,:);
    %r = reshape(cumuall(len,:),length(gy),length(gx));
    %r=reshape(normlap2,length(yvect),length(xvect));
    l = r < tresh;
    V = sum(pi*r(l).^2*(teb-t0b));
    disp([' Zalarm = ' num2str(tre2)])
    disp([' =============================================='])
    disp([' Total space-time volume (R<Rmin):  ' num2str(V)])
    disp([' Space-time volume covered with alarms (R<Rmin):  ' num2str(Va)])
    disp([' Percent of total covered with alarms (R<Rmin):  ' num2str(Va/V*100) ' Percent' ])

    re = [re ; tre2 Va/V*100 ];
end   % for tre2

figure

matdraw
axis off

uicontrol('Units','normal',...
    'Position',[.0 .65 .08 .06],'String','Save ',...
     'Callback',{@calSave9, re(:,1), re(:,2)})

rect = [0.20,  0.10, 0.70, 0.60];
axes('position',rect)
hold on
pl = semilogy(re(:,1),re(:,2),'r');
set(pl,'LineWidth',1.5)
pl = semilogy(re(:,1),re(:,2),'ob');
set(pl,'LineWidth',1.5,'MarkerSize',10)
set(gca,'YScale','log')

set(gca,'visible','on','FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold',...
    'FontWeight','bold','LineWidth',1.5,...
    'Box','on')
grid

ylabel('Va/Vtotal in %')
xlabel('Zalarm ')
watchoff


function [varargout] = routlm(varargin)

% ROUTLM computes the projection of a point from its la/mu parameters
% these equal the "Barycentric" coordinates
%
% Use as
%   [proj] = routlm(v1, v2, v3, la, mu)
% where v1, v2 and v3 are three vertices of the triangle

% Copyright (C) 2002-2009, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This is the native MATLAB implementation.
% The mex file is many times faster and is therefore preferred.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [proj] = routlm(v1, v2, v3, la, mu);
% proj = (1-la-mu)*v1 + la*v2 + mu*v3;

% compile the missing mex file on the fly
% remember the original working directory
pwdir = pwd;

% determine the name and full path of this function
funname = mfilename('fullpath');
mexsrc  = [funname '.c'];
[mexdir, mexname] = fileparts(funname);

try
  % try to compile the mex file on the fly
  warning('trying to compile MEX file from %s', mexsrc);
  cd(mexdir);

  if ispc
    mex -I. -c geometry.c
    mex -I. -c routlm.c ; mex routlm.c routlm.obj geometry.obj
  else
    mex -I. -c geometry.c
    mex -I. -c routlm.c ; mex -o routlm routlm.o geometry.o
  end

  cd(pwdir);
  success = true;

catch
  % compilation failed
  disp(lasterr);
  error('could not locate MEX file for %s', mexname);
  cd(pwdir);
  success = false;
end

if success
  % execute the mex file that was just created
  funname   = mfilename;
  funhandle = str2func(funname);
  [varargout{1:nargout}] = funhandle(varargin{:});
end


filename='CantileverBeam_Triangle_Linear_Fine';
ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance'};
weights = [1];
constraint = {'volumeConstraint'};
optimizer = 'SLERP';
incrementFactor = 1;
designVariable = 'LevelSet';
filterType = 'P1';

nsteps = 1;
Vfrac_final = 0.4;
optimality_final =1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-3;
constr_initial = 1e-3;

TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;


function [ obblist, labellist ] = visualizeReloffset( leafreps, labeldefs, dim )
%VISUALIZERELPOS
% this function only considers the artificial dataset: exact one bed, no
% more than two objects in each category
classnum = 7;
if(dim==2)
    % turn the relpos into 3D
    nleafreps = zeros(classnum*(dim+1)*2+classnum,size(leafreps,2));
    for i = 1:classnum
        nleafreps((i-1)*(dim+1)*2+1,:) = leafreps((i-1)*dim*2+1,:);
        nleafreps((i-1)*(dim+1)*2+3,:) = leafreps((i-1)*dim*2+2,:);
        nleafreps((i-1)*(dim+1)*2+4,:) = leafreps((i-1)*dim*2+3,:);
        nleafreps((i-1)*(dim+1)*2+6,:) = leafreps((i-1)*dim*2+4,:);
    end
    nleafreps(end-classnum+1:end,:) = leafreps(end-classnum+1:end,:);
    leafreps = nleafreps;
end

offsetnum = 6;
objnum = size(leafreps,2);
relvecs = leafreps(1:classnum*offsetnum,:);
labelvecs = leafreps(classnum*offsetnum+1:end,:);

% recon the size
objsizelist = zeros(offsetnum/2,objnum);
for i = 1:objnum
    rv = relvecs(:,i);

    sizelist = [];
    for j = 1:classnum
        rvj = rv((j-1)*offsetnum+1:j*offsetnum);
        if(~all(rvj==0))
            sizelist = [sizelist,rvj(1:offsetnum/2)-rvj(offsetnum/2+1:end)];
        end
    end
    si = mean(sizelist');

    objsizelist(:,i)=si(:);
end

% assume there's only one bed and located in [0,0]
bed_label = labeldefs(:,1);
dist = zeros(objnum,1);
for i = 1:objnum
    label = labelvecs(:,i);
    dis = norm(label-bed_label,2);
    dist(i) = dis;
end
[~,I] = min(dist);
bed_index = I;

obblist = zeros(12,objnum);
info = relvecs(1:offsetnum,:);% we only use the relpos of each object relative to the bed, based on the assumption
% actually, the redundancy will cause mess.
bedminp = [0;0;0]-objsizelist(:,bed_index);
anchor = [bedminp/2;bedminp/2];
for i = 1:objnum
    bbox = info(:,i)+anchor;
    maxp = bbox(1:offsetnum/2);
    minp = bbox(offsetnum/2+1:end);

%     maxp = [maxp(1);0.1;maxp(2)];
%     minp = [minp(1);0;minp(2)];
    cent = (maxp+minp)/2;
    orient = [1;0;0;0;1;0];
    s = maxp-minp;
    obb = [cent;orient;s];
    obblist(:,i) = obb;
end

% recon the labellist
tlabellist = {'bed','stand','lamp','rug','ottoman','person','floor'};
labellist = {};
for i = 1:objnum
    label = labelvecs(:,i);
    dist = zeros(classnum,1);
    for j = 1:classnum
        clabel = labeldefs(:,j);
        dis = norm(label-clabel,2);
        dist(j) = dis;
    end
    [~,I] = min(dist);
    labellist{length(labellist)+1} = tlabellist{I};
end

end


function [Phi,dim1,dim2] = spm_def2sparse(PY,PI)
% Generate a sparse matrix encoding a deformation
% [Phi,dim1,dim2] = spm_def2sparse(PY,PI)
% PY - Filename of deformation field
% PI - Filename of image defining field of view etc
%_______________________________________________________________________
% Copyright (C) Wellcome Trust Centre for Neuroimaging (2009)

% John Ashburner
% $Id: spm_def2sparse.m 4861 2012-08-24 15:56:39Z john $

NY=nifti(PY);
NI=nifti(PI);

dim1 = [size(NY.dat) 1 1];
dim1 = dim1(1:3);

dim2 = [size(NI.dat) 1 1];
dim2 = dim2(1:3);

X1=NY.dat(:,:,:,1,1);
X2=NY.dat(:,:,:,1,2);
X3=NY.dat(:,:,:,1,3);

M = inv(NI.mat);

Y1=M(1,1)*X1+M(1,2)*X2+M(1,3)*X3+M(1,4);
Y2=M(2,1)*X1+M(2,2)*X2+M(2,3)*X3+M(2,4);
Y3=M(3,1)*X1+M(3,2)*X2+M(3,3)*X3+M(3,4);

if false
    % Nearest Neighbour
    fY1 = (round(Y1));
    fY2 = (round(Y2));
    fY3 = (round(Y3));
    I   = find(fY1>=1 & fY1<=dim2(1) & fY2>=1 & fY2<=dim2(2) & fY3>=1 & fY3<=dim2(3));
    J   = fY1(I) + dim2(1)*(fY2(I)-1 + dim2(2)*(fY3(I)-1));
    Phi = sparse(I,J,1,prod(dim1),prod(dim2));
else
    % Trilinear
    fY1 = (floor(Y1));
    fY2 = (floor(Y2));
    fY3 = (floor(Y3));

    I   = find(fY1>=1 & fY1<=dim2(1) & fY2>=1 & fY2<=dim2(2) & fY3>=1 & fY3<=dim2(3));
    J   = fY1(I) + dim2(1)*(fY2(I)-1 + dim2(2)*(fY3(I)-1));
    S   = (1-Y1+fY1).*(1-Y2+fY2).*(1-Y3+fY3);
    S   = S(I);
    Phi = sparse(I,J,S,prod(dim1),prod(dim2));

    I   = find(fY1>=0 & fY1<=dim2(1)-1 & fY2>=1 & fY2<=dim2(2) & fY3>=1 & fY3<=dim2(3));
    J   = fY1(I)+1 + dim2(1)*(fY2(I)-1 + dim2(2)*(fY3(I)-1));
    S   = (Y1-fY1).*(1-Y2+fY2).*(1-Y3+fY3);
    S   = S(I);
    Phi = Phi + sparse(I,J,S,prod(dim1),prod(dim2));

    I   = find(fY1>=1 & fY1<=dim2(1) & fY2>=0 & fY2<=dim2(2)-1 & fY3>=1 & fY3<=dim2(3));
    J   = fY1(I) + dim2(1)*(fY2(I) + dim2(2)*(fY3(I)-1));
    S   = (1-Y1+fY1).*(Y2-fY2).*(1-Y3+fY3);
    S   = S(I);
    Phi = Phi + sparse(I,J,S,prod(dim1),prod(dim2));

    I   = find(fY1>=0 & fY1<=dim2(1)-1 & fY2>=0 & fY2<=dim2(2)-1 & fY3>=1 & fY3<=dim2(3));
    J   = fY1(I)+1 + dim2(1)*(fY2(I) + dim2(2)*(fY3(I)-1));
    S   = (Y1-fY1).*(Y2-fY2).*(1-Y3+fY3);
    S   = S(I);
    Phi = Phi + sparse(I,J,S,prod(dim1),prod(dim2));

    I   = find(fY1>=1 & fY1<=dim2(1) & fY2>=1 & fY2<=dim2(2) & fY3>=0 & fY3<=dim2(3)-1);
    J   = fY1(I) + dim2(1)*(fY2(I)-1 + dim2(2)*fY3(I));
    S   = (1-Y1+fY1).*(1-Y2+fY2).*(Y3-fY3);
    S   = S(I);
    Phi = Phi + sparse(I,J,S,prod(dim1),prod(dim2));

    I   = find(fY1>=0 & fY1<=dim2(1)-1 & fY2>=1 & fY2<=dim2(2) & fY3>=0 & fY3<=dim2(3)-1);
    J   = fY1(I)+1 + dim2(1)*(fY2(I)-1 + dim2(2)*fY3(I));
    S   = (Y1-fY1).*(1-Y2+fY2).*(Y3-fY3);
    S   = S(I);
    Phi = Phi + sparse(I,J,S,prod(dim1),prod(dim2));

    I   = find(fY1>=1 & fY1<=dim2(1) & fY2>=0 & fY2<=dim2(2)-1 & fY3>=0 & fY3<=dim2(3)-1);
    J   = fY1(I) + dim2(1)*(fY2(I) + dim2(2)*fY3(I));
    S   = (1-Y1+fY1).*(Y2-fY2).*(Y3-fY3);
    S   = S(I);
    Phi = Phi + sparse(I,J,S,prod(dim1),prod(dim2));

    I   = find(fY1>=0 & fY1<=dim2(1)-1 & fY2>=0 & fY2<=dim2(2)-1 & fY3>=0 & fY3<=dim2(3)-1);
    J   = fY1(I)+1 + dim2(1)*(fY2(I) + dim2(2)*fY3(I));
    S   = (Y1-fY1).*(Y2-fY2).*(Y3-fY3);
    S   = S(I);
    Phi = Phi + sparse(I,J,S,prod(dim1),prod(dim2));
end


function test_bug2220(datainfo)

% MEM 2gb
% WALLTIME 00:20:00
% DEPENDENCY ft_preprocessing ft_preproc_padding preproc

%load('C:\Users\jorhor\Downloads\bugdatafile.mat')
cfg = [];
cfg.baselinewindow = [-.5 0];
cfg.demean = 'yes';

data = [];
data.label  = {'chan'};
data.fsample = 512;

for tr=1:10
  data.time{tr}    = linspace(-1, 2, 3*data.fsample+1);
  data.trial{tr}   = rand(1, length(data.time{tr})) .^ 2;
end

tmpdata = ft_preprocessing(cfg, data);

tbase = tmpdata.time{1} >= cfg.baselinewindow(1) & tmpdata.time{end} <= cfg.baselinewindow(2);

[ok, msg] = isalmostequal(sum(tmpdata.trial{1}(:, tbase), 2), zeros(length(data.label), 1),'abstol',eps*100);

if ~ok
  error('baseline not zero: %s', msg{1});
end

%% test with data on disk
if nargin<1
  datainfo = ref_datasets;
end

for k = 1:numel(datainfo)
  dataset = datainfo(k);

  cfg            = [];
  cfg.dataset    = fullfile(dataset.origdir,'original',dataset.type,dataset.datatype,'/',dataset.filename);

  % get header and event information
  if ~isempty(dataset.dataformat)
    hdr   = ft_read_header(cfg.dataset, 'headerformat', dataset.dataformat);
    event = ft_read_event(cfg.dataset, 'eventformat', dataset.dataformat);

    cfg.dataformat   = dataset.dataformat;
    cfg.headerformat = dataset.dataformat;
  else
    hdr   = ft_read_header(cfg.dataset);
    event = ft_read_event(cfg.dataset);
  end

  % create 10 1-second trials to be used as test-case
  begsample = ((1:10)-1)*round(hdr.Fs) + 1;
  endsample = ((1:10)  )*round(hdr.Fs);
  offset    = zeros(1,10);

  cfg.trl   = [begsample(:) endsample(:) offset(:)];
  sel       = cfg.trl(:,2)<=hdr.nSamples*hdr.nTrials;
  cfg.trl   = cfg.trl(sel,:);

  cfg.continuous     = 'yes';
  cfg.demean         = 'yes';
  cfg.baselinewindow = [0 0.5];
  if strcmp(dataset.type, 'meg') || strcmp(dataset.type, 'eeg')
    cfg.channel      = dataset.type;
  else
    cfg.channel      = 'all';
  end
  data               = ft_preprocessing(cfg);

  tbase = data.time{1} >= cfg.baselinewindow(1) & data.time{end} <= cfg.baselinewindow(2);
 [ok, msg] = isalmostequal(sum(data.trial{1}(1:end, tbase), 2), zeros(length(data.label), 1),'abstol',abs(.0001 * mean(data.trial{1}(:))));

  if ~ok
    error('baseline not zero: %s', msg{1});
  end

end


function [output_canvas] = image_blending_linear(warped_img1,warped_img2)

    c1omask{1} = imfill(im2bw(uint8(warped_img1), 0),'holes');
    c1omask{2} = imfill(im2bw(uint8(warped_img2), 0),'holes');

    c1out{1} = double(warped_img1);
    c1out{2} = double(warped_img2);

    for i = 1 : 2
        if i == 1
            out = c1out{1};
            out_mask = c1omask{1};
            % center of out
            [r, c] = find(c1omask{1}(:, :, 1));
            out_center = [mean(r) mean(c)];
        else % blend out and c1out{i}
            % center of c1out{i}
            [r, c] = find(c1omask{i}(:, :, 1));
            out_i_center = [mean(r) mean(c)];
            % compute weighted mask
            vec = out_i_center - out_center; % vector from out_center to out_i_center
            intsct_mask = c1omask{i}(:, :, 1) & out_mask(:, :, 1); % 1 channel

            [r, c] = find(intsct_mask(:, :, 1));
            idx = sub2ind(size(c1omask{i}(:, :, 1)), r, c);
            out_wmask = zeros(size(c1omask{i}(:, :, 1)));
            proj_val = (r - out_center(1))*vec(1) + (c- out_center(2))*vec(2); % inner product
            out_wmask(idx) = (proj_val - (min(proj_val)+(1e-3))) / ...
                             ((max(proj_val)-(1e-3)) - (min(proj_val)+(1e-3))); % weight map (of overlapped area) for c1out{i}, 1 channel
            % blending
            mask1 = out_mask(:, :, 1)&(out_wmask==0);
            mask2 = out_wmask;
            mask3 = c1omask{i}(:, :, 1)&(out_wmask==0);
            mask1 = cat(3, mask1, mask1, mask1); mask2 = cat(3, mask2, mask2, mask2); mask3 = cat(3, mask3, mask3, mask3);
            out = out.*(mask1+(1-mask2).*(mask2~=0)) + c1out{i}.*(mask2+mask3);
            % update
            out_mask = out_mask | c1omask{i};
            out_center = out_i_center; % update out_center by assign center of c1out{i}
        end
    end

    output_canvas = uint8(out);
end


function res = lt(a,b)
%LT           Implements  a < b  for gradients, compares only a.x and b.x
%

% written  10/16/98     S.M. Rump
% modified 12/18/02     S.M. Rump  complex comparison
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
%

  if ~isa(a,'gradient')
    if isreal(a) & isreal(b.x)
      res = ( a<b.x );
    else
      res = ( real(a)<real(b.x) ) & ( imag(a)<imag(b.x) );
    end
  elseif ~isa(b,'gradient')
    if isreal(a.x) & isreal(b)
      res = ( a.x<b );
    else
      res = ( real(a.x)<real(b) ) & ( imag(a.x)<imag(b) );
    end
  else
    if isreal(a.x) & isreal(b.x)
      res = ( a.x<b.x );
    else
      res = ( real(a.x)<real(b.x) ) & ( imag(a.x)<imag(b.x) );
    end
  end


function outcome = Convertion(Average,G,g,last_gen,change_threshold)
% Conversion condition for enter next stage

%------------------------------- 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".
%--------------------------------------------------------------------------

    if (G-g > last_gen) && (max(abs(Average(G,:)-Average(G-last_gen,:)))<=change_threshold)
        outcome = true;
    else
        outcome = false;
    end
end


function slide21

	figure('units','normalized',...
		'position',[0.1, 0.1, 0.7, 0.7],...
		'menubar','none');

	axes('units','normalized',...
		'position',[0.5, 0.5, 0.4, 0.4])

	x1 = 3;
	x2 = 5;
	y1 = 2;
	y2 = 3;

	patch([x1,x1,x2,x2],[y1,5,5,y1],[1,1,1]); % tank patch
	p1 = patch([x1,x1,x2,x2],[y1,y2,y2,y1],[0,0,1]); % liquid patch

	axis([0 6 0 6])

	t = 1;
	while true

		t = t + 0.05;

		% the upper left corner plots a cosine while the upper right corner
		% plots a sine function
		y = [y1, y1 + 2 + 0.25*cos(t),  y1 + 2 + 0.25*sin(t), y1];

		set(p1,'ydata',y)

		drawnow

	end

end


function [Raw_data Im_data] = ssfpReadData(fname, Frames, frac_ks)
% function [Raw_data Im_data] = ssfpReadData(fname, Frames, [frac_ks=5/8]);
%
%	Function reads selected data from a P-file
%
%
%	INPUT:
%		fname   = P file name.
%	    Frames  = Number of temporal frames collected
%       frac_ks = fraction of K-space traversed. [default 5/8]
%
%	EXAMPLE:
%	  [R I] = getrawdata('P00000.7', 101);	% Read full p-file
%
%	Thomas S. John -- Feb 2009.
if notDefined('frac_ks'),   frac_ks = 0.625;        end

verbose = prefsVerboseCheck;

%% load raw data from Pfile
if verbose >= 1
    fprintf('[%s]: Loading Raw Data from %s. \t(%s) \n', mfilename, fname, datestr(now));
end

A = rawloadX(fname);

%% organize/recon data into image space
if verbose >= 1
    fprintf('[%s]: Reconning %s. \t(%s) \n', mfilename, fname, datestr(now));
end

[Raw_data Im_data] = organize_data(A,Frames);

%% construct final images from partial K-space acquisitions
if verbose >= 1
    fprintf('[%s]: Homodyne recon for %s. \t(%s) \n', ...
            mfilename, fname, datestr(now));
end

[RO PE Slices_per_frame Frames] = size(Raw_data);

for f=1:Frames
    for s=1:Slices_per_frame
        Im_data(:,:,s,f) = partial_k(Raw_data(:,:,s,f),frac_ks,RO,PE);
    end
end

% up/down rows flip
Im_data = Im_data(RO:-1:1,:,:,:);

return


%% Fibres
%
%%
%
% The set of all rotations that rotate a certain vector u onto a certain
% vector v define a fibre in the rotation space. A discretisation of such a
% fibre is defined by

u = xvector;
v = yvector;
rot = rotation(fibre(u,v))


filename='Cantileverbeam_Hexahedra_Linear_Structured';
ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'holes';
cost = {'compliance'};
weights = [1];
constraint = {'volumeConstraint'};
optimizer = 'HAMILTON-JACOBI';
incrementFactor = 1;
designVariable = 'LevelSet';
filterType = 'P1';
constraint_case = 'INEQUALITY';

nsteps = 10;
Vfrac_final = 0.1;
Perimeter_target=3.5;
optimality_final =1e-4;
constr_final =1e-4;

BCscale_factor = 0.3;
rotation_per_it = 20;
HJiter0 = 1;
e2 = 100;
N_holes = [12 5 5];
R_holes = 0.2;
phase_holes = [0 0 0];

Vfrac_initial = 0.7;
optimality_initial = 5e-2;
constr_initial = 5e-2;

TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;

% maxiter = 1;
TOL.nu_plus = 0.3;
TOL.nu_minus = 0.3;

plotting = 1;
printing = 0;
monitoring = 1;
monitoring_interval = 1;


filename='Bridge_quad_coarse';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance';'perimeter'};
weights = [1, 0.1];
constraint = {'volumeConstraint'};
optimizer = 'MMA'; incrementFactor = 1;
filterType = 'P1';

nsteps = 5;
Vfrac_final = 0.2;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-2;
constr_initial = 1e-3;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;


function A = UpdateArchive(A,N)
% Update the external archive

%------------------------------- 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".
%--------------------------------------------------------------------------

    %% Select only the non-dominated solutions in the archive
    A = A(NDSort(A.objs,1)==1);

    %% Sort the solutions in A according to their crowding distances
    [~,rank] = sort(CrowdingDistance(A.objs),'descend');
    A        = A(rank(1:min(N,end)));
end


function h = scimat_imagesc(scimat, varargin)
% SCIMAT_IMAGESC  Display 2D image in real world coordinate axes.
%
% SCIMAT_IMAGESC displays the 2D image in SCIMAT.data scaling the axes to
% real world coordinates using the metadata in SCIMAT.axis.
%
% This function is a thin interface to imagesc(), with the same syntax,
% except that it saves you from having to compute X, Y for
% imagesc(X, Y, SCIMAT.data).
%
% SCIMAT_IMAGESC(SCIMAT)
%
%   SCIMAT is a struct with an image and metadata (see "help scimat").
%
% SCIMAT_IMAGESC(SCIMAT, ...)
%
%   See "help image" for extra options.
%
% See also: image, imagesc.

% Author: Ramon Casero <rcasero@gmail.com>
% Copyright © 2015 University of Oxford
% Version: 0.1.0
%
% University of Oxford means the Chancellor, Masters and Scholars of
% the University of Oxford, having an administrative office at
% Wellington Square, Oxford OX1 2JD, UK.
%
% This file is part of Gerardus.
%
% 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. The offer of this
% program under the terms of the License is subject to the License
% being interpreted in accordance with English Law and subject to any
% action against the University of Oxford being under the jurisdiction
% of the English Courts.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

% check arguments
nargoutchk(0, 1);

% image size
N = size(scimat.data, 1);
M = size(scimat.data, 2);

if (size(scimat.data, 3) > 1 || size(scimat.data, 4) > 1)
    error('SCIMAT must contain a 2D image, and no more than one frame')
end

% real world coordinates of the first and last voxels
xmin = scimat_index2world([1, 1], scimat);
xmax = scimat_index2world([N M], scimat);

% display image
if (nargout == 0)
    imagesc(...
        linspace(xmin(1), xmax(1), M), ...
        linspace(xmin(2), xmax(2), N), ...
        squeeze(scimat.data), ...
        varargin{:} ...
        )
else
        h = imagesc(...
        linspace(xmin(1), xmax(1), M), ...
        linspace(xmin(2), xmax(2), N), ...
        squeeze(scimat.data), ...
        varargin{:} ...
        );
end


function s = char(q,eps,varargin)
% quaternion to char

if nargin>1 && ~isnumeric(eps)
  varargin = [{eps},varargin];
  eps = 1;
elseif nargin == 1
  eps = 1;
end

if length(q) == 1
  [alpha,beta,gamma] = Euler(q);
  if check_option(varargin,'nodegree')
    degchar = '';
  else
    degchar = mtexdegchar;
  end

  s = ['(' xnum2str([alpha,beta,gamma]./degree,...
    'precision',eps,'delimiter',[degchar ',']) degchar ')'];

else
  s = ['Rotations: ',size2str(q)];
end


classdef S2FunTri < S2Fun
% a class represeneting a function on the sphere

  properties
    tri          % S2Triangulation
    values = []  % function values
  end

  properties (Dependent = true)
    vertices
    antipodal
  end

  methods

    function sF = S2FunTri(nodes,values)
      % initialize a spherical function

      if isa(nodes,'function_handle')
        n = equispacedS2Grid('resolution',1.5*degree);
        values = nodes(n);
        nodes = n;
      end

      if isa(nodes,'S2Triangulation')
        sF.tri = nodes;
      else
        sF.tri = S2Triangulation(nodes);
      end

      sF.values = values;
    end

    function v = get.vertices(S2F)
      v = S2F.tri.vertices;
    end

    function v = get.antipodal(S2F)
      v = S2F.tri.antipodal;
    end

    function S2F = set.vertices(S2F,v)
      if ~isempty(S2F.values), S2F.values = S2F.eval(v); end
      S2F.tri.vertices = v;
      S2F.tri.update;
    end

  end

  methods (Static = true)

    function sF = demo

      %mtexdata dubna;

      %sF = S2Fun(pf({1}).r,pf({1}).intensities);

      %plot(sF,'upper');

      odf = SantaFe;

      v = equispacedS2Grid('points',1000);

      values = odf.calcPDF(Miller(1,0,0,odf.CS),v);

      sF = S2FunTri(v,values)

      plot(sF,'upper')

    end
  end
end


img=imread('peppers.png');

imgS=single(img);
[imgH, imgW, nCh] = size(img);
if nCh==1
    img=repmat(img,[1, 1, 3]);
end

net = load('imagenet-vgg-verydeep-19.mat');
net = vl_simplenn_tidy(net) ;

imgC = imresize(imgS, net.meta.normalization.imageSize(1:2));
imgC = imgC - net.meta.normalization.averageImage;

res = vl_simplenn(net, imgC);

load projMatrix.mat

j=3; % visualizing conv3

featColor=showColorLayer(res(projMatrix(j).numLayer).x, projMatrix(j).meanFeat', projMatrix(j).V);
featColor=imresize(featColor, [imgH, imgW]);

figure, imagesc(featColor)
figure, imagesc(255-featColor);


function [traj] = initTraj(NbSteps)
traj.Rot = zeros(3,3,NbSteps);
traj.phi = zeros(1,NbSteps);
traj.theta = zeros(1,NbSteps);
traj.psi = zeros(1,NbSteps);
traj.v = zeros(3,NbSteps);
traj.x = zeros(3,NbSteps);
traj.omega_b = zeros(3,NbSteps);
traj.a_b = zeros(3,NbSteps);
end


function Image = AddTextToImageWithBorder(Image,String,Position,Color,Font,FontSize,BorderWidth,BorderColor)

% Image = AddTextToImage(Image,String,Position,Color,Font,FontSize,BorderWidth,BorderColor)
%
%   Works as AddTextToImage, except also allows for a border of thickness
%   BorderWidth pixels and color given by BorderColor. BorderColor should
%   be a 1- or 3-element vector giving Y or RGB in the range 0 to 1
%   regardless of the image class.
%
%	If no border parameters are provided, default is 1 pixel black.
%
% Daniel Warren
% Particle Therapy Cancer Research Institute
% University of Oxford

if ~exist('BorderWidth','var')
	BorderWidth = 1;
end
if ~exist('BorderColor','var')
	BorderColor = 0;
end

if BorderWidth == 0
	Image = AddTextToImage(Image,String,Position,Color,Font,FontSize);
	return;
end

% uint8 images go from 0 to 255, whereas double ones go from 0 to 1
if isa(Image, 'uint8')
    ScaleFactor = 255;
else
    ScaleFactor = 1;
end

% monochrome images need monochrome text, colour images need colour text
if ndims(Image) == 2 %#ok<ISMAT>
    BorderColor = mean(BorderColor(:));
end
if ndims(Image) == 3 && numel(BorderColor) == 1
    BorderColor = [BorderColor BorderColor BorderColor];
end

Mask = AddTextToImage(false(size(Image(:,:,1))),String,Position,1,Font,FontSize);
ConvElement = double(CircleMask(1+2*BorderWidth,1+2*BorderWidth,BorderWidth+0.5,BorderWidth+0.5,0.5+BorderWidth));
Outline = xor(conv2(double(Mask),ConvElement,'same'),Mask);
Image = AddTextToImage(Image,String,Position,Color,Font,FontSize);

for i = 1:size(Image,3)
tmp = Image(:,:,i);
tmp(Outline) = ScaleFactor*BorderColor(i);
Image(:,:,i) = tmp;
end

end

function out = CircleMask(w,h,cx,cy,r)
% function out = CircleMask(w,h,cx,cy,r)
%     Outputs a 1D bitmap of a solid circle of radius r pixels
%     centered at pixel (cx,cy) within an matrix of size w x h
%     pixels.

[x y] = meshgrid(1:w,1:h);
out = ((x-cx-0.5).^2+(y-cy-0.5).^2) <= r^2;

end


function calpak_test375 ( )

%*****************************************************************************80
%
%% CALPAK_TEST375 tests MONTH_LENGTH_REPUBLICAN.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 March 2013
%
%  Author:
%
%    John Burkardt
%
  n_test = 1;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'CALPAK_TEST375\n' );
  fprintf ( 1, '  For the Republican calendar:\n' );
  fprintf ( 1, '  MONTH_LENGTH_REPUBLICAN returns month lengths.\n' );

  y_test(1) = 4;

  for i_test = 1 : n_test

    y = y_test(i_test);
    sy = y_to_s_republican ( y );
    months = year_length_months_republican ( y );
    days = year_length_republican ( y );

    fprintf ( 1, '\n' );
    fprintf ( 1, '  %d\n', y );
    fprintf ( 1, '  %s\n', sy );
    fprintf ( 1, '  Year length in months = %d\n', months );
    fprintf ( 1, '  Year length in days = %d\n', days );
    fprintf ( 1, '\n' );

    for m = 1 : months
      month_name = month_to_month_name_republican ( m );
      fprintf ( 1, '  %10s  %2d\n', month_name, month_length_republican ( y, m ) );
    end

  end

  return
end


function [ energy x ] = neb_energies( directory )
%NEB_ENERGIES Extract energies and hyperdistance from NEB calculation.
%   [energy,x] = NEB_ENERGIES(directory) extracts the energies and
%   hyperdistance of each image from an NEB calculation. The optional
%   argument directory can be used to specify the directory containing the
%   subdirectories 00, 01, etc. If directory is specified, the current
%   directory is used. If no OUTCAR file is present in subdirectories 00
%   and N+1, then first and last value of energy of will be NaN.
%
%   See also NEB_SPLINE, PLOT_NEB_SPLINE, HYPERDISTANCE.

% shouldn't change directory

    startDir = pwd();
    if nargin == 1
        cd(directory);
    end

    nimg = num_images();

    energy = zeros(1,nimg+2);
    x = zeros(1,nimg+2);

    % read starting point
    if exist('00/OUTCAR','file')
        %buffer = import_oszicar('00/OSZICAR');
        energy(1) = import_outcar('00/OUTCAR','energy');
    else
        energy(1) = nan;
    end

    geo1 = import_poscar('00/POSCAR');
    x(1) = 0;

    % read images
    for i = 2:nimg+1
       %buffer = import_oszicar([sprintf('%02d',i-1) '/OSZICAR']);
       energy(i) = import_outcar([sprintf('%02d',i-1) '/OUTCAR'],'energy');
       geo2 = import_poscar([sprintf('%02d',i-1) '/CONTCAR']);
       x(i) = x(i-1) + hyperdistance(geo1,geo2);
       geo1=geo2;
    end

    % read ending point
    if exist([sprintf('%02d',nimg+1) '/OUTCAR'],'file')
        %buffer = import_oszicar([sprintf('%02d',nimg+1) '/OSZICAR']);
        energy(nimg+2) = import_outcar([sprintf('%02d',nimg+1) '/OUTCAR'],'energy');
    else
        energy(nimg+2) = nan;
    end

    geo2 = import_poscar([sprintf('%02d',nimg+1) '/POSCAR']);
    x(nimg+2) = x(nimg+1) + hyperdistance(geo1,geo2);

    cd(startDir);

end


function V = erasure_symbol_merge(W)
cnt = 0;
N = size(W, 2);
for i = N/2 : -1  : 1
    if W(1, i) == W(2, i)
        cnt = cnt + 1;
    else
        break;
    end
end
W_erasure = W(:, N/2 - cnt + 1 : N/2 + cnt);
erasure_probability = sum(W_erasure(1, :));
middle = erasure_probability/2 * ones(2, 2);
W_left = W(:, 1 : N/2 - cnt);
W_right = W(:, N/2 + cnt + 1 : end);
V = [W_left middle W_right];
end


%==============================================================================
% This code is part of the Matlab-based toolbox
% LagLDDDM - A Lagrangian Gauss--Newton--Krylov Solver for Mass- and
%                        Intensity-Preserving Diffeomorphic Image Registration
%
% For details and license info see
% - https://github.com/C4IR/FAIR.m/tree/master/add-ons/LagLDDMM
%
% function v0 = getVelocityStartingGuess(omega,m,nt)
%
% returns starting guess for velocity, that is, zero vector of appropiate
% size, which depends on regularizer, spatial and temporal discretization
% size.
%
% Input:
%
%  omega   - spatial domain
%      m   - number of cells for velocity
%     nt   - number of time points
%
% Output:
%
%     v0   - vector of zeros. size depends on grid for regularizer and nt
%
% =========================================================================
function v0 = getVelocityStartingGuess(omega,m,nt)
if not(exist('nt','var')) || isempty(nt)
    nt = regularizer('get','nt');% look up if regularizer is configured
    if isempty(nt),  nt = 0; end;
end
dim = numel(omega)/2;
switch regularizer('get','grid')
    case 'nodal'
        v0 = zeros(dim*prod(m+1),1);
    case 'staggered'
        v0 = zeros(sum(prod(ones(dim,1)*m+eye(dim),2)),1);
    otherwise % assume cell-centered
        v0 = zeros(dim*prod(m),1);
end
v0 = repmat(v0,nt+1,1);